NLag commited on
Commit ·
7f45320
1
Parent(s): b091f38
Add temporal router model selection
Browse files
README.md
CHANGED
|
@@ -213,14 +213,27 @@ The Modal app uses:
|
|
| 213 |
|
| 214 |
- `pozify-router-data` for raw videos, manifests, and feature caches.
|
| 215 |
- `pozify-router-models` for `baseline.joblib`, `temporal.pt`, `evaluation.json`, and the selected
|
| 216 |
-
|
| 217 |
|
| 218 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
|
| 220 |
```text
|
| 221 |
-
models/exercise_router/active/
|
| 222 |
```
|
| 223 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
Custom unknown clips can be uploaded into the data volume at `/data/raw/custom_unknown/` before the
|
| 225 |
`features` stage. Use consented clips only; useful unknown examples include idle standing, walking
|
| 226 |
into frame, setup motion, stretching, bad camera angle, and partial/unsupported reps. Unsupported
|
|
|
|
| 213 |
|
| 214 |
- `pozify-router-data` for raw videos, manifests, and feature caches.
|
| 215 |
- `pozify-router-models` for `baseline.joblib`, `temporal.pt`, `evaluation.json`, and the selected
|
| 216 |
+
router artifact.
|
| 217 |
|
| 218 |
+
The baseline trains a scikit-learn model over engineered window vectors. The temporal stage trains a
|
| 219 |
+
compact BiLSTM over 30-frame feature tensors on a Modal A10 GPU and writes `temporal.pt` plus
|
| 220 |
+
`temporal_metrics.json`. Its default hyperparameters follow the Riccio exercise-classification paper:
|
| 221 |
+
73 hidden units, 0.2174 dropout, 0.0004 learning rate, batch size 54, and 73 epochs
|
| 222 |
+
(https://arxiv.org/abs/2411.11548). Evaluation scores every available trained artifact, writes
|
| 223 |
+
per-model metrics into `evaluation.json`, and records the active artifact in `router_selection.json`.
|
| 224 |
+
Baseline wins ties to keep runtime inference lightweight unless the temporal model clearly improves
|
| 225 |
+
the metrics.
|
| 226 |
+
|
| 227 |
+
Download the selected artifact and its selection file after evaluation, then place them under:
|
| 228 |
|
| 229 |
```text
|
| 230 |
+
models/exercise_router/active/
|
| 231 |
```
|
| 232 |
|
| 233 |
+
For the baseline this directory should contain `router.joblib`; for the temporal model it should
|
| 234 |
+
contain `router.pt`. In both cases, include `router_selection.json` when present so the local loader
|
| 235 |
+
can choose the intended active artifact even if multiple artifacts exist.
|
| 236 |
+
|
| 237 |
Custom unknown clips can be uploaded into the data volume at `/data/raw/custom_unknown/` before the
|
| 238 |
`features` stage. Use consented clips only; useful unknown examples include idle standing, walking
|
| 239 |
into frame, setup motion, stretching, bad camera angle, and partial/unsupported reps. Unsupported
|
scripts/exercise_router_modal.py
CHANGED
|
@@ -325,14 +325,29 @@ def train_baseline() -> dict[str, Any]:
|
|
| 325 |
return metrics
|
| 326 |
|
| 327 |
|
| 328 |
-
@app.function(gpu="
|
| 329 |
-
def train_temporal(epochs: int =
|
| 330 |
import torch
|
| 331 |
from torch import nn
|
| 332 |
from torch.utils.data import DataLoader, TensorDataset
|
|
|
|
| 333 |
|
| 334 |
sys.path.insert(0, "/root/src")
|
| 335 |
from pozify.ml.exercise_router_features import ROUTER_LABELS
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
|
| 337 |
_vectors, tensors, labels = _load_feature_arrays()
|
| 338 |
if tensors is None or len(set(labels)) < 2:
|
|
@@ -342,24 +357,38 @@ def train_temporal(epochs: int = 8) -> dict[str, Any]:
|
|
| 342 |
return result
|
| 343 |
|
| 344 |
label_to_index = {label: index for index, label in enumerate(ROUTER_LABELS)}
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
|
|
|
|
|
|
|
|
|
| 359 |
|
| 360 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 361 |
-
|
| 362 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
loss_fn = nn.CrossEntropyLoss()
|
| 364 |
model.train()
|
| 365 |
last_loss = 0.0
|
|
@@ -373,60 +402,186 @@ def train_temporal(epochs: int = 8) -> dict[str, Any]:
|
|
| 373 |
optimizer.step()
|
| 374 |
last_loss = float(loss.detach().cpu())
|
| 375 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 376 |
torch.save(
|
| 377 |
{
|
| 378 |
"model_kind": "temporal",
|
| 379 |
-
"architecture":
|
| 380 |
"state_dict": model.cpu().state_dict(),
|
| 381 |
"labels": list(ROUTER_LABELS),
|
| 382 |
-
"input_size": int(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 383 |
},
|
| 384 |
MODEL_ROOT / "temporal.pt",
|
| 385 |
)
|
| 386 |
metrics = {
|
| 387 |
"ok": True,
|
| 388 |
"model_kind": "temporal",
|
| 389 |
-
"architecture":
|
| 390 |
"epochs": epochs,
|
| 391 |
"final_training_loss": round(last_loss, 4),
|
| 392 |
-
"window_count": int(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 393 |
}
|
| 394 |
_write_json(MODEL_ROOT / "temporal_metrics.json", metrics)
|
| 395 |
model_volume.commit()
|
| 396 |
return metrics
|
| 397 |
|
| 398 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 399 |
@app.function(volumes={str(DATA_ROOT): data_volume, str(MODEL_ROOT): model_volume})
|
| 400 |
def evaluate() -> dict[str, Any]:
|
| 401 |
import joblib
|
| 402 |
|
| 403 |
sys.path.insert(0, "/root/src")
|
| 404 |
-
from pozify.ml.exercise_router_evaluation import
|
|
|
|
|
|
|
|
|
|
|
|
|
| 405 |
|
| 406 |
-
vectors,
|
| 407 |
baseline_path = MODEL_ROOT / "baseline.joblib"
|
| 408 |
-
|
| 409 |
-
|
|
|
|
| 410 |
_write_json(MODEL_ROOT / "evaluation.json", result)
|
| 411 |
model_volume.commit()
|
| 412 |
return result
|
| 413 |
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 417 |
result = {
|
| 418 |
"ok": True,
|
| 419 |
-
"selected_model": "
|
| 420 |
-
|
|
|
|
|
|
|
| 421 |
}
|
| 422 |
_write_json(MODEL_ROOT / "evaluation.json", result)
|
| 423 |
-
shutil.copyfile(baseline_path, MODEL_ROOT / "router.joblib")
|
| 424 |
model_volume.commit()
|
| 425 |
return result
|
| 426 |
|
| 427 |
|
| 428 |
@app.local_entrypoint()
|
| 429 |
-
def main(stage: str = "evaluate", limit: int | None = None, epochs: int =
|
| 430 |
if stage == "ingest":
|
| 431 |
print(ingest.remote())
|
| 432 |
elif stage == "features":
|
|
|
|
| 325 |
return metrics
|
| 326 |
|
| 327 |
|
| 328 |
+
@app.function(gpu="A10", volumes={str(DATA_ROOT): data_volume, str(MODEL_ROOT): model_volume}, timeout=60 * 60)
|
| 329 |
+
def train_temporal(epochs: int = 73) -> dict[str, Any]:
|
| 330 |
import torch
|
| 331 |
from torch import nn
|
| 332 |
from torch.utils.data import DataLoader, TensorDataset
|
| 333 |
+
from sklearn.model_selection import train_test_split
|
| 334 |
|
| 335 |
sys.path.insert(0, "/root/src")
|
| 336 |
from pozify.ml.exercise_router_features import ROUTER_LABELS
|
| 337 |
+
from pozify.ml.exercise_router_evaluation import (
|
| 338 |
+
evaluation_to_dict,
|
| 339 |
+
evaluate_router_predictions,
|
| 340 |
+
)
|
| 341 |
+
from pozify.ml.exercise_router_temporal import (
|
| 342 |
+
TEMPORAL_ARCHITECTURE,
|
| 343 |
+
TEMPORAL_BATCH_SIZE,
|
| 344 |
+
TEMPORAL_DROPOUT_RATE,
|
| 345 |
+
TEMPORAL_HIDDEN_SIZE,
|
| 346 |
+
TEMPORAL_LEARNING_RATE,
|
| 347 |
+
TEMPORAL_NUM_LAYERS,
|
| 348 |
+
TemporalRouterConfig,
|
| 349 |
+
build_temporal_router_model,
|
| 350 |
+
)
|
| 351 |
|
| 352 |
_vectors, tensors, labels = _load_feature_arrays()
|
| 353 |
if tensors is None or len(set(labels)) < 2:
|
|
|
|
| 357 |
return result
|
| 358 |
|
| 359 |
label_to_index = {label: index for index, label in enumerate(ROUTER_LABELS)}
|
| 360 |
+
label_indices = [label_to_index.get(label, label_to_index["unknown"]) for label in labels]
|
| 361 |
+
label_counts = {label: labels.count(label) for label in sorted(set(labels))}
|
| 362 |
+
stratify = labels if min(label_counts.values()) >= 2 else None
|
| 363 |
+
train_x, valid_x, train_y, valid_y, _train_labels, valid_labels = train_test_split(
|
| 364 |
+
tensors,
|
| 365 |
+
label_indices,
|
| 366 |
+
labels,
|
| 367 |
+
test_size=0.2,
|
| 368 |
+
random_state=42,
|
| 369 |
+
stratify=stratify,
|
| 370 |
+
)
|
| 371 |
+
train_dataset = TensorDataset(
|
| 372 |
+
torch.tensor(train_x, dtype=torch.float32),
|
| 373 |
+
torch.tensor(train_y, dtype=torch.long),
|
| 374 |
+
)
|
| 375 |
+
generator = torch.Generator().manual_seed(42)
|
| 376 |
+
loader = DataLoader(train_dataset, batch_size=TEMPORAL_BATCH_SIZE, shuffle=True, generator=generator)
|
| 377 |
|
| 378 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 379 |
+
torch.manual_seed(42)
|
| 380 |
+
if torch.cuda.is_available():
|
| 381 |
+
torch.cuda.manual_seed_all(42)
|
| 382 |
+
config = TemporalRouterConfig(
|
| 383 |
+
input_size=int(tensors.shape[-1]),
|
| 384 |
+
label_count=len(ROUTER_LABELS),
|
| 385 |
+
hidden_size=TEMPORAL_HIDDEN_SIZE,
|
| 386 |
+
num_layers=TEMPORAL_NUM_LAYERS,
|
| 387 |
+
bidirectional=True,
|
| 388 |
+
dropout_rate=TEMPORAL_DROPOUT_RATE,
|
| 389 |
+
)
|
| 390 |
+
model = build_temporal_router_model(config).to(device)
|
| 391 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=TEMPORAL_LEARNING_RATE, weight_decay=1e-4)
|
| 392 |
loss_fn = nn.CrossEntropyLoss()
|
| 393 |
model.train()
|
| 394 |
last_loss = 0.0
|
|
|
|
| 402 |
optimizer.step()
|
| 403 |
last_loss = float(loss.detach().cpu())
|
| 404 |
|
| 405 |
+
valid_predictions = _predict_temporal_labels(
|
| 406 |
+
model=model,
|
| 407 |
+
tensors=valid_x,
|
| 408 |
+
labels=ROUTER_LABELS,
|
| 409 |
+
device=device,
|
| 410 |
+
)
|
| 411 |
+
validation = evaluation_to_dict(evaluate_router_predictions(list(valid_labels), valid_predictions))
|
| 412 |
+
|
| 413 |
torch.save(
|
| 414 |
{
|
| 415 |
"model_kind": "temporal",
|
| 416 |
+
"architecture": TEMPORAL_ARCHITECTURE,
|
| 417 |
"state_dict": model.cpu().state_dict(),
|
| 418 |
"labels": list(ROUTER_LABELS),
|
| 419 |
+
"input_size": int(tensors.shape[-1]),
|
| 420 |
+
"hidden_size": TEMPORAL_HIDDEN_SIZE,
|
| 421 |
+
"num_layers": TEMPORAL_NUM_LAYERS,
|
| 422 |
+
"bidirectional": True,
|
| 423 |
+
"dropout_rate": TEMPORAL_DROPOUT_RATE,
|
| 424 |
+
"learning_rate": TEMPORAL_LEARNING_RATE,
|
| 425 |
+
"batch_size": TEMPORAL_BATCH_SIZE,
|
| 426 |
},
|
| 427 |
MODEL_ROOT / "temporal.pt",
|
| 428 |
)
|
| 429 |
metrics = {
|
| 430 |
"ok": True,
|
| 431 |
"model_kind": "temporal",
|
| 432 |
+
"architecture": TEMPORAL_ARCHITECTURE,
|
| 433 |
"epochs": epochs,
|
| 434 |
"final_training_loss": round(last_loss, 4),
|
| 435 |
+
"window_count": int(tensors.shape[0]),
|
| 436 |
+
"label_counts": label_counts,
|
| 437 |
+
"learning_rate": TEMPORAL_LEARNING_RATE,
|
| 438 |
+
"batch_size": TEMPORAL_BATCH_SIZE,
|
| 439 |
+
"hidden_size": TEMPORAL_HIDDEN_SIZE,
|
| 440 |
+
"dropout_rate": TEMPORAL_DROPOUT_RATE,
|
| 441 |
+
"validation": validation,
|
| 442 |
}
|
| 443 |
_write_json(MODEL_ROOT / "temporal_metrics.json", metrics)
|
| 444 |
model_volume.commit()
|
| 445 |
return metrics
|
| 446 |
|
| 447 |
|
| 448 |
+
def _predict_temporal_labels(
|
| 449 |
+
*,
|
| 450 |
+
model: Any,
|
| 451 |
+
tensors: Any,
|
| 452 |
+
labels: tuple[str, ...],
|
| 453 |
+
device: Any,
|
| 454 |
+
) -> list[str]:
|
| 455 |
+
import torch
|
| 456 |
+
from torch.utils.data import DataLoader, TensorDataset
|
| 457 |
+
|
| 458 |
+
dataset = TensorDataset(torch.tensor(tensors, dtype=torch.float32))
|
| 459 |
+
loader = DataLoader(dataset, batch_size=128, shuffle=False)
|
| 460 |
+
predictions: list[str] = []
|
| 461 |
+
model.eval()
|
| 462 |
+
with torch.no_grad():
|
| 463 |
+
for (batch_x,) in loader:
|
| 464 |
+
logits = model(batch_x.to(device))
|
| 465 |
+
predicted_indices = torch.argmax(logits, dim=1).detach().cpu().tolist()
|
| 466 |
+
predictions.extend(labels[index] for index in predicted_indices)
|
| 467 |
+
return predictions
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
def _evaluate_temporal_checkpoint(checkpoint_path: Path, tensors: Any) -> list[str]:
|
| 471 |
+
import torch
|
| 472 |
+
|
| 473 |
+
sys.path.insert(0, "/root/src")
|
| 474 |
+
from pozify.ml.exercise_router_temporal import TemporalRouterConfig, build_temporal_router_model
|
| 475 |
+
|
| 476 |
+
checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
|
| 477 |
+
labels = tuple(str(label) for label in checkpoint["labels"])
|
| 478 |
+
config = TemporalRouterConfig(
|
| 479 |
+
input_size=int(checkpoint["input_size"]),
|
| 480 |
+
label_count=len(labels),
|
| 481 |
+
hidden_size=int(checkpoint.get("hidden_size", 64)),
|
| 482 |
+
num_layers=int(checkpoint.get("num_layers", 1)),
|
| 483 |
+
bidirectional=bool(checkpoint.get("bidirectional", True)),
|
| 484 |
+
dropout_rate=float(checkpoint.get("dropout_rate", 0.2174)),
|
| 485 |
+
)
|
| 486 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 487 |
+
model = build_temporal_router_model(config).to(device)
|
| 488 |
+
model.load_state_dict(checkpoint["state_dict"])
|
| 489 |
+
return _predict_temporal_labels(
|
| 490 |
+
model=model,
|
| 491 |
+
tensors=tensors,
|
| 492 |
+
labels=labels,
|
| 493 |
+
device=device,
|
| 494 |
+
)
|
| 495 |
+
|
| 496 |
+
|
| 497 |
@app.function(volumes={str(DATA_ROOT): data_volume, str(MODEL_ROOT): model_volume})
|
| 498 |
def evaluate() -> dict[str, Any]:
|
| 499 |
import joblib
|
| 500 |
|
| 501 |
sys.path.insert(0, "/root/src")
|
| 502 |
+
from pozify.ml.exercise_router_evaluation import (
|
| 503 |
+
evaluation_to_dict,
|
| 504 |
+
evaluate_router_predictions,
|
| 505 |
+
select_router_candidate,
|
| 506 |
+
)
|
| 507 |
|
| 508 |
+
vectors, tensors, labels = _load_feature_arrays()
|
| 509 |
baseline_path = MODEL_ROOT / "baseline.joblib"
|
| 510 |
+
temporal_path = MODEL_ROOT / "temporal.pt"
|
| 511 |
+
if vectors is None or tensors is None:
|
| 512 |
+
result = {"ok": False, "error": "Feature arrays are required"}
|
| 513 |
_write_json(MODEL_ROOT / "evaluation.json", result)
|
| 514 |
model_volume.commit()
|
| 515 |
return result
|
| 516 |
|
| 517 |
+
candidates: list[dict[str, Any]] = []
|
| 518 |
+
model_results: dict[str, Any] = {}
|
| 519 |
+
if baseline_path.exists():
|
| 520 |
+
artifact = joblib.load(baseline_path)
|
| 521 |
+
predictions = list(artifact["model"].predict(vectors))
|
| 522 |
+
baseline_evaluation = evaluation_to_dict(evaluate_router_predictions(labels, predictions))
|
| 523 |
+
model_results["baseline"] = {
|
| 524 |
+
"ok": True,
|
| 525 |
+
"artifact": "baseline.joblib",
|
| 526 |
+
**baseline_evaluation,
|
| 527 |
+
}
|
| 528 |
+
candidates.append(
|
| 529 |
+
{
|
| 530 |
+
"name": "baseline",
|
| 531 |
+
"source_artifact": baseline_path,
|
| 532 |
+
"selected_artifact": "router.joblib",
|
| 533 |
+
**baseline_evaluation,
|
| 534 |
+
}
|
| 535 |
+
)
|
| 536 |
+
|
| 537 |
+
if temporal_path.exists():
|
| 538 |
+
predictions = _evaluate_temporal_checkpoint(temporal_path, tensors)
|
| 539 |
+
temporal_evaluation = evaluation_to_dict(evaluate_router_predictions(labels, predictions))
|
| 540 |
+
model_results["temporal"] = {
|
| 541 |
+
"ok": True,
|
| 542 |
+
"artifact": "temporal.pt",
|
| 543 |
+
**temporal_evaluation,
|
| 544 |
+
}
|
| 545 |
+
candidates.append(
|
| 546 |
+
{
|
| 547 |
+
"name": "temporal",
|
| 548 |
+
"source_artifact": temporal_path,
|
| 549 |
+
"selected_artifact": "router.pt",
|
| 550 |
+
**temporal_evaluation,
|
| 551 |
+
}
|
| 552 |
+
)
|
| 553 |
+
|
| 554 |
+
if not candidates:
|
| 555 |
+
result = {"ok": False, "error": "At least one trained router artifact is required"}
|
| 556 |
+
_write_json(MODEL_ROOT / "evaluation.json", result)
|
| 557 |
+
model_volume.commit()
|
| 558 |
+
return result
|
| 559 |
+
|
| 560 |
+
selected = select_router_candidate(candidates)
|
| 561 |
+
if selected["selected_artifact"] == "router.joblib":
|
| 562 |
+
shutil.copyfile(selected["source_artifact"], MODEL_ROOT / "router.joblib")
|
| 563 |
+
else:
|
| 564 |
+
shutil.copyfile(selected["source_artifact"], MODEL_ROOT / "router.pt")
|
| 565 |
+
selection = {
|
| 566 |
+
"selected_model": f"{selected['name']}.{ 'joblib' if selected['name'] == 'baseline' else 'pt' }",
|
| 567 |
+
"selected_artifact": selected["selected_artifact"],
|
| 568 |
+
"reason": "highest accuracy, then unknown rejection rate; baseline wins ties",
|
| 569 |
+
}
|
| 570 |
+
_write_json(MODEL_ROOT / "router_selection.json", selection)
|
| 571 |
result = {
|
| 572 |
"ok": True,
|
| 573 |
+
"selected_model": selection["selected_model"],
|
| 574 |
+
"selected_artifact": selection["selected_artifact"],
|
| 575 |
+
"models": model_results,
|
| 576 |
+
**{key: selected[key] for key in ("accuracy", "precision", "recall", "unknown_rejection_rate", "confusion_matrix")},
|
| 577 |
}
|
| 578 |
_write_json(MODEL_ROOT / "evaluation.json", result)
|
|
|
|
| 579 |
model_volume.commit()
|
| 580 |
return result
|
| 581 |
|
| 582 |
|
| 583 |
@app.local_entrypoint()
|
| 584 |
+
def main(stage: str = "evaluate", limit: int | None = None, epochs: int = 73) -> None:
|
| 585 |
if stage == "ingest":
|
| 586 |
print(ingest.remote())
|
| 587 |
elif stage == "features":
|
src/pozify/ml/exercise_router_evaluation.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
from dataclasses import dataclass
|
| 4 |
-
from typing import Any
|
| 5 |
|
| 6 |
from pozify.ml.exercise_router_features import ROUTER_LABELS
|
| 7 |
|
|
@@ -63,3 +63,16 @@ def evaluation_to_dict(evaluation: RouterEvaluation) -> dict[str, Any]:
|
|
| 63 |
"confusion_matrix": evaluation.confusion_matrix,
|
| 64 |
}
|
| 65 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
from dataclasses import dataclass
|
| 4 |
+
from typing import Any, Mapping, Sequence
|
| 5 |
|
| 6 |
from pozify.ml.exercise_router_features import ROUTER_LABELS
|
| 7 |
|
|
|
|
| 63 |
"confusion_matrix": evaluation.confusion_matrix,
|
| 64 |
}
|
| 65 |
|
| 66 |
+
|
| 67 |
+
def select_router_candidate(candidates: Sequence[Mapping[str, Any]]) -> Mapping[str, Any]:
|
| 68 |
+
if not candidates:
|
| 69 |
+
raise ValueError("At least one router candidate is required")
|
| 70 |
+
return max(candidates, key=router_candidate_sort_key)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def router_candidate_sort_key(candidate: Mapping[str, Any]) -> tuple[float, float, int]:
|
| 74 |
+
return (
|
| 75 |
+
float(candidate.get("accuracy", 0.0)),
|
| 76 |
+
float(candidate.get("unknown_rejection_rate", 0.0)),
|
| 77 |
+
1 if candidate.get("name") == "baseline" else 0,
|
| 78 |
+
)
|
src/pozify/ml/exercise_router_inference.py
CHANGED
|
@@ -1,19 +1,24 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
from dataclasses import dataclass
|
|
|
|
| 4 |
from pathlib import Path
|
| 5 |
from typing import Any
|
| 6 |
|
| 7 |
import numpy as np
|
| 8 |
|
| 9 |
from pozify.ml.exercise_router_features import ROUTER_LABELS, RouterWindow
|
|
|
|
| 10 |
|
| 11 |
|
| 12 |
DEFAULT_MODEL_DIR = Path("models/exercise_router/active")
|
|
|
|
| 13 |
MODEL_FILENAMES = (
|
| 14 |
"router.joblib",
|
|
|
|
| 15 |
"model.joblib",
|
| 16 |
"baseline.joblib",
|
|
|
|
| 17 |
"exercise_router.joblib",
|
| 18 |
)
|
| 19 |
MIN_FINAL_CONFIDENCE = 0.65
|
|
@@ -49,6 +54,10 @@ class AggregatedRouterPrediction:
|
|
| 49 |
|
| 50 |
|
| 51 |
def load_router_model(model_dir: Path = DEFAULT_MODEL_DIR) -> RouterModelBundle | None:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
for filename in MODEL_FILENAMES:
|
| 53 |
path = model_dir / filename
|
| 54 |
if not path.exists():
|
|
@@ -58,6 +67,9 @@ def load_router_model(model_dir: Path = DEFAULT_MODEL_DIR) -> RouterModelBundle
|
|
| 58 |
|
| 59 |
|
| 60 |
def load_router_model_file(path: Path) -> RouterModelBundle:
|
|
|
|
|
|
|
|
|
|
| 61 |
try:
|
| 62 |
import joblib
|
| 63 |
except ImportError as exc: # pragma: no cover - dependency is declared
|
|
@@ -88,6 +100,23 @@ def load_router_model_file(path: Path) -> RouterModelBundle:
|
|
| 88 |
)
|
| 89 |
|
| 90 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
def predict_window_probabilities(
|
| 92 |
bundle: RouterModelBundle,
|
| 93 |
windows: list[RouterWindow],
|
|
@@ -202,6 +231,17 @@ def _labels_from_artifact(labels: Any, model: Any) -> tuple[str, ...]:
|
|
| 202 |
return normalized or ROUTER_LABELS
|
| 203 |
|
| 204 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
def _score_map(row: np.ndarray, labels: tuple[str, ...]) -> dict[str, float]:
|
| 206 |
row = np.asarray(row, dtype=np.float64).reshape(-1)
|
| 207 |
if row.size == 1 and len(labels) == 2:
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
from dataclasses import dataclass
|
| 4 |
+
import json
|
| 5 |
from pathlib import Path
|
| 6 |
from typing import Any
|
| 7 |
|
| 8 |
import numpy as np
|
| 9 |
|
| 10 |
from pozify.ml.exercise_router_features import ROUTER_LABELS, RouterWindow
|
| 11 |
+
from pozify.ml.exercise_router_temporal import TorchTemporalRouter
|
| 12 |
|
| 13 |
|
| 14 |
DEFAULT_MODEL_DIR = Path("models/exercise_router/active")
|
| 15 |
+
ACTIVE_SELECTION_FILENAME = "router_selection.json"
|
| 16 |
MODEL_FILENAMES = (
|
| 17 |
"router.joblib",
|
| 18 |
+
"router.pt",
|
| 19 |
"model.joblib",
|
| 20 |
"baseline.joblib",
|
| 21 |
+
"temporal.pt",
|
| 22 |
"exercise_router.joblib",
|
| 23 |
)
|
| 24 |
MIN_FINAL_CONFIDENCE = 0.65
|
|
|
|
| 54 |
|
| 55 |
|
| 56 |
def load_router_model(model_dir: Path = DEFAULT_MODEL_DIR) -> RouterModelBundle | None:
|
| 57 |
+
selected_path = _selected_artifact_path(model_dir)
|
| 58 |
+
if selected_path is not None and selected_path.exists():
|
| 59 |
+
return load_router_model_file(selected_path)
|
| 60 |
+
|
| 61 |
for filename in MODEL_FILENAMES:
|
| 62 |
path = model_dir / filename
|
| 63 |
if not path.exists():
|
|
|
|
| 67 |
|
| 68 |
|
| 69 |
def load_router_model_file(path: Path) -> RouterModelBundle:
|
| 70 |
+
if path.suffix == ".pt":
|
| 71 |
+
return _load_temporal_router_model_file(path)
|
| 72 |
+
|
| 73 |
try:
|
| 74 |
import joblib
|
| 75 |
except ImportError as exc: # pragma: no cover - dependency is declared
|
|
|
|
| 100 |
)
|
| 101 |
|
| 102 |
|
| 103 |
+
def _load_temporal_router_model_file(path: Path) -> RouterModelBundle:
|
| 104 |
+
try:
|
| 105 |
+
import torch
|
| 106 |
+
except ImportError as exc: # pragma: no cover - optional runtime dependency
|
| 107 |
+
raise RuntimeError("torch is required to load temporal exercise router artifacts") from exc
|
| 108 |
+
|
| 109 |
+
checkpoint = torch.load(path, map_location="cpu", weights_only=False)
|
| 110 |
+
labels = _labels_from_artifact(checkpoint.get("labels"), checkpoint)
|
| 111 |
+
model = TorchTemporalRouter(checkpoint=checkpoint, labels=labels)
|
| 112 |
+
return RouterModelBundle(
|
| 113 |
+
model=model,
|
| 114 |
+
labels=labels,
|
| 115 |
+
scaler=None,
|
| 116 |
+
model_kind=str(checkpoint.get("model_kind", "temporal")),
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
def predict_window_probabilities(
|
| 121 |
bundle: RouterModelBundle,
|
| 122 |
windows: list[RouterWindow],
|
|
|
|
| 231 |
return normalized or ROUTER_LABELS
|
| 232 |
|
| 233 |
|
| 234 |
+
def _selected_artifact_path(model_dir: Path) -> Path | None:
|
| 235 |
+
selection_path = model_dir / ACTIVE_SELECTION_FILENAME
|
| 236 |
+
if not selection_path.exists():
|
| 237 |
+
return None
|
| 238 |
+
selection = json.loads(selection_path.read_text(encoding="utf-8"))
|
| 239 |
+
selected_artifact = selection.get("selected_artifact")
|
| 240 |
+
if not isinstance(selected_artifact, str) or not selected_artifact:
|
| 241 |
+
return None
|
| 242 |
+
return model_dir / selected_artifact
|
| 243 |
+
|
| 244 |
+
|
| 245 |
def _score_map(row: np.ndarray, labels: tuple[str, ...]) -> dict[str, float]:
|
| 246 |
row = np.asarray(row, dtype=np.float64).reshape(-1)
|
| 247 |
if row.size == 1 and len(labels) == 2:
|
src/pozify/ml/exercise_router_temporal.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
TEMPORAL_ARCHITECTURE = "bilstm"
|
| 10 |
+
TEMPORAL_HIDDEN_SIZE = 73
|
| 11 |
+
TEMPORAL_NUM_LAYERS = 1
|
| 12 |
+
TEMPORAL_DROPOUT_RATE = 0.2174
|
| 13 |
+
TEMPORAL_LEARNING_RATE = 0.0004
|
| 14 |
+
TEMPORAL_BATCH_SIZE = 54
|
| 15 |
+
TEMPORAL_DEFAULT_EPOCHS = 73
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@dataclass(frozen=True)
|
| 19 |
+
class TemporalRouterConfig:
|
| 20 |
+
input_size: int
|
| 21 |
+
label_count: int
|
| 22 |
+
hidden_size: int = TEMPORAL_HIDDEN_SIZE
|
| 23 |
+
num_layers: int = TEMPORAL_NUM_LAYERS
|
| 24 |
+
bidirectional: bool = True
|
| 25 |
+
dropout_rate: float = TEMPORAL_DROPOUT_RATE
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def build_temporal_router_model(config: TemporalRouterConfig) -> Any:
|
| 29 |
+
torch, nn = _torch_modules()
|
| 30 |
+
|
| 31 |
+
class BiLSTMRouter(nn.Module):
|
| 32 |
+
def __init__(self) -> None:
|
| 33 |
+
super().__init__()
|
| 34 |
+
self.lstm = nn.LSTM(
|
| 35 |
+
input_size=config.input_size,
|
| 36 |
+
hidden_size=config.hidden_size,
|
| 37 |
+
num_layers=config.num_layers,
|
| 38 |
+
batch_first=True,
|
| 39 |
+
bidirectional=config.bidirectional,
|
| 40 |
+
)
|
| 41 |
+
direction_count = 2 if config.bidirectional else 1
|
| 42 |
+
self.dropout = nn.Dropout(config.dropout_rate)
|
| 43 |
+
self.head = nn.Linear(config.hidden_size * direction_count, config.label_count)
|
| 44 |
+
|
| 45 |
+
def forward(self, inputs: Any) -> Any:
|
| 46 |
+
_outputs, (hidden, _cell) = self.lstm(inputs)
|
| 47 |
+
if config.bidirectional:
|
| 48 |
+
pooled = torch.cat((hidden[-2], hidden[-1]), dim=1)
|
| 49 |
+
else:
|
| 50 |
+
pooled = hidden[-1]
|
| 51 |
+
return self.head(self.dropout(pooled))
|
| 52 |
+
|
| 53 |
+
return BiLSTMRouter()
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class TorchTemporalRouter:
|
| 57 |
+
def __init__(
|
| 58 |
+
self,
|
| 59 |
+
*,
|
| 60 |
+
checkpoint: dict[str, Any],
|
| 61 |
+
labels: tuple[str, ...],
|
| 62 |
+
device: str = "cpu",
|
| 63 |
+
) -> None:
|
| 64 |
+
torch, _nn = _torch_modules()
|
| 65 |
+
self.labels = labels
|
| 66 |
+
self.device = torch.device(device)
|
| 67 |
+
self.config = TemporalRouterConfig(
|
| 68 |
+
input_size=int(checkpoint["input_size"]),
|
| 69 |
+
label_count=len(labels),
|
| 70 |
+
hidden_size=int(checkpoint.get("hidden_size", TEMPORAL_HIDDEN_SIZE)),
|
| 71 |
+
num_layers=int(checkpoint.get("num_layers", TEMPORAL_NUM_LAYERS)),
|
| 72 |
+
bidirectional=bool(checkpoint.get("bidirectional", True)),
|
| 73 |
+
dropout_rate=float(checkpoint.get("dropout_rate", TEMPORAL_DROPOUT_RATE)),
|
| 74 |
+
)
|
| 75 |
+
self.model = build_temporal_router_model(self.config)
|
| 76 |
+
self.model.load_state_dict(checkpoint["state_dict"])
|
| 77 |
+
self.model.to(self.device)
|
| 78 |
+
self.model.eval()
|
| 79 |
+
|
| 80 |
+
def predict_proba(self, values: np.ndarray) -> np.ndarray:
|
| 81 |
+
torch, _nn = _torch_modules()
|
| 82 |
+
inputs = torch.tensor(values, dtype=torch.float32, device=self.device)
|
| 83 |
+
with torch.no_grad():
|
| 84 |
+
logits = self.model(inputs)
|
| 85 |
+
probabilities = torch.softmax(logits, dim=1)
|
| 86 |
+
return probabilities.detach().cpu().numpy()
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _torch_modules() -> tuple[Any, Any]:
|
| 90 |
+
try:
|
| 91 |
+
import torch
|
| 92 |
+
from torch import nn
|
| 93 |
+
except ImportError as exc: # pragma: no cover - optional runtime dependency
|
| 94 |
+
raise RuntimeError(
|
| 95 |
+
"torch is required to load temporal exercise router artifacts"
|
| 96 |
+
) from exc
|
| 97 |
+
return torch, nn
|
tests/test_exercise_classifier.py
CHANGED
|
@@ -1,17 +1,19 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
|
|
|
| 3 |
import math
|
| 4 |
from pathlib import Path
|
| 5 |
import sys
|
| 6 |
import tempfile
|
| 7 |
import unittest
|
| 8 |
|
|
|
|
| 9 |
import numpy as np
|
| 10 |
|
| 11 |
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
|
| 12 |
|
| 13 |
from pozify.contracts import PoseFrame, PoseSequence, UserProfile, validate_contract
|
| 14 |
-
from pozify.ml.exercise_router_evaluation import evaluate_router_predictions
|
| 15 |
from pozify.ml.exercise_router_features import (
|
| 16 |
ROUTER_LABELS,
|
| 17 |
extract_router_windows,
|
|
@@ -22,6 +24,7 @@ from pozify.ml.exercise_router_inference import (
|
|
| 22 |
RouterModelBundle,
|
| 23 |
WindowRouterPrediction,
|
| 24 |
aggregate_window_predictions,
|
|
|
|
| 25 |
)
|
| 26 |
from pozify.steps import exercise_classifier
|
| 27 |
from pozify.steps.pose_backends.landmarks import LANDMARK_NAMES
|
|
@@ -187,6 +190,39 @@ class ExerciseRouterAggregationTests(unittest.TestCase):
|
|
| 187 |
self.assertEqual(aggregate_window_predictions(inconsistent).label, "unknown")
|
| 188 |
|
| 189 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
class ExerciseClassifierStepTests(unittest.TestCase):
|
| 191 |
def test_manual_override_bypasses_model_and_validates_contract(self) -> None:
|
| 192 |
result = exercise_classifier.run(
|
|
@@ -262,6 +298,18 @@ class ExerciseRouterEvaluationTests(unittest.TestCase):
|
|
| 262 |
self.assertEqual(evaluation.confusion_matrix["shoulder_press"]["unknown"], 1)
|
| 263 |
self.assertEqual(evaluation.unknown_rejection_rate, 1.0)
|
| 264 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
|
| 266 |
if __name__ == "__main__":
|
| 267 |
unittest.main()
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
+
import json
|
| 4 |
import math
|
| 5 |
from pathlib import Path
|
| 6 |
import sys
|
| 7 |
import tempfile
|
| 8 |
import unittest
|
| 9 |
|
| 10 |
+
import joblib
|
| 11 |
import numpy as np
|
| 12 |
|
| 13 |
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
|
| 14 |
|
| 15 |
from pozify.contracts import PoseFrame, PoseSequence, UserProfile, validate_contract
|
| 16 |
+
from pozify.ml.exercise_router_evaluation import evaluate_router_predictions, select_router_candidate
|
| 17 |
from pozify.ml.exercise_router_features import (
|
| 18 |
ROUTER_LABELS,
|
| 19 |
extract_router_windows,
|
|
|
|
| 24 |
RouterModelBundle,
|
| 25 |
WindowRouterPrediction,
|
| 26 |
aggregate_window_predictions,
|
| 27 |
+
load_router_model,
|
| 28 |
)
|
| 29 |
from pozify.steps import exercise_classifier
|
| 30 |
from pozify.steps.pose_backends.landmarks import LANDMARK_NAMES
|
|
|
|
| 190 |
self.assertEqual(aggregate_window_predictions(inconsistent).label, "unknown")
|
| 191 |
|
| 192 |
|
| 193 |
+
class ExerciseRouterModelLoadingTests(unittest.TestCase):
|
| 194 |
+
def test_selection_file_controls_active_artifact(self) -> None:
|
| 195 |
+
with tempfile.TemporaryDirectory() as temp_dir:
|
| 196 |
+
model_dir = Path(temp_dir)
|
| 197 |
+
artifact_path = model_dir / "selected.joblib"
|
| 198 |
+
joblib.dump(
|
| 199 |
+
{
|
| 200 |
+
"model": _FakePushUpModel(),
|
| 201 |
+
"labels": ["unknown", "squat", "push_up", "shoulder_press"],
|
| 202 |
+
"model_kind": "baseline",
|
| 203 |
+
},
|
| 204 |
+
artifact_path,
|
| 205 |
+
)
|
| 206 |
+
(model_dir / "router_selection.json").write_text(
|
| 207 |
+
json.dumps({"selected_artifact": artifact_path.name}),
|
| 208 |
+
encoding="utf-8",
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
bundle = load_router_model(model_dir)
|
| 212 |
+
|
| 213 |
+
self.assertIsNotNone(bundle)
|
| 214 |
+
assert bundle is not None
|
| 215 |
+
self.assertEqual(bundle.labels, tuple(ROUTER_LABELS))
|
| 216 |
+
result = exercise_classifier.run(
|
| 217 |
+
_sequence("push_up"),
|
| 218 |
+
_profile("auto"),
|
| 219 |
+
mock=False,
|
| 220 |
+
model_bundle=bundle,
|
| 221 |
+
)
|
| 222 |
+
self.assertEqual(result.exercise, "push_up")
|
| 223 |
+
self.assertFalse(result.fallback_required)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
class ExerciseClassifierStepTests(unittest.TestCase):
|
| 227 |
def test_manual_override_bypasses_model_and_validates_contract(self) -> None:
|
| 228 |
result = exercise_classifier.run(
|
|
|
|
| 298 |
self.assertEqual(evaluation.confusion_matrix["shoulder_press"]["unknown"], 1)
|
| 299 |
self.assertEqual(evaluation.unknown_rejection_rate, 1.0)
|
| 300 |
|
| 301 |
+
def test_selects_temporal_only_when_metrics_win(self) -> None:
|
| 302 |
+
baseline = {"name": "baseline", "accuracy": 0.91, "unknown_rejection_rate": 0.8}
|
| 303 |
+
temporal = {"name": "temporal", "accuracy": 0.92, "unknown_rejection_rate": 0.7}
|
| 304 |
+
|
| 305 |
+
self.assertEqual(select_router_candidate([baseline, temporal]), temporal)
|
| 306 |
+
|
| 307 |
+
def test_selects_baseline_on_metric_tie(self) -> None:
|
| 308 |
+
baseline = {"name": "baseline", "accuracy": 0.91, "unknown_rejection_rate": 0.8}
|
| 309 |
+
temporal = {"name": "temporal", "accuracy": 0.91, "unknown_rejection_rate": 0.8}
|
| 310 |
+
|
| 311 |
+
self.assertEqual(select_router_candidate([baseline, temporal]), baseline)
|
| 312 |
+
|
| 313 |
|
| 314 |
if __name__ == "__main__":
|
| 315 |
unittest.main()
|