"""Run GAT on CPU with recomputed edge chunks, starting from scratch.

Example: python gat_blocked_cpu_fresh.py --checkpoint gat.pt --output gat.json
Add --resume to continue its own checkpoint. All remaining CLI options are the
same as benchmark.py; --model gat, --strategy full and --device cpu are fixed.
"""
import hashlib
from pathlib import Path
import runpy
import sys
import torch
from torch_geometric.nn import GATConv
from gat_blocked_kernel import chunked

directory=Path(__file__).resolve().parent
benchmark=directory/'benchmark.py'
kernel=directory/'gat_blocked_kernel.py'
digest=lambda path:hashlib.sha256(path.read_bytes()).hexdigest()
provenance={'name':'checkpointed-edge-chunks-cpu','chunk_size':65536,
            'kernel_sha256':digest(kernel),'runner_sha256':digest(Path(__file__)),
            'benchmark_sha256':digest(benchmark),'origin':'fresh'}
argv=sys.argv[1:]
if '--resume' in argv:
    if '--checkpoint' not in argv:
        raise ValueError('--resume requires an explicit --checkpoint')
    path=Path(argv[argv.index('--checkpoint')+1])
    state=torch.load(path,map_location='cpu',weights_only=True)
    if state.get('experimental_kernel')!=provenance:
        raise ValueError('The checkpoint does not match this runner and kernel')

old_forward=GATConv.forward
def forward(self,x,edge_index,edge_attr=None,size=None,return_attention_weights=None):
    if self.training and torch.is_grad_enabled():
        assert edge_attr is None and size is None and return_attention_weights is None and isinstance(x,torch.Tensor)
        return chunked(self,x,edge_index,65536)
    return old_forward(self,x,edge_index,edge_attr,size,return_attention_weights)
GATConv.forward=forward
old_save=torch.save
def save_with_provenance(obj,*a,**kw):
    if isinstance(obj,dict) and 'source_hash' in obj and 'config' in obj:
        obj=dict(obj);obj['experimental_kernel']=provenance
    return old_save(obj,*a,**kw)
torch.save=save_with_provenance
sys.argv=[str(benchmark),*argv,'--model','gat','--strategy','full','--device','cpu']
runpy.run_path(str(benchmark),run_name='__main__')
