Download chat_format.py from aldigobbler/constoloop: direct link, hf CLI and curl.
- Browser
- Download file 1.58 kB
-
https://huggingface.co/aldigobbler/constoloop/resolve/main/chat_format.py
- Command line
-
hf download hf://aldigobbler/constoloop/chat_format.py
-
curl -L -o chat_format.py https://huggingface.co/aldigobbler/constoloop/resolve/main/chat_format.py
1.58 kB
| """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 <think>...</think>; an unclosed block means the answer never came.""" | |
| text = re.sub(r"<think>.*?</think>", "", text, flags=re.S) | |
| return "" if "<think>" in text else text.split("</think>")[-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)] | |