System Prompts
In training and in use.
Our training examples all start with the same system message. Does it matter what system message we use later, when we actually use the model? Let's test it.
- Every example has a system message
- Does it matter later?
- Let's test it
Three system messages
We load our fine-tuned model, and ask it the same question three times. First with the exact system message from training. Then with a generic one. Then with none at all. Run it. With the training system message, we get perfect JSON. With a different one, or none, the JSON disappears. The model learned our task together with that system message.
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import PeftModel
from chat import SYSTEM
NAME = "HuggingFaceTB/SmolLM2-135M-Instruct"
tok = AutoTokenizer.from_pretrained(NAME)
model = PeftModel.from_pretrained(AutoModelForCausalLM.from_pretrained(NAME), "ticket-lora").eval()
msg = {"role": "user", "content": "Is Dune in stock?"}
for system in [SYSTEM, "You are a helpful assistant.", None]:
messages = ([{"role": "system", "content": system}] if system else []) + [msg]
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)
answer = tok.decode(out[0][ids["input_ids"].shape[1]:], skip_special_tokens=True)
print(f"{str(system)[:30]:31} {answer[:50]}")Read the customer's message. R {"intent": "stock", "book": "Dune"}
You are a helpful assistant. No, Dune in stock is not available.
None "Dune" is currently in stock.Also uses _setup.py
import shutil
shutil.copytree('/Users/hussain/Docker Complete Course/shared-data/ft_cache/ticket-lora', 'ticket-lora')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,
eval_strategy="steps", eval_steps=22,
save_strategy="no", report_to="none")
trainer = SFTTrainer(model=model, args=args, train_dataset=data["train"],
eval_dataset=data["test"], processing_class=tok, peft_config=lora)The rule
So here's the rule. Use exactly the same system message, and the same chat template, when you use the model, as when you trained it. If you want the model to work with many different system messages, then your training data must include many different system messages.
| key | value |
|---|---|
| Rule | same system message in use |
| Also | same chat template |
| Want flexibility? | vary it in training |
| Check | test with the real prompt |
Summary
Let's recap. A fine-tuned model learns its task together with the system message. Use the same one when you use the model. And vary it in training if you need flexibility. Next, examples with many turns.
Key takeaways- Same system message
- Same template
- Vary it to generalise