Train on Answers Only
Completion-only loss.
Remember the labels lesson? We only want the model to learn the answer, not the customer's question. With the prompt and completion format, the trainer does this for us automatically.
- Learn the answer only
- Not the question
- Done automatically
What the model learns from
Our trainer is set up in a file called s f t dot p y, which we'll read next lesson. It has already tokenized our data. We take the first example. Then we keep only the tokens whose label isn't minus one hundred. Run it. The example has fifty nine tokens. But the model learns from only seventeen. Just the JSON answer, and the end token.
from sft import trainer, tok
ex = trainer.train_dataset[0]
learned = [t for t, l in zip(ex["input_ids"], ex["labels"]) if l != -100]
print("Tokens in the example:", len(ex["input_ids"]))
print("Tokens it learns from:", len(learned))
print("Learned text:", repr(tok.decode(learned)))Tokens in the example: 59
Tokens it learns from: 17
Learned text: '{"intent": "complaint", "book": "Dune"}<|im_end|>\n'Also uses chat.py
import json
from datasets import load_dataset
SYSTEM = "Read the customer's message. Reply with JSON: the intent and the book."
def to_example(row):
answer = json.dumps({"intent": row["intent"], "book": row["book"]})
return {"prompt": [{"role": "system", "content": SYSTEM},
{"role": "user", "content": row["message"]}],
"completion": [{"role": "assistant", "content": answer}]}
data = load_dataset("json", data_files={"train": "tickets_train.jsonl",
"test": "tickets_test.jsonl"})
data = data.map(to_example, remove_columns=["message", "intent", "book"])Also uses ask.py
from chat import SYSTEM
def ask(model, tok, message):
model.eval() # switch off training-only behaviour
messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": message}]
ids = tok.apply_chat_template(messages, add_generation_prompt=True,
return_dict=True, return_tensors="pt")
out = model.generate(**ids, max_new_tokens=30, do_sample=False)
return tok.decode(out[0][ids["input_ids"].shape[1]:], skip_special_tokens=True)Also uses sft.py
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import LoraConfig
from trl import SFTTrainer, SFTConfig
from chat import data
NAME = "HuggingFaceTB/SmolLM2-135M-Instruct"
tok = AutoTokenizer.from_pretrained(NAME)
model = AutoModelForCausalLM.from_pretrained(NAME)
lora = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05,
target_modules="all-linear", task_type="CAUSAL_LM")
args = SFTConfig(output_dir="ticket-lora", num_train_epochs=1, learning_rate=2e-4,
per_device_train_batch_size=8, logging_steps=11,
save_strategy="no", report_to="none")
trainer = SFTTrainer(model=model, args=args, train_dataset=data["train"],
processing_class=tok, peft_config=lora)Why it matters
Why does this matter so much? Our examples are mostly prompt. If the model trained on everything, most of its effort would go into predicting customer messages, and the system message. That's wasted. With completion only loss, every bit of learning goes into the answer.
| key | value |
|---|---|
| Each example | mostly prompt |
| Train on everything | effort wasted on the prompt |
| Completion-only | all effort on the answer |
| In TRL | default for prompt + completion |
Summary
Let's recap. With prompt and completion data, TRL masks the prompt automatically. The model learns only the answer, and the end token. Next, the trainer that makes all of this easy.
Key takeaways- Prompt masked
- Answer learned
- Automatic in TRL