74343d3e48
- log_transform / _validate_unit_pre_dir now raise on non-finite input instead of letting a NaN row silently poison the persisted normalizer cache (norm < 1e-6 was always False for NaN, so the existing guard never caught it). - encode_secondaries warns when a row's secondary energies cumulatively exceed e_sec, instead of silently saturating the overflowing slot's stick-breaking logit via the _EPS floor. - EVENT_ID_FILE_STRIDE overflow now raises instead of silently colliding two files' event ids together (reintroducing train/val leakage). - make_event_split(val_fraction=0.0) now actually holds out nothing, instead of always forcing at least 1 validation event. - setup_cache.save() is now serialized with a flock, since two concurrent writers (a real scenario on this repo's shared portal/condor machines) could otherwise race and silently drop one writer's freshly-computed cache section. - Documented (no behavior change) the pre_dir ≈ -ẑ antipodal rotation singularity in _rodrigues_axis, which is real but inherent to any single-valued local-frame convention. Each fix has a regression test. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
216 lines
7.4 KiB
Python
216 lines
7.4 KiB
Python
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
|
|
import numpy as np
|
|
import torch
|
|
from torch.utils.data import IterableDataset
|
|
|
|
from giant.data.loader import event_id_offset, iter_file_chunks
|
|
from giant.data.transforms import Normalizer, build_features, sorted_membership
|
|
|
|
|
|
def make_event_split(
|
|
all_event_ids: np.ndarray,
|
|
val_fraction: float = 0.1,
|
|
seed: int = 42,
|
|
) -> tuple[set, set]:
|
|
"""Assign unique event_ids to train/val sets by event_id, not by row."""
|
|
rng = np.random.default_rng(seed)
|
|
unique = np.unique(all_event_ids)
|
|
rng.shuffle(unique)
|
|
# max(1, ...) only applies when a validation split was actually
|
|
# requested — val_fraction=0.0 is an explicit "train on everything"
|
|
# request and must not be silently overridden into holding out 1 event.
|
|
n_val = max(1, int(len(unique) * val_fraction)) if val_fraction > 0 else 0
|
|
val_set = set(unique[:n_val].tolist())
|
|
train_set = set(unique[n_val:].tolist())
|
|
return train_set, val_set
|
|
|
|
|
|
class StreamingStepsDataset(IterableDataset):
|
|
"""Streams parquet files one row-group at a time.
|
|
|
|
Never loads more than `shuffle_buffer` rows into RAM simultaneously.
|
|
Files are split evenly across DataLoader workers via worker_info.
|
|
|
|
Yields whole batches (use with `DataLoader(..., batch_size=None)`)
|
|
rather than single rows, so the batch is assembled with vectorized
|
|
numpy slicing instead of a per-row Python loop in the default collate.
|
|
|
|
Each batch is a tuple:
|
|
(cond_cont, cond_cat, target_s1, n_sec, sec_cont, proc_idx)
|
|
where:
|
|
cond_cont: (B, COND_DIM) float32
|
|
cond_cat: (B, 2) int64
|
|
target_s1: (B, 9) float32 — normalised Stage-1 primary target
|
|
n_sec: (B,) int64 — true secondary count per step
|
|
sec_cont: (B, K_MAX, SEC_SLOT_DIM) float32 — [stick_logit,
|
|
local_dir, log_mass, charge] per slot (mass/charge
|
|
normalised iff `sec_phys_normalizer` was given)
|
|
proc_idx: (B,) int64 — process-class label (ProcessRouter supervision
|
|
only; zeros when `proc_map` is None)
|
|
"""
|
|
|
|
def __init__(
|
|
self,
|
|
files: list[Path],
|
|
split_events: set,
|
|
pdg_map: dict[int, int],
|
|
mat_map: dict[str, int],
|
|
cond_normalizer: Normalizer,
|
|
target_normalizer: Normalizer,
|
|
batch_size: int,
|
|
shuffle_buffer: int = 65536,
|
|
shuffle: bool = True,
|
|
proc_map: dict[str, int] | None = None,
|
|
conditioning: str = "embedding",
|
|
sec_phys_normalizer: Normalizer | None = None,
|
|
) -> None:
|
|
self.files = list(files)
|
|
self._offsets = {path: event_id_offset(i) for i, path in enumerate(self.files)}
|
|
self.split_events = split_events
|
|
self._events_arr = np.array(sorted(split_events))
|
|
self.pdg_map = pdg_map
|
|
self.mat_map = mat_map
|
|
self.cond_normalizer = cond_normalizer
|
|
self.target_normalizer = target_normalizer
|
|
self.batch_size = batch_size
|
|
self.shuffle_buffer = max(shuffle_buffer, batch_size)
|
|
self.shuffle = shuffle
|
|
self.proc_map = proc_map
|
|
self.conditioning = conditioning
|
|
self.sec_phys_normalizer = sec_phys_normalizer
|
|
|
|
def __iter__(self):
|
|
worker_info = torch.utils.data.get_worker_info()
|
|
files = self.files
|
|
if worker_info is not None:
|
|
files = files[worker_info.id :: worker_info.num_workers]
|
|
|
|
if self.shuffle:
|
|
files = list(files)
|
|
np.random.default_rng().shuffle(files)
|
|
|
|
buf_cont: list[np.ndarray] = []
|
|
buf_cat: list[np.ndarray] = []
|
|
buf_tgt: list[np.ndarray] = []
|
|
buf_nsec: list[np.ndarray] = []
|
|
buf_sec: list[np.ndarray] = []
|
|
buf_proc: list[np.ndarray] = []
|
|
buf_n = 0
|
|
|
|
for path in files:
|
|
for chunk in iter_file_chunks(path, offset=self._offsets[path]):
|
|
mask = sorted_membership(chunk["event_id"], self._events_arr)
|
|
if not mask.any():
|
|
continue
|
|
chunk = {k: v[mask] for k, v in chunk.items()}
|
|
|
|
(
|
|
cond_cont,
|
|
cond_cat,
|
|
target_s1,
|
|
n_sec,
|
|
sec_cont,
|
|
proc_idx,
|
|
_,
|
|
_,
|
|
) = build_features(
|
|
chunk,
|
|
self.pdg_map,
|
|
self.mat_map,
|
|
cond_normalizer=self.cond_normalizer,
|
|
target_normalizer=self.target_normalizer,
|
|
sec_phys_normalizer=self.sec_phys_normalizer,
|
|
proc_map=self.proc_map,
|
|
require_secondaries=True,
|
|
conditioning=self.conditioning,
|
|
)
|
|
buf_cont.append(cond_cont)
|
|
buf_cat.append(cond_cat)
|
|
buf_tgt.append(target_s1)
|
|
buf_nsec.append(n_sec)
|
|
buf_sec.append(sec_cont)
|
|
buf_proc.append(proc_idx)
|
|
buf_n += len(cond_cont)
|
|
|
|
if buf_n >= self.shuffle_buffer:
|
|
(
|
|
buf_cont,
|
|
buf_cat,
|
|
buf_tgt,
|
|
buf_nsec,
|
|
buf_sec,
|
|
buf_proc,
|
|
buf_n,
|
|
) = yield from self._flush(
|
|
buf_cont,
|
|
buf_cat,
|
|
buf_tgt,
|
|
buf_nsec,
|
|
buf_sec,
|
|
buf_proc,
|
|
final=False,
|
|
)
|
|
|
|
if buf_n > 0:
|
|
yield from self._flush(
|
|
buf_cont,
|
|
buf_cat,
|
|
buf_tgt,
|
|
buf_nsec,
|
|
buf_sec,
|
|
buf_proc,
|
|
final=True,
|
|
)
|
|
|
|
def _flush(
|
|
self,
|
|
buf_cont: list[np.ndarray],
|
|
buf_cat: list[np.ndarray],
|
|
buf_tgt: list[np.ndarray],
|
|
buf_nsec: list[np.ndarray],
|
|
buf_sec: list[np.ndarray],
|
|
buf_proc: list[np.ndarray],
|
|
final: bool,
|
|
):
|
|
cont = np.concatenate(buf_cont)
|
|
cat = np.concatenate(buf_cat)
|
|
tgt = np.concatenate(buf_tgt)
|
|
nsec = np.concatenate(buf_nsec)
|
|
sec = np.concatenate(buf_sec)
|
|
proc = np.concatenate(buf_proc)
|
|
|
|
if self.shuffle:
|
|
idx = np.random.permutation(len(cont))
|
|
cont, cat, tgt = cont[idx], cat[idx], tgt[idx]
|
|
nsec, sec, proc = nsec[idx], sec[idx], proc[idx]
|
|
|
|
bs = self.batch_size
|
|
n = len(cont)
|
|
n_full = n // bs if not final else (n + bs - 1) // bs
|
|
for start in range(0, n_full * bs, bs):
|
|
end = min(start + bs, n)
|
|
yield (
|
|
torch.from_numpy(cont[start:end]).float(),
|
|
torch.from_numpy(cat[start:end]).long(),
|
|
torch.from_numpy(tgt[start:end]).float(),
|
|
torch.from_numpy(nsec[start:end]).long(),
|
|
torch.from_numpy(sec[start:end]).float(),
|
|
torch.from_numpy(proc[start:end]).long(),
|
|
)
|
|
|
|
if final:
|
|
return [], [], [], [], [], [], 0
|
|
rem = n_full * bs
|
|
return (
|
|
[cont[rem:]],
|
|
[cat[rem:]],
|
|
[tgt[rem:]],
|
|
[nsec[rem:]],
|
|
[sec[rem:]],
|
|
[proc[rem:]],
|
|
n - rem,
|
|
)
|