Howwise RSS
AI & Automation6 min read

Llama 3 eos_token_id and pad_token_id: Correct Values

Short answer

For Llama 3 Instruct, set eos_token_id to both 128001 (<|end_of_text|>) and 128009 (<|eot_id|>), because the model ends a turn with 128009. Llama 3 has no pad token, so pad_token_id is None until you set it.

Key takeaways
  • Instruct models end turns with <|eot_id|> (128009), so stopping only on 128001 often gives endless output.
  • Llama 3 ships with pad_token_id None; reusing eos as pad is fine for inference and batching.
  • Read ids with tokenizer.convert_tokens_to_ids instead of hardcoding them, and confirm them in generation_config.json.
  • In LlamaIndex HuggingFaceLLM, pass stopping_ids and read the tokenizer from llm._tokenizer if you never created one.
  • In fine-tuning, never let pad equal eos with labels masked, or the model never learns to stop.

Which eos and pad token ids does Llama 3 use?

Llama 3 has two different stop tokens, and which one the model emits depends on whether it is a base or an Instruct model. Base models end text with <|end_of_text|> (128001). Instruct models end each assistant turn with <|eot_id|> (128009).

The tokenizer's eos_token usually points to only one of them (128001 in the base repos; many Instruct repos point to 128009, others to 128001). That is why a single eos_token_id is unreliable for Instruct models: generate() stops only on the ids you give it.

Pad is a separate job. Padding fills short sequences so a batch has equal length, and it is masked out by the attention mask. Llama 3 ships no pad token, so tokenizer.pad_token_id is None.

ModelStop token(s)IdsPad token
Llama 3 Base<|end_of_text|>128001None by default
Llama 3 Instruct<|eot_id|> and <|end_of_text|>128009, 128001None by default
Llama 3.1 / 3.2 Instruct<|eot_id|>, <|eom_id|>, <|end_of_text|>128009, 128008, 128001None; <|finetune_right_pad_id|> is 128004
Llama 2 (do not mix)</s>2None
Warning: Llama 3 and Llama 2 ids are unrelated. An eos_token_id of 2 on a Llama 3 model stops on an ordinary token or never fires, and 128009 is out of range for a Llama 2 vocabulary.

Why does Llama 3 never stop generating?

The usual cause is that generation only watches for 128001 while the Instruct model emits 128009 at the end of its answer. The model then continues past the turn, often inventing a new user header or repeating itself until max_new_tokens.

The second cause is a malformed prompt. Instruct models learned to emit <|eot_id|> after text laid out as <|start_header_id|>role<|end_header_id|> blocks. If you send a raw string with no template, the model is out of distribution and may not close the turn.

The third is an old transformers version, which accepts only an int for eos_token_id and silently ignores or fails on a list. Lists work in recent releases (support arrived during the 4.3x series), so upgrade if you see this.

How do I fix the pad_token_id warning in generate() and pipeline?

The warning 'Setting pad_token_id to eos_token_id for open-end generation' appears because pad_token_id is None. generate() falls back to eos and carries on. For a single prompt it is harmless, but you can silence it by setting both values explicitly.

Read the ids from the tokenizer rather than typing numbers. Padding side matters for batches: decoder-only models must be padded on the left at inference, or the new tokens follow pad tokens and quality collapses.

import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline

name = "meta-llama/Meta-Llama-3-8B-Instruct"
tok = AutoTokenizer.from_pretrained(name, padding_side="left")
model = AutoModelForCausalLM.from_pretrained(name, torch_dtype=torch.bfloat16, device_map="auto")

eot = tok.convert_tokens_to_ids("<|eot_id|>")
terminators = [tok.eos_token_id, eot]
if tok.pad_token is None:
    tok.pad_token = tok.eos_token   # needed for batches

messages = [{"role": "user", "content": "Name three prime numbers."}]
inputs = tok.apply_chat_template(
    messages, add_generation_prompt=True, return_tensors="pt", return_dict=True
).to(model.device)

out = model.generate(
    **inputs, max_new_tokens=128,
    eos_token_id=terminators, pad_token_id=tok.eos_token_id,
    do_sample=True, temperature=0.6,
)
print(tok.decode(out[0][inputs["input_ids"].shape[-1]:], skip_special_tokens=True))

# pipeline equivalent
pipe = pipeline("text-generation", model=model, tokenizer=tok)
res = pipe(messages, max_new_tokens=128,
           eos_token_id=terminators, pad_token_id=tok.eos_token_id)
Tip: Pad ids only affect batching and training. Choosing 128001, 128009, a reserved token such as 128002, or 128004 (Llama 3.1 finetune right pad) gives the same output for a single unpadded prompt.

How do I set stopping_ids in LlamaIndex HuggingFaceLLM without a tokenizer object?

HuggingFaceLLM builds the model and tokenizer internally from model_name and tokenizer_name, so your code has no tokenizer variable. You have two options: load a second AutoTokenizer with the same name (cheap, it only reads small files), or reuse the private attribute llm._tokenizer after construction.

