"""Freeze numeric tasks and screen the effect of sharing on complete answers."""
import argparse
from hashlib import sha256
import json
from pathlib import Path
import random
import re
import torch
from tokenizers import Tokenizer
from crossqkv.lisa_effect_screen import WORDS
from crossqkv.lisa_generate import GenerationDecoder, generate
from crossqkv.lisa_tail import TorchTail
from functional.model import StreamingLM
from functional.run import write_json
TASKS = ('lookup', 'latest', 'addition', 'count')
SEEDS = {'screen': 621001, 'fit': 621002, 'validation': 621003, 'test': 621004}
COUNTS = {'screen': 8, 'fit': 24, 'validation': 8, 'test': 32}
SCHEDULES = {'native': (), 'direct_3': (15, 19, 23),
'direct_4': (11, 15, 19, 23), 'direct_5': (7, 11, 15, 19, 23)}
STOP_TEXT = ('<|im_end|>', '<|endoftext|>')
MAX_NEW_TOKENS = 24
def fixed_problems():
output = {}
for split, seed in SEEDS.items():
rng = random.Random(seed)
rows = []
for task in TASKS:
for i in range(COUNTS[split]):
if task in ('lookup', 'latest'):
keys = rng.sample(WORDS, 12)
values = rng.sample(range(20, 100), 12)
pos = rng.randrange(len(keys))
key = keys[pos]
if task == 'latest':
later = rng.randrange(1, len(keys))
earlier = rng.randrange(later)
keys[earlier] = keys[later]
pos, key = later, keys[later]
schedule = ', '.join(f'{k}={v}' for k, v in zip(keys, values))
descriptor = 'last recorded' if task == 'latest' else 'recorded'
question = f'Records in time order: {schedule}.\nWhat is the {descriptor} number for {key}?'
answer = values[pos]
elif task == 'addition':
a, b = sorted((rng.randint(20, 89), rng.randint(20, 89)))
question = f'What is {a} plus {b}?'
answer = a + b
else:
first, second = rng.sample(WORDS, 2)
answer = rng.randint(10, 15)
values = [first] * answer + [second] * rng.randint(3, 9)
rng.shuffle(values)
question = f"Items: {', '.join(values)}.\nHow many items are exactly '{first}'?"
rows.append({'id': f'{split}-{task}-{i:03}', 'task': task,
'question': question, 'answer': answer})
output[split] = rows
# Arithmetic questions can repeat across independently seeded splits.
# Keep the first generated occurrence and fill duplicates with new disjoint sums.
used = set()
replacement = random.Random(621005)
for rows in output.values():
for row in rows:
while row['task'] == 'addition' and row['question'] in used:
a, b = sorted((replacement.randint(20, 89), replacement.randint(20, 89)))
row.update(question=f'What is {a} plus {b}?', answer=a+b)
if row['question'] in used:
raise ValueError('Prompt repeated across the frozen set')
used.add(row['question'])
return output
def prompt(question):
return ('<|im_start|>user\n' + question + '\nReply with the integer and no other text.'
'<|im_end|>\n<|im_start|>assistant\n\n\n\n\n')
def final_integer(text):
# Only completed reasoning prefixes precede an answer.
text = re.sub(r'\A\s*(?:.*?\s*)+', '', text, flags=re.S).strip()
if '' in text or '' in text:
return None
match = re.fullmatch(r'(?:[Ff]inal answer:\s*|[Aa]nswer:\s*)?([+-]?\d+)\.?', text)
if not match:
match = re.search(r'(?:^|\n)\s*(?:[Ff]inal answer|[Aa]nswer):\s*([+-]?\d+)\.?\s*\Z', text)
return int(match[1]) if match else None
def grade(tokenizer, tokens, stop, expected):
whole = tokenizer.decode(tokens, skip_special_tokens=False)
body = tokenizer.decode(tokens[:-1] if stop == 'eos' else tokens,
skip_special_tokens=False)
value = final_integer(body) if stop == 'eos' else None
return {'tokens': tokens, 'response': whole, 'stop': stop, 'answer': value,
'correct': value == expected}
def evaluate(model, tokenizer, examples, arms, adapters=None):
stop_ids = {tokenizer.token_to_id(text) for text in STOP_TEXT}
if None in stop_ids or len(stop_ids) != len(STOP_TEXT):
raise ValueError('Unexpected tokenizer stop tokens')
ids = [tokenizer.encode(prompt(x['question']), add_special_tokens=False).ids for x in examples]
expanded = [x for x in ids for _ in arms]
schedules = list(arms.values()) * len(examples)
predictions = iter(generate(model, expanded, schedules, stop_ids, MAX_NEW_TOKENS, adapters))
return [{'id': x['id'], 'task': x['task'], 'gold': x['answer'],
'arms': {mode: grade(tokenizer, *next(predictions), x['answer']) for mode in arms}}
for x in examples]
def summarize(rows):
results = {}
for task in TASKS:
group = [row for row in rows if row['task'] == task]
results[task] = {}
for name in SCHEDULES:
original_correct = lambda row: row['arms']['native']['correct']
produced_wrong = lambda row: row['arms'][name]['answer'] is not None and not row['arms'][name]['correct']
results[task][name] = {
'n': len(group),
'correct': sum(row['arms'][name]['correct'] for row in group),
'unscored': sum(row['arms'][name]['answer'] is None for row in group),
'native_correct_to_wrong_integer': [
row['id'] for row in group if original_correct(row) and produced_wrong(row)],
}
return results
def choose(summary):
options = []
for task, arms in summary.items():
if arms['native']['correct'] >= 6:
for arm in ('direct_3', 'direct_4', 'direct_5'):
losses = arms[arm]['native_correct_to_wrong_integer']
if len(losses) >= 2:
options.append((len(losses), arms['native']['correct'],
len(SCHEDULES[arm]), task, arm))
if not options:
return None
_, _, _, task, arm = max(options)
return {'task': task, 'arm': arm, 'recipients': list(SCHEDULES[arm])}
def fingerprint(path):
return sha256(path.read_bytes()).hexdigest()
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--source', required=True, type=Path)
parser.add_argument('--out', required=True, type=Path)
parser.add_argument('--seconds', default=21600, type=int)
parser.add_argument('--batch-prompts', default=2, type=int, choices=(1, 2))
parser.add_argument('--execution-batch-prompts', type=int, choices=(1, 2),
help='Use a different execution batch on resume after replaying completed rows')
parser.add_argument('--preflight', action='store_true')
args = parser.parse_args()
torch.set_num_threads(1)
args.out.mkdir(exist_ok=True)
files = {name: fingerprint(args.source/name) for name in
('manifest.json', 'model_config.json', 'tokenizer.json')}
protocol = {'weights': files, 'schedules': SCHEDULES, 'cap': MAX_NEW_TOKENS,
'stops': STOP_TEXT, 'batch_prompts': args.batch_prompts,
'decode': 'full vocabulary greedy, closed thinking prefix'}
manifest = args.out/'frozen.json'
frozen = {'protocol': protocol, 'problems': fixed_problems()}
frozen = json.loads(json.dumps(frozen))
if manifest.exists() and json.loads(manifest.read_text()) != frozen:
raise ValueError('Frozen protocol or prompts changed')
write_json(manifest, frozen)
model = StreamingLM(args.source/'weights', json.loads((args.source/'model_config.json').read_text()),
seconds=args.seconds, process_swap_limit_kib=None)
tokenizer = Tokenizer.from_file(str(args.source/'tokenizer.json'))
examples = frozen['problems']['screen']
if args.preflight:
ids = torch.tensor([tokenizer.encode(prompt(examples[0]['question']),
add_special_tokens=False).ids])
hidden = torch.from_numpy(model.embedding(ids.numpy()))
with torch.no_grad():
expected, _ = TorchTail(model, 0)(hidden, None, torch.tensor([ids.shape[1]]),
'native', ())
decoder = GenerationDecoder(model, [()], [0])
decoder.advance(ids[:, :-2])
actual = decoder.advance(ids[:, -2:])
ref = expected[:, -2:]
torch.testing.assert_close(actual, ref, atol=8e-5, rtol=7e-5)
write_json(args.out/'preflight.json', {'prompt_id': examples[0]['id'],
'prompt_tokens': ids.shape[1], 'tail_hidden_max_abs': float((actual-ref).abs().max())})
return
path = args.out/'screen-rows.json'
rows = json.loads(path.read_text()) if path.exists() else []
if [r['id'] for r in rows] != [x['id'] for x in examples[:len(rows)]]:
raise ValueError('Existing screen results do not match frozen prompts')
batch = args.execution_batch_prompts or args.batch_prompts
if batch != args.batch_prompts:
if len(rows) < batch:
raise ValueError('The alternate batch requires enough already evaluated prompts for replay')
replay = evaluate(model, tokenizer, examples[:batch], SCHEDULES)
if replay != rows[:batch]:
raise ValueError('Alternate batch changed the first completed token streams')
write_json(args.out/'execution-batch-replay.json',
{'frozen_sha256': fingerprint(manifest), 'batch_prompts': batch,
'matched_rows': [row['id'] for row in replay]})
print('validated execution batch', batch, flush=True)
for start in range(len(rows), len(examples), batch):
rows.extend(evaluate(model, tokenizer, examples[start:start+batch], SCHEDULES))
write_json(path, rows)
print('screen complete', len(rows), '/', len(examples), flush=True)
summary = summarize(rows)
write_json(args.out/'screen-summary.json', summary)
write_json(args.out/'selection.json', {'frozen_sha256': fingerprint(manifest),
'screen_sha256': fingerprint(path),
'chosen': choose(summary)})
if __name__ == '__main__':
main()