"""Debate, voto y revisión con 5184 tokens por pregunta y método en CPU GGUF."""
import collections,decimal,hashlib,itertools,json,random,re,time
from pathlib import Path
import pandas as pd
import llama_cpp
from huggingface_hub import hf_hub_download
from transformers import AutoTokenizer
ROOT=Path('multiagent-cpu');ROOT.mkdir(parents=True,exist_ok=True)
MODEL_REV='bb5d59e06d9551d752d08b292a50eb208b07ab1f'
MANIFEST={'protocol':'cpu-gguf-512-64-v1','model':'Qwen/Qwen2.5-7B-Instruct-GGUF',
          'revision':MODEL_REV,'quantization':'Q4_K_M','tokenizer_revision':'a09a35458c702b33eeacc393d103063234e8bc28',
          'backend':'llama-cpp-python 0.3.36','threads':8,'context':2048,'input_tokens':512,'output_tokens':64,
          'temperature':0.7,'top_p':0.95,'top_k':50,'min_p':0,'repeat_penalty':1,
          'filler_token':659,'eog_mask':[128247,151643,151645,151662,151663,151664],
          'weight_sha256':['dfce12e3862a5283ccfb88221b48480e58745165de856439950d0f22590580db','539cf93f78e887edea1c04e2d7d8cdaca9d01dae9c9025bcb8accbe29df3d72a'],
          'seeds':'debate 260000+3*ronda+agente; voto 261000+agente; revisión 262000+paso; mismas semillas por pregunta',
          'gsm8k_sha256':'3730d312f6e3440559ace48831e51066acaca737f6eabec99bccb9e4b3c39d14',
          'mmlu_sha256':'6e1b210896afc60f2ea3a1b011733b86dedd74690adce6ff0893346089f83252'}
