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
13 changes: 13 additions & 0 deletions docs/rally-training.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
15 changes: 15 additions & 0 deletions src/rally_release.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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")
Expand Down
11 changes: 11 additions & 0 deletions src/temporal_selector/rally.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)


Expand Down Expand Up @@ -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"])
)
Expand Down Expand Up @@ -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."""
Expand Down Expand Up @@ -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:
Expand Down
76 changes: 73 additions & 3 deletions src/temporal_selector/rally_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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):
Expand All @@ -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):
Expand All @@ -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(
Expand Down Expand Up @@ -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: {
Expand Down Expand Up @@ -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)
Expand All @@ -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(
Expand Down Expand Up @@ -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,
Expand Down
30 changes: 28 additions & 2 deletions src/temporal_selector/rally_experiment.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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),
Expand All @@ -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(
Expand Down Expand Up @@ -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")
Expand All @@ -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,
Expand All @@ -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(
Expand All @@ -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"},
)
Expand All @@ -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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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:
Expand All @@ -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]
Expand Down
Loading
Loading