File size: 22,398 Bytes
124e919 | 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 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 | """SAM 3 package engine and official SAM 3.1 dynamic-multiplex engine."""
import gc
import hashlib
import os
from pathlib import Path
from types import SimpleNamespace
import numpy as np
ROOT = Path(__file__).resolve().parent
SAM_ROOT = Path(os.environ['SAM3_SOURCE'])
SAM2_PREDICTOR = Path(os.environ['SAM2_SOURCE']) / 'sam2/sam2_video_predictor.py'
def digest(path):
with Path(path).open('rb') as stream:
return hashlib.file_digest(stream, 'sha256').hexdigest()
class S3:
def __init__(self, paths, width, height, exclusive=False):
import torch
from holdtrack.sam.model import load_tracker
from holdtrack.sam.lifecycle import SourceBindings
from holdtrack.sam.memory import MemoryPolicy
from holdtrack.sam import backend
self.torch = torch; self.exclusive = exclusive
self.model, self.load_receipt = load_tracker(Path(os.environ['SAM3_PT']),
digest(os.environ['SAM3_PT']), SourceBindings(SAM_ROOT, SAM2_PREDICTOR), paths)
self.state = self.model.init_state(str(paths[0].parent), offload_video_to_cpu=True,
offload_state_to_cpu=True, async_loading_frames=False)
self.policy = MemoryPolicy('EXCL', on_write=self.observe_write) if exclusive else None
self.window = backend._state_noncond_retention_window(self.model, len(paths))
self.pixel_removed = 0; self.memory_writes = 0
def observe_write(self, frame, index, mask):
self.memory_writes += 1
def propagate(self, frame):
from holdtrack.sam import backend
if not self.state['obj_ids']: return {}, {}
ids, logits = backend.propagate_one_frame(self.model, self.state, frame)
return ({int(i): logits[j, 0].float().cpu().numpy() for j,i in enumerate(ids)},
{int(i): backend._score_from_state(self.state, i, frame) for i in ids})
def prompt(self, frame, ident, box, negatives):
from holdtrack.sam.transactions import _birth_prompt
from holdtrack.sam import backend
return _birth_prompt(self.model, self.state, frame, ident, box, negatives,
self.torch, SimpleNamespace(_score_from_state=backend._score_from_state))
def reject(self, ident):
self.model.remove_object(self.state, ident, strict=True, need_output=False)
def consolidate_births(self, frame):
if self.state['obj_ids']: self.model.propagate_in_video_preflight(self.state)
def commit(self, frame, births, suppressed, retired, tracks):
from holdtrack.sam.transactions import _reencode_no_object
import torch.nn.functional as F
if self.policy:
masks = []
for index in self.state['output_dict_per_obj']:
out = self.state['output_dict_per_obj'][index]
value = out['non_cond_frame_outputs'].get(frame, out['cond_frame_outputs'].get(frame))
if value is not None:
masks.append(F.interpolate(value['pred_masks'].to('cuda').float(),
size=(self.model.image_size,)*2, mode='bilinear', align_corners=False))
if masks:
stacked = self.torch.cat(masks)
x = self.model._apply_non_overlapping_constraints(stacked)
self.pixel_removed = int(((stacked > 0) & (x <= 0)).sum())
else: self.pixel_removed = 0
for ident in sorted(suppressed):
if ident not in births:
_reencode_no_object(self.model, self.state, ident, frame, self.torch, -1024., tracks[ident])
for ident in sorted(retired):
self.reject(ident)
if self.policy: self.policy.apply(self.model, self.state, frame)
return dict(exclusive_pixels_removed=self.pixel_removed, states=1,
active_objects=len(self.state['obj_ids']), no_ACM=True)
def prune(self, frame):
from holdtrack.sam import backend
backend._prune_expired_noncond_outputs(self.state, frame, self.window)
def report(self):
return dict(engine='SAM3', exclusive=self.exclusive, strict_load=self.load_receipt,
memory_write_observations=self.memory_writes, ACM=False)
def cache_summary(self):
outputs=self.state['output_dict_per_obj'].values()
return dict(retention_window=self.window,
max_noncond_frames=max((len(x['non_cond_frame_outputs']) for x in outputs),default=0))
class Multiplex:
def __init__(self, paths, width, height, exclusive=False, one_per_state=False):
import torch
from sam3.model_builder import build_sam3_multiplex_video_model
self.torch = torch; self.exclusive = exclusive; self.one_per_state = one_per_state
self.model = build_sam3_multiplex_video_model(checkpoint_path=None,
load_from_HF=False, multiplex_count=16, device='cuda').eval()
checkpoint = torch.load(os.environ['SAM31_PT'], map_location='cpu', mmap=True, weights_only=True)
if 'model' in checkpoint: checkpoint = checkpoint['model']
selected = {}; mapping = {}
for key, target in self.model.state_dict().items():
source = next((p for p in ('tracker.model.'+key, 'detector.'+key, 'tracker.'+key, key)
if p in checkpoint and checkpoint[p].shape == target.shape), None)
if source is None: raise ValueError('Missing/wrong-shaped official weight: '+key)
selected[key] = checkpoint[source]; mapping[key] = source
self.model.load_state_dict(selected, strict=True)
if one_per_state:
native_inference=self.model._run_single_frame_inference
def singleton_buckets(*args,**kwargs):
if kwargs.get('add_to_existing_state') and not kwargs.get('reconditioning'):
kwargs.update(allow_new_buckets=True,prefer_new_buckets=True)
return native_inference(*args,**kwargs)
self.model._run_single_frame_inference=singleton_buckets
self.load_receipt = dict(keys=len(selected), strict=True, mapping=mapping,
checkpoint_SHA256=digest(os.environ['SAM31_PT']))
self.birth_memory_frame=None;self.birth_memory_masks={};self.birth_memory_rewrites=0
if exclusive:
native_encoder=self.model._run_memory_encoder
def exclusive_birth_encoder(*args,**kwargs):
# Official birth preflight re-encodes the whole state. Keep
# global exclusive masks for old objects during that native
# encoding, without modifying the newborn mask inputs.
state=kwargs.get('inference_state',args[0] if args else None)
frame=kwargs.get('frame_idx',args[1] if len(args)>1 else None)
if frame==self.birth_memory_frame and self.birth_memory_masks:
import torch.nn.functional as F
high=kwargs.get('high_res_masks',args[3] if len(args)>3 else None).clone()
for j,ident in enumerate(state['obj_ids']):
if ident in self.birth_memory_masks:
value=self.birth_memory_masks[ident]
if value.shape[-2:]!=high.shape[-2:]:
value=F.interpolate(value,size=high.shape[-2:],mode='bilinear',align_corners=False)
high[j:j+1]=value;self.birth_memory_rewrites+=1
if 'high_res_masks' in kwargs:kwargs=dict(kwargs,high_res_masks=high)
else:args=(*args[:3],high,*args[4:])
return native_encoder(*args,**kwargs)
self.model._run_memory_encoder=exclusive_birth_encoder
del checkpoint, selected; gc.collect()
self.paths = paths; self.height = height; self.width = width
self.states = []; self.cache = {}; self.low = {}; self.pending = {}
self.state_peak = self.objects_peak = 0
self.retirement_anchor_events=[]
self.window = max(self.model.max_obj_ptrs_in_encoder,
self.model.num_maskmem*self.model.memory_temporal_stride_for_eval+2)
def init(self):
return self.model.init_state(self.height, self.width, len(self.paths),
cached_features=self.cache, offload_video_to_cpu=True, offload_state_to_cpu=False)
def feature(self, frame):
from sam3.model.io_utils import _load_img_as_tensor
from sam3.model.data_misc import NestedTensor
tensor, height, width = _load_img_as_tensor(str(self.paths[frame]), self.model.image_size)
assert (height,width) == (self.height,self.width)
image = ((tensor-.5)/.5).unsqueeze(0).cuda()
backbone = self.model.forward_image(NestedTensor(tensors=image, mask=None),
need_sam3_out=False, need_interactive_out=True, need_propagation_out=True)
self.cache = {frame: (image, backbone)}
for state in self.states: state['cached_features'] = self.cache
def propagate(self, frame):
self.feature(frame); self.low = {}; self.pending = {}
logits = {}; scores = {}
for state in self.states:
if not state['obj_ids']: continue
iterator = self.model.propagate_in_video(state, start_frame_idx=frame,
max_frame_num_to_track=0, reverse=False, tqdm_disable=True, run_mem_encoder=False)
f, ids, low, _, object_scores = next(iterator)
try: next(iterator); raise RuntimeError('Multiplex emitted more than one frame')
except StopIteration: pass
assert f == frame
# The official pipeline consumes LOW-resolution propagation
# outputs, not the demo's display-only per-state overlap removal.
full = self.torch.nn.functional.interpolate(low.float(),
size=(self.height,self.width), mode='bilinear', align_corners=False)
for j, ident in enumerate(ids):
logits[int(ident)] = full[j,0].float().cpu().numpy()
scores[int(ident)] = float(object_scores[j].float().cpu().reshape(-1)[0])
self.low[int(ident)] = low[j:j+1]
return logits, scores
def prompt(self, frame, ident, box, negatives):
scratch = self.init()
# Official interactive head receives the box corners (labels2,3) and
# exactly the same negative prompt points as SAM3, normalized by W/H.
points = np.asarray([[box[0],box[1]], [box[2],box[3]], *negatives], np.float32)
points /= np.asarray([self.width,self.height], np.float32)
labels = self.torch.tensor([2,3]+[0]*len(negatives), dtype=self.torch.int32)
result = self.model.add_new_points(scratch, frame_idx=frame, obj_id=ident,
points=self.torch.from_numpy(points), labels=labels, clear_old_points=True,
rel_coordinates=True)
assert int(result[0]) == frame
full = result[3]; index = list(result[1]).index(ident)
logits = full[index,0].float().cpu().numpy().copy()
outputs = scratch['output_dict']['cond_frame_outputs']
out = outputs.get(frame)
if out is None:
for stores in scratch['temp_output_dict_per_obj'].values():
if frame in stores['cond_frame_outputs']:
out = stores['cond_frame_outputs'][frame]; break
score = float(out['object_score_logits'].float().cpu().reshape(-1)[index])
self.pending[ident] = logits
del scratch
return logits, score
def reject(self, ident):
self.pending.pop(ident, None)
def consolidate_births(self, frame):
pass # Birth masks have not mutated the real multiplex states yet.
def commit(self, frame, births, suppressed, retired, tracks):
import torch.nn.functional as F
torch = self.torch
# Official global masks are sorted by external IDs, then assigned back
# to each dynamic state (_tracker_update_memories).
ids = sorted(self.low)
self.birth_memory_rewrites=0
removed = 0
if ids:
shape = self.model.maskmem_backbone.mask_downsampler.interpol_size
high = torch.cat([F.interpolate(self.low[i].to('cuda').float(), size=shape,
mode='bilinear', align_corners=False) for i in ids])
# Official native shrinkage suppression is global and retains
# overlap unless an object loses over70% of its area.
high = self.model._suppress_object_pw_area_shrinkage(high)
for j, ident in enumerate(ids):
if ident in suppressed: high[j].fill_(-1024.)
if self.exclusive:
competitors = [high]
newborn = sorted(i for i in births if i not in retired)
if newborn:
competitors.extend(F.interpolate(torch.from_numpy(births[i]).to('cuda')[None,None],
size=shape, mode='bilinear', align_corners=False) for i in newborn)
stacked = torch.cat(competitors)
x = self.model._apply_non_overlapping_constraints(stacked)
removed = int(((stacked[:len(ids)] > 0) & (x[:len(ids)] <= 0)).sum())
high = x[:len(ids)]
index = {ident:j for j,ident in enumerate(ids)}
for state in self.states:
local_ids = state['obj_ids']
if not local_ids: continue
masks = high[[index[i] for i in local_ids]]
object_scores = torch.where((masks > 0).any(dim=(-1,-2)), 10., -10.)
memory = self.model._run_memory_encoder(state, frame, len(local_ids),
masks, object_scores, is_mask_from_pts=False)
for key in ('cond_frame_outputs', 'non_cond_frame_outputs'):
if frame not in state['output_dict'][key]: continue
out = state['output_dict'][key][frame]
absent = [j for j,i in enumerate(local_ids) if i in suppressed]
if absent:
out['pred_masks'] = out['pred_masks'].clone()
out['object_score_logits'] = out['object_score_logits'].clone()
out['pred_masks'][absent] = -1024.
out['object_score_logits'][absent] = -1024.
multiplex = state['multiplex_state']
pointers = multiplex.demux(out['obj_ptr']).clone()
pointers[absent] = self.model.no_obj_ptr_linear(pointers[absent])
out['obj_ptr'] = multiplex.mux(pointers)
for field,value in zip(('maskmem_features','maskmem_pos_enc','image_features','image_pos_enc'), memory):
out[field] = value
self.model._add_output_per_object(state, frame, out, key)
self.birth_memory_frame=frame
self.birth_memory_masks={ident:high[j:j+1] for j,ident in enumerate(ids)} if self.exclusive and ids else {}
pending = sorted(i for i in births if i not in retired)
while pending:
# Exact official _tracker_add_new_objects: best fit of the WHOLE
# newborn batch. A fresh state can itself have multiple buckets.
required=1 if self.one_per_state else len(pending)
available = [s for s in self.states if s['obj_ids'] and
(self.one_per_state or s['multiplex_state'].available_slots >= required)]
state = min(available,key=lambda s:s['multiplex_state'].available_slots) if available else self.init()
if not available: self.states.append(state)
count=1 if self.one_per_state else len(pending)
batch=pending[:count];pending=pending[count:]
logits=torch.from_numpy(np.stack([births[i] for i in batch])).to('cuda')
masks=F.interpolate(logits[:,None],size=(self.model.input_mask_size,)*2,
mode='bilinear',align_corners=False)[:,0]>0
# Official dense births enter each available state as ONE batch.
# M1 uses their native prefer_new_buckets path, one birth per call,
# rather than changing the conditioning clock via separate states.
self.model.add_new_masks(state, frame, batch,masks,add_mask_to_memory=True)
self.model.propagate_in_video_preflight(state, run_mem_encoder=True)
self.birth_memory_frame=None;self.birth_memory_masks={}
# Official removal keeps external object IDs unchanged while remapping
# internal slots. Assert that invariant for every retirement.
for state in self.states:
to_remove = sorted(set(state['obj_ids']) & retired)
if to_remove:
expected = [i for i in state['obj_ids'] if i not in retired]
# Official interactive removal erases ALL tracking results if
# clearing the last founding prompt removes the last condition.
# In a forward-only tracker, surviving late entrants must keep
# their current history. Keep that original packed condition
# for the native slicer, without inserting a new mask or moving
# any later frame into the conditioning set.
orphaned_prompt_frame=None
anchors=set(state['output_dict']['cond_frame_outputs'])
inputs=(state['mask_inputs_per_obj'],state['point_inputs_per_obj'])
def prompts_at(ident):
index=state['obj_id_to_idx'][ident]
return {f for store in inputs for f in store[index]}
if expected and anchors and all(not (anchors & prompts_at(i)) for i in expected):
removed_prompts=set().union(*(prompts_at(i) for i in to_remove))
if anchors<=removed_prompts:
assert len(anchors)==1, 'Multiple conditioning frames need separate review'
anchor=next(iter(anchors))
orphaned_prompt_frame=anchor
self.retirement_anchor_events.append(dict(frame=frame,anchor=anchor,
removed=to_remove,survivors=expected,original_clock=True))
for ident in to_remove:
for store in inputs:store[state['obj_id_to_idx'][ident]].pop(anchor,None)
self.model.remove_objects(state, to_remove, strict=True, need_output=False)
if orphaned_prompt_frame is not None:
# This tensor is still a valid conditioning memory. Its
# user prompt belonged to a retired object. On a later
# birth, official preflight compares prompt-frame indices
# with the prompts of the currently registered objects.
assert orphaned_prompt_frame < frame
assert orphaned_prompt_frame in state['output_dict']['cond_frame_outputs']
assert all(orphaned_prompt_frame not in prompts_at(i) for i in expected)
state['consolidated_frame_inds']['cond_frame_outputs'].remove(orphaned_prompt_frame)
assert state['obj_ids'] == expected
assert not expected or state['output_dict']['cond_frame_outputs']
self.states = [s for s in self.states if s['obj_ids']]
self.state_peak = max(self.state_peak, len(self.states))
active = sum(len(s['obj_ids']) for s in self.states)
self.objects_peak = max(self.objects_peak, active)
self.pending = {}; self.low = {}
return dict(exclusive_pixels_removed=removed, states=len(self.states),
memory_grid_shape=list(high.shape[-2:]) if ids else None,
buckets=[int(s['multiplex_state'].num_buckets) for s in self.states],
active_objects=active, no_ACM=True,
birth_preflight_old_masks_kept_global_exclusive=self.birth_memory_rewrites,
newborn_masks_left_native=True)
def prune(self, frame):
cutoff = frame-self.window
for state in self.states:
noncond = state['output_dict']['non_cond_frame_outputs']
for f in list(noncond):
if f < cutoff: del noncond[f]
state['consolidated_frame_inds']['non_cond_frame_outputs'].intersection_update(noncond)
for mapping in ('output_dict_per_obj','temp_output_dict_per_obj'):
for stores in state[mapping].values():
for f in list(stores['non_cond_frame_outputs']):
if f < cutoff: del stores['non_cond_frame_outputs'][f]
for mapping in ('point_inputs_per_obj','mask_inputs_per_obj'):
for store in state[mapping].values():
for f in list(store):
if f < cutoff and f not in state['output_dict']['cond_frame_outputs']:
del store[f]
for f in list(state['frames_already_tracked']):
if f < cutoff and f not in state['output_dict']['cond_frame_outputs']:
del state['frames_already_tracked'][f]
def report(self):
return dict(engine='SAM3.1', exclusive=self.exclusive,
retirement_anchor_events=self.retirement_anchor_events, strict_load=self.load_receipt,
states_peak=self.state_peak, objects_peak=self.objects_peak,
one_object_per_bucket=self.one_per_state,
singleton_implementation='official prefer_new_buckets=True' if self.one_per_state else None,
multiplex_count=16, ACM=False,offload_state_to_cpu=False,
newborn_allocation='official whole-batch best fit; fresh state if none fits',
newborn_masks='bilinear logits to input_mask_size, threshold0, official add_new_masks')
def cache_summary(self):
return dict(retention_window=self.window,
max_noncond_frames=max((len(s['output_dict']['non_cond_frame_outputs']) for s in self.states),default=0),
singleton_bucket_occupancies=[[sum(i>=0 for i in bucket)
for bucket in s['multiplex_state'].assignments]
for s in self.states] if self.one_per_state else None)
|