Coverage for collectra/tasks/object_detection/sam3.py: 100.00%

104 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-13 04:26 +0000

1"""Object detection with SAM 3, from text prompts. 

2 

3Uses Meta's sam3 package, installed separately from its official repository. 

4Each output of the task is a kind of object: it is found by prompting SAM 3 with 

5the output's name (or the prompt given for it), and every box found is returned 

6as a crop with that name. 

7""" 

8 

9from __future__ import annotations 

10 

11import json 

12import shutil 

13import time 

14from pathlib import Path 

15from typing import Annotated, Any, Literal 

16 

17from cappa import Arg 

18from pydantic import Field, PrivateAttr 

19 

20from collectra.cli import command 

21from collectra.types.images import Image, ImageCrop 

22from collectra.utils import change_dir, threading_locked 

23 

24from ..image_segmentation.sam3 import Sam3Backend, training_progress 

25from ..machine_learning.training import ( 

26 prepare_object_detection_inputs, 

27 run_training_command, 

28) 

29from .base import Batch, Epochs, ObjectDetector 

30from .coco_data import CocoDetectionData 

31from .detr import DetectionTrainResult 

32 

33__all__ = ["ObjectDetectorSam3"] 

34 

35 

36class ObjectDetectorSam3(Sam3Backend, CocoDetectionData, ObjectDetector): 

37 """Find objects by describing them in words. 

38 

39 Attributes: 

40 model: A fine-tuned SAM 3 checkpoint. Empty uses Meta's released weights. 

41 prompt: The text prompt for every output. Empty uses each output's own 

42 name, with underscores as spaces. 

43 prompts: Output name to text prompt, for outputs that need their own. 

44 version: Which of Meta's released weights to download: sam3 or sam3.1. 

45 threshold: Minimum confidence for a detection, from 0 to 1. 

46 device: Where to run the model. SAM 3 needs a CUDA GPU. 

47 

48 SAM 3 always works at its own image size, so ``resolution`` has no effect. 

49 """ 

50 

51 model: str | Path = "" 

52 prompt: str = "" 

53 prompts: dict[str, str] = Field(default_factory=dict) 

54 version: Literal["sam3", "sam3.1"] = "sam3.1" 

55 threshold: float = Field(default=0.5, ge=0, le=1) 

56 device: str = "cuda" 

57 

58 _processor: Any = PrivateAttr(default=None) 

59 

60 def attributes_to_ignore(self): 

61 return super().attributes_to_ignore() | {"_processor"} 

62 

63 def input_type(self) -> type: 

64 return Image 

65 

66 def output_type(self) -> type: 

67 return ImageCrop 

68 

69 @threading_locked() 

70 def run(self, *args: Image) -> list[ImageCrop]: 

71 if len(args) != 1: 

72 raise ValueError("This task only supports a single Image input.") 

73 if not isinstance(args[0], Image): 

74 raise TypeError("Input must be an instance of Image.") 

75 image = args[0] 

76 prompts = self._prompts() 

77 self._init_model() 

78 self._processor.set_confidence_threshold(self.threshold) 

79 

80 import torch 

81 

82 picture = image.pil().convert("RGB") 

83 width, height = picture.size 

84 crops: list[ImageCrop] = [] 

85 # SAM 3's fused kernels need bfloat16 autocast and no gradients. 

86 device_type = torch.device(self.device).type 

87 with torch.inference_mode(), torch.autocast(device_type, dtype=torch.bfloat16): 

88 state = self._processor.set_image(picture) 

89 for label, prompt in prompts.items(): 

90 self._processor.reset_all_prompts(state) 

91 found = self._processor.set_text_prompt(prompt=prompt, state=state) 

92 boxes = found["boxes"].detach().float().cpu().numpy() 

93 scores = found["scores"].detach().float().cpu().numpy() 

94 for (x1, y1, x2, y2), score in zip(boxes, scores): 

95 x1, x2 = (max(0.0, min(float(width), float(x))) for x in (x1, x2)) 

96 y1, y2 = (max(0.0, min(float(height), float(y))) for y in (y1, y2)) 

97 if x2 <= x1 or y2 <= y1: 

98 continue 

99 crops.append( 

100 image.make_crop( 

101 x_center=(x1 + x2) / 2.0 / width, 

102 y_center=(y1 + y2) / 2.0 / height, 

103 width_relative=(x2 - x1) / width, 

104 height_relative=(y2 - y1) / height, 

105 confidence=float(score), 

106 orientation=image.orientation, 

107 name=label, 

108 ) 

109 ) 

110 return self._orient_crops(crops) 

111 

112 @command 

