Coverage for collectra/tasks/image_segmentation/yolo_training.py: 93.21%

162 statements  

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

1"""Ultralytics training on bitmap masks, imported only by the training runner.""" 

2 

3from copy import copy, deepcopy 

4import json 

5import math 

6from pathlib import Path 

7 

8import numpy as np 

9from PIL import Image 

10import torch 

11from torch.utils.data import DataLoader, Dataset 

12from ultralytics.data.dataset import YOLODataset 

13from ultralytics.models.yolo.segment import SegmentationTrainer, SegmentationValidator 

14from ultralytics.utils import __version__ 

15 

16from collectra.types.images import open_oriented 

17 

18from .mask_metrics import mask_overlap 

19from .sam3_metrics import EpochReporter 

20 

21 

22def decode_mask(rle): 

23 """Decode Collectra's lossless COCO RLE without requiring pycocotools.""" 

24 counts = rle["counts"] 

25 if not isinstance(counts, list): 

26 from pycocotools.mask import decode 

27 

28 return decode(rle).astype(bool) 

29 pixels = np.zeros(math.prod(rle["size"]), dtype=np.uint8) 

30 position = 0 

31 for index, count in enumerate(counts): 

32 if count < 0 or position + count > len(pixels): 

33 raise ValueError("Invalid COCO mask run length") 

34 pixels[position:position + count] = index % 2 

35 position += count 

36 if position != len(pixels): 

37 raise ValueError("COCO mask runs do not match the mask dimensions") 

38 return pixels.reshape(rle["size"], order="F") 

39 

40 

41class BitmapDataset(Dataset): 

42 """Resize/pad image and masks together, retaining holes and separate islands. 

43 

44 Uses horizontal/vertical flips for training. Polygon-based mosaic, random 

45 perspective and mixup are deliberately bypassed, so instance masks remain 

46 bitmaps throughout preparation and training. 

47 """ 

48 

49 rect = False 

50 mosaic = False 

51 collate_fn = staticmethod(YOLODataset.collate_fn) 

52 

53 def __init__(self, directory, imgsz, *, augment=False, fliplr=.5, flipud=0): 

54 self.directory = Path(directory) 

55 data = json.loads((self.directory / "_annotations.coco.json").read_text()) 

56 self.images = data["images"] 

57 self.categories = {item["id"]: index for index, item in enumerate(sorted(data["categories"], key=lambda item: item["id"]))} 

58 self.annotations = {} 

59 for annotation in data["annotations"]: 

60 self.annotations.setdefault(annotation["image_id"], []).append(annotation) 

61 self.imgsz, self.augment, self.fliplr, self.flipud = imgsz, augment, fliplr, flipud 

62 self.im_files = [str(self.directory / image["file_name"]) for image in self.images] 

63 self.labels = [] 

64 for image, path in zip(self.images, self.im_files): 

65 annotations = self.annotations.get(image["id"], []) 

66 boxes = np.array([a["bbox"] for a in annotations], dtype=np.float32).reshape(-1, 4) 

67 boxes[:, :2] += boxes[:, 2:] / 2 

68 boxes /= [image["width"], image["height"], image["width"], image["height"]] 

69 self.labels.append({"im_file": path, "shape": (image["height"], image["width"]), 

70 "cls": np.array([self.categories[a["category_id"]] for a in annotations], dtype=np.float32).reshape(-1, 1), 

71 "bboxes": boxes, "normalized": True, "bbox_format": "xywh"}) 

72 

73 def __len__(self): 

74 return len(self.images) 

75 

76 def __getitem__(self, index): 

77 metadata = self.images[index] 

78 image = open_oriented(self.im_files[index]).convert("RGB") 

79 width, height = image.size 

80 scale = self.imgsz / max(width, height) 

81 new_width, new_height = round(width * scale), round(height * scale) 

82 left, top = (self.imgsz - new_width) // 2, (self.imgsz - new_height) // 2 

83 canvas = Image.new("RGB", (self.imgsz, self.imgsz), (114, 114, 114)) 

