From a83f388f5981eacd1755b060626f1e0b7d34da19 Mon Sep 17 00:00:00 2001 From: Max Lin Date: Thu, 26 Nov 2026 17:09:28 -0800 Subject: [PATCH 1/2] Test Gaussian targets and quality focal loss on rally boundaries --- docs/rally-training.md | 29 ++++++++++- src/temporal_selector/observations.py | 26 +++++++--- src/temporal_selector/rally.py | 15 +++++- src/temporal_selector/rally_dataset.py | 4 ++ src/temporal_selector/rally_experiment.py | 25 +++++++-- src/temporal_selector/rally_partitions.py | 8 ++- tests/test_independent_rally_segmenter.py | 62 ++++++++++++++++++++++- 7 files changed, 155 insertions(+), 14 deletions(-) diff --git a/docs/rally-training.md b/docs/rally-training.md index b73697c..f68c3d3 100644 --- a/docs/rally-training.md +++ b/docs/rally-training.md @@ -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 @@ -87,6 +87,33 @@ 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) +and `--boundary-supervision gaussian_qfl`. The Gaussian experiment uses 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 two boundary +heads. 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; 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 diff --git a/src/temporal_selector/observations.py b/src/temporal_selector/observations.py index aba8562..5f8b8d3 100644 --- a/src/temporal_selector/observations.py +++ b/src/temporal_selector/observations.py @@ -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], @@ -52,6 +61,7 @@ def rally_boundary_targets( *, fps: float, taper_seconds: float = 0.25, + gaussian: bool = False, boundary_range: range | None = None, ) -> tuple[torch.Tensor, torch.Tensor]: """Derive owned/reviewed soft boundary targets from strict intervals.""" @@ -70,15 +80,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 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 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) diff --git a/src/temporal_selector/rally.py b/src/temporal_selector/rally.py index b858c73..4620c7c 100644 --- a/src/temporal_selector/rally.py +++ b/src/temporal_selector/rally.py @@ -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") @dataclass @@ -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( @@ -356,6 +361,7 @@ def losses( boundary_end_pos_weight: Tensor | None = None, boundary_aux_weight: float = 0.25, temporal_smoothing_weight: float = 0.0, + quality_focal_boundaries: bool = False, return_counts: bool = True, ) -> RallyLosses: if boundary_aux_weight < 0: @@ -392,12 +398,14 @@ def losses( batch.rally_start_targets, start_mask, pos_weight=boundary_start_pos_weight, + quality_focal=quality_focal_boundaries, ) end = self._masked_bce( output.rally_end_logits, batch.rally_end_targets, end_mask, pos_weight=boundary_end_pos_weight, + quality_focal=quality_focal_boundaries, ) boundary_frames = ( int((start_mask | end_mask).sum()) if return_counts else None @@ -485,6 +493,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"): @@ -497,6 +506,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"): @@ -522,6 +533,8 @@ def recovery_settings(self) -> dict[str, Any]: # 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 diff --git a/src/temporal_selector/rally_dataset.py b/src/temporal_selector/rally_dataset.py index fefca4c..56d05d8 100644 --- a/src/temporal_selector/rally_dataset.py +++ b/src/temporal_selector/rally_dataset.py @@ -88,6 +88,7 @@ class RallyDataConfig: ownership_seconds: float = 1.0 feature_view: str = "full" cached_court_tolerance: float = 1e-5 + gaussian_boundaries: bool = False def __post_init__(self) -> None: if len({source.source_id for source in self.sources}) != len(self.sources): @@ -210,6 +211,8 @@ def __init__(self, config: RallyDataConfig): for source in config.sources }, } + if config.gaussian_boundaries and self.rally_index is not None: + identity["boundary_targets"] = "gaussian" 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] @@ -500,6 +503,7 @@ def _compile_source( owned, targets, fps=fps, + gaussian=self.config.gaussian_boundaries, ) else: start_targets = torch.full((len(frames),), float(MASKED_TARGET)) diff --git a/src/temporal_selector/rally_experiment.py b/src/temporal_selector/rally_experiment.py index 6645646..c95f00b 100644 --- a/src/temporal_selector/rally_experiment.py +++ b/src/temporal_selector/rally_experiment.py @@ -36,6 +36,7 @@ ) from .model import JointRallyShuttleModel from .rally import ( + RALLY_BOUNDARY_SUPERVISION, RallySegmenter, RallySegmenterConfig, RallyTrainingRecipe, @@ -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", @@ -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, @@ -385,6 +388,10 @@ def train_rally_segmenter( list(train_windows), batch_sampler=sampler, collate_fn=collate_rally_windows ) optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate) + quality_focal_boundaries = recipe.boundary_supervision == "gaussian_qfl" + weight_fields = ["inplay_targets"] + if not quality_focal_boundaries: + weight_fields.extend(("rally_start_targets", "rally_end_targets")) weights = { field: _positive_weight( train_windows, @@ -392,7 +399,7 @@ def train_rally_segmenter( 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 @@ -431,10 +438,11 @@ 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_boundaries=quality_focal_boundaries, return_counts=False, ) if not bool(torch.isfinite(losses.total)): @@ -664,6 +672,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: @@ -1032,6 +1041,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_boundaries=recipe.boundary_supervision == "gaussian_qfl" + ) rally_dataset = RallyWindowDataset(data_config) if rally_dataset.rally_index != index: raise ValueError("rally annotations changed while preparing the train/validation split") @@ -1129,6 +1141,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, @@ -1188,6 +1201,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, @@ -1355,6 +1369,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", @@ -1373,6 +1388,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, @@ -1453,6 +1469,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")) @@ -1502,6 +1519,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" diff --git a/src/temporal_selector/rally_partitions.py b/src/temporal_selector/rally_partitions.py index 139efb7..9596b80 100644 --- a/src/temporal_selector/rally_partitions.py +++ b/src/temporal_selector/rally_partitions.py @@ -202,12 +202,16 @@ 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=config.gaussian_boundaries) + for window in dataset + ) return windows, dataset.manifest["dataset_fingerprint"] def _label_partition( window: RallyWindow, block: RallySourceRange, index: RallyIntervalIndex, source_count: int, + *, gaussian: bool = False, ) -> RallyWindow: """Restore original frame keys and supervise only boundaries inside the partition.""" intervals = index.for_source(block.source_id) @@ -218,7 +222,7 @@ def _label_partition( fps = float(window.metadata["fps"]) 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, + intervals, index.partial_start_rally_ids, frames, owned, targets, fps=fps, boundary_range=bounds, gaussian=gaussian, ) partial = tuple( ( diff --git a/tests/test_independent_rally_segmenter.py b/tests/test_independent_rally_segmenter.py index c685923..7390a89 100644 --- a/tests/test_independent_rally_segmenter.py +++ b/tests/test_independent_rally_segmenter.py @@ -1,6 +1,7 @@ from __future__ import annotations import copy +import math from dataclasses import fields, replace import pytest @@ -20,6 +21,7 @@ collate_rally_windows, rally_checkpoint, ) +from src.temporal_selector.rally_audio import RALLY_AUDIO_FEATURE_NAMES from src.temporal_selector.rally_evaluation import ( camera_held_out_folds, chronological_camera_train_validation_split, @@ -28,7 +30,8 @@ rally_metrics, stable_track_fusion_acceptance, ) -from src.temporal_selector.rally_audio import RALLY_AUDIO_FEATURE_NAMES +from src.temporal_selector.rally_intervals import RallyInterval +from src.temporal_selector.observations import rally_boundary_targets def _config() -> RallySegmenterConfig: @@ -104,6 +107,63 @@ def test_padding_missing_features_and_boundary_masks_produce_finite_cpu_loss() - assert model.frame_projection.network[0].weight.grad is not None +def test_gaussian_boundary_targets_keep_starts_sharp_and_respect_supervision() -> None: + frames = (17, 20, 23, 29, 49, 60, 63, 69, 93, 94) + starts, ends = rally_boundary_targets( + (RallyInterval("source", "rally", 20, 60),), + frozenset(), + frames, + frozenset(frames[:-1]), + [0, 1, 1, 1, 1, 1, 0, 0, MASKED_TARGET, 0], + fps=30, + gaussian=True, + ) + assert starts[1] == ends[5] == 1 + assert starts[0] == starts[2] == pytest.approx(math.exp(-0.5)) + assert ends[6] > starts[2] + assert ends[7] == pytest.approx(math.exp(-0.5 * (0.3 / 0.35)**2)) + assert ends[4] > 0.5 + assert torch.all(starts[-2:] == MASKED_TARGET) + assert torch.all(ends[-2:] == MASKED_TARGET) + + starts, cut_ends = rally_boundary_targets( + (RallyInterval("source", "rally", 20, 60),), + frozenset({"rally"}), + frames[:5], + frozenset(frames[:5]), + [0, 1, 1, 1, 1], + fps=30, + gaussian=True, + boundary_range=range(60), + ) + assert starts.count_nonzero() == cut_ends.count_nonzero() == 0 + + +def test_quality_focal_boundary_loss_uses_soft_targets_and_masks_padding() -> None: + batch = _batch() + batch.rally_start_targets[0, 0] = 0.5 + batch.rally_start_targets[0, 1] = 0.75 + batch.rally_end_targets[0, 0] = MASKED_TARGET + model = RallySegmenter(_config()) + output = model(batch) + output.rally_start_logits = torch.zeros_like(output.rally_start_logits).masked_fill( + ~batch.frame_mask, -torch.inf + ).requires_grad_() + output.rally_end_logits.retain_grad() + losses = model.losses(batch, output, quality_focal_boundaries=True) + targets = batch.rally_start_targets[batch.frame_mask] + expected = math.log(2) * (0.5 - targets).square().mean() + torch.testing.assert_close(losses.rally_start, expected) + torch.testing.assert_close(losses.inplay, model.losses(batch, output).inplay) + losses.total.backward() + start_gradient = output.rally_start_logits.grad + end_gradient = output.rally_end_logits.grad + assert torch.isfinite(start_gradient).all() and torch.isfinite(end_gradient).all() + assert start_gradient[0, 0] == end_gradient[0, 0] == 0 + assert start_gradient[0, 1] < 0 + assert start_gradient[1, 2:].count_nonzero() == end_gradient[1, 2:].count_nonzero() == 0 + + def test_temporal_smoothing_uses_only_adjacent_owned_same_state_frames() -> None: batch = _batch() model = RallySegmenter(_config()) From 70b84b878bb952c30cc00cf55dd6521ff3b0c287 Mon Sep 17 00:00:00 2001 From: Max Lin Date: Thu, 26 Nov 2026 17:26:20 -0800 Subject: [PATCH 2/2] Compare Gaussian QFL ends with triangle BCE starts --- docs/rally-training.md | 11 ++++---- src/temporal_selector/observations.py | 7 ++--- src/temporal_selector/rally.py | 17 ++++++++++--- src/temporal_selector/rally_dataset.py | 15 ++++++++--- src/temporal_selector/rally_experiment.py | 12 +++++---- src/temporal_selector/rally_partitions.py | 10 +++++--- tests/test_independent_rally_segmenter.py | 31 ++++++++++++++++++++--- 7 files changed, 76 insertions(+), 27 deletions(-) diff --git a/docs/rally-training.md b/docs/rally-training.md index f68c3d3..7089430 100644 --- a/docs/rally-training.md +++ b/docs/rally-training.md @@ -89,20 +89,21 @@ and camera splits. ## Boundary supervision comparison -The clean trainer accepts `--boundary-supervision triangle_bce` (the default) -and `--boundary-supervision gaussian_qfl`. The Gaussian experiment uses a +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 two boundary -heads. The InPlay loss retains its existing weighting. The selected recipe +`(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; do +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 \ diff --git a/src/temporal_selector/observations.py b/src/temporal_selector/observations.py index 5f8b8d3..c0de1d9 100644 --- a/src/temporal_selector/observations.py +++ b/src/temporal_selector/observations.py @@ -61,7 +61,8 @@ def rally_boundary_targets( *, fps: float, taper_seconds: float = 0.25, - gaussian: bool = False, + 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.""" @@ -83,14 +84,14 @@ def rally_boundary_targets( distance = abs(frame - interval.start_frame) target = ( _gaussian_boundary_target(distance / fps, RALLY_START_GAUSSIAN_SIGMA_SECONDS) - if gaussian else max(0.0, 1.0 - distance / (fps * taper_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: distance = abs(frame - interval.end_frame) target = ( _gaussian_boundary_target(distance / fps, RALLY_END_GAUSSIAN_SIGMA_SECONDS) - if gaussian else max(0.0, 1.0 - distance / (fps * taper_seconds)) + if gaussian_end else max(0.0, 1.0 - distance / (fps * taper_seconds)) ) end = max(end, target) starts.append(start) diff --git a/src/temporal_selector/rally.py b/src/temporal_selector/rally.py index 4620c7c..a825e97 100644 --- a/src/temporal_selector/rally.py +++ b/src/temporal_selector/rally.py @@ -22,7 +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") +RALLY_BOUNDARY_SUPERVISION = ("triangle_bce", "gaussian_qfl", "end_gaussian_qfl") @dataclass @@ -361,7 +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_boundaries: bool = False, + quality_focal_start: bool = False, + quality_focal_end: bool = False, return_counts: bool = True, ) -> RallyLosses: if boundary_aux_weight < 0: @@ -398,14 +399,14 @@ def losses( batch.rally_start_targets, start_mask, pos_weight=boundary_start_pos_weight, - quality_focal=quality_focal_boundaries, + 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_boundaries, + quality_focal=quality_focal_end, ) boundary_frames = ( int((start_mask | end_mask).sum()) if return_counts else None @@ -528,6 +529,14 @@ 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. diff --git a/src/temporal_selector/rally_dataset.py b/src/temporal_selector/rally_dataset.py index 56d05d8..357ef81 100644 --- a/src/temporal_selector/rally_dataset.py +++ b/src/temporal_selector/rally_dataset.py @@ -88,7 +88,8 @@ class RallyDataConfig: ownership_seconds: float = 1.0 feature_view: str = "full" cached_court_tolerance: float = 1e-5 - gaussian_boundaries: bool = False + 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): @@ -211,8 +212,13 @@ def __init__(self, config: RallyDataConfig): for source in config.sources }, } - if config.gaussian_boundaries and self.rally_index is not None: - identity["boundary_targets"] = "gaussian" + 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] @@ -503,7 +509,8 @@ def _compile_source( owned, targets, fps=fps, - gaussian=self.config.gaussian_boundaries, + gaussian_start=self.config.gaussian_start, + gaussian_end=self.config.gaussian_end, ) else: start_targets = torch.full((len(frames),), float(MASKED_TARGET)) diff --git a/src/temporal_selector/rally_experiment.py b/src/temporal_selector/rally_experiment.py index c95f00b..1077f82 100644 --- a/src/temporal_selector/rally_experiment.py +++ b/src/temporal_selector/rally_experiment.py @@ -388,10 +388,11 @@ def train_rally_segmenter( list(train_windows), batch_sampler=sampler, collate_fn=collate_rally_windows ) optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate) - quality_focal_boundaries = recipe.boundary_supervision == "gaussian_qfl" weight_fields = ["inplay_targets"] - if not quality_focal_boundaries: - weight_fields.extend(("rally_start_targets", "rally_end_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, @@ -442,7 +443,8 @@ def train_rally_segmenter( boundary_end_pos_weight=weights.get("rally_end_targets"), boundary_aux_weight=boundary_aux_weight, temporal_smoothing_weight=temporal_smoothing_weight, - quality_focal_boundaries=quality_focal_boundaries, + quality_focal_start=recipe.gaussian_start, + quality_focal_end=recipe.gaussian_end, return_counts=False, ) if not bool(torch.isfinite(losses.total)): @@ -1042,7 +1044,7 @@ def run_clean_rally_experiment( # 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_boundaries=recipe.boundary_supervision == "gaussian_qfl" + data_config, gaussian_start=recipe.gaussian_start, gaussian_end=recipe.gaussian_end ) rally_dataset = RallyWindowDataset(data_config) if rally_dataset.rally_index != index: diff --git a/src/temporal_selector/rally_partitions.py b/src/temporal_selector/rally_partitions.py index 9596b80..8f5c66c 100644 --- a/src/temporal_selector/rally_partitions.py +++ b/src/temporal_selector/rally_partitions.py @@ -203,7 +203,10 @@ def prepare_rally_partition( config, sources=(child,), rally_intervals_path=None, rally_manifest_path=None, )) windows = tuple( - _label_partition(window, block, index, parent.frame_count, gaussian=config.gaussian_boundaries) + _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"] @@ -211,7 +214,7 @@ def prepare_rally_partition( def _label_partition( window: RallyWindow, block: RallySourceRange, index: RallyIntervalIndex, source_count: int, - *, gaussian: bool = False, + *, 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) @@ -222,7 +225,8 @@ def _label_partition( fps = float(window.metadata["fps"]) 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=gaussian, + intervals, index.partial_start_rally_ids, frames, owned, targets, fps=fps, boundary_range=bounds, + gaussian_start=gaussian_start, gaussian_end=gaussian_end, ) partial = tuple( ( diff --git a/tests/test_independent_rally_segmenter.py b/tests/test_independent_rally_segmenter.py index 7390a89..c5eb289 100644 --- a/tests/test_independent_rally_segmenter.py +++ b/tests/test_independent_rally_segmenter.py @@ -116,7 +116,8 @@ def test_gaussian_boundary_targets_keep_starts_sharp_and_respect_supervision() - frozenset(frames[:-1]), [0, 1, 1, 1, 1, 1, 0, 0, MASKED_TARGET, 0], fps=30, - gaussian=True, + gaussian_start=True, + gaussian_end=True, ) assert starts[1] == ends[5] == 1 assert starts[0] == starts[2] == pytest.approx(math.exp(-0.5)) @@ -126,6 +127,20 @@ def test_gaussian_boundary_targets_keep_starts_sharp_and_respect_supervision() - assert torch.all(starts[-2:] == MASKED_TARGET) assert torch.all(ends[-2:] == MASKED_TARGET) + intervals = (RallyInterval("source", "rally", 20, 60),) + owned = frozenset(frames) + labels = [0] * len(frames) + triangle_starts, _ = rally_boundary_targets(intervals, frozenset(), frames, owned, labels, fps=30) + _, gaussian_ends = rally_boundary_targets( + intervals, frozenset(), frames, owned, labels, fps=30, + gaussian_start=True, gaussian_end=True, + ) + hybrid_starts, hybrid_ends = rally_boundary_targets( + intervals, frozenset(), frames, owned, labels, fps=30, gaussian_end=True, + ) + torch.testing.assert_close(hybrid_starts, triangle_starts, rtol=0, atol=0) + torch.testing.assert_close(hybrid_ends, gaussian_ends, rtol=0, atol=0) + starts, cut_ends = rally_boundary_targets( (RallyInterval("source", "rally", 20, 60),), frozenset({"rally"}), @@ -133,7 +148,8 @@ def test_gaussian_boundary_targets_keep_starts_sharp_and_respect_supervision() - frozenset(frames[:5]), [0, 1, 1, 1, 1], fps=30, - gaussian=True, + gaussian_start=True, + gaussian_end=True, boundary_range=range(60), ) assert starts.count_nonzero() == cut_ends.count_nonzero() == 0 @@ -150,7 +166,16 @@ def test_quality_focal_boundary_loss_uses_soft_targets_and_masks_padding() -> No ~batch.frame_mask, -torch.inf ).requires_grad_() output.rally_end_logits.retain_grad() - losses = model.losses(batch, output, quality_focal_boundaries=True) + start_weight = torch.tensor(4.0) + losses = model.losses( + batch, output, quality_focal_start=True, quality_focal_end=True, + boundary_start_pos_weight=start_weight, + ) + hybrid = model.losses(batch, output, quality_focal_end=True, boundary_start_pos_weight=start_weight) + baseline = model.losses(batch, output, boundary_start_pos_weight=start_weight) + torch.testing.assert_close(hybrid.rally_start, baseline.rally_start) + torch.testing.assert_close(hybrid.rally_end, losses.rally_end) + assert not torch.isclose(hybrid.rally_start, losses.rally_start) targets = batch.rally_start_targets[batch.frame_mask] expected = math.log(2) * (0.5 - targets).square().mean() torch.testing.assert_close(losses.rally_start, expected)