113 def train( 

114 self, 

115 inputs: Annotated[ 

116 list[str], 

117 Arg( 

118 help="Pipeline data files or directories containing training annotations." 

119 ), 

120 ], 

121 output: Annotated[ 

122 Path | None, 

123 Arg(help="Directory for training logs, dataset files, and checkpoints."), 

124 ] = None, 

125 keep_log: Annotated[ 

126 bool, 

127 Arg( 

128 help="Keep the training directory after saving the model to the pipeline." 

129 ), 

130 ] = True, 

131 validation: Annotated[ 

132 str, 

133 Arg( 

134 help="Partition value identifying validation examples. The best model is the one with the highest box average precision on them." 

135 ), 

136 ] = "", 

137 exclude: Annotated[ 

138 str, 

139 Arg(help="Partition value identifying examples to exclude from training."), 

140 ] = "", 

141 epochs: Epochs = None, 

142 batch: Batch = None, 

143 num_gpus: Annotated[ 

144 int, Arg(help="Number of GPUs used for training on this machine.") 

145 ] = 1, 

146 wandb: Annotated[ 

147 bool, 

148 Arg(help="Log training metrics to Weights & Biases."), 

149 ] = False, 

150 model: Annotated[ 

151 str, 

152 Arg( 

153 help="SAM 3 checkpoint to start from. Omit to keep the configured model, or else Meta's released weights." 

154 ), 

155 ] = "", 

156 max_items: Annotated[ 

157 int, 

158 Arg( 

159 help="Use at most this many images in each of the training and validation sets (0 uses all); for quick tests." 

160 ), 

161 ] = 0, 

162 ): 

163 """Fine-tune SAM 3 on annotated boxes, with Meta's trainer.""" 

164 settings = self._settings_for_run(epochs=epochs, batch=batch) 

165 return run_training_command( 

166 self, 

167 inputs, 

168 self._train, 

169 keep_log=keep_log, 

170 output=output, 

171 validation=validation, 

172 exclude=exclude, 

173 prepare_inputs=prepare_object_detection_inputs, 

174 include_unlabelled=True, 

175 epochs=settings["epochs"], 

176 batch=settings["batch"], 

177 num_gpus=num_gpus, 

178 wandb=wandb, 

179 model=model, 

180 max_items=max_items, 

181 ) 

182 

183 def _train(self, *images: ImageCrop, **kwargs) -> DetectionTrainResult: 

184 if kwargs.get("model"): 

185 self.model = kwargs["model"] 

186 log = kwargs.get("log", None) 

187 if log is None: 

188 raise ValueError( 

189 "Log directory must be specified in kwargs with key 'log'." 

190 ) 

191 if "base_folder" not in kwargs: 

192 raise ValueError( 

193 "Base folder must be specified in kwargs with key 'base_folder'." 

194 ) 

195 log = kwargs["base_folder"] / log 

196 log.mkdir(parents=True, exist_ok=True) 

197 print(f"Training files will be saved to: {log}") 

198 

199 classes = list(kwargs.get("classes") or self._declared_outputs()) 

200 classes = classes or sorted( 

201 {img.name for img in images if isinstance(img, ImageCrop)} 

202 ) 

203 if not classes: 

204 raise ValueError("No classes provided/found for SAM 3 training.") 

205 prompts = self._prompts_for(classes) 

206 if len(set(prompts.values())) != len(classes): 

207 raise ValueError( 

208 "SAM 3 learns each class from its prompt, so every output needs a " 

209 f"different prompt; got {prompts}" 

210 ) 

211 

212 train_samples, val_samples = self._prepare_assets( 

213 classes, 

214 kwargs.get("validation", ""), 

215 kwargs.get("exclude", ""), 

216 *images, 

217 ) 

218 max_items = int(kwargs.get("max_items", 0) or 0) 

219 if max_items > 0: 

220 train_samples = train_samples[:max_items] 

221 val_samples = val_samples[:max_items] 

222 self._check_distribution(classes, train_samples, val_samples) 

223 with change_dir(kwargs["base_folder"]): 

224 dataset = self._write_coco_dataset( 

225 train_samples, val_samples, classes, log / "dataset" 

226 ) 

227 name_categories(dataset, prompts) 

228 checkpoint = self._run_trainer( 

229 dataset, 

230 log, 

231 masks=False, 

232 epochs=int(kwargs.get("epochs", self.epochs)), 

233 batch=int(kwargs.get("batch", self.batch)), 

234 num_gpus=int(kwargs.get("num_gpus", 1)), 

235 wandb=bool(kwargs.get("wandb", False)), 

236 project=kwargs.get("project"), 

237 started=time.monotonic(), 

238 ) 

239 weights = log / "weights" 

240 weights.mkdir(exist_ok=True) 

241 shutil.copy2(checkpoint, weights / "best.pt") 

242 training_progress(f"Best SAM 3 model saved to: {weights / 'best.pt'}") 

243 return DetectionTrainResult( 

244 save_dir=log, results_dict={"status": "completed", "classes": classes} 

245 ) 

246 

247 

248def name_categories(dataset: Path, prompts: dict[str, str]) -> None: 

249 """Rename each COCO category to its prompt: SAM 3 learns a class by its words.""" 

250 for split in ("train", "valid"): 

251 path = dataset / split / "_annotations.coco.json" 

252 data = json.loads(path.read_text()) 

253 for category in data["categories"]: 

254 category["name"] = prompts[category["name"]] 

255 path.write_text(json.dumps(data, indent=2))