nero
Add relaxed grader (--mode relaxed), preserve <think> blocks, and update README with Open SLM Leaderboard results
05aad65 verified Download slm_instruct_bench_grade.py from Emergent-Knowledge/assay: direct link, hf CLI and curl.
- Browser
- Download file 18.7 kB
-
https://huggingface.co/datasets/Emergent-Knowledge/assay/resolve/main/slm_instruct_bench_grade.py
- Command line
-
hf download hf://datasets/Emergent-Knowledge/assay/slm_instruct_bench_grade.py
-
curl -L -o slm_instruct_bench_grade.py https://huggingface.co/datasets/Emergent-Knowledge/assay/resolve/main/slm_instruct_bench_grade.py
18.7 kB
| """Deterministic, standard-library-only grading. Does not call a model. | |
| Usage: python3 grader.py --data slm_instruct_bench.jsonl --responses responses.jsonl | |
| Responses: {"id":"...","response":"..."}; episodes use "responses":["...",...]. | |
| """ | |
| import argparse | |
| import collections | |
| import json | |
| import re | |
| from decimal import Decimal, InvalidOperation | |
| from pathlib import Path | |
| EDGE='.,!?;:"\'()[]{}' | |
| def contract(item): | |
| value=item['check'] | |
| if not value.startswith('json:'):raise ValueError('Executable json: check required') | |
| return json.loads(value[5:]) | |
| def clean(value,c): | |
| return value.strip() if c.get('strip_outer',True) else value | |
| def words(value):return [x.strip(EDGE) for x in value.split()] | |
| def letters(value):return ''.join(re.findall('[A-Za-z]',value)) | |
| def constraint_result(value,rules): | |
| failures=[];w=words(value);lo=[x.casefold() for x in w];lines=value.splitlines() | |
| rows=[[x.casefold() for x in words(line)] for line in lines] | |
| lens=[len(letters(x)) for x in w] | |
| def increasing(seq):return all(a<b for a,b in zip(seq,seq[1:])) | |
| def decreasing(seq):return all(a>b for a,b in zip(seq,seq[1:])) | |
| def at_positions(spec, fn): | |
| pairs=[p.split(':') for p in spec.split(',')] | |
| return all(0<int(i)<=len(w) and fn(lo[int(i)-1],v) for i,v in pairs) | |
| for rule in rules: | |
| key,sep,arg=rule.partition('=');ok=False | |
| if key=='words':ok=len(w)==int(arg) | |
| elif key=='min_words':ok=len(w)>=int(arg) | |
| elif key=='max_words':ok=len(w)<=int(arg) | |
| elif key=='lines':ok=len(lines)==int(arg) and all(x.strip() for x in lines) | |
| elif key=='line_words':ok=[len(words(x)) for x in lines]==list(map(int,arg.split(','))) | |
| elif key=='allowed':ok=all(x in arg.casefold().split(',') for x in lo) | |
| elif key=='unique':ok=len(lo)==len(set(lo)) | |
| elif key=='lower':ok=value==value.lower() | |
| elif key=='upper':ok=value==value.upper() | |
| elif key=='no_punct':ok=bool(re.fullmatch(r'[A-Za-z0-9\s]+',value)) | |
| elif key=='no_spaces':ok=' ' not in value | |
| elif key=='forbid':ok=not any(x.casefold() in value.casefold() for x in arg) | |
| elif key=='alphabet':ok=all(x in arg or x.isspace() for x in value) | |
| elif key=='contains':ok=all(x in lo for x in arg.casefold().split(',')) | |
| elif key=='ban':ok=all(x not in lo for x in arg.casefold().split(',')) | |
| elif key=='count': | |
| token,n=arg.rsplit(':',1);ok=lo.count(token.casefold())==int(n) | |
| elif key=='first':ok=bool(w) and lo[0]==arg.casefold() | |
| elif key=='last':ok=bool(w) and lo[-1]==arg.casefold() | |
| elif key=='nth': | |
| n,t=arg.split(':',1);i=int(n)-1;ok=0<=i<len(w) and lo[i]==t.casefold() | |
| elif key=='first_initial':ok=bool(w) and w[0].casefold().startswith(arg.casefold()) | |
| elif key=='last_initial':ok=bool(w) and w[-1].casefold().startswith(arg.casefold()) | |
| elif key=='last_suffix':ok=bool(w) and w[-1].casefold().endswith(arg.casefold()) | |
| elif key=='all_initial':ok=bool(w) and all(x.casefold().startswith(arg.casefold()) for x in w) | |
| elif key=='all_contains':ok=bool(w) and all(arg.casefold() in x.casefold() for x in w) | |
| elif key=='each_count': | |
| token,n=arg.split(':');ok=bool(w) and all(x.casefold().count(token.casefold())==int(n) for x in w) | |
| elif key=='word_lengths':ok=[len(letters(x)) for x in w]==list(map(int,arg.split(','))) | |
| elif key=='min_length':ok=bool(w) and all(len(letters(x))>=int(arg) for x in w) | |
| elif key=='max_length':ok=bool(w) and all(len(letters(x))<=int(arg) for x in w) | |
| elif key=='even_lengths':ok=bool(w) and all(len(letters(x))%2==0 for x in w) | |
| elif key=='ascending':ok=lo==sorted(lo) and len(lo)==len(set(lo)) | |
| elif key=='descending':ok=lo==sorted(lo,reverse=True) and len(lo)==len(set(lo)) | |
| elif key=='line_ascending':ok=all(increasing(row) for row in rows) | |
| elif key=='line_unique':ok=all(len(row)==len(set(row)) for row in rows) | |
| elif key=='line_starts':ok=len(rows)==len(arg.split(',')) and all(row and row[0]==t for row,t in zip(rows,arg.split(','))) | |
| elif key=='line_ends':ok=len(rows)==len(arg.split(',')) and all(row and row[-1]==t for row,t in zip(rows,arg.split(','))) | |
| elif key=='position_lengths':ok=at_positions(arg,lambda x,n:len(letters(x))==int(n)) | |
| elif key=='position_initials':ok=at_positions(arg,lambda x,c:x.startswith(c)) | |
| elif key=='positions_ascending': | |
| ix=[int(x)-1 for x in arg.split(',')];ok=all(0<=i<len(lo) for i in ix) and increasing([lo[i] for i in ix]) | |
| elif key=='tokens_containing': | |
| char,n=arg.split(':');ok=sum(char in x for x in lo)==int(n) | |
| elif key=='line_sort': | |
| ix=[int(x)-1 for x in arg.split(',')];ok=all(0<=i<len(rows) and increasing(rows[i]) for i in ix) | |
| elif key=='line_initials':ok=len(rows)==len(arg.split(',')) and all(all(x.startswith(c) for x in row) for row,c in zip(rows,arg.split(','))) | |
| elif key=='line_first_initial':ok=all(row and row[0].startswith(arg) for row in rows) | |
| elif key=='first_line_initial':ok=bool(rows) and all(x.startswith(arg) for x in rows[0]) | |
| elif key=='first_line_lengths':ok=bool(rows) and all(len(letters(x))==int(arg) for x in rows[0]) | |
| elif key=='line_lengths':ok=len(rows)==len(arg.split(',')) and all(all(len(letters(x))==int(n) for x in row) for row,n in zip(rows,arg.split(','))) | |
| elif key=='line_first_min':ok=all(row and len(letters(row[0]))>=int(arg) for row in rows) | |
| elif key=='initials':ok=''.join(x[:1] for x in lo)==arg | |
| elif key=='line_token_count': | |
| token,n=arg.split(':');ok=all(row.count(token)==int(n) for row in rows) | |
| elif key=='line_suffix_count': | |
| suffix,n=arg.split(':');ok=all(sum(x.endswith(suffix) for x in row)==int(n) for row in rows) | |
| elif key=='line_initial_count': | |
| i,char,n=arg.split(':');i=int(i)-1;ok=0<=i<len(rows) and sum(x.startswith(char) for x in rows[i])==int(n) | |
| elif key=='line_max_initial':ok=all(max(collections.Counter(x[:1] for x in row).values(),default=0)<=int(arg) for row in rows) | |
| elif key=='line_members': | |
| members,n=arg.split(':');ok=all(sum(x in members.split(',') for x in row)==int(n) for row in rows) | |
| elif key=='line_contains': | |
| i,tokens=arg.split(':');i=int(i)-1;ok=0<=i<len(rows) and all(t in rows[i] for t in tokens.split(',')) | |
| elif key=='line_some_length':ok=all(any(len(letters(x))==int(arg) for x in row) for row in rows) | |
| elif key=='line_letter_parity':ok=all(sum(len(letters(x)) for x in row)%2==({'even':0,'odd':1}[arg]) for row in rows) | |
| elif key=='shared_only': | |
| ok=len(rows)==2 and set(rows[0])&set(rows[1])==set(arg.split(',')) | |
| elif key=='same_line':ok=any(all(t in row for t in arg.split(',')) for row in rows) | |
| elif key=='different_lines': | |
| a,b=arg.split(',');ok=any(a in row for row in rows) and any(b in row for row in rows) and all(not(a in row and b in row) for row in rows) | |
| elif key=='token_lines': | |
| token,n=arg.split(':');ok=sum(token in row for row in rows)==int(n) | |
| elif key=='max_token_lines':ok=all(sum(t in row for row in rows)<=int(arg) for t in set(lo)) | |
| elif key=='lasts_differ': | |
| ends=[row[-1] for row in rows if row];ok=len(ends)==len(rows) and len(ends)==len(set(ends)) | |
| elif key=='firsts_differ': | |
| starts=[row[0] for row in rows if row];ok=len(starts)==len(rows) and len(starts)==len(set(starts)) | |
| elif key=='firsts_ascending':ok=all(rows) and increasing([row[0] for row in rows]) | |
| elif key=='firsts_descending':ok=all(rows) and decreasing([row[0] for row in rows]) | |
| elif key=='lasts_ascending':ok=all(rows) and increasing([row[-1] for row in rows]) | |
| elif key=='lasts_descending':ok=all(rows) and decreasing([row[-1] for row in rows]) | |
| elif key=='tail_ascending':ok=all(increasing(row[1:]) for row in rows) | |
| elif key=='adjacent_different':ok=all(a!=b for a,b in zip(lo,lo[1:])) | |
| elif key=='adjacent_except':ok=all(a!=b for i,(a,b) in enumerate(zip(lo,lo[1:]),1) if i!=int(arg)) | |
| elif key=='endpoints_differ':ok=bool(lo) and lo[0]!=lo[-1] | |
| elif key=='palindrome_tokens':ok=lo==lo[::-1] | |
| elif key=='pattern': | |
| ok=len(lo)==len(arg) and all((arg[i]==arg[j])==(lo[i]==lo[j]) for i in range(len(arg)) for j in range(len(arg))) | |
| elif key=='repeat_halves':ok=len(lo)%2==0 and lo[:len(lo)//2]==lo[len(lo)//2:] | |
| elif key=='reverse_lines':ok=len(rows)==2 and rows[1]==rows[0][::-1] | |
| elif key=='rotate_line':ok=len(rows)==2 and rows[1]==rows[0][int(arg):]+rows[0][:int(arg)] | |
| elif key=='gap': | |
| token,n=arg.split(':');ix=[i for i,t in enumerate(lo) if t==token];ok=len(ix)==2 and ix[1]-ix[0]-1==int(n) | |
| elif key=='length_count': | |
| n,c=map(int,arg.split(':'));ok=lens.count(n)==c | |
| elif key=='length_increasing':ok=increasing(lens) | |
| elif key=='length_decreasing':ok=decreasing(lens) | |
| elif key=='length_ascending_alpha':ok=list(zip(lens,lo))==sorted(zip(lens,lo)) | |
| elif key=='length_descending_alpha':ok=list(zip(lens,lo))==sorted(zip(lens,lo),key=lambda x:(-x[0],x[1])) | |
| elif key=='length_parity':ok=[x%2 for x in lens]==[{'odd':1,'even':0}[x] for x in arg.split(',')] | |
| elif key=='endings_count': | |
| chars,n=arg.split(':');ok=sum(bool(t) and t[-1] in chars for t in lo)==int(n) | |
| elif key=='interior_unique':ok=len(lo[1:-1])==len(set(lo[1:-1])) | |
| elif key=='interior_contains':ok=all(arg in t for t in lo[1:-1]) | |
| elif key=='label_total': | |
| table={t:int(n) for t,n in (p.split(':') for p in arg.split(','))};labels=lo[:-1] | |
| ok=len(labels)==3 and len(set(labels))==3 and all(x in table for x in labels) and lo[-1].isdigit() and int(lo[-1])==sum(table[x] for x in labels) | |
| elif key=='ascending_labels':ok=increasing(lo[:-1]) | |
| elif key=='descending_labels':ok=decreasing(lo[:-1]) | |
| elif key=='disjoint_lines': | |
| sets=[set(x.casefold() for x in words(line)) for line in lines] | |
| ok=all(not (a&b) for i,a in enumerate(sets) for b in sets[i+1:]) | |
| elif key=='line_shorter': | |
| a,b=map(int,arg.split(','));ok=max(a,b)<=len(lines) and len(words(lines[a-1]))<len(words(lines[b-1])) | |
| elif key=='regex':ok=re.fullmatch(arg,value) is not None | |
| elif key=='literal_count': | |
| token,n=arg.rsplit(':',1);ok=value.count(token)==int(n) | |
| elif key=='syllables': | |
| specification=json.loads(arg);table=specification['table'];counts=specification['counts'] | |
| try:ok=[sum(table[x.casefold()] for x in words(line)) for line in lines]==counts | |
| except KeyError:ok=False | |
| else:raise ValueError('Unknown constraint '+key) | |
| if not ok:failures.append(rule) | |
| return failures | |
| def grade_value(response,answer,c): | |
| if not isinstance(response,str):return {'pass':False,'failures':['response must be a string']} | |
| value=clean(response,c);mode=c['type'];failures=[] | |
| if mode=='choice': | |
| if value!=answer:failures=['incorrect option letter or extra output'] | |
| elif mode=='exact': | |
| if not c.get('case_sensitive',False):value=value.casefold();answer=answer.casefold() | |
| if value!=answer:failures=['incorrect literal answer or extra output'] | |
| elif mode=='one_of': | |
| accepted=c['values'] | |
| if not c.get('case_sensitive',False):value=value.casefold();accepted=[x.casefold() for x in accepted] | |
| if value not in accepted:failures=['not an accepted answer'] | |
| elif mode=='number': | |
| try: | |
| pattern={'integer':r'[+-]?[0-9]+','digits':r'[0-9]+'}.get(c.get('format'),r'[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)') | |
| if not re.fullmatch(pattern,value):raise InvalidOperation() | |
| a=Decimal(value);b=Decimal(answer) | |
| if not a.is_finite() or a!=b:failures=['incorrect numeric value'] | |
| except InvalidOperation:failures=['numeric answer required; no units or commentary'] | |
| elif mode=='constraints': | |
| failures=constraint_result(value,c['rules']) | |
| if not value:failures.append('nonempty answer required') | |
| else:raise ValueError('Unknown verifier '+mode) | |
| return {'pass':not failures,'failures':failures} | |
| def clean_model_output(text): | |
| if not isinstance(text, str): | |
| return '' | |
| for stop in ('<|im_end|>', '\nUser:', '\nuser:'): | |
| if stop in text: | |
| text = text.split(stop)[0] | |
| return text.strip() | |
| def _tokens_in_order(expected_str, response_str): | |
| exp = re.findall(r'[a-z0-9]+', str(expected_str).casefold()) | |
| got = re.findall(r'[a-z0-9]+', str(response_str).casefold()) | |
| if not exp: | |
| return False | |
| it = iter(got) | |
| return all(tok in it for tok in exp) | |
| def grade_value_relaxed(response, answer, c): | |
| if not isinstance(response, str): | |
| return {'pass': False, 'failures': ['response must be a string']} | |
| cleaned = clean_model_output(response) | |
| if not cleaned: | |
| return {'pass': False, 'failures': ['nonempty answer required']} | |
| strict = grade_value(cleaned, answer, c) | |
| if strict['pass']: | |
| return strict | |
| mode = c['type'] | |
| ok = False | |
| if mode == 'choice': | |
| m = re.findall(r'(?i)(?:answer(?:\s+is)?|option|choice)\s*[:\-]?\s*\(?([A-D])\)?\b', cleaned) | |
| if m: | |
| ok = m[-1].upper() == answer.upper() | |
| else: | |
| m2 = re.findall(r'\b([A-D])\b', cleaned) | |
| ok = bool(m2) and m2[-1].upper() == answer.upper() | |
| elif mode == 'number': | |
| nums = re.findall(r'[+-]?(?:\d+(?:\.\d+)?|\.\d+)', cleaned) | |
| if nums: | |
| try: | |
| ok = Decimal(nums[-1]) == Decimal(str(answer)) | |
| except InvalidOperation: | |
| ok = False | |
| elif mode == 'exact': | |
| ok = _tokens_in_order(answer, cleaned) | |
| elif mode == 'one_of': | |
| ok = any(_tokens_in_order(v, cleaned) for v in c['values']) | |
| elif mode == 'constraints': | |
| ok = _tokens_in_order(answer, cleaned) | |
| return {'pass': ok, 'failures': [] if ok else strict['failures']} | |
| def grade_relaxed(item, response): | |
| c = contract(item) | |
| if c['type'] != 'episode': | |
| return grade_value_relaxed(response, item['answer'], c) | |
| if not isinstance(response, list) or len(response) != len(c['turns']): | |
| return {'pass': False, 'failures': ['one response for each declared turn is required']} | |
| results = [grade_value_relaxed(v, t['answer'], t['check']) for v, t in zip(response, c['turns'])] | |
| failures = [f'turn {i+1}: {reason}' for i, r in enumerate(results) for reason in r['failures']] | |
| return {'pass': not failures, 'failures': failures, 'turns': results} | |
| def grade(item,response,relaxed=False): | |
| if relaxed:return grade_relaxed(item,response) | |
| c=contract(item) | |
| if c['type']!='episode':return grade_value(response,item['answer'],c) | |
| if not isinstance(response,list) or len(response)!=len(c['turns']): | |
| return {'pass':False,'failures':['one response for each declared turn is required']} | |
| results=[grade_value(v,t['answer'],t['check']) for v,t in zip(response,c['turns'])] | |
| failures=[f'turn {i+1}: {reason}' for i,r in enumerate(results) for reason in r['failures']] | |
| for pair in c.get('equal_turns',[]): | |
| a,b=pair | |
| if response[a].strip().casefold()!=response[b].strip().casefold():failures.append(f'turns {a+1}/{b+1} inconsistent') | |
| return {'pass':not failures,'failures':failures,'turns':results} | |
| def render_initial(item): | |
| p=item['prompt'] | |
| if 'choices' in item:p+='\n\n'+'\n'.join(f'{chr(65+i)}. {s}' for i,s in enumerate(item['choices'])) | |
| return [{'role':'user','content':p}] | |
| def next_messages(item,responses): | |
| """Build actual episode history from actual responses, never oracle answers.""" | |
| c=contract(item);messages=render_initial(item) | |
| if c['type']!='episode':return messages if not responses else None | |
| for i,response in enumerate(responses): | |
| messages.append({'role':'assistant','content':response}) | |
| if i+1<len(c['turns']):messages.append({'role':'user','content':c['turns'][i+1]['prompt']}) | |
| return messages if len(responses)<len(c['turns']) else None | |
| def main(): | |
| ap=argparse.ArgumentParser();ap.add_argument('--data',type=Path,required=True);ap.add_argument('--responses',type=Path,required=True);ap.add_argument('--output',type=Path);ap.add_argument('--mode',choices=['relaxed','strict','both'],default='relaxed') | |
| a=ap.parse_args();items=[json.loads(s) for s in a.data.read_text().splitlines()] | |
| supplied={} | |
| for line in a.responses.read_text().splitlines(): | |
| r=json.loads(line) | |
| if not isinstance(r.get('id'),str):raise ValueError('Response ID must be a string') | |
| if ('response' in r)==('responses' in r):raise ValueError('Supply exactly one response or responses field') | |
| if r['id'] in supplied:raise ValueError('Duplicate response ID '+r['id']) | |
| supplied[r['id']]=r.get('responses',r.get('response')) | |
| known={r['id'] for r in items};extra=set(supplied)-known | |
| if extra:raise ValueError('Unknown response IDs '+str(sorted(extra))) | |
| records=[];cats=collections.defaultdict(list);strict_passed=0;relaxed_passed=0 | |
| for item in items: | |
| if item['id'] not in supplied: | |
| s_res={'pass':False,'failures':['missing response']} | |
| r_res={'pass':False,'failures':['missing response']} | |
| else: | |
| raw=supplied[item['id']] | |
| cleaned=[clean_model_output(x) for x in raw] if isinstance(raw,list) else clean_model_output(raw) | |
| s_res=grade(item,cleaned,relaxed=False) | |
| r_res=grade(item,raw,relaxed=True) | |
| if s_res['pass']:strict_passed+=1 | |
| if r_res['pass']:relaxed_passed+=1 | |
| result=s_res if a.mode=='strict' else r_res | |
| rec={'id':item['id'],'category':item['category'],'strict_pass':s_res['pass'],'relaxed_pass':r_res['pass'],**result} | |
| records.append(rec);cats[item['category']].append(result['pass']) | |
| summary={'items':len(items),'submitted':len(supplied),'mode':a.mode, | |
| 'passed':strict_passed if a.mode=='strict' else relaxed_passed, | |
| 'relaxed_percent':100*relaxed_passed/len(items), | |
| 'strict_percent':100*strict_passed/len(items), | |
| 'categories':{k:{'items':len(v),'passed':sum(v),'percent':100*sum(v)/len(v)} for k,v in cats.items()}, | |
| 'method':'deterministic response grading; no model calls'} | |
| if a.output:a.output.write_text(''.join(json.dumps(x)+'\n' for x in records)) | |
| print(json.dumps(summary,indent=2)) | |
| if __name__=='__main__':main() | |