[GOLD] Byte-offset alignment for byte-fallback tokenizers (Gemma 4), not only ByteLevel
Feature request
Extend GOLD's byte-offset alignment (use_extended_uld=True, #5885) from ByteLevel BPE tokenizers to byte-fallback BPE tokenizers such as Gemma 4's. A Gemma 4 student would then be aligned by bytes with a ByteLevel teacher, instead of falling back to positional ULD.
As a smaller, optional second part: build the hybrid loss's vocabulary map (ULDLoss._initialize_vocabulary_mapping) by the bytes each token decodes to, not by its raw string.
Motivation
How I got here. I hit this while designing cross-tokenizer distillation for Halo framework, by reading GOLD's code. I have not run a Gemma 4 GOLD training. What I did run are the tokenizer-level checks below (CPU, under 30 s).
The gap.
- #6388 recommends a
google/gemma-4-E4B-itstudent with aQwen/Qwen3-4Bteacher. Because Gemma 4 is not ByteLevel, the example has to use--no_use_extended_uld:encode_with_byte_offsetsraisesNotImplementedErrorfor every non-ByteLevel tokenizer. - Positional ULD pairs the i-th student token with the i-th teacher token. After the first word the two tokenizers split differently, the pairs cover different text. It still trains something on the example's single-span rows (the original ULD approximation), but this is exactly the mismatch the byte-offset alignment from #5885 was added to fix.
- The X-Token PR #6126 forces byte offsets (
use_extended_uld or xtoken_loss_type != "none") and reusesULDLoss._align_by_byte_offsets. As I read it, X-Token cannot take a Gemma 4 student at all until this limit is lifted.
Why ByteLevel-only is not needed. Gemma 4's fast tokenizer gives clean char offsets that cover the text with no gaps. The one special case is byte fallback: a character outside the vocab becomes several <0xXX> tokens that all report the same char span. Each <0xXX> token is exactly one byte, so the span splits exactly. The bytes of each piece are known:
<0xXX>: that one byte;- any other piece: its UTF-8 bytes, with
▁(U+2581) read as one space byte.
This gives exact byte spans on both paths:
- Off-policy (
encode_with_byte_offsets): char offsets → byte offsets, and runs of repeated spans are split by each piece's bytes. This is what_split_repeated_byte_offsetsalready does for ByteLevel; only the per-piece byte count changes. Todaypiece_byte_lenreturnslen(piece), which counts<0xF0>as 6 bytes. - On-policy (
_maybe_add_completion_byte_offsets, spans from the sampled ids): the cumulative sum of each piece's bytes, the same waypiece_byte_lenis used today.
Reproduction (TRL main at e29597afc, transformers 5.16.1, tokenizers 0.23.1, CPU):
import re
from transformers import AutoTokenizer
from trl.experimental.gold.gold_trainer import ULDLoss
from trl.experimental.utils import encode_with_byte_offsets
student = AutoTokenizer.from_pretrained("google/gemma-4-E4B-it") # byte-fallback BPE
teacher = AutoTokenizer.from_pretrained("Qwen/Qwen3-4B") # ByteLevel BPE
text = '{"name": "get_weather",\n "args": {"city": "Kyiv"}} héllo 🦙 東京'
try:
encode_with_byte_offsets(student.backend_tokenizer, [text])
except NotImplementedError as e:
print("today:", e)
enc = student(text, add_special_tokens=False, return_offsets_mapping=True)
pieces = student.convert_ids_to_tokens(enc["input_ids"])
print([(p, o) for p, o in zip(pieces, enc["offset_mapping"]) if p.startswith("<0x")])
def piece_bytes(piece: str) -> bytes:
"""Bytes of one byte-fallback BPE piece: `<0xXX>` is one byte, `▁` is a space."""
m = re.fullmatch(r"<0x([0-9A-F]{2})>", piece)
return bytes([int(m[1], 16)]) if m else piece.replace("▁", " ").encode()
spans, cursor = [], 0
for piece in pieces:
n = len(piece_bytes(piece))
spans.append((cursor, cursor + n))
cursor += n
assert b"".join(map(piece_bytes, pieces)) == text.encode()
[(teacher_ids, teacher_spans)] = encode_with_byte_offsets(teacher.backend_tokenizer, [text])
s_groups, t_groups = ULDLoss._align_by_byte_offsets(spans, teacher_spans)
print(f"{len(pieces)} student / {len(teacher_spans)} teacher tokens -> {len(s_groups)} aligned groups")
Output:
today: Cross-tokenizer ULD currently supports only ByteLevel BPE tokenizers (Llama-3, Qwen, SmolLM, Phi, Mistral v0.3+, …). The given tokenizer is not ByteLevel.
[('<0xF0>', (60, 61)), ('<0x9F>', (60, 61)), ('<0xA6>', (60, 61)), ('<0x99>', (60, 61))]
29 student / 27 teacher tokens -> 24 aligned groups
I also checked that the off-policy path (char offsets with the runs split) and the on-policy path (sum of piece bytes) give identical spans on tool-call JSON, Cyrillic, CJK, emoji, indentation and Gemma's own chat-template markers.
Hybrid vocabulary map (optional part). The map matches raw token strings. That is exact between two ByteLevel tokenizers, but between Gemma 4 and Qwen3 the same text is spelled differently (▁hello vs Ġhello, é vs é). Matched pairs over the full vocabularies:
| Matching | Gemma 4 ↔ Qwen3 matched tokens |
|---|---|
| raw strings (today) | 24,519, of which 160 decode to different bytes |
_canonical_token from #6126 (leading ▁/_/space → Ġ) |
63,687 |
| decoded bytes (proposed) | 95,822 |
The 160 are wrong matches: the same string means different bytes in the two tokenizers.
Proposed change
trl/experimental/utils.py: one per-piece byte helper for ByteLevel and byte-fallback pieces, used byencode_with_byte_offsets,_split_repeated_byte_offsetsand the on-policypiece_byte_lenpath. Accept a tokenizer only when it is ByteLevel, or a BPE model withbyte_fallback: true, a▁normalizer and a decoder that does not strip.- Refuse decoders with
Strip(older SentencePiece tokenizers such as Llama 2). They drop the leading space when decoding, so on-policy the piece bytes differ from the decoded text the teacher re-encodes. Those keep positional ULD, as today. - Make the existing monotonic-offset check stricter: also raise when the spans do not cover the text bytes exactly, instead of aligning over a gap.
- Optional:
_initialize_vocabulary_mappingmatches tokens by decoded bytes. Byte-fallback and special tokens stay unmatched. - Tests: the Gemma 4 tokenizer already used in
tests/experimental/test_gold_trainer.pyagainst a ByteLevel tokenizer. They cover a byte-fallback run, off-policy spans == on-policy spans, theStriprefusal and the byte-matched vocabulary map. - The Gemma 4 command in
examples/gold_chatbot_arena/gold_chatbot_arena.pydrops--no_use_extended_uld.
Questions:
- One PR, or the offsets first and the vocabulary map as a follow-up?
- Should this land before #6126, or inside it, since X-Token needs the same offsets?
Your contribution
I can open the PR once this is assigned to me.