Llama 3 Strange Characters in Output: Causes and Fixes
Llama 3 strange characters in output come from showing raw byte-level BPE tokens (Ġ, Ċ), decoding one token at a time (�), or printing special tokens like <|eot_id|>. Decode accumulated token IDs with tokenizer.decode and stop on IDs 128001 and 128009.
- Ġ and Ċ are the byte-level BPE spellings of a space and a newline, and you only see them when you print token strings instead of calling tokenizer.decode on IDs.
- A � appears when a multi-byte UTF-8 character is split across tokens, so decode the accumulated IDs and print only the new suffix, holding back text that ends in �.
- skip_special_tokens=True removes <|eot_id|> and header tokens but never touches Ġ or Ċ, because those are ordinary vocabulary entries.
- Stop generation on IDs 128001 and 128009, build prompts with apply_chat_template(add_generation_prompt=True), and mask reserved token IDs in a custom sampler.
- Run print(repr(text)) and print(ids) first: the symbol you see tells you which of the causes you have.
Llama 3 strange characters in output: which symbol do you have?
Llama 3 strange characters in output show up in a handful of recognisable ways, and each symbol points to a different cause. Before changing code, print the raw string and the IDs, because terminals and notebooks hide whitespace and sometimes render bytes oddly.
Use print(repr(text)) and print(ids[:20]). The repr shows the exact characters, including \n and \ufffd, so you can match the symptom below.
| What you see | Cause | One-line fix |
|---|---|---|
| Ġthe, ĊĊ, Ġ in the text | You printed token strings (convert_ids_to_tokens, tokenize, str(token)), not decoded text | tokenizer.decode(ids) |
| � (U+FFFD) in emoji, accents, CJK | One token holds only part of a multi-byte UTF-8 character and you decoded it alone | Decode all generated IDs, print only the new suffix, skip a suffix ending in � |
| <|eot_id|>, <|end_of_text|>, <|start_header_id|>assistant | Special tokens decoded into text, or the model was not stopped | skip_special_tokens=True and stop on 128001 and 128009 |
| Model keeps writing headers, a fake user turn, or junk after the answer | No stop token configured, or no chat template used | eos_token_id=[128001, 128009] and apply_chat_template |
| <|reserved_special_token_17|> and similar | Sampler picked an untrained reserved ID (128002 and up) | Set those logits to -inf before sampling |
| Words glued together: Hello world as Helloworld | You called .strip() on each single-token piece | Never strip per token; keep the leading space |
ids = generated_ids # list[int]
print(ids[:20])
print(repr(tok.decode(ids))) # what the user should see
print(tok.convert_ids_to_tokens(ids[:20])) # Ġ / Ċ live here
print(repr(tok.decode(ids, skip_special_tokens=True))) Why does Llama 3 output Ġ and Ċ?
Llama 3 uses a tiktoken-style byte-level BPE vocabulary of 128,256 entries. Every token is a sequence of raw bytes, and to store those bytes as readable vocabulary strings the Hugging Face tokenizer maps each byte to a printable Unicode character. The space byte (0x20) becomes Ġ and the newline byte (0x0A) becomes Ċ.
So the token ' the' is stored as 'Ġthe', and a blank line is 'ĊĊ'. That is the internal spelling, not a bug in the model. It appears whenever you look at tokens rather than text: tokenizer.tokenize(), tokenizer.convert_ids_to_tokens(), or printing a token object in a loop.
tokenizer.decode(ids) reverses the byte mapping, joins the bytes and decodes them as UTF-8, which is why it returns clean text. convert_tokens_to_string(tokens) does the same for a list of token strings, but only if you pass all of them together.
skip_special_tokens has no effect on Ġ and Ċ because they are not special tokens. They are normal vocabulary entries, and the flag only removes IDs registered as special (for example 128000, 128001, 128006, 128007, 128009).
ids = tok("Hello world\n\nBye", add_special_tokens=False).input_ids
print(tok.convert_ids_to_tokens(ids)) # ['Hello', 'Ġworld', 'ĊĊ', 'Bye']
print(repr(tok.decode(ids))) # 'Hello world\n\nBye'
print(tok.convert_tokens_to_string(tok.convert_ids_to_tokens(ids))) Why do I get � when decoding one token at a time?
A single character such as an emoji or an accented letter can need 2 to 4 UTF-8 bytes, and the BPE may split those bytes across several tokens. Decoding the first token alone gives an incomplete byte sequence, so Python substitutes the replacement character � (U+FFFD). The text is not corrupted; you simply looked too early.
The fix is incremental decoding: keep every generated ID, decode the whole list each step, and print only the part you have not printed yet. If the decoded string currently ends in �, hold it back until the next token completes the character.
Decoding the full list is quadratic over very long outputs, but for a few thousand tokens the cost is negligible next to the model forward pass. This is also why you must not strip text per token: the leading space belongs to the next word, so ' the' correctly decodes with its space.
generated, printed = [], ""
def emit(new_id):
global printed
generated.append(new_id)
text = tok.decode(generated, skip_special_tokens=True,
clean_up_tokenization_spaces=False)
if text.endswith("\ufffd"):
return "" # incomplete character, wait for more bytes
piece = text[len(printed):]
printed = text
return pieceHow do I stop <|eot_id|>, header tokens and reserved tokens?
Llama 3.1 Instruct marks the end of an assistant turn with <|eot_id|> (128009), and <|end_of_text|> (128001) can also occur. The chat format wraps each turn as <|start_header_id|>role<|end_header_id|> then the content then <|eot_id|>. If your loop does not stop on these IDs, the model carries on, often inventing a new header or a user turn.
The base tokenizer config may list only 128001 as EOS, so model.generate stops late unless you override it. A raw prompt without the template is the other common cause of rambling: the model never sees the headers it was trained on.
Reserved tokens are a separate trap in a custom sampler. IDs from 128002 upward (other than the named ones such as 128006, 128007, 128008, 128009) are placeholders such as <|reserved_special_token_0|>. They are barely trained, but with high temperature or a wide top-k they can be picked and print as strange strings, so mask them.
- Build the prompt with tok.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt"), which appends the assistant header for you.
- Pass eos_token_id=[128001, 128009] to model.generate, or break your manual loop when the sampled ID is in {128001, 128009}.
- In a custom sampler, set logits of every ID from 128000 to 128255 to -inf except the stop IDs.
- Decode with skip_special_tokens=True as a safety net, not as the main fix.
A complete working token-by-token loop for Llama 3.1 Instruct
This loop uses the KV cache, so each step feeds only the newest token instead of the whole sequence. Without past_key_values every step reprocesses the entire prompt, which makes manual generation many times slower than generate. It also masks special IDs, samples from top-k, stops on both stop tokens and prints without garbling.
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
model_id = "meta-llama/Llama-3.1-8B-Instruct"
tok = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
model_id, torch_dtype=torch.bfloat16, device_map="auto")
messages = [{"role": "user", "content": "Say hello in French, with an emoji."}]
cur = tok.apply_chat_template(
messages, add_generation_prompt=True, return_tensors="pt"
).to(model.device)
STOP = {128001, 128009}
vocab = model.get_output_embeddings().weight.shape[0]
ban = torch.zeros(vocab, dtype=torch.bool, device=model.device)
ban[128000:] = True
ban[list(STOP)] = False
generated, printed, past = [], "", None
with torch.no_grad():
for _ in range(512):
out = model(input_ids=cur, past_key_values=past, use_cache=True)
past = out.past_key_values
logits = out.logits[0, -1].float()
logits[ban] = float("-inf")
vals, idx = torch.topk(logits / 0.7, 50)
nxt = idx[torch.multinomial(torch.softmax(vals, -1), 1)]
tid = nxt.item()
if tid in STOP:
break
generated.append(tid)
text = tok.decode(generated, skip_special_tokens=True,
clean_up_tokenization_spaces=False)
if not text.endswith("\ufffd"):
print(text[len(printed):], end="", flush=True)
printed = text
cur = nxt.view(1, 1)
final = tok.decode(generated, skip_special_tokens=True,
clean_up_tokenization_spaces=False)
print(final[len(printed):])Should I use TextStreamer instead, and what about clean_up_tokenization_spaces?
Unless you need custom sampling, yes. model.generate with a streamer handles incremental decoding, multi-byte buffering and the KV cache for you. TextStreamer prints to stdout, and TextIteratorStreamer lets you consume text from another thread, for example in a web server. Set skip_prompt=True or the prompt is echoed first.
Most custom logic can be expressed through generate arguments such as temperature, top_k, top_p, logits_processor and bad_words_ids, so reaching for a manual loop is rarely required.
from threading import Thread
from transformers import TextIteratorStreamer
inputs = tok.apply_chat_template(
messages, add_generation_prompt=True,
return_tensors="pt", return_dict=True).to(model.device)
streamer = TextIteratorStreamer(
tok, skip_prompt=True, skip_special_tokens=True,
clean_up_tokenization_spaces=False)
Thread(target=model.generate, kwargs=dict(
**inputs, streamer=streamer, max_new_tokens=512,
do_sample=True, temperature=0.7, top_k=50,
eos_token_id=[128001, 128009])).start()
for chunk in streamer:
print(chunk, end="", flush=True) What does clean_up_tokenization_spaces actually do?
It is a post-processing step in decode that rewrites patterns like ' .' to '.', ' ,' to ',' and ' n't' to "n't". It exists to repair spacing in older WordPiece-style tokenizers. It does not remove Ġ, Ċ, � or special tokens, so turning it on will never fix the symptoms above.
For Llama 3, set it to False explicitly. Left on, it can silently alter legitimate text such as code, French punctuation spacing or a deliberate ' ,' in output, and it makes streamed text differ from the final decode.
The only authoritative statement of the chat format and special token roles is the model card and prompt format page published by Meta; the Hugging Face tokenizer docs describe the decode flags. Beyond those, printing repr and IDs answers most questions faster.
Common questions
Why is skip_special_tokens=True not working on Llama 3.1?
Usually the text is not a special token at all. Ġ and Ċ are byte-mapped normal tokens, and a string such as <|reserved_special_token_5|> may be a real special token that you decoded token by token or through convert_ids_to_tokens, which ignores the flag. Call tokenizer.decode(ids, skip_special_tokens=True) on a list of IDs and the flag works.
What is the difference between convert_ids_to_tokens and decode for Llama 3?
convert_ids_to_tokens returns the vocabulary strings with the byte-to-unicode mapping, so you get Ġ and Ċ and special tokens as literal text. decode converts IDs back to bytes, decodes UTF-8 and optionally drops special tokens, producing readable text.
Can I just replace Ġ with a space and Ċ with a newline?
That works for plain ASCII but breaks other text, because many other bytes are also mapped to unusual characters and multi-byte characters will appear as mojibake. Use tokenizer.decode or convert_tokens_to_string, which reverse the whole mapping correctly.
Why does the model keep generating after its answer finishes?
The generation config may treat only <|end_of_text|> (128001) as a stop token, while Instruct models end turns with <|eot_id|> (128009). Pass eos_token_id=[128001, 128009] to generate, or break on either ID in your loop.
Why is my token-by-token loop so much slower than generate?
If you do not pass past_key_values back in, every step recomputes attention over the whole prompt and history, so cost grows with each token. Reuse the cache and feed only the last token, or use generate with a streamer.