DiChat-Mini-10M-Base / release_benchmark_v1.py
DiChat-models's picture
Initial DiChat Mini 10M Base release
76389c9 verified
Raw History Blame Contribute Delete
7.71 kB
import json,random,torch,hashlib,datetime
from pathlib import Path
from collections import defaultdict
from tokenizers import Tokenizer
from transformers import AutoTokenizer,AutoModelForCausalLM
from model import Config,DiChat10M
R=Path(__file__).resolve().parent
rng=random.Random(20261028)
torch.set_num_threads(4)
names=[('кот','cat'),('робот','robot'),('мальчик','boy'),('пёс','dog'),('заяц','rabbit'),('девочка','girl'),('медведь','bear'),('пират','pirate'),('учёный','scientist'),('дракон','dragon')]
colors=[('красный','red'),('синий','blue'),('зелёный','green'),('жёлтый','yellow'),('белый','white'),('чёрный','black'),('серый','gray'),('розовый','pink'),('оранжевый','orange'),('фиолетовый','purple')]
places=[('лесу','forest'),('саду','garden'),('парке','park'),('доме','house'),('замке','castle'),('гараже','garage'),('сарае','barn'),('магазине','shop'),('школе','school'),('поле','field')]
items=[('ключ','key'),('мяч','ball'),('камень','stone'),('цветок','flower'),('фонарь','lamp'),('подарок','gift'),('карандаш','pencil'),('рюкзак','backpack'),('телефон','phone'),('билет','ticket')]
tasks=[]
def add(cat,ru,en,gr,wr,ge,we):
tasks.append(dict(category=cat,ru=ru,en=en,ru_good=gr,ru_bad=wr,en_good=ge,en_bad=we))
for i in range(100):
a,b=rng.sample(range(10),2);c,d=rng.sample(range(10),2)
if i%2:
ru=f'Предмет А был {colors[c][0]}. Предмет Б был {colors[d][0]}. Предмет Б был '
en=f'Object A was {colors[c][1]}. Object B was {colors[d][1]}. Object B was '
c,d=d,c
else:
ru=f'Предмет А был {colors[c][0]}, но предмет Б был {colors[d][0]}. Предмет А был '
en=f'Object A was {colors[c][1]}, but object B was {colors[d][1]}. Object A was '
add('attributes',ru,en,colors[c][0]+'.',colors[d][0]+'.',colors[c][1]+'.',colors[d][1]+'.')
for i in range(100):
a,b=rng.sample(range(10),2);c,d=rng.sample(range(10),2)
if i%2:
ru=f'{names[a][0].capitalize()} был в {places[c][0]}. {names[b][0].capitalize()} был в {places[d][0]}. Где был {names[b][0]}? В '
en=f'The {names[a][1]} was in the {places[c][1]}. The {names[b][1]} was in the {places[d][1]}. Where was the {names[b][1]}? In the '
c,d=d,c
else:
ru=f'{names[a][0].capitalize()} был в {places[c][0]}, а {names[b][0]} был в {places[d][0]}. Где был {names[a][0]}? В '
en=f'The {names[a][1]} was in the {places[c][1]}, and the {names[b][1]} was in the {places[d][1]}. Where was the {names[a][1]}? In the '
add('locations',ru,en,places[c][0]+'.',places[d][0]+'.',places[c][1]+'.',places[d][1]+'.')
for i in range(100):
a,b=rng.sample(range(10),2);c,d=rng.sample(range(10),2)
if i%2:
ru=f'У {names[a][0]} был {items[c][0]}, а у {names[b][0]} был {items[d][0]}. У {names[b][0]} был '
en=f'The {names[a][1]} had a {items[c][1]}, while the {names[b][1]} had a {items[d][1]}. The {names[b][1]} had a '
c,d=d,c
else:
ru=f'У {names[a][0]} был {items[c][0]}, а у {names[b][0]} был {items[d][0]}. У {names[a][0]} был '
en=f'The {names[a][1]} had a {items[c][1]}, while the {names[b][1]} had a {items[d][1]}. The {names[a][1]} had a '
add('ownership',ru,en,items[c][0]+'.',items[d][0]+'.',items[c][1]+'.',items[d][1]+'.')
for i in range(100):
a=rng.randrange(10);c,d=rng.sample(range(10),2)
if i%2:
ru=f'Сначала {names[a][0]} был в {places[c][0]}. Затем он перешёл в {places[d][0]}. После этого он вернулся в {places[c][0]}. Теперь он в '
en=f'First the {names[a][1]} was in the {places[c][1]}. Then it went to the {places[d][1]}. After that it returned to the {places[c][1]}. Now it is in the '
good,bad=c,d
else:
ru=f'Сначала {names[a][0]} был в {places[c][0]}. Затем он перешёл в {places[d][0]}. Теперь он в '
en=f'First the {names[a][1]} was in the {places[c][1]}. Then it went to the {places[d][1]}. Now it is in the '
good,bad=d,c
add('event_tracking',ru,en,places[good][0]+'.',places[bad][0]+'.',places[good][1]+'.',places[bad][1]+'.')
for i in range(100):
a,b=rng.sample(range(10),2);c,d=rng.sample(range(10),2)
if i%2:
ru=f'{names[a][0].capitalize()} не взял {items[c][0]}. Вместо этого он взял {items[d][0]}. Он взял '
en=f'The {names[a][1]} did not take the {items[c][1]}. Instead, it took the {items[d][1]}. It took the '
good,bad=d,c
else:
ru=f'{names[a][0].capitalize()} взял {items[c][0]}, а {items[d][0]} оставил на месте. Он взял '
en=f'The {names[a][1]} took the {items[c][1]} but left the {items[d][1]} behind. It took the '
good,bad=c,d
add('negation_distractors',ru,en,items[good][0]+'.',items[bad][0]+'.',items[good][1]+'.',items[bad][1]+'.')
rng.shuffle(tasks)
ck=torch.load(R/'latest_big.pt',map_location='cpu',weights_only=False)
dt=Tokenizer.from_file(str(R/'tokenizer_big.json'))
dm=DiChat10M(Config(**ck['config']));dm.load_state_dict(ck['model']);dm.eval().to('cuda' if torch.cuda.is_available() else 'cpu')
print('LOADING TinyStories',flush=True)
tt=AutoTokenizer.from_pretrained('roneneldan/TinyStories-3M')
tm=AutoModelForCausalLM.from_pretrained('roneneldan/TinyStories-3M').eval().to(next(dm.parameters()).device)
def score(model,tokenize,prefix,ending):
ids=tokenize(prefix)+tokenize(ending);n=len(tokenize(prefix))
if len(ids)>512:return None
x=torch.tensor([ids[:-1]],device=next(model.parameters()).device)
with torch.inference_mode():
o=model(x)
logits=o.logits if hasattr(o,'logits') else o
lp=logits.float().log_softmax(-1)[0]
return sum(lp[k-1,ids[k]].item() for k in range(n,len(ids)))/max(1,len(ids)-n)
denc=lambda s:dt.encode(s).ids
tenc=lambda s:tt.encode(s,add_special_tokens=False)
for j,t in enumerate(tasks):
dg=score(dm,denc,t['ru'],t['ru_good']);db=score(dm,denc,t['ru'],t['ru_bad'])
tg=score(tm,tenc,t['en'],t['en_good']);tb=score(tm,tenc,t['en'],t['en_bad'])
t['dichat_correct']=dg>db if dg is not None and db is not None else None
t['tiny_correct']=tg>tb if tg is not None and tb is not None else None
if (j+1)%100==0:print('EVALUATED',j+1,'/',len(tasks),flush=True)
summary={}
for cat in sorted(set(t['category'] for t in tasks)):
subset=[t for t in tasks if t['category']==cat]
summary[cat]={m:{'correct':sum(t[m] is True for t in subset),'evaluated':sum(t[m] is not None for t in subset)} for m in ('dichat_correct','tiny_correct')}
summary['OVERALL']={m:{'correct':sum(t[m] is True for t in tasks),'evaluated':sum(t[m] is not None for t in tasks)} for m in ('dichat_correct','tiny_correct')}
out={'benchmark':'DiChat Release Benchmark v1.0','created_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'checkpoint_step':ck['step'],'dichat_parameters':sum(p.numel() for p in dm.parameters()),'tiny_model':'roneneldan/TinyStories-3M','method':'500 paired RU/EN cloze comparisons, 5 skills x 100, fixed seed, mean per-token log-probability, each model evaluated in its primary language; custom exploratory benchmark, not standardized; independently tokenized endings; not generative QA','limitations':['Template-generated examples','Different languages and tokenizers','Possible lexical and length bias','No independent item review','No proof of generalization or overall model superiority'],'summary':summary,'items':tasks}
(R/'release_benchmark_v1_results.json').write_text(json.dumps(out,ensure_ascii=False,indent=2),encoding='utf-8')
print('FINAL_SUMMARY',json.dumps(summary,ensure_ascii=False),flush=True)