Skip to content
Merged
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
33 changes: 33 additions & 0 deletions docs/rally-training.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,3 +152,36 @@ Each fold tunes a higher rally entry threshold and a lower continuation
threshold on its validation frames.
The production checkpoint freezes both thresholds using out-of-fold
predictions, along with the gap and minimum-duration settings.

## Joint and court velocity experiment

Use `--clean-only --feature-view full_motion` to add signed x/y velocity for
each pose landmark and each player's court position. Use
`full_audio_zscore_motion` for the corresponding normalized-audio recipe.
Both views use the existing court-centered coordinate convention, with the
court center at zero and the outer lines at ±1 along each axis. Coordinates
can extend beyond the lines. A centered three-frame median on each court
axis suppresses isolated spikes in the position channels. It uses one frame
of lookahead within the offline source or split clip. All three samples must
be valid, belong to the same track, and have an accepted, unrepaired pose with
visible landmarks on both feet. An available foot diagnostic must not
disagree with the assigned side and court bounds. Other positions retain
their original values and masks.

The motion views map crop landmarks back to image pixels using the exact
stored crop box. They center pose on the midpoint of the hips and normalize
by the median visible shoulder-midpoint to hip-midpoint distance for that
player track within the source or split clip. Frames with either hip missing
or no usable track torso scale have masked pose features.

Joint velocity uses a trailing three-frame slope and court velocity uses
four raw projected positions before the median. Slopes are per second, in torso-length units for joints and
court half-width or half-length units for court position. A velocity requires
all samples in its window to be valid and on the same track. Motion is computed
before slicing overlapping model windows.

