Cvetka-R1-27B / usage /chat.py
klokedm's picture
Cvetka-R1-27B P20 research release
753087c
Raw History Blame Contribute Delete
5.11 kB
"""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()