File size: 5,106 Bytes
753087c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
"""Generate a single text answer with a downloaded Cvetka-R1-27B version."""
import argparse
import hashlib
import json
import re
import sys
import unicodedata
from pathlib import Path

from gams_micka import tokenizer_pin

MICKA_SHA256 = 'b3326f8fc365e8f3f4b9545f6cafba8e2dab454352d825066c78f1384bbc6353'
LONGSFT_SERVING_SHA256 = '0eea3ae96556cc2176b666ed125d7d988a38758d77defca711bd51fc13b78a25'
RESERVED_SPELLING = re.compile(r'⸢(?=[^⸢⸥\s]{1,64}⸥)')
CHANNEL = re.compile(r'⸢CHANNEL⸥(?:thought|analysis)\s*.*?⸢/CHANNEL⸥', re.DOTALL)


def read_checked(root, name, expected):
    data = (root / name).read_bytes()
    if hashlib.sha256(data).hexdigest() != expected:
        raise ValueError(f'{name} differs from its expected SHA-256')
    return data


def load_chat(root):
    manifest = json.loads((root / 'export_manifest.json').read_bytes())
    read_checked(root, 'tokenizer.json', MICKA_SHA256)
    tokenizer = tokenizer_pin.load(root)
    if len(tokenizer) != 65536:
        raise ValueError('expected the 65,536-ID Micka tokenizer')
    protocol = json.loads(read_checked(root, 'chat_protocol.json', manifest['files']['chat_protocol.json']))
    if [tokenizer.convert_tokens_to_ids(t) for t in protocol['stop_tokens']] != protocol['stop_token_ids']:
        raise ValueError('the tokenizer and chat protocol disagree on stop IDs')
    if manifest['stage'] == 'longsft-anchor':
        name, digest = 'serving_chat_template.jinja', LONGSFT_SERVING_SHA256
    else:
        name = 'chat_template.jinja'
        digest = manifest['files'][name]
    return tokenizer, read_checked(root, name, digest).decode(), protocol


def render(tokenizer, template, question, thinking):
    question = RESERVED_SPELLING.sub('⸢\u2060', unicodedata.normalize('NFC', question))
    prompt = tokenizer.apply_chat_template(
        [{'role': 'user', 'content': question}], chat_template=template, tokenize=False,
        add_generation_prompt=True, enable_thinking=thinking, preserve_thinking=True,
    )
    ids = tokenizer.encode(prompt, add_special_tokens=False)
    if not ids or ids[0] != tokenizer.bos_token_id:
        raise ValueError('the chat template must supply exactly one initial BOS')
    return ids


def visible_answer(raw, thinking):
    # Publish only the final answer. An unfinished or malformed thought has no displayable answer.
    raw = raw.strip()
    if raw.startswith('⸢CHANNEL⸥'):
        thought = CHANNEL.match(raw)
        if thought:
            raw = raw[thought.end():].strip()
        elif thinking and not raw.startswith('⸢CHANNEL⸥final'):
            return ''
    elif thinking:
        return ''
    if raw.startswith('⸢CHANNEL⸥final'):
        raw = raw.removeprefix('⸢CHANNEL⸥final').strip()
    if '⸢CHANNEL⸥' in raw or '⸢/CHANNEL⸥' in raw or '<think>' in raw:
        return ''
    return raw


def generate(root, question, device, dtype, thinking, max_new_tokens):
    import torch
    from gams_micka.cvetka.eval_media import load_model

    tokenizer, template, protocol = load_chat(root)
    ids = render(tokenizer, template, question, thinking)
    net = load_model(root, device=device, dtype=getattr(torch, dtype)).eval()
    if len(ids) + max_new_tokens > net.config.text_config.max_position_embeddings:
        raise ValueError('prompt and requested generation exceed the configured context')
    tokens = torch.tensor([ids], device=device)
    stops = protocol['stop_token_ids']
    with torch.inference_mode():
        output = net.generate(
            input_ids=tokens, attention_mask=torch.ones_like(tokens), do_sample=False,
            eos_token_id=stops, suppress_tokens=protocol['suppress_token_ids'],
            pad_token_id=tokenizer.pad_token_id, max_new_tokens=max_new_tokens,
        )
    new_ids = output[0, len(ids):].tolist()
    stopped = bool(new_ids and new_ids[-1] in stops)
    raw = tokenizer.decode(new_ids[:-1] if stopped else new_ids, skip_special_tokens=False)
    return visible_answer(raw, thinking), len(new_ids), stopped


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('model', type=Path, help='downloaded model directory')
    parser.add_argument('question')
    parser.add_argument('--device', default='cuda', choices=('cuda', 'cpu'))
    parser.add_argument('--dtype', default='bfloat16', choices=('bfloat16', 'float32'))
    parser.add_argument('--max-new-tokens', type=int, default=128)
    parser.add_argument('--thinking', action='store_true')
    args = parser.parse_args()
    if args.max_new_tokens < 1 or not args.question.strip():
        parser.error('a question and a positive token budget are required')
    answer, count, stopped = generate(args.model, args.question, args.device, args.dtype,
                                      args.thinking, args.max_new_tokens)
    if answer:
        print(answer)
    if not stopped:
        print(f'Reached the {count}-token generation limit.', file=sys.stderr)
    if not answer:
        print('No final answer was produced.', file=sys.stderr)


if __name__ == '__main__':
    main()