Datasets:
File size: 6,104 Bytes
7a088d4 | 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 | #!/usr/bin/env python3
"""Small deterministic training-text recall comparison; never opens held-out binaries."""
import argparse
import gc
import hashlib
import json
from pathlib import Path
import numpy as np
import torch
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, GenerationConfig
def digest(path):
with path.open('rb') as handle:
return hashlib.file_digest(handle, 'sha256').hexdigest()
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--samples', type=int, default=3)
parser.add_argument('--output', default='worklog/2026-10-25-wikisource-recall.json')
args = parser.parse_args()
if args.samples < 1:
parser.error('--samples must be positive')
run = Path('runs/classical-smollm2-trunk')
export = run / 'export'
data = Path('unified/training-tokens-v1/build-006')
manifest = json.loads((data / 'manifest.json').read_text())
for name in ('wikisource.train.bin', 'splits.jsonl', 'tokenizer.model'):
assert digest(data / name) == manifest['files'][name], name
assert digest(export / 'tokenizer.model') == digest(data / 'tokenizer.model')
rows = [json.loads(line) for line in (data / 'splits.jsonl').open()]
eligible = [r for r in rows if r['source'] == 'wikisource' and r['split'] == 'train' and r['tokens'] >= 384]
eligible.sort(key=lambda r: hashlib.sha256(('recall-small-v1:' + r['id']).encode()).hexdigest())
selected, groups = [], set()
for row in eligible:
if row['group'] in groups:
continue
selected.append(row)
groups.add(row['group'])
if len(selected) == args.samples:
break
if len(selected) != args.samples:
parser.error(f'Only {len(selected)} distinct eligible training groups available')
tokenizer = AutoTokenizer.from_pretrained(export, local_files_only=True, trust_remote_code=True)
stream = np.memmap(data / 'wikisource.train.bin', mode='r', dtype='<u4')
samples = []
for row in selected:
# Skip document BOS, then use 128 real training tokens as context and 64 as target.
offset = row['split_offset'] + 1
tokens = stream[offset:offset + 192].astype(np.int64).tolist()
assert not any(t in (1, 2, 3) for t in tokens)
samples.append(dict(id=row['id'], title=row['title'], group=row['group'],
source_url=row['date_evidence']['source_url'], split='train',
split_offset=offset, prompt_ids=tokens[:128], target_ids=tokens[128:],
prompt=tokenizer.decode(tokens[:128]), reference=tokenizer.decode(tokens[128:])))
report = dict(selection=f'First {args.samples} distinct groups sorted by SHA256(recall-small-v1:document_id), train only; no output-based selection',
prompt_tokens=128, target_tokens=64, decoding='greedy, EOS stop, no repetition penalties', samples=samples, models={})
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
for name, path in [('27500', run / 'checkpoints/checkpoint-00027500'), ('final', export)]:
model = AutoModelForCausalLM.from_pretrained(
path, config=AutoConfig.from_pretrained(export, local_files_only=True),
generation_config=GenerationConfig.from_pretrained(export, local_files_only=True),
local_files_only=True, dtype=torch.float32, attn_implementation='sdpa',
).to(device).eval()
results = []
for sample in samples:
ids = torch.tensor([sample['prompt_ids'] + sample['target_ids']], device=device)
with torch.inference_mode():
with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == 'cuda'):
logits = model(ids, use_cache=False).logits[:, 127:-1].float()
targets = ids[:, 128:]
nll = torch.nn.functional.cross_entropy(logits.flatten(0, 1), targets.flatten()).item()
accuracy = (logits.argmax(-1) == targets).float().mean().item()
generated = model.generate(
input_ids=ids[:, :128], attention_mask=torch.ones_like(ids[:, :128]),
max_new_tokens=64, do_sample=False, use_cache=True,
pad_token_id=tokenizer.pad_token_id, eos_token_id=tokenizer.eos_token_id,
)[0, 128:].tolist()
target = sample['target_ids']
prefix = 0
for actual, expected in zip(generated, target):
if actual != expected:
break
prefix += 1
text = tokenizer.decode(generated, skip_special_tokens=True)
char_prefix = 0
for actual, expected in zip(text, sample['reference']):
if actual != expected:
break
char_prefix += 1
result = dict(id=sample['id'], title=sample['title'], suffix_nll=nll,
teacher_forced_token_accuracy=accuracy, exact_match=generated == target,
exact_prefix_tokens=prefix, exact_prefix_characters=char_prefix,
positional_token_accuracy=sum(a == b for a, b in zip(generated, target)) / len(target),
generated_ids=generated, generated=text)
results.append(result)
print(name, json.dumps(result, ensure_ascii=False), flush=True)
report['models'][name] = dict(path=str(path), weights_sha256=digest(path / 'model.safetensors'),
results=results, mean_suffix_nll=sum(r['suffix_nll'] for r in results) / len(results),
exact_matches=sum(r['exact_match'] for r in results))
del model
gc.collect()
if device.type == 'cuda':
torch.cuda.empty_cache()
Path(args.output).write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
print('Saved', args.output)
if __name__ == '__main__':
main()
|