Coverage for collectra/tasks/image_segmentation/sam3.py: 94.59%
185 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
1"""SAM 3/3.1 image instance segmentation and mask-supervised training data.
3Uses Meta's sam3 package, installed separately from its official repository.
4Dataset preparation requires only Collectra's ordinary image dependencies.
5"""
7from __future__ import annotations
9import os
10import shutil
11import subprocess
12import sys
13import time
14import uuid
15from datetime import datetime
16from pathlib import Path
17from typing import Annotated
19from cappa import Arg
20import numpy as np
21import yaml
22from PIL import Image as PILImage
24from collectra.cli import command
25from collectra.tasks.base import Task
26from collectra.types.images import Image, ImageSegmentation
27from collectra.utils import threading_locked
30def training_progress(message):
31 """Keep progress visible in terminals and redirected cluster job logs."""
32 print(f"[SAM3] {message}", flush=True)
35_INSTALL = (
36 'Install it with `uv sync --extra sam3` (or pip install "sam3 @ '
37 'git+https://github.com/facebookresearch/sam3.git").'
38)
39_PLATFORM = (
40 " SAM 3 only works on Linux with an NVIDIA GPU (CUDA), and this computer is "
41 "not running Linux: run this task on a Linux GPU machine."
42)
45def _sam3():
46 """Meta's ``sam3`` package, or an ImportError that says what to do about it."""
47 try:
48 import sam3
49 except ModuleNotFoundError as error:
50 on_linux = sys.platform.startswith("linux")
51 hint = "" if on_linux else _PLATFORM
52 if error.name == "sam3":
53 message = (
54 f"SAM 3 is not installed. {_INSTALL} It needs Python 3.12+, "
55 f"PyTorch and access to Meta's checkpoints.{hint}"
56 )
57 elif error.name == "triton" and not on_linux:
58 message = (
59 "SAM 3 is installed but needs the Python package 'triton', which "
60 f"only has packages for Linux.{hint}"
61 )
62 else:
63 message = (
64 f"SAM 3 is installed but needs the Python package {error.name!r}, "
65 f"which is missing. {_INSTALL}{hint}"
66 )
67 raise ImportError(message) from error
68 return sam3
71# Keep these imports available for callers using the original SAM3 module.
72from .data import (
73 SegmentationSample,
74 SegmentationTrainingData,
75 _bounds,
76 _sample_partition,
77 encode_rle,
78 export_dataset,
79 mask_in_view,
80 mask_to_source,
81 prepare_segmentation_inputs,
82)
85class Sam3Backend:
86 """What the SAM 3 tasks share: their prompts, checkpoint and processor.
88 A task using it has ``model``, ``prompt``, ``prompts``, ``version``,
89 ``threshold`` and ``device`` settings and keeps its processor in ``_processor``.
90 """
92 def _declared_outputs(self):
93 """The outputs the pipeline gives this task; empty if it gives none."""
94 outputs = getattr(self, "output", None) or []
95 return outputs if isinstance(outputs, list) else [outputs]
97 def _outputs(self):
98 return self._declared_outputs() or [self.get_output_name()]
100 def _prompts(self):
101 return self._prompts_for(self._outputs())
103 def _prompts_for(self, labels):
104 """The text prompt for each label: those given, else one for all, else its name."""
105 if self.prompts:
106 mapping = self.prompts
107 else:
108 mapping = {
109 label: self.prompt or label.replace("_", " ") for label in labels
110 }
111 if any(not label or not prompt.strip() for label, prompt in mapping.items()):
112 raise ValueError("SAM prompts and output labels must be nonempty")
113 return mapping
115 def _checkpoint(self):
116 _sam3()
117 if self.model:
118 path = Path(self.model).expanduser()
119 if not path.is_absolute() and self.pipeline is not None:
120 path = Path(self.pipeline.path) / path
121 path = path.resolve()
122 if not path.is_file():
123 raise FileNotFoundError(path)
124 return path
125 from sam3.model_builder import download_ckpt_from_hf
127 return Path(download_ckpt_from_hf(version=self.version))
129 def _init_model(self):
130 if self._processor is None:
131 self._processor = self._load_processor()
133 def _load_processor(self):
134 _sam3()
135 import torch
136 from sam3.model_builder import build_sam3_image_model
137 from sam3.model.sam3_image_processor import Sam3Processor
139 checkpoint = self._checkpoint()
140 state = torch.load(checkpoint, map_location="cpu", weights_only=True)
141 state = state.get("model", state)
142 from .sam3_training import load_image_state
144 model = build_sam3_image_model(
145 checkpoint_path=None,
146 load_from_HF=False,
147 device=self.device,
148 enable_segmentation=True,
149 )
150 load_image_state(model, state)
151 model.to(self.device).eval()
152 return Sam3Processor(
153 model, device=self.device, confidence_threshold=self.threshold
154 )
156 def _run_trainer(
157 self,
158 dataset,
159 output,
160 *,
161 masks,
162 epochs,
163 batch,
164 num_gpus,
165 wandb,
166 project,
167 started,
168 ):
169 """Fine-tune with Meta's trainer, returning the best weights it saved.
171 ``masks=False`` trains on boxes alone, for object detection.
172 """
173 from .sam3_training import training_config
175 training_progress("Resolving the SAM checkpoint (a download may be needed)")
176 initial_checkpoint = self._checkpoint()
177 training_progress(f"Using checkpoint: {initial_checkpoint}")
178 training_progress("Building the SAM training configuration")
179 config = training_config(
180 dataset,
181 output,
182 initial_checkpoint,
183 epochs=epochs,
184 batch=batch,
185 num_gpus=num_gpus,
186 wandb=wandb,
187 run_name=output.name,
188 project=project,
189 confidence_threshold=self.threshold,
190 masks=masks,
191 )
192 config_path = output / "sam3-training.yaml"
193 config_path.write_text(
194 yaml.safe_dump(config, sort_keys=False), encoding="utf-8"
195 )
196 training_progress(f"Configuration saved: {config_path}")
197 training_progress(
198 f"Starting SAM trainer ({time.monotonic() - started:.1f}s preparation); "
199 "trainer output follows"
200 )
201 subprocess.run(
202 [
203 sys.executable,
204 "-u",
205 "-c",
206 "from collectra.tasks.image_segmentation.sam3_training import launch; import sys; launch(sys.argv[1])",
207 str(config_path),
208 ],
209 check=True,
210 env={**os.environ, "PYTHONUNBUFFERED": "1"},
211 )
212 training_progress("SAM trainer exited successfully; checking its checkpoint")
213 checkpoint = output / "training" / "checkpoints" / "best.pt"
214 if not checkpoint.is_file():
215 raise FileNotFoundError(
216 f"SAM training produced no checkpoint at {checkpoint}"
217 )
218 return checkpoint
221class ImageSegmenterSam3(Sam3Backend, SegmentationTrainingData, Task):
222 """Find all instances matching text prompts and return one mask per instance."""
224 def __init__(
225 self,
226 name: str,
227 model: str | Path = "",
228 prompt: str = "",
229 prompts: dict[str, str] | None = None,
230 version: str = "sam3.1",
231 threshold: float = 0.5,
232 device: str = "cuda",
233 **kwargs,
234 ):
235 super().__init__(name, **kwargs)
236 if version not in {"sam3", "sam3.1"}:
237 raise ValueError("version must be sam3 or sam3.1")
238 if not 0 <= threshold <= 1:
239 raise ValueError("threshold must be between 0 and 1")
240 self.model, self.prompt, self.prompts = model, prompt, prompts or {}
241 self.version, self.threshold, self.device = version, threshold, device
242 self._processor = None
244 def attributes_to_ignore(self):
245 return super().attributes_to_ignore() | {"_processor"}
247 def input_type(self) -> type:
248 return Image
250 def output_type(self) -> type:
251 return ImageSegmentation
253 _progress = staticmethod(training_progress)
255 @threading_locked()
256 def run(self, *images: Image) -> list[ImageSegmentation]:
257 if not images or any(not isinstance(image, Image) for image in images):
258 raise TypeError(
259 "SAM requires one or more Image artefacts (including subclasses)"
260 )
261 prompts = self._prompts()
262 self._init_model()
263 directory = Path(self.context.file_path or Path.cwd()) / "masks"
264 directory.mkdir(parents=True, exist_ok=True)
265 import torch
267 results = []
268 # SAM3's fused ViT MLP kernel (addmm_act) always returns bfloat16, so
269 # the following float32 layers need bfloat16 autocast, as in Meta's
270 # own inference examples; it also requires gradients to be disabled.
271 device_type = torch.device(self.device).type
272 with torch.inference_mode(), torch.autocast(device_type, dtype=torch.bfloat16):
273 for image in images:
274 state = self._processor.set_image(image.pil().convert("RGB"))
275 for label, prompt in prompts.items():
276 self._processor.reset_all_prompts(state)
277 prediction = self._processor.set_text_prompt(
278 prompt=prompt, state=state
279 )
280 masks = prediction["masks"]
281 if hasattr(masks, "detach"):
282 # Under autocast masks may be bfloat16, which NumPy lacks.
283 masks = masks.detach().float().cpu().numpy()
284 masks = np.asarray(masks)
285 if masks.ndim == 4 and masks.shape[1] == 1:
286 masks = masks[:, 0]
287 if masks.ndim != 3:
288 raise ValueError("SAM returned masks with an unexpected shape")
289 for mask in masks:
290 pixels = mask_to_source(image, mask > 0.5)
291 if not pixels.any():
292 continue
293 path = directory / f"sam3-{uuid.uuid4().hex}.png"
294 PILImage.fromarray(pixels).save(path)
295 results.append(
296 ImageSegmentation(
297 name=label,
298 data=image.get_path(),
299 mask=path,
300 parents=[image.id],
301 orientation=image.orientation,
302 partition=image.partition,
303 )
304 )
305 return results
307 @command
308 def train(
309 self,
310 inputs: Annotated[
311 list[str],
312 Arg(
313 required=False,
314 default=[],
315 help="Results YAML files, result directories, or parent directories containing annotated images and masks. May be omitted when reusing an existing export.",
316 ),
317 ],
318 output: Annotated[
319 Path | None,
320 Arg(
321 help="Directory for prepared data, metrics.csv, logs and best model weights. Defaults to a timestamped directory; required with --reuse-data."
322 ),
323 ] = None,
324 validation: Annotated[
325 str,
326 Arg(
327 help="Partition used for validation and best-model selection by mask IoU. Omit to train without validation. Ignored when reusing an existing export."
328 ),
329 ] = "",
330 exclude: Annotated[
331 str,
332 Arg(
333 help="Partition excluded from both training and validation during data preparation. Ignored when reusing an existing export."
334 ),
335 ] = "",
336 epochs: Annotated[
337 int,
338 Arg(
339 help="Number of training epochs; validation runs after every epoch when available."
340 ),
341 ] = 20,
342 batch: Annotated[
343 int,
344 Arg(help="Number of training images per batch on each GPU."),
345 ] = 1,
346 num_gpus: Annotated[
347 int,
348 Arg(help="Number of GPUs used for training on this node."),
349 ] = 1,
350 keep_log: Annotated[
351 bool,
352 Arg(
353 help="Keep prepared data, metrics, logs and checkpoints after copying the best weights into the pipeline. --no-keep-log removes the output directory."
354 ),
355 ] = True,
356 reuse_data: Annotated[
357 bool,
358 Arg(
359 help="Reuse OUTPUT/dataset when both split annotation files exist; otherwise prepare it from the input paths. Requires --output. Reuse ignores input paths, partitions and --max-items. Does not resume optimizer state."
360 ),
361 ] = False,
362 wandb: Annotated[
363 bool,
364 Arg(
365 help="Log epoch metrics to Weights & Biases. Project: <pipeline-directory>-<task>; run: output directory name; entity: W&B settings or WANDB_ENTITY."
366 ),
367 ] = False,
368 max_items: Annotated[
369 int | None,
370 Arg(
371 help="Maximum total images across training and validation, after exclusions, in input order. Omit for all images. Ignored when reusing an existing export."
372 ),
373 ] = None,
374 ) -> Path:
375 """Prepare instance masks and fine-tune using Meta's image trainer.
377 --reuse-data uses OUTPUT/dataset directly when present, otherwise
378 prepares it from inputs. It requires --output.
379 """
380 if min(epochs, batch, num_gpus) < 1:
381 raise ValueError("epochs, batch and num_gpus must be positive")
382 if reuse_data and output is None:
383 raise ValueError("--reuse-data requires --output")
384 output = (
385 Path(output).expanduser().resolve()
386 if output is not None
387 else Path.cwd() / datetime.now().strftime("%Y%m%d_%H%M%S")
388 )
389 reuse_prepared = reuse_data and all(
390 (output / "dataset" / split / "_annotations.coco.json").is_file()
391 for split in ("train", "valid")
392 )
393 if not reuse_prepared and max_items is not None and max_items < 1:
394 raise ValueError("max_items must be positive")
395 if not reuse_prepared and not inputs:
396 raise ValueError(
397 "Supply training inputs to prepare the dataset; --reuse-data without "
398 f"inputs requires an existing export at {output / 'dataset'}"
399 )
400 output.mkdir(parents=True, exist_ok=True)
401 started = time.monotonic()
402 training_progress(
403 f"Training {self.name}: output={output}, epochs={epochs}, batch={batch}, GPUs={num_gpus}"
404 )
405 if reuse_prepared:
406 dataset = output / "dataset"
407 training_progress(f"Reusing prepared dataset directly: {dataset}")
408 training_progress(
409 "Skipping source checks and export; using existing train/validation splits"
410 )
411 if max_items is not None:
412 training_progress(
413 "Ignoring --max-items because --reuse-data uses the existing dataset unchanged"
414 )
415 else:
416 if reuse_data:
417 training_progress(
418 "Prepared dataset is missing or incomplete; falling back to preparation from inputs"
419 )
420 training_progress("Preparing the dataset before GPU training starts")
421 dataset = self.prepare_training_data(
422 inputs, output / "dataset", validation, exclude, max_items=max_items
423 )
424 checkpoint = self._run_trainer(
425 dataset,
426 output,
427 masks=True,
428 epochs=epochs,
429 batch=batch,
430 num_gpus=num_gpus,
431 wandb=wandb,
432 project=f"{self.pipeline.name}-{self.name}",
433 started=started,
434 )
435 destination = self.pipeline.path / f"{self.name}-{uuid.uuid4().hex[:8]}.pt"
436 shutil.copy2(checkpoint, destination)
437 self.model = destination
438 self._processor = None
439 self.pipeline.data[self.name]["model"] = destination.name
440 self.pipeline.save(self.name)
441 training_progress(f"Saved trained checkpoint: {destination}")
442 if not keep_log:
443 shutil.rmtree(output, ignore_errors=True)
444 training_progress(f"Removed training directory: {output}")
445 training_progress(f"Training complete ({time.monotonic() - started:.1f}s)")
446 return destination
449# The former name of ImageSegmenterSam3.
450ImageSegmentationSam3 = ImageSegmenterSam3