Compare motion views on the same camera folds and source artifacts, with the
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.
6 changes: 3 additions & 3 deletions experiments/temporal_selector/shortcut_diagnostic.py
Original file line number Diff line number Diff line change
Expand Up @@ -369,8 +369,8 @@ def project_rally_windows(
view = RALLY_FEATURE_VIEWS.get(feature_view)
if view is None:
raise ValueError(f"unknown rally feature view: {feature_view}")
if view.uses_audio:
raise ValueError("audio features must be compiled from the source recording")
if view.uses_audio or view.uses_motion:
raise ValueError("audio and motion features must be compiled from the source recording")
output: list[RallyWindow] = []
for window in windows:
if window.frame_values.shape[-1] != len(FULL_RALLY_FEATURE_NAMES):
Expand Down Expand Up @@ -659,7 +659,7 @@ def run_rally_feature_ablations(
view_results: dict[str, Any] = {}
predictions: dict[str, list[dict[str, Any]]] = {}
for view_name, view in RALLY_FEATURE_VIEWS.items():
if view.uses_audio:
if view.uses_audio or view.uses_motion:
continue
view_dir = output_dir / view_name
view_dir.mkdir()
Expand Down
4 changes: 3 additions & 1 deletion src/temporal_selector/rally.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,9 @@ def __post_init__(self) -> None:
raise ValueError("dropout must be in [0, 1)")
if self.layer_norm_eps <= 0:
raise ValueError("layer_norm_eps must be positive")
if self.audio_attention and self.frame_feature_dim != RALLY_FEATURE_VIEWS["full_audio"].dimension:
if self.audio_attention and self.frame_feature_dim not in {
view.dimension for view in RALLY_FEATURE_VIEWS.values() if view.uses_audio
}:
raise ValueError("audio attention requires the full visual and audio features")


Expand Down
159 changes: 105 additions & 54 deletions src/temporal_selector/rally_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,10 @@
from .rally_audio import read_rally_audio
from .rally_features import (
FULL_RALLY_FEATURE_NAMES,
normalize_rally_motion_pose,
rally_feature_view,
rally_motion_features,
smooth_rally_court_positions,
)
from .rally_intervals import read_rally_intervals

Expand Down Expand Up @@ -127,6 +130,32 @@ class RallyWindow:
metadata: Mapping[str, Any] = field(default_factory=dict)


def _reliable_court_foot(
slot: Mapping, pose: Mapping, visibility_threshold: float,
) -> bool:
"""Require an accepted, unrepaired pose with visible evidence from both feet."""
if (
pose.get("status") != "detected"
or pose.get("temporal_status") not in (None, "original", "validated")
):
return False
if slot.get("foot_diagnostic", {}).get("status") == "disagrees":
return False
landmarks = pose.get("pose_landmarks") or []
if len(landmarks) != 33:
return False
threshold = max(0.5, visibility_threshold)
return all(
any(
float(landmarks[index].get("visibility", 0)) >= threshold
and math.isfinite(float(landmarks[index]["x"]))
and math.isfinite(float(landmarks[index]["y"]))
for index in foot
)
for foot in ((29, 31), (30, 32))
)


class RallyWindowDataset(Dataset[RallyWindow]):
"""Compile dense source-local windows without loading shuttle artifacts."""

Expand Down Expand Up @@ -163,9 +192,10 @@ def __init__(self, config: RallyDataConfig):
"feature_view": self.feature_view.name,
"feature_names": self.feature_view.names,
"pose_coordinate_mode": config.pose_coordinate_mode,
"pose_representation_version": POSE_REPRESENTATION_VERSION[
config.pose_coordinate_mode
],
"pose_representation_version": (
"pelvis-root-track-median-torso-v1" if self.feature_view.uses_motion
else POSE_REPRESENTATION_VERSION[config.pose_coordinate_mode]
),
"pose_visibility_threshold": config.pose_visibility_threshold,
"context_seconds": config.context_seconds,
"ownership_seconds": config.ownership_seconds,
Expand Down Expand Up @@ -383,6 +413,70 @@ def _compile_source(
radius = max(1, round(fps * self.config.context_seconds))
if radius < ownership // 2:
raise ValueError("rally context radius must cover the entire ownership window")
source_values: list[list[float]] = []
source_validity: list[list[bool]] = []
track_ids: list[list[int]] = []
reliable_feet: list[list[bool]] = []
for frame in range(frame_count):
frame_values, frame_validity = frame_context(
assignments[frame],
poses,
frame,
image_size,
"full_context",
self.config.pose_visibility_threshold,
"image" if self.feature_view.uses_motion else self.config.pose_coordinate_mode,
)
for player_index, role in enumerate(("P1", "P2")):
item = assignments[frame].get("slots", {}).get(role, {}).get("assignment")
if not isinstance(item, Mapping):
continue
projected = homography.project_to_court([item["foot"]])[0]
cached = np.asarray([item.get("court_x"), item.get("court_y")], dtype=float)
if not np.isfinite(cached).all() or not np.allclose(
cached,
projected,
rtol=0.0,
atol=self.config.cached_court_tolerance,
):
raise ValueError(
f"cached assignment court coordinates disagree with canonical calibration at frame {frame} {role}"
)
offset = player_index * 11
frame_values[offset + 6] = float(projected[0]) / HALF_WIDTH
frame_values[offset + 7] = float(projected[1]) / HALF_LENGTH
source_values.append(frame_values)
source_validity.append(frame_validity)
if self.feature_view.uses_motion:
frame_tracks = []
frame_reliability = []
for role in ("P1", "P2"):
slot = assignments[frame]["slots"].get(role, {})
item = slot.get("assignment")
track = int(item["track_id"]) if isinstance(item, Mapping) else -1
frame_tracks.append(track)
frame_reliability.append(_reliable_court_foot(
slot, poses.get((frame, track), {}), self.config.pose_visibility_threshold,
))
track_ids.append(frame_tracks)
reliable_feet.append(frame_reliability)
value_tensor = torch.tensor(source_values, dtype=torch.float32)
validity_tensor = torch.tensor(source_validity, dtype=torch.bool)
if self.feature_view.uses_motion:
track_tensor = torch.tensor(track_ids)
normalize_rally_motion_pose(value_tensor, validity_tensor, track_tensor, image_size)
velocity, velocity_valid = rally_motion_features(
value_tensor, validity_tensor, track_tensor, fps
)
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)
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)
value_tensor, validity_tensor = self.feature_view.select(value_tensor, validity_tensor)
windows: list[RallyWindow] = []
for owned_start in range(0, frame_count, ownership):
owned = frozenset(
Expand All @@ -392,51 +486,12 @@ def _compile_source(
start = max(0, anchor - radius)
end = min(frame_count - 1, anchor + radius)
frames = tuple(range(start, end + 1))
values: list[list[float]] = []
validity: list[list[bool]] = []
targets: list[int] = []
for frame in frames:
frame_values, frame_validity = frame_context(
assignments[frame],
poses,
frame,
image_size,
"full_context",
self.config.pose_visibility_threshold,
self.config.pose_coordinate_mode,
)
for player_index, role in enumerate(("P1", "P2")):
item = assignments[frame].get("slots", {}).get(role, {}).get("assignment")
if not isinstance(item, Mapping):
continue
projected = homography.project_to_court([item["foot"]])[0]
cached = np.asarray([item.get("court_x"), item.get("court_y")], dtype=float)
if not np.isfinite(cached).all() or not np.allclose(
cached,
projected,
rtol=0.0,
atol=self.config.cached_court_tolerance,
):
raise ValueError(
f"cached assignment court coordinates disagree with canonical calibration at frame {frame} {role}"
)
offset = player_index * 11
frame_values[offset + 6] = float(projected[0]) / HALF_WIDTH
frame_values[offset + 7] = float(projected[1]) / HALF_LENGTH
if audio is not None:
frame_values.extend(audio_values[frame].tolist())
frame_validity.extend(audio.validity[frame].tolist())
selected_values, selected_validity = self.feature_view.select(
torch.tensor(frame_values, dtype=torch.float32),
torch.tensor(frame_validity, dtype=torch.bool),
)
values.append(selected_values.tolist())
validity.append(selected_validity.tolist())
targets.append(
self.rally_index.target(source.source_id, frame)
if self.rally_index is not None and frame in owned
else MASKED_TARGET
)
targets = [
self.rally_index.target(source.source_id, frame)
if self.rally_index is not None and frame in owned
else MASKED_TARGET
for frame in frames
]
if self.rally_index is not None:
start_targets, end_targets = rally_boundary_targets(
self.rally_index.for_source(source.source_id),
Expand All @@ -460,12 +515,8 @@ def _compile_source(
[(frame - anchor) / fps for frame in frames],
dtype=torch.float32,
),
frame_values=torch.tensor(
values, dtype=torch.float32
).reshape(len(frames), self.feature_view.dimension),
frame_validity=torch.tensor(
validity, dtype=torch.bool
).reshape(len(frames), self.feature_view.dimension),
frame_values=value_tensor[start : end + 1].clone(),
frame_validity=validity_tensor[start : end + 1].clone(),
inplay_targets=torch.tensor(targets, dtype=torch.long),
rally_start_targets=start_targets,
rally_end_targets=end_targets,
Expand Down
8 changes: 5 additions & 3 deletions src/temporal_selector/rally_experiment.py
Original file line number Diff line number Diff line change
Expand Up @@ -1490,8 +1490,8 @@ 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"):
raise ValueError("the RTMPose audio preset requires the full_audio_zscore feature view")
if args.feature_view not in (None, "full_audio_zscore", "full_audio_zscore_motion"):
raise ValueError("the RTMPose audio preset requires a normalized-audio feature view")
overrides.setdefault("temporal_smoothing_weight", 0.1)
recipe = RallyTrainingRecipe.from_preset(
"default" if rtmpose_preset else args.preset, **overrides
Expand All @@ -1517,7 +1517,9 @@ def main(argv: Sequence[str] | None = None) -> int:
RALLY_TRANSFORMER_CONTEXT_RADIUS_SECONDS if rtmpose_preset else RallyDataConfig.context_seconds
),
)
feature_view = "full_audio_zscore" if rtmpose_preset else args.feature_view
feature_view = args.feature_view
if rtmpose_preset and feature_view is None:
feature_view = "full_audio_zscore"
if feature_view is not None:
data_config = replace(data_config, feature_view=feature_view)
camera_sources = _load_camera_sources(raw.get("camera_sources"))
Expand Down
Loading
Loading