84 canvas.paste(image.resize((new_width, new_height), Image.Resampling.BILINEAR), (left, top)) 

85 pixels = np.asarray(canvas).copy() 

86 masks, classes = [], [] 

87 for annotation in self.annotations.get(metadata["id"], []): 

88 mask = decode_mask(annotation["segmentation"]) 

89 if mask.shape != (height, width): 

90 raise ValueError("Annotation mask dimensions differ from the dataset image") 

91 resized = Image.fromarray(mask.astype(np.uint8)).resize((new_width, new_height), Image.Resampling.NEAREST) 

92 canvas = np.zeros((self.imgsz, self.imgsz), dtype=np.uint8) 

93 canvas[top:top + new_height, left:left + new_width] = np.asarray(resized) 

94 if canvas.any(): 

95 masks.append(canvas) 

96 classes.append(self.categories[annotation["category_id"]]) 

97 masks = np.asarray(masks, dtype=np.uint8).reshape(-1, self.imgsz, self.imgsz) 

98 if self.augment and np.random.random() < self.fliplr: 

99 pixels, masks = pixels[:, ::-1], masks[:, :, ::-1] 

100 if self.augment and np.random.random() < self.flipud: 

101 pixels, masks = pixels[::-1], masks[:, ::-1] 

102 boxes = [] 

103 for mask in masks: 

104 ys, xs = np.nonzero(mask) 

105 x1, y1, x2, y2 = xs.min(), ys.min(), xs.max() + 1, ys.max() + 1 

106 boxes.append([(x1 + x2) / 2, (y1 + y2) / 2, x2 - x1, y2 - y1]) 

107 return { 

108 "img": torch.from_numpy(np.ascontiguousarray(pixels.transpose(2, 0, 1))), 

109 "masks": torch.from_numpy(np.ascontiguousarray(masks)), 

110 "cls": torch.tensor(classes, dtype=torch.float32).reshape(-1, 1), 

111 "bboxes": torch.tensor(boxes, dtype=torch.float32).reshape(-1, 4) / self.imgsz, 

112 "batch_idx": torch.zeros(len(classes)), "im_file": self.im_files[index], 

113 "ori_shape": (height, width), "resized_shape": (self.imgsz, self.imgsz), 

114 "ratio_pad": ((new_height / height, new_width / width), (left, top)), 

115 } 

116 

117 

118class MaskValidator(SegmentationValidator): 

119 def init_metrics(self, model): 

120 super().init_metrics(model) 

121 self.overlap = torch.zeros(2, dtype=torch.int64, device=self.device) 

122 

123 def _process_batch(self, preds, batch): 

124 self.overlap += mask_overlap( 

125 {"masks": preds["masks"], "labels": preds["cls"], "scores": preds["conf"]}, 

126 {"masks": batch["masks"], "labels": batch["cls"]}, self.mask_threshold, 

127 ) 

128 return super()._process_batch(preds, batch) 

129 

130 def gather_stats(self): 

131 super().gather_stats() 

132 if torch.distributed.is_available() and torch.distributed.is_initialized(): 

133 torch.distributed.all_reduce(self.overlap) 

134 

135 def get_stats(self): 

136 stats = super().get_stats() 

137 stats["val/mask_iou"] = float(self.overlap[0] / self.overlap[1].clamp_min(1)) 

138 stats["fitness"] = stats["val/mask_iou"] 

139 return stats 

140 

141 

142class MaskSegmentationTrainer(SegmentationTrainer): 

143 """Train against bitmap targets and keep only the best EMA weights.""" 

144 

145 def get_dataset(self): 

146 self.collectra = json.loads(Path(self.args.data).read_text()) 

147 directory = Path(self.collectra["dataset"]) 

148 annotations = json.loads((directory / "train/_annotations.coco.json").read_text()) 

149 names = {index: item["name"] for index, item in enumerate(sorted(annotations["categories"], key=lambda item: item["id"]))} 

150 return {"train": str(directory / "train"), 

151 "val": str(directory / "valid"), 

152 "names": names, "nc": len(names), "channels": 3, "path": directory} 

