diff --git a/docs/rally-training.md b/docs/rally-training.md index b73697c..ce644ae 100644 --- a/docs/rally-training.md +++ b/docs/rally-training.md @@ -158,6 +158,32 @@ threshold on its validation frames. The production checkpoint freezes both thresholds using out-of-fold predictions, along with the gap and minimum-duration settings. +## Context-window grid + +Run the three centered windows sequentially with the same local config and +training recipe. At 30 fps, the full windows contain 121, 241, and 481 frames. +They have two, four, and eight seconds of lookahead respectively. Each arm +uses the same one-second ownership by default and tunes its decoder using +only its validation frames. + +```bash +for span in 4 8 16; do + python -u -m src.temporal_selector.rally_experiment \ + --config config/rally-experiment.local.json --output-dir "outputs/rally-context/${span}s" \ + --clean-only --evaluation-only --preset rtmpose-audio --device cuda \ + --epochs 25 --seed 1729 --batch-size 16 --context-span-seconds "$span" || exit +done +python -m experiments.temporal_selector.rally_context_grid \ + --config config/rally-experiment.local.json --run-root outputs/rally-context +``` + +Read `comparison.json` for false starts, interval recall and precision, and +false splits on each held-out camera. A false start here is a complete decoded +interval inside reviewed out-of-play footage, with an observed transition +into and out of the prediction. The report includes source-local timestamps +for checking shuttle passes. The rally annotations do not identify the +activity in a break. + ## Joint and court velocity representation The canonical view adds signed x/y velocity for each pose landmark and each diff --git a/experiments/temporal_selector/rally_context_grid.py b/experiments/temporal_selector/rally_context_grid.py new file mode 100644 index 0000000..eff7f61 --- /dev/null +++ b/experiments/temporal_selector/rally_context_grid.py @@ -0,0 +1,131 @@ +"""Summarize held-out predictions for the 4, 8, and 16 second InPlay grid.""" + +import argparse +import hashlib +import json +from itertools import groupby +from pathlib import Path + +from src.temporal_selector.rally_dataset import rally_data_config_from_selector_mapping +from src.temporal_selector.rally_intervals import read_rally_intervals +from src.workflow.artifacts import atomic_write_json + +SPANS = (4, 8, 16) + + +def break_predictions(rows, fps): + """Find decoded intervals that start and finish in reviewed breaks.""" + events = [] + for (is_inplay, _), group in groupby(enumerate(rows), key=lambda item: ( + item[1]["decoded_inplay"], item[1]["frame"] - item[0] + )): + if not is_inplay: + continue + run = list(group) + start_index, start = run[0] + end_index, end = run[-1] + if start_index == 0 or end_index == len(rows) - 1: + continue + before, after = rows[start_index - 1], rows[end_index + 1] + if ( + before["frame"] != start["frame"] - 1 or after["frame"] != end["frame"] + 1 + or before["decoded_inplay"] or after["decoded_inplay"] + or before["inplay_target"] != 0 or after["inplay_target"] not in (0, 1) + or any(row["inplay_target"] != 0 for _, row in run) + ): + continue + events.append({ + "start_frame": start["frame"], + "end_frame": end["frame"], + "start_seconds": start["frame"] / fps, + "duration_seconds": len(run) / fps, + }) + return events + + +def summarize(root, fps_by_source): + runs = {} + reference = None + for span in SPANS: + arm = root / f"{span}s" + metrics = json.loads((arm / "metrics.json").read_text()) + dataset = metrics["dataset_manifest"] + if dataset["context_seconds"] * 2 != span: + raise ValueError(f"{arm} has the wrong context duration") + split_keys = ("train_window_ids", "validation_window_ids", "test_window_ids") + identity = { + "dataset": {key: dataset[key] for key in ( + "sources", "annotation_fingerprint", "feature_view", "feature_names", + "ownership_seconds", "audio_coverage", "pose_visibility_threshold", + "pose_coordinate_mode", "pose_representation_version", + )}, + "pose": {key: value for key, value in dataset["pose_training_metadata"]["preprocessing"].items() + if key != "context_seconds"}, + "pose_model": dataset["pose_training_metadata"]["pose_model_sha256"], + "recipe": metrics["training_recipe"], + "camera_sources": metrics["camera_sources"], + "folds": [ + {**{key: fold["split_manifest"][key] for key in split_keys}, + "ranges": fold["split_manifest"]["train_validation"]["cameras"]} + for fold in metrics["folds"] + ], + } + by_camera = {} + labels = hashlib.sha256() + for fold in metrics["folds"]: + split = fold["split_manifest"] + camera = split["held_out_camera"] + prediction_path = arm / f"fold-{split['fold_id']}-{camera}" / "test-predictions.jsonl" + sources = {} + with prediction_path.open() as predictions: + for source, group in groupby(map(json.loads, predictions), key=lambda row: row["source_id"]): + rows = list(group) + labels.update(json.dumps([source, [(row["frame"], row["inplay_target"]) + for row in rows]]).encode()) + events = break_predictions(rows, fps_by_source[source]) + sources[source] = { + "false_starts": len(events), + "reviewed_break_seconds": sum(row["inplay_target"] == 0 for row in rows) / fps_by_source[source], + "events": events, + } + intervals = fold["test"]["intervals"] + by_camera[camera] = { + "false_starts": sum(row["false_starts"] for row in sources.values()), + "interval_f1": intervals["f1"], + "interval_precision": intervals["precision"], + "interval_recall": intervals["recall"], + "false_splits": intervals["false_split_count"], + "by_source": sources, + } + identity["held_out_labels"] = labels.hexdigest() + if reference is None: + reference = identity + elif reference != identity: + raise ValueError(f"{arm} differs from the 4-second arm in inputs, recipe, or splits") + runs[f"{span}s"] = { + "false_starts": sum(row["false_starts"] for row in by_camera.values()), + "reviewed_break_seconds": sum( + source["reviewed_break_seconds"] + for row in by_camera.values() for source in row["by_source"].values() + ), + "macro": metrics["macro"], + "by_camera": by_camera, + } + return {"context_spans_seconds": list(SPANS), "training_recipe": reference["recipe"], "runs": runs} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--run-root", type=Path, required=True) + args = parser.parse_args() + config = rally_data_config_from_selector_mapping( + json.loads(args.config.read_text()), base_dir=args.config.resolve().parent, + ) + index = read_rally_intervals(config.rally_intervals_path, config.rally_manifest_path) + result = summarize(args.run_root, {source: manifest.fps for source, manifest in index.sources.items()}) + atomic_write_json(args.run_root / "comparison.json", result) + + +if __name__ == "__main__": + main() diff --git a/src/temporal_selector/rally_experiment.py b/src/temporal_selector/rally_experiment.py index 6645646..0016cd5 100644 --- a/src/temporal_selector/rally_experiment.py +++ b/src/temporal_selector/rally_experiment.py @@ -1012,6 +1012,7 @@ def run_clean_rally_experiment( require_rtmpose: bool = False, person_model: str | None = None, pose_model: Path | None = None, + evaluation_only: bool = False, ) -> dict[str, Any]: """Run candidate-free camera-held-out training without loading shuttle artifacts.""" recipe = recipe or RallyTrainingRecipe() @@ -1177,6 +1178,20 @@ def run_clean_rally_experiment( } _write_json(fold_dir / "metrics.json", fold_result) fold_artifacts.append(fold_result) + result = { + "schema": "clean_cross_camera_rally_segmenter", + "schema_version": 1, + "dataset_manifest": rally_dataset.manifest, + "training_recipe": asdict(recipe), + "camera_sources": {key: list(value) for key, value in camera_sources.items()}, + "folds": fold_artifacts, + "by_camera": camera_metrics, + "macro": _macro_metrics(camera_metrics), + "production": None, + } + if evaluation_only: + _write_json(output_dir / "metrics.json", result) + return result production_epoch = round(statistics.median(selected_epochs)) production = RallySegmenter(model_config).to(device) production_history = train_rally_segmenter_fixed_epochs( @@ -1223,15 +1238,10 @@ def run_clean_rally_experiment( "experiment_role": "expanded_clean_only_production"}, ) torch.save(production_checkpoint, output_dir / "production-rally-segmenter.pt") - result = { - "schema": "clean_cross_camera_rally_segmenter", "schema_version": 1, - "dataset_manifest": rally_dataset.manifest, - "training_recipe": asdict(recipe), "camera_sources": {key: list(value) for key, value in camera_sources.items()}, - "folds": fold_artifacts, "by_camera": camera_metrics, - "macro": _macro_metrics(camera_metrics), - "production": {"checkpoint": "production-rally-segmenter.pt", - "chosen_epoch": production_epoch, - "decoder_configuration": asdict(oof_decoder)}, + result["production"] = { + "checkpoint": "production-rally-segmenter.pt", + "chosen_epoch": production_epoch, + "decoder_configuration": asdict(oof_decoder), } _write_json(output_dir / "metrics.json", result) return result @@ -1462,6 +1472,14 @@ def _parser() -> argparse.ArgumentParser: help="Resume the clean-only run from committed epochs", ) parser.add_argument("--clean-only", action="store_true") + parser.add_argument( + "--context-span-seconds", type=float, + help="Full centered context duration, split equally before and after the anchor", + ) + parser.add_argument( + "--evaluation-only", action="store_true", + help="Evaluate held-out cameras and skip fitting an all-source model", + ) 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( @@ -1474,7 +1492,10 @@ def _parser() -> argparse.ArgumentParser: def main(argv: Sequence[str] | None = None) -> int: - args = _parser().parse_args(argv) + parser = _parser() + args = parser.parse_args(argv) + if not args.clean_only and (args.context_span_seconds is not None or args.evaluation_only): + parser.error("--context-span-seconds and --evaluation-only require --clean-only") raw_training = json.loads(args.config.expanduser().read_text(encoding="utf-8")).get( "training", {} ) @@ -1521,6 +1542,8 @@ def main(argv: Sequence[str] | None = None) -> int: RALLY_TRANSFORMER_CONTEXT_RADIUS_SECONDS if rtmpose_preset else RallyDataConfig.context_seconds ), ) + if args.context_span_seconds is not None: + data_config = replace(data_config, context_seconds=args.context_span_seconds / 2) feature_view = args.feature_view if rtmpose_preset and feature_view is None: feature_view = CANONICAL_RALLY_FEATURE_VIEW @@ -1543,6 +1566,7 @@ def main(argv: Sequence[str] | None = None) -> int: require_rtmpose=rtmpose_preset, person_model=args.person_model, pose_model=args.pose_model, + evaluation_only=args.evaluation_only, ) return 0 if args.candidate_inclusive_only: diff --git a/tests/test_rally_context_grid.py b/tests/test_rally_context_grid.py new file mode 100644 index 0000000..b881877 --- /dev/null +++ b/tests/test_rally_context_grid.py @@ -0,0 +1,20 @@ +from experiments.temporal_selector.rally_context_grid import break_predictions + + +def test_break_predictions_requires_a_complete_prediction_in_reviewed_break(): + def rows(first_frame, labels, decoded): + return [ + {"frame": frame, "inplay_target": label, "decoded_inplay": bool(predicted)} + for frame, (label, predicted) in enumerate(zip(labels, decoded, strict=True), first_frame) + ] + + predictions = ( + rows(0, [0, 0, 0, 0], [0, 1, 1, 0]) + + rows(6, [0, 0, 0], [1, 1, 0]) + + rows(10, [0, 0, -100, 0, 0], [0, 1, 1, 1, 0]) + + rows(16, [0, 0, 1, 0], [0, 1, 1, 0]) + + rows(21, [0, 0, 0], [0, 1, 1]) + ) + assert break_predictions(predictions, fps=4) == [ + {"start_frame": 1, "end_frame": 2, "start_seconds": 0.25, "duration_seconds": 0.5} + ] diff --git a/tests/test_rally_training_recovery.py b/tests/test_rally_training_recovery.py index 94d564b..7b1df00 100644 --- a/tests/test_rally_training_recovery.py +++ b/tests/test_rally_training_recovery.py @@ -252,6 +252,9 @@ def test_cli_resolves_config_and_command_line_overrides(tmp_path, monkeypatch): assert called["resume"] +@pytest.mark.parametrize( + ("cli_span", "evaluation_only"), [(None, False), (16, True)] +) @pytest.mark.parametrize( ("dataset_overrides", "expected_seconds"), [({}, 2.0), ({"rally_context_seconds": 3.0}, 3.0)] ) @@ -261,6 +264,7 @@ def test_cli_resolves_config_and_command_line_overrides(tmp_path, monkeypatch): ) def test_rtmpose_preset_defaults_to_canonical_motion_and_allows_audio_baseline( tmp_path, monkeypatch, dataset_overrides, expected_seconds, cli_view, expected_view, + cli_span, evaluation_only, ): import json @@ -282,6 +286,7 @@ def test_rtmpose_preset_defaults_to_canonical_motion_and_allows_audio_baseline( feature_view=config.feature_view, smoothing_weight=k["recipe"].temporal_smoothing_weight, require_rtmpose=k["require_rtmpose"], + evaluation_only=k["evaluation_only"], )) arguments = [ "--config", str(config), "--output-dir", str(tmp_path / "output"), @@ -289,10 +294,13 @@ def test_rtmpose_preset_defaults_to_canonical_motion_and_allows_audio_baseline( ] if cli_view is not None: arguments.extend(("--feature-view", cli_view)) + if cli_span is not None: + arguments.extend(("--context-span-seconds", str(cli_span), "--evaluation-only")) + expected_seconds = cli_span / 2 assert training.main(arguments) == 0 assert called == { "context": expected_seconds, "feature_view": expected_view, "smoothing_weight": 0.1, - "require_rtmpose": True, + "require_rtmpose": True, "evaluation_only": evaluation_only, }