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
25 changes: 25 additions & 0 deletions docs/rally-training.md
Original file line number Diff line number Diff line change
Expand Up @@ -191,3 +191,28 @@ training recipe fixed. Report interval F1 and signed start/end errors by
camera. The motion views change both pose normalization and velocity
channels, so comparisons against the original views measure their combined
effect. The filter windows span less time at higher FPS.

## Singles-base ablation

Run the canonical motion baseline and the two singles-base views with the
same camera folds and training settings.

```bash
for view in full_audio_zscore_motion full_audio_zscore_motion_base_distance full_audio_zscore_motion_base_radial; do
python -m src.temporal_selector.rally_experiment \
--config config/rally-experiment.local.json --clean-only --preset rtmpose-audio \
--feature-view "$view" --device cuda --output-dir "outputs/singles-base/$view"
done
```

The base is the midpoint of each player's singles half-court, halfway from
the net to the baseline. Distance is Euclidean in court metres, divided by
the distance from the midpoint to a singles corner. The radial view also
fits a trailing four-frame slope of that distance per second. Positive values
indicate movement away from base and negative values indicate recovery toward
it. The slope is masked across missing court observations and track changes.
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.
13 changes: 11 additions & 2 deletions src/temporal_selector/rally_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
normalize_rally_motion_pose,
rally_feature_view,
rally_motion_features,
rally_singles_base_features,
smooth_rally_court_positions,
)
from .rally_intervals import read_rally_intervals
Expand Down Expand Up @@ -468,11 +469,19 @@ def _compile_source(
velocity, velocity_valid = rally_motion_features(
value_tensor, validity_tensor, track_tensor, fps
)
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
)
values.append(base_values)
validity.append(base_validity)
smooth_rally_court_positions(
value_tensor, validity_tensor, track_tensor, torch.tensor(reliable_feet)
)
value_tensor = torch.cat((value_tensor, velocity), dim=-1)
validity_tensor = torch.cat((validity_tensor, velocity_valid), dim=-1)
value_tensor = torch.cat(values, dim=-1)
validity_tensor = torch.cat(validity, dim=-1)
if audio is not None:
value_tensor = torch.cat((value_tensor, torch.as_tensor(audio_values)), dim=-1)
validity_tensor = torch.cat((validity_tensor, torch.as_tensor(audio.validity)), dim=-1)
Expand Down
2 changes: 1 addition & 1 deletion src/temporal_selector/rally_experiment.py
Original file line number Diff line number Diff line change
Expand Up @@ -1494,7 +1494,7 @@ def main(argv: Sequence[str] | None = None) -> int:
if rtmpose_preset:
if not args.clean_only:
raise ValueError("the RTMPose audio preset requires --clean-only")
if args.feature_view not in (None, "full_audio_zscore", CANONICAL_RALLY_FEATURE_VIEW):
if args.feature_view is not None and not rally_feature_view(args.feature_view).audio_zscore:
raise ValueError("the RTMPose audio preset requires a normalized-audio feature view")
overrides.setdefault("temporal_smoothing_weight", 0.1)
recipe = RallyTrainingRecipe.from_preset(
Expand Down
66 changes: 61 additions & 5 deletions src/temporal_selector/rally_features.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,15 @@
import torch
from torch import Tensor

from src.court_projection import HALF_LENGTH, HALF_SINGLES_WIDTH, HALF_WIDTH

from .rally_audio import RALLY_AUDIO_FEATURE_NAMES

RALLY_FEATURE_SCHEMA: Final = "baddievision.rally.feature_views"
RALLY_FEATURE_VERSION: Final = 2
CANONICAL_RALLY_FEATURE_VIEW: Final = "full_audio_zscore_motion"
BASE_DISTANCE_RALLY_FEATURE_VIEW: Final = "full_audio_zscore_motion_base_distance"
BASE_RADIAL_RALLY_FEATURE_VIEW: Final = "full_audio_zscore_motion_base_radial"

PLAYER_CONTEXT_FIELDS: Final = (
"bbox_x1",
Expand Down Expand Up @@ -59,12 +63,44 @@
FULL_RALLY_FEATURE_NAMES[index][-1]
for index in MOTION_POSITION_INDICES
)
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


# Two court coordinates per player, followed by 66 pose coordinates per player.
_MOTION_PLAYER_INDICES: Final = (0, 0, 1, 1) + (0,) * 66 + (1,) * 66


def _four_sample_slope(samples: Tensor) -> Tensor:
return (3 * (samples[..., 3] - samples[..., 0]) + samples[..., 2] - samples[..., 1]) / 10


def rally_singles_base_features(
values: Tensor, validity: Tensor, track_ids: Tensor, fps: float,
) -> 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)))
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)
)
slope = _four_sample_slope(distance.unfold(0, 4, 1)) * fps
radial_velocity[3:] = torch.where(radial_valid[3:], slope, 0.0)
return (
torch.cat((torch.where(observed, distance, 0.0), radial_velocity), dim=-1),
torch.cat((observed, radial_valid), dim=-1),
)


