"""Registra top logits del motor ya cargado sin iniciar otra copia del modelo."""
import json,torch
from pathlib import Path
def probe(model,weights,tokenizer,path):
    rows=[]
    for prompt in ('Hello.','What is 2+2? Answer briefly.'):
        ids=tokenizer.apply_chat_template([{'role':'user','content':prompt}],tokenize=True,add_generation_prompt=True)
        if hasattr(ids,'keys'):ids=ids['input_ids']
        x=torch.tensor([ids],device=weights['token_embd.weight'].device)
        with torch.no_grad():
            logits=model.forward(weights,x,36,16,2,1e-6,1e6,last_only=True)[0,-1]
            logits[len(tokenizer):]=float('-inf')
            probs=logits.softmax(-1);values,indices=probs.topk(10)
        rows.append({'prompt':prompt,'ids':ids,'top':[{'id':int(i),'prob':float(v),'logit':float(logits[i])} for v,i in zip(values,indices)]})
    if weights['token_embd.weight'].is_cuda:
        torch.cuda.synchronize();gpu={'allocated':torch.cuda.memory_allocated(),'peak_allocated':torch.cuda.max_memory_allocated(),'peak_reserved':torch.cuda.max_memory_reserved()}
    else:gpu=None
    Path(path).write_text(json.dumps({'rows':rows,'gpu_bytes':gpu},indent=2),encoding='utf-8')
    print('Probe de logits guardado en',path,flush=True)
