import math import pytest import torch from hades.config import ModelConfig, load_run_config from hades.model.model import HadesLM @pytest.fixture def tiny(): torch.manual_seed(0) return HadesLM(load_run_config("configs/tiny.yaml").model).eval() def test_param_counts(): assert HadesLM(load_run_config("configs/tiny.yaml").model).num_params() == 7_407_872 assert HadesLM(load_run_config("configs/small.yaml").model).num_params() == 40_512_000 def test_shapes_and_loss(tiny): idx = torch.randint(0, 16384, (2, 16)) logits, loss = tiny(idx, torch.randint(0, 16384, (2, 16))) assert logits.shape == (2, 16, 16384) assert abs(loss.item() - math.log(16384)) < 0.5 def test_no_targets_no_loss(tiny): _, loss = tiny(torch.randint(0, 16384, (1, 8))) assert loss is None def test_causality(tiny): idx = torch.randint(0, 16384, (2, 16)) changed = idx.clone() changed[:, 10] = (changed[:, 10] + 1) % 16384 with torch.no_grad(): a, _ = tiny(idx) b, _ = tiny(changed) assert torch.allclose(a[:, :10], b[:, :10], atol=1e-6) assert not torch.allclose(a[:, 10:], b[:, 10:], atol=1e-6) def test_sdpa_matches_reference(tiny): idx = torch.randint(0, 16384, (2, 32)) with torch.no_grad(): tiny.attn_impl = "sdpa" a, _ = tiny(idx) tiny.attn_impl = "reference" b, _ = tiny(idx) assert torch.allclose(a, b, atol=1e-5) def test_ignore_index(tiny): idx = torch.randint(0, 16384, (1, 12)) targets = torch.full_like(idx, -100) targets[0, 5] = 42 with torch.no_grad(): logits, loss = tiny(idx, targets) expected = torch.nn.functional.cross_entropy(logits[0, 5:6], torch.tensor([42])) assert loss.item() == pytest.approx(expected.item(), rel=1e-5) def test_tied_embeddings(tiny): assert tiny.lm_head_weight() is tiny.tok_emb.weight def test_module_names(tiny): names = {n for n, _ in tiny.named_parameters()} for n in ["tok_emb.weight", "final_norm.weight", "blocks.0.attn.q_proj.weight", "blocks.0.attn.out_proj.weight", "blocks.0.mlp.gate_proj.weight", "blocks.0.mlp.down_proj.weight", "blocks.0.attn_norm.weight", "blocks.0.mlp_norm.weight"]: assert n in names def test_init_std(): torch.manual_seed(0) cfg = load_run_config("configs/small.yaml").model m = HadesLM(cfg) target = 0.02 / math.sqrt(2 * cfg.n_layers) assert m.blocks[0].attn.out_proj.weight.std().item() == pytest.approx(target, rel=0.1) assert m.blocks[0].mlp.down_proj.weight.std().item() == pytest.approx(target, rel=0.1) assert m.blocks[0].attn.q_proj.weight.std().item() == pytest.approx(0.02, rel=0.1) def test_overfit_single_batch(): torch.manual_seed(0) cfg = ModelConfig(d_model=256, n_layers=4, n_heads=4, ffn_hidden=704, context_len=256) m = HadesLM(cfg) x = torch.randint(0, 16384, (4, 65)) opt = torch.optim.AdamW(m.parameters(), lr=3e-3) for _ in range(500): _, loss = m(x[:, :-1], x[:, 1:]) opt.zero_grad() loss.backward() opt.step() if loss.item() < 0.05: break assert loss.item() < 0.05