AI Hints
Home›Fine-Tuning LLMs Tutorial›Precision, Length and Hardware
Fine-Tuning LLMs · Lesson 65 of 120

Sequence Length and Packing

Tokens per example.

⏱ 2 min read▶ Video at 1:41:19🎓 Free
Watch this lesson in the Fine-Tuning LLMs courseWatch on YouTube ↗Full Fine-Tuning LLMs course

Every example is a sequence of tokens. Longer sequences need more memory, and more time. So it's worth checking how long our examples really are.

  • Every example is a sequence
  • Longer = more memory
  • Check the real lengths

Measure our lengths

We format each example with the chat template, just as the trainer does. Then we count its tokens. We print the shortest, the longest, and the average. And how much would be wasted, if every example were padded to the longest one. Run it. Our examples are short, between fifty one and sixty nine tokens. Padding everything to the longest would waste fourteen percent of the work.

app.pypython
from transformers import AutoTokenizer
from chat import data

tok = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M-Instruct")
lengths = []
for ex in data["train"]:
    text = tok.apply_chat_template(ex["prompt"] + ex["completion"], tokenize=False)
    lengths.append(len(tok(text)["input_ids"]))
lengths.sort()
print("Examples:      ", len(lengths))
print("Shortest:      ", lengths[0], "tokens")
print("Longest:       ", lengths[-1], "tokens")
print("Average:       ", round(sum(lengths) / len(lengths)), "tokens")
print("Padding to max wastes", f"{1 - sum(lengths) / (len(lengths) * lengths[-1]):.0%}")
Output
Examples:       527
Shortest:       51 tokens
Longest:        69 tokens
Average:        59 tokens
Padding to max wastes 14%
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)

max_length and packing

Two settings help. Max length cuts off examples that are too long. Check your data first, so you don't cut off answers. Packing joins several short examples into one long sequence, with no padding at all. It can make training much faster, when examples vary a lot in length.

keyvalue
max_lengthcut off long examples
Check firstnever cut off answers
packing=Truejoin short examples
Benefitno wasted padding

Summary

Let's recap. Measure your token lengths before training. Set max length so answers are never cut off. And use packing when many examples are short. Next, where to actually train bigger models.

Key takeaways
  • Measure lengths
  • max_length
  • packing=True
Next up: Where to Train — laptops, Colab and the cloud