"""Builder-side compile of the three GDN specializations a served 27B boot uses (verify, verify+fold, flush commit),
through the real wrapper with CPU tensors (tri_warm). Prints the Triton cache dirs produced."""
import os, sys
import torch
sys.path.insert(0, os.path.dirname(__file__)); import tri_warm; tri_warm.install()
import arbi_serve.kernels.fused_sigmoid_gating as fsg
from arbi_serve.kernels.fused_sigmoid_gating import fused_sigmoid_gating_delta_rule_update as F

H, HV, K, V, TB = (int(x) for x in os.environ.get("GEOM", "16,48,128,128,8").split(","))
bf = torch.bfloat16
B, T, n = 2, TB, 5
A_log = torch.zeros(HV, dtype=bf); dt_bias = torch.zeros(HV, dtype=bf)
slab = torch.zeros(n, HV, V, K)
rk = torch.zeros(n, TB, H, K, dtype=bf); rv = torch.zeros(n, TB, HV, V, dtype=bf)
rb = torch.zeros(n, TB, HV, dtype=bf); ra = torch.zeros(n, TB, HV, dtype=bf)
ak, ab, aa = torch.zeros_like(rk), torch.zeros_like(rb), torch.zeros_like(ra)
qkv = torch.zeros(B * T, 2 * H * K + HV * V, dtype=bf); ba = torch.zeros(B * T, 2 * HV, dtype=bf)
q = qkv[:, : H * K].view(B * T, H, K); k = qkv[:, H * K : 2 * H * K].view(B * T, H, K); v = qkv[:, 2 * H * K :].view(B * T, HV, V)
rows = torch.arange(1, B + 1, dtype=torch.int32); has_init = torch.ones(B, dtype=torch.bool).view(torch.int8)
pending = torch.zeros(n, dtype=torch.int32); parity = torch.zeros(n, dtype=torch.int32)


def verify(fold):
    kw = dict(fold_n_steps=pending, fold_parity=parity, fold_alt_kba=(ak, ab, aa)) if fold else {}
    F(A_log=A_log, a=ba[:, HV:], b=ba[:, :HV], dt_bias=dt_bias, q=q.unflatten(0, (-1, T)), k=k.unflatten(0, (-1, T)),
      v=v.unflatten(0, (-1, T)), initial_state=slab, cu_seqlens=None, ssm_state_indices=rows, num_accepted_tokens=None,
      final_state_out=None, final_state_last_only=False, init_state_per_bos=False, round_h0_to_act_dtype=False,
      init_state_mask=has_init, save_inputs_kvba=(rk, rv, rb, ra), commit_final_state=False, use_qk_l2norm_in_kernel=True, **kw)


def commit():
    cu = torch.arange(0, n * TB + 1, TB, dtype=torch.int32)
    F(A_log=A_log, a=ra.view(n * TB, -1), b=rb.view(n * TB, -1), dt_bias=dt_bias, q=rk.view(1, n * TB, H, K),
      k=rk.view(1, n * TB, H, K), v=rv.view(1, n * TB, HV, V), initial_state=slab, cu_seqlens=cu,
      ssm_state_indices=torch.arange(n, dtype=torch.int32), final_state_out=slab, final_state_last_only=True,
      init_state_per_bos=False, round_h0_to_act_dtype=False, init_state_mask=torch.ones(n, dtype=torch.float32),
      n_steps=torch.ones(n, dtype=torch.int32), replay_only=True, use_qk_l2norm_in_kernel=True)


cache = os.environ["TRITON_CACHE_DIR"]
for name, fn in (("verify", lambda: verify(False)), ("verify_fold", lambda: verify(True)), ("commit", commit)):
    before = set(os.listdir(cache)); fn(); new = sorted(set(os.listdir(cache)) - before)
    print(name, new, flush=True)
