Download tests/test_phase4_pcgrad.py from Anupam-Rawat-IITB/code-switch-mtp: direct link, hf CLI and curl.
- Browser
- Download file 6.98 kB
-
https://huggingface.co/Anupam-Rawat-IITB/code-switch-mtp/resolve/main/tests/test_phase4_pcgrad.py
- Command line
-
hf download hf://Anupam-Rawat-IITB/code-switch-mtp/tests/test_phase4_pcgrad.py
-
curl -L -o test_phase4_pcgrad.py https://huggingface.co/Anupam-Rawat-IITB/code-switch-mtp/resolve/main/tests/test_phase4_pcgrad.py
6.98 kB
| """Tests for the conflict-aware projection pilot: projection math and gradient bookkeeping.""" | |
| import copy | |
| import importlib.util | |
| from pathlib import Path | |
| import torch | |
| import torch.nn as nn | |
| from src.train.model import MTPStack | |
| from src.train.trainer import train_step | |
| HIDDEN, VOCAB = 32, 64 | |
| _SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "phase4_pcgrad_train.py" | |
| _spec = importlib.util.spec_from_file_location("phase4_pcgrad_train", _SCRIPT) | |
| pcgrad = importlib.util.module_from_spec(_spec) | |
| _spec.loader.exec_module(pcgrad) | |
| def _frozen_unembedding() -> nn.Module: | |
| unemb = nn.Linear(HIDDEN, VOCAB, bias=False) | |
| for p in unemb.parameters(): | |
| p.requires_grad = False | |
| return unemb | |
| def _perturbed_stack(seed: int, scale: float = 0.05) -> MTPStack: | |
| torch.manual_seed(seed) | |
| stack = MTPStack(HIDDEN, _frozen_unembedding(), 4) | |
| with torch.no_grad(): | |
| for p in stack.trainable_parameters(): | |
| p.add_(scale * torch.randn_like(p)) | |
| return stack | |
| def _arm(stack: MTPStack, mode: str) -> "pcgrad.ProjectionArm": | |
| return pcgrad.ProjectionArm( | |
| name=mode, mode=mode, unit="word", stack=stack, | |
| optimizer=torch.optim.AdamW(stack.trainable_parameters(), lr=1e-3), | |
| loss_sums=[0.0] * stack.n_heads, cross_fraction_sums=[0.0] * stack.n_heads, | |
| ) | |
| def _trunk_grad(stack: MTPStack) -> torch.Tensor: | |
| return torch.cat([p.grad.reshape(-1) for p in stack.trunk.parameters()]) | |
| # --- parameter-level projection ------------------------------------------------- | |
| def test_conflicting_component_is_removed(): | |
| g1 = torch.tensor([1.0, 2.0, -1.0, 0.5]) | |
| gb = torch.tensor([-3.0, 0.5, 2.0, 1.0]) | |
| assert torch.dot(g1, gb) < 0 | |
| projected, fired = pcgrad.project_conflict(g1, gb) | |
| assert fired | |
| assert abs(float(torch.dot(projected, g1))) < 1e-6 | |
| assert torch.allclose(projected, gb - torch.dot(g1, gb) / torch.dot(g1, g1) * g1) | |
| def test_no_change_when_dot_product_is_non_negative(): | |
| g1 = torch.tensor([1.0, 0.0, 2.0]) | |
| for gb in (torch.tensor([0.5, 3.0, 0.1]), torch.tensor([0.0, 5.0, 0.0])): # positive, exactly orthogonal | |
| projected, fired = pcgrad.project_conflict(g1, gb) | |
| assert not fired | |
| assert torch.equal(projected, gb) | |
| # --- token-level projection ----------------------------------------------------- | |
| def test_per_token_projection_is_orthogonal_where_conflicting_and_identity_elsewhere(): | |
| torch.manual_seed(0) | |
| g1 = torch.randn(2, 7, 16) | |
| gb = torch.randn(2, 7, 16) | |
| projected, conflict = pcgrad.project_per_token(g1, gb) | |
| dots_before = (g1 * gb).sum(-1) | |
| assert torch.equal(conflict, dots_before < 0) | |
| assert conflict.any() and (~conflict).any() # both branches exercised | |
| dots_after = (g1 * projected).sum(-1) | |
| assert torch.all(dots_after[conflict].abs() < 1e-5) | |
| assert torch.equal(projected[~conflict], gb[~conflict]) | |
| def test_per_token_projection_changes_nothing_when_no_dot_is_negative(): | |
| torch.manual_seed(1) | |
| g1 = torch.randn(3, 5, 8) | |
| gb = g1 * torch.rand(3, 5, 1) + 0.0 # positively aligned at every position | |
| gb[0, 0] = 0.0 # a position with no cross-unit gradient at all | |
| projected, conflict = pcgrad.project_per_token(g1, gb) | |
| assert not conflict.any() | |
| assert torch.equal(projected, gb) | |
| gw = torch.randn(3, 5, 8) | |
| assert torch.equal(g1 + gw + projected, g1 + gw + gb) | |
| def test_crossing_mask_marks_targets_past_a_word_start(): | |
| """Words start at 0, 3 and 7; for offset 2 the target crosses exactly when it starts a word itself.""" | |
| starts = torch.zeros(1, 10, dtype=torch.bool) | |
| starts[0, [0, 3, 7]] = True | |
| assert pcgrad.crossing_mask(starts, 2)[0].tolist() == [0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0] | |
| assert pcgrad.crossing_mask(starts, 1).sum() == 0 | |
| # --- whole-step bookkeeping ----------------------------------------------------- | |
| def test_standard_arm_reproduces_phase3_gradients(): | |
| """With projection disabled, g1 + gW + gB must equal the ordinary MTP gradient.""" | |
| reference = _perturbed_stack(0, scale=0.01) | |
| pilot = copy.deepcopy(reference) | |
| ntp = MTPStack(HIDDEN, reference.heads[0].unembedding, 1) | |
| hidden = torch.randn(2, 16, HIDDEN) | |
| block = torch.randint(0, VOCAB, (2, 16)) | |
| train_step( | |
| hidden, block, reference, ntp, | |
| torch.optim.AdamW(reference.trainable_parameters(), lr=1e-3), | |
| torch.optim.AdamW(ntp.trainable_parameters(), lr=1e-3), | |
| nn.CrossEntropyLoss(), | |
| ) | |
| pcgrad.projection_step(_arm(pilot, "none"), hidden, block, torch.rand(2, 16) < 0.4) | |
| for p_ref, p_pilot in zip(reference.trainable_parameters(), pilot.trainable_parameters()): | |
| assert torch.allclose(p_ref.grad, p_pilot.grad, atol=1e-6, rtol=1e-5) | |
| def test_token_mode_equals_standard_when_no_target_crosses_a_unit(): | |
| """No unit starts -> gB(t) = 0 everywhere -> nothing to project -> same gradients as standard.""" | |
| base = _perturbed_stack(2) | |
| plain, token = copy.deepcopy(base), copy.deepcopy(base) | |
| hidden = torch.randn(2, 16, HIDDEN) | |
| block = torch.randint(0, VOCAB, (2, 16)) | |
| no_starts = torch.zeros(2, 16, dtype=torch.bool) | |
| arm_token = _arm(token, "token") | |
| pcgrad.projection_step(_arm(plain, "none"), hidden, block, no_starts) | |
| pcgrad.projection_step(arm_token, hidden, block, no_starts) | |
| assert arm_token.token_conflict == 0 | |
| for a, b in zip(plain.trainable_parameters(), token.trainable_parameters()): | |
| assert torch.allclose(a.grad, b.grad, atol=1e-6, rtol=1e-5) | |
| def test_projection_touches_only_the_shared_trunk(): | |
| """Head ResBlocks get identical gradients whatever the projection mode; the | |
| trunk gradient changes exactly when a projection fires (seeds searched so | |
| both modes' firing branches are exercised).""" | |
| fired_seen = {"param": False, "token": False} | |
| for seed in range(40): | |
| base = _perturbed_stack(seed) | |
| hidden = torch.randn(2, 16, HIDDEN) | |
| block = torch.randint(0, VOCAB, (2, 16)) | |
| starts = torch.rand(2, 16) < 0.4 | |
| plain = copy.deepcopy(base) | |
| arm_plain = _arm(plain, "none") | |
| pcgrad.projection_step(arm_plain, hidden, block, starts) | |
| for mode in ("param", "token"): | |
| projected = copy.deepcopy(base) | |
| arm = _arm(projected, mode) | |
| pcgrad.projection_step(arm, hidden, block, starts) | |
| for head_plain, head_proj in zip(plain.heads, projected.heads): | |
| for a, b in zip(head_plain.resblock.parameters(), head_proj.resblock.parameters()): | |
| assert torch.allclose(a.grad, b.grad, atol=1e-7) | |
| fired = arm.param_fired if mode == "param" else arm.token_conflict | |
| if fired: | |
| fired_seen[mode] = True | |
| assert not torch.allclose(_trunk_grad(plain), _trunk_grad(projected)) | |
| else: | |
| assert torch.allclose(_trunk_grad(plain), _trunk_grad(projected), atol=1e-6, rtol=1e-5) | |
| assert all(fired_seen.values()) | |