ho22joshua Claude Opus 5.5 commited on
Commit
9076261
·
1 Parent(s): 9a04b7b

feat: PFN prior from the ATLAS Open Data 2025 MC, held-out processes and mixed classes

Browse files

configs/opendata_pfn.yaml (written by scripts/opendata_prior.py) meta-trains
the PFN on 1299 classes, one per skim and process, of 334 processes of the
2025 Open Data MC; H -> gamma gamma processes are left out so GamGam stays
unseen. New keys: task.holdout_classes (left out of training tasks, the only
labels of validation tasks), task.mixture_labels (a class mixes several
labels in Dirichlet proportions), task.min_class_events and
data.max_events_per_file. Without them the prior and its random stream are
unchanged.

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

configs/opendata_pfn.yaml ADDED
The diff for this file is too large to render. See raw diff
 
scripts/opendata_prior.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Write configs/opendata_pfn.yaml: PFN meta-training on the ATLAS Open Data
2
+ 2025 MC samples of ho22joshua/atlas_opendata, one class per skim and process.
3
+
4
+ Processes with H -> gamma gamma (or gamma* gamma) are left out, so the GamGam
5
+ benchmark stays unseen; a tenth of the remaining processes (in every skim)
6
+ are held out of training tasks and form the validation tasks. Real data has
7
+ no process label and is not used.
8
+
9
+ uv run python scripts/opendata_prior.py
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import csv
16
+ import random
17
+ import re
18
+ from pathlib import Path
19
+
20
+ REPO = "ho22joshua/atlas_opendata"
21
+ REVISION = "d1bcc9ccaa304ea09e11f7d724342568f72a0d6e"
22
+ SKIMS = ("GamGam/2025", "2J2LMET", "4lep", "2to4lep")
23
+ DIPHOTON_HIGGS = re.compile(r"gamgam|gammagamma|gamstargam|Hyy|_yy|x0yy", re.I)
24
+ FILE = re.compile(r"_mc_(\d+)\.(.+)\.[^.]+\.root$")
25
+
26
+ HEADER = """\
27
+ # Meta-training of the PFN (src/gnn4colliders/pfn.py) on classification tasks
28
+ # drawn from the ATLAS Open Data 2025 MC samples: one class per skim and
29
+ # process, written by scripts/opendata_prior.py. H -> gamma gamma processes
30
+ # are left out, so configs/gamgam_pfn.yaml evaluates on unseen processes;
31
+ # task.holdout_classes (a tenth of the processes, in every skim) are left out
32
+ # of training tasks and are the validation tasks. Classes of a task mix 1 to
33
+ # 3 processes. The node features match configs/gamgam.yaml (GeV here).
34
+ #
35
+ # gnn4colliders prepare configs/opendata_pfn.yaml
36
+ # gnn4colliders train configs/opendata_pfn.yaml
37
+ name: opendata_pfn
38
+
39
+ data:
40
+ hf_repo: {repo}
41
+ hf_revision: {revision}
42
+ files:
43
+ {files}
44
+ class_names: {class_names}
45
+ tree_name: analysis
46
+ # Electrons and muons share lep_*; b-tagging at the 70% working point is
47
+ # jet_btag_quantile >= 4, as MV2c10 > 0.8244273 in configs/gamgam.yaml.
48
+ derived_branches:
49
+ ele_pt: {{source: lep_pt, where: {{lep_type: 11}}}}
50
+ ele_eta: {{source: lep_eta, where: {{lep_type: 11}}}}
51
+ ele_phi: {{source: lep_phi, where: {{lep_type: 11}}}}
52
+ ele_charge: {{source: lep_charge, where: {{lep_type: 11}}}}
53
+ mu_pt: {{source: lep_pt, where: {{lep_type: 13}}}}
54
+ mu_eta: {{source: lep_eta, where: {{lep_type: 13}}}}
55
+ mu_phi: {{source: lep_phi, where: {{lep_type: 13}}}}
56
+ mu_charge: {{source: lep_charge, where: {{lep_type: 13}}}}
57
+ jet_btag: {{source: jet_btag_quantile, above: 3.5}}
58
+ feature_branches:
59
+ - [jet_pt, ele_pt, mu_pt, photon_pt, met]
60
+ - [jet_eta, ele_eta, mu_eta, photon_eta, 0]
61
+ - [jet_phi, ele_phi, mu_phi, photon_phi, met_phi]
62
+ - CALC_E
63
+ - [jet_btag, 0, 0, 0, 0]
64
+ - [0, ele_charge, mu_charge, 0, 0]
65
+ - NODE_TYPE
66
+ object_types: [vector, vector, vector, vector, single]
67
+ # Momenta are in GeV; 0.1 gives the pretraining unit of 10 GeV.
68
+ scales: [0.1, 1, 1, 0.1, 1, 1, 1]
69
+ fold_var: eventNumber
70
+ fold_modulus: 10
71
+ train_folds: [0, 1, 2, 3, 4, 5, 6, 7]
72
+ validation_folds: [8]
73
+ test_folds: [9]
74
+ weight_var: null
75
+ # The prior needs many processes, not many events of each.
76
+ max_events_per_file: {max_events}
77
+ cache: outputs/opendata_pfn/events.pt
78
+ batch_size: 8192
79
+ prepare_workers: 8
80
+ loader_workers: 4
81
+ pin_memory: true
82
+
83
+ model:
84
+ name: pfn
85
+ hid_size: 128
86
+ n_layers: 4
87
+ n_heads: 8
88
+ ffn_size: 512
89
+ dropout: 0.0
90
+ pair_bias: true
91
+ pretrained: null
92
+ max_classes: 10
93
+ pfn_layers: 6
94
+
95
+ task:
96
+ name: pfn
97
+ holdout_classes: {holdout}
98
+ task_classes: [2, 10]
99
+ mixture_labels: [1, 3]
100
+ min_class_events: 100
101
+ context_events: [16, 4096]
102
+ query_events: 256
103
+ energy_jitter: 0.2
104
+ steps_per_epoch: 1000
105
+ validation_steps: 50
106
+
107
+ train:
108
+ max_epochs: 50
109
+ optimizer: adamw
110
+ learning_rate: 1.0e-4
111
+ weight_decay: 0.01
112
+ lr_decay: 0.95
113
+ early_stopping: null
114
+ best_metric: loss
115
+ """
116
+
117
+
118
+ def main() -> None:
119
+ parser = argparse.ArgumentParser(
120
+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
121
+ )
122
+ parser.add_argument("--skims", nargs="+", default=SKIMS)
123
+ parser.add_argument("--max-events", type=int, default=50000)
124
+ parser.add_argument("--holdout-fraction", type=float, default=0.1)
125
+ parser.add_argument("--out", type=Path, default=Path("configs/opendata_pfn.yaml"))
126
+ args = parser.parse_args()
127
+
128
+ from huggingface_hub import HfApi, hf_hub_download
129
+
130
+ info = HfApi().dataset_info(REPO, revision=REVISION, files_metadata=True)
131
+ metadata = hf_hub_download(
132
+ REPO, "metadata.csv", repo_type="dataset", revision=REVISION
133
+ )
134
+ names = {
135
+ row["dataset_number"]: row["physics_short"]
136
+ for row in csv.DictReader(open(metadata))
137
+ }
138
+ files = []
139
+ for sibling in sorted(info.siblings, key=lambda s: s.rfilename):
140
+ path = sibling.rfilename
141
+ match = FILE.search(path)
142
+ # MC files are in <skim>/MC/, except 2to4lep's (in 2to4lep/).
143
+ skim = next(
144
+ (s for s in args.skims if re.match(rf"{s}/(MC/)?[^/]+$", path)), None
145
+ )
146
+ if skim is None or match is None:
147
+ continue
148
+ number, process = match.groups()
149
+ if DIPHOTON_HIGGS.search(names.get(number, process)):
150
+ continue
151
+ files.append((skim, number, process, path, sibling))
152
+ numbers = sorted({number for _, number, *_ in files})
153
+ held = set(
154
+ random.Random(0).sample(numbers, round(args.holdout_fraction * len(numbers)))
155
+ )
156
+ lines, class_names, holdout = [], [], []
157
+ for label, (skim, number, process, path, sibling) in enumerate(files):
158
+ # Small files are stored in Git, not LFS: no SHA-256 to check.
159
+ sha256 = f", sha256: {sibling.lfs.sha256}" if sibling.lfs else ""
160
+ lines.append(
161
+ f" - {{path: {path}, label: {label}, "
162
+ f"size_bytes: {sibling.size}{sha256}}}"
163
+ )
164
+ class_names.append(f"{skim.split('/')[0]}:{number}:{process}")
165
+ if number in held:
166
+ holdout.append(label)
167
+ args.out.write_text(
168
+ HEADER.format(
169
+ repo=REPO,
170
+ revision=REVISION,
171
+ files="\n".join(lines),
172
+ class_names="[" + ", ".join(class_names) + "]",
173
+ max_events=args.max_events,
174
+ holdout="[" + ", ".join(map(str, holdout)) + "]",
175
+ )
176
+ )
177
+ print(
178
+ f"{args.out}: {len(files)} classes of {len(numbers)} processes, "
179
+ f"{len(holdout)} classes ({len(held)} processes) held out"
180
+ )
181
+
182
+
183
+ if __name__ == "__main__":
184
+ main()
src/gnn4colliders/config.py CHANGED
@@ -38,6 +38,8 @@ class DataConfig:
38
  fold_modulus: int | None = None
