"""Replay the Boolean attention-mask comparison on PyTorch CPU."""

import json
import platform

import torch
from torch import nn
from torch.nn.functional import scaled_dot_product_attention

PYTHON_VERSION = "3.13.17"
TORCH_VERSION = "2.9.1+cpu"
TORCH_REVISION = "5811a8d7da873dd699ff6687092c225caffcf1bb"

if platform.python_version() != PYTHON_VERSION:
    raise SystemExit(f"Expected Python {PYTHON_VERSION}")
if (torch.__version__, torch.version.git_version) != (TORCH_VERSION, TORCH_REVISION):
    raise SystemExit(f"Expected PyTorch {TORCH_VERSION} at {TORCH_REVISION}")

values = [2.0, 8.0]
cases = (
    ("same_mask", [True, False], [True, False], (8.0, 2.0)),
    ("inverted_sdpa_mask", [True, False], [False, True], (8.0, 8.0)),
    ("unmasked", None, None, (5.0, 5.0)),
    ("swapped_mask", [False, True], [False, True], (2.0, 8.0)),
)


def mask_tensor(mask):
    return None if mask is None else torch.tensor([mask], dtype=torch.bool)


@torch.inference_mode()
def observe():
    module = nn.MultiheadAttention(
        embed_dim=1, num_heads=1, dropout=0.0, bias=False, batch_first=True
    ).eval()
    module.in_proj_weight.fill_(1.0)
    module.out_proj.weight.fill_(1.0)
    query = torch.zeros((1, 1, 1), dtype=torch.float32, device="cpu")
    key = torch.zeros((1, 2, 1), dtype=torch.float32, device="cpu")
    value = torch.tensor(values, dtype=torch.float32, device="cpu").reshape(1, 2, 1)
    rows = []
    for name, mha_mask, sdpa_mask, expected in cases:
        masked, weights = module(
            query, key, value, attn_mask=mask_tensor(mha_mask), need_weights=True
        )
        output_only, _ = module(
            query, key, value, attn_mask=mask_tensor(mha_mask), need_weights=False
        )
        direct_mask = (
            ~mask_tensor(mha_mask)
            if name == "inverted_sdpa_mask"
            else mask_tensor(sdpa_mask)
        )
        if direct_mask is not None and direct_mask.tolist() != [sdpa_mask]:
            raise ValueError(f"{name}: SDPA mask differs from the fixture")
        direct = scaled_dot_product_attention(
            query.unsqueeze(1),
            key.unsqueeze(1),
            value.unsqueeze(1),
            attn_mask=direct_mask,
            dropout_p=0.0,
            is_causal=False,
        )
        actual = (masked.item(), direct.item())
        if actual != expected or output_only.item() != expected[0]:
            raise ValueError(f"{name}: expected {expected}, observed {actual}")
        rows.append(
            {
                "case": name,
                "mha_mask": mha_mask,
                "sdpa_mask": sdpa_mask,
                "mha_output": actual[0],
                "mha_output_without_weights": output_only.item(),
                "mha_weights": weights.flatten().tolist(),
                "sdpa_output": actual[1],
            }
        )
    return rows


if __name__ == "__main__":
    receipt = {
        "python": platform.python_version(),
        "torch": torch.__version__,
        "torch_revision": torch.version.git_version,
        "device": "cpu",
        "dtype": "float32",
        "query": [0.0],
        "keys": [0.0, 0.0],
        "values": values,
        "cases": observe(),
    }
    print(json.dumps(receipt, indent=2))
