skip to content

A Transformers text-generation pipeline batch job returns different text each run; which defaults cause it, and how do you pass generation settings?

level: seniorimportance: should knowfreq 12%

answer

  1. a default you never set
  2. your args, model file, then fallback
  3. sampling switched on by the pipeline
  4. leftover keywords reach generate
  5. max_new_tokens, not max_length

basics

~10 s

Unless the model's generation_config.json sets them, the Transformers v5 text-generation pipeline falls back to do_sample=True, temperature=0.7 and max_new_tokens=256. Pass do_sample=False and max_new_tokens as keyword arguments, which the pipeline forwards to model.generate.

solid answer

~40 s

In Transformers v5 the `text-generation` pipeline builds its generation config in priority order: arguments you pass, then a `generation_config` object you supply, then the model's `generation_config.json`, then the pipeline's fallback (`max_new_tokens=256`, `do_sample=True`, `temperature=0.7`), which fills only what the model left unset. So a checkpoint without sampling settings samples by default, and a batch job gets different text each run. Fix it by passing settings explicitly: any keyword argument the pipeline does not consume itself is forwarded to `model.generate`, at construction or per call, as in `pipe(prompts, do_sample=False, max_new_tokens=200)`. Prefer `max_new_tokens` to `max_length`, because the pipeline also hands `max_length` to the tokenizer and it counts the prompt. Drop to `model.generate` only for what the pipeline wraps away, such as raw output objects or your own tokenization and batching.

code

python · 13 lines
python
from transformers import pipeline

gen = pipeline(
    "text-generation",
    model="HuggingFaceTB/SmolLM3-3B",  # pin revision= in production
    do_sample=False,       # overrides the pipeline's sampling fallback
    max_new_tokens=200,    # caps generated tokens only
)

docs = ["First report text ...", "Second report text ..."]
chats = [[{"role": "user", "content": "Summarize: " + d}] for d in docs]
for out in gen(chats):
    print(out[0]["generated_text"][-1]["content"])

go deeper

for a junior

Recall that the text-generation pipeline returns generated_text, that max_new_tokens caps output length, and that extra keyword arguments reach model.generate.

for a middle

Explain the priority order behind the generation config and the pipeline's fallback of max_new_tokens=256, do_sample=True and temperature 0.7 when the model's file is silent.

for a senior

Diagnose run-to-run variation as the sampling fallback, pin decoding settings in the job, avoid the max_length clash, and know when model.generate is genuinely needed.

for a principal

Set a team convention for generation settings: explicit values or a reviewed GenerationConfig in code, so a model swap or a changed generation_config.json cannot silently change batch output.

