From ba94384ab7f3ab40ae264f396b149d661371bf14 Mon Sep 17 00:00:00 2001 From: Max Lin Date: Thu, 26 Nov 2026 22:19:22 -0800 Subject: [PATCH] Fit a median singles base on each rally training fold --- docs/rally-training.md | 13 ++++ src/rally_release.py | 15 +++++ src/temporal_selector/rally.py | 11 ++++ src/temporal_selector/rally_dataset.py | 76 ++++++++++++++++++++++- src/temporal_selector/rally_experiment.py | 30 ++++++++- src/temporal_selector/rally_features.py | 67 ++++++++++++++++---- src/temporal_selector/rally_inference.py | 1 + tests/test_independent_rally_segmenter.py | 54 +++++++++++++++- tests/test_rally_pipeline.py | 16 +++-- 9 files changed, 261 insertions(+), 22 deletions(-) diff --git a/docs/rally-training.md b/docs/rally-training.md index 5c899f0..d4b97d6 100644 --- a/docs/rally-training.md +++ b/docs/rally-training.md @@ -216,3 +216,16 @@ Both features use the raw projected positions before court smoothing. Compare held-out interval F1, boundary error, and false splits and merges. The distance-only arm isolates the effect of adding radial velocity to the distance channels. + +For a matched comparison against a data-derived base, run the radial view +with `--fit-singles-base` and a separate output directory. Each fold takes +the coordinate-wise median of in-bounds singles positions from observed +players on reviewed in-play training frames. Each owned frame contributes +once per observed player. The depth coordinate is mirrored across the net +and the across-court coordinate keeps its sign. Validation and held-out +sources use the same frozen training-fold base. Production fits once across +all training sources. + +Fold metrics and checkpoints record the resulting `singles_base_metres` +in lateral-coordinate, depth order. The inference exporter carries the +frozen pair into the model's preprocessing contract. diff --git a/src/rally_release.py b/src/rally_release.py index e645928..d28fdfa 100644 --- a/src/rally_release.py +++ b/src/rally_release.py @@ -40,9 +40,11 @@ ) from src.temporal_selector.rally_dataset import RALLY_TRANSFORMER_CONTEXT_RADIUS_SECONDS from src.temporal_selector.rally_features import ( + BASE_RADIAL_RALLY_FEATURE_VIEW, RALLY_FEATURE_SCHEMA, RALLY_FEATURE_VERSION, RALLY_FEATURE_VIEWS, + validate_singles_base_metres, ) RELEASE_SCHEMA = "baddievision.rally.inference_release" @@ -187,6 +189,11 @@ def validate_manifest(manifest: Mapping[str, Any]) -> dict[str, Any]: expected_preprocessing = set(defaults) if not legacy: expected_preprocessing.add("pose_model_sha256") + if "singles_base_metres" in preprocessing: + if view.name != BASE_RADIAL_RALLY_FEATURE_VIEW: + raise ValueError("a fitted singles base requires the distance plus radial velocity view") + validate_singles_base_metres(preprocessing["singles_base_metres"]) + expected_preprocessing.add("singles_base_metres") if set(preprocessing) - {"tracking_profile"} != expected_preprocessing: raise ValueError("release preprocessing fields are incompatible") if release_tracking_profile(value) not in PLAYER_TRACKING_PROFILES: @@ -426,6 +433,14 @@ def export_release( pose_asset = ("pose_model", pose_model, DEFAULT_RTMPOSE_MODEL_NAME) runtime = _package_version("onnxruntime-gpu") pose_runtime = {"onnxruntime": _package_version("onnxruntime") if runtime == "uninstalled" else runtime} + trained_base = research.get("singles_base_metres") + if "singles_base_metres" in recipe: + if trained_base is None or validate_singles_base_metres( + recipe["singles_base_metres"] + ) != validate_singles_base_metres(trained_base): + raise ValueError("export singles base differs from training") + if trained_base is not None: + recipe["singles_base_metres"] = list(validate_singles_base_metres(trained_base)) output = Path(output_dir) if output.exists() and any(output.iterdir()): raise FileExistsError("release output directory must be empty") diff --git a/src/temporal_selector/rally.py b/src/temporal_selector/rally.py index b858c73..4a03c82 100644 --- a/src/temporal_selector/rally.py +++ b/src/temporal_selector/rally.py @@ -13,9 +13,11 @@ from .batch import MASKED_TARGET from .rally_audio import RALLY_AUDIO_FEATURE_NAMES from .rally_features import ( + BASE_RADIAL_RALLY_FEATURE_VIEW, RALLY_FEATURE_SCHEMA, RALLY_FEATURE_VERSION, RALLY_FEATURE_VIEWS, + validate_singles_base_metres, ) @@ -466,6 +468,10 @@ def from_checkpoint( raise ValueError("rally checkpoint feature names/dimension are incompatible") if checkpoint["context_direction"] != RALLY_CONTEXT_DIRECTION: raise ValueError("rally checkpoint is not offline centered") + if "singles_base_metres" in checkpoint: + if feature_view != BASE_RADIAL_RALLY_FEATURE_VIEW: + raise ValueError("a fitted singles base requires the distance plus radial velocity view") + validate_singles_base_metres(checkpoint["singles_base_metres"]) model = cls( RallySegmenterConfig(**checkpoint["rally_segmenter_config"]) ) @@ -555,6 +561,7 @@ def rally_checkpoint( feature_view: str | None = None, calibration_fingerprints: Mapping[str, str] | None = None, pose_training_metadata: Mapping[str, Any] | None = None, + singles_base_metres: tuple[float, float] | None = None, extra: Mapping[str, Any] | None = None, ) -> dict[str, Any]: """Build a self-describing checkpoint without altering legacy formats.""" @@ -602,6 +609,10 @@ def rally_checkpoint( } if pose_training_metadata is not None: payload["pose_training_metadata"] = dict(pose_training_metadata) + if singles_base_metres is not None: + if feature_view != BASE_RADIAL_RALLY_FEATURE_VIEW: + raise ValueError("a fitted singles base requires the distance plus radial velocity view") + payload["singles_base_metres"] = list(validate_singles_base_metres(singles_base_metres)) if extra: overlap = set(payload).intersection(extra) if overlap: diff --git a/src/temporal_selector/rally_dataset.py b/src/temporal_selector/rally_dataset.py index e06b3f3..ae998db 100644 --- a/src/temporal_selector/rally_dataset.py +++ b/src/temporal_selector/rally_dataset.py @@ -5,7 +5,7 @@ import hashlib import json import math -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from pathlib import Path from typing import Any, Mapping, Sequence @@ -35,12 +35,17 @@ ) from .rally_audio import read_rally_audio from .rally_features import ( + BASE_FEATURE_NAMES, + BASE_RADIAL_RALLY_FEATURE_VIEW, FULL_RALLY_FEATURE_NAMES, + SINGLES_BASE_VELOCITY_FRAMES, + SinglesBaseObservations, normalize_rally_motion_pose, rally_feature_view, rally_motion_features, rally_singles_base_features, smooth_rally_court_positions, + validate_singles_base_metres, ) from .rally_intervals import read_rally_intervals @@ -89,6 +94,8 @@ class RallyDataConfig: ownership_seconds: float = 1.0 feature_view: str = "full" cached_court_tolerance: float = 1e-5 + singles_base_metres: tuple[float, float] | None = None + fit_singles_base: bool = False def __post_init__(self) -> None: if len({source.source_id for source in self.sources}) != len(self.sources): @@ -105,6 +112,15 @@ def __post_init__(self) -> None: ): raise ValueError("rally context and ownership durations must be finite and positive") rally_feature_view(self.feature_view) + if self.fit_singles_base or self.singles_base_metres is not None: + if self.feature_view != BASE_RADIAL_RALLY_FEATURE_VIEW: + raise ValueError("a fitted singles base requires the distance plus radial velocity view") + if self.singles_base_metres is not None: + if self.fit_singles_base: + raise ValueError("a singles base can be fitted or supplied") + object.__setattr__( + self, "singles_base_metres", validate_singles_base_metres(self.singles_base_metres) + ) if self.cached_court_tolerance < 0: raise ValueError("cached court-coordinate tolerance cannot be negative") if (self.rally_intervals_path is None) != (self.rally_manifest_path is None): @@ -129,6 +145,47 @@ class RallyWindow: rally_start_targets: torch.Tensor rally_end_targets: torch.Tensor metadata: Mapping[str, Any] = field(default_factory=dict) + singles_base_observations: SinglesBaseObservations | None = field(default=None, repr=False) + + +def fit_rally_singles_base(windows: Sequence[RallyWindow]) -> tuple[float, float]: + """Pool one position per observed player per owned, reviewed in-play frame.""" + samples = [] + for window in windows: + observations = window.singles_base_observations + if observations is None: + raise ValueError("singles-base fitting requires raw court observations") + owned_inplay = (window.inplay_targets == 1) & torch.tensor( + [frame in window.owned_frames for frame in window.frame_indices] + ) + frames = owned_inplay.nonzero(as_tuple=True)[0] + len(observations.positions) - len(window.frame_indices) + samples.append(observations.mirrored_in_bounds_metres(frames)) + if not samples or not any(len(sample) for sample in samples): + raise ValueError("singles-base fitting requires observed in-play positions within the singles court") + x, depth = torch.cat(samples).quantile(0.5, dim=0).tolist() + return x, depth + + +def with_rally_singles_base( + windows: Sequence[RallyWindow], base_metres: tuple[float, float], +) -> list[RallyWindow]: + """Replace only base channels using a frozen midpoint or fitted base.""" + view = rally_feature_view(BASE_RADIAL_RALLY_FEATURE_VIEW) + columns = tuple(view.names.index(name) for name in BASE_FEATURE_NAMES) + result = [] + for window in windows: + observations = window.singles_base_observations + if observations is None or window.metadata.get("feature_view") != view.name: + raise ValueError("recomputing singles-base channels requires raw observations in the radial view") + base_values, base_validity = rally_singles_base_features( + observations, float(window.metadata["fps"]), base_metres, + ) + length = len(window.frame_indices) + values, validity = window.frame_values.clone(), window.frame_validity.clone() + values[:, columns] = base_values[-length:] + validity[:, columns] = base_validity[-length:] + result.append(replace(window, frame_values=values, frame_validity=validity, singles_base_observations=None)) + return result def _reliable_court_foot( @@ -200,6 +257,8 @@ def __init__(self, config: RallyDataConfig): "pose_visibility_threshold": config.pose_visibility_threshold, "context_seconds": config.context_seconds, "ownership_seconds": config.ownership_seconds, + **({"singles_base_strategy": "training_inplay_median"} if config.fit_singles_base else {}), + **({"singles_base_metres": config.singles_base_metres} if config.singles_base_metres is not None else {}), "annotation": annotation_identity, "sources": { source.source_id: { @@ -463,6 +522,7 @@ def _compile_source( reliable_feet.append(frame_reliability) value_tensor = torch.tensor(source_values, dtype=torch.float32) validity_tensor = torch.tensor(source_validity, dtype=torch.bool) + base_observations = None if self.feature_view.uses_motion: track_tensor = torch.tensor(track_ids) normalize_rally_motion_pose(value_tensor, validity_tensor, track_tensor, image_size) @@ -472,9 +532,15 @@ def _compile_source( values = [value_tensor, velocity] validity = [validity_tensor, velocity_valid] if self.feature_view.uses_singles_base: - base_values, base_validity = rally_singles_base_features( - value_tensor, validity_tensor, track_tensor, fps + base_observations = SinglesBaseObservations.from_features( + value_tensor, validity_tensor, track_tensor, ) + if self.config.singles_base_metres is None: + base_values, base_validity = rally_singles_base_features(base_observations, fps) + else: + base_values, base_validity = rally_singles_base_features( + base_observations, fps, self.config.singles_base_metres, + ) values.append(base_values) validity.append(base_validity) smooth_rally_court_positions( @@ -529,6 +595,10 @@ def _compile_source( inplay_targets=torch.tensor(targets, dtype=torch.long), rally_start_targets=start_targets, rally_end_targets=end_targets, + singles_base_observations=( + base_observations.frame_range(max(0, start - SINGLES_BASE_VELOCITY_FRAMES + 1), end + 1) + if self.config.fit_singles_base and base_observations is not None else None + ), metadata={ "fps": fps, "frame_count": frame_count, diff --git a/src/temporal_selector/rally_experiment.py b/src/temporal_selector/rally_experiment.py index 7757f13..67b07a4 100644 --- a/src/temporal_selector/rally_experiment.py +++ b/src/temporal_selector/rally_experiment.py @@ -47,7 +47,9 @@ RallyWindow, RallyWindowDataset, collate_rally_windows, + fit_rally_singles_base, rally_data_config_from_selector_mapping, + with_rally_singles_base, ) from .rally_evaluation import ( DEFAULT_CAMERA_SOURCES, @@ -1106,6 +1108,12 @@ def run_clean_rally_experiment( test = [window for source in fold.test_source_ids for window in full_windows[source]] if not validation or not test: raise ValueError("clean rally fold requires validation and held-out windows") + singles_base = data_config.singles_base_metres + if data_config.fit_singles_base: + singles_base = fit_rally_singles_base(train) + train = with_rally_singles_base(train, singles_base) + validation = with_rally_singles_base(validation, singles_base) + test = with_rally_singles_base(test, singles_base) split_manifest = { "fold_id": fold.fold_id, "held_out_camera": fold.held_out_camera, "training_source_ids": list(fold.training_source_ids), @@ -1117,6 +1125,7 @@ def run_clean_rally_experiment( "checkpoint_selection": "validation_raw_bce_only", "decoder_selection": "validation_labels_only", "test_labels_used_for_selection": False, "test_evaluations": 1, + **({"singles_base_metres": list(singles_base)} if singles_base is not None else {}), } model = RallySegmenter(model_config).to(device) history, epoch = train_rally_segmenter( @@ -1166,6 +1175,7 @@ def run_clean_rally_experiment( pose_training_metadata=rally_dataset.manifest.get("pose_training_metadata"), feature_view=feature_view.name, calibration_fingerprints=calibration_fingerprints, + singles_base_metres=singles_base, extra={"epoch_history": history, "experiment_role": "expanded_clean_only"}, ) torch.save(checkpoint, fold_dir / "rally-segmenter.pt") @@ -1179,9 +1189,14 @@ def run_clean_rally_experiment( fold_artifacts.append(fold_result) production_epoch = round(statistics.median(selected_epochs)) production = RallySegmenter(model_config).to(device) + production_windows = rally_dataset.windows + production_base = data_config.singles_base_metres + if data_config.fit_singles_base: + production_base = fit_rally_singles_base(production_windows) + production_windows = with_rally_singles_base(production_windows, production_base) production_history = train_rally_segmenter_fixed_epochs( production, - rally_dataset.windows, + production_windows, device=device, epochs=production_epoch, batch_size=recipe.batch_size, @@ -1198,6 +1213,7 @@ def run_clean_rally_experiment( "annotation_fingerprint": rally_dataset.annotation_fingerprint, "epoch_selection": "median_fold_best_epoch", "fold_best_epochs": selected_epochs, + **({"singles_base_metres": list(production_base)} if production_base is not None else {}), }, ) oof_decoder, oof_search = tune_rally_decoder( @@ -1219,6 +1235,7 @@ def run_clean_rally_experiment( pose_training_metadata=rally_dataset.manifest.get("pose_training_metadata"), feature_view=feature_view.name, calibration_fingerprints=calibration_fingerprints, + singles_base_metres=production_base, extra={"epoch_history": production_history, "out_of_fold_decoder_search": oof_search, "experiment_role": "expanded_clean_only_production"}, ) @@ -1231,7 +1248,8 @@ def run_clean_rally_experiment( "macro": _macro_metrics(camera_metrics), "production": {"checkpoint": "production-rally-segmenter.pt", "chosen_epoch": production_epoch, - "decoder_configuration": asdict(oof_decoder)}, + "decoder_configuration": asdict(oof_decoder), + **({"singles_base_metres": list(production_base)} if production_base is not None else {})}, } _write_json(output_dir / "metrics.json", result) return result @@ -1462,6 +1480,10 @@ def _parser() -> argparse.ArgumentParser: help="Resume the clean-only run from committed epochs", ) parser.add_argument("--clean-only", action="store_true") + parser.add_argument( + "--fit-singles-base", action="store_true", + help="Fit the radial view's base from each camera fold's reviewed in-play training positions", + ) parser.add_argument("--person-model", help="Original detector asset for split recordings") parser.add_argument("--pose-model", type=Path, help="Original pose asset for split recordings") parser.add_argument( @@ -1510,6 +1532,8 @@ def main(argv: Sequence[str] | None = None) -> int: raise ValueError("choose only one rally experiment arm") if args.feature_view is not None and not args.clean_only: raise ValueError("--feature-view requires --clean-only") + if args.fit_singles_base and not args.clean_only: + raise ValueError("--fit-singles-base requires --clean-only") if not args.clean_only and (args.person_model is not None or args.pose_model is not None): raise ValueError("partition extraction model options require --clean-only") if args.clean_only: @@ -1526,6 +1550,8 @@ def main(argv: Sequence[str] | None = None) -> int: feature_view = CANONICAL_RALLY_FEATURE_VIEW if feature_view is not None: data_config = replace(data_config, feature_view=feature_view) + if args.fit_singles_base: + data_config = replace(data_config, fit_singles_base=True) camera_sources = _load_camera_sources(raw.get("camera_sources")) configured = {source.source_id for source in data_config.sources} grouped = [source for sources in camera_sources.values() for source in sources] diff --git a/src/temporal_selector/rally_features.py b/src/temporal_selector/rally_features.py index 9b4ccb2..8f3c86f 100644 --- a/src/temporal_selector/rally_features.py +++ b/src/temporal_selector/rally_features.py @@ -4,6 +4,7 @@ from collections.abc import Mapping, Sequence from dataclasses import dataclass +from numbers import Real from typing import Final import torch @@ -66,6 +67,8 @@ BASE_DISTANCE_FEATURE_NAMES: Final = ("p1_base_distance", "p2_base_distance") BASE_RADIAL_FEATURE_NAMES: Final = ("p1_base_radial_velocity", "p2_base_radial_velocity") BASE_FEATURE_NAMES: Final = BASE_DISTANCE_FEATURE_NAMES + BASE_RADIAL_FEATURE_NAMES +DEFAULT_SINGLES_BASE_METRES: Final = (0.0, HALF_LENGTH / 2) +SINGLES_BASE_VELOCITY_FRAMES: Final = 4 # Two court coordinates per player, followed by 66 pose coordinates per player. @@ -76,25 +79,65 @@ def _four_sample_slope(samples: Tensor) -> Tensor: return (3 * (samples[..., 3] - samples[..., 0]) + samples[..., 2] - samples[..., 1]) / 10 +def validate_singles_base_metres(value: object) -> tuple[float, float]: + if ( + not isinstance(value, (tuple, list)) + or len(value) != 2 + or any(not isinstance(item, Real) or isinstance(item, bool) for item in value) + or not -HALF_SINGLES_WIDTH <= value[0] <= HALF_SINGLES_WIDTH + or not 0 <= value[1] <= HALF_LENGTH + ): + raise ValueError("singles base must be [lateral metres, depth metres] inside the singles half-court") + return float(value[0]), float(value[1]) + + +@dataclass(frozen=True) +class SinglesBaseObservations: + positions: Tensor + observed: Tensor + track_ids: Tensor + + @classmethod + def from_features(cls, values: Tensor, validity: Tensor, track_ids: Tensor) -> SinglesBaseObservations: + positions = values[:, _COURT_POSITION_INDICES].reshape(-1, 2, 2) + observed = validity[:, _COURT_POSITION_INDICES].reshape(-1, 2, 2).all(dim=-1) + return cls(positions, observed & (track_ids >= 0), track_ids) + + def frame_range(self, start: int, stop: int) -> SinglesBaseObservations: + return SinglesBaseObservations( + self.positions[start:stop], self.observed[start:stop], self.track_ids[start:stop], + ) + + def mirrored_in_bounds_metres(self, frames: Tensor) -> Tensor: + positions = self.positions[frames] * self.positions.new_tensor( + ((HALF_WIDTH, -HALF_LENGTH), (HALF_WIDTH, HALF_LENGTH)) + ) + x, depth = positions.unbind(dim=-1) + inside = (x.abs() <= HALF_SINGLES_WIDTH) & (depth >= 0) & (depth <= HALF_LENGTH) + return positions[self.observed[frames] & inside] + + def rally_singles_base_features( - values: Tensor, validity: Tensor, track_ids: Tensor, fps: float, + observations: SinglesBaseObservations, + fps: float, + base_metres: tuple[float, float] = DEFAULT_SINGLES_BASE_METRES, ) -> tuple[Tensor, Tensor]: - """Measure distance and its signed slope about each singles half-court midpoint.""" - positions = values[:, _COURT_POSITION_INDICES].reshape(-1, 2, 2) - observed = validity[:, _COURT_POSITION_INDICES].reshape(-1, 2, 2).all(dim=-1) - observed &= track_ids >= 0 - base = positions.new_tensor(((0.0, -0.5), (0.0, 0.5))) + """Measure distance and signed slope about the same mirrored base on each half.""" + positions, observed = observations.positions, observations.observed + x, depth = base_metres + base = positions.new_tensor(((x / HALF_WIDTH, -depth / HALF_LENGTH), (x / HALF_WIDTH, depth / HALF_LENGTH))) metres = (positions - base) * positions.new_tensor((HALF_WIDTH, HALF_LENGTH)) distance = metres.norm(dim=-1) / (HALF_SINGLES_WIDTH**2 + (HALF_LENGTH / 2)**2)**0.5 radial_velocity = torch.zeros_like(distance) radial_valid = torch.zeros_like(observed) - if len(distance) >= 4: - tracks = track_ids.unfold(0, 4, 1) - radial_valid[3:] = ( - observed.unfold(0, 4, 1).all(dim=-1) & (tracks == tracks[..., :1]).all(dim=-1) + count = SINGLES_BASE_VELOCITY_FRAMES + if len(distance) >= count: + tracks = observations.track_ids.unfold(0, count, 1) + radial_valid[count - 1:] = ( + observed.unfold(0, count, 1).all(dim=-1) & (tracks == tracks[..., :1]).all(dim=-1) ) - slope = _four_sample_slope(distance.unfold(0, 4, 1)) * fps - radial_velocity[3:] = torch.where(radial_valid[3:], slope, 0.0) + slope = _four_sample_slope(distance.unfold(0, count, 1)) * fps + radial_velocity[count - 1:] = torch.where(radial_valid[count - 1:], slope, 0.0) return ( torch.cat((torch.where(observed, distance, 0.0), radial_velocity), dim=-1), torch.cat((observed, radial_valid), dim=-1), diff --git a/src/temporal_selector/rally_inference.py b/src/temporal_selector/rally_inference.py index 15560c9..6bc4270 100644 --- a/src/temporal_selector/rally_inference.py +++ b/src/temporal_selector/rally_inference.py @@ -129,6 +129,7 @@ def predict_source( keys = ( "pose_visibility_threshold", "pose_coordinate_mode", "context_seconds", "ownership_seconds", "feature_view", "cached_court_tolerance", + "singles_base_metres", ) settings = {key: preprocessing[key] for key in keys if key in preprocessing} # Release manifests may use the existing checkpoint's view key. diff --git a/tests/test_independent_rally_segmenter.py b/tests/test_independent_rally_segmenter.py index f2bca89..5e604ae 100644 --- a/tests/test_independent_rally_segmenter.py +++ b/tests/test_independent_rally_segmenter.py @@ -411,6 +411,7 @@ def test_rally_singles_base_features_use_metric_distance_and_mask_discontinuous_ from src.court_projection import HALF_LENGTH, HALF_SINGLES_WIDTH, HALF_WIDTH from src.temporal_selector.rally_features import ( FULL_RALLY_FEATURE_NAMES, + SinglesBaseObservations, rally_singles_base_features, ) @@ -427,7 +428,8 @@ def test_rally_singles_base_features_use_metric_distance_and_mask_discontinuous_ values[:, far_y] = 0.5 + distance_metres.flip((0,)) / HALF_LENGTH tracks[4:, 1] = 2 observed[4, near_y] = False - features, valid = rally_singles_base_features(values, observed, tracks, fps=30) + observations = SinglesBaseObservations.from_features(values, observed, tracks) + features, valid = rally_singles_base_features(observations, fps=30) normalization = (HALF_SINGLES_WIDTH**2 + (HALF_LENGTH / 2)**2)**0.5 assert torch.allclose(features[:4, 0], distance_metres[:4] / normalization) @@ -441,6 +443,56 @@ def test_rally_singles_base_features_use_metric_distance_and_mask_discontinuous_ assert torch.count_nonzero(features[~valid]) == 0 +def test_fit_singles_base_uses_owned_inplay_positions_and_mirrors_depth() -> None: + from src.court_projection import HALF_LENGTH, HALF_WIDTH + from src.temporal_selector.rally_dataset import fit_rally_singles_base, with_rally_singles_base + from src.temporal_selector.rally_features import ( + BASE_FEATURE_NAMES, + BASE_RADIAL_RALLY_FEATURE_VIEW, + SinglesBaseObservations, + rally_feature_view, + rally_singles_base_features, + ) + + view = rally_feature_view(BASE_RADIAL_RALLY_FEATURE_VIEW) + metres = torch.tensor([ + [[2.0, -6.0], [2.0, 6.0]], + [[-2.0, -5.0], [-2.0, 5.0]], + [[1.0, -4.0], [1.0, 4.0]], + [[-1.0, -2.0], [1.0, 4.0]], + [[0.4, -3.0], [3.0, 5.0]], + [[-2.0, -5.0], [-2.0, 5.0]], + ]) + observations = SinglesBaseObservations( + metres / torch.tensor([HALF_WIDTH, HALF_LENGTH]), + torch.ones((6, 2), dtype=torch.bool), + torch.ones((6, 2), dtype=torch.long), + ) + window = replace( + _window("train", 4), + frame_indices=(3, 4, 5), + owned_frames=frozenset((3, 4)), + inplay_targets=torch.ones(3, dtype=torch.long), + frame_values=torch.ones(3, view.dimension), + frame_validity=torch.ones(3, view.dimension, dtype=torch.bool), + metadata={"fps": 30.0, "feature_view": view.name}, + singles_base_observations=observations, + ) + base = fit_rally_singles_base([window]) + assert base == pytest.approx((0.4, 3.0)) + with pytest.raises(ValueError, match="observed in-play"): + fit_rally_singles_base([replace(window, inplay_targets=torch.zeros(3))]) + + fitted = with_rally_singles_base([window], base)[0] + expected_values, expected_validity = rally_singles_base_features(observations, 30, base) + columns = [view.names.index(name) for name in BASE_FEATURE_NAMES] + assert torch.equal(fitted.frame_values[:, columns], expected_values[3:]) + assert torch.equal(fitted.frame_validity[:, columns], expected_validity[3:]) + assert fitted.frame_validity[0, columns[2:]].all() + assert torch.all(fitted.frame_values[:, :min(columns)] == 1) + assert torch.all(fitted.frame_values[:, max(columns) + 1:] == 1) + + def test_rally_motion_pose_uses_crop_geometry_and_track_median_torso() -> None: from src.temporal_selector.observations import frame_context from src.temporal_selector.rally_features import ( diff --git a/tests/test_rally_pipeline.py b/tests/test_rally_pipeline.py index 41e41b1..fb6c95c 100644 --- a/tests/test_rally_pipeline.py +++ b/tests/test_rally_pipeline.py @@ -435,11 +435,16 @@ def test_explicit_device_failure_and_auto_fallback(pipeline, monkeypatch): assert calls == {"person": 0, "players": 0} -@pytest.mark.parametrize("view", [ - "no_position", "full_audio", "full_motion", "full_audio_zscore_motion", - "full_audio_zscore_motion_base_distance", "full_audio_zscore_motion_base_radial", +@pytest.mark.parametrize(("view", "base"), [ + ("no_position", None), + ("full_audio", None), + ("full_motion", None), + ("full_audio_zscore_motion", None), + ("full_audio_zscore_motion_base_distance", None), + ("full_audio_zscore_motion_base_radial", None), + ("full_audio_zscore_motion_base_radial", (0.18, 3.6)), ]) -def test_pipeline_uses_manifest_feature_view(pipeline, view): +def test_pipeline_uses_manifest_feature_view(pipeline, view, base): kwargs, _ = pipeline config = RallySegmenterConfig( frame_feature_dim=RALLY_FEATURE_VIEWS[view].dimension, @@ -461,6 +466,7 @@ def test_pipeline_uses_manifest_feature_view(pipeline, view): chosen_epoch=1, decoder_configuration=asdict(InPlayDecoderConfig()), feature_view=view, + singles_base_metres=base, ) torch.save(checkpoint, research) original_manifest = json.loads(kwargs["model_manifest"].read_text()) @@ -477,6 +483,8 @@ def test_pipeline_uses_manifest_feature_view(pipeline, view): base_url=output.as_uri(), model_id="view-v1", ) + if base is not None: + assert json.loads(manifest.read_text())["preprocessing"]["singles_base_metres"] == list(base) result = run_pipeline( **dict( kwargs, checkpoint=output / "rally-segmenter.pt", model_manifest=manifest