Fine-tuning Llama 3.1 for Medical Questions - Romeu Cornelius Junior
Tutorial · Updated 2026 · Medical AITutorial · Atualizado em 2026 · IA médica

Fine-tune Llama 3.1 to answer medical questionsAjuste fino do Llama 3.1 para responder questões médicas

Train Llama 3.1 8B on a free Kaggle GPU with QLoRA so it answers patient questions in the style of a doctor. Weights & Biases tracks the run and the result is saved as a small adapter on Hugging Face.Treine o Llama 3.1 8B em uma GPU gratuita do Kaggle com QLoRA para que ele responda perguntas de pacientes no estilo de um médico. O Weights & Biases acompanha o treino e o resultado fica salvo como um adaptador pequeno no Hugging Face.

What you buildO que você monta

  • A Llama 3.1 8B tuned with QLoRA on doctor and patient dialoguesUm Llama 3.1 8B ajustado com QLoRA em diálogos de médico e paciente
  • Live training curves in Weights & BiasesCurvas de treino ao vivo no Weights & Biases
  • A LoRA adapter on Hugging Face, far smaller than the base modelUm adaptador LoRA no Hugging Face, muito menor que o modelo base

What you needO que você precisa

  • Accounts at Hugging Face, Kaggle and Weights & Biases, plus access to the Llama licenseContas no Hugging Face, Kaggle e Weights & Biases, e o acesso à licença do Llama
  • A Kaggle notebook with a GPU (P100 or T4)Um notebook do Kaggle com GPU (P100 ou T4)
  • Basic PythonPython básico

Llama 3.1, QLoRA, Kaggle, Hugging Face, Weights & Biases

How the pieces fitComo as peças se encaixam

The notebook loads the base model in 4 bits, trains only a small LoRA layer on 1,000 dialogues, logs every step to Weights & Biases and pushes the adapter to the Hub.O notebook carrega o modelo base em 4 bits, treina apenas uma pequena camada LoRA em 1.000 diálogos, registra cada passo no Weights & Biases e envia o adaptador para o Hub.

Datasetai-medical-chatbot Kaggle notebookNotebook KaggleGPU · QLoRA Hugging Face HubLoRA adapteradaptador LoRA Weights & Biasestraining metricsmétricas de treino
The notebook reads the dataset, tracks the run and publishes the adapter.O notebook lê o dataset, acompanha o treino e publica o adaptador.
Educational use only. A model tuned this way imitates the tone of the data; it can be wrong and must never replace a doctor or be used for clinical decisions.Somente para estudo. Um modelo ajustado assim imita o tom dos dados; ele pode errar e nunca deve substituir um médico nem ser usado em decisões clínicas.

1. Prepare your accounts1. Prepare as contas

  1. Fill in the Meta download form with the email you will use everywhere.Preencha o formulário de download da Meta com o e-mail que você usará em todas as contas.
  2. Create a Hugging Face account with that email and request access to the gated Llama 3.1 8B Instruct model, accepting the license.Crie uma conta no Hugging Face com esse e-mail e peça acesso ao modelo Llama 3.1 8B Instruct (restrito), aceitando a licença.
  3. Create a Kaggle account and a Weights & Biases account with the same email.Crie uma conta no Kaggle e outra no Weights & Biases com o mesmo e-mail.
  4. Generate a Hugging Face access token (read is enough for training; use write if you will push the adapter) and copy your W&B API key.Gere um token de acesso no Hugging Face (leitura basta para treinar; use escrita para enviar o adaptador) e copie sua chave de API do W&B.

2. Set up the Kaggle notebook2. Configure o notebook do Kaggle

Kaggle gives free GPU time every week, which is enough for this project. Create a new notebook and open the session options.O Kaggle oferece horas de GPU gratuitas por semana, o que basta para este projeto. Crie um novo notebook e abra as opções da sessão.

  1. Choose GPU P100 as the accelerator (a T4 also works).Escolha GPU P100 como acelerador (a T4 também funciona).
  2. Go to Add-ons > Secrets and add HUGGINGFACE_TOKEN and WANDB_API_KEY, then enable both for this notebook.Vá em Add-ons > Secrets e adicione HUGGINGFACE_TOKEN e WANDB_API_KEY, ativando os dois neste notebook.
  3. Install the packages in the first cell:Instale os pacotes na primeira célula:
