Coverage for collectra/tasks/image_segmentation/sam3_training.py: 91.75%

97 statements  

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

1"""Adapt Meta's installed image-training template for mask-supervised COCO data.""" 

2 

3import copy 

4from pathlib import Path 

5from types import MethodType, SimpleNamespace 

6 

7import yaml 

8 

9 

10def training_config( 

11 dataset, 

12 output, 

13 checkpoint, 

14 *, 

15 epochs, 

16 batch, 

17 num_gpus, 

18 wandb=False, 

19 run_name=None, 

20 project=None, 

21 confidence_threshold=0.5, 

22 masks=True, 

23): 

24 """The trainer's configuration; ``masks=False`` trains on boxes alone.""" 

25 from .sam3 import _sam3 

26 

27 package = Path(_sam3().__file__).parent 

28 template = ( 

29 package / "train/configs/roboflow_v100/roboflow_v100_full_ft_100_images.yaml" 

30 ) 

31 if not template.is_file(): 

32 raise FileNotFoundError( 

33 f"Install SAM3's training sources; template missing: {template}" 

34 ) 

35 config = yaml.safe_load(template.read_text()) 

36 config["paths"].update( 

37 roboflow_vl_100_root=str(dataset), 

38 experiment_log_dir=str(output / "training"), 

39 bpe_path=str(package / "assets/bpe_simple_vocab_16e6.txt.gz"), 

40 ) 

41 settings = config["roboflow_train"] 

42 settings.update(supercategory="collectra", num_images=None) 

43 if masks: 

44 losses = settings["loss"]["loss_fns_find"] 

45 losses.append( 

46 { 

47 "_target_": "sam3.train.loss.loss_fns.Masks", 

48 "focal_alpha": 0.25, 

49 "focal_gamma": 2.0, 

50 "weight_dict": {"loss_mask": 200.0, "loss_dice": 10.0}, 

51 "compute_aux": False, 

52 } 

53 ) 

54 # Validation masks must be decoded too; Meta's detection template only 

55 # decodes them in the training transform sequence. 

56 settings["val_transforms"][0]["transforms"].insert( 

57 0, 

58 { 

59 "_target_": "sam3.train.transforms.segmentation.DecodeRle", 

60 }, 

61 ) 

62 config["scratch"].update( 

63 enable_segmentation=masks, 

64 train_batch_size=batch, 

65 num_train_workers=0, 

66 num_val_workers=0, 

67 ) 

68 trainer = config["trainer"] 

69 trainer.update( 

70 _target_="collectra.tasks.image_segmentation.sam3_metrics.create_trainer", 

71 max_epochs=epochs, 

72 skip_saving_ckpts=True, 

73 val_epoch_freq=1, 

74 skip_first_val=False, 

75 collectra_output=str(output), 

76 collectra_wandb=wandb, 

77 collectra_run_name=run_name, 

78 collectra_project=project, 

79 collectra_selection="mask_iou" if masks else "bbox_ap", 

80 ) 

81 trainer["model"] = { 

82 "_target_": "collectra.tasks.image_segmentation.sam3_training.build_training_model", 

83 "checkpoint": str(checkpoint), 

84 "bpe_path": config["paths"]["bpe_path"], 

85 "masks": masks, 

86 } 

87 for split, folder in (("train", "train"), ("val", "valid")): 

88 data = trainer["data"][split] 

89 data["dataset"].update( 

90 img_folder=str(dataset / folder), 

91 ann_file=str(dataset / folder / "_annotations.coco.json"), 

92 load_segmentation=masks, 

93 ) 

94 data["drop_last"] = False 

95 if masks: 

96 # After every epoch the training images are also scored like validation 

97 # (no augmentation, eval mode), so train/mask_iou is comparable to 

98 # val/mask_iou. Box-only training has no masks to score. 

99 train_eval = copy.deepcopy(trainer["data"]["val"]) 

100 train_eval["dataset"].update( 

101 img_folder=str(dataset / "train"), 

102 ann_file=str(dataset / "train/_annotations.coco.json"), 

103 ) 

104 trainer.update( 

105 collectra_train_eval=train_eval, 

106 collectra_mask_threshold=confidence_threshold, 

107 ) 

108 import json 

109 

110 valid = json.loads((dataset / "valid/_annotations.coco.json").read_text()) 

111 if valid["images"]: 

112 evaluator = trainer["meters"]["val"]["roboflow100"]["detection"][ 

113 "pred_file_evaluators" 

114 ][0] 

115 evaluator["gt_path"] = str(dataset / "valid/_annotations.coco.json") 

116 if masks: 

117 trainer["meters"]["val"]["roboflow100"]["mask_iou"] = { 

118 "_target_": "collectra.tasks.image_segmentation.sam3_metrics.MaskIoU", 

119 "confidence_threshold": confidence_threshold, 

120 } 

121 else: 

122 # Training without held-out images must not silently evaluate on training data. 

