Repository: huggingface/transformers
Pull request: protect imports

# What does this PR do?

<!--
Congratulations! You've made it this far! You're not quite done yet though.

Once merged, your PR is going to appear in the release notes with the title you set, so make sure it's a great title that fully reflects the extent of your awesome contribution.

Then, please replace this with a description of the change and which issue is fixed (if applicable). Please also include relevant motivation and context. List any dependencies (if any) that are required for this change.

Once you're done, someone will review your PR shortly (see the section "Who can review?" below to tag some potential reviewers). They may suggest changes to make the code even better. If no one reviewed your PR after a week has passed, don't hesitate to post a new comment @-mentioning the same persons---sometimes notifications get lost.
-->

<!-- Remove if not applicable -->

Fixes # (issue)


## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
- [ ] Did you read the [contributor guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#create-a-pull-request),
      Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the [forum](https://discuss.huggingface.co/)? Please add a link
      to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes? Here are the
      [documentation guidelines](https://github.com/huggingface/transformers/tree/main/docs), and
      [here are tips on formatting docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [ ] Did you write any new necessary tests?


## Who can review?

Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.

<!-- Your PR will be replied to more quickly if you can figure out the right person to tag with @

 If you know how to use git blame, that is the easiest way, otherwise, here is a rough guide of **who to tag**.
 Please tag fewer than 3 people.

Models:

- text models: @ArthurZucker @Cyrilvallez
- vision models: @yonigozlan @molbap
- audio models: @eustlb @ebezzam @vasqu
- multimodal models: @zucchini-nlp
- graph models: @clefourrier

Library:

- generate: @zucchini-nlp (visual-language models) or @gante (all others)
- continuous batching: @remi-or @ArthurZucker @McPatate
- pipelines: @Rocketknight1
- tokenizers: @ArthurZucker and @itazap
- trainer: @SunMarc
- attention: @vasqu @ArthurZucker @CyrilVallez
- model loading (from pretrained, etc): @CyrilVallez
- distributed: @3outeille @ArthurZucker
- CIs: @ydshieh

Integrations:

- ray/raytune: @richardliaw, @amogkam
- Big Model Inference: @SunMarc
- quantization: @SunMarc @MekkCyber
- kernels: @MekkCyber @drbh
- peft: @BenjaminBossan @githubnemo

Devices/Backends:

- AMD ROCm: @ivarflakstad
- Intel XPU: @IlyasMoutawwakil
- Ascend NPU: @ivarflakstad 

Documentation: @stevhliu

Research projects are not maintained and should be taken as is.

 -->


Changed files:
filename: src/transformers/models/auto/processing_auto.py
patch: @@ -17,6 +17,7 @@
 import inspect
 import json
 from collections import OrderedDict
+from typing import TYPE_CHECKING
 
 # Build the list of all feature extractors
 from ...configuration_utils import PreTrainedConfig
@@ -41,140 +42,144 @@
 
 
 logger = logging.get_logger(__name__)
-
-PROCESSOR_MAPPING_NAMES = OrderedDict(
-    [
-        ("aimv2", "CLIPProcessor"),
-        ("align", "AlignProcessor"),
-        ("altclip", "AltCLIPProcessor"),
-        ("aria", "AriaProcessor"),
-        ("audioflamingo3", "AudioFlamingo3Processor"),
-        ("aya_vision", "AyaVisionProcessor"),
-        ("bark", "BarkProcessor"),
-        ("blip", "BlipProcessor"),
-        ("blip-2", "Blip2Processor"),
-        ("bridgetower", "BridgeTowerProcessor"),
-        ("chameleon", "ChameleonProcessor"),
-        ("chinese_clip", "ChineseCLIPProcessor"),
-        ("clap", "ClapProcessor"),
-        ("clip", "CLIPProcessor"),
-        ("clipseg", "CLIPSegProcessor"),
-        ("clvp", "ClvpProcessor"),
-        ("cohere2_vision", "Cohere2VisionProcessor"),
-        ("colmodernvbert", "ColModernVBertProcessor"),
-        ("colpali", "ColPaliProcessor"),
-        ("colqwen2", "ColQwen2Processor"),
-        ("deepseek_vl", "DeepseekVLProcessor"),
-        ("deepseek_vl_hybrid", "DeepseekVLHybridProcessor"),
-        ("dia", "DiaProcessor"),
-        ("edgetam", "Sam2Processor"),
-        ("emu3", "Emu3Processor"),
-        ("ernie4_5_vl_moe", "Ernie4_5_VLMoeProcessor"),
-        ("evolla", "EvollaProcessor"),
-        ("flava", "FlavaProcessor"),
-        ("florence2", "Florence2Processor"),
-        ("fuyu", "FuyuProcessor"),
-        ("gemma3", "Gemma3Processor"),
-        ("gemma3n", "Gemma3nProcessor"),
-        ("git", "GitProcessor"),
-        ("glm46v", "Glm46VProcessor"),
-        ("glm4v", "Glm4vProcessor"),
-        ("glm4v_moe", "Glm4vProcessor"),
-        ("glm_image", "Glm4vProcessor"),
-        ("glmasr", "GlmAsrProcessor"),
-        ("got_ocr2", "GotOcr2Processor"),
-        ("granite_speech", "GraniteSpeechProcessor"),
-        ("grounding-dino", "GroundingDinoProcessor"),
-        ("groupvit", "CLIPProcessor"),
-        ("higgs_audio_v2", "HiggsAudioV2Processor"),
-        ("hubert", "Wav2Vec2Processor"),
-        ("idefics", "IdeficsProcessor"),
-        ("idefics2", "Idefics2Processor"),
-        ("idefics3", "Idefics3Processor"),
-        ("instructblip", "InstructBlipProcessor"),
-        ("instructblipvideo", "InstructBlipVideoProcessor"),
-        ("internvl", "InternVLProcessor"),
-        ("janus", "JanusProcessor"),
-        ("kosmos-2", "Kosmos2Processor"),
-        ("kosmos-2.5", "Kosmos2_5Processor"),
-        ("kyutai_speech_to_text", "KyutaiSpeechToTextProcessor"),
-        ("lasr_ctc", "LasrProcessor"),
-        ("lasr_encoder", "LasrProcessor"),
-        ("layoutlmv2", "LayoutLMv2Processor"),
-        ("layoutlmv3", "LayoutLMv3Processor"),
-        ("layoutxlm", "LayoutXLMProcessor"),
-        ("lfm2_vl", "Lfm2VlProcessor"),
-        ("lighton_ocr", "LightOnOcrProcessor"),
-        ("llama4", "Llama4Processor"),
-        ("llava", "LlavaProcessor"),
-        ("llava_next", "LlavaNextProcessor"),
-        ("llava_next_video", "LlavaNextVideoProcessor"),
-        ("llava_onevision", "LlavaOnevisionProcessor"),
-        ("markuplm", "MarkupLMProcessor"),
-        ("metaclip_2", "CLIPProcessor"),
-        ("mgp-str", "MgpstrProcessor"),
-        ("mistral3", "PixtralProcessor"),
-        ("mllama", "MllamaProcessor"),
-        ("mm-grounding-dino", "GroundingDinoProcessor"),
-        ("modernvbert", "Idefics3Processor"),
-        ("moonshine", "Wav2Vec2Processor"),
-        ("moonshine_streaming", "MoonshineStreamingProcessor"),
-        ("omdet-turbo", "OmDetTurboProcessor"),
-        ("oneformer", "OneFormerProcessor"),
-        ("ovis2", "Ovis2Processor"),
-        ("owlv2", "Owlv2Processor"),
-        ("owlvit", "OwlViTProcessor"),
-        ("paddleocr_vl", "PaddleOCRVLProcessor"),
-        ("paligemma", "PaliGemmaProcessor"),
-        ("perception_lm", "PerceptionLMProcessor"),
-        ("phi4_multimodal", "Phi4MultimodalProcessor"),
-        ("pix2struct", "Pix2StructProcessor"),
-        ("pixtral", "PixtralProcessor"),
-        ("pop2piano", "Pop2PianoProcessor"),
-        ("qwen2_5_omni", "Qwen2_5OmniProcessor"),
-        ("qwen2_5_vl", "Qwen2_5_VLProcessor"),
-        ("qwen2_audio", "Qwen2AudioProcessor"),
-        ("qwen2_vl", "Qwen2VLProcessor"),
-        ("qwen3_5", "Qwen3VLProcessor"),
-        ("qwen3_5_moe", "Qwen3VLProcessor"),
-        ("qwen3_omni_moe", "Qwen3OmniMoeProcessor"),
-        ("qwen3_vl", "Qwen3VLProcessor"),
-        ("qwen3_vl_moe", "Qwen3VLProcessor"),
-        ("sam", "SamProcessor"),
-        ("sam2", "Sam2Processor"),
-        ("sam3", "Sam3Processor"),
-        ("sam_hq", "SamHQProcessor"),
-        ("seamless_m4t", "SeamlessM4TProcessor"),
-        ("sew", "Wav2Vec2Processor"),
-        ("sew-d", "Wav2Vec2Processor"),
-        ("shieldgemma2", "ShieldGemma2Processor"),
-        ("siglip", "SiglipProcessor"),
-        ("siglip2", "Siglip2Processor"),
-        ("smolvlm", "SmolVLMProcessor"),
-        ("speech_to_text", "Speech2TextProcessor"),
-        ("speecht5", "SpeechT5Processor"),
-        ("t5gemma2", "Gemma3Processor"),
-        ("t5gemma2_encoder", "Gemma3Processor"),
-        ("trocr", "TrOCRProcessor"),
-        ("tvp", "TvpProcessor"),
-        ("udop", "UdopProcessor"),
-        ("unispeech", "Wav2Vec2Processor"),
-        ("unispeech-sat", "Wav2Vec2Processor"),
-        ("vibevoice_asr", "VibeVoiceAsrProcessor"),
-        ("video_llava", "VideoLlavaProcessor"),
-        ("vilt", "ViltProcessor"),
-        ("vipllava", "LlavaProcessor"),
-        ("vision-text-dual-encoder", "VisionTextDualEncoderProcessor"),
-        ("voxtral", "VoxtralProcessor"),
-        ("voxtral_realtime", "VoxtralRealtimeProcessor"),
-        ("wav2vec2", "Wav2Vec2Processor"),
-        ("wav2vec2-bert", "Wav2Vec2Processor"),
-        ("wav2vec2-conformer", "Wav2Vec2Processor"),
-        ("wavlm", "Wav2Vec2Processor"),
-        ("whisper", "WhisperProcessor"),
-        ("xclip", "XCLIPProcessor"),
-    ]
-)
+if TYPE_CHECKING:
+    # This significantly improves completion suggestion performance when
+    # the transformers package is used with Microsoft's Pylance language server.
+    PROCESSOR_MAPPING_NAMES: OrderedDict[str, str | None] = OrderedDict()
+else:
+    PROCESSOR_MAPPING_NAMES = OrderedDict(
+        [
+            ("aimv2", "CLIPProcessor"),
+            ("align", "AlignProcessor"),
+            ("altclip", "AltCLIPProcessor"),
+            ("aria", "AriaProcessor"),
+            ("audioflamingo3", "AudioFlamingo3Processor"),
+            ("aya_vision", "AyaVisionProcessor"),
+            ("bark", "BarkProcessor"),
+            ("blip", "BlipProcessor"),
+            ("blip-2", "Blip2Processor"),
+            ("bridgetower", "BridgeTowerProcessor"),
+            ("chameleon", "ChameleonProcessor"),
+            ("chinese_clip", "ChineseCLIPProcessor"),
+            ("clap", "ClapProcessor"),
+            ("clip", "CLIPProcessor"),
+            ("clipseg", "CLIPSegProcessor"),
+            ("clvp", "ClvpProcessor"),
+            ("cohere2_vision", "Cohere2VisionProcessor"),
+            ("colmodernvbert", "ColModernVBertProcessor"),
+            ("colpali", "ColPaliProcessor"),
+            ("colqwen2", "ColQwen2Processor"),
+            ("deepseek_vl", "DeepseekVLProcessor"),
+            ("deepseek_vl_hybrid", "DeepseekVLHybridProcessor"),
+            ("dia", "DiaProcessor"),
+            ("edgetam", "Sam2Processor"),
+            ("emu3", "Emu3Processor"),
+            ("ernie4_5_vl_moe", "Ernie4_5_VLMoeProcessor"),
+            ("evolla", "EvollaProcessor"),
+            ("flava", "FlavaProcessor"),
+            ("florence2", "Florence2Processor"),
+            ("fuyu", "FuyuProcessor"),
+            ("gemma3", "Gemma3Processor"),
+            ("gemma3n", "Gemma3nProcessor"),
+            ("git", "GitProcessor"),
+            ("glm46v", "Glm46VProcessor"),
+            ("glm4v", "Glm4vProcessor"),
+            ("glm4v_moe", "Glm4vProcessor"),
+            ("glm_image", "Glm4vProcessor"),
+            ("glmasr", "GlmAsrProcessor"),
+            ("got_ocr2", "GotOcr2Processor"),
+            ("granite_speech", "GraniteSpeechProcessor"),
+            ("grounding-dino", "GroundingDinoProcessor"),
+            ("groupvit", "CLIPProcessor"),
+            ("higgs_audio_v2", "HiggsAudioV2Processor"),
+            ("hubert", "Wav2Vec2Processor"),
+            ("idefics", "IdeficsProcessor"),
+            ("idefics2", "Idefics2Processor"),
+            ("idefics3", "Idefics3Processor"),
+            ("instructblip", "InstructBlipProcessor"),
+            ("instructblipvideo", "InstructBlipVideoProcessor"),
+            ("internvl", "InternVLProcessor"),
+            ("janus", "JanusProcessor"),
+            ("kosmos-2", "Kosmos2Processor"),
+            ("kosmos-2.5", "Kosmos2_5Processor"),
+            ("kyutai_speech_to_text", "KyutaiSpeechToTextProcessor"),
+            ("lasr_ctc", "LasrProcessor"),
+            ("lasr_encoder", "LasrProcessor"),
+            ("layoutlmv2", "LayoutLMv2Processor"),
+            ("layoutlmv3", "LayoutLMv3Processor"),
+            ("layoutxlm", "LayoutXLMProcessor"),
+            ("lfm2_vl", "Lfm2VlProcessor"),
+            ("lighton_ocr", "LightOnOcrProcessor"),
+            ("llama4", "Llama4Processor"),
+            ("llava", "LlavaProcessor"),
+            ("llava_next", "LlavaNextProcessor"),
+            ("llava_next_video", "LlavaNextVideoProcessor"),
+            ("llava_onevision", "LlavaOnevisionProcessor"),
+            ("markuplm", "MarkupLMProcessor"),
+            ("metaclip_2", "CLIPProcessor"),
+            ("mgp-str", "MgpstrProcessor"),
+            ("mistral3", "PixtralProcessor"),
+            ("mllama", "MllamaProcessor"),
+            ("mm-grounding-dino", "GroundingDinoProcessor"),
+            ("modernvbert", "Idefics3Processor"),
+            ("moonshine", "Wav2Vec2Processor"),
+            ("moonshine_streaming", "MoonshineStreamingProcessor"),
+            ("omdet-turbo", "OmDetTurboProcessor"),
+            ("oneformer", "OneFormerProcessor"),
+            ("ovis2", "Ovis2Processor"),
+            ("owlv2", "Owlv2Processor"),
+            ("owlvit", "OwlViTProcessor"),
+            ("paddleocr_vl", "PaddleOCRVLProcessor"),
+            ("paligemma", "PaliGemmaProcessor"),
+            ("perception_lm", "PerceptionLMProcessor"),
+            ("phi4_multimodal", "Phi4MultimodalProcessor"),
+            ("pix2struct", "Pix2StructProcessor"),
+            ("pixtral", "PixtralProcessor"),
+            ("pop2piano", "Pop2PianoProcessor"),
+            ("qwen2_5_omni", "Qwen2_5OmniProcessor"),
+            ("qwen2_5_vl", "Qwen2_5_VLProcessor"),
+            ("qwen2_audio", "Qwen2AudioProcessor"),
+            ("qwen2_vl", "Qwen2VLProcessor"),
+            ("qwen3_5", "Qwen3VLProcessor"),
+            ("qwen3_5_moe", "Qwen3VLProcessor"),
+            ("qwen3_omni_moe", "Qwen3OmniMoeProcessor"),
+            ("qwen3_vl", "Qwen3VLProcessor"),
+            ("qwen3_vl_moe", "Qwen3VLProcessor"),
+            ("sam", "SamProcessor"),
+            ("sam2", "Sam2Processor"),
+            ("sam3", "Sam3Processor"),
+            ("sam_hq", "SamHQProcessor"),
+            ("seamless_m4t", "SeamlessM4TProcessor"),
+            ("sew", "Wav2Vec2Processor"),
+            ("sew-d", "Wav2Vec2Processor"),
+            ("shieldgemma2", "ShieldGemma2Processor"),
+            ("siglip", "SiglipProcessor"),
+            ("siglip2", "Siglip2Processor"),
+            ("smolvlm", "SmolVLMProcessor"),
+            ("speech_to_text", "Speech2TextProcessor"),
+            ("speecht5", "SpeechT5Processor"),
+            ("t5gemma2", "Gemma3Processor"),
+            ("t5gemma2_encoder", "Gemma3Processor"),
+            ("trocr", "TrOCRProcessor"),
+            ("tvp", "TvpProcessor"),
+            ("udop", "UdopProcessor"),
+            ("unispeech", "Wav2Vec2Processor"),
+            ("unispeech-sat", "Wav2Vec2Processor"),
+            ("vibevoice_asr", "VibeVoiceAsrProcessor"),
+            ("video_llava", "VideoLlavaProcessor"),
+            ("vilt", "ViltProcessor"),
+            ("vipllava", "LlavaProcessor"),
+            ("vision-text-dual-encoder", "VisionTextDualEncoderProcessor"),
+            ("voxtral", "VoxtralProcessor"),
+            ("voxtral_realtime", "VoxtralRealtimeProcessor"),
+            ("wav2vec2", "Wav2Vec2Processor"),
+            ("wav2vec2-bert", "Wav2Vec2Processor"),
+            ("wav2vec2-conformer", "Wav2Vec2Processor"),
+            ("wavlm", "Wav2Vec2Processor"),
+            ("whisper", "WhisperProcessor"),
+            ("xclip", "XCLIPProcessor"),
+        ]
+    )
 
 PROCESSOR_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, PROCESSOR_MAPPING_NAMES)
 

filename: src/transformers/models/colmodernvbert/modular_colmodernvbert.py
patch: @@ -25,6 +25,7 @@
 from ...tokenization_utils_base import TextInput
 from ...utils import ModelOutput, TransformersKwargs, auto_docstring, logging
 from ...utils.generic import can_return_tuple
+from ...utils.import_utils import requires
 from ..auto import CONFIG_MAPPING
 from ..auto.modeling_auto import AutoModel
 from ..colpali.modeling_colpali import ColPaliForRetrieval, ColPaliPreTrainedModel
@@ -114,6 +115,8 @@ class ColModernVBertProcessorKwargs(Idefics3ProcessorKwargs, total=False):
     }
 
 
+@requires(backends=("torch",))
+@auto_docstring
 class ColModernVBertProcessor(Idefics3Processor):
     r"""
     Constructs a ColModernVBert processor which wraps a ModernVBertProcessor and special methods to process images and queries, as

filename: src/transformers/models/colmodernvbert/processing_colmodernvbert.py
patch: @@ -30,6 +30,7 @@
 from ...processing_utils import MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack
 from ...tokenization_utils_base import AddedToken, BatchEncoding, TextInput
 from ...utils import auto_docstring
+from ...utils.import_utils import requires
 
 
 if TYPE_CHECKING:
@@ -102,6 +103,7 @@ def get_image_prompt_string(
     )
 
 
+@requires(backends=("torch",))
 @auto_docstring
 class ColModernVBertProcessor(ProcessorMixin):
     r"""

filename: src/transformers/models/higgs_audio_v2_tokenizer/modeling_higgs_audio_v2_tokenizer.py
patch: @@ -31,6 +31,7 @@
 from ...audio_utils import conv1d_output_length
 from ...modeling_utils import PreTrainedAudioTokenizerBase
 from ...utils import ModelOutput, auto_docstring
+from ...utils.import_utils import requires
 from ..auto import AutoModel
 from .configuration_higgs_audio_v2_tokenizer import HiggsAudioV2TokenizerConfig
 
@@ -447,6 +448,7 @@ def decode(self, codes: torch.Tensor) -> torch.Tensor:
         return quantized_out
 
 
+@requires(backends=("torchaudio",))
 @auto_docstring(custom_intro="""The HiggsAudioV2Tokenizer neural audio codec model.""")
 class HiggsAudioV2TokenizerModel(HiggsAudioV2TokenizerPreTrainedModel):
     def __init__(self, config):

filename: src/transformers/models/higgs_audio_v2_tokenizer/modular_higgs_audio_v2_tokenizer.py
patch: @@ -17,6 +17,8 @@
 import torch.nn.functional as F
 import torchaudio
 
+from ...utils import auto_docstring
+from ...utils.import_utils import requires
 from ..xcodec.configuration_xcodec import XcodecConfig
 from ..xcodec.modeling_xcodec import XcodecEuclideanCodebook, XcodecModel, XcodecPreTrainedModel
 
@@ -150,6 +152,8 @@ def decode(self, embed_ind):
         return quantize
 
 
+@requires(backends=("torchaudio",))
+@auto_docstring(custom_intro="""The HiggsAudioV2Tokenizer neural audio codec model.""")
 class HiggsAudioV2TokenizerModel(XcodecModel):
     def _extract_semantic_features(self, input_values: torch.FloatTensor) -> torch.FloatTensor:
         if self.config.sample_rate != self.config.semantic_sample_rate: