Run this model with HF Jobs
Run Justin331/sam3 on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/Justin331/sam3. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/Justin331/sam3 on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use Justin331/sam3 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Justin331/sam3 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("mask-generation", model="Justin331/sam3")# pip install -U transformers accelerate # Load model directly from transformers import AutoProcessor, AutoModel processor = AutoProcessor.from_pretrained("Justin331/sam3") model = AutoModel.from_pretrained("Justin331/sam3", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Upload handler.py with huggingface_hub
Browse files49 unmodified lines5051525354555657585992 unmodified lines15215315415515615715815916051 unmodified lines21221321421521621717 unmodified lines23523623723823924024124224324449 unmodified lines# Build SAM3 video predictor# This automatically downloads model from facebook/sam3 on HuggingFacetry:self.predictor = build_sam3_video_predictor(gpus_to_use=[0])print("[INIT] SAM3 video predictor loaded successfully")except Exception as e:print(f"[INIT] Error loading SAM3 predictor: {e}")raise# Initialize HuggingFace API for uploads (if available)92 unmodified linesfor frame_idx, frame_output in outputs_per_frame.items():self._save_frame_masks(frame_output, masks_dir, frame_idx)# Collect object IDsif "object_ids" in frame_output and frame_output["object_ids"] is not None:all_object_ids.update(frame_output["object_ids"])print(f"[STEP 5] Saved masks for {len(outputs_per_frame)} frames")51 unmodified lines"error_type": type(e).__name__}def _prepare_video(self, video_data: str, tmpdir: Path) -> Path:"""Decode base64 video and save to file."""try:17 unmodified linesmasks = frame_output["masks"]object_ids = frame_output.get("object_ids", [])# Convert to numpy if tensorif torch.is_tensor(masks):masks = masks.cpu().numpy()# Save each object's maskfor i, obj_id in enumerate(object_ids):if i < len(masks):49 unmodified lines5051525354555657585960616263646566676892 unmodified lines16116216316416516616716816917017117217317417517617717817918051 unmodified lines23223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728817 unmodified lines30630730830931031131231331431531631731831932032132232332432532632732849 unmodified lines# Build SAM3 video predictor# This automatically downloads model from facebook/sam3 on HuggingFacetry:# Ensure BPE tokenizer file existsbpe_path = self._ensure_bpe_file()# Build predictor with explicit bpe_pathself.predictor = build_sam3_video_predictor(gpus_to_use=[0],bpe_path=bpe_path)print("[INIT] SAM3 video predictor loaded successfully")except Exception as e:print(f"[INIT] Error loading SAM3 predictor: {e}")import tracebacktraceback.print_exc()raise# Initialize HuggingFace API for uploads (if available)92 unmodified linesfor frame_idx, frame_output in outputs_per_frame.items():self._save_frame_masks(frame_output, masks_dir, frame_idx)# Collect object IDs - handle tensors properlyif "object_ids" in frame_output and frame_output["object_ids"] is not None:obj_ids = frame_output["object_ids"]# Convert to list if tensor or numpy arrayif torch.is_tensor(obj_ids):obj_ids = obj_ids.cpu().tolist()elif isinstance(obj_ids, np.ndarray):obj_ids = obj_ids.tolist()# Add to set (handles single int or list)if isinstance(obj_ids, list):all_object_ids.update(obj_ids)else:all_object_ids.add(obj_ids)print(f"[STEP 5] Saved masks for {len(outputs_per_frame)} frames")51 unmodified lines"error_type": type(e).__name__}def _ensure_bpe_file(self) -> str:"""Ensure BPE tokenizer file exists. Download from HuggingFace if missing.Returns path to the BPE file."""# Default expected pathassets_dir = Path("/repository/assets")bpe_file = assets_dir / "bpe_simple_vocab_16e6.txt.gz"if bpe_file.exists():print(f"[INIT] BPE file found at: {bpe_file}")return str(bpe_file)print(f"[INIT] BPE file not found, downloading from HuggingFace...")# Create assets directoryassets_dir.mkdir(parents=True, exist_ok=True)# Download BPE file from facebook/sam3 repotry:from huggingface_hub import hf_hub_downloaddownloaded_path = hf_hub_download(repo_id="facebook/sam3",filename="assets/bpe_simple_vocab_16e6.txt.gz",local_dir="/repository",local_dir_use_symlinks=False)print(f"[INIT] BPE file downloaded to: {downloaded_path}")return downloaded_pathexcept Exception as e:print(f"[INIT] Error downloading BPE file: {e}")print(f"[INIT] Trying alternative download method...")# Fallback: download directly from raw URLimport urllib.requesturl = "https://huggingface.co/facebook/sam3/resolve/main/assets/bpe_simple_vocab_16e6.txt.gz"try:urllib.request.urlretrieve(url, str(bpe_file))print(f"[INIT] BPE file downloaded to: {bpe_file}")return str(bpe_file)except Exception as e2:print(f"[INIT] Fallback download also failed: {e2}")raise ValueError(f"Could not download BPE tokenizer file. Please add assets/bpe_simple_vocab_16e6.txt.gz "f"to your repository. Download from: {url}")def _prepare_video(self, video_data: str, tmpdir: Path) -> Path:"""Decode base64 video and save to file."""try:17 unmodified linesmasks = frame_output["masks"]object_ids = frame_output.get("object_ids", [])# Handle different types of object_idsif torch.is_tensor(object_ids):object_ids = object_ids.cpu().tolist()elif isinstance(object_ids, np.ndarray):object_ids = object_ids.tolist()elif not isinstance(object_ids, list):object_ids = list(object_ids) if object_ids is not None else []# Convert masks to numpy if tensorif torch.is_tensor(masks):masks = masks.cpu().numpy()# Ensure masks is 3D array [num_objects, height, width]if len(masks.shape) == 4:# Remove batch dimension if presentmasks = masks[0]# Save each object's maskfor i, obj_id in enumerate(object_ids):if i < len(masks):
handler.py+88-4