Files
ModelHub XC c1ce9811bb 初始化项目,由ModelHub XC社区提供模型
Model: Xirui1208/selective-readtwice-7b-early-evaluated-20260928
Source: Original Platform
2026-11-17 05:18:17 +08:00

188 lines
13 KiB
Python

"""Shared training/inference runtime: exact paging, frozen reader, auditable rewards."""
from __future__ import annotations
import asyncio, hashlib, json, math, sqlite3, sys, time
from pathlib import Path
import aiohttp
from transformers import AutoTokenizer
ROOT=Path(__file__).resolve().parent
CFG=json.loads((ROOT/'config.json').read_text())
sys.path.insert(0,CFG['source_repo'])
from selective.protocol_readtwice import TEMPLATE_SKIM,TEMPLATE_UPDATE_READTWICE,TEMPLATE_FINAL,NO_MEMORY,KEEP_MEMORY,clean_gist,build_outline
from selective.protocol_selective_v64 import format_gate_prompt
from selective.answer_scoring import extract_last_boxed,formal_qa_metrics
from selective.protocol_gate_hybrid_legacy_v64 import balanced_page_ranges
def tokenizer(): return AutoTokenizer.from_pretrained(CFG['model_path'],local_files_only=True)
def chat_ids(tok,text): return tok.apply_chat_template([{'role':'user','content':text}],tokenize=True,add_generation_prompt=True)
def read_jsonl(path):
with open(path) as f: return [json.loads(x) for x in f if x.strip()]
def atomic_json(path,obj):
path=Path(path); temp=path.with_suffix(path.suffix+'.tmp'); temp.write_text(json.dumps(obj,ensure_ascii=False,indent=2)); temp.replace(path)
def data_fingerprint(example):
payload=[example['question'],example['chunks'],CFG['model_revision'],CFG['chunk_tokens'],CFG['max_page_sections'],CFG['gate_prompt_budget'],'unicode_safe_v1_raw_memory1024']
if CFG.get('memory_update_protocol'):payload.append(CFG['memory_update_protocol'])
return hashlib.sha256(json.dumps(payload,ensure_ascii=False).encode()).hexdigest()
def slot_positions(ids, marker):
width=len(marker)
return [i+width-1 for i in range(len(ids)-width+1) if ids[i:i+width]==marker]
def plan_pages(tok,question,gists,*,budget=None,max_sections=None):
"""Balanced contiguous pages, recursively split by REAL chat token count.
No prompt truncation. Every global ID occurs once. Local IDs are 1-based,
global IDs 0-based, and the explicit map is persisted with each page.
"""
budget=CFG['gate_prompt_budget'] if budget is None else budget
cap=CFG['max_page_sections'] if max_sections is None else max_sections
if not gists: raise ValueError('A document must have at least one chunk')
if not 0<budget<=CFG['model_context']: raise ValueError('Invalid gate budget')
marker=tok.encode('<gate_slot>\n',add_special_tokens=False)
pages=[]
def add(start,end):
outline=build_outline(gists[start:end]); prompt=format_gate_prompt(outline,question,end-start)
ids=chat_ids(tok,prompt)
if len(ids)>budget:
if end-start==1: raise ValueError(f'One section cannot fit: {len(ids)} > {budget}; refusing silent truncation')
middle=start+(end-start+1)//2; add(start,middle); add(middle,end); return
positions=slot_positions(ids,marker)
if len(positions)!=end-start: raise ValueError('Invalid or injected gate slot marker')
pages.append({'global_ids':list(range(start,end)),'outline':outline,'prompt':prompt,'input_ids':ids,'slot_positions':positions,'input_tokens':len(ids)})
for start,end in balanced_page_ranges(len(gists),target_page_sections=cap): add(start,end)
if [j for p in pages for j in p['global_ids']]!=list(range(len(gists))): raise AssertionError('Pagination lost/duplicated/reordered chunks')
return pages
def gold_coverage(example,selected):
chosen=set(selected); facts=example['supporting_facts']
if not facts: raise ValueError('No gold evidence')
covered=[any(set(a)<=chosen for a in f['alternatives']) for f in facts]
return sum(covered)/len(covered),all(covered)
def reward(result,baseline,example,efficiency_weight=0.25):
"""Accuracy tiers cannot be overturned by cost savings (lambda <= .5).
Gold coverage provides training-only credit for multi-hop bridge evidence.
Savings are rewarded only for an exact correct answer. Dropping a question
the read-all reader answered correctly incurs an additional penalty.
"""
if not 0<=efficiency_weight<=.5: raise ValueError('Efficiency weight breaks accuracy priority')
correct=result['em']; regression=float(baseline['em']>0 and not correct)
recall,complete=gold_coverage(example,result['selected'])
savings=1-result['read_token_fraction']
value=2*correct-2*regression+.1*(1-correct)*result['f1']+.2*recall-.5*(not complete)+efficiency_weight*correct*savings
if not result['box_valid']: value-=.25
return float(value)
class Reader:
def __init__(self,tok,concurrency=192,cache_path=None):
self.tok=tok; self.sem=asyncio.Semaphore(concurrency); self.counter=0; self.inflight={}
self.update_template=TEMPLATE_UPDATE_READTWICE
if CFG.get('memory_update_protocol'):
from selective.protocol_readtwice_conservative import templates
self.update_template=templates(CFG['memory_update_protocol'])[0]
self.db=sqlite3.connect(str(cache_path or ROOT/'data'/'reader_cache.sqlite'),timeout=120)
self.db.execute('PRAGMA journal_mode=WAL'); self.db.execute('PRAGMA busy_timeout=120000')
self.db.execute('CREATE TABLE IF NOT EXISTS responses (key TEXT PRIMARY KEY, value TEXT NOT NULL)'); self.db.commit()
self.session=None; self.network_requests=0; self.cache_hits=0
async def __aenter__(self):
self.session=aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=1800),connector=aiohttp.TCPConnector(limit=256)); return self
async def __aexit__(self,*_):
await self.session.close(); self.db.close()
async def generate(self,prompt,max_tokens):
ids=chat_ids(self.tok,prompt)
if len(ids)+max_tokens>CFG['model_context']:
raise ValueError(f'Context overflow: {len(ids)} + {max_tokens}; never truncate prompts')
key=hashlib.sha256(json.dumps([CFG['model_revision'],ids,max_tokens,801],separators=(',',':')).encode()).hexdigest()
cached=self.db.execute('SELECT value FROM responses WHERE key=?',(key,)).fetchone()
if cached: self.cache_hits+=1; return json.loads(cached[0])
if key in self.inflight: return await self.inflight[key]
future=asyncio.get_running_loop().create_future(); self.inflight[key]=future
try:
async with self.sem:
url=CFG['reader_urls'][self.counter%len(CFG['reader_urls'])]; self.counter+=1
payload={'model':'reader','prompt':ids,'max_tokens':max_tokens,'temperature':0,'top_p':1,'seed':801}
for attempt in range(4):
try:
async with self.session.post(url,json=payload) as response:
body=await response.json()
if response.status!=200: raise RuntimeError(f'HTTP {response.status}: {body}')
break
except (aiohttp.ClientError,asyncio.TimeoutError):
if attempt==3: raise
await asyncio.sleep(2**attempt)
choice=body['choices'][0]
result={'text':choice['text'],'finish_reason':choice['finish_reason'],'prompt_tokens':body['usage']['prompt_tokens'],'completion_tokens':body['usage']['completion_tokens']}
self.db.execute('INSERT OR IGNORE INTO responses VALUES (?,?)',(key,json.dumps(result))); self.db.commit(); self.network_requests+=1
future.set_result(result); return result
except BaseException as exc:
future.set_exception(exc); future.exception(); raise
finally: self.inflight.pop(key,None)
async def outlines(self,example):
responses=await asyncio.gather(*(self.generate(TEMPLATE_SKIM.format(chunk=c),CFG['skim_tokens']) for c in example['chunks']))
gists=[clean_gist(r['text']) for r in responses]
if any(not g for g in gists): raise ValueError('Empty outline')
# A capped outline can omit topics; fail open by reading its entire chunk.
forced=[i for i,r in enumerate(responses) if r['finish_reason']=='length']
return {'fingerprint':data_fingerprint(example),'gists':gists,'force_read_ids':forced,'skim_usage':{'prompt_tokens':sum(r['prompt_tokens'] for r in responses),'completion_tokens':sum(r['completion_tokens'] for r in responses)},'pages':plan_pages(self.tok,example['question'],gists)}
async def rollout(self,example,prepared,selected,*,trace=False):
chosen=sorted(set(map(int,selected)))
if any(i<0 or i>=len(example['chunks']) for i in chosen): raise ValueError('Unknown selected chunk')
# Shared fail-open behavior in training and deployment.
chosen=sorted(set(chosen)|set(prepared.get('force_read_ids',[])))
mapping={gid:(page,i+1) for page in prepared['pages'] for i,gid in enumerate(page['global_ids'])}
if set(mapping)!=set(range(len(example['chunks']))): raise ValueError('Invalid page-to-document map')
memory=NO_MEMORY; updates=[]; usage={'prompt_tokens':0,'completion_tokens':0}; capped=0
for gid in chosen:
page,local=mapping[gid]
prompt=self.update_template.format(chunk=example['chunks'][gid],prompt=example['question'],memory=memory,section_id=local,outline=page['outline'])
response=await self.generate(prompt,CFG['memory_tokens'])
text=response['text'].strip()
if text.upper()!=KEEP_MEMORY:
# Match checkpoint's memagent_raw_accept_with_readtwice_keep.
# Persist a REPLACEMENT, never append a memory delta.
memory=text
capped+=int(response['finish_reason']=='length')
for k in usage: usage[k]+=response[k]
if trace: updates.append({'global_id':gid,'local_id':local,'page_global_ids':page['global_ids'],'response':text,'memory_after':memory,'finish_reason':response['finish_reason']})
final=await self.generate(TEMPLATE_FINAL.format(prompt=example['question'],memory=memory),CFG['answer_tokens'])
for k in usage: usage[k]+=final[k]
answer=extract_last_boxed(final['text'])
scores=[formal_qa_metrics(answer or '',a) for a in example.get('answers',[])]
result={'id':example['id'],'selected':chosen,'read_chunks':len(chosen),'total_chunks':len(example['chunks']),
'read_token_fraction':sum(example['chunk_lengths'][i] for i in chosen)/sum(example['chunk_lengths']),
'answer':answer,'raw_answer':final['text'],'box_valid':answer is not None,
'em':max((s['em'] for s in scores),default=None),'f1':max((s['f1'] for s in scores),default=None),
'sub_em':max((s['sub_em'] for s in scores),default=None),'usage':usage,'capped_memory_updates':capped,'page_count':len(prepared['pages'])}
if 'supporting_facts' in example:
result['gold_recall'],result['gold_complete']=gold_coverage(example,chosen)
if trace: result['updates']=updates; result['final_memory']=memory
return result
async def prepare_main(splits,limit=None,baseline=True):
tok=tokenizer(); start=time.time()
async with Reader(tok) as reader:
sem=asyncio.Semaphore(48)
async def one(ex,handle):
async with sem:
p=await reader.outlines(ex)
if baseline: p['baseline']=await reader.rollout(ex,p,range(ex['num_chunks']))
p['id']=ex['id']; handle.write(json.dumps(p,ensure_ascii=False)+'\n'); handle.flush()
print(json.dumps({'prepared':ex['id'],'elapsed':round(time.time()-start),'pages':len(p['pages']),'chunks':ex['num_chunks'],'baseline_em':p.get('baseline',{}).get('em'),'requests':reader.network_requests,'cache_hits':reader.cache_hits}),flush=True)
for split in splits:
examples=read_jsonl(ROOT/'data'/f'{split}.jsonl')
if limit: examples=examples[:limit]
path=ROOT/'data'/f'{split}.prepared.jsonl'
expected={ex['id']:data_fingerprint(ex) for ex in examples}
previous=read_jsonl(path) if path.exists() else []
valid={r['id']:r for r in previous if r.get('fingerprint')==expected.get(r['id']) and (not baseline or 'baseline' in r)}
temp=path.with_suffix('.tmp')
temp.write_text(''.join(json.dumps(r,ensure_ascii=False)+'\n' for r in valid.values())); temp.replace(path)
done=set(valid)
with path.open('a') as handle: await asyncio.gather(*(one(ex,handle) for ex in examples if ex['id'] not in done))
if __name__=='__main__':
import argparse
ap=argparse.ArgumentParser(); ap.add_argument('--splits',nargs='+',default=['train','calibration','test']); ap.add_argument('--limit',type=int); ap.add_argument('--outlines-only',action='store_true'); a=ap.parse_args()
asyncio.run(prepare_main(a.splits,a.limit,not a.outlines_only))