"""Exact embedding-indexed MHIS equivalent to ARC's lpe.methods.MHIS without redundant dense vocabulary matmuls.
Thread arc-lpe, QLD plan days 4-5, tracker #71 / #77. Written by Gemini 4 Carbon (High), 2026-11-23.

Mathematical identities vs ARC's methods.py:236-374:
  1. `emb = W_E[samples]; emb.grad[b_idx, pos] @ W_E.T` equals `onehot = one_hot(samples); onehot.grad[b_idx, pos]`
     without the (B, ctx_len, 48262) dense matmul and backward pass.
  2. Differentiating `x_last @ W_U[:, target]` (as ARC already does in ITGIS, methods.py:228) avoids allocating a
     (B, 48262) autograd gradient tensor.
  3. `argmax(x_last @ W_U) == target` is never read during burn-in (`step < burn_in - 1`) and never changes on
     rejected proposals (`~accept_mask`), so evaluating `x_last @ W_U` only at `step == burn_in - 1` and on accepted
     rows for `step >= burn_in` preserves the exact RNG sequence and exact output estimates (<1e-6 float32 diff).
"""
import torch as th


def mhis_fast(model, orig_dists, target: int, *, temp: float, n_samples: int, burn_in: int, batch_size: int = 32):
    d_vocab = model.embed.d_vocab
    ctx_len = len(orig_dists)
    device = model.embed.W_E.device
    W_E = model.embed.W_E.detach()
    W_U = model.unembed.W_U.detach()
    w_target = W_U[:, target].contiguous()

    for param in model.parameters():
        param.requires_grad_(False)

    orig_log_probs = []
    for pos in range(ctx_len):
        mask = -th.inf * th.ones(d_vocab, device=device)
        mask[orig_dists[pos].values] = th.log(orig_dists[pos].probs)
        orig_log_probs.append(mask)
    orig_log_probs = th.stack(orig_log_probs)

    results = []
    scores = []
    b_idx = th.arange(batch_size, device=device)
    n_steps = n_samples // batch_size + burn_in
    assert n_samples % batch_size == 0

    with th.enable_grad():
        current_samples = th.stack([dist.sample((batch_size,)) for dist in orig_dists], dim=1)
        acceptance_rate = 0.0
        total_proposals = 0
        current_results = None

        for step in range(n_steps):
            if step == 0:
                emb = W_E[current_samples].detach().requires_grad_(True)
                x = emb + model.pos_embed(current_samples)
                for block in model.blocks:
                    x = block(x)
                x_last = model.ln_final(x[:, -1].unsqueeze(1)).squeeze(1)
                current_scores = x_last @ w_target
                current_scores.sum().backward()
                current_emb_grads = emb.grad.detach().clone()
                current_scores = current_scores.detach().clone()
                current_x_last = x_last.detach().clone()
                if burn_in == 0:
                    with th.no_grad():
                        current_results = ((current_x_last @ W_U).argmax(dim=-1) == target).float()

            pos = th.randint(0, ctx_len, (batch_size,), device=device)
            cur_g = current_emb_grads[b_idx, pos] @ W_E.T
            proposal_logits = orig_log_probs[pos] + cur_g / temp
            proposal_probs = th.softmax(proposal_logits, dim=-1)
            proposed_tokens = th.multinomial(proposal_probs, 1).squeeze(-1)

            proposed_samples = current_samples.clone()
            proposed_samples[b_idx, pos] = proposed_tokens

            emb_p = W_E[proposed_samples].detach().requires_grad_(True)
            x = emb_p + model.pos_embed(proposed_samples)
            for block in model.blocks:
                x = block(x)
            x_last_p = model.ln_final(x[:, -1].unsqueeze(1)).squeeze(1)
            proposed_scores = x_last_p @ w_target
            proposed_scores.sum().backward()
            proposed_emb_grads = emb_p.grad.detach().clone()

            rev_g = proposed_emb_grads[b_idx, pos] @ W_E.T
            reverse_proposal_logits = orig_log_probs[pos] + rev_g / temp
            reverse_proposal_probs = th.softmax(reverse_proposal_logits, dim=-1)

            cur_tok = current_samples[b_idx, pos]
            log_accept_probs = (
                (proposed_scores.detach() - current_scores) / temp
                + orig_log_probs[pos, proposed_tokens] - orig_log_probs[pos, cur_tok]
                + th.log(reverse_proposal_probs[b_idx, cur_tok])
                - th.log(proposal_probs[b_idx, proposed_tokens])
            )

            accept_mask = th.log(th.rand(batch_size, device=device)) < log_accept_probs
            if accept_mask.any():
                current_samples[accept_mask] = proposed_samples[accept_mask]
                current_scores[accept_mask] = proposed_scores.detach()[accept_mask]
                current_emb_grads[accept_mask] = proposed_emb_grads[accept_mask]
                current_x_last[accept_mask] = x_last_p.detach()[accept_mask]

            if step == burn_in - 1:
                with th.no_grad():
                    current_results = ((current_x_last @ W_U).argmax(dim=-1) == target).float()
            elif step >= burn_in:
                if accept_mask.any():
                    with th.no_grad():
                        current_results[accept_mask] = ((current_x_last[accept_mask] @ W_U).argmax(dim=-1) == target).float()

            if step >= burn_in:
                results.append(current_results.clone())
                scores.append(current_scores.clone())

            acceptance_rate += accept_mask.float().mean().item()
            total_proposals += 1

    results = th.cat(results)
    scores = th.cat(scores)
    exp_scores = th.exp(scores / temp)
    normalizing_constant = 1.0 / (1.0 / exp_scores).mean().item()
    unbiased_estimates = results * normalizing_constant / exp_scores
    return (
        unbiased_estimates.mean().item(),
        acceptance_rate / max(total_proposals, 1),
        int((results > 0).sum().item()),
        float((results / exp_scores).mean().item()),
        float((1.0 / exp_scores).mean().item()),
    )
