processing_auto.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. # Copyright 2021 The HuggingFace Inc. team.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """AutoProcessor class."""
  15. import importlib
  16. import json
  17. from collections import OrderedDict
  18. from typing import TYPE_CHECKING
  19. # Build the list of all feature extractors
  20. from ...configuration_utils import PreTrainedConfig
  21. from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
  22. from ...feature_extraction_utils import FeatureExtractionMixin
  23. from ...image_processing_utils import ImageProcessingMixin
  24. from ...processing_utils import ProcessorMixin
  25. from ...tokenization_python import TOKENIZER_CONFIG_FILE
  26. from ...utils import FEATURE_EXTRACTOR_NAME, PROCESSOR_NAME, VIDEO_PROCESSOR_NAME, cached_file, logging
  27. from ...video_processing_utils import BaseVideoProcessor
  28. from .auto_factory import _LazyAutoMapping
  29. from .configuration_auto import (
  30. CONFIG_MAPPING_NAMES,
  31. AutoConfig,
  32. model_type_to_module_name,
  33. replace_list_option_in_docstrings,
  34. )
  35. from .feature_extraction_auto import AutoFeatureExtractor
  36. from .image_processing_auto import AutoImageProcessor
  37. from .tokenization_auto import AutoTokenizer
  38. from .video_processing_auto import AutoVideoProcessor
  39. logger = logging.get_logger(__name__)
  40. if TYPE_CHECKING:
  41. # This significantly improves completion suggestion performance when
  42. # the transformers package is used with Microsoft's Pylance language server.
  43. PROCESSOR_MAPPING_NAMES: OrderedDict[str, str | None] = OrderedDict()
  44. else:
  45. PROCESSOR_MAPPING_NAMES = OrderedDict(
  46. [
  47. ("aimv2", "CLIPProcessor"),
  48. ("align", "AlignProcessor"),
  49. ("altclip", "AltCLIPProcessor"),
  50. ("aria", "AriaProcessor"),
  51. ("audioflamingo3", "AudioFlamingo3Processor"),
  52. ("aya_vision", "AyaVisionProcessor"),
  53. ("bark", "BarkProcessor"),
  54. ("blip", "BlipProcessor"),
  55. ("blip-2", "Blip2Processor"),
  56. ("bridgetower", "BridgeTowerProcessor"),
  57. ("chameleon", "ChameleonProcessor"),
  58. ("chinese_clip", "ChineseCLIPProcessor"),
  59. ("clap", "ClapProcessor"),
  60. ("clip", "CLIPProcessor"),
  61. ("clipseg", "CLIPSegProcessor"),
  62. ("clvp", "ClvpProcessor"),
  63. ("cohere2_vision", "Cohere2VisionProcessor"),
  64. ("cohere_asr", "CohereAsrProcessor"),
  65. ("colmodernvbert", "ColModernVBertProcessor"),
  66. ("colpali", "ColPaliProcessor"),
  67. ("colqwen2", "ColQwen2Processor"),
  68. ("deepseek_vl", "DeepseekVLProcessor"),
  69. ("deepseek_vl_hybrid", "DeepseekVLHybridProcessor"),
  70. ("dia", "DiaProcessor"),
  71. ("edgetam", "Sam2Processor"),
  72. ("emu3", "Emu3Processor"),
  73. ("ernie4_5_vl_moe", "Ernie4_5_VLMoeProcessor"),
  74. ("evolla", "EvollaProcessor"),
  75. ("flava", "FlavaProcessor"),
  76. ("florence2", "Florence2Processor"),
  77. ("fuyu", "FuyuProcessor"),
  78. ("gemma3", "Gemma3Processor"),
  79. ("gemma3n", "Gemma3nProcessor"),
  80. ("gemma4", "Gemma4Processor"),
  81. ("git", "GitProcessor"),
  82. ("glm46v", "Glm46VProcessor"),
  83. ("glm4v", "Glm4vProcessor"),
  84. ("glm4v_moe", "Glm4vProcessor"),
  85. ("glm_image", "Glm4vProcessor"),
  86. ("glmasr", "GlmAsrProcessor"),
  87. ("got_ocr2", "GotOcr2Processor"),
  88. ("granite_speech", "GraniteSpeechProcessor"),
  89. ("grounding-dino", "GroundingDinoProcessor"),
  90. ("groupvit", "CLIPProcessor"),
  91. ("higgs_audio_v2", "HiggsAudioV2Processor"),
  92. ("hubert", "Wav2Vec2Processor"),
  93. ("idefics", "IdeficsProcessor"),
  94. ("idefics2", "Idefics2Processor"),
  95. ("idefics3", "Idefics3Processor"),
  96. ("instructblip", "InstructBlipProcessor"),
  97. ("instructblipvideo", "InstructBlipVideoProcessor"),
  98. ("internvl", "InternVLProcessor"),
  99. ("janus", "JanusProcessor"),
  100. ("kosmos-2", "Kosmos2Processor"),
  101. ("kosmos-2.5", "Kosmos2_5Processor"),
  102. ("kyutai_speech_to_text", "KyutaiSpeechToTextProcessor"),
  103. ("lasr_ctc", "LasrProcessor"),
  104. ("lasr_encoder", "LasrProcessor"),
  105. ("layoutlmv2", "LayoutLMv2Processor"),
  106. ("layoutlmv3", "LayoutLMv3Processor"),
  107. ("layoutxlm", "LayoutXLMProcessor"),
  108. ("lfm2_vl", "Lfm2VlProcessor"),
  109. ("lighton_ocr", "LightOnOcrProcessor"),
  110. ("llama4", "Llama4Processor"),
  111. ("llava", "LlavaProcessor"),
  112. ("llava_next", "LlavaNextProcessor"),
  113. ("llava_next_video", "LlavaNextVideoProcessor"),
  114. ("llava_onevision", "LlavaOnevisionProcessor"),
  115. ("markuplm", "MarkupLMProcessor"),
  116. ("metaclip_2", "CLIPProcessor"),
  117. ("mgp-str", "MgpstrProcessor"),
  118. ("mistral3", "PixtralProcessor"),
  119. ("mllama", "MllamaProcessor"),
  120. ("mm-grounding-dino", "GroundingDinoProcessor"),
  121. ("modernvbert", "Idefics3Processor"),
  122. ("moonshine", "Wav2Vec2Processor"),
  123. ("moonshine_streaming", "MoonshineStreamingProcessor"),
  124. ("musicflamingo", "MusicFlamingoProcessor"),
  125. ("omdet-turbo", "OmDetTurboProcessor"),
  126. ("oneformer", "OneFormerProcessor"),
  127. ("ovis2", "Ovis2Processor"),
  128. ("owlv2", "Owlv2Processor"),
  129. ("owlvit", "OwlViTProcessor"),
  130. ("paddleocr_vl", "PaddleOCRVLProcessor"),
  131. ("paligemma", "PaliGemmaProcessor"),
  132. ("perception_lm", "PerceptionLMProcessor"),
  133. ("phi4_multimodal", "Phi4MultimodalProcessor"),
  134. ("pi0", "PI0Processor"),
  135. ("pix2struct", "Pix2StructProcessor"),
  136. ("pixtral", "PixtralProcessor"),
  137. ("pop2piano", "Pop2PianoProcessor"),
  138. ("pp_chart2table", "PPChart2TableProcessor"),
  139. ("qwen2_5_omni", "Qwen2_5OmniProcessor"),
  140. ("qwen2_5_vl", "Qwen2_5_VLProcessor"),
  141. ("qwen2_audio", "Qwen2AudioProcessor"),
  142. ("qwen2_vl", "Qwen2VLProcessor"),
  143. ("qwen3_5", "Qwen3VLProcessor"),
  144. ("qwen3_5_moe", "Qwen3VLProcessor"),
  145. ("qwen3_omni_moe", "Qwen3OmniMoeProcessor"),
  146. ("qwen3_vl", "Qwen3VLProcessor"),
  147. ("qwen3_vl_moe", "Qwen3VLProcessor"),
  148. ("sam", "SamProcessor"),
  149. ("sam2", "Sam2Processor"),
  150. ("sam3", "Sam3Processor"),
  151. ("sam_hq", "SamHQProcessor"),
  152. ("seamless_m4t", "SeamlessM4TProcessor"),
  153. ("sew", "Wav2Vec2Processor"),
  154. ("sew-d", "Wav2Vec2Processor"),
  155. ("shieldgemma2", "ShieldGemma2Processor"),
  156. ("siglip", "SiglipProcessor"),
  157. ("siglip2", "Siglip2Processor"),
  158. ("smolvlm", "SmolVLMProcessor"),
  159. ("speech_to_text", "Speech2TextProcessor"),
  160. ("speecht5", "SpeechT5Processor"),
  161. ("t5gemma2", "Gemma3Processor"),
  162. ("t5gemma2_encoder", "Gemma3Processor"),
  163. ("trocr", "TrOCRProcessor"),
  164. ("tvp", "TvpProcessor"),
  165. ("udop", "UdopProcessor"),
  166. ("unispeech", "Wav2Vec2Processor"),
  167. ("unispeech-sat", "Wav2Vec2Processor"),
  168. ("vibevoice_asr", "VibeVoiceAsrProcessor"),
  169. ("video_llava", "VideoLlavaProcessor"),
  170. ("vilt", "ViltProcessor"),
  171. ("vipllava", "LlavaProcessor"),
  172. ("vision-text-dual-encoder", "VisionTextDualEncoderProcessor"),
  173. ("voxtral", "VoxtralProcessor"),
  174. ("voxtral_realtime", "VoxtralRealtimeProcessor"),
  175. ("wav2vec2", "Wav2Vec2Processor"),
  176. ("wav2vec2-bert", "Wav2Vec2Processor"),
  177. ("wav2vec2-conformer", "Wav2Vec2Processor"),
  178. ("wavlm", "Wav2Vec2Processor"),
  179. ("whisper", "WhisperProcessor"),
  180. ("xclip", "XCLIPProcessor"),
  181. ]
  182. )
  183. PROCESSOR_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, PROCESSOR_MAPPING_NAMES)
  184. def processor_class_from_name(class_name: str):
  185. for module_name, processors in PROCESSOR_MAPPING_NAMES.items():
  186. if class_name in processors:
  187. module_name = model_type_to_module_name(module_name)
  188. module = importlib.import_module(f".{module_name}", "transformers.models")
  189. try:
  190. return getattr(module, class_name)
  191. except AttributeError:
  192. continue
  193. for processor in PROCESSOR_MAPPING._extra_content.values():
  194. if getattr(processor, "__name__", None) == class_name:
  195. return processor
  196. # We did not find the class, but maybe it's because a dep is missing. In that case, the class will be in the main
  197. # init and we return the proper dummy to get an appropriate error message.
  198. main_module = importlib.import_module("transformers")
  199. if hasattr(main_module, class_name):
  200. return getattr(main_module, class_name)
  201. return None
  202. class AutoProcessor:
  203. r"""
  204. This is a generic processor class that will be instantiated as one of the processor classes of the library when
  205. created with the [`AutoProcessor.from_pretrained`] class method.
  206. This class cannot be instantiated directly using `__init__()` (throws an error).
  207. """
  208. def __init__(self):
  209. raise OSError(
  210. "AutoProcessor is designed to be instantiated "
  211. "using the `AutoProcessor.from_pretrained(pretrained_model_name_or_path)` method."
  212. )
  213. @classmethod
  214. @replace_list_option_in_docstrings(PROCESSOR_MAPPING_NAMES)
  215. def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
  216. r"""
  217. Instantiate one of the processor classes of the library from a pretrained model vocabulary.
  218. The processor class to instantiate is selected based on the `model_type` property of the config object (either
  219. passed as an argument or loaded from `pretrained_model_name_or_path` if possible):
  220. List options
  221. Params:
  222. pretrained_model_name_or_path (`str` or `os.PathLike`):
  223. This can be either:
  224. - a string, the *model id* of a pretrained feature_extractor hosted inside a model repo on
  225. huggingface.co.
  226. - a path to a *directory* containing a processor files saved using the `save_pretrained()` method,
  227. e.g., `./my_model_directory/`.
  228. cache_dir (`str` or `os.PathLike`, *optional*):
  229. Path to a directory in which a downloaded pretrained model feature extractor should be cached if the
  230. standard cache should not be used.
  231. force_download (`bool`, *optional*, defaults to `False`):
  232. Whether or not to force to (re-)download the feature extractor files and override the cached versions
  233. if they exist.
  234. proxies (`dict[str, str]`, *optional*):
  235. A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
  236. 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
  237. token (`str` or *bool*, *optional*):
  238. The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
  239. when running `hf auth login` (stored in `~/.huggingface`).
  240. revision (`str`, *optional*, defaults to `"main"`):
  241. The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
  242. git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
  243. identifier allowed by git.
  244. return_unused_kwargs (`bool`, *optional*, defaults to `False`):
  245. If `False`, then this function returns just the final feature extractor object. If `True`, then this
  246. functions returns a `Tuple(feature_extractor, unused_kwargs)` where *unused_kwargs* is a dictionary
  247. consisting of the key/value pairs whose keys are not feature extractor attributes: i.e., the part of
  248. `kwargs` which has not been used to update `feature_extractor` and is otherwise ignored.
  249. trust_remote_code (`bool`, *optional*, defaults to `False`):
  250. Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
  251. should only be set to `True` for repositories you trust and in which you have read the code, as it will
  252. execute code present on the Hub on your local machine.
  253. kwargs (`dict[str, Any]`, *optional*):
  254. The values in kwargs of any keys which are feature extractor attributes will be used to override the
  255. loaded values. Behavior concerning key/value pairs whose keys are *not* feature extractor attributes is
  256. controlled by the `return_unused_kwargs` keyword parameter.
  257. <Tip>
  258. Passing `token=True` is required when you want to use a private model.
  259. </Tip>
  260. Examples:
  261. ```python
  262. >>> from transformers import AutoProcessor
  263. >>> # Download processor from huggingface.co and cache.
  264. >>> processor = AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h")
  265. >>> # If processor files are in a directory (e.g. processor was saved using *save_pretrained('./test/saved_model/')*)
  266. >>> # processor = AutoProcessor.from_pretrained("./test/saved_model/")
  267. ```"""
  268. config = kwargs.pop("config", None)
  269. trust_remote_code = kwargs.pop("trust_remote_code", None)
  270. kwargs["_from_auto"] = True
  271. processor_class = None
  272. processor_auto_map = None
  273. # First, let's see if we have a processor or preprocessor config.
  274. # Filter the kwargs for `cached_file`.
  275. _hub_valid_kwargs = (
  276. "cache_dir",
  277. "force_download",
  278. "proxies",
  279. "token",
  280. "revision",
  281. "local_files_only",
  282. "subfolder",
  283. "repo_type",
  284. "user_agent",
  285. )
  286. cached_file_kwargs = {key: kwargs[key] for key in _hub_valid_kwargs if key in kwargs}
  287. # We don't want to raise
  288. cached_file_kwargs.update(
  289. {
  290. "_raise_exceptions_for_gated_repo": False,
  291. "_raise_exceptions_for_missing_entries": False,
  292. "_raise_exceptions_for_connection_errors": False,
  293. }
  294. )
  295. # Let's start by checking whether the processor class is saved in a processor config
  296. processor_config_file = cached_file(pretrained_model_name_or_path, PROCESSOR_NAME, **cached_file_kwargs)
  297. if processor_config_file is not None:
  298. config_dict, _ = ProcessorMixin.get_processor_dict(pretrained_model_name_or_path, **kwargs)
  299. processor_class = config_dict.get("processor_class")
  300. if "AutoProcessor" in config_dict.get("auto_map", {}):
  301. processor_auto_map = config_dict["auto_map"]["AutoProcessor"]
  302. if processor_class is None:
  303. # If not found, let's check whether the processor class is saved in an image processor config
  304. preprocessor_config_file = cached_file(
  305. pretrained_model_name_or_path, FEATURE_EXTRACTOR_NAME, **cached_file_kwargs
  306. )
  307. if preprocessor_config_file is not None:
  308. config_dict, _ = ImageProcessingMixin.get_image_processor_dict(pretrained_model_name_or_path, **kwargs)
  309. processor_class = config_dict.get("processor_class", None)
  310. if "AutoProcessor" in config_dict.get("auto_map", {}):
  311. processor_auto_map = config_dict["auto_map"]["AutoProcessor"]
  312. # Saved as video processor
  313. if preprocessor_config_file is None:
  314. preprocessor_config_file = cached_file(
  315. pretrained_model_name_or_path, VIDEO_PROCESSOR_NAME, **cached_file_kwargs
  316. )
  317. if preprocessor_config_file is not None:
  318. config_dict, _ = BaseVideoProcessor.get_video_processor_dict(
  319. pretrained_model_name_or_path, **kwargs
  320. )
  321. processor_class = config_dict.get("processor_class", None)
  322. if "AutoProcessor" in config_dict.get("auto_map", {}):
  323. processor_auto_map = config_dict["auto_map"]["AutoProcessor"]
  324. # Saved as feature extractor
  325. if preprocessor_config_file is None:
  326. preprocessor_config_file = cached_file(
  327. pretrained_model_name_or_path, FEATURE_EXTRACTOR_NAME, **cached_file_kwargs
  328. )
  329. if preprocessor_config_file is not None and processor_class is None:
  330. config_dict, _ = FeatureExtractionMixin.get_feature_extractor_dict(
  331. pretrained_model_name_or_path, **kwargs
  332. )
  333. processor_class = config_dict.get("processor_class", None)
  334. if "AutoProcessor" in config_dict.get("auto_map", {}):
  335. processor_auto_map = config_dict["auto_map"]["AutoProcessor"]
  336. if processor_class is None:
  337. # Next, let's check whether the processor class is saved in a tokenizer
  338. tokenizer_config_file = cached_file(
  339. pretrained_model_name_or_path, TOKENIZER_CONFIG_FILE, **cached_file_kwargs
  340. )
  341. if tokenizer_config_file is not None:
  342. with open(tokenizer_config_file, encoding="utf-8") as reader:
  343. config_dict = json.load(reader)
  344. processor_class = config_dict.get("processor_class", None)
  345. if "AutoProcessor" in config_dict.get("auto_map", {}):
  346. processor_auto_map = config_dict["auto_map"]["AutoProcessor"]
  347. if processor_class is None:
  348. # Last resort: try loading the model config to get processor_class.
  349. # This handles cases where processor info is only in config.json (not in any
  350. # preprocessor/tokenizer config files). AutoConfig.from_pretrained may raise
  351. # ValueError if the model_type is unrecognized or the config is invalid -
  352. # we catch and ignore this to allow fallback to AutoTokenizer/AutoImageProcessor.
  353. try:
  354. if not isinstance(config, PreTrainedConfig):
  355. config = AutoConfig.from_pretrained(
  356. pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs
  357. )
  358. processor_class = getattr(config, "processor_class", None)
  359. if hasattr(config, "auto_map") and "AutoProcessor" in config.auto_map:
  360. processor_auto_map = config.auto_map["AutoProcessor"]
  361. except ValueError:
  362. # Config loading failed (unrecognized model_type, invalid config, etc.)
  363. # Continue to fallback logic below (AutoTokenizer, AutoImageProcessor, etc.)
  364. pass
  365. if processor_class is not None:
  366. processor_class = processor_class_from_name(processor_class)
  367. has_remote_code = processor_auto_map is not None
  368. has_local_code = processor_class is not None or type(config) in PROCESSOR_MAPPING
  369. explicit_local_code = has_local_code and not (
  370. processor_class or PROCESSOR_MAPPING[type(config)]
  371. ).__module__.startswith("transformers.")
  372. if has_remote_code:
  373. if "--" in processor_auto_map:
  374. upstream_repo = processor_auto_map.split("--")[0]
  375. else:
  376. upstream_repo = None
  377. trust_remote_code = resolve_trust_remote_code(
  378. trust_remote_code, pretrained_model_name_or_path, has_local_code, has_remote_code, upstream_repo
  379. )
  380. if has_remote_code and trust_remote_code and not explicit_local_code:
  381. processor_class = get_class_from_dynamic_module(
  382. processor_auto_map, pretrained_model_name_or_path, **kwargs
  383. )
  384. _ = kwargs.pop("code_revision", None)
  385. processor_class.register_for_auto_class()
  386. return processor_class.from_pretrained(
  387. pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs
  388. )
  389. elif processor_class is not None:
  390. return processor_class.from_pretrained(
  391. pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs
  392. )
  393. # Last try: we use the PROCESSOR_MAPPING.
  394. elif type(config) in PROCESSOR_MAPPING:
  395. return PROCESSOR_MAPPING[type(config)].from_pretrained(pretrained_model_name_or_path, **kwargs)
  396. # At this stage, there doesn't seem to be a `Processor` class available for this model.
  397. # Let's try the commonly available classes
  398. for klass in (AutoTokenizer, AutoImageProcessor, AutoVideoProcessor, AutoFeatureExtractor):
  399. try:
  400. return klass.from_pretrained(
  401. pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs
  402. )
  403. except Exception:
  404. continue
  405. raise ValueError(
  406. f"Unrecognized processing class in {pretrained_model_name_or_path}. Can't instantiate a processor, a "
  407. "tokenizer, an image processor, a video processor or a feature extractor for this model. "
  408. "Make sure the repository contains the files of at least one of those processing classes."
  409. )
  410. @staticmethod
  411. def register(config_class, processor_class, exist_ok=False):
  412. """
  413. Register a new processor for this class.
  414. Args:
  415. config_class ([`PreTrainedConfig`]):
  416. The configuration corresponding to the model to register.
  417. processor_class ([`ProcessorMixin`]): The processor to register.
  418. """
  419. PROCESSOR_MAPPING.register(config_class, processor_class, exist_ok=exist_ok)
  420. __all__ = ["PROCESSOR_MAPPING", "AutoProcessor"]