This view is limited to 50 files because it contains too many changes. See the raw diff here.
Files changed (50) hide show
  1. .github/workflows/ci.yml +75 -0
  2. .gitignore +26 -0
  3. .python-version +1 -0
  4. AGENTS.md +477 -0
  5. CHANGELOG.md +13 -0
  6. MANIFEST.in +3 -0
  7. README.md +252 -358
  8. benchmarks/README.md +48 -0
  9. benchmarks/__init__.py +1 -0
  10. benchmarks/_common.py +70 -0
  11. benchmarks/benchmark_dataloader.py +63 -0
  12. benchmarks/benchmark_inference.py +52 -0
  13. benchmarks/benchmark_preprocessing.py +61 -0
  14. benchmarks/benchmark_training.py +73 -0
  15. configs/.gitkeep +1 -0
  16. configs/data/.gitkeep +1 -0
  17. configs/environment/.gitkeep +1 -0
  18. configs/model/.gitkeep +1 -0
  19. configs/model/root_gnn/.gitkeep +1 -0
  20. configs/task/.gitkeep +1 -0
  21. configs/trainer/.gitkeep +1 -0
  22. data/fixtures/.gitkeep +1 -0
  23. data/raw/.gitkeep +1 -0
  24. docs/architecture.md +375 -0
  25. docs/compatibility.md +22 -0
  26. docs/configuration.md +94 -0
  27. docs/end_to_end_validation.md +30 -0
  28. docs/export.md +36 -0
  29. docs/migration.md +288 -0
  30. docs/performance.md +20 -0
  31. docs/perlmutter.md +58 -0
  32. docs/releasing.md +23 -0
  33. docs/testing.md +29 -0
  34. examples/README.md +18 -0
  35. LICENSE β†’ legacy/LICENSE +0 -0
  36. legacy/README.md +358 -0
  37. {physicsnemo β†’ legacy/physicsnemo}/configs/config.yaml +0 -0
  38. {physicsnemo β†’ legacy/physicsnemo}/configs/config_stats_all.yaml +0 -0
  39. {physicsnemo β†’ legacy/physicsnemo}/configs/tHjb_CP_0_vs_45.yaml +0 -0
  40. {physicsnemo β†’ legacy/physicsnemo}/configs/tHjb_CP_0_vs_90.yaml +0 -0
  41. {physicsnemo β†’ legacy/physicsnemo}/configs/tHjb_CP_0_vs_90_edge_network.yaml +0 -0
  42. {physicsnemo β†’ legacy/physicsnemo}/configs/tHjb_CP_0_vs_90_globals.yaml +0 -0
  43. {physicsnemo β†’ legacy/physicsnemo}/dataset/Dataset.py +0 -0
  44. {physicsnemo β†’ legacy/physicsnemo}/dataset/GraphBuilder.py +0 -0
  45. {physicsnemo β†’ legacy/physicsnemo}/dataset/Graphs.py +0 -0
  46. {physicsnemo β†’ legacy/physicsnemo}/dataset/Normalization.py +0 -0
  47. {physicsnemo β†’ legacy/physicsnemo}/metrics.py +0 -0
  48. {physicsnemo β†’ legacy/physicsnemo}/models/Edge_Network.py +0 -0
  49. {physicsnemo β†’ legacy/physicsnemo}/models/MeshGraphNet.py +0 -0
  50. {physicsnemo β†’ legacy/physicsnemo}/models/utils.py +0 -0
