"""Conservatively count a target's wins under the full-vocabulary float32 scorer.
No sampling or activation I/O. Callers must provide the same reconstructed tensor
used by their dense reference. Witnesses never confer a win or settle a tie.
"""
import torch as th


def target_wins(rows, weights, target, witness_indexes, dense_batch=1024):
    """Boolean wins and number of rows scored exhaustively.

    rows: [n,d] float32, weights: [d,vocab] float32, both finite.
    witness_indexes: iterable of index tensors [n]; original receiver/donor
    winners are useful but any valid indices are sound.
    Assumes IEEE float32 accumulation (no reduced-precision matrix multiply).
    """
    if rows.dtype != th.float32 or weights.dtype != th.float32:
        raise ValueError("Float32 dense scorer required")
    if rows.ndim != 2 or weights.ndim != 2 or rows.shape[1] != weights.shape[0]:
        raise ValueError("Incompatible shapes")
    if not 0 <= target < weights.shape[1] or dense_batch < 1:
        raise ValueError("Invalid target or batch")
    count, d = rows.shape
    y = rows.double()
    t = weights[:, target].double()
    yt = y @ t
    norm = y.norm(dim=1)
    # Conservative absolute error bound for dot products of rounded float inputs.
    u = th.finfo(th.float32).eps / 2
    g = (2 * d * u) / (1 - 2 * d * u)
    alive = th.ones(count, dtype=th.bool, device=rows.device)
    for idx in witness_indexes:
        if idx.shape != (count,) or idx.dtype != th.int64:
            raise ValueError("Each witness vector needs one int64 index per row")
        v = weights[:, idx].T.double()
        rival = (y * v).sum(dim=1)
        band = g * norm * (t.norm() + v.norm(dim=1))
        # Leave nonfinite and borderline rows to the unchanged scorer.
        margin = rival - yt
        alive &= ~((idx != target) & th.isfinite(margin)
                   & th.isfinite(band) & (margin > band))
    result = th.zeros(count, dtype=th.bool, device=rows.device)
    pending = th.where(alive)[0]
    for ii in pending.split(dense_batch):
        if len(ii):
            result[ii] = (rows[ii] @ weights).argmax(dim=1) == target
    return result, len(pending)


if __name__ == "__main__":
    # Includes a tied row (lowest-index winner), witnesses that equal target,
    # a clear target win, a clear rejection, and an intentionally weak witness.
    kept = th.tensor([[0., 0.], [2., 1.], [-2., 1.], [0., 2.]])
    weights = th.tensor([[1., -1., 0.], [0., 0., 1.]])
    for k in range(3):
        exact = (kept @ weights).argmax(dim=1) == k
        result, fallback = target_wins(kept, weights, k,
                                       [th.tensor([0, 0, 1, 1])], 2)
        assert th.equal(result, exact), (k, result, exact, fallback)
    print("PASS: known winners, exact tie and ambiguous witness")
