Spaces:
Running on T4
Running on T4
File size: 9,125 Bytes
326d3cc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 | """Trainable endpoints and phase/boundary heads. Candidate weights do not auto-activate."""
from pathlib import Path
import importlib.util
import subprocess
import numpy as np
from .storage import read_json, sha256_file, digest, atomic_json
from .contracts import RTMW_CORE, Event
MS_TCN_REVISION = "aef4e46c31bc7b2462065354054f968f91e54be1"
PHASES = ["setup", "load", "stride", "forward_swing", "follow_through"]
BOUNDARIES = ["load", "lead_foot_lift", "lead_foot_contact", "forward_swing_onset", "contact", "follow_through"]
FEATURE_VERSION = "body_object_visual_v1"
def endpoint_network():
import torch.nn as nn
class EndpointCNN(nn.Module):
def __init__(self):
super().__init__()
self.stem = nn.Sequential(nn.Conv2d(3,32,5,2,2),nn.ReLU(),nn.Conv2d(32,64,3,2,1),nn.ReLU(),
nn.Conv2d(64,64,3,1,1),nn.ReLU())
self.heatmap = nn.Conv2d(64,2,1)
self.visible = nn.Sequential(nn.AdaptiveAvgPool2d(1),nn.Flatten(),nn.Linear(64,2))
def forward(self,x):
features=self.stem(x)
return self.heatmap(features),self.visible(features)
return EndpointCNN()
def temporal_network(repository, architecture):
import torch
import torch.nn as nn
repository=Path(repository)
revision=subprocess.run(["git","-C",str(repository),"rev-parse","HEAD"],capture_output=True,text=True,check=True).stdout.strip()
if revision != MS_TCN_REVISION:
raise ValueError("MS-TCN++ source must be the selected valid pinned revision")
source=repository/"model.py"
module_spec=importlib.util.spec_from_file_location("batting_official_mstcn",source)
module=importlib.util.module_from_spec(module_spec);module_spec.loader.exec_module(module)
class TemporalHead(nn.Module):
def __init__(self):
super().__init__()
self.phases=module.MS_TCN2(architecture["prediction_layers"],architecture["refinement_layers"],
architecture["refinements"],architecture["channels"],architecture["feature_dim"],len(PHASES))
self.boundaries=nn.Conv1d(len(PHASES),len(BOUNDARIES),1)
self.presence=nn.Linear(len(PHASES),len(BOUNDARIES))
def forward(self,x):
phases=self.phases(x)
probability=torch.softmax(phases[-1],dim=1)
return phases,self.boundaries(probability),self.presence(probability.mean(-1))
return TemporalHead(), {"revision":revision,"model_source_sha256":sha256_file(source)}
def features(observations,capture):
values=[]
indices=list(RTMW_CORE.values())
for frame, timing in zip(observations["frames"],capture["frames"]):
scale=np.array([timing["width"],timing["height"]],float)
points=np.asarray(frame["body_points"],float)[indices]/scale
valid=np.array([frame["body_states"][i] in {"manual","image_supported","model_inferred"} for i in indices])
valid &= np.isfinite(points).all(1);points[~valid]=0
bat=np.zeros((2,2));bat_mask=np.zeros(2)
if frame["bat"].get("points") is not None:
bat=np.asarray(frame["bat"]["points"],float)/scale
bat_mask=np.array([s in {"manual","image_supported"} for s in frame["bat"]["states"]],float)
bat[bat_mask==0]=0
ball=np.zeros(2);ball_mask=0
if frame["ball"].get("point") is not None:
ball=np.asarray(frame["ball"]["point"],float)/scale;ball_mask=1
visual=np.asarray(frame.get("visual_feature",np.zeros(64)),float)
values.append(np.r_[points.ravel(),valid,bat.ravel(),bat_mask,ball,ball_mask,visual])
return np.asarray(values,np.float32).T
def qualification(manifest_path,checkpoint,kind):
manifest=read_json(manifest_path)
if manifest.get("kind")!=kind or manifest.get("checkpoint_sha256")!=sha256_file(checkpoint):
raise ValueError("Checkpoint kind/hash does not match manifest")
record=manifest.get("qualification",{})
if record.get("status")!="passed" or record.get("held_out_athletes") is not True or not record.get("evaluation_sha256"):
raise ValueError("Checkpoint has no passed held-out technical qualification")
# Qualification is explicit experimental scope, never proof of biomechanical validity.
if not record.get("scope"): raise ValueError("Checkpoint qualification scope missing")
evidence_path=Path(manifest_path).resolve().parent/"evaluation.json"
if not evidence_path.is_file() or sha256_file(evidence_path)!=record["evaluation_sha256"]:
raise ValueError("Checkpoint qualification evidence missing or changed")
evidence=read_json(evidence_path)
if evidence.get("passed") is not True or evidence.get("checkpoint_sha256")!=manifest["checkpoint_sha256"] or evidence.get("scope")!=record["scope"]:
raise ValueError("Checkpoint qualification evidence mismatch")
return manifest
class EndpointPredictor:
def __init__(self,checkpoint,manifest_path,device):
import torch
self.torch=torch;self.device=device
self.manifest=qualification(manifest_path,checkpoint,"endpoint_cnn")
self.model=endpoint_network().to(device).eval()
self.model.load_state_dict(torch.load(checkpoint,map_location=device,weights_only=True))
def __call__(self,image,box):
import cv2
x1,y1,x2,y2=np.asarray(box,int)
h,w=image.shape[:2];x1=max(x1,0);y1=max(y1,0);x2=min(x2,w);y2=min(y2,h)
if x2-x1<8 or y2-y1<8: return None
crop=cv2.resize(image[y1:y2,x1:x2],(256,256))[...,::-1].copy()/255.
x=self.torch.tensor(crop.transpose(2,0,1),dtype=self.torch.float32,device=self.device)[None]
with self.torch.no_grad(): heatmap,visibility=self.model(x)
if (visibility.sigmoid()<self.manifest.get("visibility_threshold",.5)).any(): return None
maps=heatmap[0].cpu().numpy();flat=maps.reshape(2,-1).argmax(1)
xy=np.stack([flat%64,flat//64],1).astype(float)+.5
points=xy/64*[x2-x1,y2-y1]+[x1,y1]
# Reject border predictions where a true endpoint may lie outside the crop.
if np.any(xy<2) or np.any(xy>62): return None
return {"points":points.tolist(),"states":["model_inferred"]*2,"method":"qualified_endpoint_cnn_v1",
"qualification_scope":self.manifest["qualification"]["scope"]}
def run_learned_events(request,capture,config,observations):
root=Path(request["root"])
try:
if not config.event_manifest_path or not config.event_checkpoint_path:
raise ValueError("no_qualified_checkpoint")
import torch
manifest=qualification(config.event_manifest_path,config.event_checkpoint_path,"mstcn_events")
if manifest.get("feature_version")!=FEATURE_VERSION: raise ValueError("Event feature definition mismatch")
model,source=temporal_network(config.mstcn_repo,manifest["architecture"])
if source!=manifest["source"]: raise ValueError("Event source hash mismatch")
model.load_state_dict(torch.load(config.event_checkpoint_path,map_location="cpu",weights_only=True))
model=model.to(config.device).eval()
x=features(observations,capture)
with torch.no_grad(): phase,boundary,presence=model(torch.tensor(x,device=config.device)[None])
phase=phase[-1].softmax(1)[0].cpu().numpy(); boundary=boundary.sigmoid()[0].cpu().numpy();presence=presence.sigmoid()[0].cpu().numpy()
candidates=[]
for i,name in enumerate(BOUNDARIES):
if presence[i]<manifest.get("presence_threshold",.5): continue
index=int(boundary[i].argmax())
if boundary[i,index]<manifest.get("boundary_threshold",.5):continue
candidates.append({"type":name,"frame_interval":[max(index-1,0),min(index+1,capture["frame_count"]-1)],
"evidence_frames":[index],"state":"candidate"})
np.savez_compressed(root/"learned_events.npz",phase_probability=phase,boundary_score=boundary,presence_score=presence)
status={"status":"complete","candidates":candidates,"checkpoint_sha256":manifest["checkpoint_sha256"],
"qualification_scope":manifest["qualification"]["scope"],"source":source,
"confidence_interpretation":"network_scores_not_calibrated_contact_probabilities"}
except Exception as error:
status={"status":"unavailable","reason":str(error)[:300],"error_type":type(error).__name__}
atomic_json(root/"learned_events_status.json",status)
def merge_learned(events,status):
if status.get("status")!="complete":return events
for i,candidate in enumerate(status["candidates"]):
# Human-reviewed absence/unknown/confirmation is never overwritten.
if any(e.type==candidate["type"] and e.review_status=="reviewed" for e in events):continue
events.append(Event("learned_"+str(i),candidate["type"],"candidate",candidate["frame_interval"],
candidate["evidence_frames"],"qualified_mstcn_v1",notes=["Experimental trained candidate; requires visible evidence/review"]))
return events
|