model2vec icon indicating copy to clipboard operation
model2vec copied to clipboard

Byte-level BPE custom vocabulary distillation double-encodes token prefixes

Open AryanRG opened this issue 1 month ago • 2 comments

With a byte-level BPE tokenizer, distilling a custom vocabulary sends internal token strings back through the teacher tokenizer as raw text. For example, the new token Ġzebra is encoded as ['Ġ', 'Ä', 'ł', 'zeb', 'ra'] instead of the teacher's normal tokenization of zebra, ['Ġzeb', 'ra']. The stored vector matches the former sequence.

Reproduced on main e53b8f50799959dc43713f9b01b56dfb5c429076, Python 3.13.12, tokenizers 0.22.2, transformers 5.3.0 and torch 2.10.0. This example builds a tiny tokenizer and teacher locally; no model downloads are needed.

import numpy as np
import torch
from tokenizers import Tokenizer, decoders, models, pre_tokenizers, trainers
from transformers import GPT2Config, GPT2Model, PreTrainedTokenizerFast
from model2vec.distill import distill_from_model
from model2vec.distill.inference import create_embeddings

torch.manual_seed(0)
tok = Tokenizer(models.BPE())
tok.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=True)
tok.decoder = decoders.ByteLevel()
tok.train_from_iterator(
    ["the cat sat on the mat zeb ra", "a dog ran"] * 20,
    trainers.BpeTrainer(
        vocab_size=300,
        initial_alphabet=pre_tokenizers.ByteLevel.alphabet(),
        special_tokens=["<pad>"],
    ),
)
hf = PreTrainedTokenizerFast(tokenizer_object=tok, pad_token="<pad>")
model = GPT2Model(GPT2Config(
    vocab_size=len(hf), n_embd=8, n_layer=1, n_head=2, n_positions=16,
)).eval()
sm = distill_from_model(
    model=model, tokenizer=hf, vocabulary=["zebra"], device="cpu",
    pca_dims=None, sif_coefficient=None, token_remove_pattern=None,
    quantize_to="float32",
)
row = sm.tokenizer.token_to_id("Ġzebra")
actual_ids = hf("Ġzebra", add_special_tokens=False).input_ids
expected_ids = hf(" zebra", add_special_tokens=False).input_ids
actual_vector, expected_vector = create_embeddings(
    model, [actual_ids, expected_ids], "cpu", hf.pad_token_id,
)
print(hf.convert_ids_to_tokens(actual_ids))
print(hf.convert_ids_to_tokens(expected_ids))
print(np.allclose(sm.embedding[row], actual_vector, atol=1e-6))
print(np.allclose(sm.embedding[row], expected_vector, atol=1e-6))

Output:

['Ġ', 'Ä', 'ł', 'zeb', 'ra']
['Ġzeb', 'ra']
True
False

distill_from_model passes the processed vocabulary to turn_tokens_into_ids, which calls tokenizer.encode(token) for entries absent from the original vocabulary. That appears to encode the byte-level prefix a second time.

Would a fix that converts new byte-level token strings back to text before teacher encoding fit the intended behavior? I can add a regression for custom-vocabulary distillation once the approach is agreed.

AryanRG avatar Oct 18 '26 16:10 AryanRG

Hey @AryanRG,

Thanks for reporting, this indeed seems to be a bug. Feel free to submit a fix.

stephantul avatar Oct 18 '26 16:10 stephantul

Hey @AryanRG,

I already found a fix. Because it uses skeletoken internals, this fix will work for other tokenizers as well.

stephantul avatar Oct 18 '26 16:10 stephantul