Coverage for collectra/tasks/image_classifier/torchvision.py: 92.83%

307 statements  

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

1"""Torchvision image classification with portable, metadata-bearing checkpoints.""" 

2 

3from __future__ import annotations 

4 

5from pydantic import BaseModel 

6 

7from collectra.commons import PositionalFields 

8from pathlib import Path 

9from typing import Annotated 

10 

11from cappa import Arg 

12 

13from collectra.cli import command 

14from collectra.logger import get_logger 

15from collectra.types.images import ( 

16 Image, 

17 ImageCrop, 

18 image_channel_count, 

19 read_tiff_channels, 

20) 

21from collectra.types.links import Link 

22from collectra.utils import threading_locked 

23from ..machine_learning.training import run_training_command 

24from .training import ( 

25 ClassificationTrainResult, 

26 TorchClassifierTask, 

27 prepare_classification_inputs, 

28) 

29 

30__all__ = ["ImageClassifierTorchvision"] 

31logger = get_logger(__name__) 

32 

33 

34def _tiff_tensor(pixels): 

35 """Convert HWC TIFF samples to float32 CHW, preserving every channel.""" 

36 import numpy as np 

37 import torch 

38 

39 values = pixels.astype(np.float32) 

40 if np.issubdtype(pixels.dtype, np.unsignedinteger): 

41 values /= np.iinfo(pixels.dtype).max 

42 return torch.from_numpy(np.ascontiguousarray(values.transpose(2, 0, 1))) 

43 

44 

45def _load_classifier_image(path): 

46 """ImageFolder loader that bypasses Pillow for TIFF images.""" 

47 from torchvision.datasets.folder import pil_loader 

48 

49 if Path(path).suffix.lower() in {".tif", ".tiff"}: 

50 return _tiff_tensor(read_tiff_channels(path)) 

51 return pil_loader(path) 

52 

53 

54def _target_tiff_pixels(image, *, tiff_maxworkers: int | None = None): 

55 import numpy as np 

56 

57 target = image.resolve() if type(image) is Link else image 

58 pixels = read_tiff_channels(target.get_path(), maxworkers=tiff_maxworkers) 

59 if isinstance(target, ImageCrop): 

60 left, top, right, bottom = target.coordinates() 

61 if right <= left or bottom <= top: 

62 raise ValueError(f"ImageCrop {target.id!r} produces an empty pixel crop") 

63 pixels = pixels[top:bottom, left:right, :] 

