feat: add the ATLAS Open Data GamGam 5-class task and faster training
Browse filesAdd the Higgs production multiclass task of Ho et al. (2026), Table 3:
ttH, ggF, VBF, WH, ZH from the ATLAS Open Data 13 TeV GamGam MC, pinned to
a Hugging Face dataset revision.
Data:
- derived branches split ``lep_*`` into electrons and muons and apply the
MV2c10 70% working point, so the pretraining node schema applies
- ``fold_modulus`` derives folds from event numbers in exact integers
- 64-event fixtures of the five samples and an end-to-end workflow test
Training:
- paper recipe (Adam 1e-4, 0.99 decay, stop after 5 epochs without
training-loss improvement) and ``best.pt`` selection by validation AUC
- checkpoint save_every_epochs/save_best/save_last are now honored;
per-epoch history.jsonl; evaluate can write metrics JSON
- macro precision/recall/F1 for multiclass tasks
- O(n log n) weighted ROC AUC on the metric device (was O(P*N) pairs)
Speed (A100, GamGam, batch 1024): about 56 s -> 35 s per epoch by default,
18 s with the opt-in paper_fast preset:
- loader worker processes with pinned, non-blocking batch transfers
- no per-step host synchronization in the multiclass loss or loss check
- group sizes from known counts, index_select gathers, Identity for p=0
dropout (forward outputs unchanged bitwise; parity tests pass)
- opt-in CUDA graph replay of padded training steps and TF32 matmuls
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Files changed (38)
- data/fixtures/testing/atlas_opendata_gamgam/mc_341081.ttH125_gamgam_64.rootAdded
- data/fixtures/testing/atlas_opendata_gamgam/mc_343981.ggH125_gamgam_64.rootAdded
- data/fixtures/testing/atlas_opendata_gamgam/mc_345041.VBFH125_gamgam_64.rootAdded
- data/fixtures/testing/atlas_opendata_gamgam/mc_345318.WpH125J_Wincl_gamgam_64.rootAdded
- data/fixtures/testing/atlas_opendata_gamgam/mc_345319.ZH125J_Zincl_gamgam_64.rootAdded
- scripts/dev/shrink_root_sample.py+37-7
- scripts/slurm/train_gamgam_paper.shAdded+32
- src/gnn4colliders/config/application.py+125-16
- src/gnn4colliders/config/factories.py+1
- src/gnn4colliders/configs/checkpoint/best_auc.yamlAdded+9
- src/gnn4colliders/configs/checkpoint/default.yaml+3
- src/gnn4colliders/configs/config_atlas_opendata_gamgam.yamlAdded+16
- src/gnn4colliders/configs/data/atlas_opendata_gamgam.yamlAdded+82
- src/gnn4colliders/configs/inference/default.yaml+2
- src/gnn4colliders/configs/model/root_gnn/edge_network_gamgam.yamlAdded+8
- src/gnn4colliders/configs/task/gamgam_multiclass.yamlAdded+4
- src/gnn4colliders/configs/trainer/default.yaml+5
- src/gnn4colliders/configs/trainer/paper.yamlAdded+21
- src/gnn4colliders/configs/trainer/paper_fast.yamlAdded+8
- src/gnn4colliders/data/dataset.py+37-13
- src/gnn4colliders/data/loader.py+58-2
- src/gnn4colliders/data/preparation.py+14-5
- src/gnn4colliders/features/derived.pyAdded+103
- src/gnn4colliders/graphs/padding.pyAdded+118
- src/gnn4colliders/models/root_gnn/blocks.py+6-1
- src/gnn4colliders/models/root_gnn/edge_network.py+17-11
- src/gnn4colliders/sequences/sample.py+5-2
- src/gnn4colliders/tasks/_common.py+85-14
- src/gnn4colliders/tasks/multiclass_classification.py+13-3
- src/gnn4colliders/training/__init__.py+2-1
- src/gnn4colliders/training/cuda_graphs.pyAdded+101
- src/gnn4colliders/training/reproducibility.py+11
- src/gnn4colliders/training/trainer.py+77-21
- tests/integration/test_gamgam_workflow.pyAdded+150
- tests/unit/features/test_derived.pyAdded+101
- tests/unit/graphs/test_padding.pyAdded+62
- tests/unit/tasks/test_fast_metrics.pyAdded+72
- tests/unit/training/test_lifecycle_policies.pyAdded+125
12342 unmodified lines7891011121315 unmodified lines2930313233343536373839404142434445461 unmodified line4849505152535455"""Create a small ROOT fixture from a Delphes sample."""from __future__ import annotations2 unmodified linesimport uprootBRANCHES = ("jet_pt","jet_eta","jet_phi",15 unmodified lines"Number",)def shrink_sample(source: Path, target: Path, entries: int) -> None:"""Copy the active branches and first ``entries`` events to ``target``."""if entries < 1:raise ValueError("entries must be positive")target.parent.mkdir(parents=True, exist_ok=True)with uproot.open(source) as source_file:arrays = source_file["output"].arrays(BRANCHES, entry_start=0, entry_stop=entries, library="ak")with uproot.recreate(target) as target_file:target_file["output"] = arraysdef main() -> None:1 unmodified lineparser.add_argument("source", type=Path)parser.add_argument("target", type=Path)parser.add_argument("--entries", type=int, default=64)args = parser.parse_args()shrink_sample(args.source, args.target, args.entries)print(f"Wrote {args.entries} events to {args.target}")12342 unmodified lines7891011121315 unmodified lines29303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374751 unmodified line777879808182838485"""Create a small ROOT fixture from a Delphes or ATLAS Open Data sample."""from __future__ import annotations2 unmodified linesimport uprootDELPHES_BRANCHES = ("jet_pt","jet_eta","jet_phi",15 unmodified lines"Number",)#: Branches read by ``data=atlas_opendata_gamgam``.ATLAS_OPENDATA_BRANCHES = ("jet_pt","jet_eta","jet_phi","jet_MV2c10","photon_pt","photon_eta","photon_phi","lep_pt","lep_eta","lep_phi","lep_charge","lep_type","met_et","met_phi","mcWeight","eventNumber",)PRESETS = {"delphes": ("output", DELPHES_BRANCHES),"atlas_opendata": ("mini", ATLAS_OPENDATA_BRANCHES),}BRANCHES = DELPHES_BRANCHESdef shrink_sample(source: Path, target: Path, entries: int, *, preset: str = "delphes") -> None:"""Copy the active branches and first ``entries`` events to ``target``."""if entries < 1:raise ValueError("entries must be positive")tree, branches = PRESETS[preset]target.parent.mkdir(parents=True, exist_ok=True)with uproot.open(source) as source_file:arrays = source_file[tree].arrays(branches, entry_start=0, entry_stop=entries, library="ak")with uproot.recreate(target) as target_file:target_file[tree] = arraysdef main() -> None:1 unmodified lineparser.add_argument("source", type=Path)parser.add_argument("target", type=Path)parser.add_argument("--entries", type=int, default=64)parser.add_argument("--preset", choices=sorted(PRESETS), default="delphes")args = parser.parse_args()shrink_sample(args.source, args.target, args.entries, preset=args.preset)print(f"Wrote {args.entries} events to {args.target}")
1234567891011121314151617181920212223242526272829303132#!/bin/bash# One baseline training of the ATLAS Open Data GamGam 5-class Higgs production# task (Ho et al. 2026, Table 3), then test-split evaluation of the epoch with# the best validation AUC. The paper's ensemble varies only the seed:# for seed in 1 2 3 4 5; do# sbatch -A <account> --export=ALL,SEED=$seed scripts/slurm/train_gamgam_paper.sh# done# Prepare the event cache first: uv run gnn4colliders prepare \# --config-name config_atlas_opendata_gamgam#SBATCH -N 1#SBATCH -C gpu#SBATCH -q shared#SBATCH -G 1#SBATCH -c 32#SBATCH -t 06:00:00#SBATCH -o logs/gamgam_paper_%j.out#SBATCH -e logs/gamgam_paper_%j.err
set -euo pipefailcd "${SLURM_SUBMIT_DIR:-$(pwd)}"SEED="${SEED:-42}"RUN="${RUN:-outputs/atlas_opendata_gamgam/baseline_seed${SEED}}"export OMP_NUM_THREADS="${OMP_NUM_THREADS:-8}"# Home-directory file locks are unavailable on Perlmutter compute nodes.export UV_CACHE_DIR="${UV_CACHE_DIR:-${SCRATCH:-${HOME}/.cache}/uv-cache}"
run=(--config-name config_atlas_opendata_gamgam environment.device=cuda environment.output_root="${RUN}" trainer.seed="${SEED}" data.seed="${SEED}")uv run gnn4colliders train "${run[@]}" "$@"uv run gnn4colliders evaluate "${run[@]}" \ inference.checkpoint="${RUN}/checkpoints/best.pt" inference.split=test \ inference.metrics_output="${RUN}/test_metrics.json" "$@"1 unmodified line234567822 unmodified lines31323334353645 unmodified lines8283848586878889909169 unmodified lines16116216316416516618 unmodified lines1851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172 unmodified lines22022122222322422513 unmodified lines2392402412422432441 unmodified linefrom __future__ import annotationsimport osfrom pathlib import Pathfrom typing import Any22 unmodified linesfrom gnn4colliders.sequences import collate_sequence_batchfrom gnn4colliders.training import (CheckpointManager,restore_training_state,seed_everything,)45 unmodified linesraise ValueError("root_transformer sequence loading does not yet support DDP")result = {}for name in ("train", "validation", "test"):options = {"indices": events.split_indices(split, name),"shuffle": bool(config.data.shuffle) if name == "train" else False,"seed": int(config.data.seed),}batch_size = int(config.data.batch_size)result[name] = (69 unmodified lines)try:seed_everything(int(config.trainer.seed) + context.rank)run_root = Path(config.environment.output_root)if context.is_main_process:save_resolved(config, run_root)18 unmodified linesvalidation_loader = (split_loaders["validation"] if len(split_loaders["validation"]) else None)trainer.fit(split_loaders["train"],validation_loader,epochs=int(config.trainer.max_epochs),)if not context.is_main_process:barrier(context)return (Path(config.checkpoint.directory)/ f"epoch_{trainer.state.epoch:04d}.pt")manager = CheckpointManager(config.checkpoint.directory)path = manager.save(model=trainer.model,trainer_state=trainer.state,optimizer=trainer.optimizer,scheduler=trainer.scheduler,early_stopping=trainer.early_stopping,task_config=plain(config.task),model_config=plain(config.model),)barrier(context)return pathfinally:finalize(context)def predict_or_evaluate(config: DictConfig, *, evaluate: bool = False) -> Any:validate_config(plain(config))context = initialize(2 unmodified linesdevice=config.trainer.device,)try:split_loaders = loaders(config, context)model, task = _model_and_task(config, split_loaders[config.inference.split])payload = CheckpointManager.load(13 unmodified linesif evaluateelse predictor.predict(split_loaders[config.inference.split]))if not evaluate and context.is_main_process:output = Path(config.inference.output)if str(config.inference.format).lower() != "npz":1 unmodified line234567891022 unmodified lines3334353637383945 unmodified lines8586878889909192939495969769 unmodified lines16716816917017117217317417518 unmodified lines1941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113122 unmodified lines31531631731831932032132232313 unmodified lines3373383393403413423433443453463473483493503513523531 unmodified linefrom __future__ import annotationsimport jsonimport osimport timefrom pathlib import Pathfrom typing import Any22 unmodified linesfrom gnn4colliders.sequences import collate_sequence_batchfrom gnn4colliders.training import (CheckpointManager,configure_matmul_precision,restore_training_state,seed_everything,)45 unmodified linesraise ValueError("root_transformer sequence loading does not yet support DDP")result = {}for name in ("train", "validation", "test"):loading = config.data.get("loader") or {}options = {"indices": events.split_indices(split, name),"shuffle": bool(config.data.shuffle) if name == "train" else False,"seed": int(config.data.seed),"num_workers": int(loading.get("num_workers", 0)),"pin_memory": bool(loading.get("pin_memory", False)),}batch_size = int(config.data.batch_size)result[name] = (69 unmodified lines)try:seed_everything(int(config.trainer.seed) + context.rank)configure_matmul_precision(allow_tf32=bool(config.trainer.get("allow_tf32", False)))run_root = Path(config.environment.output_root)if context.is_main_process:save_resolved(config, run_root)18 unmodified linesvalidation_loader = (split_loaders["validation"] if len(split_loaders["validation"]) else None)policy = _CheckpointPolicy(config, trainer, run_root, context)trainer.fit(split_loaders["train"],validation_loader,epochs=int(config.trainer.max_epochs),on_epoch_end=policy.on_epoch_end,)path = policy.finish()barrier(context)return pathfinally:finalize(context)class _CheckpointPolicy:"""Apply ``config.checkpoint`` saving rules and record epoch history.``save_every_epochs`` saves ``epoch_NNNN.pt`` periodically, ``save_best``keeps ``best.pt`` at the best validation ``monitor`` (a metric name or``loss``) in ``mode``, and ``save_last`` saves the final epoch. Every epochappends one JSON line to ``history.jsonl`` in the run directory. Only themain process writes files."""def __init__(self,config: DictConfig,trainer: Any,run_root: Path,context: DistributedContext,) -> None:options = config.checkpointself.trainer = trainerself.enabled = context.is_main_processself.directory = Path(options.directory)self.every = int(options.get("save_every_epochs") or 0)self.save_best = bool(options.get("save_best", False))self.save_last = bool(options.get("save_last", True))self.monitor = str(options.get("monitor") or "loss")self.mode = str(options.get("mode") or "min")if self.mode not in {"min", "max"}:raise ValueError("checkpoint.mode must be 'min' or 'max'")self.best: float | None = Noneself.task_config = plain(config.task)self.model_config = plain(config.model)self.history = run_root / "history.jsonl"self.started = time.perf_counter()self.manager = CheckpointManager(self.directory) if self.enabled else Noneif self.enabled and not config.checkpoint.resume:self.history.unlink(missing_ok=True)def _save(self, name: str | None = None, value: float | None = None) -> Path:return self.manager.save(model=self.trainer.model,trainer_state=self.trainer.state,optimizer=self.trainer.optimizer,scheduler=self.trainer.scheduler,early_stopping=self.trainer.early_stopping,task_config=self.task_config,model_config=self.model_config,name=name,monitor_name=None if value is None else self.monitor,monitor_value=value,)def _monitored(self, validation: Any) -> float | None:if validation is None:return Noneif self.monitor == "loss":return float(validation.loss)if self.monitor not in validation.metrics:raise KeyError(f"checkpoint monitor {self.monitor!r} was not produced")return float(validation.metrics[self.monitor])def on_epoch_end(self, train_result: Any, validation_result: Any) -> None:if not self.enabled:returnepoch = int(self.trainer.state.epoch)value = self._monitored(validation_result)if self.every and (epoch + 1) % self.every == 0:self._save(value=value)improved = value is not None and (self.best is Noneor (value > self.best if self.mode == "max" else value < self.best))if self.save_best and improved:self.best = valueself._save(name="best.pt", value=value)now = time.perf_counter()record = {"epoch": epoch,"seconds": now - self.started,"learning_rate": [group["lr"] for group in self.trainer.optimizer.param_groups],"train": {"loss": train_result.loss, **train_result.metrics},}self.started = nowif validation_result is not None:record["validation"] = {"loss": validation_result.loss,**validation_result.metrics,}with self.history.open("a") as stream:stream.write(json.dumps(record) + "\n")def finish(self) -> Path:last = self.directory / f"epoch_{self.trainer.state.epoch:04d}.pt"if self.enabled and (self.save_last or not last.exists()):return self._save()return lastdef predict_or_evaluate(config: DictConfig, *, evaluate: bool = False) -> Any:validate_config(plain(config))context = initialize(2 unmodified linesdevice=config.trainer.device,)try:configure_matmul_precision(allow_tf32=bool(config.trainer.get("allow_tf32", False)))split_loaders = loaders(config, context)model, task = _model_and_task(config, split_loaders[config.inference.split])payload = CheckpointManager.load(13 unmodified linesif evaluateelse predictor.predict(split_loaders[config.inference.split]))metrics_output = config.inference.get("metrics_output")if evaluate and metrics_output and context.is_main_process:target = Path(metrics_output)target.parent.mkdir(parents=True, exist_ok=True)summary = {"checkpoint": str(config.inference.checkpoint),"split": str(config.inference.split),"num_samples": int(result.predictions.logits.shape[0]),"metrics": dict(result.metrics),}target.write_text(json.dumps(summary, indent=2) + "\n")if not evaluate and context.is_main_process:output = Path(config.inference.output)if str(config.inference.format).lower() != "npz":
177 unmodified lines178179180181177 unmodified linesearly_stopping=early,scheduler_step=scheduler_step,distributed_context=distributed_context,)177 unmodified lines178179180181182177 unmodified linesearly_stopping=early,scheduler_step=scheduler_step,distributed_context=distributed_context,cuda_graphs=bool(_get(config, "cuda_graphs", False)),)
123456789defaults: - default - _self_
# Keep the epoch with the highest validation AUC (paper model selection).save_every_epochs: 0save_best: truemonitor: aucmode: max3 unmodified lines4563 unmodified linessave_every_epochs: 1save_best: falsesave_last: true3 unmodified lines4567893 unmodified linessave_every_epochs: 1save_best: falsesave_last: true# Validation quantity for save_best: ``loss`` or a task metric name.monitor: lossmode: min
12345678910111213141516defaults: - data: atlas_opendata_gamgam - model: root_gnn/edge_network_gamgam - task: gamgam_multiclass - trainer: paper - checkpoint: best_auc - inference: default - environment: local - distributed: single - export: onnx - _self_
experiment: name: atlas_opendata_gamgamlogging: level: INFO12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182defaults: - _self_
# ATLAS Open Data 13 TeV (2020 release) GamGam collection, Higgs -> gamma gamma# MC for five production modes: the 5-class Higgs production task of# Ho et al., JINST 21 (2026) P08006 (2,473,335 events).source: type: huggingface repo_id: ho22joshua/atlas_opendata repo_type: dataset revision: d1bcc9ccaa304ea09e11f7d724342568f72a0d6e cache_dir: null files: - path: GamGam/2020/MC/mc_341081.ttH125_gamgam.GamGam.root label: 0 size_bytes: 217819076 sha256: c498974926f6c55143d17fc4d3d6fa69bd3718ff92cf7d5cad5c3d67a836c7b7 - path: GamGam/2020/MC/mc_343981.ggH125_gamgam.GamGam.root label: 1 size_bytes: 218418347 sha256: 05b3e6709e8836a7b862a7fde09086b3a9d4d494d62a6984d5df39d8daad13eb - path: GamGam/2020/MC/mc_345041.VBFH125_gamgam.GamGam.root label: 2 size_bytes: 108616148 sha256: 92334fce3bffc9eb6e0745dd6ef354d5ce33da764858511b8f9ca49b862b44e2 - path: GamGam/2020/MC/mc_345318.WpH125J_Wincl_gamgam.GamGam.root label: 3 size_bytes: 29757932 sha256: f255a9c3c6935f976f788b6f32d9a8f6bf576eb12ecd03a6f3fd0a5dea9d1248 - path: GamGam/2020/MC/mc_345319.ZH125J_Zincl_gamgam.GamGam.root label: 4 size_bytes: 58701804 sha256: c85623b04ac0176c64acdb2ecf8e992a63824cfc430a421df742319518ff6748class_names: [ttH, ggF, VBF, WH, ZH]tree_name: mini# Electrons and muons share the ``lep_*`` collection; b-tagging uses the# MV2c10 70% efficiency working point of the Open Data documentation.derived_branches: ele_pt: {source: lep_pt, where: {lep_type: 11}} ele_eta: {source: lep_eta, where: {lep_type: 11}} ele_phi: {source: lep_phi, where: {lep_type: 11}} ele_charge: {source: lep_charge, where: {lep_type: 11}} mu_pt: {source: lep_pt, where: {lep_type: 13}} mu_eta: {source: lep_eta, where: {lep_type: 13}} mu_phi: {source: lep_phi, where: {lep_type: 13}} mu_charge: {source: lep_charge, where: {lep_type: 13}} jet_btag: {source: jet_MV2c10, above: 0.8244273}# Node types match the pretraining schema: jet, electron, muon, photon, MET.feature_branches: - [jet_pt, ele_pt, mu_pt, photon_pt, met_et] - [jet_eta, ele_eta, mu_eta, photon_eta, 0] - [jet_phi, ele_phi, mu_phi, photon_phi, met_phi] - CALC_E - [jet_btag, 0, 0, 0, 0] - [0, ele_charge, mu_charge, 0, 0] - NODE_TYPEobject_types: [vector, vector, vector, vector, single]# Open Data momenta are in MeV; 1e-4 gives the pretraining unit of 10 GeV.scales: [1.0e-4, 1, 1, 1.0e-4, 1, 1, 1]global_features: []# eventNumber % 10 gives the paper's 80:10:10 train:validation:test split.fold_var: eventNumberfold_modulus: 10# Training is unweighted: every event counts once and classes are balanced# by the per-class mean loss. Override with weight_var: mcWeight to study# generator weights (23% of ttH events have mcWeight = -1).weight_var: nullbatch_size: 1024# Preparation worker processes.num_workers: 8# Training-time batch collation runs ahead of the GPU in worker processes.loader: num_workers: 4 pin_memory: trueshuffle: trueseed: 42cache: path: outputs/atlas_opendata_gamgam/events.ptsplits: train_folds: [0, 1, 2, 3, 4, 5, 6, 7] validation_folds: [8] test_folds: [9]1 unmodified line2341 unmodified lineoutput: ${environment.output_root}/predictions/predictions.npzformat: npzsplit: test1 unmodified line234561 unmodified lineoutput: ${environment.output_root}/predictions/predictions.npzformat: npzsplit: test# evaluate also writes its metrics as JSON here when set.metrics_output: null
12345678# Baseline GNN of Ho et al. (2026), Table 1, with a 5-class output.family: root_gnnname: edge_networkhid_size: 64out_size: 5n_layers: 4n_proc_steps: 4dropout: 0.01234# Five Higgs production modes: ttH, ggF, VBF, WH, ZH (data.class_names).type: multiclass_classificationnum_classes: 5absolute_weights: false12 unmodified lines13141512 unmodified linesmode: minpatience: 10min_delta: 1.0e-812 unmodified lines131415161718192012 unmodified linesmode: minpatience: 10min_delta: 1.0e-8# Opt-in GPU speedups; results then match float32 eager training to# floating-point rounding rather than bitwise. cuda_graphs needs a CUDA device,# a single process, graph batches, and an Adam optimizer.allow_tf32: falsecuda_graphs: false
123456789101112131415161718192021# Training recipe of Ho et al. (2026), sections 3.2 and 3.5: Adam at 1e-4# decayed by 0.99 per epoch, stopped after 5 epochs without training-loss# improvement. Model selection (best validation AUC) is checkpoint.monitor.max_epochs: 200device: ${environment.device}seed: 42optimizer: name: adam learning_rate: 1.0e-4 weight_decay: 0.0scheduler: name: exponential gamma: 0.99early_stopping: enabled: true monitor: train_loss mode: min patience: 5 min_delta: 0.0allow_tf32: falsecuda_graphs: false12345678defaults: - paper - _self_
# The paper recipe with captured CUDA graph steps and TF32 matmuls: about 2x# faster per epoch on an A100 for the GamGam task (docs/performance.md).allow_tf32: truecuda_graphs: true1 unmodified line23456789101112131436 unmodified lines515253545556577 unmodified lines6566676869709 unmodified lines808182838485868788899091929336 unmodified lines13013113213313413513623 unmodified lines1601611621631641651664 unmodified lines17117217317417517617 unmodified lines1941951961971981992002012022032042051 unmodified linefrom __future__ import annotationsfrom collections.abc import Iterator, Sequencefrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Anyimport numpy as npfrom .metadata import EventMetadatafrom .root_io import branch_names_from_specs, read_tree, tree_num_entriesfrom .sample import EventSample36 unmodified lines"""Read selected ROOT branches and expose deterministic event indexing.Fold and weight are read as named metadata. Files and events areconcatenated in the order supplied by the caller."""def __init__(7 unmodified linesglobal_features: Sequence[Any] = (),fold_var: str = "eventNumber",weight_var: str | None = None,) -> None:if isinstance(files, (str, Path)):files = [files]9 unmodified lines# entries are represented by the named fold/weight fields below.del tracking_infoself.metadata_specs = (fold_var, 1 if weight_var is None else weight_var)self._branches = branch_names_from_specs(feature_branches,metadata_specs=self.metadata_specs,global_features=self.global_specs,)for file_label in self.labels:if isinstance(file_label, str) and file_label not in self._branches:self._branches = (*self._branches, file_label)self._offsets: tuple[int, ...] = self._make_offsets()def _make_offsets(self) -> tuple[int, ...]:36 unmodified linesfile_start, local_start = self._offsets[file_index], chunk.entry_startfor offset in range(chunk.entry_stop - local_start):local_index = local_start + offsetevent = {branch: arrays[branch][offset] for branch in self._branches}metadata_values = np.asarray([_as_float(event[value])23 unmodified linesglobal_features=globals_,event_index=file_start + local_index,metadata=EventMetadata(fold=int(metadata_values[0]),weight=float(metadata_values[1]),sample_id=f"{path}:{self.tree_name}:{local_index}",extra={4 unmodified lines),)def iter_chunks(self, start: int = 0, stop: int | None = None, *, step: int | None = None) -> Iterator[EventChunk]:17 unmodified linespath=path,entry_start=chunk_start,entry_stop=chunk_stop,arrays=read_tree(path,self.tree_name,self._branches,entry_start=chunk_start,entry_stop=chunk_stop,),)1 unmodified line23456789101112131415161718192036 unmodified lines575859606162636465667 unmodified lines74757677787980819 unmodified lines91929394959697989910010110210310410510610710810936 unmodified lines14614714814915015115223 unmodified lines1761771781791801811824 unmodified lines18718818919019119219319419519619717 unmodified lines2152162172182192202212222232242252262272282291 unmodified linefrom __future__ import annotationsfrom collections.abc import Iterator, Mapping, Sequencefrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Anyimport numpy as npfrom gnn4colliders.features.derived import (apply_derived_branches,parse_derived_branches,resolve_branch_names,)from .metadata import EventMetadatafrom .root_io import branch_names_from_specs, read_tree, tree_num_entriesfrom .sample import EventSample36 unmodified lines"""Read selected ROOT branches and expose deterministic event indexing.Fold and weight are read as named metadata. Files and events areconcatenated in the order supplied by the caller. ``derived_branches``(see :mod:`gnn4colliders.features.derived`) may be referenced like storedbranches. With ``fold_modulus`` the fold is the integer fold branchmodulo that value instead of the branch value itself."""def __init__(7 unmodified linesglobal_features: Sequence[Any] = (),fold_var: str = "eventNumber",weight_var: str | None = None,derived_branches: Any = None,fold_modulus: int | None = None,) -> None:if isinstance(files, (str, Path)):files = [files]9 unmodified lines# entries are represented by the named fold/weight fields below.del tracking_infoself.metadata_specs = (fold_var, 1 if weight_var is None else weight_var)if fold_modulus is not None and int(fold_modulus) < 1:raise ValueError("fold_modulus must be positive")self.fold_modulus = None if fold_modulus is None else int(fold_modulus)self._requested = branch_names_from_specs(feature_branches,metadata_specs=self.metadata_specs,global_features=self.global_specs,)for file_label in self.labels:if isinstance(file_label, str) and file_label not in self._requested:self._requested = (*self._requested, file_label)self._derived = parse_derived_branches(derived_branches)self._branches = resolve_branch_names(self._requested, self._derived)self._offsets: tuple[int, ...] = self._make_offsets()def _make_offsets(self) -> tuple[int, ...]:36 unmodified linesfile_start, local_start = self._offsets[file_index], chunk.entry_startfor offset in range(chunk.entry_stop - local_start):local_index = local_start + offsetevent = {branch: arrays[branch][offset] for branch in self._requested}metadata_values = np.asarray([_as_float(event[value])23 unmodified linesglobal_features=globals_,event_index=file_start + local_index,metadata=EventMetadata(fold=self._fold(event, metadata_values[0]),weight=float(metadata_values[1]),sample_id=f"{path}:{self.tree_name}:{local_index}",extra={4 unmodified lines),)def _fold(self, event: Mapping[str, Any], value: np.float32) -> int:if self.fold_modulus is None:return int(value)return int(np.int64(event[self.metadata_specs[0]])) % self.fold_modulusdef iter_chunks(self, start: int = 0, stop: int | None = None, *, step: int | None = None) -> Iterator[EventChunk]:17 unmodified linespath=path,entry_start=chunk_start,entry_stop=chunk_stop,arrays=apply_derived_branches(read_tree(path,self.tree_name,self._branches,entry_start=chunk_start,entry_stop=chunk_stop,),self._derived,),)
11 unmodified lines1213141516171819202122236 unmodified lines30313233343536373824 unmodified lines636465666768697015 unmodified lines8687888990913 unmodified lines959697989910011 unmodified linesCollate = Callable[[PackedEvents, torch.Tensor], Any]class EventLoader:"""Batch a selection of events with a representation-specific ``collate``.``indices`` selects events in their stored order. Shuffling permutes thatselection with a local generator seeded by ``seed + epoch``, so iteratingdoes not mutate process-wide random state."""def __init__(6 unmodified linesshuffle: bool = False,drop_last: bool = False,seed: int = 12345,) -> None:if batch_size < 1:raise ValueError("batch_size must be positive")self.events = eventsself.collate = collateself.batch_size = batch_size24 unmodified linesdef __iter__(self) -> Iterator[Any]:order = self._order()limit = len(order) - (len(order) % self.batch_size if self.drop_last else 0)for start in range(0, limit, self.batch_size):yield self.collate(self.events, order[start : start + self.batch_size])class DistributedEventLoader(EventLoader):15 unmodified linesshuffle: bool = False,drop_last: bool = False,seed: int = 12345,) -> None:super().__init__(events,3 unmodified linesshuffle=shuffle,drop_last=drop_last,seed=seed,)from gnn4colliders.distributed import DistributedIndices11 unmodified lines12131415161718192021222324252627282930313233343536373839404142434445464748495051526 unmodified lines596061626364656667686970717273747524 unmodified lines10010110210310410510610710810911011111211311411511611711811912015 unmodified lines1361371381391401411421431443 unmodified lines14814915015115215315415515611 unmodified linesCollate = Callable[[PackedEvents, torch.Tensor], Any]class _Batches(torch.utils.data.Dataset):"""Batch ``i`` of one epoch's fixed event order, for DataLoader workers."""def __init__(self,events: PackedEvents,collate: Collate,order: torch.Tensor,batch_size: int,limit: int,) -> None:self.events, self.collate, self.order = events, collate, orderself.batch_size, self.limit = batch_size, limitdef __len__(self) -> int:return -(-self.limit // self.batch_size)def __getitem__(self, index: int) -> Any:start = index * self.batch_sizestop = min(start + self.batch_size, self.limit)return self.collate(self.events, self.order[start:stop])class EventLoader:"""Batch a selection of events with a representation-specific ``collate``.``indices`` selects events in their stored order. Shuffling permutes thatselection with a local generator seeded by ``seed + epoch``, so iteratingdoes not mutate process-wide random state.With ``num_workers > 0`` batches are collated ahead of time in workerprocesses (a standard ``torch.utils.data.DataLoader``) and yielded in thesame order; workers run single-threaded, so batch contents do not dependon the host's thread count. ``pin_memory`` returns page-locked batchesthat can be copied to an accelerator asynchronously."""def __init__(6 unmodified linesshuffle: bool = False,drop_last: bool = False,seed: int = 12345,num_workers: int = 0,pin_memory: bool = False,prefetch_factor: int = 4,) -> None:if batch_size < 1:raise ValueError("batch_size must be positive")if num_workers < 0:raise ValueError("num_workers must be non-negative")self.num_workers = num_workersself.pin_memory = pin_memoryself.prefetch_factor = prefetch_factorself.events = eventsself.collate = collateself.batch_size = batch_size24 unmodified linesdef __iter__(self) -> Iterator[Any]:order = self._order()limit = len(order) - (len(order) % self.batch_size if self.drop_last else 0)if self.num_workers == 0:for start in range(0, limit, self.batch_size):batch = self.collate(self.events, order[start : start + self.batch_size])yield batch.pin_memory() if self.pin_memory else batchreturnyield from torch.utils.data.DataLoader(_Batches(self.events, self.collate, order, self.batch_size, limit),batch_size=None,shuffle=False,num_workers=self.num_workers,pin_memory=self.pin_memory,prefetch_factor=self.prefetch_factor,)class DistributedEventLoader(EventLoader):15 unmodified linesshuffle: bool = False,drop_last: bool = False,seed: int = 12345,num_workers: int = 0,pin_memory: bool = False,prefetch_factor: int = 4,) -> None:super().__init__(events,3 unmodified linesshuffle=shuffle,drop_last=drop_last,seed=seed,num_workers=num_workers,pin_memory=pin_memory,prefetch_factor=prefetch_factor,)from gnn4colliders.distributed import DistributedIndices
46 unmodified lines47484950515244 unmodified lines97989910010110210310410511 unmodified lines11711811912012112212312446 unmodified linesglobal_features=data.get("global_features", []),fold_var=str(data.get("fold_var", "eventNumber")),weight_var=data.get("weight_var"),)44 unmodified linesdata["object_types"],data["scales"],)fold, weight = (_flat_float32(arrays, spec, count) for spec in source.metadata_specs)global_specs = source.global_specsglobals_ = (torch.from_numpy(11 unmodified lines),labels=_labels(source.labels[chunk.file_index], arrays, count),global_features=globals_,# ``int(float32(x))`` and ``float(float32(x))`` match EventSample.fold=torch.from_numpy(fold.astype(np.int64)),weight=torch.from_numpy(weight),file_index=torch.full((count,), chunk.file_index, dtype=torch.long),entry_index=torch.arange(chunk.entry_start, chunk.entry_stop),46 unmodified lines474849505152535444 unmodified lines9910010110210310410510610710810911011111211311411511 unmodified lines12712812913013113213346 unmodified linesglobal_features=data.get("global_features", []),fold_var=str(data.get("fold_var", "eventNumber")),weight_var=data.get("weight_var"),derived_branches=data.get("derived_branches"),fold_modulus=data.get("fold_modulus"),)44 unmodified linesdata["object_types"],data["scales"],)fold_spec, weight_spec = source.metadata_specsweight = _flat_float32(arrays, weight_spec, count)if source.fold_modulus is None:# ``int(float32(x))`` matches EventSample.fold = _flat_float32(arrays, fold_spec, count).astype(np.int64)else:# Exact integer arithmetic: event numbers exceed float32 precision.fold = (np.asarray(ak.to_numpy(arrays[fold_spec])).astype(np.int64)% source.fold_modulus)global_specs = source.global_specsglobals_ = (torch.from_numpy(11 unmodified lines),labels=_labels(source.labels[chunk.file_index], arrays, count),global_features=globals_,fold=torch.from_numpy(fold),weight=torch.from_numpy(weight),file_index=torch.full((count,), chunk.file_index, dtype=torch.long),entry_index=torch.arange(chunk.entry_start, chunk.entry_stop),
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103"""Branches derived from stored ROOT branches before feature construction.
Some ntuples store several object kinds in one collection (for example ATLASOpen Data ``lep_*`` holds electrons and muons, told apart by ``lep_type``) orstore a continuous tagger score where the node schema expects a tag. Aderived branch names such a quantity so the ordinary feature specificationcan refer to it like any stored branch::
derived_branches: ele_pt: {source: lep_pt, where: {lep_type: 11}} jet_btag: {source: jet_MV2c10, above: 0.8244273}
``where`` keeps the objects whose parallel branches equal the given values;``above`` replaces values by ``1.0`` where they exceed the threshold and``0.0`` elsewhere. Both may be combined; selection is applied first."""
from __future__ import annotations
from collections.abc import Iterable, Mappingfrom dataclasses import dataclassfrom typing import Any
import awkward as akimport numpy as np
@dataclass(frozen=True)class DerivedBranch: name: str source: str where: tuple[tuple[str, Any], ...] = () above: float | None = None
@property def inputs(self) -> tuple[str, ...]: return (self.source, *(branch for branch, _ in self.where))
def parse_derived_branches( specification: Mapping[str, Mapping[str, Any]] | None,) -> tuple[DerivedBranch, ...]: """Validate a ``derived_branches`` mapping from the data configuration.""" if not specification: return () derived = [] for name, options in specification.items(): unknown = set(options) - {"source", "where", "above"} if unknown: raise ValueError(f"derived branch {name!r} has unknown keys {unknown}") if "source" not in options: raise ValueError(f"derived branch {name!r} requires a source") derived.append( DerivedBranch( name=str(name), source=str(options["source"]), where=tuple( (str(k), v) for k, v in (options.get("where") or {}).items() ), above=None if options.get("above") is None else float(options["above"]), ) ) names = {item.name for item in derived} for item in derived: if names.intersection(item.inputs): raise ValueError( f"derived branch {item.name!r} depends on a derived branch" ) return tuple(derived)
def resolve_branch_names( requested: Iterable[str], derived: tuple[DerivedBranch, ...]) -> tuple[str, ...]: """Stored branches to read so that every ``requested`` name is available.""" by_name = {item.name: item for item in derived} names: list[str] = [] for name in requested: for stored in by_name[name].inputs if name in by_name else (name,): if stored not in names: names.append(stored) return tuple(names)
def apply_derived_branches( arrays: Any, derived: tuple[DerivedBranch, ...]) -> Mapping[str, Any]: """Return ``arrays`` extended with every derived branch.""" if not derived: return arrays result = {name: arrays[name] for name in arrays.fields} for item in derived: values = arrays[item.source] if item.where: mask = None for branch, expected in item.where: matches = arrays[branch] == expected mask = matches if mask is None else mask & matches values = values[mask] if item.above is not None: values = ak.values_astype(values > item.above, np.float32) result[item.name] = values return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118"""Fixed-capacity graph batch buffers for CUDA graph replay.
A captured CUDA graph replays kernels on fixed tensor addresses and shapes,while collider graph batches vary in node and edge count. A:class:`StaticGraphBatch` holds one capacity bucket: real nodes and edgesfill a prefix and the remainder forms :data:`PADDING_GRAPHS` extra graphswhose edges connect only padding nodes. Sums, means, and LayerNorm never mixgraphs, so the real graphs' outputs do not depend on the padding; the modelreturns ``graphs + PADDING_GRAPHS`` rows of which the last are discarded.Padding is spread over many nodes and graphs because scatter-adds into asingle row serialize on atomic contention."""
from __future__ import annotations
import torch
from gnn4colliders.data.metadata import BatchMetadata
from .batch import GraphBatchfrom .tensor_graph import TensorGraph
#: Extra graphs (and the minimum number of padding nodes) per buffer.PADDING_GRAPHS = 64
def graph_batch_capacity( batch: GraphBatch, *, node_multiple: int, edge_multiple: int) -> tuple[int, int, int]: """``(graphs, nodes, edges)`` bucket for ``batch``.
Capacities are rounded up to a multiple and leave at least :data:`PADDING_GRAPHS` padding nodes and one padding edge. """ graph = batch.graph nodes = int(graph.node_features.shape[0]) + PADDING_GRAPHS edges = int(graph.edge_features.shape[0]) return ( int(graph.node_counts.numel()), -(-nodes // node_multiple) * node_multiple, (edges // edge_multiple + 1) * edge_multiple, )
class StaticGraphBatch: """Device buffers for one ``(graphs, nodes, edges)`` capacity bucket."""
def __init__(self, example: GraphBatch, capacity: tuple[int, int, int]) -> None: graphs, nodes, edges = capacity graph = example.graph device = graph.node_features.device
def buffer(like: torch.Tensor, rows: int) -> torch.Tensor: return like.new_zeros((rows, *like.shape[1:]))
self.graphs, self.nodes, self.edges = graphs, nodes, edges self.graph = TensorGraph( node_features=buffer(graph.node_features, nodes), edge_features=buffer(graph.edge_features, edges), edge_src=buffer(graph.edge_src, edges), edge_dst=buffer(graph.edge_dst, edges), node_batch=buffer(graph.node_batch, nodes), edge_batch=buffer(graph.edge_batch, edges), node_counts=buffer(graph.node_counts, graphs + PADDING_GRAPHS), edge_counts=buffer(graph.edge_counts, graphs + PADDING_GRAPHS), ) self.global_features = ( None if example.global_features is None else buffer(example.global_features, graphs + PADDING_GRAPHS) ) self._positions = torch.arange(max(nodes, edges), device=device) self.batch = GraphBatch( graph=self.graph, labels=buffer(example.labels, graphs).to(device), global_features=self.global_features, metadata=BatchMetadata( fold=buffer(example.metadata.fold, graphs).to(device), weight=buffer(example.metadata.weight, graphs).to(device), sample_id=(), ), )
def load(self, batch: GraphBatch) -> None: """Copy ``batch`` (already on the buffers' device) into the buffers.""" source, target = batch.graph, self.graph nodes = int(source.node_features.shape[0]) edges = int(source.edge_features.shape[0]) if int(source.node_counts.numel()) != self.graphs: raise ValueError("batch has a different number of graphs") padding_nodes, padding_edges = self.nodes - nodes, self.edges - edges if padding_nodes < PADDING_GRAPHS or padding_edges < 1: raise ValueError("batch exceeds the buffer capacity") for name in ("node_features", "node_batch"): getattr(target, name)[:nodes].copy_(getattr(source, name)) for name in ("edge_features", "edge_src", "edge_dst", "edge_batch"): getattr(target, name)[:edges].copy_(getattr(source, name)) # Padding edges are self-loops on padding nodes, assigned round-robin # to the padding graphs; padding node ``k`` belongs to padding graph # ``k % PADDING_GRAPHS``. Stale padding feature rows stay in padding. node_slots = self._positions[:padding_nodes] edge_slots = self._positions[:padding_edges] target.node_batch[nodes:].copy_(node_slots % PADDING_GRAPHS + self.graphs) loops = edge_slots % padding_nodes + nodes target.edge_src[edges:].copy_(loops) target.edge_dst[edges:].copy_(loops) target.edge_batch[edges:].copy_((loops - nodes) % PADDING_GRAPHS + self.graphs) # Padding-graph counts only reach discarded rows; any positive value # keeps them finite without a host synchronization to count them. target.node_counts[: self.graphs].copy_(source.node_counts) target.node_counts[self.graphs :].fill_(1) target.edge_counts[: self.graphs].copy_(source.edge_counts) target.edge_counts[self.graphs :].fill_(1) if self.global_features is not None: self.global_features[: self.graphs].copy_(batch.global_features) self.batch.labels.copy_(batch.labels) self.batch.metadata.fold.copy_(batch.metadata.fold) self.batch.metadata.weight.copy_(batch.metadata.weight)31 unmodified lines323334353637383931 unmodified linessizes.extend((hidden_size, hidden_size) for _ in range(n_layers - 2))sizes.append((hidden_size, out_size))for input_size, output_size in sizes:layers.extend((nn.Linear(input_size, output_size), activation(), nn.Dropout(dropout)))layers.append(nn.LayerNorm(out_size))return nn.Sequential(*layers)31 unmodified lines3233343536373839404142434431 unmodified linessizes.extend((hidden_size, hidden_size) for _ in range(n_layers - 2))sizes.append((hidden_size, out_size))for input_size, output_size in sizes:# Identity keeps module indices (and so state-dict keys) unchanged.layers.extend((nn.Linear(input_size, output_size),activation(),nn.Dropout(dropout) if dropout > 0 else nn.Identity(),))layers.append(nn.LayerNorm(out_size))return nn.Sequential(*layers)
18 unmodified lines19202122232425262728293097 unmodified lines1281291301311321331341351361371381391401411423 unmodified lines1461471481491501511522 unmodified lines15515615715815916016116218 unmodified linesreturn result.index_add_(0, groups, values)def _mean_by_group(values: torch.Tensor, groups: torch.Tensor, count: int) -> torch.Tensor:sums = _sum_by_group(values, groups, count)sizes = _sum_by_group(values.new_ones((values.shape[0], 1)), groups, count)return sums / sizes.clamp_min(1)class EdgeNetwork(nn.Module):97 unmodified linesnode_h = self.node_encoder(graph.node_features)edge_h = self.edge_encoder(graph.edge_features)global_h = self.global_encoder(self._globals(graph, global_features))graph_count = int(graph.node_counts.numel())for _ in range(self.n_proc_steps):edge_h = self.edge_update(torch.cat((edge_h,node_h[graph.edge_src],node_h[graph.edge_dst],global_h[graph.edge_batch],),dim=1,)3 unmodified lines(node_h,_sum_by_group(edge_h, graph.edge_dst, node_h.shape[0]),global_h[graph.node_batch],),dim=1,)2 unmodified linestorch.cat((global_h,_mean_by_group(node_h, graph.node_batch, graph_count),_mean_by_group(edge_h, graph.edge_batch, graph_count),),dim=1,)18 unmodified lines1920212223242526272829303132333435363797 unmodified lines1351361371381391401411421431441451461471483 unmodified lines1521531541551561571582 unmodified lines16116216316416516616716818 unmodified linesreturn result.index_add_(0, groups, values)def _gather(values: torch.Tensor, index: torch.Tensor) -> torch.Tensor:"""``values[index]``; its gradient is a scatter-add rather than thesort-based accumulation of advanced indexing, which is much faster on GPUs."""return values.index_select(0, index)def _mean_by_group(values: torch.Tensor, groups: torch.Tensor, sizes: torch.Tensor) -> torch.Tensor:"""Per-group means; ``sizes`` holds the (exact, integer) group sizes."""sums = _sum_by_group(values, groups, int(sizes.numel()))return sums / sizes.to(values.dtype)[:, None].clamp_min(1)class EdgeNetwork(nn.Module):97 unmodified linesnode_h = self.node_encoder(graph.node_features)edge_h = self.edge_encoder(graph.edge_features)global_h = self.global_encoder(self._globals(graph, global_features))for _ in range(self.n_proc_steps):edge_h = self.edge_update(torch.cat((edge_h,_gather(node_h, graph.edge_src),_gather(node_h, graph.edge_dst),_gather(global_h, graph.edge_batch),),dim=1,)3 unmodified lines(node_h,_sum_by_group(edge_h, graph.edge_dst, node_h.shape[0]),_gather(global_h, graph.node_batch),),dim=1,)2 unmodified linestorch.cat((global_h,_mean_by_group(node_h, graph.node_batch, graph.node_counts),_mean_by_group(edge_h, graph.edge_batch, graph.edge_counts),),dim=1,)
36 unmodified lines37383940414243444536 unmodified linesdef to(self, device: torch.device | str, *, non_blocking: bool = False) -> "SequenceBatch":def move(value: torch.Tensor) -> torch.Tensor:return value.to(device, non_blocking=non_blocking)metadata = BatchMetadata(fold=move(self.metadata.fold),weight=move(self.metadata.weight),36 unmodified lines37383940414243444546474836 unmodified linesdef to(self, device: torch.device | str, *, non_blocking: bool = False) -> "SequenceBatch":return self._map(lambda value: value.to(device, non_blocking=non_blocking))def pin_memory(self) -> "SequenceBatch":return self._map(lambda value: value.pin_memory())def _map(self, move: Any) -> "SequenceBatch":metadata = BatchMetadata(fold=move(self.metadata.fold),weight=move(self.metadata.weight),
49 unmodified lines5051525354553 unmodified lines596061626364656667686970717273747576777849 unmodified linesreturn result / len(unique_labels)def positive_weight_mask(weights: torch.Tensor) -> torch.Tensor:"""The legacy metric path excludes non-positive original weights."""3 unmodified linesdef weighted_binary_auc(labels: torch.Tensor, scores: torch.Tensor, weights: torch.Tensor) -> float:"""Compute weighted binary ROC AUC, including half-credit ties."""labels = labels.detach().cpu().to(dtype=torch.bool)scores = scores.detach().cpu().to(dtype=torch.float64)weights = weights.detach().cpu().to(dtype=torch.float64)positive = labelsnegative = ~labelspositive_weight = weights[positive].sum()negative_weight = weights[negative].sum()if positive_weight <= 0 or negative_weight <= 0:raise ValueError("ROC AUC requires positive and negative samples")pair_scores = scores[positive, None] - scores[None, negative]pair_value = (pair_scores > 0).to(torch.float64) + 0.5 * (pair_scores == 0)pair_weights = weights[positive, None] * weights[None, negative]return float((pair_value * pair_weights).sum() / (positive_weight * negative_weight))49 unmodified lines505152535455565758596061626364656667686970717273747576777879803 unmodified lines8485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814949 unmodified linesreturn result / len(unique_labels)def per_class_weighted_mean(elementwise_loss: torch.Tensor,labels: torch.Tensor,weights: torch.Tensor,num_classes: int,) -> torch.Tensor:""":func:`per_label_weighted_mean` for integer labels in ``[0, num_classes)``.The same reduction (one weighted mean per class present in the batch,averaged equally) computed with dense per-class sums, so it needs nohost synchronization. Per-class sums are accumulated in a different orderthan the masked legacy form, so values agree to floating-point rounding."""one_hot = torch.nn.functional.one_hot(labels, num_classes).to(elementwise_loss.dtype)present = one_hot.sum(dim=0) > 0numerator = (one_hot * (weights * elementwise_loss)[:, None]).sum(dim=0)denominator = (one_hot * weights[:, None]).sum(dim=0)# Absent classes would divide 0 by 0; keep NaN out of the gradient.means = numerator / torch.where(present, denominator, torch.ones_like(denominator))return torch.where(present, means, torch.zeros_like(means)).sum() / present.sum()def positive_weight_mask(weights: torch.Tensor) -> torch.Tensor:"""The legacy metric path excludes non-positive original weights."""3 unmodified linesdef weighted_binary_auc(labels: torch.Tensor, scores: torch.Tensor, weights: torch.Tensor) -> float:"""Compute weighted binary ROC AUC, including half-credit ties.Equivalent to averaging ``1[s_pos > s_neg] + 0.5 * 1[s_pos == s_neg]``over all weighted positive/negative pairs, evaluated in ``O(n log n)`` bysorting scores and accumulating weights per distinct score. Runs on thedevice of ``scores`` using only deterministic operations."""device = scores.devicelabels = labels.detach().to(device=device, dtype=torch.bool).reshape(-1)scores = scores.detach().to(dtype=torch.float64).reshape(-1)weights = weights.detach().to(device=device, dtype=torch.float64).reshape(-1)zero = weights.new_zeros(())positive = torch.where(labels, weights, zero)negative = torch.where(labels, zero, weights)positive_weight = positive.sum()negative_weight = negative.sum()if positive_weight <= 0 or negative_weight <= 0:raise ValueError("ROC AUC requires positive and negative samples")order = torch.argsort(scores)sorted_scores = scores[order]# Cumulative weights at the last element of every group of equal scores.group_end = torch.ones_like(sorted_scores, dtype=torch.bool)group_end[:-1] = sorted_scores[1:] != sorted_scores[:-1]cumulative_positive = torch.cumsum(positive[order], 0)[group_end]cumulative_negative = torch.cumsum(negative[order], 0)[group_end]group_positive = torch.diff(cumulative_positive, prepend=zero.reshape(1))group_negative = torch.diff(cumulative_negative, prepend=zero.reshape(1))below = cumulative_negative - group_negativepair_value = (group_positive * (below + 0.5 * group_negative)).sum()return float(pair_value / (positive_weight * negative_weight))def macro_classification_scores(labels: torch.Tensor, predictions: torch.Tensor, num_classes: int) -> dict[str, float]:"""Macro-averaged precision, recall, and F1 over ``num_classes`` classes.Event counts are unweighted, like accuracy. A class without predicted(or true) events contributes zero precision (or recall)."""confusion = (torch.bincount(labels.reshape(-1).to(torch.long) * num_classes+ predictions.reshape(-1).to(torch.long),minlength=num_classes * num_classes,).reshape(num_classes, num_classes).to(torch.float64))true_positive = confusion.diagonal()predicted = confusion.sum(dim=0)actual = confusion.sum(dim=1)precision = torch.where(predicted > 0, true_positive / predicted, 0.0)recall = torch.where(actual > 0, true_positive / actual, 0.0)total = precision + recallf1 = torch.where(total > 0, 2 * precision * recall / total, 0.0)return {"precision": float(precision.mean()),"recall": float(recall.mean()),"f1": float(f1.mean()),}
8 unmodified lines910111213141530 unmodified lines4647484950515224 unmodified lines777879808 unmodified linesfrom ._common import (batch_labels,batch_weights,per_label_weighted_mean,positive_weight_mask,weighted_binary_auc,)30 unmodified lineselementwise = torch.nn.functional.cross_entropy(logits, labels, reduction="none")return per_label_weighted_mean(elementwise, labels, weights)@staticmethoddef predictions(logits: torch.Tensor) -> dict[str, torch.Tensor]:24 unmodified linesauc = sum(class_aucs) / len(class_aucs)except ValueError:auc = float("nan")return {"accuracy": float(accuracy), "roc_auc": float(auc), "auc": float(auc)}8 unmodified lines91011121314151630 unmodified lines47484950515253545524 unmodified lines80818283848586878889908 unmodified linesfrom ._common import (batch_labels,batch_weights,macro_classification_scores,per_class_weighted_mean,positive_weight_mask,weighted_binary_auc,)30 unmodified lineselementwise = torch.nn.functional.cross_entropy(logits, labels, reduction="none")return per_class_weighted_mean(elementwise, labels, weights, int(logits.shape[1]))@staticmethoddef predictions(logits: torch.Tensor) -> dict[str, torch.Tensor]:24 unmodified linesauc = sum(class_aucs) / len(class_aucs)except ValueError:auc = float("nan")return {"accuracy": float(accuracy),"roc_auc": float(auc),"auc": float(auc),**macro_classification_scores(labels, output["predictions"], output["scores"].shape[1]),}
10 unmodified lines111213141516176 unmodified lines24252627282910 unmodified lines)from .early_stopping import EarlyStoppingfrom .optim import build_optimizer, trainable_parametersfrom .reproducibility import seed_everythingfrom .schedulers import build_schedulerfrom .state import BatchResult, EpochResult, TrainerState, TrainingHistoryfrom .trainer import Trainer6 unmodified lines"TrainerState","TrainingHistory","build_optimizer","build_scheduler","seed_everything","trainable_parameters",10 unmodified lines111213141516176 unmodified lines2425262728293010 unmodified lines)from .early_stopping import EarlyStoppingfrom .optim import build_optimizer, trainable_parametersfrom .reproducibility import configure_matmul_precision, seed_everythingfrom .schedulers import build_schedulerfrom .state import BatchResult, EpochResult, TrainerState, TrainingHistoryfrom .trainer import Trainer6 unmodified lines"TrainerState","TrainingHistory","build_optimizer","configure_matmul_precision","build_scheduler","seed_everything","trainable_parameters",
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101"""Opt-in CUDA graph replay of complete training steps.
Small message-passing models launch on the order of a thousand short kernelsper step, so eager training is bound by host launch overhead rather than GPUwork. Capturing forward, backward, and optimizer step once per batch shapeand replaying it removes that overhead. Graph batches are padded intocapacity buckets (:mod:`gnn4colliders.graphs.padding`) so that a fewcaptures serve a whole epoch.
Results agree with eager training to floating-point rounding, not bitwise:matrix multiplications see padded row counts and the optimizer runs in its``capturable`` form."""
from __future__ import annotations
from dataclasses import dataclassfrom typing import Any
import torchfrom torch import nn
from gnn4colliders.graphs.batch import GraphBatchfrom gnn4colliders.graphs.padding import StaticGraphBatch, graph_batch_capacity
@dataclassclass _Capture: graph: torch.cuda.CUDAGraph buffers: StaticGraphBatch loss: torch.Tensor logits: torch.Tensor learning_rates: tuple[float, ...]
class CudaGraphTrainStep: """Replay captured training steps for graph batches on a CUDA device.
The model must not synchronize with the host. A step is captured for each ``(graphs, nodes, edges)`` bucket and captured again whenever a learning rate changes, because captured kernels hold the rate as a constant. """
def __init__( self, model: nn.Module, task: Any, optimizer: torch.optim.Optimizer, forward: Any, *, node_multiple: int = 512, edge_multiple: int = 4096, ) -> None: if not isinstance(optimizer, (torch.optim.Adam, torch.optim.AdamW)): raise ValueError("CUDA graph training supports the Adam optimizers") for group in optimizer.param_groups: group["capturable"] = True self.model, self.task, self.optimizer = model, task, optimizer self.forward = forward self.node_multiple, self.edge_multiple = node_multiple, edge_multiple self._captures: dict[tuple[int, int, int], _Capture] = {}
@staticmethod def supports(batch: Any) -> bool: return isinstance(batch, GraphBatch) and batch.graph.node_features.is_cuda
def _learning_rates(self) -> tuple[float, ...]: return tuple(float(group["lr"]) for group in self.optimizer.param_groups)
def _capture( self, key: tuple[int, int, int], batch: GraphBatch, rates: tuple[float, ...] ) -> _Capture: self._captures.pop(key, None) buffers = StaticGraphBatch(batch, key) buffers.load(batch) # Gradients allocated during capture belong to this graph's pool. self.optimizer.zero_grad(set_to_none=True) torch.cuda.synchronize() graph = torch.cuda.CUDAGraph() # Loader pin-memory threads keep using CUDA while this thread captures. with torch.cuda.graph(graph, capture_error_mode="thread_local"): logits = self.forward(self.model, buffers.batch)[: buffers.graphs] loss = self.task.loss(logits, buffers.batch) loss.backward() self.optimizer.step() capture = _Capture(graph, buffers, loss, logits, rates) self._captures[key] = capture return capture
def __call__(self, batch: GraphBatch) -> tuple[torch.Tensor, torch.Tensor]: """Train on ``batch``; return copies of its loss and logits.""" key = graph_batch_capacity( batch, node_multiple=self.node_multiple, edge_multiple=self.edge_multiple ) rates = self._learning_rates() capture = self._captures.get(key) if capture is None or capture.learning_rates != rates: capture = self._capture(key, batch, rates) capture.buffers.load(batch) capture.graph.replay() return capture.loss.detach().clone(), capture.logits.detach().clone()17 unmodified lines18192017 unmodified linestorch.cuda.manual_seed_all(seed)if deterministic:torch.use_deterministic_algorithms(True)17 unmodified lines181920212223242526272829303117 unmodified linestorch.cuda.manual_seed_all(seed)if deterministic:torch.use_deterministic_algorithms(True)def configure_matmul_precision(*, allow_tf32: bool) -> None:"""Choose float32 or TensorFloat-32 CUDA matrix multiplication.TF32 rounds matmul inputs to a 10-bit mantissa on Ampere and newer GPUs.The setting is process-wide in PyTorch, so it is applied explicitly fromconfiguration before training or evaluation."""torch.backends.cuda.matmul.allow_tf32 = bool(allow_tf32)
4 unmodified lines567891013 unmodified lines24252627282963 unmodified lines9394959697988 unmodified lines1071081091101111121131141151161171181191201211221231242 unmodified lines12712812913013113213313413513613713813914014114214314414521 unmodified lines16716816917017117217348 unmodified lines22222322422522622722822923023123223323423523623723827 unmodified lines2662672682692702712722736 unmodified lines2802812822832842852862872882892902912922932 unmodified lines2962972982994 unmodified linesimport inspectimport loggingimport mathfrom types import SimpleNamespacefrom typing import Any13 unmodified lineslogger = logging.getLogger(__name__)_POSITIONAL_ARGUMENTS: dict[type, int] = {}63 unmodified linesearly_stopping: EarlyStopping | None = None,scheduler_step: str = "epoch",distributed_context: DistributedContext | None = None,) -> None:if scheduler_step not in {"epoch", "validation"}:raise ValueError("scheduler_step must be 'epoch' or 'validation'")8 unmodified linesself.early_stopping = early_stoppingself.scheduler_step = scheduler_stepself.state = TrainerState()def _train_moved_batch(self, batch: Any) -> BatchResult:self.optimizer.zero_grad(set_to_none=True)logits = _model_forward(self.model, batch)loss = self.task.loss(logits, batch)value = float(loss.detach())if not math.isfinite(value):raise FloatingPointError("non-finite training loss")loss.backward()self.optimizer.step()self.state.global_step += 1return BatchResult(loss=value, logits=logits.detach())def train_batch(self, batch: Any) -> BatchResult:"""Run one optimizer step, moving the supplied batch to the device."""2 unmodified linesdef train_epoch(self, loader: Any) -> EpochResult:self.model.train()losses: list[float] = []batches: list[Any] = []outputs: list[torch.Tensor] = []num_samples = 0for batch in loader:moved = batch.to(self.device)result = self._train_moved_batch(moved)losses.append(result.loss)batches.append(_summary(moved))outputs.append(result.logits)num_samples += int(moved.labels.shape[0])if not losses:raise ValueError("cannot train on an empty loader")logits = torch.cat(outputs, dim=0)combined = _combined_batch(batches, logits)if self.distributed_context.enabled:21 unmodified linesoutputs: list[torch.Tensor] = []with torch.inference_mode():for batch in loader:moved = batch.to(self.device)outputs.append(_model_forward(self.model, moved).detach())batches.append(_summary(moved))if not outputs:48 unmodified linesvalidation_loader: Any | None = None,*,epochs: int,) -> TrainingHistory:"""Train using validation data for every-epoch model selection.The held-out test split is intentionally absent from this method andshould be passed to :meth:`evaluate` only after model selection iscomplete. This avoids the legacy train/test/val naming inversion."""if epochs < 1:raise ValueError("epochs must be positive")if self.early_stopping is not None and validation_loader is None:raise ValueError("early stopping requires a validation loader")history = TrainingHistory()# ``state.epoch`` is the last completed epoch. This makes a saved27 unmodified lines# Record the completed epoch before policy logic can terminate# the loop, so a checkpoint after early stopping is resumable.self.state.epoch = epochif self.early_stopping is not None:if self.early_stopping.monitor == "loss":monitored = validation_result.losselse:if validation_result is None:6 unmodified linesraise KeyError(f"metric {self.early_stopping.monitor!r} was not produced") from errorstop = (self.early_stopping.update(monitored)if self.distributed_context.is_main_processelse False)if broadcast_bool(stop, self.distributed_context):breakif self.scheduler is not None:if self.scheduler_step == "validation":if validation_result is None:raise ValueError(2 unmodified linesself.scheduler.step(validation_result.loss)else:self.scheduler.step()return history4 unmodified lines56789101113 unmodified lines2526272829303132333463 unmodified lines98991001011021031048 unmodified lines1131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491502 unmodified lines15315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218321 unmodified lines20520620720820921021148 unmodified lines26026126226326426526626726826927027127227327427527627727827928028128228328428528628727 unmodified lines3153163173183193203213223233243256 unmodified lines3323333343353363373383393403413423433443452 unmodified lines3483493503513523533543554 unmodified linesimport inspectimport loggingimport mathfrom collections.abc import Callablefrom types import SimpleNamespacefrom typing import Any13 unmodified lineslogger = logging.getLogger(__name__)#: Eager steps before the first CUDA graph capture (lazy CUDA and optimizer#: initialization must not happen during capture).CUDA_GRAPH_WARMUP_STEPS = 3_POSITIONAL_ARGUMENTS: dict[type, int] = {}63 unmodified linesearly_stopping: EarlyStopping | None = None,scheduler_step: str = "epoch",distributed_context: DistributedContext | None = None,cuda_graphs: bool = False,) -> None:if scheduler_step not in {"epoch", "validation"}:raise ValueError("scheduler_step must be 'epoch' or 'validation'")8 unmodified linesself.early_stopping = early_stoppingself.scheduler_step = scheduler_stepself.state = TrainerState()self._graph_step = Noneif cuda_graphs:if self.distributed_context.enabled:raise ValueError("CUDA graph training does not support DDP")if torch.device(self.device).type != "cuda":raise ValueError("CUDA graph training requires a CUDA device")from .cuda_graphs import CudaGraphTrainStepself._graph_step = CudaGraphTrainStep(self.model, task, optimizer, _model_forward)def _step(self, batch: Any) -> tuple[torch.Tensor, torch.Tensor]:"""One optimizer step; returns the detached loss and logits.Nothing here waits for the device, so the host can queue the nextbatch while this one runs."""self.optimizer.zero_grad(set_to_none=True)logits = _model_forward(self.model, batch)loss = self.task.loss(logits, batch)loss.backward()self.optimizer.step()self.state.global_step += 1return loss.detach(), logits.detach()def _train_moved_batch(self, batch: Any) -> BatchResult:loss, logits = self._step(batch)value = float(loss)if not math.isfinite(value):raise FloatingPointError("non-finite training loss")return BatchResult(loss=value, logits=logits)def train_batch(self, batch: Any) -> BatchResult:"""Run one optimizer step, moving the supplied batch to the device."""2 unmodified linesdef train_epoch(self, loader: Any) -> EpochResult:self.model.train()loss_tensors: list[torch.Tensor] = []batches: list[Any] = []outputs: list[torch.Tensor] = []for batch in loader:# Pinned batches (see EventLoader.pin_memory) copy asynchronously.moved = batch.to(self.device, non_blocking=True)if (self._graph_step is not Noneand self.state.global_step >= CUDA_GRAPH_WARMUP_STEPSand self._graph_step.supports(moved)):loss, batch_logits = self._graph_step(moved)self.state.global_step += 1else:loss, batch_logits = self._step(moved)loss_tensors.append(loss)batches.append(_summary(moved))outputs.append(batch_logits)if not loss_tensors:raise ValueError("cannot train on an empty loader")# Batch losses are checked once per epoch to avoid a per-step sync.losses = [float(value) for value in torch.stack(loss_tensors).cpu()]if not all(math.isfinite(value) for value in losses):step = next(i for i, value in enumerate(losses) if not math.isfinite(value))raise FloatingPointError(f"non-finite training loss at batch {step}")logits = torch.cat(outputs, dim=0)combined = _combined_batch(batches, logits)if self.distributed_context.enabled:21 unmodified linesoutputs: list[torch.Tensor] = []with torch.inference_mode():for batch in loader:moved = batch.to(self.device, non_blocking=True)outputs.append(_model_forward(self.model, moved).detach())batches.append(_summary(moved))if not outputs:48 unmodified linesvalidation_loader: Any | None = None,*,epochs: int,on_epoch_end: Callable[[EpochResult, EpochResult | None], None] | None = None,) -> TrainingHistory:"""Train using validation data for every-epoch model selection.The held-out test split is intentionally absent from this method andshould be passed to :meth:`evaluate` only after model selection iscomplete. This avoids the legacy train/test/val naming inversion.``on_epoch_end(train_result, validation_result)`` runs on every rankafter each completed epoch, once ``state``, early stopping, and thescheduler reflect it, so a checkpoint saved there is resumable.Early stopping monitors the validation loss or a validation metric,or the training loss with ``monitor="train_loss"``."""if epochs < 1:raise ValueError("epochs must be positive")if (self.early_stopping is not Noneand self.early_stopping.monitor != "train_loss"and validation_loader is None):raise ValueError("early stopping requires a validation loader")history = TrainingHistory()# ``state.epoch`` is the last completed epoch. This makes a saved27 unmodified lines# Record the completed epoch before policy logic can terminate# the loop, so a checkpoint after early stopping is resumable.self.state.epoch = epochstop = Falseif self.early_stopping is not None:if self.early_stopping.monitor == "train_loss":monitored = train_result.losselif self.early_stopping.monitor == "loss":monitored = validation_result.losselse:if validation_result is None:6 unmodified linesraise KeyError(f"metric {self.early_stopping.monitor!r} was not produced") from errorstop = broadcast_bool(self.early_stopping.update(monitored)if self.distributed_context.is_main_processelse False,self.distributed_context,)# The scheduler is not stepped after the final, stopping epoch.if self.scheduler is not None and not stop:if self.scheduler_step == "validation":if validation_result is None:raise ValueError(2 unmodified linesself.scheduler.step(validation_result.loss)else:self.scheduler.step()if on_epoch_end is not None:on_epoch_end(train_result, validation_result)if stop:breakreturn history
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150"""The ATLAS Open Data GamGam task on 64-event fixtures of its five samples."""
from __future__ import annotations
import jsonimport mathfrom pathlib import Path
import numpy as npimport pytestimport torchimport uproot
from gnn4colliders.cli import mainfrom gnn4colliders.data import EventCachefrom gnn4colliders.training import CheckpointManager
pytestmark = pytest.mark.integration
FIXTURE_DIR = Path("data/fixtures/testing/atlas_opendata_gamgam")# Sorted by dataset ID: ttH, ggF, VBF, WH, ZH, i.e. labels 0..4.FIXTURES = sorted(FIXTURE_DIR.glob("mc_*_64.root"))BTAG_THRESHOLD = 0.8244273
def _common(tmp_path: Path) -> list[str]: return [ "--config-name", "config_atlas_opendata_gamgam", f"data.cache.path={tmp_path}/events.pt", "data.num_workers=0", "data.loader.num_workers=0", "data.loader.pin_memory=false", "data.batch_size=64", "trainer.device=cpu", f"environment.output_root={tmp_path}/run", ]
@pytest.fixturedef prepared(tmp_path: Path) -> Path: if len(FIXTURES) != 5: pytest.skip(f"GamGam fixtures are absent: {FIXTURE_DIR}") files = ",".join(str(path.resolve()) for path in FIXTURES) source = ["~data.source", f"+data.files=[{files}]", "+data.label=[0,1,2,3,4]"] assert main(["prepare", *_common(tmp_path), *source]) == 0 return tmp_path
def test_prepared_features_follow_the_open_data_schema(prepared: Path): events = EventCache(prepared / "events.pt").load() assert len(events) == 5 * 64 assert events.labels.tolist() == [label for label in range(5) for _ in range(64)] assert torch.equal(events.weight, torch.ones(len(events))) offset = 0 for path in FIXTURES: raw = uproot.open(path)["mini"].arrays(library="ak") assert ( events.fold[offset : offset + 64].tolist() == (np.asarray(raw.eventNumber, dtype=np.int64) % 10).tolist() ) for local in (0, 17, 63): event = raw[local] row = int(events.object_offsets[offset + local]) nodes = events.object_features[ row : int(events.object_offsets[offset + local + 1]) ] electron = np.asarray(event.lep_type) == 11 muon = np.asarray(event.lep_type) == 13 pt = np.concatenate( [ np.asarray(event.jet_pt), np.asarray(event.lep_pt)[electron], np.asarray(event.lep_pt)[muon], np.asarray(event.photon_pt), [event.met_et], ] ) node_type = np.repeat( np.arange(5), [ len(event.jet_pt), electron.sum(), muon.sum(), len(event.photon_pt), 1, ], ) # MeV -> units of 10 GeV, matching the pretraining schema. np.testing.assert_allclose(nodes[:, 0], pt * 1e-4, rtol=1e-6) assert nodes[:, 6].tolist() == node_type.tolist() jets = len(event.jet_pt) assert ( nodes[:jets, 4].tolist() == (np.asarray(event.jet_MV2c10) > BTAG_THRESHOLD) .astype(float) .tolist() ) charge = np.concatenate( [ np.asarray(event.lep_charge)[electron], np.asarray(event.lep_charge)[muon], ] ) leptons = slice(jets, jets + len(charge)) assert nodes[leptons, 5].tolist() == charge.astype(float).tolist() assert nodes[-1, 1] == 0.0 # MET has no pseudorapidity offset += 64 assert bool((events.object_counts >= 3).all()) # two photons and MET at least
def test_paper_training_selects_best_validation_auc_and_evaluates(prepared: Path): common = _common(prepared) run = prepared / "run" assert main(["train", *common, "trainer.max_epochs=3"]) == 0 history = [ json.loads(line) for line in (run / "history.jsonl").read_text().splitlines() ] assert [row["epoch"] for row in history] == [0, 1, 2] for row in history: assert row["learning_rate"][0] == pytest.approx( 1e-4 * 0.99 ** (row["epoch"] + 1) ) assert {"accuracy", "auc", "f1", "precision", "recall"} <= set( row["validation"] ) best = CheckpointManager.load(run / "checkpoints" / "best.pt") best_auc = max(row["validation"]["auc"] for row in history) assert best["monitor_name"] == "auc" assert best["monitor_value"] == pytest.approx(best_auc) assert history[best["epoch"]]["validation"]["auc"] == pytest.approx(best_auc) assert (run / "checkpoints" / "epoch_0002.pt").is_file()
output = prepared / "test_metrics.json" assert ( main( [ "evaluate", *common, f"inference.checkpoint={run}/checkpoints/best.pt", "inference.split=test", f"inference.metrics_output={output}", ] ) == 0 ) summary = json.loads(output.read_text()) events = EventCache(prepared / "events.pt").load() assert summary["num_samples"] == int((events.fold == 9).sum()) assert all(math.isfinite(value) for value in summary["metrics"].values())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101from pathlib import Path
import awkward as akimport numpy as npimport pytestimport torchimport uproot
from gnn4colliders.data.preparation import build_packed_eventsfrom gnn4colliders.features.derived import ( apply_derived_branches, parse_derived_branches, resolve_branch_names,)
DERIVED = { "ele_pt": {"source": "lep_pt", "where": {"lep_type": 11}}, "mu_pt": {"source": "lep_pt", "where": {"lep_type": 13}}, "jet_btag": {"source": "jet_score", "above": 0.5},}
def _arrays() -> ak.Array: return ak.Array( { "lep_pt": [[30.0, 20.0, 10.0], [], [5.0]], "lep_type": [[11, 13, 11], [], [13]], "jet_score": [[0.2, 0.9], [0.5], []], } )
def test_derived_branches_select_parallel_objects_and_threshold(): arrays = apply_derived_branches(_arrays(), parse_derived_branches(DERIVED)) assert arrays["ele_pt"].to_list() == [[30.0, 10.0], [], []] assert arrays["mu_pt"].to_list() == [[20.0], [], [5.0]] # ``above`` is strict: a score equal to the threshold is not tagged. assert arrays["jet_btag"].to_list() == [[0.0, 1.0], [0.0], []] assert arrays["lep_pt"].to_list() == _arrays()["lep_pt"].to_list()
def test_resolve_branch_names_reads_sources_once(): derived = parse_derived_branches(DERIVED) assert resolve_branch_names(["ele_pt", "mu_pt", "jet_pt"], derived) == ( "lep_pt", "lep_type", "jet_pt", )
@pytest.mark.parametrize( "specification, message", [ ({"x": {"where": {"a": 1}}}, "requires a source"), ({"x": {"source": "a", "below": 1}}, "unknown keys"), ({"x": {"source": "a"}, "y": {"source": "x"}}, "depends on a derived"), ],)def test_invalid_derived_branches_are_rejected(specification, message): with pytest.raises(ValueError, match=message): parse_derived_branches(specification)
def _write(path: Path) -> None: with uproot.recreate(path) as root_file: root_file["mini"] = { # Above 2**24, where float32 cannot represent every integer. "eventNumber": np.array([2**24 + 1, 2**24 + 3, 7], dtype=np.int64), "lep_pt": ak.Array([[30.0, 20.0], [], [5.0]]), "lep_type": ak.Array([[11, 13], [], [13]]), "met": np.array([1.0, 2.0, 3.0], dtype=np.float32), }
def test_preparation_uses_derived_branches_and_exact_fold_modulus(tmp_path): path = tmp_path / "events.root" _write(path) data = { "tree_name": "mini", "derived_branches": { "ele_pt": {"source": "lep_pt", "where": {"lep_type": 11}}, "mu_pt": {"source": "lep_pt", "where": {"lep_type": 13}}, }, "feature_branches": [["ele_pt", "mu_pt", "met"], "NODE_TYPE"], "object_types": ["vector", "vector", "single"], "scales": [1, 1], "fold_var": "eventNumber", "fold_modulus": 10, } events = build_packed_events(data, [path], [0], 0, 3) assert events.fold.tolist() == [7, 9, 7] assert events.object_counts.tolist() == [3, 1, 2] assert events.object_features.tolist() == [ [30.0, 0.0], [20.0, 1.0], [1.0, 2.0], [2.0, 2.0], [5.0, 1.0], [3.0, 2.0], ] assert events.object_features.dtype == torch.float321234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162import pytestimport torch
from gnn4colliders.data import pack_eventsfrom gnn4colliders.graphs import collate_graph_batchfrom gnn4colliders.graphs.padding import ( PADDING_GRAPHS, StaticGraphBatch, graph_batch_capacity,)from gnn4colliders.models.root_gnn import EdgeNetwork
def _events(seed: int, count: int = 12): generator = torch.Generator().manual_seed(seed) objects = [ torch.rand((int(n), 7), generator=generator) for n in torch.randint(1, 6, (count,), generator=generator) ] return pack_events(objects, torch.randint(0, 3, (count,), generator=generator))
def test_padded_batch_reproduces_real_graph_outputs(): events = _events(0) batch = collate_graph_batch(events, torch.arange(len(events))) torch.manual_seed(0) model = EdgeNetwork(batch.graph, None, 16, 3, 2, 2).eval() capacity = graph_batch_capacity(batch, node_multiple=32, edge_multiple=64) static = StaticGraphBatch(batch, capacity) # Garbage left in padding rows by an earlier, larger batch must not leak. static.graph.node_features.normal_() static.graph.edge_features.normal_() static.load(batch) with torch.no_grad(): expected = model(batch.graph) padded = model(static.batch.graph) assert padded.shape[0] == len(events) + PADDING_GRAPHS torch.testing.assert_close(padded[: len(events)], expected, rtol=1e-5, atol=1e-6) assert torch.equal(static.batch.labels, batch.labels)
def test_capacity_buckets_always_leave_padding_room(): events = _events(1) batch = collate_graph_batch(events, torch.arange(len(events))) graphs, nodes, edges = graph_batch_capacity(batch, node_multiple=8, edge_multiple=8) assert graphs == len(events) assert nodes - batch.graph.node_features.shape[0] >= PADDING_GRAPHS assert edges > batch.graph.edge_features.shape[0] assert nodes % 8 == 0 and edges % 8 == 0
def test_static_batch_rejects_batches_beyond_capacity(): def batch(nodes: int): events = pack_events([torch.rand((nodes, 7)) for _ in range(4)], [0] * 4) return collate_graph_batch(events, torch.arange(4))
small = batch(1) static = StaticGraphBatch( small, graph_batch_capacity(small, node_multiple=1, edge_multiple=1) ) with pytest.raises(ValueError, match="capacity"): static.load(batch(5))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172import pytestimport torch
from gnn4colliders.tasks import MulticlassClassificationTaskfrom gnn4colliders.tasks._common import ( macro_classification_scores, per_class_weighted_mean, per_label_weighted_mean, weighted_binary_auc,)
def _pairwise_auc(labels, scores, weights): positive, negative = labels, ~labels difference = scores[positive, None] - scores[None, negative] value = (difference > 0).double() + 0.5 * (difference == 0).double() pair = weights[positive, None].double() * weights[None, negative].double() total = weights[positive].double().sum() * weights[negative].double().sum() return float((value * pair).sum() / total)
@pytest.mark.parametrize("seed", [0, 1, 2])def test_sorted_auc_equals_pairwise_definition_with_ties(seed): generator = torch.Generator().manual_seed(seed) labels = torch.rand(400, generator=generator) < 0.3 # Coarse scores create many ties across classes. scores = torch.round(torch.rand(400, generator=generator) * 12) / 12 weights = torch.rand(400, generator=generator) + 0.1 assert weighted_binary_auc(labels, scores, weights) == pytest.approx( _pairwise_auc(labels, scores, weights), abs=1e-12 )
def test_auc_rejects_a_single_class(): with pytest.raises(ValueError, match="positive and negative"): weighted_binary_auc( torch.ones(3, dtype=torch.bool), torch.rand(3), torch.ones(3) )
def test_macro_scores_follow_per_class_definitions(): labels = torch.tensor([0, 0, 1, 1, 2, 2]) predictions = torch.tensor([0, 1, 1, 1, 0, 0]) scores = macro_classification_scores(labels, predictions, 3) precision = (1 / 3 + 2 / 3 + 0) / 3 recall = (1 / 2 + 1 + 0) / 3 f1 = (2 * (1 / 3) * (1 / 2) / (1 / 3 + 1 / 2) + 2 * (2 / 3) / (2 / 3 + 1)) / 3 assert scores == pytest.approx({"precision": precision, "recall": recall, "f1": f1})
def test_dense_per_class_mean_matches_masked_legacy_reduction(): generator = torch.Generator().manual_seed(3) loss = torch.rand(50, generator=generator) labels = torch.randint(0, 4, (50,), generator=generator) labels[labels == 2] = 0 # class 2 absent from the batch weights = torch.rand(50, generator=generator) assert torch.allclose( per_class_weighted_mean(loss, labels, weights, 5), per_label_weighted_mean(loss, labels, weights), rtol=1e-6, )
def test_absent_classes_do_not_poison_gradients(): logits = torch.randn(6, 5, requires_grad=True)
class Batch: labels = torch.tensor([0, 0, 1, 1, 3, 3]) metadata = type("Metadata", (), {"weight": torch.ones(6)})
MulticlassClassificationTask().loss(logits, Batch).backward() assert torch.isfinite(logits.grad).all()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125import copy
import pytestimport torch
from gnn4colliders.data import pack_eventsfrom gnn4colliders.data.loader import EventLoaderfrom gnn4colliders.graphs import collate_graph_batchfrom gnn4colliders.models.root_gnn import EdgeNetworkfrom gnn4colliders.tasks import MulticlassClassificationTaskfrom gnn4colliders.training import EarlyStopping, Trainer, build_scheduler
def _events(count: int = 40, seed: int = 0): generator = torch.Generator().manual_seed(seed) objects = [ torch.rand((int(n), 7), generator=generator) for n in torch.randint(1, 6, (count,), generator=generator) ] return pack_events(objects, torch.arange(count) % 3)
def _trainer(events, **kwargs): batch = collate_graph_batch(events, torch.arange(4)) torch.manual_seed(0) model = EdgeNetwork(batch.graph, None, 8, 3, 2, 1) optimizer = torch.optim.Adam(model.parameters(), lr=1e-2) scheduler = build_scheduler(optimizer, gamma=0.5) return Trainer( model, MulticlassClassificationTask(), optimizer, scheduler, **kwargs )
def test_training_loss_early_stopping_needs_no_validation_loader(): events = _events() loader = EventLoader(events, collate_graph_batch, 8) stopping = EarlyStopping(monitor="train_loss", patience=1, min_delta=10.0) trainer = _trainer(events, early_stopping=stopping) history = trainer.fit(loader, epochs=5) # The first epoch sets the best; the second cannot beat it by min_delta. assert len(history.train) == 2 assert trainer.state.epoch == 1
def test_epoch_hook_sees_completed_epoch_and_stepped_scheduler(): events = _events() loader = EventLoader(events, collate_graph_batch, 8) trainer = _trainer(events) seen = []
def hook(train_result, validation_result): seen.append( ( trainer.state.epoch, trainer.optimizer.param_groups[0]["lr"], validation_result is None, train_result.num_samples, ) )
trainer.fit(loader, epochs=2, on_epoch_end=hook) assert seen == [(0, 5e-3, True, 40), (1, 2.5e-3, True, 40)]
def test_loader_workers_yield_identical_pinned_batches(): events = _events(seed=4) serial = EventLoader(events, collate_graph_batch, 7, shuffle=True, seed=3) workers = EventLoader( events, collate_graph_batch, 7, shuffle=True, seed=3, num_workers=2, pin_memory=torch.cuda.is_available(), ) for loader in (serial, workers): loader.set_epoch(2) pairs = list(zip(serial, workers, strict=True)) assert len(pairs) == len(serial) == 6 for left, right in pairs: assert torch.equal(left.graph.edge_features, right.graph.edge_features) assert torch.equal(left.graph.edge_src, right.graph.edge_src) assert torch.equal(left.labels, right.labels) assert left.metadata.sample_id == right.metadata.sample_id
def test_non_finite_loss_is_reported_at_the_end_of_the_epoch(): events = _events() events.object_features[0, 0] = float("nan") trainer = _trainer(events) with pytest.raises(FloatingPointError, match="batch 0"): trainer.train_epoch(EventLoader(events, collate_graph_batch, 8))
@pytest.mark.gpu@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA unavailable")def test_cuda_graph_steps_match_eager_gradients(): from gnn4colliders.training.cuda_graphs import CudaGraphTrainStep from gnn4colliders.training.trainer import _model_forward
events = _events(64, seed=5) batches = [ batch.to("cuda") for batch in EventLoader(events, collate_graph_batch, 16) ] task = MulticlassClassificationTask() torch.manual_seed(0) eager = EdgeNetwork(batches[0].graph, None, 8, 3, 2, 1).cuda() graphed = copy.deepcopy(eager) # A zero learning rate keeps parameters fixed so gradients are comparable. optimizer = torch.optim.Adam(graphed.parameters(), lr=0.0, capturable=True) for batch in batches[:3]: optimizer.zero_grad(set_to_none=True) task.loss(_model_forward(graphed, batch), batch).backward() optimizer.step() step = CudaGraphTrainStep(graphed, task, optimizer, _model_forward) for batch in batches[3:]: eager.zero_grad(set_to_none=True) expected = task.loss(_model_forward(eager, batch), batch) expected.backward() loss, logits = step(batch) torch.testing.assert_close(loss, expected.detach(), rtol=1e-5, atol=1e-6) assert logits.shape == (16, 3) for left, right in zip(eager.parameters(), graphed.parameters()): torch.testing.assert_close(right.grad, left.grad, rtol=1e-4, atol=1e-6)