Download tests/test_units.py from Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs: direct link, hf CLI and curl.
- Browser
- Download file 6.97 kB
-
https://huggingface.co/Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs/resolve/main/tests/test_units.py
- Command line
-
hf download hf://Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs/tests/test_units.py
-
curl -L -o test_units.py https://huggingface.co/Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs/resolve/main/tests/test_units.py
6.97 kB
| """Unit tests: perturbation invariance, contrast-head shape, GRPO loss.""" | |
| from __future__ import annotations | |
| import random | |
| import numpy as np | |
| import pytest | |
| import torch | |
| from causal_difficulty.data.perturbations import ( | |
| OPERATORS, | |
| assert_same_requirements, | |
| make_twins_for_job, | |
| _OPERATOR_FNS, | |
| ) | |
| from causal_difficulty.encoders.hashing import HashingEncoder | |
| from causal_difficulty.models.losses import grpo_loss | |
| from causal_difficulty.models.sce import SCE, SCEHeads | |
| def test_perturbations_preserve_requirements(jobs): | |
| rng = random.Random(0) | |
| for job in jobs[:5]: | |
| for op in OPERATORS: | |
| if op == "paraphrase_llm": | |
| continue | |
| text = _OPERATOR_FNS[op](job, rng) | |
| ok, reason = assert_same_requirements(job, text) | |
| assert ok, f"{op} broke invariance: {reason}" | |
| def test_make_twins_returns_valid_twins(jobs): | |
| rng = random.Random(1) | |
| twins = make_twins_for_job(jobs[0], 3, rng) | |
| assert len(twins) == 3 | |
| assert all(t.invariance_ok for t in twins) | |
| assert all(t.base_id == jobs[0].id for t in twins) | |
| def test_contrast_head_shapes(): | |
| enc = HashingEncoder(dim=128) | |
| heads = SCEHeads(embed_dim=128, hidden=32, complexity_dim=8) | |
| h = enc.encode(["a job description", "another one"]) | |
| hp = enc.encode(["a job description blue", "another one green"]) | |
| d = heads.contrast(h, hp) | |
| assert d.shape == (2,) | |
| ex = heads.ex_ante(h) | |
| assert ex.shape == (2, 2) | |
| def test_contrast_mode_input_dim(): | |
| diff = SCEHeads(embed_dim=16, complexity_dim=4, contrast_mode="diff") | |
| concat = SCEHeads(embed_dim=16, complexity_dim=4, contrast_mode="concat") | |
| assert diff.contrast_head.net[0].in_features == 16 | |
| assert concat.contrast_head.net[0].in_features == 32 | |
| def test_complexity_dim_must_be_a_strict_subspace(): | |
| with pytest.raises(ValueError, match="complexity_dim"): | |
| SCEHeads(embed_dim=16, complexity_dim=16) | |
| def test_contrast_context_widths(context, blocks): | |
| heads = SCEHeads(embed_dim=16, complexity_dim=4, contrast_context=context) | |
| assert heads.contrast_head.net[0].in_features == blocks * 16 | |
| h, hp = torch.randn(4, 16), torch.randn(4, 16) | |
| assert heads.contrast(h, hp).shape == (4,) | |
| def test_pair_context_is_the_standard_uvw_encoding(): | |
| """contrast_context='pair' feeds [d ; h ; h'], i.e. the InferSent/SBERT | |
| [u; v; u - v] pair encoding up to block order.""" | |
| heads = SCEHeads(embed_dim=16, complexity_dim=4, contrast_context="pair") | |
| h, hp = torch.randn(4, 16), torch.randn(4, 16) | |
| assert torch.allclose(heads._context(h, hp), torch.cat([h, hp], dim=-1)) | |
| def test_surface_pair_context_removes_complexity_from_both_towers(): | |
| heads = SCEHeads(embed_dim=16, complexity_dim=4, contrast_context="surface_pair") | |
| h, hp = torch.randn(4, 16), torch.randn(4, 16) | |
| ctx = heads._context(h, hp) | |
| q = heads._orthonormal_basis() | |
| # every appended block must be orthogonal to the complexity subspace | |
| assert torch.allclose(ctx[:, :16] @ q, torch.zeros(4, 4), atol=1e-5) | |
| assert torch.allclose(ctx[:, 16:] @ q, torch.zeros(4, 4), atol=1e-5) | |
| def test_unknown_contrast_context_is_rejected(): | |
| with pytest.raises(ValueError, match="contrast_context"): | |
| SCEHeads(embed_dim=16, complexity_dim=4, contrast_context="serface") | |
| def test_difference_only_head_ignores_the_base_job(): | |
| """The point of contrast_context: without it the head is blind to which | |
| job an edit was applied to, so shifting both twins together changes | |
| nothing; with it, the prediction moves.""" | |
| shift = torch.randn(1, 16) | |
| h, hp = torch.randn(4, 16), torch.randn(4, 16) | |
| plain = SCEHeads(embed_dim=16, complexity_dim=4, contrast_context="none").eval() | |
| surface = SCEHeads(embed_dim=16, complexity_dim=4, contrast_context="surface").eval() | |
| with torch.no_grad(): | |
| assert torch.allclose(plain.contrast(h, hp), plain.contrast(h + shift, hp + shift), | |
| atol=1e-5) | |
| assert not torch.allclose(surface.contrast(h, hp), | |
| surface.contrast(h + shift, hp + shift), atol=1e-5) | |
| def test_checkpoint_round_trips_a_trainable_encoder(): | |
| """A trainable encoder's weights must survive save/load: the heads were | |
| fitted against them, so silently reloading the pretrained ones would make | |
| every downstream metric meaningless.""" | |
| class _TinyTrainableEncoder: | |
| dim = 8 | |
| def __init__(self): | |
| self.layer = torch.nn.Linear(8, 8) | |
| def encode(self, texts): | |
| return self.layer(torch.ones(len(texts), 8)) | |
| def trainable_parameters(self): | |
| return list(self.layer.parameters()) | |
| def state_dict(self): | |
| return self.layer.state_dict() | |
| def load_state_dict(self, sd): | |
| self.layer.load_state_dict(sd) | |
| trained = SCE(_TinyTrainableEncoder(), SCEHeads(embed_dim=8, hidden=8, complexity_dim=2)) | |
| with torch.no_grad(): | |
| trained.encoder.layer.weight.add_(1.0) | |
| sd = trained.state_dict() | |
| restored = SCE(_TinyTrainableEncoder(), SCEHeads(embed_dim=8, hidden=8, complexity_dim=2)) | |
| restored.load_state_dict(sd) | |
| assert torch.allclose(restored.encoder.layer.weight, trained.encoder.layer.weight) | |
| # A heads-only checkpoint must fail loudly rather than pair trained heads | |
| # with an untrained encoder. | |
| with pytest.raises(RuntimeError, match="head weights only"): | |
| restored.load_state_dict(sd["heads"]) | |
| def test_frozen_checkpoint_format_is_unchanged(): | |
| """Existing sce_heads.pt files for frozen backbones must still load.""" | |
| enc = HashingEncoder(dim=32) | |
| sce = SCE(enc, SCEHeads(embed_dim=32, hidden=8, complexity_dim=4)) | |
| sd = sce.state_dict() | |
| assert set(sd) == set(sce.heads.state_dict()) | |
| sce.load_state_dict(sd) | |
| def test_grpo_loss_is_scale_invariant(): | |
| torch.manual_seed(0) | |
| dhat = torch.randn(6, requires_grad=True) | |
| delta = torch.tensor([0.1, 0.5, 0.3, 0.2, 0.8, 0.4]) | |
| base_ids = ["job_A", "job_A", "job_A", "job_B", "job_B", "job_B"] | |
| loss1 = grpo_loss(dhat, delta, base_ids) | |
| loss2 = grpo_loss(dhat, delta * 10.0, base_ids) | |
| assert abs(loss1.item() - loss2.item()) < 1e-5 | |
| def test_grpo_loss_zero_for_perfect_rank(): | |
| delta = torch.tensor([0.1, 0.5, 0.9]) | |
| mu, sig = delta.mean(), delta.std(unbiased=False) | |
| tilde = (delta - mu) / sig | |
| dhat = tilde.clone().detach().requires_grad_(True) | |
| base_ids = ["job_A", "job_A", "job_A"] | |
| loss = grpo_loss(dhat, delta, base_ids) | |
| assert loss.item() < 1e-6 | |
| def test_grpo_loss_skips_degenerate_groups(): | |
| dhat = torch.randn(4, requires_grad=True) | |
| delta = torch.tensor([0.5, 0.5, 0.1, 0.9]) | |
| base_ids = ["job_A", "job_A", "job_B", "job_B"] | |
| loss = grpo_loss(dhat, delta, base_ids) | |
| assert torch.isfinite(loss) | |
| loss.backward() | |