"""Builder-side Triton compile: run a bench's launches with CPU tensors and compile every specialization
they would JIT into TRITON_CACHE_DIR, GPU-free (the kernel's warmup path, target forced to sm_89).
A GPU run then mounts that cache read-only and finds every binary."""
import torch, triton
from triton.backends.compiler import GPUTarget
from triton.runtime import driver
from triton.runtime.jit import MockTensor
import arbi_serve.kernels.fused_sigmoid_gating as fsg

ARCH = 89
N_COMPILED = [0]


def install():
    tgt = GPUTarget("cuda", ARCH, 32)
    drv = driver.active
    drv.get_current_target = lambda: tgt
    try:
        drv.get_current_device = lambda: 0
        drv.get_current_stream = lambda dev: 0
    except Exception:  # noqa: BLE001
        pass
    real = fsg.fused_sigmoid_gating_delta_rule_update_kernel

    class Proxy:
        def __getitem__(self, grid):
            def call(**kw):
                kw = {k: (MockTensor(v.dtype, list(v.shape)) if isinstance(v, torch.Tensor) else v) for k, v in kw.items()}
                real.warmup(grid=grid, **kw)
                N_COMPILED[0] += 1
            return call

    fsg.fused_sigmoid_gating_delta_rule_update_kernel = Proxy()
