"""Multi-target QLD: ARC's QLD (methods.py, line 73 bracketed) restructured so that one logit matmul per
activation chunk serves every target token. Thread arc-lpe, QLD plan day 1, tracker #71.
Written by Claude Opus 5.5 (Claude Code), 2026-11-17.

Notation follows ARC's code (row vectors):
  u = (x - mean) @ inv(A.T)            whitened samples (line 73 with brackets)
  logits = u @ P.T + beta,  P = W_U.T @ A,  beta = W_U.T @ mean
For target t with unit direction d_t (ARC's shortest accepting vector):
  a = u . d_t,  b = u - a d_t,  g_t = P @ d_t  (one number per vocabulary entry)
  logits of b: Lb = Lu - a g_t,  with Lu = u @ P.T + beta shared by all targets  <- the one matmul per chunk
  interval for a (ARC lines 102-110): numerator_j = Lb_t - Lb_j, denominator_j = -(g_t[t] - g_t[j])
variant "b": line 103 uses b_samps (the paper's Algorithm 3).
variant "y": line 103 as published, numerator from y = u, which equals shifting each interval by -a_i.

ARC's random_constraint_projection and QLD are taken verbatim from the pinned methods.py by AST extraction,
so the shortest-accepting-vector search is ARC's own code, and test_equiv.py can compare against ARC's QLD.
"""
import ast
import hashlib
import os

import torch as th

HERE = os.path.dirname(os.path.abspath(__file__))
METHODS = os.path.join(HERE, "arc_methods.py")
PINNED_SHA256 = "523e28c0cf187844a8fc51036e5fd02892fcbb90c6f17dd963d6560fdd973ba6"  # ARC HEAD acad4a7, lpe/methods.py
LINE73_OLD = "u_samps = act_samps - mean @ th.inverse(A.T)"
LINE73_NEW = "u_samps = (act_samps - mean) @ th.inverse(A.T)"
LINE103_OLD = "numerator = y @ pullbacks_diff + biases[target] - biases"
LINE103_NEW = "numerator = b_samps @ pullbacks_diff + biases[target] - biases"
EDITS = {"published": [], "y": [(LINE73_OLD, LINE73_NEW)], "b": [(LINE73_OLD, LINE73_NEW), (LINE103_OLD, LINE103_NEW)]}


def arc_functions(edits=()):
    """random_constraint_projection and QLD from ARC's methods.py, with exact string edits applied."""
    src = open(METHODS).read()
    h = hashlib.sha256(src.encode()).hexdigest()
    assert h == PINNED_SHA256, f"methods.py sha256 {h} is not the pinned file"
    for old, new in edits:
        assert src.count(old) == 1, f"edit target found {src.count(old)} times: {old}"
        src = src.replace(old, new)
    ns = {"th": th}
    for node in ast.parse(src).body:
        if isinstance(node, ast.FunctionDef) and node.name in ("random_constraint_projection", "QLD"):
            exec(compile(ast.get_source_segment(src, node), f"{METHODS}:{node.name}", "exec"), ns)
    return ns


_RCP = arc_functions()["random_constraint_projection"]


def whiten(acts, eps=1e-5):
    """Sample mean and Cholesky factor exactly as ARC's QLD computes them (lines 66-72)."""
    n, dm = acts.shape
    mean = acts.mean(dim=0)
    cov = (acts - mean).T @ (acts - mean) / n
    A = th.linalg.cholesky(cov + eps * th.eye(dm, dtype=acts.dtype, device=acts.device))
    return mean, A


def sav_direction(P, beta, t, seed):
    """ARC's shortest accepting vector for target t (lines 80-86), seeded."""
    th.manual_seed(seed)
    Pd = P[t].unsqueeze(0) - P
    bd = beta[t].unsqueeze(0) - beta
    bd[t] = 100
    old = th.get_default_dtype()
    th.set_default_dtype(P.dtype)  # ARC's search starts from th.zeros(d), which takes the default dtype
    try:
        d = _RCP(Pd, bd, n_reps=200, factor=0.95)
    finally:
        th.set_default_dtype(old)
    return d / th.norm(d)


def qld_multi(W_U, acts, targets, *, variant="b", chunk=2**14, mean=None, A=None, D=None, seeds=None):
    """QLD estimates for all targets from one pass over the activations.

    mean, A: whitening (default: sample estimates, as Algorithm 3). D: (d_model, T) unit directions
    (default: ARC's shortest accepting vector per target, seeded by `seeds` or the token id).
    Returns (estimates list, D)."""
    assert variant in ("b", "y")
    if mean is None:
        mean, A = whiten(acts)
    u = (acts - mean) @ th.inverse(A.T)
    P = W_U.T @ A
    beta = W_U.T @ mean
    if D is None:
        seeds = seeds or list(targets)
        D = th.stack([sav_direction(P, beta, t, s) for t, s in zip(targets, seeds)], dim=1)
    n = u.shape[0]
    G = P @ D                                  # (V, T): g_t for every target
    a_sorted = (u @ D).sort(dim=0).values.T.contiguous()  # (T, n)
    counts = th.zeros(len(targets), dtype=th.float64)
    inf = th.tensor(float("inf"), dtype=acts.dtype)
    for uc in u.split(chunk):
        Lu = uc @ P.T + beta                   # (m, V): the one logit matmul, shared by all targets
        ac = uc @ D if variant == "b" else None  # (m, T)
        for k, t in enumerate(targets):
            g = G[:, k]
            Lb = Lu - ac[:, k:k + 1] * g if variant == "b" else Lu
            num = Lb[:, t:t + 1] - Lb
            den = -(g[t] - g)
            ratio = num / den
            lower = th.where(den < 0, ratio, -inf).max(-1).values
            upper = th.where(den > 0, ratio, inf).min(-1).values
            cnt = (th.searchsorted(a_sorted[k], upper) - th.searchsorted(a_sorted[k], lower)).clamp(min=0)
            counts[k] += cnt.sum().double()
    return (counts / n / n).tolist(), D
