diff --git a/.claude/skills/gnn4colliders-workflow/SKILL.md b/.claude/skills/gnn4colliders-workflow/SKILL.md index 9a1d1d46922fe3d9061aaee8bf6f7a96ed3b3d8b..0a8a544885c380e9e67ea272fa736b0b2620f5e3 100644 --- a/.claude/skills/gnn4colliders-workflow/SKILL.md +++ b/.claude/skills/gnn4colliders-workflow/SKILL.md @@ -19,8 +19,9 @@ end-to-end check, run `uv run python scripts/dev/smoke_end_to_end.py`. Run `uv run python -m validation.run_public_validation` for scientific validation and `GNN4COLLIDERS_REQUIRE_ROOT_GNN=1 uv run pytest tests/parity` for strict ROOT-GNN parity. The first transformer path is selected with -`model=root_transformer/transformer`; it adapts node features from a prepared -graph cache and currently supports single-process training only. Before +`model=root_transformer/transformer`; it pads the same prepared event-cache +objects into token sequences and currently supports single-process training +only. All models run on plain PyTorch; there is no DGL dependency. Before non-trivial changes, inspect `docs/architecture.md` and `docs/migration.md`. Historical runtime code is not part of main; use frozen parity fixtures and explicit compatibility diff --git a/.codex/skills/gnn4colliders-workflow/SKILL.md b/.codex/skills/gnn4colliders-workflow/SKILL.md index f113cceb767ccc0f8350b4d62a90848ae9e324d9..bf5561d5f406d27d89eef55ae8e33f9b85abbabc 100644 --- a/.codex/skills/gnn4colliders-workflow/SKILL.md +++ b/.codex/skills/gnn4colliders-workflow/SKILL.md @@ -28,8 +28,9 @@ Key routing: neutral; put graph topology in `graphs/` and model-specific behavior in `models/root_gnn/` or `models/root_transformer/`. - The first transformer path is selected with - `model=root_transformer/transformer`; it adapts node features from a - prepared graph cache and currently supports single-process training only. + `model=root_transformer/transformer`; it pads the same prepared event-cache + objects into token sequences and currently supports single-process training + only. All models run on plain PyTorch; there is no DGL dependency. - Historical runtime code is not part of main. Use committed frozen parity fixtures and explicit compatibility adapters for old checkpoints or output formats. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 23ff57dbcfa8a287c49a5ea2c40c0563f7f00cd8..db1994a394dcafd03a0f56cf2947d5a95e11c86c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,23 +27,27 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + lfs: true - uses: astral-sh/setup-uv@v6 with: version: "0.8.x" enable-cache: true - run: uv sync --dev - - run: uv run pytest + - run: GNN4COLLIDERS_REQUIRE_ROOT_GNN=1 uv run pytest test-macos: - name: test (macOS ROOT-GNN CPU) + name: test (macOS CPU) runs-on: macos-14 steps: - uses: actions/checkout@v4 + with: + lfs: true - uses: astral-sh/setup-uv@v6 with: version: "0.8.x" enable-cache: true - - run: uv sync --dev --extra root-gnn + - run: uv sync --dev - run: uv run pytest tests/unit tests/integration package: @@ -83,5 +87,5 @@ jobs: with: version: "0.8.x" enable-cache: true - - run: uv sync --dev --extra root-gnn --extra onnx + - run: uv sync --dev --extra onnx - run: uv run pytest tests/unit/export -v diff --git a/AGENTS.md b/AGENTS.md index 1e2d23742fef29664721a59cf7ca73f8050c0c89..d322773cb89e3610ee604e2aae4ffe2e38423431 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -382,12 +382,14 @@ unless the task explicitly calls for evaluating or adopting them. Scientific dependencies should be introduced intentionally and with environment compatibility in mind. PyTorch is shared infrastructure for the expected model families and belongs -in the base package dependencies. Architecture-specific dependencies belong in -named extras, for example `root-gnn` for DGL. The canonical development -environment for the active ROOT-GNN rewrite is: +in the base package dependencies. Model families are implemented in plain +PyTorch on the shared packed-event representation; do not reintroduce a graph +or model framework (for example DGL or PyTorch Geometric) as a runtime +dependency without explicit agreement. Architecture-specific optional +dependencies belong in named extras. The canonical development environment is: ```bash -uv sync --extra root-gnn +uv sync --dev ``` --- @@ -449,15 +451,16 @@ pytest ruff check . ``` -ROOT-GNN parity validation requires DGL. A package-wide environment where DGL -is intentionally absent may skip DGL-dependent tests, but that is incomplete -ROOT-GNN validation. The required parity gate is: +ROOT-GNN parity validation compares against committed frozen references (Git +LFS). The required parity gate is: ```bash GNN4COLLIDERS_REQUIRE_ROOT_GNN=1 pytest ``` -The gate must fail when DGL cannot be imported. +The gate must fail when any frozen parity artifact (reference fixtures, +pretrained checkpoint, ROOT fixture) is missing or is an unfetched Git LFS +pointer, so parity tests can never skip silently. Run more focused tests first when appropriate. diff --git a/CHANGELOG.md b/CHANGELOG.md index 187cfb4f3087b880bae3768010000b8269af1d3f..9084f6068251f09110b5ce8954edcbe62106cf71 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,15 +9,30 @@ ### Changed -- Graph-cache preparation moved from `gnn4colliders.config.application` to - `gnn4colliders.graphs.preparation`; the application functions `prepare`, - `prepare_shard`, and `write_shard_manifest` remain as thin wrappers and - produce identical caches. +- DGL was removed. Preparation is vectorized and writes a model-neutral packed + `EventCache` (cache schema 2) instead of pickled DGL graphs; graph batches + (`TensorGraph`, edge-index layout) and transformer token batches are built + per batch from it. The PyTorch model is the canonical `EdgeNetwork` + (`TensorEdgeNetwork` remains an alias). Outputs are pinned bit-for-bit to + frozen DGL references. On real ttH data preparation is about 190x faster, + caches are 14.5x smaller, and GPU training epochs are about 6.5x faster. + Existing graph caches and shards must be prepared again; the `root-gnn` + extra and `model.backend=dgl` no longer exist. See `docs/migration.md`. +- Epoch metrics no longer keep every batch alive until the epoch ends. +- The Slurm training wrappers set `OMP_NUM_THREADS` from the allocation. - Rewrite task specifications moved to `docs/history/rewrite_tasks/` and the paper source to `docs/paper/`; empty scaffolding directories were removed. - The Perlmutter Slurm wrappers documented in `docs/perlmutter.md` are now tracked; an unanchored `slurm/` ignore rule had excluded them. +### Fixed + +- `gnn4colliders train` under DDP deadlocked: only rank 0 called `train`, so + rank 0 waited forever for its peers in `init_process_group`. +- Distributed epoch metrics and evaluation loss combined rank-local logits + with labels and weights gathered from all ranks, which failed with a shape + mismatch. + ### Compatibility - The `0.1.0` package version remains a static, single-source version exposed diff --git a/README_PROJECT.md b/README_PROJECT.md index 5066b36ba0d4302a20fe8a4f70b9596d47ec19c0..4fd75fa22af775a3033a67bc048404de2653b82d 100644 --- a/README_PROJECT.md +++ b/README_PROJECT.md @@ -8,9 +8,9 @@ distributed utilities are designed so that the sequence model (ROOT-Transformer) can reuse them without requiring every event to be a graph. ```text -ROOT files -> EventSample -> shared collider features - ├── GraphSample -> ROOT-GNN - └── SequenceSample -> ROOT-Transformer +ROOT files -> shared collider features -> EventCache (packed objects) + ├── graph batches -> ROOT-GNN + └── sequence batches -> ROOT-Transformer ``` The new implementation lives under [`src/gnn4colliders`](src/gnn4colliders/). @@ -25,22 +25,15 @@ The supported development environment is Python 3.12 (`>=3.12,<3.13`). Core development is supported on macOS and Linux: ```bash -# macOS (Apple Silicon): CPU ROOT-GNN development and tests -uv sync --dev --extra root-gnn - -# Linux x86_64 with an NVIDIA GPU: validated ROOT-GNN development -uv sync --dev --extra root-gnn +uv sync --dev +git lfs pull # frozen parity references and pretrained checkpoints ``` -The core package can be installed without DGL when only shared data or task -code is needed. ROOT-GNN models, graph construction, and ROOT-GNN reference tests -require the `root-gnn` extra. On Linux x86_64, it uses the validated CUDA 12.1 -wheels configured in `pyproject.toml`; a compatible NVIDIA driver is still -required. On Apple Silicon macOS, it installs the CPU DGL wheel, supporting -local graph/cache development. The default ROOT-GNN backend performs training -with native PyTorch graph tensors, so it runs on Apple MPS, NVIDIA CUDA, and -CPU; DGL remains a cache and graph compatibility adapter. Do not add -site-specific CUDA, Slurm, or filesystem paths to model or task configuration. +Every model family runs on plain PyTorch, so the same environment supports +CPU, NVIDIA CUDA (Linux x86_64 uses the CUDA 12.1 PyTorch wheels configured in +`pyproject.toml`; a compatible driver is still required), and Apple MPS. There +is no graph-library dependency. Do not add site-specific CUDA, Slurm, or +filesystem paths to model or task configuration. Use the MPS profile on an Apple Silicon Mac: @@ -68,7 +61,7 @@ before writing its preparation configuration. ## Quick start -Prepare a graph cache from a ROOT tree. The feature specifications below are +Prepare an event cache from a ROOT tree. The feature specifications below are illustrative placeholders; replace them with the branches in the input tree. The full preparation interface is documented in [`docs/configuration.md`](docs/configuration.md). @@ -123,17 +116,20 @@ Metadata includes `fold`, `weight`, and stable `sample_id`; callers should not interpret public `tracking[:, N]` columns. Legacy tracking mappings exist only at compatibility boundaries. -The ROOT-GNN adapter converts shared features to a directed, fully connected -graph with no self-loops: an event with `N` nodes has `N * (N - 1)` edges. +Preparation stores each event's objects once, in a model-neutral packed +`EventCache`. The ROOT-GNN collate function turns a batch of events into a +directed, fully connected graph with no self-loops: an event with `N` nodes +has `N * (N - 1)` edges (a one-node event keeps one self-loop). Node columns are, in order, `pt`, `eta`, `phi`, `energy`, `btag`, `charge`, and `node_type`. Edge columns are `deta`, wrapped `dphi`, and `dR`. Object collections are concatenated in configured object-type order. The compatibility energy is `pt * cosh(eta)` before per-column scaling. -`GraphSampleCache` stores processed graph samples and schema metadata. It is a -Level-2 graph cache, not the universal event cache. Feature, graph, and cache -schema versions are checked when loading; incompatible versions fail before -training. +`EventCache` stores packed object features, labels, globals, named metadata, +and schema versions; graph topology and edge features are rebuilt per batch, +and the transformer pads the same objects into token sequences. Feature and +cache schema versions are checked when loading; incompatible versions, and +caches from before the packed format, fail before training. ## ROOT-GNN training and transfer @@ -217,15 +213,15 @@ compatibility adapter. ### ONNX export -Install the optional export dependencies and export a prepared graph-cache +Install the optional export dependencies and export a prepared event-cache checkpoint with numerical ONNX validation: ```bash -uv sync --extra root-gnn --extra onnx +uv sync --extra onnx uv run gnn4colliders export \ export.checkpoint=/path/to/checkpoint.pt \ export.output=model.onnx \ - data.cache.path=/path/to/graph-cache.pt + data.cache.path=/path/to/events.pt ``` The model accepts processed graph tensors and returns raw logits. See @@ -258,9 +254,10 @@ configs, and predictions, and metrics/results are gathered across ranks. The configured seed controls initialization and deterministic local loader ordering; distributed process seeds are rank-offset and samplers use -`set_epoch`. CPU runs are reproducible for fixed inputs and environment. GPU -kernels, DGL, and distributed scheduling can remain nondeterministic, so the -project does not promise bitwise GPU reproducibility. +`set_epoch`. Single-threaded CPU runs (`OMP_NUM_THREADS=1`) are bitwise +reproducible for fixed inputs and environment; multithreaded CPU reductions, +GPU kernels, and distributed scheduling can remain nondeterministic, so the +project does not promise bitwise reproducibility outside that setting. ## Development and validation @@ -293,9 +290,8 @@ ROOT-GNN v1 covers ROOT preparation, validated feature/graph/model/task behavior, training, fine-tuning, checkpoint resume, evaluation, prediction, single-process/DDP execution, and validated ONNX export. Streaming distributed output remains follow-up work. An initial ROOT-Transformer -(`model=root_transformer/transformer`) trains single-process from an existing -graph cache; a native sequence cache and DDP sequence loading are follow-up -work. +(`model=root_transformer/transformer`) trains single-process from the same +event cache; DDP sequence loading is follow-up work. ## Repository layout diff --git a/benchmarks/README.md b/benchmarks/README.md index 82ab74777dfa02d3c8ebe824f7b0829808f6d731..8a6c50c166c3aa9e021ab8d7f5ea27d40f123242 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -12,37 +12,32 @@ uv run python benchmarks/benchmark_inference.py --device cpu uv run python benchmarks/benchmark_training.py --device cuda --profile ``` -DGL-dependent scripts report a structured `skipped` result when the optional -`root-gnn` extra is absent. Profiler traces go under `profiles/` and are not -committed. +Loader, training, and inference benchmarks use synthetic packed events with +3-20 objects per event at batch size 1024. Profiler traces go under +`profiles/` and are not committed. Set `OMP_NUM_THREADS` to the CPU allocation; +the default of every visible core distorts CPU timings. ## Baseline measurements -The portable baseline in this checkout uses Python 3.12.13, PyTorch 2.2.2+cu121, -DGL 2.4.0+cu121, CPU, `nodes=32`, `iterations=10`, and `warmup=3`. Exact timings are machine -dependent; the JSON output from a local run is authoritative. - -| Measurement | Mean | Median | -| --- | ---: | ---: | -| feature construction | 0.47 ms/event | 0.46 ms/event | -| edge features | 0.11 ms/graph | 0.11 ms/graph | -| graph-sample loader | 1.65 ms/iteration | 1.65 ms/iteration | -| ROOT-GNN training step | 21.19 ms/step | 5.32 ms/step | -| ROOT-GNN inference | 1.48 ms/graph | 1.49 ms/graph | - -On the available NVIDIA A100-PCIE-40GB with CUDA 12.1 runtime, the same small -synthetic ROOT-GNN benchmark measured 6.41 ms/step (17.3 MiB peak allocated) -and 2.00 ms/graph. These are microbenchmarks, not production-workload claims. - -DGL is available in this environment. The training mean is skewed by one CPU -warmup-adjacent outlier; median is the more useful steady-state indicator. DDP -measurements require a multi-process run and are not inferred from CPU numbers. - -The topology cache is bounded to 32 node-count/device/policy entries and only -stores reusable index tensors, never event-specific edge features. - -On the same CPU, a direct topology microbenchmark for 64 nodes measured -201.6 microseconds per cold construction versus 10.5 microseconds for a warm -cache lookup (about 19x for this isolated operation). This is a targeted -index-construction result, not an end-to-end training speedup; graph feature -construction and DGL message passing remain separate costs. +Measured in this checkout with Python 3.12.13, PyTorch 2.2.2+cu121, +`OMP_NUM_THREADS=8`, `iterations=10`, and `warmup=3`, on synthetic batches of +1024 events (about 11.5 objects and 153,000 edges per batch). Exact timings are +machine dependent; the JSON output from a local run is authoritative. + +| Measurement | Mean | +| --- | ---: | +| graph batch construction (CPU) | 6.0 ms/batch | +| sequence batch construction (CPU) | 0.8 ms/batch | +| per-event feature construction (32 objects) | 0.42 ms/event | +| ROOT-GNN training step, A100 (hid 128, 4 steps) | 55.3 ms/step, 2.6 GiB peak | +| ROOT-GNN inference, A100 | 23.0 ms/batch | +| ROOT-GNN training step, CPU | 2.86 s/step | + +Real-data measurements of preparation, cache size, and epoch throughput are in +[`../docs/performance.md`](../docs/performance.md). Preparation is measured +end to end with `benchmark_prepare.py`; the vectorized preparation path does +not use the per-event feature builder timed above. + +The topology cache of `fully_connected_edges` is bounded to 32 +node-count/device/policy entries and only stores reusable index tensors; +batched graphs use the vectorized `fully_connected_batch_edges` instead. diff --git a/benchmarks/_common.py b/benchmarks/_common.py index 842b9868f12deaa72d568c4504658cb26260f572..40d51127ba1f7949fbd7dccaee79456648e55cd2 100644 --- a/benchmarks/_common.py +++ b/benchmarks/_common.py @@ -57,14 +57,23 @@ def metadata(device: torch.device) -> dict[str, Any]: } if device.type == "cuda" and torch.cuda.is_available(): result["gpu"] = torch.cuda.get_device_name(device) - try: - import dgl - - result["dgl"] = dgl.__version__ - except ImportError: - result["dgl"] = None return result +def synthetic_events(count: int, *, seed: int, max_objects: int = 20): + """Collider-like packed events with 3 to ``max_objects`` objects each.""" + from gnn4colliders.data import pack_events + + generator = torch.Generator().manual_seed(seed) + counts = torch.randint(3, max_objects + 1, (count,), generator=generator) + objects = [] + for size in counts.tolist(): + features = torch.randn((size, 7), generator=generator) + features[:, 2] = torch.rand(size, generator=generator) * 6.28 - 3.14 + objects.append(features) + labels = torch.randint(0, 2, (count,), generator=generator) + return pack_events(objects, labels) + + def report(name: str, values: dict[str, Any]) -> None: print(json.dumps({"benchmark": name, **values}, sort_keys=True)) diff --git a/benchmarks/benchmark_dataloader.py b/benchmarks/benchmark_dataloader.py index c57eba9128660b18cd21aaa0a6be5da7172c1fd8..aa02ac0a7089e4fa1b9c58db3811a6bdc9b4b47d 100644 --- a/benchmarks/benchmark_dataloader.py +++ b/benchmarks/benchmark_dataloader.py @@ -1,62 +1,48 @@ -"""Measure deterministic loader/batch construction when ROOT-GNN is installed.""" +"""Measure batch construction from packed events at a realistic batch size.""" from __future__ import annotations import torch try: - from ._common import common_parser, measure, metadata, report + from ._common import common_parser, measure, metadata, report, synthetic_events except ImportError: - from _common import common_parser, measure, metadata, report + from _common import common_parser, measure, metadata, report, synthetic_events + +from gnn4colliders.data import EventLoader +from gnn4colliders.graphs import collate_graph_batch +from gnn4colliders.sequences import collate_sequence_batch def main() -> None: parser = common_parser(__doc__) - parser.add_argument("--batch-size", type=int, default=8) - parser.add_argument("--samples", type=int, default=64) + parser.add_argument("--batch-size", type=int, default=1024) + parser.add_argument("--batches", type=int, default=8) args = parser.parse_args() device = torch.device(args.device) - try: - import dgl - - from gnn4colliders.data import ( - EventMetadata, - GraphDataLoader, - GraphDataset, - GraphSample, + events = synthetic_events(args.batch_size * args.batches, seed=args.seed) + for name, collate in ( + ("graph_batches", collate_graph_batch), + ("sequence_batches", collate_sequence_batch), + ): + loader = EventLoader(events, collate, args.batch_size, shuffle=True) + result = measure( + lambda: [batch.to(device) for batch in loader], + iterations=args.iterations, + warmup=args.warmup, + device=device, ) - except ImportError: + per_batch = result["mean_ms"] / len(loader) report( - "dataloader", - {**metadata(device), "status": "skipped: install root-gnn extra"}, - ) - return - samples = [] - for index in range(args.samples): - graph = dgl.graph((torch.tensor([0, 1]), torch.tensor([1, 0])), num_nodes=2) - graph.ndata["features"] = torch.ones(2, 7) - graph.edata["features"] = torch.ones(2, 3) - samples.append( - GraphSample( - graph, torch.tensor(index % 2), None, EventMetadata(0, 1.0, str(index)) - ) + name, + { + **metadata(device), + **result, + "batch_size": args.batch_size, + "ms_per_batch": per_batch, + "events_per_second": args.batch_size * 1000 / per_batch, + }, ) - loader = GraphDataLoader(GraphDataset(samples), args.batch_size) - result = measure( - lambda: list(loader), - iterations=args.iterations, - warmup=args.warmup, - device=device, - ) - report( - "dataloader", - { - **metadata(device), - **result, - "batch_size": args.batch_size, - "batches_per_second": 1000 / result["mean_ms"], - }, - ) if __name__ == "__main__": diff --git a/benchmarks/benchmark_inference.py b/benchmarks/benchmark_inference.py index 7db8fdaf569c035219bf9389ed5e6e6c5a82cdaf..65796e782cdb89065058dcb1af4a85fc15026de9 100644 --- a/benchmarks/benchmark_inference.py +++ b/benchmarks/benchmark_inference.py @@ -1,36 +1,28 @@ -"""Measure ROOT-GNN inference with fixed synthetic graph input.""" +"""Measure ROOT-GNN inference on a realistic synthetic batch.""" from __future__ import annotations import torch try: - from ._common import common_parser, measure, metadata, report + from ._common import common_parser, measure, metadata, report, synthetic_events except ImportError: - from _common import common_parser, measure, metadata, report + from _common import common_parser, measure, metadata, report, synthetic_events + +from gnn4colliders.graphs import collate_graph_batch +from gnn4colliders.models.root_gnn import EdgeNetwork def main() -> None: parser = common_parser(__doc__) + parser.add_argument("--batch-size", type=int, default=1024) args = parser.parse_args() device = torch.device(args.device) - try: - import dgl - - from gnn4colliders.models.root_gnn import EdgeNetwork - except ImportError: - report( - "inference", - {**metadata(device), "status": "skipped: install root-gnn extra"}, - ) - return - graph = dgl.graph((torch.tensor([0, 1]), torch.tensor([1, 0])), num_nodes=2).to( - device - ) - graph.ndata["features"] = torch.ones(2, 7, device=device) - graph.edata["features"] = torch.ones(2, 3, device=device) + events = synthetic_events(args.batch_size, seed=args.seed) + batch = collate_graph_batch(events, torch.arange(len(events))).to(device) + graph = batch.graph model = ( - EdgeNetwork(graph, None, hid_size=16, out_size=2, n_layers=1, n_proc_steps=1) + EdgeNetwork(graph, None, hid_size=128, out_size=1, n_layers=2, n_proc_steps=4) .to(device) .eval() ) diff --git a/benchmarks/benchmark_prepare.py b/benchmarks/benchmark_prepare.py index 395d17371f07b70a2e9f33c8ba9422254642f4b3..86fe215673862bb7a6a19465d3c15a3abc335e82 100644 --- a/benchmarks/benchmark_prepare.py +++ b/benchmarks/benchmark_prepare.py @@ -1,4 +1,4 @@ -"""Benchmark ROOT reading, feature construction, and graph preparation.""" +"""Benchmark ROOT reading, feature construction, and event-cache preparation.""" from __future__ import annotations @@ -56,7 +56,7 @@ def main() -> None: root_file = Path(directory) / "events.root" _write_fixture(root_file, args.events, args.nodes) data["files"] = [str(root_file)] - data["cache"] = {"path": str(Path(directory) / "graphs.pt")} + data["cache"] = {"path": str(Path(directory) / "events.pt")} data["num_workers"] = args.workers start = time.perf_counter() prepare(OmegaConf.create({"data": data, "distributed": {"enabled": False}})) diff --git a/benchmarks/benchmark_training.py b/benchmarks/benchmark_training.py index 51743dd3a4fdf52aa60541b2eebf076e609c3728..2acfbfdcf8d2d8ed42626fde66faffe7c3c88ae8 100644 --- a/benchmarks/benchmark_training.py +++ b/benchmarks/benchmark_training.py @@ -1,4 +1,4 @@ -"""Measure a short ROOT-GNN training section and optionally emit a profiler trace.""" +"""Measure ROOT-GNN training steps and optionally emit a profiler trace.""" from __future__ import annotations @@ -7,42 +7,38 @@ from pathlib import Path import torch try: - from ._common import common_parser, measure, metadata, report + from ._common import common_parser, measure, metadata, report, synthetic_events except ImportError: - from _common import common_parser, measure, metadata, report + from _common import common_parser, measure, metadata, report, synthetic_events + +from gnn4colliders.graphs import collate_graph_batch +from gnn4colliders.models.root_gnn import EdgeNetwork def main() -> None: parser = common_parser(__doc__) - parser.add_argument("--batch-size", type=int, default=4) + parser.add_argument("--batch-size", type=int, default=1024) + parser.add_argument("--hid-size", type=int, default=128) parser.add_argument("--profile", action="store_true") parser.add_argument("--profile-dir", default="profiles") args = parser.parse_args() device = torch.device(args.device) - try: - import dgl - - from gnn4colliders.models.root_gnn import EdgeNetwork - except ImportError: - report( - "training", - {**metadata(device), "status": "skipped: install root-gnn extra"}, - ) - return torch.manual_seed(args.seed) - graph = dgl.graph((torch.tensor([0, 1]), torch.tensor([1, 0])), num_nodes=2).to( - device - ) - graph.ndata["features"] = torch.randn(2, 7, device=device) - graph.edata["features"] = torch.randn(2, 3, device=device) + events = synthetic_events(args.batch_size, seed=args.seed) + batch = collate_graph_batch(events, torch.arange(len(events))).to(device) model = EdgeNetwork( - graph, None, hid_size=16, out_size=2, n_layers=1, n_proc_steps=1 + batch.graph, + None, + hid_size=args.hid_size, + out_size=1, + n_layers=2, + n_proc_steps=4, ).to(device) optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) def step() -> None: optimizer.zero_grad(set_to_none=True) - loss = model(graph).square().mean() + loss = model(batch.graph).square().mean() loss.backward() optimizer.step() @@ -61,6 +57,8 @@ def main() -> None: { **metadata(device), **result, + "batch_size": args.batch_size, + "edges": int(batch.graph.edge_features.shape[0]), "steps_per_second": 1000 / result["mean_ms"], "peak_memory_mb": torch.cuda.max_memory_allocated(device) / 2**20 if device.type == "cuda" diff --git a/docs/agent-workflows/gnn4colliders-workflow.md b/docs/agent-workflows/gnn4colliders-workflow.md index 80469a72d9fd2cec64dd0810feea0275e1986d9c..f4de549559ea44c543792a4ed0cb51bbb6b0c5ae 100644 --- a/docs/agent-workflows/gnn4colliders-workflow.md +++ b/docs/agent-workflows/gnn4colliders-workflow.md @@ -24,11 +24,12 @@ implementation imports. The normal development environment is: ```bash -uv sync --dev --extra root-gnn +uv sync --dev ``` -Use the `root-gnn` extra for DGL-backed tests and ROOT-GNN workflows. ONNX -checks additionally need the `onnx` extra. +All model families run on plain PyTorch; there is no model-framework extra. +ONNX checks additionally need the `onnx` extra. Run `git lfs pull` before the +parity gate. For the shortest end-to-end check, use the repository's temporary ROOT fixture: @@ -37,7 +38,7 @@ fixture: uv run python scripts/dev/smoke_end_to_end.py ``` -This creates a temporary ROOT file, prepares a graph cache, trains one CPU +This creates a temporary ROOT file, prepares an event cache, trains one CPU epoch, evaluates, predicts, and removes its temporary files. ## Public data and configurations @@ -97,8 +98,9 @@ uv run ruff check . uv run ruff format --check . ``` -The strict parity command must fail when DGL is unavailable; do not replace it -with a command that permits parity tests to skip. A CUDA-only skip is expected +The strict parity command must fail when frozen parity artifacts are missing +or are unfetched Git LFS pointers; do not replace it with a command that +permits parity tests to skip. A CUDA-only skip is expected on CPU hosts and must be reported. ## Change discipline diff --git a/docs/architecture.md b/docs/architecture.md index 549e0883de82317ed2d5c353b0117fefde309238..6b43668af4e485c694b321b5514abbe7d354d7b8 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -6,24 +6,22 @@ GNN4Colliders is organized around an architecture-neutral event boundary: ```text ROOT/Awkward - ↓ -EventSample + EventMetadata - ↓ -shared features and representation adapters - ├── GraphSample -> GraphSampleCache -> GraphBatch - └── SequenceSample -> transformer/token models - ↓ -model family + ↓ vectorized over event chunks (data.preparation, features) +EventCache / PackedEvents: per-object features + named per-event metadata + ↓ EventLoader(collate=...) per batch + ├── collate_graph_batch -> GraphBatch(TensorGraph) -> models.root_gnn + └── collate_sequence_batch -> SequenceBatch (padded) -> models.root_transformer ↓ Task -> Trainer/Predictor -> named outputs ``` | Layer | Responsibility | |---|---| -| `data` | ROOT/Awkward ingestion, metadata, datasets, folds, batching, and caches | +| `data` | ROOT/Awkward ingestion, vectorized preparation, packed event cache, metadata, folds, and loaders | | `features` | Collider-object features and derived physics quantities | -| `graphs` | Topology, edge construction, graph-specific adapters, and graph-cache preparation | -| `models` | Architecture-specific neural networks | +| `graphs` | Topology, edge features, `TensorGraph`, and graph batch collation | +| `sequences` | Token sequences and padded sequence batch collation | +| `models` | Architecture-specific neural networks in plain PyTorch | | `tasks` | Labels, weights, losses, scores, predictions, and metrics | | `training` | Optimizers, lifecycle, reproducibility, checkpointing, and distributed utilities | | `inference` | Ordered prediction, evaluation, and named output writing | @@ -39,22 +37,27 @@ their representation permits it. ## Data and representation boundaries `EventSample` and named `EventMetadata(fold, weight, sample_id, extra)` are -representation-independent. `GraphSample` and `GraphBatch` are the current -graph representation boundary. `TensorGraph` provides a native tensor path -for ROOT-GNN execution on CPU, CUDA, and MPS; DGL remains an optional graph -adapter and cache dependency. - -`SequenceSample` and `SequenceBatch` are the topology-free representation -boundary for transformer experiments. `TransformerClassifier` consumes padded -object-token sequences and returns raw logits while reusing shared task, -training, checkpoint, and inference interfaces. +representation-independent. Prepared data is stored once as `PackedEvents` +(`EventCache` on disk): object features in one flat tensor, event boundaries +as offsets, and labels, folds, weights, and sample-identity columns. Nothing +in the cache is graph- or model-specific, and it loads with +`weights_only=True` and optional memory mapping. + +A model family supplies only a collate function from `(PackedEvents, +indices)` to its batch type. `collate_graph_batch` builds `TensorGraph` +batches in the edge-index layout common to PyTorch GNN libraries (flat node +and edge tensors, `edge_src`/`edge_dst`, per-element graph membership), which +runs on CPU, CUDA, and MPS. `collate_sequence_batch` builds padded +`SequenceBatch` token batches with a mask for `TransformerClassifier`. No +graph library is a dependency. The active collider node schema has seven columns: `[pt, eta, phi, energy, btag, charge, node_type]`. Graph edges are directed, source-major, fully connected without self-loops except for the one-node case, and carry `[deta, dphi, dR]` features. These are compatibility contracts -captured by deterministic tests and the frozen `root-gnn-parity-baseline` -reference fixture. +captured by deterministic tests, the frozen `root-gnn-parity-baseline` +reference fixture, and the frozen DGL outputs in +`tests/fixtures/root_gnn_dgl_reference/`. ## Configuration and lifecycle @@ -74,7 +77,7 @@ Additional model families should introduce only their representation-specific boundary and model implementation, for example: ```text -data.EventSample -> features -> SequenceSample -> models.root_transformer +PackedEvents -> collate function (representation) -> models. ``` It should include a deterministic fixture, unit tests for the representation, diff --git a/docs/configuration.md b/docs/configuration.md index 0e857508ec4d0644af3ca7de3e32ffd58b4d72a6..4b355b4c62136317c769ef1b68d84f4512fc1320 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -9,7 +9,7 @@ class import paths. | Group | Purpose | | --- | --- | -| `data` | ROOT source or graph-cache path, batch settings, and fold splits | +| `data` | ROOT source or event-cache path, batch settings, and fold splits | | `model` | Model family and supported ROOT-GNN constructor settings | | `task` | Binary or multiclass loss, score, and metric semantics | | `trainer` | Device, seed, epochs, optimizer, scheduler, and early stopping | @@ -29,8 +29,14 @@ The active model groups are `root_gnn/edge_network` and seven-column feature contract: one branch/constant specification per output column and one entry per configured object type. `CALC_E` and `NODE_TYPE` are reserved derived specifications. `object_types` entries are `vector` or -`single`. Preparation reads the configured tree in file order and writes a -versioned `GraphSampleCache`. +`single`. Preparation reads the configured tree in file order, builds features +vectorized over chunks of events, and writes a versioned `EventCache`: packed +per-object features plus named per-event metadata. The cache is +representation-neutral; graph topology and edge features (or padded token +sequences) are built at batch time by the selected model family, so one cache +serves every model. `data.cache.path` may also point at a shard directory with +a `manifest.json` (see [perlmutter.md](perlmutter.md)); its shards are loaded +in order. Example overrides are easiest to maintain in a YAML file for real datasets: @@ -54,10 +60,12 @@ fold_var: eventNumber weight_var: weight ``` -Then compose it with `data=my_events`. The cache stores processed graph -samples, labels, globals, named metadata, and feature/graph/cache schema -versions. Changing the feature or graph schema requires a new compatible cache; -loading a mismatched schema raises an error. +Then compose it with `data=my_events`. The cache stores packed object +features, labels, globals, named metadata, and feature/cache schema versions. +It contains only tensors and plain values (loaded with `weights_only=True`). +Changing the feature schema requires a new compatible cache; loading a +mismatched schema, or a cache written before the packed format, raises an +error asking for the cache to be prepared again. ## Common overrides @@ -109,7 +117,7 @@ by the default configuration and is cached by the Hub client for later runs. `data.num_workers` controls local process parallelism during `prepare`. The default is `0` (single-process). Positive values split the ordered event range -into independent temporary graph-cache shards and merge them deterministically; +into independent temporary event-cache parts and merge them deterministically; workers do not write the final cache concurrently. This setting does not launch distributed preparation and should be benchmarked on the target machine. diff --git a/docs/end_to_end_validation.md b/docs/end_to_end_validation.md index ef6ad17064569ae00d438d1868e059622b188e70..8f243be2ad5167535e55532c35ded2c361d19f55 100644 --- a/docs/end_to_end_validation.md +++ b/docs/end_to_end_validation.md @@ -7,7 +7,7 @@ The first failing stage is retained in JSON and Markdown reports. Legacy and rewrite extraction may use separate environments. Each writes the version-1 artifact described in `validation/README.md`; the comparator never -imports legacy modules or DGL graph objects. Record ROOT file/tree, selection, +imports legacy modules or graph-library objects. Record ROOT file/tree, selection, event count, file size, SHA-256, branches, seeds, versions, device and source identities in the artifact manifest. Do not use an absolute personal path as a scientific event identity. diff --git a/docs/export.md b/docs/export.md index 37d9280953376494ba94ab0c7c9cdc1eec81a1b6..0a1005f7a70bf83a1b32b7ce225603b3a95720d5 100644 --- a/docs/export.md +++ b/docs/export.md @@ -5,7 +5,7 @@ It does not read ROOT files or move feature construction into the deployment model. Install the optional dependencies with: ```bash -uv sync --extra root-gnn --extra onnx +uv sync --extra onnx ``` Export a checkpoint with the project CLI: @@ -14,7 +14,7 @@ Export a checkpoint with the project CLI: uv run gnn4colliders export \ export.checkpoint=/path/to/checkpoint.pt \ export.output=model.onnx \ - data.cache.path=/path/to/graph-cache.pt + data.cache.path=/path/to/events.pt ``` The exported model accepts six tensor inputs: `node_features`, @@ -30,7 +30,6 @@ supports `EdgeNetwork` multiclass models and `FineTunedEdgeNetwork` binary models. Empty graphs are invalid; single-node graphs (zero edges) are represented and pooled with a zero edge contribution. -Direct DGL export was not retained: the active model uses DGL graph mutation -and reductions (`apply_edges`, `update_all`, and graph pooling) that are not a -portable ONNX contract. The adapter expresses those operations with standard -tensor indexing, `index_add`, and per-graph means. +The export adapter mirrors `EdgeNetwork` but replaces its `index_add` +reductions with dense membership-matrix products, because ONNX scatter +operations do not reliably reduce duplicate indices. diff --git a/docs/migration.md b/docs/migration.md index 772128960360f5d550cb9e91606a3e2e004779d7..9fe6868e639a5678b02f08f49ea68f769d8fe8c9 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -6,7 +6,7 @@ The `root-gnn-parity-baseline` tag records the completed migration of the active ROOT-GNN behavior into `src/gnn4colliders.models.root_gnn`. The campaign covered full event preprocessing and graph parity, binary objectives and metrics, deterministic fine-tuning, full-split training, checkpoint reload -and resume, reproducibility, and serialized graph-cache checks. +and resume, reproducibility, and serialized cache checks. The historical implementation is no longer in the active source tree. Its observable behavior is represented by committed fixtures, tests, and the @@ -38,12 +38,52 @@ The first `root_transformer` vertical slice is implemented with: 5. Add checkpoint, prediction, and reproducibility tests. The first implementation is available as -`model=root_transformer/transformer`. It can train on an existing graph cache -by adapting node features into ordered sequence tokens; this is a migration -bridge while a native sequence cache and DDP sequence loader are evaluated. +`model=root_transformer/transformer`. It trains from the shared packed event +cache, which `collate_sequence_batch` pads into token batches. Distributed +sequence loading remains follow-up work. -Native sequence-cache storage and distributed sequence loading remain follow-up -work; do not generalize shared interfaces until those use cases require it. +## DGL removal + +DGL was removed as a dependency. The packed `EventCache` replaced the pickled +DGL `GraphSampleCache`, graph batches are built per batch as `TensorGraph` +(edge-index layout), and the PyTorch implementation is the canonical +`EdgeNetwork`. Before removal, the DGL graph builder and model outputs were +frozen on the 64-event fixture (`tests/fixtures/root_gnn_dgl_reference/`): +prepared graphs, edge features, metadata, and all forward outputs (including +the 12-class pretrained checkpoint) are reproduced bit-for-bit; gradients +agree to float32 summation-order tolerance. Single-threaded CPU training was +also verified bit-identical to the previous main for two epochs, and forward +logits on 2,048 real ttH events match the DGL-era rewrite exactly. + +Intentional differences: + +- caches written before the packed format must be prepared again + (`CACHE_SCHEMA_VERSION` 2); old shard directories are not reused; +- `model.backend` is no longer a choice; `dgl` is rejected with an error; +- the DGL model's optional per-node pooling weights (`ndata["w"]`) were not + carried over; no pipeline in the package ever produced them; +- the unused `CacheMetadata.preprocessing` fingerprint was dropped with the + graph cache; +- the `root-gnn` install extra no longer exists. + +Validation completed on 2026-10-19: + +- `GNN4COLLIDERS_REQUIRE_ROOT_GNN=1 uv run --offline pytest -q`: 155 passed, + 2 skipped (MPS unavailable), including frozen DGL forward/gradient and + prepared-feature references, ONNX, CUDA, and two-rank CPU CLI training. +- `uv run --offline python -m validation.run_public_validation --no-download`: + PASS against the public fixture's golden scientific outputs. +- `uv run --offline python scripts/dev/smoke_end_to_end.py`: passed preparation, + pretraining, fine-tuning, evaluation, and prediction. AUC is undefined for + this tiny smoke fixture's single-class evaluation split. +- Ruff lint and formatting checks, source/wheel builds, and Twine metadata + checks passed. + +Signed NLO weights can cancel in small batches under the preserved legacy +weighted-loss normalization. The DDP CLI regression uses +`task.absolute_weights=true`, as does the ttH CP task; loss semantics have +not been changed. Transformer DDP remains unsupported, and MPS requires +validation on Apple hardware. ## Validation requirements diff --git a/docs/performance.md b/docs/performance.md index 59777b3114a269c6914993bbbfb0b1a325a85ae1..d0bc1586e51d7bd0efc6c7be2a60851c266aead9 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -12,14 +12,45 @@ The cache is graph-specific and does not alter scientific behavior. Training already uses `zero_grad(set_to_none=True)` and inference already uses `torch.inference_mode()` with detached CPU accumulation. -Mixed precision, `torch.compile`, custom kernels, aggressive worker defaults, -and cache-format replacement were not retained without target-machine -measurements. The main known bottleneck is the quadratic graph workload -`N * (N - 1)` and associated DGL message passing; size-aware batching and -streaming prediction remain follow-up work because they affect ordering or -output semantics. - -## Graph preparation benchmark and parallelism +## Packed events and batching + +Preparation writes packed per-object features (`EventCache`) instead of one +pickled graph per event; graph topology and edge features are built per batch +with vectorized tensor operations, and transformer batches pad the same rows. +Measured on 200,000 real ttH events (7.4 objects/event, A100 node, 8 CPU +threads) against the previous DGL graph cache: + +| Stage | Before (DGL graph cache) | Packed events | +| --- | ---: | ---: | +| Preparation, single core | 3,763 us/event | 19.8 us/event | +| Cache size | 3,658 bytes/event | 252 bytes/event | +| Cache load | 312 us/event | 0.16 us/event | +| Batch construction (1024 events) | 83 ms | 3.3 ms | +| GPU training epoch | 166.5 ms/batch | 25.8 ms/batch | + +Training is now bound by the GPU step itself. Mixed precision, +`torch.compile`, and size-aware batching are the next levers and have not been +adopted without measurements; size-aware batching and streaming prediction +affect ordering or output semantics. + +## CPU threads + +PyTorch sizes its CPU thread pool to every core it can see. On a 128-core node +that made batch construction about 5x slower than with 8 threads, and it makes +multithreaded CPU reductions non-reproducible between runs. Set +`OMP_NUM_THREADS` (the Slurm wrappers use `SLURM_CPUS_PER_TASK`) to match the +allocation. Single-threaded CPU training is bitwise reproducible. + +## Known float32 artifacts + +Two historical feature values depend on PyTorch CPU kernels rather than on the +physics: `CALC_E` energies use `torch.cosh`, whose SIMD and scalar paths can +differ by 1-2 ULP, so energies are evaluated per event exactly as before; and +the CPU `torch.sqrt` used for `dR` is not correctly rounded (CUDA's is). Both +are preserved for bit-exact parity and are candidates for a deliberate, +versioned feature change (for example float64 evaluation). + +## Preparation benchmark and parallelism Benchmark the complete ROOT-to-cache path on a deterministic temporary sample: diff --git a/docs/perlmutter.md b/docs/perlmutter.md index 64c8e926a46670071139ca0fd79f2697f7f51783..4cfc52bf61dd232d4240a436bc0574c6d0a4d81c 100644 --- a/docs/perlmutter.md +++ b/docs/perlmutter.md @@ -9,7 +9,7 @@ Hydra configuration as on a workstation. ```bash uv run gnn4colliders train \ - data.cache.path=/path/to/graphs.pt \ + data.cache.path=/path/to/events.pt \ environment=perlmutter \ trainer.device=cuda \ trainer.max_epochs=10 @@ -19,14 +19,14 @@ The equivalent Slurm wrapper is: ```bash sbatch scripts/slurm/train_single_gpu.sh \ - data.cache.path=/path/to/graphs.pt trainer.max_epochs=10 + data.cache.path=/path/to/events.pt trainer.max_epochs=10 ``` ## Single-node DDP ```bash GPUS_PER_NODE=4 sbatch scripts/slurm/train_multi_gpu.sh \ - data.cache.path=/path/to/graphs.pt trainer.max_epochs=10 + data.cache.path=/path/to/events.pt trainer.max_epochs=10 ``` The wrapper uses `torchrun`; `batch_size` and `num_workers` are per GPU. @@ -37,7 +37,7 @@ Effective batch size is `data.batch_size * number_of_processes`, and only rank ```bash GPUS_PER_NODE=4 sbatch scripts/slurm/train_multi_node.sh \ - data.cache.path=/path/to/graphs.pt trainer.max_epochs=10 + data.cache.path=/path/to/events.pt trainer.max_epochs=10 ``` Use the provided script as a template and adapt only allocation/account @@ -48,16 +48,17 @@ results in memory. ## Checks and common failures ```bash -uv run python -c "import torch, dgl; print(torch.__version__, dgl.__version__, torch.cuda.is_available())" +uv run python -c "import torch; print(torch.__version__, torch.cuda.is_available(), torch.get_num_threads())" uv run gnn4colliders --help ``` -An unavailable DGL wheel, incompatible driver, missing cache, or mismatched -cache schema should be fixed in the environment/input rather than hidden with -package-level path changes. GPU kernels and distributed execution are not +An incompatible driver, missing cache, or mismatched cache schema should be +fixed in the environment/input rather than hidden with package-level path +changes. The Slurm wrappers set `OMP_NUM_THREADS` from the allocation; set it +yourself in interactive sessions (see [performance.md](performance.md)). GPU kernels and distributed execution are not promised bitwise deterministic. -## Large ROOT graph preparation +## Large ROOT preparation Large samples should be prepared as persistent shards. Each Slurm array task reads one contiguous global event range and writes one `shard-NNNNN.pt` file; diff --git a/docs/quickstart.md b/docs/quickstart.md index 0192305893e2eec09e540526a810cd4188a9d3f3..bd3783c9651163a92afa0d6f76db5b066a2e062f 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -7,7 +7,7 @@ family is `root_gnn`; the shared data and task layers are intended to support future representations as well. ```text -ROOT -> EventSample -> features -> GraphSampleCache -> ROOT-GNN -> logits +ROOT -> features -> EventCache (packed objects) -> graph or sequence batch -> model -> logits ``` ## Install @@ -15,11 +15,11 @@ ROOT -> EventSample -> features -> GraphSampleCache -> ROOT-GNN -> logits The supported environment is Python 3.12. From the repository root: ```bash -uv sync --dev --extra root-gnn +uv sync --dev ``` -The `root-gnn` extra is required for DGL-backed graph workflows and ROOT-GNN -parity tests. Add `--extra onnx` when using export validation. +Everything, including ROOT-GNN, runs on plain PyTorch (CPU, CUDA, or Apple +MPS). Add `--extra onnx` when using export validation. ## Run a local end-to-end smoke test @@ -133,8 +133,8 @@ uv run gnn4colliders train \ `checkpoint.pretrained` starts a new task from model weights and creates a new head and optimizer. Evaluation uses the held-out test split by default. -The first transformer model reuses node features as ordered tokens and the -same task/trainer lifecycle. It can be trained from an existing prepared cache: +The first transformer model uses the same prepared objects as ordered tokens +and the same task/trainer lifecycle. It trains from the same prepared cache: ```bash uv run gnn4colliders train \ @@ -144,8 +144,8 @@ uv run gnn4colliders train \ model.hid_size=64 model.n_heads=4 ``` -This bridge intentionally ignores graph edges. Native sequence-cache storage -and distributed sequence loading are follow-up work. +Sequence batches are padded with a token mask; graph topology is never +built for this model. Distributed sequence loading is follow-up work. ## Validate changes @@ -165,8 +165,9 @@ For the portable public-data regression: uv run python -m validation.run_public_validation --no-download ``` -The parity gate requires DGL and compares the new implementation against -committed frozen reference fixtures. Historical runtime code is not imported +The parity gate compares the implementation against committed frozen +reference fixtures (including outputs recorded from the historical DGL model) +and fails if those Git LFS artifacts are not present. Historical runtime code is not imported from main; compatibility adapters are reserved for old checkpoint, metadata, and output boundaries. diff --git a/docs/releasing.md b/docs/releasing.md index 8e3863dc352e9f71586e08030bae24b756b09e3d..ce759bed0211ba6069ec7a74d7251b33b48feadd 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -7,8 +7,8 @@ metadata. The current package is not published to PyPI. Before a release: 1. Update `__version__`, `CHANGELOG.md`, and this release checklist. -2. Run `uv sync --dev` (and `--extra root-gnn` when ROOT-GNN validation is - available), then run lint and tests. +2. Run `uv sync --dev` and `git lfs pull`, then run lint and + `GNN4COLLIDERS_REQUIRE_ROOT_GNN=1 uv run pytest`. 3. Run `bash scripts/dev/check_release.sh` to build and inspect the sdist and wheel and smoke-test a wheel installation outside the checkout. 4. Review the generated artifacts and `git diff`, then create a version tag @@ -17,7 +17,5 @@ Before a release: The release-validation script never publishes artifacts. Publishing, if adopted later, must use repository-managed credentials or trusted publishing. -The direct DGL wheel source is retained in `pyproject.toml` because the -validated ROOT-GNN environment requires the CUDA 12.1 DGL wheel. Core imports -do not import DGL or ONNX; install the corresponding extras for those -workflows. +The CUDA 12.1 PyTorch wheel index is configured in `pyproject.toml` for Linux +x86_64. Core imports do not import ONNX; install the `onnx` extra for export. diff --git a/docs/testing.md b/docs/testing.md index 55a52cec990a46a39f3a626d53f637b2134055c6..1f9808d1512150450670eedc0854b576dc11cc4a 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -9,7 +9,7 @@ uv run pytest tests/unit # Full CPU suite, including integration and parity tests uv run pytest -# Required ROOT-GNN parity gate (must fail if DGL is unavailable) +# Required ROOT-GNN parity gate (fails if frozen LFS artifacts are absent) GNN4COLLIDERS_REQUIRE_ROOT_GNN=1 uv run pytest # Optional layers @@ -19,12 +19,12 @@ uv run pytest -m gpu -v GNN4COLLIDERS_ROOT_FIXTURE=/path/to/reduced.root uv run pytest -m real_data -v ``` -On Apple Silicon macOS, `uv sync --dev --extra root-gnn` supports CPU -ROOT-GNN unit and integration testing. CUDA and the required ROOT-GNN parity -gate are validated on Linux x86_64 with the `root-gnn` extra installed. +`uv sync --dev` supports the complete suite on Linux and macOS; there is no +separate model-framework extra. Fetch Git LFS files (`git lfs pull`) before +running the parity gate. -Unit tests use deterministic, small tensors and generated ROOT files. DGL, -ONNX, CUDA, distributed execution, and reduced real-data fixtures remain +Unit tests use deterministic, small tensors and generated ROOT files. ONNX, +CUDA, MPS, distributed execution, and reduced real-data fixtures remain optional layers. Tests should assert public contracts and scientific invariants rather than private call sequences. New regression tests should use `tmp_path`, explicit seeds, and justified numerical tolerances. diff --git a/pyproject.toml b/pyproject.toml index c3971bad6e4a157881a16e685041bee2c8943ca1..09f0efabde4103b60634c22ac5e87581f5987f3f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta" [project] name = "gnn4colliders" dynamic = ["version"] -description = "Graph neural network tools for collider event analysis." +description = "Machine-learning tools for collider event analysis." readme = "README.md" requires-python = ">=3.12,<3.13" dependencies = [ @@ -19,12 +19,6 @@ dependencies = [ ] [project.optional-dependencies] -root-gnn = [ - "dgl==2.4.0+cu121; sys_platform == 'linux' and platform_machine == 'x86_64'", - "dgl==2.2.0; sys_platform == 'darwin' and platform_machine == 'arm64'", - "pydantic>=2,<3; sys_platform == 'darwin' and platform_machine == 'arm64'", - "torchdata>=0.7,<0.8; sys_platform == 'darwin' and platform_machine == 'arm64'", -] onnx = [ "onnx>=1.16,<2", "onnxruntime>=1.18,<2", @@ -57,22 +51,12 @@ version = { attr = "gnn4colliders.__version__" } torch = [ { index = "pytorch-cu121", marker = "sys_platform == 'linux' and platform_machine == 'x86_64'" }, ] -dgl = [ - { index = "dgl", marker = "sys_platform == 'linux' and platform_machine == 'x86_64'" }, -] [[tool.uv.index]] name = "pytorch-cu121" url = "https://download.pytorch.org/whl/cu121" explicit = true -[[tool.uv.index]] -name = "dgl" -url = "https://data.dgl.ai/wheels/torch-2.2/cu121/repo.html" -format = "flat" -explicit = true - - [tool.pytest.ini_options] testpaths = ["tests"] addopts = "-ra" diff --git a/scripts/dev/smoke_end_to_end.py b/scripts/dev/smoke_end_to_end.py index a97654cb82823103ae3b677a0eae8b723241594b..c0a3ceb40278cbb23da70e82a037495038d6803f 100644 --- a/scripts/dev/smoke_end_to_end.py +++ b/scripts/dev/smoke_end_to_end.py @@ -67,17 +67,10 @@ def _train(root: Path, cache: Path, output: Path, *extra: str) -> Path: def main() -> None: - try: - import dgl # noqa: F401 - except ImportError as error: # pragma: no cover - environment-dependent - raise SystemExit( - "install the root-gnn extra before running this smoke test" - ) from error - with tempfile.TemporaryDirectory(prefix="gnn4colliders-smoke-") as directory: root = Path(directory) root_file = root / "events.root" - cache = root / "graphs.pt" + cache = root / "events.pt" target_cache = root / "target.pt" _write_root(root_file) _prepare(root_file, cache) diff --git a/scripts/slurm/evaluate.sh b/scripts/slurm/evaluate.sh index b3e6bcb671357357eba902152adb9935ba7b7e0b..c62095b2c7cbeb5fb753798e50fefd4708579c57 100755 --- a/scripts/slurm/evaluate.sh +++ b/scripts/slurm/evaluate.sh @@ -7,4 +7,7 @@ set -euo pipefail cd "${SLURM_SUBMIT_DIR:-$(pwd)}" +# PyTorch otherwise sizes CPU thread pools to every core on the node, which +# slows batch construction several-fold; match the Slurm allocation. +export OMP_NUM_THREADS="${OMP_NUM_THREADS:-${SLURM_CPUS_PER_TASK:-8}}" uv run gnn4colliders evaluate "$@" diff --git a/scripts/slurm/prepare_tth_cp_even_odd.sh b/scripts/slurm/prepare_tth_cp_even_odd.sh index 7b2c640d4d52b52fa79fbc14c9bdfd2d6c9f5864..07e2d44bc690f4c20e56dad8dc1922c6b2cf4c44 100755 --- a/scripts/slurm/prepare_tth_cp_even_odd.sh +++ b/scripts/slurm/prepare_tth_cp_even_odd.sh @@ -1,5 +1,5 @@ #!/bin/bash -# Prepare one independent graph-cache shard for the ttH CP benchmark. +# Prepare one independent event-cache shard for the ttH CP benchmark. # Submit with: sbatch --array=0-255%32 scripts/slurm/prepare_tth_cp_even_odd.sh # Override SHARD_DIR, SHARD_COUNT, and CONFIG when needed. #SBATCH -N 1 @@ -15,7 +15,7 @@ cd "${SLURM_SUBMIT_DIR:-$(pwd)}" : "${SLURM_ARRAY_TASK_ID:?submit this script as a Slurm array}" SHARD_COUNT="${SHARD_COUNT:-256}" -SHARD_DIR="${SHARD_DIR:-outputs/ttH_cp_even_odd/shards}" +SHARD_DIR="${SHARD_DIR:-outputs/ttH_cp_even_odd/event_shards}" CONFIG="${CONFIG:-config_tth_cp_even_odd}" # Prevent native math libraries from multiplying the Slurm CPU allocation. diff --git a/scripts/slurm/train_multi_gpu.sh b/scripts/slurm/train_multi_gpu.sh index c57825ab29105c12b96833ff119ff38e88a108ce..bfc3d3689f27f1938115d66cbd89a94f4bc12820 100755 --- a/scripts/slurm/train_multi_gpu.sh +++ b/scripts/slurm/train_multi_gpu.sh @@ -7,5 +7,8 @@ set -euo pipefail cd "${SLURM_SUBMIT_DIR:-$(pwd)}" +# PyTorch otherwise sizes CPU thread pools to every core on the node, which +# slows batch construction several-fold; match the Slurm allocation. +export OMP_NUM_THREADS="${OMP_NUM_THREADS:-${SLURM_CPUS_PER_TASK:-8}}" GPUS_PER_NODE="${GPUS_PER_NODE:-4}" uv run torchrun --standalone --nproc_per_node="${GPUS_PER_NODE}" -m gnn4colliders.cli train "$@" distributed=ddp environment=perlmutter diff --git a/scripts/slurm/train_multi_node.sh b/scripts/slurm/train_multi_node.sh index e9deabbab4daacec2b0e15110781b389f1634a96..76a060ab9017e5e35c7c9f488032e2d111a25845 100755 --- a/scripts/slurm/train_multi_node.sh +++ b/scripts/slurm/train_multi_node.sh @@ -8,6 +8,9 @@ set -euo pipefail cd "${SLURM_SUBMIT_DIR:-$(pwd)}" +# PyTorch otherwise sizes CPU thread pools to every core on the node, which +# slows batch construction several-fold; match the Slurm allocation. +export OMP_NUM_THREADS="${OMP_NUM_THREADS:-${SLURM_CPUS_PER_TASK:-8}}" GPUS_PER_NODE="${GPUS_PER_NODE:-4}" MASTER_ADDR="$(scontrol show hostnames "$SLURM_JOB_NODELIST" | head -n 1)" MASTER_PORT="${MASTER_PORT:-29500}" diff --git a/scripts/slurm/train_single_gpu.sh b/scripts/slurm/train_single_gpu.sh index 1faae99dcafcff3e8193eab036ad5bca6f6b35fa..2679fbc06e748df13d617d25a27757dfd20dac37 100755 --- a/scripts/slurm/train_single_gpu.sh +++ b/scripts/slurm/train_single_gpu.sh @@ -7,4 +7,7 @@ set -euo pipefail cd "${SLURM_SUBMIT_DIR:-$(pwd)}" +# PyTorch otherwise sizes CPU thread pools to every core on the node, which +# slows batch construction several-fold; match the Slurm allocation. +export OMP_NUM_THREADS="${OMP_NUM_THREADS:-${SLURM_CPUS_PER_TASK:-8}}" uv run gnn4colliders train "$@" environment.device=cuda diff --git a/src/gnn4colliders/cli/__init__.py b/src/gnn4colliders/cli/__init__.py index 1516b904db03c2dd85dcaf9262dc17bb6279204a..047dba6b2c59635854d7e4607c113ed8c1d4506c 100644 --- a/src/gnn4colliders/cli/__init__.py +++ b/src/gnn4colliders/cli/__init__.py @@ -157,10 +157,12 @@ def main(argv: list[str] | None = None) -> int: shard_count=shard_count, output_dir=output_dir, ) - print(f"prepared graph shard: {shard}") + print(f"prepared event shard: {shard}") elif command == "train": + # Every rank must train: DDP collectives need all processes. + checkpoint = train(config) if _is_main_process(): - print(f"saved checkpoint: {train(config)}") + print(f"saved checkpoint: {checkpoint}") elif command == "export": if _is_main_process(): print(f"wrote ONNX model: {export_onnx(config)}") diff --git a/src/gnn4colliders/config/application.py b/src/gnn4colliders/config/application.py index d845e8c63b6cdb1123f0cd7c31e62c9252761de4..4e1f5a003074317c7d6808855835fc25226c0cbc 100644 --- a/src/gnn4colliders/config/application.py +++ b/src/gnn4colliders/config/application.py @@ -9,12 +9,16 @@ from typing import Any from omegaconf import DictConfig, OmegaConf from gnn4colliders.data import ( - DistributedGraphDataLoader, - GraphDataLoader, - GraphDataset, - GraphSampleCache, + DistributedEventLoader, + EventCache, + EventLoader, + PackedEvents, SplitDefinition, - select_split, +) +from gnn4colliders.data.preparation import ( + prepare_event_cache, + prepare_event_shard, + write_event_shard_manifest, ) from gnn4colliders.distributed import ( DistributedContext, @@ -22,16 +26,9 @@ from gnn4colliders.distributed import ( finalize, initialize, ) -from gnn4colliders.graphs.preparation import ( - prepare_graph_cache, - prepare_graph_shard, - write_graph_shard_manifest, -) +from gnn4colliders.graphs import collate_graph_batch from gnn4colliders.inference import Predictor, write_npz -from gnn4colliders.sequences import ( - SequenceDataLoader, - sequence_samples_from_graph_samples, -) +from gnn4colliders.sequences import collate_sequence_batch from gnn4colliders.training import ( CheckpointManager, restore_training_state, @@ -53,68 +50,48 @@ def save_resolved(config: DictConfig, output_root: str | Path) -> Path: return target -def load_samples(config: DictConfig) -> GraphDataset: - data = config.data - cache_path = data.cache.path +def load_events(config: DictConfig) -> PackedEvents: + cache_path = config.data.cache.path if not cache_path: raise ValueError("data.cache.path is required for train/evaluate/predict") - cache = GraphSampleCache(cache_path) + cache = EventCache(cache_path) if not cache.exists(): - raise FileNotFoundError(f"graph sample cache does not exist: {cache_path}") - return GraphDataset(cache.load()) + raise FileNotFoundError(f"event cache does not exist: {cache_path}") + return cache.load() + + +def _collate(config: DictConfig): + family = str(config.model.get("family", "root_gnn")).lower() + return ( + collate_sequence_batch if family == "root_transformer" else collate_graph_batch + ) def loaders( config: DictConfig, context: DistributedContext | None = None ) -> dict[str, Any]: - samples = load_samples(config) + events = load_events(config) split = SplitDefinition( train_folds=frozenset(config.data.splits.train_folds), validation_folds=frozenset(config.data.splits.validation_folds), test_folds=frozenset(config.data.splits.test_folds), ) - if str(config.model.get("family", "root_gnn")).lower() == "root_transformer": - if context is not None and context.enabled: - raise ValueError( - "root_transformer sequence loading does not yet support DDP" - ) - sequence_samples = sequence_samples_from_graph_samples(samples.samples) - result = {} - for name in ("train", "validation", "test"): - selected = select_split(sequence_samples, split, name) - result[name] = SequenceDataLoader( - selected, - int(config.data.batch_size), - shuffle=bool(config.data.shuffle) if name == "train" else False, - seed=int(config.data.seed), - ) - return result - tensor_graphs = str(config.model.get("backend", "torch")).lower() == "torch" + distributed = context is not None and context.enabled + collate = _collate(config) + if distributed and collate is collate_sequence_batch: + raise ValueError("root_transformer sequence loading does not yet support DDP") result = {} for name in ("train", "validation", "test"): - selected = GraphDataset(select_split(samples.samples, split, name)) - loader_type = ( - DistributedGraphDataLoader - if context is not None and context.enabled - else GraphDataLoader - ) + options = { + "indices": events.split_indices(split, name), + "shuffle": bool(config.data.shuffle) if name == "train" else False, + "seed": int(config.data.seed), + } + batch_size = int(config.data.batch_size) result[name] = ( - loader_type( - selected, - int(config.data.batch_size), - context, - shuffle=bool(config.data.shuffle) if name == "train" else False, - seed=int(config.data.seed), - tensor_graphs=tensor_graphs, - ) - if loader_type is DistributedGraphDataLoader - else loader_type( - selected, - int(config.data.batch_size), - shuffle=bool(config.data.shuffle) if name == "train" else False, - seed=int(config.data.seed), - tensor_graphs=tensor_graphs, - ) + DistributedEventLoader(events, collate, batch_size, context, **options) + if distributed + else EventLoader(events, collate, batch_size, **options) ) return result @@ -130,7 +107,7 @@ def prepare(config: DictConfig) -> Path: "prepare does not support distributed launch; use data.num_workers " "for local process parallelism", ) - return prepare_graph_cache(plain(config.data)) + return prepare_event_cache(plain(config.data)) def prepare_shard( @@ -140,8 +117,8 @@ def prepare_shard( shard_count: int, output_dir: str | Path, ) -> Path: - """Prepare one restartable graph-cache shard; see ``prepare_graph_shard``.""" - return prepare_graph_shard( + """Prepare one restartable event-cache shard; see ``prepare_event_shard``.""" + return prepare_event_shard( plain(config.data), shard_index=shard_index, shard_count=shard_count, @@ -152,13 +129,13 @@ def prepare_shard( def write_shard_manifest( config: DictConfig, *, shard_count: int, output_dir: str | Path ) -> Path: - """Describe a shard set; see ``write_graph_shard_manifest``.""" - return write_graph_shard_manifest( + """Describe a shard set; see ``write_event_shard_manifest``.""" + return write_event_shard_manifest( plain(config.data), shard_count=shard_count, output_dir=output_dir ) -def _model_and_task(config: DictConfig, loader: GraphDataLoader): +def _model_and_task(config: DictConfig, loader: EventLoader): first = next(iter(loader), None) if first is None: raise ValueError("selected data split is empty") diff --git a/src/gnn4colliders/config/factories.py b/src/gnn4colliders/config/factories.py index b0dc2693aa97246491c7bfe9f01cc65d87d61632..5893e18db92633e2675fec2f67c42e5d1da7d668 100644 --- a/src/gnn4colliders/config/factories.py +++ b/src/gnn4colliders/config/factories.py @@ -8,11 +8,7 @@ from typing import Any import torch from gnn4colliders.distributed import DistributedContext -from gnn4colliders.models.root_gnn import ( - EdgeNetwork, - FineTunedEdgeNetwork, - TensorEdgeNetwork, -) +from gnn4colliders.models.root_gnn import EdgeNetwork, FineTunedEdgeNetwork from gnn4colliders.models.root_transformer import TransformerClassifier from gnn4colliders.tasks import BinaryClassificationTask, MulticlassClassificationTask from gnn4colliders.training import ( @@ -74,9 +70,12 @@ def build_model( if family != "root_gnn": raise ValueError(f"unsupported model family {family!r}") backend = str(_get(config, "backend", "torch")).lower() - if backend not in {"torch", "dgl"}: - raise ValueError(f"unsupported root_gnn backend {backend!r}") - model_class = TensorEdgeNetwork if backend == "torch" else EdgeNetwork + if backend != "torch": + raise ValueError( + f"unsupported root_gnn backend {backend!r}; the DGL backend was removed " + "and ROOT-GNN always runs on PyTorch tensors" + ) + model_class = EdgeNetwork kwargs = { "hid_size": int(_get(config, "hid_size", _get(config, "hidden_dim", 128))), "out_size": int(_get(config, "out_size", 1)), diff --git a/src/gnn4colliders/configs/data/hf_delphes.yaml b/src/gnn4colliders/configs/data/hf_delphes.yaml index f9c5aa5ac7b412d6f8222ed131b1b129268c8551..ee941b7b582846bb43c61ae2278ff662a1024e7f 100644 --- a/src/gnn4colliders/configs/data/hf_delphes.yaml +++ b/src/gnn4colliders/configs/data/hf_delphes.yaml @@ -39,7 +39,7 @@ num_workers: 0 shuffle: true seed: 42 cache: - path: outputs/hf_delphes/graphs + path: outputs/hf_delphes/events.pt splits: train_folds: [1, 2, 3] validation_folds: [0] diff --git a/src/gnn4colliders/configs/data/hf_smoke.yaml b/src/gnn4colliders/configs/data/hf_smoke.yaml index a288ce5fabff4d00645c4fec7203048d68af2e7e..0dac44fcf8cb08f21e4a4748031f61216b9ecccf 100644 --- a/src/gnn4colliders/configs/data/hf_smoke.yaml +++ b/src/gnn4colliders/configs/data/hf_smoke.yaml @@ -31,7 +31,7 @@ num_workers: 0 shuffle: true seed: 42 cache: - path: outputs/hf_smoke/graphs + path: outputs/hf_smoke/events.pt splits: train_folds: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, diff --git a/src/gnn4colliders/configs/data/tth_cp_even_odd.yaml b/src/gnn4colliders/configs/data/tth_cp_even_odd.yaml index f56fa7027f2b2a5deaee1d394ab2b640894bc252..5466d89a2e45766daa8dbd36cfc53bfdf50b5d2f 100644 --- a/src/gnn4colliders/configs/data/tth_cp_even_odd.yaml +++ b/src/gnn4colliders/configs/data/tth_cp_even_odd.yaml @@ -26,7 +26,7 @@ num_workers: 0 shuffle: true seed: 42 cache: - path: outputs/ttH_cp_even_odd/graphs.pt + path: outputs/ttH_cp_even_odd/events.pt splits: train_folds: [0, 1, 2, 3, 4, 5, 6, 7] validation_folds: [8] diff --git a/src/gnn4colliders/configs/model/root_gnn/edge_network.yaml b/src/gnn4colliders/configs/model/root_gnn/edge_network.yaml index fd8adb8de975365726966bb5b1697e9042f1a781..17b359d2241a9db07d45b58e8027383d28f0c5d3 100644 --- a/src/gnn4colliders/configs/model/root_gnn/edge_network.yaml +++ b/src/gnn4colliders/configs/model/root_gnn/edge_network.yaml @@ -1,5 +1,4 @@ family: root_gnn -backend: torch name: edge_network hid_size: 128 out_size: 12 diff --git a/src/gnn4colliders/configs/model/root_gnn/edge_network_binary.yaml b/src/gnn4colliders/configs/model/root_gnn/edge_network_binary.yaml index 1eac8d45abe1ffdae227b96e5500c0a55e3d1ec0..e38873eee8d6b200de2f4676a0d3d1e64b53ca94 100644 --- a/src/gnn4colliders/configs/model/root_gnn/edge_network_binary.yaml +++ b/src/gnn4colliders/configs/model/root_gnn/edge_network_binary.yaml @@ -1,5 +1,4 @@ family: root_gnn -backend: torch name: edge_network hid_size: 128 out_size: 1 diff --git a/src/gnn4colliders/configs/model/root_gnn/fine_tuned_edge_network.yaml b/src/gnn4colliders/configs/model/root_gnn/fine_tuned_edge_network.yaml index 590073731bb3c85703a018accb704cc4166db242..3962b6cc1f15a1c6dc74b8d90924e9af3c250bc1 100644 --- a/src/gnn4colliders/configs/model/root_gnn/fine_tuned_edge_network.yaml +++ b/src/gnn4colliders/configs/model/root_gnn/fine_tuned_edge_network.yaml @@ -1,5 +1,4 @@ family: root_gnn -backend: torch name: fine_tuned_edge_network hid_size: 128 out_size: 1 diff --git a/src/gnn4colliders/data/__init__.py b/src/gnn4colliders/data/__init__.py index c7ee696e4ec6ede3cb0a4b9b3c38573375759188..3d0d91c8e71e1bb1bdc4ab10f31c99514c6e698d 100644 --- a/src/gnn4colliders/data/__init__.py +++ b/src/gnn4colliders/data/__init__.py @@ -1,17 +1,9 @@ """Generic data access and dataset infrastructure.""" -from .cache import CacheMetadata, GraphSampleCache -from .dataset import RootEventDataset -from .graph_dataset import ( - DistributedGraphDataLoader, - GraphBatch, - GraphDataLoader, - GraphDataset, - GraphSample, - TensorGraph, - batch_graph_samples, -) +from .dataset import EventChunk, RootEventDataset +from .events import EventCache, PackedEvents, concatenate_events, pack_events from .huggingface import resolve_data_files +from .loader import DistributedEventLoader, EventLoader from .metadata import ( CACHE_SCHEMA_VERSION, FEATURE_SCHEMA_VERSION, @@ -27,15 +19,13 @@ __all__ = [ "EventSample", "EventMetadata", "BatchMetadata", - "GraphSample", - "TensorGraph", - "GraphBatch", - "GraphDataset", - "GraphDataLoader", - "DistributedGraphDataLoader", - "batch_graph_samples", - "CacheMetadata", - "GraphSampleCache", + "EventChunk", + "PackedEvents", + "EventCache", + "concatenate_events", + "pack_events", + "EventLoader", + "DistributedEventLoader", "SplitDefinition", "select_folds", "select_split", diff --git a/src/gnn4colliders/data/cache.py b/src/gnn4colliders/data/cache.py deleted file mode 100644 index 98d266dd18c208e250aa14adf8351aca585e5aed..0000000000000000000000000000000000000000 --- a/src/gnn4colliders/data/cache.py +++ /dev/null @@ -1,69 +0,0 @@ -"""Versioned cache for processed graph samples.""" - -from __future__ import annotations - -from dataclasses import asdict, dataclass, field -from pathlib import Path -from typing import Any - -import torch - -from .graph_dataset import GraphSample -from .metadata import CACHE_SCHEMA_VERSION, FEATURE_SCHEMA_VERSION, GRAPH_SCHEMA_VERSION - - -@dataclass(frozen=True) -class CacheMetadata: - feature_schema_version: int = FEATURE_SCHEMA_VERSION - graph_schema_version: int = GRAPH_SCHEMA_VERSION - cache_schema_version: int = CACHE_SCHEMA_VERSION - source: str | None = None - preprocessing: dict[str, Any] = field(default_factory=dict) - - -class GraphSampleCache: - """Save/load graph samples with schema metadata checked before use.""" - - def __init__(self, path: str | Path, metadata: CacheMetadata | None = None) -> None: - self.path = Path(path) - self.metadata = metadata or CacheMetadata() - - def save(self, samples: list[GraphSample] | tuple[GraphSample, ...]) -> None: - payload = { - "cache_metadata": asdict(self.metadata), - "samples": tuple(samples), - } - self.path.parent.mkdir(parents=True, exist_ok=True) - torch.save(payload, self.path) - - def load(self) -> tuple[GraphSample, ...]: - payload = torch.load(self.path, map_location="cpu", weights_only=False) - if not isinstance(payload, dict): - raise ValueError("cache payload must be a mapping") - actual = payload.get("cache_metadata", {}) - if not isinstance(actual, dict): - raise ValueError("cache metadata is missing or malformed") - expected = asdict(self.metadata) - for key in ( - "feature_schema_version", - "graph_schema_version", - "cache_schema_version", - ): - if actual.get(key) != expected[key]: - raise ValueError( - f"cache schema mismatch for {key}: " - f"found {actual.get(key)!r}, expected {expected[key]!r}" - ) - if actual.get("preprocessing", {}) != expected["preprocessing"]: - raise ValueError("cache preprocessing fingerprint mismatch") - if "samples" not in payload: - raise ValueError("cache samples are missing") - samples = payload["samples"] - if not isinstance(samples, (list, tuple)): - raise ValueError("cache samples are malformed") - if any(not isinstance(sample, GraphSample) for sample in samples): - raise ValueError("cache contains invalid graph samples") - return tuple(samples) - - def exists(self) -> bool: - return self.path.is_file() diff --git a/src/gnn4colliders/data/dataset.py b/src/gnn4colliders/data/dataset.py index 36321b597138666bde373f7d19315773db4658a6..0576c38109d87771815b69f4a4047dacbbe731c0 100644 --- a/src/gnn4colliders/data/dataset.py +++ b/src/gnn4colliders/data/dataset.py @@ -3,6 +3,7 @@ from __future__ import annotations from collections.abc import Iterator, Sequence +from dataclasses import dataclass from pathlib import Path from typing import Any @@ -27,6 +28,17 @@ def _as_float(value: Any) -> float: return float(array) +@dataclass(frozen=True) +class EventChunk: + """Selected branches for local entries ``[entry_start, entry_stop)``.""" + + file_index: int + path: Path + entry_start: int + entry_stop: int + arrays: Any + + def _file_labels(label: Any, count: int) -> list[Any]: if isinstance(label, Sequence) and not isinstance(label, (str, bytes)): if len(label) != count: @@ -113,24 +125,10 @@ class RootEventDataset: self, start: int = 0, stop: int | None = None ) -> Iterator[EventSample]: """Yield events in ``[start, stop)`` while reading each file once.""" - start = max(0, int(start)) - stop = len(self) if stop is None else min(len(self), int(stop)) - if start > stop: - raise ValueError("start must not exceed stop") - for file_index, path in enumerate(self.files): - file_start, file_stop = self._offsets[file_index : file_index + 2] - local_start = max(start, file_start) - file_start - local_stop = min(stop, file_stop) - file_start - if local_start >= local_stop: - continue - arrays = read_tree( - path, - self.tree_name, - self._branches, - entry_start=local_start, - entry_stop=local_stop, - ) - for offset in range(local_stop - local_start): + for chunk in self.iter_chunks(start, stop): + file_index, path, arrays = chunk.file_index, chunk.path, chunk.arrays + file_start, local_start = self._offsets[file_index], chunk.entry_start + for offset in range(chunk.entry_stop - local_start): local_index = local_start + offset event = {branch: arrays[branch][offset] for branch in self._branches} metadata_values = np.asarray( @@ -173,5 +171,37 @@ class RootEventDataset: ), ) + def iter_chunks( + self, start: int = 0, stop: int | None = None, *, step: int | None = None + ) -> Iterator[EventChunk]: + """Yield the selected branches of ``[start, stop)`` as Awkward arrays. + + Chunks never span files and hold at most ``step`` events when given. + """ + start = max(0, int(start)) + stop = len(self) if stop is None else min(len(self), int(stop)) + if start > stop: + raise ValueError("start must not exceed stop") + for file_index, path in enumerate(self.files): + file_start, file_stop = self._offsets[file_index : file_index + 2] + local_start = max(start, file_start) - file_start + local_stop = min(stop, file_stop) - file_start + size = step or max(1, local_stop - local_start) + for chunk_start in range(local_start, local_stop, size): + chunk_stop = min(local_stop, chunk_start + size) + yield EventChunk( + file_index=file_index, + path=path, + entry_start=chunk_start, + entry_stop=chunk_stop, + arrays=read_tree( + path, + self.tree_name, + self._branches, + entry_start=chunk_start, + entry_stop=chunk_stop, + ), + ) + def __iter__(self) -> Iterator[EventSample]: yield from self.iter_range() diff --git a/src/gnn4colliders/data/events.py b/src/gnn4colliders/data/events.py new file mode 100644 index 0000000000000000000000000000000000000000..0abfb4a1f2578de1afe67f0d635073a17440baf1 --- /dev/null +++ b/src/gnn4colliders/data/events.py @@ -0,0 +1,303 @@ +"""Representation-neutral packed storage for prepared collider events. + +Events are stored column-wise: every object of every event is one row of +``object_features`` and ``object_offsets`` delimits the rows of each event. +Graph, sequence, or any other representation is derived at batch time, so the +same prepared data serves every model family. +""" + +from __future__ import annotations + +import pickle +from collections.abc import Sequence +from dataclasses import dataclass, fields +from pathlib import Path +from typing import Any + +import torch + +from .metadata import CACHE_SCHEMA_VERSION, FEATURE_SCHEMA_VERSION, BatchMetadata +from .splits import SplitDefinition + +_TENSOR_FIELDS = ( + "object_features", + "object_offsets", + "labels", + "fold", + "weight", + "file_index", + "entry_index", +) + + +@dataclass(frozen=True) +class PackedEvents: + """Prepared events in a flat, memory-mappable tensor layout. + + ``object_features`` has one row per object and columns named by + ``feature_names``; rows of event ``i`` are + ``object_offsets[i]:object_offsets[i + 1]``. Per-event metadata is stored + as named columns. ``sample_id`` is derived from ``source_files``, + ``tree_name``, ``file_index``, and ``entry_index``. + """ + + object_features: torch.Tensor + object_offsets: torch.Tensor + labels: torch.Tensor + global_features: torch.Tensor | None + fold: torch.Tensor + weight: torch.Tensor + file_index: torch.Tensor + entry_index: torch.Tensor + source_files: tuple[str, ...] + tree_name: str + feature_names: tuple[str, ...] + + def __post_init__(self) -> None: + count = int(self.object_offsets.numel()) - 1 + if count < 0: + raise ValueError("object_offsets must contain at least one entry") + if self.object_features.ndim != 2: + raise ValueError("object_features must have shape [objects, features]") + if int(self.object_offsets[-1]) != self.object_features.shape[0]: + raise ValueError("object_offsets do not cover object_features") + if self.object_features.shape[1] != len(self.feature_names): + raise ValueError("feature_names must name every object feature column") + for name in ("labels", "fold", "weight", "file_index", "entry_index"): + if getattr(self, name).shape[0] != count: + raise ValueError(f"{name} must have one entry per event") + if self.global_features is not None and ( + self.global_features.ndim != 2 or self.global_features.shape[0] != count + ): + raise ValueError("global_features must have shape [events, features]") + + def __len__(self) -> int: + return int(self.object_offsets.numel()) - 1 + + @property + def object_counts(self) -> torch.Tensor: + return self.object_offsets.diff() + + def sample_ids(self, indices: torch.Tensor) -> tuple[str, ...]: + files = self.file_index[indices].tolist() + entries = self.entry_index[indices].tolist() + return tuple( + f"{self.source_files[file]}:{self.tree_name}:{entry}" + for file, entry in zip(files, entries) + ) + + def gather_objects( + self, indices: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor]: + """Return the object rows and per-event counts of ``indices`` in order.""" + starts = self.object_offsets[indices] + counts = self.object_offsets[indices + 1] - starts + total = int(counts.sum()) + first = torch.cumsum(counts, 0) - counts + rows = torch.arange(total, dtype=torch.long) + torch.repeat_interleave( + starts - first, counts, output_size=total + ) + return self.object_features[rows], counts + + def batch_metadata(self, indices: torch.Tensor) -> BatchMetadata: + """Columnar metadata for ``indices`` in the order given.""" + sample_ids = self.sample_ids(indices) + files = self.file_index[indices].tolist() + entries = self.entry_index[indices].tolist() + return BatchMetadata( + fold=self.fold[indices].to(torch.long), + weight=self.weight[indices].to(torch.float32), + sample_id=sample_ids, + extra={ + "entry_index": tuple(entries), + "source_file": tuple(self.source_files[file] for file in files), + "tree_name": (self.tree_name,) * len(files), + }, + ) + + def split_indices(self, split: SplitDefinition, name: str) -> torch.Tensor: + """Event indices of one named split, in stored event order.""" + try: + folds = { + "train": split.train_folds, + "validation": split.validation_folds, + "test": split.test_folds, + }[name] + except KeyError as error: + raise ValueError(f"unknown split {name!r}") from error + selected = torch.tensor(sorted(folds), dtype=self.fold.dtype) + return torch.nonzero(torch.isin(self.fold, selected)).flatten() + + +def pack_events( + objects: Sequence[torch.Tensor], + labels: Sequence[Any] | torch.Tensor, + *, + weights: Sequence[float] | torch.Tensor | None = None, + folds: Sequence[int] | torch.Tensor | None = None, + global_features: torch.Tensor | None = None, + feature_names: Sequence[str] | None = None, + source: str = "memory", + tree_name: str = "events", +) -> PackedEvents: + """Pack in-memory per-event object tensors (``[objects, features]``). + + Weights default to one and folds to zero. Sample identifiers are + ``f"{source}:{tree_name}:{index}"``. + """ + if not objects: + raise ValueError("at least one event is required") + width = int(objects[0].shape[1]) + counts = torch.tensor([int(item.shape[0]) for item in objects], dtype=torch.long) + count = len(objects) + return PackedEvents( + object_features=torch.cat([item.to(torch.float32) for item in objects]), + object_offsets=torch.cat((torch.zeros(1, dtype=torch.long), counts.cumsum(0))), + labels=torch.as_tensor(labels), + global_features=global_features, + fold=( + torch.zeros(count, dtype=torch.long) + if folds is None + else torch.as_tensor(folds, dtype=torch.long) + ), + weight=( + torch.ones(count) + if weights is None + else torch.as_tensor(weights, dtype=torch.float32) + ), + file_index=torch.zeros(count, dtype=torch.long), + entry_index=torch.arange(count), + source_files=(source,), + tree_name=tree_name, + feature_names=( + tuple(feature_names) + if feature_names is not None + else tuple(f"feature_{index}" for index in range(width)) + ), + ) + + +def concatenate_events(parts: Sequence[PackedEvents]) -> PackedEvents: + """Concatenate prepared events in the given order.""" + if not parts: + raise ValueError("at least one part is required") + first = parts[0] + for part in parts[1:]: + if part.feature_names != first.feature_names: + raise ValueError("cannot concatenate events with different features") + if part.tree_name != first.tree_name: + raise ValueError("cannot concatenate events from different trees") + if (part.global_features is None) != (first.global_features is None): + raise ValueError("global_features must be present in every part or none") + files: list[str] = [] + file_index: list[torch.Tensor] = [] + for part in parts: + mapping = [] + for name in part.source_files: + if name not in files: + files.append(name) + mapping.append(files.index(name)) + file_index.append( + torch.tensor(mapping, dtype=torch.long)[part.file_index] + if mapping + else part.file_index + ) + offsets = [first.object_offsets] + base = first.object_offsets[-1] + for part in parts[1:]: + offsets.append(part.object_offsets[1:] + base) + base = base + part.object_offsets[-1] + return PackedEvents( + object_features=torch.cat([part.object_features for part in parts]), + object_offsets=torch.cat(offsets), + labels=torch.cat([part.labels for part in parts]), + global_features=( + None + if first.global_features is None + else torch.cat([part.global_features for part in parts]) + ), + fold=torch.cat([part.fold for part in parts]), + weight=torch.cat([part.weight for part in parts]), + file_index=torch.cat(file_index), + entry_index=torch.cat([part.entry_index for part in parts]), + source_files=tuple(files), + tree_name=first.tree_name, + feature_names=first.feature_names, + ) + + +class EventCache: + """Save and load :class:`PackedEvents` with schema versions checked. + + A cache is either one ``.pt`` file or a directory of shards described by + ``manifest.json``; shards are loaded in manifest order and concatenated. + Files contain only tensors and plain Python values, so they load with + ``weights_only=True`` and can be memory-mapped. + """ + + def __init__(self, path: str | Path) -> None: + self.path = Path(path) + + def save(self, events: PackedEvents) -> None: + payload: dict[str, Any] = { + "cache_schema_version": CACHE_SCHEMA_VERSION, + "feature_schema_version": FEATURE_SCHEMA_VERSION, + } + for item in fields(PackedEvents): + value = getattr(events, item.name) + payload[item.name] = ( + value.contiguous() if isinstance(value, torch.Tensor) else value + ) + payload["source_files"] = list(events.source_files) + payload["feature_names"] = list(events.feature_names) + self.path.parent.mkdir(parents=True, exist_ok=True) + torch.save(payload, self.path) + + def exists(self) -> bool: + return self.path.is_file() or (self.path / "manifest.json").is_file() + + def load(self, *, mmap: bool = False) -> PackedEvents: + if self.path.is_dir(): + return self._load_shards(mmap=mmap) + return _load_file(self.path, mmap=mmap) + + def _load_shards(self, *, mmap: bool) -> PackedEvents: + import json + + manifest = json.loads((self.path / "manifest.json").read_text()) + paths = [self.path / shard["path"] for shard in manifest["shards"]] + missing = [str(path) for path in paths if not path.is_file()] + if missing: + raise FileNotFoundError(f"cache shards are missing: {missing[:5]}") + return concatenate_events([_load_file(path, mmap=mmap) for path in paths]) + + +def _load_file(path: Path, *, mmap: bool) -> PackedEvents: + try: + # ``mmap`` requires a string filename in PyTorch 2.2. + payload = torch.load( + str(path), map_location="cpu", weights_only=True, mmap=mmap + ) + except (RuntimeError, EOFError, pickle.UnpicklingError) as error: + raise ValueError( + f"{path} is not a GNN4Colliders event cache (caches written before " + "the packed event format must be prepared again)" + ) from error + if not isinstance(payload, dict): + raise ValueError("cache payload must be a mapping") + for key, expected in ( + ("cache_schema_version", CACHE_SCHEMA_VERSION), + ("feature_schema_version", FEATURE_SCHEMA_VERSION), + ): + if payload.get(key) != expected: + raise ValueError( + f"cache schema mismatch for {key}: " + f"found {payload.get(key)!r}, expected {expected!r}" + ) + values = {item.name: payload.get(item.name) for item in fields(PackedEvents)} + missing = [name for name in _TENSOR_FIELDS if values[name] is None] + if missing: + raise ValueError(f"cache is missing fields: {missing}") + values["source_files"] = tuple(values["source_files"]) + values["feature_names"] = tuple(values["feature_names"]) + return PackedEvents(**values) diff --git a/src/gnn4colliders/data/graph_dataset.py b/src/gnn4colliders/data/graph_dataset.py deleted file mode 100644 index 7253d52e0af308ad2bd7cc7a091d0cb88fc2a6cd..0000000000000000000000000000000000000000 --- a/src/gnn4colliders/data/graph_dataset.py +++ /dev/null @@ -1,295 +0,0 @@ -"""Graph samples and deterministic batching for the ROOT-GNN path.""" - -from __future__ import annotations - -from collections.abc import Iterator, Sequence -from dataclasses import dataclass -from typing import Any - -import torch - -from .metadata import BatchMetadata, EventMetadata - - -@dataclass(frozen=True) -class GraphSample: - graph: Any - label: torch.Tensor - global_features: torch.Tensor | None - metadata: EventMetadata - - -@dataclass(frozen=True) -class GraphBatch: - graph: Any - labels: torch.Tensor - global_features: torch.Tensor | None - metadata: BatchMetadata - - def to(self, device: torch.device | str) -> "GraphBatch": - """Return a copy with tensor and graph data placed on ``device``. - - Sample identifiers and other Python metadata intentionally remain - ordinary CPU-side values. - """ - - graph = self.graph.to(device) if hasattr(self.graph, "to") else self.graph - metadata = BatchMetadata( - fold=self.metadata.fold.to(device), - weight=self.metadata.weight.to(device), - sample_id=self.metadata.sample_id, - extra=self.metadata.extra, - ) - return GraphBatch( - graph=graph, - labels=self.labels.to(device), - global_features=( - None - if self.global_features is None - else self.global_features.to(device) - ), - metadata=metadata, - ) - - -@dataclass(frozen=True) -class TensorGraph: - """Batched graph tensors usable on CPU, CUDA, and Apple's MPS backend.""" - - node_features: torch.Tensor - edge_features: torch.Tensor - edge_src: torch.Tensor - edge_dst: torch.Tensor - node_batch: torch.Tensor - edge_batch: torch.Tensor - node_counts: torch.Tensor - edge_counts: torch.Tensor - - def to(self, device: torch.device | str) -> "TensorGraph": - return TensorGraph( - *( - value.to(device) - for value in ( - self.node_features, - self.edge_features, - self.edge_src, - self.edge_dst, - self.node_batch, - self.edge_batch, - self.node_counts, - self.edge_counts, - ) - ) - ) - - -def _tensor_graphs(samples: Sequence[GraphSample]) -> TensorGraph: - node_features: list[torch.Tensor] = [] - edge_features: list[torch.Tensor] = [] - edge_src: list[torch.Tensor] = [] - edge_dst: list[torch.Tensor] = [] - node_counts: list[int] = [] - edge_counts: list[int] = [] - offset = 0 - for sample in samples: - graph = sample.graph - if isinstance(graph, TensorGraph): - if graph.node_counts.numel() != 1: - raise ValueError("each GraphSample must contain one graph") - nodes, edges = graph.node_features, graph.edge_features - src, dst = graph.edge_src, graph.edge_dst - else: - try: - nodes = graph.ndata["features"] - edges = graph.edata["features"] - src, dst = graph.edges(order="eid") - except AttributeError as error: - raise TypeError( - "GraphSample graph must be DGL-like or TensorGraph" - ) from error - node_count, edge_count = int(nodes.shape[0]), int(edges.shape[0]) - node_features.append(nodes) - edge_features.append(edges) - edge_src.append(src.to(dtype=torch.long) + offset) - edge_dst.append(dst.to(dtype=torch.long) + offset) - node_counts.append(node_count) - edge_counts.append(edge_count) - offset += node_count - node_count_tensor = torch.tensor(node_counts, dtype=torch.long) - edge_count_tensor = torch.tensor(edge_counts, dtype=torch.long) - return TensorGraph( - node_features=torch.cat(node_features), - edge_features=torch.cat(edge_features), - edge_src=torch.cat(edge_src), - edge_dst=torch.cat(edge_dst), - node_batch=torch.repeat_interleave( - torch.arange(len(samples)), node_count_tensor - ), - edge_batch=torch.repeat_interleave( - torch.arange(len(samples)), edge_count_tensor - ), - node_counts=node_count_tensor, - edge_counts=edge_count_tensor, - ) - - -def batch_graph_samples( - samples: Sequence[GraphSample], *, tensor_graphs: bool = False -) -> GraphBatch: - """Batch samples into either DGL or portable tensor graph batches.""" - - if not samples: - raise ValueError("cannot batch an empty sequence") - if tensor_graphs: - graphs = _tensor_graphs(samples) - else: - try: - import dgl - except ImportError as error: # pragma: no cover - optional dependency - raise ImportError("DGL batching requires the 'root-gnn' extra") from error - graphs = dgl.batch([sample.graph for sample in samples]) - labels = torch.stack([torch.as_tensor(sample.label) for sample in samples]) - globals_ = [sample.global_features for sample in samples] - if any(value is None for value in globals_): - if not all(value is None for value in globals_): - raise ValueError("global_features must be present for every sample or none") - batched_globals = None - else: - batched_globals = torch.stack( - [value for value in globals_ if value is not None] - ) - return GraphBatch( - graph=graphs, - labels=labels, - global_features=batched_globals, - metadata=BatchMetadata.from_events([sample.metadata for sample in samples]), - ) - - -class GraphDataLoader: - """Deterministic, dependency-light loader over :class:`GraphDataset`. - - Shuffling uses a local Torch generator, so constructing or iterating a - loader does not mutate process-wide random state. - """ - - def __init__( - self, - dataset: Sequence[GraphSample], - batch_size: int, - *, - shuffle: bool = False, - drop_last: bool = False, - seed: int = 12345, - tensor_graphs: bool = False, - ) -> None: - if batch_size < 1: - raise ValueError("batch_size must be positive") - self.dataset = dataset - self.batch_size = batch_size - self.shuffle = shuffle - self.drop_last = drop_last - self.seed = seed - self.tensor_graphs = tensor_graphs - self.epoch = 0 - - def set_epoch(self, epoch: int) -> None: - self.epoch = epoch - - def __len__(self) -> int: - count, remainder = divmod(len(self.dataset), self.batch_size) - return count if self.drop_last or remainder == 0 else count + 1 - - def __iter__(self) -> Iterator[GraphBatch]: - indices = torch.arange(len(self.dataset), dtype=torch.long) - if self.shuffle: - generator = torch.Generator() - generator.manual_seed(self.seed + self.epoch) - indices = indices[torch.randperm(len(indices), generator=generator)] - limit = len(indices) - (len(indices) % self.batch_size if self.drop_last else 0) - for start in range(0, limit, self.batch_size): - selected = [ - self.dataset[int(index)] - for index in indices[start : start + self.batch_size] - ] - yield batch_graph_samples(selected, tensor_graphs=self.tensor_graphs) - - -class DistributedGraphDataLoader(GraphDataLoader): - """Shard individual graph samples before batching. - - Training sharding pads to equal rank lengths; evaluation sharding does not - pad, preventing duplicate events from biasing metrics or predictions. - ``batch_size`` is a per-process value. - """ - - def __init__( - self, - dataset, - batch_size, - context, - *, - shuffle=False, - drop_last=False, - seed=12345, - tensor_graphs=False, - ): - super().__init__( - dataset, - batch_size, - shuffle=shuffle, - drop_last=drop_last, - seed=seed, - tensor_graphs=tensor_graphs, - ) - from gnn4colliders.distributed import DistributedIndices - - self.distributed_indices = DistributedIndices( - len(dataset), - context, - shuffle=shuffle, - drop_last=drop_last, - seed=seed, - pad=shuffle, - ) - - def set_epoch(self, epoch: int) -> None: - super().set_epoch(epoch) - self.distributed_indices.set_epoch(epoch) - - def __len__(self) -> int: - count = len(self.distributed_indices.indices()) - return ( - count // self.batch_size - if self.drop_last - else (count + self.batch_size - 1) // self.batch_size - ) - - def __iter__(self) -> Iterator[GraphBatch]: - indices = self.distributed_indices.indices() - limit = len(indices) - (len(indices) % self.batch_size if self.drop_last else 0) - for start in range(0, limit, self.batch_size): - yield batch_graph_samples( - [ - self.dataset[index] - for index in indices[start : start + self.batch_size] - ], - tensor_graphs=self.tensor_graphs, - ) - - -class GraphDataset(Sequence[GraphSample]): - """Small immutable-semantics dataset over already processed graph samples.""" - - def __init__(self, samples: Sequence[GraphSample]) -> None: - self._samples = tuple(samples) - - def __len__(self) -> int: - return len(self._samples) - - def __getitem__(self, index: int) -> GraphSample: - return self._samples[index] - - @property - def samples(self) -> tuple[GraphSample, ...]: - return self._samples diff --git a/src/gnn4colliders/data/loader.py b/src/gnn4colliders/data/loader.py new file mode 100644 index 0000000000000000000000000000000000000000..b110a2c3ffe1b5b83d1504c6ba04ac8ecc8aa871 --- /dev/null +++ b/src/gnn4colliders/data/loader.py @@ -0,0 +1,119 @@ +"""Deterministic, representation-agnostic batch loaders over packed events.""" + +from __future__ import annotations + +from collections.abc import Callable, Iterator +from typing import Any + +import torch + +from .events import PackedEvents + +Collate = Callable[[PackedEvents, torch.Tensor], Any] + + +class EventLoader: + """Batch a selection of events with a representation-specific ``collate``. + + ``indices`` selects events in their stored order. Shuffling permutes that + selection with a local generator seeded by ``seed + epoch``, so iterating + does not mutate process-wide random state. + """ + + def __init__( + self, + events: PackedEvents, + collate: Collate, + batch_size: int, + *, + indices: torch.Tensor | None = None, + shuffle: bool = False, + drop_last: bool = False, + seed: int = 12345, + ) -> None: + if batch_size < 1: + raise ValueError("batch_size must be positive") + self.events = events + self.collate = collate + self.batch_size = batch_size + self.indices = ( + torch.arange(len(events), dtype=torch.long) if indices is None else indices + ) + self.shuffle = shuffle + self.drop_last = drop_last + self.seed = seed + self.epoch = 0 + + def set_epoch(self, epoch: int) -> None: + self.epoch = epoch + + def _order(self) -> torch.Tensor: + if not self.shuffle: + return self.indices + generator = torch.Generator().manual_seed(self.seed + self.epoch) + return self.indices[torch.randperm(len(self.indices), generator=generator)] + + def _count(self) -> int: + return len(self.indices) + + def __len__(self) -> int: + count, remainder = divmod(self._count(), self.batch_size) + return count if self.drop_last or remainder == 0 else count + 1 + + def __iter__(self) -> Iterator[Any]: + order = self._order() + limit = len(order) - (len(order) % self.batch_size if self.drop_last else 0) + for start in range(0, limit, self.batch_size): + yield self.collate(self.events, order[start : start + self.batch_size]) + + +class DistributedEventLoader(EventLoader): + """Shard a selection of events across ranks before batching. + + Training sharding pads to equal rank lengths; evaluation sharding does not + pad, preventing duplicate events from biasing metrics or predictions. + ``batch_size`` is a per-process value. + """ + + def __init__( + self, + events: PackedEvents, + collate: Collate, + batch_size: int, + context: Any, + *, + indices: torch.Tensor | None = None, + shuffle: bool = False, + drop_last: bool = False, + seed: int = 12345, + ) -> None: + super().__init__( + events, + collate, + batch_size, + indices=indices, + shuffle=shuffle, + drop_last=drop_last, + seed=seed, + ) + from gnn4colliders.distributed import DistributedIndices + + self.distributed_indices = DistributedIndices( + len(self.indices), + context, + shuffle=shuffle, + drop_last=drop_last, + seed=seed, + pad=shuffle, + ) + + def set_epoch(self, epoch: int) -> None: + super().set_epoch(epoch) + self.distributed_indices.set_epoch(epoch) + + def _order(self) -> torch.Tensor: + positions = torch.tensor(self.distributed_indices.indices(), dtype=torch.long) + return self.indices[positions] + + def _count(self) -> int: + return len(self.distributed_indices.indices()) diff --git a/src/gnn4colliders/data/metadata.py b/src/gnn4colliders/data/metadata.py index 2eb813170b5f797a54903d67a1673feb9df45556..d8da7ce25a719453f218d4dbd63f4b2ee35698bb 100644 --- a/src/gnn4colliders/data/metadata.py +++ b/src/gnn4colliders/data/metadata.py @@ -10,7 +10,7 @@ import torch FEATURE_SCHEMA_VERSION = 1 GRAPH_SCHEMA_VERSION = 1 -CACHE_SCHEMA_VERSION = 1 +CACHE_SCHEMA_VERSION = 2 @dataclass(frozen=True) diff --git a/src/gnn4colliders/data/preparation.py b/src/gnn4colliders/data/preparation.py new file mode 100644 index 0000000000000000000000000000000000000000..6c1f68c22019efb884dedb711ec7342473fd8cd1 --- /dev/null +++ b/src/gnn4colliders/data/preparation.py @@ -0,0 +1,327 @@ +"""Prepare packed event caches from ROOT event sources. + +Preparation is vectorized over chunks of events and writes the +representation-neutral :class:`PackedEvents` layout; graphs, sequences, or +other model inputs are built from it at batch time. Every function takes the +resolved ``data`` configuration as a plain mapping so that it can be shipped +to spawned worker processes. +""" + +from __future__ import annotations + +import json +import logging +import multiprocessing +import os +import shutil +import tempfile +from collections.abc import Mapping, Sequence +from concurrent.futures import ProcessPoolExecutor +from pathlib import Path +from typing import Any + +import awkward as ak +import numpy as np +import torch + +from gnn4colliders.features import NODE_FEATURE_NAMES, build_object_feature_table + +from .dataset import EventChunk, RootEventDataset +from .events import EventCache, PackedEvents, concatenate_events +from .huggingface import resolve_data_files + +logger = logging.getLogger(__name__) + +#: Events read from ROOT per vectorized step; bounds peak worker memory. +CHUNK_EVENTS = 100_000 + + +def _event_dataset( + data: Mapping[str, Any], files: list[Path], labels: list[Any] +) -> RootEventDataset: + return RootEventDataset( + files, + tree_name=str(data["tree_name"]), + label=labels, + feature_branches=data.get("feature_branches"), + global_features=data.get("global_features", []), + fold_var=str(data.get("fold_var", "eventNumber")), + weight_var=data.get("weight_var"), + ) + + +def open_event_source( + data: Mapping[str, Any], +) -> tuple[RootEventDataset, list[Path], list[Any]]: + """Resolve input files and per-file labels and open the event source.""" + files, labels = resolve_data_files(data) + labels_per_file = ( + list(labels) if isinstance(labels, (list, tuple)) else [labels] * len(files) + ) + if not isinstance(labels, (list, tuple)) and isinstance(labels, Sequence): + labels_per_file = list(labels) + return _event_dataset(data, files, labels_per_file), files, labels_per_file + + +def _flat_float32(arrays: Any, spec: Any, count: int) -> np.ndarray: + """Per-event scalar values as float32, like ``EventSample`` metadata.""" + if not isinstance(spec, str): + return np.full(count, float(spec), dtype=np.float32) + values = arrays[spec] + if isinstance(values, ak.Array) and values.ndim != 1: + raise ValueError(f"tracking/global value is not scalar: branch {spec!r}") + return np.asarray(ak.to_numpy(values), dtype=np.float32) + + +def _labels(label: Any, arrays: Any, count: int) -> torch.Tensor: + if isinstance(label, str): + values = np.asarray(ak.to_numpy(arrays[label])) + if values.dtype.kind in "iu": + return torch.from_numpy(values.astype(np.int64)) + if values.dtype.kind == "b": + return torch.from_numpy(values.astype(np.bool_)) + return torch.from_numpy(values.astype(np.float32)) + scalar = torch.as_tensor(label) + return torch.full((count,), label, dtype=scalar.dtype) + + +def _pack_chunk( + data: Mapping[str, Any], source: RootEventDataset, chunk: EventChunk +) -> PackedEvents: + arrays = chunk.arrays + count = chunk.entry_stop - chunk.entry_start + features, counts = build_object_feature_table( + arrays, + count, + data["feature_branches"], + data["object_types"], + data["scales"], + ) + fold, weight = ( + _flat_float32(arrays, spec, count) for spec in source.metadata_specs + ) + global_specs = source.global_specs + globals_ = ( + torch.from_numpy( + np.stack( + [_flat_float32(arrays, spec, count) for spec in global_specs], axis=1 + ) + ) + if global_specs + else None + ) + return PackedEvents( + object_features=features, + object_offsets=torch.cat( + (torch.zeros(1, dtype=torch.long), torch.cumsum(counts, 0)) + ), + labels=_labels(source.labels[chunk.file_index], arrays, count), + global_features=globals_, + # ``int(float32(x))`` and ``float(float32(x))`` match EventSample. + fold=torch.from_numpy(fold.astype(np.int64)), + weight=torch.from_numpy(weight), + file_index=torch.full((count,), chunk.file_index, dtype=torch.long), + entry_index=torch.arange(chunk.entry_start, chunk.entry_stop), + source_files=tuple(str(path) for path in source.files), + tree_name=source.tree_name, + feature_names=_feature_names(features.shape[1]), + ) + + +def _feature_names(width: int) -> tuple[str, ...]: + if width == len(NODE_FEATURE_NAMES): + return NODE_FEATURE_NAMES + return tuple(f"feature_{index}" for index in range(width)) + + +def build_packed_events( + data: Mapping[str, Any], + files: list[Path], + labels: list[Any], + start: int, + stop: int, +) -> PackedEvents: + """Prepare the global event range ``[start, stop)``.""" + for key in ("feature_branches", "object_types", "scales"): + if data.get(key) is None: + raise ValueError( + "prepare requires data.feature_branches, object_types, and scales" + ) + source = _event_dataset(data, files, labels) + parts = [ + _pack_chunk(data, source, chunk) + for chunk in source.iter_chunks(start, stop, step=CHUNK_EVENTS) + ] + if not parts: + return _empty(data, source) + return concatenate_events(parts) + + +def _empty(data: Mapping[str, Any], source: RootEventDataset) -> PackedEvents: + width = len(data["feature_branches"]) + globals_count = len(source.global_specs) + return PackedEvents( + object_features=torch.empty((0, width)), + object_offsets=torch.zeros(1, dtype=torch.long), + labels=torch.empty(0, dtype=torch.long), + global_features=torch.empty((0, globals_count)) if globals_count else None, + fold=torch.empty(0, dtype=torch.long), + weight=torch.empty(0), + file_index=torch.empty(0, dtype=torch.long), + entry_index=torch.empty(0, dtype=torch.long), + source_files=tuple(str(path) for path in source.files), + tree_name=source.tree_name, + feature_names=_feature_names(width), + ) + + +def _build_from_args(args: tuple[Any, ...]) -> PackedEvents: + data, files, labels, start, stop = args + return build_packed_events(data, files, labels, start, stop) + + +def _write_part(args: tuple[Any, ...]) -> Path: + data, files, labels, start, stop, path = args + EventCache(path).save(build_packed_events(data, files, labels, start, stop)) + return Path(path) + + +def _worker_count(data: Mapping[str, Any]) -> int: + return max(0, int(data.get("num_workers", 0))) + + +def _run(function: Any, args: list[tuple[Any, ...]], workers: int) -> list[Any]: + if workers > 1: + with ProcessPoolExecutor( + max_workers=workers, + mp_context=multiprocessing.get_context("spawn"), + ) as pool: + return list(pool.map(function, args)) + return [function(item) for item in args] + + +def _ranges(start: int, stop: int, parts: int) -> list[tuple[int, int]]: + ranges = [ + ( + start + (stop - start) * index // parts, + start + (stop - start) * (index + 1) // parts, + ) + for index in range(parts) + ] + return [(low, high) for low, high in ranges if low < high] + + +def shard_range(total: int, shard_index: int, shard_count: int) -> tuple[int, int]: + """Return the contiguous ``[start, stop)`` event range of one shard.""" + if shard_count < 1: + raise ValueError("shard_count must be positive") + if shard_index < 0 or shard_index >= shard_count: + raise ValueError("shard_index must be in [0, shard_count)") + return ( + total * shard_index // shard_count, + total * (shard_index + 1) // shard_count, + ) + + +def prepare_event_cache(data: Mapping[str, Any]) -> Path: + """Build the complete event cache at ``data.cache.path``. + + With ``data.num_workers > 1`` contiguous event ranges are prepared in + worker processes and concatenated in event order. + """ + source, files, labels = open_event_source(data) + path = Path(data["cache"]["path"]) + path.parent.mkdir(parents=True, exist_ok=True) + workers = _worker_count(data) + ranges = _ranges(0, len(source), max(1, workers)) or [(0, 0)] + if workers <= 1: + EventCache(path).save(build_packed_events(data, files, labels, 0, len(source))) + return path + part_dir = Path(tempfile.mkdtemp(prefix=f".{path.name}.parts-", dir=path.parent)) + args = [ + (data, files, labels, start, stop, part_dir / f"part-{index:04d}.pt") + for index, (start, stop) in enumerate(ranges) + ] + try: + parts = [EventCache(part).load() for part in _run(_write_part, args, workers)] + EventCache(path).save(concatenate_events(parts)) + finally: + shutil.rmtree(part_dir, ignore_errors=True) + return path + + +def prepare_event_shard( + data: Mapping[str, Any], + *, + shard_index: int, + shard_count: int, + output_dir: str | Path, +) -> Path: + """Prepare one persistent, restartable event-cache shard. + + Shards use contiguous global event ranges and are independent of one + another, making this function suitable for a Slurm job array. Existing + valid shards are reused so interrupted arrays can be resubmitted safely. + A shard directory with its ``manifest.json`` is itself a loadable cache. + """ + source, files, labels = open_event_source(data) + start, stop = shard_range(len(source), shard_index, shard_count) + target_dir = Path(output_dir) + target_dir.mkdir(parents=True, exist_ok=True) + target = target_dir / f"shard-{shard_index:05d}.pt" + expected = stop - start + if target.is_file(): + try: + if len(EventCache(target).load(mmap=True)) == expected: + logger.info("reusing completed shard %s", target) + return target + except (OSError, RuntimeError, ValueError, EOFError): + logger.warning("discarding incomplete or incompatible shard %s", target) + + workers = _worker_count(data) + args = [ + (data, files, labels, low, high) + for low, high in _ranges(start, stop, max(1, workers)) + ] + parts = _run(_build_from_args, args, workers) + events = concatenate_events(parts) if parts else _empty(data, source) + if len(events) != expected: + raise RuntimeError( + f"shard {shard_index} produced {len(events)} events, expected {expected}" + ) + temporary = target.with_suffix(target.suffix + f".tmp-{os.getpid()}") + EventCache(temporary).save(events) + os.replace(temporary, target) + return target + + +def write_event_shard_manifest( + data: Mapping[str, Any], *, shard_count: int, output_dir: str | Path +) -> Path: + """Write an immutable description of the event ranges in a shard set.""" + source, files, labels = open_event_source(data) + target_dir = Path(output_dir) + target_dir.mkdir(parents=True, exist_ok=True) + manifest = { + "format": 2, + "total_events": len(source), + "shard_count": int(shard_count), + "tree_name": str(data["tree_name"]), + "files": [str(path) for path in files], + "labels": labels, + "shards": [ + { + "index": index, + "start": start, + "stop": stop, + "path": f"shard-{index:05d}.pt", + } + for index in range(shard_count) + for start, stop in [shard_range(len(source), index, shard_count)] + ], + } + target = target_dir / "manifest.json" + temporary = target.with_suffix(".json.tmp") + temporary.write_text(json.dumps(manifest, indent=2) + "\n") + os.replace(temporary, target) + return target diff --git a/src/gnn4colliders/data/sample.py b/src/gnn4colliders/data/sample.py index bce15bbaf82d9c9b7ad3ebeb839d19acdc7e3b91..8ad93968387b3e0f8f96cdcf3b7cddc2457aba6f 100644 --- a/src/gnn4colliders/data/sample.py +++ b/src/gnn4colliders/data/sample.py @@ -17,7 +17,7 @@ class EventSample: ``objects`` is a read-only mapping of selected ROOT branch names to the event's scalar or jagged values. Keeping branch values here lets the - shared feature layer consume the sample without introducing DGL or model + shared feature layer consume the sample without introducing graph or model classes into the data package. """ diff --git a/src/gnn4colliders/export/onnx.py b/src/gnn4colliders/export/onnx.py index 1d01d54179dc7832446ef1cb4b39f5436c8baea8..984698f11b5ad091db087798c1bfec7ea152bf6e 100644 --- a/src/gnn4colliders/export/onnx.py +++ b/src/gnn4colliders/export/onnx.py @@ -1,7 +1,7 @@ """Tensor-only ROOT-GNN export and ONNX Runtime validation. -The native model intentionally remains DGL-based. This module is an -inference/deployment adapter whose public tensor contract is: +This module is an inference/deployment adapter whose public tensor contract +is: ``node_features``, ``edge_features``, ``edge_src``, ``edge_dst``, ``node_batch``, and ``global_features``. ``global_features`` is a required runtime input for a stable ONNX signature; for models without configured @@ -22,6 +22,7 @@ import torch from torch import nn from gnn4colliders.data.metadata import FEATURE_SCHEMA_VERSION, GRAPH_SCHEMA_VERSION +from gnn4colliders.graphs.tensor_graph import TensorGraph from gnn4colliders.models.root_gnn import EdgeNetwork, FineTunedEdgeNetwork from gnn4colliders.training import CheckpointManager, load_model_weights @@ -58,18 +59,15 @@ class RootGNNExportInputs: def inputs_from_graph_batch(batch: Any) -> RootGNNExportInputs: """Convert a ``GraphBatch`` to explicit, metadata-free export inputs.""" graph = batch.graph if hasattr(batch, "graph") else batch - if not hasattr(graph, "ndata") or not hasattr(graph, "edata"): - raise TypeError("example batch must contain a DGL graph") - node_features = graph.ndata["features"] - edge_features = graph.edata["features"] + if not isinstance(graph, TensorGraph): + raise TypeError("example batch must contain a TensorGraph") + node_features = graph.node_features + edge_features = graph.edge_features if node_features.ndim != 2 or edge_features.ndim != 2: raise ValueError("graph node and edge features must be rank-2 tensors") - try: - node_counts = graph.batch_num_nodes().to(dtype=torch.long) - edge_counts = graph.batch_num_edges().to(dtype=torch.long) - edge_src, edge_dst = graph.edges(order="eid") - except AttributeError as error: - raise ValueError("export requires a batched DGL graph") from error + node_counts = graph.node_counts.to(dtype=torch.long) + edge_counts = graph.edge_counts.to(dtype=torch.long) + edge_src, edge_dst = graph.edge_src, graph.edge_dst if ( node_counts.numel() == 0 or int(node_counts.sum()) == 0 @@ -85,7 +83,7 @@ def inputs_from_graph_batch(batch: Any) -> RootGNNExportInputs: # The edge batch is deliberately derived from source node membership in the # adapter; checking it here catches malformed graph batches early. if edge_batch.numel() and not torch.equal(edge_batch, node_batch[edge_src]): - raise ValueError("DGL edge ordering does not agree with graph membership") + raise ValueError("edge ordering does not agree with graph membership") globals_ = getattr(batch, "global_features", None) if globals_ is None: globals_ = node_counts[:, None].to(dtype=node_features.dtype) @@ -198,8 +196,7 @@ def _optional_onnx() -> Any: import onnx except ImportError as error: raise ImportError( - "ONNX export requires the 'onnx' extra. Install with: " - "uv sync --extra root-gnn --extra onnx" + "ONNX export requires the 'onnx' extra. Install with: uv sync --extra onnx" ) from error return onnx @@ -226,7 +223,7 @@ def validate_onnx_runtime( except ImportError as error: raise ImportError( "ONNX Runtime validation requires the 'onnx' extra. Install with: " - "uv sync --extra root-gnn --extra onnx" + "uv sync --extra onnx" ) from error session = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"]) values = { diff --git a/src/gnn4colliders/features/__init__.py b/src/gnn4colliders/features/__init__.py index e0e796935fe151dead2757ade59c9592b497732a..56e5916063772849b7e5044b3e1866fcaa486b86 100644 --- a/src/gnn4colliders/features/__init__.py +++ b/src/gnn4colliders/features/__init__.py @@ -1,5 +1,15 @@ """Collider-domain feature transformations shared across model families.""" -from .objects import NODE_FEATURE_NAMES, build_node_features, build_object_features +from .objects import ( + NODE_FEATURE_NAMES, + build_node_features, + build_object_feature_table, + build_object_features, +) -__all__ = ["NODE_FEATURE_NAMES", "build_node_features", "build_object_features"] +__all__ = [ + "NODE_FEATURE_NAMES", + "build_node_features", + "build_object_feature_table", + "build_object_features", +] diff --git a/src/gnn4colliders/features/objects.py b/src/gnn4colliders/features/objects.py index f9596568d2329a18fdcaee623f192a3142f5b123..93d6f67c88e67a94ee4d7f7549fcd096b3557933 100644 --- a/src/gnn4colliders/features/objects.py +++ b/src/gnn4colliders/features/objects.py @@ -106,6 +106,119 @@ def build_node_features( return features * scale_tensor, lengths +def _grouped_energy( + pt: torch.Tensor, eta: torch.Tensor, sizes: np.ndarray +) -> torch.Tensor: + """``pt * cosh(eta)`` evaluated one group (event) at a time. + + PyTorch's CPU ``cosh`` can differ by 1-2 ULP between SIMD lanes and the + scalar tail, so results depend on an element's position in the tensor. + The per-event builder evaluates each event separately; grouping the same + way keeps both builders bit-identical. This position (and CPU vector + width) dependence is a known legacy artifact. + """ + groups = [int(size) for size in sizes if size] + if not groups: + return pt.new_empty(0) + return pt * torch.cat([torch.cosh(part) for part in torch.split(eta, groups)]) + + +def build_object_feature_table( + arrays: Mapping[str, Any], + num_events: int, + feature_branches: Sequence[Any], + object_types: Sequence[str], + scales: Sequence[Number] | torch.Tensor, + *, + dtype: torch.dtype = torch.float32, +) -> tuple[torch.Tensor, torch.Tensor]: + """Vectorized :func:`build_node_features` over many events at once. + + ``arrays`` maps branch names to per-event values for ``num_events`` + events: Awkward/NumPy jagged arrays for ``vector`` object types and flat + arrays for ``single`` ones. Returns the object rows of all events in event + order (identical to concatenating per-event results) and the number of + objects per event. + """ + import awkward as ak + + if not feature_branches: + return torch.empty((0, 0), dtype=dtype), torch.zeros( + num_events, dtype=torch.long + ) + first_column = feature_branches[0] + if len(first_column) != len(object_types): + raise ValueError("one branch specification is required per object type") + + lengths: list[np.ndarray] = [] + for branch, object_type in zip(first_column, object_types): + if object_type == "single": + lengths.append(np.ones(num_events, dtype=np.int64)) + elif object_type == "vector": + lengths.append(np.asarray(ak.num(arrays[branch], axis=1), dtype=np.int64)) + else: + raise ValueError(f"unknown object type: {object_type!r}") + per_type = np.stack(lengths, axis=1) if lengths else np.zeros((num_events, 0)) + counts = per_type.sum(axis=1) + event_start = np.cumsum(counts) - counts + total = int(counts.sum()) + + # Destination row of every object of each type, in event-major order. + positions: list[np.ndarray] = [] + for type_index in range(len(object_types)): + type_lengths = per_type[:, type_index] + base = event_start + per_type[:, :type_index].sum(axis=1) + type_total = int(type_lengths.sum()) + local = np.arange(type_total, dtype=np.int64) - np.repeat( + np.cumsum(type_lengths) - type_lengths, type_lengths + ) + positions.append(np.repeat(base, type_lengths) + local) + + def flat_values(branch: Any, type_index: int) -> np.ndarray: + size = positions[type_index].size + if isinstance(branch, Number): + return np.full(size, branch, dtype=np.float32) + values = arrays[branch] + if object_types[type_index] == "vector": + values = ak.flatten(values, axis=1) + return np.asarray( + ak.to_numpy(values) if isinstance(values, ak.Array) else values + ).astype(np.float32) + + columns: list[torch.Tensor] = [] + for column_index, specification in enumerate(feature_branches): + if specification == _CALCULATED_ENERGY: + columns.append(_grouped_energy(columns[0], columns[1], counts)) + continue + if specification == _NODE_TYPE: + node_type = np.empty(total, dtype=np.float32) + for type_index, rows in enumerate(positions): + node_type[rows] = type_index + columns.append(torch.from_numpy(node_type).to(dtype)) + continue + if len(specification) != len(object_types): + raise ValueError( + f"feature column {column_index} has the wrong number of branches" + ) + column = np.empty(total, dtype=np.float32) + for type_index, branch in enumerate(specification): + rows = positions[type_index] + if branch == _CALCULATED_ENERGY: + index = torch.from_numpy(rows) + column[rows] = _grouped_energy( + columns[0][index], columns[1][index], per_type[:, type_index] + ).numpy() + else: + column[rows] = flat_values(branch, type_index) + columns.append(torch.from_numpy(column).to(dtype)) + + features = torch.stack(columns, dim=1) + scale_tensor = torch.as_tensor(scales, dtype=dtype) + if scale_tensor.ndim != 1 or scale_tensor.numel() != features.shape[1]: + raise ValueError("scales must contain one value per feature column") + return features * scale_tensor, torch.from_numpy(counts.astype(np.int64)) + + def build_object_features( event: Mapping[str, Any], feature_branches: Sequence[Any], diff --git a/src/gnn4colliders/graphs/__init__.py b/src/gnn4colliders/graphs/__init__.py index d9c70a2d3886bfb5077ad9c69ea7334197b5a230..3bdded6d2322dc2d3c2c067f9d96b9443891dc13 100644 --- a/src/gnn4colliders/graphs/__init__.py +++ b/src/gnn4colliders/graphs/__init__.py @@ -1,13 +1,18 @@ """Graph representations and graph-specific transformations.""" -from .dgl import build_dgl_graph +from .batch import GraphBatch, collate_graph_batch from .edges import build_edge_features +from .tensor_graph import TensorGraph, build_tensor_graph, fully_connected_batch_edges from .topology import clear_topology_cache, fully_connected_edges, topology_cache_info __all__ = [ - "build_dgl_graph", + "GraphBatch", + "TensorGraph", "build_edge_features", - "fully_connected_edges", + "build_tensor_graph", "clear_topology_cache", + "collate_graph_batch", + "fully_connected_batch_edges", + "fully_connected_edges", "topology_cache_info", ] diff --git a/src/gnn4colliders/graphs/batch.py b/src/gnn4colliders/graphs/batch.py new file mode 100644 index 0000000000000000000000000000000000000000..21faafa2b7b01912322fc594991e0b2847b85260 --- /dev/null +++ b/src/gnn4colliders/graphs/batch.py @@ -0,0 +1,76 @@ +"""Graph batches collated from packed events.""" + +from __future__ import annotations + +from dataclasses import dataclass + +import torch + +from gnn4colliders.data.events import PackedEvents +from gnn4colliders.data.metadata import BatchMetadata + +from .tensor_graph import TensorGraph, build_tensor_graph + + +@dataclass(frozen=True) +class GraphBatch: + graph: TensorGraph + labels: torch.Tensor + global_features: torch.Tensor | None + metadata: BatchMetadata + + def to( + self, device: torch.device | str, *, non_blocking: bool = False + ) -> "GraphBatch": + """Return a copy with tensors placed on ``device``. + + Sample identifiers and other Python metadata intentionally remain + ordinary CPU-side values. + """ + return GraphBatch( + graph=self.graph.to(device, non_blocking=non_blocking), + labels=self.labels.to(device, non_blocking=non_blocking), + global_features=( + None + if self.global_features is None + else self.global_features.to(device, non_blocking=non_blocking) + ), + metadata=BatchMetadata( + fold=self.metadata.fold.to(device, non_blocking=non_blocking), + weight=self.metadata.weight.to(device, non_blocking=non_blocking), + sample_id=self.metadata.sample_id, + extra=self.metadata.extra, + ), + ) + + def pin_memory(self) -> "GraphBatch": + return GraphBatch( + graph=self.graph.pin_memory(), + labels=self.labels.pin_memory(), + global_features=( + None + if self.global_features is None + else self.global_features.pin_memory() + ), + metadata=BatchMetadata( + fold=self.metadata.fold.pin_memory(), + weight=self.metadata.weight.pin_memory(), + sample_id=self.metadata.sample_id, + extra=self.metadata.extra, + ), + ) + + +def collate_graph_batch(events: PackedEvents, indices: torch.Tensor) -> GraphBatch: + """Build a fully connected ROOT-GNN graph batch for ``indices`` in order.""" + if indices.numel() == 0: + raise ValueError("cannot batch an empty sequence") + nodes, counts = events.gather_objects(indices) + return GraphBatch( + graph=build_tensor_graph(nodes, counts), + labels=events.labels[indices], + global_features=( + None if events.global_features is None else events.global_features[indices] + ), + metadata=events.batch_metadata(indices), + ) diff --git a/src/gnn4colliders/graphs/dgl.py b/src/gnn4colliders/graphs/dgl.py deleted file mode 100644 index c27f418d3b846ac0b5f7ea8e13badf4f21f01f0a..0000000000000000000000000000000000000000 --- a/src/gnn4colliders/graphs/dgl.py +++ /dev/null @@ -1,44 +0,0 @@ -"""DGL boundary for ROOT-GNN graph construction.""" - -from __future__ import annotations - -import torch - -from gnn4colliders.features import NODE_FEATURE_NAMES - -from .edges import build_edge_features -from .topology import fully_connected_edges - - -def build_dgl_graph( - node_features: torch.Tensor, - *, - self_loops: bool = False, - eta_index: int = NODE_FEATURE_NAMES.index("eta"), - phi_index: int = NODE_FEATURE_NAMES.index("phi"), -): - """Build a DGL graph with compatible node and edge feature keys. - - DGL is imported only when this representation boundary is used. Inputs - are not moved between devices; callers control placement explicitly. - """ - try: - import dgl - except ImportError as error: # pragma: no cover - depends on optional extra - raise ImportError( - "build_dgl_graph requires the optional 'root-gnn' dependency" - ) from error - - if node_features.ndim != 2: - raise ValueError("node_features must be a two-dimensional tensor") - src, dst = fully_connected_edges( - node_features.shape[0], self_loops=self_loops, device=node_features.device - ) - graph = dgl.graph( - (src, dst), num_nodes=node_features.shape[0], device=node_features.device - ) - graph.ndata["features"] = node_features - graph.edata["features"] = build_edge_features( - node_features, src, dst, eta_index=eta_index, phi_index=phi_index - ) - return graph diff --git a/src/gnn4colliders/graphs/preparation.py b/src/gnn4colliders/graphs/preparation.py deleted file mode 100644 index 4d320df79751057e057f8573b6b39af25c640470..0000000000000000000000000000000000000000 --- a/src/gnn4colliders/graphs/preparation.py +++ /dev/null @@ -1,256 +0,0 @@ -"""Prepare graph-sample caches from ROOT event sources. - -Every function takes the resolved ``data`` configuration as a plain mapping so -that it can be shipped to spawned worker processes. -""" - -from __future__ import annotations - -import json -import logging -import multiprocessing -import os -import shutil -import tempfile -from collections.abc import Mapping, Sequence -from concurrent.futures import ProcessPoolExecutor -from pathlib import Path -from typing import Any - -import torch - -from gnn4colliders.data import ( - GraphSample, - GraphSampleCache, - RootEventDataset, - resolve_data_files, -) -from gnn4colliders.features import build_node_features - -from .dgl import build_dgl_graph - -logger = logging.getLogger(__name__) - - -def _event_dataset( - data: Mapping[str, Any], files: list[Path], labels: list[Any] -) -> RootEventDataset: - return RootEventDataset( - files, - tree_name=str(data["tree_name"]), - label=labels, - feature_branches=data.get("feature_branches"), - global_features=data.get("global_features", []), - fold_var=str(data.get("fold_var", "eventNumber")), - weight_var=data.get("weight_var"), - ) - - -def open_event_source( - data: Mapping[str, Any], -) -> tuple[RootEventDataset, list[Path], list[Any]]: - """Resolve input files and per-file labels and open the event source.""" - files, labels = resolve_data_files(data) - labels_per_file = ( - list(labels) if isinstance(labels, (list, tuple)) else [labels] * len(files) - ) - if not isinstance(labels, (list, tuple)) and isinstance(labels, Sequence): - labels_per_file = list(labels) - return _event_dataset(data, files, labels_per_file), files, labels_per_file - - -def build_graph_samples( - data: Mapping[str, Any], - files: list[Path], - labels: list[Any], - start: int, - stop: int, -) -> list[GraphSample]: - """Convert the global event range ``[start, stop)`` into graph samples.""" - feature_branches = data.get("feature_branches") - object_types = data.get("object_types") - scales = data.get("scales") - if feature_branches is None or object_types is None or scales is None: - raise ValueError( - "prepare requires data.feature_branches, object_types, and scales" - ) - source = _event_dataset(data, files, labels) - samples: list[GraphSample] = [] - for event in source.iter_range(start, stop): - features, _ = build_node_features( - event.objects, feature_branches, object_types, scales - ) - graph = build_dgl_graph(features) - globals_ = torch.as_tensor(event.global_features, dtype=torch.float32) - samples.append( - GraphSample( - graph, - torch.as_tensor(event.label), - globals_ if globals_.numel() else None, - event.event_metadata, - ) - ) - return samples - - -def _build_graph_samples_from_args(args: tuple[Any, ...]) -> list[GraphSample]: - data, files, labels, start, stop = args - return build_graph_samples(data, files, labels, start, stop) - - -def _write_graph_shard(args: tuple[Any, ...]) -> tuple[Path, int]: - data, files, labels, start, stop, path = args - samples = build_graph_samples(data, files, labels, start, stop) - shard_path = Path(path) - GraphSampleCache(shard_path).save(samples) - return shard_path, len(samples) - - -def _worker_count(data: Mapping[str, Any]) -> int: - return max(0, int(data.get("num_workers", 0))) - - -def _run(function: Any, args: list[tuple[Any, ...]], workers: int) -> list[Any]: - if workers > 1: - with ProcessPoolExecutor( - max_workers=workers, - mp_context=multiprocessing.get_context("spawn"), - ) as pool: - return list(pool.map(function, args)) - return [function(item) for item in args] - - -def shard_range(total: int, shard_index: int, shard_count: int) -> tuple[int, int]: - """Return the contiguous ``[start, stop)`` event range of one shard.""" - if shard_count < 1: - raise ValueError("shard_count must be positive") - if shard_index < 0 or shard_index >= shard_count: - raise ValueError("shard_index must be in [0, shard_count)") - return ( - total * shard_index // shard_count, - total * (shard_index + 1) // shard_count, - ) - - -def prepare_graph_cache(data: Mapping[str, Any]) -> Path: - """Build the complete graph cache at ``data.cache.path``. - - With ``data.num_workers > 1`` events are split into ordered temporary - shards built in worker processes and merged in event order. - """ - source, files, labels = open_event_source(data) - path = Path(data["cache"]["path"]) - path.parent.mkdir(parents=True, exist_ok=True) - workers = _worker_count(data) - shard_count = max(1, workers) - ranges = [ - (len(source) * index // shard_count, len(source) * (index + 1) // shard_count) - for index in range(shard_count) - ] - shard_dir = Path(tempfile.mkdtemp(prefix=f".{path.name}.shards-", dir=path.parent)) - args = [ - ( - data, - [Path(file) for file in files], - labels, - start, - stop, - shard_dir / f"shard-{index:04d}.pt", - ) - for index, (start, stop) in enumerate(ranges) - if start < stop - ] - try: - shard_results = _run(_write_graph_shard, args, workers) - samples: list[GraphSample] = [] - for shard_path, _ in shard_results: - samples.extend(GraphSampleCache(shard_path).load()) - GraphSampleCache(path).save(samples) - finally: - shutil.rmtree(shard_dir, ignore_errors=True) - return path - - -def prepare_graph_shard( - data: Mapping[str, Any], - *, - shard_index: int, - shard_count: int, - output_dir: str | Path, -) -> Path: - """Prepare one persistent, restartable graph-cache shard. - - Shards use contiguous global event ranges and are independent of one - another, making this function suitable for a Slurm job array. Existing - valid shards are reused so interrupted arrays can be resubmitted safely. - """ - source, files, labels = open_event_source(data) - start, stop = shard_range(len(source), shard_index, shard_count) - target_dir = Path(output_dir) - target_dir.mkdir(parents=True, exist_ok=True) - target = target_dir / f"shard-{shard_index:05d}.pt" - expected = stop - start - if target.is_file(): - try: - if len(GraphSampleCache(target).load()) == expected: - logger.info("reusing completed shard %s", target) - return target - except (OSError, RuntimeError, ValueError, EOFError): - logger.warning("discarding incomplete or incompatible shard %s", target) - - workers = _worker_count(data) - local_shards = max(1, workers) - local_ranges = [ - ( - start + (stop - start) * index // local_shards, - start + (stop - start) * (index + 1) // local_shards, - ) - for index in range(local_shards) - ] - args = [ - (data, files, labels, local_start, local_stop) - for local_start, local_stop in local_ranges - if local_start < local_stop - ] - local_results = _run(_build_graph_samples_from_args, args, workers) - samples = [sample for result in local_results for sample in result] - if len(samples) != expected: - raise RuntimeError( - f"shard {shard_index} produced {len(samples)} samples, expected {expected}" - ) - temporary = target.with_suffix(target.suffix + f".tmp-{os.getpid()}") - GraphSampleCache(temporary).save(samples) - os.replace(temporary, target) - return target - - -def write_graph_shard_manifest( - data: Mapping[str, Any], *, shard_count: int, output_dir: str | Path -) -> Path: - """Write an immutable description of the event ranges in a shard set.""" - source, files, labels = open_event_source(data) - target_dir = Path(output_dir) - target_dir.mkdir(parents=True, exist_ok=True) - manifest = { - "format": 1, - "total_events": len(source), - "shard_count": int(shard_count), - "tree_name": str(data["tree_name"]), - "files": [str(path) for path in files], - "labels": labels, - "shards": [ - { - "index": index, - "start": start, - "stop": stop, - "path": f"shard-{index:05d}.pt", - } - for index in range(shard_count) - for start, stop in [shard_range(len(source), index, shard_count)] - ], - } - target = target_dir / "manifest.json" - temporary = target.with_suffix(".json.tmp") - temporary.write_text(json.dumps(manifest, indent=2) + "\n") - os.replace(temporary, target) - return target diff --git a/src/gnn4colliders/graphs/tensor_graph.py b/src/gnn4colliders/graphs/tensor_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..6e74cf412b6b9662bf7b4ff035f71295ed6a8fbe --- /dev/null +++ b/src/gnn4colliders/graphs/tensor_graph.py @@ -0,0 +1,137 @@ +"""Batched graph tensors in the edge-index layout used across PyTorch GNNs. + +A :class:`TensorGraph` stores nodes and directed edges of many graphs as flat +tensors with per-element graph membership (``node_batch``/``edge_batch``), +the same convention as PyTorch Geometric's ``edge_index``/``batch``. It runs on +CPU, CUDA, and MPS without a graph library. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +import torch + +from gnn4colliders.features import NODE_FEATURE_NAMES + +from .edges import build_edge_features + + +@dataclass(frozen=True) +class TensorGraph: + """Batched graph tensors usable on CPU, CUDA, and Apple's MPS backend.""" + + node_features: torch.Tensor + edge_features: torch.Tensor + edge_src: torch.Tensor + edge_dst: torch.Tensor + node_batch: torch.Tensor + edge_batch: torch.Tensor + node_counts: torch.Tensor + edge_counts: torch.Tensor + + @property + def edge_index(self) -> torch.Tensor: + """``[2, edges]`` source/destination indices (PyG convention).""" + return torch.stack((self.edge_src, self.edge_dst)) + + @property + def num_graphs(self) -> int: + return int(self.node_counts.numel()) + + def to( + self, device: torch.device | str, *, non_blocking: bool = False + ) -> "TensorGraph": + return TensorGraph( + *( + value.to(device, non_blocking=non_blocking) + for value in ( + self.node_features, + self.edge_features, + self.edge_src, + self.edge_dst, + self.node_batch, + self.edge_batch, + self.node_counts, + self.edge_counts, + ) + ) + ) + + def pin_memory(self) -> "TensorGraph": + return TensorGraph( + *( + value.pin_memory() + for value in ( + self.node_features, + self.edge_features, + self.edge_src, + self.edge_dst, + self.node_batch, + self.edge_batch, + self.node_counts, + self.edge_counts, + ) + ) + ) + + +def fully_connected_batch_edges( + node_counts: torch.Tensor, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Directed all-pairs edges for consecutive graphs of ``node_counts`` nodes. + + Within each graph edges are source-major without self-loops, except that a + one-node graph keeps its single self-loop (legacy ROOT-GNN behavior). This + is the batched equivalent of :func:`fully_connected_edges` and returns + global ``(src, dst)`` node indices plus edges per graph. + """ + counts = node_counts.to(torch.long) + device = counts.device + edge_counts = torch.where(counts > 1, counts * (counts - 1), counts.clamp(max=1)) + total = int(edge_counts.sum()) + node_start = torch.cumsum(counts, 0) - counts + edge_start = torch.cumsum(edge_counts, 0) - edge_counts + graph = torch.repeat_interleave( + torch.arange(counts.numel(), device=device), edge_counts, output_size=total + ) + local = torch.arange(total, device=device) - edge_start[graph] + width = (counts[graph] - 1).clamp(min=1) + src = local // width + other = local % width + dst = torch.where(counts[graph] > 1, other + (other >= src).to(torch.long), src) + offset = node_start[graph] + return src + offset, dst + offset, edge_counts + + +def build_tensor_graph( + node_features: torch.Tensor, + node_counts: torch.Tensor, + *, + eta_index: int = NODE_FEATURE_NAMES.index("eta"), + phi_index: int = NODE_FEATURE_NAMES.index("phi"), +) -> TensorGraph: + """Build fully connected collider graphs with ``[deta, dphi, dR]`` edges. + + Runs on the device of ``node_features``; build after moving nodes to the + accelerator to compute topology and edge features there. + """ + counts = node_counts.to(device=node_features.device, dtype=torch.long) + src, dst, edge_counts = fully_connected_batch_edges(counts) + graphs = torch.arange(counts.numel(), device=node_features.device) + return TensorGraph( + node_features=node_features, + edge_features=build_edge_features( + node_features, src, dst, eta_index=eta_index, phi_index=phi_index + ), + edge_src=src, + edge_dst=dst, + node_batch=torch.repeat_interleave( + graphs, counts, output_size=node_features.shape[0] + ), + edge_batch=torch.repeat_interleave( + graphs, edge_counts, output_size=src.numel() + ), + node_counts=counts, + edge_counts=edge_counts, + ) diff --git a/src/gnn4colliders/inference/predictor.py b/src/gnn4colliders/inference/predictor.py index 8d87e9d0e137292ac04e0d654411cde6d42c8244..b1ac1ca2235bf979ab4035e2be742e1e36160be4 100644 --- a/src/gnn4colliders/inference/predictor.py +++ b/src/gnn4colliders/inference/predictor.py @@ -10,7 +10,6 @@ from typing import Any import torch from torch import nn -from gnn4colliders.data.graph_dataset import GraphBatch from gnn4colliders.distributed import ( DistributedContext, gather_objects, @@ -24,8 +23,8 @@ from .results import EvaluationResult, PredictionResult def _forward(model: nn.Module, batch: Any) -> torch.Tensor: - """Call the public GraphBatch or graph/global model boundary.""" - if isinstance(batch, GraphBatch): + """Call the public graph-batch or graph/global model boundary.""" + if hasattr(batch, "graph") and hasattr(batch, "global_features"): return model(batch.graph, batch.global_features) if hasattr(batch, "tokens"): return model(batch) diff --git a/src/gnn4colliders/models/root_gnn/__init__.py b/src/gnn4colliders/models/root_gnn/__init__.py index e017e4226a6146ef433116d14aa05ef9b96ab3f8..2f5aac05646367405f59c0789c717068d8ec8c36 100644 --- a/src/gnn4colliders/models/root_gnn/__init__.py +++ b/src/gnn4colliders/models/root_gnn/__init__.py @@ -1,7 +1,6 @@ """ROOT-GNN model components.""" -from .edge_network import EdgeNetwork -from .tensor_edge_network import TensorEdgeNetwork +from .edge_network import EdgeNetwork, TensorEdgeNetwork from .transfer import FineTunedEdgeNetwork, load_legacy_edge_network_state_dict __all__ = [ diff --git a/src/gnn4colliders/models/root_gnn/edge_network.py b/src/gnn4colliders/models/root_gnn/edge_network.py index 8aefeefb4f31cd6b54893b59cb3dff50ec37a2d8..97ac658c60aacd4841475f17d23d0d08d48ab146 100644 --- a/src/gnn4colliders/models/root_gnn/edge_network.py +++ b/src/gnn4colliders/models/root_gnn/edge_network.py @@ -1,4 +1,4 @@ -"""The active edge-message-passing ROOT-GNN architecture.""" +"""The ROOT-GNN edge/node/global message-passing network.""" from __future__ import annotations @@ -7,24 +7,38 @@ from typing import Any import torch from torch import nn +from gnn4colliders.graphs.tensor_graph import TensorGraph + from .blocks import make_mlp -def _broadcast(values: torch.Tensor, counts: torch.Tensor) -> torch.Tensor: - return torch.repeat_interleave(values, counts, dim=0) +def _sum_by_group( + values: torch.Tensor, groups: torch.Tensor, count: int +) -> torch.Tensor: + result = values.new_zeros((count, values.shape[1])) + return result.index_add_(0, groups, values) -def _copy_destination(edges: Any) -> dict[str, torch.Tensor]: - """DGL 2.x has ``copy_u`` but no built-in destination copy primitive.""" - return {"m_v": edges.dst["h"]} +def _mean_by_group( + values: torch.Tensor, groups: torch.Tensor, count: int +) -> torch.Tensor: + sums = _sum_by_group(values, groups, count) + sizes = _sum_by_group(values.new_ones((values.shape[0], 1)), groups, count) + return sums / sizes.clamp_min(1) class EdgeNetwork(nn.Module): - """ROOT-GNN ``Edge_Network`` with an explicit feature/classifier split.""" + """ROOT-GNN ``Edge_Network`` over :class:`TensorGraph` batches. + + Pure PyTorch (CPU, CUDA, MPS). Parameter names and update equations match + the historical DGL implementation, so its checkpoints load without + conversion; outputs are pinned to frozen DGL references in the parity + tests. Returns raw logits. + """ def __init__( self, - sample_graph: Any, + sample_graph: TensorGraph, sample_global: torch.Tensor | None, hid_size: int, out_size: int, @@ -34,32 +48,28 @@ class EdgeNetwork(nn.Module): **_: Any, ) -> None: super().__init__() + if not isinstance(sample_graph, TensorGraph): + raise TypeError("EdgeNetwork requires a TensorGraph sample") if n_proc_steps < 0: raise ValueError("n_proc_steps must be non-negative") - node_features = sample_graph.ndata["features"] - edge_features = sample_graph.edata["features"] global_width = 0 if sample_global is None else sample_global.shape[1] self.has_global = global_width != 0 - if not self.has_global: - global_width = 1 + encoder_global_width = global_width or 1 self.hid_size = hid_size self.n_layers = n_layers self.n_proc_steps = n_proc_steps - self.node_feature_size = int(node_features.shape[1]) - self.edge_feature_size = int(edge_features.shape[1]) - self.global_feature_size = ( - int(sample_global.shape[1]) if sample_global is not None else 0 - ) + self.node_feature_size = int(sample_graph.node_features.shape[1]) + self.edge_feature_size = int(sample_graph.edge_features.shape[1]) + self.global_feature_size = int(global_width) self.dropout = float(dropout) - self.node_encoder = make_mlp( - node_features.shape[1], hid_size, hid_size, n_layers, dropout=dropout + self.node_feature_size, hid_size, hid_size, n_layers, dropout=dropout ) self.edge_encoder = make_mlp( - edge_features.shape[1], hid_size, hid_size, n_layers, dropout=dropout + self.edge_feature_size, hid_size, hid_size, n_layers, dropout=dropout ) self.global_encoder = make_mlp( - global_width, hid_size, hid_size, n_layers, dropout=dropout + encoder_global_width, hid_size, hid_size, n_layers, dropout=dropout ) self.node_update = make_mlp( 3 * hid_size, hid_size, hid_size, n_layers, dropout=dropout @@ -75,8 +85,11 @@ class EdgeNetwork(nn.Module): ) self.classifier = nn.Linear(hid_size, out_size) + @property + def classify(self) -> nn.Linear: + return self.classifier + def checkpoint_config(self) -> dict[str, Any]: - """Return constructor information without serializing a sample graph.""" return { "family": "root_gnn", "class": type(self).__name__, @@ -90,99 +103,76 @@ class EdgeNetwork(nn.Module): "dropout": self.dropout, } - # Compatibility with the legacy public attribute while keeping the new - # name in the model API. - @property - def classify(self) -> nn.Linear: - return self.classifier - - def _features( - self, graph: Any, global_features: torch.Tensor | None + def _globals( + self, graph: TensorGraph, global_features: torch.Tensor | None ) -> torch.Tensor: if not self.has_global: - return graph.batch_num_nodes()[:, None].to( - device=graph.ndata["features"].device, dtype=torch.float32 + return graph.node_counts[:, None].to( + device=graph.node_features.device, dtype=torch.float32 ) if global_features is None: raise ValueError("global_features are required for this model") if global_features.ndim == 1: - if graph.batch_num_nodes().numel() != 1: - raise ValueError( - "one-dimensional global_features are valid only for one graph" - ) - global_features = global_features.unsqueeze(0) + if graph.node_counts.numel() != 1: + raise ValueError("one-dimensional global_features require one graph") + return global_features.unsqueeze(0) return global_features def forward_features( - self, graph: Any, global_features: torch.Tensor | None = None + self, graph: TensorGraph, global_features: torch.Tensor | None = None ) -> torch.Tensor: - """Return the decoded graph representation before classification.""" - try: - import dgl - except ImportError as error: # pragma: no cover - optional dependency - raise ImportError("EdgeNetwork requires the 'root-gnn' extra") from error if hasattr(graph, "graph") and hasattr(graph, "global_features"): - global_features = graph.global_features - graph = graph.graph - with graph.local_scope(): - h = self.node_encoder(graph.ndata["features"]) - e = self.edge_encoder(graph.edata["features"]) - graph.ndata["h"] = h - graph.edata["e"] = e - h_global = self.global_encoder(self._features(graph, global_features)) - counts = graph.batch_num_nodes() - for _ in range(self.n_proc_steps): - graph.apply_edges(dgl.function.copy_u("h", "m_u")) - graph.apply_edges(_copy_destination) - graph.edata["e"] = self.edge_update( - torch.cat( - ( - graph.edata["e"], - graph.edata["m_u"], - graph.edata["m_v"], - _broadcast(h_global, graph.batch_num_edges()), - ), - dim=1, - ) - ) - graph.update_all( - dgl.function.copy_e("e", "m"), dgl.function.sum("m", "h_e") + global_features, graph = graph.global_features, graph.graph + if not isinstance(graph, TensorGraph): + raise TypeError("EdgeNetwork requires TensorGraph inputs") + node_h = self.node_encoder(graph.node_features) + edge_h = self.edge_encoder(graph.edge_features) + global_h = self.global_encoder(self._globals(graph, global_features)) + graph_count = int(graph.node_counts.numel()) + for _ in range(self.n_proc_steps): + edge_h = self.edge_update( + torch.cat( + ( + edge_h, + node_h[graph.edge_src], + node_h[graph.edge_dst], + global_h[graph.edge_batch], + ), + dim=1, ) - graph.ndata["h"] = self.node_update( - torch.cat( - ( - graph.ndata["h"], - graph.ndata["h_e"], - _broadcast(h_global, counts), - ), - dim=1, - ) + ) + node_h = self.node_update( + torch.cat( + ( + node_h, + _sum_by_group(edge_h, graph.edge_dst, node_h.shape[0]), + global_h[graph.node_batch], + ), + dim=1, ) - if "w" in graph.ndata: - mask = torch.any(graph.ndata["features"] != 0, dim=1) - valid_counts = [] - start = 0 - for count in counts.tolist(): - valid_counts.append(mask[start : start + count].sum()) - start += count - denominator = ( - torch.stack(valid_counts).to(h.dtype).clamp_min(1)[:, None] - ) - mean_nodes = dgl.sum_nodes(graph, "h", "w") / denominator - else: - mean_nodes = dgl.mean_nodes(graph, "h") - h_global = self.global_update( - torch.cat((h_global, mean_nodes, dgl.mean_edges(graph, "e")), dim=1) + ) + global_h = self.global_update( + torch.cat( + ( + global_h, + _mean_by_group(node_h, graph.node_batch, graph_count), + _mean_by_group(edge_h, graph.edge_batch, graph_count), + ), + dim=1, ) - return self.global_decoder(h_global) + ) + return self.global_decoder(global_h) def forward( - self, graph: Any, global_features: torch.Tensor | None = None + self, graph: TensorGraph, global_features: torch.Tensor | None = None ) -> torch.Tensor: return self.classifier(self.forward_features(graph, global_features)) def representation( - self, graph: Any, global_features: torch.Tensor | None = None + self, graph: TensorGraph, global_features: torch.Tensor | None = None ) -> torch.Tensor: - """Legacy alias for the reusable decoded representation.""" return self.forward_features(graph, global_features) + + +#: Class name recorded by checkpoints written before the DGL model was removed. +TensorEdgeNetwork = EdgeNetwork diff --git a/src/gnn4colliders/models/root_gnn/tensor_edge_network.py b/src/gnn4colliders/models/root_gnn/tensor_edge_network.py deleted file mode 100644 index b7e11ea02a70abc1847b944a7ccf9c533c124e5e..0000000000000000000000000000000000000000 --- a/src/gnn4colliders/models/root_gnn/tensor_edge_network.py +++ /dev/null @@ -1,173 +0,0 @@ -"""Portable tensor-only ROOT-GNN message passing.""" - -from __future__ import annotations - -from typing import Any - -import torch -from torch import nn - -from gnn4colliders.data import TensorGraph - -from .blocks import make_mlp - - -def _sum_by_group( - values: torch.Tensor, groups: torch.Tensor, count: int -) -> torch.Tensor: - result = values.new_zeros((count, values.shape[1])) - return result.index_add_(0, groups, values) - - -def _mean_by_group( - values: torch.Tensor, groups: torch.Tensor, count: int -) -> torch.Tensor: - sums = _sum_by_group(values, groups, count) - sizes = _sum_by_group(values.new_ones((values.shape[0], 1)), groups, count) - return sums / sizes.clamp_min(1) - - -class TensorEdgeNetwork(nn.Module): - """ROOT-GNN using only PyTorch tensors, including on MPS and CUDA. - - Parameter names and update equations intentionally match :class:`EdgeNetwork` - so historical checkpoints load without conversion. - """ - - def __init__( - self, - sample_graph: TensorGraph, - sample_global: torch.Tensor | None, - hid_size: int, - out_size: int, - n_layers: int, - n_proc_steps: int, - dropout: float = 0.0, - **_: Any, - ) -> None: - super().__init__() - if not isinstance(sample_graph, TensorGraph): - raise TypeError("TensorEdgeNetwork requires a TensorGraph sample") - if n_proc_steps < 0: - raise ValueError("n_proc_steps must be non-negative") - global_width = 0 if sample_global is None else sample_global.shape[1] - self.has_global = global_width != 0 - encoder_global_width = global_width or 1 - self.hid_size = hid_size - self.n_layers = n_layers - self.n_proc_steps = n_proc_steps - self.node_feature_size = int(sample_graph.node_features.shape[1]) - self.edge_feature_size = int(sample_graph.edge_features.shape[1]) - self.global_feature_size = int(global_width) - self.dropout = float(dropout) - self.node_encoder = make_mlp( - self.node_feature_size, hid_size, hid_size, n_layers, dropout=dropout - ) - self.edge_encoder = make_mlp( - self.edge_feature_size, hid_size, hid_size, n_layers, dropout=dropout - ) - self.global_encoder = make_mlp( - encoder_global_width, hid_size, hid_size, n_layers, dropout=dropout - ) - self.node_update = make_mlp( - 3 * hid_size, hid_size, hid_size, n_layers, dropout=dropout - ) - self.edge_update = make_mlp( - 4 * hid_size, hid_size, hid_size, n_layers, dropout=dropout - ) - self.global_update = make_mlp( - 3 * hid_size, hid_size, hid_size, n_layers, dropout=dropout - ) - self.global_decoder = make_mlp( - hid_size, hid_size, hid_size, n_layers, dropout=dropout - ) - self.classifier = nn.Linear(hid_size, out_size) - - @property - def classify(self) -> nn.Linear: - return self.classifier - - def checkpoint_config(self) -> dict[str, Any]: - return { - "family": "root_gnn", - "class": type(self).__name__, - "backend": "torch", - "node_feature_size": self.node_feature_size, - "edge_feature_size": self.edge_feature_size, - "global_feature_size": self.global_feature_size, - "hid_size": self.hid_size, - "out_size": int(self.classifier.out_features), - "n_layers": self.n_layers, - "n_proc_steps": self.n_proc_steps, - "dropout": self.dropout, - } - - def _globals( - self, graph: TensorGraph, global_features: torch.Tensor | None - ) -> torch.Tensor: - if not self.has_global: - return graph.node_counts[:, None].to( - device=graph.node_features.device, dtype=torch.float32 - ) - if global_features is None: - raise ValueError("global_features are required for this model") - if global_features.ndim == 1: - if graph.node_counts.numel() != 1: - raise ValueError("one-dimensional global_features require one graph") - return global_features.unsqueeze(0) - return global_features - - def forward_features( - self, graph: TensorGraph, global_features: torch.Tensor | None = None - ) -> torch.Tensor: - if hasattr(graph, "graph") and hasattr(graph, "global_features"): - global_features, graph = graph.global_features, graph.graph - if not isinstance(graph, TensorGraph): - raise TypeError("TensorEdgeNetwork requires TensorGraph inputs") - node_h = self.node_encoder(graph.node_features) - edge_h = self.edge_encoder(graph.edge_features) - global_h = self.global_encoder(self._globals(graph, global_features)) - graph_count = int(graph.node_counts.numel()) - for _ in range(self.n_proc_steps): - edge_h = self.edge_update( - torch.cat( - ( - edge_h, - node_h[graph.edge_src], - node_h[graph.edge_dst], - global_h[graph.edge_batch], - ), - dim=1, - ) - ) - node_h = self.node_update( - torch.cat( - ( - node_h, - _sum_by_group(edge_h, graph.edge_dst, node_h.shape[0]), - global_h[graph.node_batch], - ), - dim=1, - ) - ) - global_h = self.global_update( - torch.cat( - ( - global_h, - _mean_by_group(node_h, graph.node_batch, graph_count), - _mean_by_group(edge_h, graph.edge_batch, graph_count), - ), - dim=1, - ) - ) - return self.global_decoder(global_h) - - def forward( - self, graph: TensorGraph, global_features: torch.Tensor | None = None - ) -> torch.Tensor: - return self.classifier(self.forward_features(graph, global_features)) - - def representation( - self, graph: TensorGraph, global_features: torch.Tensor | None = None - ) -> torch.Tensor: - return self.forward_features(graph, global_features) diff --git a/src/gnn4colliders/sequences/__init__.py b/src/gnn4colliders/sequences/__init__.py index 35113710f2fd57c262cb815fa91143c740b86682..dfab0b4ff172ecb2aed3b56c768c7fe492ae8078 100644 --- a/src/gnn4colliders/sequences/__init__.py +++ b/src/gnn4colliders/sequences/__init__.py @@ -5,8 +5,8 @@ from .sample import ( SequenceDataLoader, SequenceSample, batch_sequence_samples, + collate_sequence_batch, sequence_sample_from_event, - sequence_samples_from_graph_samples, ) __all__ = [ @@ -14,6 +14,6 @@ __all__ = [ "SequenceBatch", "SequenceDataLoader", "batch_sequence_samples", + "collate_sequence_batch", "sequence_sample_from_event", - "sequence_samples_from_graph_samples", ] diff --git a/src/gnn4colliders/sequences/sample.py b/src/gnn4colliders/sequences/sample.py index 6fa52fd8a429d7eead7745a13f422077082cb89a..a40f7badacee2b1374aaf2d4086f7036e0f17691 100644 --- a/src/gnn4colliders/sequences/sample.py +++ b/src/gnn4colliders/sequences/sample.py @@ -8,7 +8,7 @@ from typing import Any import torch -from gnn4colliders.data.graph_dataset import GraphSample +from gnn4colliders.data.events import PackedEvents from gnn4colliders.data.metadata import BatchMetadata, EventMetadata from gnn4colliders.data.sample import EventSample from gnn4colliders.features import build_node_features @@ -34,21 +34,24 @@ class SequenceBatch: global_features: torch.Tensor | None metadata: BatchMetadata - def to(self, device: torch.device | str) -> "SequenceBatch": + def to( + self, device: torch.device | str, *, non_blocking: bool = False + ) -> "SequenceBatch": + def move(value: torch.Tensor) -> torch.Tensor: + return value.to(device, non_blocking=non_blocking) + metadata = BatchMetadata( - fold=self.metadata.fold.to(device), - weight=self.metadata.weight.to(device), + fold=move(self.metadata.fold), + weight=move(self.metadata.weight), sample_id=self.metadata.sample_id, extra=self.metadata.extra, ) return SequenceBatch( - tokens=self.tokens.to(device), - token_mask=self.token_mask.to(device), - labels=self.labels.to(device), + tokens=move(self.tokens), + token_mask=move(self.token_mask), + labels=move(self.labels), global_features=( - None - if self.global_features is None - else self.global_features.to(device) + None if self.global_features is None else move(self.global_features) ), metadata=metadata, ) @@ -73,26 +76,33 @@ def sequence_sample_from_event( ) -def sequence_samples_from_graph_samples( - samples: Sequence[GraphSample], -) -> tuple[SequenceSample, ...]: - """Adapt an existing graph cache for topology-free model experiments.""" - result = [] - for sample in samples: - tokens = sample.graph.ndata["features"].detach().cpu() - result.append( - SequenceSample( - tokens=tokens, - label=torch.as_tensor(sample.label), - global_features=( - None - if sample.global_features is None - else sample.global_features.detach().cpu() - ), - metadata=sample.metadata, - ) - ) - return tuple(result) +def collate_sequence_batch( + events: PackedEvents, indices: torch.Tensor +) -> SequenceBatch: + """Pad the object rows of ``indices`` into a token batch, in order.""" + if indices.numel() == 0: + raise ValueError("cannot batch an empty sequence") + rows, counts = events.gather_objects(indices) + max_length = int(counts.max()) if counts.numel() else 0 + batch_index = torch.repeat_interleave( + torch.arange(counts.numel()), counts, output_size=rows.shape[0] + ) + position = ( + torch.arange(rows.shape[0]) - (torch.cumsum(counts, 0) - counts)[batch_index] + ) + tokens = rows.new_zeros((counts.numel(), max_length, rows.shape[1])) + tokens[batch_index, position] = rows + token_mask = torch.zeros((counts.numel(), max_length), dtype=torch.bool) + token_mask[batch_index, position] = True + return SequenceBatch( + tokens=tokens, + token_mask=token_mask, + labels=events.labels[indices], + global_features=( + None if events.global_features is None else events.global_features[indices] + ), + metadata=events.batch_metadata(indices), + ) def batch_sequence_samples(samples: Sequence[SequenceSample]) -> SequenceBatch: diff --git a/src/gnn4colliders/training/trainer.py b/src/gnn4colliders/training/trainer.py index d1be0483f694f641bedefa0c403e9719366475e6..997d3a9f5412d4147a54a5112712ec88626c7fa8 100644 --- a/src/gnn4colliders/training/trainer.py +++ b/src/gnn4colliders/training/trainer.py @@ -4,13 +4,13 @@ from __future__ import annotations import inspect import logging +import math from types import SimpleNamespace from typing import Any import torch from torch import nn -from gnn4colliders.data.graph_dataset import GraphBatch from gnn4colliders.distributed import ( DistributedContext, broadcast_bool, @@ -25,28 +25,48 @@ from .state import BatchResult, EpochResult, TrainerState, TrainingHistory logger = logging.getLogger(__name__) -def _model_forward(model: nn.Module, batch: GraphBatch) -> torch.Tensor: - """Call both supported model boundaries without masking model errors.""" +_POSITIONAL_ARGUMENTS: dict[type, int] = {} - if hasattr(batch, "tokens"): - return model(batch) +def _positional_arguments(model: nn.Module) -> int: + """Number of positional ``forward`` parameters, cached per model class.""" + cached = _POSITIONAL_ARGUMENTS.get(type(model)) + if cached is not None: + return cached try: signature = inspect.signature(model.forward) - positional = [ - parameter - for parameter in signature.parameters.values() - if parameter.kind + count = sum( + parameter.kind in (parameter.POSITIONAL_ONLY, parameter.POSITIONAL_OR_KEYWORD) - ] + for parameter in signature.parameters.values() + ) except (TypeError, ValueError): - positional = [] - if len(positional) <= 1: + count = 0 + _POSITIONAL_ARGUMENTS[type(model)] = count + return count + + +def _model_forward(model: nn.Module, batch: Any) -> torch.Tensor: + """Call both supported model boundaries without masking model errors.""" + + if hasattr(batch, "tokens"): + return model(batch) + if _positional_arguments(model) <= 1: return model(batch) return model(batch.graph, batch.global_features) -def _combined_batch(batches: list[GraphBatch], logits: torch.Tensor) -> Any: +def _summary(batch: Any) -> Any: + """Keep only what epoch metrics need, so batch tensors can be released.""" + return SimpleNamespace( + labels=batch.labels, + metadata=SimpleNamespace( + weight=batch.metadata.weight, sample_id=batch.metadata.sample_id + ), + ) + + +def _combined_batch(batches: list[Any], logits: torch.Tensor) -> Any: labels = torch.cat([batch.labels.reshape(-1) for batch in batches]) weights = torch.cat([batch.metadata.weight.reshape(-1) for batch in batches]) sample_ids = tuple( @@ -88,18 +108,19 @@ class Trainer: self.scheduler_step = scheduler_step self.state = TrainerState() - def _train_moved_batch(self, batch: GraphBatch) -> BatchResult: + def _train_moved_batch(self, batch: Any) -> BatchResult: self.optimizer.zero_grad(set_to_none=True) logits = _model_forward(self.model, batch) loss = self.task.loss(logits, batch) - if not torch.isfinite(loss): + value = float(loss.detach()) + if not math.isfinite(value): raise FloatingPointError("non-finite training loss") loss.backward() self.optimizer.step() self.state.global_step += 1 - return BatchResult(loss=float(loss.detach().cpu()), logits=logits.detach()) + return BatchResult(loss=value, logits=logits.detach()) - def train_batch(self, batch: GraphBatch) -> BatchResult: + def train_batch(self, batch: Any) -> BatchResult: """Run one optimizer step, moving the supplied batch to the device.""" return self._train_moved_batch(batch.to(self.device)) @@ -107,14 +128,14 @@ class Trainer: def train_epoch(self, loader: Any) -> EpochResult: self.model.train() losses: list[float] = [] - batches: list[GraphBatch] = [] + batches: list[Any] = [] outputs: list[torch.Tensor] = [] num_samples = 0 for batch in loader: moved = batch.to(self.device) result = self._train_moved_batch(moved) losses.append(result.loss) - batches.append(moved) + batches.append(_summary(moved)) outputs.append(result.logits) num_samples += int(moved.labels.shape[0]) if not losses: @@ -130,7 +151,7 @@ class Trainer: global_loss = sum(losses) / len(losses) metrics = { key: float(value) - for key, value in self.task.metrics(logits, combined).items() + for key, value in self.task.metrics(combined.logits, combined).items() } # Legacy training reports the arithmetic mean of batch losses, while # metrics are evaluated over every event in the complete epoch. @@ -142,19 +163,22 @@ class Trainer: self, loader: Any, *, return_outputs: bool = False ) -> EpochResult | Any: self.model.eval() - batches: list[GraphBatch] = [] + batches: list[Any] = [] outputs: list[torch.Tensor] = [] with torch.inference_mode(): for batch in loader: moved = batch.to(self.device) outputs.append(_model_forward(self.model, moved).detach()) - batches.append(moved) + batches.append(_summary(moved)) if not outputs: raise ValueError("cannot evaluate an empty loader") logits = torch.cat(outputs, dim=0) combined = _combined_batch(batches, logits) if self.distributed_context.enabled: combined = self._gather_combined(combined) + # After a distributed gather, labels and weights cover every rank, so + # the gathered logits must be used with them. + logits = combined.logits loss = self.task.loss(logits, combined) metrics = { key: float(value) diff --git a/tests/integration/test_ddp_cli.py b/tests/integration/test_ddp_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..8b9cd3ef91ce71b5504ab2e5a609c0a9789c53ac --- /dev/null +++ b/tests/integration/test_ddp_cli.py @@ -0,0 +1,89 @@ +"""The train CLI under two CPU DDP ranks (regression for rank-0-only training).""" + +import multiprocessing as mp +import os +import socket +import sys +from pathlib import Path + +import pytest +import torch + +pytestmark = [pytest.mark.integration, pytest.mark.distributed] + +FIXTURE = Path("data/fixtures/testing/ttH_NLO_64.root") + + +def _port() -> int: + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + return sock.getsockname()[1] + + +def _rank(rank: int, port: int, argv: list[str], queue) -> None: + os.environ.update( + RANK=str(rank), + LOCAL_RANK=str(rank), + WORLD_SIZE="2", + MASTER_ADDR="127.0.0.1", + MASTER_PORT=str(port), + ) + torch.set_num_threads(1) + from gnn4colliders.cli import main + + sys.argv = ["gnn4colliders", *argv] + queue.put((rank, main())) + + +@pytest.mark.skipif( + not torch.distributed.is_available(), reason="torch.distributed unavailable" +) +def test_train_cli_runs_on_every_ddp_rank(tmp_path: Path): + if not FIXTURE.is_file(): + pytest.skip(f"ROOT fixture is absent: {FIXTURE}") + from gnn4colliders.cli import main + + common = ["--config-name", "config_hf_smoke", f"data.cache.path={tmp_path}/e.pt"] + # Use both labels so the fixture exercises binary metrics. + source = FIXTURE.resolve() + prepare = ["~data.source", f"+data.files=[{source},{source}]", "+data.label=[0,1]"] + assert main(["prepare", *common, *prepare]) == 0 + train = [ + "train", + *common, + "distributed=ddp", + "distributed.backend=gloo", + "trainer.device=cpu", + # Signed NLO weights can cancel within a tiny batch under the legacy + # per-label weighted mean; absolute weights keep the loss finite. + "task.absolute_weights=true", + f"environment.output_root={tmp_path}/run", + f"checkpoint.directory={tmp_path}/run/checkpoints", + ] + context = mp.get_context("spawn") + queue = context.Queue() + port = _port() + processes = [ + context.Process(target=_rank, args=(rank, port, train, queue)) + for rank in range(2) + ] + try: + for process in processes: + process.start() + for process in processes: + process.join(180) + assert [process.exitcode for process in processes] == [0, 0] + assert sorted(queue.get(timeout=5) for _ in processes) == [(0, 0), (1, 0)] + finally: + # A regression can deadlock a rank in a collective. Do not leave that + # child alive and prevent pytest from exiting after the timeout. + for process in processes: + if process.is_alive(): + process.terminate() + process.join(5) + if process.is_alive(): + process.kill() + process.join(5) + queue.close() + queue.join_thread() + assert len(list((tmp_path / "run/checkpoints").glob("epoch_*.pt"))) == 1 diff --git a/tests/integration/test_parallel_prepare.py b/tests/integration/test_parallel_prepare.py index f03c00b7c8c8051075c31c583a3e27dcd65155e4..b000362b415b7c8ad46f57f3c87de5c5210fbf62 100644 --- a/tests/integration/test_parallel_prepare.py +++ b/tests/integration/test_parallel_prepare.py @@ -3,6 +3,7 @@ from pathlib import Path import awkward as ak import numpy as np import pytest +import torch import uproot from omegaconf import OmegaConf @@ -11,7 +12,7 @@ from gnn4colliders.config.application import ( prepare_shard, write_shard_manifest, ) -from gnn4colliders.data import GraphSampleCache +from gnn4colliders.data import EventCache, PackedEvents def _write_fixture(path: Path, events: int = 8) -> None: @@ -25,9 +26,26 @@ def _write_fixture(path: Path, events: int = 8) -> None: } +def _assert_same_events(left: PackedEvents, right: PackedEvents) -> None: + assert len(left) == len(right) + for name in ( + "object_features", + "object_offsets", + "labels", + "fold", + "weight", + "file_index", + "entry_index", + ): + assert torch.equal(getattr(left, name), getattr(right, name)), name + assert left.source_files == right.source_files + assert left.sample_ids(torch.arange(len(left))) == right.sample_ids( + torch.arange(len(right)) + ) + + @pytest.mark.integration def test_parallel_prepare_matches_serial_cache(tmp_path: Path): - pytest.importorskip("dgl") root_file = tmp_path / "events.root" _write_fixture(root_file) base = { @@ -61,19 +79,13 @@ def test_parallel_prepare_matches_serial_cache(tmp_path: Path): ) prepare(parallel_config) - serial = GraphSampleCache(tmp_path / "serial.pt").load() - parallel = GraphSampleCache(tmp_path / "parallel.pt").load() - assert len(serial) == len(parallel) - for left, right in zip(serial, parallel, strict=True): - assert left.metadata == right.metadata - assert left.label.equal(right.label) - assert left.graph.ndata["features"].equal(right.graph.ndata["features"]) - assert left.graph.edata["features"].equal(right.graph.edata["features"]) + serial = EventCache(tmp_path / "serial.pt").load() + parallel = EventCache(tmp_path / "parallel.pt").load() + _assert_same_events(serial, parallel) @pytest.mark.integration def test_shards_are_restartable_and_cover_source(tmp_path: Path): - pytest.importorskip("dgl") root_file = tmp_path / "events.root" _write_fixture(root_file, events=10) data = { @@ -109,7 +121,7 @@ def test_shards_are_restartable_and_cover_source(tmp_path: Path): ) for index in range(3) ] - assert [len(GraphSampleCache(path).load()) for path in paths] == [3, 3, 4] + assert [len(EventCache(path).load()) for path in paths] == [3, 3, 4] assert ( prepare_shard( config, @@ -119,3 +131,12 @@ def test_shards_are_restartable_and_cover_source(tmp_path: Path): ) == paths[1] ) + + serial_config = OmegaConf.create( + { + "data": dict(data, num_workers=0, cache={"path": str(tmp_path / "all.pt")}), + "distributed": {"enabled": False}, + } + ) + serial = EventCache(prepare(serial_config)).load() + _assert_same_events(EventCache(output).load(), serial) diff --git a/tests/integration/test_real_root_model.py b/tests/integration/test_real_root_model.py index 1c5434b236a60267c4557e20f6f9ba6b7e291581..5afe2fc0d47aa9e8bbd7fa436042e5839f82a958 100644 --- a/tests/integration/test_real_root_model.py +++ b/tests/integration/test_real_root_model.py @@ -9,13 +9,11 @@ import awkward as ak import pytest import torch -from gnn4colliders.data import EventMetadata, GraphSample, batch_graph_samples +from gnn4colliders.data import pack_events from gnn4colliders.features import build_node_features -from gnn4colliders.graphs import build_dgl_graph +from gnn4colliders.graphs import collate_graph_batch from gnn4colliders.models.root_gnn import EdgeNetwork, FineTunedEdgeNetwork -pytest.importorskip("dgl") - pytestmark = [pytest.mark.integration, pytest.mark.real_data] uproot = pytest.importorskip("uproot") @@ -42,39 +40,33 @@ def _fixture_path() -> Path: @pytest.fixture(scope="module") -def root_graph_samples(): +def root_events(): path = _fixture_path() if not path.exists(): pytest.skip(f"ROOT sample fixture is absent: {path}") with uproot.open(path) as root_file: arrays = root_file["output"].arrays(entry_start=0, entry_stop=64, library="ak") - samples = [] - for index, event in enumerate(ak.Array(arrays)): + objects, globals_ = [], [] + for event in ak.Array(arrays): features, _ = build_node_features( event, FEATURE_BRANCHES, OBJECT_TYPES, FEATURE_SCALES ) - samples.append( - GraphSample( - graph=build_dgl_graph(features), - label=torch.tensor(index % 2, dtype=torch.long), - global_features=torch.tensor( - [float(event["Number"]), float(event["weight"])], - dtype=torch.float32, - ), - metadata=EventMetadata( - fold=index % 4, - weight=float(event["weight"]), - sample_id=f"fixture:{index}", - ), - ) - ) - return samples + objects.append(features) + globals_.append([float(event["Number"]), float(event["weight"])]) + return pack_events( + objects, + torch.arange(64) % 2, + folds=[index % 4 for index in range(64)], + weights=[float(value) for value in arrays["weight"]], + global_features=torch.tensor(globals_, dtype=torch.float32), + source="fixture", + ) -def test_all_64_real_root_graphs_run_as_one_graph_batch(root_graph_samples): - batch = batch_graph_samples(root_graph_samples) +def test_all_64_real_root_graphs_run_as_one_graph_batch(root_events): + batch = collate_graph_batch(root_events, torch.arange(64)) model = EdgeNetwork( - root_graph_samples[0].graph, + batch.graph, torch.zeros(1, 2), hid_size=16, out_size=12, @@ -87,29 +79,32 @@ def test_all_64_real_root_graphs_run_as_one_graph_batch(root_graph_samples): with torch.no_grad(): logits = model(batch) transfer_logits = transferred(batch) - assert batch.graph.batch_num_nodes().shape == (64,) + assert batch.graph.node_counts.shape == (64,) assert logits.shape == (64, 12) assert transfer_logits.shape == (64, 1) assert torch.isfinite(logits).all() assert torch.isfinite(transfer_logits).all() -def test_real_root_graph_batch_matches_individual_forward(root_graph_samples): +def test_real_root_graph_batch_matches_individual_forward(root_events): + batch = collate_graph_batch(root_events, torch.arange(64)) model = EdgeNetwork( - root_graph_samples[0].graph, + batch.graph, torch.zeros(1, 2), hid_size=8, out_size=1, n_layers=2, n_proc_steps=1, ).eval() - batch = batch_graph_samples(root_graph_samples) with torch.no_grad(): batched = model(batch) individual = torch.cat( [ - model(sample.graph, sample.global_features) - for sample in root_graph_samples + model(single.graph, single.global_features) + for single in ( + collate_graph_batch(root_events, torch.tensor([index])) + for index in range(64) + ) ] ) assert torch.allclose(batched, individual, atol=1e-5, rtol=1e-5) diff --git a/tests/integration/test_real_root_sample.py b/tests/integration/test_real_root_sample.py index c6ac4a9a618ff5714840ccbe480471333cd1a27d..0549e47da8a759afb9a6ee348813f5f321bb2825 100644 --- a/tests/integration/test_real_root_sample.py +++ b/tests/integration/test_real_root_sample.py @@ -10,10 +10,8 @@ import pytest import torch import uproot -from gnn4colliders.features import build_node_features -from gnn4colliders.graphs import build_dgl_graph - -pytest.importorskip("dgl") +from gnn4colliders.features import build_node_features, build_object_feature_table +from gnn4colliders.graphs import build_tensor_graph pytestmark = [pytest.mark.integration, pytest.mark.real_data] @@ -64,13 +62,27 @@ def test_real_root_events_build_features_and_graphs(root_tree): event_features, lengths = build_node_features( event, FEATURE_BRANCHES, OBJECT_TYPES, FEATURE_SCALES ) - graph = build_dgl_graph(event_features) + graph = build_tensor_graph( + event_features, torch.tensor([event_features.shape[0]]) + ) assert event_features.dtype == torch.float32 assert event_features.shape == (sum(lengths), 7) - assert graph.number_of_nodes() == event_features.shape[0] + assert graph.node_features.shape[0] == event_features.shape[0] expected_edges = event_features.shape[0] * max(event_features.shape[0] - 1, 1) - assert graph.number_of_edges() == expected_edges - assert graph.edata["features"].shape == (expected_edges, 3) + assert graph.edge_features.shape == (expected_edges, 3) assert torch.isfinite(event_features).all() - assert torch.isfinite(graph.edata["features"]).all() + assert torch.isfinite(graph.edge_features).all() + + +def test_vectorized_feature_table_matches_per_event_features(root_tree): + arrays = root_tree.arrays(library="ak") + per_event = [ + build_node_features(event, FEATURE_BRANCHES, OBJECT_TYPES, FEATURE_SCALES)[0] + for event in ak.Array(arrays) + ] + table, counts = build_object_feature_table( + arrays, len(arrays), FEATURE_BRANCHES, OBJECT_TYPES, FEATURE_SCALES + ) + assert torch.equal(table, torch.cat(per_event)) + assert counts.tolist() == [len(features) for features in per_event] diff --git a/tests/integration/test_root_gnn_model.py b/tests/integration/test_root_gnn_model.py index 043285c88cc8fbb8a1523f9b4fe12b01cd748ef8..32669f22064237949b034cf41170d0bb7555307b 100644 --- a/tests/integration/test_root_gnn_model.py +++ b/tests/integration/test_root_gnn_model.py @@ -1,23 +1,19 @@ -import pytest import torch -from gnn4colliders.data import EventMetadata, GraphSample, batch_graph_samples -from gnn4colliders.graphs import build_dgl_graph +from gnn4colliders.data import pack_events +from gnn4colliders.graphs import collate_graph_batch from gnn4colliders.models.root_gnn import EdgeNetwork, FineTunedEdgeNetwork -pytest.importorskip("dgl") - def test_graph_batch_runs_through_pretraining_and_transfer_models(): - graph = build_dgl_graph(torch.tensor([[10.0, 0.2, 0.1], [8.0, -0.3, -0.2]])) - sample = GraphSample( - graph=graph, - label=torch.tensor(1), - global_features=torch.tensor([1.0, 2.0]), - metadata=EventMetadata(fold=0, weight=1.0, sample_id="fixture:0"), + events = pack_events( + [torch.tensor([[10.0, 0.2, 0.1], [8.0, -0.3, -0.2]])], + torch.tensor([1]), + global_features=torch.tensor([[1.0, 2.0]]), + source="fixture", ) - batch = batch_graph_samples([sample]) - model = EdgeNetwork(graph, torch.zeros(1, 2), 8, 12, 2, 1) + batch = collate_graph_batch(events, torch.tensor([0])) + model = EdgeNetwork(batch.graph, torch.zeros(1, 2), 8, 12, 2, 1) transferred = FineTunedEdgeNetwork.from_pretrained(model, 1) assert model(batch).shape == (1, 12) assert transferred(batch).shape == (1, 1) diff --git a/tests/parity/conftest.py b/tests/parity/conftest.py index 6b21d34c7762b89f458f94489e59540f773435ff..fa52725cfbafd160c3575af903c358f83ddd8da2 100644 --- a/tests/parity/conftest.py +++ b/tests/parity/conftest.py @@ -1,27 +1,44 @@ """Shared setup for parity tests against frozen canonical references.""" import os +from pathlib import Path import pytest pytestmark = pytest.mark.parity +ROOT = Path(__file__).parents[2] -def _dgl_is_importable(): - try: - import dgl # noqa: F401 - except ImportError: - return False - return True +#: Artifacts the parity suite compares against. Git LFS checkouts without +#: ``git lfs pull`` leave small pointer files in their place. +REQUIRED_ARTIFACTS = ( + ROOT / "tests/fixtures/root_gnn_reference/reference.npz", + ROOT / "tests/fixtures/root_gnn_dgl_reference/reference.npz", + ROOT / "Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_71.pt", + ROOT / "data/fixtures/testing/ttH_NLO_64.root", +) + + +def _unusable(path: Path) -> str | None: + if not path.is_file(): + return "missing" + with path.open("rb") as handle: + if handle.read(64).startswith(b"version https://git-lfs"): + return "a Git LFS pointer (run `git lfs pull`)" + return None @pytest.fixture(scope="session", autouse=True) -def require_root_gnn_dependencies(): - if ( - os.environ.get("GNN4COLLIDERS_REQUIRE_ROOT_GNN") == "1" - and not _dgl_is_importable() - ): +def require_parity_artifacts(): + if os.environ.get("GNN4COLLIDERS_REQUIRE_ROOT_GNN") != "1": + return + problems = [ + f"{path.relative_to(ROOT)} is {reason}" + for path in REQUIRED_ARTIFACTS + if (reason := _unusable(path)) + ] + if problems: pytest.fail( - "ROOT-GNN parity requires an importable DGL installation", + "ROOT-GNN parity requires its frozen artifacts: " + "; ".join(problems), pytrace=False, ) diff --git a/tests/parity/test_dgl_reference.py b/tests/parity/test_dgl_reference.py index 7a4455ac81d01bfe37fc48ad0f660eba07ab1525..36e71d4133fa6cdb56b4a84a5070157103709789 100644 --- a/tests/parity/test_dgl_reference.py +++ b/tests/parity/test_dgl_reference.py @@ -9,7 +9,9 @@ import pytest import torch from gnn4colliders.compat import load_legacy_checkpoint -from gnn4colliders.data import TensorGraph +from gnn4colliders.data import EventCache +from gnn4colliders.data.preparation import prepare_event_cache +from gnn4colliders.graphs import TensorGraph, collate_graph_batch from gnn4colliders.models.root_gnn import ( FineTunedEdgeNetwork, TensorEdgeNetwork, @@ -19,6 +21,26 @@ from gnn4colliders.models.root_gnn import ( ROOT = Path(__file__).parents[2] REFERENCE = ROOT / "tests/fixtures/root_gnn_dgl_reference/reference.npz" PRETRAINED = ROOT / "Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_71.pt" +FIXTURE = ROOT / "data/fixtures/testing/ttH_NLO_64.root" +DATA = { + "files": [str(FIXTURE)], + "label": 0, + "tree_name": "output", + "feature_branches": [ + ["jet_pt", "ele_pt", "mu_pt", "ph_pt", "MET_met"], + ["jet_eta", "ele_eta", "mu_eta", "ph_eta", 0], + ["jet_phi", "ele_phi", "mu_phi", "ph_phi", "MET_phi"], + "CALC_E", + ["jet_btag", 0, 0, 0, 0], + [0, "ele_charge", "mu_charge", 0, 0], + "NODE_TYPE", + ], + "object_types": ["vector", "vector", "vector", "vector", "single"], + "scales": [0.1, 1, 1, 0.1, 1, 1, 1], + "global_features": [], + "fold_var": "Number", + "weight_var": "weight", +} @pytest.fixture(scope="module") @@ -109,3 +131,37 @@ def test_legacy_pretrained_checkpoint_matches_dgl(reference): with torch.no_grad(): logits = model(graph, None).numpy() np.testing.assert_array_equal(logits, reference["pretrained.logits"]) + + +@pytest.mark.parametrize("workers", [0, 2]) +def test_prepared_graphs_match_dgl(reference, tmp_path, workers): + if not FIXTURE.is_file(): + pytest.skip(f"ROOT fixture is absent: {FIXTURE}") + data = dict(DATA, cache={"path": str(tmp_path / "events.pt")}, num_workers=workers) + events = EventCache(prepare_event_cache(data)).load() + batch = collate_graph_batch(events, torch.arange(len(events))) + expected = _graph(reference) + for name in ( + "node_features", + "edge_features", + "edge_src", + "edge_dst", + "node_counts", + "edge_counts", + ): + actual, wanted = getattr(batch.graph, name), getattr(expected, name) + assert actual.dtype == wanted.dtype, name + assert torch.equal(actual, wanted), name + assert batch.labels.tolist() == reference["labels"].tolist() + assert batch.labels.dtype == torch.long + assert batch.metadata.fold.tolist() == reference["fold"].tolist() + np.testing.assert_array_equal(batch.metadata.weight.numpy(), reference["weight"]) + # Reference IDs embed the generating machine's absolute fixture path. + assert batch.metadata.sample_id == tuple( + f"{FIXTURE}:{str(value).rsplit(':', 2)[1]}:{str(value).rsplit(':', 2)[2]}" + for value in reference["sample_id"] + ) + assert all( + str(value).rsplit(":", 2)[0].endswith(FIXTURE.name) + for value in reference["sample_id"] + ) diff --git a/tests/parity/test_graph_and_edges.py b/tests/parity/test_graph_and_edges.py index fc61273c63fc7345a1868eac88cc1025b08f7209..9940f0fe18e311d0e31b0437808a07d3da68cfbe 100644 --- a/tests/parity/test_graph_and_edges.py +++ b/tests/parity/test_graph_and_edges.py @@ -4,8 +4,8 @@ import numpy as np import torch from gnn4colliders.graphs import ( - build_dgl_graph, build_edge_features, + build_tensor_graph, fully_connected_edges, ) @@ -20,11 +20,11 @@ def test_fully_connected_topology_is_source_major_without_self_loops(): assert list(zip(source.tolist(), destination.tolist())) == expected -def test_dgl_graph_uses_canonical_topology_and_features(): +def test_tensor_graph_uses_canonical_topology_and_features(): nodes = torch.tensor([[10.0, 1.0, 3.1], [20.0, -0.5, -3.1]]) - graph = build_dgl_graph(nodes) - assert graph.num_nodes() == 2 - assert graph.num_edges() == 2 + graph = build_tensor_graph(nodes, torch.tensor([2])) + assert graph.node_features.shape[0] == 2 + assert graph.edge_features.shape[0] == 2 expected_deta = torch.tensor([1.5, -1.5]) expected_dphi = torch.tensor([-0.0831853, 0.0831853]) expected = torch.stack( @@ -32,7 +32,7 @@ def test_dgl_graph_uses_canonical_topology_and_features(): dim=1, ) np.testing.assert_allclose( - graph.edata["features"].numpy(), expected.numpy(), rtol=0, atol=1e-5 + graph.edge_features.numpy(), expected.numpy(), rtol=0, atol=1e-5 ) diff --git a/tests/parity/test_model_parity.py b/tests/parity/test_model_parity.py index aba2866e8864787280c55b1e0ba1b8a711ee1ff4..8c5c813c28702a206a887dd70b539be97d56902a 100644 --- a/tests/parity/test_model_parity.py +++ b/tests/parity/test_model_parity.py @@ -5,19 +5,15 @@ from __future__ import annotations from pathlib import Path import numpy as np -import pytest import torch -from gnn4colliders.graphs import build_dgl_graph +from gnn4colliders.graphs import build_tensor_graph from gnn4colliders.models.root_gnn import ( EdgeNetwork, FineTunedEdgeNetwork, load_legacy_edge_network_state_dict, ) -pytest.importorskip("dgl") - - REFERENCE = ( Path(__file__).parents[1] / "fixtures" / "root_gnn_reference" / "reference.npz" ) @@ -30,7 +26,8 @@ def _fixture(): def _graph_and_globals(): values = _fixture() - graph = build_dgl_graph(torch.from_numpy(values["nodes"])) + nodes = torch.from_numpy(values["nodes"]) + graph = build_tensor_graph(nodes, torch.tensor([nodes.shape[0]])) globals_ = torch.from_numpy(values["globals"]) return graph, globals_, values diff --git a/tests/unit/data/test_batching.py b/tests/unit/data/test_batching.py index cd47c8ab04a60b17fb8849975a211f957f85688f..6c9f6de65a469b28cea7f90d7381b1e2e49aea7e 100644 --- a/tests/unit/data/test_batching.py +++ b/tests/unit/data/test_batching.py @@ -1,33 +1,51 @@ import pytest import torch -from gnn4colliders.data import EventMetadata, GraphSample, batch_graph_samples -from gnn4colliders.graphs import build_dgl_graph +from gnn4colliders.data import pack_events +from gnn4colliders.graphs import collate_graph_batch -dgl = pytest.importorskip("dgl") - -def _sample(index: int, node_count: int) -> GraphSample: - nodes = torch.arange(node_count * 3, dtype=torch.float32).reshape(node_count, 3) - return GraphSample( - graph=build_dgl_graph(nodes), - label=torch.tensor(index), - global_features=torch.tensor([float(index), -float(index)]), - metadata=EventMetadata(index, index + 0.5, f"sample_{index}"), +def _events(counts): + objects = [ + torch.arange(count * 3, dtype=torch.float32).reshape(count, 3) + for count in counts + ] + return pack_events( + objects, + torch.arange(len(counts)), + weights=[index + 0.5 for index in range(len(counts))], + folds=list(range(len(counts))), + global_features=torch.tensor( + [[float(index), -float(index)] for index in range(len(counts))] + ), + source="sample", ) @pytest.mark.parametrize("counts", [(1,), (1, 2), (1, 3, 2)]) def test_graph_batch_preserves_heterogeneous_order_and_metadata(counts): - samples = [_sample(index, count) for index, count in enumerate(counts)] - batch = batch_graph_samples(samples) + events = _events(counts) + batch = collate_graph_batch(events, torch.arange(len(counts))) assert batch.labels.tolist() == list(range(len(counts))) - assert batch.metadata.sample_id == tuple(f"sample_{i}" for i in range(len(counts))) + assert batch.metadata.sample_id == tuple( + f"sample:events:{i}" for i in range(len(counts)) + ) assert batch.metadata.weight.tolist() == pytest.approx( [i + 0.5 for i in range(len(counts))] ) assert batch.global_features[:, 0].tolist() == list(map(float, range(len(counts)))) - assert batch.graph.batch_num_nodes().tolist() == list(counts) - assert batch.graph.batch_num_edges().tolist() == [ + assert batch.graph.node_counts.tolist() == list(counts) + assert batch.graph.edge_counts.tolist() == [ count * (count - 1) if count > 1 else 1 for count in counts ] + + +def test_graph_batch_follows_requested_event_order(): + events = _events((2, 1, 3)) + batch = collate_graph_batch(events, torch.tensor([2, 0])) + assert batch.labels.tolist() == [2, 0] + assert batch.graph.node_counts.tolist() == [3, 2] + assert torch.equal( + batch.graph.node_features, + torch.cat((events.object_features[3:6], events.object_features[0:2])), + ) diff --git a/tests/unit/data/test_orchestration.py b/tests/unit/data/test_orchestration.py index eff193f4f59610050614816a618558fc96ad4d76..139443c63eb1ea5914a2478cdceefd4540df6d8a 100644 --- a/tests/unit/data/test_orchestration.py +++ b/tests/unit/data/test_orchestration.py @@ -1,35 +1,42 @@ from pathlib import Path -import numpy as np import pytest +import torch from gnn4colliders.data import ( - FEATURE_SCHEMA_VERSION, BatchMetadata, + EventCache, + EventLoader, EventMetadata, SplitDefinition, + concatenate_events, + pack_events, select_folds, ) -from gnn4colliders.data.cache import CacheMetadata, GraphSampleCache -from gnn4colliders.data.graph_dataset import GraphDataLoader, GraphDataset, GraphSample - - -def _sample(sample_id: str, fold: int) -> GraphSample: - return GraphSample( - graph=object(), - label=np.asarray(fold), - global_features=None, - metadata=EventMetadata( - fold=fold, - weight=-0.5 if fold else 1.0, - sample_id=sample_id, - extra={"source_file": "events.root"}, - ), +from gnn4colliders.data.metadata import CACHE_SCHEMA_VERSION + + +def _events(count: int = 5, *, source: str = "events.root"): + return pack_events( + [torch.full((index % 3 + 1, 2), float(index)) for index in range(count)], + torch.arange(count), + folds=[index % 2 for index in range(count)], + weights=[-0.5 if index % 2 else 1.0 for index in range(count)], + source=source, + tree_name="Events", ) +def _ids(events): + return lambda packed, indices: packed.sample_ids(indices) + + def test_select_folds_is_named_deterministic_and_non_mutating(): - samples = [_sample("a", 1), _sample("b", 0), _sample("c", 1)] + class Sample: + def __init__(self, sample_id, fold): + self.metadata = EventMetadata(fold, 1.0, sample_id) + + samples = [Sample("a", 1), Sample("b", 0), Sample("c", 1)] selected = select_folds(samples, {1}) assert [sample.metadata.sample_id for sample in selected] == ["a", "c"] assert [sample.metadata.sample_id for sample in samples] == ["a", "b", "c"] @@ -47,28 +54,41 @@ def test_batch_metadata_preserves_order_and_extra_fields(): assert batch.extra == {"run": (10, 2), "tag": (None, "b")} -def test_graph_loader_shuffle_is_seeded_by_epoch_without_global_rng_mutation(): - pytest.importorskip("dgl") - import torch - - from gnn4colliders.graphs import build_dgl_graph - - samples = [ - GraphSample( - build_dgl_graph(torch.ones(1, 3)), - torch.tensor(i), - None, - EventMetadata(0, 1.0, str(i)), - ) - for i in range(5) - ] - loader = GraphDataLoader(GraphDataset(samples), 2, shuffle=True, seed=11) - first = [item for batch in loader for item in batch.metadata.sample_id] - second = [item for batch in loader for item in batch.metadata.sample_id] +def test_packed_batch_metadata_is_named_and_ordered(): + metadata = _events().batch_metadata(torch.tensor([3, 0])) + assert metadata.sample_id == ("events.root:Events:3", "events.root:Events:0") + assert metadata.fold.tolist() == [1, 0] + assert metadata.weight.tolist() == [-0.5, 1.0] + assert metadata.extra == { + "entry_index": (3, 0), + "source_file": ("events.root", "events.root"), + "tree_name": ("Events", "Events"), + } + + +def test_loader_shuffle_is_seeded_by_epoch_without_global_rng_mutation(): + events = _events() + loader = EventLoader(events, _ids(events), 2, shuffle=True, seed=11) + state = torch.random.get_rng_state() + first = [item for batch in loader for item in batch] + second = [item for batch in loader for item in batch] loader.set_epoch(1) - third = [item for batch in loader for item in batch.metadata.sample_id] + third = [item for batch in loader for item in batch] + assert torch.equal(state, torch.random.get_rng_state()) assert first == second assert third != first + assert sorted(first) == sorted(third) + assert len(loader) == 3 + + +def test_split_indices_preserve_stored_order(): + events = _events() + split = SplitDefinition(train_folds=frozenset({0}), test_folds=frozenset({1})) + assert events.split_indices(split, "train").tolist() == [0, 2, 4] + assert events.split_indices(split, "test").tolist() == [1, 3] + assert events.split_indices(split, "validation").tolist() == [] + with pytest.raises(ValueError, match="unknown split"): + events.split_indices(split, "holdout") def test_split_definition_rejects_overlapping_folds(): @@ -76,59 +96,101 @@ def test_split_definition_rejects_overlapping_folds(): SplitDefinition(train_folds=frozenset({0}), test_folds=frozenset({0})) -def test_graph_cache_round_trip_and_schema_check(tmp_path: Path): - path = tmp_path / "graphs.pt" - cache = GraphSampleCache(path) - samples = (_sample("event.root:Events:3", 2),) - cache.save(samples) - loaded = cache.load() - assert loaded[0].metadata.sample_id == samples[0].metadata.sample_id - assert loaded[0].metadata.weight == -0.5 - - stale = GraphSampleCache( - path, CacheMetadata(feature_schema_version=FEATURE_SCHEMA_VERSION + 1) +def test_gather_objects_returns_rows_in_requested_order(): + events = _events() + rows, counts = events.gather_objects(torch.tensor([4, 1])) + assert counts.tolist() == [2, 2] + assert rows[:, 0].tolist() == [4.0, 4.0, 1.0, 1.0] + + +@pytest.mark.parametrize("mmap", [False, True]) +def test_event_cache_round_trip(tmp_path: Path, mmap): + path = tmp_path / "events.pt" + events = _events() + EventCache(path).save(events) + loaded = EventCache(path).load(mmap=mmap) + assert torch.equal(loaded.object_features, events.object_features) + assert torch.equal(loaded.object_offsets, events.object_offsets) + assert loaded.sample_ids(torch.arange(5)) == events.sample_ids(torch.arange(5)) + assert loaded.feature_names == events.feature_names + + +def test_concatenate_events_remaps_source_files(): + left, right = _events(2, source="a.root"), _events(3, source="b.root") + combined = concatenate_events([left, right]) + assert combined.source_files == ("a.root", "b.root") + assert combined.sample_ids(torch.arange(5)) == ( + "a.root:Events:0", + "a.root:Events:1", + "b.root:Events:0", + "b.root:Events:1", + "b.root:Events:2", ) - with pytest.raises(ValueError, match="schema mismatch"): - stale.load() - - -@pytest.mark.parametrize( - "payload, message", - [ - ({"samples": ()}, "schema mismatch"), - ({"cache_metadata": {}, "samples": ()}, "schema mismatch"), - ( - { - "cache_metadata": { - "feature_schema_version": 1, - "graph_schema_version": 1, - "cache_schema_version": 1, - } - }, - "samples", - ), - ], -) -def test_cache_rejects_missing_or_incomplete_metadata(tmp_path, payload, message): - path = tmp_path / "broken.pt" - import torch + assert combined.object_offsets.tolist() == [0, 1, 3, 4, 6, 9] + +def test_cache_rejects_schema_mismatch(tmp_path): + path = tmp_path / "events.pt" + EventCache(path).save(_events()) + payload = torch.load(path, weights_only=True) + payload["cache_schema_version"] = CACHE_SCHEMA_VERSION + 1 torch.save(payload, path) - with pytest.raises(ValueError, match=message): - GraphSampleCache(path).load() + with pytest.raises(ValueError, match="schema mismatch"): + EventCache(path).load() -def test_cache_rejects_preprocessing_fingerprint_mismatch(tmp_path): - path = tmp_path / "graphs.pt" - GraphSampleCache(path, CacheMetadata(preprocessing={"features": "a"})).save( - [_sample("event:0", 0)] - ) - with pytest.raises(ValueError, match="fingerprint"): - GraphSampleCache(path, CacheMetadata(preprocessing={"features": "b"})).load() +def test_cache_rejects_missing_fields(tmp_path): + path = tmp_path / "events.pt" + EventCache(path).save(_events()) + payload = torch.load(path, weights_only=True) + del payload["object_offsets"] + torch.save(payload, path) + with pytest.raises(ValueError, match="missing fields"): + EventCache(path).load() -def test_cache_rejects_truncated_artifact(tmp_path): +def test_cache_rejects_truncated_or_legacy_artifacts(tmp_path): path = tmp_path / "truncated.pt" path.write_bytes(b"not a torch archive") - with pytest.raises(Exception): - GraphSampleCache(path).load() + with pytest.raises(ValueError, match="prepared again"): + EventCache(path).load() + legacy = tmp_path / "graphs.pt" + torch.save({"cache_metadata": {}, "samples": (object(),)}, legacy) + with pytest.raises(ValueError, match="prepared again"): + EventCache(legacy).load() + + +def test_distributed_loader_shards_selected_events_across_ranks(): + from types import SimpleNamespace + + from gnn4colliders.data import DistributedEventLoader + + events = _events(11) + selected = torch.tensor([0, 2, 3, 5, 6, 7, 9, 10]) + ranks = [ + SimpleNamespace(enabled=True, rank=rank, world_size=3) for rank in range(3) + ] + + def ids(shuffle): + loaders = [ + DistributedEventLoader( + events, + lambda packed, indices: indices.tolist(), + 2, + context, + indices=selected, + shuffle=shuffle, + seed=4, + ) + for context in ranks + ] + for loader in loaders: + loader.set_epoch(1) + return [[item for batch in loader for item in batch] for loader in loaders] + + train = ids(shuffle=True) + assert len({len(part) for part in train}) == 1 # padded to equal length + assert set().union(*map(set, train)) == set(selected.tolist()) + evaluation = ids(shuffle=False) + flat = [item for part in evaluation for item in part] + assert sorted(flat) == selected.tolist() # disjoint and complete, no padding diff --git a/tests/unit/graphs/test_preparation.py b/tests/unit/data/test_shard_ranges.py similarity index 90% rename from tests/unit/graphs/test_preparation.py rename to tests/unit/data/test_shard_ranges.py index aeb7bb2a5c2848b48eb1ed1e32a1ada572f7d49e..5495ea125ed86901484a1e986ac2881ab8c13cab 100644 --- a/tests/unit/graphs/test_preparation.py +++ b/tests/unit/data/test_shard_ranges.py @@ -1,6 +1,6 @@ import pytest -from gnn4colliders.graphs.preparation import shard_range +from gnn4colliders.data.preparation import shard_range def test_shard_ranges_are_contiguous_and_cover_every_event(): diff --git a/tests/unit/export/test_onnx_export.py b/tests/unit/export/test_onnx_export.py index 7ca99483060d9c9a9d0136f132fb79fbfd1c6e6b..869fca87b4f1d1383db264fb705b6a9b574d0284 100644 --- a/tests/unit/export/test_onnx_export.py +++ b/tests/unit/export/test_onnx_export.py @@ -1,41 +1,37 @@ import pytest import torch -from gnn4colliders.data import EventMetadata, GraphSample, batch_graph_samples +from gnn4colliders.data import pack_events from gnn4colliders.export import ( RootGNNExportAdapter, export_root_gnn_onnx, inputs_from_graph_batch, ) -from gnn4colliders.graphs import build_dgl_graph +from gnn4colliders.graphs import collate_graph_batch from gnn4colliders.models.root_gnn import EdgeNetwork, FineTunedEdgeNetwork pytestmark = pytest.mark.onnx -dgl = pytest.importorskip("dgl") def _batch(): - samples = [] - for index, count in enumerate((2, 3)): - nodes = torch.arange(count * 3, dtype=torch.float32).reshape(count, 3) - samples.append( - GraphSample( - build_dgl_graph(nodes), - torch.tensor(index), - torch.tensor([1.0, 2.0]), - EventMetadata(index, 1.0, f"fixture:{index}"), - ) - ) - return batch_graph_samples(samples) + events = pack_events( + [ + torch.arange(count * 3, dtype=torch.float32).reshape(count, 3) + for count in (2, 3) + ], + torch.tensor([0, 1]), + global_features=torch.tensor([[1.0, 2.0], [1.0, 2.0]]), + source="fixture", + ) + return collate_graph_batch(events, torch.arange(2)) def test_export_inputs_preserve_graph_membership_and_edges(): batch = _batch() inputs = inputs_from_graph_batch(batch) - src, _ = batch.graph.edges(order="eid") - assert torch.equal(inputs.node_features, batch.graph.ndata["features"]) - assert torch.equal(inputs.edge_features, batch.graph.edata["features"]) - assert torch.equal(inputs.edge_src, src) + assert torch.equal(inputs.node_features, batch.graph.node_features) + assert torch.equal(inputs.edge_features, batch.graph.edge_features) + assert torch.equal(inputs.edge_src, batch.graph.edge_src) assert inputs.node_batch.tolist() == [0, 0, 1, 1, 1] assert inputs.global_features.shape == (2, 2) diff --git a/tests/unit/graphs/test_dgl_graph.py b/tests/unit/graphs/test_dgl_graph.py deleted file mode 100644 index 4325c1c96086cf4446a66d635d478ab4289dca5d..0000000000000000000000000000000000000000 --- a/tests/unit/graphs/test_dgl_graph.py +++ /dev/null @@ -1,19 +0,0 @@ -import pytest -import torch - -from gnn4colliders.graphs import build_dgl_graph - -pytest.importorskip("dgl") - - -def test_build_dgl_graph_attaches_compatible_features(): - node_features = torch.tensor( - [[10.0, 1.0, 3.1], [20.0, -0.5, -3.1]], dtype=torch.float32 - ) - graph = build_dgl_graph(node_features, eta_index=1, phi_index=2) - - assert graph.number_of_nodes() == 2 - assert graph.number_of_edges() == 2 - assert graph.ndata["features"] is node_features - assert graph.edata["features"].shape == (2, 3) - assert graph.edata["features"].dtype == torch.float32 diff --git a/tests/unit/graphs/test_tensor_graph.py b/tests/unit/graphs/test_tensor_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..be99c8328dc5e9e153bd8231b1b7b1cc42b921a4 --- /dev/null +++ b/tests/unit/graphs/test_tensor_graph.py @@ -0,0 +1,47 @@ +import pytest +import torch + +from gnn4colliders.graphs import ( + build_edge_features, + build_tensor_graph, + fully_connected_batch_edges, + fully_connected_edges, +) + + +@pytest.mark.parametrize("counts", [[1], [2, 3], [0, 1, 4, 0, 2], [5, 1, 1]]) +def test_batched_topology_matches_per_graph_topology(counts): + src, dst, edge_counts = fully_connected_batch_edges(torch.tensor(counts)) + expected_src, expected_dst, offset = [], [], 0 + for count in counts: + if count: + local_src, local_dst = fully_connected_edges(count) + expected_src.append(local_src + offset) + expected_dst.append(local_dst + offset) + offset += count + empty = torch.empty(0, dtype=torch.long) + assert torch.equal(src, torch.cat(expected_src) if expected_src else empty) + assert torch.equal(dst, torch.cat(expected_dst) if expected_dst else empty) + assert edge_counts.tolist() == [ + count * (count - 1) if count > 1 else count for count in counts + ] + + +def test_tensor_graph_carries_edge_features_and_membership(): + nodes = torch.tensor( + [[10.0, 1.0, 3.1], [20.0, -0.5, -3.1], [5.0, 0.0, 0.0]], dtype=torch.float32 + ) + graph = build_tensor_graph(nodes, torch.tensor([2, 1]), eta_index=1, phi_index=2) + assert graph.node_features is nodes + assert graph.edge_features.shape == (3, 3) + assert graph.edge_features.dtype == torch.float32 + assert torch.equal( + graph.edge_features, + build_edge_features( + nodes, graph.edge_src, graph.edge_dst, eta_index=1, phi_index=2 + ), + ) + assert graph.node_batch.tolist() == [0, 0, 1] + assert graph.edge_batch.tolist() == [0, 0, 1] + assert graph.edge_index.tolist() == [[0, 1, 2], [1, 0, 2]] + assert graph.num_graphs == 2 diff --git a/tests/unit/models/root_gnn/test_devices.py b/tests/unit/models/root_gnn/test_devices.py new file mode 100644 index 0000000000000000000000000000000000000000..2030dfd9c338d3752bc70473b068f7b1da89b82f --- /dev/null +++ b/tests/unit/models/root_gnn/test_devices.py @@ -0,0 +1,53 @@ +import pytest +import torch + +from gnn4colliders.data import pack_events +from gnn4colliders.graphs import collate_graph_batch +from gnn4colliders.models.root_gnn import EdgeNetwork + + +def _batch(): + events = pack_events( + [ + torch.tensor([[10.0, 0.2, 0.1], [8.0, -0.3, -0.2]]), + torch.tensor([[4.0, 0.1, 2.8]]), + ], + torch.tensor([0, 1]), + global_features=torch.tensor([[1.0, 2.0], [1.0, 2.0]]), + ) + return collate_graph_batch(events, torch.arange(2)) + + +@pytest.mark.parametrize( + "device", + [ + pytest.param( + "mps", + marks=pytest.mark.skipif( + not torch.backends.mps.is_available(), reason="MPS unavailable" + ), + ), + pytest.param( + "cuda", + marks=[ + pytest.mark.gpu, + pytest.mark.skipif( + not torch.cuda.is_available(), reason="CUDA unavailable" + ), + ], + ), + ], +) +def test_edge_network_runs_forward_and_backward_on_accelerator(device): + batch = _batch() + torch.manual_seed(3) + model = EdgeNetwork(batch.graph, batch.global_features, 8, 3, 2, 1).eval() + with torch.no_grad(): + expected = model(batch.graph, batch.global_features) + model = model.to(device) + moved = batch.to(device) + logits = model(moved.graph, moved.global_features) + logits.square().mean().backward() + assert logits.device.type == device + assert all(parameter.grad is not None for parameter in model.parameters()) + torch.testing.assert_close(logits.detach().cpu(), expected, rtol=1e-4, atol=1e-5) diff --git a/tests/unit/models/root_gnn/test_edge_cases.py b/tests/unit/models/root_gnn/test_edge_cases.py index 6ff3c4a195a60c8130a02e3da40779de5942e202..45d36f490602b372ebc168aae2f196b1b1bd680a 100644 --- a/tests/unit/models/root_gnn/test_edge_cases.py +++ b/tests/unit/models/root_gnn/test_edge_cases.py @@ -1,15 +1,17 @@ import pytest import torch -from gnn4colliders.graphs import build_dgl_graph +from gnn4colliders.graphs import build_tensor_graph from gnn4colliders.models.root_gnn import EdgeNetwork, FineTunedEdgeNetwork -pytest.importorskip("dgl") + +def _tensor_graph(*events, dtype=torch.float32): + nodes = torch.cat([torch.tensor(event, dtype=dtype) for event in events]) + return build_tensor_graph(nodes, torch.tensor([len(event) for event in events])) def _graph(node_features): - graph = build_dgl_graph(torch.tensor(node_features, dtype=torch.float32)) - return graph, torch.tensor([[1.0]], dtype=torch.float32) + return _tensor_graph(node_features), torch.tensor([[1.0]], dtype=torch.float32) def test_no_globals_uses_graph_node_count_as_legacy_fallback(): @@ -26,18 +28,15 @@ def test_missing_or_mismatched_global_shapes_fail_clearly(): model = EdgeNetwork(graph, globals_, 4, 1, 1, 0) with pytest.raises(ValueError, match="global_features are required"): model(graph) - batched_graph = build_dgl_graph( - torch.tensor([[10.0, 0.2, 0.1], [8.0, -0.3, -0.2]], dtype=torch.float32) + batched_graph = _tensor_graph( + [[10.0, 0.2, 0.1]], [[10.0, 0.2, 0.1], [8.0, -0.3, -0.2]] ) - batched_graph = __import__("dgl").batch([graph, batched_graph]) with pytest.raises(ValueError, match="one-dimensional"): model(batched_graph, torch.tensor([1.0])) def test_model_preserves_float64_dtype(): - graph = build_dgl_graph( - torch.tensor([[10.0, 0.2, 0.1], [8.0, -0.3, -0.2]], dtype=torch.float64) - ) + graph = _tensor_graph([[10.0, 0.2, 0.1], [8.0, -0.3, -0.2]], dtype=torch.float64) globals_ = torch.tensor([[1.0]], dtype=torch.float64) model = EdgeNetwork(graph, globals_, 4, 1, 1, 1).double().eval() assert model(graph, globals_).dtype == torch.float64 @@ -52,19 +51,10 @@ def test_negative_processing_steps_are_rejected(): def test_single_node_graph_and_zero_processing_step_are_supported(): graph, globals_ = _graph([[10.0, 0.2, 0.1]]) model = EdgeNetwork(graph, globals_, 4, 1, 1, 0).eval() - assert graph.number_of_edges() == 1 + assert graph.edge_features.shape[0] == 1 assert model(graph, globals_).shape == (1, 1) -def test_weighted_padded_nodes_produce_finite_logits(): - graph, globals_ = _graph([[10.0, 0.2, 0.1], [8.0, -0.3, -0.2], [0.0, 0.0, 0.0]]) - graph.ndata["w"] = torch.tensor([[1.0], [1.0], [0.0]]) - model = EdgeNetwork(graph, globals_, 4, 1, 1, 1).eval() - logits = model(graph, globals_) - assert logits.shape == (1, 1) - assert torch.isfinite(logits).all() - - def test_unfrozen_transfer_backbone_receives_gradients(): graph, globals_ = _graph([[10.0, 0.2, 0.1], [8.0, -0.3, -0.2]]) source = EdgeNetwork(graph, globals_, 4, 3, 1, 1) diff --git a/tests/unit/models/root_gnn/test_edge_network.py b/tests/unit/models/root_gnn/test_edge_network.py index 154a42d243556932b37b48482d46018d633e2c7c..9c3ca57664c4b5ee6195e883d790999a3df807ff 100644 --- a/tests/unit/models/root_gnn/test_edge_network.py +++ b/tests/unit/models/root_gnn/test_edge_network.py @@ -1,21 +1,24 @@ import pytest import torch -from gnn4colliders.graphs import build_dgl_graph +from gnn4colliders.graphs import build_tensor_graph from gnn4colliders.models.root_gnn import EdgeNetwork, FineTunedEdgeNetwork -dgl = pytest.importorskip("dgl") + +def _graph(): + nodes = torch.tensor([[10.0, 0.2, 0.1], [8.0, -0.3, -0.2]]) + return build_tensor_graph(nodes, torch.tensor([2])) def _model(out_size=1): - graph = build_dgl_graph(torch.tensor([[10.0, 0.2, 0.1], [8.0, -0.3, -0.2]])) + graph = _graph() return EdgeNetwork(graph, torch.zeros(1, 2), 8, out_size, 2, 2), graph def test_edge_network_returns_raw_binary_logits_without_graph_leakage(): model, graph = _model() globals_ = torch.tensor([[1.0, 2.0]]) - before = set(graph.ndata.keys()) | set(graph.edata.keys()) + before = [value.clone() for value in vars(graph).values()] logits = model(graph, globals_) again = model(graph, globals_) assert logits.shape == (1, 1) @@ -25,7 +28,7 @@ def test_edge_network_returns_raw_binary_logits_without_graph_leakage(): model.representation(graph, globals_), model.forward_features(graph, globals_) ) assert model.classify is model.classifier - assert before == (set(graph.ndata.keys()) | set(graph.edata.keys())) + assert all(torch.equal(old, new) for old, new in zip(before, vars(graph).values())) def test_edge_network_supports_multiclass_and_transfer_freezing(): @@ -44,7 +47,7 @@ def test_edge_network_supports_multiclass_and_transfer_freezing(): @pytest.mark.parametrize("out_size", [1, 3]) @pytest.mark.parametrize("n_proc_steps", [0, 1]) def test_model_shape_matrix_and_state_dict_round_trip(out_size, n_proc_steps): - graph = build_dgl_graph(torch.tensor([[10.0, 0.2, 0.1], [8.0, -0.3, -0.2]])) + graph = _graph() globals_ = torch.tensor([[1.0, 2.0]]) torch.manual_seed(7) model = EdgeNetwork(graph, globals_, 4, out_size, 1, n_proc_steps).eval() diff --git a/tests/unit/models/root_gnn/test_tensor_edge_network.py b/tests/unit/models/root_gnn/test_tensor_edge_network.py deleted file mode 100644 index 185e956e372c6b222c491ee086b1ceb790f51fb6..0000000000000000000000000000000000000000 --- a/tests/unit/models/root_gnn/test_tensor_edge_network.py +++ /dev/null @@ -1,67 +0,0 @@ -from __future__ import annotations - -import pytest -import torch - -from gnn4colliders.data import EventMetadata, GraphDataset, GraphSample -from gnn4colliders.data.graph_dataset import GraphDataLoader -from gnn4colliders.graphs import build_dgl_graph -from gnn4colliders.models.root_gnn import EdgeNetwork, TensorEdgeNetwork - -pytest.importorskip("dgl") - - -def _batch(): - samples = [ - GraphSample( - build_dgl_graph(nodes), - torch.tensor(index), - torch.tensor([1.0, 2.0]), - EventMetadata(0, 1.0, str(index)), - ) - for index, nodes in enumerate( - ( - torch.tensor([[10.0, 0.2, 0.1], [8.0, -0.3, -0.2]]), - torch.tensor([[4.0, 0.1, 2.8]]), - ) - ) - ] - dgl_batch = next(iter(GraphDataLoader(GraphDataset(samples), 2))) - tensor_batch = next( - iter(GraphDataLoader(GraphDataset(samples), 2, tensor_graphs=True)) - ) - return dgl_batch, tensor_batch - - -def test_tensor_backend_matches_dgl_for_fixed_weights(): - dgl_batch, tensor_batch = _batch() - dgl_model = EdgeNetwork( - dgl_batch.graph, dgl_batch.global_features, 8, 3, 2, 2 - ).eval() - tensor_model = TensorEdgeNetwork( - tensor_batch.graph, tensor_batch.global_features, 8, 3, 2, 2 - ).eval() - tensor_model.load_state_dict(dgl_model.state_dict()) - with torch.no_grad(): - expected = dgl_model(dgl_batch.graph, dgl_batch.global_features) - actual = tensor_model(tensor_batch.graph, tensor_batch.global_features) - torch.testing.assert_close(actual, expected, rtol=0, atol=0) - dgl_model(dgl_batch.graph, dgl_batch.global_features).sum().backward() - tensor_model(tensor_batch.graph, tensor_batch.global_features).sum().backward() - for expected_parameter, actual_parameter in zip( - dgl_model.parameters(), tensor_model.parameters(), strict=True - ): - torch.testing.assert_close( - actual_parameter.grad, expected_parameter.grad, rtol=0, atol=0 - ) - - -@pytest.mark.skipif(not torch.backends.mps.is_available(), reason="MPS unavailable") -def test_tensor_backend_runs_forward_and_backward_on_mps(): - _, batch = _batch() - model = TensorEdgeNetwork(batch.graph, batch.global_features, 8, 3, 2, 1).to("mps") - moved = batch.to("mps") - logits = model(moved.graph, moved.global_features) - logits.square().mean().backward() - assert logits.device.type == "mps" - assert all(parameter.grad is not None for parameter in model.parameters()) diff --git a/tests/unit/sequences/test_sequence_sample.py b/tests/unit/sequences/test_sequence_sample.py index 300cc912b70c780baf2fb0bb23aa585551181f47..c8f88b3ab4926a7bc273ec6e8857e41d7c68e0e4 100644 --- a/tests/unit/sequences/test_sequence_sample.py +++ b/tests/unit/sequences/test_sequence_sample.py @@ -59,3 +59,32 @@ def test_sequence_batch_pads_and_masks_in_source_order(): loader = SequenceDataLoader(samples, batch_size=1, shuffle=True, seed=9) loader.set_epoch(2) assert len(list(loader)) == 2 + + +def test_packed_sequence_collation_matches_per_sample_batching(): + from gnn4colliders.data import EventMetadata, pack_events + from gnn4colliders.sequences import ( + SequenceSample, + batch_sequence_samples, + collate_sequence_batch, + ) + + objects = [torch.randn(count, 7) for count in (3, 1, 4)] + events = pack_events(objects, torch.tensor([1, 0, 1]), source="fixture") + order = torch.tensor([2, 0, 1]) + packed = collate_sequence_batch(events, order) + expected = batch_sequence_samples( + [ + SequenceSample( + tokens=objects[index], + label=torch.tensor([1, 0, 1][index]), + global_features=None, + metadata=EventMetadata(0, 1.0, f"fixture:events:{index}"), + ) + for index in order.tolist() + ] + ) + assert torch.equal(packed.tokens, expected.tokens) + assert torch.equal(packed.token_mask, expected.token_mask) + assert torch.equal(packed.labels, expected.labels) + assert packed.metadata.sample_id == expected.metadata.sample_id diff --git a/tests/unit/training/test_trainer.py b/tests/unit/training/test_trainer.py index f08d9b553c700cbc36d86b4622fcdc1f888503b0..f3d3f8290665a680a6fb5f2b6256a686b25b0454 100644 --- a/tests/unit/training/test_trainer.py +++ b/tests/unit/training/test_trainer.py @@ -2,7 +2,8 @@ import pytest import torch from torch import nn -from gnn4colliders.data import BatchMetadata, EventMetadata, GraphBatch +from gnn4colliders.data import BatchMetadata, EventMetadata +from gnn4colliders.graphs import GraphBatch from gnn4colliders.tasks import BinaryClassificationTask from gnn4colliders.training import ( EarlyStopping, diff --git a/uv.lock b/uv.lock index 80cbb00fe1b82535adf96bc427e2a7017a85de4b..b432c57dbb630232472b21a1f6be01c9f3209f2d 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 2 +revision = 3 requires-python = "==3.12.*" resolution-markers = [ "platform_machine == 'x86_64' and sys_platform == 'linux'", @@ -8,15 +8,6 @@ resolution-markers = [ "(platform_machine != 'x86_64' and sys_platform == 'linux') or (sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32')", ] -[[package]] -name = "annotated-types" -version = "0.8.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/5f/56/a8120250d128bed162cd73c76d45f6ef9991f3e068f62a8ee060afa3104a/annotated_types-0.8.0.tar.gz", hash = "sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7", size = 15893, upload-time = "2026-07-23T20:16:13.995Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/99/91/8acff4f5e50511b911bbccb72b8628a49c68ce14148cd9f6431094859a90/annotated_types-0.8.0-py3-none-any.whl", hash = "sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0", size = 13427, upload-time = "2026-07-23T20:16:12.938Z" }, -] - [[package]] name = "antlr4-python3-runtime" version = "4.9.3" @@ -78,8 +69,6 @@ sdist = { url = "https://files.pythonhosted.org/packages/9e/ef/008a1939e372c0632 wheels = [ { url = "https://files.pythonhosted.org/packages/56/e6/8941622732edec876dd17d0453dce07317ae96db34f2ec1436c9d3785986/cffi-2.1.1-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a", size = 214799, upload-time = "2026-08-03T21:19:47.218Z" }, { url = "https://files.pythonhosted.org/packages/44/de/f98430906df1545ffde0d543dd124a7a439bc2cd32b36b9c53f805df7333/cffi-2.1.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890", size = 222389, upload-time = "2026-08-03T21:19:48.331Z" }, - { url = "https://files.pythonhosted.org/packages/6a/5b/717f1526b9957b34456313c31645c5b82b8fb5c3fe9e4752999be7128bfc/cffi-2.1.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50", size = 210249, upload-time = "2026-08-03T21:19:49.543Z" }, - { url = "https://files.pythonhosted.org/packages/64/b3/f8aa4f3e34986c7e4ec45072d1b1b9dd295b6b18007b45518d79726dd725/cffi-2.1.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e", size = 208775, upload-time = "2026-08-03T21:19:50.918Z" }, { url = "https://files.pythonhosted.org/packages/b1/db/dceb9dd5b231e1da801793f8acc9f3c52a7e1afe40bb1aae37e02b0faad5/cffi-2.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf", size = 221822, upload-time = "2026-08-03T21:19:52.054Z" }, { url = "https://files.pythonhosted.org/packages/a0/d2/6cd24ae3be000a634109c247d1475d62e5616d0dc78c82770942ec384248/cffi-2.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517", size = 225232, upload-time = "2026-08-03T21:19:53.109Z" }, { url = "https://files.pythonhosted.org/packages/cb/52/3fa190537004dd7f0ab860a6dc7c0175b8667f68d1e618a46f5498d30250/cffi-2.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735", size = 223597, upload-time = "2026-08-03T21:19:54.515Z" }, @@ -216,22 +205,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/57/ef/8f2df13c7216bcad3e1c74e07f6e193d93e998e114f524a53877c9af27ad/cryptography-50.0.0-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:fd9192b7b70c573d7f214eb1ae35e00d359f6f5e4b27c7e21e30de1fc6204645", size = 4719554, upload-time = "2026-07-31T14:23:35.611Z" }, { url = "https://files.pythonhosted.org/packages/d9/41/029086c34d91052fc3b88bcc8056f709a7c915c7a23b235a54eb800b1c97/cryptography-50.0.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:06a32a980526a6ab9a4b9bf8f7385800791e2bb960903cb6b530e4817509a3b7", size = 4702130, upload-time = "2026-07-31T14:23:37.635Z" }, { url = "https://files.pythonhosted.org/packages/7d/ff/b6ce0954962e7f7b969f850a883744197bb3910bdfd7b6da162eab7d9f68/cryptography-50.0.0-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:a1b30560f2acc95aa8b2e06e716a13dbfc97314747b80d9707e307f77b40d6b3", size = 4725244, upload-time = "2026-07-31T14:23:39.471Z" }, - { url = "https://files.pythonhosted.org/packages/06/1e/63a1027cb7fec360a182208e1b7767d5aa1fe57be3d6aa856e69a321edc0/cryptography-50.0.0-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:8d89f3976b10b4ce31118de72329025f70d2c6ead14a8217c5514dd2c6d5a78f", size = 5342265, upload-time = "2026-07-31T14:23:41.286Z" }, { url = "https://files.pythonhosted.org/packages/6b/72/a1116d683a6d7ece94590013882515de087edf9ef0e6292aae615a44df73/cryptography-50.0.0-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:b42a28c1844fd9de8f3f7d540e36b66f3a9c83fceac7170ebc7a6a19edd9dcae", size = 4734609, upload-time = "2026-07-31T14:23:43.139Z" }, { url = "https://files.pythonhosted.org/packages/15/37/36a9c479bbe49acea2636c7fd3360d20f7b7e079c300352011c44850b181/cryptography-50.0.0-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:900131fafd8aead39ac7dd3a7e833be754c17a95cfd91221636949fe4eb0aa8a", size = 4356517, upload-time = "2026-07-31T14:23:44.939Z" }, { url = "https://files.pythonhosted.org/packages/32/98/8a151d64367204cbc63ec65d37502f1d9c53cf4bfc6ec3c532614dbec60d/cryptography-50.0.0-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:07949c449a1abcf60d1ee6e88956d89404c7df3c8258f46589e912988e551987", size = 4724529, upload-time = "2026-07-31T14:23:46.93Z" }, - { url = "https://files.pythonhosted.org/packages/22/f6/ec13b470172126464a86bf54d2294a46d29837fc51ba3e45d4047946fb5e/cryptography-50.0.0-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:f89831ef99dd7dd169ab06d63a831adb9e20a87aac6d380266bbda5823349169", size = 5299852, upload-time = "2026-07-31T14:23:48.851Z" }, { url = "https://files.pythonhosted.org/packages/da/3a/f05e32c99d440c9bb891ea0e36c9091891e36be5a9a87ab2ee6ea20729f6/cryptography-50.0.0-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:82148ec5bddac30b51a5b3c1945075f896fa022cb93f8e4a01e9f6ee95292c5f", size = 4734462, upload-time = "2026-07-31T14:23:50.861Z" }, { url = "https://files.pythonhosted.org/packages/ca/dc/bd72b26be8953f80625f63151efd38eee71c76ca6cf591c08ff34615a79e/cryptography-50.0.0-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:1489e263a8048bb8b6a8bac662eb2d402ea5d2b7b4699b72f385f1e2772db105", size = 4852708, upload-time = "2026-07-31T14:23:52.715Z" }, { url = "https://files.pythonhosted.org/packages/27/20/c930314a2ab476d15dec966ec87e2e9637bb02b06106b12c0396c57bb603/cryptography-50.0.0-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:7cec5b856506da6defb290f30c9ee687d5f5e8cb0bd3f6459dde43b0b4fa40ef", size = 5004179, upload-time = "2026-07-31T14:23:54.887Z" }, { url = "https://files.pythonhosted.org/packages/ff/c6/7a6202a534e32103a285b7834a120869557fe198d51d7cfe59754c8bda9c/cryptography-50.0.0-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:910e1d2668e7de9648f2bcee30e180db2a6b15c30f887d7c4c93ddf96e3992e3", size = 4745252, upload-time = "2026-07-31T14:24:26.118Z" }, { url = "https://files.pythonhosted.org/packages/85/4f/0fa8c2f4428198f15d9ff8d63400e27afbf94ce833f6108da1eb3753f945/cryptography-50.0.0-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a91296cb61e8df6f86d0c19cc4068228da256bf59bf86049fbd821084565327f", size = 4728939, upload-time = "2026-07-31T14:24:27.994Z" }, { url = "https://files.pythonhosted.org/packages/d1/63/54dd723490ba2dc09b299682c10b38db38f159728bcaae8c591b8af2f22d/cryptography-50.0.0-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:e722f16708d854fe924790e051061f6704a472c3bac347b6fd88033ea8dd0dc5", size = 4748483, upload-time = "2026-07-31T14:24:30.254Z" }, - { url = "https://files.pythonhosted.org/packages/1d/dd/7c77d26285cc7f6991efce64a0f5b4f9383bfa5dd8c5033003eaf7db4cdb/cryptography-50.0.0-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:d764dcf130c428ef66786f866dd750f53182bc608813489915e9fc106bb0c82f", size = 5367599, upload-time = "2026-07-31T14:24:32.457Z" }, { url = "https://files.pythonhosted.org/packages/46/c9/f60aed34c013f317f92817b6c171c2d22a78270fa41109bd4b08af26b194/cryptography-50.0.0-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:105110f43a471dbd0060b9c9516cb8a6a79233631a04cc2ba16f28323ac6e025", size = 4762647, upload-time = "2026-07-31T14:24:34.599Z" }, { url = "https://files.pythonhosted.org/packages/be/f3/f9a0173b139372c3a48ed98154b45cc6b9de17c789d5ab552e621c293609/cryptography-50.0.0-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:828743d939e9629bc267b8e2d08d8bb67cd4319c771a33d4b18b22dd8fb7440a", size = 4385197, upload-time = "2026-07-31T14:24:36.647Z" }, { url = "https://files.pythonhosted.org/packages/d8/36/83bb81f6e569bc38e1e4a7bc80f29b46bb9601920bc455fc8e888f5d5742/cryptography-50.0.0-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:2a8183b489dc1f7f80f135780fadc1108f14b31b8a40411c7a5b17425f65f28b", size = 4748095, upload-time = "2026-07-31T14:24:39.493Z" }, - { url = "https://files.pythonhosted.org/packages/6b/16/d3008eff98c764979865834c3d386d4fd041b5f52e7f34fc29ac1a5eb515/cryptography-50.0.0-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:6e7d61120573a7f2cd94cc095f9e81f6967c61ccdf194285aa143ecec8e0b708", size = 5325948, upload-time = "2026-07-31T14:24:41.556Z" }, { url = "https://files.pythonhosted.org/packages/9c/f8/d97f9603efda3888187bfdb893f26c41be4735c10631d05d284ee6b047c4/cryptography-50.0.0-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:37fdb0d0111f1e2ff07139dfb79f1b49531f8e213c46f1163dd7642979b58c47", size = 4762400, upload-time = "2026-07-31T14:24:43.636Z" }, { url = "https://files.pythonhosted.org/packages/64/a2/4615c8f7d81a00b1d6e6afe19f694e1543582349fb5f4076f6cb5dc36485/cryptography-50.0.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:c87f62a3d3b9888ed0fdde100ec06aa61ca9cd44bad9057d1dff9a516b5f5bb9", size = 4878208, upload-time = "2026-07-31T14:24:45.522Z" }, { url = "https://files.pythonhosted.org/packages/d2/1a/efcfb02f91407149a0dacffffab791f7e19bf6385f63b3666dc8b5e5c9c8/cryptography-50.0.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:65c2c3add92b45fd0709db8594536aea39c2a67af0e27ffcf049c498501140b7", size = 5037050, upload-time = "2026-07-31T14:24:47.697Z" }, @@ -246,51 +231,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl", hash = "sha256:85cef7cff222d8644161529808465972e51340599459b8ac3ccbac5a854e0d30", size = 8321, upload-time = "2023-10-07T05:32:16.783Z" }, ] -[[package]] -name = "dgl" -version = "2.2.0" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "(platform_machine != 'x86_64' and sys_platform == 'linux') or (sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32')", -] -dependencies = [ - { name = "networkx", marker = "(platform_machine != 'x86_64' and sys_platform == 'linux') or (sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32')" }, - { name = "numpy", marker = "(platform_machine != 'x86_64' and sys_platform == 'linux') or (sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32')" }, - { name = "pandas", marker = "(platform_machine != 'x86_64' and sys_platform == 'linux') or (sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32')" }, - { name = "psutil", marker = "(platform_machine != 'x86_64' and sys_platform == 'linux') or (sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32')" }, - { name = "requests", marker = "(platform_machine != 'x86_64' and sys_platform == 'linux') or (sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32')" }, - { name = "scipy", marker = "(platform_machine != 'x86_64' and sys_platform == 'linux') or (sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32')" }, - { name = "torchdata", marker = "(platform_machine != 'x86_64' and sys_platform == 'linux') or (sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32')" }, - { name = "tqdm", marker = "(platform_machine != 'x86_64' and sys_platform == 'linux') or (sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32')" }, -] -wheels = [ - { url = "https://files.pythonhosted.org/packages/dc/82/a8857a5a86e7a0f8c12913e51c1dfecabe5a658ca43569ce26ddb0e7020d/dgl-2.2.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:b05d98c1dc8c8cd30de5aaffbca4905dd6426ba3bb17c967cc99317d0c2d5685", size = 7382847, upload-time = "2024-05-08T07:16:20.225Z" }, -] - -[[package]] -name = "dgl" -version = "2.4.0+cu121" -source = { registry = "https://data.dgl.ai/wheels/torch-2.2/cu121/repo.html" } -resolution-markers = [ - "platform_machine == 'x86_64' and sys_platform == 'linux'", -] -dependencies = [ - { name = "networkx", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" }, - { name = "numpy", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" }, - { name = "packaging", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" }, - { name = "pandas", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" }, - { name = "psutil", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" }, - { name = "pydantic", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" }, - { name = "pyyaml", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" }, - { name = "requests", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" }, - { name = "scipy", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" }, - { name = "torch", version = "2.2.2+cu121", source = { registry = "https://download.pytorch.org/whl/cu121" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" }, - { name = "tqdm", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" }, -] -wheels = [ - { url = "https://data.dgl.ai/wheels/torch-2.2/cu121/dgl-2.4.0%2Bcu121-cp312-cp312-manylinux1_x86_64.whl" }, -] - [[package]] name = "docutils" version = "0.23" @@ -362,12 +302,6 @@ onnx = [ { name = "onnx" }, { name = "onnxruntime" }, ] -root-gnn = [ - { name = "dgl", version = "2.2.0", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'arm64' and sys_platform == 'darwin'" }, - { name = "dgl", version = "2.4.0+cu121", source = { registry = "https://data.dgl.ai/wheels/torch-2.2/cu121/repo.html" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" }, - { name = "pydantic", marker = "platform_machine == 'arm64' and sys_platform == 'darwin'" }, - { name = "torchdata", marker = "platform_machine == 'arm64' and sys_platform == 'darwin'" }, -] [package.dev-dependencies] dev = [ @@ -383,21 +317,17 @@ dev = [ [package.metadata] requires-dist = [ { name = "awkward", specifier = ">=2.0" }, - { name = "dgl", marker = "platform_machine == 'arm64' and sys_platform == 'darwin' and extra == 'root-gnn'", specifier = "==2.2.0" }, - { name = "dgl", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'root-gnn'", specifier = "==2.4.0+cu121", index = "https://data.dgl.ai/wheels/torch-2.2/cu121/repo.html" }, { name = "huggingface-hub", specifier = ">=0.36,<1" }, { name = "hydra-core", specifier = ">=1.3" }, { name = "numpy", specifier = ">=1.24,<2" }, { name = "onnx", marker = "extra == 'onnx'", specifier = ">=1.16,<2" }, { name = "onnxruntime", marker = "extra == 'onnx'", specifier = ">=1.18,<2" }, - { name = "pydantic", marker = "platform_machine == 'arm64' and sys_platform == 'darwin' and extra == 'root-gnn'", specifier = ">=2,<3" }, { name = "scikit-learn", specifier = ">=1.3" }, { name = "torch", marker = "platform_machine != 'x86_64' or sys_platform != 'linux'", specifier = "==2.2.2" }, { name = "torch", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'", specifier = "==2.2.2", index = "https://download.pytorch.org/whl/cu121" }, - { name = "torchdata", marker = "platform_machine == 'arm64' and sys_platform == 'darwin' and extra == 'root-gnn'", specifier = ">=0.7,<0.8" }, { name = "uproot", specifier = ">=5.0" }, ] -provides-extras = ["root-gnn", "onnx"] +provides-extras = ["onnx"] [package.metadata.requires-dev] dev = [ @@ -922,24 +852,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" }, ] -[[package]] -name = "pandas" -version = "3.0.5" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "numpy", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, - { name = "python-dateutil", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/be/4f/5f3422a2afec5ffc46308b79e53291365a93748b498ac2e58bead0197916/pandas-3.0.5.tar.gz", hash = "sha256:dca3734d6ab7c906e6730f0788b0a1dbb9f2467731f9711f77995c8e9d62d712", size = 4658219, upload-time = "2026-07-22T22:19:28.819Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/1c/54/1dc810ea558d1320b597aa140a514f2fdf1d2ea09c38cf556f13ea712ec9/pandas-3.0.5-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:fa290c16964d4963fbfbc358928239cf3bd755b20e988ce944877def2f44471d", size = 10411717, upload-time = "2026-07-22T22:18:08.307Z" }, - { url = "https://files.pythonhosted.org/packages/68/56/fbe81c09195924d8b7b8d4461a20458fe80a6a5ed6b24f0314da684277e1/pandas-3.0.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:c2e26bb46934b8a2ca0c3de1d3d606fc5f6746584791b2db264d58cf370e08dc", size = 9957095, upload-time = "2026-07-22T22:18:10.6Z" }, - { url = "https://files.pythonhosted.org/packages/e0/51/fac252f4a913ed5eabf3c11b880a9e8d5a6c10f0b2129d0462212d238b4d/pandas-3.0.5-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:73fa87b08a7ef706f8aafda39ddaccf2a99047bea62d8c88a0361bcafb2237bc", size = 10485458, upload-time = "2026-07-22T22:18:12.834Z" }, - { url = "https://files.pythonhosted.org/packages/12/98/e976540c1addf70442be7842a18cf70884a964abbf69442504f4d2939989/pandas-3.0.5-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d373ce03ffd84010ed9839fa73672a9c8256990532e158440c0085db7d914b34", size = 10998091, upload-time = "2026-07-22T22:18:15.209Z" }, - { url = "https://files.pythonhosted.org/packages/a4/8c/1f29b5be8d3fc47dd7567eb167fabba2085879b31e0287ce7cba6d3d2ff4/pandas-3.0.5-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:2a29c53d85ea98c5e792c59ef82ee9fbe6ca902c0d0adb6b23f45ef894cd7bf6", size = 11499501, upload-time = "2026-07-22T22:18:17.689Z" }, - { url = "https://files.pythonhosted.org/packages/9d/e2/bd9c98ad2df7b38bde002adde4cdf353519da51881634323b126c55997f9/pandas-3.0.5-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a5ad3b02ed6bc7d7ae9b70804b2c6aa31827489d150f8e623ce82491b82085d7", size = 12060559, upload-time = "2026-07-22T22:18:20.147Z" }, -] - [[package]] name = "pillow" version = "12.3.0" @@ -981,20 +893,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/19/c7/5f7c636ec43e0c545e28d1f1db71990108306f7bdcb89f069ba97e428e7f/protobuf-7.35.1-py3-none-any.whl", hash = "sha256:4bc97768d8fe4ad6743c8a19403e314511ed9f6d13205b687e52421c023ac1b9", size = 171659, upload-time = "2026-06-11T21:55:39.155Z" }, ] -[[package]] -name = "psutil" -version = "7.2.2" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/aa/c6/d1ddf4abb55e93cebc4f2ed8b5d6dbad109ecb8d63748dd2b20ab5e57ebe/psutil-7.2.2.tar.gz", hash = "sha256:0746f5f8d406af344fd547f1c8daa5f5c33dbc293bb8d6a16d80b4bb88f59372", size = 493740, upload-time = "2026-01-28T18:14:54.428Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/e7/36/5ee6e05c9bd427237b11b3937ad82bb8ad2752d72c6969314590dd0c2f6e/psutil-7.2.2-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:ed0cace939114f62738d808fdcecd4c869222507e266e574799e9c0faa17d486", size = 129090, upload-time = "2026-01-28T18:15:22.168Z" }, - { url = "https://files.pythonhosted.org/packages/80/c4/f5af4c1ca8c1eeb2e92ccca14ce8effdeec651d5ab6053c589b074eda6e1/psutil-7.2.2-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:1a7b04c10f32cc88ab39cbf606e117fd74721c831c98a27dc04578deb0c16979", size = 129859, upload-time = "2026-01-28T18:15:23.795Z" }, - { url = "https://files.pythonhosted.org/packages/b5/70/5d8df3b09e25bce090399cf48e452d25c935ab72dad19406c77f4e828045/psutil-7.2.2-cp36-abi3-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:076a2d2f923fd4821644f5ba89f059523da90dc9014e85f8e45a5774ca5bc6f9", size = 155560, upload-time = "2026-01-28T18:15:25.976Z" }, - { url = "https://files.pythonhosted.org/packages/63/65/37648c0c158dc222aba51c089eb3bdfa238e621674dc42d48706e639204f/psutil-7.2.2-cp36-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b0726cecd84f9474419d67252add4ac0cd9811b04d61123054b9fb6f57df6e9e", size = 156997, upload-time = "2026-01-28T18:15:27.794Z" }, - { url = "https://files.pythonhosted.org/packages/8e/13/125093eadae863ce03c6ffdbae9929430d116a246ef69866dad94da3bfbc/psutil-7.2.2-cp36-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:fd04ef36b4a6d599bbdb225dd1d3f51e00105f6d48a28f006da7f9822f2606d8", size = 148972, upload-time = "2026-01-28T18:15:29.342Z" }, - { url = "https://files.pythonhosted.org/packages/04/78/0acd37ca84ce3ddffaa92ef0f571e073faa6d8ff1f0559ab1272188ea2be/psutil-7.2.2-cp36-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:b58fabe35e80b264a4e3bb23e6b96f9e45a3df7fb7eed419ac0e5947c61e47cc", size = 148266, upload-time = "2026-01-28T18:15:31.597Z" }, -] - [[package]] name = "pycparser" version = "3.0" @@ -1004,47 +902,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/0c/c3/44f3fbbfa403ea2a7c779186dc20772604442dde72947e7d01069cbe98e3/pycparser-3.0-py3-none-any.whl", hash = "sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992", size = 48172, upload-time = "2026-01-21T14:26:50.693Z" }, ] -[[package]] -name = "pydantic" -version = "2.13.4" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "annotated-types", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, - { name = "pydantic-core", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, - { name = "typing-extensions", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, - { name = "typing-inspection", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/18/a5/b60d21ac674192f8ab0ba4e9fd860690f9b4a6e51ca5df118733b487d8d6/pydantic-2.13.4.tar.gz", hash = "sha256:c40756b57adaa8b1efeeced5c196f3f3b7c435f90e84ea7f443901bec8099ef6", size = 844775, upload-time = "2026-05-06T13:43:05.343Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/fd/7b/122376b1fd3c62c1ed9dc80c931ace4844b3c55407b6fb2d199377c9736f/pydantic-2.13.4-py3-none-any.whl", hash = "sha256:45a282cde31d808236fd7ea9d919b128653c8b38b393d1c4ab335c62924d9aba", size = 472262, upload-time = "2026-05-06T13:43:02.641Z" }, -] - -[[package]] -name = "pydantic-core" -version = "2.46.4" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "typing-extensions", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/9d/56/921726b776ace8d8f5db44c4ef961006580d91dc52b803c489fafd1aa249/pydantic_core-2.46.4.tar.gz", hash = "sha256:62f875393d7f270851f20523dd2e29f082bcc82292d66db2b64ea71f64b6e1c1", size = 471464, upload-time = "2026-05-06T13:37:06.98Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ce/8c/af022f0af448d7747c5154288d46b5f2bc5f17366eaa0e23e9aa04d59f3b/pydantic_core-2.46.4-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:3245406455a5d98187ec35530fd772b1d799b26667980872c8d4614991e2c4a2", size = 2106158, upload-time = "2026-05-06T13:38:57.215Z" }, - { url = "https://files.pythonhosted.org/packages/19/95/6195171e385007300f0f5574592e467c568becce2d937a0b6804f218bc49/pydantic_core-2.46.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:962ccbab7b642487b1d8b7df90ef677e03134cf1fd8880bf698649b22a69371f", size = 1951724, upload-time = "2026-05-06T13:37:02.697Z" }, - { url = "https://files.pythonhosted.org/packages/8e/bc/f47d1ff9cbb1620e1b5b697eef06010035735f07820180e74178226b27b3/pydantic_core-2.46.4-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8233f2947cf85404441fd7e0085f53b10c93e0ee78611099b5c7237e36aacbf7", size = 1975742, upload-time = "2026-05-06T13:37:09.448Z" }, - { url = "https://files.pythonhosted.org/packages/5b/11/9b9a5b0306345664a2da6410877af6e8082481b5884b3ddd78d47c6013ce/pydantic_core-2.46.4-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:3a233125ac121aa3ffba9a2b59edfc4a985a76092dc8279586ab4b71390875e7", size = 2052418, upload-time = "2026-05-06T13:37:38.234Z" }, - { url = "https://files.pythonhosted.org/packages/f1/b7/a65fec226f5d78fc39f4a13c4cc0c768c22b113438f60c14adc9d2865038/pydantic_core-2.46.4-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5b712b53160b79a5850310b912a5ef8e57e56947c8ad690c227f5c9d7e561712", size = 2232274, upload-time = "2026-05-06T13:38:27.753Z" }, - { url = "https://files.pythonhosted.org/packages/68/f0/92039db98b907ef49269a8271f67db9cb78ae2fc68062ef7e4e77adb5f61/pydantic_core-2.46.4-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9401557acd873c3a7f3eb9383edef8ac4968f9510e340f4808d427e75667e7b4", size = 2309940, upload-time = "2026-05-06T13:38:05.353Z" }, - { url = "https://files.pythonhosted.org/packages/5f/97/2aab507d3d00ca626e8e57c1eac6a79e4e5fbcc63eb99733ff55d1717f65/pydantic_core-2.46.4-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:926c9541b14b12b1681dca8a0b75feb510b06c6341b70a8e500c2fdcff837cce", size = 2094516, upload-time = "2026-05-06T13:39:10.577Z" }, - { url = "https://files.pythonhosted.org/packages/22/37/a8aca44d40d737dde2bc05b3c6c07dff0de07ce6f82e9f3167aeaf4d5dea/pydantic_core-2.46.4-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:56cb4851bcaf3d117eddcef4fe66afd750a50274b0da8e22be256d10e5611987", size = 2136854, upload-time = "2026-05-06T13:40:22.59Z" }, - { url = "https://files.pythonhosted.org/packages/ae/6c/fc44000918855b42779d007ae63b0532794739027b2f417321cddbc44f6a/pydantic_core-2.46.4-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:b2f69dec1725e79a012d920df1707de5caf7ed5e08f3be4435e25803efc47458", size = 2190044, upload-time = "2026-05-06T13:40:43.231Z" }, - { url = "https://files.pythonhosted.org/packages/6b/65/d9cadc9f1920d7a127ad2edba16c1db7916e59719285cd6c94600b0080ba/pydantic_core-2.46.4-cp312-cp312-musllinux_1_1_armv7l.whl", hash = "sha256:8d0820e8192167f80d88d64038e609c31452eeca865b4e1d9950a27a4609b00b", size = 2329133, upload-time = "2026-05-06T13:39:57.365Z" }, - { url = "https://files.pythonhosted.org/packages/d0/cf/c873d91679f3a30bcf5e7ac280ce5573483e72295307685120d0d5ad3416/pydantic_core-2.46.4-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:fbdb89b3e1c94a30cc5edfce477c6e6a5dc4d8f84665b455c27582f211a1c72c", size = 2374464, upload-time = "2026-05-06T13:38:06.976Z" }, - { url = "https://files.pythonhosted.org/packages/9d/1d/8987ad40f65ae1432753072f214fb5c74fe47ffbd0698bb9cbbb585664f8/pydantic_core-2.46.4-graalpy312-graalpy250_312_native-macosx_10_12_x86_64.whl", hash = "sha256:1d8ba486450b14f3b1d63bc521d410ec7565e52f887b9fb671791886436a42f7", size = 2095527, upload-time = "2026-05-06T13:39:52.283Z" }, - { url = "https://files.pythonhosted.org/packages/64/d3/84c282a7eee1d3ac4c0377546ef5a1ea436ce26840d9ac3b7ed54a377507/pydantic_core-2.46.4-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:3009f12e4e90b7f88b4f9adb1b0c4a3d58fe7820f3238c190047209d148026df", size = 1936024, upload-time = "2026-05-06T13:40:15.671Z" }, - { url = "https://files.pythonhosted.org/packages/d7/ca/eac61596cdeb4d7e174d3dc0bd8a6238f14f75f97a24e7b7db4c7e7340a0/pydantic_core-2.46.4-graalpy312-graalpy250_312_native-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ad785e92e6dc634c21555edc8bd6b64957ab844541bcb96a1366c202951ae526", size = 1990696, upload-time = "2026-05-06T13:38:34.717Z" }, - { url = "https://files.pythonhosted.org/packages/fa/c3/7c8b240552251faf6b3a957db200fcfbbcec36763c050428b601e0c9b83b/pydantic_core-2.46.4-graalpy312-graalpy250_312_native-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:00c603d540afdd6b80eb39f078f33ebd46211f02f33e34a32d9f053bba711de0", size = 2147590, upload-time = "2026-05-06T13:39:29.883Z" }, -] - [[package]] name = "pygments" version = "2.21.0" @@ -1360,19 +1217,6 @@ wheels = [ { url = "https://download-r2.pytorch.org/whl/cu121/torch-2.2.2%2Bcu121-cp312-cp312-linux_x86_64.whl", hash = "sha256:badc14d413ff1847d15021a1ec0affa479d24dfc83e6d51b9b4b9fbfaad1b14c", upload-time = "2024-04-24T17:07:56Z" }, ] -[[package]] -name = "torchdata" -version = "0.7.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "requests", marker = "(platform_machine != 'x86_64' and sys_platform == 'linux') or (sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32')" }, - { name = "torch", version = "2.2.2", source = { registry = "https://pypi.org/simple" }, marker = "(platform_machine != 'x86_64' and sys_platform == 'linux') or (sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32')" }, - { name = "urllib3", marker = "(platform_machine != 'x86_64' and sys_platform == 'linux') or (sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32')" }, -] -wheels = [ - { url = "https://files.pythonhosted.org/packages/e2/c8/34eda2bd6beb8a11c06cf905db74092bdbc3dec51a48f4f22cc474866a0a/torchdata-0.7.1-py3-none-any.whl", hash = "sha256:9f9476a26987d90fa3f87cb09ec82b78ce6031ddcaa91851c9fa9f732a987ab8", size = 184418, upload-time = "2023-11-15T17:09:10.159Z" }, -] - [[package]] name = "tqdm" version = "4.70.0" @@ -1414,18 +1258,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, ] -[[package]] -name = "typing-inspection" -version = "0.4.4" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "typing-extensions", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a3/26/b09b8010994eccc3c09092e6b34058f36a460eea2d4c3e8b910c695975a0/typing_inspection-0.4.4.tar.gz", hash = "sha256:547274fa6b0a561ccf549cc9524b999a578e737d015d8709d021f9d0d13bea47", size = 76928, upload-time = "2026-08-12T12:37:25.997Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/67/81/4add07e5172b7ac40d8ed5ff580409a7801a4fe26d529bdd915401dabfbe/typing_inspection-0.4.4-py3-none-any.whl", hash = "sha256:65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147", size = 14750, upload-time = "2026-08-12T12:37:24.648Z" }, -] - [[package]] name = "uproot" version = "5.7.5" diff --git a/validation/batching.py b/validation/batching.py index f58be324d0c9968c903be35ab59f3681bd2780a9..62872f16b2800782bbb661b58d6d6e5a2c49c6c2 100644 --- a/validation/batching.py +++ b/validation/batching.py @@ -7,10 +7,11 @@ import argparse import json from pathlib import Path +import numpy as np import torch from validation.artifacts import load_artifact -from validation.forward import _graph +from validation.forward import batch_graph def main() -> int: @@ -20,29 +21,41 @@ def main() -> int: parser.add_argument("--batch-size", type=int, default=8) args = parser.parse_args() artifact = load_artifact(args.artifact) - from gnn4colliders.data import ( - EventMetadata, - GraphDataLoader, - GraphDataset, - GraphSample, + from gnn4colliders.data import EventLoader, PackedEvents + from gnn4colliders.graphs import GraphBatch + + # Batch the artifact's stored graphs directly; ``PackedEvents`` only + # provides the deterministic ordered loader and named metadata here. + counts = [len(artifact.event_nodes(index)) for index in range(artifact.event_count)] + events = PackedEvents( + object_features=torch.zeros((sum(counts), 1)), + object_offsets=torch.tensor([0, *np.cumsum(counts).tolist()]), + labels=torch.as_tensor(artifact.labels), + global_features=None, + fold=torch.as_tensor(artifact.folds, dtype=torch.long), + weight=torch.as_tensor(artifact.weights, dtype=torch.float32), + file_index=torch.zeros(artifact.event_count, dtype=torch.long), + entry_index=torch.arange(artifact.event_count), + source_files=("artifact",), + tree_name="events", + feature_names=("unused",), ) + sample_ids = [str(value) for value in artifact.sample_id] - samples = [] - for index in range(artifact.event_count): - samples.append( - GraphSample( - _graph(artifact, index), - torch.tensor(artifact.labels[index]), - None, - EventMetadata( - int(artifact.folds[index]), - float(artifact.weights[index]), - str(artifact.sample_id[index]), - {"index": index}, - ), - ) + def collate(packed, indices): + metadata = packed.batch_metadata(indices) + return GraphBatch( + graph=batch_graph(artifact, indices.tolist()), + labels=packed.labels[indices], + global_features=None, + metadata=type(metadata)( + fold=metadata.fold, + weight=metadata.weight, + sample_id=tuple(sample_ids[index] for index in indices.tolist()), + ), ) - loader = GraphDataLoader(GraphDataset(samples), args.batch_size, shuffle=False) + + loader = EventLoader(events, collate, args.batch_size, shuffle=False) batches = [] for batch in loader: graph = batch.graph @@ -53,8 +66,8 @@ def main() -> int: { "sample_id": ids, "num_graphs": len(ids), - "nodes": int(graph.num_nodes()), - "edges": int(graph.num_edges()), + "nodes": int(graph.node_features.shape[0]), + "edges": int(graph.edge_features.shape[0]), "labels": labels.reshape(-1).tolist(), "weights": weights, } diff --git a/validation/binary_step.py b/validation/binary_step.py index 696b8d53ca58d792bbc416cc2ae1d25faff72713..cb6c09107e930bda946882658df985df8dc66ae1 100644 --- a/validation/binary_step.py +++ b/validation/binary_step.py @@ -6,12 +6,11 @@ from __future__ import annotations import argparse from pathlib import Path -import dgl import numpy as np import torch from validation.artifacts import load_artifact -from validation.forward import _graph +from validation.forward import batch_graph def _loss( @@ -49,9 +48,8 @@ def main() -> int: artifact = load_artifact(args.artifact) count = args.per_class_events indices = np.concatenate([np.arange(count), np.arange(100000, 100000 + count)]) - graphs = [_graph(artifact, int(index)) for index in indices] - graph = dgl.batch(graphs) - empty_globals = torch.empty((len(graphs), 0), dtype=torch.float32) + graph = batch_graph(artifact, indices) + empty_globals = torch.empty((len(indices), 0), dtype=torch.float32) from gnn4colliders.models.root_gnn import ( EdgeNetwork, @@ -59,7 +57,7 @@ def main() -> int: load_legacy_edge_network_state_dict, ) - backbone = EdgeNetwork(graphs[0], empty_globals[:1], 64, 12, 4, 4, dropout=0.0) + backbone = EdgeNetwork(graph, empty_globals[:1], 64, 12, 4, 4, dropout=0.0) payload = torch.load(args.checkpoint, map_location="cpu", weights_only=False) load_legacy_edge_network_state_dict(backbone, payload) model = FineTunedEdgeNetwork( diff --git a/validation/end_to_end_binary.py b/validation/end_to_end_binary.py index b8b08576e4255c851ac88eb653a08d9960c8b90b..c23f40d89d842b0b00b88e608ed2fb83c5748153 100644 --- a/validation/end_to_end_binary.py +++ b/validation/end_to_end_binary.py @@ -6,12 +6,11 @@ from __future__ import annotations import argparse from pathlib import Path -import dgl import numpy as np import torch from validation.artifacts import load_artifact -from validation.forward import _graph +from validation.forward import batch_graph def loss(logits, labels, weights): @@ -42,8 +41,7 @@ def run_batches(model, artifact, indices, batch_size, optimizer=None): values = [] for start in range(0, len(indices), batch_size): batch_indices = indices[start : start + batch_size] - graphs = [_graph(artifact, int(index)) for index in batch_indices] - graph = dgl.batch(graphs) + graph = batch_graph(artifact, batch_indices) labels = torch.from_numpy(artifact.labels[batch_indices]).to(torch.float32) weights = torch.from_numpy(artifact.weights[batch_indices]).to(torch.float32) if optimizer is not None: @@ -77,7 +75,7 @@ def main() -> int: test = all_indices[split == 4] generator = np.random.default_rng(20260818) train = train[generator.permutation(len(train))] - first_graph = _graph(artifact, int(train[0])) + first_graph = batch_graph(artifact, train[:1]) model = make_model( first_graph, torch.empty((1, 0), dtype=torch.float32), diff --git a/validation/forward.py b/validation/forward.py index afd822b846381cab36bd8afe8b7e0d18972d296c..b545f33db4cbefc7e6f6e82a7621e980f4394559 100644 --- a/validation/forward.py +++ b/validation/forward.py @@ -7,22 +7,41 @@ import argparse from dataclasses import replace from pathlib import Path -import dgl import numpy as np import torch from validation.artifacts import load_artifact, save_artifact -def _graph(artifact, index: int): - nodes = torch.from_numpy(artifact.event_nodes(index)).to(torch.float32) - src, dst, edges = artifact.event_edges(index) - graph = dgl.graph( - (torch.from_numpy(src), torch.from_numpy(dst)), num_nodes=nodes.shape[0] +def batch_graph(artifact, indices): + """Batch the artifact's stored per-event nodes and edges (not recomputed).""" + from gnn4colliders.graphs import TensorGraph + + nodes, edges, src, dst, node_counts, edge_counts = [], [], [], [], [], [] + offset = 0 + for index in indices: + event_nodes = torch.from_numpy(artifact.event_nodes(int(index))) + event_src, event_dst, event_edges = artifact.event_edges(int(index)) + nodes.append(event_nodes.to(torch.float32)) + edges.append(torch.from_numpy(event_edges).to(torch.float32)) + src.append(torch.from_numpy(event_src).to(torch.long) + offset) + dst.append(torch.from_numpy(event_dst).to(torch.long) + offset) + node_counts.append(event_nodes.shape[0]) + edge_counts.append(len(event_src)) + offset += event_nodes.shape[0] + node_counts = torch.tensor(node_counts) + edge_counts = torch.tensor(edge_counts) + graphs = torch.arange(len(node_counts)) + return TensorGraph( + node_features=torch.cat(nodes), + edge_features=torch.cat(edges), + edge_src=torch.cat(src), + edge_dst=torch.cat(dst), + node_batch=torch.repeat_interleave(graphs, node_counts), + edge_batch=torch.repeat_interleave(graphs, edge_counts), + node_counts=node_counts, + edge_counts=edge_counts, ) - graph.ndata["features"] = nodes - graph.edata["features"] = torch.from_numpy(edges).to(torch.float32) - return graph def main() -> int: @@ -38,32 +57,30 @@ def main() -> int: if args.events is None else min(args.events, artifact.event_count) ) - graphs = [_graph(artifact, index) for index in range(event_count)] - batch_graph = dgl.batch(graphs) - first = graphs[0] + graph = batch_graph(artifact, range(event_count)) empty_globals = torch.empty((1, 0), dtype=torch.float32) from gnn4colliders.models.root_gnn import ( EdgeNetwork, load_legacy_edge_network_state_dict, ) - model = EdgeNetwork(first, empty_globals, 64, 12, 4, 4, dropout=0.0) + model = EdgeNetwork(graph, empty_globals, 64, 12, 4, 4, dropout=0.0) payload = torch.load(args.checkpoint, map_location="cpu", weights_only=False) load_legacy_edge_network_state_dict(model, payload) model.eval() with torch.inference_mode(): - logits = model(batch_graph, None).cpu().numpy() + logits = model(graph, None).cpu().numpy() args.output.mkdir(parents=True, exist_ok=True) reload_path = args.output / "checkpoint_reload.pt" torch.save({"model_state_dict": model.state_dict()}, reload_path) - fresh = type(model)(first, empty_globals, 64, 12, 4, 4, dropout=0.0) + fresh = type(model)(graph, empty_globals, 64, 12, 4, 4, dropout=0.0) fresh.load_state_dict( torch.load(reload_path, map_location="cpu")["model_state_dict"] ) fresh.eval() with torch.inference_mode(): - reloaded_logits = fresh(batch_graph, None).cpu().numpy() + reloaded_logits = fresh(graph, None).cpu().numpy() scores = torch.softmax(torch.from_numpy(logits), dim=1).numpy() predictions = scores.argmax(axis=1) updated = replace( diff --git a/validation/train_step.py b/validation/train_step.py index 6e70502d658370c8fa5f6a67cb2b5b3ea0532fac..229ab69592183d973d1166646356e05aa44158a6 100644 --- a/validation/train_step.py +++ b/validation/train_step.py @@ -6,12 +6,11 @@ from __future__ import annotations import argparse from pathlib import Path -import dgl import numpy as np import torch from validation.artifacts import load_artifact -from validation.forward import _graph +from validation.forward import batch_graph def _weighted_loss(logits, labels, weights): @@ -57,15 +56,14 @@ def main() -> int: args = parser.parse_args() artifact = load_artifact(args.artifact) count = min(args.events, artifact.event_count) - graphs = [_graph(artifact, index) for index in range(count)] - graph = dgl.batch(graphs) + graph = batch_graph(artifact, range(count)) empty_globals = torch.empty((count, 0), dtype=torch.float32) from gnn4colliders.models.root_gnn import ( EdgeNetwork, load_legacy_edge_network_state_dict, ) - model = EdgeNetwork(graphs[0], empty_globals[:1], 64, 12, 4, 4, dropout=0.0) + model = EdgeNetwork(graph, empty_globals[:1], 64, 12, 4, 4, dropout=0.0) payload = torch.load(args.checkpoint, map_location="cpu", weights_only=False) load_legacy_edge_network_state_dict(model, payload) model.train() diff --git a/validation/transfer.py b/validation/transfer.py index 7229401da13b4ec5f568eaaa544dcf87b850cd54..7e1254564f42e860ce1731c2b0dabde6b6be121b 100644 --- a/validation/transfer.py +++ b/validation/transfer.py @@ -6,12 +6,11 @@ from __future__ import annotations import argparse from pathlib import Path -import dgl import numpy as np import torch from validation.artifacts import load_artifact -from validation.forward import _graph +from validation.forward import batch_graph def main() -> int: @@ -24,8 +23,7 @@ def main() -> int: args = parser.parse_args() artifact = load_artifact(args.artifact) count = min(args.events, artifact.event_count) - graphs = [_graph(artifact, index) for index in range(count)] - batch_graph = dgl.batch(graphs) + graph = batch_graph(artifact, range(count)) empty_globals = torch.empty((1, 0), dtype=torch.float32) from gnn4colliders.models.root_gnn import ( EdgeNetwork, @@ -33,7 +31,7 @@ def main() -> int: load_legacy_edge_network_state_dict, ) - backbone = EdgeNetwork(graphs[0], empty_globals, 64, 12, 4, 4, dropout=0.0) + backbone = EdgeNetwork(graph, empty_globals, 64, 12, 4, 4, dropout=0.0) payload = torch.load(args.checkpoint, map_location="cpu", weights_only=False) load_legacy_edge_network_state_dict(backbone, payload) model = FineTunedEdgeNetwork( @@ -44,7 +42,7 @@ def main() -> int: classifier.load_state_dict(torch.nn.Linear(64, 1).state_dict()) model.eval() with torch.inference_mode(): - logits = model(batch_graph, None).cpu().numpy() + logits = model(graph, None).cpu().numpy() args.output.parent.mkdir(parents=True, exist_ok=True) np.savez_compressed(args.output, logits=logits) return 0