## Where a text-generation pipeline gets its settings The Hugging Face Transformers `text-generation` pipeline is a thin layer over **`model.generate`**. Every call ends in a `generate` call on the tokenized prompt with a `generation_config` attached. Knowing which values that config holds explains most reports of a batch job behaving differently from the notebook it came from. When the pipeline is constructed, Transformers v5 assembles the generation config in this **priority order**, highest first: 1. **Keyword arguments** you pass, at construction or on each call. 2. A **`GenerationConfig` object** passed as `generation_config=`; when given, it replaces the model's own file as the base. 3. The model's **`generation_config.json`** from its Hub repo. 4. The pipeline's **fallback defaults**: `max_new_tokens=256`, `do_sample=True`, `temperature=0.7`. These only fill values that the base config leaves at the library-wide defaults. ## Why a batch job varies from run to run Many base checkpoints and some fine-tunes ship no sampling settings. For those, the fallback turns **sampling on** at temperature 0.7, so the same prompt yields different text on each run. That surprises anyone expecting greedy decoding, which is `generate`'s own library-wide default (`do_sample=False`). What sampling and temperature do to the token distribution is decoding theory; the pipeline-specific fact is that this pipeline switches sampling on unless told otherwise. A chat model's `generation_config.json` often sets its own values, which then take precedence over the fallback. To make the job behave predictably, pass the settings explicitly, for example `do_sample=False` and a `max_new_tokens` that fits the task. ## A configuration that does not drift The model's `generation_config.json` lives in its Hub repo, so it changes when the repo owner pushes a new one. A job that relies on it inherits those changes silently. Three habits close the gap: - **Pin the model** with `model=` and a `revision=` commit, so the file you tested is the file you run. - **Write the decoding values the job depends on** (`do_sample`, `max_new_tokens`, and any others) into the code or a reviewed `GenerationConfig`, so neither the model file nor the pipeline fallback decides them. - **Log the effective config** once at start-up; the pipeline keeps it as `pipe.generation_config`, which shows exactly what the merge produced. ## How generation arguments reach `generate` - **Text generation takes loose keyword arguments.** The pipeline consumes the arguments it knows, such as `return_full_text`, `return_tensors`, `prefix`, `stop_sequence`, `continue_final_message` and `truncation`, and forwards every remaining keyword to `model.generate`. Those leftovers are what its docstring calls `generate_kwargs`: `do_sample`, `max_new_tokens`, `num_return_sequences`, `repetition_penalty` and so on. - **Construction versus call.** Arguments given to `pipeline(...)` become the pipeline's defaults; arguments given to a call override them for that call only. - **Other generating pipelines differ.** `image-text-to-text` takes a `generate_kwargs` dict plus a top-level `max_new_tokens`; automatic speech recognition accepts both a dict and loose keywords. Check the specific pipeline's signature rather than assuming one convention. - **A `GenerationConfig` object** keeps a reviewed set of values in one place; passed on a call as `generation_config=cfg`, it takes precedence for that call. ## Traps in the pass-through | Argument | Trap | |---|---| | `max_length` | Sent to the tokenizer (where, with truncation, it can cut the prompt) and to `generate`, where it counts prompt plus output. Cap output with `max_new_tokens`; pass tokenizer-only options through `tokenizer_encode_kwargs`. | | `return_full_text` | Defaults to `True`: for a string prompt, `generated_text` starts with the prompt. Set it to `False` to get only the new text. | | Chat input | With a messages list, `generated_text` is the whole conversation with the assistant's reply appended; read `[-1]["content"]`. | | `stop_sequence` | Encoded and passed to `generate` as `eos_token_id`. | The pipeline also switches a right-padding tokenizer to left padding for batched decoder-only generation; why that matters is a tokenizer subject. ## When to call `model.generate` yourself Because the pipeline forwards nearly every `generate` argument, needing a particular decoding setting is not a reason to leave it. Reasons that are: - You want the raw **`GenerateOutput`**, for example with `return_dict_in_generate=True` and `output_scores=True`, with its per-step structure intact instead of the pipeline's decoded and reshaped records. - You want to own **tokenization, padding and batch assembly**: pre-tokenized tensors reused across calls, inputs sorted by length, or a custom attention mask. - The checkpoint is outside the pipeline's causal-LM architectures, such as an encoder-decoder model loaded with `AutoModelForSeq2SeqLM` in v5. - Generation is one step inside a larger tensor loop, such as evaluation during training, where decoding to text and re-tokenizing is waste. Then you load `AutoTokenizer` with `AutoModelForCausalLM` (or the seq2seq class), apply the chat template, call `generate` and decode: exactly the steps the pipeline was doing for you.

  • A text-generation pipeline's output starts by repeating the prompt. Is the model misbehaving?
    No. `return_full_text` defaults to `True`, so for a string prompt `generated_text` is the prompt followed by the continuation. Pass `return_full_text=False` to get only the new text. With chat input the equivalent is that `generated_text` holds the whole conversation, and the reply is its last message.
  • Why might pipe(prompts, max_length=50, truncation=True) cut the prompt, not just the output?
    In the text-generation pipeline `max_length` goes to the tokenizer as well as to `generate`, so with truncation it can shorten the prompt, and inside `generate` it counts prompt tokens plus new ones. `max_new_tokens` limits only generated tokens. Tokenizer-only options belong in `tokenizer_encode_kwargs`, which the pipeline sends to the tokenizer or chat template alone.
  • When is calling model.generate directly the better choice than the pipeline?
    When you need what the pipeline wraps away: the raw `GenerateOutput` with per-step scores, your own tokenization, padding and batch assembly, a checkpoint outside its causal-LM architectures such as a seq2seq model, or generation inside a larger tensor loop where decoding and re-tokenizing is waste. A decoding setting alone is not a reason, since the pipeline forwards those.

  • The text-generation pipeline decodes greedily unless you set do_sample=True.
  • Generation settings can only be set when the pipeline is constructed.
  • max_length and max_new_tokens are interchangeable in a pipeline call.
  • By default generated_text holds only the model's new text.
  • Needing temperature control means you must drop to model.generate.
  • The pipeline ignores the model's generation_config.json.

Assumes Transformers v5 (5.18): the text-generation pipeline's fallback is max_new_tokens=256, do_sample=True, temperature=0.7, applied only where the model's generation_config.json is silent.