Como Fazer Fine-Tuning do Llama-2 (7B) para Superar o ChatGPT

Built for Speed: ~10ms Latency, Even Under Load
Blazingly fast way to build, track and deploy your models!
- Handles 350+ RPS on just 1 vCPU — no tuning needed
- Production-ready with full enterprise support
Os modelos de linguagem grandes (LLMs) estão se tornando cada vez mais poderosos e estão sendo usados para uma variedade de tarefas, incluindo chatbots, geração de texto e resposta a perguntas. No entanto, os LLMs podem ser caros e exigir muitos recursos para serem treinados. Neste post de blog, mostraremos como fazer o fine-tuning de um LLM menor (7B) para ter um desempenho melhor do que o ChatGPT.
O fine-tuning é um processo de treinamento de um LLM em um conjunto de dados específico para melhorar seu desempenho em uma tarefa específica. Neste caso, faremos o fine-tuning de um LLM de 7B para multiplicar dois números.
Então vamos começar com o desempenho de diferentes modelos de linguagem grandes em uma tarefa de multiplicação simples: 458*987 = 452046.
Primeiro, olharemos para o modelo Llama-2-7B, lançado recentemente pela Meta. Implantamos o Llama-2 na TrueFoundry e o testamos com as integrações LangChain da TrueFoundry. Aqui está o resultado para a mesma operação.

Como podemos ver claramente, ele não se sai bem nessa tarefa (o que também é esperado, dado o tamanho do modelo). Vamos ver como os modelos no estado da arte se saem na mesma tarefa:
Vamos olhar para o resultado do ChatGPT (GPT-3.5 Turbo):

Agora a resposta (451.086) está muito próxima da resposta real, que é 452.046, mas a resposta não está correta.
Vamos tentar com um prompt diferente (para fazer um cálculo passo a passo e ver o que ele faz):
0:00/1×
ChatGPT com prompt personalizado para multiplicação
Mas, novamente, ele chega a um resultado incorreto: 450.606 🤨
Por fim, vamos tentar com o modelo no estado da arte (GPT-4) e verificar seu desempenho na tarefa:

Está muito perto da resposta correta (452.046) e pode parecer correto para qualquer pessoa. Mas, claramente, a resposta está incorreta.
Por que os LLMs têm um desempenho ruim em tarefas simples de multiplicação?
A resposta para essa pergunta é muito simples. Eles não foram "treinados" para isso.
Os LLMs são treinados em grandes conjuntos de dados de texto e código, mas esses dados nem sempre estão estruturados de uma forma que seja útil para o raciocínio matemático. Por exemplo, os dados podem não incluir representações explícitas de conceitos matemáticos, como adição, subtração, multiplicação e divisão. Isso pode dificultar para os LLMs aprenderem a realizar essas operações corretamente.
Por isso, pensamos: é possível treinar um LLM para realizar operações matemáticas? Fizemos um experimento e os resultados foram bastante promissores!
Fazer fine-tuning no Llama-2 7B para aprender multiplicação
Curadoria de um Dataset
Para começar, curamos um dataset de 40.000 linhas de prompts e instruções. Tentamos imitar os passos exatos seguidos no método de multiplicação longa, que envolve dividir o multiplicando e o multiplicador em seus dígitos individuais, depois multiplicar cada dígito do multiplicando por cada dígito do multiplicador e colocar os resultados nas posições apropriadas com base em seus valores posicionais. Finalmente, todos os produtos individuais são somados para obter o resultado final.
Aqui está um exemplo de prompt:
You are a helpful assistant providing detailed answers to multiplication questions. Ensure you provide a thorough explanation using the long multiplication method for the math problem given below.
If you don't know the answer to a question, please don't share false information. What is 5244 * 1932?
E aqui está um exemplo de resposta:
Here are the steps for multiplying 5244 * 1932 using the long multiplication method.
Step 1: Break 5244 into its individual digits: 5 (thousands place), 2 (hundreds place), 4 (tens place), and 4 (ones place).
Step 2: Similarly, break 1932 into its individual digits: 1 (thousands place), 9 (hundreds place), 3 (tens place), and 2 (ones place).
- 4 (from 1 place of first number) * 2 (from 1 place of second number) = 8 -> Shift it 0 places to the left (because we are multiplying with the 1 place of the second number) to get 8
- 4 (from 1 place of first number) * 3 (from 10 place of second number) = 12 -> Shift it 1 places to the left (because we are multiplying with the 10 place of the second number) to get 120
- 4 (from 1 place of first number) * 9 (from 100 place of second number) = 36 -> Shift it 2 places to the left (because we are multiplying with the 100 place of the second number) to get 3600
- 4 (from 1 place of first number) * 1 (from 1000 place of second number) = 4 -> Shift it 3 places to the left (because we are multiplying with the 1000 place of the second number) to get 4000
- 4 (from 10 place of first number) * 2 (from 1 place of second number) = 8 -> Shift it 1 places to the left (because we are multiplying with the 1 place of the second number) to get 80
- 4 (from 10 place of first number) * 3 (from 10 place of second number) = 12 -> Shift it 2 places to the left (because we are multiplying with the 10 place of the second number) to get 1200
- 4 (from 10 place of first number) * 9 (from 100 place of second number) = 36 -> Shift it 3 places to the left (because we are multiplying with the 100 place of the second number) to get 36000
- 4 (from 10 place of first number) * 1 (from 1000 place of second number) = 4 -> Shift it 4 places to the left (because we are multiplying with the 1000 place of the second number) to get 40000
- 2 (from 100 place of first number) * 2 (from 1 place of second number) = 4 -> Shift it 2 places to the left (because we are multiplying with the 1 place of the second number) to get 400
- 2 (from 100 place of first number) * 3 (from 10 place of second number) = 6 -> Shift it 3 places to the left (because we are multiplying with the 10 place of the second number) to get 6000
- 2 (from 100 place of first number) * 9 (from 100 place of second number) = 18 -> Shift it 4 places to the left (because we are multiplying with the 100 place of the second number) to get 180000
- 2 (from 100 place of first number) * 1 (from 1000 place of second number) = 2 -> Shift it 5 places to the left (because we are multiplying with the 1000 place of the second number) to get 200000
- 5 (from 1000 place of first number) * 2 (from 1 place of second number) = 10 -> Shift it 3 places to the left (because we are multiplying with the 1 place of the second number) to get 10000
- 5 (from 1000 place of first number) * 3 (from 10 place of second number) = 15 -> Shift it 4 places to the left (because we are multiplying with the 10 place of the second number) to get 150000
- 5 (from 1000 place of first number) * 9 (from 100 place of second number) = 45 -> Shift it 5 places to the left (because we are multiplying with the 100 place of the second number) to get 4500000
- 5 (from 1000 place of first number) * 1 (from 1000 place of second number) = 5 -> Shift it 6 places to the left (because we are multiplying with the 1000 place of the second number) to get 5000000
Now, add all these results together:
The sum of 8 + 120 + 3600 + 4000 + 80 + 1200 + 36000 + 40000 + 400 + 6000 + 180000 + 200000 + 10000 + 150000 + 4500000 + 5000000 = 10131408.
Em seguida, escrevemos um script Python que gera pares de prompt-resposta selecionando aleatoriamente dois dígitos para multiplicação. Curamos um dataset com 40.000 linhas.
Fazer o Fine-Tuning do Modelo
Agora, com o dataset pronto, precisamos fazer o fine-tuning do modelo.
Estamos usando a variante chat com fine-tuning da Meta (7 bilhões de parâmetros) do Llama-2 como modelo base.
Realizamos o fine-tuning usando fine-tuning com QLoRA utilizando as bibliotecas BitsAndBytes e Peft. Aqui está a lora config que usamos:
LoraConfig(
lora_alpha=16,
lora_dropout=0.1,
r=64,
bias="none",
task_type="CAUSAL_LM",
target_modules=[
"q_proj",
"k_proj",
"v_proj",
"o_proj",
],
)
Levou cerca de 8 horas para treinar em uma máquina com GPU A100 de 40GB para um dataset de 40.000 linhas.
Finalmente, implantamos o modelo ajustado na TrueFoundry novamente e aqui estão os resultados:

Então, finalmente!! Podemos ver que o modelo com fine-tuning é capaz de calcular o resultado corretamente.
Conclusão
Embora a aritmética não seja uma tarefa para a qual usaríamos um LLM, este exemplo demonstra como um LLM "pequeno" (7B de parâmetros) com o fine-tuning adequado para uma tarefa específica pode superar os LLMs "grandes" (como o GPT-3.5 Turbo - 175B de parâmetros e o GPT-4) em uma tarefa específica.
Os modelos menores que passam por fine-tuning são baratos na inferência, melhores em tarefas especializadas e podem ser implantados facilmente na sua própria nuvem!
Escrevemos um blog detalhado sobre fine-tuning do Llama 2
TrueFoundry AI Gateway delivers ~3–4 ms latency, handles 350+ RPS on 1 vCPU, scales horizontally with ease, and is production-ready, while LiteLLM suffers from high latency, struggles beyond moderate RPS, lacks built-in scaling, and is best for light or prototype workloads.
















.png)
.png)

.png)






.png)

.png)


.png)

.png)
.png)