39
  #: Per-event weight branch; unweighted when null.
40
  weight_var: str | None = None
 
 
41
  train_folds: list[int] = field(default_factory=lambda: list(range(8)))
42
  validation_folds: list[int] = field(default_factory=lambda: [8])
43
  test_folds: list[int] = field(default_factory=lambda: [9])
@@ -162,6 +164,14 @@ class TaskConfig:
162
  # PFN meta-training: the prior over tasks (see pfn.py).
163
  #: Labels tasks draw their classes from (default: all).
164
  prior_classes: list[int] | None = None
 
 
 
 
 
 
 
 
165
  #: Smallest and largest number of classes of a task.
166
  task_classes: list[int] = field(default_factory=lambda: [2, 10])
167
  #: Smallest and largest number of context events (log-uniform).
 
38
  fold_modulus: int | None = None
39
  #: Per-event weight branch; unweighted when null.
40
  weight_var: str | None = None
41
+ #: Read at most this many leading entries of each file.
42
+ max_events_per_file: int | None = None
43
  train_folds: list[int] = field(default_factory=lambda: list(range(8)))
44
  validation_folds: list[int] = field(default_factory=lambda: [8])
45
  test_folds: list[int] = field(default_factory=lambda: [9])
 
164
  # PFN meta-training: the prior over tasks (see pfn.py).
