"""A small fixed-head benchmark; no transformer blocks, weights, or I/O datasets."""
import hashlib, json, random, statistics, subprocess, time
from pathlib import Path
import torch
from compact_head import compact, dense, safe_dense, result, IGNORE

def main():
    torch.set_num_threads(1)
    assert torch.cuda.is_available() and torch.cuda.get_device_capability()==(7,5)
    torch.backends.cuda.matmul.allow_tf32=False
    dev='cuda'
    g=torch.Generator(device=dev).manual_seed(24621)
    correctness=[]
    for n in [0,1,12,64]:
        for k in sorted({0,n,n//2}):
            for red in ['sum','mean']:
                for dt in [torch.float64,torch.float32]:
                    dims=(n,19,61)
                    p=[torch.randn(s,dtype=dt,device=dev,generator=g).requires_grad_() for s in [(n,19),(61,19),(61,)]]
                    y=torch.full((n,),IGNORE,dtype=torch.long,device=dev)
                    y[torch.randperm(n,generator=g,device=dev)[:k]]=torch.randint(61,(k,),generator=g,device=dev)
                    want=result(dense if k else safe_dense,p,y,red)
                    have=result(compact,p,y,red)
                    tol=1e-12 if dt==torch.float64 else 1e-5
                    for a,b in zip(have,want): torch.testing.assert_close(a,b,atol=tol,rtol=tol)
                    assert torch.count_nonzero(have[1][y==IGNORE])==0
                    if not k: assert all(torch.count_nonzero(a)==0 for a in have)
                    correctness.append(dict(dtype=str(dt),dims=dims,kept=k,reduction=red,
                                            max_abs_error=[(a-b).abs().max().item() if a.numel() else 0 for a,b in zip(want,have)]))
    rng=random.Random(1503)
    rows=[]
    # Event timings and sync roundtrip wall time. Dynamic torch.where may sync
    # to determine result length, reflected in the honest wall timing.
    for n,d,v in [(256,256,4096),(512,512,8192)]:
        for dt in [torch.float32,torch.float16]:
            p=[(torch.randn(s,device=dev,dtype=dt,generator=g)*.04).requires_grad_() for s in [(n,d),(v,d),(v,)]]
            labels=torch.randint(v,(n,),generator=g,device=dev)
            perm=torch.randperm(n,generator=g,device=dev)
            for keep in [1.,.95,.75,.5,.25,.1,.01,0.]:
                k=round(keep*n)
                y=torch.full((n,), IGNORE,dtype=torch.long,device=dev)
                y[perm[:k]]=labels[perm[:k]]
                funcs={'dense':dense if k else safe_dense, 'compact':compact}
                raw={name:[] for name in funcs}
                # A timing-shape scalar and complete gradient spot check.
                ref=result(funcs['dense'],p,y,'mean')
                selected=result(compact,p,y,'mean')
                atol,rtol=(2e-5,3e-4) if dt==torch.float32 else (2e-5,3e-3)
                deltas=[(a-b).abs().max().item() for a,b in zip(ref,selected)]
                for a,b in zip(ref,selected):
                    # FP16 CE sums can use different reduction order.
                    if a.ndim==0 and dt==torch.float16:
                        torch.testing.assert_close(a,b,atol=2e-2,rtol=3e-3)
                    else:
                        torch.testing.assert_close(a,b,atol=atol,rtol=rtol)
                del ref,selected
                peak={}
                for name, fn in funcs.items():
                    torch.cuda.synchronize()
                    start_bytes=torch.cuda.memory_allocated()
                    torch.cuda.reset_peak_memory_stats()
                    _=result(fn,p,y,'mean')
                    torch.cuda.synchronize()
                    peak[name]=torch.cuda.max_memory_allocated()-start_bytes
                    del _
                events=[torch.cuda.Event(enable_timing=True) for _ in range(3)]
                for i in range(25):
                    names=list(funcs); rng.shuffle(names)
                    for name in names:
                        a,b,c=events
                        torch.cuda.synchronize()
                        start=time.perf_counter_ns()
                        a.record()
                        loss=funcs[name](*p,y,'mean')
                        b.record()
                        grad=torch.autograd.grad(loss,p)
                        c.record();c.synchronize()
                        wall=(time.perf_counter_ns()-start)/1e6
                        if i>=5: raw[name].append([a.elapsed_time(b),b.elapsed_time(c),a.elapsed_time(c),wall])
                        del loss,grad
                med={k0:[statistics.median(s) for s in zip(*r)] for k0,r in raw.items()}
                ratio=[a/b for a,b in zip(med['dense'],med['compact'])]
                rows.append(dict(rows=n,hidden=d,vocab=v,dtype=str(dt),kept=k,fraction=k/n,
                                 median_ms=med,ratio_dense_over_compact=ratio,samples_ms=raw,
                                 incremental_cuda_peak_allocated_bytes=peak,max_abs_error=deltas))
    receipt=dict(device=torch.cuda.get_device_name(),torch_version=torch.__version__,runtime=torch.version.cuda,
                 commit_inputs={p:hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in ['cuda_head.py','compact_head.py']},
                 units=['CUDA event fwd ms','CUDA event backward ms','CUDA event total ms','sync wall total ms'],
                 CUDA_dtype='FP32 and FP16, no AMP, TF32 disabled', repeats=20,warmup_pairs=5,
                 stats_nvidia_smi=subprocess.check_output(['nvidia-smi','--query-gpu=temperature.gpu,power.draw,clocks.current.sm,memory.used','--format=csv,noheader'],text=True).strip(),
                 correctness=correctness,results=rows)
    Path('result-cuda.json').write_text(json.dumps(receipt,allow_nan=False,indent=2)+'\n')
    print('PASS parity',len(correctness),'timing shapes',len(rows))
    for r in rows:
        print(r['rows'],r['dtype'],r['kept'],*[round(z,3) for z in r['ratio_dense_over_compact'][2:]])
if __name__=='__main__': main()
