Claude Opus 5.5
feat: tabular in-context models, LoRA meta-training, pretraining objectives and probes
8dff74c Download tests/test_contrastive.py from HWresearch/GNN4Colliders: direct link, hf CLI and curl.
- Browser
- Download file 4.8 kB
-
https://huggingface.co/HWresearch/GNN4Colliders/resolve/main/tests/test_contrastive.py
- Command line
-
hf download hf://HWresearch/GNN4Colliders/tests/test_contrastive.py
-
curl -L -o test_contrastive.py https://huggingface.co/HWresearch/GNN4Colliders/resolve/main/tests/test_contrastive.py
4.8 kB
| """Contrastive pretraining of both backbones: the random views, the NT-Xent | |
| loss, and pretraining then fine-tuning and probing.""" | |
| import json | |
| import math | |
| import pytest | |
| import torch | |
| from conftest import GAMGAM_FIXTURES, TTH_FIXTURE, fixture_config, random_events | |
| from gnn4colliders.cli import main | |
| from gnn4colliders.config import ModelConfig, save_config | |
| from gnn4colliders.contrastive import random_view | |
| from gnn4colliders.models import build_model | |
| from gnn4colliders.sequences import ETA, PHI, PT, collate_sequence_batch | |
| BACKBONES = { | |
| "transformer": {"hid_size": 16, "n_layers": 1, "n_heads": 2, "pair_bias": True}, | |
| "edge_network": {"hid_size": 16, "n_layers": 2, "n_proc_steps": 2, "n_heads": 2}, | |
| } | |
| backbones = pytest.mark.parametrize("backbone", BACKBONES) | |
| def _batch(): | |
| events = random_events() | |
| events.object_features[:, 6] = torch.randint( | |
| 0, 5, (events.object_features.shape[0],) | |
| ).float() | |
| return collate_sequence_batch(events, torch.arange(16)) | |
| def test_views_rotate_flip_scale_and_drop_objects_but_keep_the_first(): | |
| batch = _batch() | |
| tokens, mask = batch.tokens, batch.token_mask | |
| generator = torch.Generator().manual_seed(0) | |
| view, kept = random_view( | |
| tokens, mask, scale_jitter=0.2, object_dropout=0.5, generator=generator | |
| ) | |
| assert kept[:, 0].all() and not (kept & ~mask).any() and (mask & ~kept).any() | |
| # One factor per event on pt, one sign on eta, azimuths in [-pi, pi). | |
| ratio = view[..., PT][mask] / tokens[..., PT][mask] | |
| assert ((ratio > 0.8 - 1e-6) & (ratio < 1.2 + 1e-6)).all() | |
| sign = view[..., ETA][mask] / tokens[..., ETA][mask] | |
| torch.testing.assert_close(sign.abs(), torch.ones_like(sign)) | |
| assert (view[..., PHI].abs() <= math.pi).all() | |
| torch.testing.assert_close(view[~mask], tokens[~mask]) | |
| def test_loss_is_finite_and_trains_every_encoder_parameter(backbone): | |
| torch.manual_seed(0) | |
| config = ModelConfig(name="contrastive", backbone=backbone, **BACKBONES[backbone]) | |
| model = build_model(config, num_features=7, num_node_types=5).train() | |
| outputs = model(_batch()) | |
| assert outputs.shape == (16, 3) and torch.isfinite(outputs).all() | |
| # A loss above log(1) and at most about log(2 * 16 - 1) at initialization. | |
| assert 0 < outputs[:, 0].mean() < math.log(31) + 1 | |
| outputs[:, 0].mean().backward() | |
| for name, parameter in model.context_encoder.named_parameters(): | |
| assert parameter.grad is not None and parameter.grad.abs().sum() > 0, name | |
| def test_pretrain_then_fine_tune_and_probe_on_gamgam( | |
| backbone, pretrain_config, finetune_config, overrides, tmp_path | |
| ): | |
| small = [f"model.{key}={value}" for key, value in BACKBONES[backbone].items()] | |
| pretrain = fixture_config( | |
| pretrain_config, | |
| [TTH_FIXTURE, TTH_FIXTURE], | |
| [0, 1], | |
| tmp_path / "pretrain", | |
| "train.max_epochs=2", | |
| *small, | |
| *overrides, | |
| ) | |
| path = str(save_config(pretrain, tmp_path / "pretrain.yaml")) | |
| assert main(["prepare", path]) == 0 | |
| assert main(["train", path]) == 0 | |
| history = [ | |
| json.loads(line) | |
| for line in (pretrain.path / "history.jsonl").read_text().splitlines() | |
| ] | |
| spread = ( | |
| "embedding_spread" if pretrain.model.name == "contrastive" else "target_spread" | |
| ) | |
| assert len(history) == 2 and history[1]["validation"][spread] > 0 | |
| # The pretraining config probes its own encoder, on its labels. | |
| probe = ["data.train_events=40", "model.probe_neighbours=5", "split=validation"] | |
| probe.append(f"model.pretrained={pretrain.path}/last.pt") | |
| assert main(["probe", path, *probe]) == 0 | |
| summary = json.loads((pretrain.path / "validation_probe.json").read_text()) | |
| assert math.isfinite(summary["knn"]["accuracy"]) | |
| finetune = fixture_config( | |
| finetune_config, | |
| GAMGAM_FIXTURES, | |
| list(range(5)), | |
| tmp_path / "finetune", | |
| "train.max_epochs=1", | |
| f"model.pretrained={pretrain.path}/last.pt", | |
| "data.train_events=100", | |
| "model.probe_neighbours=5", | |
| *small, | |
| ) | |
| path = str(save_config(finetune, tmp_path / "finetune.yaml")) | |
| assert main(["prepare", path]) == 0 | |
| assert main(["train", path]) == 0 | |
| assert main(["probe", path]) == 0 | |
| summary = json.loads((finetune.path / "test_probe.json").read_text()) | |
| assert math.isfinite(summary["linear"]["auc"]) | |