stopping_ids is a constructor argument, so the simplest copy-paste route is to load the tokenizer first. Passing the ids inside generate_kwargs also works, and it is forwarded to model.generate().

import torch
from transformers import AutoTokenizer
from llama_index.llms.huggingface import HuggingFaceLLM

name = "meta-llama/Meta-Llama-3-8B-Instruct"
tok = AutoTokenizer.from_pretrained(name)   # same name as the LLM
stop_ids = [tok.eos_token_id, tok.convert_tokens_to_ids("<|eot_id|>")]

llm = HuggingFaceLLM(
    model_name=name,
    tokenizer_name=name,
    context_window=8192,
    max_new_tokens=256,
    stopping_ids=stop_ids,
    generate_kwargs={
        "do_sample": True,
        "temperature": 0.6,
        "top_p": 0.9,
        "eos_token_id": stop_ids,
        "pad_token_id": tok.eos_token_id,
    },
    tokenizer_kwargs={"max_length": 8192, "padding_side": "left"},
    model_kwargs={"torch_dtype": torch.bfloat16},
    device_map="auto",
)

# alternative: reuse the internal tokenizer after construction
print(llm._tokenizer.convert_tokens_to_ids("<|eot_id|>"))
Tip: Use messages_to_prompt and completion_to_prompt functions (or the chat interface with a Llama 3 template) so the prompt has the header structure. Otherwise the model may not emit <|eot_id|> even with correct stopping_ids. Argument names can shift between llama-index versions, so confirm against your installed signature.

How do I check that eos and pad are set correctly?

Do not trust the numbers in a tutorial. Print what your installed tokenizer and model actually report, then decode a real output without stripping special tokens to see how it ended.

  1. Print tok.eos_token_id, tok.pad_token_id and tok.convert_tokens_to_ids('<|eot_id|>'). Expect an eos of 128001 or 128009, pad None, and eot 128009.
  2. Print model.generation_config. Llama 3 Instruct lists an eos_token_id of 128001 and 128009; Llama 3.1 lists [128001, 128008, 128009].
  3. Generate a short answer and decode with skip_special_tokens=False.
  4. Confirm the output ends with <|eot_id|> (or <|end_of_text|>) and that the generated length is below max_new_tokens. If it hit the limit, the stop ids or prompt format are wrong.
print(tok.eos_token_id, tok.pad_token_id, tok.convert_tokens_to_ids("<|eot_id|>"))
print(model.generation_config)
gen = out[0][inputs["input_ids"].shape[-1]:]
print(tok.decode(gen, skip_special_tokens=False))
print(len(gen), "tokens, last id:", gen[-1].item())

What mistakes break Llama 3 stopping and fine-tuning?

Most failures come from a few repeated errors. The fine-tuning one is the least obvious, because training runs without any error.

MistakeEffectFix
Base ids (128001 only) on InstructOutput runs past the turnAdd 128009 to eos_token_id
Raw string prompt, no chat templateModel does not close the turnUse apply_chat_template with add_generation_prompt=True
pad = eos in training with pad labels masked to -100Real EOS labels are masked too, so the model never learns to stopUse a distinct pad such as 128004, or keep the EOS label unmasked
Right padding at inferenceGarbled batched outputpadding_side='left' for generate, right for training
Llama 2 id 2 on Llama 3Wrong or no stopRead ids from the tokenizer
Old transformersList form ignored or errorsUpgrade transformers
Tool calls on 3.1Turn ends with <|eom_id|> (128008)Include 128008 in stop ids if you parse tool calls
Warning: Changing the pad token in a fine-tuning setup alters the training labels. If you add a new token, resize the embeddings and retrain, or prefer an existing reserved token to avoid that.

Common questions

Is it safe to set pad_token_id to eos_token_id for Llama 3?

Yes for inference. The attention mask hides pad positions, so the choice has no effect on output. In training it is risky only if you also mask every pad-valued label, which hides the real EOS.

Which reserved token can I use as a Llama 3 pad token?

Any unused <|reserved_special_token_N|>, for example 128002, works since it never appears in normal text. Llama 3.1 also provides <|finetune_right_pad_id|> at 128004, which is the cleanest choice for training.

Why is eos_token_id 128009 in some repos and 128001 in others?

Meta's tokenizer config differs between base and Instruct releases, and later repo updates changed some defaults. Always read generation_config.json and the tokenizer rather than assuming, and pass both ids to generate().

Does the <|eom_id|> token matter for Llama 3.1 chat?

<|eom_id|> (128008) signals the end of a message when the model expects a tool result before continuing. For plain chat you rarely see it, but include it in stop ids if you use tool calling.

Can I stop generation with a stop string instead of ids?

Yes, recent transformers accept stop_strings in generate() together with the tokenizer argument. Token ids are more reliable because they match exactly and need no string decoding on each step.

Related topics:llama-3transformersllamaindextokenizer