StrikeTwice 0.1.0__py3-none-any.whl

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,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
+ }
@@ -0,0 +1,238 @@
1
+ """Typed batches, encoder states, and task-head outputs."""
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Optional, Tuple
5
+
6
+ import torch
7
+ from torch import Tensor
8
+
9
+
10
+ def _require(condition: bool, message: str) -> None:
11
+ if not condition:
12
+ raise ValueError(message)
13
+
14
+
15
+ def gather_path_nodes(X: Tensor, p: Tensor, path_mask: Tensor) -> Tensor:
16
+ """Return the ordered gather ``X o p`` and zero padded path positions.
17
+
18
+ ``p`` may contain any sentinel value at padded positions. Only indices for
19
+ which ``path_mask`` is true are required to belong to ``[0, n)``.
20
+ """
21
+
22
+ _require(X.ndim == 3, "X must have shape [B, n, d_x].")
23
+ _require(p.ndim == 2, "p must have shape [B, k].")
24
+ _require(path_mask.ndim == 2, "path_mask must have shape [B, k].")
25
+ _require(p.shape == path_mask.shape, "p and path_mask must have equal shapes.")
26
+ _require(X.shape[0] == p.shape[0], "X and p must have the same batch size.")
27
+ _require(p.dtype == torch.long, "p must use torch.long indices.")
28
+ _require(path_mask.dtype == torch.bool, "path_mask must be boolean.")
29
+
30
+ n = X.shape[1]
31
+ valid_indices = p[path_mask]
32
+ if valid_indices.numel() > 0:
33
+ _require(bool((valid_indices >= 0).all()), "Valid path indices must be non-negative.")
34
+ _require(bool((valid_indices < n).all()), "A valid path index exceeds n - 1.")
35
+
36
+ safe_p = p.masked_fill(~path_mask, 0)
37
+ gather_index = safe_p.unsqueeze(-1).expand(-1, -1, X.shape[-1])
38
+ gathered = torch.gather(X, dim=1, index=gather_index)
39
+ return gathered.masked_fill(~path_mask.unsqueeze(-1), 0)
40
+
41
+
42
+ def gather_path_pairs(Y: Tensor, p: Tensor, path_mask: Tensor) -> Tensor:
43
+ r"""Return the ordered pair pullback ``Y[p_s, p_t]``.
44
+
45
+ The returned array has shape ``[B, k, k, d_y]``. Padded occurrence
46
+ pairs are exactly zero, and sentinel values in ``p`` are never indexed.
47
+ Repeated path vertices are preserved as distinct occurrence rows.
48
+ """
49
+
50
+ _require(Y.ndim == 4, "Y must have shape [B, n, n, d_y].")
51
+ _require(Y.shape[1] == Y.shape[2], "Y must have square pair axes.")
52
+ _require(p.ndim == 2, "p must have shape [B, k].")
53
+ _require(path_mask.shape == p.shape, "path_mask must match p.")
54
+ _require(Y.shape[0] == p.shape[0], "Y and p must have the same batch size.")
55
+ _require(p.dtype == torch.long, "p must use torch.long indices.")
56
+ _require(path_mask.dtype == torch.bool, "path_mask must be boolean.")
57
+
58
+ batch_size, n, _, _ = Y.shape
59
+ valid_indices = p[path_mask]
60
+ if valid_indices.numel() > 0:
61
+ _require(bool((valid_indices >= 0).all()), "Valid path indices must be non-negative.")
62
+ _require(bool((valid_indices < n).all()), "A valid path index exceeds n - 1.")
63
+
64
+ safe_p = p.masked_fill(~path_mask, 0)
65
+ k = p.shape[1]
66
+ batch = torch.arange(batch_size, device=Y.device).view(batch_size, 1, 1)
67
+ source = safe_p.unsqueeze(2).expand(-1, -1, k)
68
+ target = safe_p.unsqueeze(1).expand(-1, k, -1)
69
+ gathered = Y[batch, source, target]
70
+ pair_mask = path_mask.unsqueeze(2) & path_mask.unsqueeze(1)
71
+ return gathered.masked_fill(~pair_mask.unsqueeze(-1), 0)
72
+
73
+
74
+ def junction_mask_from_path_mask(path_mask: Tensor) -> Tensor:
75
+ """A junction is valid exactly when both adjacent path positions exist."""
76
+
77
+ _require(path_mask.ndim == 2, "path_mask must have shape [B, k].")
78
+ _require(path_mask.dtype == torch.bool, "path_mask must be boolean.")
79
+ return path_mask[:, :-1] & path_mask[:, 1:]
80
+
81
+
82
+ def masked_path_mean(Z: Tensor, path_mask: Tensor) -> Tensor:
83
+ """Compute the exact arithmetic mean over valid path positions."""
84
+
85
+ _require(Z.ndim == 3, "Z must have shape [B, k, d_h].")
86
+ _require(path_mask.shape == Z.shape[:2], "path_mask must match the first two axes of Z.")
87
+ _require(path_mask.dtype == torch.bool, "path_mask must be boolean.")
88
+ lengths = path_mask.sum(dim=1)
89
+ _require(bool((lengths > 0).all()), "Every example must contain at least one valid path token.")
90
+ weights = path_mask.unsqueeze(-1).to(dtype=Z.dtype)
91
+ return (Z * weights).sum(dim=1) / lengths.unsqueeze(-1).to(dtype=Z.dtype)
92
+
93
+
94
+ @dataclass(frozen=True)
95
+ class GraphPathBatch:
96
+ """A padded batch of graph/path examples.
97
+
98
+ Shapes follow the paper's ``(X, Y, P)`` convention. In code, the path is
99
+ named ``p`` and padded positions conventionally contain ``-1``.
100
+ """
101
+
102
+ X: Tensor # [B, n, d_x]
103
+ Y: Tensor # [B, n, n, d_y]
104
+ p: Tensor # [B, k]
105
+ node_mask: Tensor # [B, n]
106
+ path_mask: Tensor # [B, k]
107
+ # Optional batching metadata. Equal values identify repeated query rows of
108
+ # the same immutable graph, allowing graph encoders to run only once.
109
+ graph_index: Optional[Tensor] = None # [B]
110
+
111
+ def __post_init__(self) -> None:
112
+ self.validate()
113
+
114
+ @property
115
+ def shape(self) -> Tuple[int, int, int]:
116
+ return self.X.shape[0], self.X.shape[1], self.p.shape[1]
117
+
118
+ @property
119
+ def path_lengths(self) -> Tensor:
120
+ return self.path_mask.sum(dim=1)
121
+
122
+ @property
123
+ def junction_mask(self) -> Tensor:
124
+ return junction_mask_from_path_mask(self.path_mask)
125
+
126
+ def gather_path_nodes(self) -> Tensor:
127
+ return gather_path_nodes(self.X, self.p, self.path_mask)
128
+
129
+ def gather_path_pairs(self) -> Tensor:
130
+ return gather_path_pairs(self.Y, self.p, self.path_mask)
131
+
132
+ def validate(self) -> None:
133
+ _require(self.X.ndim == 3, "X must have shape [B, n, d_x].")
134
+ _require(self.Y.ndim == 4, "Y must have shape [B, n, n, d_y].")
135
+ _require(self.p.ndim == 2, "p must have shape [B, k].")
136
+ _require(self.node_mask.ndim == 2, "node_mask must have shape [B, n].")
137
+ _require(self.path_mask.ndim == 2, "path_mask must have shape [B, k].")
138
+
139
+ batch_size, n, _ = self.X.shape
140
+ _require(self.Y.shape[:3] == (batch_size, n, n), "Y axes must be [B, n, n, d_y].")
141
+ _require(self.p.shape[0] == batch_size, "p must have the same batch size as X.")
142
+ _require(self.node_mask.shape == (batch_size, n), "node_mask must have shape [B, n].")
143
+ _require(self.path_mask.shape == self.p.shape, "path_mask must have the same shape as p.")
144
+ _require(self.p.dtype == torch.long, "p must use torch.long indices.")
145
+ _require(self.node_mask.dtype == torch.bool, "node_mask must be boolean.")
146
+ _require(self.path_mask.dtype == torch.bool, "path_mask must be boolean.")
147
+ if self.graph_index is not None:
148
+ _require(
149
+ self.graph_index.shape == (batch_size,),
150
+ "graph_index must have shape [B].",
151
+ )
152
+ _require(
153
+ self.graph_index.dtype == torch.long,
154
+ "graph_index must use torch.long indices.",
155
+ )
156
+ _require(
157
+ self.graph_index.device == self.X.device,
158
+ "graph_index must be on the same device as X.",
159
+ )
160
+ _require(self.X.is_floating_point(), "X must be floating point.")
161
+ _require(self.Y.is_floating_point(), "Y must be floating point.")
162
+ _require(bool((self.path_lengths > 0).all()), "Every example needs at least one path token.")
163
+
164
+ # Batches use prefix masks: valid positions followed only by padding.
165
+ if self.path_mask.shape[1] > 1:
166
+ has_hole = self.path_mask[:, 1:] & ~self.path_mask[:, :-1]
167
+ _require(not bool(has_hole.any()), "path_mask must be left-aligned without holes.")
168
+
169
+ # This also validates the numerical range of every unmasked path index.
170
+ safe_p = self.p.masked_fill(~self.path_mask, 0)
171
+ gather_path_nodes(self.X, self.p, self.path_mask)
172
+ selected_nodes_exist = torch.gather(self.node_mask, dim=1, index=safe_p)
173
+ _require(
174
+ bool((selected_nodes_exist | ~self.path_mask).all()),
175
+ "A valid path position references a padded graph node.",
176
+ )
177
+
178
+ def to(self, *args: object, **kwargs: object) -> "GraphPathBatch":
179
+ """Return a batch with all tensors moved using ``Tensor.to``."""
180
+
181
+ moved_X = self.X.to(*args, **kwargs)
182
+ return GraphPathBatch(
183
+ X=moved_X,
184
+ Y=self.Y.to(*args, **kwargs),
185
+ # A requested floating-point dtype applies only to feature arrays.
186
+ p=self.p.to(device=moved_X.device),
187
+ node_mask=self.node_mask.to(device=moved_X.device),
188
+ path_mask=self.path_mask.to(device=moved_X.device),
189
+ graph_index=(
190
+ None
191
+ if self.graph_index is None
192
+ else self.graph_index.to(device=moved_X.device)
193
+ ),
194
+ )
195
+
196
+
197
+ @dataclass
198
+ class EdgeVertexOutput:
199
+ r"""Contextualized graph states returned by the EVT backbone."""
200
+
201
+ X: Tensor # [B, n, d_h]
202
+ Y: Tensor # [B, n, n, d_h]
203
+
204
+
205
+ @dataclass
206
+ class PathEncoderOutput:
207
+ r"""Typed encoder output corresponding to :math:`(X',Y',Z)` or
208
+ :math:`(X',Y',Z,R)`.
209
+
210
+ For the path-only controls, ``X`` is the shared pointwise projection of
211
+ every input node and ``Y`` is passed through unchanged. Their path stream
212
+ ``Z`` still reads only the gathered nodes ``X o P``. EVT encoders replace
213
+ ``X`` and ``Y`` by contextualized graph states. Strike Twice additionally
214
+ exposes the second-strike occurrence-pair states ``R`` so a structured
215
+ task head can use them without changing the graph-level output fields.
216
+ """
217
+
218
+ X: Tensor # [B, n, d_x_prime]
219
+ Y: Tensor # [B, n, n, d_y_prime]
220
+ Z: Tensor # [B, k, d_h]
221
+ R: Optional[Tensor] = None # [B, k, k, d_r], occurrence-pair states
222
+
223
+
224
+ @dataclass
225
+ class ScalarTaskOutput:
226
+ """Output of a scalar task head; ``u`` is derived from encoder tokens."""
227
+
228
+ u: Tensor # [B, d_h]
229
+ prediction: Tensor # [B, d_scalar]
230
+
231
+
232
+ @dataclass
233
+ class StructuredTaskOutput:
234
+ """Output of a task head aligned with path positions and junctions."""
235
+
236
+ J: Tensor # [B, k - 1, d_h]
237
+ node_logits: Tensor # [B, k, d_node]
238
+ junction_logits: Tensor # [B, k - 1, d_junction]
@@ -0,0 +1 @@
1
+ """PyTorch implementations of EVT and StrikeTwice."""
@@ -0,0 +1,149 @@
1
+ """Shared projections and task heads for path encoders."""
2
+
3
+ from typing import Optional
4
+
5
+ import torch
6
+ from torch import Tensor, nn
7
+
8
+ from path_augmented_transformer.data_types import (
9
+ PathEncoderOutput,
10
+ ScalarTaskOutput,
11
+ StructuredTaskOutput,
12
+ junction_mask_from_path_mask,
13
+ masked_path_mean,
14
+ )
15
+
16
+
17
+ def attention_softmax(scores: Tensor, dim: int = -1) -> Tensor:
18
+ """Apply a stable softmax without discarding float64 precision.
19
+
20
+ Half-precision scores are promoted to float32 for numerical stability;
21
+ float32 and float64 inputs retain their native accumulation precision.
22
+ """
23
+
24
+ compute_dtype = (
25
+ scores.dtype if scores.dtype in {torch.float32, torch.float64}
26
+ else torch.float32
27
+ )
28
+ return torch.softmax(scores.to(compute_dtype), dim=dim).to(scores.dtype)
29
+
30
+
31
+ def make_projection(d_in: int, d_out: int, kind: str) -> nn.Module:
32
+ r"""Build the pointwise map :math:`\phi_X`."""
33
+
34
+ if kind == "identity":
35
+ if d_in != d_out:
36
+ raise ValueError("identity projection requires d_x == d_h.")
37
+ return nn.Identity()
38
+ if kind == "linear":
39
+ return nn.Linear(d_in, d_out)
40
+ if kind == "mlp":
41
+ return nn.Sequential(
42
+ nn.Linear(d_in, d_out),
43
+ nn.GELU(),
44
+ nn.Linear(d_out, d_out),
45
+ )
46
+ raise ValueError("projection must be one of: 'identity', 'linear', 'mlp'.")
47
+
48
+
49
+ def make_mlp(d_in: int, d_hidden: int, d_out: int, dropout: float) -> nn.Sequential:
50
+ return nn.Sequential(
51
+ nn.Linear(d_in, d_hidden),
52
+ nn.GELU(),
53
+ nn.Dropout(dropout),
54
+ nn.Linear(d_hidden, d_out),
55
+ )
56
+
57
+
58
+ class JunctionTokenBuilder(nn.Module):
59
+ """Derive final path-junction tokens from adjacent occurrence tokens.
60
+
61
+ These path-only models have no pair stream, so this implements
62
+ ``J_t = phi_J(Z_t, Z_{t+1}, 0)`` with the zero argument omitted.
63
+ """
64
+
65
+ def __init__(self, d_h: int, dropout: float = 0.0) -> None:
66
+ super().__init__()
67
+ self.network = make_mlp(2 * d_h, d_h, d_h, dropout)
68
+
69
+ def forward(self, Z: Tensor, path_mask: Tensor) -> Tensor:
70
+ if Z.shape[1] < 2:
71
+ return Z.new_zeros((Z.shape[0], 0, Z.shape[2]))
72
+ J = self.network(torch.cat((Z[:, :-1], Z[:, 1:]), dim=-1))
73
+ junction_mask = junction_mask_from_path_mask(path_mask)
74
+ return J.masked_fill(~junction_mask.unsqueeze(-1), 0)
75
+
76
+
77
+ class ScalarPathHead(nn.Module):
78
+ """Mean-pool encoder tokens and predict a scalar or short vector."""
79
+
80
+ def __init__(
81
+ self,
82
+ d_h: int,
83
+ output_dim: int = 1,
84
+ hidden_dim: Optional[int] = None,
85
+ dropout: float = 0.0,
86
+ ) -> None:
87
+ super().__init__()
88
+ d_hidden = d_h if hidden_dim is None else hidden_dim
89
+ self.network = make_mlp(d_h, d_hidden, output_dim, dropout)
90
+
91
+ def forward(self, encoding: PathEncoderOutput, path_mask: Tensor) -> ScalarTaskOutput:
92
+ """Predict from the mean of the unmasked path vertex states."""
93
+
94
+ u = masked_path_mean(encoding.Z, path_mask)
95
+ return ScalarTaskOutput(u=u, prediction=self.network(u))
96
+
97
+
98
+ class StructuredPathHead(nn.Module):
99
+ """Build optional junction tokens and make aligned predictions.
100
+
101
+ Path-only encoders derive ``J_t`` from adjacent occurrence tokens. An
102
+ encoder such as Strike Twice may instead expose a complete occurrence-pair
103
+ array ``R``; in that case ``J_t = R[t,t+1]`` is used directly.
104
+ """
105
+
106
+ def __init__(
107
+ self,
108
+ d_h: int,
109
+ node_output_dim: int = 1,
110
+ junction_output_dim: int = 1,
111
+ hidden_dim: Optional[int] = None,
112
+ dropout: float = 0.0,
113
+ ) -> None:
114
+ super().__init__()
115
+ d_hidden = d_h if hidden_dim is None else hidden_dim
116
+ self.junction_builder = JunctionTokenBuilder(d_h=d_h, dropout=dropout)
117
+ self.node_head = make_mlp(d_h, d_hidden, node_output_dim, dropout)
118
+ self.junction_head = make_mlp(d_h, d_hidden, junction_output_dim, dropout)
119
+
120
+ def forward(
121
+ self,
122
+ encoding: PathEncoderOutput,
123
+ path_mask: Tensor,
124
+ ) -> StructuredTaskOutput:
125
+ if encoding.R is None:
126
+ J = self.junction_builder(encoding.Z, path_mask)
127
+ else:
128
+ if encoding.R.ndim != 4:
129
+ raise ValueError("R must have shape [B, k, k, d_h].")
130
+ batch_size, path_length, _, d_h = encoding.R.shape
131
+ if encoding.R.shape[:3] != (batch_size, path_length, path_length):
132
+ raise ValueError("R must have shape [B, k, k, d_h].")
133
+ if path_length != encoding.Z.shape[1] or d_h != encoding.Z.shape[2]:
134
+ raise ValueError("R and Z must use the same path length and hidden width.")
135
+ positions = torch.arange(max(0, path_length - 1), device=encoding.R.device)
136
+ J = encoding.R[:, positions, positions + 1]
137
+ junction_mask = junction_mask_from_path_mask(path_mask)
138
+ J = J.masked_fill(~junction_mask.unsqueeze(-1), 0)
139
+ node_logits = self.node_head(encoding.Z)
140
+ junction_logits = self.junction_head(J)
141
+
142
+ node_logits = node_logits.masked_fill(~path_mask.unsqueeze(-1), 0)
143
+ junction_mask = junction_mask_from_path_mask(path_mask)
144
+ junction_logits = junction_logits.masked_fill(~junction_mask.unsqueeze(-1), 0)
145
+ return StructuredTaskOutput(
146
+ J=J,
147
+ node_logits=node_logits,
148
+ junction_logits=junction_logits,
149
+ )