File size: 16,519 Bytes
2eed5eb 200cb5d 2eed5eb e115a15 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 2810b72 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 2810b72 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 2810b72 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb 200cb5d 2eed5eb |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# src/ds_proc.py
# ============================================================
# ImageProcessor (AutoImageProcessor integration)
# ImageProcessor (AutoImageProcessor ์ฐ๋)
# ============================================================
from typing import Any
import numpy as np
import torch
from transformers import AutoImageProcessor, AutoConfig
from transformers.image_processing_base import ImageProcessingMixin
from transformers.utils.generic import TensorType
try:
# Hub/Colab: dynamic module ๋ก๋ฉ์์๋ ์๋ import๊ฐ ์ ์
from .ds_cfg import BackboneID, BACKBONE_META
except ImportError:
# ๋ก์ปฌ: python script.py ๋๋ top-level import์์๋ ์ ๋ import๋ก fallback
from ds_cfg import BackboneID, BACKBONE_META
class BackboneMLPHead224ImageProcessor(ImageProcessingMixin):
"""
This processor performs image preprocessing and outputs {"pixel_values": ...}.
์ด processor๋ ์ด๋ฏธ์ง ์ ์ฒ๋ฆฌ๋ฅผ ์ํํ๊ณ {"pixel_values": ...}๋ฅผ ๋ฐํํจ.
Key requirements:
ํต์ฌ ์๊ตฌ์ฌํญ:
1) save_pretrained() must produce a JSON-serializable preprocessor_config.json.
save_pretrained()๋ JSON ์ง๋ ฌํ ๊ฐ๋ฅํ preprocessor_config.json์ ์์ฑํด์ผ ํจ.
2) Runtime-only objects (delegate processor, timm/torchvision transforms) must NOT be serialized.
๋ฐํ์ ๊ฐ์ฒด(delegate processor, timm/torchvision transform)๋ ์ ๋ ์ง๋ ฌํํ๋ฉด ์ ๋จ.
3) Runtime objects are rebuilt at init/load time based on backbone meta.
๋ฐํ์ ๊ฐ์ฒด๋ backbone meta์ ๋ฐ๋ผ init/load ์์ ์ ์ฌ๊ตฌ์ฑ.
4) For reproducibility, use_fast must be explicitly persisted and honored on load.
์ฌํ์ฑ์ ์ํด use_fast๋ ๋ช
์์ ์ผ๋ก ์ ์ฅ๋๊ณ , ๋ก๋์ ๋ฐ๋์ ๋ฐ์๋์ด์ผ ํจ.
"""
# HF vision models conventionally expect "pixel_values" as the primary input key.
# HF vision ๋ชจ๋ธ์ ๊ด๋ก์ ์ผ๋ก ์
๋ ฅ ํค๋ก "pixel_values"๋ฅผ ๊ธฐ๋.
model_input_names = ["pixel_values"]
def __init__(
self,
backbone_name_or_path: BackboneID,
is_training: bool = False, # timm ์์ data augmentation ์ฉ.
use_fast: bool = False,
**kwargs,
):
# ImageProcessingMixin stores extra kwargs and manages auto_map metadata.
# ImageProcessingMixin์ ์ถ๊ฐ kwargs๋ฅผ ์ ์ฅํ๊ณ auto_map ๋ฉํ๋ฅผ ๊ด๋ฆฌ.
super().__init__(**kwargs)
# Enforce whitelist via BACKBONE_META to keep behavior stable.
# ๋์ ์์ ์ฑ์ ์ํด BACKBONE_META ๊ธฐ๋ฐ ํ์ดํธ๋ฆฌ์คํธ๋ฅผ ๊ฐ์ . - fast fail
if backbone_name_or_path not in BACKBONE_META:
raise ValueError(
f"Unsupported backbone_name_or_path={backbone_name_or_path}. "
f"Allowed: {sorted(BACKBONE_META.keys())}"
)
# Serializable fields only: these should appear in preprocessor_config.json.
# ์ง๋ ฌํ ๊ฐ๋ฅํ ํ๋๋ง: ์ด ๊ฐ๋ค๋ง preprocessor_config.json์ ๋ค์ด๊ฐ์ผ ํจ
self.backbone_name_or_path = backbone_name_or_path
self.is_training = bool(is_training)
# Reproducibility switch for transformers processors.
# transformers processor์ fast/slow ์ ํ์ ์ฌํ ๊ฐ๋ฅํ๊ฒ ๊ณ ์ .
self.use_fast = bool(use_fast)
# Runtime-only fields: must never be serialized.
# ๋ฐํ์ ์ ์ฉ ํ๋: ์ ๋ ์ง๋ ฌํ๋๋ฉด ์ ๋จ.
self._meta = None
self._delegate = None
self._timm_transform = None
self._torchvision_transform = None
# Build runtime objects according to backbone type.
# backbone type์ ๋ฐ๋ผ ๋ฐํ์ ๊ฐ์ฒด๋ฅผ ๊ตฌ์ฑ.
self._build_runtime()
# ============================================================
# Runtime builders
# ๋ฐํ์ ๋น๋
# ============================================================
def _build_runtime(self):
"""
Build runtime delegate/transform based on BACKBONE_META["type"].
BACKBONE_META["type"]์ ๋ฐ๋ผ ๋ฐํ์ delegate/transform์ ๊ตฌ์ฑ.
"""
meta = BACKBONE_META[self.backbone_name_or_path]
self._meta = meta
# Always reset runtime fields before rebuilding.
# ์ฌ๊ตฌ์ฑ ์ ๋ฐํ์ ํ๋๋ ํญ์ ์ด๊ธฐํ.
self._delegate = None
self._timm_transform = None
self._torchvision_transform = None
t = meta["type"]
if t == "timm_densenet":
# timm DenseNet uses timm.data transforms for ImageNet-style preprocessing.
# timm DenseNet์ ImageNet ์ ์ฒ๋ฆฌ๋ฅผ ์ํด timm.data transform์ ์ฌ์ฉ.
self._timm_transform = self._build_timm_transform(
backbone_id=self.backbone_name_or_path,
is_training=self.is_training,
)
return
if t == "torchvision_densenet":
# torchvision DenseNet requires torchvision-style preprocessing (resize/crop/tensor/normalize).
# torchvision DenseNet์ torchvision ์คํ์ผ ์ ์ฒ๋ฆฌ(resize/crop/tensor/normalize)๊ฐ ํ์.
self._torchvision_transform = self._build_torchvision_densenet_transform(
is_training=self.is_training
)
return
# Default: transformers backbone delegates to its official AutoImageProcessor.
# ๊ธฐ๋ณธ: transformers ๋ฐฑ๋ณธ์ ๊ณต์ AutoImageProcessor์ ์์.
#
# IMPORTANT:
# - use_fast๋ transformers ๊ธฐ๋ณธ๊ฐ ๋ณ๊ฒฝ์ ํ๋ค๋ฆฌ์ง ์๋๋ก ๋ฐ๋์ ๋ช
์์ ์ผ๋ก ์ ๋ฌ.
self._delegate = AutoImageProcessor.from_pretrained(
self.backbone_name_or_path,
use_fast=self.use_fast,
# trust_remote_code = True,
)
@staticmethod
def _build_timm_transform(*, backbone_id: str, is_training: bool):
"""
Create timm transform without storing non-serializable objects in config.
๋น์ง๋ ฌํ ๊ฐ์ฒด๋ฅผ config์ ์ ์ฅํ์ง ์๊ณ timm transform์ ์์ฑ.
"""
try:
import timm
from timm.data import resolve_model_data_config, create_transform
except Exception as e:
raise ImportError(
"timm backbone processor requires `timm`. Install: pip install timm"
) from e
# We only need model metadata to resolve data config, so pretrained=False is preferred.
# data config ์ถ์ถ๋ง ํ์ํ๋ฏ๋ก pretrained=False๋ฅผ ์ฐ์ ์ฌ์ฉ.
m = timm.create_model(f"hf_hub:{backbone_id}", pretrained=False, num_classes=0)
dc = resolve_model_data_config(m)
# create_transform returns a torchvision-like callable that maps PIL -> torch.Tensor(C,H,W).
# create_transform์ PIL -> torch.Tensor(C,H,W)๋ก ๋งคํํ๋ callable์ ๋ฐํ.
tfm = create_transform(**dc, is_training=is_training) # is_training :Data Aug.
return tfm
@staticmethod
def _build_torchvision_densenet_transform(*, is_training: bool):
"""
Build torchvision preprocessing for DenseNet-121 (224 pipeline).
DenseNet-121์ฉ torchvision ์ ์ฒ๋ฆฌ(224 ํ์ดํ๋ผ์ธ)๋ฅผ ๊ตฌ์ฑ.
"""
try:
from torchvision import transforms
except Exception as e:
raise ImportError(
"torchvision DenseNet processor requires `torchvision`. Install: pip install torchvision"
) from e
# These are the standard ImageNet normalization stats used by torchvision weights.
# ์ด ๊ฐ๋ค์ torchvision weights๊ฐ ์ฌ์ฉํ๋ ํ์ค ImageNet ์ ๊ทํ ํต๊ณ.
mean = (0.485, 0.456, 0.406)
std = (0.229, 0.224, 0.225)
# Training pipeline typically uses RandomResizedCrop and horizontal flip.
# ํ์ต ํ์ดํ๋ผ์ธ์ ๋ณดํต RandomResizedCrop๊ณผ ์ข์ฐ๋ฐ์ ์ ์ฌ์ฉ.
if is_training:
return transforms.Compose(
[
# transforms.RandomResizedCrop(224),
# transforms.RandomHorizontalFlip(p=0.5),
transforms.Resize(224),
transforms.ToTensor(),
transforms.Normalize(mean=mean, std=std),
]
)
# Inference pipeline typically uses Resize(256) + CenterCrop(224).
# ์ถ๋ก ํ์ดํ๋ผ์ธ์ ๋ณดํต Resize(256) + CenterCrop(224)๋ฅผ ์ฌ์ฉ.
return transforms.Compose(
[
transforms.Resize(256),
# transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=mean, std=std),
]
)
# ============================================================
# Serialization
# ์ง๋ ฌํ
# ============================================================
def to_dict(self) -> dict[str, Any]:
"""
Return a JSON-serializable dict for preprocessor_config.json.
preprocessor_config.json์ ๋ค์ด๊ฐ JSON ์ง๋ ฌํ dict๋ฅผ ๋ฐํ.
Important: do not leak runtime objects into the serialized dict.
์ค์: ๋ฐํ์ ๊ฐ์ฒด๊ฐ ์ง๋ ฌํ dict์ ์์ด๋ฉด ์ ๋จ.
"""
# ImageProcessingMixin.to_dict() adds metadata such as image_processor_type/auto_map.
# ImageProcessingMixin.to_dict()๋ image_processor_type/auto_map ๊ฐ์ ๋ฉํ๋ฅผ ์ถ๊ฐํฉ๋๋ค.
d = super().to_dict()
# Force minimal stable fields for long-term compatibility.
# ์ฅ๊ธฐ ํธํ์ ์ํด ์ต์ ์์ ํ๋๋ฅผ ๊ฐ์ ๋ก ์ง์ .
d["image_processor_type"] = self.__class__.__name__
d["backbone_name_or_path"] = self.backbone_name_or_path
d["is_training"] = self.is_training
d["use_fast"] = self.use_fast
# Remove any runtime-only fields defensively.
# ๋ฐํ์ ์ ์ฉ ํ๋๋ ๋ณด์์ ์ผ๋ก ์ ๊ฑฐ.
for key in ["_meta", "_delegate", "_timm_transform", "_torchvision_transform"]:
d.pop(key, None)
return d
@classmethod
def from_dict(cls, image_processor_dict: dict[str, Any], **kwargs):
"""
Standard load path used by BaseImageProcessor / AutoImageProcessor.
BaseImageProcessor / AutoImageProcessor๊ฐ ์ฌ์ฉํ๋ ํ์ค ๋ก๋ ๊ฒฝ๋ก์.
"""
backbone = image_processor_dict.get("backbone_name_or_path", None)
if backbone is None:
raise ValueError("preprocessor_config.json missing key: backbone_name_or_path")
is_training = bool(image_processor_dict.get("is_training", False))
use_fast = bool(image_processor_dict.get("use_fast", False))
return cls(
backbone_name_or_path=backbone,
is_training=is_training,
use_fast=use_fast,
**kwargs,
)
@classmethod
def from_pretrained(cls, pretrained_model_name_or_path: str, **kwargs):
"""
Fallback path if AutoImageProcessor calls class.from_pretrained directly.
AutoImageProcessor๊ฐ class.from_pretrained๋ฅผ ์ง์ ํธ์ถํ๋ ๊ฒฝ์ฐ๋ฅผ ๋๋นํ ๋ฉ์๋.
Strategy:
์ ๋ต:
- Read config.json via AutoConfig and recover backbone_name_or_path.
AutoConfig๋ก config.json์ ์ฝ๊ณ backbone_name_or_path๋ฅผ ๋ณต๊ตฌ.
"""
# is_training is runtime-only and should default to False for inference/serving.
# is_training์ ๋ฐํ์ ์ ์ฉ์ด๋ฉฐ ์ถ๋ก /์๋น ๊ธฐ๋ณธ๊ฐ์ False ์.
#
# IMPORTANT:
# - use_fast๋ kwargs๋ก ์ ๋ฌ๋ ์ ์์ผ๋ฏ๋ก, ์์ผ๋ฉด ๋ฐ์.
use_fast = bool(kwargs.pop("use_fast", False))
kwargs.pop("trust_remote_code", None)
cfg = AutoConfig.from_pretrained(
pretrained_model_name_or_path,
trust_remote_code =True,
**kwargs)
backbone = getattr(cfg, "backbone_name_or_path", None)
if backbone is None:
raise ValueError("Cannot build processor: backbone_name_or_path not found in config.json")
return cls(backbone_name_or_path=backbone, is_training=False, use_fast=use_fast)
# ============================================================
# Call interface
# ํธ์ถ ์ธํฐํ์ด์ค
# ============================================================
@staticmethod
def _ensure_list(images: Any) -> list[Any]:
# Normalize scalar image input to a list for uniform processing.
# ๋จ์ผ ์
๋ ฅ์ ๋ฆฌ์คํธ๋ก ์ ๊ทํํ์ฌ ๋์ผํ ์ฒ๋ฆฌ ๊ฒฝ๋ก๋ฅผ ์ฌ์ฉ.
if isinstance(images, (list, tuple)):
return list(images)
return [images]
@staticmethod
def _to_pil_rgb(x: Any):
# Convert common image inputs into PIL RGB images.
# ์ผ๋ฐ์ ์ธ ์
๋ ฅ์ PIL RGB ์ด๋ฏธ์ง๋ก ๋ณํ.
from PIL import Image as PILImage
if isinstance(x, PILImage.Image):
return x.convert("RGB")
if isinstance(x, np.ndarray) and x.ndim == 3:
return PILImage.fromarray(x).convert("RGB")
raise TypeError(f"Unsupported image type: {type(x)}")
def __call__(
self,
images: Any | list[Any],
return_tensors: str | TensorType | None = "pt",
**kwargs,
) -> dict[str, Any]:
"""
Convert images into {"pixel_values": Tensor/ndarray}.
์ด๋ฏธ์ง๋ฅผ {"pixel_values": Tensor/ndarray}๋ก ๋ณํ.
"""
images = self._ensure_list(images)
# Rebuild runtime if needed (e.g., right after deserialization).
# ์ง๋ ฌํ ๋ณต์ ์งํ ๋ฑ ๋ฐํ์์ด ๋น์ด์์ ์ ์์ผ๋ฏ๋ก ์ฌ๊ตฌ์ฑ.
if (self._delegate is None) and (self._timm_transform is None) and (self._torchvision_transform is None):
self._build_runtime()
# timm path: PIL -> torch.Tensor(C,H,W) normalized float32.
# timm ๊ฒฝ๋ก: PIL -> torch.Tensor(C,H,W) ์ ๊ทํ float32.
if self._timm_transform is not None:
pv: list[torch.Tensor] = []
for im in images:
pil = self._to_pil_rgb(im)
t = self._timm_transform(pil)
if not isinstance(t, torch.Tensor):
raise RuntimeError("Unexpected timm transform output (expected torch.Tensor).")
pv.append(t)
pixel_values = torch.stack(pv, dim=0) # (B,C,H,W)
return self._format_return(pixel_values, return_tensors)
# torchvision path: PIL -> torch.Tensor(C,H,W) normalized float32.
# torchvision ๊ฒฝ๋ก: PIL -> torch.Tensor(C,H,W) ์ ๊ทํ float32.
if self._torchvision_transform is not None:
pv: list[torch.Tensor] = []
for im in images:
pil = self._to_pil_rgb(im)
t = self._torchvision_transform(pil)
if not isinstance(t, torch.Tensor):
raise RuntimeError("Unexpected torchvision transform output (expected torch.Tensor).")
pv.append(t)
pixel_values = torch.stack(pv, dim=0) # (B,C,H,W)
return self._format_return(pixel_values, return_tensors)
# transformers delegate path: rely on official processor behavior.
# transformers ์์ ๊ฒฝ๋ก: ๊ณต์ processor ๋์์ ๊ทธ๋๋ก ์ฌ์ฉ.
if self._delegate is None:
raise RuntimeError("Processor runtime not built: delegate is None and no transforms are available.")
return self._delegate(images, return_tensors=return_tensors, **kwargs)
@staticmethod
def _format_return(pixel_values: torch.Tensor, return_tensors: str | TensorType | None) -> dict[str, Any]:
"""
Format pixel_values according to return_tensors.
return_tensors์ ๋ง์ถฐ pixel_values ๋ฐํ ํฌ๋งท์ ๋ณํ.
"""
if return_tensors is None or return_tensors in ("pt", TensorType.PYTORCH):
return {"pixel_values": pixel_values}
if return_tensors in ("np", TensorType.NUMPY):
return {"pixel_values": pixel_values.detach().cpu().numpy()}
raise ValueError(f"Unsupported return_tensors={return_tensors}. Use 'pt' or 'np'.")
# Register this processor for AutoImageProcessor resolution.
# AutoImageProcessor ํด์์ ์ํด ์ด processor๋ฅผ ๋ฑ๋ก.
if __name__ != "__main__":
BackboneMLPHead224ImageProcessor.register_for_auto_class("AutoImageProcessor")
|