"""Identity init of the F12 temporal head and metadata bias."""

import torch

from method.f12_temporal import FrameASDTemporalHead, MetaLogitBias, apply_cycle_bias
from method.frame_asd import FrameASDHead


def test_temporal_head_matches_linear_at_init():
    torch.manual_seed(0)
    frames = torch.randn(2, 17, 32)
    temporal = FrameASDTemporalHead(in_dim=32, n_layers=2, n_heads=4, dropout=0.1)
    temporal.eval()
    with torch.no_grad():
        hidden = frames
        for block in temporal.blocks:
            hidden = block(hidden)
        assert torch.allclose(hidden, frames, atol=1e-5)
        logit_c, logit_w = temporal(frames)
    linear = FrameASDHead(in_dim=32, dropout=0.1)
    linear.crackle.load_state_dict(temporal.crackle.state_dict())
    linear.wheeze.load_state_dict(temporal.wheeze.state_dict())
    linear.eval()
    with torch.no_grad():
        ref_c, ref_w = linear(frames)
    assert torch.allclose(logit_c, ref_c, atol=1e-5)
    assert torch.allclose(logit_w, ref_w, atol=1e-5)


def test_meta_bias_is_zero_at_init():
    meta = MetaLogitBias()
    device_id = torch.tensor([0, 3, 1])
    loc_id = torch.tensor([1, 7, 0])
    bias_c, bias_w = meta(device_id, loc_id)
    assert torch.count_nonzero(bias_c) == 0
    assert torch.count_nonzero(bias_w) == 0

    head = FrameASDTemporalHead(in_dim=32, n_layers=1, n_heads=4)
    head.meta = meta
    frames = torch.randn(3, 5, 32)
    head.eval()
    with torch.no_grad():
        logit_c, logit_w = head(frames)
        shifted_c, shifted_w = apply_cycle_bias(head, logit_c, logit_w, device_id, loc_id)
    assert torch.allclose(shifted_c, logit_c)
    assert torch.allclose(shifted_w, logit_w)
