ho22joshua Claude Opus 5.5 commited on
Commit
f43b1e5
·
1 Parent(s): 2f04f23

feat(transformer): type embedding instead of positions, pre-norm, ONNX export

Browse files

Objects are stored by type, so the position embedding mostly relearned the
object type and made the output depend on object order. Tokens are now a
linear map of the kinematics (phi as cos/sin) plus a node-type embedding;
model.max_seq_len is gone. The transformer exports to ONNX with tokens and
token_mask inputs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

configs/gamgam_transformer.yaml CHANGED
@@ -77,7 +77,6 @@ model:
77
  n_heads: 4
78
  ffn_size: 256
79
  dropout: 0.1
80
- max_seq_len: 64
81
 
82
  task:
83
  name: multiclass
 
77
  n_heads: 4
78
  ffn_size: 256
79
  dropout: 0.1
 
80
 
81
  task:
82
  name: multiclass
docs/design.md CHANGED
@@ -33,6 +33,15 @@ with features `[deta, dphi, dR]`. These conventions, the seven node columns,
33
  the MLP layout and the parameter names are those of the original ROOT-GNN, so
34
  the pretrained checkpoints in `Pretrained_GNN/` load without conversion.
35
 
 
 
 
 
 
 
 
 
 
36
  The loss is a weighted mean per class present in the batch, averaged over
37
  those classes, which balances the classes without explicit class weights.
