AI Hints
Home›Fine-Tuning LLMs Tutorial›Models, Logits and Generation
Fine-Tuning LLMs · Lesson 15 of 120

Generating Text

Model.generate().

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

Predicting one token is nice. But we want whole answers. The generate method runs the predict, add, repeat loop for us.

  • One token isn't enough
  • We want whole answers
  • generate() runs the loop

generate()

We tokenize the start of a sentence. Generate predicts twenty new tokens. Do sample equals false means it always takes the most likely token. Then we compare lengths, and decode. Skip special tokens hides signals like the end token. Run it. Seven tokens went in, twenty seven came out. That's our seven, plus twenty new ones. And again, the base model repeats itself.

app.pypython
from transformers import AutoTokenizer, AutoModelForCausalLM

name = "HuggingFaceTB/SmolLM2-135M"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name)

inputs = tok("A bookshop is a place where", return_tensors="pt")
output = model.generate(**inputs, max_new_tokens=20, do_sample=False)
print("Input tokens: ", inputs["input_ids"].shape[1])
print("Output tokens:", output.shape[1])
print(tok.decode(output[0], skip_special_tokens=True))
Output
Input tokens:  7
Output tokens: 27
A bookshop is a place where you can buy books.

The bookshop is a place where you can buy books.

Important: output includes the input

Here's a detail that confuses many people. Generate returns the input tokens, followed by the new ones. If you only want the answer, slice off the input first. You'll see us do that a lot, with output, then square brackets, starting at the input length.

keyvalue
generate() returnsinput + new tokens
Only the answer?slice off the input
Codeoutput[0][n_input:]
Thendecode it

Summary

Let's recap. Generate runs the predict and add loop. Max new tokens limits the length. And the output includes the input, so slice it off to get just the answer. Next, the settings that change how a model picks its tokens.

Key takeaways
  • model.generate()
  • max_new_tokens
  • Output includes the input
Next up: Decoding Settings — greedy, sampling, temperature