165
  #: Labels tasks draw their classes from (default: all).
166
  prior_classes: list[int] | None = None
167
+ #: Labels left out of training tasks; validation tasks use only these, so
168
+ #: they measure classification of processes never seen in meta-training.
169
+ holdout_classes: list[int] | None = None
170
+ #: Smallest and largest number of labels mixed (in Dirichlet proportions)
171
+ #: into one class of a task; ``[1, 1]``: each class is one label.
172
+ mixture_labels: list[int] = field(default_factory=lambda: [1, 1])
173
+ #: Labels with fewer events in the split are not used.
174
+ min_class_events: int = 1
175
  #: Smallest and largest number of classes of a task.
176
  task_classes: list[int] = field(default_factory=lambda: [2, 10])
177
  #: Smallest and largest number of context events (log-uniform).
src/gnn4colliders/data.py CHANGED
@@ -514,6 +514,8 @@ def prepare(config: DataConfig, *, workers: int | None = None) -> Path:
514
  for file_index, (path, _) in enumerate(files):
515
  with uproot.open(path) as root_file:
516
  entries = int(root_file[config.tree_name].num_entries)
 
 
517
  chunks.extend(
518
  (config, files, file_index, start, min(start + CHUNK_EVENTS, entries))
519
  for start in range(0, entries, CHUNK_EVENTS)
 
514
  for file_index, (path, _) in enumerate(files):
515
  with uproot.open(path) as root_file:
516
  entries = int(root_file[config.tree_name].num_entries)
517
+ if config.max_events_per_file is not None:
518
+ entries = min(entries, config.max_events_per_file)
519
  chunks.extend(
520
  (config, files, file_index, start, min(start + CHUNK_EVENTS, entries))
521
  for start in range(0, entries, CHUNK_EVENTS)
src/gnn4colliders/pfn.py CHANGED
@@ -246,13 +246,22 @@ class TaskLoader:
246
  )
247
  self.num_workers, self.pin_memory, self.epoch = num_workers, pin_memory, 0
248
  labels = events.labels[indices]
249
- allowed = config.prior_classes
 
 
 
 
 
 
 
 
250
  self.pools = [
251
- indices[labels == label]
252
  for label in labels.unique().tolist()
253
- if allowed is None or label in allowed
 
254
  ]
255
- if len(self.pools) < 2:
256
  raise ValueError("the PFN prior needs events of at least two classes")
257
 
258
  def set_epoch(self, epoch: int) -> None:
@@ -278,25 +287,48 @@ class TaskLoader:
278
  context = min(max(context, low), high)
279
  size = context + config.query_events
280
  tasks = max(1, self.batch_size // size)
281
- largest = min(config.task_classes[1], len(self.pools), context)
 
282
  smallest = min(config.task_classes[0], largest)
 
 
 
 
 
283
  indices, labels, num_classes = [], [], []
284
  for _ in range(tasks):
285
  k = int(torch.randint(smallest, largest + 1, (), generator=generator))
286
- chosen = torch.randperm(len(self.pools), generator=generator)[:k]
287
- # Dirichlet(1) class proportions; every class has a context event.
288
- share = -torch.log(torch.rand(k, generator=generator))
289
- share = share / share.sum()
290
- rest = torch.multinomial(share, size - k, True, generator=generator)
 
 
 
 
 
 
 
 
291
  task_labels = torch.cat((torch.arange(k), rest))
292
  task_indices = torch.empty(size, dtype=torch.long)
293
  for label in range(k):
294
- pool = self.pools[int(chosen[label])]
295
- where = task_labels == label
296
- draw = torch.randint(
297
- len(pool), (int(where.sum()),), generator=generator
 
 
 
 
298
  )
299
- task_indices[where] = pool[draw]
 
 
 
 
 
300
  indices.append(task_indices)
301
  labels.append(task_labels)
302
  num_classes.append(k)
 
246
  )
247
  self.num_workers, self.pin_memory, self.epoch = num_workers, pin_memory, 0
248
  labels = events.labels[indices]
249
+ allowed, held_out = config.prior_classes, set(config.holdout_classes or [])
250
+
251
+ def used(label: int) -> bool:
252
+ if allowed is not None and label not in allowed:
253
+ return False
254
+ # Training tasks never see held-out labels; validation tasks, if
255
+ # any are held out, see only them.
256
+ return label not in held_out if train or not held_out else label in held_out
257
+
258
  self.pools = [
259
+ pool
260
  for label in labels.unique().tolist()
261
+ if used(label)
262
+ and len(pool := indices[labels == label]) >= config.min_class_events
263
  ]
264
+ if len(self.pools) < 2 * config.mixture_labels[0]:
265
  raise ValueError("the PFN prior needs events of at least two classes")
266
 
267
  def set_epoch(self, epoch: int) -> None:
 
287
  context = min(max(context, low), high)
288
  size = context + config.query_events
289
  tasks = max(1, self.batch_size // size)
290
+ fewest, most = config.mixture_labels
291
+ largest = min(config.task_classes[1], len(self.pools) // fewest, context)
292
  smallest = min(config.task_classes[0], largest)
293
+
294
+ def dirichlet(count: int) -> torch.Tensor: # Dirichlet(1) proportions
295
+ share = -torch.log(torch.rand(count, generator=generator))
296
+ return share / share.sum()
297
+
298
  indices, labels, num_classes = [], [], []
299
  for _ in range(tasks):
300
  k = int(torch.randint(smallest, largest + 1, (), generator=generator))
301
+ # Each class mixes 1 to ``most`` labels, no label in two classes.
302
+ # Without mixing, no draws are added: earlier priors are unchanged.
303
+ mixed = (
304
+ torch.randint(fewest, most + 1, (k,), generator=generator)
305
+ if most > 1
306
+ else torch.ones(k, dtype=torch.long)
307
+ )
308
+ while int(mixed.sum()) > len(self.pools):
309
+ mixed[int(torch.argmax(mixed))] -= 1
310
+ chosen = torch.randperm(len(self.pools), generator=generator)
311
+ chosen = chosen[: int(mixed.sum())].split(mixed.tolist())
312
+ # Every class has a context event.
313
+ rest = torch.multinomial(dirichlet(k), size - k, True, generator=generator)
314
  task_labels = torch.cat((torch.arange(k), rest))
315
  task_indices = torch.empty(size, dtype=torch.long)
316
  for label in range(k):
317
+ where = (task_labels == label).nonzero().flatten()
318
+ parts = chosen[label]
319
+ part = (
320
+ torch.multinomial(
321
+ dirichlet(len(parts)), len(where), True, generator=generator
322
+ )
323
+ if len(parts) > 1
324
+ else torch.zeros(len(where), dtype=torch.long)
325
  )
326
+ for which, pool_index in enumerate(parts.tolist()):
327
+ pool, members = self.pools[pool_index], where[part == which]
328
+ draw = torch.randint(
329
+ len(pool), (len(members),), generator=generator
330
+ )
331
+ task_indices[members] = pool[draw]
332
  indices.append(task_indices)
333
  labels.append(task_labels)
334
  num_classes.append(k)
tests/test_data.py CHANGED
@@ -122,6 +122,16 @@ def test_parallel_and_chunked_preparation_match_serial(gamgam, tmp_path, monkeyp
122
  assert torch.equal(parallel.entry_index, serial.entry_index)
123
 
124
 
 
 
 
 
 
 
 
 
 
 
125
  def test_delphes_preparation_reads_signed_weights_and_number_folds(tmp_path):
126
  config = fixture_config("tth_cp_even_odd", [TTH_FIXTURE], [0], tmp_path)
127
  events = load_events(prepare(config.data))
 
122
  assert torch.equal(parallel.entry_index, serial.entry_index)
123
 
124
 
125
+ def test_preparation_reads_the_leading_events_of_each_file(gamgam, tmp_path):
126
+ full = load_events(gamgam.data.cache)
127
+ gamgam.data.cache, gamgam.data.max_events_per_file = str(tmp_path / "c.pt"), 5
128
+ capped = load_events(prepare(gamgam.data))
129
+ files = full.file_index.unique()
130
+ assert len(capped) == 5 * len(files)
131
+ assert (capped.entry_index < 5).all()
132
+ assert torch.equal(capped.file_index.unique(), files)
133
+
134
+
135
  def test_delphes_preparation_reads_signed_weights_and_number_folds(tmp_path):
136
  config = fixture_config("tth_cp_even_odd", [TTH_FIXTURE], [0], tmp_path)
137
  events = load_events(prepare(config.data))
tests/test_pfn.py CHANGED
@@ -63,6 +63,34 @@ def test_tasks_follow_the_prior():
63
  assert not set(original.tolist()) - {1, 2, 3}
64
 
65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  def test_training_tasks_vary_by_epoch_and_validation_tasks_do_not():
67
  events = _events()
68
 
 
63
  assert not set(original.tolist()) - {1, 2, 3}
64
 
65
 
66
+ def _originals(events, batch):
67
+ """Per task, the original labels behind each task label."""
68
+ tasks = batch.context_labels.shape[0]
69
+ index = batch.events.event_index.view(tasks, -1)
70
+ labels = torch.cat((batch.context_labels, batch.labels.view(tasks, -1)), 1)
71
+ return [
72
+ [set(events.labels[index[t]][labels[t] == k].tolist()) for k in range(n)]
73
+ for t, n in enumerate(batch.num_classes.tolist())
74
+ ]
75
+
76
+
77
+ def test_held_out_labels_make_the_validation_tasks_only():
78
+ events = _events()
79
+ for train, allowed in ((True, {0, 1}), (False, {2, 3})):
80
+ for batch in _loader(events, train=train, holdout_classes=[2, 3]):
81
+ for classes in _originals(events, batch):
82
+ assert set().union(*classes) <= allowed
83
+
84
+
85
+ def test_mixed_classes_draw_on_disjoint_labels():
86
+ events = _events()
87
+ loader = _loader(events, task_classes=[2, 2], mixture_labels=[2, 2])
88
+ for batch in loader:
89
+ for first, second in _originals(events, batch):
90
+ assert 1 <= len(first) <= 2 and 1 <= len(second) <= 2
91
+ assert not first & second
92
+
93
+
94
  def test_training_tasks_vary_by_epoch_and_validation_tasks_do_not():
95
  events = _events()
96