153 

154 def build_dataset(self, img_path, mode="train", batch=None): 

155 return BitmapDataset(img_path, self.args.imgsz, augment=mode == "train", 

156 fliplr=self.args.fliplr, flipud=self.args.flipud) 

157 

158 def get_dataloader(self, dataset_path, batch_size=16, rank=0, mode="train"): 

159 if mode == "val" and not self.collectra["has_validation"]: 

160 dataset = self.build_dataset(dataset_path, mode, batch_size) 

161 return DataLoader(dataset, batch_size=1, collate_fn=dataset.collate_fn) 

162 return super().get_dataloader(dataset_path, batch_size, rank, mode) 

163 

164 def get_validator(self): 

165 validator = MaskValidator(self.test_loader, save_dir=self.save_dir, args=copy(self.args), _callbacks=self.callbacks) 

166 validator.mask_threshold = self.collectra["threshold"] 

167 return validator 

168 

169 def validate(self): 

170 if not self.collectra["has_validation"]: 

171 loss = torch.tensor(sum(float(value) for value in self.tloss.values()), device=self.device) 

172 if torch.distributed.is_available() and torch.distributed.is_initialized(): 

173 torch.distributed.all_reduce(loss) 

174 loss /= torch.distributed.get_world_size() 

175 fitness = -float(loss) 

176 self.best_fitness = fitness if self.best_fitness is None else max(self.best_fitness, fitness) 

177 return {}, fitness 

178 return super().validate() 

179 

180 def save_model(self): 

181 if not math.isfinite(float(self.fitness)) or self.fitness != self.best_fitness: 

182 return False 

183 model = deepcopy(self.ema.ema).float().cpu().to(memory_format=torch.contiguous_format) 

184 if hasattr(model, "criterion"): 

185 model.criterion = None 

186 self.wdir.mkdir(parents=True, exist_ok=True) 

187 temporary = self.best.with_suffix(".tmp") 

188 torch.save({"model": model, "epoch": self.epoch, "train_args": vars(self.args), 

189 "version": __version__, "optimizer": None}, temporary) 

190 temporary.replace(self.best) 

191 (self.save_dir / "best.json").write_text(json.dumps({ 

192 "epoch": self.epoch + 1, 

193 "metric": "val/mask_iou" if self.collectra["has_validation"] else "train/loss", 

194 "value": float(self.fitness) if self.collectra["has_validation"] else -float(self.fitness), 

195 })) 

196 return True 

197 

198 def save_metrics(self, metrics): 

199 super().save_metrics(metrics) 

200 if not hasattr(self, "reporter"): 

201 self.reporter = EpochReporter(self.save_dir, wandb=self.collectra["wandb"], 

202 project=self.collectra["project"], run_name=self.collectra["run_name"], 

203 config=vars(self.args)) 

204 self.reporter.record(self.epoch + 1, "", metrics) 

205 

206 def final_eval(self): 

207 # No last checkpoint or second validation pass; the selected weights 

208 # and their epoch's validation score already agree. 

209 if hasattr(self, "reporter"): 

210 self.reporter.close() 

211 self.reporter.run = None 

212 

213 

214def launch(config_path): 

215 from collectra.tasks.machine_learning.yolo import YOLOTask, get_yolo_class 

216 

217 config = json.loads(Path(config_path).read_text()) 

218 model = get_yolo_class()(config["model"]) 

219 if model.task != "segment": 

220 raise ValueError("ImageSegmenterYOLO requires a YOLO segmentation model (-seg)") 

221 (Path(config["params"]["project"]) / config["params"]["name"] / "weights" / "best.pt").unlink(missing_ok=True) 

222 with YOLOTask("train", model=model)._wandb_logging(False): 

223 try: 

224 model.train(trainer=MaskSegmentationTrainer, **config["params"]) 

225 finally: 

226 reporter = getattr(getattr(model, "trainer", None), "reporter", None) 

227 if reporter is not None and reporter.run is not None: 

228 reporter.close()