"""Train-only throughput/memory probe; never produces model-selection scores."""
import argparse
import json
from pathlib import Path
import sys
import time

PROJECT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(PROJECT))
import numpy as np
import torch
from pallet.pose_benchmark import ROOT,EndToEnd,load_data,seed_all,atomic_json
from pallet.pose_refinement import loss_value


def main():
    parser=argparse.ArgumentParser()
    parser.add_argument('--name',required=True)
    args=parser.parse_args()
    rows,arrays=load_data('metric')
    assert all(r['split']=='train' for r in rows)
    report=dict(gpu=str(torch.cuda.get_device_properties(0)),train_only=True,families={})
    for family in ('pointnext','ptv3','dgcnn'):
        records=[]
        for batch in (8,16,32):
            seed_all(42)
            model=EndToEnd(family,arrays['g'][:,0]).cuda()
            optimizer=torch.optim.AdamW(model.parameters(),lr=1e-4)
            f=torch.from_numpy(arrays['f'][:batch,0].copy()).cuda()
            g=torch.from_numpy(arrays['g'][:batch,0]).cuda()
            y=torch.from_numpy(arrays['y'][:batch]).cuda()
            times=[]
            for step in range(9):
                torch.cuda.synchronize();start=time.perf_counter()
                model.train();optimizer.zero_grad(set_to_none=True)
                loss=loss_value(model(f,g),y)
                assert torch.isfinite(loss)
                loss.backward();torch.nn.utils.clip_grad_norm_(model.parameters(),5);optimizer.step()
                torch.cuda.synchronize()
                if step==2:torch.cuda.reset_peak_memory_stats()
                if step>=3:times.append(time.perf_counter()-start)
            record=dict(batch=batch,step_ms_median=float(np.median(times)*1000),
                        samples_per_second=float(batch/np.median(times)),
                        peak_memory_bytes=torch.cuda.max_memory_allocated())
            records.append(record);print(json.dumps(dict(family=family,training=record)),flush=True)
            if batch==32:
                model.eval();f=torch.tensor(arrays['f'][:64,0].copy(),device='cuda')
                g=torch.tensor(arrays['g'][:64,0],device='cuda')
                with torch.no_grad():
                    reference=torch.cat([model(f[i:i+8],g[i:i+8]) for i in range(0,64,8)])
                    inference=[]
                    for count in (8,32,64):
                        times=[]
                        for step in range(5):
                            torch.cuda.synchronize();start=time.perf_counter()
                            p=torch.cat([model(f[i:i+count],g[i:i+count]) for i in range(0,64,count)])
                            torch.cuda.synchronize()
                            if step:times.append(time.perf_counter()-start)
                        difference=float((p-reference).abs().max())
                        assert difference<1e-3, (family,count,difference)
                        inference.append(dict(batch=count,samples_per_second=float(64/np.median(times)),
                                              max_residual_abs_difference_vs_batch8=difference))
            del model,optimizer,f,g,y
            torch.cuda.empty_cache()
        report['families'][family]=dict(training=records,inference=inference)
    atomic_json(ROOT/('throughput_'+args.name+'.json'),report)


if __name__=='__main__':main()