def normalize_rally_motion_pose(
values: Tensor, validity: Tensor, track_ids: Tensor, image_size: tuple[int, int],
) -> None:
Expand Down Expand Up @@ -131,7 +167,7 @@ def rally_motion_features(
samples = positions[:, columns].unfold(0, count, 1)
slope = (samples[..., -1] - samples[..., 0]) / 2
if count == 4:
slope = (3 * (samples[..., -1] - samples[..., 0]) + samples[..., 2] - samples[..., 1]) / 10
slope = _four_sample_slope(samples)
velocity[count - 1:, columns] = torch.where(valid[count - 1:, columns], slope * fps, 0.0)
return velocity, valid

Expand All @@ -146,6 +182,7 @@ class RallyFeatureView:
uses_audio: bool = False
audio_zscore: bool = False
uses_motion: bool = False
uses_singles_base: bool = False

@property
def dimension(self) -> int:
Expand All @@ -157,6 +194,8 @@ def select(self, values: Tensor, validity: Tensor) -> tuple[Tensor, Tensor]:
input_dimension = len(FULL_RALLY_FEATURE_NAMES)
if self.uses_motion:
input_dimension += len(MOTION_FEATURE_NAMES)
if self.uses_singles_base:
input_dimension += len(BASE_FEATURE_NAMES)
if self.uses_audio:
input_dimension += len(RALLY_AUDIO_FEATURE_NAMES)
if values.shape[-1] != input_dimension:
Expand All @@ -178,34 +217,49 @@ def _names_for_fields(fields: Sequence[str], *, include_pose: bool = True) -> tu

def _view(
name: str, names: Sequence[str], *, uses_audio: bool = False, audio_zscore: bool = False,
uses_motion: bool = False,
uses_motion: bool = False, uses_singles_base: bool = False,
) -> RallyFeatureView:
requested = tuple(names)
if len(requested) != len(set(requested)):
raise AssertionError(f"duplicate feature in rally view {name}")
input_names = (
(MOTION_BASE_FEATURE_NAMES + MOTION_FEATURE_NAMES if uses_motion else FULL_RALLY_FEATURE_NAMES)
+ (BASE_FEATURE_NAMES if uses_singles_base else ())
+ (RALLY_AUDIO_FEATURE_NAMES if uses_audio else ())
)
positions = {feature: index for index, feature in enumerate(input_names)}
missing = [feature for feature in requested if feature not in positions]
if missing:
raise AssertionError(f"unknown feature in rally view {name}: {missing}")
return RallyFeatureView(
name, requested, tuple(positions[item] for item in requested), uses_audio, audio_zscore, uses_motion
name, requested, tuple(positions[item] for item in requested), uses_audio, audio_zscore,
uses_motion, uses_singles_base,
)


_MOTION_VISUAL_FEATURE_NAMES: Final = MOTION_BASE_FEATURE_NAMES + MOTION_FEATURE_NAMES


RALLY_FEATURE_VIEWS: Final[Mapping[str, RallyFeatureView]] = {
"full": _view("full", FULL_RALLY_FEATURE_NAMES),
"full_motion": _view(
"full_motion", MOTION_BASE_FEATURE_NAMES + MOTION_FEATURE_NAMES, uses_motion=True
"full_motion", _MOTION_VISUAL_FEATURE_NAMES, uses_motion=True
),
"full_audio_zscore_motion": _view(
"full_audio_zscore_motion",
MOTION_BASE_FEATURE_NAMES + MOTION_FEATURE_NAMES + RALLY_AUDIO_FEATURE_NAMES,
_MOTION_VISUAL_FEATURE_NAMES + RALLY_AUDIO_FEATURE_NAMES,
uses_audio=True, audio_zscore=True, uses_motion=True,
),
BASE_DISTANCE_RALLY_FEATURE_VIEW: _view(
BASE_DISTANCE_RALLY_FEATURE_VIEW,
_MOTION_VISUAL_FEATURE_NAMES + BASE_DISTANCE_FEATURE_NAMES + RALLY_AUDIO_FEATURE_NAMES,
uses_audio=True, audio_zscore=True, uses_motion=True, uses_singles_base=True,
),
BASE_RADIAL_RALLY_FEATURE_VIEW: _view(
BASE_RADIAL_RALLY_FEATURE_VIEW,
_MOTION_VISUAL_FEATURE_NAMES + BASE_FEATURE_NAMES + RALLY_AUDIO_FEATURE_NAMES,
uses_audio=True, audio_zscore=True, uses_motion=True, uses_singles_base=True,
),
"full_audio": _view(
"full_audio", FULL_RALLY_FEATURE_NAMES + RALLY_AUDIO_FEATURE_NAMES, uses_audio=True
),
Expand Down Expand Up @@ -288,6 +342,8 @@ def rally_feature_indices(names: Sequence[str]) -> tuple[int, ...]:
"full": 154,
"full_motion": 290,
"full_audio_zscore_motion": 297,
BASE_DISTANCE_RALLY_FEATURE_VIEW: 299,
BASE_RADIAL_RALLY_FEATURE_VIEW: 301,
"full_audio": 161,
"full_audio_zscore": 161,
"calibrated_canonical": 142,
Expand Down
34 changes: 34 additions & 0 deletions tests/test_independent_rally_segmenter.py
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,40 @@ def test_rally_motion_uses_elapsed_time_and_masks_gaps_and_track_changes(fps) ->
assert torch.equal(values[:, :positions.shape[1]], positions)


def test_rally_singles_base_features_use_metric_distance_and_mask_discontinuous_motion() -> None:
from src.court_projection import HALF_LENGTH, HALF_SINGLES_WIDTH, HALF_WIDTH
from src.temporal_selector.rally_features import (
FULL_RALLY_FEATURE_NAMES,
rally_singles_base_features,
)

values = torch.zeros(8, len(FULL_RALLY_FEATURE_NAMES))
observed = torch.ones_like(values, dtype=torch.bool)
tracks = torch.ones(8, 2, dtype=torch.long)
near_x, near_y, far_y = (
FULL_RALLY_FEATURE_NAMES.index(name)
for name in ("p1_court_x", "p1_court_y", "p2_court_y")
)
distance_metres = torch.arange(8) * 0.25
values[:, near_x] = distance_metres / HALF_WIDTH
values[:, near_y] = -0.5
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)

normalization = (HALF_SINGLES_WIDTH**2 + (HALF_LENGTH / 2)**2)**0.5
assert torch.allclose(features[:4, 0], distance_metres[:4] / normalization)
assert torch.allclose(features[:, 1], distance_metres.flip((0,)) / normalization)
assert torch.isclose(features[3, 2], torch.tensor(7.5 / normalization))
assert torch.isclose(features[3, 3], torch.tensor(-7.5 / normalization))
assert valid[:, 2].tolist() == [False, False, False, True, False, False, False, False]
assert valid[:, 3].tolist() == [False, False, False, True, False, False, False, True]
assert not valid[4, 0]
assert valid[-1, 1] and features[-1, 1] == 0
assert torch.count_nonzero(features[~valid]) == 0


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 (
Expand Down
5 changes: 4 additions & 1 deletion tests/test_rally_pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -435,7 +435,10 @@ 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"])
@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",
])
def test_pipeline_uses_manifest_feature_view(pipeline, view):
kwargs, _ = pipeline
config = RallySegmenterConfig(
Expand Down
2 changes: 2 additions & 0 deletions tests/test_shortcut_diagnostic.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ def test_registered_feature_views_have_exact_names_dimensions_and_masks() -> Non
"full": 154,
"full_motion": 290,
"full_audio_zscore_motion": 297,
"full_audio_zscore_motion_base_distance": 299,
"full_audio_zscore_motion_base_radial": 301,
"full_audio": 161,
"full_audio_zscore": 161,
"calibrated_canonical": 142,
Expand Down
Loading