Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 29 additions & 1 deletion docs/rally-training.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ python -m src.temporal_selector.rally_experiment \

A config's optional `training` object accepts `seed`, `epochs`, `batch_size`,
`sampling` (`boundary_balanced` or `uniform`), `boundary_aux_weight`, `optimizer`
(`AdamW`), `learning_rate`, `gradient_clip_norm`, and `device`. CLI values take
(`AdamW`), `learning_rate`, `gradient_clip_norm`, `device`, and `boundary_supervision`. CLI values take
precedence. Every run writes `resolved-config.json` before training, and final
metrics and inference exports record the resolved recipe. The historical
25-epoch MPS configuration remains available as `--preset benchmark`; overrides
Expand Down Expand Up @@ -87,6 +87,34 @@ channel and emits zero when there is insufficient history or variance.
`full_audio` to compare against raw audio with the same attention architecture
and camera splits.

## Boundary supervision comparison

The clean trainer accepts `--boundary-supervision triangle_bce` (the default),
`gaussian_qfl` for both heads, and `end_gaussian_qfl` for Gaussian/QFL ends
with triangle targets and weighted BCE for starts. Gaussian targets use a
standard deviation of 0.10 seconds for starts and 0.35 seconds for ends, with
targets cut off beyond three standard deviations. The annotated frame remains
the peak. Unreviewed or unowned frames remain masked, and boundaries outside
a split clip do not contribute to its targets.

Quality Focal Loss multiplies unweighted binary cross-entropy by
`(sigmoid(logit) - target)²` on each supervised frame of the configured boundary
head. The InPlay loss retains its existing weighting. The selected recipe
is stored in the resolved run and checkpoints.

```bash
for supervision in triangle_bce gaussian_qfl end_gaussian_qfl; do
python -m src.temporal_selector.rally_experiment \
--config config/rally-experiment.local.json --clean-only \
--preset rtmpose-audio --device cuda \
--boundary-supervision "$supervision" --output-dir "outputs/rally-$supervision"
done
```

The interval decoder uses InPlay scores. Compare decoded start and end errors
in the held-out `interval_matches` alongside interval F1, and use the saved
boundary logits in `test-predictions.jsonl` to evaluate the two heads directly.

## Clean train and validation partitions

