"""Runnable counterexamples to stronger claims about masked-head compaction."""
import json
from pathlib import Path
import torch
import torch.nn.functional as F
from compact_head import compact, dense

def main():
    torch.set_num_threads(1)
    dtype = torch.float64
    x = torch.tensor([[2.0], [0.0]], dtype=dtype, requires_grad=True)
    w = torch.tensor([[1.0], [-1.0]], dtype=dtype, requires_grad=True)
    b = torch.zeros(2, dtype=dtype, requires_grad=True)
    labels = torch.tensor([-100, 0])

    def causal_attention(v):
        # A real attention special case with Q=K=0, V=x, and causal mask.
        n = v.shape[0]
        z = torch.zeros((n, 1), dtype=dtype)
        mask = torch.ones((n, n), dtype=torch.bool).triu(1)
        return (z @ z.T).masked_fill(mask, -torch.inf).softmax(dim=-1) @ v

    def grads(loss):
        return torch.autograd.grad(loss, (x, w, b))

    h = causal_attention(x)
    baseline = dense(h, w, b, labels, 'mean')
    g_dense = grads(baseline)
    good = compact(causal_attention(x), w, b, labels, 'mean')
    g_good = grads(good)
    torch.testing.assert_close(g_good, g_dense, rtol=0, atol=0)
    torch.testing.assert_close(good, baseline, rtol=0, atol=0)
    assert abs(g_good[0][0].item()) > .1

    dropped = dense(causal_attention(x[1:]), w, b, labels[1:], 'mean')
    g_dropped = grads(dropped)
    assert dropped > good and g_dropped[0][0].item() == 0

    # Dividing the exact same sum by dense row count is the wrong mean.
    wrong = compact(causal_attention(x), w, b, labels, 'sum') / labels.numel()
    g_wrong = grads(wrong)
    torch.testing.assert_close(wrong * 2, good, rtol=0, atol=0)
    torch.testing.assert_close(tuple(p * 2 for p in g_wrong), g_good, rtol=0, atol=0)

    def with_aux(also_project_ignored):
        h = causal_attention(x)
        ce = compact(h, w, b, labels, 'mean')
        aux_h = h if also_project_ignored else h[labels != -100]
        # Fixed coefficient and sum; no hidden change in averaging.
        return ce + .25 * F.linear(aux_h, w, b).square().sum()
    aux_all, aux_selected = with_aux(True), with_aux(False)
    g_aux_all, g_aux_selected = grads(aux_all), grads(aux_selected)
    assert aux_all > aux_selected and not torch.equal(g_aux_all[1], g_aux_selected[1])

    # A separate bookkeeping counterexample: average microbatch means with
    # K=[1,2], rather than weighting by the number of supervised examples.
    logits = torch.tensor([[0., 0.], [0., 0.], [2., -2.], [2., -2.]], dtype=dtype)
    y = torch.tensor([0, -100, 0, 0])
    loss = lambda uv, yv, red: F.cross_entropy(uv, yv, ignore_index=-100, reduction=red)
    a, c = loss(logits[:2], y[:2], 'sum'), loss(logits[2:], y[2:], 'sum')
    glob = loss(logits, y, 'mean')
    local_average = (a + c/2) / 2
    torch.testing.assert_close((a+c)/3, glob, rtol=1e-15, atol=1e-15)
    assert abs(local_average - glob) > .1

    res = {
        'torch_version': torch.__version__, 'precision':'float64',
        'dense': baseline.item(), 'head_only_compaction': good.item(),
        'dense_and_compact_ignored_prompt_input_grad': g_good[0][0].item(),
        'wrong_upstream_prompt_deletion': dropped.item(),
        'wrong_deletion_ignored_prompt_input_grad': g_dropped[0][0].item(),
        'wrong_all_row_normalizer': wrong.item(),
        'wrong_all_row_normalizer_prompt_input_grad': g_wrong[0][0].item(),
        'aux_all_logits_loss': aux_all.item(), 'aux_selected_logits_only_loss': aux_selected.item(),
        'aux_head_grad_max_difference': (g_aux_all[1]-g_aux_selected[1]).abs().max().item(),
        'correct_global_mean_k1_k2': glob.item(),
        'wrong_average_of_microbatch_means_k1_k2': local_average.item(),
    }
    Path(__file__).with_name('counterexamples.json').write_text(json.dumps(res,indent=2)+'\n')
    print(json.dumps(res,indent=2))

if __name__ == '__main__':
    main()