.github/workflows/ci.yml ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ pull_request:
6
+
7
+ concurrency:
8
+ group: ci-${{ github.workflow }}-${{ github.ref }}
9
+ cancel-in-progress: true
10
+
11
+ jobs:
12
+ lint:
13
+ name: lint
14
+ runs-on: ubuntu-latest
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ - uses: astral-sh/setup-uv@v6
18
+ with:
19
+ version: "0.8.x"
20
+ enable-cache: true
21
+ - run: uv sync --dev
22
+ - run: uv run ruff check .
23
+ - run: uv run ruff format --check .
24
+
25
+ test:
26
+ name: test
27
+ runs-on: ubuntu-latest
28
+ steps:
29
+ - uses: actions/checkout@v4
30
+ - uses: astral-sh/setup-uv@v6
31
+ with:
32
+ version: "0.8.x"
33
+ enable-cache: true
34
+ - run: uv sync --dev
35
+ - run: uv run pytest
36
+
37
+ package:
38
+ name: package
39
+ runs-on: ubuntu-latest
40
+ steps:
41
+ - uses: actions/checkout@v4
42
+ - uses: astral-sh/setup-uv@v6
43
+ with:
44
+ version: "0.8.x"
45
+ enable-cache: true
46
+ - run: uv sync --dev
47
+ - run: uv build
48
+ - run: uv run python -m twine check dist/*
49
+ - name: Wheel install smoke test
50
+ shell: bash
51
+ run: |
52
+ set -euo pipefail
53
+ smoke_dir="$(mktemp -d)"
54
+ trap 'rm -rf "$smoke_dir"' EXIT
55
+ uv venv "$smoke_dir/venv"
56
+ uv pip install --python "$smoke_dir/venv/bin/python" dist/*.whl
57
+ (
58
+ cd "$smoke_dir"
59
+ "$smoke_dir/venv/bin/python" -c 'import gnn4colliders; print(gnn4colliders.__version__)'
60
+ "$smoke_dir/venv/bin/gnn4colliders" --help
61
+ "$smoke_dir/venv/bin/gnn4colliders" train --help
62
+ "$smoke_dir/venv/bin/gnn4colliders" export --help
63
+ )
64
+
65
+ onnx:
66
+ name: onnx
67
+ runs-on: ubuntu-latest
68
+ steps:
69
+ - uses: actions/checkout@v4
70
+ - uses: astral-sh/setup-uv@v6
71
+ with:
72
+ version: "0.8.x"
73
+ enable-cache: true
74
+ - run: uv sync --dev --extra root-gnn --extra onnx
75
+ - run: uv run pytest tests/unit/export -v
.gitignore CHANGED
@@ -4,3 +4,29 @@ scores/
4
  slurm/
5
  .onnx
6
  .png
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  slurm/
5
  .onnx
6
  .png
7
+
8
+ # Python tooling
9
+ *.py[cod]
10
+ .pytest_cache/
11
+ .ruff_cache/
12
+ .mypy_cache/
13
+ *.egg-info/
14
+ .venv/
15
+ venv/
16
+ htmlcov/
17
+ .coverage
18
+ profiles/
19
+ *.trace.json
20
+ dist/
21
+ build/
22
+ benchmark-results/
23
+ validation_output/
24
+
25
+ # Local data and generated outputs
26
+ data/raw/*
27
+ !data/raw/.gitkeep
28
+ data/processed/
29
+ outputs/
30
+ checkpoints/
31
+
32
+ # Keep the legacy implementation immutable by convention; do not add generated files there.
.python-version ADDED
@@ -0,0 +1 @@
 
 
1
+ 3.12
AGENTS.md ADDED
@@ -0,0 +1,477 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # GNN4Colliders Agent Instructions
2
+
3
+ ## Project purpose
4
+
5
+ GNN4Colliders is a collider machine-learning package intended to support multiple model architectures over shared collider-physics data infrastructure.
6
+
7
+ The first model family being rewritten is:
8
+
9
+ ```text
10
+ root_gnn
11
+ ```
12
+
13
+ Future model families may include architectures such as:
14
+
15
+ ```text
16
+ root_transformer
17
+ ```
18
+
19
+ Do not design shared infrastructure around assumptions that only apply to GNNs.
20
+
21
+ ---
22
+
23
+ ## Source of truth
24
+
25
+ Before making non-trivial changes, inspect:
26
+
27
+ ```text
28
+ docs/architecture.md
29
+ docs/migration.md
30
+ ```
31
+
32
+ and the relevant existing source and tests.
33
+
34
+ The `legacy/` tree is a behavioral reference for the rewrite.
35
+
36
+ Unless explicitly instructed otherwise:
37
+
38
+ * do not modify legacy code
39
+ * do not reorganize legacy code
40
+ * do not mechanically copy legacy architecture into the new package
41
+
42
+ When legacy behavior and documentation disagree, identify the discrepancy rather than silently choosing one.
43
+
44
+ ---
45
+
46
+ ## Package architecture
47
+
48
+ Production Python code belongs under:
49
+
50
+ ```text
51
+ src/gnn4colliders/
52
+ ```
53
+
54
+ The intended boundaries are:
55
+
56
+ ```text
57
+ data/
58
+ Data access, datasets, caching, batching, folds, and generic
59
+ representation-independent data infrastructure.
60
+
61
+ features/
62
+ Collider-domain feature transformations, selections, scaling,
63
+ and derived physics quantities.
64
+
65
+ graphs/
66
+ Graph representation, topology, edge construction, and other
67
+ graph-specific transformations.
68
+
69
+ models/
70
+ Architecture-specific neural network implementations.
71
+
72
+ models/root_gnn/
73
+ ROOT-GNN-specific model components.
74
+
75
+ training/
76
+ Training lifecycle, losses, metrics, checkpointing,
77
+ reproducibility, and distributed-training utilities where
78
+ architecture-independent.
79
+
80
+ inference/
81
+ Prediction, evaluation, output writing, and model export.
82
+
83
+ cli/
84
+ Thin command-line entry points only.
85
+ ```
86
+
87
+ Do not place ROOT file-reading logic inside a specific model family unless it is genuinely architecture-specific.
88
+
89
+ Do not place reusable physics-feature logic inside `root_gnn`.
90
+
91
+ Do not place core implementation in notebooks or shell scripts.
92
+
93
+ ---
94
+
95
+ ## Shared infrastructure vs model-specific code
96
+
97
+ Use this decision rule:
98
+
99
+ **Shared collider or experiment behavior β†’ shared package module.**
100
+
101
+ Examples:
102
+
103
+ ```text
104
+ ROOT reading
105
+ event selections
106
+ physics features
107
+ dataset splits
108
+ metrics
109
+ checkpoint orchestration
110
+ ```
111
+
112
+ **Representation-specific behavior β†’ representation module.**
113
+
114
+ Examples:
115
+
116
+ ```text
117
+ graph topology
118
+ edge construction
119
+ sequence/token construction
120
+ ```
121
+
122
+ **Architecture-specific behavior β†’ models/<model_family>/.**
123
+
124
+ Examples:
125
+
126
+ ```text
127
+ message-passing network
128
+ transformer encoder
129
+ architecture-specific layers
130
+ ```
131
+
132
+ The package should allow future architectures to reuse the same data and physics infrastructure where practical.
133
+
134
+ ---
135
+
136
+ ## Configuration
137
+
138
+ Experiment configuration should describe intent rather than expose implementation details.
139
+
140
+ Prefer:
141
+
142
+ ```yaml
143
+ model:
144
+ type: root_gnn
145
+ ```
146
+
147
+ over configuration that directly names Python module paths and class names.
148
+
149
+ Configuration should eventually support composition across concerns such as:
150
+
151
+ ```text
152
+ data
153
+ model
154
+ task
155
+ trainer
156
+ environment
157
+ ```
158
+
159
+ Do not hardcode site-specific filesystem paths, CUDA settings, Slurm settings, or machine configuration into model or task definitions.
160
+
161
+ Environment-specific configuration belongs in an environment configuration layer.
162
+
163
+ ---
164
+
165
+ ## CLI design
166
+
167
+ The intended user-facing interface is a single project CLI with subcommands conceptually similar to:
168
+
169
+ ```bash
170
+ gnn4colliders prepare
171
+ gnn4colliders train
172
+ gnn4colliders evaluate
173
+ gnn4colliders predict
174
+ gnn4colliders export
175
+ ```
176
+
177
+ CLI modules should be thin.
178
+
179
+ They may:
180
+
181
+ * parse/compose configuration
182
+ * construct application objects
183
+ * invoke library functions
184
+ * handle user-facing errors
185
+
186
+ They should not contain core training, data-processing, graph-building, or model logic.
187
+
188
+ ---
189
+
190
+ ## Rewrite strategy
191
+
192
+ This repository is being rewritten incrementally.
193
+
194
+ Do not attempt to rewrite the entire legacy repository in one task.
195
+
196
+ For substantial migrations:
197
+
198
+ 1. inspect the relevant legacy implementation
199
+ 2. identify externally observable behavior
200
+ 3. inspect existing characterization/parity tests
201
+ 4. state or infer the intended new interface
202
+ 5. implement the smallest coherent unit
203
+ 6. add or update tests
204
+ 7. run relevant validation
205
+ 8. report intentional differences and unresolved ambiguity
206
+
207
+ Prefer vertical, testable migration steps over large speculative refactors.
208
+
209
+ ---
210
+
211
+ ## Behavioral parity
212
+
213
+ The legacy implementation defines important behavior that may need to remain compatible during migration.
214
+
215
+ Important compatibility areas include, where applicable:
216
+
217
+ * input feature definitions
218
+ * feature ordering
219
+ * tensor shapes
220
+ * tensor dtypes
221
+ * graph topology
222
+ * edge feature definitions
223
+ * label semantics
224
+ * event weights
225
+ * fold semantics
226
+ * loss calculations
227
+ * metric definitions
228
+ * model outputs
229
+ * checkpoint compatibility
230
+ * inference outputs
231
+
232
+ Do not alter behavior merely because the legacy implementation appears unusual.
233
+
234
+ If behavior seems incorrect or ambiguous:
235
+
236
+ 1. document it
237
+ 2. characterize it with a test when possible
238
+ 3. separate compatibility from proposed improvement
239
+
240
+ Improvements can be made deliberately after the behavior is understood.
241
+
242
+ ---
243
+
244
+ ## Testing
245
+
246
+ Tests belong under:
247
+
248
+ ```text
249
+ tests/unit/
250
+ tests/integration/
251
+ tests/parity/
252
+ ```
253
+
254
+ ### Unit tests
255
+
256
+ Use unit tests for isolated transformations and components.
257
+
258
+ They should be:
259
+
260
+ * fast
261
+ * deterministic
262
+ * focused
263
+ * independent of large external datasets
264
+
265
+ ### Integration tests
266
+
267
+ Use integration tests for small end-to-end workflows such as:
268
+
269
+ ```text
270
+ input fixture
271
+ β†’ features
272
+ β†’ representation
273
+ β†’ model
274
+ β†’ output
275
+ ```
276
+
277
+ ### Parity tests
278
+
279
+ Use parity tests to compare the rewrite with the legacy implementation.
280
+
281
+ Prefer small deterministic fixtures and reference outputs.
282
+
283
+ Do not weaken or delete parity tests simply to make new code pass.
284
+
285
+ If a parity difference is intentional, document the reason.
286
+
287
+ ---
288
+
289
+ ## Test data
290
+
291
+ Large production datasets do not belong in the repository.
292
+
293
+ Small deterministic fixtures may live under:
294
+
295
+ ```text
296
+ tests/fixtures/
297
+ ```
298
+
299
+ Fixtures should be only large enough to exercise relevant behavior.
300
+
301
+ Where possible, create reference outputs for deterministic legacy behavior before replacing that behavior.
302
+
303
+ ---
304
+
305
+ ## Reproducibility
306
+
307
+ Reproducibility is a project requirement.
308
+
309
+ Randomness should be explicit and controllable.
310
+
311
+ Where relevant, account for:
312
+
313
+ * Python random state
314
+ * NumPy random state
315
+ * PyTorch random state
316
+ * CUDA random state
317
+ * DataLoader workers
318
+ * shuffling
319
+ * sampling
320
+ * data augmentation
321
+ * distributed execution
322
+
323
+ Do not introduce hidden global random-state mutation.
324
+
325
+ Seeds should be passed or configured explicitly.
326
+
327
+ Do not claim bitwise deterministic training unless the execution environment actually guarantees it.
328
+
329
+ ---
330
+
331
+ ## Code quality
332
+
333
+ Domain meaning must be represented by named fields or schemas, not only by
334
+ positional column indices. New APIs must not require callers to know that a
335
+ particular tensor column means fold, weight, or another domain field.
336
+
337
+ Prefer:
338
+
339
+ * small modules with clear responsibilities
340
+ * typed function signatures
341
+ * explicit inputs and outputs
342
+ * dataclasses or typed configuration where appropriate
343
+ * composition over hidden global state
344
+ * readable names over abbreviations
345
+ * dependency injection over implicit filesystem/environment assumptions
346
+
347
+ Avoid:
348
+
349
+ * repository-relative `sys.path` modifications
350
+ * mutable global configuration
351
+ * hidden singleton state
352
+ * wildcard imports
353
+ * giant utility modules
354
+ * giant training scripts
355
+ * model-specific behavior in generic data code
356
+ * duplicated preprocessing logic
357
+ * unnecessary abstraction introduced before a second use case exists
358
+
359
+ Keep public interfaces intentionally small.
360
+
361
+ ---
362
+
363
+ ## Dependencies
364
+
365
+ Do not introduce a dependency merely to simplify a small amount of code.
366
+
367
+ Before adding a major framework or runtime dependency, explain why it is necessary.
368
+
369
+ In particular, do not introduce architectural frameworks such as:
370
+
371
+ ```text
372
+ PyTorch Lightning
373
+ Kedro
374
+ ```
375
+
376
+ unless the task explicitly calls for evaluating or adopting them.
377
+
378
+ Scientific dependencies should be introduced intentionally and with environment compatibility in mind.
379
+
380
+ PyTorch is shared infrastructure for the expected model families and belongs
381
+ in the base package dependencies. Architecture-specific dependencies belong in
382
+ named extras, for example `root-gnn` for DGL. The canonical development
383
+ environment for the active ROOT-GNN rewrite is:
384
+
385
+ ```bash
386
+ uv sync --extra root-gnn
387
+ ```
388
+
389
+ ---
390
+
391
+ ## Documentation
392
+
393
+ Update documentation when a change alters:
394
+
395
+ * architecture
396
+ * configuration
397
+ * public interfaces
398
+ * expected workflow
399
+ * compatibility guarantees
400
+
401
+ Do not document speculative functionality as if it already exists.
402
+
403
+ Use:
404
+
405
+ ```text
406
+ docs/architecture.md
407
+ ```
408
+
409
+ for the target system structure and important architectural decisions.
410
+
411
+ Use:
412
+
413
+ ```text
414
+ docs/migration.md
415
+ ```
416
+
417
+ for rewrite progress and migration sequencing.
418
+
419
+ ---
420
+
421
+ ## Scope discipline
422
+
423
+ Do not make unrelated changes.
424
+
425
+ When implementing a task:
426
+
427
+ * modify only the modules necessary for that task
428
+ * do not opportunistically refactor unrelated code
429
+ * do not rename public concepts without a clear reason
430
+ * do not remove compatibility behavior without explicit instruction
431
+ * do not modify generated artifacts unless required
432
+
433
+ If a larger architectural issue is discovered, report it rather than expanding the task automatically.
434
+
435
+ ---
436
+
437
+ ## Validation before finishing
438
+
439
+ After code changes, run the relevant available checks.
440
+
441
+ As the project matures, the expected baseline should include:
442
+
443
+ ```bash
444
+ pytest
445
+ ruff check .
446
+ ```
447
+
448
+ ROOT-GNN parity validation requires DGL. A package-wide environment where DGL
449
+ is intentionally absent may skip DGL-dependent tests, but that is incomplete
450
+ ROOT-GNN validation. The required parity gate is:
451
+
452
+ ```bash
453
+ GNN4COLLIDERS_REQUIRE_ROOT_GNN=1 pytest
454
+ ```
455
+
456
+ The gate must fail when DGL cannot be imported.
457
+
458
+ Run more focused tests first when appropriate.
459
+
460
+ If the full suite is expensive, run the relevant subset and clearly report what was and was not run.
461
+
462
+ Do not claim validation succeeded unless the commands actually succeeded.
463
+
464
+ ---
465
+
466
+ ## Completion report
467
+
468
+ For non-trivial changes, finish with a concise report containing:
469
+
470
+ * files changed
471
+ * behavior implemented
472
+ * tests/checks run
473
+ * parity status where relevant
474
+ * intentional deviations from legacy behavior
475
+ * unresolved questions or ambiguities
476
+
477
+ Do not hide failed checks or incomplete behavior.
CHANGELOG.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+
5
+ ### Added
6
+
7
+ - Release validation and CI coverage for the rewritten package.
8
+ - Installed-package Hydra configuration discovery and public import smoke tests.
9
+
10
+ ### Compatibility
11
+
12
+ - The `0.1.0` package version remains a static, single-source version exposed
13
+ as `gnn4colliders.__version__`.
MANIFEST.in ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ include README.md
2
+ include CHANGELOG.md
3
+ recursive-include docs *.md
README.md CHANGED
@@ -1,358 +1,252 @@
1
- ---
2
- license: mit
3
- tags:
4
- - arXiv:2412.10665
5
- ---
6
-
7
- This is a demo is of the approach described in the paper, ["Pretrained Event Classification Model for High Energy Physics Analysis"](https://arxiv.org/abs/2412.10665)
8
- ```
9
- @misc{ho2024pretrained,
10
- title={Pretrained Event Classification Model for High Energy Physics Analysis},
11
- author={Joshua Ho, Benjamin Ryan Roberts, Shuo Han, Haichen Wang},
12
- year={2024},
13
- eprint={2412.10665},
14
- archivePrefix={arXiv}
15
- }
16
- ```
17
-
18
- ## Abstract
19
-
20
- We introduce a foundation model for event classification in high-energy physics, built on a **Graph Neural Network** architecture and trained on **120 million simulated proton-proton collision events** spanning 12 distinct physics processes. The model is *pretrained* to learn a general and robust representation of collision data using challenging multiclass and multilabel classification tasks.
21
-
22
- Its performance is evaluated across five event classification tasks, which include both physics processes used during pretraining and new processes not encountered during pretraining. Fine-tuning the pretrained model significantly improves classification performance, particularly in scenarios with limited training data, demonstrating gains in both accuracy and computational efficiency.
23
-
24
- To investigate the underlying mechanisms behind these performance improvements, we employ a representational similarity evaluation framework based on *Centered Kernel Alignment*. This analysis reveals notable differences in the learned representations of fine-tuned pretrained models compared to baseline models trained from scratch.
25
-
26
- ## Introduction
27
-
28
- Machine learning has become a ubiquitous tool in particle physics, employed in a variety of tasks including triggering, simulation, reconstruction, and offline analysis. While its utility spans classification, regression, and generative tasks, the current paradigm of developing machine learning models from scratch for each specific application presents several challenges. This approach not only demands specialized expertise and substantial computing resources but can also result in suboptimal performance due to limited training data. The from-scratch development of models necessitates individual validation studies to ensure that neural networks utilize well-modeled information from training samples, whether derived from Monte Carlo simulations or control samples from experimental data.
29
-
30
- Foundation models offer a promising direction to address these limitations. These models, pre-trained on large, diverse datasets across various tasks, provide robust and general representations of underlying data structures. Notable examples in other fields include GPT-4 [OpenAI et al., 2024](#ref-openai-2024-gpt4) and BERT [Devlin et al., 2018](#ref-devlin-2018-bert) in natural language processing, Stable Diffusion [Rombach et al., 2021](#ref-rombach-2021-latentdiffusion) in image processing, and AlphaFold [Jumper et al., 2021](#ref-jumper-2021-alphafold) in structural biology. The foundation model approach offers several advantages for particle physics applications: reduced computing resources for fine-tuning [Yosinski et al., 2014](#ref-yosinski-2014-transfer) compared to training from scratch, superior performance on specific tasks (particularly with limited training data), and potentially simplified validation procedures as downstream tasks inherit verified representations from the pre-trained model.
31
-
32
- Current literature on pretrained models for particle physics can be categorized based on the data representation they handle. Models operating on particle- or event-level numerical data use features like particle four momenta or jets, leveraging self-supervised or generative methods to learn versatile representations. Detector-focused models operate on high-dimensional responses such as calorimeter deposits or pixel hits, employing geometry-aware techniques for accurate simulation and analysis. Finally, models using textual or code representations apply large language model architectures to integrate domain knowledge, enabling tasks like question answering and code generation.
33
-
34
- Recent studies have begun exploring foundation models tailored to particle physics data, which has a variety of distinct structures and properties across many experiments and data processing stages, including:
35
-
36
- - particle-level & event-level numeric data [Wildridge et al., 2024](#ref-wildridge-2024-bumblebee), [Katel et al., 2024](#ref-katel-2024-jet), [Golling et al., 2024](#ref-golling-2024-maskedset), [Mikuni & Nachman, 2024](#ref-mikuni-2024-omnilearn), [Harris et al., 2024](#ref-harris-2024-resimulation), [Birk et al., 2024](#ref-birk-2024-omnijet), [Vigl et al., 2024](#ref-vigl-2024-finetune),
37
- - detector-level & geometry-aware data [Araz et al., 2024](#ref-araz-2024-pointcloud), [Liu et al., 2023](#ref-liu-2023-gaam), [Hashemi et al., 2024](#ref-hashemi-2024-gen), [Huang et al., 2024](#ref-huang-2024-lmtracking),
38
- - textual or code data [Zhang et al., 2024](#ref-zhang-2024-xiwu).
39
-
40
- This paper presents a foundation model designed specifically for collider event-level data. In modern collider experiments, final-stage analysis processes information from reconstructed objects that either directly correspond to particles in collision final states (such as leptons and photons) or serve as proxies (such as jets and missing transverse energy). While traditional approaches often relied on "high-level" variables calculated from object features, recent trends favor direct input of event objects and their features into neural networks for analysis tasks. A notable example is [ATLAS Collaboration, 2023](#ref-atlas-2023-4top), which established the observation of simultaneous production of four top quarks with the ATLAS experiment by employing a graph neural network (GNN) architecture to process event-level object information.
41
-
42
- We present foundation models that adopt an architecture similar to that used for [ATLAS Collaboration, 2023](#ref-atlas-2023-4top). Our models are pre-trained using either multiclass classification or multi-label learning tasks across 12 distinct physics processes. We evaluate these models through fine-tuning and testing on five classification tasks, including both familiar and novel processes not seen during pre-training. Our analysis benchmarks the models' performance improvements, their scaling behavior with training sample size, and computational efficiency, representing the first prototype of a foundation model operating on collider final-state object data.
43
-
44
- ## Data Samples
45
-
46
- To provide a diverse set of physics processes for the pretraining, we use Madgraph@NLO 2.7.3 [Alwall et al., 2014](#ref-alwall-2014hca) to generate proton-proton collision events at next-to-leading order (NLO) in Quantum Chromodynamics (QCD). We generate 12 distinct Standard Model (SM) physics processes, including six major Higgs boson production mechanisms: gluon fusion production \\(ggF\\), vector boson fusion \\(VBF\\), associated production of the Higgs boson with a W boson \\(WH\\) or a Z boson \\(ZH\\), associated production of the Higgs boson with a top-quark pair \\(t\bar{t}H\\), and associated production of the Higgs boson with a single top quark and a forward quark \\(tHq\\). Additionally, we simulate six top quark production processes: single top production, top-quark pair production \\(t\bar{t}\\), top quark pair production in association with a pair of photons \\(t\bar{t}\gamma\gamma\\), associated production of a top-quark pair with a W boson \\(t\bar{t}W\\), simultaneous production of three top quarks \\(t\bar{t}t\\), and simultaneous production of four top quarks \\(t\bar{t}t\bar{t}\\). In these samples, the Higgs boson and top quarks decay inclusively. These 12 Higgs and top quark production processes constitute the pretraining dataset.
47
-
48
- To test the pretrained model, we further generated four processes including three beyond Standard Model (SM) processes: a SM \\(t\bar{t}H\\) production where the Higgs boson decays exclusively to a pair of photons, a \\(t\bar{t}H\\) production with the Higgs boson decaying to a pair of photons, where the top-Yukawa coupling is CP-odd, implemented using the Higgs Characterization model [Artoisenet et al., 2013](#ref-artoisinet-2013puc), the production of a pair of superpartners of the top quark (s-top) using the Minimal Supersymmetric Standard Model (MSSM) [Rosiek, 1990](#ref-rosiek-1990), [Allanach et al., 2009](#ref-allanach-2009), and flavor changing neutral current (FCNC) processes [Degrande et al., 2015](#ref-degrande-2015), [Durieux et al., 2015](#ref-durieux-2015). For the s-top process, we simulate the production of heavier s-top pairs \\(t_2\bar{t_2}\\), where each heavier s-top (mass 582 GeV) decays into a lighter s-top \\(t_1\\) or \\(\bar{t_1}\\), mass 400 GeV) and a Higgs boson. The FCNC process involves \\(t\bar{t}\\) production where one top quark decays to a Higgs boson and a light quark. We generate 10 million events for each process, except for \\(tHq\\) and \\(t\bar{t}t\bar{t}\\), where 5 million events were produced.
49
-
50
- In all simulation samples, the center of mass energy of the proton-proton collision is set to 13 TeV. The Higgs boson, top quarks, and vector bosons are set to decay inclusively (except the \\(t\bar{t}H \rightarrow \gamma\gamma\\) samples), with MadSpin [Artoisenet et al., 2012](#ref-artoisinet-2012st) handling the decays of top quarks and W bosons. The generated events are processed through Pythia 8.235 [Sjostrand et al., 2015](#ref-sjostrand-2015) for parton showering and heavy particle decays, followed by Delphes 3.4.2 [de Favereau et al., 2014](#ref-defavereau-2014) configured to emulate the ATLAS detector [ATLAS Collaboration, 2008](#ref-atlas-2008) for fast detector simulation.
51
-
52
- The detector-level object selection criteria are defined to align with typical experimental conditions. Photons are required to have transverse momentum \\(p_T \geq 20~\mathrm{GeV}\\) and pseudorapidity \\(|\eta| \leq 2.37\\), excluding the electromagnetic calorimeter crack region \\(1.37 < |\eta| < 1.52\\). Electrons must have \\(p_T \geq 10~\mathrm{GeV}\\) and \\(|\eta| \leq 2.47\\) (excluding the same crack region), while muons are selected with \\(p_T \geq 10~\mathrm{GeV}\\) and \\(|\eta| \leq 2.7\\). Jets are reconstructed using the anti-\\(k_t\\) algorithm [Cacciari et al., 2008](#ref-cacciari-2008gp) with radius parameter \\(\Delta R=0.4\\), where \\(\Delta R\\) is defined as \\(\sqrt{\Delta\eta ^2 + \Delta\phi^2}\\), with \\(\Delta\eta\\) being the difference in pseudorapidity and \\(\Delta\phi\\) the difference in azimuthal angle. Jets must satisfy \\(p_T \geq 25~\mathrm{GeV}\\) and \\(|\eta| \leq 2.5\\). To avoid double-counting, jets are removed if they are within \\(\Delta R < 0.4\\) of a photon or lepton. The identification of jets originating from b-quark decays (b-tagging) is performed by matching jets within \\(\Delta R = 0.4\\) of a b-quark, with efficiency corrections applied to match the performance of the ATLAS experiment's b-tagging algorithm [ATLAS Collaboration, 2019](#ref-atlas-2019bwq).
53
-
54
- ## Methods
55
-
56
- ### Overview
57
-
58
- We present a methodology for developing and evaluating a foundation model for particle collision event analysis. The approach centers on pretraining a Graph Neural Network (GNN) architecture using a comprehensive dataset that spans multiple physics tasks, enabling the model to learn robust and transferable features. For task-specific applications, we employ a fine-tuning strategy that combines output layer adaptation with carefully calibrated learning rates for updating the pretrained parameters.
59
-
60
- Given the prevalence of classification problems in particle physics data analysis, we evaluate the model's efficacy through a systematic assessment across five binary classification tasks:
61
-
62
- - \\(t\bar{t}H(\rightarrow \gamma\gamma)\\) with CP-even versus CP-odd t-H interaction
63
- - \\(t\bar{t}\\) with FCNC top quark decays versus $tHq$ processes
64
- - \\(t\bar{t}W\\) versus $ttt$ processes
65
- - Stop pair production with Higgs bosons in the decay chain versus \\(t\bar{t}H\\) processes
66
- - \\(WH\\) versus \\(ZH\\) production modes
67
-
68
- Our evaluation metrics encompass classification performance, computational efficiency, and model interpretability. The investigation extends to analyzing the model's scaling behavior with respect to training dataset size, benchmarked against models trained without pretraining. Although we explored transfer learning through parameter freezing of pretrained layers, this approach did not yield performance improvements, leading us to focus our detailed analysis on fine-tuning strategies.
69
-
70
- This methodological framework demonstrates the potential of foundation models to enhance the efficiency of particle physics analyses while improving task-specific performance, offering a promising direction for future high-energy physics research.
71
-
72
- ---
73
-
74
- ### GNN Architecture
75
-
76
- We implement a Graph Neural Network (GNN) architecture that naturally accommodates the point-cloud structure of particle physics data, employing the DGL framework with a PyTorch backend [Wang et al., 2019][ref-dgl-2019], [Paszke et al., 2019][ref-pytorch-2019]. A fully connected graph is constructed for each event, with nodes corresponding to reconstructed jets, electrons, muons, photons, and \\(\vec{E}_T^{\text{miss}}\\). The features of each node include the four-momentum \\((p_T, \eta, \phi, E)\\) of the object with a massless assumption (\\(E = p_T \cosh \eta\\)), the b-tagging label (for jets), the charge (for leptons), and an integer labeling the type of object represented by the node. We use a placeholder value of 0 for features which are not defined for every node type such as the b-jet tag, lepton charge, or the pseudorapidity of \\(\vec{E}_T^{\text{miss}}\\). We assign the angular distances (\\(\Delta \eta, \Delta \phi, \Delta R\\)) as edge features and the number of nodes $N$ in the graph as a global feature. We denote the node features \\(\{\vec x_i\}\\), edge features \\(\{\vec y_{ij}\}\\), and global features \\(\{\vec z\}\\).
77
-
78
- The GNN model is based on the graph network architecture described in [Battaglia et al., 2018][ref-graphnets-2018] using simple multilayer perceptron (MLP) feature functions and summation aggregation. The model is comprised of three primary components: an encoder, the graph network, and a decoder. In the encoder, three MLPs embed the nodes, edges, and global features into a latent space of dimension 64. The graph network block, which is designed to facilitate message passing between different domains of the graph, performs an edge update $f_e$, followed by a node update $f_n$, and finally a global update $f_g$, all defined below. The inputs to each update MLP are concatenated.
79
-
80
- $$
81
- \vec {y'}_{ij} = f_e\left(\{\vec x_k\},\vec y_{ij},\vec z\right) = \mathrm{MLP}\left(\vec x_i,\vec x_j,\vec y_{ij},\vec z\right)
82
- $$
83
-
84
- $$
85
- \vec{x'}_{i} = f_n\left(\vec x_i,\{\vec{y'}_{jk}\},\vec z\right) = \mathrm{MLP}\left(\vec x_i,\sum_j\vec{y'}_{ij},\vec z\right)
86
- $$
87
-
88
- $$
89
- \vec{z'} = f_g\left(\{\vec{x'}_i\},\{\vec{y'}_{ij}\},\vec z\right) = \mathrm{MLP}\left(\sum_i\vec{x'}_i,\sum_{i,j}\vec{y'}_{ij},\vec z\right)
90
- $$
91
-
92
- This graph block is iterated four times with the same update MLPs. Finally, the global features are passed through a decoder MLP and a final layer linear to produce the desired model outputs. Each MLP consists of 4 linear layers, each with an output width of 64, with the `ReLU` activation function. The output of the MLP is then passed through a `LayerNorm` layer [Ba et al., 2016][ref-layernorm-2016]. The total number of trainable parameters in this model is about 400,000.
93
-
94
- As a performance benchmark, a baseline GNN model is trained from scratch for each classification task. The initial learning rate is set to \\(10^{-4}\\) with an exponential decay following \\(LR(x) = LR_{\text{initial}}\cdot(0.99)^x\\), where \\(x\\) represents the epoch number.
95
-
96
- ---
97
-
98
- ### Pretraining Strategy
99
-
100
- We explore two complementary pretraining approaches to develop robust representations of collision events: (1) multi-class classification, which trains the model to distinguish between different physics processes, and (2) multi-label classification, which predicts the existence and kinematics of heavy particles with prompt decays. The pretraining dataset consists of approximately 120 million events, evenly distributed across 12 distinct physics processes, including all major Higgs boson production mechanisms and top quark processes as described in [Data Samples](#sec-data). This large-scale pretraining effort was conducted on the Perlmutter supercomputer at NERSC.
101
-
102
- #### Multi-class Classification
103
-
104
- For Monte Carlo simulated events, the underlying physics process that generated each event is known precisely, providing natural labels for supervised learning. However, the challenge lies in the complexity of collision events: different physics processes can produce similar kinematics and event topologies, particularly in certain regions of phase space. No single observable can unambiguously identify the underlying process. By training the model to distinguish between 12 different processes simultaneously, we challenge it to learn subtle differences in kinematics and topology that collectively characterize each process. The model is trained using categorical cross entropy as the loss function. The output layer of the multiclass classification model has 832 trainable parameters.
105
-
106
- #### Multi-label Classification
107
-
108
- This approach combines both classification and regression tasks to characterize collision events. For discrete properties like particle presence in specific kinematic regions, we employ classification labels with binary cross-entropy loss. For continuous quantities like particle multiplicities, we use regression labels with mean-squared error loss. This hybrid approach enables the model to learn both categorical and continuous aspects of the physics processes simultaneously.
109
-
110
- We develop a comprehensive set of 41 labels that capture both particle multiplicities and kinematic properties. This approach increases prediction granularity and enhances model interpretability. By training the model to predict event kinematics rather than event identification, we create a task-independent framework that can potentially generalize better to novel scenarios not seen during pretraining.
111
-
112
- The particle multiplicity labels count the number of Higgs bosons (\\(n_{\text{higgs}}\\)), top quarks (\\(n_{\text{tops}}\\)), vector bosons (\\(n_V\\)), \\(W\\) bosons (\\(n_W\\)), and \\(Z\\) bosons (\\(n_Z\\)). The kinematic labels characterize the transverse momentum (\\(p_T\\)), pseudorapidity (\\(\eta\\)), and azimuthal angle (\\(\phi\\)) of Higgs bosons and top quarks through binned classifications.
113
-
114
- For Higgs bosons, $p_T$ is categorized into three ranges: (0, 30) GeV, (30, 200) GeV, and (200, \\(\infty\\)) GeV, with the upper range particularly sensitive to potential BSM effects. Similarly, both leading and subleading top quarks have $p_T$ classifications spanning (0, 30) GeV, (30, 300) GeV, and (300, \\(\infty\\)) GeV. When no particle exists within a specific \\(p_T\\) range, the corresponding label is set to \\([0, 0, 0]\\). For all particles, \\(\eta\\) measurements are divided into 4 bins with boundaries at \\([-1.5, 0, 1.5]\\), while \\(\phi\\) measurements use 4 bins with boundaries at \\([-\frac{\pi}{2}, 0, \frac{\pi}{2}]\\). As with \\(p_T\\), both \\(\eta\\) and \\(\phi\\) labels default to \\([0, 0, 0, 0]\\) in the absence of a particle. This comprehensive labeling schema enables fine-grained learning of kinematic distributions and particle multiplicities, essential for characterizing complex collision events.
115
-
116
- The loss function combines individual losses from all 41 labels through weighted averaging. Binary cross-entropy is applied to classification labels, while mean-squared error is used for regression labels. The model generates predictions for all labels simultaneously, with individual losses calculated according to their respective types. The final loss is computed as an equally-weighted average across all labels, with weights set to 1 to ensure uniform contribution to the optimization process. The output layer of the multilabel model has 2,688 trainable parameters.
117
-
118
- #### Pretraining
119
-
120
- During pre-training, the initial learning rate is \\(10^{-4}\\), and the learning rate decays by 1% each epoch following the power law function \\(LR(x) = 10^{-4}\cdot(0.99)^x\\), where \\(x\\) is the number of epochs. Both pre-trained models reach a plateau in loss by epoch 50, at which point the training is stopped.
121
-
122
- ---
123
- ### Fine-tuning Methodology
124
-
125
- For downstream tasks, we adjust the model architecture for fine-tuning by replacing the original output layer (final linear layer) with a newly initialized linear layer while retaining the pre-trained weights for all other layers. This modification allows the model to specialize in the specific downstream task while leveraging the general features learned during pretraining.
126
-
127
- The fine-tuning process begins with distinct learning rate setups for different parts of the model. The newly initialized linear layer is trained with an initial learning rate of \\(10^{-4}\\), matching the rate used for models trained from scratch. Meanwhile, the pre-trained layers are fine-tuned more cautiously with a lower initial learning rate of \\(10^{-5}\\). This approach ensures that the pre-trained layers adapt gradually without losing their general features, while the new layer learns effectively from scratch. Both learning rates decay over time following the same power law function, \\(LR(x) = LR_{initial} \cdot (0.99)^x\\), to promote stable convergence as training progresses.
128
-
129
- We also evaluated a transfer learning setup in which either the decoder MLP or the final linear layer was replaced with a newly initialized component. During this process, all other model parameters remained frozen, leveraging the pre-trained features without further updating them. However, we did not observe performance improvements using the transfer learning setup. Consequently, we focus on reporting results obtained with the fine-tuning approach.
130
-
131
- ---
132
-
133
- ### Performance Evaluation
134
-
135
- We assess model performance using two figures of merit: the classification accuracy and the Area Under the Curve (AUC) of the Receiver Operating Characteristic (ROC) curve. The accuracy is defined as the fraction of correctly classified events when applying a threshold of 0.5 to the neural network output score. Both metrics demonstrate consistent trends in our analysis.
136
-
137
- To obtain reliable performance estimates and uncertainties, we employ an ensemble training approach where 5 independent models are trained for each configuration with random weight initialization and random subsets of the training dataset. This enables us to evaluate both the models' sensitivity to initial parameters and to quantify uncertainties in their performance.
138
-
139
- To investigate how model performance scales with training data, we conducted training runs using sample sizes ranging from \\(10^3\\) to \\(10^7\\) events per class (\\(10^3\\), \\(10^4\\), \\(10^5\\), \\(10^6\\), and \\(10^7\\)) for each model setup: the from-scratch baseline and models fine-tuned from multi-class or multi-label pretrained models. For the \\(10^7\\) case, only the initialization was randomized due to dataset size limitations. All models were evaluated on the same testing dataset, consisting of 2 million events per class, which remained separate from the training process.
140
-
141
- | **Name of Task** | **Pretraining Task** | \\(10^3\\) | \\(10^4\\) | \\(10^5\\) | \\(10^6\\) | \\(10^7\\) |
142
- |----------------------|----------------------|--------------------|--------------------|--------------------|--------------------|--------------------|
143
- | **ttH CP Even vs Odd** | Baseline Accuracy | 56.5 Β± 1.1 | 62.2 Β± 0.1 | 64.3 Β± 0.0 | 65.7 Β± 0.0 | 66.2 Β± 0.0 |
144
- | | Multiclass (%) | +4.8 Β± 1.1 | +3.4 Β± 0.1 | +1.3 Β± 0.0 | +0.2 Β± 0.0 | βˆ’0.0 Β± 0.0 |
145
- | | Multilabel (%) | +2.1 Β± 1.2 | +1.9 Β± 0.1 | +0.8 Β± 0.1 | +0.0 Β± 0.0 | βˆ’0.1 Β± 0.0 |
146
- | **FCNC vs tHq** | Baseline Accuracy | 63.6 Β± 0.7 | 67.8 Β± 0.4 | 68.4 Β± 0.3 | 69.3 Β± 0.3 | 67.9 Β± 0.0 |
147
- | | Multiclass (%) | +5.8 Β± 0.8 | +1.2 Β± 0.4 | +1.4 Β± 0.3 | +0.5 Β± 0.3 | βˆ’0.0 Β± 0.0 |
148
- | | Multilabel (%) | βˆ’5.3 Β± 0.8 | βˆ’1.3 Β± 0.4 | +0.9 Β± 0.4 | +0.3 Β± 0.3 | +0.4 Β± 0.1 |
149
- | **ttW vs ttt** | Baseline Accuracy | 75.8 Β± 0.1 | 77.6 Β± 0.1 | 78.9 Β± 0.0 | 79.8 Β± 0.0 | 80.3 Β± 0.0 |
150
- | | Multiclass (%) | +3.7 Β± 0.1 | +2.7 Β± 0.1 | +1.3 Β± 0.0 | +0.4 Β± 0.0 | +0.0 Β± 0.0 |
151
- | | Multilabel (%) | +2.2 Β± 0.1 | +1.1 Β± 0.1 | +0.5 Β± 0.0 | +0.0 Β± 0.0 | βˆ’0.1 Β± 0.0 |
152
- | **stop vs ttH** | Baseline Accuracy | 83.0 Β± 0.2 | 86.3 Β± 0.1 | 87.6 Β± 0.0 | 88.5 Β± 0.0 | 88.8 Β± 0.0 |
153
- | | Multiclass (%) | +0.4 Β± 0.2 | +1.9 Β± 0.1 | +1.0 Β± 0.0 | +0.3 Β± 0.0 | +0.0 Β± 0.0 |
154
- | | Multilabel (%) | +2.8 Β± 0.2 | +1.0 Β± 0.1 | +0.5 Β± 0.0 | +0.0 Β± 0.0 | βˆ’0.0 Β± 0.0 |
155
- | **WH vs ZH** | Baseline Accuracy | 51.4 Β± 0.1 | 53.9 Β± 0.1 | 55.8 Β± 0.0 | 57.5 Β± 0.0 | 58.0 Β± 0.0 |
156
- | | Multiclass (%) | +5.2 Β± 0.1 | +5.3 Β± 0.1 | +3.1 Β± 0.0 | +0.6 Β± 0.0 | +0.1 Β± 0.0 |
157
- | | Multilabel (%) | βˆ’1.1 Β± 0.1 | βˆ’0.9 Β± 0.2 | +0.5 Β± 0.1 | +0.1 Β± 0.0 | βˆ’0.1 Β± 0.0 |
158
-
159
- > **Table 1**: Accuracy of the traditional model versus the accuracy increase due to fine-tuning from various pretraining tasks.
160
- > The accuracies are averaged over 5 independently trained models with randomly initialized weights and trained on a random subset of the data. One exception is the \\(10^7\\) training where all models use the same dataset due to limitations on our dataset size. The random subsets are allowed to overlap, but this overlap should be very minimal because all models take an independent random subset of \\(10^7\\) events. The testing accuracy is calculated from the same testing set of 2 million events per class across all models for a specific training task. The errors are the propagated errors (root sum of squares) of the standard deviation of accuracies for each model.
161
-
162
- ## Results
163
-
164
- ### Classification Performance
165
-
166
- Since the observations of AUC and accuracy show similar trends, we focus the presentation of the results using accuracy here for conciseness in Table 1.
167
-
168
- In general, the fine-tuned pretrained model achieves at least the same level of classification performance as the baseline model. Notably, there are significant improvements, particularly when the sample size is small, ranging from \\(10^3\\) to \\(10^4\\) events. In some cases, the accuracy improvements exceed five percentage points, demonstrating that pretrained models provide a strong initial representation that compensates for limited data. The numerical values of the improvements in accuracy may not fully capture the impact on the sensitivity of the measurements for which the neural network classifier is used, and the final sensitivity improvement is likely to be greater.
169
-
170
- As the training sample size grows to \\(10^5\\), \\(10^6\\), and eventually \\(10^7\\) events, the added benefit of pretraining diminishes. With abundant data, models trained from scratch approach or even match the accuracy of fine-tuned pretrained models. This suggests that large datasets enable effective learning from scratch, rendering the advantage of pretraining negligible in such scenarios.
171
-
172
- Although both pretraining approaches offer benefits, multiclass pretraining tends to provide more consistent improvements across tasks, especially in the low-data regime. In contrast, multilabel pretraining can sometimes lead to neutral or even slightly negative effects for certain tasks and data sizes. This highlights the importance of the pretraining task design, as the similarity between pretraining and fine-tuning tasks in the multiclass approach appears to yield better-aligned representations.
173
-
174
- Finally, the spread of accuracy across the five tasks for the baseline model is quite large, offering a robust test of fine-tuning across tasks of varying difficulty. The consistent observation of these trends across tasks confirms the reliability and robustness of the findings.
175
-
176
- ---
177
-
178
- ### Model Interpretability
179
-
180
- We aim to understand whether pretrained and baseline models learn the same underlying representations. If the two models exhibit high similarity, a plausible interpretation is that pretraining provides the pretrained model with an advantageous initialization, allowing it to converge to a similar state as the baseline model more efficiently. Conversely, significant differences between the models would indicate that pretraining facilitates the development of a more general and robust latent space, which serves as a foundation for fine-tuning to effectively adapt to the downstream task. To investigate this, we analyzed the representational similarity between a pretrained model fine-tuned for the downstream task and a baseline model trained directly on the downstream task without pretraining.
181
-
182
- We use Centered Kernel Alignment (CKA) [Kornblith et al., 2019][ref-kornblith-2019-cka] to analyze model similarity and interpretability. CKA is a robust metric that quantifies the similarity between the internal representations of neural networks by comparing their feature matrices in a manner that is invariant to scaling, rotation, and alignment. This invariance makes CKA particularly effective for studying relationships between network layers, even across networks of different sizes or those trained from varying initializations.
183
-
184
- The similarity is evaluated using a 64-dimensional latent representation after the decoder stage of the GNN model. This choice allows us to compare the internal states of the models at a fine-grained level and understand how training strategies impact the representations directly used for the output task.
185
-
186
- To provide an intuitive understanding of CKA values, we construct a table of the CKA scores for various transformations performed on a set of dummy data.
187
-
188
- - **A:** randomly initialized matrix with shape (1000, 64), following a normal distribution (\\(\sigma = 1, \mu = 0\\))
189
- - **B:** matrix with shape (1000, 64) constructed via various transformations performed on \\(A\\)
190
- - **Noise:** randomly initialized noise matrix with shape (1000, 64), following a normal distribution (\\(\sigma = 1, \mu = 0\\))
191
-
192
- | Dataset | CKA Score |
193
- |---------|-----------|
194
- | \\(A, B = A\\) | 1.00 |
195
- | \\(A, B =\\) permutation on columns of \\(A\\) | 1.00 |
196
- | \\(A, B = A + \mathrm{Noise}(0.1)\\) | 0.99 |
197
- | \\(A, B = A + \mathrm{Noise}(0.5)\\) | 0.80 |
198
- | \\(A, B = A + \mathrm{Noise}(0.75)\\) | 0.77 |
199
- | \\(A, B = A \cdot \mathrm{Noise}(1)\\) (Linear Transformation) | 0.76 |
200
- | \\(A, B = A + \mathrm{Noise}(1)\\) | 0.69 |
201
- | \\(A, B = A + \mathrm{Noise}(2)\\) | 0.51 |
202
- | \\(A, B = A + \mathrm{Noise}(5)\\) | 0.39 |
203
-
204
- **Table 2:** CKA scores for a dummy dataset \\(A\\) and \\(B\\), where \\(B\\) is created via various transformations performed on \\(A\\).
205
-
206
- As seen in Table 2 and in the definition of the CKA, the CKA score is permutation-invariant. We will use the CKA score to evaluate the similarity between various models and gain insight into the learned representation of detector events in each model (i.e., the information that each model learns).
207
-
208
- We train ensembles of models for each training task to observe how the CKA score changes due to the random initialization of our models. The CKA score between two models is then defined to be:
209
-
210
- \\[
211
- CKA(A, B) = \frac{1}{n^2} \sum_i^n \sum_j^n CKA(A_i, B_j)
212
- \\]
213
-
214
- where \\(A_i\\) is the representation learned by the \\(i^{\text{th}}\\) model in an ensemble with \\(n\\) total models. The error in CKA is the standard deviation of \\(CKA(A_i, B_j)\\).
215
-
216
- Here we present results for the CKA similarity between the final model in each setup with the final model in the baseline, shown in Table 3.
217
-
218
- | Training Task | Baseline | Multiclass | Multilabel |
219
- |-----------------------|------------------|-----------------|-----------------|
220
- | ttH CP Even vs Odd | 0.94 Β± 0.05 | 0.82 Β± 0.01 | 0.77 Β± 0.06 |
221
- | FCNC vs tHq | 0.96 Β± 0.03 | 0.76 Β± 0.01 | 0.81 Β± 0.01 |
222
- | ttW vs ttt | 0.91 Β± 0.08 | 0.75 Β± 0.10 | 0.72 Β± 0.05 |
223
- | stop vs ttH | 0.87 Β± 0.11 | 0.79 Β± 0.12 | 0.71 Β± 0.08 |
224
- | WH vs ZH | 0.90 Β± 0.07 | 0.53 Β± 0.03 | 0.44 Β± 0.06 |
225
-
226
- **Table 3:** CKA Similarity of the latent representation before the decoder with the baseline model, averaged over 3 models per training setup, and all models trained with the full dataset (\\(10^7\\)). The baseline column is not guaranteed to be 1.0 because of the random initialization of the model. Each baseline model converges to a slightly different representation as seen in the CKA values in that column.
227
-
228
- The baseline models with different initializations exhibit high similarity values, ranging from approximately 0.87 to 0.96, which indicates that independently trained baseline models tend to converge on similar internal representations despite random initialization. Across the considered tasks, models trained as multi-class or multi-label classifiers exhibit noticeably lower CKA similarity scores when compared to the baseline model. For example, in the WH vs ZH task, the baseline model and another baseline trained model have a high similarity of 0.90, whereas the multi-class and multi-label models show significantly reduced similarities (0.53 and 0.44, respectively). This pattern suggests that the representational spaces developed by multi-class or multi-label models differ substantially from those learned by the baseline model that was trained directly on the downstream classification task.
229
-
230
- ### Computational Efficiency
231
-
232
- To estimate the computational resources required for each approach, we measured the wall time needed for a model to reach its final performance. For baseline models, this is defined as the wall time from the start of training until the loss of the model plateaus. For the foundation model approach, the estimate includes both the pretraining time and the fine-tuning time, each measured from the start of training until the loss plateaus. This approach ensures a consistent and comprehensive evaluation of the computational demands.
233
-
234
- ![The ratio of the fine-tuning time required to achieve 99% of the baseline model's final classification accuracy to the total time spent training the baseline model.](training_time.png)
235
- *Fig. 1: The ratio of the fine-tuning time required to achieve 99% of the baseline model's final classification accuracy to the total time spent training the baseline model.*
236
-
237
- Figure 1 shows the fine-tuning time for the model pretrained with multiclass classification, relative to the time required for the baseline model, as a function of training sample size. In general, the fine-tuning time is significantly shorter than the training time required by the baseline model approach. For smaller training sets, on the order of \\(10^5\\) events, tasks such as FCNC vs. tHq and ttW vs. ttt benefit substantially from the pretrained model’s β€œhead start,” achieving their final performance in only about 1% of the baseline time. For large training datasets, the fine-tuning time relative to the baseline training time becomes larger; however, given that the large training sample typically requires longer training time, fine-tuning still yields much faster training convergence. The ttH CP-even vs. ttH CP-odd task, with a training sample size of \\(10^7\\) events, is an exception where the fine-tuning time exceeds the training time required for the baseline model. This is likely because the processes involved in this task include photon objects in the final states, which are absent from the events used during pretraining.
238
-
239
- To accurately evaluate the total time consumption, it is necessary to include the pretraining time required for the foundation model approach. The pretraining times are as follows:
240
-
241
- - **Multi-class pretraining:** 45.5 GPU hours
242
- - **Multi-label pretraining:** 60.0 GPU hours
243
-
244
- The GPU hours recorded for the multi-label model represent the total time required when training the model in parallel on 16 GPUs. This includes a model synchronization step, which results in higher GPU hours compared to the multi-class pretraining model.
245
-
246
- The foundation model approach becomes increasingly efficient when a large number of tasks are fine-tuned using the same pretrained model, compared to training each task independently from scratch. To illustrate this, we evaluate the computational time required for a scenario where the training sample contains \\(10^7\\) events. For the five tasks tested in this study, the baseline training time (training from scratch) ranges from 1.68 GPU hours (WH vs. ZH) to 5.30 GPU hours (ttW vs. ttt), with an average baseline training time of 2.94 GPU hours. In contrast, the average fine-tuning time for the foundation model approach, relative to the baseline, is 38% of the baseline training time for \\(10^7\\) events. Based on these averages, we estimate that the foundation model approach becomes more computationally efficient than the baseline approach when fine-tuning is performed for more than 41 tasks.
247
-
248
- As a practical example, the ATLAS measurement of Higgs boson couplings using the \\(H \rightarrow \gamma\gamma\\) decay channel [ATLAS Collaboration, 2023][ref-atlas-2023-higg] involved training 42 classifiers for event categorization. This coincides with our estimate, suggesting that the foundation model approach can reduce computational costs even for a single high-energy physics measurement.
249
-
250
- ## Conclusions
251
-
252
- We presented an in-depth study of a particle physics foundation model designed to operate on the four-momentum and identification properties of event final-state objects. This model is built on a Graph Neural Network (GNN) architecture and trained on a dataset comprising 120 million simulated proton-proton collision events across 12 distinct physics processes. The pretraining phase explored both multiclass and multilabel classification tasks, providing a robust foundation for downstream applications. Notably, the pretrained models demonstrated significant improvements in event classification performance when fine-tuned, particularly for tasks with limited training samples.
253
-
254
- The foundation model approach also offers substantial computational advantages. By leveraging fine-tuning, this methodology reduces the computational resources required for large-scale applications across multiple tasks. Our estimates indicate that significant resource savings can be achieved even for single particle physics measurements, making this approach both scalable and efficient.
255
-
256
- To better understand the learned representations of the pretrained model and guide future optimization efforts, we employed a representational similarity evaluation framework using Centered Kernel Alignment (CKA). This metric allowed us to investigate the source of the performance gains observed in the foundation model. Our analysis revealed notable differences in the learned representations between the fine-tuned pretrained model and a baseline model trained from scratch. In deep learning, it is well-established that multiple equally valid solutions can exist. Future studies are necessary to determine whether the low similarity in latent representations reflects complementary information uniquely captured by the foundation and baseline models, or if it can simply be attributed to connected local minima in the loss landscape.
257
-
258
- ## Acknowledgments
259
-
260
- This work is supported by the U.S. National Science Foundation under the Award No. 2046280, and by U.S. Department of Energy, Office of Science under contract DE-AC02-05CH11231.
261
-
262
- ## References
263
-
264
- - <span id="ref-openai-2024-gpt4"></span> **OpenAI et al.** GPT-4 Technical Report. arXiv:2303.08774 (2024). [https://arxiv.org/abs/2303.08774](https://arxiv.org/abs/2303.08774)
265
-
266
- - <span id="ref-yosinski-2014-transfer"></span> **Jason Yosinski, Jeff Clune, Yoshua Bengio, Hod Lipson.** How transferable are features in deep neural networks? CoRR abs/1411.1792 (2014). [http://arxiv.org/abs/1411.1792](http://arxiv.org/abs/1411.1792)
267
-
268
- - <span id="ref-rombach-2021-latentdiffusion"></span> **Robin Rombach, Andreas Blattmann, Dominik Lorenz, Patrick Esser, BjΓΆrn Ommer.** High-Resolution Image Synthesis with Latent Diffusion Models. CoRR abs/2112.10752 (2021). [https://arxiv.org/abs/2112.10752](https://arxiv.org/abs/2112.10752)
269
-
270
- - <span id="ref-podell-2023-sdxl"></span> **Dustin Podell, Zion English, Kyle Lacey et al.** SDXL: Improving Latent Diffusion Models for High-Resolution Image Synthesis. arXiv:2307.01952 (2023). [https://arxiv.org/abs/2307.01952](https://arxiv.org/abs/2307.01952)
271
-
272
- - <span id="ref-jumper-2021-alphafold"></span> **John Jumper, Richard Evans, Alexander Pritzel et al.** Highly accurate protein structure prediction with AlphaFold. Nature 596, 583-589 (2021). [https://doi.org/10.1038/s41586-021-03819-2](https://doi.org/10.1038/s41586-021-03819-2)
273
-
274
- - <span id="ref-devlin-2018-bert"></span> **Jacob Devlin, Ming-Wei Chang, Kenton Lee, Kristina Toutanova.** BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. CoRR abs/1810.04805 (2018). [http://arxiv.org/abs/1810.04805](http://arxiv.org/abs/1810.04805)
275
-
276
- - <span id="ref-atlas-2023-higg"></span> **ATLAS Collaboration.** Measurement of the properties of Higgs boson production at \\(\sqrt{s} = 13\,\text{TeV}\\) in the \\(H \to \gamma\gamma\\) channel using \\(139\,\text{fb}^{-1}\\) of \\(pp\\) collision data with the ATLAS experiment. JHEP 07 (2023) 088. [arXiv:2207.00348](https://arxiv.org/abs/2207.00348), [https://doi.org/10.1007/JHEP07(2023)088](https://doi.org/10.1007/JHEP07(2023)088)
277
-
278
- - <span id="ref-atlas-2023-4top"></span> **ATLAS Collaboration.** Observation of four-top-quark production in the multilepton final state with the ATLAS detector. Eur. Phys. J. C 83 (2023) 496. [arXiv:2303.15061](https://arxiv.org/abs/2303.15061), [https://doi.org/10.1140/epjc/s10052-023-11573-0](https://doi.org/10.1140/epjc/s10052-023-11573-0)
279
-
280
- - <span id="ref-kornblith-2019-cka"></span> **Simon Kornblith, Mohammad Norouzi, Honglak Lee, Geoffrey Hinton.** Similarity of Neural Network Representations Revisited. CoRR abs/1905.00414 (2019). [http://arxiv.org/abs/1905.00414](http://arxiv.org/abs/1905.00414)
281
-
282
- ---
283
-
284
- <!-- Historical/General Physics foundational texts -->
285
-
286
- - <span id="ref-birell-1982-qfields"></span> **N. D. Birell, P. C. W. Davies.** Quantum Fields in Curved Space. Cambridge Univ. Press (1982).
287
-
288
- - <span id="ref-feynman-1954"></span> **R. P. Feynman.** Phys. Rev. 94, 262 (1954).
289
-
290
- - <span id="ref-einstein-1935-epr"></span> **A. Einstein, Yu. Podolsky, N. Rosen.** Phys. Rev. 47, 777 (1935).
291
-
292
- - <span id="ref-berman-1983-stability"></span> **G. P. Berman, Jr., F. M. Izrailev, Jr.** Stability of nonlinear modes. Physica D 88, 445 (1983).
293
-
294
- - <span id="ref-davies-1988-trapped"></span> **E. B. Davies, L. Parns.** Trapped modes in acoustic waveguides. Q. J. Mech. Appl. Math. 51, 477–492 (1988).
295
-
296
- - <span id="ref-witten-2001"></span> **Edward Witten.** hep-th/0106109 (2001). [https://arxiv.org/abs/hep-th/0106109](https://arxiv.org/abs/hep-th/0106109)
297
-
298
- ---
299
-
300
- <!-- Particle physics/data science foundational models -->
301
-
302
- - <span id="ref-beutler-1994-hem"></span> **E. Beutler.** Williams Hematology, 5th Edition, Chapter 7, pp. 654–662. McGraw-Hill, New York (1994).
303
-
304
- - <span id="ref-knuth-1973-fa"></span> **Donald E. Knuth.** The Art of Computer Programming vol. 1: Fundamental Algorithms, 2nd Ed., Addison-Wesley (1973).
305
-
306
- - <span id="ref-smith-2005-philos"></span> **J. S. Smith, G. W. Johnson.** Philos. Trans. R. Soc. London, Ser. B 777, 1395 (2005).
307
-
308
- - <span id="ref-smith-2010-jap-unpub"></span> **W. J. Smith, T. J. Johnson, B. G. Miller.** Surface chemistry and preferential crystal orientation on a silicon surface. J. Appl. Phys. (unpublished, 2010).
309
-
310
- - <span id="ref-smith-2010-jap-sub"></span> **V. K. Smith, K. Johnson, M. O. Klein.** Surface chemistry and preferential crystal orientation on a silicon surface. J. Appl. Phys. (submitted, 2010).
311
-
312
- - <span id="ref-underwood-1988-lowerbounds"></span> **Ulrich Underwood, Ned Net, Paul Pot.** Lower Bounds for Wishful Research Results. Talk at Fanstord University (1988).
313
-
314
- - <span id="ref-johnson-2007-comm"></span> **M. P. Johnson, K. L. Miller, K. Smith.** Personal communication (Jan-May 2007).
315
-
316
- ---
317
-
318
- <!-- Prototypical collider software and tools -->
319
-
320
- - <span id="ref-pytorch-2019"></span> **Adam Paszke et al.** PyTorch: An Imperative Style, High-Performance Deep Learning Library. arXiv:1912.01703 (2019). [http://arxiv.org/abs/1912.01703](http://arxiv.org/abs/1912.01703)
321
-
322
- - <span id="ref-dgl-2019"></span> **Minjie Wang et al.** Deep Graph Library: Towards Efficient and Scalable Deep Learning on Graphs. arXiv:1909.01315 (2019). [http://arxiv.org/abs/1909.01315](http://arxiv.org/abs/1909.01315)
323
-
324
- - <span id="ref-graphnets-2018"></span> **Peter W. Battaglia et al.** Relational inductive biases, deep learning, and graph networks. arXiv:1806.01261 (2018). [http://arxiv.org/abs/1806.01261](http://arxiv.org/abs/1806.01261)
325
-
326
- - <span id="ref-layernorm-2016"></span> **Jimmy Lei Ba, Jamie Ryan Kiros, Geoffrey E. Hinton.** Layer Normalization. arXiv:1607.06450 (2016). [https://arxiv.org/abs/1607.06450](https://arxiv.org/abs/1607.06450)
327
-
328
- ---
329
-
330
- <!-- Recent & foundation models in HEP ML -->
331
-
332
- - <span id="ref-wildridge-2024-bumblebee"></span> **Andrew J. Wildridge et al.** Bumblebee: Foundation Model for Particle Physics Discovery. arXiv:2412.07867 (2024). [https://arxiv.org/abs/2412.07867](https://arxiv.org/abs/2412.07867)
333
-
334
- - <span id="ref-katel-2024-jet"></span> **Subash Katel et al.** Learning Symmetry-Independent Jet Representations via Jet-Based Joint Embedding Predictive Architecture. arXiv:2412.05333 (2024). [https://arxiv.org/abs/2412.05333](https://arxiv.org/abs/2412.05333)
335
-
336
- - <span id="ref-araz-2024-pointcloud"></span> **Jack Y. Araz et al.** Point cloud-based diffusion models for the Electron-Ion Collider. arXiv:2410.22421 (2024). [https://arxiv.org/abs/2410.22421](https://arxiv.org/abs/2410.22421)
337
-
338
- - <span id="ref-leigh-2024-maskedparticle"></span> **Matthew Leigh et al.** Is Tokenization Needed for Masked Particle Modelling? arXiv:2409.12589 (2024). [https://arxiv.org/abs/2409.12589](https://arxiv.org/abs/2409.12589)
339
-
340
- - <span id="ref-mikuni-2024-omnilearn"></span> **Vinicius Mikuni, Benjamin Nachman.** OmniLearn: A Method to Simultaneously Facilitate All Jet Physics Tasks. arXiv:2404.16091 (2024). [https://arxiv.org/abs/2404.16091](https://arxiv.org/abs/2404.16091)
341
-
342
- - <span id="ref-zhang-2024-xiwu"></span> **Zhengde Zhang et al.** Xiwu: A Basis Flexible and Learnable LLM for High Energy Physics. arXiv:2404.08001 (2024). [https://arxiv.org/abs/2404.08001](https://arxiv.org/abs/2404.08001)
343
-
344
- - <span id="ref-harris-2024-resimulation"></span> **Philip Harris et al.** Re-Simulation-based Self-Supervised Learning for Pre-Training Foundation Models. arXiv:2403.07066 (2024). [https://arxiv.org/abs/2403.07066](https://arxiv.org/abs/2403.07066)
345
-
346
- - <span id="ref-birk-2024-omnijet"></span> **Joschka Birk, Anna Hallin, Gregor Kasieczka.** OmniJet-$\alpha$: the first cross-task foundation model for particle physics. Machine Learning: Science and Technology. 5(3), 035031 (Aug 2024). [https://doi.org/10.1088/2632-2153/ad66ad](https://doi.org/10.1088/2632-2153/ad66ad)
347
-
348
- - <span id="ref-huang-2024-lmtracking"></span> **Andris Huang et al.** A Language Model for Particle Tracking. arXiv:2402.10239 (2024). [https://arxiv.org/abs/2402.10239](https://arxiv.org/abs/2402.10239)
349
-
350
- - <span id="ref-golling-2024-maskedset"></span> **Tobias Golling et al.** Masked Particle Modeling on Sets: Towards Self-Supervised High Energy Physics Foundation Models. arXiv:2401.13537 (2024). [https://arxiv.org/abs/2401.13537](https://arxiv.org/abs/2401.13537)
351
-
352
- - <span id="ref-liu-2023-gaam"></span> **Junze Liu et al.** Generalizing to new geometries with Geometry-Aware Autoregressive Models (GAAMs) for fast calorimeter simulation. Journal of Instrumentation 18(11), P11003 (Nov 2023). [https://doi.org/10.1088/1748-0221/18/11/p11003](https://doi.org/10.1088/1748-0221/18/11/p11003)
353
-
354
- - <span id="ref-hashemi-2024-gen"></span> **Baran Hashemi et al.** Ultra-high-granularity detector simulation with intra-event aware generative adversarial network and self-supervised relational reasoning. Nature Communications 15(1) (June 2024). [https://doi.org/10.1038/s41467-024-49104-4](https://doi.org/10.1038/s41467-024-49104-4)
355
-
356
- - <span id="ref-vigl-2024-finetune"></span> **Matthias Vigl et al.** Finetuning Foundation Models for Joint Analysis Optimization. arXiv:2401.13536 (2024). [https://arxiv.org/abs/2401.13536](https://arxiv.org/abs/2401.13536)
357
-
358
- - <span id="ref-li-2024-refine"></span> **Chen Li, Hao Cai, Xianyang Jiang.** Refine neutrino events reconstruction with BEiT-3. Journal of Instrumentation 19(6), T06003 (Jun 2024). [https://doi.org/10.1088/1748-0221/19/06/t06003](https://doi.org/10.1088/1748-0221/19/06/t06003)
 
1
+ # GNN4Colliders
2
+
3
+ GNN4Colliders is a collider-machine-learning toolkit. The repository name
4
+ reflects its first production model family, ROOT-GNN; the Python package is
5
+ `gnn4colliders`, and the configuration identifier is `root_gnn`. Shared ROOT
6
+ ingestion, collider features, metadata, tasks, training, inference, and
7
+ distributed utilities are designed so that a future sequence model can reuse
8
+ them without requiring every event to be a graph.
9
+
10
+ ```text
11
+ ROOT files -> EventSample -> shared collider features
12
+ β”œβ”€β”€ GraphSample -> ROOT-GNN
13
+ └── future SequenceSample -> ROOT-Transformer
14
+ ```
15
+
16
+ The new implementation lives under [`src/gnn4colliders`](src/gnn4colliders/).
17
+ [`legacy/`](legacy/) is a frozen behavioral reference for parity work and
18
+ historical checkpoint investigation, not a supported runtime backend.
19
+
20
+ ## Installation
21
+
22
+ The supported development environment is Python 3.12 (`>=3.12,<3.13`), with
23
+ PyTorch 2.2.2 and the optional ROOT-GNN stack DGL 2.4.0. The canonical setup
24
+ is:
25
+
26
+ ```bash
27
+ uv sync --dev --extra root-gnn
28
+ ```
29
+
30
+ The core package can be installed without DGL when only shared data or task
31
+ code is needed. ROOT-GNN models, graph construction, and ROOT-GNN parity tests
32
+ require the `root-gnn` extra. The DGL extra uses the validated CUDA 12.1 wheel
33
+ source configured in `pyproject.toml`; a compatible NVIDIA driver is still
34
+ required. Do not add site-specific CUDA, Slurm, or filesystem paths to model
35
+ or task configuration.
36
+
37
+ ## Quick start
38
+
39
+ Prepare a graph cache from a ROOT tree. The feature specifications below are
40
+ illustrative placeholders; replace them with the branches in the input tree.
41
+ The full preparation interface is documented in
42
+ [`docs/configuration.md`](docs/configuration.md).
43
+
44
+ ```bash
45
+ uv run gnn4colliders prepare \
46
+ data.files=[data/events.root] \
47
+ data.tree_name=Events \
48
+ data.cache.path=cache/events.pt \
49
+ 'data.feature_branches=[["jet_pt"],["jet_eta"],["jet_phi"],CALC_E,[1.0],[0.0],NODE_TYPE]' \
50
+ data.object_types=[vector] \
51
+ data.scales=[1,1,1,1,1,1,1]
52
+ ```
53
+
54
+ Train, evaluate, and predict from that cache:
55
+
56
+ ```bash
57
+ uv run gnn4colliders train \
58
+ data.cache.path=cache/events.pt \
59
+ trainer.max_epochs=1 \
60
+ environment.output_root=outputs/pretraining_multiclass
61
+
62
+ uv run gnn4colliders evaluate \
63
+ data.cache.path=cache/events.pt \
64
+ inference.checkpoint=outputs/pretraining_multiclass/checkpoints/epoch_0000.pt
65
+
66
+ uv run gnn4colliders predict \
67
+ data.cache.path=cache/events.pt \
68
+ inference.checkpoint=outputs/pretraining_multiclass/checkpoints/epoch_0000.pt \
69
+ inference.output=outputs/pretraining_multiclass/predictions.npz
70
+ ```
71
+
72
+ For a dependency-complete, temporary-data version of this flow, run
73
+ `uv run python scripts/dev/smoke_end_to_end.py`.
74
+
75
+ ## Core concepts
76
+
77
+ `EventSample` is the architecture-neutral event boundary. It contains the
78
+ selected `objects`, `label`, `global_features`, and named `EventMetadata`.
79
+ Metadata includes `fold`, `weight`, and stable `sample_id`; callers should not
80
+ interpret public `tracking[:, N]` columns. Legacy tracking mappings exist only
81
+ at compatibility boundaries.
82
+
83
+ The ROOT-GNN adapter converts shared features to a directed, fully connected
84
+ graph with no self-loops: an event with `N` nodes has `N * (N - 1)` edges.
85
+ Node columns are, in order, `pt`, `eta`, `phi`, `energy`, `btag`, `charge`,
86
+ and `node_type`. Edge columns are `deta`, wrapped `dphi`, and `dR`.
87
+ Object collections are concatenated in configured object-type order. The
88
+ compatibility energy is `pt * cosh(eta)` before per-column scaling.
89
+
90
+ `GraphSampleCache` stores processed graph samples and schema metadata. It is a
91
+ Level-2 graph cache, not the universal event cache. Feature, graph, and cache
92
+ schema versions are checked when loading; incompatible versions fail before
93
+ training.
94
+
95
+ ## ROOT-GNN training and transfer
96
+
97
+ `EdgeNetwork` encodes node, edge, and global features, performs iterative
98
+ edge/node/global message passing, decodes a graph representation, and applies
99
+ the classifier. Its output is raw logits; sigmoid or softmax is task-owned.
100
+
101
+ Multiclass pretraining uses the semantic `model=root_gnn/edge_network` and
102
+ `task=pretraining_multiclass` groups:
103
+
104
+ ```bash
105
+ uv run gnn4colliders train \
106
+ data.cache.path=cache/events.pt \
107
+ model=root_gnn/edge_network task=pretraining_multiclass \
108
+ trainer.max_epochs=20 data.batch_size=64 \
109
+ environment.output_root=outputs/pretraining_multiclass
110
+ ```
111
+
112
+ Fine-tuning is a separate workflow. It loads a pretrained backbone, replaces
113
+ the classifier, and creates a new task/head optimizer:
114
+
115
+ ```bash
116
+ uv run gnn4colliders train \
117
+ data.cache.path=cache/target.pt \
118
+ model=root_gnn/fine_tuned_edge_network \
119
+ task=binary_classification \
120
+ checkpoint.pretrained=/path/to/pretrained.pt \
121
+ model.freeze_backbone=true \
122
+ trainer.max_epochs=10
123
+ ```
124
+
125
+ Set `model.freeze_backbone=false` to train the reused backbone as well.
126
+ Transfer learning is not resume training:
127
+
128
+ | Workflow | Meaning | Restored state |
129
+ | --- | --- | --- |
130
+ | Resume | Continue the same task/run | model, optimizer, scheduler, trainer, early stopping, and RNG state when present |
131
+ | Transfer | Start a new task from a pretrained backbone | model weights only; new classifier and optimizer |
132
+
133
+ Resume example:
134
+
135
+ ```bash
136
+ uv run gnn4colliders train \
137
+ data.cache.path=cache/events.pt \
138
+ checkpoint.resume=outputs/pretraining_multiclass/checkpoints/epoch_0000.pt \
139
+ trainer.max_epochs=20
140
+ ```
141
+
142
+ Validation is evaluated each epoch and drives scheduling/early stopping;
143
+ `test` remains held out. Evaluation computes task metrics over the complete
144
+ selected split, including weighted ROC AUC where defined:
145
+
146
+ ```bash
147
+ uv run gnn4colliders evaluate \
148
+ data.cache.path=cache/events.pt \
149
+ inference.split=test \
150
+ inference.checkpoint=/path/to/checkpoint.pt
151
+ ```
152
+
153
+ Prediction writes a named compressed NPZ. Labeled data includes `labels`;
154
+ `fold` and `weight` are included when available. Every result includes
155
+ `sample_id`, `logits`, `scores`, and `predictions`:
156
+
157
+ ```bash
158
+ uv run gnn4colliders predict \
159
+ data.cache.path=cache/events.pt \
160
+ inference.checkpoint=/path/to/checkpoint.pt \
161
+ inference.output=outputs/predictions.npz
162
+ ```
163
+
164
+ Optional Python-level ROOT writing is provided by
165
+ `gnn4colliders.inference.write_root_scores`. It clones the selected tree,
166
+ adds `score` (or `score_class_N`), and writes `selection_pass`; IDs ending in
167
+ `:<entry>` preserve alignment and unselected entries receive NaN scores. The
168
+ CLI currently exposes NPZ output only.
169
+
170
+ The supported legacy checkpoint, metadata, and output boundary is documented
171
+ in [`docs/compatibility.md`](docs/compatibility.md). New code should use named
172
+ metadata fields; positional tracking is accepted only by the explicit
173
+ compatibility adapter.
174
+
175
+ ### ONNX export
176
+
177
+ Install the optional export dependencies and export a prepared graph-cache
178
+ checkpoint with numerical ONNX validation:
179
+
180
+ ```bash
181
+ uv sync --extra root-gnn --extra onnx
182
+ uv run gnn4colliders export \
183
+ export.checkpoint=/path/to/checkpoint.pt \
184
+ export.output=model.onnx \
185
+ data.cache.path=/path/to/graph-cache.pt
186
+ ```
187
+
188
+ The model accepts processed graph tensors and returns raw logits. See
189
+ [`docs/export.md`](docs/export.md) for the tensor contract and limitations.
190
+
191
+ ## Configuration and environments
192
+
193
+ Hydra groups are `data`, `model`, `task`, `trainer`, `checkpoint`,
194
+ `inference`, `environment`, and `distributed`. Use configuration for a new
195
+ experiment and Python for new behavior. Examples:
196
+
197
+ ```bash
198
+ uv run gnn4colliders train trainer.max_epochs=50 data.batch_size=64
199
+ uv run gnn4colliders train environment=perlmutter environment.device=cuda
200
+ uv run gnn4colliders train distributed=ddp environment=perlmutter
201
+ ```
202
+
203
+ Each run writes a resolved configuration to
204
+ `<environment.output_root>/resolved_config.yaml`. See
205
+ [`docs/configuration.md`](docs/configuration.md) for the group reference and
206
+ [`docs/perlmutter.md`](docs/perlmutter.md) for launch examples.
207
+
208
+ ## Distributed execution and reproducibility
209
+
210
+ Launch DDP with `torchrun` or the provided Slurm wrappers. `data.batch_size`
211
+ and `data.num_workers` are per process, so the ordinary effective batch size
212
+ is `batch_size * world_size`. Training shards may be padded for equal steps;
213
+ validation and prediction are unpadded. Rank 0 writes shared checkpoints,
214
+ configs, and predictions, and metrics/results are gathered across ranks.
215
+
216
+ The configured seed controls initialization and deterministic local loader
217
+ ordering; distributed process seeds are rank-offset and samplers use
218
+ `set_epoch`. CPU runs are reproducible for fixed inputs and environment. GPU
219
+ kernels, DGL, and distributed scheduling can remain nondeterministic, so the
220
+ project does not promise bitwise GPU reproducibility.
221
+
222
+ ## Development and validation
223
+
224
+ ```bash
225
+ uv run pytest
226
+ uv run pytest tests/unit
227
+ GNN4COLLIDERS_REQUIRE_ROOT_GNN=1 uv run pytest tests/parity -v
228
+ uv run ruff check .
229
+ uv run ruff format --check .
230
+ uv run python benchmarks/benchmark_preprocessing.py
231
+ uv run python benchmarks/benchmark_training.py --device cpu
232
+ ```
233
+
234
+ Unit tests cover isolated components, integration tests cover small workflows,
235
+ and parity tests compare deterministic behavior with the frozen legacy
236
+ reference. Performance guidance and measured caveats are in
237
+ [`docs/performance.md`](docs/performance.md) and
238
+ [`benchmarks/README.md`](benchmarks/README.md).
239
+ See [`docs/testing.md`](docs/testing.md) for test layers, optional dependency
240
+ markers, and package smoke validation.
241
+
242
+ ## Architecture and migration status
243
+
244
+ See [`docs/architecture.md`](docs/architecture.md) for responsibility
245
+ boundaries and the future sequence-model extension point. See
246
+ [`docs/migration.md`](docs/migration.md) for the migration matrix,
247
+ intentional redesigns, compatibility limits, and deferred work.
248
+
249
+ ROOT-GNN v1 covers ROOT preparation, validated feature/graph/model/task
250
+ behavior, training, fine-tuning, checkpoint resume, evaluation, prediction,
251
+ single-process/DDP execution, and validated ONNX export. Streaming distributed
252
+ output, legacy cleanup, and ROOT-Transformer remain follow-up work.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/README.md ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Performance benchmarks
2
+
3
+ These scripts use fixed synthetic inputs, explicit seeds, warmup iterations,
4
+ and JSON-lines output. GPU timings synchronize after every measured operation;
5
+ warmup and one-time setup costs are excluded from steady-state numbers.
6
+
7
+ ```bash
8
+ uv run python benchmarks/benchmark_preprocessing.py
9
+ uv run python benchmarks/benchmark_dataloader.py
10
+ uv run python benchmarks/benchmark_training.py --device cpu
11
+ uv run python benchmarks/benchmark_inference.py --device cpu
12
+ uv run python benchmarks/benchmark_training.py --device cuda --profile
13
+ ```
14
+
15
+ DGL-dependent scripts report a structured `skipped` result when the optional
16
+ `root-gnn` extra is absent. Profiler traces go under `profiles/` and are not
17
+ committed.
18
+
19
+ ## Baseline measurements
20
+
21
+ The portable baseline in this checkout uses Python 3.12.13, PyTorch 2.2.2+cu121,
22
+ DGL 2.4.0+cu121, CPU, `nodes=32`, `iterations=10`, and `warmup=3`. Exact timings are machine
23
+ dependent; the JSON output from a local run is authoritative.
24
+
25
+ | Measurement | Mean | Median |
26
+ | --- | ---: | ---: |
27
+ | feature construction | 0.47 ms/event | 0.46 ms/event |
28
+ | edge features | 0.11 ms/graph | 0.11 ms/graph |
29
+ | graph-sample loader | 1.65 ms/iteration | 1.65 ms/iteration |
30
+ | ROOT-GNN training step | 21.19 ms/step | 5.32 ms/step |
31
+ | ROOT-GNN inference | 1.48 ms/graph | 1.49 ms/graph |
32
+
33
+ On the available NVIDIA A100-PCIE-40GB with CUDA 12.1 runtime, the same small
34
+ synthetic ROOT-GNN benchmark measured 6.41 ms/step (17.3 MiB peak allocated)
35
+ and 2.00 ms/graph. These are microbenchmarks, not production-workload claims.
36
+
37
+ DGL is available in this environment. The training mean is skewed by one CPU
38
+ warmup-adjacent outlier; median is the more useful steady-state indicator. DDP
39
+ measurements require a multi-process run and are not inferred from CPU numbers.
40
+
41
+ The topology cache is bounded to 32 node-count/device/policy entries and only
42
+ stores reusable index tensors, never event-specific edge features.
43
+
44
+ On the same CPU, a direct topology microbenchmark for 64 nodes measured
45
+ 201.6 microseconds per cold construction versus 10.5 microseconds for a warm
46
+ cache lookup (about 19x for this isolated operation). This is a targeted
47
+ index-construction result, not an end-to-end training speedup; graph feature
48
+ construction and DGL message passing remain separate costs.
benchmarks/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Standalone, reproducible performance measurements for GNN4Colliders."""
benchmarks/_common.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Small helpers shared by benchmark entry points."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import platform
8
+ import statistics
9
+ import time
10
+ from collections.abc import Callable
11
+ from typing import Any
12
+
13
+ import torch
14
+
15
+
16
+ def common_parser(description: str) -> argparse.ArgumentParser:
17
+ parser = argparse.ArgumentParser(description=description)
18
+ parser.add_argument("--iterations", type=int, default=20)
19
+ parser.add_argument("--warmup", type=int, default=5)
20
+ parser.add_argument("--device", default="cpu")
21
+ parser.add_argument("--seed", type=int, default=1234)
22
+ return parser
23
+
24
+
25
+ def synchronize(device: torch.device) -> None:
26
+ if device.type == "cuda":
27
+ torch.cuda.synchronize(device)
28
+
29
+
30
+ def measure(
31
+ operation: Callable[[], Any], *, iterations: int, warmup: int, device: torch.device
32
+ ) -> dict[str, float]:
33
+ for _ in range(warmup):
34
+ operation()
35
+ synchronize(device)
36
+ durations = []
37
+ for _ in range(iterations):
38
+ start = time.perf_counter()
39
+ operation()
40
+ synchronize(device)
41
+ durations.append(time.perf_counter() - start)
42
+ return {
43
+ "mean_ms": statistics.mean(durations) * 1000,
44
+ "median_ms": statistics.median(durations) * 1000,
45
+ "min_ms": min(durations) * 1000,
46
+ "max_ms": max(durations) * 1000,
47
+ "stdev_ms": statistics.stdev(durations) * 1000 if len(durations) > 1 else 0.0,
48
+ }
49
+
50
+
51
+ def metadata(device: torch.device) -> dict[str, Any]:
52
+ result: dict[str, Any] = {
53
+ "python": platform.python_version(),
54
+ "torch": torch.__version__,
55
+ "device": str(device),
56
+ "cuda_available": torch.cuda.is_available(),
57
+ }
58
+ if device.type == "cuda" and torch.cuda.is_available():
59
+ result["gpu"] = torch.cuda.get_device_name(device)
60
+ try:
61
+ import dgl
62
+
63
+ result["dgl"] = dgl.__version__
64
+ except ImportError:
65
+ result["dgl"] = None
66
+ return result
67
+
68
+
69
+ def report(name: str, values: dict[str, Any]) -> None:
70
+ print(json.dumps({"benchmark": name, **values}, sort_keys=True))
benchmarks/benchmark_dataloader.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Measure deterministic loader/batch construction when ROOT-GNN is installed."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import torch
6
+
7
+ try:
8
+ from ._common import common_parser, measure, metadata, report
9
+ except ImportError:
10
+ from _common import common_parser, measure, metadata, report
11
+
12
+
13
+ def main() -> None:
14
+ parser = common_parser(__doc__)
15
+ parser.add_argument("--batch-size", type=int, default=8)
16
+ parser.add_argument("--samples", type=int, default=64)
17
+ args = parser.parse_args()
18
+ device = torch.device(args.device)
19
+ try:
20
+ import dgl
21
+
22
+ from gnn4colliders.data import (
23
+ EventMetadata,
24
+ GraphDataLoader,
25
+ GraphDataset,
26
+ GraphSample,
27
+ )
28
+ except ImportError:
29
+ report(
30
+ "dataloader",
31
+ {**metadata(device), "status": "skipped: install root-gnn extra"},
32
+ )
33
+ return
34
+ samples = []
35
+ for index in range(args.samples):
36
+ graph = dgl.graph((torch.tensor([0, 1]), torch.tensor([1, 0])), num_nodes=2)
37
+ graph.ndata["features"] = torch.ones(2, 7)
38
+ graph.edata["features"] = torch.ones(2, 3)
39
+ samples.append(
40
+ GraphSample(
41
+ graph, torch.tensor(index % 2), None, EventMetadata(0, 1.0, str(index))
42
+ )
43
+ )
44
+ loader = GraphDataLoader(GraphDataset(samples), args.batch_size)
45
+ result = measure(
46
+ lambda: list(loader),
47
+ iterations=args.iterations,
48
+ warmup=args.warmup,
49
+ device=device,
50
+ )
51
+ report(
52
+ "dataloader",
53
+ {
54
+ **metadata(device),
55
+ **result,
56
+ "batch_size": args.batch_size,
57
+ "batches_per_second": 1000 / result["mean_ms"],
58
+ },
59
+ )
60
+
61
+
62
+ if __name__ == "__main__":
63
+ main()
benchmarks/benchmark_inference.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Measure ROOT-GNN inference with fixed synthetic graph input."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import torch
6
+
7
+ try:
8
+ from ._common import common_parser, measure, metadata, report
9
+ except ImportError:
10
+ from _common import common_parser, measure, metadata, report
11
+
12
+
13
+ def main() -> None:
14
+ parser = common_parser(__doc__)
15
+ args = parser.parse_args()
16
+ device = torch.device(args.device)
17
+ try:
18
+ import dgl
19
+
20
+ from gnn4colliders.models.root_gnn import EdgeNetwork
21
+ except ImportError:
22
+ report(
23
+ "inference",
24
+ {**metadata(device), "status": "skipped: install root-gnn extra"},
25
+ )
26
+ return
27
+ graph = dgl.graph((torch.tensor([0, 1]), torch.tensor([1, 0])), num_nodes=2).to(
28
+ device
29
+ )
30
+ graph.ndata["features"] = torch.ones(2, 7, device=device)
31
+ graph.edata["features"] = torch.ones(2, 3, device=device)
32
+ model = (
33
+ EdgeNetwork(graph, None, hid_size=16, out_size=2, n_layers=1, n_proc_steps=1)
34
+ .to(device)
35
+ .eval()
36
+ )
37
+
38
+ def infer() -> None:
39
+ with torch.inference_mode():
40
+ model(graph)
41
+
42
+ result = measure(
43
+ infer, iterations=args.iterations, warmup=args.warmup, device=device
44
+ )
45
+ report(
46
+ "inference",
47
+ {**metadata(device), **result, "graphs_per_second": 1000 / result["mean_ms"]},
48
+ )
49
+
50
+
51
+ if __name__ == "__main__":
52
+ main()
benchmarks/benchmark_preprocessing.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Measure shared feature and graph preprocessing on fixed synthetic events."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import torch
6
+
7
+ from gnn4colliders.features import build_node_features
8
+ from gnn4colliders.graphs import build_edge_features, fully_connected_edges
9
+
10
+ try:
11
+ from ._common import common_parser, measure, metadata, report
12
+ except ImportError:
13
+ from _common import common_parser, measure, metadata, report
14
+
15
+
16
+ def main() -> None:
17
+ parser = common_parser(__doc__)
18
+ parser.add_argument("--nodes", type=int, default=32)
19
+ args = parser.parse_args()
20
+ torch.manual_seed(args.seed)
21
+ event = {
22
+ "pt": torch.arange(args.nodes, dtype=torch.float32) + 1,
23
+ "eta": torch.linspace(-2, 2, args.nodes),
24
+ "phi": torch.linspace(-3.0, 3.0, args.nodes),
25
+ }
26
+ branches = [["pt"], ["eta"], ["phi"], "CALC_E", [1.0], [0.0], "NODE_TYPE"]
27
+ object_types = ["vector"]
28
+ scales = [1.0] * 7
29
+ device = torch.device(args.device)
30
+
31
+ feature_result = measure(
32
+ lambda: build_node_features(event, branches, object_types, scales),
33
+ iterations=args.iterations,
34
+ warmup=args.warmup,
35
+ device=device,
36
+ )
37
+ nodes = build_node_features(event, branches, object_types, scales)[0]
38
+ src, dst = fully_connected_edges(args.nodes)
39
+ graph_result = measure(
40
+ lambda: build_edge_features(nodes, src, dst, eta_index=1, phi_index=2),
41
+ iterations=args.iterations,
42
+ warmup=args.warmup,
43
+ device=device,
44
+ )
45
+ base = {**metadata(device), "nodes": args.nodes, "iterations": args.iterations}
46
+ report(
47
+ "feature_construction",
48
+ {
49
+ **base,
50
+ **feature_result,
51
+ "events_per_second": 1000 / feature_result["mean_ms"],
52
+ },
53
+ )
54
+ report(
55
+ "edge_features",
56
+ {**base, **graph_result, "graphs_per_second": 1000 / graph_result["mean_ms"]},
57
+ )
58
+
59
+
60
+ if __name__ == "__main__":
61
+ main()
benchmarks/benchmark_training.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Measure a short ROOT-GNN training section and optionally emit a profiler trace."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import torch
8
+
9
+ try:
10
+ from ._common import common_parser, measure, metadata, report
11
+ except ImportError:
12
+ from _common import common_parser, measure, metadata, report
13
+
14
+
15
+ def main() -> None:
16
+ parser = common_parser(__doc__)
17
+ parser.add_argument("--batch-size", type=int, default=4)
18
+ parser.add_argument("--profile", action="store_true")
19
+ parser.add_argument("--profile-dir", default="profiles")
20
+ args = parser.parse_args()
21
+ device = torch.device(args.device)
22
+ try:
23
+ import dgl
24
+
25
+ from gnn4colliders.models.root_gnn import EdgeNetwork
26
+ except ImportError:
27
+ report(
28
+ "training",
29
+ {**metadata(device), "status": "skipped: install root-gnn extra"},
30
+ )
31
+ return
32
+ torch.manual_seed(args.seed)
33
+ graph = dgl.graph((torch.tensor([0, 1]), torch.tensor([1, 0])), num_nodes=2).to(
34
+ device
35
+ )
36
+ graph.ndata["features"] = torch.randn(2, 7, device=device)
37
+ graph.edata["features"] = torch.randn(2, 3, device=device)
38
+ model = EdgeNetwork(
39
+ graph, None, hid_size=16, out_size=2, n_layers=1, n_proc_steps=1
40
+ ).to(device)
41
+ optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
42
+
43
+ def step() -> None:
44
+ optimizer.zero_grad(set_to_none=True)
45
+ loss = model(graph).square().mean()
46
+ loss.backward()
47
+ optimizer.step()
48
+
49
+ if args.profile:
50
+ profile_dir = Path(args.profile_dir)
51
+ profile_dir.mkdir(parents=True, exist_ok=True)
52
+ with torch.profiler.profile(record_shapes=True, profile_memory=True) as prof:
53
+ for _ in range(args.warmup + args.iterations):
54
+ step()
55
+ prof.export_chrome_trace(str(profile_dir / "training.trace.json"))
56
+ result = measure(
57
+ step, iterations=args.iterations, warmup=args.warmup, device=device
58
+ )
59
+ report(
60
+ "training_step",
61
+ {
62
+ **metadata(device),
63
+ **result,
64
+ "steps_per_second": 1000 / result["mean_ms"],
65
+ "peak_memory_mb": torch.cuda.max_memory_allocated(device) / 2**20
66
+ if device.type == "cuda"
67
+ else 0.0,
68
+ },
69
+ )
70
+
71
+
72
+ if __name__ == "__main__":
73
+ main()
configs/.gitkeep ADDED
@@ -0,0 +1 @@
 
 
1
+
configs/data/.gitkeep ADDED
@@ -0,0 +1 @@
 
 
1
+
configs/environment/.gitkeep ADDED
@@ -0,0 +1 @@
 
 
1
+
configs/model/.gitkeep ADDED
@@ -0,0 +1 @@
 
 
1
+
configs/model/root_gnn/.gitkeep ADDED
@@ -0,0 +1 @@
 
 
1
+
configs/task/.gitkeep ADDED
@@ -0,0 +1 @@
 
 
1
+
configs/trainer/.gitkeep ADDED
@@ -0,0 +1 @@
 
 
1
+
data/fixtures/.gitkeep ADDED
@@ -0,0 +1 @@
 
 
1
+
data/raw/.gitkeep ADDED
@@ -0,0 +1 @@
 
 
1
+
docs/architecture.md ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # GNN4Colliders architecture
2
+
3
+ ## Current v1 architecture
4
+
5
+ The supported rewrite is layered around an architecture-neutral event boundary:
6
+
7
+ ```text
8
+ ROOT/Awkward
9
+ ↓
10
+ EventSample + EventMetadata
11
+ ↓
12
+ shared collider feature construction
13
+ β”œβ”€β”€ GraphSample -> versioned graph cache -> GraphBatch
14
+ └── future SequenceSample -> ROOT-Transformer (not implemented)
15
+ ↓
16
+ ROOT-GNN EdgeNetwork
17
+ ↓
18
+ raw logits -> Task
19
+ β”œβ”€β”€ loss
20
+ β”œβ”€β”€ predictions
21
+ └── full-split metrics
22
+ ↓
23
+ Trainer / Predictor / outputs
24
+ ```
25
+
26
+ | Layer | Responsibility |
27
+ | --- | --- |
28
+ | `data` | ROOT/Awkward ingestion, event samples, metadata, graph caches, folds, and batching |
29
+ | `features` | Shared collider-object features and derived physics quantities |
30
+ | `graphs` | Topology, edge features, and the DGL representation adapter |
31
+ | `models/root_gnn` | ROOT-GNN encoders, message passing, classifier, and transfer boundary |
32
+ | `tasks` | Loss, score/prediction, labels, weights, and metrics |
33
+ | `training` | Optimizer lifecycle, validation, early stopping, checkpointing, and reproducibility |
34
+ | `inference` | Ordered prediction/evaluation and NPZ/ROOT output adapters |
35
+ | `distributed` | Rank-local devices, sharding, DDP, and cross-rank collection |
36
+ | `config` / `cli` | Semantic Hydra composition and thin user-facing commands |
37
+
38
+ `EventSample` is shared infrastructure, not a ROOT-GNN object. `GraphSample`
39
+ is the current representation-specific adapter. This separation is the
40
+ extension point for a future sequence/token representation.
41
+
42
+ The new public metadata contract is named `EventMetadata(fold, weight,
43
+ sample_id, extra)`. The legacy positional tracking tensor is accepted only by
44
+ compatibility-facing ingestion code. A `GraphSampleCache` is deliberately a
45
+ Level-2 graph cache; replacing it with a universal cache would couple future
46
+ model families to DGL.
47
+
48
+ For deployment, a prepared `GraphBatch` can pass through the isolated
49
+ `RootGNNExportAdapter` into an ONNX model. This is an inference boundary only;
50
+ the native model continues to consume DGL graphs and ONNX does not read ROOT
51
+ or construct collider features.
52
+
53
+ ## Current public workflow
54
+
55
+ `prepare` reads ROOT through `RootEventDataset`, builds shared features and
56
+ DGL graphs, and saves a schema-checked cache. `train` creates a model/task and
57
+ `Trainer`; validation is the model-selection split and test is held out.
58
+ `evaluate` computes metrics after collecting the complete split. `predict`
59
+ returns detached CPU tensors in loader order and writes named NPZ fields.
60
+ `write_root_scores` is an optional Python adapter with explicit entry alignment;
61
+ the CLI currently exposes NPZ output.
62
+
63
+ Compatibility responsibilities are isolated in `gnn4colliders.compat`.
64
+ Supported historical checkpoint prefixes, classifier names, and the two-column
65
+ tracking conversion are listed in [`compatibility.md`](compatibility.md).
66
+ The modern pipeline does not propagate positional tracking or historical NPZ
67
+ fields.
68
+
69
+ Checkpoints are independent of the model implementation: they carry model and
70
+ task metadata, lifecycle state, schema versions, and optional RNG state.
71
+ Prefix normalization supports DDP `module.` and compiled `_orig_mod.` weights,
72
+ plus the active ROOT-GNN historical classifier-name compatibility path.
73
+
74
+ ---
75
+
76
+ ## Historical behavioral reference
77
+
78
+ This document covers the target system in `legacy/root_gnn_dgl/`. The sibling
79
+ `legacy/physicsnemo/` tree is a prior rewrite attempt and is not a behavioral
80
+ target.
81
+
82
+ ## 1. High-level system description
83
+
84
+ The active rewrite exposes `gnn4colliders.models.root_gnn.EdgeNetwork`. Its
85
+ encoders and message-passing blocks form a reusable backbone whose decoded
86
+ graph representation is passed to an explicit classifier. `FineTunedEdgeNetwork`
87
+ reuses that backbone and replaces only the task-specific classifier, with
88
+ explicit frozen or trainable-backbone control.
89
+
90
+ `root_gnn_dgl` is a ROOT-to-DGL graph classification system. YAML selects
91
+ dataset, model, loss, and finish-function classes by import path. The dataset
92
+ reads ROOT trees, converts collider objects to fully connected DGL graphs, and
93
+ saves graph chunks. Training loads those chunks, applies fold selection and
94
+ optional pre-batching/padding, trains a graph network, writes one PyTorch
95
+ checkpoint per epoch, and reports weighted loss, accuracy, and ROC AUC.
96
+
97
+ The primary model is `models.GCN.Edge_Network` ([`GCN.py:182-251`](../legacy/root_gnn_dgl/models/GCN.py)).
98
+ It encodes node, edge, and global features, repeats edge -> node -> global
99
+ message passing `n_proc_steps` times, decodes the global state, and applies
100
+ `classify`. Fine-tuning uses `models.GCN.Transferred_Learning_Finetuning`
101
+ ([`GCN.py:884-997`](../legacy/root_gnn_dgl/models/GCN.py)), which loads a
102
+ pretrained `Edge_Network`, removes its final classifier, and applies a new one.
103
+ The active configs use output size 12 for multiclass pretraining and output
104
+ size 1 for binary tasks ([`configs/stats_100K/pretraining_multiclass.yaml:1-45`](../legacy/root_gnn_dgl/configs/stats_100K/pretraining_multiclass.yaml),
105
+ [`configs/stats_100K/finetuning_ttH_CP_even_vs_odd.yaml:1-45`](../legacy/root_gnn_dgl/configs/stats_100K/finetuning_ttH_CP_even_vs_odd.yaml)).
106
+
107
+ ### Entry points and flows
108
+
109
+ - `scripts/training_script.py:main` and its CLI parser load YAML, create
110
+ loaders, construct the model, and call `train`; `--evaluate` calls
111
+ `evaluate` ([`training_script.py:638-843`](../legacy/root_gnn_dgl/scripts/training_script.py)).
112
+ - `scripts/prep_data.py:main` creates configured graph caches
113
+ ([`prep_data.py:68-110`](../legacy/root_gnn_dgl/scripts/prep_data.py)).
114
+ - `scripts/inference.py:main` reconstructs an unlazy dataset, loads one or
115
+ more checkpoints, and writes `.npz` or ROOT scores
116
+ ([`inference.py:163-387`](../legacy/root_gnn_dgl/scripts/inference.py)).
117
+ - `scripts/export_onnx.py:main` exports an ONNX-friendly model
118
+ ([`export_onnx.py:979-1035`](../legacy/root_gnn_dgl/scripts/export_onnx.py)).
119
+ - `selections.py:main`, `check_dataset_files.py:main`, and
120
+ `plot_config_distributions.py:main` are diagnostic entry points. `run_demo.sh`
121
+ sequences pretraining, binary training, fine-tuning, and inference
122
+ ([`run_demo.sh:3-59`](../legacy/root_gnn_dgl/run_demo.sh)).
123
+
124
+ The training flow is:
125
+
126
+ ```text
127
+ YAML -> load_config/buildFromConfig -> RootDataset/LazyDataset
128
+ -> ROOT/Awkward -> DGL graph + labels/tracking/globals -> .bin cache
129
+ -> fold_selection -> prebatch/padding -> GraphDataLoader
130
+ -> Edge_Network or transfer model -> weighted loss/metrics
131
+ -> model_epoch_N.pt, logs, evaluation/inference output
132
+ ```
133
+
134
+ `training_script.train` is the lifecycle implementation
135
+ ([`training_script.py:143-614`](../legacy/root_gnn_dgl/scripts/training_script.py));
136
+ distributed paths use NCCL/DDP ([`training_script.py:616-839`](../legacy/root_gnn_dgl/scripts/training_script.py)).
137
+ Inference uses `CustomPreBatchedDataset`, applies a configured finish function,
138
+ and collects `scores`, `labels`, and `tracking_info`
139
+ ([`inference.py:20-76`](../legacy/root_gnn_dgl/scripts/inference.py),
140
+ [`inference.py:223-325`](../legacy/root_gnn_dgl/scripts/inference.py)).
141
+
142
+ ## 2. Dependency and data-flow map
143
+
144
+ ```text
145
+ ROOT files (raw_dir/file_names, tree_name)
146
+ -> gnn4colliders.data.RootEventDataset (Uproot/Awkward)
147
+ -> node feature construction (dataset.py:15-50)
148
+ -> full_connected_graph (dataset.py:52-59)
149
+ -> EdgeDataset.make_graph: [deta, dphi, dR] (dataset.py:471-482)
150
+ -> DGL .bin cache / LazyDataset / PreBatchedDataset
151
+ -> GraphDataLoader -> models.GCN -> loss/metrics -> outputs
152
+ ```
153
+
154
+ `RootDataset` provides `process`, `save`, `load`, `__getitem__`, and `__len__`
155
+ ([`dataset.py:160-469`](../legacy/root_gnn_dgl/root_gnn_base/dataset.py));
156
+ `LazyDataset` loads one chunk through a ring buffer
157
+ ([`dataset.py:525-578`](../legacy/root_gnn_dgl/root_gnn_base/dataset.py));
158
+ `PreBatchedDataset.process` selects, shuffles, batches, pads, and caches
159
+ ([`batched_dataset.py:34-146`](../legacy/root_gnn_dgl/root_gnn_base/batched_dataset.py)).
160
+
161
+ `load_config` uses PyYAML `FullLoader` and shallow `include` merging, while
162
+ `buildFromConfig` dynamically imports `module`, resolves `class`, merges extra
163
+ keys into `args`, converts list-valued weights to tensors, and injects runtime
164
+ arguments ([`utils.py:10-43`](../legacy/root_gnn_dgl/root_gnn_base/utils.py)).
165
+ This reflection shape is a de facto interface for configured components.
166
+
167
+ ### Data and preprocessing
168
+
169
+ The active node schema is seven columns: `pt`, `eta`, `phi`, `energy`, `btag`,
170
+ `charge`, and `node_type`. `CALC_E` is `pt*cosh(eta)`, constants are broadcast
171
+ per object type, `NODE_TYPE` is an integer type code, and feature scales are
172
+ applied columnwise ([`dataset.py:15-50`](../legacy/root_gnn_dgl/root_gnn_base/dataset.py)).
173
+ `full_connected_graph` makes directed all-pairs edges; `EdgeDataset` requests
174
+ no self-loops and stores `[deta, dphi, dR]`
175
+ ([`dataset.py:52-59`](../legacy/root_gnn_dgl/root_gnn_base/dataset.py),
176
+ [`dataset.py:471-482`](../legacy/root_gnn_dgl/root_gnn_base/dataset.py)).
177
+
178
+ Selections are strings evaluated with builtins disabled or
179
+ `(variable, cut, operator)` triples (`check_selection`, `selection_mask`;
180
+ [`dataset.py:75-145`](../legacy/root_gnn_dgl/root_gnn_base/dataset.py)). Fold
181
+ selection uses `tracking[:,0] % n_folds`; tracking column 0 is fold and column 1
182
+ is weight ([`utils.py:121-143`](../legacy/root_gnn_dgl/root_gnn_base/utils.py),
183
+ [`dataset.py:176-182`](../legacy/root_gnn_dgl/root_gnn_base/dataset.py)).
184
+ `hash_partition` and a seeded Torch generator control pre-batch order
185
+ ([`batched_dataset.py:27-99`](../legacy/root_gnn_dgl/root_gnn_base/batched_dataset.py)).
186
+ Padding modes are `NONE`, `STEPS`, `FIXED`, and `NODE`; `FIXED` is hardcoded to
187
+ 16,000 nodes and 104,000 edges ([`batched_dataset.py:100-125`](../legacy/root_gnn_dgl/root_gnn_base/batched_dataset.py)).
188
+
189
+ ### Model, losses, and metrics
190
+
191
+ `Make_MLP` builds linear/ReLU/dropout blocks followed by LayerNorm
192
+ ([`GCN.py:18-35`](../legacy/root_gnn_dgl/models/GCN.py)). Each `Edge_Network`
193
+ step encodes inputs, copies source/destination states to edges, updates edges,
194
+ sums edge messages into nodes, updates nodes, then mean-pools nodes/edges to
195
+ update globals ([`GCN.py:195-249`](../legacy/root_gnn_dgl/models/GCN.py)). It
196
+ returns logits `[graphs, out_size]` without sigmoid/softmax.
197
+
198
+ The default objective is elementwise `BCEWithLogitsLoss`, multiplied by
199
+ `tracking[:,1]`, averaged separately per unique label, then averaged across
200
+ labels ([`training_script.py:143-185`](../legacy/root_gnn_dgl/scripts/training_script.py),
201
+ [`training_script.py:320-359`](../legacy/root_gnn_dgl/scripts/training_script.py)).
202
+ `--abs` makes weights positive. Binary metrics use sigmoid threshold 0.5 and
203
+ weighted ROC AUC; multiclass metrics use argmax and one-vs-rest ROC AUC
204
+ ([`training_script.py:438-510`](../legacy/root_gnn_dgl/scripts/training_script.py)).
205
+ Additional configurable losses/finishers live in `models/loss.py`
206
+ ([`loss.py:6-310`](../legacy/root_gnn_dgl/models/loss.py)).
207
+
208
+ ### Checkpoints and outputs
209
+
210
+ Training writes `Training_Directory/model_epoch_<epoch>.pt` containing `epoch`,
211
+ `model_state_dict`, `optimizer_state_dict`, and serialized `early_stop`
212
+ ([`training_script.py:565-604`](../legacy/root_gnn_dgl/scripts/training_script.py)).
213
+ Keys strip `module.` and compiled models save the underlying `_orig_mod` state;
214
+ `get_last_epoch`, `get_specific_epoch`, and `get_best_epoch` load the files
215
+ ([`utils.py:145-248`](../legacy/root_gnn_dgl/root_gnn_base/utils.py)).
216
+ `evaluate` writes `evaluation_<epoch>.npz`; inference writes `.npz` fields
217
+ `scores`, `labels`, `tracking_info`, or adds score branches and `selection_pass`
218
+ to a cloned ROOT tree ([`training_script.py:57-140`](../legacy/root_gnn_dgl/scripts/training_script.py),
219
+ [`inference.py:328-385`](../legacy/root_gnn_dgl/scripts/inference.py)).
220
+
221
+ ### Training lifecycle boundary
222
+
223
+ The active rewrite keeps lifecycle orchestration architecture-independent:
224
+
225
+ ```text
226
+ GraphDataLoader -> GraphBatch -> Model -> Task -> Trainer
227
+ loss/metrics
228
+ ```
229
+
230
+ `gnn4colliders.training.Trainer` owns device placement, train/evaluation mode,
231
+ gradient and optimizer steps, epoch aggregation, optional scheduler stepping,
232
+ early stopping, and in-memory history. Tasks own loss and metric semantics;
233
+ the trainer does not inspect positional tracking columns or collider-specific
234
+ features. Evaluation concatenates detached outputs across the complete split
235
+ before calling task metrics, so ROC AUC is not computed per mini-batch.
236
+
237
+ Checkpoint persistence and the Python inference/output layer are implemented
238
+ as separate adapters. The semantic CLI and distributed application boundary
239
+ are implemented in the current stack. `gnn4colliders.inference.Predictor` accumulates detached CPU
240
+ logits, task-defined scores/predictions, labels, and named event metadata in
241
+ loader order; `write_npz` is the primary named-field format and ROOT score
242
+ writing is an optional alignment-aware adapter.
243
+
244
+ The new lifecycle uses conventional split semantics. `train` updates model
245
+ parameters, `validation` is evaluated after every epoch and drives scheduler,
246
+ early-stopping, and later model selection, and `test` is held out. The trainer
247
+ does not accept a test loader in `fit`; callers evaluate the held-out test set
248
+ separately after training. This deliberately corrects the legacy convention
249
+ where a loader named `test` was used for model selection and `val` represented
250
+ held-out testing.
251
+
252
+ ## Distributed execution
253
+
254
+ `gnn4colliders.distributed` contains the small DDP boundary used by the
255
+ application layer. `DistributedContext` reads the standard `torchrun`
256
+ environment (`RANK`, `LOCAL_RANK`, and `WORLD_SIZE`), selects the rank-local
257
+ device, and owns process-group cleanup. Graph samples are sharded before
258
+ batching; training may pad rank shards for equal step counts, while validation
259
+ and prediction use unpadded shards so events are not counted twice.
260
+
261
+ The configured graph `batch_size` is per process. DDP wraps an otherwise
262
+ ordinary model after device placement, and checkpoint state is normalized to
263
+ the underlying model keys. Loss gradients are synchronized by DDP; epoch
264
+ metrics and evaluation outputs are gathered across ranks. Rank 0 writes
265
+ resolved configuration, checkpoints, and NPZ predictions. Moderate-size
266
+ prediction gathering is in-memory; streaming/sharded output is a future
267
+ extension.
268
+
269
+
270
+ ## Randomness, external services, and coupling
271
+
272
+ The CLI exposes `--seed`, but `main` passes it to model construction rather
273
+ than globally seeding Python, NumPy, or Torch
274
+ ([`training_script.py:638-753`](../legacy/root_gnn_dgl/scripts/training_script.py)).
275
+ Pre-batching has explicit seeds, but `AugmentedDataset` mutates the process-wide
276
+ NumPy seed ([`dataset.py:716-827`](../legacy/root_gnn_dgl/root_gnn_base/dataset.py)),
277
+ clustering uses unseeded `torch.randperm`/`randint` (`loss.py:259-295`), and
278
+ model reset/fine-tuning hardcodes `torch.manual_seed(2)`
279
+ ([`GCN.py:58-65`](../legacy/root_gnn_dgl/models/GCN.py),
280
+ [`GCN.py:900-915`](../legacy/root_gnn_dgl/models/GCN.py)). CUDA kernels, DDP,
281
+ and DataLoader behavior are not made deterministic.
282
+
283
+ Implicit coupling includes repository-relative `sys.path` insertion
284
+ ([`training_script.py:14-20`](../legacy/root_gnn_dgl/scripts/training_script.py)),
285
+ dynamic imports, mutable default lists/dicts, global `FEATURE_DTYPE`
286
+ ([`dataset.py:13`](../legacy/root_gnn_dgl/root_gnn_base/dataset.py)),
287
+ in-place `tracking_info` mutation ([`dataset.py:176-181`](../legacy/root_gnn_dgl/root_gnn_base/dataset.py)),
288
+ and in-place DGL graph mutation during forward.
289
+
290
+ The legacy environment assumes Python 3.8, PyTorch 2.0.1, CUDA 11.8, DGL
291
+ 1.1.1, ROOT, Awkward, Uproot, PyYAML, and scikit-learn
292
+ ([`setup/environment.yml:1-10`](../legacy/root_gnn_dgl/setup/environment.yml),
293
+ [`setup/environment.yml:240-295`](../legacy/root_gnn_dgl/setup/environment.yml)).
294
+ The active Linux development environment is intentionally separate: Python
295
+ 3.12, PyTorch 2.2.2/CUDA 12.1, and DGL 2.4.0 from the official DGL wheel
296
+ repository. CUDA runtime wheels do not replace the compatible host NVIDIA
297
+ driver and do not encode Perlmutter module settings.
298
+ Standard configs assume `/global/cfs/` and `/pscratch/` paths, CUDA/NCCL,
299
+ Slurm, and optionally Podman-HPC. `setup/download_data.sh` downloads the
300
+ external Hugging Face dataset `HWresearch/Delphes`
301
+ ([`download_data.sh:13-67`](../legacy/root_gnn_dgl/setup/download_data.sh)).
302
+
303
+ ## Apparent unused or secondary code
304
+
305
+ Not selected by the standard stats/Delphes configs, or only reachable from
306
+ optional workflows, are `GCN_global`, `GCN_global_2way`, most transfer variants,
307
+ attention models, `MultiModel`, and `Clustering`
308
+ ([`GCN.py:122-1933`](../legacy/root_gnn_dgl/models/GCN.py)); `UprootDataset`,
309
+ `tHbbEdgeDataset`, `AugmentedDataset`, and photon-ID paths
310
+ ([`uproot_dataset.py:10-31`](../legacy/root_gnn_dgl/root_gnn_base/uproot_dataset.py),
311
+ [`dataset.py:484-827`](../legacy/root_gnn_dgl/root_gnn_base/dataset.py),
312
+ [`photon_ID_dataset.py:1-33`](../legacy/root_gnn_dgl/root_gnn_base/photon_ID_dataset.py));
313
+ optional loss and similarity utilities; and the no-op
314
+ `root_gnn_base.utils.graph_augmentation` ([`utils.py:393-395`](../legacy/root_gnn_dgl/root_gnn_base/utils.py)).
315
+ The main path evaluates `test_loaders`; validation loaders are only assembled
316
+ when a config has a validation fold ([`training_script.py:682-747`](../legacy/root_gnn_dgl/scripts/training_script.py)).
317
+
318
+ ## 3. De facto interfaces to preserve
319
+
320
+ ### Metadata-aware dataset boundary
321
+
322
+ The rewrite uses named `EventMetadata` (`fold`, `weight`, and stable
323
+ `sample_id`) instead of exposing the legacy positional tracking tensor.
324
+ `GraphSample`, `GraphBatch`, `SplitDefinition`, and `GraphDataLoader` form the
325
+ ROOT-GNN orchestration boundary. Graph caches carry feature, graph, and cache
326
+ schema versions and reject incompatible artifacts before loading.
327
+
328
+ The current cache implementation stores processed `GraphSample` values (the
329
+ Level-2 cache). The separation from `RootEventDataset` is intentional: a
330
+ future Level-1 cache can store normalized `EventSample`/feature data for
331
+ sequence or transformer representations without requiring DGL graph caches.
332
+
333
+ The rewrite's shared data boundary is `gnn4colliders.data`: it reads selected
334
+ ROOT/Awkward branches and returns architecture-neutral event samples. Feature
335
+ construction and graph building remain separate downstream boundaries, so the
336
+ same samples can be reused by non-graph model families.
337
+
338
+ ### Configuration and CLI boundary
339
+
340
+ Hydra composes semantic YAML groups under `configs/` and passes the resolved
341
+ configuration to explicit application factories in `gnn4colliders.config`.
342
+ Those factories allow-list supported models, tasks, and trainer components;
343
+ YAML is never treated as an arbitrary Python import specification. The thin
344
+ `gnn4colliders` CLI selects `prepare`, `train`, `evaluate`, or `predict` and
345
+ delegates to the stable data, training, checkpoint, and inference APIs. A new
346
+ experiment should generally be a YAML change; new behavior belongs in Python.
347
+
348
+ 1. YAML `module`, `class`, `args`, plus runtime `sample_graph` and
349
+ `sample_global` injection.
350
+ 2. Dataset items `(DGLGraph, label, tracking, global_features)`.
351
+ 3. `ndata['features']`, `edata['features']`, seven node columns, and three edge
352
+ columns in `[deta, dphi, dR]` order.
353
+ 4. Tracking column 0 fold and column 1 weight semantics.
354
+ 5. `model(graph, global_feats)`, logits shape `[batch, out_size]`, and
355
+ `representation` where used.
356
+ 6. Weighted per-label loss, metric thresholds, checkpoint keys/prefix cleanup,
357
+ epoch filenames, and `.npz`/ROOT output fields.
358
+
359
+ ## 4. Ambiguous behavior
360
+
361
+ - Historical edge order/self-loop expectations; empty and padding graph inputs.
362
+ - Whether negative weights are meaningful or should always be absolute.
363
+ - Whether β€œvalidation” is intended to differ from the active test-loader path.
364
+ - Shape semantics of multi-label finishers and experimental transfer classes.
365
+ - Whether chunk IDs must match historical `np.array_split` boundaries.
366
+ - Required behavior for missing branches and dynamic selection expressions.
367
+
368
+ ## 5. Recommended rewrite boundaries
369
+
370
+ Separate typed configuration; ROOT/Awkward I/O; selections/folds/features/
371
+ edges; DGL cache/lazy loading/batching; active models and checkpoint adapters;
372
+ objectives/metrics; training lifecycle; and inference/ONNX applications.
373
+ Establish parity for the active `LazyDataset -> PreBatchedDataset ->
374
+ Edge_Network` binary/multiclass path first. Add experimental classes only when
375
+ a config or consumer proves they are required.
docs/compatibility.md ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Compatibility boundary
2
+
3
+ The package's canonical APIs use named `EventMetadata` fields and the version
4
+ 1 checkpoint schema. Compatibility is explicit and one-way: old artifacts are
5
+ adapted into the new representation and are never rewritten implicitly.
6
+
7
+ | Artifact or behavior | Supported | Boundary | Notes |
8
+ | --- | :---: | --- | --- |
9
+ | New checkpoint (`schema_version: 1`) | yes | `CheckpointManager` | Full model/lifecycle resume when state is present |
10
+ | Legacy `model_epoch_N.pt` checkpoint | yes | `gnn4colliders.compat.load_legacy_checkpoint` | Model state and active early-stop fields are adapted |
11
+ | Legacy DDP/compiled prefixes | yes | `normalize_legacy_state_dict_keys` | Supports `module.` and `_orig_mod.` |
12
+ | Legacy ROOT-GNN classifier name | yes | `map_legacy_edge_network_state_dict` | Maps `classify` to `classifier` |
13
+ | Legacy optimizer state | partial | legacy checkpoint adapter | Loaded when present; scheduler state is not available in the historical format |
14
+ | Legacy scheduler state | no | β€” | Historical checkpoints do not carry a supported scheduler state |
15
+ | Positional tracking rows | yes, at ingestion boundary | `EventMetadata.from_legacy_tracking` | Exactly `tracking[0] = fold`, `tracking[1] = weight`; shorter rows fail |
16
+ | Generic/unknown tracking layouts | no | β€” | The package does not guess historical column meanings |
17
+ | Modern NPZ output | yes | `inference.write_npz` | Named fields: `sample_id`, `logits`, `scores`, `predictions`, and available metadata |
18
+ | Historical `tracking_info` NPZ output | no | β€” | No active consumer remains; positional output is intentionally unsupported |
19
+ | Legacy YAML `module`/`class`/`args` | compatibility only | configuration boundary | Accepted only where the semantic factory can safely interpret it; new configs use semantic model names |
20
+
21
+ The frozen `legacy/` tree remains available to parity tests and historical
22
+ investigation. Production modules do not import executable code from it.
docs/configuration.md ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Configuration guide
2
+
3
+ The CLI composes the installed `gnn4colliders.configs/config.yaml` with semantic
4
+ Hydra groups. A config
5
+ describes experiment intent; it does not contain arbitrary Python module or
6
+ class import paths.
7
+
8
+ ## Groups
9
+
10
+ | Group | Purpose |
11
+ | --- | --- |
12
+ | `data` | ROOT source or graph-cache path, batch settings, and fold splits |
13
+ | `model` | Model family and supported ROOT-GNN constructor settings |
14
+ | `task` | Binary or multiclass loss, score, and metric semantics |
15
+ | `trainer` | Device, seed, epochs, optimizer, scheduler, and early stopping |
16
+ | `checkpoint` | Output directory, resume checkpoint, or pretrained checkpoint |
17
+ | `inference` | Checkpoint, split, output path, and output format |
18
+ | `environment` | Device and experiment output root |
19
+ | `distributed` | Single-process/DDP selection and process-group backend |
20
+
21
+ The active model groups are `root_gnn/edge_network` and
22
+ `root_gnn/fine_tuned_edge_network`. The active task groups are
23
+ `pretraining_multiclass`, `binary_classification`, and `tth_cp_finetune`.
24
+
25
+ ## Preparation
26
+
27
+ `prepare` requires `data.files`, `data.cache.path`, `data.feature_branches`,
28
+ `data.object_types`, and `data.scales`. `feature_branches` follows the shared
29
+ seven-column feature contract: one branch/constant specification per output
30
+ column and one entry per configured object type. `CALC_E` and `NODE_TYPE` are
31
+ reserved derived specifications. `object_types` entries are `vector` or
32
+ `single`. Preparation reads the configured tree in file order and writes a
33
+ versioned `GraphSampleCache`.
34
+
35
+ Example overrides are easiest to maintain in a YAML file for real datasets:
36
+
37
+ ```yaml
38
+ # project-local example: data/my_events.yaml
39
+ files: [data/events.root]
40
+ tree_name: Events
41
+ cache:
42
+ path: cache/events.pt
43
+ feature_branches:
44
+ - [jet_pt]
45
+ - [jet_eta]
46
+ - [jet_phi]
47
+ - CALC_E
48
+ - [1.0]
49
+ - [0.0]
50
+ - NODE_TYPE
51
+ object_types: [vector]
52
+ scales: [1, 1, 1, 1, 1, 1, 1]
53
+ fold_var: eventNumber
54
+ weight_var: weight
55
+ ```
56
+
57
+ Then compose it with `data=my_events`. The cache stores processed graph
58
+ samples, labels, globals, named metadata, and feature/graph/cache schema
59
+ versions. Changing the feature or graph schema requires a new compatible cache;
60
+ loading a mismatched schema raises an error.
61
+
62
+ ## Common overrides
63
+
64
+ ```bash
65
+ uv run gnn4colliders train \
66
+ data.cache.path=cache/events.pt \
67
+ data.batch_size=64 \
68
+ trainer.max_epochs=50 \
69
+ trainer.seed=123 \
70
+ environment.output_root=outputs/my_run
71
+ ```
72
+
73
+ `data.batch_size` is per process. `data.splits.train_folds`,
74
+ `validation_folds`, and `test_folds` define conventional train/validation/test
75
+ selection and must be disjoint. Model/task mismatches are rejected during
76
+ config validation; binary tasks require `model.out_size=1`, while multiclass
77
+ tasks require `model.out_size=task.num_classes`.
78
+
79
+ ## Checkpoints and resolved configuration
80
+
81
+ Training writes `epoch_####.pt` and the fully resolved configuration at
82
+ `<environment.output_root>/resolved_config.yaml`. A checkpoint includes schema
83
+ version, model weights/config, task config, trainer/optimizer/scheduler state,
84
+ early stopping state, metadata, and optional RNG state. Set
85
+ `checkpoint.resume=/path/to/epoch_####.pt` to continue a run. Set
86
+ `checkpoint.pretrained=/path/to/epoch_####.pt` with the fine-tuned model group
87
+ to load weights into a new task head; these options are mutually exclusive.
88
+
89
+ ## Environment profiles
90
+
91
+ `environment=local` selects CPU by default. `environment=perlmutter` selects
92
+ the CUDA device and a conventional output-root pattern. Profiles should hold
93
+ device/output policy only; site-specific module loads and filesystem paths
94
+ belong in a launcher or shell environment.
docs/end_to_end_validation.md ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # End-to-end legacy/rewrite validation
2
+
3
+ Task 21 compares staged event identity, labels, folds, weights, globals, node
4
+ features, topology, edge features, batching, fixed-weight forward, loss and
5
+ metrics, one optimizer step, short training, checkpoint reload, and inference.
6
+ The first failing stage is retained in JSON and Markdown reports.
7
+
8
+ Legacy and rewrite extraction may use separate environments. Each writes the
9
+ version-1 artifact described in `validation/README.md`; the comparator never
10
+ imports legacy modules or DGL graph objects. Record ROOT file/tree, selection,
11
+ event count, file size, SHA-256, branches, seeds, versions, device and source
12
+ identities in the artifact manifest. Do not use an absolute personal path as a
13
+ scientific event identity.
14
+
15
+ The captured runtime versions and seed policy are recorded in
16
+ `validation/manifests/environments.json`; the HF composite fixture provenance
17
+ is recorded in `validation/manifests/multiclass_fixture.json`.
18
+
19
+ Strict parity applies to preprocessing, topology, fixed forward, loss, and
20
+ one-step CPU updates. Multi-epoch, GPU and DDP comparisons are scientific:
21
+ compare curves, metrics, distributions and event-level correlations. Named
22
+ metadata, modern NPZ names and the version-1 checkpoint schema are expected
23
+ interface differences and must be reported explicitly.
24
+
25
+ Run the existing gates separately:
26
+
27
+ ```bash
28
+ GNN4COLLIDERS_REQUIRE_ROOT_GNN=1 uv run pytest
29
+ uv run ruff check .
30
+ ```
docs/export.md ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ROOT-GNN ONNX export
2
+
3
+ ONNX export is an inference-only adapter for prepared ROOT-GNN graph batches.
4
+ It does not read ROOT files or move feature construction into the deployment
5
+ model. Install the optional dependencies with:
6
+
7
+ ```bash
8
+ uv sync --extra root-gnn --extra onnx
9
+ ```
10
+
11
+ Export a checkpoint with the project CLI:
12
+
13
+ ```bash
14
+ uv run gnn4colliders export \
15
+ export.checkpoint=/path/to/checkpoint.pt \
16
+ export.output=model.onnx \
17
+ data.cache.path=/path/to/graph-cache.pt
18
+ ```
19
+
20
+ The exported model accepts six tensor inputs: `node_features`,
21
+ `edge_features`, `edge_src`, `edge_dst`, `node_batch`, and `global_features`.
22
+ `node_batch` identifies the graph for each node; edge membership is derived
23
+ from `node_batch[edge_src]`. Graph, node, edge, and batch dimensions are
24
+ dynamic. The model returns raw `logits`; task postprocessing and metadata stay
25
+ outside ONNX.
26
+
27
+ The exporter uses ONNX opset 17, validates the structure with `onnx.checker`,
28
+ and writes compact provenance/schema metadata to `model.onnx.json`. It
29
+ supports `EdgeNetwork` multiclass models and `FineTunedEdgeNetwork` binary
30
+ models. Empty graphs are invalid; single-node graphs (zero edges) are
31
+ represented and pooled with a zero edge contribution.
32
+
33
+ Direct DGL export was not retained: the active model uses DGL graph mutation
34
+ and reductions (`apply_edges`, `update_all`, and graph pooling) that are not a
35
+ portable ONNX contract. The adapter expresses those operations with standard
36
+ tensor indexing, `index_add`, and per-graph means.
docs/migration.md ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Incremental migration plan: `root_gnn_dgl`
2
+
3
+ The target is `legacy/root_gnn_dgl/`. `legacy/physicsnemo/` is a prior rewrite
4
+ attempt and may inspire abstractions, but it is not a parity target. Neither
5
+ legacy tree should be modified during migration.
6
+
7
+ Each phase should add focused unit tests, a deterministic fixture in
8
+ `data/fixtures/`, and parity tests under `tests/parity/` before moving upward.
9
+ Record intentional differences and checkpoint consequences here.
10
+
11
+ ## Phase 0 β€” freeze observations and fixtures
12
+
13
+ Capture a small representative ROOT-equivalent fixture containing the seven
14
+ active node features, three edge features, labels, fold values, weights, and
15
+ globals. Record outputs of `node_features_from_tree`, `full_connected_graph`,
16
+ `EdgeDataset.make_graph`, and `fold_selection`
17
+ ([`dataset.py:15-59`](../legacy/root_gnn_dgl/root_gnn_base/dataset.py),
18
+ [`dataset.py:471-482`](../legacy/root_gnn_dgl/root_gnn_base/dataset.py),
19
+ [`utils.py:121-143`](../legacy/root_gnn_dgl/root_gnn_base/utils.py)). Preserve
20
+ one `.bin`, one `model_epoch_N.pt`, one evaluation `.npz`, and one inference
21
+ `.npz` fixture if available.
22
+
23
+ Task 3 characterization records the active-path observations. Node rows are
24
+ concatenated by object type in the configured order (jets, electrons, muons,
25
+ photons, MET), and the seven columns are `[pt, eta, phi, energy, btag, charge,
26
+ node_type]`. `CALC_E` is `pt*cosh(eta)` before the configured column scale is
27
+ applied. The graph is directed and uses all ordered pairs except self-loops
28
+ for graphs with more than one node; edge order is source-major. A one-node
29
+ graph is a special case: the no-self-loop branch retains its sole self-loop.
30
+ Edge columns are `[deta, dphi, dR]`, with `dphi` wrapped into `[-pi, pi]`.
31
+ Dataset items expose `(graph, label, tracking, global_features)`; tracking
32
+ column 0 is the fold identifier and column 1 is the event weight. These are
33
+ compatibility observations, not proposed fixes.
34
+
35
+ ## Phase 1 β€” configuration boundary
36
+
37
+ Implement a typed configuration layer that reads `Training`, `Model`,
38
+ optional `Loss`, and `Datasets`. Initially retain a compatibility adapter for
39
+ `module`/`class`/`args` and runtime injection of `sample_graph` and
40
+ `sample_global`, matching `buildFromConfig`
41
+ ([`utils.py:10-43`](../legacy/root_gnn_dgl/root_gnn_base/utils.py)). Keep
42
+ dynamic imports isolated at this boundary rather than spreading reflection
43
+ through new code.
44
+
45
+ ## Phase 2 β€” pure preprocessing parity
46
+
47
+ Port and test, in isolation:
48
+
49
+ - branch-to-node conversion, `CALC_E`, `NODE_TYPE`, constants, scaling, empty
50
+ objects, and dtypes (`node_features_from_tree`,
51
+ [`dataset.py:15-50`](../legacy/root_gnn_dgl/root_gnn_base/dataset.py));
52
+ - string/tuple selections and cutflow (`check_selection`, `selection_mask`,
53
+ `compute_cutflow`, [`dataset.py:75-158`](../legacy/root_gnn_dgl/root_gnn_base/dataset.py));
54
+ - fold masks and cache suffixes (`fold_selection`, `fold_selection_name`,
55
+ [`utils.py:121-143`](../legacy/root_gnn_dgl/root_gnn_base/utils.py));
56
+ - deterministic chunk partitioning (`hash_partition`,
57
+ [`batched_dataset.py:27-31`](../legacy/root_gnn_dgl/root_gnn_base/batched_dataset.py)).
58
+
59
+ This is the highest-value parity layer: model parity is invalid if graph inputs
60
+ differ.
61
+
62
+ Task 4 implements the shared branch-to-node feature builder under
63
+ `gnn4colliders.features`. It preserves the active seven-column schema,
64
+ object-type ordering, explicit scales, derived `CALC_E`, node-type codes,
65
+ float32 output, and supported empty vector collections. Selection, fold, and
66
+ chunk helpers remain deferred to later data-infrastructure work.
67
+
68
+ Task 6 implements the shared ROOT/Awkward ingestion boundary under
69
+ `gnn4colliders.data`. `RootEventDataset` returns immutable, architecture-neutral
70
+ `EventSample` values with selected branch data, labels, tracking, and globals;
71
+ events are ordered by input file order with a global zero-based index. Fold
72
+ filtering, caching, batching, and model-specific conversion remain deferred.
73
+
74
+ ## Phase 3 β€” graph construction and cache format
75
+
76
+ Implement graph construction with tests for node/edge counts, directed edge
77
+ ordering, self-loop policy, `[deta, dphi, dR]` order, metadata, and empty graphs.
78
+ Preserve the dataset item contract `(graph, label, tracking, global_features)`
79
+ from `RootDataset.__getitem__`
80
+ ([`dataset.py:465-469`](../legacy/root_gnn_dgl/root_gnn_base/dataset.py)).
81
+
82
+ Then implement DGL `.bin` serialization, lazy chunk loading, pre-batching, and
83
+ padding. Compare against `RootDataset.save/load`, `LazyDataset`, and
84
+ `PreBatchedDataset` ([`dataset.py:396-469`](../legacy/root_gnn_dgl/root_gnn_base/dataset.py),
85
+ [`batched_dataset.py:129-174`](../legacy/root_gnn_dgl/root_gnn_base/batched_dataset.py)).
86
+ Treat `NONE`, `STEPS`, `FIXED`, and `NODE` as explicit features; do not hide
87
+ the hardcoded fixed padding sizes.
88
+
89
+ Task 7 establishes the metadata-aware orchestration boundary around this
90
+ phase: `EventMetadata`, `GraphSample`, `GraphBatch`, fold-based split
91
+ selection, deterministic batching, and a version-checked graph-sample cache.
92
+ The cache is deliberately Level 2; normalized event caching remains a future
93
+ extension so non-graph model families can reuse ROOT preprocessing.
94
+
95
+ ## Phase 4 β€” active model parity
96
+
97
+ Task 8 adds the active `EdgeNetwork` and `FineTunedEdgeNetwork` under
98
+ `gnn4colliders.models.root_gnn`. The update order and MLP ordering follow the
99
+ legacy active path. The rewrite uses an explicit backbone/classifier boundary,
100
+ local DGL graph scope, and does not mutate global RNG state in constructors.
101
+ Model parity now covers fixed-weight pretraining and transfer paths, including
102
+ historical checkpoint prefixes. The legacy transfer implementation has an
103
+ active bug when nonempty globals are supplied (`Pretrained_Output` ignores its
104
+ argument); parity therefore characterizes its supported no-global path, while
105
+ the rewritten model supports both global and fallback modes.
106
+
107
+ Port `models.GCN.Edge_Network` first. Preserve constructor parameters,
108
+ `forward(graph, global_feats)`, feature keys, processor order, MLP LayerNorm
109
+ placement, and logits shape. Compare intermediate and final tensors on fixed
110
+ graphs using the legacy architecture
111
+ ([`GCN.py:18-35`](../legacy/root_gnn_dgl/models/GCN.py),
112
+ [`GCN.py:182-251`](../legacy/root_gnn_dgl/models/GCN.py)).
113
+
114
+ Next port `Transferred_Learning_Finetuning`, including pretrained
115
+ `model_state_dict` loading, removal of the final classifier, and new classifier
116
+ initialization ([`GCN.py:884-997`](../legacy/root_gnn_dgl/models/GCN.py)). Test
117
+ both frozen and unfrozen modes. Defer other model classes until an active
118
+ config or consumer proves they are needed.
119
+
120
+ ## Phase 5 β€” objectives and metrics
121
+
122
+ Implement the default objective exactly: elementwise configured loss,
123
+ tracking-column weights, per-unique-label normalization, and averaging across
124
+ labels ([`training_script.py:320-359`](../legacy/root_gnn_dgl/scripts/training_script.py)).
125
+ Add parity cases for positive, zero, and negative weights and binary versus
126
+ multiclass shapes.
127
+
128
+ Port metric behavior from
129
+ [`training_script.py:438-510`](../legacy/root_gnn_dgl/scripts/training_script.py):
130
+ sigmoid threshold 0.5, argmax, weight masking, weighted ROC AUC, one-vs-rest
131
+ multiclass AUC, and NaN behavior when AUC is undefined. Add `models/loss.py`
132
+ classes only with dedicated tests; do not substitute their reductions.
133
+
134
+ ## Phase 6 β€” checkpoint and lifecycle
135
+
136
+ Task 10 implemented the in-memory single-process training lifecycle before the
137
+ checkpoint portion of this phase: `Trainer`, explicit optimizer/scheduler
138
+ builders, `EarlyStopping`, reproducibility seeding, `GraphBatch.to`, and
139
+ epoch/history result types. Checkpoint persistence/resume and the Python
140
+ inference/evaluation and named NPZ/ROOT output layers are now implemented.
141
+ Distributed execution and CLI wiring were completed in the later phases.
142
+
143
+ Task 10 also establishes corrected split semantics: validation is evaluated
144
+ every epoch and is the only split used for model selection or early stopping;
145
+ the test split remains held out and is evaluated separately after fitting. The
146
+ legacy loader naming inversion (`test` used for selection and `val` held out)
147
+ is not carried into the rewrite.
148
+
149
+ Create a checkpoint adapter preserving `model_epoch_<epoch>.pt` and keys
150
+ `epoch`, `model_state_dict`, `optimizer_state_dict`, and `early_stop`
151
+ ([`training_script.py:565-604`](../legacy/root_gnn_dgl/scripts/training_script.py)).
152
+ Support legacy DDP/compiled prefixes (`module.` and `_orig_mod.`) as exercised
153
+ by checkpoint lookup and inference
154
+ ([`utils.py:145-248`](../legacy/root_gnn_dgl/root_gnn_base/utils.py),
155
+ [`inference.py:274-290`](../legacy/root_gnn_dgl/scripts/inference.py)). Port
156
+ `EarlyStop` state and log parsing separately
157
+ ([`utils.py:325-390`](../legacy/root_gnn_dgl/root_gnn_base/utils.py)). Verify
158
+ resume, restart, early termination, and `.npz` fields before distributed work.
159
+
160
+ ## Phase 7 β€” CLI, inference, and export
161
+
162
+ Task 12 implemented ordered prediction/evaluation, task-owned score
163
+ semantics, checkpoint weight-only loading, named metadata retention, NPZ
164
+ output, and explicit ROOT entry alignment. The semantic CLI and the validated
165
+ ROOT-GNN ONNX export adapter are implemented.
166
+
167
+ Task 13 adds Hydra composition and a single-process CLI around those existing
168
+ APIs. The current application data boundary is a versioned
169
+ `GraphSampleCache`; ROOT preparation converts events through the shared
170
+ feature and graph builders before writing that cache.
171
+
172
+ Build thin new applications around tested library interfaces in this order:
173
+
174
+ 1. preprocessing/cache generation (`scripts/prep_data.py`);
175
+ 2. training/evaluation (`scripts/training_script.py`);
176
+ 3. inference to `.npz` and ROOT (`scripts/inference.py`);
177
+ 4. ONNX export after PyTorch parity (`gnn4colliders export`).
178
+
179
+ Use subprocess integration tests with tiny fixtures. Preserve CLI options only
180
+ where they serve an active workflow; document removed diagnostic/cluster-only
181
+ options.
182
+
183
+ ## Phase 8 β€” reproducibility and deployment
184
+
185
+ Task 14 adds the initial deployment boundary: CPU/GPU DDP through standard
186
+ `torchrun` variables, rank-local graph-sample sharding, global metric/output
187
+ gathering, rank-0 checkpoint/config writing, and Perlmutter-oriented Slurm
188
+ examples. Evaluation deliberately avoids sampler padding duplicates. The
189
+ remaining follow-up is a streaming or sharded output path for very large
190
+ distributed inference jobs.
191
+
192
+ The seed policy remains explicit: the configured seed is offset by rank for
193
+ process-local randomness, while distributed sample assignment is derived from
194
+ the configured seed, world size, and epoch. GPU kernel nondeterminism and
195
+ exact per-rank RNG checkpoint replay remain environment-dependent. Slurm/NCCL,
196
+ Podman-HPC, ROOT, and Hugging Face integrations stay in launcher/adapters
197
+ rather than package code.
198
+
199
+ ## Checkpoint compatibility checklist
200
+
201
+ - [x] Load a checked-in or generated multiclass pretrained checkpoint.
202
+ - [x] Load a legacy fine-tuning checkpoint after prefix normalization.
203
+ - [x] Resume optimizer and early-stop state.
204
+ - [x] Produce equivalent logits on a deterministic graph fixture.
205
+ - [x] Produce equivalent `.npz` score, label, and metadata fields.
206
+ - [x] Preserve ROOT scalar/vector score branch conventions in the Python adapter.
207
+
208
+ Known risks are documented in [`architecture.md`](architecture.md): edge order,
209
+ self-loops, weight semantics, validation/test naming, padding, dynamic
210
+ selection evaluation, reproducibility, and the experimental model/loss surface.
211
+
212
+ ## Migration closure status
213
+
214
+ ### Task 18 compatibility closure
215
+
216
+ The compatibility boundary is now explicit in `gnn4colliders.compat`.
217
+ Production ingestion stores named `EventMetadata`; legacy two-column tracking
218
+ is converted only at the compatibility boundary. Checkpoint prefix cleanup and
219
+ the historical ROOT-GNN `classify` to `classifier` mapping have one canonical
220
+ implementation. The new checkpoint schema and named NPZ output remain
221
+ canonical. See [`compatibility.md`](compatibility.md) for the supported and
222
+ intentionally unsupported historical artifacts.
223
+
224
+ The following matrix describes the supported new stack, rather than every
225
+ class that exists in `legacy/`:
226
+
227
+ | Legacy area | New-stack status | Notes |
228
+ | --- | --- | --- |
229
+ | ROOT/Awkward ingestion | migrated | `RootEventDataset` returns `EventSample` in file/event order |
230
+ | node features | migrated + parity-tested | seven-column schema, `CALC_E`, ordering, scales, float32 |
231
+ | edge construction | migrated + parity-tested | directed source-major topology and `[deta,dphi,dR]` |
232
+ | graph cache | migrated | versioned `GraphSampleCache`; graph-level cache only |
233
+ | folds and weights | migrated | named `EventMetadata.fold` and `.weight` |
234
+ | batching | migrated | deterministic local loader and DDP sharding |
235
+ | legacy padding modes | deferred | no active new-stack consumer |
236
+ | `Edge_Network` | migrated + parity-tested | `EdgeNetwork`, raw logits |
237
+ | transfer/fine-tuning | migrated + parity-tested | frozen or trainable backbone |
238
+ | loss and metrics | migrated + parity-tested | task-owned weighted reductions and full-split AUC |
239
+ | training lifecycle | migrated | `Trainer`, validation semantics, scheduler, early stopping |
240
+ | checkpoints/resume | migrated | schema v1; historical weight/prefix adapter |
241
+ | inference/NPZ | migrated | named output fields and ordered accumulation |
242
+ | ROOT score output | compatibility adapter | Python API supported; CLI currently NPZ-only |
243
+ | DDP | migrated | torchrun boundary, rank-0 artifacts, gathered metrics |
244
+ | Slurm/Perlmutter | launcher examples | site policy remains outside package code |
245
+ | ONNX export | migrated for ROOT-GNN | tensor-only adapter, ONNX Runtime validation, and `export` CLI; raw graph tensors are the input contract |
246
+
247
+ ### Intentional redesigns
248
+
249
+ These are deliberate new-stack contracts, not accidental parity failures:
250
+
251
+ * `tracking[:, 0]` and `tracking[:, 1]` become named `metadata.fold` and
252
+ `metadata.weight`; public consumers do not depend on positional columns.
253
+ * Dynamic legacy YAML `module`/`class` construction becomes allow-listed
254
+ semantic Hydra configuration.
255
+ * The monolithic training script becomes `Task` + `Trainer` + checkpoint and
256
+ inference adapters.
257
+ * Graph state is scoped to the forward pass rather than relying on persistent
258
+ mutation of shared graph state.
259
+ * Model constructors do not mutate global RNG state; seeding is explicit in
260
+ the training/application boundary.
261
+ * Validation is the selection/early-stopping split and test is held out. This
262
+ corrects the legacy loader-name inversion.
263
+
264
+ Compatibility preserves externally observable scientific behavior where it is
265
+ validated; it does not promise to preserve every legacy implementation bug.
266
+ The characterized legacy transfer path had a nonempty-global handling bug;
267
+ the rewrite supports named globals. Negative weights, rare empty graphs,
268
+ historical checkpoint variants, and legacy padding edge cases remain areas to
269
+ audit when a supported consumer requires them.
270
+
271
+ ## ROOT-GNN v1 completion checklist
272
+
273
+ - [x] active ROOT data path and graph cache
274
+ - [x] validated feature, graph, model, task, and metric behavior
275
+ - [x] train from scratch and fine-tune a pretrained backbone
276
+ - [x] resume new-stack checkpoints and load supported historical weights
277
+ - [x] evaluate and predict named outputs
278
+ - [x] single-process and DDP application boundaries
279
+ - [x] Perlmutter/Slurm launcher examples and profiling guidance
280
+ - [x] ROOT-GNN ONNX export and CPU Runtime parity
281
+ - [ ] streaming/sharded large-scale prediction output
282
+ - [ ] removal of frozen legacy reference
283
+ - [ ] ROOT-Transformer representation/model
284
+
285
+ ROOT-GNN v1 is complete when the checked-in new stack can prepare active data,
286
+ reproduce validated legacy behavior, train, transfer, resume, evaluate,
287
+ predict, and run single-process or DDP workflows. The remaining unchecked
288
+ items are intentionally deferred rather than undocumented promises.
docs/performance.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Performance notes
2
+
3
+ The scripts in [`../benchmarks/`](../benchmarks/) separate setup, warmup, and
4
+ steady-state timings and emit JSON lines with execution metadata. Float32 eager
5
+ execution remains the correctness reference path.
6
+
7
+ `fully_connected_edges` has a bounded 32-entry cache keyed by node count,
8
+ self-loop policy, and device. It preserves source-major ordering and only
9
+ reuses topology indices; event-dependent edge features are always recomputed.
10
+ The cache is graph-specific and does not alter scientific behavior.
11
+
12
+ Training already uses `zero_grad(set_to_none=True)` and inference already uses
13
+ `torch.inference_mode()` with detached CPU accumulation.
14
+
15
+ Mixed precision, `torch.compile`, custom kernels, aggressive worker defaults,
16
+ and cache-format replacement were not retained without target-machine
17
+ measurements. The main known bottleneck is the quadratic graph workload
18
+ `N * (N - 1)` and associated DGL message passing; size-aware batching and
19
+ streaming prediction remain follow-up work because they affect ordering or
20
+ output semantics.
docs/perlmutter.md ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Perlmutter execution
2
+
3
+ The package does not encode Perlmutter paths, modules, or allocation policy.
4
+ Create the uv environment in the project location appropriate for your
5
+ account, select a site-compatible GPU/driver environment, and use the same
6
+ Hydra configuration as on a workstation.
7
+
8
+ ## Single GPU
9
+
10
+ ```bash
11
+ uv run gnn4colliders train \
12
+ data.cache.path=/path/to/graphs.pt \
13
+ environment=perlmutter \
14
+ trainer.device=cuda \
15
+ trainer.max_epochs=10
16
+ ```
17
+
18
+ The equivalent Slurm wrapper is:
19
+
20
+ ```bash
21
+ sbatch scripts/slurm/train_single_gpu.sh \
22
+ data.cache.path=/path/to/graphs.pt trainer.max_epochs=10
23
+ ```
24
+
25
+ ## Single-node DDP
26
+
27
+ ```bash
28
+ GPUS_PER_NODE=4 sbatch scripts/slurm/train_multi_gpu.sh \
29
+ data.cache.path=/path/to/graphs.pt trainer.max_epochs=10
30
+ ```
31
+
32
+ The wrapper uses `torchrun`; `batch_size` and `num_workers` are per GPU.
33
+ Effective batch size is `data.batch_size * number_of_processes`, and only rank
34
+ 0 writes the shared checkpoint/config/prediction artifacts.
35
+
36
+ ## Multi-node DDP
37
+
38
+ ```bash
39
+ GPUS_PER_NODE=4 sbatch scripts/slurm/train_multi_node.sh \
40
+ data.cache.path=/path/to/graphs.pt trainer.max_epochs=10
41
+ ```
42
+
43
+ Use the provided script as a template and adapt only allocation/account
44
+ settings required by the site. Evaluation and prediction can use
45
+ `scripts/slurm/evaluate.sh`; prediction currently gathers moderate-size
46
+ results in memory.
47
+
48
+ ## Checks and common failures
49
+
50
+ ```bash
51
+ uv run python -c "import torch, dgl; print(torch.__version__, dgl.__version__, torch.cuda.is_available())"
52
+ uv run gnn4colliders --help
53
+ ```
54
+
55
+ An unavailable DGL wheel, incompatible driver, missing cache, or mismatched
56
+ cache schema should be fixed in the environment/input rather than hidden with
57
+ package-level path changes. GPU kernels and distributed execution are not
58
+ promised bitwise deterministic.
docs/releasing.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Releasing
2
+
3
+ The project uses a static version defined once in
4
+ `src/gnn4colliders/__init__.py`; setuptools reads that value for package
5
+ metadata. The current package is not published to PyPI.
6
+
7
+ Before a release:
8
+
9
+ 1. Update `__version__`, `CHANGELOG.md`, and this release checklist.
10
+ 2. Run `uv sync --dev` (and `--extra root-gnn` when ROOT-GNN validation is
11
+ available), then run lint and tests.
12
+ 3. Run `bash scripts/dev/check_release.sh` to build and inspect the sdist and
13
+ wheel and smoke-test a wheel installation outside the checkout.
14
+ 4. Review the generated artifacts and `git diff`, then create a version tag
15
+ according to the repository's release policy.
16
+
17
+ The release-validation script never publishes artifacts. Publishing, if
18
+ adopted later, must use repository-managed credentials or trusted publishing.
19
+
20
+ The direct DGL wheel source is retained in `pyproject.toml` because the
21
+ validated ROOT-GNN environment requires the CUDA 12.1 DGL wheel. Core imports
22
+ do not import DGL or ONNX; install the corresponding extras for those
23
+ workflows.
docs/testing.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Testing
2
+
3
+ The suite is layered by dependency and purpose:
4
+
5
+ ```bash
6
+ # Fast shared-package tests
7
+ uv run pytest tests/unit
8
+
9
+ # Full CPU suite, including integration and parity tests
10
+ uv run pytest
11
+
12
+ # Required ROOT-GNN parity gate (must fail if DGL is unavailable)
13
+ GNN4COLLIDERS_REQUIRE_ROOT_GNN=1 uv run pytest
14
+
15
+ # Optional layers
16
+ uv run pytest -m distributed -v
17
+ uv run pytest -m onnx -v
18
+ uv run pytest -m gpu -v
19
+ GNN4COLLIDERS_ROOT_FIXTURE=/path/to/reduced.root uv run pytest -m real_data -v
20
+ ```
21
+
22
+ Unit tests use deterministic, small tensors and generated ROOT files. DGL,
23
+ ONNX, CUDA, distributed execution, and reduced real-data fixtures remain
24
+ optional layers. Tests should assert public contracts and scientific
25
+ invariants rather than private call sequences. New regression tests should
26
+ use `tmp_path`, explicit seeds, and justified numerical tolerances.
27
+
28
+ Release validation additionally builds a wheel and runs the CLI help command
29
+ in a clean environment; it is not part of the ordinary pytest suite.
examples/README.md ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Examples
2
+
3
+ The supported experiment interface is the root CLI with Hydra configuration;
4
+ examples do not define a second application framework. The repository's
5
+ reference groups cover multiclass pretraining, binary fine-tuning, resume,
6
+ evaluation, and NPZ prediction. Start with the commands in the top-level
7
+ [`README.md`](../README.md), then copy a config group into a local config file
8
+ when a dataset needs more than command-line overrides.
9
+
10
+ For a complete CPU smoke workflow using generated temporary ROOT data:
11
+
12
+ ```bash
13
+ uv run python scripts/dev/smoke_end_to_end.py
14
+ ```
15
+
16
+ Values such as input ROOT paths, cache locations, and checkpoint paths are
17
+ deliberately local placeholders. Production datasets and generated outputs do
18
+ not belong in this directory.
LICENSE β†’ legacy/LICENSE RENAMED
File without changes
legacy/README.md ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ tags:
4
+ - arXiv:2412.10665
5
+ ---
6
+
7
+ This is a demo is of the approach described in the paper, ["Pretrained Event Classification Model for High Energy Physics Analysis"](https://arxiv.org/abs/2412.10665)
8
+ ```
9
+ @misc{ho2024pretrained,
10
+ title={Pretrained Event Classification Model for High Energy Physics Analysis},
11
+ author={Joshua Ho, Benjamin Ryan Roberts, Shuo Han, Haichen Wang},
12
+ year={2024},
13
+ eprint={2412.10665},
14
+ archivePrefix={arXiv}
15
+ }
16
+ ```
17
+
18
+ ## Abstract
19
+
20
+ We introduce a foundation model for event classification in high-energy physics, built on a **Graph Neural Network** architecture and trained on **120 million simulated proton-proton collision events** spanning 12 distinct physics processes. The model is *pretrained* to learn a general and robust representation of collision data using challenging multiclass and multilabel classification tasks.
21
+
22
+ Its performance is evaluated across five event classification tasks, which include both physics processes used during pretraining and new processes not encountered during pretraining. Fine-tuning the pretrained model significantly improves classification performance, particularly in scenarios with limited training data, demonstrating gains in both accuracy and computational efficiency.
23
+
24
+ To investigate the underlying mechanisms behind these performance improvements, we employ a representational similarity evaluation framework based on *Centered Kernel Alignment*. This analysis reveals notable differences in the learned representations of fine-tuned pretrained models compared to baseline models trained from scratch.
25
+
26
+ ## Introduction
27
+
28
+ Machine learning has become a ubiquitous tool in particle physics, employed in a variety of tasks including triggering, simulation, reconstruction, and offline analysis. While its utility spans classification, regression, and generative tasks, the current paradigm of developing machine learning models from scratch for each specific application presents several challenges. This approach not only demands specialized expertise and substantial computing resources but can also result in suboptimal performance due to limited training data. The from-scratch development of models necessitates individual validation studies to ensure that neural networks utilize well-modeled information from training samples, whether derived from Monte Carlo simulations or control samples from experimental data.
29
+
30
+ Foundation models offer a promising direction to address these limitations. These models, pre-trained on large, diverse datasets across various tasks, provide robust and general representations of underlying data structures. Notable examples in other fields include GPT-4 [OpenAI et al., 2024](#ref-openai-2024-gpt4) and BERT [Devlin et al., 2018](#ref-devlin-2018-bert) in natural language processing, Stable Diffusion [Rombach et al., 2021](#ref-rombach-2021-latentdiffusion) in image processing, and AlphaFold [Jumper et al., 2021](#ref-jumper-2021-alphafold) in structural biology. The foundation model approach offers several advantages for particle physics applications: reduced computing resources for fine-tuning [Yosinski et al., 2014](#ref-yosinski-2014-transfer) compared to training from scratch, superior performance on specific tasks (particularly with limited training data), and potentially simplified validation procedures as downstream tasks inherit verified representations from the pre-trained model.
31
+
32
+ Current literature on pretrained models for particle physics can be categorized based on the data representation they handle. Models operating on particle- or event-level numerical data use features like particle four momenta or jets, leveraging self-supervised or generative methods to learn versatile representations. Detector-focused models operate on high-dimensional responses such as calorimeter deposits or pixel hits, employing geometry-aware techniques for accurate simulation and analysis. Finally, models using textual or code representations apply large language model architectures to integrate domain knowledge, enabling tasks like question answering and code generation.
33
+
34
+ Recent studies have begun exploring foundation models tailored to particle physics data, which has a variety of distinct structures and properties across many experiments and data processing stages, including:
35
+
36
+ - particle-level & event-level numeric data [Wildridge et al., 2024](#ref-wildridge-2024-bumblebee), [Katel et al., 2024](#ref-katel-2024-jet), [Golling et al., 2024](#ref-golling-2024-maskedset), [Mikuni & Nachman, 2024](#ref-mikuni-2024-omnilearn), [Harris et al., 2024](#ref-harris-2024-resimulation), [Birk et al., 2024](#ref-birk-2024-omnijet), [Vigl et al., 2024](#ref-vigl-2024-finetune),
37
+ - detector-level & geometry-aware data [Araz et al., 2024](#ref-araz-2024-pointcloud), [Liu et al., 2023](#ref-liu-2023-gaam), [Hashemi et al., 2024](#ref-hashemi-2024-gen), [Huang et al., 2024](#ref-huang-2024-lmtracking),
38
+ - textual or code data [Zhang et al., 2024](#ref-zhang-2024-xiwu).
39
+
40
+ This paper presents a foundation model designed specifically for collider event-level data. In modern collider experiments, final-stage analysis processes information from reconstructed objects that either directly correspond to particles in collision final states (such as leptons and photons) or serve as proxies (such as jets and missing transverse energy). While traditional approaches often relied on "high-level" variables calculated from object features, recent trends favor direct input of event objects and their features into neural networks for analysis tasks. A notable example is [ATLAS Collaboration, 2023](#ref-atlas-2023-4top), which established the observation of simultaneous production of four top quarks with the ATLAS experiment by employing a graph neural network (GNN) architecture to process event-level object information.
41
+
42
+ We present foundation models that adopt an architecture similar to that used for [ATLAS Collaboration, 2023](#ref-atlas-2023-4top). Our models are pre-trained using either multiclass classification or multi-label learning tasks across 12 distinct physics processes. We evaluate these models through fine-tuning and testing on five classification tasks, including both familiar and novel processes not seen during pre-training. Our analysis benchmarks the models' performance improvements, their scaling behavior with training sample size, and computational efficiency, representing the first prototype of a foundation model operating on collider final-state object data.
43
+
44
+ ## Data Samples
45
+
46
+ To provide a diverse set of physics processes for the pretraining, we use Madgraph@NLO 2.7.3 [Alwall et al., 2014](#ref-alwall-2014hca) to generate proton-proton collision events at next-to-leading order (NLO) in Quantum Chromodynamics (QCD). We generate 12 distinct Standard Model (SM) physics processes, including six major Higgs boson production mechanisms: gluon fusion production \\(ggF\\), vector boson fusion \\(VBF\\), associated production of the Higgs boson with a W boson \\(WH\\) or a Z boson \\(ZH\\), associated production of the Higgs boson with a top-quark pair \\(t\bar{t}H\\), and associated production of the Higgs boson with a single top quark and a forward quark \\(tHq\\). Additionally, we simulate six top quark production processes: single top production, top-quark pair production \\(t\bar{t}\\), top quark pair production in association with a pair of photons \\(t\bar{t}\gamma\gamma\\), associated production of a top-quark pair with a W boson \\(t\bar{t}W\\), simultaneous production of three top quarks \\(t\bar{t}t\\), and simultaneous production of four top quarks \\(t\bar{t}t\bar{t}\\). In these samples, the Higgs boson and top quarks decay inclusively. These 12 Higgs and top quark production processes constitute the pretraining dataset.
47
+
48
+ To test the pretrained model, we further generated four processes including three beyond Standard Model (SM) processes: a SM \\(t\bar{t}H\\) production where the Higgs boson decays exclusively to a pair of photons, a \\(t\bar{t}H\\) production with the Higgs boson decaying to a pair of photons, where the top-Yukawa coupling is CP-odd, implemented using the Higgs Characterization model [Artoisenet et al., 2013](#ref-artoisinet-2013puc), the production of a pair of superpartners of the top quark (s-top) using the Minimal Supersymmetric Standard Model (MSSM) [Rosiek, 1990](#ref-rosiek-1990), [Allanach et al., 2009](#ref-allanach-2009), and flavor changing neutral current (FCNC) processes [Degrande et al., 2015](#ref-degrande-2015), [Durieux et al., 2015](#ref-durieux-2015). For the s-top process, we simulate the production of heavier s-top pairs \\(t_2\bar{t_2}\\), where each heavier s-top (mass 582 GeV) decays into a lighter s-top \\(t_1\\) or \\(\bar{t_1}\\), mass 400 GeV) and a Higgs boson. The FCNC process involves \\(t\bar{t}\\) production where one top quark decays to a Higgs boson and a light quark. We generate 10 million events for each process, except for \\(tHq\\) and \\(t\bar{t}t\bar{t}\\), where 5 million events were produced.
49
+
50
+ In all simulation samples, the center of mass energy of the proton-proton collision is set to 13 TeV. The Higgs boson, top quarks, and vector bosons are set to decay inclusively (except the \\(t\bar{t}H \rightarrow \gamma\gamma\\) samples), with MadSpin [Artoisenet et al., 2012](#ref-artoisinet-2012st) handling the decays of top quarks and W bosons. The generated events are processed through Pythia 8.235 [Sjostrand et al., 2015](#ref-sjostrand-2015) for parton showering and heavy particle decays, followed by Delphes 3.4.2 [de Favereau et al., 2014](#ref-defavereau-2014) configured to emulate the ATLAS detector [ATLAS Collaboration, 2008](#ref-atlas-2008) for fast detector simulation.
51
+
52
+ The detector-level object selection criteria are defined to align with typical experimental conditions. Photons are required to have transverse momentum \\(p_T \geq 20~\mathrm{GeV}\\) and pseudorapidity \\(|\eta| \leq 2.37\\), excluding the electromagnetic calorimeter crack region \\(1.37 < |\eta| < 1.52\\). Electrons must have \\(p_T \geq 10~\mathrm{GeV}\\) and \\(|\eta| \leq 2.47\\) (excluding the same crack region), while muons are selected with \\(p_T \geq 10~\mathrm{GeV}\\) and \\(|\eta| \leq 2.7\\). Jets are reconstructed using the anti-\\(k_t\\) algorithm [Cacciari et al., 2008](#ref-cacciari-2008gp) with radius parameter \\(\Delta R=0.4\\), where \\(\Delta R\\) is defined as \\(\sqrt{\Delta\eta ^2 + \Delta\phi^2}\\), with \\(\Delta\eta\\) being the difference in pseudorapidity and \\(\Delta\phi\\) the difference in azimuthal angle. Jets must satisfy \\(p_T \geq 25~\mathrm{GeV}\\) and \\(|\eta| \leq 2.5\\). To avoid double-counting, jets are removed if they are within \\(\Delta R < 0.4\\) of a photon or lepton. The identification of jets originating from b-quark decays (b-tagging) is performed by matching jets within \\(\Delta R = 0.4\\) of a b-quark, with efficiency corrections applied to match the performance of the ATLAS experiment's b-tagging algorithm [ATLAS Collaboration, 2019](#ref-atlas-2019bwq).
53
+
54
+ ## Methods
55
+
56
+ ### Overview
57
+
58
+ We present a methodology for developing and evaluating a foundation model for particle collision event analysis. The approach centers on pretraining a Graph Neural Network (GNN) architecture using a comprehensive dataset that spans multiple physics tasks, enabling the model to learn robust and transferable features. For task-specific applications, we employ a fine-tuning strategy that combines output layer adaptation with carefully calibrated learning rates for updating the pretrained parameters.
59
+
60
+ Given the prevalence of classification problems in particle physics data analysis, we evaluate the model's efficacy through a systematic assessment across five binary classification tasks:
61
+
62
+ - \\(t\bar{t}H(\rightarrow \gamma\gamma)\\) with CP-even versus CP-odd t-H interaction
63
+ - \\(t\bar{t}\\) with FCNC top quark decays versus $tHq$ processes
64
+ - \\(t\bar{t}W\\) versus $ttt$ processes
65
+ - Stop pair production with Higgs bosons in the decay chain versus \\(t\bar{t}H\\) processes
66
+ - \\(WH\\) versus \\(ZH\\) production modes
67
+
68
+ Our evaluation metrics encompass classification performance, computational efficiency, and model interpretability. The investigation extends to analyzing the model's scaling behavior with respect to training dataset size, benchmarked against models trained without pretraining. Although we explored transfer learning through parameter freezing of pretrained layers, this approach did not yield performance improvements, leading us to focus our detailed analysis on fine-tuning strategies.
69
+
70
+ This methodological framework demonstrates the potential of foundation models to enhance the efficiency of particle physics analyses while improving task-specific performance, offering a promising direction for future high-energy physics research.
71
+
72
+ ---
73
+
74
+ ### GNN Architecture
75
+
76
+ We implement a Graph Neural Network (GNN) architecture that naturally accommodates the point-cloud structure of particle physics data, employing the DGL framework with a PyTorch backend [Wang et al., 2019][ref-dgl-2019], [Paszke et al., 2019][ref-pytorch-2019]. A fully connected graph is constructed for each event, with nodes corresponding to reconstructed jets, electrons, muons, photons, and \\(\vec{E}_T^{\text{miss}}\\). The features of each node include the four-momentum \\((p_T, \eta, \phi, E)\\) of the object with a massless assumption (\\(E = p_T \cosh \eta\\)), the b-tagging label (for jets), the charge (for leptons), and an integer labeling the type of object represented by the node. We use a placeholder value of 0 for features which are not defined for every node type such as the b-jet tag, lepton charge, or the pseudorapidity of \\(\vec{E}_T^{\text{miss}}\\). We assign the angular distances (\\(\Delta \eta, \Delta \phi, \Delta R\\)) as edge features and the number of nodes $N$ in the graph as a global feature. We denote the node features \\(\{\vec x_i\}\\), edge features \\(\{\vec y_{ij}\}\\), and global features \\(\{\vec z\}\\).
77
+
78
+ The GNN model is based on the graph network architecture described in [Battaglia et al., 2018][ref-graphnets-2018] using simple multilayer perceptron (MLP) feature functions and summation aggregation. The model is comprised of three primary components: an encoder, the graph network, and a decoder. In the encoder, three MLPs embed the nodes, edges, and global features into a latent space of dimension 64. The graph network block, which is designed to facilitate message passing between different domains of the graph, performs an edge update $f_e$, followed by a node update $f_n$, and finally a global update $f_g$, all defined below. The inputs to each update MLP are concatenated.
79
+
80
+ $$
81
+ \vec {y'}_{ij} = f_e\left(\{\vec x_k\},\vec y_{ij},\vec z\right) = \mathrm{MLP}\left(\vec x_i,\vec x_j,\vec y_{ij},\vec z\right)
82
+ $$
83
+
84
+ $$
85
+ \vec{x'}_{i} = f_n\left(\vec x_i,\{\vec{y'}_{jk}\},\vec z\right) = \mathrm{MLP}\left(\vec x_i,\sum_j\vec{y'}_{ij},\vec z\right)
86
+ $$
87
+
88
+ $$
89
+ \vec{z'} = f_g\left(\{\vec{x'}_i\},\{\vec{y'}_{ij}\},\vec z\right) = \mathrm{MLP}\left(\sum_i\vec{x'}_i,\sum_{i,j}\vec{y'}_{ij},\vec z\right)
90
+ $$
91
+
92
+ This graph block is iterated four times with the same update MLPs. Finally, the global features are passed through a decoder MLP and a final layer linear to produce the desired model outputs. Each MLP consists of 4 linear layers, each with an output width of 64, with the `ReLU` activation function. The output of the MLP is then passed through a `LayerNorm` layer [Ba et al., 2016][ref-layernorm-2016]. The total number of trainable parameters in this model is about 400,000.
93
+
94
+ As a performance benchmark, a baseline GNN model is trained from scratch for each classification task. The initial learning rate is set to \\(10^{-4}\\) with an exponential decay following \\(LR(x) = LR_{\text{initial}}\cdot(0.99)^x\\), where \\(x\\) represents the epoch number.
95
+
96
+ ---
97
+
98
+ ### Pretraining Strategy
99
+
100
+ We explore two complementary pretraining approaches to develop robust representations of collision events: (1) multi-class classification, which trains the model to distinguish between different physics processes, and (2) multi-label classification, which predicts the existence and kinematics of heavy particles with prompt decays. The pretraining dataset consists of approximately 120 million events, evenly distributed across 12 distinct physics processes, including all major Higgs boson production mechanisms and top quark processes as described in [Data Samples](#sec-data). This large-scale pretraining effort was conducted on the Perlmutter supercomputer at NERSC.
101
+
102
+ #### Multi-class Classification
103
+
104
+ For Monte Carlo simulated events, the underlying physics process that generated each event is known precisely, providing natural labels for supervised learning. However, the challenge lies in the complexity of collision events: different physics processes can produce similar kinematics and event topologies, particularly in certain regions of phase space. No single observable can unambiguously identify the underlying process. By training the model to distinguish between 12 different processes simultaneously, we challenge it to learn subtle differences in kinematics and topology that collectively characterize each process. The model is trained using categorical cross entropy as the loss function. The output layer of the multiclass classification model has 832 trainable parameters.
105
+
106
+ #### Multi-label Classification
107
+
108
+ This approach combines both classification and regression tasks to characterize collision events. For discrete properties like particle presence in specific kinematic regions, we employ classification labels with binary cross-entropy loss. For continuous quantities like particle multiplicities, we use regression labels with mean-squared error loss. This hybrid approach enables the model to learn both categorical and continuous aspects of the physics processes simultaneously.
109
+
110
+ We develop a comprehensive set of 41 labels that capture both particle multiplicities and kinematic properties. This approach increases prediction granularity and enhances model interpretability. By training the model to predict event kinematics rather than event identification, we create a task-independent framework that can potentially generalize better to novel scenarios not seen during pretraining.
111
+
112
+ The particle multiplicity labels count the number of Higgs bosons (\\(n_{\text{higgs}}\\)), top quarks (\\(n_{\text{tops}}\\)), vector bosons (\\(n_V\\)), \\(W\\) bosons (\\(n_W\\)), and \\(Z\\) bosons (\\(n_Z\\)). The kinematic labels characterize the transverse momentum (\\(p_T\\)), pseudorapidity (\\(\eta\\)), and azimuthal angle (\\(\phi\\)) of Higgs bosons and top quarks through binned classifications.
113
+
114
+ For Higgs bosons, $p_T$ is categorized into three ranges: (0, 30) GeV, (30, 200) GeV, and (200, \\(\infty\\)) GeV, with the upper range particularly sensitive to potential BSM effects. Similarly, both leading and subleading top quarks have $p_T$ classifications spanning (0, 30) GeV, (30, 300) GeV, and (300, \\(\infty\\)) GeV. When no particle exists within a specific \\(p_T\\) range, the corresponding label is set to \\([0, 0, 0]\\). For all particles, \\(\eta\\) measurements are divided into 4 bins with boundaries at \\([-1.5, 0, 1.5]\\), while \\(\phi\\) measurements use 4 bins with boundaries at \\([-\frac{\pi}{2}, 0, \frac{\pi}{2}]\\). As with \\(p_T\\), both \\(\eta\\) and \\(\phi\\) labels default to \\([0, 0, 0, 0]\\) in the absence of a particle. This comprehensive labeling schema enables fine-grained learning of kinematic distributions and particle multiplicities, essential for characterizing complex collision events.
115
+
116
+ The loss function combines individual losses from all 41 labels through weighted averaging. Binary cross-entropy is applied to classification labels, while mean-squared error is used for regression labels. The model generates predictions for all labels simultaneously, with individual losses calculated according to their respective types. The final loss is computed as an equally-weighted average across all labels, with weights set to 1 to ensure uniform contribution to the optimization process. The output layer of the multilabel model has 2,688 trainable parameters.
117
+
118
+ #### Pretraining
119
+
120
+ During pre-training, the initial learning rate is \\(10^{-4}\\), and the learning rate decays by 1% each epoch following the power law function \\(LR(x) = 10^{-4}\cdot(0.99)^x\\), where \\(x\\) is the number of epochs. Both pre-trained models reach a plateau in loss by epoch 50, at which point the training is stopped.
121
+
122
+ ---
123
+ ### Fine-tuning Methodology
124
+
125
+ For downstream tasks, we adjust the model architecture for fine-tuning by replacing the original output layer (final linear layer) with a newly initialized linear layer while retaining the pre-trained weights for all other layers. This modification allows the model to specialize in the specific downstream task while leveraging the general features learned during pretraining.
126
+
127
+ The fine-tuning process begins with distinct learning rate setups for different parts of the model. The newly initialized linear layer is trained with an initial learning rate of \\(10^{-4}\\), matching the rate used for models trained from scratch. Meanwhile, the pre-trained layers are fine-tuned more cautiously with a lower initial learning rate of \\(10^{-5}\\). This approach ensures that the pre-trained layers adapt gradually without losing their general features, while the new layer learns effectively from scratch. Both learning rates decay over time following the same power law function, \\(LR(x) = LR_{initial} \cdot (0.99)^x\\), to promote stable convergence as training progresses.
128
+
129
+ We also evaluated a transfer learning setup in which either the decoder MLP or the final linear layer was replaced with a newly initialized component. During this process, all other model parameters remained frozen, leveraging the pre-trained features without further updating them. However, we did not observe performance improvements using the transfer learning setup. Consequently, we focus on reporting results obtained with the fine-tuning approach.
130
+
131
+ ---
132
+
133
+ ### Performance Evaluation
134
+
135
+ We assess model performance using two figures of merit: the classification accuracy and the Area Under the Curve (AUC) of the Receiver Operating Characteristic (ROC) curve. The accuracy is defined as the fraction of correctly classified events when applying a threshold of 0.5 to the neural network output score. Both metrics demonstrate consistent trends in our analysis.
136
+
137
+ To obtain reliable performance estimates and uncertainties, we employ an ensemble training approach where 5 independent models are trained for each configuration with random weight initialization and random subsets of the training dataset. This enables us to evaluate both the models' sensitivity to initial parameters and to quantify uncertainties in their performance.
138
+
139
+ To investigate how model performance scales with training data, we conducted training runs using sample sizes ranging from \\(10^3\\) to \\(10^7\\) events per class (\\(10^3\\), \\(10^4\\), \\(10^5\\), \\(10^6\\), and \\(10^7\\)) for each model setup: the from-scratch baseline and models fine-tuned from multi-class or multi-label pretrained models. For the \\(10^7\\) case, only the initialization was randomized due to dataset size limitations. All models were evaluated on the same testing dataset, consisting of 2 million events per class, which remained separate from the training process.
140
+
141
+ | **Name of Task** | **Pretraining Task** | \\(10^3\\) | \\(10^4\\) | \\(10^5\\) | \\(10^6\\) | \\(10^7\\) |
142
+ |----------------------|----------------------|--------------------|--------------------|--------------------|--------------------|--------------------|
143
+ | **ttH CP Even vs Odd** | Baseline Accuracy | 56.5 Β± 1.1 | 62.2 Β± 0.1 | 64.3 Β± 0.0 | 65.7 Β± 0.0 | 66.2 Β± 0.0 |
144
+ | | Multiclass (%) | +4.8 Β± 1.1 | +3.4 Β± 0.1 | +1.3 Β± 0.0 | +0.2 Β± 0.0 | βˆ’0.0 Β± 0.0 |
145
+ | | Multilabel (%) | +2.1 Β± 1.2 | +1.9 Β± 0.1 | +0.8 Β± 0.1 | +0.0 Β± 0.0 | βˆ’0.1 Β± 0.0 |
146
+ | **FCNC vs tHq** | Baseline Accuracy | 63.6 Β± 0.7 | 67.8 Β± 0.4 | 68.4 Β± 0.3 | 69.3 Β± 0.3 | 67.9 Β± 0.0 |
147
+ | | Multiclass (%) | +5.8 Β± 0.8 | +1.2 Β± 0.4 | +1.4 Β± 0.3 | +0.5 Β± 0.3 | βˆ’0.0 Β± 0.0 |
148
+ | | Multilabel (%) | βˆ’5.3 Β± 0.8 | βˆ’1.3 Β± 0.4 | +0.9 Β± 0.4 | +0.3 Β± 0.3 | +0.4 Β± 0.1 |
149
+ | **ttW vs ttt** | Baseline Accuracy | 75.8 Β± 0.1 | 77.6 Β± 0.1 | 78.9 Β± 0.0 | 79.8 Β± 0.0 | 80.3 Β± 0.0 |
150
+ | | Multiclass (%) | +3.7 Β± 0.1 | +2.7 Β± 0.1 | +1.3 Β± 0.0 | +0.4 Β± 0.0 | +0.0 Β± 0.0 |
151
+ | | Multilabel (%) | +2.2 Β± 0.1 | +1.1 Β± 0.1 | +0.5 Β± 0.0 | +0.0 Β± 0.0 | βˆ’0.1 Β± 0.0 |
152
+ | **stop vs ttH** | Baseline Accuracy | 83.0 Β± 0.2 | 86.3 Β± 0.1 | 87.6 Β± 0.0 | 88.5 Β± 0.0 | 88.8 Β± 0.0 |
153
+ | | Multiclass (%) | +0.4 Β± 0.2 | +1.9 Β± 0.1 | +1.0 Β± 0.0 | +0.3 Β± 0.0 | +0.0 Β± 0.0 |
154
+ | | Multilabel (%) | +2.8 Β± 0.2 | +1.0 Β± 0.1 | +0.5 Β± 0.0 | +0.0 Β± 0.0 | βˆ’0.0 Β± 0.0 |
155
+ | **WH vs ZH** | Baseline Accuracy | 51.4 Β± 0.1 | 53.9 Β± 0.1 | 55.8 Β± 0.0 | 57.5 Β± 0.0 | 58.0 Β± 0.0 |
156
+ | | Multiclass (%) | +5.2 Β± 0.1 | +5.3 Β± 0.1 | +3.1 Β± 0.0 | +0.6 Β± 0.0 | +0.1 Β± 0.0 |
157
+ | | Multilabel (%) | βˆ’1.1 Β± 0.1 | βˆ’0.9 Β± 0.2 | +0.5 Β± 0.1 | +0.1 Β± 0.0 | βˆ’0.1 Β± 0.0 |
158
+
159
+ > **Table 1**: Accuracy of the traditional model versus the accuracy increase due to fine-tuning from various pretraining tasks.
160
+ > The accuracies are averaged over 5 independently trained models with randomly initialized weights and trained on a random subset of the data. One exception is the \\(10^7\\) training where all models use the same dataset due to limitations on our dataset size. The random subsets are allowed to overlap, but this overlap should be very minimal because all models take an independent random subset of \\(10^7\\) events. The testing accuracy is calculated from the same testing set of 2 million events per class across all models for a specific training task. The errors are the propagated errors (root sum of squares) of the standard deviation of accuracies for each model.
161
+
162
+ ## Results
163
+
164
+ ### Classification Performance
165
+
166
+ Since the observations of AUC and accuracy show similar trends, we focus the presentation of the results using accuracy here for conciseness in Table 1.
167
+
168
+ In general, the fine-tuned pretrained model achieves at least the same level of classification performance as the baseline model. Notably, there are significant improvements, particularly when the sample size is small, ranging from \\(10^3\\) to \\(10^4\\) events. In some cases, the accuracy improvements exceed five percentage points, demonstrating that pretrained models provide a strong initial representation that compensates for limited data. The numerical values of the improvements in accuracy may not fully capture the impact on the sensitivity of the measurements for which the neural network classifier is used, and the final sensitivity improvement is likely to be greater.
169
+
170
+ As the training sample size grows to \\(10^5\\), \\(10^6\\), and eventually \\(10^7\\) events, the added benefit of pretraining diminishes. With abundant data, models trained from scratch approach or even match the accuracy of fine-tuned pretrained models. This suggests that large datasets enable effective learning from scratch, rendering the advantage of pretraining negligible in such scenarios.
171
+
172
+ Although both pretraining approaches offer benefits, multiclass pretraining tends to provide more consistent improvements across tasks, especially in the low-data regime. In contrast, multilabel pretraining can sometimes lead to neutral or even slightly negative effects for certain tasks and data sizes. This highlights the importance of the pretraining task design, as the similarity between pretraining and fine-tuning tasks in the multiclass approach appears to yield better-aligned representations.
173
+
174
+ Finally, the spread of accuracy across the five tasks for the baseline model is quite large, offering a robust test of fine-tuning across tasks of varying difficulty. The consistent observation of these trends across tasks confirms the reliability and robustness of the findings.
175
+
176
+ ---
177
+
178
+ ### Model Interpretability
179
+
180
+ We aim to understand whether pretrained and baseline models learn the same underlying representations. If the two models exhibit high similarity, a plausible interpretation is that pretraining provides the pretrained model with an advantageous initialization, allowing it to converge to a similar state as the baseline model more efficiently. Conversely, significant differences between the models would indicate that pretraining facilitates the development of a more general and robust latent space, which serves as a foundation for fine-tuning to effectively adapt to the downstream task. To investigate this, we analyzed the representational similarity between a pretrained model fine-tuned for the downstream task and a baseline model trained directly on the downstream task without pretraining.
181
+
182
+ We use Centered Kernel Alignment (CKA) [Kornblith et al., 2019][ref-kornblith-2019-cka] to analyze model similarity and interpretability. CKA is a robust metric that quantifies the similarity between the internal representations of neural networks by comparing their feature matrices in a manner that is invariant to scaling, rotation, and alignment. This invariance makes CKA particularly effective for studying relationships between network layers, even across networks of different sizes or those trained from varying initializations.
183
+
184
+ The similarity is evaluated using a 64-dimensional latent representation after the decoder stage of the GNN model. This choice allows us to compare the internal states of the models at a fine-grained level and understand how training strategies impact the representations directly used for the output task.
185
+
186
+ To provide an intuitive understanding of CKA values, we construct a table of the CKA scores for various transformations performed on a set of dummy data.
187
+
188
+ - **A:** randomly initialized matrix with shape (1000, 64), following a normal distribution (\\(\sigma = 1, \mu = 0\\))
189
+ - **B:** matrix with shape (1000, 64) constructed via various transformations performed on \\(A\\)
190
+ - **Noise:** randomly initialized noise matrix with shape (1000, 64), following a normal distribution (\\(\sigma = 1, \mu = 0\\))
191
+
192
+ | Dataset | CKA Score |
193
+ |---------|-----------|
194
+ | \\(A, B = A\\) | 1.00 |
195
+ | \\(A, B =\\) permutation on columns of \\(A\\) | 1.00 |
196
+ | \\(A, B = A + \mathrm{Noise}(0.1)\\) | 0.99 |
197
+ | \\(A, B = A + \mathrm{Noise}(0.5)\\) | 0.80 |
198
+ | \\(A, B = A + \mathrm{Noise}(0.75)\\) | 0.77 |
199
+ | \\(A, B = A \cdot \mathrm{Noise}(1)\\) (Linear Transformation) | 0.76 |
200
+ | \\(A, B = A + \mathrm{Noise}(1)\\) | 0.69 |
201
+ | \\(A, B = A + \mathrm{Noise}(2)\\) | 0.51 |
202
+ | \\(A, B = A + \mathrm{Noise}(5)\\) | 0.39 |
203
+
204
+ **Table 2:** CKA scores for a dummy dataset \\(A\\) and \\(B\\), where \\(B\\) is created via various transformations performed on \\(A\\).
205
+
206
+ As seen in Table 2 and in the definition of the CKA, the CKA score is permutation-invariant. We will use the CKA score to evaluate the similarity between various models and gain insight into the learned representation of detector events in each model (i.e., the information that each model learns).
207
+
208
+ We train ensembles of models for each training task to observe how the CKA score changes due to the random initialization of our models. The CKA score between two models is then defined to be:
209
+
210
+ \\[
211
+ CKA(A, B) = \frac{1}{n^2} \sum_i^n \sum_j^n CKA(A_i, B_j)
212
+ \\]
213
+
214
+ where \\(A_i\\) is the representation learned by the \\(i^{\text{th}}\\) model in an ensemble with \\(n\\) total models. The error in CKA is the standard deviation of \\(CKA(A_i, B_j)\\).
215
+
216
+ Here we present results for the CKA similarity between the final model in each setup with the final model in the baseline, shown in Table 3.
217
+
218
+ | Training Task | Baseline | Multiclass | Multilabel |
219
+ |-----------------------|------------------|-----------------|-----------------|
220
+ | ttH CP Even vs Odd | 0.94 Β± 0.05 | 0.82 Β± 0.01 | 0.77 Β± 0.06 |
221
+ | FCNC vs tHq | 0.96 Β± 0.03 | 0.76 Β± 0.01 | 0.81 Β± 0.01 |
222
+ | ttW vs ttt | 0.91 Β± 0.08 | 0.75 Β± 0.10 | 0.72 Β± 0.05 |
223
+ | stop vs ttH | 0.87 Β± 0.11 | 0.79 Β± 0.12 | 0.71 Β± 0.08 |
224
+ | WH vs ZH | 0.90 Β± 0.07 | 0.53 Β± 0.03 | 0.44 Β± 0.06 |
225
+
226
+ **Table 3:** CKA Similarity of the latent representation before the decoder with the baseline model, averaged over 3 models per training setup, and all models trained with the full dataset (\\(10^7\\)). The baseline column is not guaranteed to be 1.0 because of the random initialization of the model. Each baseline model converges to a slightly different representation as seen in the CKA values in that column.
227
+
228
+ The baseline models with different initializations exhibit high similarity values, ranging from approximately 0.87 to 0.96, which indicates that independently trained baseline models tend to converge on similar internal representations despite random initialization. Across the considered tasks, models trained as multi-class or multi-label classifiers exhibit noticeably lower CKA similarity scores when compared to the baseline model. For example, in the WH vs ZH task, the baseline model and another baseline trained model have a high similarity of 0.90, whereas the multi-class and multi-label models show significantly reduced similarities (0.53 and 0.44, respectively). This pattern suggests that the representational spaces developed by multi-class or multi-label models differ substantially from those learned by the baseline model that was trained directly on the downstream classification task.
229
+
230
+ ### Computational Efficiency
231
+
232
+ To estimate the computational resources required for each approach, we measured the wall time needed for a model to reach its final performance. For baseline models, this is defined as the wall time from the start of training until the loss of the model plateaus. For the foundation model approach, the estimate includes both the pretraining time and the fine-tuning time, each measured from the start of training until the loss plateaus. This approach ensures a consistent and comprehensive evaluation of the computational demands.
233
+
234
+ ![The ratio of the fine-tuning time required to achieve 99% of the baseline model's final classification accuracy to the total time spent training the baseline model.](training_time.png)
235
+ *Fig. 1: The ratio of the fine-tuning time required to achieve 99% of the baseline model's final classification accuracy to the total time spent training the baseline model.*
236
+
237
+ Figure 1 shows the fine-tuning time for the model pretrained with multiclass classification, relative to the time required for the baseline model, as a function of training sample size. In general, the fine-tuning time is significantly shorter than the training time required by the baseline model approach. For smaller training sets, on the order of \\(10^5\\) events, tasks such as FCNC vs. tHq and ttW vs. ttt benefit substantially from the pretrained model’s β€œhead start,” achieving their final performance in only about 1% of the baseline time. For large training datasets, the fine-tuning time relative to the baseline training time becomes larger; however, given that the large training sample typically requires longer training time, fine-tuning still yields much faster training convergence. The ttH CP-even vs. ttH CP-odd task, with a training sample size of \\(10^7\\) events, is an exception where the fine-tuning time exceeds the training time required for the baseline model. This is likely because the processes involved in this task include photon objects in the final states, which are absent from the events used during pretraining.
238
+
239
+ To accurately evaluate the total time consumption, it is necessary to include the pretraining time required for the foundation model approach. The pretraining times are as follows:
240
+
241
+ - **Multi-class pretraining:** 45.5 GPU hours
242
+ - **Multi-label pretraining:** 60.0 GPU hours
243
+
244
+ The GPU hours recorded for the multi-label model represent the total time required when training the model in parallel on 16 GPUs. This includes a model synchronization step, which results in higher GPU hours compared to the multi-class pretraining model.
245
+
246
+ The foundation model approach becomes increasingly efficient when a large number of tasks are fine-tuned using the same pretrained model, compared to training each task independently from scratch. To illustrate this, we evaluate the computational time required for a scenario where the training sample contains \\(10^7\\) events. For the five tasks tested in this study, the baseline training time (training from scratch) ranges from 1.68 GPU hours (WH vs. ZH) to 5.30 GPU hours (ttW vs. ttt), with an average baseline training time of 2.94 GPU hours. In contrast, the average fine-tuning time for the foundation model approach, relative to the baseline, is 38% of the baseline training time for \\(10^7\\) events. Based on these averages, we estimate that the foundation model approach becomes more computationally efficient than the baseline approach when fine-tuning is performed for more than 41 tasks.
247
+
248
+ As a practical example, the ATLAS measurement of Higgs boson couplings using the \\(H \rightarrow \gamma\gamma\\) decay channel [ATLAS Collaboration, 2023][ref-atlas-2023-higg] involved training 42 classifiers for event categorization. This coincides with our estimate, suggesting that the foundation model approach can reduce computational costs even for a single high-energy physics measurement.
249
+
250
+ ## Conclusions
251
+
252
+ We presented an in-depth study of a particle physics foundation model designed to operate on the four-momentum and identification properties of event final-state objects. This model is built on a Graph Neural Network (GNN) architecture and trained on a dataset comprising 120 million simulated proton-proton collision events across 12 distinct physics processes. The pretraining phase explored both multiclass and multilabel classification tasks, providing a robust foundation for downstream applications. Notably, the pretrained models demonstrated significant improvements in event classification performance when fine-tuned, particularly for tasks with limited training samples.
253
+
254
+ The foundation model approach also offers substantial computational advantages. By leveraging fine-tuning, this methodology reduces the computational resources required for large-scale applications across multiple tasks. Our estimates indicate that significant resource savings can be achieved even for single particle physics measurements, making this approach both scalable and efficient.
255
+
256
+ To better understand the learned representations of the pretrained model and guide future optimization efforts, we employed a representational similarity evaluation framework using Centered Kernel Alignment (CKA). This metric allowed us to investigate the source of the performance gains observed in the foundation model. Our analysis revealed notable differences in the learned representations between the fine-tuned pretrained model and a baseline model trained from scratch. In deep learning, it is well-established that multiple equally valid solutions can exist. Future studies are necessary to determine whether the low similarity in latent representations reflects complementary information uniquely captured by the foundation and baseline models, or if it can simply be attributed to connected local minima in the loss landscape.
257
+
258
+ ## Acknowledgments
259
+
260
+ This work is supported by the U.S. National Science Foundation under the Award No. 2046280, and by U.S. Department of Energy, Office of Science under contract DE-AC02-05CH11231.
261
+
262
+ ## References
263
+
264
+ - <span id="ref-openai-2024-gpt4"></span> **OpenAI et al.** GPT-4 Technical Report. arXiv:2303.08774 (2024). [https://arxiv.org/abs/2303.08774](https://arxiv.org/abs/2303.08774)
265
+
266
+ - <span id="ref-yosinski-2014-transfer"></span> **Jason Yosinski, Jeff Clune, Yoshua Bengio, Hod Lipson.** How transferable are features in deep neural networks? CoRR abs/1411.1792 (2014). [http://arxiv.org/abs/1411.1792](http://arxiv.org/abs/1411.1792)
267
+
268
+ - <span id="ref-rombach-2021-latentdiffusion"></span> **Robin Rombach, Andreas Blattmann, Dominik Lorenz, Patrick Esser, BjΓΆrn Ommer.** High-Resolution Image Synthesis with Latent Diffusion Models. CoRR abs/2112.10752 (2021). [https://arxiv.org/abs/2112.10752](https://arxiv.org/abs/2112.10752)
269
+
270
+ - <span id="ref-podell-2023-sdxl"></span> **Dustin Podell, Zion English, Kyle Lacey et al.** SDXL: Improving Latent Diffusion Models for High-Resolution Image Synthesis. arXiv:2307.01952 (2023). [https://arxiv.org/abs/2307.01952](https://arxiv.org/abs/2307.01952)
271
+
272
+ - <span id="ref-jumper-2021-alphafold"></span> **John Jumper, Richard Evans, Alexander Pritzel et al.** Highly accurate protein structure prediction with AlphaFold. Nature 596, 583-589 (2021). [https://doi.org/10.1038/s41586-021-03819-2](https://doi.org/10.1038/s41586-021-03819-2)
273
+
274
+ - <span id="ref-devlin-2018-bert"></span> **Jacob Devlin, Ming-Wei Chang, Kenton Lee, Kristina Toutanova.** BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. CoRR abs/1810.04805 (2018). [http://arxiv.org/abs/1810.04805](http://arxiv.org/abs/1810.04805)
275
+
276
+ - <span id="ref-atlas-2023-higg"></span> **ATLAS Collaboration.** Measurement of the properties of Higgs boson production at \\(\sqrt{s} = 13\,\text{TeV}\\) in the \\(H \to \gamma\gamma\\) channel using \\(139\,\text{fb}^{-1}\\) of \\(pp\\) collision data with the ATLAS experiment. JHEP 07 (2023) 088. [arXiv:2207.00348](https://arxiv.org/abs/2207.00348), [https://doi.org/10.1007/JHEP07(2023)088](https://doi.org/10.1007/JHEP07(2023)088)
277
+
278
+ - <span id="ref-atlas-2023-4top"></span> **ATLAS Collaboration.** Observation of four-top-quark production in the multilepton final state with the ATLAS detector. Eur. Phys. J. C 83 (2023) 496. [arXiv:2303.15061](https://arxiv.org/abs/2303.15061), [https://doi.org/10.1140/epjc/s10052-023-11573-0](https://doi.org/10.1140/epjc/s10052-023-11573-0)
279
+
280
+ - <span id="ref-kornblith-2019-cka"></span> **Simon Kornblith, Mohammad Norouzi, Honglak Lee, Geoffrey Hinton.** Similarity of Neural Network Representations Revisited. CoRR abs/1905.00414 (2019). [http://arxiv.org/abs/1905.00414](http://arxiv.org/abs/1905.00414)
281
+
282
+ ---
283
+
284
+ <!-- Historical/General Physics foundational texts -->
285
+
286
+ - <span id="ref-birell-1982-qfields"></span> **N. D. Birell, P. C. W. Davies.** Quantum Fields in Curved Space. Cambridge Univ. Press (1982).
287
+
288
+ - <span id="ref-feynman-1954"></span> **R. P. Feynman.** Phys. Rev. 94, 262 (1954).
289
+
290
+ - <span id="ref-einstein-1935-epr"></span> **A. Einstein, Yu. Podolsky, N. Rosen.** Phys. Rev. 47, 777 (1935).
291
+
292
+ - <span id="ref-berman-1983-stability"></span> **G. P. Berman, Jr., F. M. Izrailev, Jr.** Stability of nonlinear modes. Physica D 88, 445 (1983).
293
+
294
+ - <span id="ref-davies-1988-trapped"></span> **E. B. Davies, L. Parns.** Trapped modes in acoustic waveguides. Q. J. Mech. Appl. Math. 51, 477–492 (1988).
295
+
296
+ - <span id="ref-witten-2001"></span> **Edward Witten.** hep-th/0106109 (2001). [https://arxiv.org/abs/hep-th/0106109](https://arxiv.org/abs/hep-th/0106109)
297
+
298
+ ---
299
+
300
+ <!-- Particle physics/data science foundational models -->
301
+
302
+ - <span id="ref-beutler-1994-hem"></span> **E. Beutler.** Williams Hematology, 5th Edition, Chapter 7, pp. 654–662. McGraw-Hill, New York (1994).
303
+
304
+ - <span id="ref-knuth-1973-fa"></span> **Donald E. Knuth.** The Art of Computer Programming vol. 1: Fundamental Algorithms, 2nd Ed., Addison-Wesley (1973).
305
+
306
+ - <span id="ref-smith-2005-philos"></span> **J. S. Smith, G. W. Johnson.** Philos. Trans. R. Soc. London, Ser. B 777, 1395 (2005).
307
+
308
+ - <span id="ref-smith-2010-jap-unpub"></span> **W. J. Smith, T. J. Johnson, B. G. Miller.** Surface chemistry and preferential crystal orientation on a silicon surface. J. Appl. Phys. (unpublished, 2010).
309
+
310
+ - <span id="ref-smith-2010-jap-sub"></span> **V. K. Smith, K. Johnson, M. O. Klein.** Surface chemistry and preferential crystal orientation on a silicon surface. J. Appl. Phys. (submitted, 2010).
311
+
312
+ - <span id="ref-underwood-1988-lowerbounds"></span> **Ulrich Underwood, Ned Net, Paul Pot.** Lower Bounds for Wishful Research Results. Talk at Fanstord University (1988).
313
+
314
+ - <span id="ref-johnson-2007-comm"></span> **M. P. Johnson, K. L. Miller, K. Smith.** Personal communication (Jan-May 2007).
315
+
316
+ ---
317
+
318
+ <!-- Prototypical collider software and tools -->
319
+
320
+ - <span id="ref-pytorch-2019"></span> **Adam Paszke et al.** PyTorch: An Imperative Style, High-Performance Deep Learning Library. arXiv:1912.01703 (2019). [http://arxiv.org/abs/1912.01703](http://arxiv.org/abs/1912.01703)
321
+
322
+ - <span id="ref-dgl-2019"></span> **Minjie Wang et al.** Deep Graph Library: Towards Efficient and Scalable Deep Learning on Graphs. arXiv:1909.01315 (2019). [http://arxiv.org/abs/1909.01315](http://arxiv.org/abs/1909.01315)
323
+
324
+ - <span id="ref-graphnets-2018"></span> **Peter W. Battaglia et al.** Relational inductive biases, deep learning, and graph networks. arXiv:1806.01261 (2018). [http://arxiv.org/abs/1806.01261](http://arxiv.org/abs/1806.01261)
325
+
326
+ - <span id="ref-layernorm-2016"></span> **Jimmy Lei Ba, Jamie Ryan Kiros, Geoffrey E. Hinton.** Layer Normalization. arXiv:1607.06450 (2016). [https://arxiv.org/abs/1607.06450](https://arxiv.org/abs/1607.06450)
327
+
328
+ ---
329
+
330
+ <!-- Recent & foundation models in HEP ML -->
331
+
332
+ - <span id="ref-wildridge-2024-bumblebee"></span> **Andrew J. Wildridge et al.** Bumblebee: Foundation Model for Particle Physics Discovery. arXiv:2412.07867 (2024). [https://arxiv.org/abs/2412.07867](https://arxiv.org/abs/2412.07867)
333
+
334
+ - <span id="ref-katel-2024-jet"></span> **Subash Katel et al.** Learning Symmetry-Independent Jet Representations via Jet-Based Joint Embedding Predictive Architecture. arXiv:2412.05333 (2024). [https://arxiv.org/abs/2412.05333](https://arxiv.org/abs/2412.05333)
335
+
336
+ - <span id="ref-araz-2024-pointcloud"></span> **Jack Y. Araz et al.** Point cloud-based diffusion models for the Electron-Ion Collider. arXiv:2410.22421 (2024). [https://arxiv.org/abs/2410.22421](https://arxiv.org/abs/2410.22421)
337
+
338
+ - <span id="ref-leigh-2024-maskedparticle"></span> **Matthew Leigh et al.** Is Tokenization Needed for Masked Particle Modelling? arXiv:2409.12589 (2024). [https://arxiv.org/abs/2409.12589](https://arxiv.org/abs/2409.12589)
339
+
340
+ - <span id="ref-mikuni-2024-omnilearn"></span> **Vinicius Mikuni, Benjamin Nachman.** OmniLearn: A Method to Simultaneously Facilitate All Jet Physics Tasks. arXiv:2404.16091 (2024). [https://arxiv.org/abs/2404.16091](https://arxiv.org/abs/2404.16091)
341
+
342
+ - <span id="ref-zhang-2024-xiwu"></span> **Zhengde Zhang et al.** Xiwu: A Basis Flexible and Learnable LLM for High Energy Physics. arXiv:2404.08001 (2024). [https://arxiv.org/abs/2404.08001](https://arxiv.org/abs/2404.08001)
343
+
344
+ - <span id="ref-harris-2024-resimulation"></span> **Philip Harris et al.** Re-Simulation-based Self-Supervised Learning for Pre-Training Foundation Models. arXiv:2403.07066 (2024). [https://arxiv.org/abs/2403.07066](https://arxiv.org/abs/2403.07066)
345
+
346
+ - <span id="ref-birk-2024-omnijet"></span> **Joschka Birk, Anna Hallin, Gregor Kasieczka.** OmniJet-$\alpha$: the first cross-task foundation model for particle physics. Machine Learning: Science and Technology. 5(3), 035031 (Aug 2024). [https://doi.org/10.1088/2632-2153/ad66ad](https://doi.org/10.1088/2632-2153/ad66ad)
347
+
348
+ - <span id="ref-huang-2024-lmtracking"></span> **Andris Huang et al.** A Language Model for Particle Tracking. arXiv:2402.10239 (2024). [https://arxiv.org/abs/2402.10239](https://arxiv.org/abs/2402.10239)
349
+
350
+ - <span id="ref-golling-2024-maskedset"></span> **Tobias Golling et al.** Masked Particle Modeling on Sets: Towards Self-Supervised High Energy Physics Foundation Models. arXiv:2401.13537 (2024). [https://arxiv.org/abs/2401.13537](https://arxiv.org/abs/2401.13537)
351
+
352
+ - <span id="ref-liu-2023-gaam"></span> **Junze Liu et al.** Generalizing to new geometries with Geometry-Aware Autoregressive Models (GAAMs) for fast calorimeter simulation. Journal of Instrumentation 18(11), P11003 (Nov 2023). [https://doi.org/10.1088/1748-0221/18/11/p11003](https://doi.org/10.1088/1748-0221/18/11/p11003)
353
+
354
+ - <span id="ref-hashemi-2024-gen"></span> **Baran Hashemi et al.** Ultra-high-granularity detector simulation with intra-event aware generative adversarial network and self-supervised relational reasoning. Nature Communications 15(1) (June 2024). [https://doi.org/10.1038/s41467-024-49104-4](https://doi.org/10.1038/s41467-024-49104-4)
355
+
356
+ - <span id="ref-vigl-2024-finetune"></span> **Matthias Vigl et al.** Finetuning Foundation Models for Joint Analysis Optimization. arXiv:2401.13536 (2024). [https://arxiv.org/abs/2401.13536](https://arxiv.org/abs/2401.13536)
357
+
358
+ - <span id="ref-li-2024-refine"></span> **Chen Li, Hao Cai, Xianyang Jiang.** Refine neutrino events reconstruction with BEiT-3. Journal of Instrumentation 19(6), T06003 (Jun 2024). [https://doi.org/10.1088/1748-0221/19/06/t06003](https://doi.org/10.1088/1748-0221/19/06/t06003)
{physicsnemo β†’ legacy/physicsnemo}/configs/config.yaml RENAMED
File without changes
{physicsnemo β†’ legacy/physicsnemo}/configs/config_stats_all.yaml RENAMED
File without changes
{physicsnemo β†’ legacy/physicsnemo}/configs/tHjb_CP_0_vs_45.yaml RENAMED
File without changes
{physicsnemo β†’ legacy/physicsnemo}/configs/tHjb_CP_0_vs_90.yaml RENAMED
File without changes
{physicsnemo β†’ legacy/physicsnemo}/configs/tHjb_CP_0_vs_90_edge_network.yaml RENAMED
File without changes
{physicsnemo β†’ legacy/physicsnemo}/configs/tHjb_CP_0_vs_90_globals.yaml RENAMED
File without changes
{physicsnemo β†’ legacy/physicsnemo}/dataset/Dataset.py RENAMED
File without changes
{physicsnemo β†’ legacy/physicsnemo}/dataset/GraphBuilder.py RENAMED
File without changes
{physicsnemo β†’ legacy/physicsnemo}/dataset/Graphs.py RENAMED
File without changes
{physicsnemo β†’ legacy/physicsnemo}/dataset/Normalization.py RENAMED
File without changes
{physicsnemo β†’ legacy/physicsnemo}/metrics.py RENAMED
File without changes
{physicsnemo β†’ legacy/physicsnemo}/models/Edge_Network.py RENAMED
File without changes
{physicsnemo β†’ legacy/physicsnemo}/models/MeshGraphNet.py RENAMED
File without changes
{physicsnemo β†’ legacy/physicsnemo}/models/utils.py RENAMED
File without changes