64 return np.rot90(pixels, k=target.orientation.to_degree() // 90, axes=(0, 1)) 

65 

66 

67class _NormalizeClassifierPixels(PositionalFields, BaseModel): 

68 mean: list[float] 

69 std: list[float] 

70 

71 def __call__(self, pixels): 

72 import torch 

73 from torchvision.transforms import functional as F 

74 

75 if not isinstance(pixels, torch.Tensor): 

76 pixels = F.to_tensor(pixels) 

77 channels = pixels.shape[0] 

78 if len(self.mean) == len(self.std) == 3 and channels != 3: 

79 # RGB statistics have no defined meaning for spectral bands. 

80 return pixels 

81 if len(self.mean) != len(self.std) or len(self.mean) not in (1, channels): 

82 raise ValueError( 

83 f"Normalization statistics do not match {channels} image channels" 

84 ) 

85 return F.normalize(pixels, self.mean, self.std) 

86 

87 

88class _RandomRotate90: 

89 """Rotate a PIL image or CHW tensor by a random multiple of 90 degrees.""" 

90 

91 def __call__(self, pixels): 

92 import torch 

93 

94 turns = int(torch.randint(4, ()).item()) 

95 if isinstance(pixels, torch.Tensor): 

96 return torch.rot90(pixels, turns, dims=(-2, -1)) 

97 return pixels.rotate(90 * turns, expand=True) 

98 

99 

100def _replace_head(model, num_classes: int): 

101 """Replace the output projection for torchvision's classification families.""" 

102 from torch import nn 

103 

104 for name in ("fc", "classifier", "heads", "head"): 

105 head = getattr(model, name, None) 

106 if head is None: 

107 continue 

108 if isinstance(head, nn.Linear): 

109 replacement = nn.Linear( 

110 head.in_features, num_classes, bias=head.bias is not None 

111 ) 

112 setattr(model, name, replacement) 

113 return replacement 

114 if isinstance(head, nn.Sequential): 

115 projections = [ 

116 (path, module) 

117 for path, module in head.named_modules() 

118 if isinstance(module, (nn.Linear, nn.Conv2d)) 

119 ] 

120 if not projections: 

121 continue 

122 path, layer = projections[-1] 

123 if isinstance(layer, nn.Linear): 

124 replacement = nn.Linear( 

125 layer.in_features, num_classes, bias=layer.bias is not None 

126 ) 

127 else: # SqueezeNet's classifier is a 1x1 convolution. 

128 replacement = nn.Conv2d( 

129 layer.in_channels, 

130 num_classes, 

131 layer.kernel_size, 

132 stride=layer.stride, 

133 padding=layer.padding, 

134 dilation=layer.dilation, 

135 groups=layer.groups, 

136 bias=layer.bias is not None, 

137 ) 

138 model.num_classes = num_classes 

139 parent_path, _, child = path.rpartition(".") 

140 parent = head.get_submodule(parent_path) if parent_path else head 

141 setattr(parent, child, replacement) 

142 return replacement 

143 raise ValueError(f"Unsupported classification head in {type(model).__name__}") 

144 

145 

146def _disable_auxiliary_heads(model) -> None: 

147 # GoogLeNet and Inception should return a single logits tensor in training too. 

148 if hasattr(model, "aux_logits"): 

149 model.aux_logits = False 

150 for name in ("AuxLogits", "aux1", "aux2"): 

151 if hasattr(model, name): 

152 setattr(model, name, None) 

153 

154 

155def _ensure_supported_multichannel_architecture( 

156 architecture: str, input_channels: int 

157) -> None: 

158 if input_channels == 3: 

159 return 

160 # supported = {"resnet18", "resnet34", "resnet50"} 

161 supported = { 

162 "resnet18", 

163 "resnet34", 

164 "resnet50", 

165 "resnet101", 

166 "resnet152", 

167 "convnext_base", 

168 "convnext_tiny", 

169 "convnext_small", 

170 "convnext_large", 

171 } 

172 if architecture not in supported: 

173 raise ValueError( 

174 f"{input_channels}-channel input adaptation is currently supported only for " 

175 "resnet18, resnet34, resnet50, resnet101, resnet152, convnext_base, convnext_tiny, convnext_small, convnext_large" 

176 ) 

177 

178 

179class ImageClassifierTorchvision(TorchClassifierTask): 

180 """Train torchvision classifiers and return predicted class Links.""" 

181 

182 prepare_training_inputs = staticmethod(prepare_classification_inputs) 

183 

184 def __init__( 

185 self, name: str, model: str | Path = "resnet18", fusion: bool = False, **kwargs 

186 ): 

187 if not isinstance(fusion, bool): 

188 raise ValueError("fusion must be a YAML boolean (true or false)") 

189 super().__init__(name, model=model, fusion=fusion, **kwargs) 

190 self.original_model_path: Path | None = None 

191 self._categories: list[str] = [] 

192 self._architecture = "" 

193 self._model_kwargs: dict = {} 

194 self._preprocessing: dict = {} 

195 self._device = "cpu" 

196 self._input_channels = 3 

197 

198 def _transforms( 

199 self, 

200 *, 

201 training: bool = False, 

202 fliplr: float = 0.0, 

203 flipud: float = 0.0, 

204 rotate90: bool = False, 

205 ): 

206 from torchvision import transforms as T 

207 

208 config = self._preprocessing 

209 interpolation = T.InterpolationMode(config["interpolation"]) 

210 # Rotate before resizing so non-square crops keep their configured shape. 

211 steps = [_RandomRotate90()] if training and rotate90 else [] 

212 steps += [ 

213 T.Resize( 

214 config["resize_size"], interpolation=interpolation, antialias=True 

215 ), 

216 T.CenterCrop(config["crop_size"]), 

217 ] 

218 if training and fliplr: 

219 steps.append(T.RandomHorizontalFlip(fliplr)) 

220 if training and flipud: 

221 steps.append(T.RandomVerticalFlip(flipud)) 

222 steps.append(_NormalizeClassifierPixels(config["mean"], config["std"])) 

223 return T.Compose(steps) 

224 

225 def _export_image( 

226 self, target, destination, min_size, tiff_maxworkers: int | None = None 

227 ): 

228 if target.get_path().suffix.lower() not in {".tif", ".tiff"}: 

229 return super()._export_image( 

230 target, 

231 destination, 

232 min_size, 

233 tiff_maxworkers=tiff_maxworkers, 

234 ) 

235 import numpy as np 

236 import tifffile 

237 

238 pixels = _target_tiff_pixels(target, tiff_maxworkers=tiff_maxworkers) 

239 if min(pixels.shape[:2]) < max(1, min_size): 

240 logger.warning( 

241 "Skipping classifier image %s below minimum size %d", 

242 target.id, 

243 min_size, 

244 ) 

245 return False 

246 tifffile.imwrite( 

247 destination.with_suffix(".tif"), 

248 np.ascontiguousarray(pixels.transpose(2, 0, 1)), 

249 photometric="minisblack", 

250 metadata={"axes": "CYX"}, 

251 ) 

252 return True 

253 

254 def _make_datasets(self, train_dir, val_dir, augmentation): 

255 from torchvision.datasets import ImageFolder 

256 

257 train = ImageFolder(train_dir, loader=_load_classifier_image) 

258 val = ImageFolder(val_dir, loader=_load_classifier_image, allow_empty=True) 

259 detected = { 

260 path: ( 

261 image_channel_count(path) 

262 if Path(path).suffix.lower() in {".tif", ".tiff"} 

263 else 3 

264 ) 

265 for path, _ in [*train.samples, *val.samples] 

266 } 

267 if len(set(detected.values())) != 1: 

268 details = ", ".join( 

269 f"{path}: {count} channels" for path, count in detected.items() 

270 ) 

271 raise ValueError( 

272 f"Inconsistent input channel counts in classifier dataset: {details}" 

273 ) 

274 channels = next(iter(detected.values())) 

275 if self.fusion: 

276 if channels < 3 or channels % 3: 

277 raise ValueError( 

278 "fusion requires stacked RGB views with a channel count divisible by 3" 

279 ) 

280 from .torchvision_fusion import RGBViewFusionClassifier 

281 

282 if ( 

283 isinstance(self.model, RGBViewFusionClassifier) 

284 and self.model.input_channels != channels 

285 ): 

286 raise ValueError( 

287 f"Fusion checkpoint expects {self.model.input_channels} channels; dataset has {channels}" 

288 ) 

289 self._preprocessing["channels"] = channels 

290 self._input_channels = channels 

291 if ( 

292 channels != 3 

293 and len(self._preprocessing["mean"]) == len(self._preprocessing["std"]) == 3 

294 ): 

295 if channels % 3 == 0: 

296 num_views = channels // 3 

297 logger.info( 

298 "Detected %d RGB views (%d channels); repeating pretrained RGB normalization", 

299 num_views, 

300 channels, 

301 ) 

302 self._preprocessing["mean"] = self._preprocessing["mean"] * num_views 

303 self._preprocessing["std"] = self._preprocessing["std"] * num_views 

304 else: 

305 logger.info( 

306 "Using identity normalization for %d channels; channel count is not divisible by 3", 

307 channels, 

308 ) 

309 self._preprocessing["mean"] = [0.0] * channels 

310 self._preprocessing["std"] = [1.0] * channels 

311 train.transform = self._transforms(training=True, **augmentation) 

312 val.transform = self._transforms() 

313 return train, val 

314 

315 def _load(self, *, pretrained: bool = True) -> None: 

316 import torch 

317 from torchvision import models 

318 

319 if isinstance(self.model, torch.nn.Module): 

320 return 

321 if not isinstance(self.model, (str, Path)): 

322 raise ValueError( 

323 "Model must be a torchvision model name or a checkpoint path" 

324 ) 

325 path = Path(self.model).expanduser() 

326 if path.is_file(): 

327 checkpoint = torch.load(path, map_location="cpu", weights_only=True) 

328 required = { 

329 "architecture", 

330 "state_dict", 

331 "classes", 

332 "preprocessing", 

333 "model_kwargs", 

334 } 

335 if not isinstance(checkpoint, dict) or not required.issubset(checkpoint): 

336 raise ValueError( 

337 "Expected a Collectra torchvision checkpoint containing architecture, " 

338 "state_dict, classes, preprocessing, and model_kwargs. " 

339 "A bare state_dict does not identify its architecture or class labels." 

340 ) 

341 self._architecture = checkpoint["architecture"] 

342 self._model_kwargs = checkpoint["model_kwargs"] 

343 self._categories = checkpoint["classes"] 

344 self._preprocessing = checkpoint["preprocessing"] 

345 model = models.get_model( 

346 self._architecture, weights=None, **self._model_kwargs 

347 ) 

348 self._input_channels = checkpoint.get("input_channels", 3) 

349 fusion_spec = checkpoint.get("fusion") 

350 

351 if self._input_channels != 3 and not fusion_spec: 

352 if self.fusion: 

353 raise ValueError( 

354 "Cannot enable fusion on a first-layer-adapted checkpoint; " 

355 "start from an RGB model or a fusion checkpoint" 

356 ) 

357 _ensure_supported_multichannel_architecture( 

358 self._architecture, self._input_channels 

359 ) 

360 _adapt_rgb_input_channels( 

361 model, 

362 self._input_channels, 

363 ) 

364 

365 _disable_auxiliary_heads(model) 

366 _replace_head(model, len(self._categories)) 

367 if fusion_spec: 

368 from .torchvision_fusion import restore_fusion 

369 

370 model = restore_fusion(model, self._input_channels, fusion_spec) 

371 self.fusion = True 

372 model.load_state_dict(checkpoint["state_dict"]) 

373 self.original_model_path = path.resolve() 

374 else: 

375 name = str(self.model) 

376 available = models.list_models(module=models) 

377 if name not in available: 

378 raise ValueError( 

379 f"Unknown torchvision classification model or missing checkpoint: {name!r}. " 

380 f"Available models: {', '.join(available)}" 

381 ) 

382 weights = models.get_model_weights(name).DEFAULT 

383 preset = weights.transforms() 

384 self._preprocessing = { 

385 "crop_size": preset.crop_size, 

386 "resize_size": preset.resize_size, 

387 "mean": preset.mean, 

388 "std": preset.std, 

389 "interpolation": preset.interpolation.value, 

390 } 

391 builder_kwargs = {} 

392 if name.startswith("vit_"): 

393 builder_kwargs["image_size"] = preset.crop_size[0] 

394 if name in {"inception_v3", "googlenet"}: 

395 builder_kwargs["init_weights"] = False 

396 model = models.get_model( 

397 name, weights=weights if pretrained else None, **builder_kwargs 

398 ) 

399 _disable_auxiliary_heads(model) 

400 self._architecture = name 

401 self._model_kwargs = dict(builder_kwargs) 

402 if hasattr(model, "transform_input"): 

403 self._model_kwargs["transform_input"] = model.transform_input 

404 if hasattr(model, "aux_logits"): 

405 self._model_kwargs["aux_logits"] = False 

406 if hasattr(model, "image_size"): 

407 self._model_kwargs["image_size"] = model.image_size 

408 self._categories = list(weights.meta["categories"]) 

409 self.original_model_path = None 

410 self.model = model.to(self._device) 

411 self.model.eval() 

412 

413 @threading_locked() 

414 def run(self, *args: Image) -> Link: 

415 """Classify one image or crop and link the predicted class to it.""" 

416 import torch 

417 

418 if len(args) != 1 or not isinstance(args[0], Image): 

419 raise ValueError("This task requires a single Image or ImageCrop input") 

420 self._device = self._select_device(getattr(self, "device", "")) 

421 self._load() 

422 self.model.to(self._device).eval() 

423 image = args[0] 

424 if image.get_path().suffix.lower() in {".tif", ".tiff"}: 

425 pixels = _tiff_tensor(_target_tiff_pixels(image)) 

426 batch = self._transforms()(pixels).unsqueeze(0).to(self._device) 

427 else: 

428 with image.pil() as pixels: 

429 batch = ( 

430 self._transforms()(pixels.convert("RGB")) 

431 .unsqueeze(0) 

432 .to(self._device) 

433 ) 

434 with torch.inference_mode(): 

435 class_index = self.model(batch).argmax(dim=1).item() 

436 class_name = self._categories[class_index] 

437 outputs = getattr(self, "output", []) 

438 outputs = [outputs] if isinstance(outputs, str) else outputs 

439 if outputs and class_name not in outputs: 

440 raise ValueError( 

441 f"Predicted class {class_name!r} is not a configured output: {outputs}" 

442 ) 

443 return Link(name=class_name, target=image) 

444 

445 @command 

446 def train( 

447 self, 

448 inputs: Annotated[ 

449 list[str], 

450 Arg( 

451 help="Pipeline data files or directories containing classification labels." 

452 ), 

453 ], 

454 model: Annotated[ 

455 str, 

456 Arg( 

457 help="Torchvision classification model name (e.g. resnet18, efficientnet_b0, vit_b_16) or a Collectra torchvision checkpoint. Omit to keep the configured model." 

458 ), 

459 ] = "", 

460 output: Annotated[ 

461 Path | None, 

462 Arg( 

463 help="Directory for extracted train/val images, metrics, and checkpoints." 

464 ), 

465 ] = None, 

466 use_existing: Annotated[ 

467 bool, 

468 Arg( 

469 help="Reuse an existing output train/ and val/ dataset if present; skip image export." 

470 ), 

471 ] = False, 

472 keep_log: Annotated[ 

473 bool, 

474 Arg( 

475 help="Keep extracted images and training logs after saving the model to the pipeline." 

476 ), 

477 ] = True, 

478 validation: Annotated[ 

479 str, 

480 Arg( 

481 help="Partition value identifying validation images; omit to train without validation." 

482 ), 

483 ] = "", 

484 exclude: Annotated[ 

485 str, Arg(help="Partition value identifying images to exclude.") 

486 ] = "", 

487 epochs: Annotated[int, Arg(help="Number of training epochs.")] = 10, 

488 batch: Annotated[int, Arg(help="Number of images per training batch.")] = 16, 

489 learning_rate: Annotated[ 

490 float, Arg(help="Initial learning rate for AdamW.") 

491 ] = 0.0001, 

492 weight_decay: Annotated[ 

493 float, Arg(help="Weight decay used for regularization.") 

494 ] = 0.0001, 

495 pretrained: Annotated[ 

496 bool, 

497 Arg( 

498 help="Use DEFAULT pretrained weights for a named model; checkpoints always load their saved weights." 

499 ), 

500 ] = True, 

501 freeze_backbone: Annotated[ 

502 bool, 

503 Arg( 

504 help="Train only the final classification layer; freeze all other parameters." 

505 ), 

506 ] = False, 

507 early_stop: Annotated[ 

508 int, 

509 Arg( 

510 help="Stop after this many epochs without validation-loss improvement; 0 disables." 

511 ), 

512 ] = 10, 

513 min_size: Annotated[ 

514 int, 

515 Arg( 

516 help="Skip images or crops with either dimension below this pixel threshold; 0 disables." 

517 ), 

518 ] = 0, 

519 fliplr: Annotated[ 

520 float, 

521 Arg( 

522 help="Probability of horizontal flipping during training, from 0 to 1." 

523 ), 

524 ] = 0.5, 

525 workers: Annotated[ 

526 int, 

527 Arg( 

528 help="Number of data-loading worker processes (default 8, capped by available CPUs)." 

529 ), 

530 ] = 8, 

531 wandb: Annotated[ 

532 bool, 

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

534 ] = False, 

535 device: Annotated[ 

536 str, 

537 Arg( 

538 help="Torch device such as cpu, cuda, cuda:0, or mps; omit for automatic selection." 

539 ), 

540 ] = "", 

541 seed: Annotated[ 

542 int, Arg(help="Random seed for model initialization and data loading.") 

543 ] = 0, 

544 flipud: Annotated[ 

545 float, 

546 Arg(help="Probability of vertical flipping during training, from 0 to 1."), 

547 ] = 0.0, 

548 rotate90: Annotated[ 

549 bool, 

550 Arg(help="Randomly rotate training images by 0, 90, 180 or 270 degrees."), 

551 ] = False, 

552 ): 

553 """Fine-tune a torchvision image classifier using its weights' prescribed image preprocessing.""" 

554 result = run_training_command( 

555 self, 

556 inputs, 

557 self._train, 

558 keep_log=keep_log, 

559 output=output, 

560 use_existing=use_existing, 

561 validation=validation, 

562 exclude=exclude, 

563 prepare_inputs=self.prepare_training_inputs, 

564 model=model, 

565 epochs=epochs, 

566 batch=batch, 

567 learning_rate=learning_rate, 

568 weight_decay=weight_decay, 

569 pretrained=pretrained, 

570 freeze_backbone=freeze_backbone, 

571 early_stop=early_stop, 

572 min_size=min_size, 

573 fliplr=fliplr, 

574 flipud=flipud, 

575 rotate90=rotate90, 

576 workers=workers, 

577 wandb=wandb, 

578 device=device, 

579 seed=seed, 

580 ) 

581 if self.pipeline is not None: 

582 saved_model = self.pipeline.data[self.name]["model"] 

583 self.original_model_path = (self.pipeline.path / saved_model).resolve() 

584 return result 

585 

586 def _checkpoint(self, epoch: int, metrics: dict) -> dict: 

587 return { 

588 "format_version": 1, 

589 "architecture": self._architecture, 

590 "model_kwargs": self._model_kwargs, 

591 "input_channels": self._input_channels, 

592 "fusion": self.model.fusion_spec if self.fusion else None, 

593 "classes": self._categories, 

594 "preprocessing": self._preprocessing, 

595 "state_dict": { 

596 name: value.detach().cpu() 

597 for name, value in self.model.state_dict().items() 

598 }, 

599 "epoch": epoch, 

600 "metrics": metrics, 

601 } 

602 

603 def _prepare_training_model(self, classes, pretrained, freeze): 

604 import torch 

605 

606 self._load(pretrained=pretrained) 

607 

608 if self.fusion: 

609 from .torchvision_fusion import RGBViewFusionClassifier 

610 

611 if not isinstance(self.model, RGBViewFusionClassifier): 

612 self.model = RGBViewFusionClassifier(self.model, self._input_channels) 

613 elif self.model.input_channels != self._input_channels: 

614 raise ValueError( 

615 "Fusion checkpoint channel count differs from training inputs" 

616 ) 

617 elif self._input_channels != 3: 

618 _ensure_supported_multichannel_architecture( 

619 self._architecture, 

620 self._input_channels, 

621 ) 

622 _adapt_rgb_input_channels( 

623 self.model, 

624 self._input_channels, 

625 ) 

626 

627 # Retain a fine-tuned head only when its class order still matches exactly. 

628 if classes != self._categories: 

629 _replace_head(self.model, len(classes)) 

630 self._categories = classes 

631 self.model.to(self._device) 

632 self.model.requires_grad_(not freeze) 

633 if freeze and self.fusion: 

634 self.model.attention.requires_grad_(True) 

635 if freeze: 

636 for name in ("fc", "classifier", "heads", "head"): 

637 head = getattr(self.model, name, None) 

638 if head is not None: 

639 layers = [ 

640 m 

641 for m in head.modules() 

642 if isinstance(m, (torch.nn.Linear, torch.nn.Conv2d)) 

643 ] 

644 if layers: 

645 layers[-1].requires_grad_(True) 

646 break 

647 

648 def _forward(self, pixels): 

649 return self.model(pixels.to(self._device)) 

650 

651 

652def _adapt_rgb_input_channels(model, input_channels: int): 

653 import torch 

654 

655 # original RT coding 

656 # if not hasattr(model, "conv1"): 

657 # raise ValueError( 

658 # f"{type(model).__name__} does not expose a ResNet-style conv1" 

659 # ) 

660 # old_conv = model.conv1 

661 # if not isinstance(old_conv, torch.nn.Conv2d): 

662 # raise ValueError( 

663 # f"Expected model.conv1 to be Conv2d, got {type(old_conv).__name__}" 

664 # ) 

665 # --- 

666 # KT addition to allow for convnext models 

667 # Locate the model's first convolution. 

668 if hasattr(model, "conv1"): 

669 # ResNet-style models 

670 old_conv = model.conv1 

671 conv_location = "conv1" 

672 

673 elif ( 

674 hasattr(model, "features") 

675 and len(model.features) > 0 

676 and isinstance(model.features[0][0], torch.nn.Conv2d) 

677 ): 

678 # TorchVision ConvNeXt-style models 

679 old_conv = model.features[0][0] 

680 conv_location = "convnext" 

681 

682 else: 

683 raise ValueError( 

684 f"Could not find first Conv2d for model type " f"{type(model).__name__}" 

685 ) 

686 

687 if not isinstance(old_conv, torch.nn.Conv2d): 

688 raise ValueError( 

689 f"Expected first layer to be Conv2d, " f"got {type(old_conv).__name__}" 

690 ) 

691 # end KT addition 

692 

693 if old_conv.in_channels == input_channels: 

694 return 

695 

696 if old_conv.in_channels != 3: 

697 raise ValueError( 

698 f"Expected source model to have 3 input channels, " 

699 f"got {old_conv.in_channels}" 

700 ) 

701 

702 if old_conv.groups != 1: 

703 raise ValueError( 

704 f"Cannot adapt grouped conv1 with groups={old_conv.groups}; expected 1" 

705 # KT add 

706 f"groups={old_conv.groups}; expected 1" 

707 ) 

708 

709 if input_channels % 3 != 0: 

710 raise ValueError( 

711 f"Cannot adapt RGB pretrained weights to " 

712 f"{input_channels} channels: channel count must be " 

713 f"divisible by 3." 

714 ) 

715 

716 num_views = input_channels // 3 

717 # KT additional 

718 logger.info( 

719 "Adapting first convolution: %d -> %d input channels (%d RGB stacks)", 

720 old_conv.in_channels, 

721 input_channels, 

722 num_views, 

723 ) 

724 # end KT additional 

725 

726 new_conv = torch.nn.Conv2d( 

727 in_channels=input_channels, 

728 out_channels=old_conv.out_channels, 

729 kernel_size=old_conv.kernel_size, 

730 stride=old_conv.stride, 

731 padding=old_conv.padding, 

732 dilation=old_conv.dilation, 

733 groups=old_conv.groups, 

734 bias=old_conv.bias is not None, 

735 padding_mode=old_conv.padding_mode, 

736 ).to( 

737 device=old_conv.weight.device, 

738 dtype=old_conv.weight.dtype, 

739 ) 

740 

741 with torch.no_grad(): 

742 new_conv.weight.copy_(old_conv.weight.repeat(1, num_views, 1, 1) / num_views) 

743 

744 if old_conv.bias is not None: 

745 new_conv.bias.copy_(old_conv.bias) 

746 

747 # original RT coding 

748 # model.conv1 = new_conv 

749 # --- 

750 # KT addition 

751 # Put the adapted convolution back into the model. 

752 if conv_location == "conv1": 

753 model.conv1 = new_conv 

754 else: 

755 model.features[0][0] = new_conv 

756 # end KT addition