"""LFM2.5 tokenizer helpers and the chat format."""
import re
TOKENIZER, REVISION = "LiquidAI/LFM2.5-230M", "40cb2ad3b3044d5a41eee083a6103c8b523afa45"
BOS, END_DOC, IM_START, IM_END = 1, 2, 6, 7
def load_tokenizer():
from tokenizers import Tokenizer
tok = Tokenizer.from_pretrained(TOKENIZER, revision=REVISION)
for name, want in (("<|startoftext|>", BOS), ("<|endoftext|>", END_DOC),
("<|im_start|>", IM_START), ("<|im_end|>", IM_END)):
assert tok.token_to_id(name) == want, name
tok.encode_special_tokens = True # special-token text inside data stays plain text
return tok
def strip_think(text):
"""Remove ...; an unclosed block means the answer never came."""
text = re.sub(r".*?", "", text, flags=re.S)
return "" if "" in text else text.split("")[-1].strip()
def encode_chat(tok, messages, add_reply=False):
"""-> (ids, labels); only assistant text and its <|im_end|> are trained on."""
enc = lambda s: tok.encode(s, add_special_tokens=False).ids
ids, train = [BOS], [False]
for m in messages:
head = [IM_START] + enc(m["role"] + "\n")
body = enc(m["content"]) + [IM_END]
mine = m["role"] == "assistant"
ids += head + body + enc("\n")
train += [False] * len(head) + [mine] * len(body) + [False] * len(enc("\n"))
if add_reply:
head = [IM_START] + enc("assistant\n")
ids += head
train += [False] * len(head)
return ids, [t if on else -100 for t, on in zip(ids, train)]