123 trainer["data"].pop("val", None) 

124 trainer["meters"] = {} 

125 trainer["mode"] = "train_only" 

126 config["launcher"].update(gpus_per_node=num_gpus, num_nodes=1) 

127 config["submitit"].update(use_cluster=False, job_array=None) 

128 return config 

129 

130 

131def load_image_state(model, state): 

132 """Load image weights, adapting SAM3.1's three-level detection neck.""" 

133 if any(key.startswith("detector.") for key in state): 

134 state = { 

135 key.removeprefix("detector."): value 

136 for key, value in state.items() 

137 if key.startswith("detector.") 

138 } 

139 prefix = "backbone.vision_backbone." 

140 tracking = (prefix + "interactive_convs.", prefix + "propagation_convs.") 

141 if any(key.startswith(tracking) for key in state): 

142 state = { 

143 key: value for key, value in state.items() if not key.startswith(tracking) 

144 } 

145 # SAM3.1 stores three detection scales. The image builder creates four, 

146 # then SAM3VLBackbone(scalp=1) discards the fourth. Initialize only that 

147 # unused scale from the equivalent stride-1 convolutions; never tolerate 

148 # missing weights in any feature level actually consumed by the model. 

149 neck = model.backbone.vision_backbone 

150 if model.backbone.scalp != 1 or tuple(neck.scale_factors) != ( 

151 4.0, 

152 2.0, 

153 1.0, 

154 0.5, 

155 ): 

156 raise ValueError("Unsupported SAM3 image backbone for SAM3.1 checkpoint") 

157 for suffix in ( 

158 "conv_1x1.weight", 

159 "conv_1x1.bias", 

160 "conv_3x3.weight", 

161 "conv_3x3.bias", 

162 ): 

163 target = prefix + "convs.3." + suffix 

164 if target not in state: 

165 state[target] = state[prefix + "convs.2." + suffix].clone() 

166 model.load_state_dict(state, strict=True) 

167 

168 

169def _training_mlp_forward(self, x): 

170 """SAM3 ViT MLP with ordinary autograd-capable PyTorch operations.""" 

171 x = self.act(self.fc1(x)) 

172 x = self.drop1(x) 

173 x = self.norm(x) 

174 x = self.fc2(x) 

175 return self.drop2(x) 

176 

177 

178def enable_training_mlps(model): 

179 from sam3.model.vitdet import Mlp 

180 

181 # Upstream Mlp.forward uses addmm_act, an inference-only fused kernel. 

182 # Bind only this model's MLPs; keep parameter names/checkpoints intact and 

183 # leave SAM3's inference implementation untouched. 

184 for module in model.modules(): 

185 if isinstance(module, Mlp): 

186 module.forward = MethodType(_training_mlp_forward, module) 

187 

188 

189def freeze_unused_semantic_head(model): 

190 """Instance-mask losses do not supervise the separate semantic output.""" 

191 segmentation = getattr(model, "segmentation_head", None) 

192 semantic = getattr(segmentation, "semantic_seg_head", None) 

193 if semantic is not None: 

194 # DDP sees this head in forward's outputs, so find_unused_parameters 

195 # cannot detect that the loss never consumes it. Freeze its parameters 

196 # before DDP/optimizer construction, preserving checkpoint compatibility. 

197 semantic.requires_grad_(False) 

198 

199 

200def freeze_segmentation_head(model): 

201 """Box training does not supervise the mask head at all.""" 

202 head = getattr(model, "segmentation_head", None) 

203 if head is not None: 

204 # The weights stay in the model, so the checkpoint is still a full SAM 3 

205 # that the segmenter can load; DDP just must not wait for gradients. 

206 head.requires_grad_(False) 

207 

208 

209def build_training_model(checkpoint, bpe_path, masks=True): 

210 import torch 

211 from sam3.model_builder import build_sam3_image_model 

212 

213 state = torch.load(checkpoint, map_location="cpu", weights_only=True) 

214 state = state.get("model", state) 

215 model = build_sam3_image_model( 

216 bpe_path=bpe_path, 

217 load_from_HF=False, 

218 enable_segmentation=True, 

219 device="cpu", 

220 eval_mode=False, 

221 ) 

222 load_image_state(model, state) 

223 enable_training_mlps(model) 

224 freeze_unused_semantic_head(model) 

225 if not masks: 

226 freeze_segmentation_head(model) 

227 return model 

228 

229 

230def launch(config_path): 

231 from hydra import initialize_config_dir 

232 from sam3.train.train import main, register_omegaconf_resolvers 

233 

234 config_path = Path(config_path).resolve() 

235 register_omegaconf_resolvers() 

236 with initialize_config_dir(str(config_path.parent), version_base="1.2"): 

237 main( 

238 SimpleNamespace( 

239 config=config_path.name, use_cluster=False, num_gpus=None, num_nodes=1 

240 ) 

241 )