Project: Train
Version two.
Our data has its new system message. Now we train version two. Same model, same LoRA settings, same learning rate. Only the system message has changed.
- New system message
- Train version two
- Only one change
Training version two
Here's the training script. It's the same as before. Epochs and out, at the top, set the number of epochs, and the folder name. We keep the result that train returns. Then we print the steps, the final loss, and the time it took. And save the adapter. Run it. Sixty six steps, on a laptop CPU, in about two minutes.
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import LoraConfig
from trl import SFTTrainer, SFTConfig
from chat import data
NAME = "HuggingFaceTB/SmolLM2-135M-Instruct"
EPOCHS, OUT = 1, "tickets-v2"
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=OUT, num_train_epochs=EPOCHS, learning_rate=2e-4,
per_device_train_batch_size=8, save_strategy="no", report_to="none")
trainer = SFTTrainer(model=model, args=args, train_dataset=data["train"],
processing_class=tok, peft_config=lora)
result = trainer.train()
print(f"trained {OUT}: {result.global_step} steps, loss {result.training_loss:.3f}, "
f"{result.metrics['train_runtime']:.0f} seconds")
trainer.save_model(OUT)trained tickets-v2: 66 steps, loss 0.177, 138 seconds
Also uses chat.py
import json
from datasets import load_dataset
INTENTS = ["order_status", "return", "price", "stock", "complaint"]
SYSTEM = ("Read the customer's message. Reply with JSON: the intent and the book. "
"The intent must be one of: " + ", ".join(INTENTS) + ".")
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 score.py
import json
from ask import ask
def score(model, tok, rows):
valid = correct = 0
for row in rows:
reply = ask(model, tok, row["message"])
try:
answer = json.loads(reply)
except json.JSONDecodeError:
continue # not JSON: neither valid nor correct
if not isinstance(answer, dict):
continue # JSON, but not an object
valid += 1
if answer.get("intent") == row["intent"] and answer.get("book") == row["book"]:
correct += 1
n = len(rows)
return {"valid_json": f"{valid / n:.0%}", "correct": f"{correct / n:.0%}"}While it trains
While a model trains, it's a good time to think about what you expect. We expect no invented intents, because the model now sees the list. And we hope the score goes up. Writing down what you expect, before you look, keeps you honest.
| key | value |
|---|---|
| Expect | no invented intents |
| Hope | higher score |
| Habit | predict before you look |
| Why | keeps you honest |
Summary
Let's recap. Version two changes only the system message. Training takes a few minutes, on a laptop. And it's good practice to predict the result, before you look. Next, we evaluate it.
Key takeaways- One change only
- Train and save
- Predict first