Coverage for collectra/tasks/image_classifier/huggingface.py: 94.71%
170 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"""Transformers image classifiers with portable Collectra checkpoints."""
3from __future__ import annotations
5import copy
6import json
7import tempfile
8from typing import Annotated, Any
9from pydantic import BaseModel, ConfigDict
11from collectra.commons import PositionalFields
12from pathlib import Path
14from cappa import Arg
16from collectra.cli import command
17from collectra.types.images import Image
18from collectra.types.links import Link
19from collectra.utils import threading_locked
20from ..machine_learning.training import run_training_command
21from .training import (
22 ClassificationTrainResult,
23 TorchClassifierTask,
24 prepare_classification_inputs,
25)
27__all__ = ["ImageClassifierHuggingFace"]
30class _ProcessorTransform(PositionalFields, BaseModel):
31 """A picklable per-image transform for DataLoader worker processes."""
33 model_config = ConfigDict(arbitrary_types_allowed=True)
35 processor: Any
36 fliplr: float = 0.0
38 def __call__(self, image):
39 import torch
40 from PIL import ImageOps
42 image = image.convert("RGB")
43 if self.fliplr and torch.rand(()).item() < self.fliplr:
44 image = ImageOps.mirror(image)
45 inputs = self.processor(images=image, return_tensors="pt")
46 return {name: value.squeeze(0) for name, value in inputs.items()}
49def _class_names(config) -> list[str]:
50 return [
51 config.id2label.get(index, config.id2label.get(str(index), str(index)))
52 for index in range(config.num_labels)
53 ]
56def _set_classes(config, classes: list[str]) -> None:
57 config.num_labels = len(classes)
58 config.id2label = dict(enumerate(classes))
59 config.label2id = {name: index for index, name in enumerate(classes)}
60 config.problem_type = "single_label_classification"
63def _head_modules(model):
64 """Identify task-specific layers outside the Transformers base model."""
65 backbone = model.base_model
66 if backbone is model:
67 raise ValueError(
68 f"{type(model).__name__} does not expose a separate classification backbone"
69 )
70 backbone_modules = {id(module) for module in backbone.modules()}
71 return [
72 module
73 for module in model.modules()
74 if module is not model and id(module) not in backbone_modules
75 ]
78def _reset_head(model) -> None:
79 # Also reset when the new labels have the same count but different meanings.
80 reset = False
81 for module in _head_modules(model):
82 if hasattr(module, "reset_parameters"):
83 module.reset_parameters()
84 reset = True
85 if not reset:
86 raise ValueError(
87 f"Cannot reset the classification head of {type(model).__name__}"
88 )
91class ImageClassifierHuggingFace(TorchClassifierTask):
92 """Fine-tune Transformers image classifiers and return predicted class Links."""
94 prepare_training_inputs = staticmethod(prepare_classification_inputs)
96 def __init__(
97 self,
98 name: str,
99 model: str | Path = "google/vit-base-patch16-224-in21k",
100 **kwargs,
101 ):
102 super().__init__(name, model=model, **kwargs)
103 self.original_model_path: Path | None = None
104 self._categories: list[str] = []
105 self._processor = None
106 self._device = "cpu"
108 @staticmethod
109 def _config_from_dict(data):
110 from transformers import AutoConfig
112 data = copy.deepcopy(data)
113 model_type = data.pop("model_type")
114 return AutoConfig.for_model(model_type, **data)
116 def _from_state(self, config, state, classes=None):
117 from transformers import AutoModelForImageClassification
119 changed = classes is not None and classes != _class_names(config)
120 if classes is not None:
121 _set_classes(config, classes)
122 model = AutoModelForImageClassification.from_config(
123 config, trust_remote_code=False
124 )
125 if changed:
126 # Keep the trained backbone, but never reuse output rows for different labels.
127 backbone = model.base_model
128 if backbone is model:
129 raise ValueError(
130 f"Cannot adapt the classification head of {type(model).__name__}"
131 )
132 prefix = next(
133 name for name, module in model.named_modules() if module is backbone
134 )
135 prefix += "."
136 backbone.load_state_dict(
137 {
138 name[len(prefix) :]: value
139 for name, value in state.items()
140 if name.startswith(prefix)
141 }
142 )
143 else:
144 model.load_state_dict(state)
145 return model
147 def _load(
148 self, *, pretrained: bool = True, classes: list[str] | None = None
149 ) -> None:
150 import torch
151 from transformers import (
152 AutoConfig,
153 AutoImageProcessor,
154 AutoModelForImageClassification,
155 )
157 if isinstance(self.model, torch.nn.Module):
158 if classes is not None and classes != self._categories:
159 self.model = self._from_state(
160 copy.deepcopy(self.model.config), self.model.state_dict(), classes
161 )
162 if classes is not None:
163 _set_classes(self.model.config, classes)
164 self._categories = _class_names(self.model.config)
165 self.model.to(self._device).eval()
166 return
167 if not isinstance(self.model, (str, Path)):
168 raise ValueError(
169 "Model must be a Hugging Face model ID, local model directory, or Collectra checkpoint"
170 )
171 path = Path(self.model).expanduser()
172 if path.is_file():
173 checkpoint = torch.load(path, map_location="cpu", weights_only=True)
174 required = {"backend", "config", "processor", "state_dict", "classes"}
175 if (
176 not isinstance(checkpoint, dict)
177 or not required.issubset(checkpoint)
178 or checkpoint["backend"] != "huggingface"
179 ):
180 raise ValueError(
181 "Expected a Collectra Hugging Face checkpoint with model config, processor, classes, and state_dict; a bare weight file is not sufficient"
182 )
183 config = self._config_from_dict(checkpoint["config"])
184 if checkpoint["classes"] != _class_names(config):
185 raise ValueError(
186 "Checkpoint class names do not match its model configuration"
187 )
188 # AutoImageProcessor resolves built-in processor types from its standard JSON file.
189 with tempfile.TemporaryDirectory() as directory:
190 (Path(directory) / "preprocessor_config.json").write_text(
191 json.dumps(checkpoint["processor"])
192 )
193 self._processor = AutoImageProcessor.from_pretrained(
194 directory,
195 local_files_only=True,
196 trust_remote_code=False,
197 )
198 model = self._from_state(config, checkpoint["state_dict"], classes)
199 self.original_model_path = path.resolve()
200 else:
201 if isinstance(self.model, Path) and not path.is_dir():
202 raise ValueError(
203 f"Model directory or checkpoint does not exist: {path}"
204 )
205 if not path.exists() and (
206 str(self.model).startswith(("/", "./", "../", "~"))
207 or path.suffix in {".pt", ".pth", ".bin", ".safetensors"}
208 ):
209 raise ValueError(
210 f"Model directory or checkpoint does not exist: {path}"
211 )
212 source = str(path) if path.is_dir() else str(self.model)
213 config = AutoConfig.from_pretrained(source, trust_remote_code=False)
214 self._processor = AutoImageProcessor.from_pretrained(
215 source, trust_remote_code=False
216 )
217 changed = classes is not None and classes != _class_names(config)
218 if classes is not None:
219 _set_classes(config, classes)
220 # Local checkpoints always retain their learned weights, as with torchvision.
221 if pretrained or path.is_dir():
222 model = AutoModelForImageClassification.from_pretrained(
223 source,
224 config=config,
225 ignore_mismatched_sizes=changed,
226 trust_remote_code=False,
227 )
228 if changed:
229 _reset_head(model)
230 else:
231 model = AutoModelForImageClassification.from_config(
232 config, trust_remote_code=False
233 )
234 self.original_model_path = path.resolve() if path.is_dir() else None
235 self.model = model.to(self._device)
236 self._categories = _class_names(self.model.config)
237 self.model.eval()
239 def _prepare_training_model(self, classes, pretrained, freeze):
240 self._load(pretrained=pretrained, classes=classes)
241 self.model.requires_grad_(True)
242 if freeze:
243 _head_modules(
244 self.model
245 ) # Check that this architecture exposes a separate backbone.
246 self.model.base_model.requires_grad_(False)
247 if not any(
248 parameter.requires_grad for parameter in self.model.parameters()
249 ):
250 raise ValueError(
251 "No trainable classification head remains after freezing the backbone"
252 )
254 def _transforms(self, *, training=False, fliplr=0.0):
255 return _ProcessorTransform(self._processor, fliplr if training else 0.0)
257 def _forward(self, pixels):
258 inputs = {name: tensor.to(self._device) for name, tensor in pixels.items()}
259 return self.model(**inputs).logits
261 @threading_locked()
262 def run(self, *args: Image) -> Link:
263 """Classify one image or crop and link its predicted class to the input."""
264 import torch
266 if len(args) != 1 or not isinstance(args[0], Image):
267 raise ValueError("This task requires a single Image or ImageCrop input")
268 self._device = self._select_device(getattr(self, "device", ""))
269 self._load()
270 image = args[0]
271 with image.pil() as pixels:
272 inputs = {
273 name: tensor.unsqueeze(0)
274 for name, tensor in self._transforms()(pixels).items()
275 }
276 with torch.inference_mode():
277 class_index = self._forward(inputs).argmax(dim=1).item()
278 class_name = self._categories[class_index]
279 outputs = getattr(self, "output", [])
280 outputs = [outputs] if isinstance(outputs, str) else outputs
281 if outputs and class_name not in outputs:
282 raise ValueError(
283 f"Predicted class {class_name!r} is not a configured output: {outputs}"
284 )
285 return Link(name=class_name, target=image)
287 def _checkpoint(self, epoch, metrics):
288 return {
289 "format_version": 1,
290 "backend": "huggingface",
291 "config": json.loads(self.model.config.to_json_string(use_diff=False)),
292 "processor": json.loads(self._processor.to_json_string()),
293 "classes": self._categories,
294 "state_dict": {
295 name: value.detach().cpu()
296 for name, value in self.model.state_dict().items()
297 },
298 "epoch": epoch,
299 "metrics": metrics,
300 }
302 def _train(self, *images: Image, **kwargs) -> ClassificationTrainResult:
303 result = super()._train(*images, **kwargs)
304 directory = result.save_dir / "weights" / "huggingface"
305 self.model.save_pretrained(directory)
306 self._processor.save_pretrained(directory)
307 return result
309 @command
310 def train(
311 self,
312 inputs: Annotated[
313 list[str],
314 Arg(
315 help="Pipeline data files or directories containing classification labels."
316 ),
317 ],
318 model: Annotated[
319 str,
320 Arg(
321 help="Hugging Face model ID (e.g. google/vit-base-patch16-224-in21k), local save_pretrained directory, or Collectra Hugging Face checkpoint. Omit to keep the configured model."
322 ),
323 ] = "",
324 output: Annotated[
325 Path | None,
326 Arg(
327 help="Directory for extracted train/val images, metrics, and checkpoints."
328 ),
329 ] = None,
330 keep_log: Annotated[
331 bool,
332 Arg(
333 help="Keep extracted images and training logs after saving the model to the pipeline."
334 ),
335 ] = True,
336 validation: Annotated[
337 str,
338 Arg(
339 help="Partition value identifying validation images; omit to train without validation."
340 ),
341 ] = "",
342 exclude: Annotated[
343 str, Arg(help="Partition value identifying images to exclude.")
344 ] = "",
345 epochs: Annotated[int, Arg(help="Number of training epochs.")] = 10,
346 batch: Annotated[int, Arg(help="Number of images per training batch.")] = 16,
347 learning_rate: Annotated[
348 float, Arg(help="Initial learning rate for AdamW.")
349 ] = 0.00005,
350 weight_decay: Annotated[
351 float, Arg(help="Weight decay used for regularization.")
352 ] = 0.0001,
353 pretrained: Annotated[
354 bool,
355 Arg(
356 help="Load pretrained Hub weights; local directories and checkpoints always retain their saved weights. Disable to initialize from a Hub model configuration."
357 ),
358 ] = True,
359 freeze_backbone: Annotated[
360 bool,
361 Arg(help="Train the classification head and freeze the model backbone."),
362 ] = False,
363 early_stop: Annotated[
364 int,
365 Arg(
366 help="Stop after this many epochs without validation-loss improvement; 0 disables."
367 ),
368 ] = 10,
369 min_size: Annotated[
370 int,
371 Arg(
372 help="Skip images or crops with either dimension below this pixel threshold; 0 disables."
373 ),
374 ] = 0,
375 fliplr: Annotated[
376 float,
377 Arg(
378 help="Probability of horizontal flipping during training, from 0 to 1."
379 ),
380 ] = 0.5,
381 workers: Annotated[
382 int, Arg(help="Number of data-loading worker processes.")
383 ] = 0,
384 wandb: Annotated[
385 bool,
386 Arg(help="Log training metrics to Weights & Biases."),
387 ] = False,
388 device: Annotated[
389 str,
390 Arg(
391 help="Torch device such as cpu, cuda, cuda:0, or mps; omit for automatic selection."
392 ),
393 ] = "",
394 seed: Annotated[
395 int, Arg(help="Random seed for model initialization and data loading.")
396 ] = 0,
397 ):
398 """Fine-tune a Hugging Face image classifier using its saved image processor."""
399 result = run_training_command(
400 self,
401 inputs,
402 self._train,
403 keep_log=keep_log,
404 output=output,
405 validation=validation,
406 exclude=exclude,
407 prepare_inputs=self.prepare_training_inputs,
408 model=model,
409 epochs=epochs,
410 batch=batch,
411 learning_rate=learning_rate,
412 weight_decay=weight_decay,
413 pretrained=pretrained,
414 freeze_backbone=freeze_backbone,
415 early_stop=early_stop,
416 min_size=min_size,
417 fliplr=fliplr,
418 workers=workers,
419 wandb=wandb,
420 device=device,
421 seed=seed,
422 )
423 if self.pipeline is not None:
424 saved_model = self.pipeline.data[self.name]["model"]
425 self.original_model_path = (self.pipeline.path / saved_model).resolve()
426 return result