!pip install -q -U transformers trl peft bitsandbytes accelerate datasets wandb

LoginLogin

from kaggle_secrets import UserSecretsClient
from huggingface_hub import login
import wandb

secrets = UserSecretsClient()
login(token=secrets.get_secret("HUGGINGFACE_TOKEN"))
wandb.login(key=secrets.get_secret("WANDB_API_KEY"))
wandb.init(project="llama31-medical", job_type="training")

3. Load the model in 4 bits3. Carregue o modelo em 4 bits

An 8B model does not fit in a P100 at full precision. QLoRA loads it in 4 bits (about 6 GB), which saves memory and speeds up tuning. The P100 has no bfloat16, so the compute type is float16.Um modelo de 8B não cabe em uma P100 em precisão total. O QLoRA carrega o modelo em 4 bits (cerca de 6 GB), o que economiza memória e acelera o ajuste. A P100 não tem bfloat16, então o tipo de cálculo é float16.

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig

base = "meta-llama/Llama-3.1-8B-Instruct"

bnb = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.float16,
    bnb_4bit_use_double_quant=True,
)

tokenizer = AutoTokenizer.from_pretrained(base)
tokenizer.pad_token = tokenizer.eos_token
model = AutoModelForCausalLM.from_pretrained(
    base, quantization_config=bnb, device_map="auto", torch_dtype=torch.float16)
Llama 3.1 already ships its own chat template, so the tokenizer formats conversations for you. The older ChatML template from the first version of this guide is no longer needed.O Llama 3.1 já traz o próprio template de chat, então o tokenizador formata as conversas por você. O template ChatML da primeira versão deste guia não é mais necessário.

4. Prepare the dataset4. Prepare o dataset

We use ruslanmv/ai-medical-chatbot, with about 250 thousand patient and doctor dialogues. To keep training short we shuffle it and keep 1,000 rows, then join each question and answer into one chat-formatted text column.Usamos o ruslanmv/ai-medical-chatbot, com cerca de 250 mil diálogos entre paciente e médico. Para manter o treino curto, embaralhamos e ficamos com 1.000 linhas, juntando pergunta e resposta em uma coluna de texto no formato de chat.

from datasets import load_dataset

ds = load_dataset("ruslanmv/ai-medical-chatbot", split="train")
ds = ds.shuffle(seed=65).select(range(1000))

def to_chat(row):
    messages = [
        {"role": "user", "content": row["Patient"]},
        {"role": "assistant", "content": row["Doctor"]},
    ]
    return {"text": tokenizer.apply_chat_template(messages, tokenize=False)}

ds = ds.map(to_chat)
ds = ds.train_test_split(test_size=0.1, seed=65)
print(ds["train"][0]["text"][:400])  # check the special tokensconfira os tokens especiais

5. Train with LoRA5. Treine com LoRA

Instead of updating all 8 billion weights, LoRA adds small adapter layers and trains only those. The run is faster, uses less memory and produces a small file. The sequence length stays at 512 so the GPU does not run out of memory.Em vez de atualizar os 8 bilhões de pesos, o LoRA adiciona pequenas camadas adaptadoras e treina só elas. O treino fica mais rápido, usa menos memória e gera um arquivo pequeno. O comprimento da sequência fica em 512 para a GPU não estourar a memória.

from peft import LoraConfig
from trl import SFTConfig, SFTTrainer

lora = LoraConfig(
    r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM",
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
)

args = SFTConfig(
    output_dir="out",
    num_train_epochs=1,
    per_device_train_batch_size=1,
    gradient_accumulation_steps=8,
    learning_rate=2e-4,
    lr_scheduler_type="cosine",
    warmup_ratio=0.03,
    optim="paged_adamw_8bit",
    fp16=True,
    gradient_checkpointing=True,
    logging_steps=10,
    eval_strategy="steps",
    eval_steps=50,
    dataset_text_field="text",
    max_length=512,   # older TRL versions call this max_seq_lengthversões antigas do TRL chamam de max_seq_length
    report_to="wandb",
)

trainer = SFTTrainer(model=model, args=args, train_dataset=ds["train"],
    eval_dataset=ds["test"], peft_config=lora, processing_class=tokenizer)