Each fold holds out one complete camera. For each remaining camera, the clean
Expand Down
27 changes: 21 additions & 6 deletions src/temporal_selector/observations.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,15 @@ def read_jsonl_artifact(path: Path) -> tuple[dict[str, Any], list[dict[str, Any]
return records[0], records[1:]


RALLY_START_GAUSSIAN_SIGMA_SECONDS = 0.10
RALLY_END_GAUSSIAN_SIGMA_SECONDS = 0.35


def _gaussian_boundary_target(distance_seconds: float, sigma_seconds: float) -> float:
scaled = distance_seconds / sigma_seconds
return math.exp(-0.5 * scaled**2) if scaled <= 3.0 else 0.0


def rally_boundary_targets(
intervals: Sequence[RallyInterval],
partial_start_rally_ids: frozenset[str],
Expand All @@ -52,6 +61,8 @@ def rally_boundary_targets(
*,
fps: float,
taper_seconds: float = 0.25,
gaussian_start: bool = False,
gaussian_end: bool = False,
boundary_range: range | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Derive owned/reviewed soft boundary targets from strict intervals."""
Expand All @@ -70,15 +81,19 @@ def rally_boundary_targets(
interval.rally_id not in partial_start_rally_ids
and (boundary_range is None or interval.start_frame in boundary_range)
):
start = max(
start,
max(0.0, 1.0 - abs(frame - interval.start_frame) / (fps * taper_seconds)),
distance = abs(frame - interval.start_frame)
target = (
_gaussian_boundary_target(distance / fps, RALLY_START_GAUSSIAN_SIGMA_SECONDS)
if gaussian_start else max(0.0, 1.0 - distance / (fps * taper_seconds))
)
start = max(start, target)
if boundary_range is None or interval.end_frame in boundary_range:
end = max(
end,
max(0.0, 1.0 - abs(frame - interval.end_frame) / (fps * taper_seconds)),
distance = abs(frame - interval.end_frame)
target = (
_gaussian_boundary_target(distance / fps, RALLY_END_GAUSSIAN_SIGMA_SECONDS)
if gaussian_end else max(0.0, 1.0 - distance / (fps * taper_seconds))
)
end = max(end, target)
starts.append(start)
ends.append(end)
return torch.tensor(starts), torch.tensor(ends)
Expand Down
24 changes: 23 additions & 1 deletion src/temporal_selector/rally.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
RALLY_FEATURE_DIM = RALLY_FEATURE_VIEWS["full"].dimension
RALLY_CONTEXT_DIRECTION = "offline_centered"
RALLY_MODEL_TYPE = "RallySegmenter"
RALLY_BOUNDARY_SUPERVISION = ("triangle_bce", "gaussian_qfl", "end_gaussian_qfl")


@dataclass
Expand Down Expand Up @@ -335,15 +336,19 @@ def _masked_bce(
mask: Tensor,
*,
pos_weight: Tensor | None,
quality_focal: bool = False,
) -> Tensor:
safe_logits = torch.where(mask, logits, torch.zeros_like(logits))
safe_targets = targets.masked_fill(~mask, 0).to(logits.dtype)
values = F.binary_cross_entropy_with_logits(
safe_logits,
safe_targets,
pos_weight=pos_weight,
pos_weight=None if quality_focal else pos_weight,
reduction="none",
)
if quality_focal:
# Quality Focal Loss with beta=2 for continuous targets.
values = values * (safe_logits.sigmoid() - safe_targets).square()
return torch.where(mask, values, 0.0).sum() / mask.sum().clamp_min(1)

def losses(
Expand All @@ -356,6 +361,8 @@ def losses(
boundary_end_pos_weight: Tensor | None = None,
boundary_aux_weight: float = 0.25,
temporal_smoothing_weight: float = 0.0,
quality_focal_start: bool = False,
quality_focal_end: bool = False,
return_counts: bool = True,
) -> RallyLosses:
if boundary_aux_weight < 0:
Expand Down Expand Up @@ -392,12 +399,14 @@ def losses(
batch.rally_start_targets,
start_mask,
pos_weight=boundary_start_pos_weight,
quality_focal=quality_focal_start,
)
end = self._masked_bce(
output.rally_end_logits,
batch.rally_end_targets,
end_mask,
pos_weight=boundary_end_pos_weight,
quality_focal=quality_focal_end,
)
boundary_frames = (
int((start_mask | end_mask).sum()) if return_counts else None
Expand Down Expand Up @@ -485,6 +494,7 @@ class RallyTrainingRecipe:
gradient_clip_norm: float = 1.0
device: str = "mps"
temporal_smoothing_weight: float = 0.0
boundary_supervision: str = "triangle_bce"

def __post_init__(self) -> None:
for name in ("epochs", "batch_size"):
Expand All @@ -497,6 +507,8 @@ def __post_init__(self) -> None:
or self.seed < 0
):
raise ValueError("seed must be a nonnegative integer")
if self.boundary_supervision not in RALLY_BOUNDARY_SUPERVISION:
raise ValueError("unsupported rally boundary supervision")
if self.optimizer != "AdamW":
raise ValueError("supported rally optimizer is AdamW")
if self.sampling not in ("boundary_balanced", "uniform"):
Expand All @@ -517,11 +529,21 @@ def __post_init__(self) -> None:
if not math.isfinite(self.temporal_smoothing_weight) or self.temporal_smoothing_weight < 0:
raise ValueError("temporal smoothing weight must be finite and nonnegative")

@property
def gaussian_start(self) -> bool:
return self.boundary_supervision == "gaussian_qfl"

@property
def gaussian_end(self) -> bool:
return self.boundary_supervision != "triangle_bce"

def recovery_settings(self) -> dict[str, Any]:
settings = asdict(self)
# Older runs have no smoothing setting in their recovery files.
if not self.temporal_smoothing_weight:
settings.pop("temporal_smoothing_weight")
if self.boundary_supervision == "triangle_bce":
settings.pop("boundary_supervision")
return settings

@classmethod
Expand Down
11 changes: 11 additions & 0 deletions src/temporal_selector/rally_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ class RallyDataConfig:
ownership_seconds: float = 1.0
feature_view: str = "full"
cached_court_tolerance: float = 1e-5
gaussian_start: bool = False
gaussian_end: bool = False

def __post_init__(self) -> None:
if len({source.source_id for source in self.sources}) != len(self.sources):
Expand Down Expand Up @@ -210,6 +212,13 @@ def __init__(self, config: RallyDataConfig):
for source in config.sources
},
}
if self.rally_index is not None:
if config.gaussian_start and config.gaussian_end:
identity["boundary_targets"] = "gaussian"
elif config.gaussian_start:
identity["boundary_targets"] = "gaussian_start"
elif config.gaussian_end:
identity["boundary_targets"] = "gaussian_end"
pose_sources = list(self._pose_sources.values())
if any(item.get("pose_backend") == RTMPOSE_BACKEND_TYPE for item in pose_sources):
pose = pose_sources[0]
Expand Down Expand Up @@ -500,6 +509,8 @@ def _compile_source(
owned,
targets,
fps=fps,
gaussian_start=self.config.gaussian_start,
gaussian_end=self.config.gaussian_end,
)
else:
start_targets = torch.full((len(frames),), float(MASKED_TARGET))
Expand Down
27 changes: 24 additions & 3 deletions src/temporal_selector/rally_experiment.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
)
from .model import JointRallyShuttleModel
from .rally import (
RALLY_BOUNDARY_SUPERVISION,
RallySegmenter,
RallySegmenterConfig,
RallyTrainingRecipe,
Expand Down Expand Up @@ -330,6 +331,7 @@ def train_rally_segmenter(
seed: int,
boundary_aux_weight: float = 0.25,
temporal_smoothing_weight: float = 0.0,
boundary_supervision: str = "triangle_bce",
learning_rate: float = 3e-4,
gradient_clip_norm: float = 1.0,
sampling: str = "boundary_balanced",
Expand All @@ -349,6 +351,7 @@ def train_rally_segmenter(
batch_size=batch_size,
boundary_aux_weight=boundary_aux_weight,
temporal_smoothing_weight=temporal_smoothing_weight,
boundary_supervision=boundary_supervision,
learning_rate=learning_rate,
gradient_clip_norm=gradient_clip_norm,
sampling=sampling,
Expand Down Expand Up @@ -385,14 +388,19 @@ def train_rally_segmenter(
list(train_windows), batch_sampler=sampler, collate_fn=collate_rally_windows
)
optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)
weight_fields = ["inplay_targets"]
if not recipe.gaussian_start:
weight_fields.append("rally_start_targets")
if not recipe.gaussian_end:
weight_fields.append("rally_end_targets")
weights = {
field: _positive_weight(
train_windows,
field,
device=device,
cap=10.0 if field != "inplay_targets" else None,
)
for field in ("inplay_targets", "rally_start_targets", "rally_end_targets")
for field in weight_fields
}
history: list[dict[str, Any]] = []
best: tuple[float, int, dict[str, torch.Tensor]] | None = None
Expand Down Expand Up @@ -431,10 +439,12 @@ def train_rally_segmenter(
losses = model.losses(
batch,
inplay_pos_weight=weights["inplay_targets"],
boundary_start_pos_weight=weights["rally_start_targets"],
boundary_end_pos_weight=weights["rally_end_targets"],
boundary_start_pos_weight=weights.get("rally_start_targets"),
boundary_end_pos_weight=weights.get("rally_end_targets"),
boundary_aux_weight=boundary_aux_weight,
temporal_smoothing_weight=temporal_smoothing_weight,
quality_focal_start=recipe.gaussian_start,
quality_focal_end=recipe.gaussian_end,
return_counts=False,
)
if not bool(torch.isfinite(losses.total)):
Expand Down Expand Up @@ -664,6 +674,7 @@ def _prepare_rally_run(
)
if isinstance(previous.get("training_recipe"), dict):
previous["training_recipe"].setdefault("temporal_smoothing_weight", 0.0)
previous["training_recipe"].setdefault("boundary_supervision", "triangle_bce")
if previous != configuration:
raise ValueError("resume configuration or dataset identity has changed")
else:
Expand Down Expand Up @@ -1032,6 +1043,9 @@ def run_clean_rally_experiment(
output_dir = Path(output_dir).expanduser().resolve()
# Full-source observations are used for held-out scoring and production.
# A source divided by a fold cut gets independently extracted observations.
data_config = replace(
data_config, gaussian_start=recipe.gaussian_start, gaussian_end=recipe.gaussian_end
)
rally_dataset = RallyWindowDataset(data_config)
if rally_dataset.rally_index != index:
raise ValueError("rally annotations changed while preparing the train/validation split")
Expand Down Expand Up @@ -1129,6 +1143,7 @@ def run_clean_rally_experiment(
seed=recipe.seed,
boundary_aux_weight=recipe.boundary_aux_weight,
temporal_smoothing_weight=recipe.temporal_smoothing_weight,
boundary_supervision=recipe.boundary_supervision,
learning_rate=recipe.learning_rate,
gradient_clip_norm=recipe.gradient_clip_norm,
sampling=recipe.sampling,
Expand Down Expand Up @@ -1188,6 +1203,7 @@ def run_clean_rally_experiment(
seed=recipe.seed,
boundary_aux_weight=recipe.boundary_aux_weight,
temporal_smoothing_weight=recipe.temporal_smoothing_weight,
boundary_supervision=recipe.boundary_supervision,
learning_rate=recipe.learning_rate,
gradient_clip_norm=recipe.gradient_clip_norm,
sampling=recipe.sampling,
Expand Down Expand Up @@ -1355,6 +1371,7 @@ def train_rally_segmenter_fixed_epochs(
seed: int,
boundary_aux_weight: float,
temporal_smoothing_weight: float = 0.0,
boundary_supervision: str = "triangle_bce",
learning_rate: float = 3e-4,
gradient_clip_norm: float = 1.0,
sampling: str = "boundary_balanced",
Expand All @@ -1373,6 +1390,7 @@ def train_rally_segmenter_fixed_epochs(
seed=seed,
boundary_aux_weight=boundary_aux_weight,
temporal_smoothing_weight=temporal_smoothing_weight,
boundary_supervision=boundary_supervision,
learning_rate=learning_rate,
gradient_clip_norm=gradient_clip_norm,
sampling=sampling,
Expand Down Expand Up @@ -1453,6 +1471,7 @@ def _parser() -> argparse.ArgumentParser:
parser.add_argument("--learning-rate", type=float)
parser.add_argument("--gradient-clip-norm", type=float)
parser.add_argument("--boundary-aux-weight", type=float)
parser.add_argument("--boundary-supervision", choices=RALLY_BOUNDARY_SUPERVISION)
parser.add_argument("--temporal-smoothing-weight", type=float)
parser.add_argument("--seed", type=int)
parser.add_argument("--sampling", choices=("boundary_balanced", "uniform"))
Expand Down Expand Up @@ -1502,6 +1521,8 @@ def main(argv: Sequence[str] | None = None) -> int:
)
if recipe.temporal_smoothing_weight and not args.clean_only:
raise ValueError("temporal smoothing requires --clean-only")
if recipe.boundary_supervision != "triangle_bce" and not args.clean_only:
raise ValueError("Gaussian boundary supervision requires --clean-only")
if args.resume and not args.clean_only:
raise ValueError(
"epoch recovery currently requires --clean-only; comparative study arms use their historical trainer"
Expand Down
10 changes: 9 additions & 1 deletion src/temporal_selector/rally_partitions.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,12 +202,19 @@ def prepare_rally_partition(
dataset = RallyWindowDataset(replace(
config, sources=(child,), rally_intervals_path=None, rally_manifest_path=None,
))
windows = tuple(_label_partition(window, block, index, parent.frame_count) for window in dataset)
windows = tuple(
_label_partition(
window, block, index, parent.frame_count,
gaussian_start=config.gaussian_start, gaussian_end=config.gaussian_end,
)
for window in dataset
)
return windows, dataset.manifest["dataset_fingerprint"]


def _label_partition(
window: RallyWindow, block: RallySourceRange, index: RallyIntervalIndex, source_count: int,
*, gaussian_start: bool = False, gaussian_end: bool = False,
) -> RallyWindow:
"""Restore original frame keys and supervise only boundaries inside the partition."""
intervals = index.for_source(block.source_id)
Expand All @@ -219,6 +226,7 @@ def _label_partition(
bounds = range(block.start, block.stop)
starts, ends = rally_boundary_targets(
intervals, index.partial_start_rally_ids, frames, owned, targets, fps=fps, boundary_range=bounds,
gaussian_start=gaussian_start, gaussian_end=gaussian_end,
)
partial = tuple(
(
Expand Down
Loading
Loading