processing_auto.py 20 KB

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