Commit ·
fa0afd8
1
Parent(s): 125ce6d
feat: replace DGL with shared packed events and native PyTorch graphs
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .claude/skills/gnn4colliders-workflow/SKILL.md+3-2
- .codex/skills/gnn4colliders-workflow/SKILL.md+3-2
- .github/workflows/ci.yml+8-4
- AGENTS.md+11-8
- CHANGELOG.md+19-4
- README_PROJECT.md+29-33
- benchmarks/README.md+26-31
- benchmarks/_common.py+15-6
- benchmarks/benchmark_dataloader.py+29-43
- benchmarks/benchmark_inference.py+11-19
- benchmarks/benchmark_prepare.py+2-2
- benchmarks/benchmark_training.py+19-21
- docs/agent-workflows/gnn4colliders-workflow.md+8-6
- docs/architecture.md+26-23
- docs/configuration.md+16-8
- docs/end_to_end_validation.md+1-1
- docs/export.md+5-6
- docs/migration.md+46-6
- docs/performance.md+39-8
- docs/perlmutter.md+10-9
- docs/quickstart.md+11-10
- docs/releasing.md+4-6
- docs/testing.md+6-6
- pyproject.toml+1-17
- scripts/dev/smoke_end_to_end.py+1-8
- scripts/slurm/evaluate.sh+3
- scripts/slurm/prepare_tth_cp_even_odd.sh+2-2
- scripts/slurm/train_multi_gpu.sh+3
- scripts/slurm/train_multi_node.sh+3
- scripts/slurm/train_single_gpu.sh+3
- src/gnn4colliders/cli/__init__.py+4-2
- src/gnn4colliders/config/application.py+43-66
- src/gnn4colliders/config/factories.py+7-8
- src/gnn4colliders/configs/data/hf_delphes.yaml+1-1
- src/gnn4colliders/configs/data/hf_smoke.yaml+1-1
- src/gnn4colliders/configs/data/tth_cp_even_odd.yaml+1-1
- src/gnn4colliders/configs/model/root_gnn/edge_network.yaml-1
- src/gnn4colliders/configs/model/root_gnn/edge_network_binary.yaml-1
- src/gnn4colliders/configs/model/root_gnn/fine_tuned_edge_network.yaml-1
- src/gnn4colliders/data/__init__.py+10-20
- src/gnn4colliders/data/cache.pyDeleted-69
- src/gnn4colliders/data/dataset.py+48-18
- src/gnn4colliders/data/events.pyAdded+303
- src/gnn4colliders/data/graph_dataset.pyDeleted-295
- src/gnn4colliders/data/loader.pyAdded+119
- src/gnn4colliders/data/metadata.py+1-1
- src/gnn4colliders/graphs/preparation.py → src/gnn4colliders/data/preparation.pyRenamed+161-90
- src/gnn4colliders/data/sample.py+1-1
- src/gnn4colliders/export/onnx.py+13-16
- src/gnn4colliders/features/__init__.py+12-2
18 unmodified lines192021222324252618 unmodified lines`uv run python -m validation.run_public_validation` for scientific validationand `GNN4COLLIDERS_REQUIRE_ROOT_GNN=1 uv run pytest tests/parity` for strictROOT-GNN parity. The first transformer path is selected with`model=root_transformer/transformer`; it adapts node features from a preparedgraph cache and currently supports single-process training only. Beforenon-trivial changes, inspect`docs/architecture.md` and `docs/migration.md`. Historical runtime code isnot part of main; use frozen parity fixtures and explicit compatibility18 unmodified lines19202122232425262718 unmodified lines`uv run python -m validation.run_public_validation` for scientific validationand `GNN4COLLIDERS_REQUIRE_ROOT_GNN=1 uv run pytest tests/parity` for strictROOT-GNN parity. The first transformer path is selected with`model=root_transformer/transformer`; it pads the same prepared event-cacheobjects into token sequences and currently supports single-process trainingonly. All models run on plain PyTorch; there is no DGL dependency. Beforenon-trivial changes, inspect`docs/architecture.md` and `docs/migration.md`. Historical runtime code isnot part of main; use frozen parity fixtures and explicit compatibility
27 unmodified lines282930313233343527 unmodified linesneutral; put graph topology in `graphs/` and model-specific behavior in`models/root_gnn/` or `models/root_transformer/`.- The first transformer path is selected with`model=root_transformer/transformer`; it adapts node features from aprepared graph cache and currently supports single-process training only.- Historical runtime code is not part of main. Use committed frozen parityfixtures and explicit compatibility adapters for old checkpoints or outputformats.27 unmodified lines28293031323334353627 unmodified linesneutral; put graph topology in `graphs/` and model-specific behavior in`models/root_gnn/` or `models/root_transformer/`.- The first transformer path is selected with`model=root_transformer/transformer`; it pads the same prepared event-cacheobjects into token sequences and currently supports single-process trainingonly. All models run on plain PyTorch; there is no DGL dependency.- Historical runtime code is not part of main. Use committed frozen parityfixtures and explicit compatibility adapters for old checkpoints or outputformats.
26 unmodified lines272829303132333435363738394041424344454647484933 unmodified lines838485868726 unmodified linesruns-on: ubuntu-lateststeps:- uses: actions/checkout@v4- uses: astral-sh/setup-uv@v6with:version: "0.8.x"enable-cache: true- run: uv sync --dev- run: uv run pytesttest-macos:name: test (macOS ROOT-GNN CPU)runs-on: macos-14steps:- uses: actions/checkout@v4- uses: astral-sh/setup-uv@v6with:version: "0.8.x"enable-cache: true- run: uv sync --dev --extra root-gnn- run: uv run pytest tests/unit tests/integrationpackage:33 unmodified lineswith:version: "0.8.x"enable-cache: true- run: uv sync --dev --extra root-gnn --extra onnx- run: uv run pytest tests/unit/export -v26 unmodified lines27282930313233343536373839404142434445464748495051525333 unmodified lines878889909126 unmodified linesruns-on: ubuntu-lateststeps:- uses: actions/checkout@v4with:lfs: true- uses: astral-sh/setup-uv@v6with:version: "0.8.x"enable-cache: true- run: uv sync --dev- run: GNN4COLLIDERS_REQUIRE_ROOT_GNN=1 uv run pytesttest-macos:name: test (macOS CPU)runs-on: macos-14steps:- uses: actions/checkout@v4with:lfs: true- uses: astral-sh/setup-uv@v6with:version: "0.8.x"enable-cache: true- run: uv sync --dev- run: uv run pytest tests/unit tests/integrationpackage:33 unmodified lineswith:version: "0.8.x"enable-cache: true- run: uv sync --dev --extra onnx- run: uv run pytest tests/unit/export -v
381 unmodified lines38238338438538638738838939039139239355 unmodified lines449450451452453454455456457458459460461462463381 unmodified linesScientific dependencies should be introduced intentionally and with environment compatibility in mind.PyTorch is shared infrastructure for the expected model families and belongsin the base package dependencies. Architecture-specific dependencies belong innamed extras, for example `root-gnn` for DGL. The canonical developmentenvironment for the active ROOT-GNN rewrite is:```bashuv sync --extra root-gnn```---55 unmodified linesruff check .```ROOT-GNN parity validation requires DGL. A package-wide environment where DGLis intentionally absent may skip DGL-dependent tests, but that is incompleteROOT-GNN validation. The required parity gate is:```bashGNN4COLLIDERS_REQUIRE_ROOT_GNN=1 pytest```The gate must fail when DGL cannot be imported.Run more focused tests first when appropriate.381 unmodified lines38238338438538638738838939039139239339439555 unmodified lines451452453454455456457458459460461462463464465466381 unmodified linesScientific dependencies should be introduced intentionally and with environment compatibility in mind.PyTorch is shared infrastructure for the expected model families and belongsin the base package dependencies. Model families are implemented in plainPyTorch on the shared packed-event representation; do not reintroduce a graphor model framework (for example DGL or PyTorch Geometric) as a runtimedependency without explicit agreement. Architecture-specific optionaldependencies belong in named extras. The canonical development environment is:```bashuv sync --dev```---55 unmodified linesruff check .```ROOT-GNN parity validation compares against committed frozen references (GitLFS). The required parity gate is:```bashGNN4COLLIDERS_REQUIRE_ROOT_GNN=1 pytest```The gate must fail when any frozen parity artifact (reference fixtures,pretrained checkpoint, ROOT fixture) is missing or is an unfetched Git LFSpointer, so parity tests can never skip silently.Run more focused tests first when appropriate.
8 unmodified lines910111213141516171819202122238 unmodified lines### Changed- Graph-cache preparation moved from `gnn4colliders.config.application` to`gnn4colliders.graphs.preparation`; the application functions `prepare`,`prepare_shard`, and `write_shard_manifest` remain as thin wrappers andproduce identical caches.- Rewrite task specifications moved to `docs/history/rewrite_tasks/` and thepaper source to `docs/paper/`; empty scaffolding directories were removed.- The Perlmutter Slurm wrappers documented in `docs/perlmutter.md` are nowtracked; an unanchored `slurm/` ignore rule had excluded them.### Compatibility- The `0.1.0` package version remains a static, single-source version exposed8 unmodified lines910111213141516171819202122232425262728293031323334353637388 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 builtper batch from it. The PyTorch model is the canonical `EdgeNetwork`(`TensorEdgeNetwork` remains an alias). Outputs are pinned bit-for-bit tofrozen DGL references. On real ttH data preparation is about 190x faster,caches are 14.5x smaller, and GPU training epochs are about 6.5x faster.Existing graph caches and shards must be prepared again; the `root-gnn`extra and `model.backend=dgl` no longer exist. See `docs/migration.md`.- Epoch metrics no longer keep every batch alive until the epoch ends.- The Slurm training wrappers set `OMP_NUM_THREADS` from the allocation.- Rewrite task specifications moved to `docs/history/rewrite_tasks/` and thepaper source to `docs/paper/`; empty scaffolding directories were removed.- The Perlmutter Slurm wrappers documented in `docs/perlmutter.md` are nowtracked; an unanchored `slurm/` ignore rule had excluded them.### Fixed- `gnn4colliders train` under DDP deadlocked: only rank 0 called `train`, sorank 0 waited forever for its peers in `init_process_group`.- Distributed epoch metrics and evaluation loss combined rank-local logitswith labels and weights gathered from all ranks, which failed with a shapemismatch.### Compatibility- The `0.1.0` package version remains a static, single-source version exposed
7 unmodified lines89101112131415168 unmodified lines2526272829303132333435363738394041424344454621 unmodified lines6869707172737448 unmodified lines12312412512612712812913013113213313413513613713813977 unmodified lines21721821922022122222322422522622722822923023126 unmodified lines25825926026126226326426526626 unmodified lines2932942952962972982993003017 unmodified linescan reuse them without requiring every event to be a graph.```textROOT files -> EventSample -> shared collider features├── GraphSample -> ROOT-GNN└── SequenceSample -> ROOT-Transformer```The new implementation lives under [`src/gnn4colliders`](src/gnn4colliders/).8 unmodified linesdevelopment is supported on macOS and Linux:```bash# macOS (Apple Silicon): CPU ROOT-GNN development and testsuv sync --dev --extra root-gnn# Linux x86_64 with an NVIDIA GPU: validated ROOT-GNN developmentuv sync --dev --extra root-gnn```The core package can be installed without DGL when only shared data or taskcode is needed. ROOT-GNN models, graph construction, and ROOT-GNN reference testsrequire the `root-gnn` extra. On Linux x86_64, it uses the validated CUDA 12.1wheels configured in `pyproject.toml`; a compatible NVIDIA driver is stillrequired. On Apple Silicon macOS, it installs the CPU DGL wheel, supportinglocal graph/cache development. The default ROOT-GNN backend performs trainingwith native PyTorch graph tensors, so it runs on Apple MPS, NVIDIA CUDA, andCPU; DGL remains a cache and graph compatibility adapter. Do not addsite-specific CUDA, Slurm, or filesystem paths to model or task configuration.Use the MPS profile on an Apple Silicon Mac:21 unmodified lines## Quick startPrepare a graph cache from a ROOT tree. The feature specifications below areillustrative placeholders; replace them with the branches in the input tree.The full preparation interface is documented in[`docs/configuration.md`](docs/configuration.md).48 unmodified linesinterpret public `tracking[:, N]` columns. Legacy tracking mappings exist onlyat compatibility boundaries.The ROOT-GNN adapter converts shared features to a directed, fully connectedgraph with no self-loops: an event with `N` nodes has `N * (N - 1)` edges.Node columns are, in order, `pt`, `eta`, `phi`, `energy`, `btag`, `charge`,and `node_type`. Edge columns are `deta`, wrapped `dphi`, and `dR`.Object collections are concatenated in configured object-type order. Thecompatibility energy is `pt * cosh(eta)` before per-column scaling.`GraphSampleCache` stores processed graph samples and schema metadata. It is aLevel-2 graph cache, not the universal event cache. Feature, graph, and cacheschema versions are checked when loading; incompatible versions fail beforetraining.## ROOT-GNN training and transfer77 unmodified lines### ONNX exportInstall the optional export dependencies and export a prepared graph-cachecheckpoint with numerical ONNX validation:```bashuv sync --extra root-gnn --extra onnxuv run gnn4colliders export \export.checkpoint=/path/to/checkpoint.pt \export.output=model.onnx \data.cache.path=/path/to/graph-cache.pt```The model accepts processed graph tensors and returns raw logits. See26 unmodified linesThe configured seed controls initialization and deterministic local loaderordering; distributed process seeds are rank-offset and samplers use`set_epoch`. CPU runs are reproducible for fixed inputs and environment. GPUkernels, DGL, and distributed scheduling can remain nondeterministic, so theproject does not promise bitwise GPU reproducibility.## Development and validation26 unmodified linesbehavior, training, fine-tuning, checkpoint resume, evaluation, prediction,single-process/DDP execution, and validated ONNX export. Streaming distributedoutput remains follow-up work. An initial ROOT-Transformer(`model=root_transformer/transformer`) trains single-process from an existinggraph cache; a native sequence cache and DDP sequence loading are follow-upwork.## Repository layout7 unmodified lines89101112131415168 unmodified lines25262728293031323334353637383921 unmodified lines6162636465666748 unmodified lines11611711811912012112212312412512612712812913013113213313413577 unmodified lines21321421521621721821922022122222322422522622726 unmodified lines25425525625725825926026126226326 unmodified lines2902912922932942952962977 unmodified linescan reuse them without requiring every event to be a graph.```textROOT files -> shared collider features -> EventCache (packed objects)├── graph batches -> ROOT-GNN└── sequence batches -> ROOT-Transformer```The new implementation lives under [`src/gnn4colliders`](src/gnn4colliders/).8 unmodified linesdevelopment is supported on macOS and Linux:```bashuv sync --devgit lfs pull # frozen parity references and pretrained checkpoints```Every model family runs on plain PyTorch, so the same environment supportsCPU, NVIDIA CUDA (Linux x86_64 uses the CUDA 12.1 PyTorch wheels configured in`pyproject.toml`; a compatible driver is still required), and Apple MPS. Thereis no graph-library dependency. Do not add site-specific CUDA, Slurm, orfilesystem paths to model or task configuration.Use the MPS profile on an Apple Silicon Mac:21 unmodified lines## Quick startPrepare an event cache from a ROOT tree. The feature specifications below areillustrative placeholders; replace them with the branches in the input tree.The full preparation interface is documented in[`docs/configuration.md`](docs/configuration.md).48 unmodified linesinterpret public `tracking[:, N]` columns. Legacy tracking mappings exist onlyat compatibility boundaries.Preparation stores each event's objects once, in a model-neutral packed`EventCache`. The ROOT-GNN collate function turns a batch of events into adirected, fully connected graph with no self-loops: an event with `N` nodeshas `N * (N - 1)` edges (a one-node event keeps one self-loop).Node columns are, in order, `pt`, `eta`, `phi`, `energy`, `btag`, `charge`,and `node_type`. Edge columns are `deta`, wrapped `dphi`, and `dR`.Object collections are concatenated in configured object-type order. Thecompatibility energy is `pt * cosh(eta)` before per-column scaling.`EventCache` stores packed object features, labels, globals, named metadata,and schema versions; graph topology and edge features are rebuilt per batch,and the transformer pads the same objects into token sequences. Feature andcache schema versions are checked when loading; incompatible versions, andcaches from before the packed format, fail before training.## ROOT-GNN training and transfer77 unmodified lines### ONNX exportInstall the optional export dependencies and export a prepared event-cachecheckpoint with numerical ONNX validation:```bashuv sync --extra onnxuv run gnn4colliders export \export.checkpoint=/path/to/checkpoint.pt \export.output=model.onnx \data.cache.path=/path/to/events.pt```The model accepts processed graph tensors and returns raw logits. See26 unmodified linesThe configured seed controls initialization and deterministic local loaderordering; distributed process seeds are rank-offset and samplers use`set_epoch`. Single-threaded CPU runs (`OMP_NUM_THREADS=1`) are bitwisereproducible for fixed inputs and environment; multithreaded CPU reductions,GPU kernels, and distributed scheduling can remain nondeterministic, so theproject does not promise bitwise reproducibility outside that setting.## Development and validation26 unmodified linesbehavior, training, fine-tuning, checkpoint resume, evaluation, prediction,single-process/DDP execution, and validated ONNX export. Streaming distributedoutput remains follow-up work. An initial ROOT-Transformer(`model=root_transformer/transformer`) trains single-process from the sameevent cache; DDP sequence loading is follow-up work.## Repository layout
11 unmodified lines1213141516171819202122232425262728293031323334353637383940414243444546474811 unmodified linesuv run python benchmarks/benchmark_training.py --device cuda --profile```DGL-dependent scripts report a structured `skipped` result when the optional`root-gnn` extra is absent. Profiler traces go under `profiles/` and are notcommitted.## Baseline measurementsThe portable baseline in this checkout uses Python 3.12.13, PyTorch 2.2.2+cu121,DGL 2.4.0+cu121, CPU, `nodes=32`, `iterations=10`, and `warmup=3`. Exact timings are machinedependent; the JSON output from a local run is authoritative.| Measurement | Mean | Median || --- | ---: | ---: || feature construction | 0.47 ms/event | 0.46 ms/event || edge features | 0.11 ms/graph | 0.11 ms/graph || graph-sample loader | 1.65 ms/iteration | 1.65 ms/iteration || ROOT-GNN training step | 21.19 ms/step | 5.32 ms/step || ROOT-GNN inference | 1.48 ms/graph | 1.49 ms/graph |On the available NVIDIA A100-PCIE-40GB with CUDA 12.1 runtime, the same smallsynthetic ROOT-GNN benchmark measured 6.41 ms/step (17.3 MiB peak allocated)and 2.00 ms/graph. These are microbenchmarks, not production-workload claims.DGL is available in this environment. The training mean is skewed by one CPUwarmup-adjacent outlier; median is the more useful steady-state indicator. DDPmeasurements require a multi-process run and are not inferred from CPU numbers.The topology cache is bounded to 32 node-count/device/policy entries and onlystores reusable index tensors, never event-specific edge features.On the same CPU, a direct topology microbenchmark for 64 nodes measured201.6 microseconds per cold construction versus 10.5 microseconds for a warmcache lookup (about 19x for this isolated operation). This is a targetedindex-construction result, not an end-to-end training speedup; graph featureconstruction and DGL message passing remain separate costs.11 unmodified lines121314151617181920212223242526272829303132333435363738394041424311 unmodified linesuv run python benchmarks/benchmark_training.py --device cuda --profile```Loader, training, and inference benchmarks use synthetic packed events with3-20 objects per event at batch size 1024. Profiler traces go under`profiles/` and are not committed. Set `OMP_NUM_THREADS` to the CPU allocation;the default of every visible core distorts CPU timings.## Baseline measurementsMeasured in this checkout with Python 3.12.13, PyTorch 2.2.2+cu121,`OMP_NUM_THREADS=8`, `iterations=10`, and `warmup=3`, on synthetic batches of1024 events (about 11.5 objects and 153,000 edges per batch). Exact timings aremachine dependent; the JSON output from a local run is authoritative.| Measurement | Mean || --- | ---: || graph batch construction (CPU) | 6.0 ms/batch || sequence batch construction (CPU) | 0.8 ms/batch || per-event feature construction (32 objects) | 0.42 ms/event || ROOT-GNN training step, A100 (hid 128, 4 steps) | 55.3 ms/step, 2.6 GiB peak || ROOT-GNN inference, A100 | 23.0 ms/batch || ROOT-GNN training step, CPU | 2.86 s/step |Real-data measurements of preparation, cache size, and epoch throughput are in[`../docs/performance.md`](../docs/performance.md). Preparation is measuredend to end with `benchmark_prepare.py`; the vectorized preparation path doesnot use the per-event feature builder timed above.The topology cache of `fully_connected_edges` is bounded to 32node-count/device/policy entries and only stores reusable index tensors;batched graphs use the vectorized `fully_connected_batch_edges` instead.
56 unmodified lines575859606162636465666768697056 unmodified lines}if device.type == "cuda" and torch.cuda.is_available():result["gpu"] = torch.cuda.get_device_name(device)try:import dglresult["dgl"] = dgl.__version__except ImportError:result["dgl"] = Nonereturn resultdef report(name: str, values: dict[str, Any]) -> None:print(json.dumps({"benchmark": name, **values}, sort_keys=True))56 unmodified lines575859606162636465666768697071727374757677787956 unmodified lines}if device.type == "cuda" and torch.cuda.is_available():result["gpu"] = torch.cuda.get_device_name(device)return resultdef synthetic_events(count: int, *, seed: int, max_objects: int = 20):"""Collider-like packed events with 3 to ``max_objects`` objects each."""from gnn4colliders.data import pack_eventsgenerator = torch.Generator().manual_seed(seed)counts = torch.randint(3, max_objects + 1, (count,), generator=generator)objects = []for size in counts.tolist():features = torch.randn((size, 7), generator=generator)features[:, 2] = torch.rand(size, generator=generator) * 6.28 - 3.14objects.append(features)labels = torch.randint(0, 2, (count,), generator=generator)return pack_events(objects, labels)def report(name: str, values: dict[str, Any]) -> None:print(json.dumps({"benchmark": name, **values}, sort_keys=True))
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162"""Measure deterministic loader/batch construction when ROOT-GNN is installed."""from __future__ import annotationsimport torchtry:from ._common import common_parser, measure, metadata, reportexcept ImportError:from _common import common_parser, measure, metadata, reportdef main() -> None:parser = common_parser(__doc__)parser.add_argument("--batch-size", type=int, default=8)parser.add_argument("--samples", type=int, default=64)args = parser.parse_args()device = torch.device(args.device)try:import dglfrom gnn4colliders.data import (EventMetadata,GraphDataLoader,GraphDataset,GraphSample,)except ImportError:report("dataloader",{**metadata(device), "status": "skipped: install root-gnn extra"},)returnsamples = []for index in range(args.samples):graph = dgl.graph((torch.tensor([0, 1]), torch.tensor([1, 0])), num_nodes=2)graph.ndata["features"] = torch.ones(2, 7)graph.edata["features"] = torch.ones(2, 3)samples.append(GraphSample(graph, torch.tensor(index % 2), None, EventMetadata(0, 1.0, str(index))))loader = GraphDataLoader(GraphDataset(samples), args.batch_size)result = measure(lambda: list(loader),iterations=args.iterations,warmup=args.warmup,device=device,)report("dataloader",{**metadata(device),**result,"batch_size": args.batch_size,"batches_per_second": 1000 / result["mean_ms"],},)if __name__ == "__main__":123456789101112131415161718192021222324252627282930313233343536373839404142434445464748"""Measure batch construction from packed events at a realistic batch size."""from __future__ import annotationsimport torchtry:from ._common import common_parser, measure, metadata, report, synthetic_eventsexcept ImportError:from _common import common_parser, measure, metadata, report, synthetic_eventsfrom gnn4colliders.data import EventLoaderfrom gnn4colliders.graphs import collate_graph_batchfrom gnn4colliders.sequences import collate_sequence_batchdef main() -> None:parser = common_parser(__doc__)parser.add_argument("--batch-size", type=int, default=1024)parser.add_argument("--batches", type=int, default=8)args = parser.parse_args()device = torch.device(args.device)events = synthetic_events(args.batch_size * args.batches, seed=args.seed)for name, collate in (("graph_batches", collate_graph_batch),("sequence_batches", collate_sequence_batch),):loader = EventLoader(events, collate, args.batch_size, shuffle=True)result = measure(lambda: [batch.to(device) for batch in loader],iterations=args.iterations,warmup=args.warmup,device=device,)per_batch = result["mean_ms"] / len(loader)report(name,{**metadata(device),**result,"batch_size": args.batch_size,"ms_per_batch": per_batch,"events_per_second": args.batch_size * 1000 / per_batch,},)if __name__ == "__main__":
123456789101112131415161718192021222324252627282930313233343536"""Measure ROOT-GNN inference with fixed synthetic graph input."""from __future__ import annotationsimport torchtry:from ._common import common_parser, measure, metadata, reportexcept ImportError:from _common import common_parser, measure, metadata, reportdef main() -> None:parser = common_parser(__doc__)args = parser.parse_args()device = torch.device(args.device)try:import dglfrom gnn4colliders.models.root_gnn import EdgeNetworkexcept ImportError:report("inference",{**metadata(device), "status": "skipped: install root-gnn extra"},)returngraph = dgl.graph((torch.tensor([0, 1]), torch.tensor([1, 0])), num_nodes=2).to(device)graph.ndata["features"] = torch.ones(2, 7, device=device)graph.edata["features"] = torch.ones(2, 3, device=device)model = (EdgeNetwork(graph, None, hid_size=16, out_size=2, n_layers=1, n_proc_steps=1).to(device).eval())12345678910111213141516171819202122232425262728"""Measure ROOT-GNN inference on a realistic synthetic batch."""from __future__ import annotationsimport torchtry:from ._common import common_parser, measure, metadata, report, synthetic_eventsexcept ImportError:from _common import common_parser, measure, metadata, report, synthetic_eventsfrom gnn4colliders.graphs import collate_graph_batchfrom gnn4colliders.models.root_gnn import EdgeNetworkdef main() -> None:parser = common_parser(__doc__)parser.add_argument("--batch-size", type=int, default=1024)args = parser.parse_args()device = torch.device(args.device)events = synthetic_events(args.batch_size, seed=args.seed)batch = collate_graph_batch(events, torch.arange(len(events))).to(device)graph = batch.graphmodel = (EdgeNetwork(graph, None, hid_size=128, out_size=1, n_layers=2, n_proc_steps=4).to(device).eval())
123451 unmodified lines56575859606162"""Benchmark ROOT reading, feature construction, and graph preparation."""from __future__ import annotations51 unmodified linesroot_file = Path(directory) / "events.root"_write_fixture(root_file, args.events, args.nodes)data["files"] = [str(root_file)]data["cache"] = {"path": str(Path(directory) / "graphs.pt")}data["num_workers"] = args.workersstart = time.perf_counter()prepare(OmegaConf.create({"data": data, "distributed": {"enabled": False}}))123451 unmodified lines56575859606162"""Benchmark ROOT reading, feature construction, and event-cache preparation."""from __future__ import annotations51 unmodified linesroot_file = Path(directory) / "events.root"_write_fixture(root_file, args.events, args.nodes)data["files"] = [str(root_file)]data["cache"] = {"path": str(Path(directory) / "events.pt")}data["num_workers"] = args.workersstart = time.perf_counter()prepare(OmegaConf.create({"data": data, "distributed": {"enabled": False}}))
12342 unmodified lines78910111213141516171819202122232425262728293031323334353637383940414243444546474812 unmodified lines616263646566"""Measure a short ROOT-GNN training section and optionally emit a profiler trace."""from __future__ import annotations2 unmodified linesimport torchtry:from ._common import common_parser, measure, metadata, reportexcept ImportError:from _common import common_parser, measure, metadata, reportdef main() -> None:parser = common_parser(__doc__)parser.add_argument("--batch-size", type=int, default=4)parser.add_argument("--profile", action="store_true")parser.add_argument("--profile-dir", default="profiles")args = parser.parse_args()device = torch.device(args.device)try:import dglfrom gnn4colliders.models.root_gnn import EdgeNetworkexcept ImportError:report("training",{**metadata(device), "status": "skipped: install root-gnn extra"},)returntorch.manual_seed(args.seed)graph = dgl.graph((torch.tensor([0, 1]), torch.tensor([1, 0])), num_nodes=2).to(device)graph.ndata["features"] = torch.randn(2, 7, device=device)graph.edata["features"] = torch.randn(2, 3, device=device)model = EdgeNetwork(graph, None, hid_size=16, out_size=2, n_layers=1, n_proc_steps=1).to(device)optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)def step() -> None:optimizer.zero_grad(set_to_none=True)loss = model(graph).square().mean()loss.backward()optimizer.step()12 unmodified lines{**metadata(device),**result,"steps_per_second": 1000 / result["mean_ms"],"peak_memory_mb": torch.cuda.max_memory_allocated(device) / 2**20if device.type == "cuda"12342 unmodified lines789101112131415161718192021222324252627282930313233343536373839404142434412 unmodified lines5758596061626364"""Measure ROOT-GNN training steps and optionally emit a profiler trace."""from __future__ import annotations2 unmodified linesimport torchtry:from ._common import common_parser, measure, metadata, report, synthetic_eventsexcept ImportError:from _common import common_parser, measure, metadata, report, synthetic_eventsfrom gnn4colliders.graphs import collate_graph_batchfrom gnn4colliders.models.root_gnn import EdgeNetworkdef main() -> None:parser = common_parser(__doc__)parser.add_argument("--batch-size", type=int, default=1024)parser.add_argument("--hid-size", type=int, default=128)parser.add_argument("--profile", action="store_true")parser.add_argument("--profile-dir", default="profiles")args = parser.parse_args()device = torch.device(args.device)torch.manual_seed(args.seed)events = synthetic_events(args.batch_size, seed=args.seed)batch = collate_graph_batch(events, torch.arange(len(events))).to(device)model = EdgeNetwork(batch.graph,None,hid_size=args.hid_size,out_size=1,n_layers=2,n_proc_steps=4,).to(device)optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)def step() -> None:optimizer.zero_grad(set_to_none=True)loss = model(batch.graph).square().mean()loss.backward()optimizer.step()12 unmodified lines{**metadata(device),**result,"batch_size": args.batch_size,"edges": int(batch.graph.edge_features.shape[0]),"steps_per_second": 1000 / result["mean_ms"],"peak_memory_mb": torch.cuda.max_memory_allocated(device) / 2**20if device.type == "cuda"
23 unmodified lines24252627282930313233342 unmodified lines3738394041424353 unmodified lines97989910010110210310423 unmodified linesThe normal development environment is:```bashuv sync --dev --extra root-gnn```Use the `root-gnn` extra for DGL-backed tests and ROOT-GNN workflows. ONNXchecks additionally need the `onnx` extra.For the shortest end-to-end check, use the repository's temporary ROOTfixture:2 unmodified linesuv run python scripts/dev/smoke_end_to_end.py```This creates a temporary ROOT file, prepares a graph cache, trains one CPUepoch, evaluates, predicts, and removes its temporary files.## Public data and configurations53 unmodified linesuv run ruff format --check .```The strict parity command must fail when DGL is unavailable; do not replace itwith a command that permits parity tests to skip. A CUDA-only skip is expectedon CPU hosts and must be reported.## Change discipline23 unmodified lines2425262728293031323334352 unmodified lines3839404142434453 unmodified lines989910010110210310410510623 unmodified linesThe normal development environment is:```bashuv sync --dev```All model families run on plain PyTorch; there is no model-framework extra.ONNX checks additionally need the `onnx` extra. Run `git lfs pull` before theparity gate.For the shortest end-to-end check, use the repository's temporary ROOTfixture:2 unmodified linesuv run python scripts/dev/smoke_end_to_end.py```This creates a temporary ROOT file, prepares an event cache, trains one CPUepoch, evaluates, predicts, and removes its temporary files.## Public data and configurations53 unmodified linesuv run ruff format --check .```The strict parity command must fail when frozen parity artifacts are missingor are unfetched Git LFS pointers; do not replace it with a command thatpermits parity tests to skip. A CUDA-only skip is expectedon CPU hosts and must be reported.## Change discipline
5 unmodified lines678910111213141516171819202122232425262728299 unmodified lines3940414243444546474849505152535455565758596013 unmodified lines747576777879805 unmodified lines```textROOT/Awkward↓EventSample + EventMetadata↓shared features and representation adapters├── GraphSample -> GraphSampleCache -> GraphBatch└── SequenceSample -> transformer/token models↓model family↓Task -> Trainer/Predictor -> named outputs```| Layer | Responsibility ||---|---|| `data` | ROOT/Awkward ingestion, metadata, datasets, folds, batching, and caches || `features` | Collider-object features and derived physics quantities || `graphs` | Topology, edge construction, graph-specific adapters, and graph-cache preparation || `models` | Architecture-specific neural networks || `tasks` | Labels, weights, losses, scores, predictions, and metrics || `training` | Optimizers, lifecycle, reproducibility, checkpointing, and distributed utilities || `inference` | Ordered prediction, evaluation, and named output writing |9 unmodified lines## Data and representation boundaries`EventSample` and named `EventMetadata(fold, weight, sample_id, extra)` arerepresentation-independent. `GraphSample` and `GraphBatch` are the currentgraph representation boundary. `TensorGraph` provides a native tensor pathfor ROOT-GNN execution on CPU, CUDA, and MPS; DGL remains an optional graphadapter and cache dependency.`SequenceSample` and `SequenceBatch` are the topology-free representationboundary for transformer experiments. `TransformerClassifier` consumes paddedobject-token sequences and returns raw logits while reusing shared task,training, checkpoint, and inference interfaces.The active collider node schema has seven columns:`[pt, eta, phi, energy, btag, charge, node_type]`. Graph edges are directed,source-major, fully connected without self-loops except for the one-nodecase, and carry `[deta, dphi, dR]` features. These are compatibility contractscaptured by deterministic tests and the frozen `root-gnn-parity-baseline`reference fixture.## Configuration and lifecycle13 unmodified linesboundary and model implementation, for example:```textdata.EventSample -> features -> SequenceSample -> models.root_transformer```It should include a deterministic fixture, unit tests for the representation,5 unmodified lines67891011121314151617181920212223242526279 unmodified lines37383940414243444546474849505152535455565758596061626313 unmodified lines777879808182835 unmodified lines```textROOT/Awkward↓ vectorized over event chunks (data.preparation, features)EventCache / PackedEvents: per-object features + named per-event metadata↓ EventLoader(collate=...) per batch├── collate_graph_batch -> GraphBatch(TensorGraph) -> models.root_gnn└── collate_sequence_batch -> SequenceBatch (padded) -> models.root_transformer↓Task -> Trainer/Predictor -> named outputs```| Layer | Responsibility ||---|---|| `data` | ROOT/Awkward ingestion, vectorized preparation, packed event cache, metadata, folds, and loaders || `features` | Collider-object features and derived physics quantities || `graphs` | Topology, edge features, `TensorGraph`, and graph batch collation || `sequences` | Token sequences and padded sequence batch collation || `models` | Architecture-specific neural networks in plain PyTorch || `tasks` | Labels, weights, losses, scores, predictions, and metrics || `training` | Optimizers, lifecycle, reproducibility, checkpointing, and distributed utilities || `inference` | Ordered prediction, evaluation, and named output writing |9 unmodified lines## Data and representation boundaries`EventSample` and named `EventMetadata(fold, weight, sample_id, extra)` arerepresentation-independent. Prepared data is stored once as `PackedEvents`(`EventCache` on disk): object features in one flat tensor, event boundariesas offsets, and labels, folds, weights, and sample-identity columns. Nothingin the cache is graph- or model-specific, and it loads with`weights_only=True` and optional memory mapping.A model family supplies only a collate function from `(PackedEvents,indices)` to its batch type. `collate_graph_batch` builds `TensorGraph`batches in the edge-index layout common to PyTorch GNN libraries (flat nodeand edge tensors, `edge_src`/`edge_dst`, per-element graph membership), whichruns on CPU, CUDA, and MPS. `collate_sequence_batch` builds padded`SequenceBatch` token batches with a mask for `TransformerClassifier`. Nograph library is a dependency.The active collider node schema has seven columns:`[pt, eta, phi, energy, btag, charge, node_type]`. Graph edges are directed,source-major, fully connected without self-loops except for the one-nodecase, and carry `[deta, dphi, dR]` features. These are compatibility contractscaptured by deterministic tests, the frozen `root-gnn-parity-baseline`reference fixture, and the frozen DGL outputs in`tests/fixtures/root_gnn_dgl_reference/`.## Configuration and lifecycle13 unmodified linesboundary and model implementation, for example:```textPackedEvents -> collate function (representation) -> models.<family>```It should include a deterministic fixture, unit tests for the representation,
8 unmodified lines910111213141513 unmodified lines293031323334353617 unmodified lines5455565758596061626345 unmodified lines1091101111121131141158 unmodified lines| Group | Purpose || --- | --- || `data` | ROOT source or graph-cache path, batch settings, and fold splits || `model` | Model family and supported ROOT-GNN constructor settings || `task` | Binary or multiclass loss, score, and metric semantics || `trainer` | Device, seed, epochs, optimizer, scheduler, and early stopping |13 unmodified linesseven-column feature contract: one branch/constant specification per outputcolumn and one entry per configured object type. `CALC_E` and `NODE_TYPE` arereserved derived specifications. `object_types` entries are `vector` or`single`. Preparation reads the configured tree in file order and writes aversioned `GraphSampleCache`.Example overrides are easiest to maintain in a YAML file for real datasets:17 unmodified linesweight_var: weight```Then compose it with `data=my_events`. The cache stores processed graphsamples, labels, globals, named metadata, and feature/graph/cache schemaversions. Changing the feature or graph schema requires a new compatible cache;loading a mismatched schema raises an error.## Common overrides45 unmodified lines`data.num_workers` controls local process parallelism during `prepare`. Thedefault is `0` (single-process). Positive values split the ordered event rangeinto independent temporary graph-cache shards and merge them deterministically;workers do not write the final cache concurrently. This setting does not launchdistributed preparation and should be benchmarked on the target machine.8 unmodified lines910111213141513 unmodified lines293031323334353637383940414217 unmodified lines60616263646566676869707145 unmodified lines1171181191201211221238 unmodified lines| Group | Purpose || --- | --- || `data` | ROOT source or event-cache path, batch settings, and fold splits || `model` | Model family and supported ROOT-GNN constructor settings || `task` | Binary or multiclass loss, score, and metric semantics || `trainer` | Device, seed, epochs, optimizer, scheduler, and early stopping |13 unmodified linesseven-column feature contract: one branch/constant specification per outputcolumn and one entry per configured object type. `CALC_E` and `NODE_TYPE` arereserved derived specifications. `object_types` entries are `vector` or`single`. Preparation reads the configured tree in file order, builds featuresvectorized over chunks of events, and writes a versioned `EventCache`: packedper-object features plus named per-event metadata. The cache isrepresentation-neutral; graph topology and edge features (or padded tokensequences) are built at batch time by the selected model family, so one cacheserves every model. `data.cache.path` may also point at a shard directory witha `manifest.json` (see [perlmutter.md](perlmutter.md)); its shards are loadedin order.Example overrides are easiest to maintain in a YAML file for real datasets:17 unmodified linesweight_var: weight```Then compose it with `data=my_events`. The cache stores packed objectfeatures, labels, globals, named metadata, and feature/cache schema versions.It contains only tensors and plain values (loaded with `weights_only=True`).Changing the feature schema requires a new compatible cache; loading amismatched schema, or a cache written before the packed format, raises anerror asking for the cache to be prepared again.## Common overrides45 unmodified lines`data.num_workers` controls local process parallelism during `prepare`. Thedefault is `0` (single-process). Positive values split the ordered event rangeinto independent temporary event-cache parts and merge them deterministically;workers do not write the final cache concurrently. This setting does not launchdistributed preparation and should be benchmarked on the target machine.
6 unmodified lines789101112136 unmodified linesLegacy and rewrite extraction may use separate environments. Each writes theversion-1 artifact described in `validation/README.md`; the comparator neverimports legacy modules or DGL graph objects. Record ROOT file/tree, selection,event count, file size, SHA-256, branches, seeds, versions, device and sourceidentities in the artifact manifest. Do not use an absolute personal path as ascientific event identity.6 unmodified lines789101112136 unmodified linesLegacy and rewrite extraction may use separate environments. Each writes theversion-1 artifact described in `validation/README.md`; the comparator neverimports legacy modules or graph-library objects. Record ROOT file/tree, selection,event count, file size, SHA-256, branches, seeds, versions, device and sourceidentities in the artifact manifest. Do not use an absolute personal path as ascientific event identity.
4 unmodified lines5678910112 unmodified lines141516171819209 unmodified lines303132333435364 unmodified linesmodel. Install the optional dependencies with:```bashuv sync --extra root-gnn --extra onnx```Export a checkpoint with the project CLI:2 unmodified linesuv run gnn4colliders export \export.checkpoint=/path/to/checkpoint.pt \export.output=model.onnx \data.cache.path=/path/to/graph-cache.pt```The exported model accepts six tensor inputs: `node_features`,9 unmodified linesmodels. Empty graphs are invalid; single-node graphs (zero edges) arerepresented and pooled with a zero edge contribution.Direct DGL export was not retained: the active model uses DGL graph mutationand reductions (`apply_edges`, `update_all`, and graph pooling) that are not aportable ONNX contract. The adapter expresses those operations with standardtensor indexing, `index_add`, and per-graph means.4 unmodified lines5678910112 unmodified lines141516171819209 unmodified lines3031323334354 unmodified linesmodel. Install the optional dependencies with:```bashuv sync --extra onnx```Export a checkpoint with the project CLI:2 unmodified linesuv run gnn4colliders export \export.checkpoint=/path/to/checkpoint.pt \export.output=model.onnx \data.cache.path=/path/to/events.pt```The exported model accepts six tensor inputs: `node_features`,9 unmodified linesmodels. Empty graphs are invalid; single-node graphs (zero edges) arerepresented and pooled with a zero edge contribution.The export adapter mirrors `EdgeNetwork` but replaces its `index_add`reductions with dense membership-matrix products, because ONNX scatteroperations do not reliably reduce duplicate indices.
5 unmodified lines678910111225 unmodified lines3839404142434445464748495 unmodified linesactive ROOT-GNN behavior into `src/gnn4colliders.models.root_gnn`. Thecampaign covered full event preprocessing and graph parity, binary objectivesand metrics, deterministic fine-tuning, full-split training, checkpoint reloadand resume, reproducibility, and serialized graph-cache checks.The historical implementation is no longer in the active source tree. Itsobservable behavior is represented by committed fixtures, tests, and the25 unmodified lines5. Add checkpoint, prediction, and reproducibility tests.The first implementation is available as`model=root_transformer/transformer`. It can train on an existing graph cacheby adapting node features into ordered sequence tokens; this is a migrationbridge while a native sequence cache and DDP sequence loader are evaluated.Native sequence-cache storage and distributed sequence loading remain follow-upwork; do not generalize shared interfaces until those use cases require it.## Validation requirements5 unmodified lines678910111225 unmodified lines383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788895 unmodified linesactive ROOT-GNN behavior into `src/gnn4colliders.models.root_gnn`. Thecampaign covered full event preprocessing and graph parity, binary objectivesand metrics, deterministic fine-tuning, full-split training, checkpoint reloadand resume, reproducibility, and serialized cache checks.The historical implementation is no longer in the active source tree. Itsobservable behavior is represented by committed fixtures, tests, and the25 unmodified lines5. Add checkpoint, prediction, and reproducibility tests.The first implementation is available as`model=root_transformer/transformer`. It trains from the shared packed eventcache, which `collate_sequence_batch` pads into token batches. Distributedsequence loading remains follow-up work.## DGL removalDGL was removed as a dependency. The packed `EventCache` replaced the pickledDGL `GraphSampleCache`, graph batches are built per batch as `TensorGraph`(edge-index layout), and the PyTorch implementation is the canonical`EdgeNetwork`. Before removal, the DGL graph builder and model outputs werefrozen on the 64-event fixture (`tests/fixtures/root_gnn_dgl_reference/`):prepared graphs, edge features, metadata, and all forward outputs (includingthe 12-class pretrained checkpoint) are reproduced bit-for-bit; gradientsagree to float32 summation-order tolerance. Single-threaded CPU training wasalso verified bit-identical to the previous main for two epochs, and forwardlogits on 2,048 real ttH events match the DGL-era rewrite exactly.Intentional differences:- caches written before the packed format must be prepared again(`CACHE_SCHEMA_VERSION` 2); old shard directories are not reused;- `model.backend` is no longer a choice; `dgl` is rejected with an error;- the DGL model's optional per-node pooling weights (`ndata["w"]`) were notcarried over; no pipeline in the package ever produced them;- the unused `CacheMetadata.preprocessing` fingerprint was dropped with thegraph cache;- the `root-gnn` install extra no longer exists.Validation completed on 2026-10-19:- `GNN4COLLIDERS_REQUIRE_ROOT_GNN=1 uv run --offline pytest -q`: 155 passed,2 skipped (MPS unavailable), including frozen DGL forward/gradient andprepared-feature references, ONNX, CUDA, and two-rank CPU CLI training.- `uv run --offline python -m validation.run_public_validation --no-download`:PASS against the public fixture's golden scientific outputs.- `uv run --offline python scripts/dev/smoke_end_to_end.py`: passed preparation,pretraining, fine-tuning, evaluation, and prediction. AUC is undefined forthis tiny smoke fixture's single-class evaluation split.- Ruff lint and formatting checks, source/wheel builds, and Twine metadatachecks passed.Signed NLO weights can cancel in small batches under the preserved legacyweighted-loss normalization. The DDP CLI regression uses`task.absolute_weights=true`, as does the ttH CP task; loss semantics havenot been changed. Transformer DDP remains unsupported, and MPS requiresvalidation on Apple hardware.## Validation requirements
11 unmodified lines121314151617181920212223242511 unmodified linesTraining already uses `zero_grad(set_to_none=True)` and inference already uses`torch.inference_mode()` with detached CPU accumulation.Mixed precision, `torch.compile`, custom kernels, aggressive worker defaults,and cache-format replacement were not retained without target-machinemeasurements. The main known bottleneck is the quadratic graph workload`N * (N - 1)` and associated DGL message passing; size-aware batching andstreaming prediction remain follow-up work because they affect ordering oroutput semantics.## Graph preparation benchmark and parallelismBenchmark the complete ROOT-to-cache path on a deterministic temporary sample:11 unmodified lines12131415161718192021222324252627282930313233343536373839404142434445464748495051525354555611 unmodified linesTraining already uses `zero_grad(set_to_none=True)` and inference already uses`torch.inference_mode()` with detached CPU accumulation.## Packed events and batchingPreparation writes packed per-object features (`EventCache`) instead of onepickled graph per event; graph topology and edge features are built per batchwith vectorized tensor operations, and transformer batches pad the same rows.Measured on 200,000 real ttH events (7.4 objects/event, A100 node, 8 CPUthreads) against the previous DGL graph cache:| Stage | Before (DGL graph cache) | Packed events || --- | ---: | ---: || Preparation, single core | 3,763 us/event | 19.8 us/event || Cache size | 3,658 bytes/event | 252 bytes/event || Cache load | 312 us/event | 0.16 us/event || 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 threadsPyTorch sizes its CPU thread pool to every core it can see. On a 128-core nodethat made batch construction about 5x slower than with 8 threads, and it makesmultithreaded CPU reductions non-reproducible between runs. Set`OMP_NUM_THREADS` (the Slurm wrappers use `SLURM_CPUS_PER_TASK`) to match theallocation. Single-threaded CPU training is bitwise reproducible.## Known float32 artifactsTwo historical feature values depend on PyTorch CPU kernels rather than on thephysics: `CALC_E` energies use `torch.cosh`, whose SIMD and scalar paths candiffer by 1-2 ULP, so energies are evaluated per event exactly as before; andthe CPU `torch.sqrt` used for `dR` is not correctly rounded (CUDA's is). Bothare preserved for bit-exact parity and are candidates for a deliberate,versioned feature change (for example float64 evaluation).## Preparation benchmark and parallelismBenchmark the complete ROOT-to-cache path on a deterministic temporary sample:
8 unmodified lines91011121314153 unmodified lines19202122232425262728293031324 unmodified lines373839404142434 unmodified lines484950515253545556575859606162638 unmodified lines```bashuv run gnn4colliders train \data.cache.path=/path/to/graphs.pt \environment=perlmutter \trainer.device=cuda \trainer.max_epochs=103 unmodified lines```bashsbatch scripts/slurm/train_single_gpu.sh \data.cache.path=/path/to/graphs.pt trainer.max_epochs=10```## Single-node DDP```bashGPUS_PER_NODE=4 sbatch scripts/slurm/train_multi_gpu.sh \data.cache.path=/path/to/graphs.pt trainer.max_epochs=10```The wrapper uses `torchrun`; `batch_size` and `num_workers` are per GPU.4 unmodified lines```bashGPUS_PER_NODE=4 sbatch scripts/slurm/train_multi_node.sh \data.cache.path=/path/to/graphs.pt trainer.max_epochs=10```Use the provided script as a template and adapt only allocation/account4 unmodified lines## Checks and common failures```bashuv run python -c "import torch, dgl; print(torch.__version__, dgl.__version__, torch.cuda.is_available())"uv run gnn4colliders --help```An unavailable DGL wheel, incompatible driver, missing cache, or mismatchedcache schema should be fixed in the environment/input rather than hidden withpackage-level path changes. GPU kernels and distributed execution are notpromised bitwise deterministic.## Large ROOT graph preparationLarge samples should be prepared as persistent shards. Each Slurm array taskreads one contiguous global event range and writes one `shard-NNNNN.pt` file;8 unmodified lines91011121314153 unmodified lines19202122232425262728293031324 unmodified lines373839404142434 unmodified lines48495051525354555657585960616263648 unmodified lines```bashuv run gnn4colliders train \data.cache.path=/path/to/events.pt \environment=perlmutter \trainer.device=cuda \trainer.max_epochs=103 unmodified lines```bashsbatch scripts/slurm/train_single_gpu.sh \data.cache.path=/path/to/events.pt trainer.max_epochs=10```## Single-node DDP```bashGPUS_PER_NODE=4 sbatch scripts/slurm/train_multi_gpu.sh \data.cache.path=/path/to/events.pt trainer.max_epochs=10```The wrapper uses `torchrun`; `batch_size` and `num_workers` are per GPU.4 unmodified lines```bashGPUS_PER_NODE=4 sbatch scripts/slurm/train_multi_node.sh \data.cache.path=/path/to/events.pt trainer.max_epochs=10```Use the provided script as a template and adapt only allocation/account4 unmodified lines## Checks and common failures```bashuv run python -c "import torch; print(torch.__version__, torch.cuda.is_available(), torch.get_num_threads())"uv run gnn4colliders --help```An incompatible driver, missing cache, or mismatched cache schema should befixed in the environment/input rather than hidden with package-level pathchanges. The Slurm wrappers set `OMP_NUM_THREADS` from the allocation; set ityourself in interactive sessions (see [performance.md](performance.md)). GPU kernels and distributed execution are notpromised bitwise deterministic.## Large ROOT preparationLarge samples should be prepared as persistent shards. Each Slurm array taskreads one contiguous global event range and writes one `shard-NNNNN.pt` file;
6 unmodified lines789101112131 unmodified line1516171819202122232425107 unmodified lines1331341351361371381391403 unmodified lines14414514614714814915015113 unmodified lines1651661671681691701711726 unmodified linesfuture representations as well.```textROOT -> EventSample -> features -> GraphSampleCache -> ROOT-GNN -> logits```## Install1 unmodified lineThe supported environment is Python 3.12. From the repository root:```bashuv sync --dev --extra root-gnn```The `root-gnn` extra is required for DGL-backed graph workflows and ROOT-GNNparity tests. Add `--extra onnx` when using export validation.## Run a local end-to-end smoke test107 unmodified lines`checkpoint.pretrained` starts a new task from model weights and creates a newhead and optimizer. Evaluation uses the held-out test split by default.The first transformer model reuses node features as ordered tokens and thesame task/trainer lifecycle. It can be trained from an existing prepared cache:```bashuv run gnn4colliders train \3 unmodified linesmodel.hid_size=64 model.n_heads=4```This bridge intentionally ignores graph edges. Native sequence-cache storageand distributed sequence loading are follow-up work.## Validate changes13 unmodified linesuv run python -m validation.run_public_validation --no-download```The parity gate requires DGL and compares the new implementation againstcommitted frozen reference fixtures. Historical runtime code is not importedfrom main; compatibility adapters are reserved for old checkpoint, metadata,and output boundaries.6 unmodified lines789101112131 unmodified line1516171819202122232425107 unmodified lines1331341351361371381391403 unmodified lines14414514614714814915015113 unmodified lines1651661671681691701711721736 unmodified linesfuture representations as well.```textROOT -> features -> EventCache (packed objects) -> graph or sequence batch -> model -> logits```## Install1 unmodified lineThe supported environment is Python 3.12. From the repository root:```bashuv sync --dev```Everything, including ROOT-GNN, runs on plain PyTorch (CPU, CUDA, or AppleMPS). Add `--extra onnx` when using export validation.## Run a local end-to-end smoke test107 unmodified lines`checkpoint.pretrained` starts a new task from model weights and creates a newhead and optimizer. Evaluation uses the held-out test split by default.The first transformer model uses the same prepared objects as ordered tokensand the same task/trainer lifecycle. It trains from the same prepared cache:```bashuv run gnn4colliders train \3 unmodified linesmodel.hid_size=64 model.n_heads=4```Sequence batches are padded with a token mask; graph topology is neverbuilt for this model. Distributed sequence loading is follow-up work.## Validate changes13 unmodified linesuv run python -m validation.run_public_validation --no-download```The parity gate compares the implementation against committed frozenreference fixtures (including outputs recorded from the historical DGL model)and fails if those Git LFS artifacts are not present. Historical runtime code is not importedfrom main; compatibility adapters are reserved for old checkpoint, metadata,and output boundaries.
6 unmodified lines78910111213142 unmodified lines171819202122236 unmodified linesBefore a release:1. Update `__version__`, `CHANGELOG.md`, and this release checklist.2. Run `uv sync --dev` (and `--extra root-gnn` when ROOT-GNN validation isavailable), then run lint and tests.3. Run `bash scripts/dev/check_release.sh` to build and inspect the sdist andwheel and smoke-test a wheel installation outside the checkout.4. Review the generated artifacts and `git diff`, then create a version tag2 unmodified linesThe release-validation script never publishes artifacts. Publishing, ifadopted later, must use repository-managed credentials or trusted publishing.The direct DGL wheel source is retained in `pyproject.toml` because thevalidated ROOT-GNN environment requires the CUDA 12.1 DGL wheel. Core importsdo not import DGL or ONNX; install the corresponding extras for thoseworkflows.6 unmodified lines78910111213142 unmodified lines17181920216 unmodified linesBefore a release:1. Update `__version__`, `CHANGELOG.md`, and this release checklist.2. Run `uv sync --dev` and `git lfs pull`, then run lint and`GNN4COLLIDERS_REQUIRE_ROOT_GNN=1 uv run pytest`.3. Run `bash scripts/dev/check_release.sh` to build and inspect the sdist andwheel and smoke-test a wheel installation outside the checkout.4. Review the generated artifacts and `git diff`, then create a version tag2 unmodified linesThe release-validation script never publishes artifacts. Publishing, ifadopted later, must use repository-managed credentials or trusted publishing.The CUDA 12.1 PyTorch wheel index is configured in `pyproject.toml` for Linuxx86_64. Core imports do not import ONNX; install the `onnx` extra for export.
8 unmodified lines91011121314153 unmodified lines1920212223242526272829308 unmodified lines# Full CPU suite, including integration and parity testsuv run pytest# Required ROOT-GNN parity gate (must fail if DGL is unavailable)GNN4COLLIDERS_REQUIRE_ROOT_GNN=1 uv run pytest# Optional layers3 unmodified linesGNN4COLLIDERS_ROOT_FIXTURE=/path/to/reduced.root uv run pytest -m real_data -v```On Apple Silicon macOS, `uv sync --dev --extra root-gnn` supports CPUROOT-GNN unit and integration testing. CUDA and the required ROOT-GNN paritygate are validated on Linux x86_64 with the `root-gnn` extra installed.Unit tests use deterministic, small tensors and generated ROOT files. DGL,ONNX, CUDA, distributed execution, and reduced real-data fixtures remainoptional layers. Tests should assert public contracts and scientificinvariants rather than private call sequences. New regression tests shoulduse `tmp_path`, explicit seeds, and justified numerical tolerances.8 unmodified lines91011121314153 unmodified lines1920212223242526272829308 unmodified lines# Full CPU suite, including integration and parity testsuv run pytest# Required ROOT-GNN parity gate (fails if frozen LFS artifacts are absent)GNN4COLLIDERS_REQUIRE_ROOT_GNN=1 uv run pytest# Optional layers3 unmodified linesGNN4COLLIDERS_ROOT_FIXTURE=/path/to/reduced.root uv run pytest -m real_data -v````uv sync --dev` supports the complete suite on Linux and macOS; there is noseparate model-framework extra. Fetch Git LFS files (`git lfs pull`) beforerunning the parity gate.Unit tests use deterministic, small tensors and generated ROOT files. ONNX,CUDA, MPS, distributed execution, and reduced real-data fixtures remainoptional layers. Tests should assert public contracts and scientificinvariants rather than private call sequences. New regression tests shoulduse `tmp_path`, explicit seeds, and justified numerical tolerances.
4 unmodified lines5678910117 unmodified lines19202122232425262728293026 unmodified lines575859606162636465666768697071727374757677784 unmodified lines[project]name = "gnn4colliders"dynamic = ["version"]description = "Graph neural network tools for collider event analysis."readme = "README.md"requires-python = ">=3.12,<3.13"dependencies = [7 unmodified lines][project.optional-dependencies]root-gnn = ["dgl==2.4.0+cu121; sys_platform == 'linux' and platform_machine == 'x86_64'","dgl==2.2.0; sys_platform == 'darwin' and platform_machine == 'arm64'","pydantic>=2,<3; sys_platform == 'darwin' and platform_machine == 'arm64'","torchdata>=0.7,<0.8; sys_platform == 'darwin' and platform_machine == 'arm64'",]onnx = ["onnx>=1.16,<2","onnxruntime>=1.18,<2",26 unmodified linestorch = [{ index = "pytorch-cu121", marker = "sys_platform == 'linux' and platform_machine == 'x86_64'" },]dgl = [{ index = "dgl", 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.uv.index]]name = "dgl"url = "https://data.dgl.ai/wheels/torch-2.2/cu121/repo.html"format = "flat"explicit = true[tool.pytest.ini_options]testpaths = ["tests"]addopts = "-ra"4 unmodified lines5678910117 unmodified lines19202122232426 unmodified lines5152535455565758596061624 unmodified lines[project]name = "gnn4colliders"dynamic = ["version"]description = "Machine-learning tools for collider event analysis."readme = "README.md"requires-python = ">=3.12,<3.13"dependencies = [7 unmodified lines][project.optional-dependencies]onnx = ["onnx>=1.16,<2","onnxruntime>=1.18,<2",26 unmodified linestorch = [{ 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]testpaths = ["tests"]addopts = "-ra"
66 unmodified lines676869707172737475767778798081828366 unmodified linesdef main() -> None:try:import dgl # noqa: F401except ImportError as error: # pragma: no cover - environment-dependentraise SystemExit("install the root-gnn extra before running this smoke test") from errorwith tempfile.TemporaryDirectory(prefix="gnn4colliders-smoke-") as directory:root = Path(directory)root_file = root / "events.root"cache = root / "graphs.pt"target_cache = root / "target.pt"_write_root(root_file)_prepare(root_file, cache)66 unmodified lines6768697071727374757666 unmodified linesdef main() -> None:with tempfile.TemporaryDirectory(prefix="gnn4colliders-smoke-") as directory:root = Path(directory)root_file = root / "events.root"cache = root / "events.pt"target_cache = root / "target.pt"_write_root(root_file)_prepare(root_file, cache)
6 unmodified lines789106 unmodified linesset -euo pipefailcd "${SLURM_SUBMIT_DIR:-$(pwd)}"uv run gnn4colliders evaluate "$@"6 unmodified lines789101112136 unmodified linesset -euo pipefailcd "${SLURM_SUBMIT_DIR:-$(pwd)}"# PyTorch otherwise sizes CPU thread pools to every core on the node, which# slows batch construction several-fold; match the Slurm allocation.export OMP_NUM_THREADS="${OMP_NUM_THREADS:-${SLURM_CPUS_PER_TASK:-8}}"uv run gnn4colliders evaluate "$@"
123459 unmodified lines15161718192021#!/bin/bash# Prepare one independent graph-cache shard for the ttH CP benchmark.# Submit with: sbatch --array=0-255%32 scripts/slurm/prepare_tth_cp_even_odd.sh# Override SHARD_DIR, SHARD_COUNT, and CONFIG when needed.#SBATCH -N 19 unmodified lines: "${SLURM_ARRAY_TASK_ID:?submit this script as a Slurm array}"SHARD_COUNT="${SHARD_COUNT:-256}"SHARD_DIR="${SHARD_DIR:-outputs/ttH_cp_even_odd/shards}"CONFIG="${CONFIG:-config_tth_cp_even_odd}"# Prevent native math libraries from multiplying the Slurm CPU allocation.123459 unmodified lines15161718192021#!/bin/bash# Prepare one independent event-cache shard for the ttH CP benchmark.# Submit with: sbatch --array=0-255%32 scripts/slurm/prepare_tth_cp_even_odd.sh# Override SHARD_DIR, SHARD_COUNT, and CONFIG when needed.#SBATCH -N 19 unmodified lines: "${SLURM_ARRAY_TASK_ID:?submit this script as a Slurm array}"SHARD_COUNT="${SHARD_COUNT:-256}"SHARD_DIR="${SHARD_DIR:-outputs/ttH_cp_even_odd/event_shards}"CONFIG="${CONFIG:-config_tth_cp_even_odd}"# Prevent native math libraries from multiplying the Slurm CPU allocation.
6 unmodified lines78910116 unmodified linesset -euo pipefailcd "${SLURM_SUBMIT_DIR:-$(pwd)}"GPUS_PER_NODE="${GPUS_PER_NODE:-4}"uv run torchrun --standalone --nproc_per_node="${GPUS_PER_NODE}" -m gnn4colliders.cli train "$@" distributed=ddp environment=perlmutter6 unmodified lines78910111213146 unmodified linesset -euo pipefailcd "${SLURM_SUBMIT_DIR:-$(pwd)}"# PyTorch otherwise sizes CPU thread pools to every core on the node, which# slows batch construction several-fold; match the Slurm allocation.export OMP_NUM_THREADS="${OMP_NUM_THREADS:-${SLURM_CPUS_PER_TASK:-8}}"GPUS_PER_NODE="${GPUS_PER_NODE:-4}"uv run torchrun --standalone --nproc_per_node="${GPUS_PER_NODE}" -m gnn4colliders.cli train "$@" distributed=ddp environment=perlmutter
7 unmodified lines89101112137 unmodified linesset -euo pipefailcd "${SLURM_SUBMIT_DIR:-$(pwd)}"GPUS_PER_NODE="${GPUS_PER_NODE:-4}"MASTER_ADDR="$(scontrol show hostnames "$SLURM_JOB_NODELIST" | head -n 1)"MASTER_PORT="${MASTER_PORT:-29500}"7 unmodified lines89101112131415167 unmodified linesset -euo pipefailcd "${SLURM_SUBMIT_DIR:-$(pwd)}"# PyTorch otherwise sizes CPU thread pools to every core on the node, which# slows batch construction several-fold; match the Slurm allocation.export OMP_NUM_THREADS="${OMP_NUM_THREADS:-${SLURM_CPUS_PER_TASK:-8}}"GPUS_PER_NODE="${GPUS_PER_NODE:-4}"MASTER_ADDR="$(scontrol show hostnames "$SLURM_JOB_NODELIST" | head -n 1)"MASTER_PORT="${MASTER_PORT:-29500}"
6 unmodified lines789106 unmodified linesset -euo pipefailcd "${SLURM_SUBMIT_DIR:-$(pwd)}"uv run gnn4colliders train "$@" environment.device=cuda6 unmodified lines789101112136 unmodified linesset -euo pipefailcd "${SLURM_SUBMIT_DIR:-$(pwd)}"# PyTorch otherwise sizes CPU thread pools to every core on the node, which# slows batch construction several-fold; match the Slurm allocation.export OMP_NUM_THREADS="${OMP_NUM_THREADS:-${SLURM_CPUS_PER_TASK:-8}}"uv run gnn4colliders train "$@" environment.device=cuda
156 unmodified lines157158159160161162163164165166156 unmodified linesshard_count=shard_count,output_dir=output_dir,)print(f"prepared graph shard: {shard}")elif command == "train":if _is_main_process():print(f"saved checkpoint: {train(config)}")elif command == "export":if _is_main_process():print(f"wrote ONNX model: {export_onnx(config)}")156 unmodified lines157158159160161162163164165166167168156 unmodified linesshard_count=shard_count,output_dir=output_dir,)print(f"prepared event shard: {shard}")elif command == "train":# Every rank must train: DDP collectives need all processes.checkpoint = train(config)if _is_main_process():print(f"saved checkpoint: {checkpoint}")elif command == "export":if _is_main_process():print(f"wrote ONNX model: {export_onnx(config)}")
8 unmodified lines910111213141516171819201 unmodified line2223242526272829303132333435363715 unmodified lines53545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191209 unmodified lines1301311321331341351363 unmodified lines1401411421431441451461474 unmodified lines1521531541551561571581591601611621631648 unmodified linesfrom omegaconf import DictConfig, OmegaConffrom gnn4colliders.data import (DistributedGraphDataLoader,GraphDataLoader,GraphDataset,GraphSampleCache,SplitDefinition,select_split,)from gnn4colliders.distributed import (DistributedContext,1 unmodified linefinalize,initialize,)from gnn4colliders.graphs.preparation import (prepare_graph_cache,prepare_graph_shard,write_graph_shard_manifest,)from gnn4colliders.inference import Predictor, write_npzfrom gnn4colliders.sequences import (SequenceDataLoader,sequence_samples_from_graph_samples,)from gnn4colliders.training import (CheckpointManager,restore_training_state,15 unmodified linesreturn targetdef load_samples(config: DictConfig) -> GraphDataset:data = config.datacache_path = data.cache.pathif not cache_path:raise ValueError("data.cache.path is required for train/evaluate/predict")cache = GraphSampleCache(cache_path)if not cache.exists():raise FileNotFoundError(f"graph sample cache does not exist: {cache_path}")return GraphDataset(cache.load())def loaders(config: DictConfig, context: DistributedContext | None = None) -> dict[str, Any]:samples = load_samples(config)split = SplitDefinition(train_folds=frozenset(config.data.splits.train_folds),validation_folds=frozenset(config.data.splits.validation_folds),test_folds=frozenset(config.data.splits.test_folds),)if str(config.model.get("family", "root_gnn")).lower() == "root_transformer":if context is not None and context.enabled:raise ValueError("root_transformer sequence loading does not yet support DDP")sequence_samples = sequence_samples_from_graph_samples(samples.samples)result = {}for name in ("train", "validation", "test"):selected = select_split(sequence_samples, split, name)result[name] = SequenceDataLoader(selected,int(config.data.batch_size),shuffle=bool(config.data.shuffle) if name == "train" else False,seed=int(config.data.seed),)return resulttensor_graphs = str(config.model.get("backend", "torch")).lower() == "torch"result = {}for name in ("train", "validation", "test"):selected = GraphDataset(select_split(samples.samples, split, name))loader_type = (DistributedGraphDataLoaderif context is not None and context.enabledelse GraphDataLoader)result[name] = (loader_type(selected,int(config.data.batch_size),context,shuffle=bool(config.data.shuffle) if name == "train" else False,seed=int(config.data.seed),tensor_graphs=tensor_graphs,)if loader_type is DistributedGraphDataLoaderelse loader_type(selected,int(config.data.batch_size),shuffle=bool(config.data.shuffle) if name == "train" else False,seed=int(config.data.seed),tensor_graphs=tensor_graphs,))return result9 unmodified lines"prepare does not support distributed launch; use data.num_workers ""for local process parallelism",)return prepare_graph_cache(plain(config.data))def prepare_shard(3 unmodified linesshard_count: int,output_dir: str | Path,) -> Path:"""Prepare one restartable graph-cache shard; see ``prepare_graph_shard``."""return prepare_graph_shard(plain(config.data),shard_index=shard_index,shard_count=shard_count,4 unmodified linesdef write_shard_manifest(config: DictConfig, *, shard_count: int, output_dir: str | Path) -> Path:"""Describe a shard set; see ``write_graph_shard_manifest``."""return write_graph_shard_manifest(plain(config.data), shard_count=shard_count, output_dir=output_dir)def _model_and_task(config: DictConfig, loader: GraphDataLoader):first = next(iter(loader), None)if first is None:raise ValueError("selected data split is empty")8 unmodified lines91011121314151617181920212223241 unmodified line26272829303132333415 unmodified lines5051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979 unmodified lines1071081091101111121133 unmodified lines1171181191201211221231244 unmodified lines1291301311321331341351361371381391401418 unmodified linesfrom omegaconf import DictConfig, OmegaConffrom gnn4colliders.data import (DistributedEventLoader,EventCache,EventLoader,PackedEvents,SplitDefinition,)from gnn4colliders.data.preparation import (prepare_event_cache,prepare_event_shard,write_event_shard_manifest,)from gnn4colliders.distributed import (DistributedContext,1 unmodified linefinalize,initialize,)from gnn4colliders.graphs import collate_graph_batchfrom gnn4colliders.inference import Predictor, write_npzfrom gnn4colliders.sequences import collate_sequence_batchfrom gnn4colliders.training import (CheckpointManager,restore_training_state,15 unmodified linesreturn targetdef load_events(config: DictConfig) -> PackedEvents:cache_path = config.data.cache.pathif not cache_path:raise ValueError("data.cache.path is required for train/evaluate/predict")cache = EventCache(cache_path)if not cache.exists():raise FileNotFoundError(f"event cache does not exist: {cache_path}")return cache.load()def _collate(config: DictConfig):family = str(config.model.get("family", "root_gnn")).lower()return (collate_sequence_batch if family == "root_transformer" else collate_graph_batch)def loaders(config: DictConfig, context: DistributedContext | None = None) -> dict[str, Any]:events = load_events(config)split = SplitDefinition(train_folds=frozenset(config.data.splits.train_folds),validation_folds=frozenset(config.data.splits.validation_folds),test_folds=frozenset(config.data.splits.test_folds),)distributed = context is not None and context.enabledcollate = _collate(config)if distributed and collate is collate_sequence_batch:raise 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] = (DistributedEventLoader(events, collate, batch_size, context, **options)if distributedelse EventLoader(events, collate, batch_size, **options))return result9 unmodified lines"prepare does not support distributed launch; use data.num_workers ""for local process parallelism",)return prepare_event_cache(plain(config.data))def prepare_shard(3 unmodified linesshard_count: int,output_dir: str | Path,) -> Path:"""Prepare one restartable event-cache shard; see ``prepare_event_shard``."""return prepare_event_shard(plain(config.data),shard_index=shard_index,shard_count=shard_count,4 unmodified linesdef write_shard_manifest(config: DictConfig, *, shard_count: int, output_dir: str | Path) -> Path:"""Describe a shard set; see ``write_event_shard_manifest``."""return write_event_shard_manifest(plain(config.data), shard_count=shard_count, output_dir=output_dir)def _model_and_task(config: DictConfig, loader: EventLoader):first = next(iter(loader), None)if first is None:raise ValueError("selected data split is empty")
7 unmodified lines8910111213141516171855 unmodified lines7475767778798081827 unmodified linesimport torchfrom gnn4colliders.distributed import DistributedContextfrom gnn4colliders.models.root_gnn import (EdgeNetwork,FineTunedEdgeNetwork,TensorEdgeNetwork,)from gnn4colliders.models.root_transformer import TransformerClassifierfrom gnn4colliders.tasks import BinaryClassificationTask, MulticlassClassificationTaskfrom gnn4colliders.training import (55 unmodified linesif family != "root_gnn":raise ValueError(f"unsupported model family {family!r}")backend = str(_get(config, "backend", "torch")).lower()if backend not in {"torch", "dgl"}:raise ValueError(f"unsupported root_gnn backend {backend!r}")model_class = TensorEdgeNetwork if backend == "torch" else EdgeNetworkkwargs = {"hid_size": int(_get(config, "hid_size", _get(config, "hidden_dim", 128))),"out_size": int(_get(config, "out_size", 1)),7 unmodified lines89101112131455 unmodified lines7071727374757677787980817 unmodified linesimport torchfrom gnn4colliders.distributed import DistributedContextfrom gnn4colliders.models.root_gnn import EdgeNetwork, FineTunedEdgeNetworkfrom gnn4colliders.models.root_transformer import TransformerClassifierfrom gnn4colliders.tasks import BinaryClassificationTask, MulticlassClassificationTaskfrom gnn4colliders.training import (55 unmodified linesif family != "root_gnn":raise ValueError(f"unsupported model family {family!r}")backend = str(_get(config, "backend", "torch")).lower()if backend != "torch":raise ValueError(f"unsupported root_gnn backend {backend!r}; the DGL backend was removed ""and ROOT-GNN always runs on PyTorch tensors")model_class = EdgeNetworkkwargs = {"hid_size": int(_get(config, "hid_size", _get(config, "hidden_dim", 128))),"out_size": int(_get(config, "out_size", 1)),
38 unmodified lines3940414243444538 unmodified linesshuffle: trueseed: 42cache:path: outputs/hf_delphes/graphssplits:train_folds: [1, 2, 3]validation_folds: [0]38 unmodified lines3940414243444538 unmodified linesshuffle: trueseed: 42cache:path: outputs/hf_delphes/events.ptsplits:train_folds: [1, 2, 3]validation_folds: [0]
30 unmodified lines3132333435363730 unmodified linesshuffle: trueseed: 42cache:path: outputs/hf_smoke/graphssplits:train_folds: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,30 unmodified lines3132333435363730 unmodified linesshuffle: trueseed: 42cache:path: outputs/hf_smoke/events.ptsplits:train_folds: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
25 unmodified lines2627282930313225 unmodified linesshuffle: trueseed: 42cache:path: outputs/ttH_cp_even_odd/graphs.ptsplits:train_folds: [0, 1, 2, 3, 4, 5, 6, 7]validation_folds: [8]25 unmodified lines2627282930313225 unmodified linesshuffle: trueseed: 42cache:path: outputs/ttH_cp_even_odd/events.ptsplits:train_folds: [0, 1, 2, 3, 4, 5, 6, 7]validation_folds: [8]
12345family: root_gnnbackend: torchname: edge_networkhid_size: 128out_size: 121234family: root_gnnname: edge_networkhid_size: 128out_size: 12
12345family: root_gnnbackend: torchname: edge_networkhid_size: 128out_size: 11234family: root_gnnname: edge_networkhid_size: 128out_size: 1
12345family: root_gnnbackend: torchname: fine_tuned_edge_networkhid_size: 128out_size: 11234family: root_gnnname: fine_tuned_edge_networkhid_size: 128out_size: 1
12345678910111213141516179 unmodified lines272829303132333435363738394041"""Generic data access and dataset infrastructure."""from .cache import CacheMetadata, GraphSampleCachefrom .dataset import RootEventDatasetfrom .graph_dataset import (DistributedGraphDataLoader,GraphBatch,GraphDataLoader,GraphDataset,GraphSample,TensorGraph,batch_graph_samples,)from .huggingface import resolve_data_filesfrom .metadata import (CACHE_SCHEMA_VERSION,FEATURE_SCHEMA_VERSION,9 unmodified lines"EventSample","EventMetadata","BatchMetadata","GraphSample","TensorGraph","GraphBatch","GraphDataset","GraphDataLoader","DistributedGraphDataLoader","batch_graph_samples","CacheMetadata","GraphSampleCache","SplitDefinition","select_folds","select_split",1234567899 unmodified lines19202122232425262728293031"""Generic data access and dataset infrastructure."""from .dataset import EventChunk, RootEventDatasetfrom .events import EventCache, PackedEvents, concatenate_events, pack_eventsfrom .huggingface import resolve_data_filesfrom .loader import DistributedEventLoader, EventLoaderfrom .metadata import (CACHE_SCHEMA_VERSION,FEATURE_SCHEMA_VERSION,9 unmodified lines"EventSample","EventMetadata","BatchMetadata","EventChunk","PackedEvents","EventCache","concatenate_events","pack_events","EventLoader","DistributedEventLoader","SplitDefinition","select_folds","select_split",
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869"""Versioned cache for processed graph samples."""
from __future__ import annotations
from dataclasses import asdict, dataclass, fieldfrom pathlib import Pathfrom typing import Any
import torch
from .graph_dataset import GraphSamplefrom .metadata import CACHE_SCHEMA_VERSION, FEATURE_SCHEMA_VERSION, GRAPH_SCHEMA_VERSION
@dataclass(frozen=True)class CacheMetadata: feature_schema_version: int = FEATURE_SCHEMA_VERSION graph_schema_version: int = GRAPH_SCHEMA_VERSION cache_schema_version: int = CACHE_SCHEMA_VERSION source: str | None = None preprocessing: dict[str, Any] = field(default_factory=dict)
class GraphSampleCache: """Save/load graph samples with schema metadata checked before use."""
def __init__(self, path: str | Path, metadata: CacheMetadata | None = None) -> None: self.path = Path(path) self.metadata = metadata or CacheMetadata()
def save(self, samples: list[GraphSample] | tuple[GraphSample, ...]) -> None: payload = { "cache_metadata": asdict(self.metadata), "samples": tuple(samples), } self.path.parent.mkdir(parents=True, exist_ok=True) torch.save(payload, self.path)
def load(self) -> tuple[GraphSample, ...]: payload = torch.load(self.path, map_location="cpu", weights_only=False) if not isinstance(payload, dict): raise ValueError("cache payload must be a mapping") actual = payload.get("cache_metadata", {}) if not isinstance(actual, dict): raise ValueError("cache metadata is missing or malformed") expected = asdict(self.metadata) for key in ( "feature_schema_version", "graph_schema_version", "cache_schema_version", ): if actual.get(key) != expected[key]: raise ValueError( f"cache schema mismatch for {key}: " f"found {actual.get(key)!r}, expected {expected[key]!r}" ) if actual.get("preprocessing", {}) != expected["preprocessing"]: raise ValueError("cache preprocessing fingerprint mismatch") if "samples" not in payload: raise ValueError("cache samples are missing") samples = payload["samples"] if not isinstance(samples, (list, tuple)): raise ValueError("cache samples are malformed") if any(not isinstance(sample, GraphSample) for sample in samples): raise ValueError("cache contains invalid graph samples") return tuple(samples)
def exists(self) -> bool: return self.path.is_file()2 unmodified lines34567818 unmodified lines27282930313280 unmodified lines11311411511611711811912012112212312412512612712812913013113213313413513636 unmodified lines1731741751761772 unmodified linesfrom __future__ import annotationsfrom collections.abc import Iterator, Sequencefrom pathlib import Pathfrom typing import Any18 unmodified linesreturn float(array)def _file_labels(label: Any, count: int) -> list[Any]:if isinstance(label, Sequence) and not isinstance(label, (str, bytes)):if len(label) != count:80 unmodified linesself, start: int = 0, stop: int | None = None) -> Iterator[EventSample]:"""Yield events in ``[start, stop)`` while reading each file once."""start = max(0, int(start))stop = len(self) if stop is None else min(len(self), int(stop))if start > stop:raise ValueError("start must not exceed stop")for file_index, path in enumerate(self.files):file_start, file_stop = self._offsets[file_index : file_index + 2]local_start = max(start, file_start) - file_startlocal_stop = min(stop, file_stop) - file_startif local_start >= local_stop:continuearrays = read_tree(path,self.tree_name,self._branches,entry_start=local_start,entry_stop=local_stop,)for offset in range(local_stop - local_start):local_index = local_start + offsetevent = {branch: arrays[branch][offset] for branch in self._branches}metadata_values = np.asarray(36 unmodified lines),)def __iter__(self) -> Iterator[EventSample]:yield from self.iter_range()2 unmodified lines345678918 unmodified lines282930313233343536373839404142434480 unmodified lines12512612712812913013113213313436 unmodified lines1711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072 unmodified linesfrom __future__ import annotationsfrom collections.abc import Iterator, Sequencefrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any18 unmodified linesreturn float(array)@dataclass(frozen=True)class EventChunk:"""Selected branches for local entries ``[entry_start, entry_stop)``."""file_index: intpath: Pathentry_start: intentry_stop: intarrays: Anydef _file_labels(label: Any, count: int) -> list[Any]:if isinstance(label, Sequence) and not isinstance(label, (str, bytes)):if len(label) != count:80 unmodified linesself, start: int = 0, stop: int | None = None) -> Iterator[EventSample]:"""Yield events in ``[start, stop)`` while reading each file once."""for chunk in self.iter_chunks(start, stop):file_index, path, arrays = chunk.file_index, chunk.path, chunk.arraysfile_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(36 unmodified lines),)def iter_chunks(self, start: int = 0, stop: int | None = None, *, step: int | None = None) -> Iterator[EventChunk]:"""Yield the selected branches of ``[start, stop)`` as Awkward arrays.Chunks never span files and hold at most ``step`` events when given."""start = max(0, int(start))stop = len(self) if stop is None else min(len(self), int(stop))if start > stop:raise ValueError("start must not exceed stop")for file_index, path in enumerate(self.files):file_start, file_stop = self._offsets[file_index : file_index + 2]local_start = max(start, file_start) - file_startlocal_stop = min(stop, file_stop) - file_startsize = step or max(1, local_stop - local_start)for chunk_start in range(local_start, local_stop, size):chunk_stop = min(local_stop, chunk_start + size)yield EventChunk(file_index=file_index,path=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,),)def __iter__(self) -> Iterator[EventSample]:yield from self.iter_range()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303"""Representation-neutral packed storage for prepared collider events.
Events are stored column-wise: every object of every event is one row of``object_features`` and ``object_offsets`` delimits the rows of each event.Graph, sequence, or any other representation is derived at batch time, so thesame prepared data serves every model family."""
from __future__ import annotations
import picklefrom collections.abc import Sequencefrom dataclasses import dataclass, fieldsfrom pathlib import Pathfrom typing import Any
import torch
from .metadata import CACHE_SCHEMA_VERSION, FEATURE_SCHEMA_VERSION, BatchMetadatafrom .splits import SplitDefinition
_TENSOR_FIELDS = ( "object_features", "object_offsets", "labels", "fold", "weight", "file_index", "entry_index",)
@dataclass(frozen=True)class PackedEvents: """Prepared events in a flat, memory-mappable tensor layout.
``object_features`` has one row per object and columns named by ``feature_names``; rows of event ``i`` are ``object_offsets[i]:object_offsets[i + 1]``. Per-event metadata is stored as named columns. ``sample_id`` is derived from ``source_files``, ``tree_name``, ``file_index``, and ``entry_index``. """
object_features: torch.Tensor object_offsets: torch.Tensor labels: torch.Tensor global_features: torch.Tensor | None fold: torch.Tensor weight: torch.Tensor file_index: torch.Tensor entry_index: torch.Tensor source_files: tuple[str, ...] tree_name: str feature_names: tuple[str, ...]
def __post_init__(self) -> None: count = int(self.object_offsets.numel()) - 1 if count < 0: raise ValueError("object_offsets must contain at least one entry") if self.object_features.ndim != 2: raise ValueError("object_features must have shape [objects, features]") if int(self.object_offsets[-1]) != self.object_features.shape[0]: raise ValueError("object_offsets do not cover object_features") if self.object_features.shape[1] != len(self.feature_names): raise ValueError("feature_names must name every object feature column") for name in ("labels", "fold", "weight", "file_index", "entry_index"): if getattr(self, name).shape[0] != count: raise ValueError(f"{name} must have one entry per event") if self.global_features is not None and ( self.global_features.ndim != 2 or self.global_features.shape[0] != count ): raise ValueError("global_features must have shape [events, features]")
def __len__(self) -> int: return int(self.object_offsets.numel()) - 1
@property def object_counts(self) -> torch.Tensor: return self.object_offsets.diff()
def sample_ids(self, indices: torch.Tensor) -> tuple[str, ...]: files = self.file_index[indices].tolist() entries = self.entry_index[indices].tolist() return tuple( f"{self.source_files[file]}:{self.tree_name}:{entry}" for file, entry in zip(files, entries) )
def gather_objects( self, indices: torch.Tensor ) -> tuple[torch.Tensor, torch.Tensor]: """Return the object rows and per-event counts of ``indices`` in order.""" starts = self.object_offsets[indices] counts = self.object_offsets[indices + 1] - starts total = int(counts.sum()) first = torch.cumsum(counts, 0) - counts rows = torch.arange(total, dtype=torch.long) + torch.repeat_interleave( starts - first, counts, output_size=total ) return self.object_features[rows], counts
def batch_metadata(self, indices: torch.Tensor) -> BatchMetadata: """Columnar metadata for ``indices`` in the order given.""" sample_ids = self.sample_ids(indices) files = self.file_index[indices].tolist() entries = self.entry_index[indices].tolist() return BatchMetadata( fold=self.fold[indices].to(torch.long), weight=self.weight[indices].to(torch.float32), sample_id=sample_ids, extra={ "entry_index": tuple(entries), "source_file": tuple(self.source_files[file] for file in files), "tree_name": (self.tree_name,) * len(files), }, )
def split_indices(self, split: SplitDefinition, name: str) -> torch.Tensor: """Event indices of one named split, in stored event order.""" try: folds = { "train": split.train_folds, "validation": split.validation_folds, "test": split.test_folds, }[name] except KeyError as error: raise ValueError(f"unknown split {name!r}") from error selected = torch.tensor(sorted(folds), dtype=self.fold.dtype) return torch.nonzero(torch.isin(self.fold, selected)).flatten()
def pack_events( objects: Sequence[torch.Tensor], labels: Sequence[Any] | torch.Tensor, *, weights: Sequence[float] | torch.Tensor | None = None, folds: Sequence[int] | torch.Tensor | None = None, global_features: torch.Tensor | None = None, feature_names: Sequence[str] | None = None, source: str = "memory", tree_name: str = "events",) -> PackedEvents: """Pack in-memory per-event object tensors (``[objects, features]``).
Weights default to one and folds to zero. Sample identifiers are ``f"{source}:{tree_name}:{index}"``. """ if not objects: raise ValueError("at least one event is required") width = int(objects[0].shape[1]) counts = torch.tensor([int(item.shape[0]) for item in objects], dtype=torch.long) count = len(objects) return PackedEvents( object_features=torch.cat([item.to(torch.float32) for item in objects]), object_offsets=torch.cat((torch.zeros(1, dtype=torch.long), counts.cumsum(0))), labels=torch.as_tensor(labels), global_features=global_features, fold=( torch.zeros(count, dtype=torch.long) if folds is None else torch.as_tensor(folds, dtype=torch.long) ), weight=( torch.ones(count) if weights is None else torch.as_tensor(weights, dtype=torch.float32) ), file_index=torch.zeros(count, dtype=torch.long), entry_index=torch.arange(count), source_files=(source,), tree_name=tree_name, feature_names=( tuple(feature_names) if feature_names is not None else tuple(f"feature_{index}" for index in range(width)) ), )
def concatenate_events(parts: Sequence[PackedEvents]) -> PackedEvents: """Concatenate prepared events in the given order.""" if not parts: raise ValueError("at least one part is required") first = parts[0] for part in parts[1:]: if part.feature_names != first.feature_names: raise ValueError("cannot concatenate events with different features") if part.tree_name != first.tree_name: raise ValueError("cannot concatenate events from different trees") if (part.global_features is None) != (first.global_features is None): raise ValueError("global_features must be present in every part or none") files: list[str] = [] file_index: list[torch.Tensor] = [] for part in parts: mapping = [] for name in part.source_files: if name not in files: files.append(name) mapping.append(files.index(name)) file_index.append( torch.tensor(mapping, dtype=torch.long)[part.file_index] if mapping else part.file_index ) offsets = [first.object_offsets] base = first.object_offsets[-1] for part in parts[1:]: offsets.append(part.object_offsets[1:] + base) base = base + part.object_offsets[-1] return PackedEvents( object_features=torch.cat([part.object_features for part in parts]), object_offsets=torch.cat(offsets), labels=torch.cat([part.labels for part in parts]), global_features=( None if first.global_features is None else torch.cat([part.global_features for part in parts]) ), fold=torch.cat([part.fold for part in parts]), weight=torch.cat([part.weight for part in parts]), file_index=torch.cat(file_index), entry_index=torch.cat([part.entry_index for part in parts]), source_files=tuple(files), tree_name=first.tree_name, feature_names=first.feature_names, )
class EventCache: """Save and load :class:`PackedEvents` with schema versions checked.
A cache is either one ``.pt`` file or a directory of shards described by ``manifest.json``; shards are loaded in manifest order and concatenated. Files contain only tensors and plain Python values, so they load with ``weights_only=True`` and can be memory-mapped. """
def __init__(self, path: str | Path) -> None: self.path = Path(path)
def save(self, events: PackedEvents) -> None: payload: dict[str, Any] = { "cache_schema_version": CACHE_SCHEMA_VERSION, "feature_schema_version": FEATURE_SCHEMA_VERSION, } for item in fields(PackedEvents): value = getattr(events, item.name) payload[item.name] = ( value.contiguous() if isinstance(value, torch.Tensor) else value ) payload["source_files"] = list(events.source_files) payload["feature_names"] = list(events.feature_names) self.path.parent.mkdir(parents=True, exist_ok=True) torch.save(payload, self.path)
def exists(self) -> bool: return self.path.is_file() or (self.path / "manifest.json").is_file()
def load(self, *, mmap: bool = False) -> PackedEvents: if self.path.is_dir(): return self._load_shards(mmap=mmap) return _load_file(self.path, mmap=mmap)
def _load_shards(self, *, mmap: bool) -> PackedEvents: import json
manifest = json.loads((self.path / "manifest.json").read_text()) paths = [self.path / shard["path"] for shard in manifest["shards"]] missing = [str(path) for path in paths if not path.is_file()] if missing: raise FileNotFoundError(f"cache shards are missing: {missing[:5]}") return concatenate_events([_load_file(path, mmap=mmap) for path in paths])
def _load_file(path: Path, *, mmap: bool) -> PackedEvents: try: # ``mmap`` requires a string filename in PyTorch 2.2. payload = torch.load( str(path), map_location="cpu", weights_only=True, mmap=mmap ) except (RuntimeError, EOFError, pickle.UnpicklingError) as error: raise ValueError( f"{path} is not a GNN4Colliders event cache (caches written before " "the packed event format must be prepared again)" ) from error if not isinstance(payload, dict): raise ValueError("cache payload must be a mapping") for key, expected in ( ("cache_schema_version", CACHE_SCHEMA_VERSION), ("feature_schema_version", FEATURE_SCHEMA_VERSION), ): if payload.get(key) != expected: raise ValueError( f"cache schema mismatch for {key}: " f"found {payload.get(key)!r}, expected {expected!r}" ) values = {item.name: payload.get(item.name) for item in fields(PackedEvents)} missing = [name for name in _TENSOR_FIELDS if values[name] is None] if missing: raise ValueError(f"cache is missing fields: {missing}") values["source_files"] = tuple(values["source_files"]) values["feature_names"] = tuple(values["feature_names"]) return PackedEvents(**values)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295"""Graph samples and deterministic batching for the ROOT-GNN path."""
from __future__ import annotations
from collections.abc import Iterator, Sequencefrom dataclasses import dataclassfrom typing import Any
import torch
from .metadata import BatchMetadata, EventMetadata
@dataclass(frozen=True)class GraphSample: graph: Any label: torch.Tensor global_features: torch.Tensor | None metadata: EventMetadata
@dataclass(frozen=True)class GraphBatch: graph: Any labels: torch.Tensor global_features: torch.Tensor | None metadata: BatchMetadata
def to(self, device: torch.device | str) -> "GraphBatch": """Return a copy with tensor and graph data placed on ``device``.
Sample identifiers and other Python metadata intentionally remain ordinary CPU-side values. """
graph = self.graph.to(device) if hasattr(self.graph, "to") else self.graph metadata = BatchMetadata( fold=self.metadata.fold.to(device), weight=self.metadata.weight.to(device), sample_id=self.metadata.sample_id, extra=self.metadata.extra, ) return GraphBatch( graph=graph, labels=self.labels.to(device), global_features=( None if self.global_features is None else self.global_features.to(device) ), metadata=metadata, )
@dataclass(frozen=True)class TensorGraph: """Batched graph tensors usable on CPU, CUDA, and Apple's MPS backend."""
node_features: torch.Tensor edge_features: torch.Tensor edge_src: torch.Tensor edge_dst: torch.Tensor node_batch: torch.Tensor edge_batch: torch.Tensor node_counts: torch.Tensor edge_counts: torch.Tensor
def to(self, device: torch.device | str) -> "TensorGraph": return TensorGraph( *( value.to(device) for value in ( self.node_features, self.edge_features, self.edge_src, self.edge_dst, self.node_batch, self.edge_batch, self.node_counts, self.edge_counts, ) ) )
def _tensor_graphs(samples: Sequence[GraphSample]) -> TensorGraph: node_features: list[torch.Tensor] = [] edge_features: list[torch.Tensor] = [] edge_src: list[torch.Tensor] = [] edge_dst: list[torch.Tensor] = [] node_counts: list[int] = [] edge_counts: list[int] = [] offset = 0 for sample in samples: graph = sample.graph if isinstance(graph, TensorGraph): if graph.node_counts.numel() != 1: raise ValueError("each GraphSample must contain one graph") nodes, edges = graph.node_features, graph.edge_features src, dst = graph.edge_src, graph.edge_dst else: try: nodes = graph.ndata["features"] edges = graph.edata["features"] src, dst = graph.edges(order="eid") except AttributeError as error: raise TypeError( "GraphSample graph must be DGL-like or TensorGraph" ) from error node_count, edge_count = int(nodes.shape[0]), int(edges.shape[0]) node_features.append(nodes) edge_features.append(edges) edge_src.append(src.to(dtype=torch.long) + offset) edge_dst.append(dst.to(dtype=torch.long) + offset) node_counts.append(node_count) edge_counts.append(edge_count) offset += node_count node_count_tensor = torch.tensor(node_counts, dtype=torch.long) edge_count_tensor = torch.tensor(edge_counts, dtype=torch.long) return TensorGraph( node_features=torch.cat(node_features), edge_features=torch.cat(edge_features), edge_src=torch.cat(edge_src), edge_dst=torch.cat(edge_dst), node_batch=torch.repeat_interleave( torch.arange(len(samples)), node_count_tensor ), edge_batch=torch.repeat_interleave( torch.arange(len(samples)), edge_count_tensor ), node_counts=node_count_tensor, edge_counts=edge_count_tensor, )
def batch_graph_samples( samples: Sequence[GraphSample], *, tensor_graphs: bool = False) -> GraphBatch: """Batch samples into either DGL or portable tensor graph batches."""
if not samples: raise ValueError("cannot batch an empty sequence") if tensor_graphs: graphs = _tensor_graphs(samples) else: try: import dgl except ImportError as error: # pragma: no cover - optional dependency raise ImportError("DGL batching requires the 'root-gnn' extra") from error graphs = dgl.batch([sample.graph for sample in samples]) labels = torch.stack([torch.as_tensor(sample.label) for sample in samples]) globals_ = [sample.global_features for sample in samples] if any(value is None for value in globals_): if not all(value is None for value in globals_): raise ValueError("global_features must be present for every sample or none") batched_globals = None else: batched_globals = torch.stack( [value for value in globals_ if value is not None] ) return GraphBatch( graph=graphs, labels=labels, global_features=batched_globals, metadata=BatchMetadata.from_events([sample.metadata for sample in samples]), )
class GraphDataLoader: """Deterministic, dependency-light loader over :class:`GraphDataset`.
Shuffling uses a local Torch generator, so constructing or iterating a loader does not mutate process-wide random state. """
def __init__( self, dataset: Sequence[GraphSample], batch_size: int, *, shuffle: bool = False, drop_last: bool = False, seed: int = 12345, tensor_graphs: bool = False, ) -> None: if batch_size < 1: raise ValueError("batch_size must be positive") self.dataset = dataset self.batch_size = batch_size self.shuffle = shuffle self.drop_last = drop_last self.seed = seed self.tensor_graphs = tensor_graphs self.epoch = 0
def set_epoch(self, epoch: int) -> None: self.epoch = epoch
def __len__(self) -> int: count, remainder = divmod(len(self.dataset), self.batch_size) return count if self.drop_last or remainder == 0 else count + 1
def __iter__(self) -> Iterator[GraphBatch]: indices = torch.arange(len(self.dataset), dtype=torch.long) if self.shuffle: generator = torch.Generator() generator.manual_seed(self.seed + self.epoch) indices = indices[torch.randperm(len(indices), generator=generator)] limit = len(indices) - (len(indices) % self.batch_size if self.drop_last else 0) for start in range(0, limit, self.batch_size): selected = [ self.dataset[int(index)] for index in indices[start : start + self.batch_size] ] yield batch_graph_samples(selected, tensor_graphs=self.tensor_graphs)
class DistributedGraphDataLoader(GraphDataLoader): """Shard individual graph samples before batching.
Training sharding pads to equal rank lengths; evaluation sharding does not pad, preventing duplicate events from biasing metrics or predictions. ``batch_size`` is a per-process value. """
def __init__( self, dataset, batch_size, context, *, shuffle=False, drop_last=False, seed=12345, tensor_graphs=False, ): super().__init__( dataset, batch_size, shuffle=shuffle, drop_last=drop_last, seed=seed, tensor_graphs=tensor_graphs, ) from gnn4colliders.distributed import DistributedIndices
self.distributed_indices = DistributedIndices( len(dataset), context, shuffle=shuffle, drop_last=drop_last, seed=seed, pad=shuffle, )
def set_epoch(self, epoch: int) -> None: super().set_epoch(epoch) self.distributed_indices.set_epoch(epoch)
def __len__(self) -> int: count = len(self.distributed_indices.indices()) return ( count // self.batch_size if self.drop_last else (count + self.batch_size - 1) // self.batch_size )
def __iter__(self) -> Iterator[GraphBatch]: indices = self.distributed_indices.indices() limit = len(indices) - (len(indices) % self.batch_size if self.drop_last else 0) for start in range(0, limit, self.batch_size): yield batch_graph_samples( [ self.dataset[index] for index in indices[start : start + self.batch_size] ], tensor_graphs=self.tensor_graphs, )
class GraphDataset(Sequence[GraphSample]): """Small immutable-semantics dataset over already processed graph samples."""
def __init__(self, samples: Sequence[GraphSample]) -> None: self._samples = tuple(samples)
def __len__(self) -> int: return len(self._samples)
def __getitem__(self, index: int) -> GraphSample: return self._samples[index]
@property def samples(self) -> tuple[GraphSample, ...]: return self._samples123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119"""Deterministic, representation-agnostic batch loaders over packed events."""
from __future__ import annotations
from collections.abc import Callable, Iteratorfrom typing import Any
import torch
from .events import PackedEvents
Collate = 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 that selection with a local generator seeded by ``seed + epoch``, so iterating does not mutate process-wide random state. """
def __init__( self, events: PackedEvents, collate: Collate, batch_size: int, *, indices: torch.Tensor | None = None, shuffle: bool = False, drop_last: bool = False, seed: int = 12345, ) -> None: if batch_size < 1: raise ValueError("batch_size must be positive") self.events = events self.collate = collate self.batch_size = batch_size self.indices = ( torch.arange(len(events), dtype=torch.long) if indices is None else indices ) self.shuffle = shuffle self.drop_last = drop_last self.seed = seed self.epoch = 0
def set_epoch(self, epoch: int) -> None: self.epoch = epoch
def _order(self) -> torch.Tensor: if not self.shuffle: return self.indices generator = torch.Generator().manual_seed(self.seed + self.epoch) return self.indices[torch.randperm(len(self.indices), generator=generator)]
def _count(self) -> int: return len(self.indices)
def __len__(self) -> int: count, remainder = divmod(self._count(), self.batch_size) return count if self.drop_last or remainder == 0 else count + 1
def __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): """Shard a selection of events across ranks before batching.
Training sharding pads to equal rank lengths; evaluation sharding does not pad, preventing duplicate events from biasing metrics or predictions. ``batch_size`` is a per-process value. """
def __init__( self, events: PackedEvents, collate: Collate, batch_size: int, context: Any, *, indices: torch.Tensor | None = None, shuffle: bool = False, drop_last: bool = False, seed: int = 12345, ) -> None: super().__init__( events, collate, batch_size, indices=indices, shuffle=shuffle, drop_last=drop_last, seed=seed, ) from gnn4colliders.distributed import DistributedIndices
self.distributed_indices = DistributedIndices( len(self.indices), context, shuffle=shuffle, drop_last=drop_last, seed=seed, pad=shuffle, )
def set_epoch(self, epoch: int) -> None: super().set_epoch(epoch) self.distributed_indices.set_epoch(epoch)
def _order(self) -> torch.Tensor: positions = torch.tensor(self.distributed_indices.indices(), dtype=torch.long) return self.indices[positions]
def _count(self) -> int: return len(self.distributed_indices.indices())9 unmodified lines101112131415169 unmodified linesFEATURE_SCHEMA_VERSION = 1GRAPH_SCHEMA_VERSION = 1CACHE_SCHEMA_VERSION = 1@dataclass(frozen=True)9 unmodified lines101112131415169 unmodified linesFEATURE_SCHEMA_VERSION = 1GRAPH_SCHEMA_VERSION = 1CACHE_SCHEMA_VERSION = 2@dataclass(frozen=True)
12345679 unmodified lines171819202122232425262728293031323334353622 unmodified lines596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810910 unmodified lines1201211221231241256 unmodified lines1321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871883 unmodified lines1921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292301 unmodified line232233234235236237238"""Prepare graph-sample caches from ROOT event sources.Every function takes the resolved ``data`` configuration as a plain mapping sothat it can be shipped to spawned worker processes."""from __future__ import annotations9 unmodified linesfrom pathlib import Pathfrom typing import Anyimport torchfrom gnn4colliders.data import (GraphSample,GraphSampleCache,RootEventDataset,resolve_data_files,)from gnn4colliders.features import build_node_featuresfrom .dgl import build_dgl_graphlogger = logging.getLogger(__name__)def _event_dataset(data: Mapping[str, Any], files: list[Path], labels: list[Any]22 unmodified linesreturn _event_dataset(data, files, labels_per_file), files, labels_per_filedef build_graph_samples(data: Mapping[str, Any],files: list[Path],labels: list[Any],start: int,stop: int,) -> list[GraphSample]:"""Convert the global event range ``[start, stop)`` into graph samples."""feature_branches = data.get("feature_branches")object_types = data.get("object_types")scales = data.get("scales")if feature_branches is None or object_types is None or scales is None:raise ValueError("prepare requires data.feature_branches, object_types, and scales")source = _event_dataset(data, files, labels)samples: list[GraphSample] = []for event in source.iter_range(start, stop):features, _ = build_node_features(event.objects, feature_branches, object_types, scales)graph = build_dgl_graph(features)globals_ = torch.as_tensor(event.global_features, dtype=torch.float32)samples.append(GraphSample(graph,torch.as_tensor(event.label),globals_ if globals_.numel() else None,event.event_metadata,))return samplesdef _build_graph_samples_from_args(args: tuple[Any, ...]) -> list[GraphSample]:data, files, labels, start, stop = argsreturn build_graph_samples(data, files, labels, start, stop)def _write_graph_shard(args: tuple[Any, ...]) -> tuple[Path, int]:data, files, labels, start, stop, path = argssamples = build_graph_samples(data, files, labels, start, stop)shard_path = Path(path)GraphSampleCache(shard_path).save(samples)return shard_path, len(samples)def _worker_count(data: Mapping[str, Any]) -> int:10 unmodified linesreturn [function(item) for item in args]def shard_range(total: int, shard_index: int, shard_count: int) -> tuple[int, int]:"""Return the contiguous ``[start, stop)`` event range of one shard."""if shard_count < 1:6 unmodified lines)def prepare_graph_cache(data: Mapping[str, Any]) -> Path:"""Build the complete graph cache at ``data.cache.path``.With ``data.num_workers > 1`` events are split into ordered temporaryshards built in worker processes and merged in event order."""source, files, labels = open_event_source(data)path = Path(data["cache"]["path"])path.parent.mkdir(parents=True, exist_ok=True)workers = _worker_count(data)shard_count = max(1, workers)ranges = [(len(source) * index // shard_count, len(source) * (index + 1) // shard_count)for index in range(shard_count)]shard_dir = Path(tempfile.mkdtemp(prefix=f".{path.name}.shards-", dir=path.parent))args = [(data,[Path(file) for file in files],labels,start,stop,shard_dir / f"shard-{index:04d}.pt",)for index, (start, stop) in enumerate(ranges)if start < stop]try:shard_results = _run(_write_graph_shard, args, workers)samples: list[GraphSample] = []for shard_path, _ in shard_results:samples.extend(GraphSampleCache(shard_path).load())GraphSampleCache(path).save(samples)finally:shutil.rmtree(shard_dir, ignore_errors=True)return pathdef prepare_graph_shard(data: Mapping[str, Any],*,shard_index: int,shard_count: int,output_dir: str | Path,) -> Path:"""Prepare one persistent, restartable graph-cache shard.Shards use contiguous global event ranges and are independent of oneanother, making this function suitable for a Slurm job array. Existingvalid shards are reused so interrupted arrays can be resubmitted safely."""source, files, labels = open_event_source(data)start, stop = shard_range(len(source), shard_index, shard_count)3 unmodified linesexpected = stop - startif target.is_file():try:if len(GraphSampleCache(target).load()) == expected:logger.info("reusing completed shard %s", target)return targetexcept (OSError, RuntimeError, ValueError, EOFError):logger.warning("discarding incomplete or incompatible shard %s", target)workers = _worker_count(data)local_shards = max(1, workers)local_ranges = [(start + (stop - start) * index // local_shards,start + (stop - start) * (index + 1) // local_shards,)for index in range(local_shards)]args = [(data, files, labels, local_start, local_stop)for local_start, local_stop in local_rangesif local_start < local_stop]local_results = _run(_build_graph_samples_from_args, args, workers)samples = [sample for result in local_results for sample in result]if len(samples) != expected:raise RuntimeError(f"shard {shard_index} produced {len(samples)} samples, expected {expected}")temporary = target.with_suffix(target.suffix + f".tmp-{os.getpid()}")GraphSampleCache(temporary).save(samples)os.replace(temporary, target)return targetdef write_graph_shard_manifest(data: Mapping[str, Any], *, shard_count: int, output_dir: str | Path) -> Path:"""Write an immutable description of the event ranges in a shard set."""1 unmodified linetarget_dir = Path(output_dir)target_dir.mkdir(parents=True, exist_ok=True)manifest = {"format": 1,"total_events": len(source),"shard_count": int(shard_count),"tree_name": str(data["tree_name"]),123456789109 unmodified lines20212223242526272829303132333435363738394022 unmodified lines6364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818910 unmodified lines2002012022032042052062072082092102112122132142152166 unmodified lines2232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672683 unmodified lines2722732742752762772782792802812822832842852862872882892902912922932942952962972982993003011 unmodified line303304305306307308309"""Prepare packed event caches from ROOT event sources.Preparation is vectorized over chunks of events and writes therepresentation-neutral :class:`PackedEvents` layout; graphs, sequences, orother model inputs are built from it at batch time. Every function takes theresolved ``data`` configuration as a plain mapping so that it can be shippedto spawned worker processes."""from __future__ import annotations9 unmodified linesfrom pathlib import Pathfrom typing import Anyimport awkward as akimport numpy as npimport torchfrom gnn4colliders.features import NODE_FEATURE_NAMES, build_object_feature_tablefrom .dataset import EventChunk, RootEventDatasetfrom .events import EventCache, PackedEvents, concatenate_eventsfrom .huggingface import resolve_data_fileslogger = logging.getLogger(__name__)#: Events read from ROOT per vectorized step; bounds peak worker memory.CHUNK_EVENTS = 100_000def _event_dataset(data: Mapping[str, Any], files: list[Path], labels: list[Any]22 unmodified linesreturn _event_dataset(data, files, labels_per_file), files, labels_per_filedef _flat_float32(arrays: Any, spec: Any, count: int) -> np.ndarray:"""Per-event scalar values as float32, like ``EventSample`` metadata."""if not isinstance(spec, str):return np.full(count, float(spec), dtype=np.float32)values = arrays[spec]if isinstance(values, ak.Array) and values.ndim != 1:raise ValueError(f"tracking/global value is not scalar: branch {spec!r}")return np.asarray(ak.to_numpy(values), dtype=np.float32)def _labels(label: Any, arrays: Any, count: int) -> torch.Tensor:if isinstance(label, str):values = np.asarray(ak.to_numpy(arrays[label]))if values.dtype.kind in "iu":return torch.from_numpy(values.astype(np.int64))if values.dtype.kind == "b":return torch.from_numpy(values.astype(np.bool_))return torch.from_numpy(values.astype(np.float32))scalar = torch.as_tensor(label)return torch.full((count,), label, dtype=scalar.dtype)def _pack_chunk(data: Mapping[str, Any], source: RootEventDataset, chunk: EventChunk) -> PackedEvents:arrays = chunk.arrayscount = chunk.entry_stop - chunk.entry_startfeatures, counts = build_object_feature_table(arrays,count,data["feature_branches"],data["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(np.stack([_flat_float32(arrays, spec, count) for spec in global_specs], axis=1))if global_specselse None)return PackedEvents(object_features=features,object_offsets=torch.cat((torch.zeros(1, dtype=torch.long), torch.cumsum(counts, 0))),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),source_files=tuple(str(path) for path in source.files),tree_name=source.tree_name,feature_names=_feature_names(features.shape[1]),)def _feature_names(width: int) -> tuple[str, ...]:if width == len(NODE_FEATURE_NAMES):return NODE_FEATURE_NAMESreturn tuple(f"feature_{index}" for index in range(width))def build_packed_events(data: Mapping[str, Any],files: list[Path],labels: list[Any],start: int,stop: int,) -> PackedEvents:"""Prepare the global event range ``[start, stop)``."""for key in ("feature_branches", "object_types", "scales"):if data.get(key) is None:raise ValueError("prepare requires data.feature_branches, object_types, and scales")source = _event_dataset(data, files, labels)parts = [_pack_chunk(data, source, chunk)for chunk in source.iter_chunks(start, stop, step=CHUNK_EVENTS)]if not parts:return _empty(data, source)return concatenate_events(parts)def _empty(data: Mapping[str, Any], source: RootEventDataset) -> PackedEvents:width = len(data["feature_branches"])globals_count = len(source.global_specs)return PackedEvents(object_features=torch.empty((0, width)),object_offsets=torch.zeros(1, dtype=torch.long),labels=torch.empty(0, dtype=torch.long),global_features=torch.empty((0, globals_count)) if globals_count else None,fold=torch.empty(0, dtype=torch.long),weight=torch.empty(0),file_index=torch.empty(0, dtype=torch.long),entry_index=torch.empty(0, dtype=torch.long),source_files=tuple(str(path) for path in source.files),tree_name=source.tree_name,feature_names=_feature_names(width),)def _build_from_args(args: tuple[Any, ...]) -> PackedEvents:data, files, labels, start, stop = argsreturn build_packed_events(data, files, labels, start, stop)def _write_part(args: tuple[Any, ...]) -> Path:data, files, labels, start, stop, path = argsEventCache(path).save(build_packed_events(data, files, labels, start, stop))return Path(path)def _worker_count(data: Mapping[str, Any]) -> int:10 unmodified linesreturn [function(item) for item in args]def _ranges(start: int, stop: int, parts: int) -> list[tuple[int, int]]:ranges = [(start + (stop - start) * index // parts,start + (stop - start) * (index + 1) // parts,)for index in range(parts)]return [(low, high) for low, high in ranges if low < high]def shard_range(total: int, shard_index: int, shard_count: int) -> tuple[int, int]:"""Return the contiguous ``[start, stop)`` event range of one shard."""if shard_count < 1:6 unmodified lines)def prepare_event_cache(data: Mapping[str, Any]) -> Path:"""Build the complete event cache at ``data.cache.path``.With ``data.num_workers > 1`` contiguous event ranges are prepared inworker processes and concatenated in event order."""source, files, labels = open_event_source(data)path = Path(data["cache"]["path"])path.parent.mkdir(parents=True, exist_ok=True)workers = _worker_count(data)ranges = _ranges(0, len(source), max(1, workers)) or [(0, 0)]if workers <= 1:EventCache(path).save(build_packed_events(data, files, labels, 0, len(source)))return pathpart_dir = Path(tempfile.mkdtemp(prefix=f".{path.name}.parts-", dir=path.parent))args = [(data, files, labels, start, stop, part_dir / f"part-{index:04d}.pt")for index, (start, stop) in enumerate(ranges)]try:parts = [EventCache(part).load() for part in _run(_write_part, args, workers)]EventCache(path).save(concatenate_events(parts))finally:shutil.rmtree(part_dir, ignore_errors=True)return pathdef prepare_event_shard(data: Mapping[str, Any],*,shard_index: int,shard_count: int,output_dir: str | Path,) -> Path:"""Prepare one persistent, restartable event-cache shard.Shards use contiguous global event ranges and are independent of oneanother, making this function suitable for a Slurm job array. Existingvalid shards are reused so interrupted arrays can be resubmitted safely.A shard directory with its ``manifest.json`` is itself a loadable cache."""source, files, labels = open_event_source(data)start, stop = shard_range(len(source), shard_index, shard_count)3 unmodified linesexpected = stop - startif target.is_file():try:if len(EventCache(target).load(mmap=True)) == expected:logger.info("reusing completed shard %s", target)return targetexcept (OSError, RuntimeError, ValueError, EOFError):logger.warning("discarding incomplete or incompatible shard %s", target)workers = _worker_count(data)args = [(data, files, labels, low, high)for low, high in _ranges(start, stop, max(1, workers))]parts = _run(_build_from_args, args, workers)events = concatenate_events(parts) if parts else _empty(data, source)if len(events) != expected:raise RuntimeError(f"shard {shard_index} produced {len(events)} events, expected {expected}")temporary = target.with_suffix(target.suffix + f".tmp-{os.getpid()}")EventCache(temporary).save(events)os.replace(temporary, target)return targetdef write_event_shard_manifest(data: Mapping[str, Any], *, shard_count: int, output_dir: str | Path) -> Path:"""Write an immutable description of the event ranges in a shard set."""1 unmodified linetarget_dir = Path(output_dir)target_dir.mkdir(parents=True, exist_ok=True)manifest = {"format": 2,"total_events": len(source),"shard_count": int(shard_count),"tree_name": str(data["tree_name"]),
16 unmodified lines1718192021222316 unmodified lines``objects`` is a read-only mapping of selected ROOT branch names to theevent's scalar or jagged values. Keeping branch values here lets theshared feature layer consume the sample without introducing DGL or modelclasses into the data package."""16 unmodified lines1718192021222316 unmodified lines``objects`` is a read-only mapping of selected ROOT branch names to theevent's scalar or jagged values. Keeping branch values here lets theshared feature layer consume the sample without introducing graph or modelclasses into the data package."""
123456714 unmodified lines22232425262730 unmodified lines5859606162636465666768697071727374759 unmodified lines85868788899091106 unmodified lines19819920020120220320420520 unmodified lines226227228229230231232"""Tensor-only ROOT-GNN export and ONNX Runtime validation.The native model intentionally remains DGL-based. This module is aninference/deployment adapter whose public tensor contract is:``node_features``, ``edge_features``, ``edge_src``, ``edge_dst``,``node_batch``, and ``global_features``. ``global_features`` is a requiredruntime input for a stable ONNX signature; for models without configured14 unmodified linesfrom torch import nnfrom gnn4colliders.data.metadata import FEATURE_SCHEMA_VERSION, GRAPH_SCHEMA_VERSIONfrom gnn4colliders.models.root_gnn import EdgeNetwork, FineTunedEdgeNetworkfrom gnn4colliders.training import CheckpointManager, load_model_weights30 unmodified linesdef inputs_from_graph_batch(batch: Any) -> RootGNNExportInputs:"""Convert a ``GraphBatch`` to explicit, metadata-free export inputs."""graph = batch.graph if hasattr(batch, "graph") else batchif not hasattr(graph, "ndata") or not hasattr(graph, "edata"):raise TypeError("example batch must contain a DGL graph")node_features = graph.ndata["features"]edge_features = graph.edata["features"]if node_features.ndim != 2 or edge_features.ndim != 2:raise ValueError("graph node and edge features must be rank-2 tensors")try:node_counts = graph.batch_num_nodes().to(dtype=torch.long)edge_counts = graph.batch_num_edges().to(dtype=torch.long)edge_src, edge_dst = graph.edges(order="eid")except AttributeError as error:raise ValueError("export requires a batched DGL graph") from errorif (node_counts.numel() == 0or int(node_counts.sum()) == 09 unmodified lines# The edge batch is deliberately derived from source node membership in the# adapter; checking it here catches malformed graph batches early.if edge_batch.numel() and not torch.equal(edge_batch, node_batch[edge_src]):raise ValueError("DGL edge ordering does not agree with graph membership")globals_ = getattr(batch, "global_features", None)if globals_ is None:globals_ = node_counts[:, None].to(dtype=node_features.dtype)106 unmodified linesimport onnxexcept ImportError as error:raise ImportError("ONNX export requires the 'onnx' extra. Install with: ""uv sync --extra root-gnn --extra onnx") from errorreturn onnx20 unmodified linesexcept ImportError as error:raise ImportError("ONNX Runtime validation requires the 'onnx' extra. Install with: ""uv sync --extra root-gnn --extra onnx") from errorsession = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"])values = {123456714 unmodified lines2223242526272830 unmodified lines5960616263646566676869707172739 unmodified lines83848586878889106 unmodified lines19619719819920020120220 unmodified lines223224225226227228229"""Tensor-only ROOT-GNN export and ONNX Runtime validation.This module is an inference/deployment adapter whose public tensor contractis:``node_features``, ``edge_features``, ``edge_src``, ``edge_dst``,``node_batch``, and ``global_features``. ``global_features`` is a requiredruntime input for a stable ONNX signature; for models without configured14 unmodified linesfrom torch import nnfrom gnn4colliders.data.metadata import FEATURE_SCHEMA_VERSION, GRAPH_SCHEMA_VERSIONfrom gnn4colliders.graphs.tensor_graph import TensorGraphfrom gnn4colliders.models.root_gnn import EdgeNetwork, FineTunedEdgeNetworkfrom gnn4colliders.training import CheckpointManager, load_model_weights30 unmodified linesdef inputs_from_graph_batch(batch: Any) -> RootGNNExportInputs:"""Convert a ``GraphBatch`` to explicit, metadata-free export inputs."""graph = batch.graph if hasattr(batch, "graph") else batchif not isinstance(graph, TensorGraph):raise TypeError("example batch must contain a TensorGraph")node_features = graph.node_featuresedge_features = graph.edge_featuresif node_features.ndim != 2 or edge_features.ndim != 2:raise ValueError("graph node and edge features must be rank-2 tensors")node_counts = graph.node_counts.to(dtype=torch.long)edge_counts = graph.edge_counts.to(dtype=torch.long)edge_src, edge_dst = graph.edge_src, graph.edge_dstif (node_counts.numel() == 0or int(node_counts.sum()) == 09 unmodified lines# The edge batch is deliberately derived from source node membership in the# adapter; checking it here catches malformed graph batches early.if edge_batch.numel() and not torch.equal(edge_batch, node_batch[edge_src]):raise ValueError("edge ordering does not agree with graph membership")globals_ = getattr(batch, "global_features", None)if globals_ is None:globals_ = node_counts[:, None].to(dtype=node_features.dtype)106 unmodified linesimport onnxexcept ImportError as error:raise ImportError("ONNX export requires the 'onnx' extra. Install with: uv sync --extra onnx") from errorreturn onnx20 unmodified linesexcept ImportError as error:raise ImportError("ONNX Runtime validation requires the 'onnx' extra. Install with: ""uv sync --extra onnx") from errorsession = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"])values = {
12345"""Collider-domain feature transformations shared across model families."""from .objects import NODE_FEATURE_NAMES, build_node_features, build_object_features__all__ = ["NODE_FEATURE_NAMES", "build_node_features", "build_object_features"]123456789101112131415"""Collider-domain feature transformations shared across model families."""from .objects import (NODE_FEATURE_NAMES,build_node_features,build_object_feature_table,build_object_features,)__all__ = ["NODE_FEATURE_NAMES","build_node_features","build_object_feature_table","build_object_features",]
.claude/skills/gnn4colliders-workflow/SKILL.md+3-2
.codex/skills/gnn4colliders-workflow/SKILL.md+3-2
.github/workflows/ci.yml+8-4
AGENTS.md+11-8
CHANGELOG.md+19-4
README_PROJECT.md+29-33
benchmarks/README.md+26-31
benchmarks/_common.py+15-6
benchmarks/benchmark_dataloader.py+29-43
benchmarks/benchmark_inference.py+11-19
benchmarks/benchmark_prepare.py+2-2
benchmarks/benchmark_training.py+19-21
docs/agent-workflows/gnn4colliders-workflow.md+8-6
docs/architecture.md+26-23
docs/configuration.md+16-8
docs/end_to_end_validation.md+1-1
docs/export.md+5-6
docs/migration.md+46-6
docs/performance.md+39-8
docs/perlmutter.md+10-9
docs/quickstart.md+11-10
docs/releasing.md+4-6
docs/testing.md+6-6
pyproject.toml+1-17
scripts/dev/smoke_end_to_end.py+1-8
scripts/slurm/evaluate.sh+3
scripts/slurm/prepare_tth_cp_even_odd.sh+2-2
scripts/slurm/train_multi_gpu.sh+3
scripts/slurm/train_multi_node.sh+3
scripts/slurm/train_single_gpu.sh+3
src/gnn4colliders/cli/__init__.py+4-2
src/gnn4colliders/config/application.py+43-66
src/gnn4colliders/config/factories.py+7-8
src/gnn4colliders/configs/data/hf_delphes.yaml+1-1
src/gnn4colliders/configs/data/hf_smoke.yaml+1-1
src/gnn4colliders/configs/data/tth_cp_even_odd.yaml+1-1
src/gnn4colliders/configs/model/root_gnn/edge_network.yaml-1
src/gnn4colliders/configs/model/root_gnn/edge_network_binary.yaml-1
src/gnn4colliders/configs/model/root_gnn/fine_tuned_edge_network.yaml-1
src/gnn4colliders/data/__init__.py+10-20
src/gnn4colliders/data/cache.pyDeleted-69
src/gnn4colliders/data/dataset.py+48-18
src/gnn4colliders/data/events.pyAdded+303
src/gnn4colliders/data/graph_dataset.pyDeleted-295
src/gnn4colliders/data/loader.pyAdded+119
src/gnn4colliders/data/metadata.py+1-1
src/gnn4colliders/graphs/preparation.py → src/gnn4colliders/data/preparation.pyRenamed+161-90
src/gnn4colliders/data/sample.py+1-1
src/gnn4colliders/export/onnx.py+13-16
src/gnn4colliders/features/__init__.py+12-2