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, AutoModelForCausalLMname = "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.
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.
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.