Spaces:
Paused
Paused
Zhen Ye Claude Opus 4.6 commited on
Commit ·
5749bd6
1
Parent(s): 10eb3c6
revert: remove torch.compile — runtime failures on HF Space
Browse filesReverts all torch.compile changes (b17bd6d..10eb3c6). The HF Space
container lacks Triton/inductor support, causing 500 errors. The
GPU-resident tensor pipeline from 5aec47c is retained.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
362 unmodified lines3633643653663673683693703713723733743753763773786 unmodified lines385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436176 unmodified lines613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644362 unmodified lines# Video predictor (for process_video)self._video_predictor = build_sam2_video_predictor_hf(hf_id, device=self.device,)# torch.compile individual components for fused kernels.# memory_attention uses dynamic=True (variable memory token count).# Wrapped in try/except: falls back to eager if PyTorch < 2.5 or# CUDA compiler not available.if self.device.startswith("cuda"):self._apply_torch_compile()# Image predictor (for single-frame predict)sam2_image_model = build_sam2_hf(hf_id, device=self.device)self._image_predictor = SAM2ImagePredictor(sam2_image_model)6 unmodified linesself._models_loaded = Truelogging.info("Grounded-SAM-2 models loaded successfully.")def _apply_torch_compile(self):"""Compile SAM2 sub-modules with torch.compile (max-autotune).Compiles 5 components matching Facebook's official VOS recipe.torch.compile wraps succeed immediately; actual Triton/inductorcompilation happens lazily on first forward pass. We storeoriginal forwards so propagate_segment can fall back on error."""vp = self._video_predictorcomponents = [("image_encoder", dict(mode="max-autotune", dynamic=False)),("memory_encoder", dict(mode="max-autotune", dynamic=False)),("memory_attention", dict(mode="max-autotune", dynamic=True)),("sam_prompt_encoder", dict(mode="max-autotune", dynamic=False)),("sam_mask_decoder", dict(mode="max-autotune", dynamic=False)),]self._original_forwards: Dict[str, Any] = {}compiled = []for attr, kwargs in components:module = getattr(vp, attr, None)if module is None:continuetry:self._original_forwards[attr] = module.forwardmodule.forward = torch.compile(module.forward, **kwargs)compiled.append(attr)except Exception as e:logging.warning("torch.compile wrapping failed for %s: %s", attr, e)if compiled:logging.info("torch.compile applied to: %s", ", ".join(compiled))self._torch_compiled = Trueelse:logging.info("torch.compile not available, using eager mode.")self._torch_compiled = Falsedef _revert_torch_compile(self):"""Revert compiled forwards back to eager originals."""vp = self._video_predictorfor attr, orig_fwd in self._original_forwards.items():module = getattr(vp, attr, None)if module is not None:module.forward = orig_fwdself._original_forwards.clear()self._torch_compiled = Falselogging.warning("Reverted torch.compile — falling back to eager mode.")# -- Single-frame interface (Segmenter.predict) -------------------------def predict(176 unmodified linesclass_names_list: List[str] = []cursor = 0# Wrap generator to catch torch.compile runtime failures on first frame.# If inductor/triton fails, revert to eager and restart propagation._generator = self._video_predictor.propagate_in_video(inference_state, max_frame_num_to_track=step, start_frame_idx=start_idx,)if getattr(self, '_torch_compiled', False) and not getattr(self, '_compile_verified', False):try:_first = next(_generator)except Exception as e:logging.warning("torch.compile runtime error, reverting to eager: %s", e)self._revert_torch_compile()# Re-init propagation with eager forwardsself._video_predictor.reset_state(inference_state)for obj_id, obj_info in mask_dict.labels.items():self._video_predictor.add_new_mask(inference_state, start_idx, obj_id, obj_info.mask,)_generator = self._video_predictor.propagate_in_video(inference_state, max_frame_num_to_track=step, start_frame_idx=start_idx,)_first = next(_generator)import itertoolsself._compile_verified = True_generator = itertools.chain([_first], _generator)for out_frame_idx, out_obj_ids, out_mask_logits in _generator:bool_masks = (out_mask_logits[:, 0] > 0.0) # (N, H, W) GPU asyncn = bool_masks.shape[0]362 unmodified lines3633643653663673683693703716 unmodified lines378379380381382383176 unmodified lines560561562563564565566567568362 unmodified lines# Video predictor (for process_video)self._video_predictor = build_sam2_video_predictor_hf(hf_id, device=self.device)# Image predictor (for single-frame predict)sam2_image_model = build_sam2_hf(hf_id, device=self.device)self._image_predictor = SAM2ImagePredictor(sam2_image_model)6 unmodified linesself._models_loaded = Truelogging.info("Grounded-SAM-2 models loaded successfully.")# -- Single-frame interface (Segmenter.predict) -------------------------def predict(176 unmodified linesclass_names_list: List[str] = []cursor = 0for out_frame_idx, out_obj_ids, out_mask_logits in self._video_predictor.propagate_in_video(inference_state, max_frame_num_to_track=step, start_frame_idx=start_idx,):bool_masks = (out_mask_logits[:, 0] > 0.0) # (N, H, W) GPU asyncn = bool_masks.shape[0]
models/segmenters/grounded_sam2.py+3-79