StrikeTwice 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Gwenn Guichaoua and Elodie Laine
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,124 @@
1
+ Metadata-Version: 2.4
2
+ Name: StrikeTwice
3
+ Version: 0.1.0
4
+ Summary: PyTorch implementation of StrikeTwice and the Edge–Vertex Transformer
5
+ Author: Gwenn Guichaoua, Elodie Laine
6
+ License-Expression: MIT
7
+ Project-URL: Repository, https://github.com/Guichaoua/StrikeTwice
8
+ Project-URL: Documentation, https://striketwice.readthedocs.io/en/latest/
9
+ Requires-Python: >=3.9
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: torch>=2.1
13
+ Dynamic: license-file
14
+
15
+ # StrikeTwice
16
+
17
+ Core PyTorch implementation for *StrikeTwice: Reusable Graph Representations for Path Prediction* by Gwenn Guichaoua and Elodie Laine.
18
+
19
+ The Edge–Vertex Transformer (EVT) encodes vertex and ordered-pair features. StrikeTwice uses an EVT to encode the graph, selects states in path-occurrence order, and applies a second EVT to the selected states. Several paths can share the same graph encoding.
20
+
21
+ ## Installation
22
+
23
+ Use Python 3.9 or newer. Install StrikeTwice and its PyTorch dependency from PyPI.
24
+
25
+ ```sh
26
+ python -m pip install StrikeTwice
27
+ ```
28
+
29
+ To install from a source checkout, run this command from the repository root.
30
+
31
+ ```sh
32
+ python -m pip install .
33
+ ```
34
+
35
+ Import the models from `path_augmented_transformer`.
36
+
37
+ ## Documentation
38
+
39
+ The [documentation on Read the Docs](https://striketwice.readthedocs.io/en/latest/) includes two runnable notebooks and a Python API reference. Documentation builds use CPU by default.
40
+
41
+ The [Task 2 notebook](https://striketwice.readthedocs.io/en/latest/tutorials/striketwice.html#Task-2-benchmark) uses CUDA or Apple Metal (MPS) when available. Set `STRIKETWICE_TASK2_DEVICE` to `cuda`, `mps`, or `cpu` before launching Jupyter to choose a backend explicitly.
42
+
43
+ To build locally, put Pandoc on your PATH and run these commands from the repository root.
44
+
45
+ ```sh
46
+ python -m pip install . -r docs/requirements.txt
47
+ python -m sphinx -W -b html docs docs/_build/html
48
+ ```
49
+
50
+ Open `docs/_build/html/index.html` to browse the result.
51
+
52
+ ## Use EVT on its own
53
+
54
+ ### One EVT block
55
+
56
+ Call `EdgeVertexTransformerLayer` directly on vertex states `X` of shape `[B, n, d_model]` and ordered-pair states `Y` of shape `[B, n, n, d_model]`. The boolean `node_mask` identifies valid vertices. The block runs on the graph alone and returns updated states with the same shapes.
57
+
58
+ ```python
59
+ import torch
60
+ from path_augmented_transformer import EdgeVertexTransformerLayer
61
+
62
+ X = torch.randn(1, 3, 8)
63
+ Y = torch.randn(1, 3, 3, 8)
64
+ node_mask = torch.ones(1, 3, dtype=torch.bool)
65
+
66
+ block = EdgeVertexTransformerLayer(d_model=8, num_heads=2)
67
+ X_next, Y_next = block(X, Y, node_mask)
68
+ ```
69
+
70
+ ### EVT with input projections
71
+
72
+ For raw vertex features `X` of shape `[B, n, d_x]` and ordered-pair features `Y` of shape `[B, n, n, d_y]`, use `EdgeVertexTransformer` to project both streams to width `d_h`. Set `num_layers=1` for a single EVT block. The encoder returns the contextualized states in `out.X` and `out.Y`.
73
+
74
+ ```python
75
+ import torch
76
+ from path_augmented_transformer import EdgeVertexTransformer
77
+
78
+ X = torch.tensor([[[1.0], [2.0], [3.0]]])
79
+ Y = torch.zeros(1, 3, 3, 1)
80
+ Y[0, 0, 1, 0] = 1.0 # Directed edge 0 -> 1
81
+ Y[0, 1, 2, 0] = 1.0 # Directed edge 1 -> 2
82
+ node_mask = torch.ones(1, 3, dtype=torch.bool)
83
+
84
+ evt = EdgeVertexTransformer(d_x=1, d_y=1, d_h=8, num_layers=1, num_heads=2)
85
+ out = evt(X, Y, node_mask)
86
+ print(out.X.shape, out.Y.shape) # [1, 3, 8] and [1, 3, 3, 8]
87
+ ```
88
+
89
+ ## Run the StrikeTwice CPU demo
90
+
91
+ ```sh
92
+ python demo.py
93
+ ```
94
+
95
+ The demo builds a four-vertex graph in memory and runs two paths, one of which revisits a vertex. It checks that the vertex states, pair states and scalar predictions agree when using a shared cache or recomputing the graph encoding for each path. It uses randomly initialized weights.
96
+
97
+ ## Tiled inference at 1,024 vertices
98
+
99
+ Use `--paper` to run the full Atlas architecture from the paper's scaling study. It has 778,897 parameters, width 64, two EVT layers per stage, four graph heads and eight path heads. The synthetic workload uses the study's seeds, seven vertex features, six pair features and one batch of 16 paths of length 16. The graph encoder uses the aggressive tiling settings from the paper.
100
+
101
+ ```sh
102
+ # Smoke check of the full model on CPU
103
+ python demo_scaling.py --paper --nodes 64 --device cpu
104
+
105
+ # Full-size synthetic inference workload on a CUDA GPU
106
+ python demo_scaling.py --paper --nodes 1024 --device cuda --warmups 2 --repeats 10
107
+ ```
108
+
109
+ The release measures inference with initialized weights. The forward/backward timing and memory in the paper used activation checkpointing on an A100. The separate trained-checkpoint amortization measurements used their own query workload.
110
+
111
+ ### Examples from observed traceroutes
112
+
113
+ ```sh
114
+ python demo_scaling.py # quick synthetic example
115
+ python demo_scaling.py --device cpu examples/atlas-de-1024.json examples/atlas-us-1024.json
116
+ ```
117
+
118
+ The second command builds one cache per graph and reuses it for four routes. It reports cache construction and path-processing times separately, the size of the stored cache, and the size of one triangular score tensor before and after tiling. With one FP32 head, the score tensor drops from 4 GiB to 32 MiB per tile at the default eight source rows. This is a tensor-size calculation. Use `--device cuda` to also measure the PyTorch allocator's peak on a CUDA GPU.
119
+
120
+ The demo checks that tiled and untiled inference agree on a small graph using the same weights. The opt-in PyTorch implementation tiles triangular attention over source rows and value channels, and cross-stream attention over query rows. Each softmax keeps all valid keys or intermediate vertices. Graph-encoder arithmetic remains cubic in the number of vertices, and the cache remains quadratic.
121
+
122
+ Both JSON fixtures contain 1,024 vertices from public IPv4 traceroutes collected by RIPE Atlas Region Meshes in August 2026. They pool several destinations within each region and retain directed edges between consecutive responding hops. Vertex IDs are local integers. The fixtures contain topology and route segments, and the default demo uses a width-four model for a quick CPU run. Add `--paper` to use the full model on these topologies with zero-filled input channels apart from adjacency. These regional examples are separate from the per-destination latency benchmark in the paper. [RIPE Atlas Region Meshes](https://atlas.ripe.net/docs/tools-and-code/region-meshes/) · [RIPE Atlas terms](https://www.ripe.net/about-us/legal/ripe-atlas-service-terms-and-conditions/)
123
+
124
+ The fixtures record source URLs and SHA-256 digests. To rebuild them, download each archive into `DATE/REGION/` under a local data directory and run `python examples/build_atlas_fixtures.py --raw-root /path/to/data`.
@@ -0,0 +1,110 @@
1
+ # StrikeTwice
2
+
3
+ Core PyTorch implementation for *StrikeTwice: Reusable Graph Representations for Path Prediction* by Gwenn Guichaoua and Elodie Laine.
4
+
5
+ The Edge–Vertex Transformer (EVT) encodes vertex and ordered-pair features. StrikeTwice uses an EVT to encode the graph, selects states in path-occurrence order, and applies a second EVT to the selected states. Several paths can share the same graph encoding.
6
+
7
+ ## Installation
8
+
9
+ Use Python 3.9 or newer. Install StrikeTwice and its PyTorch dependency from PyPI.
10
+
11
+ ```sh
12
+ python -m pip install StrikeTwice
13
+ ```
14
+
15
+ To install from a source checkout, run this command from the repository root.
16
+
17
+ ```sh
18
+ python -m pip install .
19
+ ```
20
+
21
+ Import the models from `path_augmented_transformer`.
22
+
23
+ ## Documentation
24
+
25
+ The [documentation on Read the Docs](https://striketwice.readthedocs.io/en/latest/) includes two runnable notebooks and a Python API reference. Documentation builds use CPU by default.
26
+
27
+ The [Task 2 notebook](https://striketwice.readthedocs.io/en/latest/tutorials/striketwice.html#Task-2-benchmark) uses CUDA or Apple Metal (MPS) when available. Set `STRIKETWICE_TASK2_DEVICE` to `cuda`, `mps`, or `cpu` before launching Jupyter to choose a backend explicitly.
28
+
29
+ To build locally, put Pandoc on your PATH and run these commands from the repository root.
30
+
31
+ ```sh
32
+ python -m pip install . -r docs/requirements.txt
33
+ python -m sphinx -W -b html docs docs/_build/html
34
+ ```
35
+
36
+ Open `docs/_build/html/index.html` to browse the result.
37
+
38
+ ## Use EVT on its own
39
+
40
+ ### One EVT block
41
+
42
+ Call `EdgeVertexTransformerLayer` directly on vertex states `X` of shape `[B, n, d_model]` and ordered-pair states `Y` of shape `[B, n, n, d_model]`. The boolean `node_mask` identifies valid vertices. The block runs on the graph alone and returns updated states with the same shapes.
43
+
44
+ ```python
45
+ import torch
46
+ from path_augmented_transformer import EdgeVertexTransformerLayer
47
+
48
+ X = torch.randn(1, 3, 8)
49
+ Y = torch.randn(1, 3, 3, 8)
50
+ node_mask = torch.ones(1, 3, dtype=torch.bool)
51
+
52
+ block = EdgeVertexTransformerLayer(d_model=8, num_heads=2)
53
+ X_next, Y_next = block(X, Y, node_mask)
54
+ ```
55
+
56
+ ### EVT with input projections
57
+
58
+ For raw vertex features `X` of shape `[B, n, d_x]` and ordered-pair features `Y` of shape `[B, n, n, d_y]`, use `EdgeVertexTransformer` to project both streams to width `d_h`. Set `num_layers=1` for a single EVT block. The encoder returns the contextualized states in `out.X` and `out.Y`.
59
+
60
+ ```python
61
+ import torch
62
+ from path_augmented_transformer import EdgeVertexTransformer
63
+
64
+ X = torch.tensor([[[1.0], [2.0], [3.0]]])
65
+ Y = torch.zeros(1, 3, 3, 1)
66
+ Y[0, 0, 1, 0] = 1.0 # Directed edge 0 -> 1
67
+ Y[0, 1, 2, 0] = 1.0 # Directed edge 1 -> 2
68
+ node_mask = torch.ones(1, 3, dtype=torch.bool)
69
+
70
+ evt = EdgeVertexTransformer(d_x=1, d_y=1, d_h=8, num_layers=1, num_heads=2)
71
+ out = evt(X, Y, node_mask)
72
+ print(out.X.shape, out.Y.shape) # [1, 3, 8] and [1, 3, 3, 8]
73
+ ```
74
+
75
+ ## Run the StrikeTwice CPU demo
76
+
77
+ ```sh
78
+ python demo.py
79
+ ```
80
+
81
+ The demo builds a four-vertex graph in memory and runs two paths, one of which revisits a vertex. It checks that the vertex states, pair states and scalar predictions agree when using a shared cache or recomputing the graph encoding for each path. It uses randomly initialized weights.
82
+
83
+ ## Tiled inference at 1,024 vertices
84
+
85
+ Use `--paper` to run the full Atlas architecture from the paper's scaling study. It has 778,897 parameters, width 64, two EVT layers per stage, four graph heads and eight path heads. The synthetic workload uses the study's seeds, seven vertex features, six pair features and one batch of 16 paths of length 16. The graph encoder uses the aggressive tiling settings from the paper.
86
+
87
+ ```sh
88
+ # Smoke check of the full model on CPU
89
+ python demo_scaling.py --paper --nodes 64 --device cpu
90
+
91
+ # Full-size synthetic inference workload on a CUDA GPU
92
+ python demo_scaling.py --paper --nodes 1024 --device cuda --warmups 2 --repeats 10
93
+ ```
94
+
95
+ The release measures inference with initialized weights. The forward/backward timing and memory in the paper used activation checkpointing on an A100. The separate trained-checkpoint amortization measurements used their own query workload.
96
+
97
+ ### Examples from observed traceroutes
98
+
99
+ ```sh
100
+ python demo_scaling.py # quick synthetic example
101
+ python demo_scaling.py --device cpu examples/atlas-de-1024.json examples/atlas-us-1024.json
102
+ ```
103
+
104
+ The second command builds one cache per graph and reuses it for four routes. It reports cache construction and path-processing times separately, the size of the stored cache, and the size of one triangular score tensor before and after tiling. With one FP32 head, the score tensor drops from 4 GiB to 32 MiB per tile at the default eight source rows. This is a tensor-size calculation. Use `--device cuda` to also measure the PyTorch allocator's peak on a CUDA GPU.
105
+
106
+ The demo checks that tiled and untiled inference agree on a small graph using the same weights. The opt-in PyTorch implementation tiles triangular attention over source rows and value channels, and cross-stream attention over query rows. Each softmax keeps all valid keys or intermediate vertices. Graph-encoder arithmetic remains cubic in the number of vertices, and the cache remains quadratic.
107
+
108
+ Both JSON fixtures contain 1,024 vertices from public IPv4 traceroutes collected by RIPE Atlas Region Meshes in August 2026. They pool several destinations within each region and retain directed edges between consecutive responding hops. Vertex IDs are local integers. The fixtures contain topology and route segments, and the default demo uses a width-four model for a quick CPU run. Add `--paper` to use the full model on these topologies with zero-filled input channels apart from adjacency. These regional examples are separate from the per-destination latency benchmark in the paper. [RIPE Atlas Region Meshes](https://atlas.ripe.net/docs/tools-and-code/region-meshes/) · [RIPE Atlas terms](https://www.ripe.net/about-us/legal/ripe-atlas-service-terms-and-conditions/)
109
+
110
+ The fixtures record source URLs and SHA-256 digests. To rebuild them, download each archive into `DATE/REGION/` under a local data directory and run `python examples/build_atlas_fixtures.py --raw-root /path/to/data`.
@@ -0,0 +1,124 @@
1
+ Metadata-Version: 2.4
2
+ Name: StrikeTwice
3
+ Version: 0.1.0
4
+ Summary: PyTorch implementation of StrikeTwice and the Edge–Vertex Transformer
5
+ Author: Gwenn Guichaoua, Elodie Laine
6
+ License-Expression: MIT
7
+ Project-URL: Repository, https://github.com/Guichaoua/StrikeTwice
8
+ Project-URL: Documentation, https://striketwice.readthedocs.io/en/latest/
9
+ Requires-Python: >=3.9
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: torch>=2.1
13
+ Dynamic: license-file
14
+
15
+ # StrikeTwice
16
+
17
+ Core PyTorch implementation for *StrikeTwice: Reusable Graph Representations for Path Prediction* by Gwenn Guichaoua and Elodie Laine.
18
+
19
+ The Edge–Vertex Transformer (EVT) encodes vertex and ordered-pair features. StrikeTwice uses an EVT to encode the graph, selects states in path-occurrence order, and applies a second EVT to the selected states. Several paths can share the same graph encoding.
20
+
21
+ ## Installation
22
+
23
+ Use Python 3.9 or newer. Install StrikeTwice and its PyTorch dependency from PyPI.
24
+
25
+ ```sh
26
+ python -m pip install StrikeTwice
27
+ ```
28
+
29
+ To install from a source checkout, run this command from the repository root.
30
+
31
+ ```sh
32
+ python -m pip install .
33
+ ```
34
+
35
+ Import the models from `path_augmented_transformer`.
36
+
37
+ ## Documentation
38
+
39
+ The [documentation on Read the Docs](https://striketwice.readthedocs.io/en/latest/) includes two runnable notebooks and a Python API reference. Documentation builds use CPU by default.
40
+
41
+ The [Task 2 notebook](https://striketwice.readthedocs.io/en/latest/tutorials/striketwice.html#Task-2-benchmark) uses CUDA or Apple Metal (MPS) when available. Set `STRIKETWICE_TASK2_DEVICE` to `cuda`, `mps`, or `cpu` before launching Jupyter to choose a backend explicitly.
42
+
43
+ To build locally, put Pandoc on your PATH and run these commands from the repository root.
44
+
45
+ ```sh
46
+ python -m pip install . -r docs/requirements.txt
47
+ python -m sphinx -W -b html docs docs/_build/html
48
+ ```
49
+
50
+ Open `docs/_build/html/index.html` to browse the result.
51
+
52
+ ## Use EVT on its own
53
+
54
+ ### One EVT block
55
+
56
+ Call `EdgeVertexTransformerLayer` directly on vertex states `X` of shape `[B, n, d_model]` and ordered-pair states `Y` of shape `[B, n, n, d_model]`. The boolean `node_mask` identifies valid vertices. The block runs on the graph alone and returns updated states with the same shapes.
57
+
58
+ ```python
59
+ import torch
60
+ from path_augmented_transformer import EdgeVertexTransformerLayer
61
+
62
+ X = torch.randn(1, 3, 8)
63
+ Y = torch.randn(1, 3, 3, 8)
64
+ node_mask = torch.ones(1, 3, dtype=torch.bool)
65
+
66
+ block = EdgeVertexTransformerLayer(d_model=8, num_heads=2)
67
+ X_next, Y_next = block(X, Y, node_mask)
68
+ ```
69
+
70
+ ### EVT with input projections
71
+
72
+ For raw vertex features `X` of shape `[B, n, d_x]` and ordered-pair features `Y` of shape `[B, n, n, d_y]`, use `EdgeVertexTransformer` to project both streams to width `d_h`. Set `num_layers=1` for a single EVT block. The encoder returns the contextualized states in `out.X` and `out.Y`.
73
+
74
+ ```python
75
+ import torch
76
+ from path_augmented_transformer import EdgeVertexTransformer
77
+
78
+ X = torch.tensor([[[1.0], [2.0], [3.0]]])
79
+ Y = torch.zeros(1, 3, 3, 1)
80
+ Y[0, 0, 1, 0] = 1.0 # Directed edge 0 -> 1
81
+ Y[0, 1, 2, 0] = 1.0 # Directed edge 1 -> 2
82
+ node_mask = torch.ones(1, 3, dtype=torch.bool)
83
+
84
+ evt = EdgeVertexTransformer(d_x=1, d_y=1, d_h=8, num_layers=1, num_heads=2)
85
+ out = evt(X, Y, node_mask)
86
+ print(out.X.shape, out.Y.shape) # [1, 3, 8] and [1, 3, 3, 8]
87
+ ```
88
+
89
+ ## Run the StrikeTwice CPU demo
90
+
91
+ ```sh
92
+ python demo.py
93
+ ```
94
+
95
+ The demo builds a four-vertex graph in memory and runs two paths, one of which revisits a vertex. It checks that the vertex states, pair states and scalar predictions agree when using a shared cache or recomputing the graph encoding for each path. It uses randomly initialized weights.
96
+
97
+ ## Tiled inference at 1,024 vertices
98
+
99
+ Use `--paper` to run the full Atlas architecture from the paper's scaling study. It has 778,897 parameters, width 64, two EVT layers per stage, four graph heads and eight path heads. The synthetic workload uses the study's seeds, seven vertex features, six pair features and one batch of 16 paths of length 16. The graph encoder uses the aggressive tiling settings from the paper.
100
+
101
+ ```sh
102
+ # Smoke check of the full model on CPU
103
+ python demo_scaling.py --paper --nodes 64 --device cpu
104
+
105
+ # Full-size synthetic inference workload on a CUDA GPU
106
+ python demo_scaling.py --paper --nodes 1024 --device cuda --warmups 2 --repeats 10
107
+ ```
108
+
109
+ The release measures inference with initialized weights. The forward/backward timing and memory in the paper used activation checkpointing on an A100. The separate trained-checkpoint amortization measurements used their own query workload.
110
+
111
+ ### Examples from observed traceroutes
112
+
113
+ ```sh
114
+ python demo_scaling.py # quick synthetic example
115
+ python demo_scaling.py --device cpu examples/atlas-de-1024.json examples/atlas-us-1024.json
116
+ ```
117
+
118
+ The second command builds one cache per graph and reuses it for four routes. It reports cache construction and path-processing times separately, the size of the stored cache, and the size of one triangular score tensor before and after tiling. With one FP32 head, the score tensor drops from 4 GiB to 32 MiB per tile at the default eight source rows. This is a tensor-size calculation. Use `--device cuda` to also measure the PyTorch allocator's peak on a CUDA GPU.
119
+
120
+ The demo checks that tiled and untiled inference agree on a small graph using the same weights. The opt-in PyTorch implementation tiles triangular attention over source rows and value channels, and cross-stream attention over query rows. Each softmax keeps all valid keys or intermediate vertices. Graph-encoder arithmetic remains cubic in the number of vertices, and the cache remains quadratic.
121
+
122
+ Both JSON fixtures contain 1,024 vertices from public IPv4 traceroutes collected by RIPE Atlas Region Meshes in August 2026. They pool several destinations within each region and retain directed edges between consecutive responding hops. Vertex IDs are local integers. The fixtures contain topology and route segments, and the default demo uses a width-four model for a quick CPU run. Add `--paper` to use the full model on these topologies with zero-filled input channels apart from adjacency. These regional examples are separate from the per-destination latency benchmark in the paper. [RIPE Atlas Region Meshes](https://atlas.ripe.net/docs/tools-and-code/region-meshes/) · [RIPE Atlas terms](https://www.ripe.net/about-us/legal/ripe-atlas-service-terms-and-conditions/)
123
+
124
+ The fixtures record source URLs and SHA-256 digests. To rebuild them, download each archive into `DATE/REGION/` under a local data directory and run `python examples/build_atlas_fixtures.py --raw-root /path/to/data`.
@@ -0,0 +1,17 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ StrikeTwice.egg-info/PKG-INFO
5
+ StrikeTwice.egg-info/SOURCES.txt
6
+ StrikeTwice.egg-info/dependency_links.txt
7
+ StrikeTwice.egg-info/requires.txt
8
+ StrikeTwice.egg-info/top_level.txt
9
+ path_augmented_transformer/__init__.py
10
+ path_augmented_transformer/atlas_profile.py
11
+ path_augmented_transformer/data_types.py
12
+ path_augmented_transformer/models/__init__.py
13
+ path_augmented_transformer/models/common.py
14
+ path_augmented_transformer/models/edge_vertex_transformer.py
15
+ path_augmented_transformer/models/evt_pool.py
16
+ path_augmented_transformer/models/strike_twice.py
17
+ path_augmented_transformer/resources/task2_reference.pt.gz
@@ -0,0 +1 @@
1
+ torch>=2.1
@@ -0,0 +1 @@
1
+ path_augmented_transformer
@@ -0,0 +1,23 @@
1
+ """Core graph and path encoders for StrikeTwice."""
2
+
3
+ from path_augmented_transformer.data_types import (
4
+ EdgeVertexOutput,
5
+ GraphPathBatch,
6
+ PathEncoderOutput,
7
+ )
8
+ from path_augmented_transformer.models.common import ScalarPathHead
9
+ from path_augmented_transformer.models.edge_vertex_transformer import (
10
+ EdgeVertexTransformer,
11
+ EdgeVertexTransformerLayer,
12
+ )
13
+ from path_augmented_transformer.models.strike_twice import StrikeTwice
14
+
15
+ __all__ = [
16
+ "EdgeVertexOutput",
17
+ "EdgeVertexTransformer",
18
+ "EdgeVertexTransformerLayer",
19
+ "GraphPathBatch",
20
+ "PathEncoderOutput",
21
+ "ScalarPathHead",
22
+ "StrikeTwice",
23
+ ]
@@ -0,0 +1,138 @@
1
+ """StrikeTwice configuration and synthetic workload for the Atlas scale profile."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ import torch
8
+ from torch import Tensor, nn
9
+
10
+ from path_augmented_transformer.data_types import EdgeVertexOutput, GraphPathBatch
11
+ from path_augmented_transformer.models.edge_vertex_transformer import EdgeVertexTransformer
12
+ from path_augmented_transformer.models.strike_twice import StrikeTwice
13
+
14
+
15
+ ATLAS_MODEL_SEED = 20261112
16
+ ATLAS_INPUT_SEED = 20261113
17
+ ATLAS_PARAMETER_COUNT = 778_897
18
+ PATH_CAPACITY = 64
19
+
20
+
21
+ @dataclass
22
+ class AtlasGraphCache(EdgeVertexOutput):
23
+ """Encoded states and the validity mask of one shared graph."""
24
+
25
+ node_mask: Tensor
26
+
27
+
28
+ class AtlasProfile(nn.Module):
29
+ """Full-size two-EVT model with the original Atlas occurrence readout."""
30
+
31
+ def __init__(self) -> None:
32
+ super().__init__()
33
+ width = 64
34
+ self.encoder = StrikeTwice(
35
+ d_x=7,
36
+ d_y=6,
37
+ d_h=width,
38
+ max_path_length=PATH_CAPACITY,
39
+ graph_num_layers=2,
40
+ path_num_layers=2,
41
+ num_heads=4,
42
+ graph_feedforward_dim=128,
43
+ path_feedforward_dim=128,
44
+ graph_triangular_head_config="balanced",
45
+ path_triangular_head_config="balanced",
46
+ )
47
+ # Replace the path stack as in the original Atlas model, which uses
48
+ # eight path heads and four graph heads.
49
+ self.encoder.path_backbone = EdgeVertexTransformer(
50
+ d_x=width + PATH_CAPACITY,
51
+ d_y=width + 2 * PATH_CAPACITY + 2,
52
+ d_h=width,
53
+ num_layers=2,
54
+ num_heads=8,
55
+ feedforward_dim=128,
56
+ triangular_head_config="balanced",
57
+ )
58
+ self.head = nn.Sequential(nn.Linear(width + 1, width), nn.GELU(), nn.Linear(width, 1))
59
+
60
+ def encode_graph(self, X: Tensor, Y: Tensor, node_mask: Tensor) -> AtlasGraphCache:
61
+ """Encode one fixed graph for subsequent batches of query paths."""
62
+
63
+ if X.ndim != 3 or X.shape[0] != 1:
64
+ raise ValueError("Atlas profiling expects one shared graph per request.")
65
+ states = self.encoder.graph_backbone(X, Y, node_mask)
66
+ return AtlasGraphCache(states.X, states.Y, node_mask)
67
+
68
+ def decode_paths(self, cache: AtlasGraphCache, p: Tensor, path_mask: Tensor) -> Tensor:
69
+ """Return the dimensionless corrections for the valid path positions."""
70
+
71
+ query_count = p.shape[0]
72
+ # Each query refers to the same graph. Expand creates views of the
73
+ # cache without allocating one full pair tensor for each query.
74
+ batch = GraphPathBatch(
75
+ X=cache.X.expand(query_count, -1, -1),
76
+ Y=cache.Y.expand(query_count, -1, -1, -1),
77
+ p=p,
78
+ node_mask=cache.node_mask.expand(query_count, -1),
79
+ path_mask=path_mask,
80
+ )
81
+ selected = self.encoder.select_occurrence_graph(EdgeVertexOutput(batch.X, batch.Y), batch)
82
+ nodes = self.encoder.path_backbone(selected.X, selected.Y, path_mask).X
83
+ position = torch.arange(nodes.shape[1], device=nodes.device, dtype=nodes.dtype)
84
+ position = position[None, :, None].expand(query_count, -1, -1) / PATH_CAPACITY
85
+ return self.head(torch.cat((nodes, position), dim=-1)).squeeze(-1)
86
+
87
+ def predict_rtt(
88
+ self, cache: AtlasGraphCache, p: Tensor, path_mask: Tensor, prior: Tensor
89
+ ) -> Tensor:
90
+ """Apply the original conversion from dimensionless correction to RTT in ms."""
91
+
92
+ if prior.shape != p.shape:
93
+ raise ValueError("The prior must have one value per path occurrence.")
94
+ return prior + 10.0 * self.decode_paths(cache, p, path_mask)
95
+
96
+ def forward(self, X: Tensor, Y: Tensor, node_mask: Tensor, p: Tensor, path_mask: Tensor) -> Tensor:
97
+ return self.decode_paths(self.encode_graph(X, Y, node_mask), p, path_mask)
98
+
99
+
100
+ def build_atlas_profile() -> AtlasProfile:
101
+ """Build the 778,897-parameter scale-profile model with initialized weights."""
102
+
103
+ return AtlasProfile()
104
+
105
+
106
+ def make_synthetic_atlas_request(
107
+ n: int, *, k: int | None = None, queries: int | None = None, seed: int = ATLAS_INPUT_SEED
108
+ ) -> dict[str, Tensor]:
109
+ """Generate the synthetic profiling graph and its directed ring paths."""
110
+
111
+ if type(n) is not int or n < 1:
112
+ raise ValueError("The graph must have a positive integer number of vertices.")
113
+ k = min(n, 16) if k is None else k
114
+ queries = min(n, 16) if queries is None else queries
115
+ if type(k) is not int or not 1 <= k <= min(n, PATH_CAPACITY):
116
+ raise ValueError("Path length must be between 1 and the smaller of graph size and 64.")
117
+ if type(queries) is not int or not 1 <= queries <= n:
118
+ raise ValueError("The number of queries must be between 1 and the graph size.")
119
+
120
+ generator = torch.Generator().manual_seed(seed + n)
121
+ X = torch.randn((1, n, 7), generator=generator, dtype=torch.float32)
122
+ Y = torch.randn((1, n, n, 6), generator=generator, dtype=torch.float32)
123
+ adjacency = torch.rand((n, n), generator=generator, dtype=torch.float32) < 0.05
124
+ adjacency.fill_diagonal_(False)
125
+ ring = torch.randperm(n, generator=generator)
126
+ adjacency[ring, ring.roll(-1)] = True
127
+ starts = torch.randperm(n, generator=generator)[:queries]
128
+ p = ring[(starts[:, None] + torch.arange(k)) % n]
129
+ Y[..., 0] = adjacency
130
+
131
+ return {
132
+ "X": X,
133
+ "Y": Y,
134
+ "node_mask": torch.ones((1, n), dtype=torch.bool),
135
+ "p": p,
136
+ "path_mask": torch.ones_like(p, dtype=torch.bool),
137
+ "prior": torch.zeros_like(p, dtype=torch.float32),
138
+ }