trl icon indicating copy to clipboard operation
trl copied to clipboard

[GOLD] Byte-offset alignment for byte-fallback tokenizers (Gemma 4), not only ByteLevel

Open Strongich opened this issue 1 month ago • 0 comments

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-it student with a Qwen/Qwen3-4B teacher. Because Gemma 4 is not ByteLevel, the example has to use --no_use_extended_uld: encode_with_byte_offsets raises NotImplementedError for 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 reuses ULDLoss._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_offsets already does for ByteLevel; only the per-piece byte count changes. Today piece_byte_len returns len(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 way piece_byte_len is 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

  1. trl/experimental/utils.py: one per-piece byte helper for ByteLevel and byte-fallback pieces, used by encode_with_byte_offsets, _split_repeated_byte_offsets and the on-policy piece_byte_len path. Accept a tokenizer only when it is ByteLevel, or a BPE model with byte_fallback: true, a ▁ normalizer and a decoder that does not strip.
  2. 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.
  3. 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.
  4. Optional: _initialize_vocabulary_mapping matches tokens by decoded bytes. Byte-fallback and special tokens stay unmatched.
  5. Tests: the Gemma 4 tokenizer already used in tests/experimental/test_gold_trainer.py against a ByteLevel tokenizer. They cover a byte-fallback run, off-policy spans == on-policy spans, the Strip refusal and the byte-matched vocabulary map.
  6. The Gemma 4 command in examples/gold_chatbot_arena/gold_chatbot_arena.py drops --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.

Strongich avatar Oct 28 '26 18:10 Strongich