trainer.train()
wandb.finish()

One pass over 1,000 rows is a quick test. For better answers, train on more rows and for about three epochs, watching the validation loss so you notice when it stops improving.Uma passada em 1.000 linhas é um teste rápido. Para respostas melhores, treine com mais linhas e por cerca de três épocas, acompanhando a perda de validação para perceber quando ela para de melhorar.

6. Evaluate the model6. Avalie o modelo

When the run ends, Weights & Biases shows the history and a summary of the session: training and validation loss, learning rate and GPU use, stored under your project name. Then try a sample patient question to see how the tuned model answers.Quando o treino termina, o Weights & Biases mostra o histórico e o resumo da sessão: perda de treino e de validação, taxa de aprendizado e uso da GPU, guardados sob o nome do projeto. Depois teste uma pergunta de paciente para ver como o modelo ajustado responde.

messages = [{"role": "user", "content": "I have had a sore throat and mild fever for two days. What should I do?"}]
inputs = tokenizer.apply_chat_template(
    messages, add_generation_prompt=True, return_tensors="pt").to(model.device)

with torch.no_grad():
    out = model.generate(inputs, max_new_tokens=250, do_sample=True, temperature=0.7)
print(tokenizer.decode(out[0][inputs.shape[1]:], skip_special_tokens=True))

Compare the answers with the base model and with assistants such as ChatGPT or Perplexity. A small tuned model will be shorter and more limited, but it should stay consistent and in the doctor’s tone.Compare as respostas com as do modelo base e com assistentes como ChatGPT ou Perplexity. Um modelo pequeno ajustado será mais curto e limitado, mas deve se manter consistente e no tom de um médico.

7. Save and publish the adapter7. Salve e publique o adaptador

Saving sends only the adapter, which is much smaller than the base model. The Hub API creates the repository for you; use a token with write permission.Salvar envia apenas o adaptador, que é bem menor que o modelo base. A API do Hub cria o repositório automaticamente; use um token com permissão de escrita.

new_model = "YOUR-USER/llama31-8b-medical-adapter"
trainer.model.save_pretrained("adapter")
trainer.model.push_to_hub(new_model)
tokenizer.push_to_hub(new_model)

To keep the notebook, click Save Version at the top right, choose Quick Save, open the advanced settings, select Always save output and press Save. Later, load the base model in half precision in a new notebook and merge the adapter into it:Para guardar o notebook, clique em Save Version no canto superior direito, escolha Quick Save, abra as configurações avançadas, marque Always save output e clique em Save. Depois, em um novo notebook, carregue o modelo base em meia precisão e mescle o adaptador:

from peft import PeftModel

base_model = AutoModelForCausalLM.from_pretrained(base, torch_dtype=torch.float16, device_map="auto")
merged = PeftModel.from_pretrained(base_model, new_model).merge_and_unload()

A merged model can be converted to GGUF and run locally. See the local AI server guide to serve it with Ollama.Um modelo mesclado pode ser convertido para GGUF e rodado localmente. Veja o guia do servidor de IA local para servi-lo com o Ollama.

Watch the walkthroughAssista ao passo a passo

ConclusionConclusão

Setting up, training and using an LLM for medical questions takes several steps, but Kaggle, Hugging Face and Weights & Biases work well together. With QLoRA you get a small model that gives consistent answers, which shows what Meta Llama 3.1 can do even on free hardware.Configurar, treinar e usar uma LLM para questões médicas exige vários passos, mas Kaggle, Hugging Face e Weights & Biases funcionam bem juntos. Com o QLoRA você obtém um modelo pequeno que dá respostas consistentes, o que mostra o que o Meta Llama 3.1 faz mesmo em hardware gratuito.

I hope this guide inspires you to explore LLMs in healthcare, always with human review and care.Espero que este guia inspire você a explorar as LLMs na área da saúde, sempre com revisão humana e cuidado.

Want a model trained on your own data?Quer um modelo treinado com os seus dados?

Tell me what you want to build or automate. I answer with questions, not a sales pitch.Conte o que você quer construir ou automatizar. Eu respondo com perguntas, não com proposta de vendas.

me@rcjr.online
© 2026 Romeu Cornelius JuniorSoftware Engineer & AI BuilderEngenheiro de Software & AI Builder