GNN4Colliders / scripts /opendata_prior.py
ho22joshua's picture
Claude Opus 5.5
fix: leave files with fewer than 100 events out of the Open Data prior
299a201
Raw History Blame Contribute Delete
6.81 kB
"""Write configs/opendata_pfn.yaml: PFN meta-training on the ATLAS Open Data
2025 MC samples of ho22joshua/atlas_opendata, one class per skim and process.
Processes with H -> gamma gamma (or gamma* gamma) are left out, so the GamGam
benchmark stays unseen; a tenth of the remaining processes (in every skim)
are held out of training tasks and form the validation tasks. Real data has
no process label and is not used. Files with fewer than --min-events events
(some skims keep none) are left out, so the files are downloaded (to the
Hugging Face cache) and opened.
uv run python scripts/opendata_prior.py
"""
from __future__ import annotations
import argparse
import csv
import random
import re
from pathlib import Path
REPO = "ho22joshua/atlas_opendata"
REVISION = "d1bcc9ccaa304ea09e11f7d724342568f72a0d6e"
SKIMS = ("GamGam/2025", "2J2LMET", "4lep", "2to4lep")
DIPHOTON_HIGGS = re.compile(r"gamgam|gammagamma|gamstargam|Hyy|_yy|x0yy", re.I)
FILE = re.compile(r"_mc_(\d+)\.(.+)\.[^.]+\.root$")
HEADER = """\
# Meta-training of the PFN (src/gnn4colliders/pfn.py) on classification tasks
# drawn from the ATLAS Open Data 2025 MC samples: one class per skim and
# process, written by scripts/opendata_prior.py. H -> gamma gamma processes
# are left out, so configs/gamgam_pfn.yaml evaluates on unseen processes;
# task.holdout_classes (a tenth of the processes, in every skim) are left out
# of training tasks and are the validation tasks. Classes of a task mix 1 to
# 3 processes. The node features match configs/gamgam.yaml (GeV here).
#
# gnn4colliders prepare configs/opendata_pfn.yaml
# gnn4colliders train configs/opendata_pfn.yaml
name: opendata_pfn
data:
hf_repo: {repo}
hf_revision: {revision}
files:
{files}
class_names: {class_names}
tree_name: analysis
# Electrons and muons share lep_*; b-tagging at the 70% working point is
# jet_btag_quantile >= 4, as MV2c10 > 0.8244273 in configs/gamgam.yaml.
derived_branches:
ele_pt: {{source: lep_pt, where: {{lep_type: 11}}}}
ele_eta: {{source: lep_eta, where: {{lep_type: 11}}}}
ele_phi: {{source: lep_phi, where: {{lep_type: 11}}}}
ele_charge: {{source: lep_charge, where: {{lep_type: 11}}}}
mu_pt: {{source: lep_pt, where: {{lep_type: 13}}}}
mu_eta: {{source: lep_eta, where: {{lep_type: 13}}}}
mu_phi: {{source: lep_phi, where: {{lep_type: 13}}}}
mu_charge: {{source: lep_charge, where: {{lep_type: 13}}}}
jet_btag: {{source: jet_btag_quantile, above: 3.5}}
feature_branches:
- [jet_pt, ele_pt, mu_pt, photon_pt, met]
- [jet_eta, ele_eta, mu_eta, photon_eta, 0]
- [jet_phi, ele_phi, mu_phi, photon_phi, met_phi]
- CALC_E
- [jet_btag, 0, 0, 0, 0]
- [0, ele_charge, mu_charge, 0, 0]
- NODE_TYPE
object_types: [vector, vector, vector, vector, single]
# Momenta are in GeV; 0.1 gives the pretraining unit of 10 GeV.
scales: [0.1, 1, 1, 0.1, 1, 1, 1]
fold_var: eventNumber
fold_modulus: 10
train_folds: [0, 1, 2, 3, 4, 5, 6, 7]
validation_folds: [8]
test_folds: [9]
weight_var: null
# The prior needs many processes, not many events of each.
max_events_per_file: {max_events}
cache: outputs/opendata_pfn/events.pt
batch_size: 8192
prepare_workers: 8
loader_workers: 4
pin_memory: true
model:
name: pfn
hid_size: 128
n_layers: 4
n_heads: 8
ffn_size: 512
dropout: 0.0
pair_bias: true
pretrained: null
max_classes: 10
pfn_layers: 6
task:
name: pfn
holdout_classes: {holdout}
task_classes: [2, 10]
mixture_labels: [1, 3]
min_class_events: 100
context_events: [16, 4096]
query_events: 256
energy_jitter: 0.2
steps_per_epoch: 1000
validation_steps: 50
train:
max_epochs: 50
optimizer: adamw
learning_rate: 1.0e-4
weight_decay: 0.01
lr_decay: 0.95
early_stopping: null
best_metric: loss
"""
def main() -> None:
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument("--skims", nargs="+", default=SKIMS)
parser.add_argument("--max-events", type=int, default=50000)
parser.add_argument("--min-events", type=int, default=100)
parser.add_argument("--holdout-fraction", type=float, default=0.1)
parser.add_argument("--out", type=Path, default=Path("configs/opendata_pfn.yaml"))
args = parser.parse_args()
import uproot
from huggingface_hub import HfApi, hf_hub_download
info = HfApi().dataset_info(REPO, revision=REVISION, files_metadata=True)
metadata = hf_hub_download(
REPO, "metadata.csv", repo_type="dataset", revision=REVISION
)
names = {
row["dataset_number"]: row["physics_short"]
for row in csv.DictReader(open(metadata))
}
files = []
for sibling in sorted(info.siblings, key=lambda s: s.rfilename):
path = sibling.rfilename
match = FILE.search(path)
# MC files are in <skim>/MC/, except 2to4lep's (in 2to4lep/).
skim = next(
(s for s in args.skims if re.match(rf"{s}/(MC/)?[^/]+$", path)), None
)
if skim is None or match is None:
continue
number, process = match.groups()
if DIPHOTON_HIGGS.search(names.get(number, process)):
continue
local = hf_hub_download(REPO, path, repo_type="dataset", revision=REVISION)
with uproot.open(local) as root_file:
tree = root_file.get("analysis")
entries = 0 if tree is None else tree.num_entries
if entries >= args.min_events:
files.append((skim, number, process, path, sibling))
numbers = sorted({number for _, number, *_ in files})
held = set(
random.Random(0).sample(numbers, round(args.holdout_fraction * len(numbers)))
)
lines, class_names, holdout = [], [], []
for label, (skim, number, process, path, sibling) in enumerate(files):
# Small files are stored in Git, not LFS: no SHA-256 to check.
sha256 = f", sha256: {sibling.lfs.sha256}" if sibling.lfs else ""
lines.append(
f" - {{path: {path}, label: {label}, "
f"size_bytes: {sibling.size}{sha256}}}"
)
class_names.append(f"{skim.split('/')[0]}:{number}:{process}")
if number in held:
holdout.append(label)
args.out.write_text(
HEADER.format(
repo=REPO,
revision=REVISION,
files="\n".join(lines),
class_names="[" + ", ".join(class_names) + "]",
max_events=args.max_events,
holdout="[" + ", ".join(map(str, holdout)) + "]",
)
)
print(
f"{args.out}: {len(files)} classes of {len(numbers)} processes, "
f"{len(holdout)} classes ({len(held)} processes) held out"
)
if __name__ == "__main__":
main()