feat: upgrade to Python 3.14 and PyTorch 2.14; add torch.compile and bfloat16
Browse files- Python 3.14, torch 2.14.1 (cu130 wheels), NumPy 2; frozen parity
references pass unchanged
- trainer.compile (dynamic-shape torch.compile) and trainer.precision
(bfloat16 autocast; graph sums, loss, optimizer in float32)
- CUDA graph steps use device-tensor learning rates, so one capture per
bucket follows the schedule; checkpoints store portable optimizer state
- trainer=paper_fast: compile + CUDA graphs + bfloat16, 5.9 vs 19.2 ms per
GamGam batch for float32 eager on an A100
- loader workers fork explicitly (Python 3.14 defaults to forkserver);
ONNX export keeps the TorchScript exporter
Correction to 5b73bcb: the pre-change float32 eager step was 21.3 ms per
batch (not ~29 ms; that profile used unshuffled ttH-only batches), so the
default path improved by about 1.2x and the large gains are opt-in.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Files changed (22)
- .python-version+1-1
- CHANGELOG.md+10-2
- README_PROJECT.md+2-1
- docs/configuration.md+15-8
- docs/migration.md+8
- docs/performance.md+38-3
- docs/quickstart.md+4-3
- pyproject.toml+6-6
- src/gnn4colliders/config/application.py+1-1
- src/gnn4colliders/config/factories.py+2
- src/gnn4colliders/configs/trainer/default.yaml+4
- src/gnn4colliders/configs/trainer/paper.yaml+2
- src/gnn4colliders/configs/trainer/paper_fast.yaml+7-3
- src/gnn4colliders/data/loader.py+4
- src/gnn4colliders/export/onnx.py+3
- src/gnn4colliders/models/root_gnn/edge_network.py+7-4
- src/gnn4colliders/training/checkpoint.py+16-1
- src/gnn4colliders/training/cuda_graphs.py+28-18
- src/gnn4colliders/training/trainer.py+38-3
- tests/fixtures/root_gnn_dgl_reference/generate.py+1-1
- tests/unit/training/test_lifecycle_policies.py+59
- uv.lock
13.1213.14
10 unmodified lines11121314151617182 unmodified lines21222324252610 unmodified linesselection (`checkpoint=best_auc`), and an ensemble Slurm script.- `data.derived_branches` (object selection and tag thresholds) and`data.fold_modulus` for ntuples outside the Delphes layout.- Opt-in CUDA graph training steps (`trainer.cuda_graphs`) and TF32 matmuls(`trainer.allow_tf32`); `trainer=paper_fast` enables both.- `data.loader.num_workers`/`pin_memory` for background batch collation.- Per-epoch `history.jsonl`, `inference.metrics_output`, early stopping on`train_loss`, and macro precision/recall/F1 for multiclass tasks.2 unmodified lines### Changed- DGL was removed. Preparation is vectorized and writes a model-neutral packed`EventCache` (cache schema 2) instead of pickled DGL graphs; graph batches(`TensorGraph`, edge-index layout) and transformer token batches are built10 unmodified lines111213141516171819202 unmodified lines23242526272829303132333410 unmodified linesselection (`checkpoint=best_auc`), and an ensemble Slurm script.- `data.derived_branches` (object selection and tag thresholds) and`data.fold_modulus` for ntuples outside the Delphes layout.- Opt-in `torch.compile` (`trainer.compile`), bfloat16 autocast(`trainer.precision`), CUDA graph training steps (`trainer.cuda_graphs`), andTF32 matmuls (`trainer.allow_tf32`); `trainer=paper_fast` enables all four,about 3x faster per GamGam epoch than float32 eager on an A100.- `data.loader.num_workers`/`pin_memory` for background batch collation.- Per-epoch `history.jsonl`, `inference.metrics_output`, early stopping on`train_loss`, and macro precision/recall/F1 for multiclass tasks.2 unmodified lines### Changed- The environment moved to Python 3.14 and PyTorch 2.14.1 (CUDA 13.0 wheels;NumPy 2), which is required for `torch.compile`. Frozen ROOT-GNN parityreferences are reproduced unchanged. ONNX export keeps the TorchScriptexporter (`dynamo=False`), and loader workers are explicitly forked becausePython 3.14 no longer forks by default.- DGL was removed. Preparation is vectorized and writes a model-neutral packed`EventCache` (cache schema 2) instead of pickled DGL graphs; graph batches(`TensorGraph`, edge-index layout) and transformer token batches are built
20 unmodified lines2122232425262720 unmodified lines## InstallationThe supported development environment is Python 3.12 (`>=3.12,<3.13`). Coredevelopment is supported on macOS and Linux:```bash20 unmodified lines212223242526272820 unmodified lines## InstallationThe supported development environment is Python 3.14 (`>=3.14,<3.15`) withPyTorch 2.14 (CUDA 13.0 wheels on Linux x86-64). Coredevelopment is supported on macOS and Linux:```bash
149 unmodified lines150151152153154155156157158159160161162163149 unmodified lines## Training speed options`trainer.allow_tf32: true` uses TensorFloat-32 CUDA matrix multiplication and`trainer.cuda_graphs: true` captures complete training steps (forward,backward, Adam step) as CUDA graphs and replays them. Graph batches are paddedinto node/edge capacity buckets with discarded padding graphs, and steps arecaptured again when the learning rate changes. CUDA graphs require a CUDAdevice, a single process, a graph model, and Adam or AdamW. Both options areoff by default: results then agree with float32 eager training tofloating-point rounding rather than bitwise. See [performance.md](performance.md).## Checkpoints and resolved configuration149 unmodified lines150151152153154155156157158159160161162163164165166167168169170149 unmodified lines## Training speed options| Option | Effect || --- | --- || `trainer.compile: true` | `torch.compile` the model forward with dynamic shapes (Inductor); the first epoch includes about a minute of compilation || `trainer.precision: bfloat16` | bfloat16 autocast for the forward pass; parameters, optimizer, loss, and graph sums stay float32 || `trainer.allow_tf32: true` | TensorFloat-32 for float32 CUDA matrix multiplication || `trainer.cuda_graphs: true` | capture complete training steps (forward, backward, Adam step) as CUDA graphs and replay them |For CUDA graphs, graph batches are padded into node/edge capacity buckets withdiscarded padding graphs, and learning rates become device tensors thatschedulers update in place, so one capture per bucket serves the whole run.They require a CUDA device, a single process, a graph model, and Adam orAdamW; checkpoints store plain learning rates and resume in any mode. All fouroptions are off by default, and with any of them results agree with float32eager training to floating-point rounding rather than bitwise.`trainer=paper_fast` enables all four. See [performance.md](performance.md).## Checkpoints and resolved configuration
113 unmodified lines114115116117118119113 unmodified lines- the scheduler is now stepped before the epoch hook rather than after theearly-stopping check; the stopping epoch still does not step it.## Validation requirementsEvery new model family must provide unit tests for its representation and113 unmodified lines114115116117118119120121122123124125126127113 unmodified lines- the scheduler is now stepped before the epoch hook rather than after theearly-stopping check; the stopping epoch still does not step it.Environment upgrade (Python 3.12 / PyTorch 2.2.2 to Python 3.14 / PyTorch2.14.1, CUDA 13.0, NumPy 2): every frozen parity reference, including thebitwise DGL forward outputs and prepared graphs, passes unchanged. ONNX exportpasses `dynamo=False` to keep the TorchScript exporter and its `dynamic_axes`contract (the default dynamo exporter needs `onnxscript`); it emits deprecationwarnings. CUDA graph steps hold learning rates as device tensors; checkpointsstore them as floats with `capturable` disabled.## Validation requirementsEvery new model family must provide unit tests for its representation and
27 unmodified lines28293031323334353627 unmodified lines| Batch construction (1024 events) | 83 ms | 3.3 ms || GPU training epoch | 166.5 ms/batch | 25.8 ms/batch |Training is now bound by the GPU step itself. Mixed precision,`torch.compile`, and size-aware batching are the next levers and have not beenadopted without measurements; size-aware batching and streaming predictionaffect ordering or output semantics.## CPU threads27 unmodified lines282930313233343536373839404142434445464748495051525354555657585960616263646566676869707127 unmodified lines| Batch construction (1024 events) | 83 ms | 3.3 ms || GPU training epoch | 166.5 ms/batch | 25.8 ms/batch |At that point eager training became bound by host-side kernel launches (abouta thousand small kernels per step for this model), not by GPU arithmetic.## GamGam training stepMeasured on the ATLAS Open Data GamGam task (1024-event batches of about 5,600nodes and 30,000 edges; paper model: hidden size 64, 4 MLP layers, 4 graphsteps), one A100-SXM4-80GB, `OMP_NUM_THREADS=8`, loader workers with pinnedmemory, steady-state `Trainer.train_epoch` over 300 shuffled batches:| Options | torch 2.2.2, Python 3.12 | torch 2.14.1, Python 3.14 || --- | ---: | ---: || float32 eager (default) | 18.4 ms | 19.2 ms || bfloat16 eager | | 22.4 ms || CUDA graphs + TF32 | 8.1 ms | 8.5 ms || `torch.compile` | n/a | 13.0 ms || compile + CUDA graphs + TF32 | n/a | 6.1 ms || compile + CUDA graphs + bfloat16 (`paper_fast`) | n/a | 5.9 ms |Before this work the float32 eager step (collation, transfer, and step on thetraining thread) took 21.3 ms per batch against 17.7 ms now with the sametorch 2.2.2 stack, and epoch metrics used a pairwise ROC AUC that could notevaluate the 2M-event training split at all. Training-set AUC after three epochs agreedacross all rows to within GPU run-to-run variation (0.862-0.867). A full`trainer=paper_fast` epoch, including validation, takes about 12.5 s (37 s forthe first, which compiles) against about 38 s for float32 eager.Observations:- bfloat16 alone is slower: the model is small (64 features), so it is notmatrix-multiplication bound, and eager autocast adds cast kernels. Under`torch.compile` the casts fuse and bfloat16 is on par with TF32.- `torch.compile` alone removes about a third of the launch overhead; CUDAgraphs remove the rest, and the two compose.- Graph sums accumulate in float32 under autocast (bfloat16 representsintegers exactly only to 256, and means divide by edge counts).Size-aware batching and streaming prediction remain unexplored because theyaffect ordering or output semantics.## CPU threads
11 unmodified lines1213141516171858 unmodified lines777879808182838411 unmodified lines## InstallThe supported environment is Python 3.12. From the repository root:```bashuv sync --dev58 unmodified linesPreparation takes about 15 s with 8 workers. Training follows the paperrecipe and keeps `best.pt`, the epoch with the best validation AUC; add`trainer=paper_fast` for CUDA graph replay and TF32 (about 2x faster perepoch on an A100). The task, its configuration choices, and the comparisonwith the paper are described in[atlas_opendata_gamgam.md](atlas_opendata_gamgam.md).11 unmodified lines121314151617181958 unmodified lines787980818283848511 unmodified lines## InstallThe supported environment is Python 3.14 with PyTorch 2.14. From therepository root:```bashuv sync --dev58 unmodified linesPreparation takes about 15 s with 8 workers. Training follows the paperrecipe and keeps `best.pt`, the epoch with the best validation AUC; add`trainer=paper_fast` for `torch.compile`, CUDA graph replay, and a bfloat16forward (about 3x faster per epoch on an A100). The task, its configuration choices, and the comparisonwith the paper are described in[atlas_opendata_gamgam.md](atlas_opendata_gamgam.md).
6 unmodified lines789101112131415161718192028 unmodified lines4950515253545556575859606 unmodified linesdynamic = ["version"]description = "Machine-learning tools for collider event analysis."readme = "README.md"requires-python = ">=3.12,<3.13"dependencies = ["awkward>=2.0","hydra-core>=1.3","huggingface-hub>=0.36,<1","numpy>=1.24,<2","scikit-learn>=1.3","torch==2.2.2","uproot>=5.0",]28 unmodified lines[tool.uv.sources]torch = [{ index = "pytorch-cu121", marker = "sys_platform == 'linux' and platform_machine == 'x86_64'" },][[tool.uv.index]]name = "pytorch-cu121"url = "https://download.pytorch.org/whl/cu121"explicit = true[tool.pytest.ini_options]6 unmodified lines789101112131415161718192028 unmodified lines4950515253545556575859606 unmodified linesdynamic = ["version"]description = "Machine-learning tools for collider event analysis."readme = "README.md"requires-python = ">=3.14,<3.15"dependencies = ["awkward>=2.0","hydra-core>=1.3","huggingface-hub>=0.36,<1","numpy>=2.1","scikit-learn>=1.3","torch==2.14.1","uproot>=5.0",]28 unmodified lines[tool.uv.sources]torch = [{ index = "pytorch-cu130", marker = "sys_platform == 'linux' and platform_machine == 'x86_64'" },][[tool.uv.index]]name = "pytorch-cu130"url = "https://download.pytorch.org/whl/cu130"explicit = true[tool.pytest.ini_options]
286 unmodified lines287288289290291292293286 unmodified lines"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},}286 unmodified lines287288289290291292293286 unmodified lines"epoch": epoch,"seconds": now - self.started,"learning_rate": [float(group["lr"]) for group in self.trainer.optimizer.param_groups],"train": {"loss": train_result.loss, **train_result.metrics},}
178 unmodified lines179180181182178 unmodified linesscheduler_step=scheduler_step,distributed_context=distributed_context,cuda_graphs=bool(_get(config, "cuda_graphs", False)),)178 unmodified lines179180181182183184178 unmodified linesscheduler_step=scheduler_step,distributed_context=distributed_context,cuda_graphs=bool(_get(config, "cuda_graphs", False)),compile_model=bool(_get(config, "compile", False)),precision=str(_get(config, "precision", "float32")),)
17 unmodified lines18192017 unmodified lines# a single process, graph batches, and an Adam optimizer.allow_tf32: falsecuda_graphs: false17 unmodified lines1819202122232417 unmodified lines# a single process, graph batches, and an Adam optimizer.allow_tf32: falsecuda_graphs: false# torch.compile the model forward (dynamic shapes), and the forward precision:# float32 or bfloat16 (autocast; loss, graph sums, and optimizer in float32).compile: falseprecision: float32
18 unmodified lines19202118 unmodified linesmin_delta: 0.0allow_tf32: falsecuda_graphs: false18 unmodified lines192021222318 unmodified linesmin_delta: 0.0allow_tf32: falsecuda_graphs: falsecompile: falseprecision: float32
1 unmodified line23456781 unmodified line- 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 line234567891011121 unmodified line- paper- _self_# The paper recipe with a compiled model, captured CUDA graph steps, and a# bfloat16 forward: about 3x faster per epoch than float32 eager on an A100# for the GamGam task (docs/performance.md). Results agree with float32 to# rounding, not bitwise.compile: truecuda_graphs: trueprecision: bfloat16allow_tf32: true
113 unmodified lines114115116117118119113 unmodified linesnum_workers=self.num_workers,pin_memory=self.pin_memory,prefetch_factor=self.prefetch_factor,)113 unmodified lines114115116117118119120121122123113 unmodified linesnum_workers=self.num_workers,pin_memory=self.pin_memory,prefetch_factor=self.prefetch_factor,# Forked workers share the events copy-on-write; Python 3.14's# default (forkserver) would pickle them to every worker. Workers# only collate on the CPU, so forking a CUDA process is safe.multiprocessing_context="fork",)
303 unmodified lines304305306307308309303 unmodified lines"logits": {0: "graphs"},},do_constant_folding=True,)validate_onnx(temporary)with torch.inference_mode():303 unmodified lines304305306307308309310311312303 unmodified lines"logits": {0: "graphs"},},do_constant_folding=True,# The TorchScript exporter keeps the dynamic_axes contract and# needs no onnxscript dependency.dynamo=False,)validate_onnx(temporary)with torch.inference_mode():
14 unmodified lines15161718192021227 unmodified lines303132333435363714 unmodified linesdef _sum_by_group(values: torch.Tensor, groups: torch.Tensor, count: int) -> torch.Tensor:result = values.new_zeros((count, values.shape[1]))return result.index_add_(0, groups, values)def _gather(values: torch.Tensor, index: torch.Tensor) -> torch.Tensor:7 unmodified linesvalues: 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):14 unmodified lines151617181920212223247 unmodified lines32333435363738394014 unmodified linesdef _sum_by_group(values: torch.Tensor, groups: torch.Tensor, count: int) -> torch.Tensor:# Sums accumulate in at least float32, also under bfloat16 autocast.dtype = torch.promote_types(values.dtype, torch.float32)result = values.new_zeros((count, values.shape[1]), dtype=dtype)return result.index_add_(0, groups, values.to(dtype))def _gather(values: torch.Tensor, index: torch.Tensor) -> torch.Tensor:7 unmodified linesvalues: torch.Tensor, groups: torch.Tensor, sizes: torch.Tensor) -> torch.Tensor:"""Per-group means; ``sizes`` holds the (exact, integer) group sizes."""# ``shape[0]`` stays symbolic under torch.compile (no recompile per size).sums = _sum_by_group(values, groups, sizes.shape[0])return sums / sizes.to(sums.dtype)[:, None].clamp_min(1)class EdgeNetwork(nn.Module):
56 unmodified lines57585960616288 unmodified lines15115215315415515615756 unmodified lines}def _rng_state() -> dict[str, Any]:state: dict[str, Any] = {"python": random.getstate(),88 unmodified lines"epoch": epoch,"global_step": int(trainer_state.global_step),"model_state_dict": _state_dict(model),"optimizer_state_dict": optimizer.state_dict()if optimizer is not Noneelse None,"scheduler_state_dict": scheduler.state_dict()56 unmodified lines57585960616263646566676869707172737475767788 unmodified lines16616716816917017117256 unmodified lines}def _portable_optimizer_state(optimizer: torch.optim.Optimizer) -> dict[str, Any]:"""Optimizer state without CUDA-graph settings (tensor learning rates and``capturable``), so any training mode can resume from it."""state = optimizer.state_dict()groups = []for group in state["param_groups"]:group = dict(group)if isinstance(group.get("lr"), torch.Tensor):group["lr"] = float(group["lr"])if "capturable" in group:group["capturable"] = Falsegroups.append(group)return {**state, "param_groups": groups}def _rng_state() -> dict[str, Any]:state: dict[str, Any] = {"python": random.getstate(),88 unmodified lines"epoch": epoch,"global_step": int(trainer_state.global_step),"model_state_dict": _state_dict(model),"optimizer_state_dict": _portable_optimizer_state(optimizer)if optimizer is not Noneelse None,"scheduler_state_dict": scheduler.state_dict()
8 unmodified lines910111213141514 unmodified lines3031323334353637383940414243448 unmodified lines53545556575859603 unmodified lines646566676869707172737475766 unmodified lines838485868788892 unmodified lines92939495969798991001018 unmodified linesResults 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 annotations14 unmodified linesbuffers: StaticGraphBatchloss: torch.Tensorlogits: torch.Tensorlearning_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 learningrate changes, because captured kernels hold the rate as a constant."""def __init__(8 unmodified lines) -> 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"] = Trueself.model, self.task, self.optimizer = model, task, optimizerself.forward = forwardself.node_multiple, self.edge_multiple = node_multiple, edge_multiple3 unmodified linesdef supports(batch: Any) -> bool:return isinstance(batch, GraphBatch) and batch.graph.node_features.is_cudadef _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.6 unmodified linesloss = self.task.loss(logits, buffers.batch)loss.backward()self.optimizer.step()capture = _Capture(graph, buffers, loss, logits, rates)self._captures[key] = capturereturn capture2 unmodified lineskey = 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()8 unmodified lines910111213141514 unmodified lines303132333435363738394041424344454647484950515253545556575859608 unmodified lines697071727374753 unmodified lines7980818283848586876 unmodified lines9495969798991002 unmodified lines1031041051061071081091101118 unmodified linesResults agree with eager training to floating-point rounding, not bitwise:matrix multiplications see padded row counts and the optimizer runs in its``capturable`` form with device-tensor learning rates."""from __future__ import annotations14 unmodified linesbuffers: StaticGraphBatchloss: torch.Tensorlogits: torch.Tensordef make_capturable(optimizer: torch.optim.Optimizer) -> None:"""Prepare an Adam optimizer for capture (idempotent).Learning rates become device tensors, which schedulers update in place,so captured steps follow the schedule without being captured again.Optimizer step counters move to the parameters' device."""for group in optimizer.param_groups:device = group["params"][0].devicegroup["capturable"] = Trueif not isinstance(group["lr"], torch.Tensor):group["lr"] = torch.tensor(float(group["lr"]), device=device)for parameter in group["params"]:state = optimizer.state.get(parameter, {})if isinstance(state.get("step"), torch.Tensor):state["step"] = state["step"].to(device)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 once per``(graphs, nodes, edges)`` capacity bucket."""def __init__(8 unmodified lines) -> None:if not isinstance(optimizer, (torch.optim.Adam, torch.optim.AdamW)):raise ValueError("CUDA graph training supports the Adam optimizers")make_capturable(optimizer)self.model, self.task, self.optimizer = model, task, optimizerself.forward = forwardself.node_multiple, self.edge_multiple = node_multiple, edge_multiple3 unmodified linesdef supports(batch: Any) -> bool:return isinstance(batch, GraphBatch) and batch.graph.node_features.is_cudadef _capture(self, key: tuple[int, int, int], batch: GraphBatch) -> _Capture:# A restored checkpoint may have replaced the optimizer settings.make_capturable(self.optimizer)buffers = StaticGraphBatch(batch, key)buffers.load(batch)# Gradients allocated during capture belong to this graph's pool.6 unmodified linesloss = self.task.loss(logits, buffers.batch)loss.backward()self.optimizer.step()capture = _Capture(graph, buffers, loss, logits)self._captures[key] = capturereturn capture2 unmodified lineskey = graph_batch_capacity(batch, node_multiple=self.node_multiple, edge_multiple=self.edge_multiple)capture = self._captures.get(key)if capture is None:capture = self._capture(key, batch)capture.buffers.load(batch)capture.graph.replay()return capture.loss.detach().clone(), capture.logits.detach().clone()
32 unmodified lines333435363738394058 unmodified lines991001011021031041051061075 unmodified lines1131141151161171183 unmodified lines1221231241251261271281291301 unmodified line13213313413513613713867 unmodified lines20620720820921021121232 unmodified lines_POSITIONAL_ARGUMENTS: dict[type, int] = {}def _positional_arguments(model: nn.Module) -> int:"""Number of positional ``forward`` parameters, cached per model class."""cached = _POSITIONAL_ARGUMENTS.get(type(model))if cached is not None:return cached58 unmodified linesscheduler_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'")self.distributed_context = (distributed_context or DistributedContext.single_process(device))5 unmodified linesself.early_stopping = early_stoppingself.scheduler_step = scheduler_stepself.state = TrainerState()self._graph_step = Noneif cuda_graphs:if self.distributed_context.enabled:3 unmodified linesfrom .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.1 unmodified linebatch 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()67 unmodified lineswith 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:raise ValueError("cannot evaluate an empty loader")32 unmodified lines3334353637383940414243444546474849505152535458 unmodified lines1131141151161171181191201211221231241255 unmodified lines1311321331341351361371381391401411421433 unmodified lines1471481491501511521531541551561571581591601611621631641651 unmodified line16716816917017117217367 unmodified lines24124224324424524624732 unmodified lines_POSITIONAL_ARGUMENTS: dict[type, int] = {}#: ``trainer.precision`` values and their autocast dtype (``None``: float32).PRECISIONS = {"float32": None, "bfloat16": torch.bfloat16}def _unwrapped(model: nn.Module) -> nn.Module:"""The user module inside ``torch.compile`` and DDP wrappers."""while True:inner = getattr(model, "_orig_mod", None) or getattr(model, "module", None)if not isinstance(inner, nn.Module):return modelmodel = innerdef _positional_arguments(model: nn.Module) -> int:"""Number of positional ``forward`` parameters, cached per model class."""model = _unwrapped(model)cached = _POSITIONAL_ARGUMENTS.get(type(model))if cached is not None:return cached58 unmodified linesscheduler_step: str = "epoch",distributed_context: DistributedContext | None = None,cuda_graphs: bool = False,compile_model: bool = False,precision: str = "float32",) -> None:if scheduler_step not in {"epoch", "validation"}:raise ValueError("scheduler_step must be 'epoch' or 'validation'")if precision not in PRECISIONS:raise ValueError(f"precision must be one of {sorted(PRECISIONS)}")self.distributed_context = (distributed_context or DistributedContext.single_process(device))5 unmodified linesself.early_stopping = early_stoppingself.scheduler_step = scheduler_stepself.state = TrainerState()self.precision = precisionself._autocast_dtype = PRECISIONS[precision]# ``self.model`` stays the eager module for checkpoints and callers;# forward passes go through the compiled wrapper when requested.self._forward_module = (torch.compile(self.model, dynamic=True) if compile_model else self.model)self._graph_step = Noneif cuda_graphs:if self.distributed_context.enabled:3 unmodified linesfrom .cuda_graphs import CudaGraphTrainStepself._graph_step = CudaGraphTrainStep(self.model, task, optimizer, lambda _model, batch: self._forward(batch))def _forward(self, batch: Any) -> torch.Tensor:"""Model logits, in float32 even when computed under autocast."""if self._autocast_dtype is None:return _model_forward(self._forward_module, batch)with torch.autocast(device_type=torch.device(self.device).type, dtype=self._autocast_dtype):logits = _model_forward(self._forward_module, batch)return logits.float()def _step(self, batch: Any) -> tuple[torch.Tensor, torch.Tensor]:"""One optimizer step; returns the detached loss and logits.1 unmodified linebatch while this one runs."""self.optimizer.zero_grad(set_to_none=True)logits = self._forward(batch)loss = self.task.loss(logits, batch)loss.backward()self.optimizer.step()67 unmodified lineswith torch.inference_mode():for batch in loader:moved = batch.to(self.device, non_blocking=True)outputs.append(self._forward(moved).detach())batches.append(_summary(moved))if not outputs:raise ValueError("cannot evaluate an empty loader")
13 unmodified lines1415161718192021222313 unmodified linesimport numpy as npimport torchfrom gnn4colliders.compat import load_legacy_checkpointfrom gnn4colliders.data import GraphDataLoader, GraphDatasetfrom gnn4colliders.graphs.preparation import build_graph_samples, open_event_sourcefrom gnn4colliders.models.root_gnn import (EdgeNetwork,FineTunedEdgeNetwork,13 unmodified lines1415161718192021222313 unmodified linesimport numpy as npimport torchfrom gnn4colliders.graphs.preparation import build_graph_samples, open_event_sourcefrom gnn4colliders.compat import load_legacy_checkpointfrom gnn4colliders.data import GraphDataLoader, GraphDatasetfrom gnn4colliders.models.root_gnn import (EdgeNetwork,FineTunedEdgeNetwork,
122 unmodified lines123124125122 unmodified linesassert 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)122 unmodified lines123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184122 unmodified linesassert 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)def test_bfloat16_autocast_trains_with_float32_logits_and_weights():events = _events(seed=6)trainer = _trainer(events, precision="bfloat16")batch = next(iter(EventLoader(events, collate_graph_batch, 8)))loss, logits = trainer._step(batch)assert logits.dtype == torch.float32 and torch.isfinite(loss)assert all(p.dtype == torch.float32 for p in trainer.model.parameters())reference = _trainer(events)._forward(batch)torch.testing.assert_close(_trainer(events, precision="bfloat16")._forward(batch),reference,rtol=5e-2,atol=5e-2,)def test_unknown_precision_is_rejected():with pytest.raises(ValueError, match="precision"):_trainer(_events(), precision="float16")@pytest.mark.gpu@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA unavailable")def test_compiled_graph_steps_with_bfloat16_track_eager_training():events = _events(96, seed=7)loader = EventLoader(events, collate_graph_batch, 16)def run(**options):trainer = _trainer(events, device="cuda", **options)return [trainer.train_epoch(loader).loss for _ in range(3)]eager = run()fast = run(compile_model=True, cuda_graphs=True, precision="bfloat16")assert fast == pytest.approx(eager, rel=5e-2)@pytest.mark.gpu@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA unavailable")def test_cuda_graph_steps_follow_the_learning_rate_schedule(tmp_path):from gnn4colliders.training import CheckpointManagerevents = _events(96, seed=8)loader = EventLoader(events, collate_graph_batch, 16)trainer = _trainer(events, device="cuda", cuda_graphs=True)trainer.train_epoch(loader) # warmup steps, then captured replays# A zero rate must reach the already captured steps.torch.optim.lr_scheduler.ExponentialLR(trainer.optimizer, gamma=0.0).step()before = [p.detach().clone() for p in trainer.model.parameters()]trainer.train_epoch(loader)for old, new in zip(before, trainer.model.parameters()):assert torch.equal(old, new)# Checkpoints stay loadable by eager training on any device.path = CheckpointManager(tmp_path).save(model=trainer.model, trainer_state=trainer.state, optimizer=trainer.optimizer)groups = CheckpointManager.load(path)["optimizer_state_dict"]["param_groups"]assert all(type(g["lr"]) is float and not g["capturable"] for g in groups)