Text Generation
PyTorch
English
recurrent-depth
fineweb-edu
File size: 1,575 Bytes
3110cd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
"""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)]