38
  Metrics (accuracy, one-vs-rest AUC averaged over classes, macro precision,
 
33
  the MLP layout and the parameter names are those of the original ROOT-GNN, so
34
  the pretrained checkpoints in `Pretrained_GNN/` load without conversion.
35
 
36
+ A batch of the transformer holds each event's objects as tokens
37
+ `[events, objects, 7]`, zero-padded to the largest event of the batch, with
38
+ a mask of real objects. A token is a linear map of the kinematic columns
39
+ (`phi` as its cosine and sine) plus a learned embedding of `node_type`. The
40
+ objects are stored by type (jets, electrons, muons, photons, MET), so a
41
+ position embedding would mostly relearn the type; without one the output
42
+ does not depend on object order, as with the edge network. A pre-norm
43
+ encoder is followed by a mean over real objects and a linear classifier.
44
+
45
  The loss is a weighted mean per class present in the batch, averaged over
46
  those classes, which balances the classes without explicit class weights.
47
  Metrics (accuracy, one-vs-rest AUC averaged over classes, macro precision,
docs/usage.md CHANGED
@@ -50,7 +50,7 @@ adds scores to a copy of a ROOT tree.
50
  | --- | --- |
51
  | `configs/gamgam.yaml` | ATLAS Open Data GamGam, 5 Higgs production modes, from scratch (the paper baseline and main benchmark) |
52
  | `configs/gamgam_finetune.yaml` | the same task fine-tuned from the pretrained multiclass model |
53
- | `configs/gamgam_transformer.yaml` | the same task with a transformer |
54
  | `configs/tth_cp_even_odd.yaml` | CP-even versus CP-odd ttH (Delphes, binary; local files) |
55
  | `configs/delphes_pretraining.yaml` | 12-class pretraining on the Delphes samples |
56
 
@@ -58,7 +58,7 @@ Each file documents its keys; `src/gnn4colliders/config.py` lists every key
58
  with its default. Common overrides:
59
 
60
  ```bash
61
- train.fast=true # torch.compile + CUDA graphs + bfloat16 + TF32
62
  train.seed=3 data.seed=3 # initialization and shuffling seeds
63
  train.max_epochs=100
64
  model.pretrained=Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_71.pt
 
50
  | --- | --- |
51
  | `configs/gamgam.yaml` | ATLAS Open Data GamGam, 5 Higgs production modes, from scratch (the paper baseline and main benchmark) |
52
  | `configs/gamgam_finetune.yaml` | the same task fine-tuned from the pretrained multiclass model |
53
+ | `configs/gamgam_transformer.yaml` | the same task with a transformer over the objects (same event cache) |
54
  | `configs/tth_cp_even_odd.yaml` | CP-even versus CP-odd ttH (Delphes, binary; local files) |
55
  | `configs/delphes_pretraining.yaml` | 12-class pretraining on the Delphes samples |
56
 
 
58
  with its default. Common overrides:
59
 
60
  ```bash
61
+ train.fast=true # torch.compile + CUDA graphs (edge network) + bfloat16 + TF32
62
  train.seed=3 data.seed=3 # initialization and shuffling seeds
63
  train.max_epochs=100
64
  model.pretrained=Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_71.pt
src/gnn4colliders/cli.py CHANGED
@@ -7,7 +7,7 @@ Commands:
7
  and ``config.yaml`` to ``run_dir``. Launch with ``torchrun`` for DDP.
8
  * ``evaluate``: metrics of ``checkpoint`` on ``split``, written as JSON.
9
  * ``predict``: per-event scores of ``checkpoint`` on ``split``, as ``.npz``.
10
- * ``export``: ONNX model of ``checkpoint`` (edge networks).
11
  """
12
 
13
  from __future__ import annotations
@@ -84,6 +84,7 @@ def make_model(config: Config, events: PackedEvents, *, load_pretrained: bool =
84
  return build_model(
85
  config.model,
86
  num_features=events.num_features,
 
87
  num_global_features=events.num_global_features,
88
  load_pretrained=load_pretrained,
89
  )
 
7
  and ``config.yaml`` to ``run_dir``. Launch with ``torchrun`` for DDP.
8
  * ``evaluate``: metrics of ``checkpoint`` on ``split``, written as JSON.
9
  * ``predict``: per-event scores of ``checkpoint`` on ``split``, as ``.npz``.
10
+ * ``export``: ONNX model of ``checkpoint``.
11
  """
12
 
13
  from __future__ import annotations
 
84
  return build_model(
85
  config.model,
86
  num_features=events.num_features,
87
+ num_node_types=len(config.data.object_types),
88
  num_global_features=events.num_global_features,
89
  load_pretrained=load_pretrained,
90
  )
src/gnn4colliders/config.py CHANGED
@@ -74,8 +74,8 @@ class ModelConfig:
74
  freeze_backbone: bool = False
75
  # Transformer only.
76
  n_heads: int = 4
 
77
  ffn_size: int | None = None
78
- max_seq_len: int = 256
79
 
80
 
81
  @dataclass
@@ -108,6 +108,7 @@ class TrainConfig:
108
  #: Continue from this checkpoint.
109
  resume: str | None = None
110
  #: Shorthand for compile, cuda_graphs, bfloat16 and TF32 together.
 
111
  fast: bool = False
112
  compile: bool = False
113
  cuda_graphs: bool = False
 
74
  freeze_backbone: bool = False
75
  # Transformer only.
76
  n_heads: int = 4
77
+ #: Feed-forward width (default ``4 * hid_size``).
78
  ffn_size: int | None = None
 
79
 
80
 
81
  @dataclass
 
108
  #: Continue from this checkpoint.
109
  resume: str | None = None
110
  #: Shorthand for compile, cuda_graphs, bfloat16 and TF32 together.
111
+ #: CUDA graphs apply to edge networks; transformer steps run uncaptured.
112
  fast: bool = False
113
  compile: bool = False
114
  cuda_graphs: bool = False
src/gnn4colliders/export.py CHANGED
@@ -1,32 +1,41 @@
1
- """ONNX export of the edge network, checked with ONNX Runtime.
2
-
3
- The exported graph takes plain tensors: ``node_features``, ``edge_features``,
4
- ``edge_src``, ``edge_dst``, ``node_batch`` and ``global_features`` (for
5
- models without global features, the per-graph node count as one column).
6
- Requires the ``onnx`` extra.
 
 
7
  """
8
 
9
  from __future__ import annotations
10
 
11
  import json
12
  from pathlib import Path
 
13
  from typing import Any
14
 
15
  import torch
16
  from torch import nn
17
 
18
  from .graphs import GraphBatch
19
- from .models import EdgeNetwork, FineTunedEdgeNetwork
 
20
 
21
  OPSET = 17
22
- INPUT_NAMES = (
23
- "node_features",
24
- "edge_features",
25
- "edge_src",
26
- "edge_dst",
27
- "node_batch",
28
- "global_features",
29
- )
 
 
 
 
 
30
 
31
 
32
  def _membership(groups: torch.Tensor, count: int, values: torch.Tensor) -> torch.Tensor:
@@ -59,7 +68,7 @@ class ExportAdapter(nn.Module):
59
  elif isinstance(model, EdgeNetwork):
60
  self.backbone = model
61
  else:
62
- raise TypeError("ONNX export supports the edge network models")
63
  self.classifier = model.classifier
64
 
65
  def forward(
@@ -101,7 +110,30 @@ class ExportAdapter(nn.Module):
101
  return self.classifier(net.global_decoder(global_h))
102
 
103
 
104
- def export_inputs(batch: GraphBatch) -> tuple[torch.Tensor, ...]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  graph = batch.graph
106
  global_features = batch.global_features
107
  if global_features is None:
@@ -118,7 +150,7 @@ def export_inputs(batch: GraphBatch) -> tuple[torch.Tensor, ...]:
118
 
119
  def export_onnx(
120
  model: nn.Module,
121
- example: GraphBatch,
122
  path: str | Path,
123
  *,
124
  metadata: dict[str, Any] | None = None,
@@ -134,24 +166,24 @@ def export_onnx(
134
  ) from error
135
  path = Path(path)
136
  path.parent.mkdir(parents=True, exist_ok=True)
137
- adapter = ExportAdapter(model.cpu()).eval()
 
 
 
 
 
138
  inputs = export_inputs(example.to("cpu"))
139
- nodes, edges = {0: "nodes"}, {0: "edges"}
140
  torch.onnx.export(
141
  adapter,
142
  inputs,
143
  str(path),
144
- input_names=list(INPUT_NAMES),
145
  output_names=["logits"],
146
  opset_version=OPSET,
147
  dynamic_axes={
148
- "node_features": nodes,
149
- "edge_features": edges,
150
- "edge_src": edges,
151
- "edge_dst": edges,
152
- "node_batch": nodes,
153
- "global_features": {0: "graphs"},
154
- "logits": {0: "graphs"},
155
  },
156
  # The TorchScript exporter keeps the dynamic axes and needs no
157
  # onnxscript dependency.
@@ -161,14 +193,14 @@ def export_onnx(
161
  session = onnxruntime.InferenceSession(
162
  str(path), providers=["CPUExecutionProvider"]
163
  )
164
- feeds = {name: tensor.numpy() for name, tensor in zip(INPUT_NAMES, inputs)}
165
  with torch.inference_mode():
166
  expected = adapter(*inputs)
167
  actual = torch.from_numpy(session.run(["logits"], feeds)[0])
168
  torch.testing.assert_close(actual, expected, rtol=1e-4, atol=1e-5)
169
  info = {
170
  "opset": OPSET,
171
- "inputs": list(INPUT_NAMES),
172
  "output": "logits",
173
  **(metadata or {}),
174
  }
 
1
+ """ONNX export, checked with ONNX Runtime.
2
+
3
+ The exported graph takes plain tensors. For edge networks: ``node_features``,
4
+ ``edge_features``, ``edge_src``, ``edge_dst``, ``node_batch`` and
5
+ ``global_features`` (for models without global features, the per-graph node
6
+ count as one column). For the transformer: ``tokens`` ``[events, objects,
7
+ 7]``, ``token_mask`` (true for real objects) and, if the model has them,
8
+ ``global_features``. Requires the ``onnx`` extra.
9
  """
10
 
11
  from __future__ import annotations
12
 
13
  import json
14
  from pathlib import Path
15
+ from types import SimpleNamespace
16
  from typing import Any
17
 
18
  import torch
19
  from torch import nn
20
 
21
  from .graphs import GraphBatch
22
+ from .models import EdgeNetwork, FineTunedEdgeNetwork, TransformerClassifier
23
+ from .sequences import SequenceBatch
24
 
25
  OPSET = 17
26
+ GRAPH_INPUTS = {
27
+ "node_features": {0: "nodes"},
28
+ "edge_features": {0: "edges"},
29
+ "edge_src": {0: "edges"},
30
+ "edge_dst": {0: "edges"},
31
+ "node_batch": {0: "nodes"},
32
+ "global_features": {0: "graphs"},
33
+ }
34
+ SEQUENCE_INPUTS = {
35
+ "tokens": {0: "events", 1: "objects"},
36
+ "token_mask": {0: "events", 1: "objects"},
37
+ "global_features": {0: "events"},
38
+ }
39
 
40
 
41
  def _membership(groups: torch.Tensor, count: int, values: torch.Tensor) -> torch.Tensor:
 
68
  elif isinstance(model, EdgeNetwork):
69
  self.backbone = model
70
  else:
71
+ raise TypeError("ONNX export supports the edge network and transformer")
72
  self.classifier = model.classifier
73
 
74
  def forward(
 
110
  return self.classifier(net.global_decoder(global_h))
111
 
112
 
113
+ class SequenceExportAdapter(nn.Module):
114
+ """The transformer's forward pass on plain tensors."""
115
+
116
+ def __init__(self, model: TransformerClassifier) -> None:
117
+ super().__init__()
118
+ self.model = model
119
+
120
+ def forward(
121
+ self,
122
+ tokens: torch.Tensor,
123
+ token_mask: torch.Tensor,
124
+ global_features: torch.Tensor | None = None,
125
+ ) -> torch.Tensor:
126
+ batch = SimpleNamespace(
127
+ tokens=tokens, token_mask=token_mask, global_features=global_features
128
+ )
129
+ return self.model(batch)
130
+
131
+
132
+ def export_inputs(batch: GraphBatch | SequenceBatch) -> tuple[torch.Tensor, ...]:
133
+ if isinstance(batch, SequenceBatch):
134
+ if batch.global_features is None:
135
+ return batch.tokens, batch.token_mask
136
+ return batch.tokens, batch.token_mask, batch.global_features
137
  graph = batch.graph
138
  global_features = batch.global_features
139
  if global_features is None:
 
150
 
151
  def export_onnx(
152
  model: nn.Module,
153
+ example: GraphBatch | SequenceBatch,
154
  path: str | Path,
155
  *,
156
  metadata: dict[str, Any] | None = None,
 
166
  ) from error
167
  path = Path(path)
168
  path.parent.mkdir(parents=True, exist_ok=True)
169
+ model = model.cpu()
170
+ if isinstance(model, TransformerClassifier):
171
+ adapter, axes = SequenceExportAdapter(model), SEQUENCE_INPUTS
172
+ else:
173
+ adapter, axes = ExportAdapter(model), GRAPH_INPUTS
174
+ adapter.eval()
175
  inputs = export_inputs(example.to("cpu"))
176
+ names = list(axes)[: len(inputs)]
177
  torch.onnx.export(
178
  adapter,
179
  inputs,
180
  str(path),
181
+ input_names=names,
182
  output_names=["logits"],
183
  opset_version=OPSET,
184
  dynamic_axes={
185
+ **{name: axes[name] for name in names},
186
+ "logits": {0: axes[names[-1]][0]},
 
 
 
 
 
187
  },
188
  # The TorchScript exporter keeps the dynamic axes and needs no
189
  # onnxscript dependency.
 
193
  session = onnxruntime.InferenceSession(
194
  str(path), providers=["CPUExecutionProvider"]
195
  )
196
+ feeds = {name: tensor.numpy() for name, tensor in zip(names, inputs)}
197
  with torch.inference_mode():
198
  expected = adapter(*inputs)
199
  actual = torch.from_numpy(session.run(["logits"], feeds)[0])
200
  torch.testing.assert_close(actual, expected, rtol=1e-4, atol=1e-5)
201
  info = {
202
  "opset": OPSET,
203
+ "inputs": names,
204
  "output": "logits",
205
  **(metadata or {}),
206
  }
src/gnn4colliders/models.py CHANGED
@@ -12,11 +12,15 @@ from typing import TYPE_CHECKING, Any
12
  import torch
13
  from torch import nn
14
 
 
15
  from .graphs import EDGE_FEATURE_NAMES, TensorGraph
16
 
17
  if TYPE_CHECKING:
18
  from .config import ModelConfig
19
 
 
 
 
20
 
21
  def make_mlp(
22
  in_size: int, hidden_size: int, out_size: int, n_layers: int, dropout: float = 0.0
@@ -165,29 +169,37 @@ class FineTunedEdgeNetwork(nn.Module):
165
 
166
 
167
  class TransformerClassifier(nn.Module):
168
- """Transformer encoder over object tokens, mean-pooled over real objects."""
 
 
 
 
 
 
169
 
170
  def __init__(
171
  self,
172
  input_size: int,
173
  out_size: int,
 
174
  hid_size: int = 64,
175
  n_layers: int = 2,
176
  n_heads: int = 4,
177
  ffn_size: int | None = None,
178
  dropout: float = 0.0,
179
- max_seq_len: int = 256,
180
  global_size: int = 0,
181
  ) -> None:
182
  super().__init__()
 
183
  self.token_encoder = nn.Linear(input_size, hid_size)
184
- self.position_embedding = nn.Parameter(torch.zeros(1, max_seq_len, hid_size))
185
  layer = nn.TransformerEncoderLayer(
186
  d_model=hid_size,
187
  nhead=n_heads,
188
  dim_feedforward=ffn_size or 4 * hid_size,
189
  dropout=dropout,
190
  batch_first=True,
 
191
  )
192
  self.encoder = nn.TransformerEncoder(
193
  layer, num_layers=n_layers, enable_nested_tensor=False
@@ -196,14 +208,25 @@ class TransformerClassifier(nn.Module):
196
  self.global_encoder = nn.Linear(global_size, hid_size) if global_size else None
197
  self.classifier = nn.Linear(hid_size, out_size)
198
 
199
- def forward(self, batch: Any) -> torch.Tensor:
200
- tokens, mask = batch.tokens, batch.token_mask
201
- if tokens.shape[1] > self.position_embedding.shape[1]:
202
- raise ValueError("an event has more objects than model.max_seq_len")
203
- encoded = (
204
- self.token_encoder(tokens) + self.position_embedding[:, : tokens.shape[1]]
 
 
 
 
 
205
  )
206
- encoded = self.norm(self.encoder(encoded, src_key_padding_mask=~mask))
 
 
 
 
 
 
207
  counts = mask.sum(dim=1, keepdim=True).clamp_min(1)
208
  pooled = (encoded * mask.unsqueeze(-1)).sum(dim=1) / counts
209
  if self.global_encoder is not None:
@@ -237,6 +260,7 @@ def build_model(
237
  config: ModelConfig,
238
  *,
239
  num_features: int,
 
240
  num_global_features: int = 0,
241
  load_pretrained: bool = True,
242
  ) -> nn.Module:
@@ -251,12 +275,12 @@ def build_model(
251
  return TransformerClassifier(
252
  input_size=num_features,
253
  out_size=config.out_size,
 
254
  hid_size=config.hid_size,
255
  n_layers=config.n_layers,
256
  n_heads=config.n_heads,
257
  ffn_size=config.ffn_size,
258
  dropout=config.dropout,
259
- max_seq_len=config.max_seq_len,
260
  global_size=num_global_features,
261
  )
262
  if config.name != "edge_network":
 
12
  import torch
13
  from torch import nn
14
 
15
+ from .data import NODE_FEATURE_NAMES
16
  from .graphs import EDGE_FEATURE_NAMES, TensorGraph
17
 
18
  if TYPE_CHECKING:
19
  from .config import ModelConfig
20
 
21
+ PHI = NODE_FEATURE_NAMES.index("phi")
22
+ NODE_TYPE = NODE_FEATURE_NAMES.index("node_type")
23
+
24
 
25
  def make_mlp(
26
  in_size: int, hidden_size: int, out_size: int, n_layers: int, dropout: float = 0.0
 
169
 
170
 
171
  class TransformerClassifier(nn.Module):
172
+ """Transformer encoder over the objects of an event, mean-pooled.
173
+
174
+ The objects of an event are a set: a token is a linear map of the object's
175
+ kinematic columns (``phi`` as its cosine and sine) plus a learned
176
+ embedding of its ``node_type``. There is no position embedding, so the
177
+ output does not depend on the order of the objects.
178
+ """
179
 
180
  def __init__(
181
  self,
182
  input_size: int,
183
  out_size: int,
184
+ num_node_types: int,
185
  hid_size: int = 64,
186
  n_layers: int = 2,
187
  n_heads: int = 4,
188
  ffn_size: int | None = None,
189
  dropout: float = 0.0,
 
190
  global_size: int = 0,
191
  ) -> None:
192
  super().__init__()
193
+ # Minus the node type column, plus the second phi column.
194
  self.token_encoder = nn.Linear(input_size, hid_size)
195
+ self.type_embedding = nn.Embedding(num_node_types, hid_size)
196
  layer = nn.TransformerEncoderLayer(
197
  d_model=hid_size,
198
  nhead=n_heads,
199
  dim_feedforward=ffn_size or 4 * hid_size,
200
  dropout=dropout,
201
  batch_first=True,
202
+ norm_first=True,
203
  )
204
  self.encoder = nn.TransformerEncoder(
205
  layer, num_layers=n_layers, enable_nested_tensor=False
 
208
  self.global_encoder = nn.Linear(global_size, hid_size) if global_size else None
209
  self.classifier = nn.Linear(hid_size, out_size)
210
 
211
+ def embed(self, tokens: torch.Tensor) -> torch.Tensor:
212
+ phi = tokens[..., PHI]
213
+ kinematics = torch.cat(
214
+ (
215
+ tokens[..., :PHI],
216
+ torch.cos(phi).unsqueeze(-1),
217
+ torch.sin(phi).unsqueeze(-1),
218
+ tokens[..., PHI + 1 : NODE_TYPE],
219
+ tokens[..., NODE_TYPE + 1 :],
220
+ ),
221
+ dim=-1,
222
  )
223
+ node_type = tokens[..., NODE_TYPE].long()
224
+ return self.token_encoder(kinematics) + self.type_embedding(node_type)
225
+
226
+ def forward(self, batch: Any) -> torch.Tensor:
227
+ mask = batch.token_mask
228
+ encoded = self.encoder(self.embed(batch.tokens), src_key_padding_mask=~mask)
229
+ encoded = self.norm(encoded)
230
  counts = mask.sum(dim=1, keepdim=True).clamp_min(1)
231
  pooled = (encoded * mask.unsqueeze(-1)).sum(dim=1) / counts
232
  if self.global_encoder is not None:
 
260
  config: ModelConfig,
261
  *,
262
  num_features: int,
263
+ num_node_types: int,
264
  num_global_features: int = 0,
265
  load_pretrained: bool = True,
266
  ) -> nn.Module:
 
275
  return TransformerClassifier(
276
  input_size=num_features,
277
  out_size=config.out_size,
278
+ num_node_types=num_node_types,
279
  hid_size=config.hid_size,
280
  n_layers=config.n_layers,
281
  n_heads=config.n_heads,
282
  ffn_size=config.ffn_size,
283
  dropout=config.dropout,
 
284
  global_size=num_global_features,
285
  )
286
  if config.name != "edge_network":
tests/test_models.py CHANGED
@@ -1,3 +1,5 @@
 
 
1
  import pytest
2
  import torch
3
  from conftest import PRETRAINED, random_events
@@ -27,6 +29,7 @@ def test_pretrained_checkpoints_fine_tune(checkpoint):
27
  model = build_model(
28
  ModelConfig(out_size=5, pretrained=str(checkpoint), freeze_backbone=True),
29
  num_features=7,
 
30
  )
31
  assert isinstance(model, FineTunedEdgeNetwork)
32
  pretrained = state_dict_of(
@@ -58,13 +61,38 @@ def test_edge_network_uses_global_features_when_configured():
58
  assert model(batch).shape == (8, 3)
59
 
60
 
61
- def test_transformer_ignores_padding_tokens():
62
- events = random_events(seed=3)
63
- model = build_model(
64
  ModelConfig(name="transformer", hid_size=16, out_size=3, n_layers=1),
65
  num_features=7,
 
66
  ).eval()
 
 
 
 
 
 
 
 
 
 
 
 
67
  alone = collate_sequence_batch(events, torch.tensor([0]))
68
  batch = collate_sequence_batch(events, torch.arange(8))
69
  with torch.no_grad():
70
  torch.testing.assert_close(model(batch)[:1], model(alone), rtol=1e-5, atol=1e-5)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+
3
  import pytest
4
  import torch
5
  from conftest import PRETRAINED, random_events
 
29
  model = build_model(
30
  ModelConfig(out_size=5, pretrained=str(checkpoint), freeze_backbone=True),
31
  num_features=7,
32
+ num_node_types=5,
33
  )
34
  assert isinstance(model, FineTunedEdgeNetwork)
35
  pretrained = state_dict_of(
 
61
  assert model(batch).shape == (8, 3)
62
 
63
 
64
+ def _transformer():
65
+ return build_model(
 
66
  ModelConfig(name="transformer", hid_size=16, out_size=3, n_layers=1),
67
  num_features=7,
68
+ num_node_types=5,
69
  ).eval()
70
+
71
+
72
+ def _typed_events(seed):
73
+ events = random_events(seed=seed)
74
+ events.object_features[:, 6] = torch.randint(
75
+ 0, 5, (events.object_features.shape[0],)
76
+ ).float()
77
+ return events
78
+
79
+
80
+ def test_transformer_ignores_padding_tokens():
81
+ events, model = _typed_events(3), _transformer()
82
  alone = collate_sequence_batch(events, torch.tensor([0]))
83
  batch = collate_sequence_batch(events, torch.arange(8))
84
  with torch.no_grad():
85
  torch.testing.assert_close(model(batch)[:1], model(alone), rtol=1e-5, atol=1e-5)
86
+
87
+
88
+ def test_transformer_does_not_depend_on_object_order():
89
+ events, model = _typed_events(4), _transformer()
90
+ batch = collate_sequence_batch(events, torch.arange(8))
91
+ permutation = torch.randperm(batch.tokens.shape[1])
92
+ shuffled = dataclasses.replace(
93
+ batch,
94
+ tokens=batch.tokens[:, permutation],
95
+ token_mask=batch.token_mask[:, permutation],
96
+ )
97
+ with torch.no_grad():
98
+ torch.testing.assert_close(model(shuffled), model(batch), rtol=1e-5, atol=1e-5)
tests/test_workflows.py CHANGED
@@ -123,6 +123,12 @@ def test_transformer_trains_on_the_same_cache(gamgam, tmp_path):
123
  path = _config_file(config, tmp_path)
124
  assert main(["train", path]) == 0
125
  assert main(["evaluate", path]) == 0
 
 
 
 
 
 
126
 
127
 
128
  def test_binary_delphes_task(tmp_path):
 
123
  path = _config_file(config, tmp_path)
124
  assert main(["train", path]) == 0
125
  assert main(["evaluate", path]) == 0
126
+ pytest.importorskip("onnxruntime")
127
+ assert main(["export", path]) == 0
128
+ assert json.loads((config.path / "model.json").read_text())["inputs"] == [
129
+ "tokens",
130
+ "token_mask",
131
+ ]
132
 
133
 
134
  def test_binary_delphes_task(tmp_path):