def run(cases_override=None):
 manifest=ROOT/'manifest.json'
 if cases_override is None:
  if manifest.exists():
   if json.loads(manifest.read_text(encoding='utf8'))!=MANIFEST:raise ValueError('Manifiesto de protocolo incompatible')
  elif (ROOT/'events.json').exists():raise ValueError('Hay eventos sin manifiesto: preservar y revisar antes de reanudar')
  else:manifest.write_text(json.dumps(MANIFEST,ensure_ascii=False,indent=2),encoding='utf8')
 names=['qwen2.5-7b-instruct-q4_k_m-00001-of-00002.gguf','qwen2.5-7b-instruct-q4_k_m-00002-of-00002.gguf']
 paths=[hf_hub_download('Qwen/Qwen2.5-7B-Instruct-GGUF',name,revision=MODEL_REV) for name in names]
 if cases_override is None:
  for path,digest in zip(paths,MANIFEST['weight_sha256']):
   h=hashlib.sha256()
   with open(path,'rb') as f:
    while chunk:=f.read(8*1024*1024):h.update(chunk)
   if h.hexdigest()!=digest:raise ValueError('Hash de pesos inesperado')
 path=paths[0]
 model=llama_cpp.Llama(model_path=path,n_ctx=2048,n_threads=8,n_batch=512,n_gpu_layers=0,verbose=False)
 tok=AutoTokenizer.from_pretrained('Qwen/Qwen2.5-7B-Instruct',revision='a09a35458c702b33eeacc393d103063234e8bc28')
 if cases_override is None:
  for filename,key in [(str(ROOT/'gsm8k-test.jsonl'),'gsm8k_sha256'),(str(ROOT/'mmlu.parquet'),'mmlu_sha256')]:
   if hashlib.sha256(Path(filename).read_bytes()).hexdigest()!=MANIFEST[key]:raise ValueError('Hash del conjunto inesperado')
  gsm=[json.loads(x) for x in (ROOT/'gsm8k-test.jsonl').read_text(encoding='utf8').splitlines()][:10]
  table=pd.read_parquet(ROOT/'mmlu.parquet').head(10)
  cases=[(r['question'],'numeric',r['answer'].split('####')[-1].strip().replace(',','')) for r in gsm]
  for _,r in table.iterrows():
   question=r['question']+'\n'+'\n'.join(f'{chr(65+i)}: {v}' for i,v in enumerate(r['choices']))
   cases.append((question,'letter',chr(65+int(r['answer']))))
 else:cases=cases_override
 filler=tok.encode(' .',add_special_tokens=False);assert filler==[MANIFEST['filler_token']] if cases_override is None else len(filler)==1
 vocab=llama_cpp.llama_model_get_vocab(model._model.model)
 eog=[i for i in range(model.n_vocab()) if llama_cpp.llama_vocab_is_eog(vocab,i)]
 if cases_override is None:assert eog==MANIFEST['eog_mask']
 def mask_eog(ids,scores):scores[eog]=-float('inf');return scores
 processor=llama_cpp.LogitsProcessorList([mask_eog])
 ledger_path=ROOT/'events.json';ledger=json.loads(ledger_path.read_text(encoding='utf8')) if ledger_path.exists() else {}
 def ask(prompt,key,seed):
  if key in ledger:
   old=ledger[key];assert old['prompt']==prompt and old['seed']==seed
   return old['text']
  chat=tok.apply_chat_template([{'role':'user','content':prompt}],tokenize=False,add_generation_prompt=True)
  ids=tok(chat,add_special_tokens=True)['input_ids'];assert ids==model.tokenize(chat.encode(),add_bos=False,special=True)
  if len(ids)>512:raise ValueError(f'{key}: {len(ids)} tokens de entrada significativos exceden 512')
  inputs=filler*(512-len(ids))+ids;model.reset();model.set_seed(seed);started=time.perf_counter()
  generated=list(itertools.islice(model.generate(inputs,temp=.7,top_p=.95,min_p=0,top_k=50,repeat_penalty=1,logits_processor=processor),64))
  assert len(generated)==64
  text=model.detokenize(generated).decode('utf8',errors='replace')
  ledger[key]={'prompt':prompt,'seed':seed,'text':text,'input_tokens':512,'meaningful_input_tokens':len(ids),
               'filler_tokens':512-len(ids),'output_tokens':64,'seconds':time.perf_counter()-started}
  temp_path=ledger_path.with_suffix('.tmp');temp_path.write_text(json.dumps(ledger,ensure_ascii=False,indent=2),encoding='utf8');temp_path.replace(ledger_path)
  print('CPU debate',len(ledger),'/540',key,round(ledger[key]['seconds'],2),'s',flush=True)
  return text
 def parse(text,kind):
  pattern=r'FINAL\s*:\s*\$?\s*([-+]?\d[\d,]*(?:\.\d+)?)' if kind=='numeric' else r'FINAL\s*:\s*([A-D])\b'
  m=re.search(pattern,text,re.I)
  if not m:return None
  if kind=='letter':return m.group(1).upper()
  try:return str(decimal.Decimal(m.group(1).replace(',','')).normalize())
  except decimal.InvalidOperation:return None
 def majority(items):
  xs=[x for x in items if x is not None]
  if not xs:return None
  counts=collections.Counter(xs);return next(x for x in xs if counts[x]==max(counts.values()))
 records=[]
 for index,(question,kind,gold) in enumerate(cases):
  gold_norm=str(decimal.Decimal(gold).normalize()) if kind=='numeric' else gold
  prompt=question+'\n'+('Finish with FINAL: followed by the numeric answer.' if kind=='numeric' else 'Finish with FINAL: followed by A, B, C or D.')
  result={}
  previous=[]
  for round_no in range(3):
   extra='' if not previous else '\nOther answers:\n'+'\n'.join(previous)+'\nReview independently.'
   previous=[ask(prompt+extra,f'{index}-debate-{round_no}-{a}',260000+round_no*3+a) for a in range(3)]
  answer=majority([parse(x,kind) for x in previous]);result['debate']={'answer':answer,'correct':answer==gold_norm if answer is not None else False,'tokens':5184}
  samples=[ask(prompt,f'{index}-voto-0-{a}',261000+a) for a in range(9)]
  answer=majority([parse(x,kind) for x in samples]);result['voto']={'answer':answer,'correct':answer==gold_norm if answer is not None else False,'tokens':5184}
  previous=ask(prompt,f'{index}-revision-0-0',262000)
  for j in range(1,9):previous=ask(prompt+'\nReview your previous answer:\n'+previous,f'{index}-revision-{j}-0',262000+j)
  answer=parse(previous,kind);result['revision']={'answer':answer,'correct':answer==gold_norm if answer is not None else False,'tokens':5184}
  records.append({'index':index,'question':question,'kind':kind,'gold':gold_norm,'results':result})
  (ROOT/'debate.json').write_text(json.dumps(records,ensure_ascii=False,indent=2),encoding='utf8')
  print('CPU pregunta completa',index,{k:v['correct'] for k,v in result.items()},flush=True)
 rng=random.Random(26);summary={}
 for kind in ('numeric','letter'):
  subset=[r for r in records if r['kind']==kind];summary[kind]={}
  for baseline in ('voto','revision'):
   delta=[int(r['results']['debate']['correct'])-int(r['results'][baseline]['correct']) for r in subset]
   boot=sorted(sum(rng.choice(delta) for _ in delta)/len(delta) for _ in range(2000))
   summary[kind][baseline]={'difference':sum(delta)/len(delta),'ci':[boot[49],boot[1949]]}
 (ROOT/'summary.json').write_text(json.dumps(summary,ensure_ascii=False,indent=2),encoding='utf8')
 print('CPU resumen',summary,flush=True)

if __name__=='__main__':
 import hashlib,requests
 sources=[('gsm8k-test.jsonl','https://raw.githubusercontent.com/openai/grade-school-math/3101c7d5072418e28b9008a6636bde82a006892c/grade_school_math/data/test.jsonl','3730d312f6e3440559ace48831e51066acaca737f6eabec99bccb9e4b3c39d14'),('mmlu.parquet','https://huggingface.co/datasets/cais/mmlu/resolve/c30699e8356da336a370243923dbaf21066bb9fe/high_school_computer_science/test-00000-of-00001.parquet','6e1b210896afc60f2ea3a1b011733b86dedd74690adce6ff0893346089f83252')]
 for name,url,digest in sources:
  p=ROOT/name
  if not p.exists():
   response=requests.get(url,timeout=90);response.raise_for_status();p.write_bytes(response.content)
  if hashlib.sha256(p.read_bytes()).hexdigest()!=digest:raise ValueError('Hash inesperado')
 hf_hub_download('Qwen/Qwen2.5-7B-Instruct-GGUF','qwen2.5-7b-instruct-q4_k_m-00002-of-00002.gguf',revision=MODEL_REV)
 run()

