State-of-the-art pretrained models for inference and training
+
+
+
+
+
+
+Transformers acts as the model-definition framework for state-of-the-art machine learning with text, computer
+vision, audio, video, and multimodal models, for both inference and training.
+
+It centralizes the model definition so that this definition is agreed upon across the ecosystem. `transformers` is the
+pivot across frameworks: if a model definition is supported, it will be compatible with the majority of training
+frameworks (Axolotl, Unsloth, DeepSpeed, FSDP, PyTorch-Lightning, ...), inference engines (vLLM, SGLang, TGI, ...),
+and adjacent modeling libraries (llama.cpp, mlx, ...) which leverage the model definition from `transformers`.
+
+We pledge to help support new state-of-the-art models and democratize their usage by having their model definition be
+simple, customizable, and efficient.
+
+There are over 1M+ Transformers [model checkpoints](https://huggingface.co/models?library=transformers&sort=trending) on the [Hugging Face Hub](https://huggingface.co/models) you can use.
+
+Explore the [Hub](https://huggingface.co/) today to find a model and use Transformers to help you get started right away.
+
+## Installation
+
+Transformers works with Python 3.10+, and [PyTorch](https://pytorch.org/get-started/locally/) 2.4+.
+
+Create and activate a virtual environment with [venv](https://docs.python.org/3/library/venv.html) or [uv](https://docs.astral.sh/uv/), a fast Rust-based Python package and project manager.
+
+```py
+# venv
+python -m venv .my-env
+source .my-env/bin/activate
+# uv
+uv venv .my-env
+source .my-env/bin/activate
+```
+
+Install Transformers in your virtual environment.
+
+```py
+# pip
+pip install "transformers[torch]"
+
+# uv
+uv pip install "transformers[torch]"
+```
+
+Install Transformers from source if you want the latest changes in the library or are interested in contributing. However, the *latest* version may not be stable. Feel free to open an [issue](https://github.com/huggingface/transformers/issues) if you encounter an error.
+
+```shell
+git clone https://github.com/huggingface/transformers.git
+cd transformers
+
+# pip
+pip install '.[torch]'
+
+# uv
+uv pip install '.[torch]'
+```
+
+## Quickstart
+
+Get started with Transformers right away with the [Pipeline](https://huggingface.co/docs/transformers/pipeline_tutorial) API. The `Pipeline` is a high-level inference class that supports text, audio, vision, and multimodal tasks. It handles preprocessing the input and returns the appropriate output.
+
+Instantiate a pipeline and specify model to use for text generation. The model is downloaded and cached so you can easily reuse it again. Finally, pass some text to prompt the model.
+
+```py
+from transformers import pipeline
+
+pipeline = pipeline(task="text-generation", model="Qwen/Qwen2.5-1.5B")
+pipeline("the secret to baking a really good cake is ")
+[{'generated_text': 'the secret to baking a really good cake is 1) to use the right ingredients and 2) to follow the recipe exactly. the recipe for the cake is as follows: 1 cup of sugar, 1 cup of flour, 1 cup of milk, 1 cup of butter, 1 cup of eggs, 1 cup of chocolate chips. if you want to make 2 cakes, how much sugar do you need? To make 2 cakes, you will need 2 cups of sugar.'}]
+```
+
+To chat with a model, the usage pattern is the same. The only difference is you need to construct a chat history (the input to `Pipeline`) between you and the system.
+
+> [!TIP]
+> You can also chat with a model directly from the command line, as long as [`transformers serve` is running](https://huggingface.co/docs/transformers/main/en/serving).
+> ```shell
+> transformers chat Qwen/Qwen2.5-0.5B-Instruct
+> ```
+
+```py
+import torch
+from transformers import pipeline
+
+chat = [
+ {"role": "system", "content": "You are a sassy, wise-cracking robot as imagined by Hollywood circa 1986."},
+ {"role": "user", "content": "Hey, can you tell me any fun things to do in New York?"}
+]
+
+pipeline = pipeline(task="text-generation", model="meta-llama/Meta-Llama-3-8B-Instruct", dtype=torch.bfloat16, device_map="auto")
+response = pipeline(chat, max_new_tokens=512)
+print(response[0]["generated_text"][-1]["content"])
+```
+
+Expand the examples below to see how `Pipeline` works for different modalities and tasks.
+
+
+Automatic speech recognition
+
+```py
+from transformers import pipeline
+
+pipeline = pipeline(task="automatic-speech-recognition", model="openai/whisper-large-v3")
+pipeline("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
+{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.'}
+```
+
+
+
+
+Image classification
+
+
+
+```py
+from transformers import pipeline
+
+pipeline = pipeline(task="visual-question-answering", model="Salesforce/blip-vqa-base")
+pipeline(
+ image="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/idefics-few-shot.jpg",
+ question="What is in the image?",
+)
+[{'answer': 'statue of liberty'}]
+```
+
+
+
+## Why should I use Transformers?
+
+1. Easy-to-use state-of-the-art models:
+ - High performance on natural language understanding & generation, computer vision, audio, video, and multimodal tasks.
+ - Low barrier to entry for researchers, engineers, and developers.
+ - Few user-facing abstractions with just three classes to learn.
+ - A unified API for using all our pretrained models.
+
+1. Lower compute costs, smaller carbon footprint:
+ - Share trained models instead of training from scratch.
+ - Reduce compute time and production costs.
+ - Hundreds of model architectures with 1M+ pretrained checkpoints across all modalities.
+
+1. Choose the right framework for every part of a model's lifetime:
+ - Train state-of-the-art models in 3 lines of code.
+ - Move a single model between PyTorch/JAX/TF2.0 frameworks at will.
+ - Pick the right framework for training, evaluation, and production.
+
+1. Easily customize a model or an example to your needs:
+ - We provide examples for each architecture to reproduce the results published by its original authors.
+ - Model internals are exposed as consistently as possible.
+ - Model files can be used independently of the library for quick experiments.
+
+
+
+
+
+## When shouldn't I use Transformers?
+
+- This library is not a modular toolbox of building blocks for neural nets. The code in the model files is not refactored with additional abstractions on purpose, so that researchers can quickly iterate on each of the models without diving into additional abstractions/files.
+- The training API is optimized to work with PyTorch models provided by Transformers. For generic machine learning loops, you should use another library like [Accelerate](https://huggingface.co/docs/accelerate).
+- The [example scripts](https://github.com/huggingface/transformers/tree/main/examples) are only *examples*. They may not necessarily work out-of-the-box on your specific use case and you'll need to adapt the code for it to work.
+
+## 100 projects using Transformers
+
+Transformers is more than a toolkit to use pretrained models, it's a community of projects built around it and the
+Hugging Face Hub. We want Transformers to enable developers, researchers, students, professors, engineers, and anyone
+else to build their dream projects.
+
+In order to celebrate Transformers 100,000 stars, we wanted to put the spotlight on the
+community with the [awesome-transformers](./awesome-transformers.md) page which lists 100
+incredible projects built with Transformers.
+
+If you own or use a project that you believe should be part of the list, please open a PR to add it!
+
+## Example models
+
+You can test most of our models directly on their [Hub model pages](https://huggingface.co/models).
+
+Expand each modality below to see a few example models for various use cases.
+
+
+Audio
+
+- Audio classification with [CLAP](https://huggingface.co/laion/clap-htsat-fused)
+- Automatic speech recognition with [Parakeet](https://huggingface.co/nvidia/parakeet-ctc-1.1b#transcribing-using-transformers-%F0%9F%A4%97), [Whisper](https://huggingface.co/openai/whisper-large-v3-turbo), [GLM-ASR](https://huggingface.co/zai-org/GLM-ASR-Nano-2512) and [Moonshine-Streaming](https://huggingface.co/UsefulSensors/moonshine-streaming-medium)
+- Keyword spotting with [Wav2Vec2](https://huggingface.co/superb/wav2vec2-base-superb-ks)
+- Speech to speech generation with [Moshi](https://huggingface.co/kyutai/moshiko-pytorch-bf16)
+- Text to audio with [MusicGen](https://huggingface.co/facebook/musicgen-large)
+- Text to speech with [CSM](https://huggingface.co/sesame/csm-1b)
+
+
+
+
+Computer vision
+
+- Automatic mask generation with [SAM](https://huggingface.co/facebook/sam-vit-base)
+- Depth estimation with [DepthPro](https://huggingface.co/apple/DepthPro-hf)
+- Image classification with [DINO v2](https://huggingface.co/facebook/dinov2-base)
+- Keypoint detection with [SuperPoint](https://huggingface.co/magic-leap-community/superpoint)
+- Keypoint matching with [SuperGlue](https://huggingface.co/magic-leap-community/superglue_outdoor)
+- Object detection with [RT-DETRv2](https://huggingface.co/PekingU/rtdetr_v2_r50vd)
+- Pose Estimation with [VitPose](https://huggingface.co/usyd-community/vitpose-base-simple)
+- Universal segmentation with [OneFormer](https://huggingface.co/shi-labs/oneformer_ade20k_swin_large)
+- Video classification with [VideoMAE](https://huggingface.co/MCG-NJU/videomae-large)
+
+
+
+
+Multimodal
+
+- Audio or text to text with [Voxtral](https://huggingface.co/mistralai/Voxtral-Mini-3B-2507), [Audio Flamingo](https://huggingface.co/nvidia/audio-flamingo-3-hf)
+- Document question answering with [LayoutLMv3](https://huggingface.co/microsoft/layoutlmv3-base)
+- Image or text to text with [Qwen-VL](https://huggingface.co/Qwen/Qwen2.5-VL-3B-Instruct)
+- Image captioning [BLIP-2](https://huggingface.co/Salesforce/blip2-opt-2.7b)
+- OCR-based document understanding with [GOT-OCR2](https://huggingface.co/stepfun-ai/GOT-OCR-2.0-hf)
+- Table question answering with [TAPAS](https://huggingface.co/google/tapas-base)
+- Unified multimodal understanding and generation with [Emu3](https://huggingface.co/BAAI/Emu3-Gen)
+- Vision to text with [Llava-OneVision](https://huggingface.co/llava-hf/llava-onevision-qwen2-0.5b-ov-hf)
+- Visual question answering with [Llava](https://huggingface.co/llava-hf/llava-1.5-7b-hf)
+- Visual referring expression segmentation with [Kosmos-2](https://huggingface.co/microsoft/kosmos-2-patch14-224)
+
+
+
+
+NLP
+
+- Masked word completion with [ModernBERT](https://huggingface.co/answerdotai/ModernBERT-base)
+- Named entity recognition with [Gemma](https://huggingface.co/google/gemma-2-2b)
+- Question answering with [Mixtral](https://huggingface.co/mistralai/Mixtral-8x7B-v0.1)
+- Summarization with [BART](https://huggingface.co/facebook/bart-large-cnn)
+- Translation with [T5](https://huggingface.co/google-t5/t5-base)
+- Text generation with [Llama](https://huggingface.co/meta-llama/Llama-3.2-1B)
+- Text classification with [Qwen](https://huggingface.co/Qwen/Qwen2.5-0.5B)
+
+
+
+## Citation
+
+We now have a [paper](https://aclanthology.org/2020.emnlp-demos.6/) you can cite for the 🤗 Transformers library:
+```bibtex
+@inproceedings{wolf-etal-2020-transformers,
+ title = "Transformers: State-of-the-Art Natural Language Processing",
+ author = "Thomas Wolf and Lysandre Debut and Victor Sanh and Julien Chaumond and Clement Delangue and Anthony Moi and Pierric Cistac and Tim Rault and Rémi Louf and Morgan Funtowicz and Joe Davison and Sam Shleifer and Patrick von Platen and Clara Ma and Yacine Jernite and Julien Plu and Canwen Xu and Teven Le Scao and Sylvain Gugger and Mariama Drame and Quentin Lhoest and Alexander M. Rush",
+ booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: System Demonstrations",
+ month = oct,
+ year = "2020",
+ address = "Online",
+ publisher = "Association for Computational Linguistics",
+ url = "https://aclanthology.org/2020.emnlp-demos.6/",
+ pages = "38--45"
+}
+```
diff --git a/.venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/RECORD b/.venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..63ceba4ebdb30a3294f8b3b2da6bf0e9f94effee
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/RECORD
@@ -0,0 +1,4928 @@
+../../../bin/transformers,sha256=lQAI_lSSmk0RkCLifMx2-1ImR9HZpe__CtsKMJRTeWA,210
+transformers-5.12.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+transformers-5.12.0.dist-info/METADATA,sha256=ufBSOr0Mu8CXH3Pl2GCmScScCoH8ew1WpzUv-ynxhH8,33140
+transformers-5.12.0.dist-info/RECORD,,
+transformers-5.12.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+transformers-5.12.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
+transformers-5.12.0.dist-info/entry_points.txt,sha256=TcBlmquYV475KJBK8EhQNnsLiegWUy_QoKR4R0pMh2g,68
+transformers-5.12.0.dist-info/licenses/LICENSE,sha256=d_1HEN757DwPYiWADgI18VpCWr1KiwNVkSf814JhIEk,11418
+transformers-5.12.0.dist-info/top_level.txt,sha256=GLBaeTo_CSdhnHvbxQ0kzpEHdlLuA_33foIogaWxntI,13
+transformers/__init__.py,sha256=vP92JqDqKudZsRQ5LPqC4UJOFZ4OQQZsxwZ8N22UoQM,41198
+transformers/__pycache__/__init__.cpython-312.pyc,,
+transformers/__pycache__/_typing.cpython-312.pyc,,
+transformers/__pycache__/activations.cpython-312.pyc,,
+transformers/__pycache__/audio_utils.cpython-312.pyc,,
+transformers/__pycache__/backbone_utils.cpython-312.pyc,,
+transformers/__pycache__/cache_utils.cpython-312.pyc,,
+transformers/__pycache__/configuration_utils.cpython-312.pyc,,
+transformers/__pycache__/conversion_mapping.cpython-312.pyc,,
+transformers/__pycache__/convert_slow_tokenizer.cpython-312.pyc,,
+transformers/__pycache__/convert_slow_tokenizers_checkpoints_to_fast.cpython-312.pyc,,
+transformers/__pycache__/core_model_loading.cpython-312.pyc,,
+transformers/__pycache__/debug_utils.cpython-312.pyc,,
+transformers/__pycache__/dependency_versions_check.cpython-312.pyc,,
+transformers/__pycache__/dependency_versions_table.cpython-312.pyc,,
+transformers/__pycache__/dynamic_module_utils.cpython-312.pyc,,
+transformers/__pycache__/feature_extraction_sequence_utils.cpython-312.pyc,,
+transformers/__pycache__/feature_extraction_utils.cpython-312.pyc,,
+transformers/__pycache__/file_utils.cpython-312.pyc,,
+transformers/__pycache__/fusion_mapping.cpython-312.pyc,,
+transformers/__pycache__/hf_argparser.cpython-312.pyc,,
+transformers/__pycache__/hyperparameter_search.cpython-312.pyc,,
+transformers/__pycache__/image_processing_backends.cpython-312.pyc,,
+transformers/__pycache__/image_processing_base.cpython-312.pyc,,
+transformers/__pycache__/image_processing_utils.cpython-312.pyc,,
+transformers/__pycache__/image_transforms.cpython-312.pyc,,
+transformers/__pycache__/image_utils.cpython-312.pyc,,
+transformers/__pycache__/initialization.cpython-312.pyc,,
+transformers/__pycache__/masking_utils.cpython-312.pyc,,
+transformers/__pycache__/model_debugging_utils.cpython-312.pyc,,
+transformers/__pycache__/modelcard.cpython-312.pyc,,
+transformers/__pycache__/modeling_attn_mask_utils.cpython-312.pyc,,
+transformers/__pycache__/modeling_flash_attention_utils.cpython-312.pyc,,
+transformers/__pycache__/modeling_gguf_pytorch_utils.cpython-312.pyc,,
+transformers/__pycache__/modeling_layers.cpython-312.pyc,,
+transformers/__pycache__/modeling_outputs.cpython-312.pyc,,
+transformers/__pycache__/modeling_rope_utils.cpython-312.pyc,,
+transformers/__pycache__/modeling_utils.cpython-312.pyc,,
+transformers/__pycache__/monkey_patching.cpython-312.pyc,,
+transformers/__pycache__/optimization.cpython-312.pyc,,
+transformers/__pycache__/processing_utils.cpython-312.pyc,,
+transformers/__pycache__/pytorch_utils.cpython-312.pyc,,
+transformers/__pycache__/safetensors_conversion.cpython-312.pyc,,
+transformers/__pycache__/testing_utils.cpython-312.pyc,,
+transformers/__pycache__/time_series_utils.cpython-312.pyc,,
+transformers/__pycache__/tokenization_mistral_common.cpython-312.pyc,,
+transformers/__pycache__/tokenization_python.cpython-312.pyc,,
+transformers/__pycache__/tokenization_utils_base.cpython-312.pyc,,
+transformers/__pycache__/tokenization_utils_sentencepiece.cpython-312.pyc,,
+transformers/__pycache__/tokenization_utils_tokenizers.cpython-312.pyc,,
+transformers/__pycache__/trainer.cpython-312.pyc,,
+transformers/__pycache__/trainer_callback.cpython-312.pyc,,
+transformers/__pycache__/trainer_jit_checkpoint.cpython-312.pyc,,
+transformers/__pycache__/trainer_optimizer.cpython-312.pyc,,
+transformers/__pycache__/trainer_pt_utils.cpython-312.pyc,,
+transformers/__pycache__/trainer_seq2seq.cpython-312.pyc,,
+transformers/__pycache__/trainer_utils.cpython-312.pyc,,
+transformers/__pycache__/training_args.cpython-312.pyc,,
+transformers/__pycache__/training_args_seq2seq.cpython-312.pyc,,
+transformers/__pycache__/video_processing_utils.cpython-312.pyc,,
+transformers/__pycache__/video_utils.cpython-312.pyc,,
+transformers/__pycache__/vision_utils.cpython-312.pyc,,
+transformers/_typing.py,sha256=emfyQ87l4ZN4PHcvgGDsS7HlgBmgkNSyjbfcycuQp4w,6999
+transformers/activations.py,sha256=SxpGnCS-TkxjIFNq1VpzN9JN4Ew-zHFZf78CZ_FWBhI,13491
+transformers/audio_utils.py,sha256=8lE2WwmtydhM2h19E4Q8g2uM4GuhgyfpGfhumCI5UTo,55672
+transformers/backbone_utils.py,sha256=nHO4XO6useSwiMAbj53HTtKLeii-z8BxFnfMIjifgWU,17044
+transformers/cache_utils.py,sha256=J4OycCkQ27bnCqBaCT9x4cUcEQ1_pzyQT8ONEuWIJUU,85947
+transformers/cli/__init__.py,sha256=A4zmzuHD2OHjQ5zmdfcnsj0JeCzHVPtpzh-wCjInugA,606
+transformers/cli/__pycache__/__init__.cpython-312.pyc,,
+transformers/cli/__pycache__/add_new_model_like.cpython-312.pyc,,
+transformers/cli/__pycache__/chat.cpython-312.pyc,,
+transformers/cli/__pycache__/download.cpython-312.pyc,,
+transformers/cli/__pycache__/serve.cpython-312.pyc,,
+transformers/cli/__pycache__/system.cpython-312.pyc,,
+transformers/cli/__pycache__/transformers.cpython-312.pyc,,
+transformers/cli/add_new_model_like.py,sha256=EgDqQRTXDDtsmlrYHiwtzrXFIcN4FQJrtLwYNAZqNbo,32486
+transformers/cli/chat.py,sha256=A7inpg9WQeWjR8o2JPwi_vgqvTdzJw1j6rVOIwOoglo,28958
+transformers/cli/download.py,sha256=hO2NipXmWif_xNAR0c4CPvZUnxPzfHxBmOu8s2dfTuE,1692
+transformers/cli/serve.py,sha256=E86-an6PJ13fnwwFwrkiZoYcpnBEBWCEfRRITdcnMUM,9431
+transformers/cli/serving/__init__.py,sha256=-FvRePN2Yv5ZLwmvo1dqzlCH2hYhGW43QD4OfKr1gSE,708
+transformers/cli/serving/__pycache__/__init__.cpython-312.pyc,,
+transformers/cli/serving/__pycache__/chat_completion.cpython-312.pyc,,
+transformers/cli/serving/__pycache__/completion.cpython-312.pyc,,
+transformers/cli/serving/__pycache__/model_manager.cpython-312.pyc,,
+transformers/cli/serving/__pycache__/response.cpython-312.pyc,,
+transformers/cli/serving/__pycache__/server.cpython-312.pyc,,
+transformers/cli/serving/__pycache__/transcription.cpython-312.pyc,,
+transformers/cli/serving/__pycache__/utils.cpython-312.pyc,,
+transformers/cli/serving/chat_completion.py,sha256=fOqEI3NB8TuK-cVapAp5-xo5Z3MwKen6P_PvBA8qbO4,18146
+transformers/cli/serving/completion.py,sha256=uDjvrqV5AWGzIeyFhqluhhl1F9uCYE6iSQRvQpHJy1Q,10223
+transformers/cli/serving/model_manager.py,sha256=UJFZyf-SAl-akS2Hx18xb-wRarBoI0u7W3EvOat7aGc,20388
+transformers/cli/serving/response.py,sha256=zycPhypZsEpXB0m9jF4he64Cp58QQehRgroVmOjl6I4,29826
+transformers/cli/serving/server.py,sha256=AnqX5PZGrlxxFraG9jwmKj8B9QGe6E3f4iK1tKUT4s0,5173
+transformers/cli/serving/transcription.py,sha256=rAsFDPHJbprkIQ8zpaWKlZhVFdVXK25REvBk332JdYg,7986
+transformers/cli/serving/utils.py,sha256=4Q0P7pR5Qz_HAStLLs9CkIDKJyGyBuw64kANhzbd-eo,53012
+transformers/cli/system.py,sha256=ma8J8mBJMeYkGarN-OzrLyI-G40feWsA-W63srHurvE,4985
+transformers/cli/transformers.py,sha256=CT9UQW3v6vMH1mPdv4gr43uDjkXZ10WijsBT2CdsjBE,1248
+transformers/configuration_utils.py,sha256=vkX57LekjCixFeJSQbRq-lOmO07OQ84PNEwVOoE4YF8,64249
+transformers/conversion_mapping.py,sha256=8GEYLJB3HVIBSAeAHMNr-gvqHxngu7W7_DidULejYiY,84705
+transformers/convert_slow_tokenizer.py,sha256=cGHl3ff-TeCFvBc8LawMuTjcQO20YdIbr4R4DmImLKI,78159
+transformers/convert_slow_tokenizers_checkpoints_to_fast.py,sha256=clQ6w0W8vfL_CrRDpPBO4CGXAxAG4AJ9pb8YL5MPhpA,5790
+transformers/core_model_loading.py,sha256=A5sgcFYZl7Sqe94PCClLCaVV3CM0D8xB00_UufPpN9c,71476
+transformers/data/__init__.py,sha256=MuXSchTzRSaUtUDC1uSeDkHiSbjtrQZg4IoKeKHoH6A,1490
+transformers/data/__pycache__/__init__.cpython-312.pyc,,
+transformers/data/__pycache__/data_collator.cpython-312.pyc,,
+transformers/data/data_collator.py,sha256=TvK95b5THl-zQUsi4_ST9i_UbuezVEjgXXUlF5ysF6w,69690
+transformers/data/datasets/__init__.py,sha256=_KGvq0E6uO2iT0Kzl_HDJIuz9xkQmePGgfqkRU4hvS8,724
+transformers/data/datasets/__pycache__/__init__.cpython-312.pyc,,
+transformers/data/datasets/__pycache__/glue.cpython-312.pyc,,
+transformers/data/datasets/__pycache__/squad.cpython-312.pyc,,
+transformers/data/datasets/glue.py,sha256=4LZJgtGm27re7foc6KOZ2rAZB3PoCS10JsQ-sbumIBo,6086
+transformers/data/datasets/squad.py,sha256=VaZNZ2SyyZbgOFg-hqnkeI0atrgNIQw5XBYPeYXp4MI,9145
+transformers/data/metrics/__init__.py,sha256=km9yg-ht5wbJYlaeBkJskzapjfpiv9wPArDP_5k4DQw,3640
+transformers/data/metrics/__pycache__/__init__.cpython-312.pyc,,
+transformers/data/metrics/__pycache__/squad_metrics.cpython-312.pyc,,
+transformers/data/metrics/squad_metrics.py,sha256=__cjdPU1qt3bjnXq3k6CC2_p_5DxbU8p6I5EL40unrg,29685
+transformers/data/processors/__init__.py,sha256=lvN5mp9mdrr5v6QvZT6VcoZ78zZUvXiumTm6Gdvlgvo,1014
+transformers/data/processors/__pycache__/__init__.cpython-312.pyc,,
+transformers/data/processors/__pycache__/glue.cpython-312.pyc,,
+transformers/data/processors/__pycache__/squad.cpython-312.pyc,,
+transformers/data/processors/__pycache__/utils.cpython-312.pyc,,
+transformers/data/processors/__pycache__/xnli.cpython-312.pyc,,
+transformers/data/processors/glue.py,sha256=e-TbSIQFJ29WhxnS1rn-Ne61Tf322Eh9HzKyZR2c95U,21368
+transformers/data/processors/squad.py,sha256=t7BnHz6ePs3TYfUJA4MekR84fQjw7ocR6HbCVyQyLBE,28895
+transformers/data/processors/utils.py,sha256=IEiGb4u5z80mOFaFUnRVkkk7lT-l19UllT05FUYBxVo,12829
+transformers/data/processors/xnli.py,sha256=6E-hvbeM2Gn_cKCqwB5eq1zHXDRitDTgam6prnfC-KE,3466
+transformers/debug_utils.py,sha256=By3zizwqZFiYRc8hCY3d0bt8qObCjIErVuJK1xJEGro,12964
+transformers/dependency_versions_check.py,sha256=Uj3M5Rn38MDjLg5q9DAz2TGnOdvkdDpwrSrxGjVukQM,2099
+transformers/dependency_versions_table.py,sha256=mPT8ghKyhYAlEOo5QF4lmjaS3zqoWJakhZ7eCDQoZgk,3177
+transformers/distributed/__init__.py,sha256=ds-xiU6Hko8BN-XiIF2cJZPCjrQ-JFlodRARkPK8g-0,978
+transformers/distributed/__pycache__/__init__.cpython-312.pyc,,
+transformers/distributed/__pycache__/configuration_utils.cpython-312.pyc,,
+transformers/distributed/configuration_utils.py,sha256=c43IoxSKL3FnA9q3-suCYgoMyjfJnLQr5HASppruVTQ,4386
+transformers/dynamic_module_utils.py,sha256=KYvOLgw_WruYl9PNJ4HNV3FBC61TNC2kKBkoxDfrH4E,36473
+transformers/feature_extraction_sequence_utils.py,sha256=22sIxIR7qFMZQGauANQ4vtZyrL78rWARpCSCTcoE4S0,19434
+transformers/feature_extraction_utils.py,sha256=JetcxVyYFVx_rBJ3cNTJPcmnO5SWMw0K159JPP0KUEE,30129
+transformers/file_utils.py,sha256=csjz46-BAJ-tNyLjRAqBQWxZZWCVrRGOoAvDTxgyHSs,2935
+transformers/fusion_mapping.py,sha256=mgWrjMwKtHVlJry3bAUJmo7D8bY0xhfGIDBdGoHMLww,10582
+transformers/generation/__init__.py,sha256=12PLGFTPLeVRvOkA1gldQHT7d7eSZevd1YSRVxYNZNw,7336
+transformers/generation/__pycache__/__init__.cpython-312.pyc,,
+transformers/generation/__pycache__/candidate_generator.cpython-312.pyc,,
+transformers/generation/__pycache__/configuration_utils.cpython-312.pyc,,
+transformers/generation/__pycache__/logits_process.cpython-312.pyc,,
+transformers/generation/__pycache__/stopping_criteria.cpython-312.pyc,,
+transformers/generation/__pycache__/streamers.cpython-312.pyc,,
+transformers/generation/__pycache__/utils.cpython-312.pyc,,
+transformers/generation/__pycache__/watermarking.cpython-312.pyc,,
+transformers/generation/candidate_generator.py,sha256=zImsEzqQh8Y1mmCdV8NUZwARCy6OgMpNCHW8bs-iydQ,77228
+transformers/generation/configuration_utils.py,sha256=X-qj3Tag-QlqDJLcyDlNtzqdXoa8Ie6q7WkpDLZlDkQ,97025
+transformers/generation/continuous_batching/__init__.py,sha256=X3bo8vwLZ3HgUL0z5KAnoyEFQb1VhLwf0nKAyVr-RWs,1027
+transformers/generation/continuous_batching/__pycache__/__init__.cpython-312.pyc,,
+transformers/generation/continuous_batching/__pycache__/cache.cpython-312.pyc,,
+transformers/generation/continuous_batching/__pycache__/cache_manager.cpython-312.pyc,,
+transformers/generation/continuous_batching/__pycache__/cb_logits_processors.cpython-312.pyc,,
+transformers/generation/continuous_batching/__pycache__/continuous_api.cpython-312.pyc,,
+transformers/generation/continuous_batching/__pycache__/distributed.cpython-312.pyc,,
+transformers/generation/continuous_batching/__pycache__/initialization.cpython-312.pyc,,
+transformers/generation/continuous_batching/__pycache__/input_outputs.cpython-312.pyc,,
+transformers/generation/continuous_batching/__pycache__/model_runner.cpython-312.pyc,,
+transformers/generation/continuous_batching/__pycache__/offloading_manager.cpython-312.pyc,,
+transformers/generation/continuous_batching/__pycache__/requests.cpython-312.pyc,,
+transformers/generation/continuous_batching/__pycache__/scheduler.cpython-312.pyc,,
+transformers/generation/continuous_batching/__pycache__/utils.cpython-312.pyc,,
+transformers/generation/continuous_batching/cache.py,sha256=r2Tw17qSifQ94nEi65kW00qnrBAr-PUEfaDIwG-Pbbg,42210
+transformers/generation/continuous_batching/cache_manager.py,sha256=mXCDw4BdnHY8tHwVFw97Z5RWsv_6WY2ybOyi0dRihIY,29435
+transformers/generation/continuous_batching/cb_logits_processors.py,sha256=sqx779aTY12y6jimiqGMY5wIhdC92h49fjRn4_2agA8,17211
+transformers/generation/continuous_batching/continuous_api.py,sha256=paAD51nXnPi5rwQtB91eiioy5F5bmeo6nvcRzSnSo30,61910
+transformers/generation/continuous_batching/distributed.py,sha256=ezYyw4JmXLKhoPgbhrhBIj9dun8lum70o0TzK-qvtSI,8825
+transformers/generation/continuous_batching/initialization.py,sha256=4W11Ebs54r68NDTG4DUS9tTrbXVZwFtFOnLDtYHUaEM,16105
+transformers/generation/continuous_batching/input_outputs.py,sha256=7FAQ0l4rgoiDAXQF_qtSO4rlgIWCLvhc4tPCy3usPWc,45711
+transformers/generation/continuous_batching/model_runner.py,sha256=lwjwCj0-Zo_pBN6-7GlIpnwfmZJdcHxbSIpg1rGSjIk,16054
+transformers/generation/continuous_batching/offloading_manager.py,sha256=SptFw6RQtxdCUhGaXsNua6z4FkL2kPZFs2P_ml8AB2s,16907
+transformers/generation/continuous_batching/requests.py,sha256=wleNC-k3S5uEYWt6zEF8WbEVvBPjNDRyseSZ765Z60E,17247
+transformers/generation/continuous_batching/scheduler.py,sha256=0fw4XsewWEMn1Yalm9Sf1R-uwYw_HFFTVy8nTCXds6A,23359
+transformers/generation/continuous_batching/utils.py,sha256=TEbhKDoWiPnoCiMMcQ5bPsSkeri65U5oEakzS7UStRI,9618
+transformers/generation/logits_process.py,sha256=Ou-5_V01ou-zfCveWWsKLFWrG_qCtV3i3ysWBis-uVc,150114
+transformers/generation/stopping_criteria.py,sha256=Bgr9I3gvxh93dLkKkkR_NsH1lt4h6UBWDnr7hlmPShc,33984
+transformers/generation/streamers.py,sha256=mI1C7rGWi40PvF8dwfD9K6uH6eB0AUECTGwUdffMUcE,16609
+transformers/generation/utils.py,sha256=Hq8K6-YflhaWjymLwzx49r_IPLQ_Vj20185XKCQTHHs,215449
+transformers/generation/watermarking.py,sha256=4US4nFfyCPJyP_NzNHjmmvZfI2s1RagUaF_ccwgZlCs,24558
+transformers/hf_argparser.py,sha256=dJktlWax22pHlUhCaXiAgNuCTGfGvZXpBB_-tWBRfRA,19734
+transformers/hyperparameter_search.py,sha256=kfMEB-nYTBT2stCzMWeAPvsleR7eI7SJKiIJu3jx1gU,3684
+transformers/image_processing_backends.py,sha256=JQOUiEqfkIRc-HtvwM8zQTN7GTQoVWxv9h7SsEvttpI,27095
+transformers/image_processing_base.py,sha256=UXMYFeq-yC97-hmWzPnIB38D2UUrMyMVFrLPOhyO0XQ,23128
+transformers/image_processing_utils.py,sha256=wKBxwibAKd77ZWWXDyliJjZ-ahvatJ4RNjej425Adiw,29590
+transformers/image_transforms.py,sha256=3Aj2-6QJe7p4oCt5HyncdjGwWsfhHJizaGn875vYzeo,45325
+transformers/image_utils.py,sha256=WQ7pMq_fv2ccFKXsqkrmFHuY8aG4ZPESYk_AA9nf4b8,41649
+transformers/initialization.py,sha256=CNMUbHE83BskMBcVY6FTlJ_XWNUaoeKtL6JRhKMe8II,12277
+transformers/integrations/__init__.py,sha256=AHNgowl25gct3go8WRcYzRY7fTvkFWittanRaEGo8p8,10212
+transformers/integrations/__pycache__/__init__.cpython-312.pyc,,
+transformers/integrations/__pycache__/accelerate.cpython-312.pyc,,
+transformers/integrations/__pycache__/aqlm.cpython-312.pyc,,
+transformers/integrations/__pycache__/awq.cpython-312.pyc,,
+transformers/integrations/__pycache__/bitnet.cpython-312.pyc,,
+transformers/integrations/__pycache__/bitsandbytes.cpython-312.pyc,,
+transformers/integrations/__pycache__/deepgemm.cpython-312.pyc,,
+transformers/integrations/__pycache__/deepspeed.cpython-312.pyc,,
+transformers/integrations/__pycache__/eager_paged.cpython-312.pyc,,
+transformers/integrations/__pycache__/eetq.cpython-312.pyc,,
+transformers/integrations/__pycache__/executorch.cpython-312.pyc,,
+transformers/integrations/__pycache__/fbgemm_fp8.cpython-312.pyc,,
+transformers/integrations/__pycache__/finegrained_fp8.cpython-312.pyc,,
+transformers/integrations/__pycache__/flash_attention.cpython-312.pyc,,
+transformers/integrations/__pycache__/flash_paged.cpython-312.pyc,,
+transformers/integrations/__pycache__/flex_attention.cpython-312.pyc,,
+transformers/integrations/__pycache__/fouroversix.cpython-312.pyc,,
+transformers/integrations/__pycache__/fp_quant.cpython-312.pyc,,
+transformers/integrations/__pycache__/fsdp.cpython-312.pyc,,
+transformers/integrations/__pycache__/gemma_quant.cpython-312.pyc,,
+transformers/integrations/__pycache__/ggml.cpython-312.pyc,,
+transformers/integrations/__pycache__/higgs.cpython-312.pyc,,
+transformers/integrations/__pycache__/hqq.cpython-312.pyc,,
+transformers/integrations/__pycache__/hub_kernels.cpython-312.pyc,,
+transformers/integrations/__pycache__/integration_utils.cpython-312.pyc,,
+transformers/integrations/__pycache__/liger.cpython-312.pyc,,
+transformers/integrations/__pycache__/metal_quantization.cpython-312.pyc,,
+transformers/integrations/__pycache__/mistral.cpython-312.pyc,,
+transformers/integrations/__pycache__/moe.cpython-312.pyc,,
+transformers/integrations/__pycache__/msa_attention.cpython-312.pyc,,
+transformers/integrations/__pycache__/mxfp4.cpython-312.pyc,,
+transformers/integrations/__pycache__/neftune.cpython-312.pyc,,
+transformers/integrations/__pycache__/npu_flash_attention.cpython-312.pyc,,
+transformers/integrations/__pycache__/peft.cpython-312.pyc,,
+transformers/integrations/__pycache__/quanto.cpython-312.pyc,,
+transformers/integrations/__pycache__/quark.cpython-312.pyc,,
+transformers/integrations/__pycache__/sdpa_attention.cpython-312.pyc,,
+transformers/integrations/__pycache__/sdpa_paged.cpython-312.pyc,,
+transformers/integrations/__pycache__/sinq.cpython-312.pyc,,
+transformers/integrations/__pycache__/sonicmoe.cpython-312.pyc,,
+transformers/integrations/__pycache__/spqr.cpython-312.pyc,,
+transformers/integrations/__pycache__/tensor_parallel.cpython-312.pyc,,
+transformers/integrations/__pycache__/tiktoken.cpython-312.pyc,,
+transformers/integrations/__pycache__/torchao.cpython-312.pyc,,
+transformers/integrations/__pycache__/tpu.cpython-312.pyc,,
+transformers/integrations/__pycache__/vptq.cpython-312.pyc,,
+transformers/integrations/accelerate.py,sha256=xJJyGLlSAr8Z3S3hyfi8hOH5OQTms0oEu5m5rDldiak,40963
+transformers/integrations/aqlm.py,sha256=EDEKYoQvw6dF685rU68LtCqv6UuzcydP7rk3Dk7nZIY,3013
+transformers/integrations/awq.py,sha256=YJNs6ZJpE0u8lc70tvUZCZDcw68u83mKYuPE5iry618,4891
+transformers/integrations/bitnet.py,sha256=CPnBKBLOS427NnaISR6YJPnbupmjQ1-9uuvKey-yK0I,14771
+transformers/integrations/bitsandbytes.py,sha256=5Uo9-qYePBvafOpS3lESR4evuNAvKUU8O-dTJN-S0-U,14708
+transformers/integrations/deepgemm.py,sha256=eyMg6wpvDgbcKN7LEbi1rtmCep1JyBNVWTSFcMzZrmY,35478
+transformers/integrations/deepspeed.py,sha256=KlJXDE00l-jfE64MqlUkx4EgSeSz7ZksvAsl96Cus9c,33670
+transformers/integrations/eager_paged.py,sha256=HlcqmSZtvwHzyPtWzO0NeDiy66yZRJVnvoD5ZkQOXAE,3334
+transformers/integrations/eetq.py,sha256=x-zrfBIlJkwJwkNMtHlWmXHZwAtjIwkC6TYIz8Vldok,4849
+transformers/integrations/executorch.py,sha256=J4JmH8bbVtNFyrTgPOyac4_fDBFCyDRvcdO9iiYgH7c,49249
+transformers/integrations/fbgemm_fp8.py,sha256=L7AKJCEJNt3uuPaDP9h7g-3Z70WAgxgaWqTs8CMnbUM,14304
+transformers/integrations/finegrained_fp8.py,sha256=oA45y6zSOQTyoBVJAoqK6H3Kf3tCdD8o_tJ6kTgQsdM,47943
+transformers/integrations/flash_attention.py,sha256=_RjbFbuExqx1sUW-lGKhgiMV-_vav2nZZHAsau9xObk,3499
+transformers/integrations/flash_paged.py,sha256=aoMDemN8_4N63a0X4FaOMyRrfAn8xzt3dwDZu54k3Po,7079
+transformers/integrations/flex_attention.py,sha256=-TocnN46PhtMjo5DI5kh-zECrZbeVUSbnFANHHLTAMw,14658
+transformers/integrations/fouroversix.py,sha256=Ui1AeP3D2mCoc6MVgH8yyaWjuw5QzE0mz5e0bHFCpdM,2966
+transformers/integrations/fp_quant.py,sha256=q62vbWPChHJFVLhZTuh2AGEGXTjSg9HBS2d7c0o8C7I,5807
+transformers/integrations/fsdp.py,sha256=yd1PIBt4d4LlaoV96JWrYEOc0wivcyHfFjozUc-QZgw,3021
+transformers/integrations/gemma_quant.py,sha256=m_bRCd_DVApGlT9bGDr3Zu3PagRFKcEtd1HbR-5xzBc,11075
+transformers/integrations/ggml.py,sha256=5H9mRQmFx2YyqO6CMWdxDcAbWeLt5_xX55aEdZqvYu4,33536
+transformers/integrations/higgs.py,sha256=sCuXXEolpskQAMq26cfet8jivD0xo4rabunGux7jVDU,30612
+transformers/integrations/hqq.py,sha256=GeTogGSqPyrgTvTHzxwt5TZhpc1vRj_lb2DdWy5BKkI,5075
+transformers/integrations/hub_kernels.py,sha256=rcvRxsjrcAZT9Mdwnk6ova7jRSDWfUKrwKqFMzpViw4,27094
+transformers/integrations/integration_utils.py,sha256=RP3do3oHiA7uiteVwOA97eJ3c7TTEvzyJiQSx3GRpD4,117816
+transformers/integrations/liger.py,sha256=zDMJmGnYHUcZxlLIgKOfjg7RavF_nSCM6qvJxD7cZMk,2012
+transformers/integrations/metal_quantization.py,sha256=RMkI9pVPAFe0mJ6lqa9L7kq7h7zDorSTrrIGxWat99Y,10510
+transformers/integrations/mistral.py,sha256=dIlmD952S101yuAW7xVlDkZkRJzNxRqpjGPprMEZ_ro,4714
+transformers/integrations/moe.py,sha256=b9P4T3ATHq8IFMrk8OHD8lX_1rMNHFTQxoy3zAqpiok,27265
+transformers/integrations/msa_attention.py,sha256=0YTO3DA_axq_CvhZmpF85rB86gDAyT6iHdIr7QM81wQ,11005
+transformers/integrations/mxfp4.py,sha256=WSjvledjPTVu3IIf5mNo7uPHREx4svudyG8R9GDZhQY,27744
+transformers/integrations/neftune.py,sha256=1YyICbg6VsIQEnzdBcj3tLUXozmjBufVHf00DsLEoGQ,4352
+transformers/integrations/npu_flash_attention.py,sha256=KNxhY_OkojCP8cQKvPUoOl6pV2IeMv7Vc_C3-xwpzl4,4407
+transformers/integrations/peft.py,sha256=Jq1bhSTb9j_L88RALOlABGD1k1uOUPuiwFz4omhPXUU,53440
+transformers/integrations/quanto.py,sha256=6hTEepeftmrV6M9tmkcp66CZxLgUNo8Ac0gCBqg-XCs,4878
+transformers/integrations/quark.py,sha256=fcHecMlc_-98Aok_70yeluJuT13CoLZcBWPRiVMwwME,1173
+transformers/integrations/sdpa_attention.py,sha256=h_kz0aLYUI31ctpcB0jGskwi_ytiV5aUmVfc2GzFdWQ,4851
+transformers/integrations/sdpa_paged.py,sha256=BBovk8Q4tDw2AQVyUXl4dqXbIyBsLesXXQ5bCWoMdo0,2421
+transformers/integrations/sinq.py,sha256=QHZhvyMzX-2EPpXK7ircYMG0BUd1LQCfDgvfdSrR8Lo,5581
+transformers/integrations/sonicmoe.py,sha256=-cG-fprbxjKNAMsxLSHv-4XQcc3KpTqy90sk4s3sI9E,7310
+transformers/integrations/spqr.py,sha256=YPuXOC0FfS5RFYsJ9JbxhAUs3xDKTToMBLvoSxQxKZU,3306
+transformers/integrations/tensor_parallel.py,sha256=vnDOvwSXUYLsOXFp4djqEUpzIbyUHjHDL2YPQ66o4nw,69353
+transformers/integrations/tiktoken.py,sha256=G3tVAsANX0WyvDx4aNKarPB7l9RNhJ1ghvI7i5cp3qQ,1993
+transformers/integrations/torchao.py,sha256=GO32bV8WUO_aNFfHfjaCS4yLAhxfJnvMHFRn8nlaGWE,10810
+transformers/integrations/tpu.py,sha256=9mL_kSiV1hSj6RMCzllIO1sI54E-G9omWqxCTOXdP-A,9736
+transformers/integrations/vptq.py,sha256=5VngTj5ip6JdWAFgfXY4YdFsaoRpegGzZd8S5zHheVY,3623
+transformers/loss/__init__.py,sha256=qETsqCwayu6Ymj_J4_A_eiwiaMRHQ0noWKM35naanzc,606
+transformers/loss/__pycache__/__init__.cpython-312.pyc,,
+transformers/loss/__pycache__/loss_d_fine.cpython-312.pyc,,
+transformers/loss/__pycache__/loss_deformable_detr.cpython-312.pyc,,
+transformers/loss/__pycache__/loss_deimv2.cpython-312.pyc,,
+transformers/loss/__pycache__/loss_for_object_detection.cpython-312.pyc,,
+transformers/loss/__pycache__/loss_grounding_dino.cpython-312.pyc,,
+transformers/loss/__pycache__/loss_lw_detr.cpython-312.pyc,,
+transformers/loss/__pycache__/loss_rf_detr.cpython-312.pyc,,
+transformers/loss/__pycache__/loss_rnnt.cpython-312.pyc,,
+transformers/loss/__pycache__/loss_rt_detr.cpython-312.pyc,,
+transformers/loss/__pycache__/loss_tdt.cpython-312.pyc,,
+transformers/loss/__pycache__/loss_utils.cpython-312.pyc,,
+transformers/loss/loss_d_fine.py,sha256=fgH4J3v4fvDWNyj_tJMfmzvOe7ZP7Q9V8urQ7YOEZ6w,15820
+transformers/loss/loss_deformable_detr.py,sha256=e9Jc3K5fIygR9xO1kQm1_8FQhVw2GfhkmtaV2SHEbZ0,8134
+transformers/loss/loss_deimv2.py,sha256=A83Lq-5t7yDSFbMCLV7wOCHymFA0GibW2XuZuuYFLYc,12204
+transformers/loss/loss_for_object_detection.py,sha256=i68qif_xh3i4nzqMqMoRjRYMPpQb_AMhuXK5UORb9P4,24347
+transformers/loss/loss_grounding_dino.py,sha256=RZZzjQgZPbLi89rq1iBYBhhzDx89orv4hY03NcVe7TA,12003
+transformers/loss/loss_lw_detr.py,sha256=4W87QoIdnzzPHdHv2kHPg5ZnhtI5psUTLGOmkD4dQ1g,15449
+transformers/loss/loss_rf_detr.py,sha256=PAwxwfxjr5uauJGjNf0YLM71ZJtowYxUtFwuKvMEQjQ,19902
+transformers/loss/loss_rnnt.py,sha256=YJ336IbVIPe_BNepUmyeDOu8Rt7Sl0HDWBluGNADkjA,4018
+transformers/loss/loss_rt_detr.py,sha256=6wQMUD4cDnXZS4iLJ6YO8SuZFfEiFngIy7YSqIj0hrQ,22064
+transformers/loss/loss_tdt.py,sha256=qAD3cEsRA95mrVX_GKEQZOtvwQTgOfUqQwJY-tvsG4M,7372
+transformers/loss/loss_utils.py,sha256=g9sWskzlw6BkIJdiSqmgrn63JEXEHYtNUFmhKYYv274,8540
+transformers/masking_utils.py,sha256=qlJdgA-CSyXL6VQsp8xbNelI58-jF44sDyNWoV_zLfI,75432
+transformers/model_debugging_utils.py,sha256=4ug0HoBDCE0o9gq10ghjFNrq2k4D0cjGtO30IlDLGEQ,17044
+transformers/modelcard.py,sha256=Mb_-Nfm4MCgdb2YIZuxckZMGvlYLAaccv4irTyWepYo,22239
+transformers/modeling_attn_mask_utils.py,sha256=ebFVViMLxu8-v6UMU-jd-RwVhyAt2WX0nHlRmnMG0F8,21843
+transformers/modeling_flash_attention_utils.py,sha256=0H8dIbaJw2JeiW2ZEmAsQQwVabcNblkibY4l5kMAZ4I,38130
+transformers/modeling_gguf_pytorch_utils.py,sha256=vvroFdfkDtRieuvEQ7zOuial4FdV2DCSMC6zpfKX5yw,36000
+transformers/modeling_layers.py,sha256=9WyFP0jx2ahgJqoPiO0cM-YpSD5KhLkzzU3dvLAOFQA,11566
+transformers/modeling_outputs.py,sha256=rkgvacs8OTrOo2mq-okfx9_tNdb8cwl0kuSkbVjPDVY,105688
+transformers/modeling_rope_utils.py,sha256=83DYWIFpwH_FJF3bg9mikoL2cPmNmaTX-oFKd3ZJ89U,58066
+transformers/modeling_utils.py,sha256=mKF_ucWgQSf3cNpNaGkypcUyHPslgzwFffirn5V3zkM,267972
+transformers/models/__init__.py,sha256=3Xqn8vb8B9Pryw1FS-ubz83YhIsSn9NEehDKVb_ce9g,14636
+transformers/models/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/afmoe/__init__.py,sha256=6JBjMRMPG1r9Ivg3wbHIKDaEdBKfqmhPYLJOLz2ZCz0,1009
+transformers/models/afmoe/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/afmoe/__pycache__/configuration_afmoe.cpython-312.pyc,,
+transformers/models/afmoe/__pycache__/modeling_afmoe.cpython-312.pyc,,
+transformers/models/afmoe/__pycache__/modular_afmoe.cpython-312.pyc,,
+transformers/models/afmoe/configuration_afmoe.py,sha256=Sv6BAjFVSOAvcbSO_TJM3xo7WfDUH1vxQPgUbMmfwT8,3940
+transformers/models/afmoe/modeling_afmoe.py,sha256=jN5CpgzNeoUdH2kUJ-Lm0U304kmIIosq54hA9DE9gAI,29467
+transformers/models/afmoe/modular_afmoe.py,sha256=uiqH8Efs3qinvD6kcVl19hFsC4ry2bb-St5QUVkEqH0,17538
+transformers/models/aimv2/__init__.py,sha256=cDli19QT_YABtn4DPLYfoWHtkmOQYGipAgPKGuRje4c,991
+transformers/models/aimv2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/aimv2/__pycache__/configuration_aimv2.cpython-312.pyc,,
+transformers/models/aimv2/__pycache__/modeling_aimv2.cpython-312.pyc,,
+transformers/models/aimv2/__pycache__/modular_aimv2.cpython-312.pyc,,
+transformers/models/aimv2/configuration_aimv2.py,sha256=JDFMwZHa1eqLbxmbuXJ0Np9TqKlp3DdxgLs7gbpCHhg,6537
+transformers/models/aimv2/modeling_aimv2.py,sha256=EatKWJ5TiOLbXbzlarjaw2N2V-K159gUtjxy5l_PL0g,30261
+transformers/models/aimv2/modular_aimv2.py,sha256=wLVGwQr_3g1GmAcmc64M22lDWjBjACBUrk_Y9fxcT1Q,19989
+transformers/models/albert/__init__.py,sha256=hxvpETbDcdrI03UPZb4pTpVbADWISlvpVvoMw-x67mY,1032
+transformers/models/albert/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/albert/__pycache__/configuration_albert.cpython-312.pyc,,
+transformers/models/albert/__pycache__/modeling_albert.cpython-312.pyc,,
+transformers/models/albert/__pycache__/tokenization_albert.cpython-312.pyc,,
+transformers/models/albert/configuration_albert.py,sha256=44Vier1u8Xcg0blto6rta19bCy5ejSI4SZ4T1mEbtCg,2676
+transformers/models/albert/modeling_albert.py,sha256=k7BiXd7kjsmLILI0fil6P-3IN3IWE-br6FHXRdWfhuA,38577
+transformers/models/albert/tokenization_albert.py,sha256=_V2aLl8NT0jldwOocNmjC4G9svDD7UVN6B5Z6ZbfJo8,7737
+transformers/models/align/__init__.py,sha256=QqTKk-Z4BylY6EkBSlYvKXVhT2te-m2Al626OUAz-r4,1027
+transformers/models/align/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/align/__pycache__/configuration_align.cpython-312.pyc,,
+transformers/models/align/__pycache__/modeling_align.cpython-312.pyc,,
+transformers/models/align/__pycache__/processing_align.cpython-312.pyc,,
+transformers/models/align/configuration_align.py,sha256=ja8Rb8fqbDhO6cDfy_quw2U6iit4MuZvNNp4Qwnl5DY,8459
+transformers/models/align/modeling_align.py,sha256=oNK7WBOAfNiwqKhiw_beMZHPTcjBOlRo_--aJaOs-8k,44759
+transformers/models/align/processing_align.py,sha256=oUDbKwqG-ts86VV2V5tY0PbIfGIW1hiBwnkU1j8ljPg,1237
+transformers/models/altclip/__init__.py,sha256=405IijUCYr1EGvOqg1xzds_GHOlxCl0HCsf1rI0wtPY,1033
+transformers/models/altclip/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/altclip/__pycache__/configuration_altclip.cpython-312.pyc,,
+transformers/models/altclip/__pycache__/modeling_altclip.cpython-312.pyc,,
+transformers/models/altclip/__pycache__/modular_altclip.cpython-312.pyc,,
+transformers/models/altclip/__pycache__/processing_altclip.cpython-312.pyc,,
+transformers/models/altclip/configuration_altclip.py,sha256=Gr9WisM8TTl8fL5uHEZIUqbwUKgLI12gKQ3x7f5kpDE,10975
+transformers/models/altclip/modeling_altclip.py,sha256=hR4v1P6NbQIFdmCrwfPIo8CWkALFoXPFxZDeulegH9c,44471
+transformers/models/altclip/modular_altclip.py,sha256=t2qC6EXpCeXGsrcTd_uNI9EYDXoi4P-pfrXb-6b5bvM,20641
+transformers/models/altclip/processing_altclip.py,sha256=tyodo5ptS2sggwrFhAJMWjlia7qrYPNDDeJc4y5mnaY,1000
+transformers/models/apertus/__init__.py,sha256=GthOdmsWx7l04JZ0ucrJtn6ayZzaHRgujOMGUbGdtvY,1256
+transformers/models/apertus/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/apertus/__pycache__/configuration_apertus.cpython-312.pyc,,
+transformers/models/apertus/__pycache__/modeling_apertus.cpython-312.pyc,,
+transformers/models/apertus/__pycache__/modular_apertus.cpython-312.pyc,,
+transformers/models/apertus/configuration_apertus.py,sha256=NPgu_rUhRA8Pn7Eox9j97q30MTKMl8KgEqSvrZuaDC4,4153
+transformers/models/apertus/modeling_apertus.py,sha256=qaBWwJy-kbNjKYDul494kJpZqcbphLDfiJSy54tIS8s,21853
+transformers/models/apertus/modular_apertus.py,sha256=x7jTr8unIeVe8kVnc6zh-6Cd2pW20Lar-pln4q-yGW0,9619
+transformers/models/arcee/__init__.py,sha256=bysIumYEa1Z1bCLBaaP_SCT_6poh8zFLgxt_4Ib-Diw,1009
+transformers/models/arcee/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/arcee/__pycache__/configuration_arcee.cpython-312.pyc,,
+transformers/models/arcee/__pycache__/modeling_arcee.cpython-312.pyc,,
+transformers/models/arcee/__pycache__/modular_arcee.cpython-312.pyc,,
+transformers/models/arcee/configuration_arcee.py,sha256=pDsjY-EDQiEA6fdEuze6OnTnZX_dijuU5Vd-4burl1E,4180
+transformers/models/arcee/modeling_arcee.py,sha256=ETTd6UZKzmOzXIiT-x_PIjmrxj99cInUOk0QnOoQEk0,21682
+transformers/models/arcee/modular_arcee.py,sha256=gY6KPbwq0Qqnw_yDeSGPkageFcJVe0nkw02hdd4KCLQ,3443
+transformers/models/aria/__init__.py,sha256=6rU6o6o4_hbx6hC1EOfF3q19eUOqoptI6mI5fOX5DmY,1111
+transformers/models/aria/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/aria/__pycache__/configuration_aria.cpython-312.pyc,,
+transformers/models/aria/__pycache__/image_processing_aria.cpython-312.pyc,,
+transformers/models/aria/__pycache__/image_processing_pil_aria.cpython-312.pyc,,
+transformers/models/aria/__pycache__/modeling_aria.cpython-312.pyc,,
+transformers/models/aria/__pycache__/modular_aria.cpython-312.pyc,,
+transformers/models/aria/__pycache__/processing_aria.cpython-312.pyc,,
+transformers/models/aria/configuration_aria.py,sha256=1C3zqdhrGkidZPEKt1CMscjVirAczmZ5t0WuPmM2h2k,6423
+transformers/models/aria/image_processing_aria.py,sha256=ZdC_ntrnpReXlyo-W0_pOPUyQ9j9yfCJZFwHf7nthTI,10299
+transformers/models/aria/image_processing_pil_aria.py,sha256=Ygv1ZLwgwxbz83ZBYEGZHo69-A_qCACvD4PV-e5rx4g,9601
+transformers/models/aria/modeling_aria.py,sha256=8zJ8Z--pQjjqQWvWR8M9F24T2l99h_SuoBkTsr4ln3w,49650
+transformers/models/aria/modular_aria.py,sha256=pQdhQKNy9mvgkry-oZ9pSAenetPqNkwJLkWNZDyhCM4,43069
+transformers/models/aria/processing_aria.py,sha256=kPuXyNOiAAkWd_NiuTmguo9RmplSI5r4sDWJffF_nPs,5800
+transformers/models/audio_spectrogram_transformer/__init__.py,sha256=a_YVwB1p4_PPeqPFWqFsGSGSQVTaSUXY0xsOd_Gflqs,1107
+transformers/models/audio_spectrogram_transformer/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/audio_spectrogram_transformer/__pycache__/configuration_audio_spectrogram_transformer.cpython-312.pyc,,
+transformers/models/audio_spectrogram_transformer/__pycache__/feature_extraction_audio_spectrogram_transformer.cpython-312.pyc,,
+transformers/models/audio_spectrogram_transformer/__pycache__/modeling_audio_spectrogram_transformer.cpython-312.pyc,,
+transformers/models/audio_spectrogram_transformer/__pycache__/modular_audio_spectrogram_transformer.cpython-312.pyc,,
+transformers/models/audio_spectrogram_transformer/configuration_audio_spectrogram_transformer.py,sha256=bJx6wRogs4e035k8ubQyTv8T4Xch7Po0rf_QUPmCg4o,2348
+transformers/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.py,sha256=q0lXdJtREwZ0E9zWYtwhKVK5phDSl-i0UV4sqx_x_OQ,9795
+transformers/models/audio_spectrogram_transformer/modeling_audio_spectrogram_transformer.py,sha256=Xvn-HHhHQARTCVwVjHYZGRMiZ4jqofS6avuzeLnnBUc,16212
+transformers/models/audio_spectrogram_transformer/modular_audio_spectrogram_transformer.py,sha256=jnPtHoveV-Ob8IKwgIu7ERoNBpPWZkVP0FJCTarChdI,10316
+transformers/models/audioflamingo3/__init__.py,sha256=IIl7s3NZKsVHtQapt7nCGPMbZ2OhlGsgUe8MPeeKgDE,1085
+transformers/models/audioflamingo3/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/audioflamingo3/__pycache__/configuration_audioflamingo3.cpython-312.pyc,,
+transformers/models/audioflamingo3/__pycache__/modeling_audioflamingo3.cpython-312.pyc,,
+transformers/models/audioflamingo3/__pycache__/modular_audioflamingo3.cpython-312.pyc,,
+transformers/models/audioflamingo3/__pycache__/processing_audioflamingo3.cpython-312.pyc,,
+transformers/models/audioflamingo3/configuration_audioflamingo3.py,sha256=MaxDEazeG4S4qqEw_ZqdvCUjPSKL9jF3AxpBtSZyxXI,4324
+transformers/models/audioflamingo3/modeling_audioflamingo3.py,sha256=bCLBH1x0ooNTLseEfh4vINincKBuWAFYHC5TRsFuFfk,28147
+transformers/models/audioflamingo3/modular_audioflamingo3.py,sha256=KinMSZW2iHg5-UNVbIWoBMy1oxvtDqfYwS0M_XIHnrs,14289
+transformers/models/audioflamingo3/processing_audioflamingo3.py,sha256=CRPwCamaGu0pQ33cFit1TbywbDfGduZRGWbs-df58_s,12263
+transformers/models/auto/__init__.py,sha256=X1F9TGTiKC60ZRJwdrKDzp1SRadfScfXpM5VqoUrk6M,1218
+transformers/models/auto/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/auto/__pycache__/auto_factory.cpython-312.pyc,,
+transformers/models/auto/__pycache__/auto_mappings.cpython-312.pyc,,
+transformers/models/auto/__pycache__/configuration_auto.cpython-312.pyc,,
+transformers/models/auto/__pycache__/feature_extraction_auto.cpython-312.pyc,,
+transformers/models/auto/__pycache__/image_processing_auto.cpython-312.pyc,,
+transformers/models/auto/__pycache__/modeling_auto.cpython-312.pyc,,
+transformers/models/auto/__pycache__/processing_auto.cpython-312.pyc,,
+transformers/models/auto/__pycache__/tokenization_auto.cpython-312.pyc,,
+transformers/models/auto/__pycache__/video_processing_auto.cpython-312.pyc,,
+transformers/models/auto/auto_factory.py,sha256=f5cdZdHL5-3ry1mjdZMH3a_02BrYx5COQXfuGZKO7d0,34071
+transformers/models/auto/auto_mappings.py,sha256=tLLy0jsp6Ifzfywft6CLdI9GUQh-n61EXSqwpGGrWPw,60096
+transformers/models/auto/configuration_auto.py,sha256=QOYsyzva2hfnBR9j21RfqPaClNjxJKpgtM8qM7vfwOU,19424
+transformers/models/auto/feature_extraction_auto.py,sha256=FAxKxIpWNuxanbrzjzr4RKKXTk6gyovl0twWqbmXeLw,18464
+transformers/models/auto/image_processing_auto.py,sha256=R-ns43X5mlvNTGYb261ir4rF6G6El91I14m7wVRoBz4,38681
+transformers/models/auto/modeling_auto.py,sha256=ggZrbBA3cgGQqKIsVMJt4t357vZviJV7pd8wD6-k1G8,107022
+transformers/models/auto/processing_auto.py,sha256=AtPgWfrfxUKu_eaV3AYqHI_s3DijAvGHSIOCFeqAx3I,17937
+transformers/models/auto/tokenization_auto.py,sha256=vjNDReSdtelRR_NPGrj5-gW0ldomlIiOeNPoWybGpM4,47402
+transformers/models/auto/video_processing_auto.py,sha256=7171yMtmC9d5euZkKMZQhbWsz5nLlGLLgpKC5ash7MY,20146
+transformers/models/autoformer/__init__.py,sha256=EzGIA8hECx9XytdzTifaGyGp7hrXqlyP0slqAq8xBNY,1001
+transformers/models/autoformer/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/autoformer/__pycache__/configuration_autoformer.cpython-312.pyc,,
+transformers/models/autoformer/__pycache__/modeling_autoformer.cpython-312.pyc,,
+transformers/models/autoformer/configuration_autoformer.py,sha256=tChcKGhvu5dvKndx8wL4cc2fvu40TAiWuXbMBb0ZNHk,7522
+transformers/models/autoformer/modeling_autoformer.py,sha256=ajjwARmB4fmW5WDgHFYQMNI1QjBfEVFFZpbJ6FYqzsA,90874
+transformers/models/aya_vision/__init__.py,sha256=-DIHmMjkXOyNGbMtZJkHtLiOzdxOYSrKq4_mmR09cfk,1042
+transformers/models/aya_vision/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/aya_vision/__pycache__/configuration_aya_vision.cpython-312.pyc,,
+transformers/models/aya_vision/__pycache__/modeling_aya_vision.cpython-312.pyc,,
+transformers/models/aya_vision/__pycache__/modular_aya_vision.cpython-312.pyc,,
+transformers/models/aya_vision/__pycache__/processing_aya_vision.cpython-312.pyc,,
+transformers/models/aya_vision/configuration_aya_vision.py,sha256=wKdPo9ExeYPKj5ywiBwj5tJxlly5LIYoLeeGC3Q-aV0,3223
+transformers/models/aya_vision/modeling_aya_vision.py,sha256=5JgGiz39aP-2Sb1dlkP0i-b4fPboyUTdPyW98p-haTs,19488
+transformers/models/aya_vision/modular_aya_vision.py,sha256=RVybLSkd6LKFitjocf-zksPqXJqwQhBSBXwd0EQtocY,11113
+transformers/models/aya_vision/processing_aya_vision.py,sha256=oJJyqV64icvuQKS9VAWKYfrIWwBmIG6ROm16R0Ct0j4,7329
+transformers/models/bamba/__init__.py,sha256=gtebRUrAdiwq-rJmlM5qpbtbGEg-xxA3pjivOHJvaRs,1040
+transformers/models/bamba/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/bamba/__pycache__/configuration_bamba.cpython-312.pyc,,
+transformers/models/bamba/__pycache__/modeling_bamba.cpython-312.pyc,,
+transformers/models/bamba/__pycache__/modular_bamba.cpython-312.pyc,,
+transformers/models/bamba/configuration_bamba.py,sha256=W5Th_M57KsU8jIPzNxcCMCcLCZite32HLZWhLDqUSuM,4821
+transformers/models/bamba/modeling_bamba.py,sha256=fzGATGaZ5e6z349nPY3bMgX27jCN4amRI-lYuurC9ls,52541
+transformers/models/bamba/modular_bamba.py,sha256=6ptpcFJWptD-osea1geqsoRIRnUvjgPwFP372oT4sGU,38888
+transformers/models/bark/__init__.py,sha256=fIlOQ6RPBARVhUKdjNx2Nvf09azEI6AiPv3lyWjk0Gc,1024
+transformers/models/bark/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/bark/__pycache__/configuration_bark.cpython-312.pyc,,
+transformers/models/bark/__pycache__/generation_configuration_bark.cpython-312.pyc,,
+transformers/models/bark/__pycache__/modeling_bark.cpython-312.pyc,,
+transformers/models/bark/__pycache__/processing_bark.cpython-312.pyc,,
+transformers/models/bark/configuration_bark.py,sha256=3biyLo7uD6FaHx_7OIOM5cDz1LkcFg2t26Yo5n98b8w,11592
+transformers/models/bark/generation_configuration_bark.py,sha256=_aItFYGQo7FpoRIhWqeyleIlazrOhCBnF4HYq5AViCg,14890
+transformers/models/bark/modeling_bark.py,sha256=8Ao9H7Jzra7IxkS1ztfQxFKXWGrIQO_O3dWpcFdO8P0,66429
+transformers/models/bark/processing_bark.py,sha256=rYETx9rMMnR9vJqMNd-9x3psdIbdzEz2Wh8c3BbLd8k,15537
+transformers/models/bart/__init__.py,sha256=S_TylapQzJgRn1IAHgBjIlpDKOUiRDrWXvXbf-72BQc,1070
+transformers/models/bart/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/bart/__pycache__/configuration_bart.cpython-312.pyc,,
+transformers/models/bart/__pycache__/modeling_bart.cpython-312.pyc,,
+transformers/models/bart/__pycache__/tokenization_bart.cpython-312.pyc,,
+transformers/models/bart/configuration_bart.py,sha256=DkTk87oL7YtVvGxw8Bp0jU3ye6IcIhxehVjKOvYtkxQ,2995
+transformers/models/bart/modeling_bart.py,sha256=iy2ZhYWglZZ6ctJ_w_br6WwOixklbn8iuyV32YvFiFo,55443
+transformers/models/bart/tokenization_bart.py,sha256=DnPB-2ksaq1XKX-4IC6iQ-B5fPUsErQVrDPn_4R7X8A,827
+transformers/models/barthez/__init__.py,sha256=LJe6JwskLg0PCFB6QkvMYXdiQ8ofaLI5NrfeQD0NHGE,958
+transformers/models/barthez/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/barthez/__pycache__/tokenization_barthez.cpython-312.pyc,,
+transformers/models/barthez/tokenization_barthez.py,sha256=SJ-XLtE6H58H5zU5oJWvtiigDaJs6Uzc9B-5VUIpYIA,6111
+transformers/models/bartpho/__init__.py,sha256=DN0zgU4dM841Kqqo6wN8FpWFeWYHCBxIq3lxrg5vUoU,958
+transformers/models/bartpho/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/bartpho/__pycache__/tokenization_bartpho.cpython-312.pyc,,
+transformers/models/bartpho/tokenization_bartpho.py,sha256=K6XSQKIJPKdkwmLtnmXzFHfpo-vzamVIYx_nKfHL70c,14255
+transformers/models/beit/__init__.py,sha256=WcaET85YL0xJDPLM68Nc9pw1JVWd-1dz4xD13nZedJQ,1075
+transformers/models/beit/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/beit/__pycache__/configuration_beit.cpython-312.pyc,,
+transformers/models/beit/__pycache__/image_processing_beit.cpython-312.pyc,,
+transformers/models/beit/__pycache__/image_processing_pil_beit.cpython-312.pyc,,
+transformers/models/beit/__pycache__/modeling_beit.cpython-312.pyc,,
+transformers/models/beit/__pycache__/modular_beit.cpython-312.pyc,,
+transformers/models/beit/configuration_beit.py,sha256=g_n-zTCiB-uCvIZWLi-6Zu4p40Pa5WTU19oEcjwjrHQ,5711
+transformers/models/beit/image_processing_beit.py,sha256=6XhZTmYBslgfZS3Gu_wuBCweBLMNSLqgBGnSo9_2WeA,9253
+transformers/models/beit/image_processing_pil_beit.py,sha256=ybwA98YA-alZgC6vHv2PtcyzZPVTNv5zKqbIZY3KDqQ,7890
+transformers/models/beit/modeling_beit.py,sha256=kPyQco0yPO4C7MjoLJRhiTmFxMp4LvHKUg6VFpDJpq8,47691
+transformers/models/beit/modular_beit.py,sha256=eZP2qsU2RjsH4KOhQk7_sQ5CsrbNcrUHppDEyU5nwUI,38600
+transformers/models/bert/__init__.py,sha256=8wed5_ySi76CWDslJ4BoPdgV2Yg_TJ0vJjlDgbNKUMo,1026
+transformers/models/bert/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/bert/__pycache__/configuration_bert.cpython-312.pyc,,
+transformers/models/bert/__pycache__/modeling_bert.cpython-312.pyc,,
+transformers/models/bert/__pycache__/tokenization_bert.cpython-312.pyc,,
+transformers/models/bert/__pycache__/tokenization_bert_legacy.cpython-312.pyc,,
+transformers/models/bert/configuration_bert.py,sha256=dXFZFILLNIiW5GeJ8nIyXKs4oCJbEsHGWl1Nu9zfkTs,2194
+transformers/models/bert/modeling_bert.py,sha256=7c21WK2Dj3zcgTHcOGl8kuT2eGWSUEr0fHKqIJs-4F0,55970
+transformers/models/bert/tokenization_bert.py,sha256=_2q3IUx7jtwz4EWFy6_6veCB9TZBofFlDQgDqR740Cg,6075
+transformers/models/bert/tokenization_bert_legacy.py,sha256=ReTGY8HTxwQSPRvp0Q_9EQCmMtXn-RERINT8f7xNin4,19727
+transformers/models/bert_generation/__init__.py,sha256=sLEyyFf2yI6QflP1lTI9LXUF5PvWBvu-fsaFbjund5I,1059
+transformers/models/bert_generation/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/bert_generation/__pycache__/configuration_bert_generation.cpython-312.pyc,,
+transformers/models/bert_generation/__pycache__/modeling_bert_generation.cpython-312.pyc,,
+transformers/models/bert_generation/__pycache__/tokenization_bert_generation.cpython-312.pyc,,
+transformers/models/bert_generation/configuration_bert_generation.py,sha256=_pQnZ42pBWhwUDjTXM3FucsyM_639Kri17HOHTXQQDg,2073
+transformers/models/bert_generation/modeling_bert_generation.py,sha256=ZuiIWr1l1mGDRA4Klsix2T4kvz_WqQpOEMVVoTbBzro,29491
+transformers/models/bert_generation/tokenization_bert_generation.py,sha256=y8DaWI_h6ETCn27QThQ2ciu2V4JKgEsaXUNgC0QNlNQ,4342
+transformers/models/bert_japanese/__init__.py,sha256=94xfgVPnIQuHQxvmc55_EedJlJQTnHiL4va6Ry6x3LE,964
+transformers/models/bert_japanese/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/bert_japanese/__pycache__/tokenization_bert_japanese.cpython-312.pyc,,
+transformers/models/bert_japanese/tokenization_bert_japanese.py,sha256=jkBjaGI_BaR33MlOniWhh1PSt3vehied8hXRbS4mYEo,35322
+transformers/models/bertweet/__init__.py,sha256=EZegs0rWTTCiOC_eY-M8eV7bCcwU60dB0HsM1S1VDzQ,959
+transformers/models/bertweet/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/bertweet/__pycache__/tokenization_bertweet.cpython-312.pyc,,
+transformers/models/bertweet/tokenization_bertweet.py,sha256=2wVAfZKa_0vdlUG-CCVxygWZxrCKS6PAhKJrJqPWJXs,24387
+transformers/models/big_bird/__init__.py,sha256=VAC27mMypSm_-3AEQ179PtQF1Dpq4XNnhs29j6n5KyU,1038
+transformers/models/big_bird/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/big_bird/__pycache__/configuration_big_bird.cpython-312.pyc,,
+transformers/models/big_bird/__pycache__/modeling_big_bird.cpython-312.pyc,,
+transformers/models/big_bird/__pycache__/tokenization_big_bird.cpython-312.pyc,,
+transformers/models/big_bird/configuration_big_bird.py,sha256=PHs-bfE01aMWglom73ijXTW5oY4YEZJPXMkbge2DEdk,3186
+transformers/models/big_bird/modeling_big_bird.py,sha256=Eu-n1iVvFhxS48zdglSq4K5vQ3QatMoocg2Oq5V2sMI,112197
+transformers/models/big_bird/tokenization_big_bird.py,sha256=mTVWymvsL_HJ0UYDkF99iVcC_aY4HH2Kku2MJ8u1Mys,7521
+transformers/models/bigbird_pegasus/__init__.py,sha256=7zOl1EhO8W2S9jE0FsyEoW8kV6yn5bLA0dspGFM1mLQ,1011
+transformers/models/bigbird_pegasus/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/bigbird_pegasus/__pycache__/configuration_bigbird_pegasus.cpython-312.pyc,,
+transformers/models/bigbird_pegasus/__pycache__/modeling_bigbird_pegasus.cpython-312.pyc,,
+transformers/models/bigbird_pegasus/configuration_bigbird_pegasus.py,sha256=bJ7z_65m1C8SdBHmcvMoHZbu-4RH9kiD6wvamHPYec0,3530
+transformers/models/bigbird_pegasus/modeling_bigbird_pegasus.py,sha256=VCF9kQmP_xlGsnvIkEWMg0LUahieZrIn6FO35YnO9w4,110015
+transformers/models/biogpt/__init__.py,sha256=pZxVjmVzt7FXlkMO_5fMg01eyPvvHYXmDA33MKhp6Yk,1032
+transformers/models/biogpt/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/biogpt/__pycache__/configuration_biogpt.cpython-312.pyc,,
+transformers/models/biogpt/__pycache__/modeling_biogpt.cpython-312.pyc,,
+transformers/models/biogpt/__pycache__/modular_biogpt.cpython-312.pyc,,
+transformers/models/biogpt/__pycache__/tokenization_biogpt.cpython-312.pyc,,
+transformers/models/biogpt/configuration_biogpt.py,sha256=sK3cSyvs1u7Ir80Yof3jKfJb6Z7KsboVXVny5JXK1o4,2053
+transformers/models/biogpt/modeling_biogpt.py,sha256=hSTaFKtMzq5xMljXEeo7ulyzcq4aZEjv28e5G3Mejn0,27839
+transformers/models/biogpt/modular_biogpt.py,sha256=51RfMQHfiaSinSa2mXxdic4zi3tec1nKwi2xebBoOrk,19918
+transformers/models/biogpt/tokenization_biogpt.py,sha256=Tg8IQ6ZhPb7eT_sdrLJBgPb2t0cNQ12Hb70yNjUnXIc,12106
+transformers/models/bit/__init__.py,sha256=urgMFBP18CdV4ytHh32_D3WOjFX7YFZZL9Rxtq5AO48,1071
+transformers/models/bit/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/bit/__pycache__/configuration_bit.cpython-312.pyc,,
+transformers/models/bit/__pycache__/image_processing_bit.cpython-312.pyc,,
+transformers/models/bit/__pycache__/image_processing_pil_bit.cpython-312.pyc,,
+transformers/models/bit/__pycache__/modeling_bit.cpython-312.pyc,,
+transformers/models/bit/configuration_bit.py,sha256=qbeKU3uEFL1Bjv9kNBIn8WGozqw7VAuPOTaXIyJclGE,3670
+transformers/models/bit/image_processing_bit.py,sha256=Yq0Q3pkpywpXItmpyT2Q5qOPfkwFtQgR2Ekvse1A8us,1260
+transformers/models/bit/image_processing_pil_bit.py,sha256=oRQ3Mib0t2ZECGdMalhVEOqKT1VSgmWCfDa5xA93urY,1250
+transformers/models/bit/modeling_bit.py,sha256=2sU71UdHn4_kXW4EeKvg-08Xk_4SNjuwb4RJt-t0VOY,28228
+transformers/models/bitnet/__init__.py,sha256=0u3B40Xd6dJ7J7TBxJzSQWcyUe2ZWJTbT6iaWVod_-A,1018
+transformers/models/bitnet/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/bitnet/__pycache__/configuration_bitnet.cpython-312.pyc,,
+transformers/models/bitnet/__pycache__/modeling_bitnet.cpython-312.pyc,,
+transformers/models/bitnet/__pycache__/modular_bitnet.cpython-312.pyc,,
+transformers/models/bitnet/configuration_bitnet.py,sha256=HAP0ulv40amjTh73v4Oz29a8V17RRI9nc_jzJHyCGKo,2336
+transformers/models/bitnet/modeling_bitnet.py,sha256=ojdBxZaWq5KlPbKLaXo85UQA-v0wEiKlOleM8HKl1Hw,21848
+transformers/models/bitnet/modular_bitnet.py,sha256=5rhqgIIIBlyJArm2Z0_vRgkwDX2TWZuw_O00Ldl-a3g,5418
+transformers/models/blenderbot/__init__.py,sha256=jU3e_DqjuRka882xLbvHUibBwY6ODhrBxmwP08UiLFg,1044
+transformers/models/blenderbot/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/blenderbot/__pycache__/configuration_blenderbot.cpython-312.pyc,,
+transformers/models/blenderbot/__pycache__/modeling_blenderbot.cpython-312.pyc,,
+transformers/models/blenderbot/__pycache__/tokenization_blenderbot.cpython-312.pyc,,
+transformers/models/blenderbot/configuration_blenderbot.py,sha256=pUtS9Y-K6uqCWtFaPCZ737q7v2uHcq2gYhGP0lEsuzs,2756
+transformers/models/blenderbot/modeling_blenderbot.py,sha256=YAzikUVS_nIQ2C_dtHIumFzvSNlaVkdvujG92jPQQCk,42685
+transformers/models/blenderbot/tokenization_blenderbot.py,sha256=4BEnkpqvtf6_xwlnfVtHGZPe2fjSfuIyGKjiHBmOZ1w,6884
+transformers/models/blenderbot_small/__init__.py,sha256=d6Zj-S0-76DHKXAjwOdnyU3j2rtUDyktiXP_y0It9l8,1116
+transformers/models/blenderbot_small/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/blenderbot_small/__pycache__/configuration_blenderbot_small.cpython-312.pyc,,
+transformers/models/blenderbot_small/__pycache__/modeling_blenderbot_small.cpython-312.pyc,,
+transformers/models/blenderbot_small/__pycache__/tokenization_blenderbot_small.cpython-312.pyc,,
+transformers/models/blenderbot_small/configuration_blenderbot_small.py,sha256=ofbrcALppVMgmkcA6DRUcvIDzqa4mOAT8Es98zSgooc,2655
+transformers/models/blenderbot_small/modeling_blenderbot_small.py,sha256=BoyG-wXXsXuOedAsyGgsLh88I6S1Wa2ZIhOQ3O0rFHU,40891
+transformers/models/blenderbot_small/tokenization_blenderbot_small.py,sha256=R7MeZBgkSaOAXd7_TDdk4sOBIibYrzN4xElF8y4GS-Q,7944
+transformers/models/blip/__init__.py,sha256=iYJ44w_U0ByI86VqYE__vKj0b1_oxG7Y-k_LGnpyTXo,1148
+transformers/models/blip/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/blip/__pycache__/configuration_blip.cpython-312.pyc,,
+transformers/models/blip/__pycache__/image_processing_blip.cpython-312.pyc,,
+transformers/models/blip/__pycache__/image_processing_pil_blip.cpython-312.pyc,,
+transformers/models/blip/__pycache__/modeling_blip.cpython-312.pyc,,
+transformers/models/blip/__pycache__/modeling_blip_text.cpython-312.pyc,,
+transformers/models/blip/__pycache__/processing_blip.cpython-312.pyc,,
+transformers/models/blip/configuration_blip.py,sha256=cehePZjTcZ3tuPX-T678HjmPjBoUAHmkgo0xcPF4yIM,6482
+transformers/models/blip/image_processing_blip.py,sha256=tjR9ixW0tSr0CRf-amyHyto1jgpNHotJ9VBmSgZAUDM,1197
+transformers/models/blip/image_processing_pil_blip.py,sha256=URcuftUWpEfh95QChQ3zQz_0mo0vgZAKDUq7YsBQaWI,1187
+transformers/models/blip/modeling_blip.py,sha256=UmV0x-GaFVe3fJGci5HiEfIWWQUKpFy-9w8a478JpQk,51496
+transformers/models/blip/modeling_blip_text.py,sha256=OWv98ZFMBNnqSWhLjOgk10_3J_YE8k-l3gmKB-XKzE8,31170
+transformers/models/blip/processing_blip.py,sha256=WdIeo2VsuxVIPNqPEZh2k_RGqAVI_-DFf-gmWcrP_qc,1586
+transformers/models/blip_2/__init__.py,sha256=kj_6H0rQ7dLoQk-COIb06LlDRnbORu3GLU3m4EdMkAM,1030
+transformers/models/blip_2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/blip_2/__pycache__/configuration_blip_2.cpython-312.pyc,,
+transformers/models/blip_2/__pycache__/modeling_blip_2.cpython-312.pyc,,
+transformers/models/blip_2/__pycache__/processing_blip_2.cpython-312.pyc,,
+transformers/models/blip_2/configuration_blip_2.py,sha256=GEdkxJaUUvqdgkHfuqzX82bbFyVXvvVlhTJ7tIQme3w,7170
+transformers/models/blip_2/modeling_blip_2.py,sha256=-60iDMy_kFwBGypy6M_J-6WFL_x0R_axzI6dZEq0ElI,84219
+transformers/models/blip_2/processing_blip_2.py,sha256=5VOE__t-z0fuNCxpKcDJXOH8bqpKACIsCMwvADd856Q,4813
+transformers/models/bloom/__init__.py,sha256=hVsmMQEVK2LVTQd_zlExF9SJjdMLX7pjgFVP6lKg2IY,1029
+transformers/models/bloom/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/bloom/__pycache__/configuration_bloom.cpython-312.pyc,,
+transformers/models/bloom/__pycache__/modeling_bloom.cpython-312.pyc,,
+transformers/models/bloom/configuration_bloom.py,sha256=KRjVQUwPtCh9-T8wmjSH5KpJgtyQixHCqmh1c6_7Xvo,3203
+transformers/models/bloom/modeling_bloom.py,sha256=HcqX8zbYvAdHp7nJI02pAEw1FunnKn31nZ4yjqGVbKU,41542
+transformers/models/blt/__init__.py,sha256=Eg5lWtgdEQ8Yld6WH0R7-x3R6hnVQJFqUMEuAooZOyo,1023
+transformers/models/blt/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/blt/__pycache__/configuration_blt.cpython-312.pyc,,
+transformers/models/blt/__pycache__/modeling_blt.cpython-312.pyc,,
+transformers/models/blt/__pycache__/modular_blt.cpython-312.pyc,,
+transformers/models/blt/configuration_blt.py,sha256=qY17NPRQbkx3ZjNW2u6eEacwwKLfolMDRuXxJFJ1bBE,11647
+transformers/models/blt/modeling_blt.py,sha256=g1TKXKqByQJA5zr7cRZxeWePxHp3LHRNKoezxCJccVU,63279
+transformers/models/blt/modular_blt.py,sha256=a-FBpLNh7z0vt1rryzG3WkQQ-VINUFc6NNa2-A4tbOk,50179
+transformers/models/bridgetower/__init__.py,sha256=1VbGQaGDaKOIxQ27aFOAgX7vkrAwmUUNfOpTuJrankY,1145
+transformers/models/bridgetower/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/bridgetower/__pycache__/configuration_bridgetower.cpython-312.pyc,,
+transformers/models/bridgetower/__pycache__/image_processing_bridgetower.cpython-312.pyc,,
+transformers/models/bridgetower/__pycache__/image_processing_pil_bridgetower.cpython-312.pyc,,
+transformers/models/bridgetower/__pycache__/modeling_bridgetower.cpython-312.pyc,,
+transformers/models/bridgetower/__pycache__/processing_bridgetower.cpython-312.pyc,,
+transformers/models/bridgetower/configuration_bridgetower.py,sha256=chB_NPhsYNSgk7vj-n5URTy5HKTdslufm3FuKHPSJNU,6042
+transformers/models/bridgetower/image_processing_bridgetower.py,sha256=obx55NQdY7ukNHkADg75-KlwWamgLSiIFttCRJN9YUk,6823
+transformers/models/bridgetower/image_processing_pil_bridgetower.py,sha256=l9Q4pfFZlowgiESwOBCLCGzRxC-EeDsmC_vReHBh1yE,5711
+transformers/models/bridgetower/modeling_bridgetower.py,sha256=nAREsxw27-T1Lt_J2q58sSF3ctgYrbPm9laWdOxUDfA,76187
+transformers/models/bridgetower/processing_bridgetower.py,sha256=pPLA_1cSpsz5S6BfddtG4JSdJdN4pWlP89mksXfGRsQ,1617
+transformers/models/bros/__init__.py,sha256=wT0avJ_J50-WK6jOB-6UbgN5kjHiBwG-NNT_iefMXr8,1024
+transformers/models/bros/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/bros/__pycache__/configuration_bros.cpython-312.pyc,,
+transformers/models/bros/__pycache__/modeling_bros.cpython-312.pyc,,
+transformers/models/bros/__pycache__/processing_bros.cpython-312.pyc,,
+transformers/models/bros/configuration_bros.py,sha256=ErWg2sXzCZS2WcWXzmrHthQECfHwPShRjpmet7fmOuU,2770
+transformers/models/bros/modeling_bros.py,sha256=iO41PFt9Tdt-y2moK7PX1upBm3XTCsLVQTQGxq1LeTw,39893
+transformers/models/bros/processing_bros.py,sha256=dUxWojDc6X766HgXqRFZxb7PeJ8q_sKs1krsZSPhyWw,1467
+transformers/models/byt5/__init__.py,sha256=O7yXvHyqMZ7stkKX67knnddmJ81pPHoKrY_7NCAauU4,955
+transformers/models/byt5/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/byt5/__pycache__/tokenization_byt5.cpython-312.pyc,,
+transformers/models/byt5/tokenization_byt5.py,sha256=hAt4Eic6Hgb8HBKwDq_Tg1MZmWhRtgYXaNRUFFGz6kw,9992
+transformers/models/camembert/__init__.py,sha256=-akJBxnuua6C8t5logymVZJ5dvX9-5ADk93h0cU3d64,1041
+transformers/models/camembert/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/camembert/__pycache__/configuration_camembert.cpython-312.pyc,,
+transformers/models/camembert/__pycache__/modeling_camembert.cpython-312.pyc,,
+transformers/models/camembert/__pycache__/modular_camembert.cpython-312.pyc,,
+transformers/models/camembert/__pycache__/tokenization_camembert.cpython-312.pyc,,
+transformers/models/camembert/configuration_camembert.py,sha256=NeWLj5s-kKIV_RLuMeRcWNpehTZOHJDRH7XQR0Yl9vA,2208
+transformers/models/camembert/modeling_camembert.py,sha256=WPmsoNfYinYDGtlKx1aBJpRVm3pGsMY15TMrbz2sYGw,53689
+transformers/models/camembert/modular_camembert.py,sha256=d5vF8H4eT-lvxna643S7vcj2dxap5oXq20vPUUk9SoU,22752
+transformers/models/camembert/tokenization_camembert.py,sha256=pnUHPAJBqhagZFHuUu8lEt_7HlWmnIwTaTQHRViJ59U,7321
+transformers/models/canine/__init__.py,sha256=ThkEqO6wPzWCnAplx0EWCUqVaKKsNYQKXQhWfTblEBU,1032
+transformers/models/canine/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/canine/__pycache__/configuration_canine.cpython-312.pyc,,
+transformers/models/canine/__pycache__/modeling_canine.cpython-312.pyc,,
+transformers/models/canine/__pycache__/tokenization_canine.cpython-312.pyc,,
+transformers/models/canine/configuration_canine.py,sha256=_kNgdVl6b1BtrF_UKwD0e77DvY2GFZyCPgUtO4LWb6I,2998
+transformers/models/canine/modeling_canine.py,sha256=dfkM2prveD9fpJoWfJ5Ok6uhR2wqKSvVVSq3ZSt8_iA,58907
+transformers/models/canine/tokenization_canine.py,sha256=hoJ8hVXuy7aibySanfuOdbOV6aOt43myk_jounws-OY,5932
+transformers/models/chameleon/__init__.py,sha256=Z742bkmnd-loagC2_wFYkom6iw9-0EBdoqXLL8sz0K8,1135
+transformers/models/chameleon/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/chameleon/__pycache__/configuration_chameleon.cpython-312.pyc,,
+transformers/models/chameleon/__pycache__/image_processing_chameleon.cpython-312.pyc,,
+transformers/models/chameleon/__pycache__/image_processing_pil_chameleon.cpython-312.pyc,,
+transformers/models/chameleon/__pycache__/modeling_chameleon.cpython-312.pyc,,
+transformers/models/chameleon/__pycache__/processing_chameleon.cpython-312.pyc,,
+transformers/models/chameleon/configuration_chameleon.py,sha256=Posz0-mHnbdMzstpWfpi3kr_8ggTve5k2MU4whZl_ic,4810
+transformers/models/chameleon/image_processing_chameleon.py,sha256=PoNhdq7jsfw54CRVbjU93-S2SWMstjNLZR15rFW2ZIw,2491
+transformers/models/chameleon/image_processing_pil_chameleon.py,sha256=RpGGUv_-piLaG7u5CiLyCRIgfMQPA-7RBs15Sqd45D8,2424
+transformers/models/chameleon/modeling_chameleon.py,sha256=zpLPVic5nUXVWfiVH9BJq5-GZVAgrOLgc88dlaeTlGY,49118
+transformers/models/chameleon/processing_chameleon.py,sha256=I_1z7yNoGVaQeU6lEY3Naem2sJF3D-ATKlpbcKU6cTw,5667
+transformers/models/chinese_clip/__init__.py,sha256=Q7FD6phmNUc_UsRF6q8ZcU6XNPdD5vHPHskl47avitM,1150
+transformers/models/chinese_clip/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/chinese_clip/__pycache__/configuration_chinese_clip.cpython-312.pyc,,
+transformers/models/chinese_clip/__pycache__/image_processing_chinese_clip.cpython-312.pyc,,
+transformers/models/chinese_clip/__pycache__/image_processing_pil_chinese_clip.cpython-312.pyc,,
+transformers/models/chinese_clip/__pycache__/modeling_chinese_clip.cpython-312.pyc,,
+transformers/models/chinese_clip/__pycache__/modular_chinese_clip.cpython-312.pyc,,
+transformers/models/chinese_clip/__pycache__/processing_chinese_clip.cpython-312.pyc,,
+transformers/models/chinese_clip/configuration_chinese_clip.py,sha256=w841mEF_ZFSVgq71kz8RA4MVaQKI2_cNmnPNMpoA_pM,11460
+transformers/models/chinese_clip/image_processing_chinese_clip.py,sha256=f1IO0LaD8Aghx7HHnlhj_eQQIIzeVTMG-XCMjCZ2-Qc,1285
+transformers/models/chinese_clip/image_processing_pil_chinese_clip.py,sha256=JzCiisQPRle-SwCPAaLVYlw6hnZaaE8rA5Kz2By9GJU,1275
+transformers/models/chinese_clip/modeling_chinese_clip.py,sha256=7qcbToT0GXfLDbL9XbJ5cidnnQmyriSKcH_DK7vg7b4,40573
+transformers/models/chinese_clip/modular_chinese_clip.py,sha256=CncXgOMT0G8cwfEUM7Tn7dpelOle99xlyjFkzbaKsSc,19665
+transformers/models/chinese_clip/processing_chinese_clip.py,sha256=JAPbqZs4NVJCTDXTRh8kZvKh0IPxNG5CU_nKKQRgrp0,995
+transformers/models/chmv2/__init__.py,sha256=Z2gYV0EXwegR1V-AfD2wK0_8sNXS0Vk_FZccxOWp7IM,1038
+transformers/models/chmv2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/chmv2/__pycache__/configuration_chmv2.cpython-312.pyc,,
+transformers/models/chmv2/__pycache__/image_processing_chmv2.cpython-312.pyc,,
+transformers/models/chmv2/__pycache__/modeling_chmv2.cpython-312.pyc,,
+transformers/models/chmv2/__pycache__/modular_chmv2.cpython-312.pyc,,
+transformers/models/chmv2/configuration_chmv2.py,sha256=Y-iDsMP7tSMKVKo1kkiVIrC-QBouvMYYlVt0qcOCWmw,5533
+transformers/models/chmv2/image_processing_chmv2.py,sha256=Z9Ads9JEtHhMEW9RID3wFs_mf5uOyJ1Qe-9vMwLvee8,17254
+transformers/models/chmv2/modeling_chmv2.py,sha256=znvwRZbQQs6aDVe5bJ87Ni-5znug2KlQfqVAq84fQeA,17070
+transformers/models/chmv2/modular_chmv2.py,sha256=cxDNVyuGB94R263J3yqR4wmREdcLwiUryclLMH0Bryg,21501
+transformers/models/clap/__init__.py,sha256=751udHbsD7FBLGAByjx_8Z4XPLly1MaQQ4wKN_9vbOY,1067
+transformers/models/clap/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/clap/__pycache__/configuration_clap.cpython-312.pyc,,
+transformers/models/clap/__pycache__/feature_extraction_clap.cpython-312.pyc,,
+transformers/models/clap/__pycache__/modeling_clap.cpython-312.pyc,,
+transformers/models/clap/__pycache__/processing_clap.cpython-312.pyc,,
+transformers/models/clap/configuration_clap.py,sha256=S3ihHOfFp3-zpXD0vnOuS2pbt_P4GBPfQgfWPPXOEsg,7732
+transformers/models/clap/feature_extraction_clap.py,sha256=orx0svfj0Ru3BLnnaZcF4tW_5iQAN18YAg3ab3OC20U,18699
+transformers/models/clap/modeling_clap.py,sha256=bOg90SNmhvvq69ZL_qjNm3bkr03IaQZ_rzae6uOZyQg,74131
+transformers/models/clap/processing_clap.py,sha256=f85IpsPResgKvu7LTfKRuVG3ny-J57bRzpDlfN6Y_aE,961
+transformers/models/clip/__init__.py,sha256=Ntt3_IUTJFYmrbPYZygh5f73r3nWk-mbDmkrpCVt6tk,1147
+transformers/models/clip/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/clip/__pycache__/configuration_clip.cpython-312.pyc,,
+transformers/models/clip/__pycache__/image_processing_clip.cpython-312.pyc,,
+transformers/models/clip/__pycache__/image_processing_pil_clip.cpython-312.pyc,,
+transformers/models/clip/__pycache__/modeling_clip.cpython-312.pyc,,
+transformers/models/clip/__pycache__/processing_clip.cpython-312.pyc,,
+transformers/models/clip/__pycache__/tokenization_clip.cpython-312.pyc,,
+transformers/models/clip/configuration_clip.py,sha256=g2Pejg-67GPPkY56X8s3JTN-GDerQqKO1NUPlaaiSjk,10674
+transformers/models/clip/image_processing_clip.py,sha256=8Ac3Ua7AXxhfRzRfkFEOSOpOoJCJugvgFzAAuwgDIJ4,1676
+transformers/models/clip/image_processing_pil_clip.py,sha256=JS4Qh2GV8NgAotDtubBUc5VWwD5Kceaj-kqFMnr5LyQ,1666
+transformers/models/clip/modeling_clip.py,sha256=RutqNSPJ56GIFzp9p2PEdr0foeMSH44cp7e5wIZVzi8,39599
+transformers/models/clip/processing_clip.py,sha256=Um6KNOUZ3pksQqCKrMbAXqaJewINGkmH2E5qkY78czI,928
+transformers/models/clip/tokenization_clip.py,sha256=-1M4oNko3rlHC8hNSTL7LWRWYR8c4U_xFAjMPsbwHvc,5202
+transformers/models/clipseg/__init__.py,sha256=12Y-b3sRDKM3Hy8-6rK4GUF2a91V1S3nLUF7559AALw,1033
+transformers/models/clipseg/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/clipseg/__pycache__/configuration_clipseg.cpython-312.pyc,,
+transformers/models/clipseg/__pycache__/modeling_clipseg.cpython-312.pyc,,
+transformers/models/clipseg/__pycache__/modular_clipseg.cpython-312.pyc,,
+transformers/models/clipseg/__pycache__/processing_clipseg.cpython-312.pyc,,
+transformers/models/clipseg/configuration_clipseg.py,sha256=7jiI_auCChCpViYgtgjzEpiXMyKtK2FSdgdhiPv9T4k,12069
+transformers/models/clipseg/modeling_clipseg.py,sha256=0BL1Q99-LoXqu-jhv-_ZaVuXzb4fO2HswhVXPXuidb8,46243
+transformers/models/clipseg/modular_clipseg.py,sha256=L3G4PF6jkoor2K5q5PvhNV7bLILOG_9uYpYcUunaMRA,26701
+transformers/models/clipseg/processing_clipseg.py,sha256=LwTtI7ddVol3tUk8IhkSwCheSSmRBD5OFqW7ssGzpaQ,3932
+transformers/models/clvp/__init__.py,sha256=RRnPofxkr_llgSxCP9tcAhu3xCR7E_m1PkrHv7KLMzo,1104
+transformers/models/clvp/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/clvp/__pycache__/configuration_clvp.cpython-312.pyc,,
+transformers/models/clvp/__pycache__/feature_extraction_clvp.cpython-312.pyc,,
+transformers/models/clvp/__pycache__/modeling_clvp.cpython-312.pyc,,
+transformers/models/clvp/__pycache__/number_normalizer.cpython-312.pyc,,
+transformers/models/clvp/__pycache__/processing_clvp.cpython-312.pyc,,
+transformers/models/clvp/__pycache__/tokenization_clvp.cpython-312.pyc,,
+transformers/models/clvp/configuration_clvp.py,sha256=XPLgqSOthBbWDkvs8jnJ2NDuNvPIq_8EXIemNCUNMgg,10568
+transformers/models/clvp/feature_extraction_clvp.py,sha256=5v9w0dCsEF9UVvpMvt98OkBbdRBbAZbuh28DiJmdgxE,10851
+transformers/models/clvp/modeling_clvp.py,sha256=yoRqsXQgNLrYV8ORlBiVmhCx0Js-_AKvC0ErQYlucMU,74126
+transformers/models/clvp/number_normalizer.py,sha256=KLJC2bIft4UKZrQVM8zisA70vOeJlHI1jtbV1xVIjd8,8918
+transformers/models/clvp/processing_clvp.py,sha256=1u5mgmf1tmUdDwITZUG_GTbon6TTOcZNCa7Ek5Cr2EY,1345
+transformers/models/clvp/tokenization_clvp.py,sha256=om3tlQSKLb-fasG20VMamRMrxTAszRcxJ2PtMYA6Vfo,10181
+transformers/models/code_llama/__init__.py,sha256=vitmyj4qzyn4U2NOEZcp0LhLYGSN4PWHXm8L_UCbvsU,961
+transformers/models/code_llama/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/code_llama/__pycache__/tokenization_code_llama.cpython-312.pyc,,
+transformers/models/code_llama/tokenization_code_llama.py,sha256=Dc-FsYs5EItOG3d1B3VCTDjFzA82xYHYh-uAm37nEFQ,15116
+transformers/models/codegen/__init__.py,sha256=KofDAB0YGRrmc5s6s8TS9ColIyx-a6_AUeBzZbTQqrY,1114
+transformers/models/codegen/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/codegen/__pycache__/configuration_codegen.cpython-312.pyc,,
+transformers/models/codegen/__pycache__/modeling_codegen.cpython-312.pyc,,
+transformers/models/codegen/__pycache__/tokenization_codegen.cpython-312.pyc,,
+transformers/models/codegen/configuration_codegen.py,sha256=M17tNFLct0hCmfqPWIb8pAogtVhrYM4HUy2Kl2cufuk,2650
+transformers/models/codegen/modeling_codegen.py,sha256=bKh2qZ81yKe-rc3tgoPGugVUbBrsAtM-eBwUtxS3Qys,20442
+transformers/models/codegen/tokenization_codegen.py,sha256=uO-6sBK0bcRJ-p74gvNHP30SJSc-NaINzJWlvIlSgvw,8512
+transformers/models/cohere/__init__.py,sha256=ODwuQ7yp4l1fhMjzk_yO5EAmCzXh1cNOmf10iBD3H9A,1032
+transformers/models/cohere/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/cohere/__pycache__/configuration_cohere.cpython-312.pyc,,
+transformers/models/cohere/__pycache__/modeling_cohere.cpython-312.pyc,,
+transformers/models/cohere/__pycache__/modular_cohere.cpython-312.pyc,,
+transformers/models/cohere/__pycache__/tokenization_cohere.cpython-312.pyc,,
+transformers/models/cohere/configuration_cohere.py,sha256=ldQdaWDCjQo7tDzOMhdwc5duFro46reYuHk_u6a1UcY,3389
+transformers/models/cohere/modeling_cohere.py,sha256=VaNF28716bPZ4rFrwfqBty1D1zyT8UrwkCn6PmJF7dc,23281
+transformers/models/cohere/modular_cohere.py,sha256=atkM3kASd9ywJKDPQ2s4Z4UGP6n8N3GIJHCx7RLfTDE,14042
+transformers/models/cohere/tokenization_cohere.py,sha256=Cqhqs5wcCt9bennRPaaNTMC0cw3F6BalIWjXna72O4E,19625
+transformers/models/cohere2/__init__.py,sha256=6Cx_c-uTSNopbO3NLWCgMmEB2-5hzkrunUWmMrb8YSU,1011
+transformers/models/cohere2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/cohere2/__pycache__/configuration_cohere2.cpython-312.pyc,,
+transformers/models/cohere2/__pycache__/modeling_cohere2.cpython-312.pyc,,
+transformers/models/cohere2/__pycache__/modular_cohere2.cpython-312.pyc,,
+transformers/models/cohere2/configuration_cohere2.py,sha256=z2bXwT_nZjPNd8Nx4M74CTMINbrH4DlKDUlcbK2fmJU,4605
+transformers/models/cohere2/modeling_cohere2.py,sha256=hCkUlHjrs0JMycq4BJTrf_kN0ywLIaeWm1e1haLqLMA,22624
+transformers/models/cohere2/modular_cohere2.py,sha256=wye0FDu9B7mpnkniTONIehbrFd02IFgwrBpUfYUsFlw,12736
+transformers/models/cohere2_moe/__init__.py,sha256=mc-HjY3yfR0zAP4HdMcpAduMKwxiwZs_LzyDsQ3msY4,1019
+transformers/models/cohere2_moe/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/cohere2_moe/__pycache__/configuration_cohere2_moe.cpython-312.pyc,,
+transformers/models/cohere2_moe/__pycache__/modeling_cohere2_moe.cpython-312.pyc,,
+transformers/models/cohere2_moe/__pycache__/modular_cohere2_moe.cpython-312.pyc,,
+transformers/models/cohere2_moe/configuration_cohere2_moe.py,sha256=wDnTTQ88kh4_1p4qiwuWODIYV9xcWZ5AUSIiKB-usQw,6334
+transformers/models/cohere2_moe/modeling_cohere2_moe.py,sha256=R2EXNdo_hb74_R7BC7AxLO8t0uBqyJhKX5SLB3Ibpng,29914
+transformers/models/cohere2_moe/modular_cohere2_moe.py,sha256=bLr4CNbqSQeq8CyMYEei5Qo6DWa9n5NxND0FW24mDM4,13028
+transformers/models/cohere2_vision/__init__.py,sha256=qHyhl239nIamdrDq6-oHG6qiERD2A6KtwBFATxeq6Xg,1105
+transformers/models/cohere2_vision/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/cohere2_vision/__pycache__/configuration_cohere2_vision.cpython-312.pyc,,
+transformers/models/cohere2_vision/__pycache__/image_processing_cohere2_vision.cpython-312.pyc,,
+transformers/models/cohere2_vision/__pycache__/modeling_cohere2_vision.cpython-312.pyc,,
+transformers/models/cohere2_vision/__pycache__/modular_cohere2_vision.cpython-312.pyc,,
+transformers/models/cohere2_vision/__pycache__/processing_cohere2_vision.cpython-312.pyc,,
+transformers/models/cohere2_vision/configuration_cohere2_vision.py,sha256=dNr18r-rJKSb-gGjR3o7YN-9xVGx-AzqhURoCdU70JA,2611
+transformers/models/cohere2_vision/image_processing_cohere2_vision.py,sha256=m6Q6O_2d1Z4vofb9gdtOiuqmbJKrDrMolIJtvmsRIrs,13431
+transformers/models/cohere2_vision/modeling_cohere2_vision.py,sha256=mbw7wSTCUBQBpOUc6bVUGb4IB5IG5SRq2bLF4bsuLEs,16926
+transformers/models/cohere2_vision/modular_cohere2_vision.py,sha256=iIsy4Ky_TNK3C_xe8FwIuPBXpLmGP0GmxBJOLVIux7k,13546
+transformers/models/cohere2_vision/processing_cohere2_vision.py,sha256=0r0Zb-C_nTczIzxUSGYllv0Kgb0YaeynTG8hpYuMmos,7099
+transformers/models/cohere_asr/__init__.py,sha256=UkDFNI1BkeMbnhEHev2H_BT77nZrviPphSDDA0F5bag,1092
+transformers/models/cohere_asr/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/cohere_asr/__pycache__/configuration_cohere_asr.cpython-312.pyc,,
+transformers/models/cohere_asr/__pycache__/feature_extraction_cohere_asr.cpython-312.pyc,,
+transformers/models/cohere_asr/__pycache__/modeling_cohere_asr.cpython-312.pyc,,
+transformers/models/cohere_asr/__pycache__/modular_cohere_asr.cpython-312.pyc,,
+transformers/models/cohere_asr/__pycache__/processing_cohere_asr.cpython-312.pyc,,
+transformers/models/cohere_asr/configuration_cohere_asr.py,sha256=DLDQEkldgB1g9CHO-mCrv8rr4F8huXJwTmRA72_OFgY,3580
+transformers/models/cohere_asr/feature_extraction_cohere_asr.py,sha256=HK9WcXwB72dJ5Pn-5Ao2J1HUQ63kfRZ6NOEhhey7ajo,17645
+transformers/models/cohere_asr/modeling_cohere_asr.py,sha256=znvIP-08okfwQXoc87oQz8zGhCm0TxVY3_ldMRWTz5g,29376
+transformers/models/cohere_asr/modular_cohere_asr.py,sha256=FOvZhQr_5uxBs4FnoaBY5RTrYddY9sCCgxLI-R5RgP8,23332
+transformers/models/cohere_asr/processing_cohere_asr.py,sha256=-L18zUAgNIoxhvqgcphCU5l8n7x3NG_ZoBe5-NTUgYI,7666
+transformers/models/colmodernvbert/__init__.py,sha256=ZFaJLo1i7A4zZ-Sf7BxZZGcoKMjFXCgQUetP4TXs2Ig,1099
+transformers/models/colmodernvbert/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/colmodernvbert/__pycache__/configuration_colmodernvbert.cpython-312.pyc,,
+transformers/models/colmodernvbert/__pycache__/modeling_colmodernvbert.cpython-312.pyc,,
+transformers/models/colmodernvbert/__pycache__/modular_colmodernvbert.cpython-312.pyc,,
+transformers/models/colmodernvbert/__pycache__/processing_colmodernvbert.cpython-312.pyc,,
+transformers/models/colmodernvbert/configuration_colmodernvbert.py,sha256=svDKjVDaEQ1IDxNZNlmQOL05Tfh9oYd9LAf6eV4sAdk,3578
+transformers/models/colmodernvbert/modeling_colmodernvbert.py,sha256=c1JtdMrounpif9etjNx3NR4mLzCPDWMUjdE5cWfuEhw,7434
+transformers/models/colmodernvbert/modular_colmodernvbert.py,sha256=AVRKPsB-f2vEaK_LNoJpftspbe_MSV8pRvWNaLcQv08,17508
+transformers/models/colmodernvbert/processing_colmodernvbert.py,sha256=XHwu5AY9DBvlG2cBg7CFnOMzdNn3eQ171ueQkw0W9m8,24119
+transformers/models/colpali/__init__.py,sha256=eG-nOojo-DPkgZJACn6hbJqqfnGE97uKmLkpWVin66A,1033
+transformers/models/colpali/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/colpali/__pycache__/configuration_colpali.cpython-312.pyc,,
+transformers/models/colpali/__pycache__/modeling_colpali.cpython-312.pyc,,
+transformers/models/colpali/__pycache__/modular_colpali.cpython-312.pyc,,
+transformers/models/colpali/__pycache__/processing_colpali.cpython-312.pyc,,
+transformers/models/colpali/configuration_colpali.py,sha256=A8FXdceQZp-wfT1BldYem2k3PBiF_Imzbyfd5igzcCE,2251
+transformers/models/colpali/modeling_colpali.py,sha256=b8TVr8nQLPN_-I7IPxTXSpmzJcA3dN2Y6DWpnQVh0EU,6927
+transformers/models/colpali/modular_colpali.py,sha256=CnPKZ8Kf_svxSQnlynGaL5-R11sX8jXA268tS4wU0iA,12882
+transformers/models/colpali/processing_colpali.py,sha256=xWONj4ldGWnCW2DXdF5P75ZyzvqL_Q1mUDpkUq7FMAo,16513
+transformers/models/colqwen2/__init__.py,sha256=GBrOYGkXcXTOuCd6AhVMss6TVb2igEKFcrAkgJbbg-Q,1036
+transformers/models/colqwen2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/colqwen2/__pycache__/configuration_colqwen2.cpython-312.pyc,,
+transformers/models/colqwen2/__pycache__/modeling_colqwen2.cpython-312.pyc,,
+transformers/models/colqwen2/__pycache__/modular_colqwen2.cpython-312.pyc,,
+transformers/models/colqwen2/__pycache__/processing_colqwen2.cpython-312.pyc,,
+transformers/models/colqwen2/configuration_colqwen2.py,sha256=oq-Q7phfIit7J9SlxIFOzNnGqp6C7Q1EYn0uzuvz2O4,2100
+transformers/models/colqwen2/modeling_colqwen2.py,sha256=7dZHqsk-BD4C0X1xRKmX4idiETEAZQpm_AnQCLPXqPg,9431
+transformers/models/colqwen2/modular_colqwen2.py,sha256=mgsVWdXuP0b-4O29pThiOMgZcA_NbqaH_Zbf7F610Rw,15480
+transformers/models/colqwen2/processing_colqwen2.py,sha256=xXZNbruZo1MTE2qSJ6dIwPZR6O5zOeRMzGRI4A0OJTg,16656
+transformers/models/conditional_detr/__init__.py,sha256=JB-FaQARoOc5rAosDYpIc6eLhNjC7JM5pD5ww-WBZJw,1123
+transformers/models/conditional_detr/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/conditional_detr/__pycache__/configuration_conditional_detr.cpython-312.pyc,,
+transformers/models/conditional_detr/__pycache__/image_processing_conditional_detr.cpython-312.pyc,,
+transformers/models/conditional_detr/__pycache__/image_processing_pil_conditional_detr.cpython-312.pyc,,
+transformers/models/conditional_detr/__pycache__/modeling_conditional_detr.cpython-312.pyc,,
+transformers/models/conditional_detr/__pycache__/modular_conditional_detr.cpython-312.pyc,,
+transformers/models/conditional_detr/configuration_conditional_detr.py,sha256=75SqjXF3OWyKV0BLHHs8S3KN55-heqdgUzbhlf8CCj4,4663
+transformers/models/conditional_detr/image_processing_conditional_detr.py,sha256=qBwbOC1X81MKHHWpinJ7qURfmYBrVpxzEim6jAS3SGU,48114
+transformers/models/conditional_detr/image_processing_pil_conditional_detr.py,sha256=6EITa3SH15tvw3V59q6-mSMGVxkcZEqz7OFPEgoVEIQ,49867
+transformers/models/conditional_detr/modeling_conditional_detr.py,sha256=w7uLDsSskVT-gRMrLx6j5fdKX1tfdGqWZYOb4GkTxHw,85706
+transformers/models/conditional_detr/modular_conditional_detr.py,sha256=hrJGhrRJo5jjmGQSaCeHYum14jv8-Z3OHstRKjPwYWc,51576
+transformers/models/convbert/__init__.py,sha256=Y0-hcRZvFjmIVqDFCtOKhQDRqp0d7wKCZc10seKejqI,1118
+transformers/models/convbert/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/convbert/__pycache__/configuration_convbert.cpython-312.pyc,,
+transformers/models/convbert/__pycache__/modeling_convbert.cpython-312.pyc,,
+transformers/models/convbert/__pycache__/tokenization_convbert.cpython-312.pyc,,
+transformers/models/convbert/configuration_convbert.py,sha256=KcyDoA-TFqFDiHVznp7S7K9BhMlT-Hlirf6inMUtUSs,2427
+transformers/models/convbert/modeling_convbert.py,sha256=S9JDKf60X5SV2QRRFnHl6xGol6VLsKJlmISndTs7Qfg,44911
+transformers/models/convbert/tokenization_convbert.py,sha256=x-ytkim2fLoFmpF9-VgIEuigm6tggJLwkaSsC1_radg,1092
+transformers/models/convnext/__init__.py,sha256=Ull3yYAgnLXLKUlqL4CY2DADJLYLS3X0r6Fw7t2j4Rg,1091
+transformers/models/convnext/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/convnext/__pycache__/configuration_convnext.cpython-312.pyc,,
+transformers/models/convnext/__pycache__/image_processing_convnext.cpython-312.pyc,,
+transformers/models/convnext/__pycache__/image_processing_pil_convnext.cpython-312.pyc,,
+transformers/models/convnext/__pycache__/modeling_convnext.cpython-312.pyc,,
+transformers/models/convnext/configuration_convnext.py,sha256=VS2-36Gh_8E3UTUCo9HgpiC8Z1kgrcf6qRruurUxGfM,2492
+transformers/models/convnext/image_processing_convnext.py,sha256=mdntjYrE2VQpmkJV-4LUHPnHrKxFTg_fju5w1YWFheo,5509
+transformers/models/convnext/image_processing_pil_convnext.py,sha256=uKiQ_Qv2wduuQknnF3lCcE_eWlvfMT2eC3ChoNbqyRo,4766
+transformers/models/convnext/modeling_convnext.py,sha256=nVR5uQDASGcJfYE-8ixuzvQl2GEzWxXENqr7nfWj-rk,15770
+transformers/models/convnextv2/__init__.py,sha256=WcvDfW6VT_st_i235oLAM_okTePdPNtxNVHsOZ4_Bi4,1001
+transformers/models/convnextv2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/convnextv2/__pycache__/configuration_convnextv2.cpython-312.pyc,,
+transformers/models/convnextv2/__pycache__/modeling_convnextv2.cpython-312.pyc,,
+transformers/models/convnextv2/configuration_convnextv2.py,sha256=WX1ToBQ7qSFj3gl3oQGt5GGNsfRABYUm-BA2gHfLi3M,2484
+transformers/models/convnextv2/modeling_convnextv2.py,sha256=qNml2R0u3IHGFAiNg7d5sERH4nE9E3WcfPllEjismIs,17332
+transformers/models/cosmos3_omni/__init__.py,sha256=Gwk-1yqinuBKoJJPk8ARwJFF4AXs_VOPkSo8a7RRBJ4,1033
+transformers/models/cosmos3_omni/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/cosmos3_omni/__pycache__/configuration_cosmos3_omni.cpython-312.pyc,,
+transformers/models/cosmos3_omni/__pycache__/modeling_cosmos3_omni.cpython-312.pyc,,
+transformers/models/cosmos3_omni/__pycache__/modular_cosmos3_omni.cpython-312.pyc,,
+transformers/models/cosmos3_omni/configuration_cosmos3_omni.py,sha256=jYQdiKpB5K9p-uh1gz2z0T2t6u_KIruxAhWEcH6sKwM,3496
+transformers/models/cosmos3_omni/modeling_cosmos3_omni.py,sha256=x6HFU-7guuGOV2-cTORJPSXowcYgGQm52ttOWlYoJ0Q,42122
+transformers/models/cosmos3_omni/modular_cosmos3_omni.py,sha256=DfC2dHqN94yU2P1jRjzZtqTLuY9kJtmBbnr6kk-v0lU,3938
+transformers/models/cpm/__init__.py,sha256=psXgdNRVfFj8JbyWxWhM84oflsqVA5_ODqYatXvkpzU,954
+transformers/models/cpm/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/cpm/__pycache__/tokenization_cpm.cpython-312.pyc,,
+transformers/models/cpm/__pycache__/tokenization_cpm_fast.cpython-312.pyc,,
+transformers/models/cpm/tokenization_cpm.py,sha256=XCOcTehy4nF7oE1K5m_b2oXGYoz6i8D0Mf8T-KEa06Y,13822
+transformers/models/cpm/tokenization_cpm_fast.py,sha256=kO2p2Z3rthXylnGlz0QKFhBe2vjGRSnsdVxP69qKVBU,9917
+transformers/models/cpmant/__init__.py,sha256=RfkbbhNqdbioJ5XVaTtxBLnZRt1GFnXugS3UFXHYV0c,1032
+transformers/models/cpmant/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/cpmant/__pycache__/configuration_cpmant.cpython-312.pyc,,
+transformers/models/cpmant/__pycache__/modeling_cpmant.cpython-312.pyc,,
+transformers/models/cpmant/__pycache__/tokenization_cpmant.cpython-312.pyc,,
+transformers/models/cpmant/configuration_cpmant.py,sha256=Fv8K3K46-H_z7RvQmeE0fJsRXOK9oUVBpMH7Id5piG0,2448
+transformers/models/cpmant/modeling_cpmant.py,sha256=x_H_Bn-Vd234Ep_pmocyMbE6VOkKJjBGsqCXkjTNlUk,31932
+transformers/models/cpmant/tokenization_cpmant.py,sha256=7y32Z-rvAP2lv8eoz6qyU6cht69VgtytfN-VMfL5b6A,7993
+transformers/models/csm/__init__.py,sha256=n-AQHwxZwD8imEHipiQoTDRf_OMo5zJhQ0tKKWMCPYs,1021
+transformers/models/csm/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/csm/__pycache__/configuration_csm.cpython-312.pyc,,
+transformers/models/csm/__pycache__/generation_csm.cpython-312.pyc,,
+transformers/models/csm/__pycache__/modeling_csm.cpython-312.pyc,,
+transformers/models/csm/__pycache__/modular_csm.cpython-312.pyc,,
+transformers/models/csm/__pycache__/processing_csm.cpython-312.pyc,,
+transformers/models/csm/configuration_csm.py,sha256=8j2EfsWnK_ukdXIESN0GR03lAurem-WZZv4aoO58EA4,6952
+transformers/models/csm/generation_csm.py,sha256=SqsQnEPVCpI3eRZgq7bu3mYwHmLne74HoyW_NVhyo_0,25491
+transformers/models/csm/modeling_csm.py,sha256=zs0COm2_BV8zi_LoQzPd7mYuywwPADu0qhn0up74yhI,51053
+transformers/models/csm/modular_csm.py,sha256=EjciSLSh2MJipxyTl1Sd8TsON5wFPcsWtokP2X0ci54,35112
+transformers/models/csm/processing_csm.py,sha256=v6WkNkanMqvF3vAZ5KACKpzSmy-x7bbkfMVUN3RIVl0,13710
+transformers/models/ctrl/__init__.py,sha256=Uj8X4puguEkwCqBv_qOznsAW6GPOlieWNi-IGUh6mBQ,1026
+transformers/models/ctrl/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/ctrl/__pycache__/configuration_ctrl.cpython-312.pyc,,
+transformers/models/ctrl/__pycache__/modeling_ctrl.cpython-312.pyc,,
+transformers/models/ctrl/__pycache__/tokenization_ctrl.cpython-312.pyc,,
+transformers/models/ctrl/configuration_ctrl.py,sha256=RmySjtQgYWdb7mJW91C6mgeDjCDFeKnd19RgZVRIeSI,2211
+transformers/models/ctrl/modeling_ctrl.py,sha256=meW2O6xeUHtIaAwPUSXLJ3xrLdk4CYPvBYBmWB7OgEg,27007
+transformers/models/ctrl/tokenization_ctrl.py,sha256=BFU4oTzkz9G141xRPHYJRXMMuY1Jv_CsBitg-Jf2VL4,6855
+transformers/models/cvt/__init__.py,sha256=PWfHQ1umBPnzjBcUQnJn2YvYAqxyWu8YrGzqmDsSHJo,987
+transformers/models/cvt/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/cvt/__pycache__/configuration_cvt.cpython-312.pyc,,
+transformers/models/cvt/__pycache__/modeling_cvt.cpython-312.pyc,,
+transformers/models/cvt/configuration_cvt.py,sha256=CON3tD2MOrr6YjACuDCnmVNcUzj29vjDCRRDyDdIJKc,4244
+transformers/models/cvt/modeling_cvt.py,sha256=-BidiG6hO38-S_EicPquojfwdfLh-LP39Anxhb_4dvI,23952
+transformers/models/cwm/__init__.py,sha256=03y-UaFJQwrYUyzQX5j0e7reFrGcd7uD93fnOrUsJSA,988
+transformers/models/cwm/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/cwm/__pycache__/configuration_cwm.cpython-312.pyc,,
+transformers/models/cwm/__pycache__/modeling_cwm.cpython-312.pyc,,
+transformers/models/cwm/__pycache__/modular_cwm.cpython-312.pyc,,
+transformers/models/cwm/configuration_cwm.py,sha256=Fhk189x6DoLljnWxtM0vc8hbkDbT6GQxSp5dhJJvx0E,5182
+transformers/models/cwm/modeling_cwm.py,sha256=cU_2IP79ppxvBkl8OiabrNVTmdWWsVmOfqWS8MoYDxk,21552
+transformers/models/cwm/modular_cwm.py,sha256=Mm2rd-p2IKTkktUwLNN-DjMGk90n9u4EDJj6mzgvBhc,7001
+transformers/models/d_fine/__init__.py,sha256=1gNscomeWytwZT7K2GJBwyXxDkfVNLhRjuDwyde2A0s,995
+transformers/models/d_fine/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/d_fine/__pycache__/configuration_d_fine.cpython-312.pyc,,
+transformers/models/d_fine/__pycache__/modeling_d_fine.cpython-312.pyc,,
+transformers/models/d_fine/__pycache__/modular_d_fine.cpython-312.pyc,,
+transformers/models/d_fine/configuration_d_fine.py,sha256=AXkrkjOXPRE6ZBj7f5QyCOkA5HSrzhl6H2B2kHErRWk,12875
+transformers/models/d_fine/modeling_d_fine.py,sha256=4_MxEBZPd4WzYe4MAVxgRHjdAGBEItyP4gmwO4M5a0Q,96676
+transformers/models/d_fine/modular_d_fine.py,sha256=dUcsOVi77YgJtldlu2ZsirnAObf6ZsS4xXfKSJLVJuY,45965
+transformers/models/dab_detr/__init__.py,sha256=ZvNYPQyXWplaRQIxFR8CURcsnu_HRPXrwojF5nTmGd4,998
+transformers/models/dab_detr/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/dab_detr/__pycache__/configuration_dab_detr.cpython-312.pyc,,
+transformers/models/dab_detr/__pycache__/modeling_dab_detr.cpython-312.pyc,,
+transformers/models/dab_detr/configuration_dab_detr.py,sha256=K2_wrp7rxc-AxWXDXlBszrHd4Vc5CgRR4zHH0hfeUuw,5833
+transformers/models/dab_detr/modeling_dab_detr.py,sha256=KL57KLCZc5OiyyKUgy6_N3k7B50BzuUBXkofAA4bMTo,74186
+transformers/models/dac/__init__.py,sha256=UpwXPmSOQOwvbIvklM21-y5HKY7MEIInmTt65xMX6Hw,1029
+transformers/models/dac/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/dac/__pycache__/configuration_dac.cpython-312.pyc,,
+transformers/models/dac/__pycache__/feature_extraction_dac.cpython-312.pyc,,
+transformers/models/dac/__pycache__/modeling_dac.cpython-312.pyc,,
+transformers/models/dac/configuration_dac.py,sha256=KmvJeHG8fefYanL3wOnGuE1aarTwba-jGQFOOSbeJvw,2797
+transformers/models/dac/feature_extraction_dac.py,sha256=npYuHvnX-pyTvcfzxndRrLXgf-HLobCxF1Tt6-vhCpI,7911
+transformers/models/dac/modeling_dac.py,sha256=iAHIMaGTJFCv-NpYHwchVcal2JQRK4XQK48i7Kckvmg,28980
+transformers/models/data2vec/__init__.py,sha256=BBiRVhmDgkquO28CdLOZNQztFSNQ9H-qP5wFYnI0NEc,1191
+transformers/models/data2vec/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/data2vec/__pycache__/configuration_data2vec_audio.cpython-312.pyc,,
+transformers/models/data2vec/__pycache__/configuration_data2vec_text.cpython-312.pyc,,
+transformers/models/data2vec/__pycache__/configuration_data2vec_vision.cpython-312.pyc,,
+transformers/models/data2vec/__pycache__/modeling_data2vec_audio.cpython-312.pyc,,
+transformers/models/data2vec/__pycache__/modeling_data2vec_text.cpython-312.pyc,,
+transformers/models/data2vec/__pycache__/modeling_data2vec_vision.cpython-312.pyc,,
+transformers/models/data2vec/__pycache__/modular_data2vec_audio.cpython-312.pyc,,
+transformers/models/data2vec/__pycache__/modular_data2vec_text.cpython-312.pyc,,
+transformers/models/data2vec/configuration_data2vec_audio.py,sha256=J6QHAACuUNPuXFn-19h8sHSkSRzck7x2T6hUTha8uf0,11098
+transformers/models/data2vec/configuration_data2vec_text.py,sha256=_4VPQPg_7YWxAGCieYi2K5YuT705qbl_9zEczBfJVeo,2166
+transformers/models/data2vec/configuration_data2vec_vision.py,sha256=jxeJ5yPHJgrr42U_HQNyNdEPGeaSjg0k3gvRPG2frFo,4015
+transformers/models/data2vec/modeling_data2vec_audio.py,sha256=8Llni84CKYichnyRT34Ew_qBVh0Zp2vC6DRTHZ2mGEs,55697
+transformers/models/data2vec/modeling_data2vec_text.py,sha256=THkRUVYNwAJmpszSdRA6HurwN3-8RmFHYLgbPbneBvc,49601
+transformers/models/data2vec/modeling_data2vec_vision.py,sha256=5tcpic21Y3Mc6jfpO6zLC01qQYiFIDqg88EI_seCGI4,53180
+transformers/models/data2vec/modular_data2vec_audio.py,sha256=9f7UwTtLQdTDQgY5er-WbBIMpJQ-t6aJhwRlxt00lYA,9673
+transformers/models/data2vec/modular_data2vec_text.py,sha256=SIFz4P_bMPP5JIQtb8Mni3Spvw-jBOf7a9mDOXr9_tk,23016
+transformers/models/dbrx/__init__.py,sha256=Kzn3gm0QHW9RKEmog_IfdCGam5TXSCzkOs_WHC43sgM,989
+transformers/models/dbrx/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/dbrx/__pycache__/configuration_dbrx.cpython-312.pyc,,
+transformers/models/dbrx/__pycache__/modeling_dbrx.cpython-312.pyc,,
+transformers/models/dbrx/__pycache__/modular_dbrx.cpython-312.pyc,,
+transformers/models/dbrx/configuration_dbrx.py,sha256=sy4sNpv9scV0VHjGyxk0BlTRkvEuArnzy-MxGoQpawo,6368
+transformers/models/dbrx/modeling_dbrx.py,sha256=bXDZdEn8gNPWG5jqHVUFmqMheOSG0K2P7nkcfrQjcVc,32121
+transformers/models/dbrx/modular_dbrx.py,sha256=dbDWQqRBI7HamisjbECXXc0dwGt3yXCiCzz6PlJWJXI,21756
+transformers/models/deberta/__init__.py,sha256=m87EmHGlh9isDhJ7-X7MlUa1cPhWtRYuqZPC3yGNE9I,1035
+transformers/models/deberta/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/deberta/__pycache__/configuration_deberta.cpython-312.pyc,,
+transformers/models/deberta/__pycache__/modeling_deberta.cpython-312.pyc,,
+transformers/models/deberta/__pycache__/tokenization_deberta.cpython-312.pyc,,
+transformers/models/deberta/configuration_deberta.py,sha256=wywO1_ZOynGb5H0TPBJfuctwtbRWcOS4ww-vir66hLg,3632
+transformers/models/deberta/modeling_deberta.py,sha256=QQJrCjvh12_8gQAOYw5qNcy5pvsZ8VurokZ7uMEPT1k,47688
+transformers/models/deberta/tokenization_deberta.py,sha256=jNbgUuJtq-ydvv8AvtPDfC9CDErYTmBgKQxg7u3KEgI,7794
+transformers/models/deberta_v2/__init__.py,sha256=XIzvjcNgxx7TXV5zmtSG35QaaQMn86eQrHjijCcDM-M,1044
+transformers/models/deberta_v2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/deberta_v2/__pycache__/configuration_deberta_v2.cpython-312.pyc,,
+transformers/models/deberta_v2/__pycache__/modeling_deberta_v2.cpython-312.pyc,,
+transformers/models/deberta_v2/__pycache__/tokenization_deberta_v2.cpython-312.pyc,,
+transformers/models/deberta_v2/configuration_deberta_v2.py,sha256=yqTumdoQkoNyqe72LL-65w4uHXr2Zw7StLtxoghtjqs,3687
+transformers/models/deberta_v2/modeling_deberta_v2.py,sha256=TYNMI4eu5lB0ZqQAfrJfXbnSSy2xXeNaBHYWf2900Ls,55398
+transformers/models/deberta_v2/tokenization_deberta_v2.py,sha256=CRG2mKAtLRBX9jIoQzpGidTZhs1M1yfBHOicb5J0lzw,7221
+transformers/models/decision_transformer/__init__.py,sha256=8XAHnFrFv8IFz495cQLTeaAk2G1AVRT7roauVHCGoJs,1021
+transformers/models/decision_transformer/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/decision_transformer/__pycache__/configuration_decision_transformer.cpython-312.pyc,,
+transformers/models/decision_transformer/__pycache__/modeling_decision_transformer.cpython-312.pyc,,
+transformers/models/decision_transformer/configuration_decision_transformer.py,sha256=sh4zjeAL8V2y_YFg0mjEzU_9UqL9FVRn0Lg7xR7659I,3371
+transformers/models/decision_transformer/modeling_decision_transformer.py,sha256=a6fUz-rcW9IaLzy-2FYTLuDHqf_-i0O098txJs0RpE0,29382
+transformers/models/deepseek_ocr2/__init__.py,sha256=wvqg3rkDYjhBqbuFSI5dephkBSIM3M3E2lk62Sh61Us,1155
+transformers/models/deepseek_ocr2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/deepseek_ocr2/__pycache__/configuration_deepseek_ocr2.cpython-312.pyc,,
+transformers/models/deepseek_ocr2/__pycache__/image_processing_deepseek_ocr2.cpython-312.pyc,,
+transformers/models/deepseek_ocr2/__pycache__/image_processing_pil_deepseek_ocr2.cpython-312.pyc,,
+transformers/models/deepseek_ocr2/__pycache__/modeling_deepseek_ocr2.cpython-312.pyc,,
+transformers/models/deepseek_ocr2/__pycache__/modular_deepseek_ocr2.cpython-312.pyc,,
+transformers/models/deepseek_ocr2/__pycache__/processing_deepseek_ocr2.cpython-312.pyc,,
+transformers/models/deepseek_ocr2/configuration_deepseek_ocr2.py,sha256=SXGuSnaFpZvopasRWlhr2NjckBYHWSSTqd9akS5CBQM,12089
+transformers/models/deepseek_ocr2/image_processing_deepseek_ocr2.py,sha256=jl4bfJDJ0ohStTCukBQv6UqKOgvs-Cl9DGqjlHtymjA,15169
+transformers/models/deepseek_ocr2/image_processing_pil_deepseek_ocr2.py,sha256=2auKhqdn7ugF9MV5dSRggyDlYgKkMPMgTHZMSf63qpk,14704
+transformers/models/deepseek_ocr2/modeling_deepseek_ocr2.py,sha256=3pkHCRhT2elTqCc8YrU5pzq2HOjyUoXBp0nE8wgNA80,74367
+transformers/models/deepseek_ocr2/modular_deepseek_ocr2.py,sha256=JKMdafCViFuHcL8ZZUxf0kV9zpA0mD2ZwA741H87OrA,46073
+transformers/models/deepseek_ocr2/processing_deepseek_ocr2.py,sha256=x5yzasvS0Rdv_71xU4x4_Jsribxb_bdgH-YM2-C0qqc,6019
+transformers/models/deepseek_v2/__init__.py,sha256=cRpNT946KLnKXl4i2mGlImi9QLOe2a1ocnWNjBSbK68,1005
+transformers/models/deepseek_v2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/deepseek_v2/__pycache__/configuration_deepseek_v2.cpython-312.pyc,,
+transformers/models/deepseek_v2/__pycache__/modeling_deepseek_v2.cpython-312.pyc,,
+transformers/models/deepseek_v2/__pycache__/modular_deepseek_v2.cpython-312.pyc,,
+transformers/models/deepseek_v2/configuration_deepseek_v2.py,sha256=2SW24eIEfvTTynB5N5nNnt73bYODsIJDYlIyO5YylVw,5554
+transformers/models/deepseek_v2/modeling_deepseek_v2.py,sha256=mAgIO1MyBRRaVKBHW0-ko0ALT-hCX2yhJtGNpo-cIzc,27378
+transformers/models/deepseek_v2/modular_deepseek_v2.py,sha256=-R0DXJSXO0mR3JdNzbR5ME53KTMLMZ3saLqsivX7kms,15184
+transformers/models/deepseek_v3/__init__.py,sha256=t-ejxAfULC_tUrUucNLt-x3hbTEIqUQp96m2DRFeaTg,1008
+transformers/models/deepseek_v3/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/deepseek_v3/__pycache__/configuration_deepseek_v3.cpython-312.pyc,,
+transformers/models/deepseek_v3/__pycache__/modeling_deepseek_v3.cpython-312.pyc,,
+transformers/models/deepseek_v3/__pycache__/modular_deepseek_v3.cpython-312.pyc,,
+transformers/models/deepseek_v3/configuration_deepseek_v3.py,sha256=9Ki2RbB0LPN_b4bnM5zZvK25I3de0CdLeHvdC49TFFE,4296
+transformers/models/deepseek_v3/modeling_deepseek_v3.py,sha256=IkTbDSxp-pwJcgyW4sA_X689UvzHj1k6zfBF5xP5lwE,31947
+transformers/models/deepseek_v3/modular_deepseek_v3.py,sha256=cv9BMytju_vJ0R7b2ot1v9_aqldC5ez9QfK3WtQjJb0,14108
+transformers/models/deepseek_v32/__init__.py,sha256=tiGvRCug2udHzjuVvQuM5buy_3n_1tSIpIXUP0UavAY,1006
+transformers/models/deepseek_v32/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/deepseek_v32/__pycache__/configuration_deepseek_v32.cpython-312.pyc,,
+transformers/models/deepseek_v32/__pycache__/modeling_deepseek_v32.cpython-312.pyc,,
+transformers/models/deepseek_v32/__pycache__/modular_deepseek_v32.cpython-312.pyc,,
+transformers/models/deepseek_v32/configuration_deepseek_v32.py,sha256=lQcg9j8PIhKIQPKf0Uw--0g2yAd6eqvY9yB48TtMHHY,6514
+transformers/models/deepseek_v32/modeling_deepseek_v32.py,sha256=znYVFgqhDuW8WN6ptn5Qasez0jKxUh7TKnw5wz6GWWg,38584
+transformers/models/deepseek_v32/modular_deepseek_v32.py,sha256=fsAp44prsR6_mV1y3MZ5XfLnXcYIHgffpkWdpy7IfU8,16594
+transformers/models/deepseek_v4/__init__.py,sha256=xCfpXsPeLA4NZkn7ydjKSyhcosTR4IQ5eJ6_kOFh-m0,1008
+transformers/models/deepseek_v4/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/deepseek_v4/__pycache__/configuration_deepseek_v4.cpython-312.pyc,,
+transformers/models/deepseek_v4/__pycache__/modeling_deepseek_v4.cpython-312.pyc,,
+transformers/models/deepseek_v4/__pycache__/modular_deepseek_v4.cpython-312.pyc,,
+transformers/models/deepseek_v4/configuration_deepseek_v4.py,sha256=tRCEmhiXhehGe45BXLzl8FFwUCXuQLmhwTua3SaVUF8,15548
+transformers/models/deepseek_v4/modeling_deepseek_v4.py,sha256=O-PFIRUH3dGzesnbsn9HUzw515InecEkUX4dOnqcQlM,78887
+transformers/models/deepseek_v4/modular_deepseek_v4.py,sha256=a2_AM36WjLw-JSU1EmyLt4k_WNap0hai7zgx_9rLPWE,63769
+transformers/models/deepseek_vl/__init__.py,sha256=Nce-BdgAp6yWqpBJoQyWmBiXTrs3v6gixcu3tCOrxm0,1161
+transformers/models/deepseek_vl/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/deepseek_vl/__pycache__/configuration_deepseek_vl.cpython-312.pyc,,
+transformers/models/deepseek_vl/__pycache__/image_processing_deepseek_vl.cpython-312.pyc,,
+transformers/models/deepseek_vl/__pycache__/image_processing_pil_deepseek_vl.cpython-312.pyc,,
+transformers/models/deepseek_vl/__pycache__/modeling_deepseek_vl.cpython-312.pyc,,
+transformers/models/deepseek_vl/__pycache__/modular_deepseek_vl.cpython-312.pyc,,
+transformers/models/deepseek_vl/__pycache__/processing_deepseek_vl.cpython-312.pyc,,
+transformers/models/deepseek_vl/configuration_deepseek_vl.py,sha256=3PXzUSt8L_opJ54h1VivcscTUzLRTU1Zmya6DVQlfng,3581
+transformers/models/deepseek_vl/image_processing_deepseek_vl.py,sha256=fO4rnqYmPmbNYLtLI1f5p33UER-hh3pnwhL7W0OGTM4,8007
+transformers/models/deepseek_vl/image_processing_pil_deepseek_vl.py,sha256=6gGz86xGNkav3ewJYPkTU6P3v7peGBd0dm0RFszobQw,6652
+transformers/models/deepseek_vl/modeling_deepseek_vl.py,sha256=ADBaH0XOkkqvQOqhg8ee3Dh0r1a_sB11RaktGlSDmIs,14618
+transformers/models/deepseek_vl/modular_deepseek_vl.py,sha256=UkwOleeXpdkoOJ9yLlUZkNCx3tfmnCaetOBIppWFvgg,9540
+transformers/models/deepseek_vl/processing_deepseek_vl.py,sha256=MBcQDEDZ5jHzIk2CjvU1ioTLGIrltFVKCogv3j1esFk,5389
+transformers/models/deepseek_vl_hybrid/__init__.py,sha256=Mcag7bDnSiJ5y3oV1VFYVAOxZNzf9eaQUmv5tArj2a8,1196
+transformers/models/deepseek_vl_hybrid/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/deepseek_vl_hybrid/__pycache__/configuration_deepseek_vl_hybrid.cpython-312.pyc,,
+transformers/models/deepseek_vl_hybrid/__pycache__/image_processing_deepseek_vl_hybrid.cpython-312.pyc,,
+transformers/models/deepseek_vl_hybrid/__pycache__/image_processing_pil_deepseek_vl_hybrid.cpython-312.pyc,,
+transformers/models/deepseek_vl_hybrid/__pycache__/modeling_deepseek_vl_hybrid.cpython-312.pyc,,
+transformers/models/deepseek_vl_hybrid/__pycache__/modular_deepseek_vl_hybrid.cpython-312.pyc,,
+transformers/models/deepseek_vl_hybrid/__pycache__/processing_deepseek_vl_hybrid.cpython-312.pyc,,
+transformers/models/deepseek_vl_hybrid/configuration_deepseek_vl_hybrid.py,sha256=QtvVQQQYgRMTn2prZyZBTUz5WW8zWZKmDUHL5LeMXW8,4514
+transformers/models/deepseek_vl_hybrid/image_processing_deepseek_vl_hybrid.py,sha256=MYqPgsLMHtbWbntd8DRpnxVxxjSbXk_PGk9GrrOZvKc,13921
+transformers/models/deepseek_vl_hybrid/image_processing_pil_deepseek_vl_hybrid.py,sha256=1eqNUEVVkMBXRb5Gi91KJ3g4t6cWf3e5q0Z-9-wUI_Q,11686
+transformers/models/deepseek_vl_hybrid/modeling_deepseek_vl_hybrid.py,sha256=ZvXQ5S_l5eFBzEPTfBQEiPBil17vskz6YJW-Eoair0c,24597
+transformers/models/deepseek_vl_hybrid/modular_deepseek_vl_hybrid.py,sha256=3oPbPjA8SpciPOysk1fJ3SGbWDIJ-cPltt-SXLl6Q2U,34942
+transformers/models/deepseek_vl_hybrid/processing_deepseek_vl_hybrid.py,sha256=2FJx0X1UShXU1iTsojei2tjvywNHv4irrDTyVYGSHlw,5547
+transformers/models/deformable_detr/__init__.py,sha256=vhC5uDyvwLJkL_GdbF7hGdIe3fj1hLR7XD-kb48KyKg,1121
+transformers/models/deformable_detr/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/deformable_detr/__pycache__/configuration_deformable_detr.cpython-312.pyc,,
+transformers/models/deformable_detr/__pycache__/image_processing_deformable_detr.cpython-312.pyc,,
+transformers/models/deformable_detr/__pycache__/image_processing_pil_deformable_detr.cpython-312.pyc,,
+transformers/models/deformable_detr/__pycache__/modeling_deformable_detr.cpython-312.pyc,,
+transformers/models/deformable_detr/__pycache__/modular_deformable_detr.cpython-312.pyc,,
+transformers/models/deformable_detr/configuration_deformable_detr.py,sha256=sPgzI63PEBUPG5CDGZLUZ4HdkN4NvvCL3svsVFLOC64,6319
+transformers/models/deformable_detr/image_processing_deformable_detr.py,sha256=uS5218r2vi8z42xgIzQq1KajhBIvA_myxs92Pft6olA,30707
+transformers/models/deformable_detr/image_processing_pil_deformable_detr.py,sha256=-2GYTarY5QhRpJbPaiGYOpBZc0ZzvwK9Ecl4cqOj1tc,31400
+transformers/models/deformable_detr/modeling_deformable_detr.py,sha256=zYz3q2Aey25Te29xxULN8e8hzfCKQ3L3ucA3LS5DnMw,79210
+transformers/models/deformable_detr/modular_deformable_detr.py,sha256=Envu5yEpLwBclr8RbiaVdGDiTojEd8qpSm9UhM34ig0,72721
+transformers/models/deimv2/__init__.py,sha256=I3RVG6NGrPMj5aGXiFf_PP7NcQSXjeAn75gBLjm3xeQ,995
+transformers/models/deimv2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/deimv2/__pycache__/configuration_deimv2.cpython-312.pyc,,
+transformers/models/deimv2/__pycache__/modeling_deimv2.cpython-312.pyc,,
+transformers/models/deimv2/__pycache__/modular_deimv2.cpython-312.pyc,,
+transformers/models/deimv2/configuration_deimv2.py,sha256=vueZL90_-xTUcGt2hOCqdduzE6vVaTDfN5FLkVAiI7g,14110
+transformers/models/deimv2/modeling_deimv2.py,sha256=DhT5ufWxC4popA1gCI56GzK6smwpcrUtlaoHyBpqOOg,102505
+transformers/models/deimv2/modular_deimv2.py,sha256=kuRyHmVSk-ba2obKfR_1O6BufyhWhZirYZbq_4RCTII,43182
+transformers/models/deit/__init__.py,sha256=55mlr2rhd4WbU7CpnbJib2TTQD91TRnIkHqzp5sa9cI,1075
+transformers/models/deit/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/deit/__pycache__/configuration_deit.cpython-312.pyc,,
+transformers/models/deit/__pycache__/image_processing_deit.cpython-312.pyc,,
+transformers/models/deit/__pycache__/image_processing_pil_deit.cpython-312.pyc,,
+transformers/models/deit/__pycache__/modeling_deit.cpython-312.pyc,,
+transformers/models/deit/__pycache__/modular_deit.cpython-312.pyc,,
+transformers/models/deit/configuration_deit.py,sha256=kbplxVs1cpgV7ylgETem3-QiCbLuHl8BHXqE5deeQ00,2610
+transformers/models/deit/image_processing_deit.py,sha256=XZ52AgwqpxNrBFzWDgpkAxB-FEWmLaonnlNtWRD8xnI,1238
+transformers/models/deit/image_processing_pil_deit.py,sha256=P3fWesJU5Dy7lQMe92vtevV4S29zvgq_Xv5tef8cfh8,1228
+transformers/models/deit/modeling_deit.py,sha256=QQXs2aRWfCtqNCzB0lN2FEkgzRP6qHSc8Fv2JbpTtnM,28260
+transformers/models/deit/modular_deit.py,sha256=5527XIIHDJv5CVJrcHBn8kPYzXCnLCoHF2m6SJSUN_A,13344
+transformers/models/deprecated/__init__.py,sha256=cBbCmNwJS_K7Qxng1In7TGSmzj61crBAhb6mN_NoqDI,988
+transformers/models/deprecated/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/depth_anything/__init__.py,sha256=Jbd8LXt-fU3_cTF7jBrkBBw-Kzscv6o7O0YiZy0R8-A,1009
+transformers/models/depth_anything/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/depth_anything/__pycache__/configuration_depth_anything.cpython-312.pyc,,
+transformers/models/depth_anything/__pycache__/modeling_depth_anything.cpython-312.pyc,,
+transformers/models/depth_anything/configuration_depth_anything.py,sha256=U-pFzEVAs6Dyi7Ds5VXFE-fOmnr1UhTJncGZapnxdoY,4243
+transformers/models/depth_anything/modeling_depth_anything.py,sha256=wBVg56HtdauQT9DIb2Lkx5enOG0mZKdIrGRV8YC2cDY,16126
+transformers/models/depth_pro/__init__.py,sha256=PESSIRnw9q2PXuutEX9sjMxJ7CEumvSqb691lRioSe0,1045
+transformers/models/depth_pro/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/depth_pro/__pycache__/configuration_depth_pro.cpython-312.pyc,,
+transformers/models/depth_pro/__pycache__/image_processing_depth_pro.cpython-312.pyc,,
+transformers/models/depth_pro/__pycache__/modeling_depth_pro.cpython-312.pyc,,
+transformers/models/depth_pro/configuration_depth_pro.py,sha256=YWkxO6C17NYPZ11l-tpvvtEWTuuEfkJtroFhTeV44A4,9390
+transformers/models/depth_pro/image_processing_depth_pro.py,sha256=yqe4SAJrPQkAs7osCnyltEvdzlWafUSMKxJdP3sZOBE,5074
+transformers/models/depth_pro/modeling_depth_pro.py,sha256=iNw7JNKkSICxyzDoVdncFDtu6jS1PMH07CnZSCyeYqM,42499
+transformers/models/detr/__init__.py,sha256=SzCHzqfV-imJKMG69UaK1Q3Ls15ECKZ_EFokxM8v4b8,1119
+transformers/models/detr/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/detr/__pycache__/configuration_detr.cpython-312.pyc,,
+transformers/models/detr/__pycache__/image_processing_detr.cpython-312.pyc,,
+transformers/models/detr/__pycache__/image_processing_pil_detr.cpython-312.pyc,,
+transformers/models/detr/__pycache__/modeling_detr.cpython-312.pyc,,
+transformers/models/detr/configuration_detr.py,sha256=xkAc3oOg3TDE2UwbLifpgc8T5gMinvtfQn0_VCY9AaY,4308
+transformers/models/detr/image_processing_detr.py,sha256=jAcrXt2NsY4bg1eraYqb9xXlEy2tav-rMdF1aZIF5Qo,46676
+transformers/models/detr/image_processing_pil_detr.py,sha256=GtafZP1besvvx3jx6IHq4WF9rNoVHo3CuNsGyCnPC3A,48454
+transformers/models/detr/modeling_detr.py,sha256=f483g4sBGkxheI5pNj0jQqj3QJPaJimLtYu7KDQ1TCk,72849
+transformers/models/dia/__init__.py,sha256=fvBcwJ7FAFDO6RNyUUMGrdSlUtowciNo3YYv7R2Qz1c,1133
+transformers/models/dia/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/dia/__pycache__/configuration_dia.cpython-312.pyc,,
+transformers/models/dia/__pycache__/feature_extraction_dia.cpython-312.pyc,,
+transformers/models/dia/__pycache__/generation_dia.cpython-312.pyc,,
+transformers/models/dia/__pycache__/modeling_dia.cpython-312.pyc,,
+transformers/models/dia/__pycache__/modular_dia.cpython-312.pyc,,
+transformers/models/dia/__pycache__/processing_dia.cpython-312.pyc,,
+transformers/models/dia/__pycache__/tokenization_dia.cpython-312.pyc,,
+transformers/models/dia/configuration_dia.py,sha256=bcrbBwt7QI3_QILgI7MiwP8goI-3VgfuyPKKRMWIeO4,6366
+transformers/models/dia/feature_extraction_dia.py,sha256=6-jSEtsGgLZx8gbI9MC_MVbTdfyz6fnpc6olNxPkcD8,8353
+transformers/models/dia/generation_dia.py,sha256=_58g6YEfANszJ2ciUSVyKH9FUz7lflMcno5v9E9mdNE,21520
+transformers/models/dia/modeling_dia.py,sha256=4s4qYwr1mgQ3Rnr-rwbTUwlYr2hTBBtTx3N7prqbMFM,37620
+transformers/models/dia/modular_dia.py,sha256=HFncXNciXsIGX20XfYM-U6Js-Tkjp2OBTuTaX5HqZvs,27581
+transformers/models/dia/processing_dia.py,sha256=7lDMN1gjv-csnjqOUUMT9z5buVZV9jACu5aubnlixVQ,20779
+transformers/models/dia/tokenization_dia.py,sha256=lWhjp7RgJ5Ok8TErIHH12dMHzbRPt9Q_m5_AgwUP5JY,4489
+transformers/models/dialogpt/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+transformers/models/dialogpt/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/diffllama/__init__.py,sha256=Yosk5eQ82PblntLff-bL3pfJZ-AVKp5jbQK5R2SLVc8,1004
+transformers/models/diffllama/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/diffllama/__pycache__/configuration_diffllama.cpython-312.pyc,,
+transformers/models/diffllama/__pycache__/modeling_diffllama.cpython-312.pyc,,
+transformers/models/diffllama/__pycache__/modular_diffllama.cpython-312.pyc,,
+transformers/models/diffllama/configuration_diffllama.py,sha256=Xu0bfHKr5UQTmb9sDHYM_MgB6QiHd9txQ9g_JbitXFg,2835
+transformers/models/diffllama/modeling_diffllama.py,sha256=dVvBWa3CWCMGms8AqkVcOSZQJN0DpuZarx2h4W3goF0,33916
+transformers/models/diffllama/modular_diffllama.py,sha256=Rp98TCC-ixoyEsDxwQ_XGO0sQc04bqAEhxGfWUw6PK4,18311
+transformers/models/diffusion_gemma/__init__.py,sha256=ioAfxaOz_Zl9RPw89JZziroEcBeVBFprOXienB0zYWo,1016
+transformers/models/diffusion_gemma/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/diffusion_gemma/__pycache__/configuration_diffusion_gemma.cpython-312.pyc,,
+transformers/models/diffusion_gemma/__pycache__/generation_diffusion_gemma.cpython-312.pyc,,
+transformers/models/diffusion_gemma/__pycache__/modeling_diffusion_gemma.cpython-312.pyc,,
+transformers/models/diffusion_gemma/__pycache__/modular_diffusion_gemma.cpython-312.pyc,,
+transformers/models/diffusion_gemma/configuration_diffusion_gemma.py,sha256=aRMbYY3N-OlbSxf630DGWMU806Sn9K5BCyZnO31VLsA,9399
+transformers/models/diffusion_gemma/generation_diffusion_gemma.py,sha256=ze1Xt-Nl8CZbHAiOmTw1i19wrN9IBV_OOWVAtNnWkbw,63628
+transformers/models/diffusion_gemma/modeling_diffusion_gemma.py,sha256=adMP2YQs2-DGT1COE8cJ6lHyiJ_mlBSOx8OXoDjizc4,81524
+transformers/models/diffusion_gemma/modular_diffusion_gemma.py,sha256=qfgh5uYXxh4lCaJAbM4ubIKHy3xM-NSscO_pp6jlQqM,70168
+transformers/models/dinat/__init__.py,sha256=N0HykajUSY5KsvPQNUxc8jAuuJntmDJ-Dz8Qa8_sJ9E,991
+transformers/models/dinat/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/dinat/__pycache__/configuration_dinat.cpython-312.pyc,,
+transformers/models/dinat/__pycache__/modeling_dinat.cpython-312.pyc,,
+transformers/models/dinat/configuration_dinat.py,sha256=SR8gbJJVs9hlqxD8YngvykOT2UOg79tVip8Yr_RVwGM,3261
+transformers/models/dinat/modeling_dinat.py,sha256=KG383GQS9NIs0P7bw9EAss-1LaRlCQbc0S7n2wd7Ndc,30956
+transformers/models/dinov2/__init__.py,sha256=OvrAMlhyPaMvvE5W2x3hxQ6EjkPYZgesizI_jOC5K3E,993
+transformers/models/dinov2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/dinov2/__pycache__/configuration_dinov2.cpython-312.pyc,,
+transformers/models/dinov2/__pycache__/modeling_dinov2.cpython-312.pyc,,
+transformers/models/dinov2/configuration_dinov2.py,sha256=XZCGK0g3ROlRdW8Yubk7waBGNMh0Td906PP7C26-l_U,3385
+transformers/models/dinov2/modeling_dinov2.py,sha256=9_uWFh5FRoVpA7kjH2lMJxUERudXc6548JhGxDCkSoM,25084
+transformers/models/dinov2_with_registers/__init__.py,sha256=s0cefgSRnlIVcdZYV0qz3Q9X3IEChU7mkGbbnr2IH6E,1023
+transformers/models/dinov2_with_registers/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/dinov2_with_registers/__pycache__/configuration_dinov2_with_registers.cpython-312.pyc,,
+transformers/models/dinov2_with_registers/__pycache__/modeling_dinov2_with_registers.cpython-312.pyc,,
+transformers/models/dinov2_with_registers/__pycache__/modular_dinov2_with_registers.cpython-312.pyc,,
+transformers/models/dinov2_with_registers/configuration_dinov2_with_registers.py,sha256=xgWDRHvCrfCuw_qu2UaibjjQPvhwRwI6aZYevJtmQ1k,4331
+transformers/models/dinov2_with_registers/modeling_dinov2_with_registers.py,sha256=LczivGmwrbeulA_eLXaJaKemyau5ggH3wRScXVx5NoY,27696
+transformers/models/dinov2_with_registers/modular_dinov2_with_registers.py,sha256=KDfKdQUIwqijSbb1w1XyYNkrUu-C5MzwuPieELWrFJM,14617
+transformers/models/dinov3_convnext/__init__.py,sha256=8VOE7Jnq3g2JBuwkVcsFoZEerdZF5dn2p5XZ26BMRY4,1011
+transformers/models/dinov3_convnext/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/dinov3_convnext/__pycache__/configuration_dinov3_convnext.cpython-312.pyc,,
+transformers/models/dinov3_convnext/__pycache__/modeling_dinov3_convnext.cpython-312.pyc,,
+transformers/models/dinov3_convnext/configuration_dinov3_convnext.py,sha256=8mko7VN1lRu4Ku8vZlu_nRNgsVuVWO2iO351RGQh7xM,2512
+transformers/models/dinov3_convnext/modeling_dinov3_convnext.py,sha256=dug8FkrjrS5qqqrOqxO-gYlcLaT9YcE_QJIkDzLIGlY,11595
+transformers/models/dinov3_vit/__init__.py,sha256=UaLl9teE_xbD4QmUznETTbT_VaOryMyuk9T7ojfg67Y,1048
+transformers/models/dinov3_vit/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/dinov3_vit/__pycache__/configuration_dinov3_vit.cpython-312.pyc,,
+transformers/models/dinov3_vit/__pycache__/image_processing_dinov3_vit.cpython-312.pyc,,
+transformers/models/dinov3_vit/__pycache__/modeling_dinov3_vit.cpython-312.pyc,,
+transformers/models/dinov3_vit/__pycache__/modular_dinov3_vit.cpython-312.pyc,,
+transformers/models/dinov3_vit/configuration_dinov3_vit.py,sha256=mhPTyeqAIKrtcFfbKKf_4P_ZuwlKYXgmG8xF7QTpu_w,4554
+transformers/models/dinov3_vit/image_processing_dinov3_vit.py,sha256=BO_PXtu9ZN0KytKSAa9mw2gHcLbBC8X67dC-jKOxFyA,3603
+transformers/models/dinov3_vit/modeling_dinov3_vit.py,sha256=hi5Cumbzs3TJbI6uO81p3DRLZesNux93AUObvM8lZNE,26041
+transformers/models/dinov3_vit/modular_dinov3_vit.py,sha256=BIBM5R5Tj44U4_1phYPLUfVQVN7v1rW6SMSE7LGAQ38,21516
+transformers/models/distilbert/__init__.py,sha256=g2DClKY8TLVEIIc78BEBK1nFt50A0aVoL2o3OVuF_yE,1087
+transformers/models/distilbert/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/distilbert/__pycache__/configuration_distilbert.cpython-312.pyc,,
+transformers/models/distilbert/__pycache__/modeling_distilbert.cpython-312.pyc,,
+transformers/models/distilbert/__pycache__/tokenization_distilbert.cpython-312.pyc,,
+transformers/models/distilbert/configuration_distilbert.py,sha256=Wlr1Mh4TFVEvnaWMXWgvt5sFnhStxYbJ-nmjBJJygHs,2739
+transformers/models/distilbert/modeling_distilbert.py,sha256=V9pcTSJRxdi4ieDCL8dXy5dGt0rm4mPUfQTYUO0PO6w,39904
+transformers/models/distilbert/tokenization_distilbert.py,sha256=BeXGmu3Y-cDILXqWBBWipyXXTluNyemzkquubE2lhFs,1716
+transformers/models/dit/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+transformers/models/dit/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/doge/__init__.py,sha256=VtPJpOlqDfo3mV2yzOowL6LTgQkm61JpmgaSmQX18t4,1009
+transformers/models/doge/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/doge/__pycache__/configuration_doge.cpython-312.pyc,,
+transformers/models/doge/__pycache__/modeling_doge.cpython-312.pyc,,
+transformers/models/doge/__pycache__/modular_doge.cpython-312.pyc,,
+transformers/models/doge/configuration_doge.py,sha256=pe0XVMcNc5K_GCYVZCv-8yRcH6vz-ruX4DNm5Ixy4Ag,4741
+transformers/models/doge/modeling_doge.py,sha256=Grv5xSAwQj7dy1ThnF8bIoDAIJjhL6hLTYm3iS3tY1w,36445
+transformers/models/doge/modular_doge.py,sha256=9SvwWpRNaTZftv9ukOckTmyqwGldeRuByfllRz_U18Q,27240
+transformers/models/donut/__init__.py,sha256=iams_uoaCepQylfk4gbtOHTPskQleTUASc8C8ZPWN3I,1125
+transformers/models/donut/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/donut/__pycache__/configuration_donut_swin.cpython-312.pyc,,
+transformers/models/donut/__pycache__/image_processing_donut.cpython-312.pyc,,
+transformers/models/donut/__pycache__/image_processing_pil_donut.cpython-312.pyc,,
+transformers/models/donut/__pycache__/modeling_donut_swin.cpython-312.pyc,,
+transformers/models/donut/__pycache__/processing_donut.cpython-312.pyc,,
+transformers/models/donut/configuration_donut_swin.py,sha256=5w5tRa6G16A8TJEIjznS4SzV1Jq7JkXDiEwv7BItFtI,2627
+transformers/models/donut/image_processing_donut.py,sha256=595eAVaTuDRqQMvhYpsxKjpSYI335lFAm0RhTC_JXgw,7658
+transformers/models/donut/image_processing_pil_donut.py,sha256=VY6sNmHReu4SFZN_4oeWsqVCWuj3ABTDE7SLcpiXdvI,7411
+transformers/models/donut/modeling_donut_swin.py,sha256=YONYckzzKiF6lVDH_AlphfNAkd_EnshMTV-w0asH7ZM,41827
+transformers/models/donut/processing_donut.py,sha256=lBJU3ezF9anLjKfhib448PCzwZ8q1WDOLH-fAdlr6dk,5287
+transformers/models/dots1/__init__.py,sha256=A2jXARtNWOrbWAW2SIrsvvydm2_2keRyUBbNEz0By-I,991
+transformers/models/dots1/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/dots1/__pycache__/configuration_dots1.cpython-312.pyc,,
+transformers/models/dots1/__pycache__/modeling_dots1.cpython-312.pyc,,
+transformers/models/dots1/__pycache__/modular_dots1.cpython-312.pyc,,
+transformers/models/dots1/configuration_dots1.py,sha256=fniHtG-6ZTjg32N3SlPg0aSrl54MUkTk_w1hO8DqobQ,5131
+transformers/models/dots1/modeling_dots1.py,sha256=n61LSBibCnREqL2iZscYcfUVGxR6HRLCnHwSaE1232c,28704
+transformers/models/dots1/modular_dots1.py,sha256=MKEsFGpt82rdxoRKxNYFEXR7pwXZClsISTPKLKklr0c,6748
+transformers/models/dpr/__init__.py,sha256=YLpIDXI8WhGlQM_ED82JpDIdk4k0C8HKgw5Qigt5NkY,1064
+transformers/models/dpr/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/dpr/__pycache__/configuration_dpr.cpython-312.pyc,,
+transformers/models/dpr/__pycache__/modeling_dpr.cpython-312.pyc,,
+transformers/models/dpr/__pycache__/tokenization_dpr.cpython-312.pyc,,
+transformers/models/dpr/__pycache__/tokenization_dpr_fast.cpython-312.pyc,,
+transformers/models/dpr/configuration_dpr.py,sha256=49a-KOdsddl3QG0bc_f8sAYr8WR5iobcPUkSyiv28pY,2052
+transformers/models/dpr/modeling_dpr.py,sha256=cYtZb-QaFzCGUPb_YJXOFezMJLMfdQhqPA4BEy5twWw,21836
+transformers/models/dpr/tokenization_dpr.py,sha256=7cfukFJ146eWUSK2euLdUWbZeVjpltfEapqB6aliLGY,16128
+transformers/models/dpr/tokenization_dpr_fast.py,sha256=ObKSKMda0tBWvBA1uNjQlZMtNK0EJ3b7qUkXDRhgd38,16020
+transformers/models/dpt/__init__.py,sha256=xjlxTpuEb30SefvnzewFd7qVjEmM6xCf8PrAQh2LR-I,1071
+transformers/models/dpt/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/dpt/__pycache__/configuration_dpt.cpython-312.pyc,,
+transformers/models/dpt/__pycache__/image_processing_dpt.cpython-312.pyc,,
+transformers/models/dpt/__pycache__/image_processing_pil_dpt.cpython-312.pyc,,
+transformers/models/dpt/__pycache__/modeling_dpt.cpython-312.pyc,,
+transformers/models/dpt/__pycache__/modular_dpt.cpython-312.pyc,,
+transformers/models/dpt/configuration_dpt.py,sha256=MvtOWEQp5w2sHQ90zCvIjhapdc-D12TynsyAIBGSQJ4,7759
+transformers/models/dpt/image_processing_dpt.py,sha256=8ZhPxeIT5aoO7jyWiQQjDBP12lORSBG6s7mG2zBOOxI,17304
+transformers/models/dpt/image_processing_pil_dpt.py,sha256=dw9Mqe2r_Af6SDeMlGluNxCtb7omjvIxA6NQcmsVGLw,12021
+transformers/models/dpt/modeling_dpt.py,sha256=l_qxYIKtEs8M2B7yFHF-v62zYT7A6DZAHxjXCj5JsrA,48575
+transformers/models/dpt/modular_dpt.py,sha256=jBTmUz9eTCf8H_EpJRnN5mH5VbnItrf6YJKjlTZ67f4,11336
+transformers/models/edgetam/__init__.py,sha256=oGzMZGNhQp2fv5UQEYcLdYLUIRQEnn3_vucmlOvmM_o,995
+transformers/models/edgetam/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/edgetam/__pycache__/configuration_edgetam.cpython-312.pyc,,
+transformers/models/edgetam/__pycache__/modeling_edgetam.cpython-312.pyc,,
+transformers/models/edgetam/__pycache__/modular_edgetam.cpython-312.pyc,,
+transformers/models/edgetam/configuration_edgetam.py,sha256=0ZcedvW7Wxj1ver7ahhFoSPPjVQjL24qgVUJ9Pb6-j4,9846
+transformers/models/edgetam/modeling_edgetam.py,sha256=JdDpAH5I5M8nnEWn5sNgWuTCLpADGil7_BicVE4QMH8,59339
+transformers/models/edgetam/modular_edgetam.py,sha256=Y7jcjSIH2wiPbrvvhlj4omaAFzfHdiWkKswqs07xqTM,9404
+transformers/models/edgetam_video/__init__.py,sha256=aNgAv9cdlvg857E879-BnK4HwZ-LuC1LC2fw8hOPtFU,1008
+transformers/models/edgetam_video/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/edgetam_video/__pycache__/configuration_edgetam_video.cpython-312.pyc,,
+transformers/models/edgetam_video/__pycache__/modeling_edgetam_video.cpython-312.pyc,,
+transformers/models/edgetam_video/__pycache__/modular_edgetam_video.cpython-312.pyc,,
+transformers/models/edgetam_video/configuration_edgetam_video.py,sha256=jZuK_okf0YfCRCcb5SvYC9i_D7uAu48iDYdc_AWtLnY,16306
+transformers/models/edgetam_video/modeling_edgetam_video.py,sha256=-5jLFsXc5SOGBqOTKBGA_dfxAA-F-vV4Z0XLzSJVJJw,147028
+transformers/models/edgetam_video/modular_edgetam_video.py,sha256=Dan0IfPEffAn-5RY32Wxx4yKq-zAsyUoEx9ZKCYPwns,66666
+transformers/models/efficientloftr/__init__.py,sha256=Io1FDdvUHq3pR_2gxWb_--m6qhhcXfVigixPRioomWI,1115
+transformers/models/efficientloftr/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/efficientloftr/__pycache__/configuration_efficientloftr.cpython-312.pyc,,
+transformers/models/efficientloftr/__pycache__/image_processing_efficientloftr.cpython-312.pyc,,
+transformers/models/efficientloftr/__pycache__/image_processing_pil_efficientloftr.cpython-312.pyc,,
+transformers/models/efficientloftr/__pycache__/modeling_efficientloftr.cpython-312.pyc,,
+transformers/models/efficientloftr/__pycache__/modular_efficientloftr.cpython-312.pyc,,
+transformers/models/efficientloftr/configuration_efficientloftr.py,sha256=EZg7T15PpIq6VqcaHINMxNUc1NH3dOUmT_m7u1LRv6k,6250
+transformers/models/efficientloftr/image_processing_efficientloftr.py,sha256=9hMs5484g5d8gxNM7NW2_eFTvH0XleR3uyScsck5aYY,12694
+transformers/models/efficientloftr/image_processing_pil_efficientloftr.py,sha256=16zc8O9SqPQXoX88rDRb4OiBp37GnNh2lcN70GaKVno,11656
+transformers/models/efficientloftr/modeling_efficientloftr.py,sha256=9DHWE0Z5ws-F8B-9IvpQMalGDxbCrA8-Qqrb19MK2sU,61444
+transformers/models/efficientloftr/modular_efficientloftr.py,sha256=i9-BcFebW1mwrcIYr0jTj8_GMt6Mwud67EiGitBcWr4,6576
+transformers/models/efficientnet/__init__.py,sha256=9jZKTogz1Q2M33cWf8LGJzpDmxTvSzyeLf7RDygjXw8,1107
+transformers/models/efficientnet/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/efficientnet/__pycache__/configuration_efficientnet.cpython-312.pyc,,
+transformers/models/efficientnet/__pycache__/image_processing_efficientnet.cpython-312.pyc,,
+transformers/models/efficientnet/__pycache__/image_processing_pil_efficientnet.cpython-312.pyc,,
+transformers/models/efficientnet/__pycache__/modeling_efficientnet.cpython-312.pyc,,
+transformers/models/efficientnet/configuration_efficientnet.py,sha256=-xQ8ZdTarRYsXDMew8qvxcMSbAwMwgn9y2nQpLkvRu8,4180
+transformers/models/efficientnet/image_processing_efficientnet.py,sha256=IrfKM0nfofkeScoQBuCfDKjlr-xuF46unxZ0s2-ItJ0,6633
+transformers/models/efficientnet/image_processing_pil_efficientnet.py,sha256=vcK_FEFra7J06nC_Y3_0CYiTyQ3h8Eh4mC54cvvomrU,4052
+transformers/models/efficientnet/modeling_efficientnet.py,sha256=A0SSLeIK22CazPlcCXBjnB-228HcMAcHrT-UZoXq01A,20358
+transformers/models/electra/__init__.py,sha256=foRaRrXexLO6dUKs4iPX0nc27V1AuGrUur66Ih64Zk4,1070
+transformers/models/electra/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/electra/__pycache__/configuration_electra.cpython-312.pyc,,
+transformers/models/electra/__pycache__/modeling_electra.cpython-312.pyc,,
+transformers/models/electra/configuration_electra.py,sha256=RV0B7g_tCUfMru0NKfjh3dGZjYBryfLYWKRYG7o6tJA,3754
+transformers/models/electra/modeling_electra.py,sha256=gdIu1LMaD7Uw3H610sfI8cHCJIiKJzfL4P5_LQC0F5w,57284
+transformers/models/emu3/__init__.py,sha256=VEBLADqeToacty2xd3Zu0F_fLQRxvhfiKPkuB9jwcFM,1070
+transformers/models/emu3/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/emu3/__pycache__/configuration_emu3.cpython-312.pyc,,
+transformers/models/emu3/__pycache__/image_processing_emu3.cpython-312.pyc,,
+transformers/models/emu3/__pycache__/modeling_emu3.cpython-312.pyc,,
+transformers/models/emu3/__pycache__/modular_emu3.cpython-312.pyc,,
+transformers/models/emu3/__pycache__/processing_emu3.cpython-312.pyc,,
+transformers/models/emu3/configuration_emu3.py,sha256=9ly-5ef4oDt4kPcLyWPv_5eSIGmzm6h305QU6GcCEHs,5245
+transformers/models/emu3/image_processing_emu3.py,sha256=6t4fq5s9DRWC4h2k_t-Qpws_h4gA2m_r_8TZfefyuJU,27364
+transformers/models/emu3/modeling_emu3.py,sha256=cFItjqEEu3ZMUwlXc7_z_BCzxoImqWvQUgmHXTPjdXI,66327
+transformers/models/emu3/modular_emu3.py,sha256=fVwLatV_1bj3a8J2ysN3FGfi9qVJkYemkXNrpdSpv28,47265
+transformers/models/emu3/processing_emu3.py,sha256=F43OE96cpPT8SMeuni0oNNlqOppSUZiqIWYPRfWm58U,11297
+transformers/models/encodec/__init__.py,sha256=QbO9yEfCaRwYKbK0vvmwKMbqRAToyos-HTHhRmf7n5s,1041
+transformers/models/encodec/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/encodec/__pycache__/configuration_encodec.cpython-312.pyc,,
+transformers/models/encodec/__pycache__/feature_extraction_encodec.cpython-312.pyc,,
+transformers/models/encodec/__pycache__/modeling_encodec.cpython-312.pyc,,
+transformers/models/encodec/configuration_encodec.py,sha256=3VdlF-sgZeNVgxMJ5-tqb832tJkE61oIyAqnPHKZ2bE,6613
+transformers/models/encodec/feature_extraction_encodec.py,sha256=sVGWrleWmP3YZodQeRg6FU3mlLWPxjc-m4vK-qI_E0g,9784
+transformers/models/encodec/modeling_encodec.py,sha256=aKbj7v8GB4zOvL_YuK_U5TdVC76tiY3FhyQUFU_fkpg,34743
+transformers/models/encoder_decoder/__init__.py,sha256=NRHrw_Gq2RpeLthXifL3JiePYtsXaetRuhXbVkQtQUs,1011
+transformers/models/encoder_decoder/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/encoder_decoder/__pycache__/configuration_encoder_decoder.cpython-312.pyc,,
+transformers/models/encoder_decoder/__pycache__/modeling_encoder_decoder.cpython-312.pyc,,
+transformers/models/encoder_decoder/configuration_encoder_decoder.py,sha256=_Ae0dLNQ2pu1-4SV8sgNJ8nvXRkVKQ3YmKwgu6Dch38,3941
+transformers/models/encoder_decoder/modeling_encoder_decoder.py,sha256=pEqlbWC7pP1cWgky367MVq0ljEQyTdqFFZoSBG2Siis,22432
+transformers/models/eomt/__init__.py,sha256=u4I4905F6pGDMp9jHMF4tkj80DVKlNCE7IzkJMCGfh4,1075
+transformers/models/eomt/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/eomt/__pycache__/configuration_eomt.cpython-312.pyc,,
+transformers/models/eomt/__pycache__/image_processing_eomt.cpython-312.pyc,,
+transformers/models/eomt/__pycache__/image_processing_pil_eomt.cpython-312.pyc,,
+transformers/models/eomt/__pycache__/modeling_eomt.cpython-312.pyc,,
+transformers/models/eomt/__pycache__/modular_eomt.cpython-312.pyc,,
+transformers/models/eomt/configuration_eomt.py,sha256=UR377diflIVGzFmx46bmrjvdNBNrjxtVG3Pf124KFWU,4465
+transformers/models/eomt/image_processing_eomt.py,sha256=2r7nhN213MUFPTeexVUyJCf635lirY4jexg6PowT_XM,27044
+transformers/models/eomt/image_processing_pil_eomt.py,sha256=G0xQLrzJbUTWqnVqLSzPqpBfuAC44oCg6CV5Awi4B_U,25763
+transformers/models/eomt/modeling_eomt.py,sha256=T55GJL_AkgRmU3z2CeoVWEiGnK8drERkK673eg3rKFI,54396
+transformers/models/eomt/modular_eomt.py,sha256=Kd54PacfikDth_aVqVc9A7lZzSRpbXPy4oCsX_0rCRE,22447
+transformers/models/eomt_dinov3/__init__.py,sha256=Z1U6ubtfNVB84kWYgRZX1bZy1vrJCVHKB_vfU9H1TwU,1004
+transformers/models/eomt_dinov3/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/eomt_dinov3/__pycache__/configuration_eomt_dinov3.cpython-312.pyc,,
+transformers/models/eomt_dinov3/__pycache__/modeling_eomt_dinov3.cpython-312.pyc,,
+transformers/models/eomt_dinov3/__pycache__/modular_eomt_dinov3.cpython-312.pyc,,
+transformers/models/eomt_dinov3/configuration_eomt_dinov3.py,sha256=VckzWUFgbRQtbXhXEOZMZHqOugvR7H3O2-OcyogoEpw,5045
+transformers/models/eomt_dinov3/modeling_eomt_dinov3.py,sha256=mFYu8Grw-8AhPJxmHLU2tVU_JRmlac92u3lRq1twQbA,61097
+transformers/models/eomt_dinov3/modular_eomt_dinov3.py,sha256=6Ku8Jv0eiMxvi2U0Nrm9bh7V-LtXfE3kh5pukwf5lVU,14960
+transformers/models/ernie/__init__.py,sha256=TyzaXpzGwu-WqsIn1tavDqa7BCV9X-mPho4JDa9gk0I,991
+transformers/models/ernie/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/ernie/__pycache__/configuration_ernie.cpython-312.pyc,,
+transformers/models/ernie/__pycache__/modeling_ernie.cpython-312.pyc,,
+transformers/models/ernie/__pycache__/modular_ernie.cpython-312.pyc,,
+transformers/models/ernie/configuration_ernie.py,sha256=J29ol1lIbebo_XMNKhyxZCvFFG592FaxJpZ-ifeCw7w,2515
+transformers/models/ernie/modeling_ernie.py,sha256=1vgfFqXQjR-Cs9fN_RIzy8c3ja9_wAP2X-b59r-PJ7k,62599
+transformers/models/ernie/modular_ernie.py,sha256=JcP9Blo3xJFBIvnR1M5OejViOBqJ4n9_WnApz-0X3Gg,36072
+transformers/models/ernie4_5/__init__.py,sha256=5tqpitaOWvT1CdXTgMtMLCKIkUG683y3jdcTZ8yuwfM,997
+transformers/models/ernie4_5/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/ernie4_5/__pycache__/configuration_ernie4_5.cpython-312.pyc,,
+transformers/models/ernie4_5/__pycache__/modeling_ernie4_5.cpython-312.pyc,,
+transformers/models/ernie4_5/__pycache__/modular_ernie4_5.cpython-312.pyc,,
+transformers/models/ernie4_5/configuration_ernie4_5.py,sha256=NmvM09fWcq7fc24nktMwnm2Op0pSLA7XPm_n94uQwSM,3253
+transformers/models/ernie4_5/modeling_ernie4_5.py,sha256=fG99NvxdRHrYclMdA9tL6qaeZSS2E8t0-MwAAsDevDQ,20906
+transformers/models/ernie4_5/modular_ernie4_5.py,sha256=4YfZKWndgZRrdXIKSTBgGN4QpRGzSTr0dkDgGxGrgiA,5613
+transformers/models/ernie4_5_moe/__init__.py,sha256=MJaAQxyB3YypXN79FGJpkSvnX6KWt86iunOFXjiA7a4,1005
+transformers/models/ernie4_5_moe/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/ernie4_5_moe/__pycache__/configuration_ernie4_5_moe.cpython-312.pyc,,
+transformers/models/ernie4_5_moe/__pycache__/modeling_ernie4_5_moe.cpython-312.pyc,,
+transformers/models/ernie4_5_moe/__pycache__/modular_ernie4_5_moe.cpython-312.pyc,,
+transformers/models/ernie4_5_moe/configuration_ernie4_5_moe.py,sha256=vjRWfi1hoZ9S5oCDHtuqjXH1eoMwEhZSV8TJAx7DIrw,4782
+transformers/models/ernie4_5_moe/modeling_ernie4_5_moe.py,sha256=j8_eNGT1ygId816PVrNzzJ-xuxtB3vFa_YLiwMcZETE,32191
+transformers/models/ernie4_5_moe/modular_ernie4_5_moe.py,sha256=j-gi2CGOeFjdg3hFIUTpAoSIj39y35hKT8upCB_P9X0,12883
+transformers/models/ernie4_5_vl_moe/__init__.py,sha256=uK_ZnQ3aTLY0DLAyTlBd2sOF-WN8EXwOsEGk0FJD6tY,1240
+transformers/models/ernie4_5_vl_moe/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/ernie4_5_vl_moe/__pycache__/configuration_ernie4_5_vl_moe.cpython-312.pyc,,
+transformers/models/ernie4_5_vl_moe/__pycache__/image_processing_ernie4_5_vl_moe.cpython-312.pyc,,
+transformers/models/ernie4_5_vl_moe/__pycache__/image_processing_pil_ernie4_5_vl_moe.cpython-312.pyc,,
+transformers/models/ernie4_5_vl_moe/__pycache__/modeling_ernie4_5_vl_moe.cpython-312.pyc,,
+transformers/models/ernie4_5_vl_moe/__pycache__/modular_ernie4_5_vl_moe.cpython-312.pyc,,
+transformers/models/ernie4_5_vl_moe/__pycache__/processing_ernie4_5_vl_moe.cpython-312.pyc,,
+transformers/models/ernie4_5_vl_moe/__pycache__/video_processing_ernie4_5_vl_moe.cpython-312.pyc,,
+transformers/models/ernie4_5_vl_moe/configuration_ernie4_5_vl_moe.py,sha256=AUVylQtwJA8DJSjUeg9SZy_ULr2F5ezLf9wutzxfVK4,9244
+transformers/models/ernie4_5_vl_moe/image_processing_ernie4_5_vl_moe.py,sha256=6_U2oT6jumkx5wLjincP3XNaImjFQS5KrhF5rC2fE4s,10623
+transformers/models/ernie4_5_vl_moe/image_processing_pil_ernie4_5_vl_moe.py,sha256=l5RlXLw6ojrm_iN0FgmYIIJoGrs8E3tiuYeqCfgYZN8,10176
+transformers/models/ernie4_5_vl_moe/modeling_ernie4_5_vl_moe.py,sha256=3UICoWGFhEKHcjU8pMk8GXSvyS0phTB51DCy7_nnwZM,89237
+transformers/models/ernie4_5_vl_moe/modular_ernie4_5_vl_moe.py,sha256=3Jjw2zZgoekMbe7LH9wiuqTZKTttsUeagg9pkJVqTHM,66917
+transformers/models/ernie4_5_vl_moe/processing_ernie4_5_vl_moe.py,sha256=q6HooGYPyGaYqM_KAlbIQ7ZOfypWFEhvznGR7U35eqo,12783
+transformers/models/ernie4_5_vl_moe/video_processing_ernie4_5_vl_moe.py,sha256=7__OF4sCQyWd6H76f8tmDo4zwcLZSxML7eM68LnSRY0,25988
+transformers/models/esm/__init__.py,sha256=TT8AHFpMRg_GNzhHdNTdh120qHr5TIal5Aouok1vTCM,1059
+transformers/models/esm/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/esm/__pycache__/configuration_esm.cpython-312.pyc,,
+transformers/models/esm/__pycache__/modeling_esm.cpython-312.pyc,,
+transformers/models/esm/__pycache__/modeling_esmfold.cpython-312.pyc,,
+transformers/models/esm/__pycache__/tokenization_esm.cpython-312.pyc,,
+transformers/models/esm/configuration_esm.py,sha256=DIgBSY8bncTizk5lSn1cdM16q1TKye-KVqBK-5zdA98,10091
+transformers/models/esm/modeling_esm.py,sha256=_5n65VSwgctu2tuIjrkev5weu78vKufxXF7FdGIfNfc,44204
+transformers/models/esm/modeling_esmfold.py,sha256=wvD3AbxVxkkG0NMNlkcumE16m1riyZOzkouAWOjj80I,85457
+transformers/models/esm/openfold_utils/__init__.py,sha256=Xy2uqvFsLC8Ax-OOce5PgoBDiZgEJgJPqs__p5SBWUY,446
+transformers/models/esm/openfold_utils/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/esm/openfold_utils/__pycache__/chunk_utils.cpython-312.pyc,,
+transformers/models/esm/openfold_utils/__pycache__/data_transforms.cpython-312.pyc,,
+transformers/models/esm/openfold_utils/__pycache__/feats.cpython-312.pyc,,
+transformers/models/esm/openfold_utils/__pycache__/loss.cpython-312.pyc,,
+transformers/models/esm/openfold_utils/__pycache__/protein.cpython-312.pyc,,
+transformers/models/esm/openfold_utils/__pycache__/residue_constants.cpython-312.pyc,,
+transformers/models/esm/openfold_utils/__pycache__/rigid_utils.cpython-312.pyc,,
+transformers/models/esm/openfold_utils/__pycache__/tensor_utils.cpython-312.pyc,,
+transformers/models/esm/openfold_utils/chunk_utils.py,sha256=LoQvShWGqJyLyyHp9RB3P7ct8a87NMDKm_0FLcrCfDU,14357
+transformers/models/esm/openfold_utils/data_transforms.py,sha256=Q5J_BpJ_8Fa5fZ8nP6kPB5ops-Y4MydSQkwZ-_yMDBA,3688
+transformers/models/esm/openfold_utils/feats.py,sha256=QCYupsVINo5jJuwYk38TejNYkPlGm6Kfc1YpNUxpI8s,8355
+transformers/models/esm/openfold_utils/loss.py,sha256=ItYvWtSw-3tCUNtQjag7_kzfsKjPm8Oiy02lt1mwjqE,3661
+transformers/models/esm/openfold_utils/protein.py,sha256=MA6iShflwkUpZRwEefmT45Ll5KPU8lJ2IuJPyH2N_mI,11482
+transformers/models/esm/openfold_utils/residue_constants.py,sha256=-y44cw8jjQJakRSjn4MAMCeGhFSHoPzUCiMv9MfdGes,37875
+transformers/models/esm/openfold_utils/rigid_utils.py,sha256=gKiZUD7ngpTm7JqRJynvm-7dfrt3VLV0E0alUkFp-34,41006
+transformers/models/esm/openfold_utils/tensor_utils.py,sha256=_LAucmEB_4mVJY1oAIL1ls_5uJNpbSYv9J0PNDA6NQ8,4716
+transformers/models/esm/tokenization_esm.py,sha256=a1NTnhESsOiS3_-KdFcZgjHv93RkLi-2uANler5lIN0,5331
+transformers/models/eurobert/__init__.py,sha256=2uE76efv-JAEUyAiAkuuPLYOI20x3Vm-2Voi6c8iHc0,1060
+transformers/models/eurobert/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/eurobert/__pycache__/configuration_eurobert.cpython-312.pyc,,
+transformers/models/eurobert/__pycache__/modeling_eurobert.cpython-312.pyc,,
+transformers/models/eurobert/__pycache__/modular_eurobert.cpython-312.pyc,,
+transformers/models/eurobert/configuration_eurobert.py,sha256=Vcxhc2GfQLPy4lRwI4k-b1OnAKW5eK2BvT4l2r1L2-k,4776
+transformers/models/eurobert/modeling_eurobert.py,sha256=-_Q98b5gtCwRUiK8jAU3R0neqYqk1tJ7O8-JOsU3KcU,26091
+transformers/models/eurobert/modular_eurobert.py,sha256=nbw9rrpqWDK2na0lEjFgJCXz4puh1qG7j8DafDm3wZY,13494
+transformers/models/evolla/__init__.py,sha256=pOj8KGoc9jqtS_PYTeNCxZUtQrlFR_txE-kdZpiAkCw,1030
+transformers/models/evolla/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/evolla/__pycache__/configuration_evolla.cpython-312.pyc,,
+transformers/models/evolla/__pycache__/modeling_evolla.cpython-312.pyc,,
+transformers/models/evolla/__pycache__/modular_evolla.cpython-312.pyc,,
+transformers/models/evolla/__pycache__/processing_evolla.cpython-312.pyc,,
+transformers/models/evolla/configuration_evolla.py,sha256=4oSUPjZBgKnjBZtlEs5071IR7DUq125Yx6VLjszNDIM,6204
+transformers/models/evolla/modeling_evolla.py,sha256=bSz9uLWphoM6UFvt-RgQFMvlwyjNQ4bCsGWeoUQcVOo,64728
+transformers/models/evolla/modular_evolla.py,sha256=xoZlOV_2Dzj94uR_CLT1Dy1WF0aWmTvcBDiLFN3CdEc,34881
+transformers/models/evolla/processing_evolla.py,sha256=nj9l_xNCRBz8-wEaraNDLR5X5gZq2-snwm_iq4lowRw,8231
+transformers/models/exaone4/__init__.py,sha256=gUDbb0olRjqxaPnB3APYKYKRlDPG2phGkfrmf7mIVD4,1018
+transformers/models/exaone4/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/exaone4/__pycache__/configuration_exaone4.cpython-312.pyc,,
+transformers/models/exaone4/__pycache__/modeling_exaone4.cpython-312.pyc,,
+transformers/models/exaone4/__pycache__/modular_exaone4.cpython-312.pyc,,
+transformers/models/exaone4/configuration_exaone4.py,sha256=P3ItH6oqdeZ3SUWfiKhyW-_Uyg-5kfxfX2y1ssQrdRM,5015
+transformers/models/exaone4/modeling_exaone4.py,sha256=3RfMZNzh5l8FwE5yUNVlq4u_LaW8tkzDI0ItTau8wVU,24146
+transformers/models/exaone4/modular_exaone4.py,sha256=xNJTmVIY5_fyolAYFizzrUBCOVSb0ALB7jihNy0E8vI,15532
+transformers/models/exaone4_5/__init__.py,sha256=qgvS7G0QAm2LMXQE4_CW2ERPLCozSF9iwZMXi7dAnls,1062
+transformers/models/exaone4_5/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/exaone4_5/__pycache__/configuration_exaone4_5.cpython-312.pyc,,
+transformers/models/exaone4_5/__pycache__/modeling_exaone4_5.cpython-312.pyc,,
+transformers/models/exaone4_5/__pycache__/modular_exaone4_5.cpython-312.pyc,,
+transformers/models/exaone4_5/__pycache__/processing_exaone4_5.cpython-312.pyc,,
+transformers/models/exaone4_5/configuration_exaone4_5.py,sha256=DeAMtUl1mI3oRXtIDvIh52EOlUvq5AtmixSaQJeThGU,4232
+transformers/models/exaone4_5/modeling_exaone4_5.py,sha256=FtPP3EvtPox869sfJG_vu9qlWwsTFRjew8vah-UqdMA,47439
+transformers/models/exaone4_5/modular_exaone4_5.py,sha256=L7IR6nCjdsncNwwEMWCe0B9o083_EeAGHKu5HZpLyIk,20461
+transformers/models/exaone4_5/processing_exaone4_5.py,sha256=dMpxBtWO2zXeqkAEgsx81EuieUVRF03CUP1-za_AQ48,6741
+transformers/models/exaone_moe/__init__.py,sha256=HXJMLnAy-yxDJWMl_xQ4vgzy49kgs9xR-oWUz2MF5Xw,1024
+transformers/models/exaone_moe/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/exaone_moe/__pycache__/configuration_exaone_moe.cpython-312.pyc,,
+transformers/models/exaone_moe/__pycache__/modeling_exaone_moe.cpython-312.pyc,,
+transformers/models/exaone_moe/__pycache__/modular_exaone_moe.cpython-312.pyc,,
+transformers/models/exaone_moe/configuration_exaone_moe.py,sha256=hgWpAvpfmbnpHyCKC6cNyCPa3Pi-BBXeOi9wWhy74yU,5967
+transformers/models/exaone_moe/modeling_exaone_moe.py,sha256=vVN0toyvhrse4yEpqZ5mwGtiTkPzrnbcig_A4yrspDM,29806
+transformers/models/exaone_moe/modular_exaone_moe.py,sha256=Hv53zFavvsW4zXtbNmcjyvOujeglxR3gzLu5iyMDoBk,9957
+transformers/models/falcon/__init__.py,sha256=qmBlF_xusyrueKMfriC2ldVrHzeLIT7ruSdduMODuE4,993
+transformers/models/falcon/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/falcon/__pycache__/configuration_falcon.cpython-312.pyc,,
+transformers/models/falcon/__pycache__/modeling_falcon.cpython-312.pyc,,
+transformers/models/falcon/configuration_falcon.py,sha256=J7uE1hl6K7B6HBF24I0Gvfq5wsqVmVXbH6xFJQbAa_4,4413
+transformers/models/falcon/modeling_falcon.py,sha256=kfCG02A5IPTmW8y7sb4WiSq9NzFr54m_2cuJv1Wj2tI,55582
+transformers/models/falcon_h1/__init__.py,sha256=cpix3f3f_xMDLf2OLuyYZULnb7enZl3UZapPQuf0YZc,1012
+transformers/models/falcon_h1/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/falcon_h1/__pycache__/configuration_falcon_h1.cpython-312.pyc,,
+transformers/models/falcon_h1/__pycache__/modeling_falcon_h1.cpython-312.pyc,,
+transformers/models/falcon_h1/__pycache__/modular_falcon_h1.cpython-312.pyc,,
+transformers/models/falcon_h1/configuration_falcon_h1.py,sha256=vZls8UwOr3MH6Tn7ZXmjxHqV8RpHpFuRqxdQwYagUqo,6632
+transformers/models/falcon_h1/modeling_falcon_h1.py,sha256=GjCssBzGKyU9UyMKpQIFOV_1qtvNdBExVUKo04XIJTo,57129
+transformers/models/falcon_h1/modular_falcon_h1.py,sha256=yXi1OnqyvE2_Kbx8kjVpXmUrNM_Ze1GOBdHoXtNYn-s,44493
+transformers/models/falcon_mamba/__init__.py,sha256=Czo-T_Nt73nvRbK-yJEZAYsU3Bxu4i1fOxFuPosiFPw,1005
+transformers/models/falcon_mamba/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/falcon_mamba/__pycache__/configuration_falcon_mamba.cpython-312.pyc,,
+transformers/models/falcon_mamba/__pycache__/modeling_falcon_mamba.cpython-312.pyc,,
+transformers/models/falcon_mamba/__pycache__/modular_falcon_mamba.cpython-312.pyc,,
+transformers/models/falcon_mamba/configuration_falcon_mamba.py,sha256=VQujfEgw_3Glbupyl_dmvVFc94x6BxvG94WiV2j5nHs,5402
+transformers/models/falcon_mamba/modeling_falcon_mamba.py,sha256=VFBZ6LykoJgXY2ecmS6e2NbiPzevCexyGKvcT6jJXCc,35945
+transformers/models/falcon_mamba/modular_falcon_mamba.py,sha256=hTlbn8mMI2SLw41vBQbKsu03UFFBrXYcT40lW9G3yhU,21230
+transformers/models/fast_vlm/__init__.py,sha256=5RFlXojuEHJ2nPYyxGIADcwSQCcVg1irLZPsgZvsgcQ,997
+transformers/models/fast_vlm/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/fast_vlm/__pycache__/configuration_fast_vlm.cpython-312.pyc,,
+transformers/models/fast_vlm/__pycache__/modeling_fast_vlm.cpython-312.pyc,,
+transformers/models/fast_vlm/__pycache__/modular_fast_vlm.cpython-312.pyc,,
+transformers/models/fast_vlm/configuration_fast_vlm.py,sha256=vrcOwBSrhwdaRdJrwGDffWlCQvU6ujkZW6o9cd88PD0,5001
+transformers/models/fast_vlm/modeling_fast_vlm.py,sha256=Ep0vQfOp3I7IEmTCphghXPjynODeUvJc2darDGUUSzU,18742
+transformers/models/fast_vlm/modular_fast_vlm.py,sha256=yoVVV01tzm8IwZPdRuh3xJzcTfnRXg6xHy0jAYcHuRs,14367
+transformers/models/fastspeech2_conformer/__init__.py,sha256=pILmX51CcqSiFGtl_dsX1yW2S_QugA3UHAT8f4psOtA,1077
+transformers/models/fastspeech2_conformer/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/fastspeech2_conformer/__pycache__/configuration_fastspeech2_conformer.cpython-312.pyc,,
+transformers/models/fastspeech2_conformer/__pycache__/modeling_fastspeech2_conformer.cpython-312.pyc,,
+transformers/models/fastspeech2_conformer/__pycache__/tokenization_fastspeech2_conformer.cpython-312.pyc,,
+transformers/models/fastspeech2_conformer/configuration_fastspeech2_conformer.py,sha256=vw_jwT_wmWyih8GAqUVzy5NU4X8hpbkjT7Q77WDwAQQ,19284
+transformers/models/fastspeech2_conformer/modeling_fastspeech2_conformer.py,sha256=PDqeZc2o2d1apd9uBAaMRyD1dZi8n-UcGjTO2Wd3GNY,70264
+transformers/models/fastspeech2_conformer/tokenization_fastspeech2_conformer.py,sha256=F5D0ttj52fzIrhefFP-w7v1GQANukmv-sYW1b117hZQ,6256
+transformers/models/flaubert/__init__.py,sha256=qjdNghRds8za303ngqPdZ5rqK6zT84rcumEAjitmWi4,1038
+transformers/models/flaubert/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/flaubert/__pycache__/configuration_flaubert.cpython-312.pyc,,
+transformers/models/flaubert/__pycache__/modeling_flaubert.cpython-312.pyc,,
+transformers/models/flaubert/__pycache__/tokenization_flaubert.cpython-312.pyc,,
+transformers/models/flaubert/configuration_flaubert.py,sha256=rRyT5ueCjcPQgBuB6jozgmXhTzQ4Xk7RpUm4xA2TeXI,6981
+transformers/models/flaubert/modeling_flaubert.py,sha256=FuYDZDYZhlVTDGqEx7KPtqGdAQMvq9Fpqba06qOYuEs,77456
+transformers/models/flaubert/tokenization_flaubert.py,sha256=CoczyQLIL-XC4V0ug7tr3rL132vKugO2JFaeU2dq9YA,20919
+transformers/models/flava/__init__.py,sha256=8tQXW-hJ2UROdvcXE_0vtnbI3OjLgTGGb88-b50z3VI,1159
+transformers/models/flava/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/flava/__pycache__/configuration_flava.cpython-312.pyc,,
+transformers/models/flava/__pycache__/image_processing_flava.cpython-312.pyc,,
+transformers/models/flava/__pycache__/image_processing_pil_flava.cpython-312.pyc,,
+transformers/models/flava/__pycache__/modeling_flava.cpython-312.pyc,,
+transformers/models/flava/__pycache__/processing_flava.cpython-312.pyc,,
+transformers/models/flava/configuration_flava.py,sha256=jlmOEjPPe6ufeON7nlt1AUrO9TbuU0ej3P1I5-5KzAk,18811
+transformers/models/flava/image_processing_flava.py,sha256=uGwP593vtHonJ2raE5jgloe0OLjZ1_fhkiPrxdYFUZ4,21107
+transformers/models/flava/image_processing_pil_flava.py,sha256=1cUdRH33Uuu3mPyOU4QuXGVv27QlkNINQO3xu773gZA,20476
+transformers/models/flava/modeling_flava.py,sha256=IXLGgDqCwbWvfasncuMWQToweK76GHE9U16WbZN5p0E,89001
+transformers/models/flava/processing_flava.py,sha256=gZiybXA2r8vs1P9AxGalkHDlcM6scMUhWNUyeyUe0JU,974
+transformers/models/flex_olmo/__init__.py,sha256=6_Fhd7qPsgNuP-c5XXBFy6YvzC_qExXPzfR48w19o3c,1000
+transformers/models/flex_olmo/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/flex_olmo/__pycache__/configuration_flex_olmo.cpython-312.pyc,,
+transformers/models/flex_olmo/__pycache__/modeling_flex_olmo.cpython-312.pyc,,
+transformers/models/flex_olmo/__pycache__/modular_flex_olmo.cpython-312.pyc,,
+transformers/models/flex_olmo/configuration_flex_olmo.py,sha256=gK19ZvMpNDVIOd5g-0cSuCMY3ZajqL_qV0MRoAnhxHM,4260
+transformers/models/flex_olmo/modeling_flex_olmo.py,sha256=5oQAyT1fH3kd-C85KfgvqZSU8V81foR9wEqHYNKUR-U,30638
+transformers/models/flex_olmo/modular_flex_olmo.py,sha256=mJTv64fsNnrRw8AJpfx6rYlNtBEiWg_cjojJQLGL-cs,9741
+transformers/models/florence2/__init__.py,sha256=H4rJT4tWJithwWolb041i7SM693Y_-oO8hhdePbjYpY,1039
+transformers/models/florence2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/florence2/__pycache__/configuration_florence2.cpython-312.pyc,,
+transformers/models/florence2/__pycache__/modeling_florence2.cpython-312.pyc,,
+transformers/models/florence2/__pycache__/modular_florence2.cpython-312.pyc,,
+transformers/models/florence2/__pycache__/processing_florence2.cpython-312.pyc,,
+transformers/models/florence2/configuration_florence2.py,sha256=GTu68EbmIdWMqNqTpVBjmnm-ECTMCHY0rvShEFaXLj0,5833
+transformers/models/florence2/modeling_florence2.py,sha256=qdMSASvz3LF_Y4Z3xQinCryk89yVhz1yuigPgr4m3K0,40991
+transformers/models/florence2/modular_florence2.py,sha256=NrSVcmpLi5Hl0clIh304JJAAA6v7wfIq15liEGHJg_c,71003
+transformers/models/florence2/processing_florence2.py,sha256=2MRRHDBrM1C3j1Dl81abTOuNPJse98Jpshlsefr1seo,34181
+transformers/models/fnet/__init__.py,sha256=mgas9n6aWayAl9GsoRBmd70n-8gTEB0vq6hXceuu4QE,1057
+transformers/models/fnet/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/fnet/__pycache__/configuration_fnet.cpython-312.pyc,,
+transformers/models/fnet/__pycache__/modeling_fnet.cpython-312.pyc,,
+transformers/models/fnet/__pycache__/tokenization_fnet.cpython-312.pyc,,
+transformers/models/fnet/configuration_fnet.py,sha256=EdtZhknw9vZZLqgPdlboXoXFpXjthlsKMTQSbbO9Ew0,2526
+transformers/models/fnet/modeling_fnet.py,sha256=sBdq0bEBfdU12np8-5A121hOFFjlQzy9jhqEwkNOTf0,42576
+transformers/models/fnet/tokenization_fnet.py,sha256=udORINJoinlRY1mE-K5CKF2RUZOFHcwW5xN2xXfWO-g,3226
+transformers/models/focalnet/__init__.py,sha256=kFk7pYv4troBIWdCYosHMKh8PAnpXqjlxaRRQ5adkG0,997
+transformers/models/focalnet/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/focalnet/__pycache__/configuration_focalnet.cpython-312.pyc,,
+transformers/models/focalnet/__pycache__/modeling_focalnet.cpython-312.pyc,,
+transformers/models/focalnet/configuration_focalnet.py,sha256=gSQoPOZ0mIwYgtaOrpoKGy_2WMaGyNUkUjonQPt5Eqw,4254
+transformers/models/focalnet/modeling_focalnet.py,sha256=psYq29hLAnxqRHuNIvYDyTdp5Wf9ad-1Ltp8BjGx7v4,36580
+transformers/models/fsmt/__init__.py,sha256=u_Xx7d3qDicqwR_W0js1h2wPiLKWM1RlMu7fsBdIHy4,1026
+transformers/models/fsmt/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/fsmt/__pycache__/configuration_fsmt.cpython-312.pyc,,
+transformers/models/fsmt/__pycache__/modeling_fsmt.cpython-312.pyc,,
+transformers/models/fsmt/__pycache__/tokenization_fsmt.cpython-312.pyc,,
+transformers/models/fsmt/configuration_fsmt.py,sha256=n9GHnqFp7NeGIIfaatBbzVMm3nQZYtMCrSbSHqIh8UE,4267
+transformers/models/fsmt/modeling_fsmt.py,sha256=-XHMkbIyfshklQwp4UGDdb1D67wQx1rYbQTS2hbxCAQ,46353
+transformers/models/fsmt/tokenization_fsmt.py,sha256=SUXZffNt4x4Rc3xgB3XP2pled00mgCRpkNxy9pMrr1U,17893
+transformers/models/funnel/__init__.py,sha256=Splt8ur4jydU5mQDedRgc9OIezrmQdoOXtEMb6AURDU,1100
+transformers/models/funnel/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/funnel/__pycache__/configuration_funnel.cpython-312.pyc,,
+transformers/models/funnel/__pycache__/modeling_funnel.cpython-312.pyc,,
+transformers/models/funnel/__pycache__/tokenization_funnel.cpython-312.pyc,,
+transformers/models/funnel/configuration_funnel.py,sha256=_YRNKSHP8lEgn40QkF-kktyiMXnV-McaxhQHVkRK_9A,4609
+transformers/models/funnel/modeling_funnel.py,sha256=19ms2QjDC-cTjiTniD_VrDkuTub640Ug5ZxG9wCf_LY,57825
+transformers/models/funnel/tokenization_funnel.py,sha256=G2HlIGS88ivH_5DF1F7-L9Ww72RdzSYDO6XiqzZTuTI,6792
+transformers/models/fuyu/__init__.py,sha256=CW0kn1R0d5agCbOD-Qr5mOIwkvYJLul8e-CMeIL4jtA,1110
+transformers/models/fuyu/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/fuyu/__pycache__/configuration_fuyu.cpython-312.pyc,,
+transformers/models/fuyu/__pycache__/image_processing_fuyu.cpython-312.pyc,,
+transformers/models/fuyu/__pycache__/image_processing_pil_fuyu.cpython-312.pyc,,
+transformers/models/fuyu/__pycache__/modeling_fuyu.cpython-312.pyc,,
+transformers/models/fuyu/__pycache__/processing_fuyu.cpython-312.pyc,,
+transformers/models/fuyu/configuration_fuyu.py,sha256=9p5L727rGTKbAI1nYUKBfPC6_7qea9oLCmBP31kuXwc,3822
+transformers/models/fuyu/image_processing_fuyu.py,sha256=qdHIBy5fA786Z_vxpOUrg9DI8WXCWKUlYetbLdK9fzY,18789
+transformers/models/fuyu/image_processing_pil_fuyu.py,sha256=YVVHLbfjNBNNYCl1oyy91Mtz_yvfS4MbeRDHIZgMbj0,21344
+transformers/models/fuyu/modeling_fuyu.py,sha256=MUjGa9q6z2PdqgYMbNKWqYZZ_hn48AbmnByC_t3eNUs,15162
+transformers/models/fuyu/processing_fuyu.py,sha256=g4rK_9K-ZFbNGMGGrKGBjNitviXYvSF7A1Jvd1RF0YE,35412
+transformers/models/gemma/__init__.py,sha256=LH4Ol4ZYhkhYMywv0wWsYggrcbX1UOsAMD-psGm8P-c,1072
+transformers/models/gemma/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/gemma/__pycache__/configuration_gemma.cpython-312.pyc,,
+transformers/models/gemma/__pycache__/modeling_gemma.cpython-312.pyc,,
+transformers/models/gemma/__pycache__/modular_gemma.cpython-312.pyc,,
+transformers/models/gemma/__pycache__/tokenization_gemma.cpython-312.pyc,,
+transformers/models/gemma/configuration_gemma.py,sha256=rEtt5cWpdyeNZSyo05K1_hDH6BzftyrGkbjiwxmJZ-k,3657
+transformers/models/gemma/modeling_gemma.py,sha256=Q0BAwumYSDrqXMfUi0IqVrFG-9rKsAJ5uP5fwtE8uNA,22464
+transformers/models/gemma/modular_gemma.py,sha256=5Rf0EJiTZmFmRpP1WSFfQQKrUAJ2xAEEfQM6Jvw4yhg,9618
+transformers/models/gemma/tokenization_gemma.py,sha256=_ySB4GmDAVGIV13GK9L6Dm8z7S0BFl2UDv53uA7o1Bk,3868
+transformers/models/gemma2/__init__.py,sha256=H0jWJX-AcGRTjdzkGJagKnjB6GnpqVUG4ODFhMF9OWM,993
+transformers/models/gemma2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/gemma2/__pycache__/configuration_gemma2.cpython-312.pyc,,
+transformers/models/gemma2/__pycache__/modeling_gemma2.cpython-312.pyc,,
+transformers/models/gemma2/__pycache__/modular_gemma2.cpython-312.pyc,,
+transformers/models/gemma2/configuration_gemma2.py,sha256=2B5avWiENtpXOuKZplWY0B6ocaiHTQyr61FJlnhVygc,4973
+transformers/models/gemma2/modeling_gemma2.py,sha256=P0v_-tUc7vYfHbeTiH-wkFzTLJSINXaHhTwHOmF3TsU,24396
+transformers/models/gemma2/modular_gemma2.py,sha256=MpcMSC7joNEAjb5Jgs-hVp6wSR8xUHh_jaf2I7PNluI,18445
+transformers/models/gemma3/__init__.py,sha256=aeP5EauEhI4uQY6DKbQYGlHO2AZL2UPZE37YnVQLzhw,1120
+transformers/models/gemma3/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/gemma3/__pycache__/configuration_gemma3.cpython-312.pyc,,
+transformers/models/gemma3/__pycache__/image_processing_gemma3.cpython-312.pyc,,
+transformers/models/gemma3/__pycache__/image_processing_pil_gemma3.cpython-312.pyc,,
+transformers/models/gemma3/__pycache__/modeling_gemma3.cpython-312.pyc,,
+transformers/models/gemma3/__pycache__/modular_gemma3.cpython-312.pyc,,
+transformers/models/gemma3/__pycache__/processing_gemma3.cpython-312.pyc,,
+transformers/models/gemma3/configuration_gemma3.py,sha256=mfy4Yghb3LkM-dGUUeQ02x5gCBr9R3FuXa-qJcGMPfw,9748
+transformers/models/gemma3/image_processing_gemma3.py,sha256=6EUAKM626x9NRCVev6onx145IaWs8L10HhOfMG7AilY,10715
+transformers/models/gemma3/image_processing_pil_gemma3.py,sha256=ffzPn0OiEVRqb7yyAHn4buD88jwlsvebBjWEQrMZjHY,8654
+transformers/models/gemma3/modeling_gemma3.py,sha256=x5OKLA_fBMVdotvo4D0S0iUB8G9duRe7HnzgGJg1QY4,49316
+transformers/models/gemma3/modular_gemma3.py,sha256=sEa9HU3gtdmCCuul_oeej5CF4yDpGzjiwrynE96NXy0,39818
+transformers/models/gemma3/processing_gemma3.py,sha256=_P_A438m4wwICvuclWIMH3-PKDJdNBpxkGKItFfK0KQ,7213
+transformers/models/gemma3n/__init__.py,sha256=ZSrv5oSiULGXY7Vszb--vaJh1l7FBe1lrZD_3LX6cj4,1079
+transformers/models/gemma3n/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/gemma3n/__pycache__/configuration_gemma3n.cpython-312.pyc,,
+transformers/models/gemma3n/__pycache__/feature_extraction_gemma3n.cpython-312.pyc,,
+transformers/models/gemma3n/__pycache__/modeling_gemma3n.cpython-312.pyc,,
+transformers/models/gemma3n/__pycache__/modular_gemma3n.cpython-312.pyc,,
+transformers/models/gemma3n/__pycache__/processing_gemma3n.cpython-312.pyc,,
+transformers/models/gemma3n/configuration_gemma3n.py,sha256=T_3ClVLaho4HU_KEoLXzjetC6KZ_cwdBg6p7maaHVrs,22687
+transformers/models/gemma3n/feature_extraction_gemma3n.py,sha256=N8o-Mp0OJDpV7nL3g_wKq179gWIBcVsjRZA3DCuMgEA,14875
+transformers/models/gemma3n/modeling_gemma3n.py,sha256=anZW-9OcFwAbrGzpomyAlEebWTcw663Tf0sCj-6DJ-0,114210
+transformers/models/gemma3n/modular_gemma3n.py,sha256=jYXbMlO63t8s0kjUxs8IUXrpQKnyr7RJylkDeaBAHsQ,118764
+transformers/models/gemma3n/processing_gemma3n.py,sha256=L1AHdCYqg_pTEQTxPHisRKPGtjw5Dq_l1ZpRAefkrJk,6287
+transformers/models/gemma4/__init__.py,sha256=u6hcRStlg_nIQbIJ2oaQPY8JJHrJ1U6qDZFotZsm33E,1209
+transformers/models/gemma4/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/gemma4/__pycache__/configuration_gemma4.cpython-312.pyc,,
+transformers/models/gemma4/__pycache__/feature_extraction_gemma4.cpython-312.pyc,,
+transformers/models/gemma4/__pycache__/image_processing_gemma4.cpython-312.pyc,,
+transformers/models/gemma4/__pycache__/image_processing_pil_gemma4.cpython-312.pyc,,
+transformers/models/gemma4/__pycache__/modeling_gemma4.cpython-312.pyc,,
+transformers/models/gemma4/__pycache__/modular_gemma4.cpython-312.pyc,,
+transformers/models/gemma4/__pycache__/processing_gemma4.cpython-312.pyc,,
+transformers/models/gemma4/__pycache__/video_processing_gemma4.cpython-312.pyc,,
+transformers/models/gemma4/configuration_gemma4.py,sha256=HFxK5IRiX5P011S2KwxONZswl49bhSRVJjk_ZaK7xU4,15553
+transformers/models/gemma4/feature_extraction_gemma4.py,sha256=RBAcfOQobi43yhBim5elwJxTs4Yq0hzm-a4109h9dtQ,14003
+transformers/models/gemma4/image_processing_gemma4.py,sha256=YD7UeZBu5uAKDaNdIYDBxw16UgcMhhxKB-dFD6CQJZg,10844
+transformers/models/gemma4/image_processing_pil_gemma4.py,sha256=nJj2Tt6zuNA31U6w6oavGrY4k0yRxCB4NvxcsJbYoX4,10736
+transformers/models/gemma4/modeling_gemma4.py,sha256=kLtdvZ94II7weFHgmTEWA-nxhfj6wu9Yjfgj89-Wt3Y,123564
+transformers/models/gemma4/modular_gemma4.py,sha256=JNvXxYCgj8XsGft9t1-u8vjPNyCTCv2eBKw7zg8rfTo,107148
+transformers/models/gemma4/processing_gemma4.py,sha256=s5qcqDECkzIBDKD0fJB3oXRckkafOJ_73TQuiieQPOk,13882
+transformers/models/gemma4/video_processing_gemma4.py,sha256=UxI8c1qefEMjlNNXkq7qvC0fzVSSYdmXx1OVgkmUeOE,10809
+transformers/models/gemma4_assistant/__init__.py,sha256=XkOTd6qzsVAyRbILpMl-xrPnB6J5gp_siuhmgDtI-h8,1014
+transformers/models/gemma4_assistant/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/gemma4_assistant/__pycache__/configuration_gemma4_assistant.cpython-312.pyc,,
+transformers/models/gemma4_assistant/__pycache__/modeling_gemma4_assistant.cpython-312.pyc,,
+transformers/models/gemma4_assistant/configuration_gemma4_assistant.py,sha256=yFNFaWRmVW54zpFk08y3hkslgVWY6kf2Y9OLuYjyvb4,4363
+transformers/models/gemma4_assistant/modeling_gemma4_assistant.py,sha256=6blQuzP7FKrosAyCZwY3_Cq9BHVu81Jw6WPbaFT3rlA,11332
+transformers/models/gemma4_unified/__init__.py,sha256=mcj1ocVwXHkBYWvvJctxIBNCoornGou-LD1zT2sxhYI,1210
+transformers/models/gemma4_unified/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/gemma4_unified/__pycache__/configuration_gemma4_unified.cpython-312.pyc,,
+transformers/models/gemma4_unified/__pycache__/feature_extraction_gemma4_unified.cpython-312.pyc,,
+transformers/models/gemma4_unified/__pycache__/image_processing_gemma4_unified.cpython-312.pyc,,
+transformers/models/gemma4_unified/__pycache__/modeling_gemma4_unified.cpython-312.pyc,,
+transformers/models/gemma4_unified/__pycache__/modular_gemma4_unified.cpython-312.pyc,,
+transformers/models/gemma4_unified/__pycache__/processing_gemma4_unified.cpython-312.pyc,,
+transformers/models/gemma4_unified/__pycache__/video_processing_gemma4_unified.cpython-312.pyc,,
+transformers/models/gemma4_unified/configuration_gemma4_unified.py,sha256=H3tC3OvT3KKFCo5_EHK2uVScSFKmtE_rMj9zhyVVZOs,13155
+transformers/models/gemma4_unified/feature_extraction_gemma4_unified.py,sha256=2PtLXT_-P-oO_7Wdw0vmUSyJskSC7sPJNIeuCKF-XcQ,5910
+transformers/models/gemma4_unified/image_processing_gemma4_unified.py,sha256=TGI_xIBeqz0va95JsdC32gapccYXwIuJxYNyNhaKwvE,16089
+transformers/models/gemma4_unified/modeling_gemma4_unified.py,sha256=41bbkIlkJVnyJ8C8ETSYa91SdAZkMb6RpUANODVYGPs,63988
+transformers/models/gemma4_unified/modular_gemma4_unified.py,sha256=uwcEyQErgc-ONtE0yex8Q7yjGtdrGevSoQMJHopBVOI,56894
+transformers/models/gemma4_unified/processing_gemma4_unified.py,sha256=NYzPAQtqvyoX6HJm-1ygGiem7qV4llFb98I3mGdtQD4,14498
+transformers/models/gemma4_unified/video_processing_gemma4_unified.py,sha256=NlGk1HLIea6bzdtrTEKLJwHYx5yV345l09mymkKUmTI,15498
+transformers/models/gemma4_unified_assistant/__init__.py,sha256=7qX3e0t2_O-Sl1uXnqGvcJoAdG10_P139943yiQ6uCY,1030
+transformers/models/gemma4_unified_assistant/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/gemma4_unified_assistant/__pycache__/configuration_gemma4_unified_assistant.cpython-312.pyc,,
+transformers/models/gemma4_unified_assistant/__pycache__/modeling_gemma4_unified_assistant.cpython-312.pyc,,
+transformers/models/gemma4_unified_assistant/__pycache__/modular_gemma4_unified_assistant.cpython-312.pyc,,
+transformers/models/gemma4_unified_assistant/configuration_gemma4_unified_assistant.py,sha256=1CCPagaUmiP_KSFyyDk9IssSkAL13XOQ1U0ls9kahig,3117
+transformers/models/gemma4_unified_assistant/modeling_gemma4_unified_assistant.py,sha256=ZyOqmtyudf-_4zqWQYfN57c9au_IOfoZn2FKvQFCa0w,12387
+transformers/models/gemma4_unified_assistant/modular_gemma4_unified_assistant.py,sha256=ZO36IjvpZTCOKPnYTl2gX_RDNI3R_D40uBm0EI0hFqA,2033
+transformers/models/git/__init__.py,sha256=jY1iLd7UMOmcCfrKgzoUJawLa0DQ55wHN26L09YSwhc,1021
+transformers/models/git/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/git/__pycache__/configuration_git.cpython-312.pyc,,
+transformers/models/git/__pycache__/modeling_git.cpython-312.pyc,,
+transformers/models/git/__pycache__/processing_git.cpython-312.pyc,,
+transformers/models/git/configuration_git.py,sha256=GOTYDekwr07wchWRnHKRzU1S1105R6jgUPviEaLmcOA,3732
+transformers/models/git/modeling_git.py,sha256=U413hCxwxJtwqUQJxe9_WFasBxvD_ynOsbhs8uKWLrQ,45221
+transformers/models/git/processing_git.py,sha256=tj0eMBNee_EHZLrbVDzfodzk8C6BKXXgB4bH0W8wA4E,905
+transformers/models/glm/__init__.py,sha256=fIafw6FAflbbeG_nEM_VPJyMJHnu_NbWHTHjECIAvIs,987
+transformers/models/glm/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/glm/__pycache__/configuration_glm.cpython-312.pyc,,
+transformers/models/glm/__pycache__/modeling_glm.cpython-312.pyc,,
+transformers/models/glm/__pycache__/modular_glm.cpython-312.pyc,,
+transformers/models/glm/configuration_glm.py,sha256=h74B4rrttHMz4ljhypNC7i-EJfPYKnLXOmVmWTYk24s,3054
+transformers/models/glm/modeling_glm.py,sha256=SDyqmicKjXZNgFDYN_qUQCSHtJsjlTf5RNn_k4mfODo,21830
+transformers/models/glm/modular_glm.py,sha256=DAM18IKC_Zgvf5tnh0emtxrZqenpiEeWyRhak3PYqdY,5598
+transformers/models/glm4/__init__.py,sha256=okqViVxR-MUlkyIdKmSwrDKA7u8pGG49OIKtW9X1hvU,989
+transformers/models/glm4/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/glm4/__pycache__/configuration_glm4.cpython-312.pyc,,
+transformers/models/glm4/__pycache__/modeling_glm4.cpython-312.pyc,,
+transformers/models/glm4/__pycache__/modular_glm4.cpython-312.pyc,,
+transformers/models/glm4/configuration_glm4.py,sha256=pmtBjnUX_zDPSxu8u57LgsRW7DBJebsWFqBI4kNK4Bc,3040
+transformers/models/glm4/modeling_glm4.py,sha256=f08WCz8S9YMO7_tFuT0-0rqaaVdkG3US35yN1vsOiPo,22706
+transformers/models/glm4/modular_glm4.py,sha256=X4mtzqFS2TZ6hg4dh6eI5qA0fpcd-J4ia_dGRw5CBXI,5026
+transformers/models/glm46v/__init__.py,sha256=xCj_lDMErfp7kKTidkFeKYqo105FcohGkWTgYcK9Ekw,1163
+transformers/models/glm46v/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/glm46v/__pycache__/configuration_glm46v.cpython-312.pyc,,
+transformers/models/glm46v/__pycache__/image_processing_glm46v.cpython-312.pyc,,
+transformers/models/glm46v/__pycache__/image_processing_pil_glm46v.cpython-312.pyc,,
+transformers/models/glm46v/__pycache__/modeling_glm46v.cpython-312.pyc,,
+transformers/models/glm46v/__pycache__/modular_glm46v.cpython-312.pyc,,
+transformers/models/glm46v/__pycache__/processing_glm46v.cpython-312.pyc,,
+transformers/models/glm46v/__pycache__/video_processing_glm46v.cpython-312.pyc,,
+transformers/models/glm46v/configuration_glm46v.py,sha256=u8YSUqT0m_lLkJqdW_Dfs5UCLVJk6fJVXudD8jlgFG0,3986
+transformers/models/glm46v/image_processing_glm46v.py,sha256=QfqI4likspHxZ9dwhe7pidvr_xd2wzYSHi9Bhbbg7vE,10651
+transformers/models/glm46v/image_processing_pil_glm46v.py,sha256=NQbD92KEyQ0-2dTkTlCRywnOtPzY84LLKpCqGJI8dZg,10713
+transformers/models/glm46v/modeling_glm46v.py,sha256=BVlmma2sBP2MB68rW4HMLTjqjF2kvArKOBJKt_zbfDU,39397
+transformers/models/glm46v/modular_glm46v.py,sha256=2ZmV7o4oiHrqaOSZ6yKQccqa-O28XGvz23csIrmLb3g,7366
+transformers/models/glm46v/processing_glm46v.py,sha256=bXhbleNabJQXF4BCwKQokTZySGQz9w66kiLxxR5kDRw,9552
+transformers/models/glm46v/video_processing_glm46v.py,sha256=8EbH7f4pjKjI6YgRvxme5fm0CC2C8YiyWZ4N-74vtk4,11618
+transformers/models/glm4_moe/__init__.py,sha256=dfmB1kPUzq5-xfXh3zFtfGdSJu7CDDbfL401u_EayjM,997
+transformers/models/glm4_moe/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/glm4_moe/__pycache__/configuration_glm4_moe.cpython-312.pyc,,
+transformers/models/glm4_moe/__pycache__/modeling_glm4_moe.cpython-312.pyc,,
+transformers/models/glm4_moe/__pycache__/modular_glm4_moe.cpython-312.pyc,,
+transformers/models/glm4_moe/configuration_glm4_moe.py,sha256=pySJRH-HkHpXl8aZozMZnCt0K_YNQ93-2hgOZnuoFso,5002
+transformers/models/glm4_moe/modeling_glm4_moe.py,sha256=R2UUu1I_mTnVa71TjkiKOVsEehkNigJ7BNW6UZBZLbk,28370
+transformers/models/glm4_moe/modular_glm4_moe.py,sha256=CSzZkvyi11W4chwAyyHMr-kDFMAAeImaxNy5Vi9Peto,7304
+transformers/models/glm4_moe_lite/__init__.py,sha256=QhYOQontNMp2Fw5CMVOJcNDD36LzURkY1csW-Y2Bpcw,1008
+transformers/models/glm4_moe_lite/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/glm4_moe_lite/__pycache__/configuration_glm4_moe_lite.cpython-312.pyc,,
+transformers/models/glm4_moe_lite/__pycache__/modeling_glm4_moe_lite.cpython-312.pyc,,
+transformers/models/glm4_moe_lite/__pycache__/modular_glm4_moe_lite.cpython-312.pyc,,
+transformers/models/glm4_moe_lite/configuration_glm4_moe_lite.py,sha256=L4F4a02Bpwk9SpsF9TwV9-foFVBKDSHS5SHXzKfTLys,4837
+transformers/models/glm4_moe_lite/modeling_glm4_moe_lite.py,sha256=E1FlxYmz3aeTkChCsiJaogH80kKYIkWbJ-kr3Dr1w7I,32625
+transformers/models/glm4_moe_lite/modular_glm4_moe_lite.py,sha256=X4djACGeQEPLgkFj0Z-KWezjVpfjj6ijjTHfJ_EMue8,5702
+transformers/models/glm4v/__init__.py,sha256=nLVqgblofG1_QIBJFtnoCXcPrJm6-FqpmNBbPIT0tMM,1157
+transformers/models/glm4v/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/glm4v/__pycache__/configuration_glm4v.cpython-312.pyc,,
+transformers/models/glm4v/__pycache__/image_processing_glm4v.cpython-312.pyc,,
+transformers/models/glm4v/__pycache__/image_processing_pil_glm4v.cpython-312.pyc,,
+transformers/models/glm4v/__pycache__/modeling_glm4v.cpython-312.pyc,,
+transformers/models/glm4v/__pycache__/modular_glm4v.cpython-312.pyc,,
+transformers/models/glm4v/__pycache__/processing_glm4v.cpython-312.pyc,,
+transformers/models/glm4v/__pycache__/video_processing_glm4v.cpython-312.pyc,,
+transformers/models/glm4v/configuration_glm4v.py,sha256=4pgQarbCw-Q1sZTHAkdL9R4yF5_JovwQrOh-0X0or3g,7260
+transformers/models/glm4v/image_processing_glm4v.py,sha256=vzk8txxi1T-mKQGM6JCuCw-52hRRyWV6yMW2knvJ2p8,9970
+transformers/models/glm4v/image_processing_pil_glm4v.py,sha256=wmDx1rJhGCZxIPawclEbGtY69sGZbPVsz-PTXiNRtsU,10034
+transformers/models/glm4v/modeling_glm4v.py,sha256=_CAT8ung4rCrVTRjq_F9Sd3NrRbGESECMyMJ0JT0RFU,74836
+transformers/models/glm4v/modular_glm4v.py,sha256=lZ1IqCX0HkNMkjHT1zi2gLaHkUvss97pF5-X3u0-YKU,52932
+transformers/models/glm4v/processing_glm4v.py,sha256=iZRdm21DcBz2DkOzJ4_RHwUz5ND3YnUnUmv5jGasOq4,9560
+transformers/models/glm4v/video_processing_glm4v.py,sha256=Y08JAIwY1Fu89S-T4OxN3coRK0bUrSPXlxYKDNu7PJQ,9886
+transformers/models/glm4v_moe/__init__.py,sha256=4MuhU3oMjO5wL4YHEEhn0uU4qIsXz17DJPMs_xqMyHA,999
+transformers/models/glm4v_moe/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/glm4v_moe/__pycache__/configuration_glm4v_moe.cpython-312.pyc,,
+transformers/models/glm4v_moe/__pycache__/modeling_glm4v_moe.cpython-312.pyc,,
+transformers/models/glm4v_moe/__pycache__/modular_glm4v_moe.cpython-312.pyc,,
+transformers/models/glm4v_moe/configuration_glm4v_moe.py,sha256=fVgMmN7bGlMFGSVSC4EM5zoUJYbm3TRxPM9HGRtbHjY,8096
+transformers/models/glm4v_moe/modeling_glm4v_moe.py,sha256=-X79Mr5JO4D5AyPggyrMxXoXHv7rMBFfEV7is2Cfr9M,85993
+transformers/models/glm4v_moe/modular_glm4v_moe.py,sha256=KY-hVXzMgzqY_ePaHnPH4YBLnRvT993P_kyFH1IDOVU,16100
+transformers/models/glm_image/__init__.py,sha256=6EFsuF26T8j2kThjgmKq1SAXbE7uFwvKfWb_1_enwD4,1136
+transformers/models/glm_image/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/glm_image/__pycache__/configuration_glm_image.cpython-312.pyc,,
+transformers/models/glm_image/__pycache__/image_processing_glm_image.cpython-312.pyc,,
+transformers/models/glm_image/__pycache__/image_processing_pil_glm_image.cpython-312.pyc,,
+transformers/models/glm_image/__pycache__/modeling_glm_image.cpython-312.pyc,,
+transformers/models/glm_image/__pycache__/modular_glm_image.cpython-312.pyc,,
+transformers/models/glm_image/__pycache__/processing_glm_image.cpython-312.pyc,,
+transformers/models/glm_image/configuration_glm_image.py,sha256=Au9M3V9MGXsqxdPD675xIJXt6uQ3EArR0jnePgdbwxk,7772
+transformers/models/glm_image/image_processing_glm_image.py,sha256=4g4mUzzdqPWcvl6PjAHk_Iduh_vvuw0O8Yq9cgEzyus,11307
+transformers/models/glm_image/image_processing_pil_glm_image.py,sha256=ECVHxzVcq90txCL6vp53iUQWF5UhUmgaiBgywYHLqwY,10583
+transformers/models/glm_image/modeling_glm_image.py,sha256=Aiuo4DZ7puZwJMFrKTYnNA_0sxoFbSA7W2SwNjzzgnM,75279
+transformers/models/glm_image/modular_glm_image.py,sha256=m40OszR3ejfxrlSojvw9_WA6UVwK_hSM_JU8gj8OmGs,62060
+transformers/models/glm_image/processing_glm_image.py,sha256=QmDvFEAo_aE6CCrIiFumk-bbpAdbFd0AiXq39z2LmAc,11931
+transformers/models/glm_moe_dsa/__init__.py,sha256=sW2Trp4R9zjg37__07KUEMPo4dkirLgDtHthTsViU-Y,1004
+transformers/models/glm_moe_dsa/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/glm_moe_dsa/__pycache__/configuration_glm_moe_dsa.cpython-312.pyc,,
+transformers/models/glm_moe_dsa/__pycache__/modeling_glm_moe_dsa.cpython-312.pyc,,
+transformers/models/glm_moe_dsa/__pycache__/modular_glm_moe_dsa.cpython-312.pyc,,
+transformers/models/glm_moe_dsa/configuration_glm_moe_dsa.py,sha256=Pdd7djITbz6GKPl4kpOnGviuc0u90M7L-5M8NaDp1Ic,7640
+transformers/models/glm_moe_dsa/modeling_glm_moe_dsa.py,sha256=5i1e7DLpb9NEHbZ-9_WV89N69v6s5ezMTibhP6bvF9w,39556
+transformers/models/glm_moe_dsa/modular_glm_moe_dsa.py,sha256=CF8pV0O4Iud5KZLt0soKYfydzkCe4MR7N6bJ1RwOcI0,13849
+transformers/models/glm_ocr/__init__.py,sha256=oeeKm635ED_6WvzpS6UgtVQK8Czp18lLyVVzsHNU8NE,996
+transformers/models/glm_ocr/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/glm_ocr/__pycache__/configuration_glm_ocr.cpython-312.pyc,,
+transformers/models/glm_ocr/__pycache__/modeling_glm_ocr.cpython-312.pyc,,
+transformers/models/glm_ocr/__pycache__/modular_glm_ocr.cpython-312.pyc,,
+transformers/models/glm_ocr/configuration_glm_ocr.py,sha256=cBXAqhiBGrBY4iipw0O8B78marsnU6ZqLDcXILZhLFM,7206
+transformers/models/glm_ocr/modeling_glm_ocr.py,sha256=31FC74y00917lfW2DD3W0bxFXqIERBIK6TUEuQZrsFg,71510
+transformers/models/glm_ocr/modular_glm_ocr.py,sha256=X1cAzWTFqBytBWnGQvD0yQ4ErfG0VmT8xHz7KT2LWcE,10806
+transformers/models/glmasr/__init__.py,sha256=UpS-w64zO1l1qsMI0GggLWffkdh2EKlW08BISsMiZz4,1031
+transformers/models/glmasr/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/glmasr/__pycache__/configuration_glmasr.cpython-312.pyc,,
+transformers/models/glmasr/__pycache__/modeling_glmasr.cpython-312.pyc,,
+transformers/models/glmasr/__pycache__/modular_glmasr.cpython-312.pyc,,
+transformers/models/glmasr/__pycache__/processing_glmasr.cpython-312.pyc,,
+transformers/models/glmasr/configuration_glmasr.py,sha256=Emoid8PaPAx6yCSq2v0vJh6VvdAwp_X-8q0g8MOsm2k,4200
+transformers/models/glmasr/modeling_glmasr.py,sha256=tQuVtiGeqqdu36fC5sZ9_fYVWX_j2zBe6VfRR3suEl0,26887
+transformers/models/glmasr/modular_glmasr.py,sha256=pGYWG-f9M9WzO83TXZGCuQyNPp-n9nWkn3jRxFRGD6c,18536
+transformers/models/glmasr/processing_glmasr.py,sha256=BMz8CYJzqg4tlPTUpndquWV40Sl1Fqpj9QN-uerj-84,13231
+transformers/models/glmga/__init__.py,sha256=t_Hd-Qvc_EzpwlDyYi_kY2n0a_N7nzPir0-XH1q6IFQ,1088
+transformers/models/glmga/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/glmga/__pycache__/configuration_glmga.cpython-312.pyc,,
+transformers/models/glmga/__pycache__/image_processing_glmga.cpython-312.pyc,,
+transformers/models/glmga/__pycache__/image_processing_pil_glmga.cpython-312.pyc,,
+transformers/models/glmga/__pycache__/modular_glmga.cpython-312.pyc,,
+transformers/models/glmga/__pycache__/video_processing_glmga.cpython-312.pyc,,
+transformers/models/glmga/configuration_glmga.py,sha256=21WSOKx6O0GsNZafsSkzify9Peuhn4sGZuobswFhUpg,4005
+transformers/models/glmga/image_processing_glmga.py,sha256=FZWiR-EC_auSJFj0OlWfsPaOOSa7eukpDAz1G4NtC3Y,10884
+transformers/models/glmga/image_processing_pil_glmga.py,sha256=b87alesEMmnFNsNdicKzgWkfsJGeYEYy65dNxKuVOgo,10873
+transformers/models/glmga/modular_glmga.py,sha256=zJexU0ED7Pe23LvE2FLA91GGJea3nznkoJujmEkXc8E,19238
+transformers/models/glmga/video_processing_glmga.py,sha256=C9feRQipL8cPRQX3CyDOAGuBKMcPCQ_kYaRfIcLGI2g,11318
+transformers/models/glpn/__init__.py,sha256=OqtxZ3a-QVtqF1ztjvlGo56g_zptMwmxbodSmsQ0yn4,1075
+transformers/models/glpn/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/glpn/__pycache__/configuration_glpn.cpython-312.pyc,,
+transformers/models/glpn/__pycache__/image_processing_glpn.cpython-312.pyc,,
+transformers/models/glpn/__pycache__/image_processing_pil_glpn.cpython-312.pyc,,
+transformers/models/glpn/__pycache__/modeling_glpn.cpython-312.pyc,,
+transformers/models/glpn/configuration_glpn.py,sha256=4g-xhMxaDjo9Zc_eabKEZlYoMtwg6lIpJOYGDb5SfIw,3451
+transformers/models/glpn/image_processing_glpn.py,sha256=bDdf6p0egqWNjWAsRQ76qQV-VKpHfquKwzTdC9Jn5Pc,5729
+transformers/models/glpn/image_processing_pil_glpn.py,sha256=7CBPaKhpXhYraUtI7z4dI5Bp9vbl_gl6R3v1XBP8NPw,5241
+transformers/models/glpn/modeling_glpn.py,sha256=Pd7JT7DDtF8vh7BNPdpyI9CDejg_hk5e7JIJq2Fu3z8,26480
+transformers/models/got_ocr2/__init__.py,sha256=WNA-QaAhwe9kiuTrSyqIhnofA5FnEzTmcb59cYsN5hQ,1137
+transformers/models/got_ocr2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/got_ocr2/__pycache__/configuration_got_ocr2.cpython-312.pyc,,
+transformers/models/got_ocr2/__pycache__/image_processing_got_ocr2.cpython-312.pyc,,
+transformers/models/got_ocr2/__pycache__/image_processing_pil_got_ocr2.cpython-312.pyc,,
+transformers/models/got_ocr2/__pycache__/modeling_got_ocr2.cpython-312.pyc,,
+transformers/models/got_ocr2/__pycache__/modular_got_ocr2.cpython-312.pyc,,
+transformers/models/got_ocr2/__pycache__/processing_got_ocr2.cpython-312.pyc,,
+transformers/models/got_ocr2/configuration_got_ocr2.py,sha256=fFJX_vse5VsMzwAOPHIsvzERt4pZSoO4JF8K761P_wI,5435
+transformers/models/got_ocr2/image_processing_got_ocr2.py,sha256=s9YRPNtDyKhd3G6vNVJW04H9bpovIfLjRNeFKCBlk_8,13222
+transformers/models/got_ocr2/image_processing_pil_got_ocr2.py,sha256=Qna70BJBDL5W8WZo-f_vOYsj_Wc35CQJAWZyERkD3dg,12838
+transformers/models/got_ocr2/modeling_got_ocr2.py,sha256=hzKTXZgGVlbnhuC4-9_40ck302zID6c_lsIRzEACOBg,33840
+transformers/models/got_ocr2/modular_got_ocr2.py,sha256=JIiO2W3BrvRx3YDggHdeC-YCO8XLUITbSPGCKrtuLOg,14550
+transformers/models/got_ocr2/processing_got_ocr2.py,sha256=sfqk_UZ1H83uNNU8gGhawieUz8anxa7dWiQd1y5cwNQ,10450
+transformers/models/gpt2/__init__.py,sha256=trifYw4vnBNfaiVq-8aSyPTNAGWdUE-eSOVJfR28nhE,1026
+transformers/models/gpt2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/gpt2/__pycache__/configuration_gpt2.cpython-312.pyc,,
+transformers/models/gpt2/__pycache__/modeling_gpt2.cpython-312.pyc,,
+transformers/models/gpt2/__pycache__/tokenization_gpt2.cpython-312.pyc,,
+transformers/models/gpt2/configuration_gpt2.py,sha256=iVNJB_VlUrmjGsTfw9r7NlUm4ilAJzX1yGgXNmfO49U,4552
+transformers/models/gpt2/modeling_gpt2.py,sha256=_NfOEWxmMh4pNbCa9Viehk4YJOBxxLhlKiDaBy990KI,51607
+transformers/models/gpt2/tokenization_gpt2.py,sha256=qdvEf7AwS5jMmgxGQrkpJHP5ZlLInB8dePQgYTU18eU,5370
+transformers/models/gpt_bigcode/__init__.py,sha256=KQNb7PO57eZpP345wSbe_C3iL-N4VPscw1GY2mv81uE,1003
+transformers/models/gpt_bigcode/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/gpt_bigcode/__pycache__/configuration_gpt_bigcode.cpython-312.pyc,,
+transformers/models/gpt_bigcode/__pycache__/modeling_gpt_bigcode.cpython-312.pyc,,
+transformers/models/gpt_bigcode/configuration_gpt_bigcode.py,sha256=IUX5km16gUoDxLUH5OgzgkUd6QKWvqW6QLrz6GofshI,3083
+transformers/models/gpt_bigcode/modeling_gpt_bigcode.py,sha256=rctTmx6SngxYhdTN2HLUVxZUuIHMGwyG5BC8l2V_cdA,34505
+transformers/models/gpt_neo/__init__.py,sha256=OG3bA-FgdEYzI3Qs45XGMCa-4zdz5F9zQycsYBXuQ_4,995
+transformers/models/gpt_neo/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/gpt_neo/__pycache__/configuration_gpt_neo.cpython-312.pyc,,
+transformers/models/gpt_neo/__pycache__/modeling_gpt_neo.cpython-312.pyc,,
+transformers/models/gpt_neo/configuration_gpt_neo.py,sha256=afbPgEg7ImJFxnrpPuaRo-1wTFsaV-gULekoRUlAXa0,5193
+transformers/models/gpt_neo/modeling_gpt_neo.py,sha256=lOOkd6fhiWFV_ai0LjBoRkUsobghQbUNvnyzUMbY6gU,38502
+transformers/models/gpt_neox/__init__.py,sha256=vH3qZOHNV6DsvrKyPvzXoO_D26e0N78HDOYSlxMWTYQ,1038
+transformers/models/gpt_neox/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/gpt_neox/__pycache__/configuration_gpt_neox.cpython-312.pyc,,
+transformers/models/gpt_neox/__pycache__/modeling_gpt_neox.cpython-312.pyc,,
+transformers/models/gpt_neox/__pycache__/modular_gpt_neox.cpython-312.pyc,,
+transformers/models/gpt_neox/__pycache__/tokenization_gpt_neox.cpython-312.pyc,,
+transformers/models/gpt_neox/configuration_gpt_neox.py,sha256=gKdT5nV5pw26GL_yjT-tp4MgHlFwMPK2ktPlfl3Ndcs,4092
+transformers/models/gpt_neox/modeling_gpt_neox.py,sha256=9l-kUaieVy8GbtWFIUsjfh15JE7afX2sTyCS9yp006s,27894
+transformers/models/gpt_neox/modular_gpt_neox.py,sha256=komCM9wvqBsYU26Cl1Ozm86ybQi9CLNuJL_XBC0-okk,25096
+transformers/models/gpt_neox/tokenization_gpt_neox.py,sha256=95fZUdUeBU-NIzFvK7gK7DomOm0B9pMrduJlXYyr8e8,6004
+transformers/models/gpt_neox_japanese/__init__.py,sha256=z4kbUmZSjE-Hs9ba8ul3Yncc9ZJy7ePufbwwRlfqWqw,1065
+transformers/models/gpt_neox_japanese/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/gpt_neox_japanese/__pycache__/configuration_gpt_neox_japanese.cpython-312.pyc,,
+transformers/models/gpt_neox_japanese/__pycache__/modeling_gpt_neox_japanese.cpython-312.pyc,,
+transformers/models/gpt_neox_japanese/__pycache__/tokenization_gpt_neox_japanese.cpython-312.pyc,,
+transformers/models/gpt_neox_japanese/configuration_gpt_neox_japanese.py,sha256=KgU78oi7KSx1NQLswRuDtTgQWuj765LZesVJ5BpKKII,3105
+transformers/models/gpt_neox_japanese/modeling_gpt_neox_japanese.py,sha256=qS8SJVDEuVLan79_n1YiF5r29jLYVheoTPT3hdgVDX0,25183
+transformers/models/gpt_neox_japanese/tokenization_gpt_neox_japanese.py,sha256=0DiKz_OKPMHfUIEXHj2eOizNdvHOP5Ib5CCwj-sbRPs,16931
+transformers/models/gpt_oss/__init__.py,sha256=a3dnVKgP6RwbuxBJW3kodYKj8oVF5Y6pLJixMthP1yA,995
+transformers/models/gpt_oss/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/gpt_oss/__pycache__/configuration_gpt_oss.cpython-312.pyc,,
+transformers/models/gpt_oss/__pycache__/modeling_gpt_oss.cpython-312.pyc,,
+transformers/models/gpt_oss/__pycache__/modular_gpt_oss.cpython-312.pyc,,
+transformers/models/gpt_oss/configuration_gpt_oss.py,sha256=mE7khI1TongDhTPE5G1DhScoSYO0k1m2Ufcygg-ELXg,3336
+transformers/models/gpt_oss/modeling_gpt_oss.py,sha256=dYDYlWNWa_mC3yMRAp6OvwKO4j8jcZKFRKg2i42FvaI,30939
+transformers/models/gpt_oss/modular_gpt_oss.py,sha256=mjhv7XvM5s6nOL4a9aCCP7WcbXtIkAi9743oQCiU4S8,17499
+transformers/models/gpt_sw3/__init__.py,sha256=-g6WlJ6EhhrJKCCsPf78cgvGD7oWvfeW9GBGBpW6wcM,958
+transformers/models/gpt_sw3/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/gpt_sw3/__pycache__/tokenization_gpt_sw3.cpython-312.pyc,,
+transformers/models/gpt_sw3/tokenization_gpt_sw3.py,sha256=Ia96IzTjuLUWbK2oHgvVfhgwMmI83Vf3tHupH-x3umo,10021
+transformers/models/gptj/__init__.py,sha256=8X2gitvP4-NmFJp4CE22JAuc0DrUHg9-lAty6XqyBkE,989
+transformers/models/gptj/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/gptj/__pycache__/configuration_gptj.cpython-312.pyc,,
+transformers/models/gptj/__pycache__/modeling_gptj.cpython-312.pyc,,
+transformers/models/gptj/configuration_gptj.py,sha256=oqpUeu1OADQhioQCwxLvHvoz4uHdceDYUvm30bUgCLo,2227
+transformers/models/gptj/modeling_gptj.py,sha256=KQyETCZ5S_ZKphQHaWa_mNUjeENz2fsuo7ud0Up4rIo,36699
+transformers/models/granite/__init__.py,sha256=cDxmZNuphkDCs2U8W5C95Vhu577kdZHKHUWWaQ3vk5U,1015
+transformers/models/granite/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/granite/__pycache__/configuration_granite.cpython-312.pyc,,
+transformers/models/granite/__pycache__/modeling_granite.cpython-312.pyc,,
+transformers/models/granite/__pycache__/modular_granite.cpython-312.pyc,,
+transformers/models/granite/configuration_granite.py,sha256=rcruQS3vDcb_DaOxl7Z0M9TyvgehgWrRETMKQkZsfHo,3444
+transformers/models/granite/modeling_granite.py,sha256=OAhWCyKArxLzmCF2EUEHpDAREFqTIS_5oVIkT8sXyB4,22657
+transformers/models/granite/modular_granite.py,sha256=se1owRj50g_kFiko-KaDFCX59Q3F9gouQYJi6roIg8Q,8847
+transformers/models/granite4_vision/__init__.py,sha256=vvaqJgYfsL7xxATI4KjY0P5OhQ36ggHea9jQzGZ4mg0,1040
+transformers/models/granite4_vision/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/granite4_vision/__pycache__/configuration_granite4_vision.cpython-312.pyc,,
+transformers/models/granite4_vision/__pycache__/modeling_granite4_vision.cpython-312.pyc,,
+transformers/models/granite4_vision/__pycache__/modular_granite4_vision.cpython-312.pyc,,
+transformers/models/granite4_vision/__pycache__/processing_granite4_vision.cpython-312.pyc,,
+transformers/models/granite4_vision/configuration_granite4_vision.py,sha256=1LLZWRMO_PQ-5fqcA3tqS0egNFVzIFQfnkOLuy12KRQ,8548
+transformers/models/granite4_vision/modeling_granite4_vision.py,sha256=asNzzCT9-3dc2-6nKRo48Sik7kVsi3CJaEuMIlqI17E,55773
+transformers/models/granite4_vision/modular_granite4_vision.py,sha256=in7BVdYZQMdgTzppoAakXmgydQjzZBIcjV_l9MnoHqY,34911
+transformers/models/granite4_vision/processing_granite4_vision.py,sha256=povDYhrDxMghUw7DY4LO-F4BscMCNI1ZQJXvsACz2pE,11825
+transformers/models/granite_speech/__init__.py,sha256=xD_zbTTnBiaB6EEG4yinaWd-yza1waa01GNKVhsGL1M,1107
+transformers/models/granite_speech/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/granite_speech/__pycache__/configuration_granite_speech.cpython-312.pyc,,
+transformers/models/granite_speech/__pycache__/feature_extraction_granite_speech.cpython-312.pyc,,
+transformers/models/granite_speech/__pycache__/modeling_granite_speech.cpython-312.pyc,,
+transformers/models/granite_speech/__pycache__/processing_granite_speech.cpython-312.pyc,,
+transformers/models/granite_speech/configuration_granite_speech.py,sha256=xZe1aCUaa0qKMbpZXhvXKM576GiniGbA0K4zWGUfTCA,5860
+transformers/models/granite_speech/feature_extraction_granite_speech.py,sha256=2Tniv33cMu7O09AhbO3_eiw7rPo_5YfvpzGagb3jxOQ,7887
+transformers/models/granite_speech/modeling_granite_speech.py,sha256=LhjtVemX6C9WSFXL--d5SRpwvydijIStiJgMIKtAcF4,28957
+transformers/models/granite_speech/processing_granite_speech.py,sha256=XET-j4EGK4Fem-NmNdO_dqZFpk5m9X5R-60P2oUbV5g,4180
+transformers/models/granite_speech_plus/__init__.py,sha256=QVNce0PhhdifjJLG3olLYGYXxh8wL8As7rqKpQoIDIw,1019
+transformers/models/granite_speech_plus/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/granite_speech_plus/__pycache__/configuration_granite_speech_plus.cpython-312.pyc,,
+transformers/models/granite_speech_plus/__pycache__/modeling_granite_speech_plus.cpython-312.pyc,,
+transformers/models/granite_speech_plus/__pycache__/modular_granite_speech_plus.cpython-312.pyc,,
+transformers/models/granite_speech_plus/configuration_granite_speech_plus.py,sha256=PDzxoEEDuQJlMn4WA2vYXh8o2KL3OhbudwbfjXf_6t0,8085
+transformers/models/granite_speech_plus/modeling_granite_speech_plus.py,sha256=lZfSgWIK5_PLEtZ7iGtpErN325FriR0rJ_oYl4n0hOE,30531
+transformers/models/granite_speech_plus/modular_granite_speech_plus.py,sha256=w3__4LwYyAs5rz4ye7AEG4TSWUsVz1BKFGjmYASi0A0,7359
+transformers/models/granitemoe/__init__.py,sha256=e4KKtNT7YFkYkPBfcS0VyhpT_1vF0JkR2qdYKPqRUcE,1001
+transformers/models/granitemoe/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/granitemoe/__pycache__/configuration_granitemoe.cpython-312.pyc,,
+transformers/models/granitemoe/__pycache__/modeling_granitemoe.cpython-312.pyc,,
+transformers/models/granitemoe/__pycache__/modular_granitemoe.cpython-312.pyc,,
+transformers/models/granitemoe/configuration_granitemoe.py,sha256=xiyStUbxTfwBhScus7bCYpAP6mL-2avFauJMDyZm15E,3047
+transformers/models/granitemoe/modeling_granitemoe.py,sha256=wplL51p5rRMrZrfOgmk7QeT77UcKVZBo6GSs29iAinE,31705
+transformers/models/granitemoe/modular_granitemoe.py,sha256=7oxUKyMoCr_fB552qV11gU8z323qaBcHNbZUkMNzMB4,12882
+transformers/models/granitemoehybrid/__init__.py,sha256=V5SQbC7YI-EoIlyHo5LoSpJ7SyuquuA5DcsuNlRoSVI,1028
+transformers/models/granitemoehybrid/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/granitemoehybrid/__pycache__/configuration_granitemoehybrid.cpython-312.pyc,,
+transformers/models/granitemoehybrid/__pycache__/modeling_granitemoehybrid.cpython-312.pyc,,
+transformers/models/granitemoehybrid/__pycache__/modular_granitemoehybrid.cpython-312.pyc,,
+transformers/models/granitemoehybrid/configuration_granitemoehybrid.py,sha256=GRuX2dQNB-deVy_AHx9Ym0EsCtLI02UqLdzbb48qRFg,4871
+transformers/models/granitemoehybrid/modeling_granitemoehybrid.py,sha256=IXj6EEQfQqSasPKbVltglsPnzSomVOs28HzURKLUulQ,63473
+transformers/models/granitemoehybrid/modular_granitemoehybrid.py,sha256=M5OkEMYxRUAENUzVK0BS72B30121_qjSMa_8LNQeTR8,12809
+transformers/models/granitemoeshared/__init__.py,sha256=vmY98tLts1c_yvkLn9X-xk6CFtXIKskzYvFGMqQAskc,1013
+transformers/models/granitemoeshared/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/granitemoeshared/__pycache__/configuration_granitemoeshared.cpython-312.pyc,,
+transformers/models/granitemoeshared/__pycache__/modeling_granitemoeshared.cpython-312.pyc,,
+transformers/models/granitemoeshared/__pycache__/modular_granitemoeshared.cpython-312.pyc,,
+transformers/models/granitemoeshared/configuration_granitemoeshared.py,sha256=werLQ0Z37ora6Hkk0AQ-nfcSy6HqH1KYl2ll4euoM2g,3590
+transformers/models/granitemoeshared/modeling_granitemoeshared.py,sha256=bCrvCHeB5QnfAmLicM1Sjvj2Pzi8sdKwSg_m4zPcyO4,34483
+transformers/models/granitemoeshared/modular_granitemoeshared.py,sha256=DvsC1sirnCn4i5XZTuuX9-afR5PZQZhYa5Zasrb20YQ,5608
+transformers/models/grounding_dino/__init__.py,sha256=6HragQu5qpA5TK5Y23Wq66u9HTbZC3mLdriQ4uQOLIc,1160
+transformers/models/grounding_dino/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/grounding_dino/__pycache__/configuration_grounding_dino.cpython-312.pyc,,
+transformers/models/grounding_dino/__pycache__/image_processing_grounding_dino.cpython-312.pyc,,
+transformers/models/grounding_dino/__pycache__/image_processing_pil_grounding_dino.cpython-312.pyc,,
+transformers/models/grounding_dino/__pycache__/modeling_grounding_dino.cpython-312.pyc,,
+transformers/models/grounding_dino/__pycache__/modular_grounding_dino.cpython-312.pyc,,
+transformers/models/grounding_dino/__pycache__/processing_grounding_dino.cpython-312.pyc,,
+transformers/models/grounding_dino/configuration_grounding_dino.py,sha256=c2PtUDy8EIDYUQ7OT_BhP3ypWtmG413dN-FN19Vlvoo,6868
+transformers/models/grounding_dino/image_processing_grounding_dino.py,sha256=GNq9uanQIVlfU1JvBazYBwJ3uv-t8tQ-HQ6-QHYYuII,31918
+transformers/models/grounding_dino/image_processing_pil_grounding_dino.py,sha256=58qz0hfBZAighOEs-a5oIz9QMKTrQTHNHHkwhG0SmGA,32613
+transformers/models/grounding_dino/modeling_grounding_dino.py,sha256=6XyPpzuMHZJtQke-Xq_9BLXpkF3HxSPOzPWs7wHRJYo,129179
+transformers/models/grounding_dino/modular_grounding_dino.py,sha256=sLqJi-S_x6jafm9DPlFrjpTFoexfT3YhWjdwL5aJC9s,8885
+transformers/models/grounding_dino/processing_grounding_dino.py,sha256=-HQ14qL3SOeK_CnRWTeKJx5MdjqvourWN8eZsweBkMk,9659
+transformers/models/groupvit/__init__.py,sha256=8z8yBl-b-usbrGBx0-rNE-6pqPf4jPP_Ev4U5t8Sphc,997
+transformers/models/groupvit/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/groupvit/__pycache__/configuration_groupvit.cpython-312.pyc,,
+transformers/models/groupvit/__pycache__/modeling_groupvit.cpython-312.pyc,,
+transformers/models/groupvit/configuration_groupvit.py,sha256=qaOGuqeP27qKcWkMztzpAg9y_95dUfWBIae9WlP1hCc,9910
+transformers/models/groupvit/modeling_groupvit.py,sha256=bCvS_TY2wPAtYcLZkTsJgkGGWaPJgKKCLwNbdY9vqXE,54595
+transformers/models/helium/__init__.py,sha256=b1Senw5Mr129rzZSd1sW6-Ies2kIAUHfplpzgGeuTFE,993
+transformers/models/helium/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/helium/__pycache__/configuration_helium.cpython-312.pyc,,
+transformers/models/helium/__pycache__/modeling_helium.cpython-312.pyc,,
+transformers/models/helium/__pycache__/modular_helium.cpython-312.pyc,,
+transformers/models/helium/configuration_helium.py,sha256=W8V8ujCjcN0IsNDppQN9EwuitwPPAHVw_Q1V_1XQDIk,2717
+transformers/models/helium/modeling_helium.py,sha256=SghkKAHVBOJrlNrULS_qja2YJ1nxK2oIM-4ner5w72g,21168
+transformers/models/helium/modular_helium.py,sha256=8_9Srsob0Vj7u0z8s8K46wUn15VwpBkSebUZIw3vIkA,5333
+transformers/models/herbert/__init__.py,sha256=TSI8jVDbbhzcO4Bl6xkcmLyL9VtLWTV8JuPy2_dk2sE,958
+transformers/models/herbert/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/herbert/__pycache__/tokenization_herbert.cpython-312.pyc,,
+transformers/models/herbert/tokenization_herbert.py,sha256=d8uN5yO5NnTeA_70H-N9W9xNwrMBiRo8yrxHMrCgCWw,3917
+transformers/models/hgnet_v2/__init__.py,sha256=sBFNC0RNpS-oEnOiwtxy2SkUPAJgmI5uXXq2WjSHRd8,999
+transformers/models/hgnet_v2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/hgnet_v2/__pycache__/configuration_hgnet_v2.cpython-312.pyc,,
+transformers/models/hgnet_v2/__pycache__/modeling_hgnet_v2.cpython-312.pyc,,
+transformers/models/hgnet_v2/__pycache__/modular_hgnet_v2.cpython-312.pyc,,
+transformers/models/hgnet_v2/configuration_hgnet_v2.py,sha256=GXx9CSqS1fwwZRueWkc95UnYcqbPvKEKJv3fLy5MrGs,6683
+transformers/models/hgnet_v2/modeling_hgnet_v2.py,sha256=P0yIIFVM42IMyIYDRtY2mQ924v1k4Vu77l9wp0jb104,18706
+transformers/models/hgnet_v2/modular_hgnet_v2.py,sha256=nJcUQvRdgCfDzZKKJMNPTP8IMPXxbkNK9I9KU-dhEAg,22990
+transformers/models/hiera/__init__.py,sha256=b1kwKtpZVISJZ5Pri421uvH2v3IoRQ6XXHzxFOPHN-g,991
+transformers/models/hiera/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/hiera/__pycache__/configuration_hiera.cpython-312.pyc,,
+transformers/models/hiera/__pycache__/modeling_hiera.cpython-312.pyc,,
+transformers/models/hiera/configuration_hiera.py,sha256=d16yJ_gf0J5rOJl2NEH_sqaGOiVvC3awF_UBK5RLGR0,5428
+transformers/models/hiera/modeling_hiera.py,sha256=IPMBV2SlTqcz5SaO9Tgf8npFe7urMS4Cp9yjZ0sAyF8,59460
+transformers/models/higgs_audio_v2/__init__.py,sha256=9l-ZUYNLVBO3B2pD0KIGMtietlzt1r8TOMcPBpIUHug,1112
+transformers/models/higgs_audio_v2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/higgs_audio_v2/__pycache__/configuration_higgs_audio_v2.cpython-312.pyc,,
+transformers/models/higgs_audio_v2/__pycache__/generation_higgs_audio_v2.cpython-312.pyc,,
+transformers/models/higgs_audio_v2/__pycache__/modeling_higgs_audio_v2.cpython-312.pyc,,
+transformers/models/higgs_audio_v2/__pycache__/modular_higgs_audio_v2.cpython-312.pyc,,
+transformers/models/higgs_audio_v2/__pycache__/processing_higgs_audio_v2.cpython-312.pyc,,
+transformers/models/higgs_audio_v2/configuration_higgs_audio_v2.py,sha256=Pa4WtCx27B-mp7l85rvtS2gY99L5lNKx-p2oqKuZYxI,5595
+transformers/models/higgs_audio_v2/generation_higgs_audio_v2.py,sha256=4OHLK_JCjoUgZwVYfbTGs1tSUrXqioWa_MiZGyygQ7M,22356
+transformers/models/higgs_audio_v2/modeling_higgs_audio_v2.py,sha256=T8pAHOr1Ljx6x0xwQuIQKyerMdOpxkf5FF3fUv67Tj0,35491
+transformers/models/higgs_audio_v2/modular_higgs_audio_v2.py,sha256=YQjCgjLF-N7-5XrJvgdgYmZx8aKrGhKsm1RCNvH8ttA,24259
+transformers/models/higgs_audio_v2/processing_higgs_audio_v2.py,sha256=kC9HMmCuUO5jCeFcXy_llNVkspT2sV5kQaI2iLmqoUU,16147
+transformers/models/higgs_audio_v2_tokenizer/__init__.py,sha256=kQTOrcA2fLHDOwYqe2krRCBnDLRXKHbagiAxFHYOOk4,1042
+transformers/models/higgs_audio_v2_tokenizer/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/higgs_audio_v2_tokenizer/__pycache__/configuration_higgs_audio_v2_tokenizer.cpython-312.pyc,,
+transformers/models/higgs_audio_v2_tokenizer/__pycache__/modeling_higgs_audio_v2_tokenizer.cpython-312.pyc,,
+transformers/models/higgs_audio_v2_tokenizer/__pycache__/modular_higgs_audio_v2_tokenizer.cpython-312.pyc,,
+transformers/models/higgs_audio_v2_tokenizer/configuration_higgs_audio_v2_tokenizer.py,sha256=L7tIlNPqYjekKfYsmJPTQ7uVvjrMt422O4--8lcRrY0,7534
+transformers/models/higgs_audio_v2_tokenizer/modeling_higgs_audio_v2_tokenizer.py,sha256=U_QKo3PYBf1Sqxx_RNT3f5OLAipkVnImNv8LEmmbU4w,28237
+transformers/models/higgs_audio_v2_tokenizer/modular_higgs_audio_v2_tokenizer.py,sha256=vDRxvVQzZQEIcnTK3WuD18FhlNEbm6Ug5ep2oPJDsG4,6043
+transformers/models/hrm_text/__init__.py,sha256=SrBCNN63z3KlxKJ8A_Toxc1kHrLL7vAra_XhRTXEoEw,1029
+transformers/models/hrm_text/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/hrm_text/__pycache__/configuration_hrm_text.cpython-312.pyc,,
+transformers/models/hrm_text/__pycache__/modeling_hrm_text.cpython-312.pyc,,
+transformers/models/hrm_text/__pycache__/modular_hrm_text.cpython-312.pyc,,
+transformers/models/hrm_text/configuration_hrm_text.py,sha256=LhKqCgigTKRleKITKAwEwmNUxO06xwEt974mRu-6dd8,7519
+transformers/models/hrm_text/modeling_hrm_text.py,sha256=PtKKfJ_N94Dx17p8R5L7srEjmZm-59SyCdTPrTw8IWI,28046
+transformers/models/hrm_text/modular_hrm_text.py,sha256=qclU0nKSNXl7h5qUJ8DHTZa90QxIXH6I9oNViTeFFy8,21207
+transformers/models/hubert/__init__.py,sha256=99_KVlRuVQxpVPnX_qPki0yEzJpggZOD527N_-aFvYM,993
+transformers/models/hubert/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/hubert/__pycache__/configuration_hubert.cpython-312.pyc,,
+transformers/models/hubert/__pycache__/modeling_hubert.cpython-312.pyc,,
+transformers/models/hubert/__pycache__/modular_hubert.cpython-312.pyc,,
+transformers/models/hubert/configuration_hubert.py,sha256=kQZYJvumBTudXTjowCRAmt2uazoXRMLwVlV7bXDCrnA,10288
+transformers/models/hubert/modeling_hubert.py,sha256=sthLXuJDXBZUwiToLvJsOUuZyYq6gw1A7JfSH3SOfag,51153
+transformers/models/hubert/modular_hubert.py,sha256=bZhnO17HZHQ4kxrHppB1yVPUmKdxPx1Z62BPagVGpWw,11999
+transformers/models/hunyuan_v1_dense/__init__.py,sha256=FZn7rOtjmLA5vwEeH99QcgAveRMl1LbHQOyBKhywPWY,442
+transformers/models/hunyuan_v1_dense/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/hunyuan_v1_dense/__pycache__/configuration_hunyuan_v1_dense.cpython-312.pyc,,
+transformers/models/hunyuan_v1_dense/__pycache__/modeling_hunyuan_v1_dense.cpython-312.pyc,,
+transformers/models/hunyuan_v1_dense/__pycache__/modular_hunyuan_v1_dense.cpython-312.pyc,,
+transformers/models/hunyuan_v1_dense/configuration_hunyuan_v1_dense.py,sha256=jgBgzKgQCcyOJTG4voaxd7Rwvz076Jl155mcsSd5B74,2345
+transformers/models/hunyuan_v1_dense/modeling_hunyuan_v1_dense.py,sha256=1pi8fifQc3FrXyqfHGGlCFujk5BOdqJcgDuvVAaI-FE,23722
+transformers/models/hunyuan_v1_dense/modular_hunyuan_v1_dense.py,sha256=eO-b6P9MGO6qLZylIXly_EFOBgjU6ALqSSCsGoR69QM,7146
+transformers/models/hunyuan_v1_moe/__init__.py,sha256=JPxEpmnMsJGVMZzSx6_wGtDDkQD33aU1BEdPdXKzHUg,403
+transformers/models/hunyuan_v1_moe/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/hunyuan_v1_moe/__pycache__/configuration_hunyuan_v1_moe.cpython-312.pyc,,
+transformers/models/hunyuan_v1_moe/__pycache__/modeling_hunyuan_v1_moe.cpython-312.pyc,,
+transformers/models/hunyuan_v1_moe/__pycache__/modular_hunyuan_v1_moe.cpython-312.pyc,,
+transformers/models/hunyuan_v1_moe/configuration_hunyuan_v1_moe.py,sha256=nmUFkjh0OFIhhTrNuv0_A3JBX-6xrGo8rYvCI2Gzi5M,4406
+transformers/models/hunyuan_v1_moe/modeling_hunyuan_v1_moe.py,sha256=NByI008IBpQCrUWd2wOckN9nac-dlZeWFWwZLaB0Jtc,28092
+transformers/models/hunyuan_v1_moe/modular_hunyuan_v1_moe.py,sha256=0RnzmbGicrBH-pMGgxDpNg6KyvYd-Mo12Dn133mt4kY,8855
+transformers/models/hy_v3/__init__.py,sha256=7jDSKJqQbqXZ11eB2b2tQJTH0X359y3NdTOvZQtCzuI,1017
+transformers/models/hy_v3/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/hy_v3/__pycache__/configuration_hy_v3.cpython-312.pyc,,
+transformers/models/hy_v3/__pycache__/modeling_hy_v3.cpython-312.pyc,,
+transformers/models/hy_v3/__pycache__/modular_hy_v3.cpython-312.pyc,,
+transformers/models/hy_v3/configuration_hy_v3.py,sha256=H3CWiCrO72SGpgGhF0CFFe97NSDgwgIen5jOTTF0cwg,4860
+transformers/models/hy_v3/modeling_hy_v3.py,sha256=PoXGyCVA3jvtD2m6fEf1pXsD4gs5o1A8Y6rd8jijMnU,26586
+transformers/models/hy_v3/modular_hy_v3.py,sha256=d9KV2z0u7ygvqrc5p4un_eXIrbdJ7d9LV_M0o2whTzA,11937
+transformers/models/hyperclovax/__init__.py,sha256=_zyHdySLUwn-B_wCxPQK4gWtfMLp4vyP-1onuRKQIas,1030
+transformers/models/hyperclovax/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/hyperclovax/__pycache__/configuration_hyperclovax.cpython-312.pyc,,
+transformers/models/hyperclovax/__pycache__/modeling_hyperclovax.cpython-312.pyc,,
+transformers/models/hyperclovax/__pycache__/modular_hyperclovax.cpython-312.pyc,,
+transformers/models/hyperclovax/configuration_hyperclovax.py,sha256=18wjMf1J023pMHjYGRv2RePpZjuRniIFjJl9r_oLQAM,6083
+transformers/models/hyperclovax/modeling_hyperclovax.py,sha256=7CKhgxKhkJA_tw_mZsfPpNcBYlUW1ip4k0Ifs6ven8c,23468
+transformers/models/hyperclovax/modular_hyperclovax.py,sha256=kIxUk5q5c0-sixZjEO6uyO7IuOySNO95uSfDy9YTkkQ,8845
+transformers/models/ibert/__init__.py,sha256=UMTcE54y6O9UNF8l9VV2rrTlJSAHooxeNeHNzPSgr_E,991
+transformers/models/ibert/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/ibert/__pycache__/configuration_ibert.cpython-312.pyc,,
+transformers/models/ibert/__pycache__/modeling_ibert.cpython-312.pyc,,
+transformers/models/ibert/__pycache__/quant_modules.cpython-312.pyc,,
+transformers/models/ibert/configuration_ibert.py,sha256=sccHFJUkImrKxME8338AcUz_l0bCzGDfAfrrTuqrmlQ,2533
+transformers/models/ibert/modeling_ibert.py,sha256=jp0s_nK1lVljGOTHHE2V8_zI7wd7S2XaomZWRRJvl0g,48559
+transformers/models/ibert/quant_modules.py,sha256=eQX3kw7hmlwleHnFmdDyliQpQkotzmaLpsFFb3KYcuU,30059
+transformers/models/idefics/__init__.py,sha256=cy2FClk_acEYSxKF0xGwcyJ59sWYp5KWhFuQZNzh2K0,1125
+transformers/models/idefics/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/idefics/__pycache__/configuration_idefics.cpython-312.pyc,,
+transformers/models/idefics/__pycache__/image_processing_idefics.cpython-312.pyc,,
+transformers/models/idefics/__pycache__/image_processing_pil_idefics.cpython-312.pyc,,
+transformers/models/idefics/__pycache__/modeling_idefics.cpython-312.pyc,,
+transformers/models/idefics/__pycache__/perceiver.cpython-312.pyc,,
+transformers/models/idefics/__pycache__/processing_idefics.cpython-312.pyc,,
+transformers/models/idefics/__pycache__/vision.cpython-312.pyc,,
+transformers/models/idefics/configuration_idefics.py,sha256=0MHzpIobJFy6X2I7fTrZ7wliVhjZOWCQ4jIsvVKpiD0,6974
+transformers/models/idefics/image_processing_idefics.py,sha256=-2zsMQDUNDQj2dJkiugnCNuIDshfsKi2tqudXnm_khU,3444
+transformers/models/idefics/image_processing_pil_idefics.py,sha256=OpnhyF6pqIG24rD9vrB1QsCmxM8YCniWdA5clZ5Ox-M,3846
+transformers/models/idefics/modeling_idefics.py,sha256=keV9nmr49h_Wa3-8KZLBFDCAYRSRiOl7sfpXZskT4GA,55912
+transformers/models/idefics/perceiver.py,sha256=9rh7lz2ImHaRk2U3X_Mg-FoZXPtKzybt2hgAOJ9vX58,9394
+transformers/models/idefics/processing_idefics.py,sha256=xhkths5rK4kW5vypBQxtgzEeUW7seQknMW8Oc7p6Kw0,16965
+transformers/models/idefics/vision.py,sha256=UK_PJO4bFtXII3woTEbmzSE4DiDBCMtxJSBdHvmpIdc,15931
+transformers/models/idefics2/__init__.py,sha256=lIXXdX1ztYyzFVYs5OgJJrXi2GzQc0oj4D5_87vItwo,1130
+transformers/models/idefics2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/idefics2/__pycache__/configuration_idefics2.cpython-312.pyc,,
+transformers/models/idefics2/__pycache__/image_processing_idefics2.cpython-312.pyc,,
+transformers/models/idefics2/__pycache__/image_processing_pil_idefics2.cpython-312.pyc,,
+transformers/models/idefics2/__pycache__/modeling_idefics2.cpython-312.pyc,,
+transformers/models/idefics2/__pycache__/processing_idefics2.cpython-312.pyc,,
+transformers/models/idefics2/configuration_idefics2.py,sha256=X-yGyLqlZmDS8kQapSaR0hfas-jzkRoupt_ZRseqrvw,6630
+transformers/models/idefics2/image_processing_idefics2.py,sha256=uujvJQnGGllTONJ1qq3u6UneS7ogkFJxHob6hBu15Vo,11359
+transformers/models/idefics2/image_processing_pil_idefics2.py,sha256=iWzRdTBVWc0cV7JLMgf3uxV_DBuTfWX8gFePxCQ9Hoc,10319
+transformers/models/idefics2/modeling_idefics2.py,sha256=2lJtwjiOYKTHP-tMTa1Tu76rk_iSmpI3OsVc5AOQmu4,49607
+transformers/models/idefics2/processing_idefics2.py,sha256=b6SmPArpHmJoNL-XagKJPgG8Nzl3Df4XjWfSfZyyjbY,8093
+transformers/models/idefics3/__init__.py,sha256=epXR-ka4t3UxJcN_luGU6sNXWN4Xc5o6gU5OvcvVH0A,1130
+transformers/models/idefics3/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/idefics3/__pycache__/configuration_idefics3.cpython-312.pyc,,
+transformers/models/idefics3/__pycache__/image_processing_idefics3.cpython-312.pyc,,
+transformers/models/idefics3/__pycache__/image_processing_pil_idefics3.cpython-312.pyc,,
+transformers/models/idefics3/__pycache__/modeling_idefics3.cpython-312.pyc,,
+transformers/models/idefics3/__pycache__/processing_idefics3.cpython-312.pyc,,
+transformers/models/idefics3/configuration_idefics3.py,sha256=hmKPQaUUcqcyJ5UWKlNPsW-EOaOf2rhHD7XuLf6rEOI,4060
+transformers/models/idefics3/image_processing_idefics3.py,sha256=e3-BzhtIzJD2X5m0JOA47d60ApO39zNPIiVKLQXoch0,23540
+transformers/models/idefics3/image_processing_pil_idefics3.py,sha256=wNlIDqKhuUOqxurB2vu-bSzyBmHp19ZnJ1I-VTpe-N0,18876
+transformers/models/idefics3/modeling_idefics3.py,sha256=qrnHNcoPmQ9WlysRT0Hg-0u4678z30ZxtPSckOwGK4M,40027
+transformers/models/idefics3/processing_idefics3.py,sha256=bV5Bj0YlPGk_IftpIFCirl9XDHPQsvJsEyK8H3ZMPrQ,13822
+transformers/models/ijepa/__init__.py,sha256=O0_Jqpy8kmorYC-x0QsoMYSHdqQt3E1j-UZGLQ9aCv0,991
+transformers/models/ijepa/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/ijepa/__pycache__/configuration_ijepa.cpython-312.pyc,,
+transformers/models/ijepa/__pycache__/modeling_ijepa.cpython-312.pyc,,
+transformers/models/ijepa/__pycache__/modular_ijepa.cpython-312.pyc,,
+transformers/models/ijepa/configuration_ijepa.py,sha256=QSS8aaOY_4MN5JSIGMKrmH-MwIIlucZbOMFr6g6M1B4,2369
+transformers/models/ijepa/modeling_ijepa.py,sha256=gH7ZySsIyVGbFplx2Xav8BSioxgtj2TLOugGkICcRbk,18424
+transformers/models/ijepa/modular_ijepa.py,sha256=SHwcLp122YYWqJsLZjjMGBpcWLGKopIGrNuRTWS7xHQ,7307
+transformers/models/imagegpt/__init__.py,sha256=tJQCMksYMktW5YmBF2Q6g49sqK7e1KPK6HTe17DLRTQ,1138
+transformers/models/imagegpt/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/imagegpt/__pycache__/configuration_imagegpt.cpython-312.pyc,,
+transformers/models/imagegpt/__pycache__/image_processing_imagegpt.cpython-312.pyc,,
+transformers/models/imagegpt/__pycache__/image_processing_pil_imagegpt.cpython-312.pyc,,
+transformers/models/imagegpt/__pycache__/modeling_imagegpt.cpython-312.pyc,,
+transformers/models/imagegpt/configuration_imagegpt.py,sha256=Le-SUmoUVhVvGnobmE6m91HP9wUHifozhEQKgu2Htb0,2753
+transformers/models/imagegpt/image_processing_imagegpt.py,sha256=WwjPs8jHciU8EF2_UN0SN18AN4EOXKXZFLpY7cOu1C8,7942
+transformers/models/imagegpt/image_processing_pil_imagegpt.py,sha256=_MKPtOErZ0z706qU4GV2Nvl4Z09mVtVfHuGXyaMIBrk,5751
+transformers/models/imagegpt/modeling_imagegpt.py,sha256=dCIpTWKDYBDwSGM4-92XR8ksEcTfwD6ZTEudeHjQF18,35889
+transformers/models/informer/__init__.py,sha256=L-BwVQfdq5ve06VJJ-OnTh-m_YqSMNcpDQ1z6sbDtNI,997
+transformers/models/informer/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/informer/__pycache__/configuration_informer.cpython-312.pyc,,
+transformers/models/informer/__pycache__/modeling_informer.cpython-312.pyc,,
+transformers/models/informer/__pycache__/modular_informer.cpython-312.pyc,,
+transformers/models/informer/configuration_informer.py,sha256=RPsEfyKppOHXO0J74NQ_RvqUaZrMWQHkftFERdeqkrY,8133
+transformers/models/informer/modeling_informer.py,sha256=oAuhgvbHREmfnOd73Br1QaW8wOTdxSPt9T2JPqZj1CQ,85263
+transformers/models/informer/modular_informer.py,sha256=DcUpO89CBAdXBKv_xz6HM_YDKZPfK1_tpH7NFMXeQR4,38685
+transformers/models/instructblip/__init__.py,sha256=gI7F0N1dRSYdZtTumtuoPcIJcuBI8PO4DEOQS4_nWuc,1048
+transformers/models/instructblip/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/instructblip/__pycache__/configuration_instructblip.cpython-312.pyc,,
+transformers/models/instructblip/__pycache__/modeling_instructblip.cpython-312.pyc,,
+transformers/models/instructblip/__pycache__/processing_instructblip.cpython-312.pyc,,
+transformers/models/instructblip/configuration_instructblip.py,sha256=Xlr6zMopQkDP2ogGG5hHEN1ogY3mNjQnc1cJnLBUsAY,7316
+transformers/models/instructblip/modeling_instructblip.py,sha256=jnvctcpiKChs5skZJxAedC2MSZ8fhP3I4qxMXysY8ZI,60233
+transformers/models/instructblip/processing_instructblip.py,sha256=afU05hN3vHDxe8hW8TpYm8NsHHqIdGOxfBnRMDlw7IU,5403
+transformers/models/instructblipvideo/__init__.py,sha256=sgK7MEwrqKB6mQyEvhxcgOQc_OAtMDc9tAZqKF0sxfM,1171
+transformers/models/instructblipvideo/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/instructblipvideo/__pycache__/configuration_instructblipvideo.cpython-312.pyc,,
+transformers/models/instructblipvideo/__pycache__/modeling_instructblipvideo.cpython-312.pyc,,
+transformers/models/instructblipvideo/__pycache__/modular_instructblipvideo.cpython-312.pyc,,
+transformers/models/instructblipvideo/__pycache__/processing_instructblipvideo.cpython-312.pyc,,
+transformers/models/instructblipvideo/__pycache__/video_processing_instructblipvideo.cpython-312.pyc,,
+transformers/models/instructblipvideo/configuration_instructblipvideo.py,sha256=8sPmxZQP4AKZHM4Niynrd_WTHeIZSgLebNJ0rh3fgqU,8365
+transformers/models/instructblipvideo/modeling_instructblipvideo.py,sha256=6aAlpY6J3g6y6LtLQfrEngLeHFNEJATNBYNfoFJblAU,61053
+transformers/models/instructblipvideo/modular_instructblipvideo.py,sha256=6wA6R_VKTrqAQcQIPvJtF1YYRVxkjL6G_HvbPWFziI8,24555
+transformers/models/instructblipvideo/processing_instructblipvideo.py,sha256=Yjx3AOxIIOO0Xvl9oQGnFxFeNXhzUqsTBNtCYN0D3NA,6953
+transformers/models/instructblipvideo/video_processing_instructblipvideo.py,sha256=ipIn4TP_HnNCkG3Pu8hDsvqG4Jr-DqAPVd9-JfvtlMM,3591
+transformers/models/internvl/__init__.py,sha256=tNXeZ8TIWlY70CelRiihyPOudKQtRBZp-c9WqglJ8ss,1081
+transformers/models/internvl/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/internvl/__pycache__/configuration_internvl.cpython-312.pyc,,
+transformers/models/internvl/__pycache__/modeling_internvl.cpython-312.pyc,,
+transformers/models/internvl/__pycache__/modular_internvl.cpython-312.pyc,,
+transformers/models/internvl/__pycache__/processing_internvl.cpython-312.pyc,,
+transformers/models/internvl/__pycache__/video_processing_internvl.cpython-312.pyc,,
+transformers/models/internvl/configuration_internvl.py,sha256=G3Uvrs2hm1C04IqY5mQcEQx5K63rdHsaPW90eeoAYvo,5138
+transformers/models/internvl/modeling_internvl.py,sha256=_snxioPepC3TJzBVXKxaZuzmfvXyNvMpZ_7R8pbUK9Y,37163
+transformers/models/internvl/modular_internvl.py,sha256=blCVjD4MVkoZ8IDCnujCNA2kNfFRXE7n3c8Uo87aL5c,25263
+transformers/models/internvl/processing_internvl.py,sha256=Hy6PzPopoQW_9iU1AL39tMbsvFyukP3c3q2j2zr69Hs,12653
+transformers/models/internvl/video_processing_internvl.py,sha256=ZDE2h9dk-53kn2rWD11-j2Cu4S8ynntf1ms_5i4KPFw,6365
+transformers/models/jais2/__init__.py,sha256=LVvqkaW19UQe2FBjDw020iqwElvB1n4uqk7Snf_gcac,991
+transformers/models/jais2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/jais2/__pycache__/configuration_jais2.cpython-312.pyc,,
+transformers/models/jais2/__pycache__/modeling_jais2.cpython-312.pyc,,
+transformers/models/jais2/__pycache__/modular_jais2.cpython-312.pyc,,
+transformers/models/jais2/configuration_jais2.py,sha256=7QMNeTVcVYvEf-Ht1fAXlNJT2zb61CytQih6YLOLDCs,4235
+transformers/models/jais2/modeling_jais2.py,sha256=1DKhNMW7Bi0aL04EiZPUv0_ReyuRlevEwaTOGVxRZRE,20007
+transformers/models/jais2/modular_jais2.py,sha256=mq_T-3GbRTsA35RZPBD_OTX3CTrZaIQUwdKnOZvyY2U,3469
+transformers/models/jamba/__init__.py,sha256=zN7Rmr--d5GCEJzMA7gxIz-BYFydPN3cyuif85YU0Fk,991
+transformers/models/jamba/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/jamba/__pycache__/configuration_jamba.cpython-312.pyc,,
+transformers/models/jamba/__pycache__/modeling_jamba.cpython-312.pyc,,
+transformers/models/jamba/__pycache__/modular_jamba.cpython-312.pyc,,
+transformers/models/jamba/configuration_jamba.py,sha256=dpWJ24mNC50qlsy_4E41fz0UnUN5IUNyODmp16hnW1E,4780
+transformers/models/jamba/modeling_jamba.py,sha256=G23lVdjKk2QZEY_s6Q-VVSnHaVZLeJYvE_uucFN51TQ,42647
+transformers/models/jamba/modular_jamba.py,sha256=4cWkSWUPtH1vI9-jDwvJRK2QAMT0-SaOaqygqRqzYcw,29252
+transformers/models/janus/__init__.py,sha256=Qj2-bPxDXUNZdZ4vvWm8esfEMWpvvEwQaD0rRWMy99c,1131
+transformers/models/janus/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/janus/__pycache__/configuration_janus.cpython-312.pyc,,
+transformers/models/janus/__pycache__/image_processing_janus.cpython-312.pyc,,
+transformers/models/janus/__pycache__/image_processing_pil_janus.cpython-312.pyc,,
+transformers/models/janus/__pycache__/modeling_janus.cpython-312.pyc,,
+transformers/models/janus/__pycache__/modular_janus.cpython-312.pyc,,
+transformers/models/janus/__pycache__/processing_janus.cpython-312.pyc,,
+transformers/models/janus/configuration_janus.py,sha256=6F4qMcRUzrta5ogeFTMUeV_Pdu9UE_91DxVPYuyx-30,6787
+transformers/models/janus/image_processing_janus.py,sha256=bO6N6HFrMoJdqeo01n9YBvEIPWzH3bCCTFMO9BU9YQ0,8892
+transformers/models/janus/image_processing_pil_janus.py,sha256=o2cx_jwzIj5gVcdyJjpry78AISqS2WkqTr6bTTMW1GE,10488
+transformers/models/janus/modeling_janus.py,sha256=8CFxJAlCJWUt1VsPXNaW2Lj4tikqjm7V1uJmrRSgGQI,59052
+transformers/models/janus/modular_janus.py,sha256=GjDc-NimzDau219mN5BjmaR90fqvO8tyUfYtN2oxOFY,46904
+transformers/models/janus/processing_janus.py,sha256=NcoTn8v13I7o94KDx8GuPp4QBOM7YvV9ybxCDX90TFY,6529
+transformers/models/jetmoe/__init__.py,sha256=zhqtP2ZDCCl3Fp3VBnnuaA044Ztbh7fsUKogAKABOt0,993
+transformers/models/jetmoe/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/jetmoe/__pycache__/configuration_jetmoe.cpython-312.pyc,,
+transformers/models/jetmoe/__pycache__/modeling_jetmoe.cpython-312.pyc,,
+transformers/models/jetmoe/__pycache__/modular_jetmoe.cpython-312.pyc,,
+transformers/models/jetmoe/configuration_jetmoe.py,sha256=QyC4qAiZKUJ4uDCBwlkocAvdR88Y9C7INHTOXtHd3Qw,2933
+transformers/models/jetmoe/modeling_jetmoe.py,sha256=kvorbtCbRtaDQyS3yqOVUjAzuWC7e37YOG0EccRQBRU,35225
+transformers/models/jetmoe/modular_jetmoe.py,sha256=XVQg4E5kOWWlNb8MBhUs2luj7Ej3cDUW58vpMBs9pbk,23833
+transformers/models/jina_embeddings_v3/__init__.py,sha256=Mqh45DvGvTXRHHWJCSmmkWChvsgEjvEcuDNHCv8o_Mw,1019
+transformers/models/jina_embeddings_v3/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/jina_embeddings_v3/__pycache__/configuration_jina_embeddings_v3.cpython-312.pyc,,
+transformers/models/jina_embeddings_v3/__pycache__/modeling_jina_embeddings_v3.cpython-312.pyc,,
+transformers/models/jina_embeddings_v3/__pycache__/modular_jina_embeddings_v3.cpython-312.pyc,,
+transformers/models/jina_embeddings_v3/configuration_jina_embeddings_v3.py,sha256=SOZi5zxdCVhtc5mIsvVSI9VLxnfpBaOr1QacTyKJxCE,3109
+transformers/models/jina_embeddings_v3/modeling_jina_embeddings_v3.py,sha256=Mv8DDGthWrYqlM6jECEAvnsS7LxfOTcR1i2dH_s1-vs,34487
+transformers/models/jina_embeddings_v3/modular_jina_embeddings_v3.py,sha256=ySgzEN31mLMyF7Ts_Xj6zUhV0xB3gAWjmjQ5fFxi_ko,14872
+transformers/models/kosmos2/__init__.py,sha256=Ow8cLelhxl6fm5XvXzNQtPLt1xjIdVmGUwz5NoVVVto,1033
+transformers/models/kosmos2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/kosmos2/__pycache__/configuration_kosmos2.cpython-312.pyc,,
+transformers/models/kosmos2/__pycache__/modeling_kosmos2.cpython-312.pyc,,
+transformers/models/kosmos2/__pycache__/processing_kosmos2.cpython-312.pyc,,
+transformers/models/kosmos2/configuration_kosmos2.py,sha256=3C6iinVGyqjOrDina6QTqfA0Zb_lRwFu-ExqXqaoH6A,4397
+transformers/models/kosmos2/modeling_kosmos2.py,sha256=Z9lZNtOOjBv04fWyQRBWEI1Lblsr0AYUA78Xw_FmmX8,72415
+transformers/models/kosmos2/processing_kosmos2.py,sha256=dZMtfTH5Xj-skpD1YgtEgXQ1YpohcnTRVUAerepGr9A,29686
+transformers/models/kosmos2_5/__init__.py,sha256=phEyHz5rA6pBlxqiF1FmqQRklxn5OA-_SmPox52VAak,1163
+transformers/models/kosmos2_5/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/kosmos2_5/__pycache__/configuration_kosmos2_5.cpython-312.pyc,,
+transformers/models/kosmos2_5/__pycache__/image_processing_kosmos2_5.cpython-312.pyc,,
+transformers/models/kosmos2_5/__pycache__/image_processing_pil_kosmos2_5.cpython-312.pyc,,
+transformers/models/kosmos2_5/__pycache__/modeling_kosmos2_5.cpython-312.pyc,,
+transformers/models/kosmos2_5/__pycache__/processing_kosmos2_5.cpython-312.pyc,,
+transformers/models/kosmos2_5/configuration_kosmos2_5.py,sha256=7r_HrzNU6U0JUZs2iApqJ_vvIlnrD1lkCvNPPfTj6so,4997
+transformers/models/kosmos2_5/image_processing_kosmos2_5.py,sha256=EXoAKzsExyUxsbZTNYaRMf4yNJ0rwnnFiuJ-xVrpK6E,11673
+transformers/models/kosmos2_5/image_processing_pil_kosmos2_5.py,sha256=0L_scd5kU0mM7hm8kj2Ih3B1ThZiwZ_mdmibRlXS11Q,9978
+transformers/models/kosmos2_5/modeling_kosmos2_5.py,sha256=j0PbEsl49HMstCzm-8hihwUvhWJWXO4HZ7xZ0wSByHk,70997
+transformers/models/kosmos2_5/processing_kosmos2_5.py,sha256=JGMgmk_AEwP4P2Lbcixwper8irDA_em4PdQp4xOwSIw,5022
+transformers/models/kyutai_speech_to_text/__init__.py,sha256=KxatXD7pSOmwZWzs7nFOXG9Hc2wxaAS3CYwxg54lq9g,1135
+transformers/models/kyutai_speech_to_text/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/kyutai_speech_to_text/__pycache__/configuration_kyutai_speech_to_text.cpython-312.pyc,,
+transformers/models/kyutai_speech_to_text/__pycache__/feature_extraction_kyutai_speech_to_text.cpython-312.pyc,,
+transformers/models/kyutai_speech_to_text/__pycache__/modeling_kyutai_speech_to_text.cpython-312.pyc,,
+transformers/models/kyutai_speech_to_text/__pycache__/modular_kyutai_speech_to_text.cpython-312.pyc,,
+transformers/models/kyutai_speech_to_text/__pycache__/processing_kyutai_speech_to_text.cpython-312.pyc,,
+transformers/models/kyutai_speech_to_text/configuration_kyutai_speech_to_text.py,sha256=Smct-1-zJX0z8DxX7dIhLsgZ8-S1CApMmP7JZ0RJ260,3926
+transformers/models/kyutai_speech_to_text/feature_extraction_kyutai_speech_to_text.py,sha256=jwuZlFRJXx7ugj587aj1Hy2HcFzT0rQesJkd9piw36A,11643
+transformers/models/kyutai_speech_to_text/modeling_kyutai_speech_to_text.py,sha256=hWHsg9Oo3oJiEfFNstZP8w5ivgEqRUR3Y8_op2_Lzms,53704
+transformers/models/kyutai_speech_to_text/modular_kyutai_speech_to_text.py,sha256=jbgus_lUxGLN3BcWoG_S2KtogTiCME-3d8OZ4FP6l-s,24092
+transformers/models/kyutai_speech_to_text/processing_kyutai_speech_to_text.py,sha256=4ytDDKi8Hm7naE_eOdlJzWs44n3ls2MNNi4so6pzS2Q,1222
+transformers/models/laguna/__init__.py,sha256=4427XDmhSxOnGMpFstyywW3xOjKzOIgZaQq6VQm3z-o,1011
+transformers/models/laguna/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/laguna/__pycache__/configuration_laguna.cpython-312.pyc,,
+transformers/models/laguna/__pycache__/modeling_laguna.cpython-312.pyc,,
+transformers/models/laguna/__pycache__/modular_laguna.cpython-312.pyc,,
+transformers/models/laguna/configuration_laguna.py,sha256=oI5J1l9KvERep2kzeUwO_PXYznIRh7V87I8K3BoiqnY,7908
+transformers/models/laguna/modeling_laguna.py,sha256=O5GRr6M9iN9U2dngzyZK6V-SG6iftzfO2ZCfsUDj2Wg,34539
+transformers/models/laguna/modular_laguna.py,sha256=tZ-Tlum9Si2TZ2EjqHfC5Qyk4h6bbj8gvAUokQd0iq8,20210
+transformers/models/lasr/__init__.py,sha256=UbsmofJn1eRFzyEA05Ln2QkBbfutcUmuFy43LhASHGA,1069
+transformers/models/lasr/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/lasr/__pycache__/configuration_lasr.cpython-312.pyc,,
+transformers/models/lasr/__pycache__/feature_extraction_lasr.cpython-312.pyc,,
+transformers/models/lasr/__pycache__/modeling_lasr.cpython-312.pyc,,
+transformers/models/lasr/__pycache__/modular_lasr.cpython-312.pyc,,
+transformers/models/lasr/__pycache__/processing_lasr.cpython-312.pyc,,
+transformers/models/lasr/__pycache__/tokenization_lasr.cpython-312.pyc,,
+transformers/models/lasr/configuration_lasr.py,sha256=RoO_k4uH9viUX4u42PZHgNwKY6PnUuEOGA8UeEF0HzA,6665
+transformers/models/lasr/feature_extraction_lasr.py,sha256=p8UAKIOxI2PsufW64Vdm03aNO1JjTaQNeu-dpUGhfWA,12687
+transformers/models/lasr/modeling_lasr.py,sha256=D07YLBHUSx0xwJ4Uy1kdX9G_hghg2sBjFj7L5NBppCY,32398
+transformers/models/lasr/modular_lasr.py,sha256=4WNHFOQTlIFYt53kY78PjEFTCz6tMA1J-kKceUVnd6E,23584
+transformers/models/lasr/processing_lasr.py,sha256=GgfGRgDum7IeGCM-o5zEVB60jIq21vNw7D2u80diB-I,4495
+transformers/models/lasr/tokenization_lasr.py,sha256=LNSDQPmRIuXu33pm9gcgtPK7u-Donam6TZ5932ucC78,8081
+transformers/models/layoutlm/__init__.py,sha256=CXQ3kNqiSnGoJfjGmZnCsZWFljg1MYZVKSGXtSRpPyg,1153
+transformers/models/layoutlm/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/layoutlm/__pycache__/configuration_layoutlm.cpython-312.pyc,,
+transformers/models/layoutlm/__pycache__/modeling_layoutlm.cpython-312.pyc,,
+transformers/models/layoutlm/configuration_layoutlm.py,sha256=e0DRMc0jSkeau3SCBkWITad3wLd52vOnUaQoQI3pvTQ,2205
+transformers/models/layoutlm/modeling_layoutlm.py,sha256=f7nZIS5q9yGgp6qJ6bNP8iMd81xewKRuGSydeJqhUXc,40916
+transformers/models/layoutlmv2/__init__.py,sha256=xGZaeyByQsDCDcPtYSB7bsLBlQ_0CE1CnbOZj46vLM4,1232
+transformers/models/layoutlmv2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/layoutlmv2/__pycache__/configuration_layoutlmv2.cpython-312.pyc,,
+transformers/models/layoutlmv2/__pycache__/image_processing_layoutlmv2.cpython-312.pyc,,
+transformers/models/layoutlmv2/__pycache__/image_processing_pil_layoutlmv2.cpython-312.pyc,,
+transformers/models/layoutlmv2/__pycache__/modeling_layoutlmv2.cpython-312.pyc,,
+transformers/models/layoutlmv2/__pycache__/processing_layoutlmv2.cpython-312.pyc,,
+transformers/models/layoutlmv2/__pycache__/tokenization_layoutlmv2.cpython-312.pyc,,
+transformers/models/layoutlmv2/configuration_layoutlmv2.py,sha256=wphONXElpIO9zUiAaXdt0nYi7hTfxV9esiMSAceJVb8,7063
+transformers/models/layoutlmv2/image_processing_layoutlmv2.py,sha256=C0Or9MRZCGoSrho8p325MIaeqbPyVs7BpDE8FataT0I,7727
+transformers/models/layoutlmv2/image_processing_pil_layoutlmv2.py,sha256=D8QD8kzt8dlX5YrAW0IAstKcQrMCCb2qQEsviceGqNA,6797
+transformers/models/layoutlmv2/modeling_layoutlmv2.py,sha256=Y9wzEgj6l0nZKCCVJm_NEhwalav_tm2TbMXmrlM3TLQ,57859
+transformers/models/layoutlmv2/processing_layoutlmv2.py,sha256=TIowT2fNZDsaTRFVmtaCSX4D23LUw2n_cDr7xyY7sig,5316
+transformers/models/layoutlmv2/tokenization_layoutlmv2.py,sha256=PYbYwyLREzS3YX3C1QS7iiq5i2Owks7wEDH3aFusj34,42661
+transformers/models/layoutlmv3/__init__.py,sha256=iSwcuvi-8MxUDuGNBPq829cKvbZsUQpZdVZndfnzrZY,1232
+transformers/models/layoutlmv3/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/layoutlmv3/__pycache__/configuration_layoutlmv3.cpython-312.pyc,,
+transformers/models/layoutlmv3/__pycache__/image_processing_layoutlmv3.cpython-312.pyc,,
+transformers/models/layoutlmv3/__pycache__/image_processing_pil_layoutlmv3.cpython-312.pyc,,
+transformers/models/layoutlmv3/__pycache__/modeling_layoutlmv3.cpython-312.pyc,,
+transformers/models/layoutlmv3/__pycache__/processing_layoutlmv3.cpython-312.pyc,,
+transformers/models/layoutlmv3/__pycache__/tokenization_layoutlmv3.cpython-312.pyc,,
+transformers/models/layoutlmv3/configuration_layoutlmv3.py,sha256=B-QP5p9lzjq4TnEBpuynqgO_XrbcskJLcaw167C8lFc,4153
+transformers/models/layoutlmv3/image_processing_layoutlmv3.py,sha256=pmZHp0Acw-gZNwuA6sIEw_sAzadmXreomQ5oZiSlMiQ,8311
+transformers/models/layoutlmv3/image_processing_pil_layoutlmv3.py,sha256=aM8VqC498J3ucPB3zCafMG2_CRoFmyJvg_X5foQn2Jg,7332
+transformers/models/layoutlmv3/modeling_layoutlmv3.py,sha256=AC-k_IsYgGWpo0VP9-Pnw0VCRmEGEJENa0u3pWsPCWY,49328
+transformers/models/layoutlmv3/processing_layoutlmv3.py,sha256=rMkBG1RLG4OvWbyhl5tVddhS0bt3G9ShwUkwVR5NSOY,5097
+transformers/models/layoutlmv3/tokenization_layoutlmv3.py,sha256=ZDTROT5oDFfLQ6cVMFAIeP2U-aVUDfiFWQFPQ1yAuJE,42660
+transformers/models/layoutxlm/__init__.py,sha256=G7vpZzVESxlNUZ7PtI8z28ng6MalHJAXFViKeoFSkCA,1043
+transformers/models/layoutxlm/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/layoutxlm/__pycache__/configuration_layoutxlm.cpython-312.pyc,,
+transformers/models/layoutxlm/__pycache__/modular_layoutxlm.cpython-312.pyc,,
+transformers/models/layoutxlm/__pycache__/processing_layoutxlm.cpython-312.pyc,,
+transformers/models/layoutxlm/__pycache__/tokenization_layoutxlm.cpython-312.pyc,,
+transformers/models/layoutxlm/configuration_layoutxlm.py,sha256=6SsAc_Xrwj0ivISa_PBlmVjVNl1wztb9k3W40GrxJQ4,7817
+transformers/models/layoutxlm/modular_layoutxlm.py,sha256=FfhLgaHkIfqPhcaVMEt1mYlD4qaOYkkSLamEpnv0eYQ,3664
+transformers/models/layoutxlm/processing_layoutxlm.py,sha256=ibbzcqmbnKb4mUSVMZjY-AfJ7ZfxuiEVh7zTR1ABBNo,5294
+transformers/models/layoutxlm/tokenization_layoutxlm.py,sha256=u6W_Tmk83PS5KI5rozEAJjt9a1sMgFEYijuZpH3k10I,46151
+transformers/models/led/__init__.py,sha256=Zsd1RB7usdzST298N6SYV9M-3tC1W6Z8d4k-xwF-Vm8,1067
+transformers/models/led/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/led/__pycache__/configuration_led.cpython-312.pyc,,
+transformers/models/led/__pycache__/modeling_led.cpython-312.pyc,,
+transformers/models/led/configuration_led.py,sha256=mHdFbu0WjiyNevsCH5io5ASveEwUjLp_BSYIoxW81Mg,3214
+transformers/models/led/modeling_led.py,sha256=kqO1EOj-d8dqqUBg7WjrmqvZe1RlgGFP2SL0VpxIpDY,106918
+transformers/models/levit/__init__.py,sha256=KPggcwdXzikwNM7XbasxTXC2BTRVBDYnVGS_7aPzkF8,1123
+transformers/models/levit/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/levit/__pycache__/configuration_levit.cpython-312.pyc,,
+transformers/models/levit/__pycache__/image_processing_levit.cpython-312.pyc,,
+transformers/models/levit/__pycache__/image_processing_pil_levit.cpython-312.pyc,,
+transformers/models/levit/__pycache__/modeling_levit.cpython-312.pyc,,
+transformers/models/levit/configuration_levit.py,sha256=6gy3WMghZ1hFJGQdoO8jKRyVWbOThIhkWSI6W68GnUI,2854
+transformers/models/levit/image_processing_levit.py,sha256=RQ9IDEt6hIquqMRW1IdADtLz-V-I4oOThFwBb_JNsUI,2647
+transformers/models/levit/image_processing_pil_levit.py,sha256=PaQB89mc_clgEkIGZn6YB_z8Wk99mpfltD1o6WZ81Wo,2600
+transformers/models/levit/modeling_levit.py,sha256=wrpiYFOSuaSkhA_zn5p2eJv_6lFmesWdTzojrqbKlpI,25343
+transformers/models/lfm2/__init__.py,sha256=9fNMRtqveDp18iRtUjNqCu0XELuvwJOmizUyI1h0zHw,989
+transformers/models/lfm2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/lfm2/__pycache__/configuration_lfm2.cpython-312.pyc,,
+transformers/models/lfm2/__pycache__/modeling_lfm2.cpython-312.pyc,,
+transformers/models/lfm2/__pycache__/modular_lfm2.cpython-312.pyc,,
+transformers/models/lfm2/configuration_lfm2.py,sha256=Lfr7yVjBuG11f7-cjFaOVo_rqgGLFc-rY_kjgdURA-w,3442
+transformers/models/lfm2/modeling_lfm2.py,sha256=Lsi-iva2VIL1TSnlLal2W4Y843tlhGQj37_acvlE8VA,26190
+transformers/models/lfm2/modular_lfm2.py,sha256=LdIpQXoSiLT-NUUZj76S3WJFzmBLIBIW0VXf1uzPX4o,13631
+transformers/models/lfm2_moe/__init__.py,sha256=_yqIDhEkNsZIDJ1IlpVkA9Lvnlby05bpiPZvZid9na8,998
+transformers/models/lfm2_moe/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/lfm2_moe/__pycache__/configuration_lfm2_moe.cpython-312.pyc,,
+transformers/models/lfm2_moe/__pycache__/modeling_lfm2_moe.cpython-312.pyc,,
+transformers/models/lfm2_moe/__pycache__/modular_lfm2_moe.cpython-312.pyc,,
+transformers/models/lfm2_moe/configuration_lfm2_moe.py,sha256=op-n8txwxs5Gjmv8rX6TY04JHHDA50cHXVb1NJ6SM2E,2873
+transformers/models/lfm2_moe/modeling_lfm2_moe.py,sha256=U1AC6TTGXOcpW46QRr4NxVGk3RP4KHb3BvkFpt24SyE,30566
+transformers/models/lfm2_moe/modular_lfm2_moe.py,sha256=YEHEPWsFrD1TAaql2jb7P9GroRYjUIxine9yMVy9gyg,8318
+transformers/models/lfm2_vl/__init__.py,sha256=kQl_igbE4MuElPA6rLyBE5TN2-P9YWVuTD6xeBczu6s,1077
+transformers/models/lfm2_vl/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/lfm2_vl/__pycache__/configuration_lfm2_vl.cpython-312.pyc,,
+transformers/models/lfm2_vl/__pycache__/image_processing_lfm2_vl.cpython-312.pyc,,
+transformers/models/lfm2_vl/__pycache__/modeling_lfm2_vl.cpython-312.pyc,,
+transformers/models/lfm2_vl/__pycache__/modular_lfm2_vl.cpython-312.pyc,,
+transformers/models/lfm2_vl/__pycache__/processing_lfm2_vl.cpython-312.pyc,,
+transformers/models/lfm2_vl/configuration_lfm2_vl.py,sha256=g3eOB9SUzFFsYc3s6JueFEFLFyA009aBSnUeQfDV5UI,2559
+transformers/models/lfm2_vl/image_processing_lfm2_vl.py,sha256=wn5eRpsZlmXUlisB-QWx6Qojuhcl_rjHAbV06aI_LEA,23843
+transformers/models/lfm2_vl/modeling_lfm2_vl.py,sha256=BE28DpBlrmqoc8iJBt7rUSKNjGLXtkUmX9qWQs9qt9s,20285
+transformers/models/lfm2_vl/modular_lfm2_vl.py,sha256=AnpEeo14QwWtfMKQ71EGQ_-ZfL8mo6RbXiPOqnF92RY,14638
+transformers/models/lfm2_vl/processing_lfm2_vl.py,sha256=TcOxkkO_pDXn4sPAOJ22bfUDai8t2zd20KXAFPS_FJw,11061
+transformers/models/lightglue/__init__.py,sha256=DyD8bttBWM0wmEmYHqb7bCuZoBYvtZB4NsEmblYUm74,1095
+transformers/models/lightglue/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/lightglue/__pycache__/configuration_lightglue.cpython-312.pyc,,
+transformers/models/lightglue/__pycache__/image_processing_lightglue.cpython-312.pyc,,
+transformers/models/lightglue/__pycache__/image_processing_pil_lightglue.cpython-312.pyc,,
+transformers/models/lightglue/__pycache__/modeling_lightglue.cpython-312.pyc,,
+transformers/models/lightglue/__pycache__/modular_lightglue.cpython-312.pyc,,
+transformers/models/lightglue/configuration_lightglue.py,sha256=CNYhIzC5uV2C75d5sX4j1cTP3Irgvu7BIXXx4624-3w,4745
+transformers/models/lightglue/image_processing_lightglue.py,sha256=8hXrYfuCgQGJjopfU0XwFAIRuqKN6302Z7Epn7VBJZM,13536
+transformers/models/lightglue/image_processing_pil_lightglue.py,sha256=V1benv-TfEdSHru9DqDMFIEw35c6G21ujStS55yCBAY,12549
+transformers/models/lightglue/modeling_lightglue.py,sha256=ETgK5QyiHnYbiXRcPLCjvkQ0VkKDaTOuEUQPZTnCzRQ,43452
+transformers/models/lightglue/modular_lightglue.py,sha256=HTZYS0rS93CVpuTbtW2rZH_g_vFhQwxNWpQ7lv_9J-I,42881
+transformers/models/lighton_ocr/__init__.py,sha256=AuPKc-HKbs3mL5TQMIXjGEKFSgmqiesmHdh_vz1ufgA,1071
+transformers/models/lighton_ocr/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/lighton_ocr/__pycache__/configuration_lighton_ocr.cpython-312.pyc,,
+transformers/models/lighton_ocr/__pycache__/modeling_lighton_ocr.cpython-312.pyc,,
+transformers/models/lighton_ocr/__pycache__/modular_lighton_ocr.cpython-312.pyc,,
+transformers/models/lighton_ocr/__pycache__/processing_lighton_ocr.cpython-312.pyc,,
+transformers/models/lighton_ocr/configuration_lighton_ocr.py,sha256=ku3bLY2-2QwQlnDdZtXrvp-oO1R9hW-WHKlduS7T-Zc,4357
+transformers/models/lighton_ocr/modeling_lighton_ocr.py,sha256=f1de5INvpSdFoJYkqW2pTF5xM10aulPKWGuuuSP1Ycg,18360
+transformers/models/lighton_ocr/modular_lighton_ocr.py,sha256=LopBS9tN1Fy6OvGy0Y7gPViJhhOR6WPOSsxJLvJ0Ea8,14559
+transformers/models/lighton_ocr/processing_lighton_ocr.py,sha256=yxlHw3wcuCC_I8mryF4HA0w7-x7-_Dcg9c2HvLf5qLA,10389
+transformers/models/lilt/__init__.py,sha256=9XEq7kJwN0mKO469mR0mtlRUdljjq7V80gejpqb59K0,989
+transformers/models/lilt/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/lilt/__pycache__/configuration_lilt.cpython-312.pyc,,
+transformers/models/lilt/__pycache__/modeling_lilt.cpython-312.pyc,,
+transformers/models/lilt/configuration_lilt.py,sha256=EPMRDBLQUlZ91cSeYk1xXEx8vqFqJUndddEmsMR-u_0,2442
+transformers/models/lilt/modeling_lilt.py,sha256=aAfPci-OHhY_DovGt5ggkj3GJr-jlpENUi2WAlxHnsQ,42216
+transformers/models/llama/__init__.py,sha256=LudwEMppX6Bp64aF29OM0FLgQ8KOlJwqvA0Uhcax-cM,1029
+transformers/models/llama/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/llama/__pycache__/configuration_llama.cpython-312.pyc,,
+transformers/models/llama/__pycache__/modeling_llama.cpython-312.pyc,,
+transformers/models/llama/__pycache__/tokenization_llama.cpython-312.pyc,,
+transformers/models/llama/configuration_llama.py,sha256=Xi6APRWVbNxAKrHEpRUaiZvTnd--y7gRgXM2V4F6rto,3896
+transformers/models/llama/modeling_llama.py,sha256=RtMT7A8RFrzBu38jeUZ6sknBQEFcZPt1ji1ZFc2LiaU,21153
+transformers/models/llama/tokenization_llama.py,sha256=zPlApP7BmmzCAHnKz2X-kWGma1jujUaaQ23lOihfysg,6346
+transformers/models/llama4/__init__.py,sha256=svVyD2-Xvg0AAjZuP8TRjcIx3IZWJqhyUYrEGrriO2A,1073
+transformers/models/llama4/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/llama4/__pycache__/configuration_llama4.cpython-312.pyc,,
+transformers/models/llama4/__pycache__/image_processing_llama4.cpython-312.pyc,,
+transformers/models/llama4/__pycache__/modeling_llama4.cpython-312.pyc,,
+transformers/models/llama4/__pycache__/processing_llama4.cpython-312.pyc,,
+transformers/models/llama4/configuration_llama4.py,sha256=4BuOxj1cGFg8nplThAzwnmHJjjqCO_PbvLSum8bBw-c,11070
+transformers/models/llama4/image_processing_llama4.py,sha256=SwjoFWqDahW-NkeFv9ST2rlLdmsA4yoWSQu4Kde97CQ,17348
+transformers/models/llama4/modeling_llama4.py,sha256=lBOGlWWGdZRfq6008ncgyG-L2vkiuU3xP7D47b-PS6o,59440
+transformers/models/llama4/processing_llama4.py,sha256=oCaHuMVqg45Nfz-3NPBhTZlxdD7gL9crBT805oBe0ok,14177
+transformers/models/llava/__init__.py,sha256=nUcGSZUWVEYYaYa3c700g8ecdhNWbCce_7KG3Hiw1oA,1115
+transformers/models/llava/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/llava/__pycache__/configuration_llava.cpython-312.pyc,,
+transformers/models/llava/__pycache__/image_processing_llava.cpython-312.pyc,,
+transformers/models/llava/__pycache__/image_processing_pil_llava.cpython-312.pyc,,
+transformers/models/llava/__pycache__/modeling_llava.cpython-312.pyc,,
+transformers/models/llava/__pycache__/processing_llava.cpython-312.pyc,,
+transformers/models/llava/configuration_llava.py,sha256=bFTKJHnra4F39qvtJYC5D5JIQSYS9syDcPY2e8ihgrk,3788
+transformers/models/llava/image_processing_llava.py,sha256=XW7V0ScLwLOc0jzlU0btdRFuvewpfQm0NAoVz_h_59g,6277
+transformers/models/llava/image_processing_pil_llava.py,sha256=ELKb9m9yNioFFRDZjp77ML84clthsNZ3UdRbG_WhChE,4557
+transformers/models/llava/modeling_llava.py,sha256=tcRh_penXK_g3-DxIe9mjhYACz_NGTkmHZcmUjDR1ck,17800
+transformers/models/llava/processing_llava.py,sha256=hzO791gF3woNzfmHhma35GLsFa3UX_yWOfo7k4XLPng,4672
+transformers/models/llava_next/__init__.py,sha256=q-B1SPHCrREt-wKWPlTYD6or6NR7fqu_RIQ8HhiXJVw,1140
+transformers/models/llava_next/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/llava_next/__pycache__/configuration_llava_next.cpython-312.pyc,,
+transformers/models/llava_next/__pycache__/image_processing_llava_next.cpython-312.pyc,,
+transformers/models/llava_next/__pycache__/image_processing_pil_llava_next.cpython-312.pyc,,
+transformers/models/llava_next/__pycache__/modeling_llava_next.cpython-312.pyc,,
+transformers/models/llava_next/__pycache__/processing_llava_next.cpython-312.pyc,,
+transformers/models/llava_next/configuration_llava_next.py,sha256=Ke32gWcsL20TqlroXhgz5h3wk18nl18bMJULBeNMkLA,3962
+transformers/models/llava_next/image_processing_llava_next.py,sha256=Qj3XsyulWtbmE3OyTFY9kUHCuudN5i1vFKiD2EH4yOA,9752
+transformers/models/llava_next/image_processing_pil_llava_next.py,sha256=5kWQKaSZgpU58YHhRCmd-K1hk-4aa5MrjUgWMLa-rm8,9062
+transformers/models/llava_next/modeling_llava_next.py,sha256=JOcy5VJOCUNkQos9dLq_C1kJmVSLSbKQqsmwoGEgyJk,30446
+transformers/models/llava_next/processing_llava_next.py,sha256=xSQBKCXKYNkE1PjHRk1dDtmr5-Pe3IfyWFoTcuAZi04,10757
+transformers/models/llava_next_video/__init__.py,sha256=OGiUL7X9x0bzmsnZi0KA6Sl2ycalLQHkTgOpISYu3q8,1113
+transformers/models/llava_next_video/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/llava_next_video/__pycache__/configuration_llava_next_video.cpython-312.pyc,,
+transformers/models/llava_next_video/__pycache__/modeling_llava_next_video.cpython-312.pyc,,
+transformers/models/llava_next_video/__pycache__/modular_llava_next_video.cpython-312.pyc,,
+transformers/models/llava_next_video/__pycache__/processing_llava_next_video.cpython-312.pyc,,
+transformers/models/llava_next_video/__pycache__/video_processing_llava_next_video.cpython-312.pyc,,
+transformers/models/llava_next_video/configuration_llava_next_video.py,sha256=U1HgiNo6y9HIvi1zSJX6PD9j0Sq6Dc9gA6VyRn7VWJ0,5484
+transformers/models/llava_next_video/modeling_llava_next_video.py,sha256=WqIixU4UyCy4bl1dqiIGIaUzLGQEzZ9ocUjXeIb2eZk,41496
+transformers/models/llava_next_video/modular_llava_next_video.py,sha256=lvx_GhBpK0ETL8hXuqVXt-IpgGVTGTVNMrP9eCuq-j4,30737
+transformers/models/llava_next_video/processing_llava_next_video.py,sha256=rDbKe33o5JrTMvLjlqSI7OK_BIlKJuqZkqJM1YONwq0,9434
+transformers/models/llava_next_video/video_processing_llava_next_video.py,sha256=M9zikrv4btULV6w01WgzWLoQsLFh1QZdOkr6xiFeLf8,1333
+transformers/models/llava_onevision/__init__.py,sha256=cpBN3UFtjQTYSGH_54uQJI5ZtMahkVWLmRgYKl9ZjEA,1217
+transformers/models/llava_onevision/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/llava_onevision/__pycache__/configuration_llava_onevision.cpython-312.pyc,,
+transformers/models/llava_onevision/__pycache__/image_processing_llava_onevision.cpython-312.pyc,,
+transformers/models/llava_onevision/__pycache__/image_processing_pil_llava_onevision.cpython-312.pyc,,
+transformers/models/llava_onevision/__pycache__/modeling_llava_onevision.cpython-312.pyc,,
+transformers/models/llava_onevision/__pycache__/modular_llava_onevision.cpython-312.pyc,,
+transformers/models/llava_onevision/__pycache__/processing_llava_onevision.cpython-312.pyc,,
+transformers/models/llava_onevision/__pycache__/video_processing_llava_onevision.cpython-312.pyc,,
+transformers/models/llava_onevision/configuration_llava_onevision.py,sha256=hygBUULtbDAl5cU7fym-mALRpmVtm1TWWN4YuHsShwY,5571
+transformers/models/llava_onevision/image_processing_llava_onevision.py,sha256=00o8SZHKMo1qmv3I51Et38ScFyOcudq4g056oPCpRS8,13317
+transformers/models/llava_onevision/image_processing_pil_llava_onevision.py,sha256=_2CvJOrJdnD-EyZWUAVIoygpJFKDnhdrXUht1IHfweo,12967
+transformers/models/llava_onevision/modeling_llava_onevision.py,sha256=tSkudatvWL8uwwnDAqshhhgIbBoMdJEeZ1wLnbvtAdo,40097
+transformers/models/llava_onevision/modular_llava_onevision.py,sha256=HHAJPhk586N20-vj9xFFPpwZDEGS6M4rAFBaUOHjeZk,39275
+transformers/models/llava_onevision/processing_llava_onevision.py,sha256=7ItGahhJSJdLURSQWPdb6azc3-sK5hLdCzoq6DRjUdM,13975
+transformers/models/llava_onevision/video_processing_llava_onevision.py,sha256=HESFKZLb3MKHPq_ONupz6cN4RZYGippChiPIMsSvD8c,1343
+transformers/models/longcat_flash/__init__.py,sha256=UhywfXc2iMxAuE8H--Mm6vxHLlKUp0FAAe0aq8QBxKA,1025
+transformers/models/longcat_flash/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/longcat_flash/__pycache__/configuration_longcat_flash.cpython-312.pyc,,
+transformers/models/longcat_flash/__pycache__/modeling_longcat_flash.cpython-312.pyc,,
+transformers/models/longcat_flash/__pycache__/modular_longcat_flash.cpython-312.pyc,,
+transformers/models/longcat_flash/configuration_longcat_flash.py,sha256=ttt4Thoa1A5RpsWf_Ni-0BoGq7WIUWnw3EKqwfRewkQ,4370
+transformers/models/longcat_flash/modeling_longcat_flash.py,sha256=du_Z8ZDsrUn94rQRVwZ8tsCjr-x9I_W4SsuoMxOg-wk,31799
+transformers/models/longcat_flash/modular_longcat_flash.py,sha256=8uoHfPqKxcyAuExihhHFy7nzje_6os93hLtODWdtAgI,17682
+transformers/models/longformer/__init__.py,sha256=qPm9rxvA-GeXV4gkzDqwu-SooVa3SBUvYI8C_SFgeYE,1088
+transformers/models/longformer/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/longformer/__pycache__/configuration_longformer.cpython-312.pyc,,
+transformers/models/longformer/__pycache__/modeling_longformer.cpython-312.pyc,,
+transformers/models/longformer/configuration_longformer.py,sha256=Ccg0XAJW2HkLakinbjNM66_JyZCBQ2_qRmpJMDtXjDE,2470
+transformers/models/longformer/modeling_longformer.py,sha256=vNQCEbZ8bEVT1o0OekzFtO4TVnjXdouyGJPPbi2Nxfc,103510
+transformers/models/longt5/__init__.py,sha256=nmh4Vo8chv_I8xPFPFKu3Rfa_YbctUxl4ik5Ao-AaIM,993
+transformers/models/longt5/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/longt5/__pycache__/configuration_longt5.cpython-312.pyc,,
+transformers/models/longt5/__pycache__/modeling_longt5.cpython-312.pyc,,
+transformers/models/longt5/configuration_longt5.py,sha256=dTitkYf2r5_2TKTsYuZotrQA1Z1tgnGpEmB-dkb8SU8,4271
+transformers/models/longt5/modeling_longt5.py,sha256=nyeGxI32ONBjZ9kYu-wAU6Nu3eqUzZgnCDt_OFHEJPE,83907
+transformers/models/luke/__init__.py,sha256=YQL403sV6tk5t8sjvi-4hgvx1rvyThx45l7S4T4xpEE,1026
+transformers/models/luke/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/luke/__pycache__/configuration_luke.cpython-312.pyc,,
+transformers/models/luke/__pycache__/modeling_luke.cpython-312.pyc,,
+transformers/models/luke/__pycache__/tokenization_luke.cpython-312.pyc,,
+transformers/models/luke/configuration_luke.py,sha256=YRivKjoKu40weKwdE0L3yKVAAqeL2cLultwiemx9xbg,2694
+transformers/models/luke/modeling_luke.py,sha256=wPbFp2ItkdYsiHYTicoeI1COYDNzSOiG6Vesgy5syMk,94751
+transformers/models/luke/tokenization_luke.py,sha256=974FzW2AXiu5_1iWb82zLcAj8H6saV1lz8cpNa7NjI4,82055
+transformers/models/lw_detr/__init__.py,sha256=aR6j6aZ-ntKyVKN1HzWJHOPLZjeNK9iVKg-476Chk04,995
+transformers/models/lw_detr/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/lw_detr/__pycache__/configuration_lw_detr.cpython-312.pyc,,
+transformers/models/lw_detr/__pycache__/modeling_lw_detr.cpython-312.pyc,,
+transformers/models/lw_detr/__pycache__/modular_lw_detr.cpython-312.pyc,,
+transformers/models/lw_detr/configuration_lw_detr.py,sha256=LCmo5vbLiL2NGUo78l59brLTGrsulAirCZt2GFfTM4E,10668
+transformers/models/lw_detr/modeling_lw_detr.py,sha256=KUXhXDpP2_nan8bmZSa4c68Gdf99DHmW3_A-6XnU0ts,74060
+transformers/models/lw_detr/modular_lw_detr.py,sha256=45oYrSCqeJO4AbrHpnDp_FpIotONG5GvruRjBSFM2cs,60788
+transformers/models/lxmert/__init__.py,sha256=kt9QI783KwDwwUPx4BIY8AH-IHKydHuVJal6hRZpINU,1067
+transformers/models/lxmert/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/lxmert/__pycache__/configuration_lxmert.cpython-312.pyc,,
+transformers/models/lxmert/__pycache__/modeling_lxmert.cpython-312.pyc,,
+transformers/models/lxmert/configuration_lxmert.py,sha256=l0IqAusZ-hBJ5o3jxknMi-6Sw2adKQTCdVcpjb2FGf0,5183
+transformers/models/lxmert/modeling_lxmert.py,sha256=a8aiH4M9R6WrX4Fwzfq9LhYiqyxPVPrYw0sC28Yqwtk,58567
+transformers/models/m2m_100/__init__.py,sha256=0uPov299rgQmMwwSyM_m0yGFejP5djgaUY37GkNGnC8,1035
+transformers/models/m2m_100/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/m2m_100/__pycache__/configuration_m2m_100.cpython-312.pyc,,
+transformers/models/m2m_100/__pycache__/modeling_m2m_100.cpython-312.pyc,,
+transformers/models/m2m_100/__pycache__/tokenization_m2m_100.cpython-312.pyc,,
+transformers/models/m2m_100/configuration_m2m_100.py,sha256=MkZHNlxlwYKSB-PlN_Y9CwTSzVLdXJz2VmLxALnocUM,2473
+transformers/models/m2m_100/modeling_m2m_100.py,sha256=XVnLhk5KaTiAIL8NqkVEgRSauHbrj-GfyLRZfL-OKns,38612
+transformers/models/m2m_100/tokenization_m2m_100.py,sha256=II_GyUrqHFNEFzTylsmYDQ-aWskX7byIXtXvwnmrrOE,16373
+transformers/models/mamba/__init__.py,sha256=4oGJySQbwoALRGVWMEwXBm0A6fhKsr4Raly46a5g1G0,991
+transformers/models/mamba/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/mamba/__pycache__/configuration_mamba.cpython-312.pyc,,
+transformers/models/mamba/__pycache__/modeling_mamba.cpython-312.pyc,,
+transformers/models/mamba/configuration_mamba.py,sha256=3GWyzZB6Vbbux66jGU0EH2HOfdUkLb-JilxPoNUT-GA,4274
+transformers/models/mamba/modeling_mamba.py,sha256=I8e0EOIEtdoBcyVm3hDJS3CoQY7LYI5Al1SwAzLrKkE,32590
+transformers/models/mamba2/__init__.py,sha256=Ui4j-I2cnPEEszkzRTLSUW42SE4Qg1YTuW6hGeaOFZg,993
+transformers/models/mamba2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/mamba2/__pycache__/configuration_mamba2.cpython-312.pyc,,
+transformers/models/mamba2/__pycache__/modeling_mamba2.cpython-312.pyc,,
+transformers/models/mamba2/configuration_mamba2.py,sha256=D85wAHsQH2XpPs6jV3nBt8esUS1QkKxa3IXhE6oMnnA,4100
+transformers/models/mamba2/modeling_mamba2.py,sha256=Ox0vldtswz5qMTxevA395Lb_NLroyFm4nhiw97KNPKc,41392
+transformers/models/marian/__init__.py,sha256=IavSoQb-8nSlrq_0eDIkX4zD1tGNj4ybHyRKrDOTnMY,1032
+transformers/models/marian/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/marian/__pycache__/configuration_marian.cpython-312.pyc,,
+transformers/models/marian/__pycache__/modeling_marian.cpython-312.pyc,,
+transformers/models/marian/__pycache__/tokenization_marian.cpython-312.pyc,,
+transformers/models/marian/configuration_marian.py,sha256=pU6s3pVjpVx4-4oc53DnZfZxD8HVrInT5bjtrYcMe7Y,3049
+transformers/models/marian/modeling_marian.py,sha256=FXETo2wBaJmdid63LvTbT5XuoYoXhNFj5H9-yzUYVYQ,46690
+transformers/models/marian/tokenization_marian.py,sha256=14YSQmg4xlvitWyRhFGVOGi1Fa3Q-ZP-u_TjkM6czL0,18086
+transformers/models/markuplm/__init__.py,sha256=-zg9rYmX3BVnq2mZPjDnW2bvZv2LIu6vm_y9grRTTRU,1083
+transformers/models/markuplm/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/markuplm/__pycache__/configuration_markuplm.cpython-312.pyc,,
+transformers/models/markuplm/__pycache__/feature_extraction_markuplm.cpython-312.pyc,,
+transformers/models/markuplm/__pycache__/modeling_markuplm.cpython-312.pyc,,
+transformers/models/markuplm/__pycache__/processing_markuplm.cpython-312.pyc,,
+transformers/models/markuplm/__pycache__/tokenization_markuplm.cpython-312.pyc,,
+transformers/models/markuplm/configuration_markuplm.py,sha256=JNyMhP3XrluPfg9K0oCJBaY7Aw5Hf1_vt2XCJ4xt-WM,3079
+transformers/models/markuplm/feature_extraction_markuplm.py,sha256=DTZiB6aiAsEW1sPj_w5qTtr76BSVCpd15wmZUXCuj9A,6428
+transformers/models/markuplm/modeling_markuplm.py,sha256=gZKditBr9AYGC-UmUKNx3EVJjZisJNz87XpVjZiwszM,36754
+transformers/models/markuplm/processing_markuplm.py,sha256=pTpnvCXls-BqlEL0KG0OuIhEB5M-KMwj7shprN8iY1k,5710
+transformers/models/markuplm/tokenization_markuplm.py,sha256=NCA_J-GDnJmNNiFkZ3VZxbFgyy23Uct9SiOwG9XImkw,48683
+transformers/models/mask2former/__init__.py,sha256=dPj1jNTWwQC9o5puiaViYedBZrJy86dHK4RdONsyzW0,1103
+transformers/models/mask2former/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/mask2former/__pycache__/configuration_mask2former.cpython-312.pyc,,
+transformers/models/mask2former/__pycache__/image_processing_mask2former.cpython-312.pyc,,
+transformers/models/mask2former/__pycache__/image_processing_pil_mask2former.cpython-312.pyc,,
+transformers/models/mask2former/__pycache__/modeling_mask2former.cpython-312.pyc,,
+transformers/models/mask2former/__pycache__/modular_mask2former.cpython-312.pyc,,
+transformers/models/mask2former/configuration_mask2former.py,sha256=_6dT-wub-X9bE2LwLWgUX38AlaUJ4SeYWxKhH0pNA1E,5631
+transformers/models/mask2former/image_processing_mask2former.py,sha256=aB12iO_ACRV9Q1hQmtEvHOmyPT9aA57jWpQirCO1-6s,38054
+transformers/models/mask2former/image_processing_pil_mask2former.py,sha256=0BDYd9trqlQIsYQhv_WMbDc-bs1Dpkv7XkwWj8rSQ8o,38874
+transformers/models/mask2former/modeling_mask2former.py,sha256=8o2fMWG5ylSB4NiMsko3bxPT2mpuG4G4Q90zZalo6dI,118096
+transformers/models/mask2former/modular_mask2former.py,sha256=S1S3t6KKSXtg3nTkvIenb0UnIrqGf4W8LaZ8JAlCKQw,30328
+transformers/models/maskformer/__init__.py,sha256=1D9sBz_NezjEvIdO2uPohNvGe1eIPtSSGfz_YZHxDDQ,1241
+transformers/models/maskformer/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/maskformer/__pycache__/configuration_maskformer.cpython-312.pyc,,
+transformers/models/maskformer/__pycache__/configuration_maskformer_swin.cpython-312.pyc,,
+transformers/models/maskformer/__pycache__/image_processing_maskformer.cpython-312.pyc,,
+transformers/models/maskformer/__pycache__/image_processing_pil_maskformer.cpython-312.pyc,,
+transformers/models/maskformer/__pycache__/modeling_maskformer.cpython-312.pyc,,
+transformers/models/maskformer/__pycache__/modeling_maskformer_swin.cpython-312.pyc,,
+transformers/models/maskformer/__pycache__/modular_maskformer.cpython-312.pyc,,
+transformers/models/maskformer/configuration_maskformer.py,sha256=QPO_r_dt3GCwFhoDgl8O6I_5VIqEQ__uF3uLf-6Q7JQ,9600
+transformers/models/maskformer/configuration_maskformer_swin.py,sha256=96SFylDenaeERHCD5GfoYGf6oeHunChp1d3prADlRsY,3084
+transformers/models/maskformer/image_processing_maskformer.py,sha256=8xY24ZvHDX3f2-aYrwAljSSa8DThAMSP4PX-YmMFCF0,37011
+transformers/models/maskformer/image_processing_pil_maskformer.py,sha256=NXdOWtOND5yS_MiaNWicn_DVrKtkFaOxGu2X4xfUm2g,37452
+transformers/models/maskformer/modeling_maskformer.py,sha256=pCeRYxx_UQhjc4gwdXiFy_w0_cgSl3p-shMHTJ-lWgY,96247
+transformers/models/maskformer/modeling_maskformer_swin.py,sha256=9vUbFA_0_vEbqF5loL8YYJXo52cb6er3HH16kdgrRe8,37084
+transformers/models/maskformer/modular_maskformer.py,sha256=s26EwLiWkGoXg4cArRgIzyZwyScBAsLCVoP0VWLp61o,68606
+transformers/models/mbart/__init__.py,sha256=VYCZE-XKXmLlOTjcAToavJNZALlW0UNqkgdcdhLnm8c,1029
+transformers/models/mbart/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/mbart/__pycache__/configuration_mbart.cpython-312.pyc,,
+transformers/models/mbart/__pycache__/modeling_mbart.cpython-312.pyc,,
+transformers/models/mbart/__pycache__/tokenization_mbart.cpython-312.pyc,,
+transformers/models/mbart/configuration_mbart.py,sha256=waS74IOaBpAUj6rBh3zlrttWVdsR_1-OW-xd9nu9G6Y,2613
+transformers/models/mbart/modeling_mbart.py,sha256=aX2gOMT7mzdowFx0tsYMjmaqvdxY3hMb_aqoCnqoa4U,61144
+transformers/models/mbart/tokenization_mbart.py,sha256=iChlZW6tL561ENOD_oTXF97aUcCk0kI0Qfmm9QA8njE,8473
+transformers/models/mbart50/__init__.py,sha256=ZxOzDc6AP0x0jp3EgGeQZx1xOApVeWbuQan7aqj-Xeo,958
+transformers/models/mbart50/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/mbart50/__pycache__/tokenization_mbart50.cpython-312.pyc,,
+transformers/models/mbart50/tokenization_mbart50.py,sha256=SRLYweqPO2HkV9nnGOo3MnpLHDVfKNmY-Wy2X89DV9g,14366
+transformers/models/megatron_bert/__init__.py,sha256=u1UIYjQlrfHcy81i2FzehRDJpt6KNfNJ4AePQYKgwOU,1007
+transformers/models/megatron_bert/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/megatron_bert/__pycache__/configuration_megatron_bert.cpython-312.pyc,,
+transformers/models/megatron_bert/__pycache__/modeling_megatron_bert.cpython-312.pyc,,
+transformers/models/megatron_bert/configuration_megatron_bert.py,sha256=zhxQJjtm8UM4NLVXwATN6-MYk4rcbRD2hbCQvgJPCVk,2165
+transformers/models/megatron_bert/modeling_megatron_bert.py,sha256=Wsm4SdwGiqlO61XtSX_E_2XghgIc897h_mvWOTd6X2A,60103
+transformers/models/megatron_gpt2/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+transformers/models/megatron_gpt2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/megatron_gpt2/__pycache__/checkpoint_reshaping_and_interoperability.cpython-312.pyc,,
+transformers/models/megatron_gpt2/checkpoint_reshaping_and_interoperability.py,sha256=3Oe0z75_0SQSM4OR-hRtH_w24LmhSV9AgsyzwKA2R9Y,37650
+transformers/models/mellum/__init__.py,sha256=aCZwnitFdfoEuhNjbrN54mDqtrz0JBlT4EhRzfbfkqQ,993
+transformers/models/mellum/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/mellum/__pycache__/configuration_mellum.cpython-312.pyc,,
+transformers/models/mellum/__pycache__/modeling_mellum.cpython-312.pyc,,
+transformers/models/mellum/__pycache__/modular_mellum.cpython-312.pyc,,
+transformers/models/mellum/configuration_mellum.py,sha256=a7tT-txqnxe1KYGsuFoa634e4U-DVrN5bC1fpoV84c8,5593
+transformers/models/mellum/modeling_mellum.py,sha256=KoDMy9AfLi3dORrARBReeMcdwGN0QP92W4zPmtLvzQY,33200
+transformers/models/mellum/modular_mellum.py,sha256=BJ9GCD7J88z-8O_u4VEw2392EscDIMKOGTscIXw27pU,4783
+transformers/models/metaclip_2/__init__.py,sha256=S5n45gZa_DwDJ3PtBbKzcjqDd6uOY4sbsSXR227oFZI,1001
+transformers/models/metaclip_2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/metaclip_2/__pycache__/configuration_metaclip_2.cpython-312.pyc,,
+transformers/models/metaclip_2/__pycache__/modeling_metaclip_2.cpython-312.pyc,,
+transformers/models/metaclip_2/__pycache__/modular_metaclip_2.cpython-312.pyc,,
+transformers/models/metaclip_2/configuration_metaclip_2.py,sha256=yeRCTRZdQrftXv4LQLcXpOemrP6VtMFoLtqkHeftZyE,11438
+transformers/models/metaclip_2/modeling_metaclip_2.py,sha256=ZpzaVJCB1Z6oMl9ZU7fMeFUpsTBUk0b0QicV1qkRmuo,48570
+transformers/models/metaclip_2/modular_metaclip_2.py,sha256=8umQZ_GH4bNmmaoT_I1QHT0Q3xdK9ACx8C_8xemO2JA,27215
+transformers/models/mgp_str/__init__.py,sha256=Qb3mXPCrWbQ1ksMRYMeXorrva97OOFNr1zoy4YQg-9k,1073
+transformers/models/mgp_str/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/mgp_str/__pycache__/configuration_mgp_str.cpython-312.pyc,,
+transformers/models/mgp_str/__pycache__/modeling_mgp_str.cpython-312.pyc,,
+transformers/models/mgp_str/__pycache__/processing_mgp_str.cpython-312.pyc,,
+transformers/models/mgp_str/__pycache__/tokenization_mgp_str.cpython-312.pyc,,
+transformers/models/mgp_str/configuration_mgp_str.py,sha256=TzBH9w4BEQjv6mbUKxLiz0mHwgfHLh15hMd2ouvFGQE,3046
+transformers/models/mgp_str/modeling_mgp_str.py,sha256=Z8faJVtcIkQTNrFtCE4qH0amHWaCa8qbOR2v8wMejgo,18185
+transformers/models/mgp_str/processing_mgp_str.py,sha256=UDIB0OiQH9v7waJ-0khtCBO6Hv0vCj8bYMr0VPKzEaE,7804
+transformers/models/mgp_str/tokenization_mgp_str.py,sha256=XrqjbDcTci9sZ-d-CXHlzzhwyw7h0lAnD6GRouCNYrs,3791
+transformers/models/mimi/__init__.py,sha256=VXRZ-D8-AyOYcmRGvSxhjwTYQcSNXcCXi5ubks6Qxhk,989
+transformers/models/mimi/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/mimi/__pycache__/configuration_mimi.cpython-312.pyc,,
+transformers/models/mimi/__pycache__/modeling_mimi.cpython-312.pyc,,
+transformers/models/mimi/configuration_mimi.py,sha256=CjL09sU2N-gozh5EjEWKGQnXmdGReAkUzVJuxhxDAMo,7783
+transformers/models/mimi/modeling_mimi.py,sha256=-uGWtuA2jENuAXekYPJE4gJIMBLg0MrSm6-sDpP-a_Y,79103
+transformers/models/minicpmv4_6/__init__.py,sha256=cCJluuxIKYMSQtT1BPE8cbeT3m_ZfGv-oFrNhDe0jxQ,1212
+transformers/models/minicpmv4_6/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/minicpmv4_6/__pycache__/configuration_minicpmv4_6.cpython-312.pyc,,
+transformers/models/minicpmv4_6/__pycache__/image_processing_minicpmv4_6.cpython-312.pyc,,
+transformers/models/minicpmv4_6/__pycache__/image_processing_pil_minicpmv4_6.cpython-312.pyc,,
+transformers/models/minicpmv4_6/__pycache__/modeling_minicpmv4_6.cpython-312.pyc,,
+transformers/models/minicpmv4_6/__pycache__/modular_minicpmv4_6.cpython-312.pyc,,
+transformers/models/minicpmv4_6/__pycache__/processing_minicpmv4_6.cpython-312.pyc,,
+transformers/models/minicpmv4_6/__pycache__/video_processing_minicpmv4_6.cpython-312.pyc,,
+transformers/models/minicpmv4_6/configuration_minicpmv4_6.py,sha256=84dl5MlSYE9Lr7iUh-J9yOiBPGJCKzDb5_h5iTzRigE,5348
+transformers/models/minicpmv4_6/image_processing_minicpmv4_6.py,sha256=Ya4QV4tHfIEaDrshUxUhcOhOj1VDfEmJw62tmNxqQsU,10711
+transformers/models/minicpmv4_6/image_processing_pil_minicpmv4_6.py,sha256=nQTU-s39EKYRqfUfRNGfdWNbzHqgvztap7q0Q3D90uM,10481
+transformers/models/minicpmv4_6/modeling_minicpmv4_6.py,sha256=o375QVTgsO85GK5g37Q-hxpZZNajz0jNUB3Da_hjEZs,40096
+transformers/models/minicpmv4_6/modular_minicpmv4_6.py,sha256=mFQt8oCpyLfE0xOC6vB1c9VNkMQcj5suBSo9kmdVAWQ,37405
+transformers/models/minicpmv4_6/processing_minicpmv4_6.py,sha256=st998dFDfCG8zsOaLRkrIYuGcbkk-0r3zkVBukj7ykk,9891
+transformers/models/minicpmv4_6/video_processing_minicpmv4_6.py,sha256=uXN0z3buKNlZ3m6ybVZwT8Gb4mT-ZlCNTHRUs-SZo-E,24237
+transformers/models/minimax/__init__.py,sha256=hP-D2E-RR4ySxC0IkUuB8AatsJj3vOX1-VbWQ01WwAM,1013
+transformers/models/minimax/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/minimax/__pycache__/configuration_minimax.cpython-312.pyc,,
+transformers/models/minimax/__pycache__/modeling_minimax.cpython-312.pyc,,
+transformers/models/minimax/__pycache__/modular_minimax.cpython-312.pyc,,
+transformers/models/minimax/configuration_minimax.py,sha256=7A0j2G9WQwDynx5hlvjxzoaw2cydSnDQn_fhmfiOIUw,5577
+transformers/models/minimax/modeling_minimax.py,sha256=dSRbdXIa1cVgoEmvvufMTMikMpBWbbBkzvCAslbzm24,40641
+transformers/models/minimax/modular_minimax.py,sha256=ENzZRHhs379Ichwm4M1BCIpGikkZG65hRWCESDNhVkA,22213
+transformers/models/minimax_m2/__init__.py,sha256=DtCF0nGskHZe44Z1-UfHth74oV7lXM52VPncoKsSzXQ,1002
+transformers/models/minimax_m2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/minimax_m2/__pycache__/configuration_minimax_m2.cpython-312.pyc,,
+transformers/models/minimax_m2/__pycache__/modeling_minimax_m2.cpython-312.pyc,,
+transformers/models/minimax_m2/__pycache__/modular_minimax_m2.cpython-312.pyc,,
+transformers/models/minimax_m2/configuration_minimax_m2.py,sha256=hiMliGwo-vLkix3dVBET859Ur4BsbPNkt7bf1wqlISc,3875
+transformers/models/minimax_m2/modeling_minimax_m2.py,sha256=pthQKjRBfzdR_PwTASYIYoEAQMkBPDOfvKOjlBe51-g,30790
+transformers/models/minimax_m2/modular_minimax_m2.py,sha256=TNWetwxSc5jfVdO_s6hI1o1YgTCIWHC8sKGbD42qtQs,9488
+transformers/models/minimax_m3_vl/__init__.py,sha256=3k1xcg3CaoQ77L-k-1XnlBzr3TzES1f8LpKL4Krz2UU,1172
+transformers/models/minimax_m3_vl/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/minimax_m3_vl/__pycache__/configuration_minimax_m3_vl.cpython-312.pyc,,
+transformers/models/minimax_m3_vl/__pycache__/image_processing_minimax_m3_vl.cpython-312.pyc,,
+transformers/models/minimax_m3_vl/__pycache__/modeling_minimax_m3_vl.cpython-312.pyc,,
+transformers/models/minimax_m3_vl/__pycache__/modular_minimax_m3_vl.cpython-312.pyc,,
+transformers/models/minimax_m3_vl/__pycache__/processing_minimax_m3_vl.cpython-312.pyc,,
+transformers/models/minimax_m3_vl/__pycache__/video_processing_minimax_m3_vl.cpython-312.pyc,,
+transformers/models/minimax_m3_vl/configuration_minimax_m3_vl.py,sha256=Uz0T20ymDatyo0d2r-3Yny6Cm83OvC09ERL7DzJlGSc,10292
+transformers/models/minimax_m3_vl/image_processing_minimax_m3_vl.py,sha256=_g5E5gYlop4aLtylGUGTRINYKxLqncGca7HPQwJsq8g,7916
+transformers/models/minimax_m3_vl/modeling_minimax_m3_vl.py,sha256=iGcKWuxbDo54EKvU4SncdKF_T_ZchLsJAc6FuNCEDVw,73852
+transformers/models/minimax_m3_vl/modular_minimax_m3_vl.py,sha256=EVPq6g1d85X5hrSTWhAXUzaiKhrC9aFfl5RbbfyIRVM,60986
+transformers/models/minimax_m3_vl/processing_minimax_m3_vl.py,sha256=vR1NebGzRC3x3s0p9c1FnJU3xF4CkBHNGhFd2XY3ozI,8020
+transformers/models/minimax_m3_vl/video_processing_minimax_m3_vl.py,sha256=7LVq9Ohx4SgXVj6mt8SJZ0CrIFQt2prdyRFab7sGfbE,5063
+transformers/models/ministral/__init__.py,sha256=618E2UYWKhHRaJQnG5YToNFqqiEPQBnYNlAVyZq889c,1019
+transformers/models/ministral/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/ministral/__pycache__/configuration_ministral.cpython-312.pyc,,
+transformers/models/ministral/__pycache__/modeling_ministral.cpython-312.pyc,,
+transformers/models/ministral/__pycache__/modular_ministral.cpython-312.pyc,,
+transformers/models/ministral/configuration_ministral.py,sha256=o5c9zriYpwdLe2nu6mP9vSgNBemX-8I9rOnGuDLHjR0,4054
+transformers/models/ministral/modeling_ministral.py,sha256=2a0iZRSJkgbZ7WgHcI5MGwMHhYrCXvhtonbKBPDIGvA,22525
+transformers/models/ministral/modular_ministral.py,sha256=03yfjLsRXQkKJKS3Fz7OOpN9omAHev-Jy52fm-9rJ-U,6629
+transformers/models/ministral3/__init__.py,sha256=5_FEbQFnuUpKN4SRGHPrlEwB_zYU28vzWuUcwTm8Q8E,1021
+transformers/models/ministral3/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/ministral3/__pycache__/configuration_ministral3.cpython-312.pyc,,
+transformers/models/ministral3/__pycache__/modeling_ministral3.cpython-312.pyc,,
+transformers/models/ministral3/__pycache__/modular_ministral3.cpython-312.pyc,,
+transformers/models/ministral3/configuration_ministral3.py,sha256=jIKTSsEFDBtUwJUpeVAyxcCa38v5sSiF7taZLejJ1Sg,4422
+transformers/models/ministral3/modeling_ministral3.py,sha256=J5VRhGNe2Ao7rm5hRDKx9-cl8YZOnSqNkJaIsKREHJM,21854
+transformers/models/ministral3/modular_ministral3.py,sha256=qRXWwsaUaB4-z1qV70hB5mnnSBWNU3oNGGLexMDTQPA,3821
+transformers/models/mistral/__init__.py,sha256=uMtejpzqHBbx1-TTTyda0f9lIZlqvdvrV45C-MFTyt4,1015
+transformers/models/mistral/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/mistral/__pycache__/configuration_mistral.cpython-312.pyc,,
+transformers/models/mistral/__pycache__/modeling_mistral.cpython-312.pyc,,
+transformers/models/mistral/__pycache__/modular_mistral.cpython-312.pyc,,
+transformers/models/mistral/configuration_mistral.py,sha256=hYpIF6R_yQB0xWZ-g2dMyb8tMoLI0gfwZd8Cjrv7-b8,3401
+transformers/models/mistral/modeling_mistral.py,sha256=lANe0W4fIGkFYlhA_9rZt7CU8EO5CkFgw8LQsMwz9Vs,21141
+transformers/models/mistral/modular_mistral.py,sha256=rCFO7ZpvtZhmQe3BScs5UVTIUP6gwvRSJnMw8WZRTzM,7044
+transformers/models/mistral3/__init__.py,sha256=ccR4AQqjFkPl8JVYyVmVvbVm618FlOw4cpwT7N-8ZD4,1036
+transformers/models/mistral3/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/mistral3/__pycache__/configuration_mistral3.cpython-312.pyc,,
+transformers/models/mistral3/__pycache__/modeling_mistral3.cpython-312.pyc,,
+transformers/models/mistral3/__pycache__/modular_mistral3.cpython-312.pyc,,
+transformers/models/mistral3/configuration_mistral3.py,sha256=rPoPI0DBjavMTkuZySYsjfGgFaJjnPG3EnB5ye6HY90,3875
+transformers/models/mistral3/modeling_mistral3.py,sha256=G1LhdUiDJjN4wr1f20vNECDmp0NxcIbBRReXVfoPjuk,20082
+transformers/models/mistral3/modular_mistral3.py,sha256=caoCyIAzdcSxc9o1YHflwvgXTVbDlot0-R0IpX5k3z4,12206
+transformers/models/mistral4/__init__.py,sha256=dswib350snQJkWAF8J8CqVukq6NOtUjajOCqYnr9mW0,1017
+transformers/models/mistral4/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/mistral4/__pycache__/configuration_mistral4.cpython-312.pyc,,
+transformers/models/mistral4/__pycache__/modeling_mistral4.cpython-312.pyc,,
+transformers/models/mistral4/__pycache__/modular_mistral4.cpython-312.pyc,,
+transformers/models/mistral4/configuration_mistral4.py,sha256=xgtR2X6OlyzsgIYWX1puzVO5l6HdNfqulzKgDlgWL2w,5016
+transformers/models/mistral4/modeling_mistral4.py,sha256=P56Bd7pAOt6uxK95fIVxNHYi5nbjtz9lhABhS709PEY,32128
+transformers/models/mistral4/modular_mistral4.py,sha256=Uto-7YrQBidzxhl5_vysPcDOxnLXL7cvAqPjKE5T714,10922
+transformers/models/mixtral/__init__.py,sha256=_i66uHDx5A0-UBwgR2nwibxSf0ZePqpTa_Qsm0Cg_Bs,1015
+transformers/models/mixtral/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/mixtral/__pycache__/configuration_mixtral.cpython-312.pyc,,
+transformers/models/mixtral/__pycache__/modeling_mixtral.cpython-312.pyc,,
+transformers/models/mixtral/__pycache__/modular_mixtral.cpython-312.pyc,,
+transformers/models/mixtral/configuration_mixtral.py,sha256=dMxjCGjapw2ns3ieStMvDsGFYCKXLCcJ6uKl-hclxiE,3222
+transformers/models/mixtral/modeling_mixtral.py,sha256=CqIJmPFmLonuDroAuZNpRpxSCWgar7j2OLvT2aF07o0,30589
+transformers/models/mixtral/modular_mixtral.py,sha256=t1ts-iNbPvpyhv7152qG1Mq4beOz8kuNi1AFGQCTZqQ,18271
+transformers/models/mlcd/__init__.py,sha256=hLiLB1E0jT7sI3s8TraLb_Z1WOpwS69zac5kyHNfx4E,989
+transformers/models/mlcd/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/mlcd/__pycache__/configuration_mlcd.cpython-312.pyc,,
+transformers/models/mlcd/__pycache__/modeling_mlcd.cpython-312.pyc,,
+transformers/models/mlcd/__pycache__/modular_mlcd.cpython-312.pyc,,
+transformers/models/mlcd/configuration_mlcd.py,sha256=oGyjUnbi4bb39G7odN97ZvpaMBv7pGZktj9k6NIY3po,2884
+transformers/models/mlcd/modeling_mlcd.py,sha256=g6O0tiXDlqlh3jzHLBdMHLTwc-Qz01ZTAkr0brbRJas,23608
+transformers/models/mlcd/modular_mlcd.py,sha256=8otip8odX9ptVhOUicF9Mdx9UV4hVmGq2Hfeo1xuw_w,17037
+transformers/models/mllama/__init__.py,sha256=rUSwSbNYKQYB1jgPm78R_vmfbFShJEjGoCnPDKOa5oQ,1120
+transformers/models/mllama/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/mllama/__pycache__/configuration_mllama.cpython-312.pyc,,
+transformers/models/mllama/__pycache__/image_processing_mllama.cpython-312.pyc,,
+transformers/models/mllama/__pycache__/image_processing_pil_mllama.cpython-312.pyc,,
+transformers/models/mllama/__pycache__/modeling_mllama.cpython-312.pyc,,
+transformers/models/mllama/__pycache__/processing_mllama.cpython-312.pyc,,
+transformers/models/mllama/configuration_mllama.py,sha256=5q3StQajAyr74LwWEn-JVSzNfirD-H09OPZRfeXJvJ8,7446
+transformers/models/mllama/image_processing_mllama.py,sha256=_dtfoOVTEV5IydvunFq-dIOvq6muCXUnbvOksxrQiXA,21508
+transformers/models/mllama/image_processing_pil_mllama.py,sha256=eAOMFX74XkpCphNr9lWT58YLxxKjy4pJ4CnRoK3zuFE,21770
+transformers/models/mllama/modeling_mllama.py,sha256=vBDXYoK07K3yrq90RzGncxZZbMcxxRFAgtnr4Q6gZ4M,72181
+transformers/models/mllama/processing_mllama.py,sha256=MR8YuRlZuvWeRA7d-8YRXEcKN0W9VjhK7C1k0FnfK3E,14444
+transformers/models/mluke/__init__.py,sha256=e_3cNftWOmhNXk-zsA1-2DOBT9L56SHr-6qev0xI7Ws,956
+transformers/models/mluke/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/mluke/__pycache__/tokenization_mluke.cpython-312.pyc,,
+transformers/models/mluke/tokenization_mluke.py,sha256=FH4j2tLjY6IalXMKHFbK_KW6Eu8kCQw0DI6O9vSczfc,88069
+transformers/models/mm_grounding_dino/__init__.py,sha256=mk2hUY_rZw6JSjfkqSL4hVYJKxh5ViM3TZfib-09kpc,1015
+transformers/models/mm_grounding_dino/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/mm_grounding_dino/__pycache__/configuration_mm_grounding_dino.cpython-312.pyc,,
+transformers/models/mm_grounding_dino/__pycache__/modeling_mm_grounding_dino.cpython-312.pyc,,
+transformers/models/mm_grounding_dino/__pycache__/modular_mm_grounding_dino.cpython-312.pyc,,
+transformers/models/mm_grounding_dino/configuration_mm_grounding_dino.py,sha256=V31SlLCRdUpjPP2-4SxO3yIczRYdgs8KnjTNvm_q9os,7041
+transformers/models/mm_grounding_dino/modeling_mm_grounding_dino.py,sha256=CCQSavP99AZabSmzuv0XAYDTQzzqGUAmV6mnPK9phrM,128372
+transformers/models/mm_grounding_dino/modular_mm_grounding_dino.py,sha256=v5T6N-Cj_qXjahoUNALFpl9KO3g6pfErb0Q4sFr74XM,11863
+transformers/models/mobilebert/__init__.py,sha256=Ahrfu5ZVpOcRpNP81dbzqZO9mJAz-gajqgpAZW5xj1Y,1087
+transformers/models/mobilebert/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/mobilebert/__pycache__/configuration_mobilebert.cpython-312.pyc,,
+transformers/models/mobilebert/__pycache__/modeling_mobilebert.cpython-312.pyc,,
+transformers/models/mobilebert/__pycache__/tokenization_mobilebert.cpython-312.pyc,,
+transformers/models/mobilebert/configuration_mobilebert.py,sha256=Hx9mCtjsP2_v8VmWVS9vLDImFa1kH54yrKv7tobxVcA,3443
+transformers/models/mobilebert/modeling_mobilebert.py,sha256=vOyNnaA_0mAutOfLp3hbUHmgsvgbSNHJex0ODPR-Tr4,50878
+transformers/models/mobilebert/tokenization_mobilebert.py,sha256=7vAsL3wIML89C7QOqQpHA0YYCBFBvcNY4wBLnGPRJQc,1002
+transformers/models/mobilenet_v1/__init__.py,sha256=Izm4lDIG_mY9a8u-NFwDRJJDk8BJnYSDvjpWVn4mXGc,1107
+transformers/models/mobilenet_v1/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/mobilenet_v1/__pycache__/configuration_mobilenet_v1.cpython-312.pyc,,
+transformers/models/mobilenet_v1/__pycache__/image_processing_mobilenet_v1.cpython-312.pyc,,
+transformers/models/mobilenet_v1/__pycache__/image_processing_pil_mobilenet_v1.cpython-312.pyc,,
+transformers/models/mobilenet_v1/__pycache__/modeling_mobilenet_v1.cpython-312.pyc,,
+transformers/models/mobilenet_v1/configuration_mobilenet_v1.py,sha256=lo1VUgefhZUpCN6kWOZ5XubOU5wtSEoaKBF1HXgnIzw,2219
+transformers/models/mobilenet_v1/image_processing_mobilenet_v1.py,sha256=_TxiEKHQSI9b1b02CyvhCTJlcaWVWHTti37Dndr9Gu8,1384
+transformers/models/mobilenet_v1/image_processing_pil_mobilenet_v1.py,sha256=CDXzGicUkOfsYVZXOu1M8q-ScKiOzyn-BUQgiAO-REo,1374
+transformers/models/mobilenet_v1/modeling_mobilenet_v1.py,sha256=kxFeYIy7dQXLBbWpXsoA2teOABDzNvjMuc9HnYk-EBE,10305
+transformers/models/mobilenet_v2/__init__.py,sha256=Q1qsOUZdtJPbeTDm6FAvlRzMUHVFsU8dM_spZbw7jUE,1107
+transformers/models/mobilenet_v2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/mobilenet_v2/__pycache__/configuration_mobilenet_v2.cpython-312.pyc,,
+transformers/models/mobilenet_v2/__pycache__/image_processing_mobilenet_v2.cpython-312.pyc,,
+transformers/models/mobilenet_v2/__pycache__/image_processing_pil_mobilenet_v2.cpython-312.pyc,,
+transformers/models/mobilenet_v2/__pycache__/modeling_mobilenet_v2.cpython-312.pyc,,
+transformers/models/mobilenet_v2/configuration_mobilenet_v2.py,sha256=zy6lR7_crL2-FIJx5_-VkHh2HIFc3EbxNIfhW5Jck8Y,3591
+transformers/models/mobilenet_v2/image_processing_mobilenet_v2.py,sha256=8GVKVJ6snfZ-TtnDmiY8d5coxAnlf_AdsOF0wt2oRro,8506
+transformers/models/mobilenet_v2/image_processing_pil_mobilenet_v2.py,sha256=2o1_UnijAPP9koyzexc0iG_maK7NQNVBGHeUVFDnXXg,7486
+transformers/models/mobilenet_v2/modeling_mobilenet_v2.py,sha256=W_4kcFCt9DpIUc_5ScrmEurAmWZDl3WcNljA7HrJniY,21175
+transformers/models/mobilevit/__init__.py,sha256=lVyEWiXhdMm0dS2APoMQLIJ60_9Tyh2KsgcDJ1aqJBY,1095
+transformers/models/mobilevit/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/mobilevit/__pycache__/configuration_mobilevit.cpython-312.pyc,,
+transformers/models/mobilevit/__pycache__/image_processing_mobilevit.cpython-312.pyc,,
+transformers/models/mobilevit/__pycache__/image_processing_pil_mobilevit.cpython-312.pyc,,
+transformers/models/mobilevit/__pycache__/modeling_mobilevit.cpython-312.pyc,,
+transformers/models/mobilevit/configuration_mobilevit.py,sha256=lPE-ERJUP6IS_d-mnKUt1YceYz2FR2EtGatNxuwMj9Y,2852
+transformers/models/mobilevit/image_processing_mobilevit.py,sha256=51CfNG6EAZ38R4KXLav0r9QNAUkvm8vdO-xEstJS838,9151
+transformers/models/mobilevit/image_processing_pil_mobilevit.py,sha256=nxXg0zn5W7bwAmal57cN_BI698HZTKprInkLXHlH4Mw,7919
+transformers/models/mobilevit/modeling_mobilevit.py,sha256=EjORL71CMMDOTlCPk8XpWuNQyd3DeyzKZmpq2oIuzqw,34881
+transformers/models/mobilevitv2/__init__.py,sha256=pAGk_9X22yOYvlcwbqTc4nm6fL4rPhAhDpdBguna5Q0,1003
+transformers/models/mobilevitv2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/mobilevitv2/__pycache__/configuration_mobilevitv2.cpython-312.pyc,,
+transformers/models/mobilevitv2/__pycache__/modeling_mobilevitv2.cpython-312.pyc,,
+transformers/models/mobilevitv2/configuration_mobilevitv2.py,sha256=fdwWqtPHuMED86MZ_vd9JWOMHl72djplvFnIyDF2kyo,3247
+transformers/models/mobilevitv2/modeling_mobilevitv2.py,sha256=EN78jDJKOIi37ZA4Qf1Y_em_eUB3nA8xNOokrh8esqI,33927
+transformers/models/modernbert/__init__.py,sha256=BEQFRFfcKvUlphA1ibW3s34Vkbm-MUuyqzaLbrIFiAA,1006
+transformers/models/modernbert/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/modernbert/__pycache__/configuration_modernbert.cpython-312.pyc,,
+transformers/models/modernbert/__pycache__/modeling_modernbert.cpython-312.pyc,,
+transformers/models/modernbert/__pycache__/modular_modernbert.cpython-312.pyc,,
+transformers/models/modernbert/configuration_modernbert.py,sha256=a93BRxveSXrPkOeGWF32vypKQ8kTxXKhui5rMxWytkg,7878
+transformers/models/modernbert/modeling_modernbert.py,sha256=3uVob6OlmoNycC_DVsj0YYzj4dyMrktngsdpZggGMw8,36723
+transformers/models/modernbert/modular_modernbert.py,sha256=m2kEc4CtEDo5xxwwb8PS5CydXtz7wJQQ_9dl52EfbMU,37922
+transformers/models/modernbert_decoder/__init__.py,sha256=RjLebVKPcGgNEORY5xypTPd8oYWcnFmbGm3hBqQX-HE,1022
+transformers/models/modernbert_decoder/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/modernbert_decoder/__pycache__/configuration_modernbert_decoder.cpython-312.pyc,,
+transformers/models/modernbert_decoder/__pycache__/modeling_modernbert_decoder.cpython-312.pyc,,
+transformers/models/modernbert_decoder/__pycache__/modular_modernbert_decoder.cpython-312.pyc,,
+transformers/models/modernbert_decoder/configuration_modernbert_decoder.py,sha256=Px3GURxsamquks4n5O8PqCe4B16xuiuYiYG_aGrCsVA,7016
+transformers/models/modernbert_decoder/modeling_modernbert_decoder.py,sha256=ZQP8JkhbLFhmayVCFXdJHgjLKyBv8f6K7uUyuMgAwDM,33503
+transformers/models/modernbert_decoder/modular_modernbert_decoder.py,sha256=QQ7XuX1Grr8oPqGJ7X8dQf11yqpZvccVvahDN9YM-Fw,30011
+transformers/models/modernvbert/__init__.py,sha256=UoCdsSmgNKgJN49IMECdDqYXtUMpThFGSQE5UTvzCW4,1191
+transformers/models/modernvbert/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/modernvbert/__pycache__/configuration_modernvbert.cpython-312.pyc,,
+transformers/models/modernvbert/__pycache__/modeling_modernvbert.cpython-312.pyc,,
+transformers/models/modernvbert/__pycache__/modular_modernvbert.cpython-312.pyc,,
+transformers/models/modernvbert/configuration_modernvbert.py,sha256=DIRV8MNTrH0xE5KotsMer5x-2J_0k6HAEonGZGukcDY,4034
+transformers/models/modernvbert/modeling_modernvbert.py,sha256=lIDuOte0thtYSRGguPPdmSomBKk6TltnIJ_GXx0Upao,33529
+transformers/models/modernvbert/modular_modernvbert.py,sha256=nMoTSHhH42g8ukeFbMQKINeqe0fLVmqJqcH8U_929LI,28625
+transformers/models/moonshine/__init__.py,sha256=eBgvc9LtoDnB6HnNvrObDWL3h_L4Sgn5-D-hepNfAmI,999
+transformers/models/moonshine/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/moonshine/__pycache__/configuration_moonshine.cpython-312.pyc,,
+transformers/models/moonshine/__pycache__/modeling_moonshine.cpython-312.pyc,,
+transformers/models/moonshine/__pycache__/modular_moonshine.cpython-312.pyc,,
+transformers/models/moonshine/configuration_moonshine.py,sha256=b16fL8nc5_XQhUwbIw-EAO8qw3txoJ6m1X2WnY1WJ88,5921
+transformers/models/moonshine/modeling_moonshine.py,sha256=3ToZPlQQhhA_DT3-3QEJWi1uE0ciFbDx_oMuvrDz65A,41954
+transformers/models/moonshine/modular_moonshine.py,sha256=b16N-o5K7XPNwWHUCk4wkJLnWvAUSxaQdk4nTsdAV-g,34881
+transformers/models/moonshine_streaming/__init__.py,sha256=9S0QRymrUyt5h-mdWY9w45E_kuoxd_mlBZuX8pLv65s,1020
+transformers/models/moonshine_streaming/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/moonshine_streaming/__pycache__/configuration_moonshine_streaming.cpython-312.pyc,,
+transformers/models/moonshine_streaming/__pycache__/modeling_moonshine_streaming.cpython-312.pyc,,
+transformers/models/moonshine_streaming/__pycache__/modular_moonshine_streaming.cpython-312.pyc,,
+transformers/models/moonshine_streaming/__pycache__/processing_moonshine_streaming.cpython-312.pyc,,
+transformers/models/moonshine_streaming/configuration_moonshine_streaming.py,sha256=w4XgJkH-CvZOktXJibvWB6Q5ouMLcVM7Lf_Ynj450u4,5289
+transformers/models/moonshine_streaming/modeling_moonshine_streaming.py,sha256=Iw3UC4gHSwRk-hvJrAhXCD4xDimpnmsS7dihXGfU-IU,49471
+transformers/models/moonshine_streaming/modular_moonshine_streaming.py,sha256=xePYgi06SG132hwB3ptCRekCoyGzyxBdp2gyjgMzIwI,17001
+transformers/models/moonshine_streaming/processing_moonshine_streaming.py,sha256=GcoGNJunzBg8SRe4B80IliE1SzCzKwLZDfL-v1VYt1Y,5173
+transformers/models/moshi/__init__.py,sha256=uW4oqTKZdbmURZaC_xwwHXnYEMyLJrMEJAlfbUzSWO8,991
+transformers/models/moshi/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/moshi/__pycache__/configuration_moshi.cpython-312.pyc,,
+transformers/models/moshi/__pycache__/modeling_moshi.cpython-312.pyc,,
+transformers/models/moshi/configuration_moshi.py,sha256=G0BQ96jGs3HDbSv2E0UujQCguxMc7fnyXUI7SIDNE68,8497
+transformers/models/moshi/modeling_moshi.py,sha256=_iqHlOUzFyZyTtbKSZvh3EOvZiP09OMZvmgi2Yz2R9k,100699
+transformers/models/mpnet/__init__.py,sha256=Lmtzs8K18d_lydT3fpJIAjwD0nBAZnNa6NdiNdqvEJg,1029
+transformers/models/mpnet/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/mpnet/__pycache__/configuration_mpnet.cpython-312.pyc,,
+transformers/models/mpnet/__pycache__/modeling_mpnet.cpython-312.pyc,,
+transformers/models/mpnet/__pycache__/tokenization_mpnet.cpython-312.pyc,,
+transformers/models/mpnet/configuration_mpnet.py,sha256=uOHprnfCIH6iyEPJFQPRz2rYVXcdZe_wTqy2RPxhRe8,2119
+transformers/models/mpnet/modeling_mpnet.py,sha256=EmUF5pPK-Hig05876d4x9uFjIHBvEf1fTn4lKE6IxTs,34510
+transformers/models/mpnet/tokenization_mpnet.py,sha256=5es3kknt0_UvkK2nxAX6v5cEpZ_orG_vHESkQHHdTnM,8732
+transformers/models/mpt/__init__.py,sha256=DAIIAY0kPL-bXMkPUvxmP97HCXPi-SoM3NLnlJJYarg,987
+transformers/models/mpt/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/mpt/__pycache__/configuration_mpt.cpython-312.pyc,,
+transformers/models/mpt/__pycache__/modeling_mpt.cpython-312.pyc,,
+transformers/models/mpt/configuration_mpt.py,sha256=Vod4M_wkunJxOwntdeyFCAJL6zGjlvxi9p9X9BHLc3A,6187
+transformers/models/mpt/modeling_mpt.py,sha256=EIBL0sVSt7HCrMPa714Rlxo0I9n6nZIXJlhOrnpEXT4,31947
+transformers/models/mra/__init__.py,sha256=51mnm4DFq6aWxOsmaaVZDL28QozNauXyTtbEihDxUQU,987
+transformers/models/mra/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/mra/__pycache__/configuration_mra.cpython-312.pyc,,
+transformers/models/mra/__pycache__/modeling_mra.cpython-312.pyc,,
+transformers/models/mra/configuration_mra.py,sha256=YGKMTvVougJwiJOdaVkBZ6Z8-pZ3KrsMogoFu5n8U_o,2758
+transformers/models/mra/modeling_mra.py,sha256=asZkbWfan4YKVzMFf0do97ZgHu34M598yyDeXaxMSTY,53740
+transformers/models/mt5/__init__.py,sha256=BTuFEuI7Ojp3tXOaLCepiUPbxYxotr4_ToZ1eXvITyA,1023
+transformers/models/mt5/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/mt5/__pycache__/configuration_mt5.cpython-312.pyc,,
+transformers/models/mt5/__pycache__/modeling_mt5.cpython-312.pyc,,
+transformers/models/mt5/configuration_mt5.py,sha256=gFKEmvVr54L-dc_T85pqiKzqR3xRlW-7zjYXy6xxiRo,3606
+transformers/models/mt5/modeling_mt5.py,sha256=MRnvfitqc8aEtwjTAmTkeanRkmsCsNJLydTAPTU1dQI,75811
+transformers/models/musicflamingo/__init__.py,sha256=1uvPQsN8ISJ1Zd4DOwcghGIrR_Jj8Q_35X_EwXul5ac,1082
+transformers/models/musicflamingo/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/musicflamingo/__pycache__/configuration_musicflamingo.cpython-312.pyc,,
+transformers/models/musicflamingo/__pycache__/modeling_musicflamingo.cpython-312.pyc,,
+transformers/models/musicflamingo/__pycache__/modular_musicflamingo.cpython-312.pyc,,
+transformers/models/musicflamingo/__pycache__/processing_musicflamingo.cpython-312.pyc,,
+transformers/models/musicflamingo/configuration_musicflamingo.py,sha256=FFAC86L0Z2KTnOHhu3b4-BDNSBQUNV4b24g4KaKWtiM,4630
+transformers/models/musicflamingo/modeling_musicflamingo.py,sha256=DfB799R4jXTn6u5_Q3JLYRGG4NjZifvTlByU-eNt_yo,22475
+transformers/models/musicflamingo/modular_musicflamingo.py,sha256=dr7qVqrMpQqUKx9Ln_LAKcSgsrbsyfv4fe3vKSe6syY,17192
+transformers/models/musicflamingo/processing_musicflamingo.py,sha256=UB1scKS-BHHKqh3eo1JPa3UzoMLYUn3uDS5rNaSNIkk,8510
+transformers/models/musicgen/__init__.py,sha256=iwtW9pg6iDe5D2dWVC4IRU8QbNmRK5kMqPCM8fsUSgo,1036
+transformers/models/musicgen/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/musicgen/__pycache__/configuration_musicgen.cpython-312.pyc,,
+transformers/models/musicgen/__pycache__/modeling_musicgen.cpython-312.pyc,,
+transformers/models/musicgen/__pycache__/processing_musicgen.cpython-312.pyc,,
+transformers/models/musicgen/configuration_musicgen.py,sha256=2MgbZaLyWyubR0WPlgD9vNTN2z8NVkgingRZRD1PIWo,6027
+transformers/models/musicgen/modeling_musicgen.py,sha256=0tow3QMPLclwwlN1Afkgfgpm9nEHnNNi0_P7gnghWQw,104257
+transformers/models/musicgen/processing_musicgen.py,sha256=Tj7AG78Ai04tF0izuDwMS8iY1lMnz_lSsa1BlhwVuJk,3360
+transformers/models/musicgen_melody/__init__.py,sha256=WVEsVs7g0XlpO_yd1X0X4QnMjhG0h_n6T41FpdJcnS8,1011
+transformers/models/musicgen_melody/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/musicgen_melody/__pycache__/configuration_musicgen_melody.cpython-312.pyc,,
+transformers/models/musicgen_melody/__pycache__/feature_extraction_musicgen_melody.cpython-312.pyc,,
+transformers/models/musicgen_melody/__pycache__/modeling_musicgen_melody.cpython-312.pyc,,
+transformers/models/musicgen_melody/__pycache__/processing_musicgen_melody.cpython-312.pyc,,
+transformers/models/musicgen_melody/configuration_musicgen_melody.py,sha256=72vfThQRZW4T9J1C2arBz_E_K_JeMr26E6mzCFFjsp8,6623
+transformers/models/musicgen_melody/feature_extraction_musicgen_melody.py,sha256=u7RdsQUkosd0vDq5y4AQjxDj_NphdFOj3eR8juaSlG4,15232
+transformers/models/musicgen_melody/modeling_musicgen_melody.py,sha256=EqQDgijGsiDg76VkDNRQ-G5aCS6HG6VcpDHnqmGjD1k,102243
+transformers/models/musicgen_melody/processing_musicgen_melody.py,sha256=jC5ueLR2V-SU3ZKPnW6RP9HVQOV4t6uHlIf0Ky4dR34,5024
+transformers/models/mvp/__init__.py,sha256=WZmfe74gf6cjN8OLNQ6ngkwTFzie-OV6VRPiAbBCTk8,1067
+transformers/models/mvp/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/mvp/__pycache__/configuration_mvp.cpython-312.pyc,,
+transformers/models/mvp/__pycache__/modeling_mvp.cpython-312.pyc,,
+transformers/models/mvp/configuration_mvp.py,sha256=_WEO40RAELEEVZX7PNpHTzOS_uoqANVg9MvkPTmNXOo,2880
+transformers/models/mvp/modeling_mvp.py,sha256=EneJQ3dM2_bCjI8j06nSetFpU-4O6VzxKqRB4vr0unA,73048
+transformers/models/myt5/__init__.py,sha256=MFQX-RuvZujGb_twBWBQpTt4NZq6FxreEysWmF2fFGI,955
+transformers/models/myt5/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/myt5/__pycache__/tokenization_myt5.cpython-312.pyc,,
+transformers/models/myt5/tokenization_myt5.py,sha256=9x5iRVCKPjao8zsLbD5_8ACxZ9WLZtg59E1c7KmTk3s,15450
+transformers/models/nanochat/__init__.py,sha256=goJP7g0uNynZWyVMqvOWSR9yAOeWGSXbaUU8sq3aZhI,391
+transformers/models/nanochat/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/nanochat/__pycache__/configuration_nanochat.cpython-312.pyc,,
+transformers/models/nanochat/__pycache__/modeling_nanochat.cpython-312.pyc,,
+transformers/models/nanochat/__pycache__/modular_nanochat.cpython-312.pyc,,
+transformers/models/nanochat/configuration_nanochat.py,sha256=OD59ZHRVdqeg6BrNE63zKndeu5nhYmY9UyAUFuzn8W4,2604
+transformers/models/nanochat/modeling_nanochat.py,sha256=zF0MJh-tCsZxYeK3RA-SNyXKqkdNZ0I-3ERZRYjrc-Y,21668
+transformers/models/nanochat/modular_nanochat.py,sha256=lAGgPSRDF97UYpmUulA-7zDnVlBC9ayJHe2FLm9Djfw,8475
+transformers/models/nemotron/__init__.py,sha256=ZwaMH1AQ0VIuFnouYe0Sx0HcCGA7PaCp3-_yw3xjeQA,997
+transformers/models/nemotron/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/nemotron/__pycache__/configuration_nemotron.cpython-312.pyc,,
+transformers/models/nemotron/__pycache__/modeling_nemotron.cpython-312.pyc,,
+transformers/models/nemotron/configuration_nemotron.py,sha256=adKI_46Elz7sTWA7tOtL2wP3pxZ_ZCM9jV4wUd5VeEU,2511
+transformers/models/nemotron/modeling_nemotron.py,sha256=8wL-ucajt0PWrEqKOlv_9AzlBfRoCCQR_PC4uoMYNSw,31507
+transformers/models/nemotron_h/__init__.py,sha256=7AJceTeyBHQBpH9DWo9mqe2hUYiHsfQmp0TJiap83T4,1001
+transformers/models/nemotron_h/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/nemotron_h/__pycache__/configuration_nemotron_h.cpython-312.pyc,,
+transformers/models/nemotron_h/__pycache__/modeling_nemotron_h.cpython-312.pyc,,
+transformers/models/nemotron_h/__pycache__/modular_nemotron_h.cpython-312.pyc,,
+transformers/models/nemotron_h/configuration_nemotron_h.py,sha256=peI5zaNAFI_2cjQsjWNwfRtz6sqTmYoIkytyIPLsn0Q,12607
+transformers/models/nemotron_h/modeling_nemotron_h.py,sha256=F10Wr9cJ1S4C912Q5MOetpzSb_3L75lEXNBbE0tYSho,57548
+transformers/models/nemotron_h/modular_nemotron_h.py,sha256=HLJ33dRNBhbSb4ouYSlsmg5zZNHVg4Xz15pH3oRje-w,21980
+transformers/models/nllb/__init__.py,sha256=fBkcHp1TFP4bRdUvTzwZf2syVKJZul8cTf5csjI2EbY,955
+transformers/models/nllb/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/nllb/__pycache__/tokenization_nllb.cpython-312.pyc,,
+transformers/models/nllb/tokenization_nllb.py,sha256=KP3SB1ew5El3j09KmHMrzSf8YPSF9DUf7rt7uvcVC-4,14688
+transformers/models/nllb_moe/__init__.py,sha256=sAfoAnhHK_reU1a2WUoF1rFtPBckeGGrzJCD8gUv54A,997
+transformers/models/nllb_moe/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/nllb_moe/__pycache__/configuration_nllb_moe.cpython-312.pyc,,
+transformers/models/nllb_moe/__pycache__/modeling_nllb_moe.cpython-312.pyc,,
+transformers/models/nllb_moe/configuration_nllb_moe.py,sha256=g_19-j-YNmkUJFDRmnKpAOZaSOr_wcKx7NmE83aqueM,5245
+transformers/models/nllb_moe/modeling_nllb_moe.py,sha256=zZytY_MDgF0XO5DuwKaKSbF5YYvujymd5SyeJY4ndCc,49256
+transformers/models/nomic_bert/__init__.py,sha256=opqxsLBIP7yLCsOfc6saEcQyBcznV6ie80AIAeS07hw,1002
+transformers/models/nomic_bert/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/nomic_bert/__pycache__/configuration_nomic_bert.cpython-312.pyc,,
+transformers/models/nomic_bert/__pycache__/modeling_nomic_bert.cpython-312.pyc,,
+transformers/models/nomic_bert/__pycache__/modular_nomic_bert.cpython-312.pyc,,
+transformers/models/nomic_bert/configuration_nomic_bert.py,sha256=DGT3XH2H6Xc9D9qfqoIoEzzRdOep0sUXBwK3CCDlc44,3167
+transformers/models/nomic_bert/modeling_nomic_bert.py,sha256=Dhs5ZVlJ5Ij93eyyyoAmD-FXGXmeuxxkFqPZqxTkbc0,29591
+transformers/models/nomic_bert/modular_nomic_bert.py,sha256=NmyW33ufzbUKhb-hSO52IM2aH5uTPvER4Rwd0refo_A,10314
+transformers/models/nougat/__init__.py,sha256=s1Twz1LhISxVkmzmNuYVmETstcDY2eGzonfsWgS8k54,1084
+transformers/models/nougat/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/nougat/__pycache__/configuration_nougat.cpython-312.pyc,,
+transformers/models/nougat/__pycache__/image_processing_nougat.cpython-312.pyc,,
+transformers/models/nougat/__pycache__/image_processing_pil_nougat.cpython-312.pyc,,
+transformers/models/nougat/__pycache__/processing_nougat.cpython-312.pyc,,
+transformers/models/nougat/__pycache__/tokenization_nougat.cpython-312.pyc,,
+transformers/models/nougat/configuration_nougat.py,sha256=m1YxlZkZrACacj48NDIo62_nwhNLkZIT1_UTOXXSxSQ,3288
+transformers/models/nougat/image_processing_nougat.py,sha256=X_lKFPkURdpzPec27FnGhuVhLwRzWYNO1ut-O1-lhJQ,10813
+transformers/models/nougat/image_processing_pil_nougat.py,sha256=FwT0WoG5vcPfMCydLEUD8adGEHPfMlZlXOPOyfpX68w,10369
+transformers/models/nougat/processing_nougat.py,sha256=TtuqEqsaYGsPHbGvkVABcux50-fxA8bFpkV5ckA_k9Q,6221
+transformers/models/nougat/tokenization_nougat.py,sha256=pCewH677NvZQAokX0nR7ya3qM7h_5LaYST4OBNunwk4,26091
+transformers/models/nystromformer/__init__.py,sha256=CwEg6m4nJW_AfNDws_MIv1O1x5IO3xPp-FYqirlFXwk,1007
+transformers/models/nystromformer/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/nystromformer/__pycache__/configuration_nystromformer.cpython-312.pyc,,
+transformers/models/nystromformer/__pycache__/modeling_nystromformer.cpython-312.pyc,,
+transformers/models/nystromformer/configuration_nystromformer.py,sha256=tGP1qMTIdTJkwlgicd6Ps0rvPQn1Xz6QCWCvrsGNIlM,2879
+transformers/models/nystromformer/modeling_nystromformer.py,sha256=WWsOFidycgTQeBM7oujlEWR62n8MWwkXtI0oAnngRP8,39552
+transformers/models/olmo/__init__.py,sha256=x9u_5vqI52-uBuj89-6aYucGDlvBUEPSOhPLLB1asok,1009
+transformers/models/olmo/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/olmo/__pycache__/configuration_olmo.cpython-312.pyc,,
+transformers/models/olmo/__pycache__/modeling_olmo.cpython-312.pyc,,
+transformers/models/olmo/__pycache__/modular_olmo.cpython-312.pyc,,
+transformers/models/olmo/configuration_olmo.py,sha256=ck3Az6aPyAN-QINkJ85PzuHKOP_Tj4KKCzrvVRFd8WI,3325
+transformers/models/olmo/modeling_olmo.py,sha256=CBlTVbc_Gf1tE2VV4OAjJQVJ1lmVtCbVOORl29LEpDU,21359
+transformers/models/olmo/modular_olmo.py,sha256=kIJz7jQmmLy-gB0_tQs81oomERgI34p1-rHM1zC8Q1s,7899
+transformers/models/olmo2/__init__.py,sha256=Frt9nEMsfPszod1lkFTAJUobU50IjOFlqI6uJkuQVcY,1011
+transformers/models/olmo2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/olmo2/__pycache__/configuration_olmo2.cpython-312.pyc,,
+transformers/models/olmo2/__pycache__/modeling_olmo2.cpython-312.pyc,,
+transformers/models/olmo2/__pycache__/modular_olmo2.cpython-312.pyc,,
+transformers/models/olmo2/configuration_olmo2.py,sha256=DCnK0DQeDcl_TNBYNbrmC3VYMl2TWvjvOmV4QB3-TCw,4225
+transformers/models/olmo2/modeling_olmo2.py,sha256=_gbDm_S-8jjuC8lGHg7OaLV5vrFT4RmB_8Pi1rjDMJc,21795
+transformers/models/olmo2/modular_olmo2.py,sha256=QFMNk9-aUn4Hz6tFElLTAbQz1MKV6e_Xs95j_FJs6fI,8794
+transformers/models/olmo3/__init__.py,sha256=NpEGa6NN749b7p7EtG9F8yf6oGweZ6wQZZ8-6YEzjL4,992
+transformers/models/olmo3/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/olmo3/__pycache__/configuration_olmo3.cpython-312.pyc,,
+transformers/models/olmo3/__pycache__/modeling_olmo3.cpython-312.pyc,,
+transformers/models/olmo3/__pycache__/modular_olmo3.cpython-312.pyc,,
+transformers/models/olmo3/configuration_olmo3.py,sha256=ZdH6NnOl0bQ4QTS-5CN06ZshZfzOJZNMM7vVqeraqAQ,4327
+transformers/models/olmo3/modeling_olmo3.py,sha256=4r8ppqFLvF9qwICxaSvdGeEWH0RA62gPvY2a0L9Nz4I,22173
+transformers/models/olmo3/modular_olmo3.py,sha256=mzdAu7-ZBURUj4SfZf2qirnqgYrAgqbtZU7haYlggzU,9197
+transformers/models/olmo_hybrid/__init__.py,sha256=wvEIP-_OKmosjwUvlG8svHclHwvGstxHHCHLkkJYZ1k,1004
+transformers/models/olmo_hybrid/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/olmo_hybrid/__pycache__/configuration_olmo_hybrid.cpython-312.pyc,,
+transformers/models/olmo_hybrid/__pycache__/modeling_olmo_hybrid.cpython-312.pyc,,
+transformers/models/olmo_hybrid/__pycache__/modular_olmo_hybrid.cpython-312.pyc,,
+transformers/models/olmo_hybrid/configuration_olmo_hybrid.py,sha256=44Fajw-ExNTYLiT6EFe3Ul7W64-AbfuaLk87gRs1jh4,7749
+transformers/models/olmo_hybrid/modeling_olmo_hybrid.py,sha256=LgFRXrdaXLjAIOGEF9geo_4vfevAlAUoILwlpJY_i54,48432
+transformers/models/olmo_hybrid/modular_olmo_hybrid.py,sha256=JEak9EKnMZKJoWnTBX4vaazy-4c1ir7wu6m5vmOIC3Q,33742
+transformers/models/olmoe/__init__.py,sha256=eQ6mx9aBIcA4RiK3p7dbqORokkuMfQNRss06E8uWNrk,991
+transformers/models/olmoe/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/olmoe/__pycache__/configuration_olmoe.cpython-312.pyc,,
+transformers/models/olmoe/__pycache__/modeling_olmoe.cpython-312.pyc,,
+transformers/models/olmoe/__pycache__/modular_olmoe.cpython-312.pyc,,
+transformers/models/olmoe/configuration_olmoe.py,sha256=Z1oE7YiHpfkHvip-YgliKc3H0Fx5Q4ib-WLQR4oUfQw,3308
+transformers/models/olmoe/modeling_olmoe.py,sha256=SYq1cgRjMnq3I186MQOu-knS-T2hDDz7fvcAJ3SwVTE,30974
+transformers/models/olmoe/modular_olmoe.py,sha256=j3SHNQ9XC1qBJX9xvUwT8xri9_PqEXb-OzoT5PPNGOI,10979
+transformers/models/omdet_turbo/__init__.py,sha256=XIckpuo9tkT7NB5uTs9wLdpxr9GDedQPVJL2P8XU-7Q,1045
+transformers/models/omdet_turbo/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/omdet_turbo/__pycache__/configuration_omdet_turbo.cpython-312.pyc,,
+transformers/models/omdet_turbo/__pycache__/modeling_omdet_turbo.cpython-312.pyc,,
+transformers/models/omdet_turbo/__pycache__/processing_omdet_turbo.cpython-312.pyc,,
+transformers/models/omdet_turbo/configuration_omdet_turbo.py,sha256=ODS3fNofiDCZZb3aMDqs1v9abXiIETthlW9NTlUcd-A,8718
+transformers/models/omdet_turbo/modeling_omdet_turbo.py,sha256=7N-7b0M4BoRn2kdWbsSwTXTjKUhYaFFfP4cFKyL3-vY,74343
+transformers/models/omdet_turbo/processing_omdet_turbo.py,sha256=0ZP_V3gWR0KQqykY1_2LQv3jk4jx5n0MFvrRLNSf468,14342
+transformers/models/oneformer/__init__.py,sha256=AHOxFhmFLZlruAactb9Y9PNeORkYNLCLU_z3oovmCiM,1135
+transformers/models/oneformer/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/oneformer/__pycache__/configuration_oneformer.cpython-312.pyc,,
+transformers/models/oneformer/__pycache__/image_processing_oneformer.cpython-312.pyc,,
+transformers/models/oneformer/__pycache__/image_processing_pil_oneformer.cpython-312.pyc,,
+transformers/models/oneformer/__pycache__/modeling_oneformer.cpython-312.pyc,,
+transformers/models/oneformer/__pycache__/processing_oneformer.cpython-312.pyc,,
+transformers/models/oneformer/configuration_oneformer.py,sha256=nrAiwncX3Iukl1dcOp8Kd9wvpto3y_emeend4dcr4ic,6780
+transformers/models/oneformer/image_processing_oneformer.py,sha256=doE99Rvpf3sSlY0H_TI6JuQXUKbtBYshwr-7DIpYRnA,40623
+transformers/models/oneformer/image_processing_pil_oneformer.py,sha256=LR6Q20zj4asQOnOmmKN8z9O-Ox2q2Xnj5uFcpX2yL2o,44117
+transformers/models/oneformer/modeling_oneformer.py,sha256=aMrwO19hE7_nSENfjofEga0SL2Xq-7PqqE2l7yNtFjI,139038
+transformers/models/oneformer/processing_oneformer.py,sha256=xU3fmwOzcxir0Q2RPP23mRL_jKG6TBKjAd4hbnIKFgs,8231
+transformers/models/openai/__init__.py,sha256=6Xrt4E8F9t4MlKOmv-zaguA_Vx93QCHsYLCVVtAONvQ,1032
+transformers/models/openai/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/openai/__pycache__/configuration_openai.cpython-312.pyc,,
+transformers/models/openai/__pycache__/modeling_openai.cpython-312.pyc,,
+transformers/models/openai/__pycache__/tokenization_openai.cpython-312.pyc,,
+transformers/models/openai/configuration_openai.py,sha256=dGkrLyvg5uK-oi0cyy_G16kDo_spzjRYY5MWziCKrrw,4453
+transformers/models/openai/modeling_openai.py,sha256=S1LCRS-He78cJu4z5zs-6Ay2zJVXV7yRp6NdVMDgfm0,31945
+transformers/models/openai/tokenization_openai.py,sha256=-DIP7TMkKZ057AEdSRt6G-oi7JUQvlZhvAZT245QdiM,3593
+transformers/models/openai_privacy_filter/__init__.py,sha256=gIMX4w0WTFeYpNSqywcFffCYN2aSE_2oulrWhL-I_o8,1023
+transformers/models/openai_privacy_filter/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/openai_privacy_filter/__pycache__/configuration_openai_privacy_filter.cpython-312.pyc,,
+transformers/models/openai_privacy_filter/__pycache__/modeling_openai_privacy_filter.cpython-312.pyc,,
+transformers/models/openai_privacy_filter/__pycache__/modular_openai_privacy_filter.cpython-312.pyc,,
+transformers/models/openai_privacy_filter/configuration_openai_privacy_filter.py,sha256=_e3cOV6HWAhnE2UzCOELkiR3kJ82YxL8jycDAiNK9xU,4871
+transformers/models/openai_privacy_filter/modeling_openai_privacy_filter.py,sha256=swOPWQ3ydApeQBpIfxNR4erm-jVRtjtbi3FvdDlrPBo,22846
+transformers/models/openai_privacy_filter/modular_openai_privacy_filter.py,sha256=LW_u-vl7T3KVu7w4TCXJ67WGagvQXYxRrAgyASpxdvY,15766
+transformers/models/opt/__init__.py,sha256=CiUBzuuyvAs-mBmRsBpCbMjI8ATPNgUMzzqEl5VhkIk,987
+transformers/models/opt/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/opt/__pycache__/configuration_opt.cpython-312.pyc,,
+transformers/models/opt/__pycache__/modeling_opt.cpython-312.pyc,,
+transformers/models/opt/configuration_opt.py,sha256=jfOtTPG3gAcclo4X2o0jN5_NjxXE3LmyLMv-n6WSPBI,3006
+transformers/models/opt/modeling_opt.py,sha256=hbLijwZTZu-rWhL2vS2Zq7uW_0cQ-Kcd9VJPwI5F10k,30064
+transformers/models/ovis2/__init__.py,sha256=-F9qiFKbsQsU53q9Ed5c5gfTgu3O5eex-hxBQXqY5g4,1121
+transformers/models/ovis2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/ovis2/__pycache__/configuration_ovis2.cpython-312.pyc,,
+transformers/models/ovis2/__pycache__/image_processing_ovis2.cpython-312.pyc,,
+transformers/models/ovis2/__pycache__/image_processing_pil_ovis2.cpython-312.pyc,,
+transformers/models/ovis2/__pycache__/modeling_ovis2.cpython-312.pyc,,
+transformers/models/ovis2/__pycache__/modular_ovis2.cpython-312.pyc,,
+transformers/models/ovis2/__pycache__/processing_ovis2.cpython-312.pyc,,
+transformers/models/ovis2/configuration_ovis2.py,sha256=UsQ5NNySed4-4hLxIkhVJK3ksFBtv9q86R6aCgJ-bA0,3675
+transformers/models/ovis2/image_processing_ovis2.py,sha256=WpCpcXaRlZ5hs4V9Byn3qAWd0tnnZkHcB5mBjWrecgA,14080
+transformers/models/ovis2/image_processing_pil_ovis2.py,sha256=Kz5emfomusOm51Z3bKysLyhh6aJq7RyQiGzQPwhKlfU,11949
+transformers/models/ovis2/modeling_ovis2.py,sha256=NGXlJ6XgQWEQ2V51qZUEX39OFUrCxKv_nQQ9WoFDoI0,30466
+transformers/models/ovis2/modular_ovis2.py,sha256=pPj4TkUVvpVLNvDjuvbGH5cf-f6ZRC_kyQTHv65rsDE,17709
+transformers/models/ovis2/processing_ovis2.py,sha256=n8aFkT7PlZhJSsEAsZZHR8fs1ni33hyQMP_Jh4xPchw,5847
+transformers/models/owlv2/__init__.py,sha256=yGL_ujde9vGh0CY1NG9p9iPsjKLVDvx_39QjqM5mvLA,1115
+transformers/models/owlv2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/owlv2/__pycache__/configuration_owlv2.cpython-312.pyc,,
+transformers/models/owlv2/__pycache__/image_processing_owlv2.cpython-312.pyc,,
+transformers/models/owlv2/__pycache__/image_processing_pil_owlv2.cpython-312.pyc,,
+transformers/models/owlv2/__pycache__/modeling_owlv2.cpython-312.pyc,,
+transformers/models/owlv2/__pycache__/modular_owlv2.cpython-312.pyc,,
+transformers/models/owlv2/__pycache__/processing_owlv2.cpython-312.pyc,,
+transformers/models/owlv2/configuration_owlv2.py,sha256=SOPJmdpaZlkfvzupAqi1qWnWKtmiY7Xee7HgNHWAnnA,4865
+transformers/models/owlv2/image_processing_owlv2.py,sha256=yvJdBh5Dc9vzZxLygwhPHRcGfZNV0iyU5CXodZAD7H8,18165
+transformers/models/owlv2/image_processing_pil_owlv2.py,sha256=Vh_R6VWTKthdxxedFFfCeoQ8Qpk3uG6TBF1uegQtGAI,18629
+transformers/models/owlv2/modeling_owlv2.py,sha256=EgX2oc8m9mnIhq2TPq-gPifPGS8qpJG7EpD4TEj1TvQ,67487
+transformers/models/owlv2/modular_owlv2.py,sha256=GVnK8DPNYb-qa4iTZzFLkffCwFFlniHTE5Zi0ho1vrM,16086
+transformers/models/owlv2/processing_owlv2.py,sha256=4YYmsD3J5I7LlcOTz9HCL5RTFiPMncBjvzYUsEs0sAY,10439
+transformers/models/owlvit/__init__.py,sha256=01XzuoQkmO4EOgwaSzksl2YlF-LDOpXf-JZ4n692DiM,1165
+transformers/models/owlvit/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/owlvit/__pycache__/configuration_owlvit.cpython-312.pyc,,
+transformers/models/owlvit/__pycache__/image_processing_owlvit.cpython-312.pyc,,
+transformers/models/owlvit/__pycache__/image_processing_pil_owlvit.cpython-312.pyc,,
+transformers/models/owlvit/__pycache__/modeling_owlvit.cpython-312.pyc,,
+transformers/models/owlvit/__pycache__/processing_owlvit.cpython-312.pyc,,
+transformers/models/owlvit/configuration_owlvit.py,sha256=9HPM088U7hdW7YBFJKaSRpZXAReuPYfSz57g9XFOTCU,4387
+transformers/models/owlvit/image_processing_owlvit.py,sha256=zC6-Gl1C1R6L-LfqOATcP1uIUV0GnVX3kAd7PPL0pbk,10905
+transformers/models/owlvit/image_processing_pil_owlvit.py,sha256=iuyrOVxr1j9-7jpTcpj22eBsPVj1pDU22wkhOkmtYNU,11244
+transformers/models/owlvit/modeling_owlvit.py,sha256=qKnnWNRKYdIi_JnUWEnVdXodPd9tnRXJll-0GhfXymo,63058
+transformers/models/owlvit/processing_owlvit.py,sha256=mNqcLhleQR-oBxPd7Z1CfT3YnHghJlm7gLSIGtiF3hM,10389
+transformers/models/paddleocr_vl/__init__.py,sha256=oDtOGkn7Yod8KSfxk6_BBLlLSb81i2ULVt3IiM9n5k4,1151
+transformers/models/paddleocr_vl/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/paddleocr_vl/__pycache__/configuration_paddleocr_vl.cpython-312.pyc,,
+transformers/models/paddleocr_vl/__pycache__/image_processing_paddleocr_vl.cpython-312.pyc,,
+transformers/models/paddleocr_vl/__pycache__/image_processing_pil_paddleocr_vl.cpython-312.pyc,,
+transformers/models/paddleocr_vl/__pycache__/modeling_paddleocr_vl.cpython-312.pyc,,
+transformers/models/paddleocr_vl/__pycache__/modular_paddleocr_vl.cpython-312.pyc,,
+transformers/models/paddleocr_vl/__pycache__/processing_paddleocr_vl.cpython-312.pyc,,
+transformers/models/paddleocr_vl/configuration_paddleocr_vl.py,sha256=ncVeqSV5GupaPo7WtRIkfR11wbnM8sX1--bD3uDtIv0,7740
+transformers/models/paddleocr_vl/image_processing_paddleocr_vl.py,sha256=uCSe6FzBmokyiVMFkiSjlK0aItgTF0fYhmqC-cukpmk,10834
+transformers/models/paddleocr_vl/image_processing_pil_paddleocr_vl.py,sha256=uH4LwuxOXBJHr2xeaXZ0nkk4EEBGqrqRlmZTYdZZSag,10169
+transformers/models/paddleocr_vl/modeling_paddleocr_vl.py,sha256=HED_Nz8LFJyikrWLBpPUvVm9Vm4f4L00lOPe9wl3R3s,75378
+transformers/models/paddleocr_vl/modular_paddleocr_vl.py,sha256=RL1X9kFcW6_xuBV40iTP0oe_b637ml7AyWuvjoSUc6w,46361
+transformers/models/paddleocr_vl/processing_paddleocr_vl.py,sha256=4GV-BoS1HVCsqDsSY2kSrLQUCMVuPQAWdw8vqC0_SxI,7115
+transformers/models/paligemma/__init__.py,sha256=nKnTTLC8XYlI7uYfS8h-D4vz3gFhknkNeDlZIwZlZ9w,1039
+transformers/models/paligemma/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/paligemma/__pycache__/configuration_paligemma.cpython-312.pyc,,
+transformers/models/paligemma/__pycache__/modeling_paligemma.cpython-312.pyc,,
+transformers/models/paligemma/__pycache__/processing_paligemma.cpython-312.pyc,,
+transformers/models/paligemma/configuration_paligemma.py,sha256=bge-tibHwG5IQpZcdZYmTO2EUUxLvq4fsn_VWjtZB4g,4111
+transformers/models/paligemma/modeling_paligemma.py,sha256=j8yVYyhAUQx6ElBhJ2xP2G0i1_J5jQiAaNskEz3nJqo,19608
+transformers/models/paligemma/processing_paligemma.py,sha256=vRxMw72Rac6_UQQmjlhq2rzh4kPc-uXJzkgftSBkdNM,11486
+transformers/models/parakeet/__init__.py,sha256=v9I-7Xsg00JcZYcr9Cwhyth5_9TUdHu5325C9B6uyds,1124
+transformers/models/parakeet/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/parakeet/__pycache__/configuration_parakeet.cpython-312.pyc,,
+transformers/models/parakeet/__pycache__/feature_extraction_parakeet.cpython-312.pyc,,
+transformers/models/parakeet/__pycache__/generation_parakeet.cpython-312.pyc,,
+transformers/models/parakeet/__pycache__/modeling_parakeet.cpython-312.pyc,,
+transformers/models/parakeet/__pycache__/modular_parakeet.cpython-312.pyc,,
+transformers/models/parakeet/__pycache__/processing_parakeet.cpython-312.pyc,,
+transformers/models/parakeet/__pycache__/tokenization_parakeet.cpython-312.pyc,,
+transformers/models/parakeet/configuration_parakeet.py,sha256=dPUsfM-IfaG_hAycdaURtJQDhe975M3JPmTHyvPGVA4,9073
+transformers/models/parakeet/feature_extraction_parakeet.py,sha256=rgPjYQrUS34yK3T70hK1HKPGN3Xn4SnnoIcR_v7uvQI,13060
+transformers/models/parakeet/generation_parakeet.py,sha256=c0rMD4h_dEjGkQmZy2amQfTQzDLn89cYNDZx0m2cCI0,12855
+transformers/models/parakeet/modeling_parakeet.py,sha256=_nosv3inLgaJ3230VSL2BZ83ilZY96XjPQsBQzdZ9Yk,49330
+transformers/models/parakeet/modular_parakeet.py,sha256=I-MP-mQPMOXL0xKEpFYcx5f-6TLucK9wI72kGHG2beQ,41785
+transformers/models/parakeet/processing_parakeet.py,sha256=tvfnYo1uuZUHekGjk7RWlySJoJSLQ4u1wTjm49TiykU,9356
+transformers/models/parakeet/tokenization_parakeet.py,sha256=8XBCL3RL_d1jqZTYYaZ_kKoO59-dh0wqyOH78GQc7Pc,1873
+transformers/models/patchtsmixer/__init__.py,sha256=deFjF_Tu67XcAcNHaq1PXO77N4kVW9wG80SnXBaeagE,1005
+transformers/models/patchtsmixer/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/patchtsmixer/__pycache__/configuration_patchtsmixer.cpython-312.pyc,,
+transformers/models/patchtsmixer/__pycache__/modeling_patchtsmixer.cpython-312.pyc,,
+transformers/models/patchtsmixer/configuration_patchtsmixer.py,sha256=kqvG7P8-y2HXVZPR103rKnsLZCNjxrrw5YBbZqOaFSc,8597
+transformers/models/patchtsmixer/modeling_patchtsmixer.py,sha256=bIxjnrK2_Cmbh04tqPmYuBYipQCXsfbLyZvttYjCTpY,84810
+transformers/models/patchtst/__init__.py,sha256=lrpuBvP25Yq6HZOCyS4yWVYZ47qWzK--rqC0AOIGGPE,997
+transformers/models/patchtst/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/patchtst/__pycache__/configuration_patchtst.cpython-312.pyc,,
+transformers/models/patchtst/__pycache__/modeling_patchtst.cpython-312.pyc,,
+transformers/models/patchtst/configuration_patchtst.py,sha256=UfEFD7SahoEo-cQyxR9E9FxQnVrLLw8tO2hjSSN_GUk,8420
+transformers/models/patchtst/modeling_patchtst.py,sha256=NAUYUvPo89ZEzYFFGuQhSriEcfnJ3Dyb3v-5oTi-k3Q,84896
+transformers/models/pe_audio/__init__.py,sha256=kPx9mIPU77pDtiJYg4xOr3RFIz_cUYBbToLt0dfC4k8,1088
+transformers/models/pe_audio/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/pe_audio/__pycache__/configuration_pe_audio.cpython-312.pyc,,
+transformers/models/pe_audio/__pycache__/feature_extraction_pe_audio.cpython-312.pyc,,
+transformers/models/pe_audio/__pycache__/modeling_pe_audio.cpython-312.pyc,,
+transformers/models/pe_audio/__pycache__/modular_pe_audio.cpython-312.pyc,,
+transformers/models/pe_audio/__pycache__/processing_pe_audio.cpython-312.pyc,,
+transformers/models/pe_audio/configuration_pe_audio.py,sha256=SqvyJfZkPdSLcEMZ5IDdfyCiW9fVdYOLNsiOHBJLVA0,4960
+transformers/models/pe_audio/feature_extraction_pe_audio.py,sha256=EzwR1sqIA2h1fr8VflbeFujIbnajl_0oUUEeuhov62o,6484
+transformers/models/pe_audio/modeling_pe_audio.py,sha256=TE5zhVPGT7aQt5WRndS_4ZWMXIaswhxySMC9pP14UVI,33378
+transformers/models/pe_audio/modular_pe_audio.py,sha256=1VSspkMOfFoQW3PMtdNcdZuTG27jZdP_t99fqZkRr0Q,11924
+transformers/models/pe_audio/processing_pe_audio.py,sha256=DGJ-IjGrDuYgn9eSlH0s-l2nsrmQzh-e8sMBGvBf4hM,879
+transformers/models/pe_audio_video/__init__.py,sha256=tt4bWq6NXVc6hA7uTtMYQ3CD9APPTUlhUrPwpOKl22k,1059
+transformers/models/pe_audio_video/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/pe_audio_video/__pycache__/configuration_pe_audio_video.cpython-312.pyc,,
+transformers/models/pe_audio_video/__pycache__/modeling_pe_audio_video.cpython-312.pyc,,
+transformers/models/pe_audio_video/__pycache__/modular_pe_audio_video.cpython-312.pyc,,
+transformers/models/pe_audio_video/__pycache__/processing_pe_audio_video.cpython-312.pyc,,
+transformers/models/pe_audio_video/configuration_pe_audio_video.py,sha256=BCpPnauN1HpY0hsoc36JVdyoXVigL4vVRHwJO-pTmog,5751
+transformers/models/pe_audio_video/modeling_pe_audio_video.py,sha256=5vyQj3MiNwl6Vadf_zzjnCzZXHw60deWJAZyg3QBdpA,46885
+transformers/models/pe_audio_video/modular_pe_audio_video.py,sha256=3ad8Fw3dx3T59HQviu0A3XfZqBbT2FUa7yeDZXrBta4,37073
+transformers/models/pe_audio_video/processing_pe_audio_video.py,sha256=id4oUsmeuemGPnVnWTPJtqnTodzIGPqQtsV9nWXtJcQ,921
+transformers/models/pe_video/__init__.py,sha256=vCPdJDp9o_fTkcffIBjSBjuOqHM-PRhS5jf74KcKQdk,1086
+transformers/models/pe_video/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/pe_video/__pycache__/configuration_pe_video.cpython-312.pyc,,
+transformers/models/pe_video/__pycache__/modeling_pe_video.cpython-312.pyc,,
+transformers/models/pe_video/__pycache__/modular_pe_video.cpython-312.pyc,,
+transformers/models/pe_video/__pycache__/processing_pe_video.cpython-312.pyc,,
+transformers/models/pe_video/__pycache__/video_processing_pe_video.cpython-312.pyc,,
+transformers/models/pe_video/configuration_pe_video.py,sha256=4cUxoGEaTUmLqTL1JdUtZybVfK3UDNL7wlNs8bMeOsw,4963
+transformers/models/pe_video/modeling_pe_video.py,sha256=vzbGIez_QXltJjsPC73B2-IZs6dm558MmFp1pibOZq8,26531
+transformers/models/pe_video/modular_pe_video.py,sha256=rmC1BTkvzFDJxMF3Ej3JudXCCR-MfT3Z1-sv8yBlJak,8958
+transformers/models/pe_video/processing_pe_video.py,sha256=ZrP95LzdcixtU5U_ZjcgKRCHnbH4_35SoFhyCSXtNwI,262
+transformers/models/pe_video/video_processing_pe_video.py,sha256=v04MsBAnyhLJfIkd2iZL6PROPIdiuYsE2R6bOKnCoFE,2663
+transformers/models/pegasus/__init__.py,sha256=jCo_uusFhqSgC-X8TuopKyGESiE96TLPuo7ooxzMx2M,1035
+transformers/models/pegasus/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/pegasus/__pycache__/configuration_pegasus.cpython-312.pyc,,
+transformers/models/pegasus/__pycache__/modeling_pegasus.cpython-312.pyc,,
+transformers/models/pegasus/__pycache__/tokenization_pegasus.cpython-312.pyc,,
+transformers/models/pegasus/configuration_pegasus.py,sha256=cyoMCEeFfs_BY-tq2LR8V-0SoMreuJLpHRqtK3FVjIU,2515
+transformers/models/pegasus/modeling_pegasus.py,sha256=B9FhHiR3cENrDQQdYHNscarAmml66HnfBw_PCuM5gVk,48621
+transformers/models/pegasus/tokenization_pegasus.py,sha256=U6Hff-4LYttOVVpsNYj4OvrtqyEOq-Fe69g-DuiRJ7c,6532
+transformers/models/pegasus_x/__init__.py,sha256=qSLaqKRA1upZOobapHW5MjSZvIEzf-ij-ZmY1VGzqaE,999
+transformers/models/pegasus_x/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/pegasus_x/__pycache__/configuration_pegasus_x.cpython-312.pyc,,
+transformers/models/pegasus_x/__pycache__/modeling_pegasus_x.cpython-312.pyc,,
+transformers/models/pegasus_x/configuration_pegasus_x.py,sha256=hKBOaqpKIBYmo_3PEOrPr64ZiNui1EZwwffHkuNVl90,3086
+transformers/models/pegasus_x/modeling_pegasus_x.py,sha256=dfPiII7dySTjnO5Ii--i9X5-lOJ1fDB7WLV515bJVu4,60595
+transformers/models/perceiver/__init__.py,sha256=7ylDdhRBV6YIb_V1MbVXfH13tGkbnYi6hEN3Johss3Y,1137
+transformers/models/perceiver/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/perceiver/__pycache__/configuration_perceiver.cpython-312.pyc,,
+transformers/models/perceiver/__pycache__/image_processing_perceiver.cpython-312.pyc,,
+transformers/models/perceiver/__pycache__/image_processing_pil_perceiver.cpython-312.pyc,,
+transformers/models/perceiver/__pycache__/modeling_perceiver.cpython-312.pyc,,
+transformers/models/perceiver/__pycache__/tokenization_perceiver.cpython-312.pyc,,
+transformers/models/perceiver/configuration_perceiver.py,sha256=HVtsJhE3Di2Cxa9wmbz_NGQF3bGj4QjQLptYS9EB1Jc,5482
+transformers/models/perceiver/image_processing_perceiver.py,sha256=gdk_k4-9qkL7FCR9GzHz5IvYdkrcEM2XaATW7GlcPiU,5269
+transformers/models/perceiver/image_processing_pil_perceiver.py,sha256=U6Lwdx4LXhuSKZH72mwoLjPWdewsVUVEeiFiAJ9yvuc,4045
+transformers/models/perceiver/modeling_perceiver.py,sha256=3glPp3ls499wSDqeHlrn0Jd6U1XAPF63WMyaAMHX_ck,134812
+transformers/models/perceiver/tokenization_perceiver.py,sha256=GVEoliqqJb7AtXDXRtjmp_45E-IJLoPZA8jNIgcHvP8,7982
+transformers/models/perception_lm/__init__.py,sha256=0c6dVdZLAq5egeXV2S01hlTG8vF4AcqiqkJb4yfQRfM,1101
+transformers/models/perception_lm/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/perception_lm/__pycache__/configuration_perception_lm.cpython-312.pyc,,
+transformers/models/perception_lm/__pycache__/image_processing_perception_lm.cpython-312.pyc,,
+transformers/models/perception_lm/__pycache__/modeling_perception_lm.cpython-312.pyc,,
+transformers/models/perception_lm/__pycache__/modular_perception_lm.cpython-312.pyc,,
+transformers/models/perception_lm/__pycache__/processing_perception_lm.cpython-312.pyc,,
+transformers/models/perception_lm/__pycache__/video_processing_perception_lm.cpython-312.pyc,,
+transformers/models/perception_lm/configuration_perception_lm.py,sha256=c_4ZJVAZA1Abhni_zrmxNsPjtv8nRhQMub6avnWnvrA,2662
+transformers/models/perception_lm/image_processing_perception_lm.py,sha256=Vgn1EczuVG1jiJx57Uel-lkJE7O-dQz0jc-LKIgfFtw,13906
+transformers/models/perception_lm/modeling_perception_lm.py,sha256=G8YB2Ai4GsSLYJev-aF5FK4K_SLa6fgj8tflv6evFqk,19824
+transformers/models/perception_lm/modular_perception_lm.py,sha256=O0x1QUt6lFq32bsOBuCimApHmF27xbKbtsJT0Va3z8Q,17782
+transformers/models/perception_lm/processing_perception_lm.py,sha256=f5_jMUPXzzBCmLM-px7tQfM7cYHYcIyE3rvcDQbF6Xo,8637
+transformers/models/perception_lm/video_processing_perception_lm.py,sha256=i49-VYt3kgRhkf7XRyD3sYaoI2pIKCNSTlyXfzjnBPk,1211
+transformers/models/persimmon/__init__.py,sha256=T1WqyE78N2TO74u9a9QdRIGaMowYqP6vWv8KhPojkLg,999
+transformers/models/persimmon/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/persimmon/__pycache__/configuration_persimmon.cpython-312.pyc,,
+transformers/models/persimmon/__pycache__/modeling_persimmon.cpython-312.pyc,,
+transformers/models/persimmon/configuration_persimmon.py,sha256=WM-QAYlMWT2UjWm4FZ3yp6UL4S6izhU8dYQUPGjbTjY,2248
+transformers/models/persimmon/modeling_persimmon.py,sha256=NVq8icX6c5JXpxhq41wsaKXIhnI6CHu2zDss3Jeqm0k,22825
+transformers/models/phi/__init__.py,sha256=4DUgmUqGKcGXxzTrxUVGcacZ43uv3SzXsOV_Ke6oeGg,1006
+transformers/models/phi/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/phi/__pycache__/configuration_phi.cpython-312.pyc,,
+transformers/models/phi/__pycache__/modeling_phi.cpython-312.pyc,,
+transformers/models/phi/__pycache__/modular_phi.cpython-312.pyc,,
+transformers/models/phi/configuration_phi.py,sha256=MBUAQnZdHXEbJCOCZC95n4jopxiN2LJRJJXzJOHqkTQ,3191
+transformers/models/phi/modeling_phi.py,sha256=57nKQvafzKgFiB9-C_tfknFeZR1Zv2vDnxtEjCuw1d0,20849
+transformers/models/phi/modular_phi.py,sha256=HVCKHckhL_OMJIhhdHEmif8F75ROIwKeAVcz-KKJnSU,10807
+transformers/models/phi3/__init__.py,sha256=dxyO-jIh0yB6t2Dzs173aRrEnTceVMIYIkg6JxIeyWs,989
+transformers/models/phi3/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/phi3/__pycache__/configuration_phi3.cpython-312.pyc,,
+transformers/models/phi3/__pycache__/modeling_phi3.cpython-312.pyc,,
+transformers/models/phi3/__pycache__/modular_phi3.cpython-312.pyc,,
+transformers/models/phi3/configuration_phi3.py,sha256=RXFud3zNEBunxLGpcjuoAl4ruzZ8dQhxJ0b6EJ9_VmU,6697
+transformers/models/phi3/modeling_phi3.py,sha256=kiM1m9ci-XjzLMlALaC188Bs0Pfl00M8JkXZWLMzimQ,23636
+transformers/models/phi3/modular_phi3.py,sha256=y1CSBUy6VuYr0y-WhOjqg0LrtEvknceNkVLl11nOTm0,10399
+transformers/models/phi4_multimodal/__init__.py,sha256=5Ds1jxc6wd0hMhbkNH8g7uLIoOEdtYzqnlD9mBPpfqs,1165
+transformers/models/phi4_multimodal/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/phi4_multimodal/__pycache__/configuration_phi4_multimodal.cpython-312.pyc,,
+transformers/models/phi4_multimodal/__pycache__/feature_extraction_phi4_multimodal.cpython-312.pyc,,
+transformers/models/phi4_multimodal/__pycache__/image_processing_phi4_multimodal.cpython-312.pyc,,
+transformers/models/phi4_multimodal/__pycache__/modeling_phi4_multimodal.cpython-312.pyc,,
+transformers/models/phi4_multimodal/__pycache__/modular_phi4_multimodal.cpython-312.pyc,,
+transformers/models/phi4_multimodal/__pycache__/processing_phi4_multimodal.cpython-312.pyc,,
+transformers/models/phi4_multimodal/configuration_phi4_multimodal.py,sha256=TOSqsY79OKSkY8CznHFYuheUCauKYUl5rtba37Jh53M,13614
+transformers/models/phi4_multimodal/feature_extraction_phi4_multimodal.py,sha256=HDFWut0WDq1UnvOatGpJmlmVYTG0s6vEOYpW_JUd-3A,13283
+transformers/models/phi4_multimodal/image_processing_phi4_multimodal.py,sha256=GcEJxdo2FyVq1EVqLXbYy7IShyqJ-ituExuQY94xL80,10474
+transformers/models/phi4_multimodal/modeling_phi4_multimodal.py,sha256=vxf3oFlgLOlngm3O5CI1iGtIwKFzUeI56ofN4pjJ80c,76043
+transformers/models/phi4_multimodal/modular_phi4_multimodal.py,sha256=ZGllwZJov9IloY-tpz4SsbhFafdRvpLaTFYbOsfS3YA,64497
+transformers/models/phi4_multimodal/processing_phi4_multimodal.py,sha256=4V3Ehgv05ldiRZOUrA7YiaDwFAu9fKaGSA501LkT17c,5525
+transformers/models/phimoe/__init__.py,sha256=wGasPysu0EH_q0QGaZmXqQL57GxfZn8NTsvB2I6U2ro,1013
+transformers/models/phimoe/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/phimoe/__pycache__/configuration_phimoe.cpython-312.pyc,,
+transformers/models/phimoe/__pycache__/modeling_phimoe.cpython-312.pyc,,
+transformers/models/phimoe/__pycache__/modular_phimoe.cpython-312.pyc,,
+transformers/models/phimoe/configuration_phimoe.py,sha256=DsLz9WR0qMBkXnUyY7o1ZASqhbWS-91cqzFGvDyXJRw,4000
+transformers/models/phimoe/modeling_phimoe.py,sha256=ZyU0M-j-3SD2vU1a63naQnrczoi6yA4oF2psr95Y7DI,38669
+transformers/models/phimoe/modular_phimoe.py,sha256=6nyDbrE7pP2tKbJ8uKtjawpfUx1NAHt06zqfeIpPxPU,15585
+transformers/models/phobert/__init__.py,sha256=mau-2HIOzSk8qGIhxivVBPPYTx3hhdgoKPtnptDF38M,958
+transformers/models/phobert/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/phobert/__pycache__/tokenization_phobert.cpython-312.pyc,,
+transformers/models/phobert/tokenization_phobert.py,sha256=WKrjnlFs4-Oh41kJMLDkdegGB50YKNAjooQY7WxxZ5E,13057
+transformers/models/pi0/__init__.py,sha256=1BwaAxPhlic8B_HeGOJsQpb5ddweoT2gIUqXOn_nrBw,1058
+transformers/models/pi0/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/pi0/__pycache__/configuration_pi0.cpython-312.pyc,,
+transformers/models/pi0/__pycache__/image_processing_pi0.cpython-312.pyc,,
+transformers/models/pi0/__pycache__/modeling_pi0.cpython-312.pyc,,
+transformers/models/pi0/__pycache__/modular_pi0.cpython-312.pyc,,
+transformers/models/pi0/__pycache__/processing_pi0.cpython-312.pyc,,
+transformers/models/pi0/configuration_pi0.py,sha256=B-9Sd_MRYmzZiqzeTp-J0z26fkFISxA1uANEFrF2qy0,6487
+transformers/models/pi0/image_processing_pi0.py,sha256=ti2iPJaTJN5t5dvsCkTzTHDAStXSiLIzMgmg82-hkww,2086
+transformers/models/pi0/modeling_pi0.py,sha256=Zf77FOqpb_bv9yj2r3czIbaNBcUQA-yHeZQ3ZiQfPYs,16856
+transformers/models/pi0/modular_pi0.py,sha256=eoj1-EbMWlJyt_YNpe3Dhv-gOuLYBpJqxuUSypXwIGI,28370
+transformers/models/pi0/processing_pi0.py,sha256=j6pccO1_raF9tzGO9sq0EP_mlykFJaJtH4c0hwXRvR8,10040
+transformers/models/pix2struct/__init__.py,sha256=rAdKNFbf_v793ptiB5m1WHHXotlptkISpFjPAp1eSc8,1140
+transformers/models/pix2struct/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/pix2struct/__pycache__/configuration_pix2struct.cpython-312.pyc,,
+transformers/models/pix2struct/__pycache__/image_processing_pil_pix2struct.cpython-312.pyc,,
+transformers/models/pix2struct/__pycache__/image_processing_pix2struct.cpython-312.pyc,,
+transformers/models/pix2struct/__pycache__/modeling_pix2struct.cpython-312.pyc,,
+transformers/models/pix2struct/__pycache__/processing_pix2struct.cpython-312.pyc,,
+transformers/models/pix2struct/configuration_pix2struct.py,sha256=16eX8O5ASUCmhrB54E3zvTgTDkE4hphMm9ksXOAS-W0,8355
+transformers/models/pix2struct/image_processing_pil_pix2struct.py,sha256=Mznm6J0jAayaZMjCb0Nn-2511Aon7NEIoaKQG-8jjQ4,16103
+transformers/models/pix2struct/image_processing_pix2struct.py,sha256=Tw8MLqT0XErVRSx71p7Fein3xmfPlBzBONFTp4HpYOs,16982
+transformers/models/pix2struct/modeling_pix2struct.py,sha256=-gI5nV1W-_MY9aCl9-KD1e2ctkwiz27kYB7JZ7PPUJA,58602
+transformers/models/pix2struct/processing_pix2struct.py,sha256=GW-ZQSxH38270eh03EbjRm3nVT7sS4zFck7JwL2w-mk,4167
+transformers/models/pixio/__init__.py,sha256=G834ZPfjQ3fixXcSbc1mYJcb5FurIq7Ux5fYfD5ECGc,1041
+transformers/models/pixio/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/pixio/__pycache__/configuration_pixio.cpython-312.pyc,,
+transformers/models/pixio/__pycache__/modeling_pixio.cpython-312.pyc,,
+transformers/models/pixio/__pycache__/modular_pixio.cpython-312.pyc,,
+transformers/models/pixio/configuration_pixio.py,sha256=2ML7DhcmU7kr4h4hBPopxK2mpUaHwpG66Kh3RUYK1dw,3865
+transformers/models/pixio/modeling_pixio.py,sha256=iHA-ZO8XxT1h7EhKQBCaD99dGJDc_Z5XxGKDTfdMBpY,18481
+transformers/models/pixio/modular_pixio.py,sha256=yrfpRq6DoELsVcirHsGOsYAEppoMjhZClafIWD0AnFg,11784
+transformers/models/pixtral/__init__.py,sha256=GUDUJrPmbLV07-UczEEswlAOgednJKz-aLrdJwFZed8,1125
+transformers/models/pixtral/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/pixtral/__pycache__/configuration_pixtral.cpython-312.pyc,,
+transformers/models/pixtral/__pycache__/image_processing_pil_pixtral.cpython-312.pyc,,
+transformers/models/pixtral/__pycache__/image_processing_pixtral.cpython-312.pyc,,
+transformers/models/pixtral/__pycache__/modeling_pixtral.cpython-312.pyc,,
+transformers/models/pixtral/__pycache__/processing_pixtral.cpython-312.pyc,,
+transformers/models/pixtral/configuration_pixtral.py,sha256=N8CPneyxaJ81Pjvc099Jtu97QfAse3jyJamRk2TK9gI,2020
+transformers/models/pixtral/image_processing_pil_pixtral.py,sha256=jWRkYWODjkGH4vI0T3E20i8lK0nW8Q4hheh6K3ww21w,8808
+transformers/models/pixtral/image_processing_pixtral.py,sha256=1j-r72yQJ4WMwbpHgfYoEdnHERnztrbpoLxZuZ5VPbY,9859
+transformers/models/pixtral/modeling_pixtral.py,sha256=5xNgX8wGI8tJssJblq59fThftuTiVT5Uhx47WjL5ppk,19425
+transformers/models/pixtral/processing_pixtral.py,sha256=htqw_vhvdlc-D1Vp8_mn9vQ82subagP41a-pw9f1IKw,9473
+transformers/models/plbart/__init__.py,sha256=jmP857QTG7jGfr9n0qK3TB_1-hdVDD1ajtJvP6C7FIw,1032
+transformers/models/plbart/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/plbart/__pycache__/configuration_plbart.cpython-312.pyc,,
+transformers/models/plbart/__pycache__/modeling_plbart.cpython-312.pyc,,
+transformers/models/plbart/__pycache__/modular_plbart.cpython-312.pyc,,
+transformers/models/plbart/__pycache__/tokenization_plbart.cpython-312.pyc,,
+transformers/models/plbart/configuration_plbart.py,sha256=Jd7XxpwggeJ5OoxTjK5yQ-ZShx8mFcPnvG0O4kYa59o,2605
+transformers/models/plbart/modeling_plbart.py,sha256=0HEme2xCUfMoR_Df4lCTTe9kEBTC4lKOq4XGL_r_exA,48492
+transformers/models/plbart/modular_plbart.py,sha256=whZrMSbZxYi5qjMmw6QVyI7GS4-2qc5nH0mf2xDHWGE,17348
+transformers/models/plbart/tokenization_plbart.py,sha256=lR3AaTrYtFQI-yoF_c8gilRh9XzRvGhukwTeY_FGwpI,15698
+transformers/models/poolformer/__init__.py,sha256=iMC4C8fvtFvKpIbAAKYS_LYoHAO2KuhtEjnGtTOy8Fk,1148
+transformers/models/poolformer/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/poolformer/__pycache__/configuration_poolformer.cpython-312.pyc,,
+transformers/models/poolformer/__pycache__/image_processing_pil_poolformer.cpython-312.pyc,,
+transformers/models/poolformer/__pycache__/image_processing_poolformer.cpython-312.pyc,,
+transformers/models/poolformer/__pycache__/modeling_poolformer.cpython-312.pyc,,
+transformers/models/poolformer/configuration_poolformer.py,sha256=dP7BRmy4hcbTD8HlAy1d6cdV2dOUVRHBCqgbuSedyoE,2844
+transformers/models/poolformer/image_processing_pil_poolformer.py,sha256=Pu9jjHxmAEcytpcjDIfcDvcqSbagjfZO8cW74K4VpgY,4668
+transformers/models/poolformer/image_processing_poolformer.py,sha256=fAipxwIy-Y9UDDUH2eF8gcE4qDrnestMYxzI-5YNeUg,5388
+transformers/models/poolformer/modeling_poolformer.py,sha256=3WKkrPYNLWyvFdXk4h144Tx7SGy8BlEZYmC4WI4GXrk,14258
+transformers/models/pop2piano/__init__.py,sha256=I2PPcFi-p0X5py7dLqobymv3E9g-mUv1QRn0luyPlIk,999
+transformers/models/pop2piano/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/pop2piano/__pycache__/configuration_pop2piano.cpython-312.pyc,,
+transformers/models/pop2piano/__pycache__/feature_extraction_pop2piano.cpython-312.pyc,,
+transformers/models/pop2piano/__pycache__/modeling_pop2piano.cpython-312.pyc,,
+transformers/models/pop2piano/__pycache__/processing_pop2piano.cpython-312.pyc,,
+transformers/models/pop2piano/__pycache__/tokenization_pop2piano.cpython-312.pyc,,
+transformers/models/pop2piano/configuration_pop2piano.py,sha256=IQjt61qkD8ME-BrQCeaQJN3tkHIVcZrlY-OdBpwusT8,2839
+transformers/models/pop2piano/feature_extraction_pop2piano.py,sha256=gwI8jIAeCX2P86gLyddK7Tqv11-4m3fxCk1sTToQl4s,19870
+transformers/models/pop2piano/modeling_pop2piano.py,sha256=0m7mmzoctxU_WIm7rgEXE6dW60zYvg0wvGnuEGGCJII,49579
+transformers/models/pop2piano/processing_pop2piano.py,sha256=Ufls4EQt6eAMcMuFhWnvJA4R-dshtRGKv-hiDoFYcIA,5235
+transformers/models/pop2piano/tokenization_pop2piano.py,sha256=cV3QqOZxqUG_5RpdOEktAOp73pRRu6Jeo6dJjqZCQek,32550
+transformers/models/pp_chart2table/__init__.py,sha256=GuSbpkNTiMo5VQMPWBvAbHAAX4uIZWHPBRa58qATRt8,1118
+transformers/models/pp_chart2table/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/pp_chart2table/__pycache__/configuration_pp_chart2table.cpython-312.pyc,,
+transformers/models/pp_chart2table/__pycache__/image_processing_pil_pp_chart2table.cpython-312.pyc,,
+transformers/models/pp_chart2table/__pycache__/image_processing_pp_chart2table.cpython-312.pyc,,
+transformers/models/pp_chart2table/__pycache__/modular_pp_chart2table.cpython-312.pyc,,
+transformers/models/pp_chart2table/__pycache__/processing_pp_chart2table.cpython-312.pyc,,
+transformers/models/pp_chart2table/configuration_pp_chart2table.py,sha256=jRib0eYgi6r_MJnd0Kfz4fy6pGDtt3_yy-drw6pFfLo,5605
+transformers/models/pp_chart2table/image_processing_pil_pp_chart2table.py,sha256=QwHpTTtbUkg98FNuGHHxf2f10S3SKXnpwdDUfNNMndE,1915
+transformers/models/pp_chart2table/image_processing_pp_chart2table.py,sha256=UePM86wqIpS6F9Hc4BfuuzKzCHwpSWjtoY1awdpg63I,1925
+transformers/models/pp_chart2table/modular_pp_chart2table.py,sha256=2ZENiN_8ozebR5T3FDAPbm1fX43bwi3TxYkZVGzzaKI,3225
+transformers/models/pp_chart2table/processing_pp_chart2table.py,sha256=eOEkzNoZqywGcSNwd4XbgwoqdnRhfRcraZ1XLtcK1Vs,2441
+transformers/models/pp_doclayout_v2/__init__.py,sha256=wf3tov6peTKmt8bIR3fuzOtzgPYnq46impLs9mkVtzs,1065
+transformers/models/pp_doclayout_v2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/pp_doclayout_v2/__pycache__/configuration_pp_doclayout_v2.cpython-312.pyc,,
+transformers/models/pp_doclayout_v2/__pycache__/image_processing_pp_doclayout_v2.cpython-312.pyc,,
+transformers/models/pp_doclayout_v2/__pycache__/modeling_pp_doclayout_v2.cpython-312.pyc,,
+transformers/models/pp_doclayout_v2/__pycache__/modular_pp_doclayout_v2.cpython-312.pyc,,
+transformers/models/pp_doclayout_v2/configuration_pp_doclayout_v2.py,sha256=FJglA1hSLsZ3PEh-DfQ0S1-452miQkNWJYvsdR_0SsE,13337
+transformers/models/pp_doclayout_v2/image_processing_pp_doclayout_v2.py,sha256=8YKLOnsaaUkDaoEr9ogppDi9nnh2jjH4k-NVxHrDkpE,8801
+transformers/models/pp_doclayout_v2/modeling_pp_doclayout_v2.py,sha256=xFCNjJfZTY4XEMX3_R4F9tPIgs79gLCv9lUeThQDudQ,116264
+transformers/models/pp_doclayout_v2/modular_pp_doclayout_v2.py,sha256=Hpfx8ZhHFf1ix0BVp5Rkxjq1r7RaWhAZuxKbflZqizo,46789
+transformers/models/pp_doclayout_v3/__init__.py,sha256=1Da1_NlTNac3Y9nDAf-Immo668IpjCEDEwlQLXeRB0s,1065
+transformers/models/pp_doclayout_v3/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/pp_doclayout_v3/__pycache__/configuration_pp_doclayout_v3.cpython-312.pyc,,
+transformers/models/pp_doclayout_v3/__pycache__/image_processing_pp_doclayout_v3.cpython-312.pyc,,
+transformers/models/pp_doclayout_v3/__pycache__/modeling_pp_doclayout_v3.cpython-312.pyc,,
+transformers/models/pp_doclayout_v3/__pycache__/modular_pp_doclayout_v3.cpython-312.pyc,,
+transformers/models/pp_doclayout_v3/configuration_pp_doclayout_v3.py,sha256=drVpEnxSFohfCoQzLHM1UyD5TA8pgc2gAqEcF0ZgYQw,9794
+transformers/models/pp_doclayout_v3/image_processing_pp_doclayout_v3.py,sha256=WwZPpzg92hKzVQRI6ud9T2J6ECwl6LTbJdmehfukq8Y,13517
+transformers/models/pp_doclayout_v3/modeling_pp_doclayout_v3.py,sha256=EoyZtZXcSiKoqKKm8dZa1alCCohV1BpLkDcsG5c7gXs,96777
+transformers/models/pp_doclayout_v3/modular_pp_doclayout_v3.py,sha256=v0Grjpd5oW7Wxk-CaGvLJNT7_G2Kyuhi14M6-KyGkTs,68294
+transformers/models/pp_formulanet/__init__.py,sha256=eo38nMUdR-UhKwSJdS-BpgYo1EKrFPYZi30QAdrNYi0,1058
+transformers/models/pp_formulanet/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/pp_formulanet/__pycache__/configuration_pp_formulanet.cpython-312.pyc,,
+transformers/models/pp_formulanet/__pycache__/image_processing_pp_formulanet.cpython-312.pyc,,
+transformers/models/pp_formulanet/__pycache__/modeling_pp_formulanet.cpython-312.pyc,,
+transformers/models/pp_formulanet/__pycache__/modular_pp_formulanet.cpython-312.pyc,,
+transformers/models/pp_formulanet/__pycache__/processing_pp_formulanet.cpython-312.pyc,,
+transformers/models/pp_formulanet/configuration_pp_formulanet.py,sha256=Ur0d0P3tUjSPRYYLRF0LuQQ0VbwXahlf1uHSOoFTUuo,6648
+transformers/models/pp_formulanet/image_processing_pp_formulanet.py,sha256=5INkiWMr2Ic7VfzDCA-Cbwf0_e7qpZVK2C5cxORqMac,11651
+transformers/models/pp_formulanet/modeling_pp_formulanet.py,sha256=h73pkR_2ExaGZC8pTk7l0qrYNY2nTRsvf3TtW2RTAU8,50943
+transformers/models/pp_formulanet/modular_pp_formulanet.py,sha256=XxwUdD1TZ3uRUM4m4cN41RNg0EZgVJqAHYicJNkoVMA,21429
+transformers/models/pp_formulanet/processing_pp_formulanet.py,sha256=SOySHKz7MenUDJf9hlms_WRnFMZt5uhazx0GoioK2mE,6901
+transformers/models/pp_lcnet/__init__.py,sha256=TsPZERTGhWU-NT7mV7hFC9gToI0LdphS-El4JegEZvw,1042
+transformers/models/pp_lcnet/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/pp_lcnet/__pycache__/configuration_pp_lcnet.cpython-312.pyc,,
+transformers/models/pp_lcnet/__pycache__/image_processing_pp_lcnet.cpython-312.pyc,,
+transformers/models/pp_lcnet/__pycache__/modeling_pp_lcnet.cpython-312.pyc,,
+transformers/models/pp_lcnet/__pycache__/modular_pp_lcnet.cpython-312.pyc,,
+transformers/models/pp_lcnet/configuration_pp_lcnet.py,sha256=EK2WMUKCOi58cyoEZuZ3IXyVuZ81xhSbSUCXUPqx_PY,5465
+transformers/models/pp_lcnet/image_processing_pp_lcnet.py,sha256=ljMdvrYEvNpNACQgBdxipszsybhIo18IPB-BqhGrjss,6006
+transformers/models/pp_lcnet/modeling_pp_lcnet.py,sha256=AMLXZzbrAsJPVtjqN9W8Ao-TBbbosfyCf6yl_v8uGmU,13528
+transformers/models/pp_lcnet/modular_pp_lcnet.py,sha256=07ucOqrx0xjTnFc6XSt1Cvrw7G_1kaG5b_Vw9lADmPE,20292
+transformers/models/pp_lcnet_v3/__init__.py,sha256=VkvZybzQ4fWBg0AfZSaqUEaFLyxNMQV6rQuiWoAWsgY,1003
+transformers/models/pp_lcnet_v3/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/pp_lcnet_v3/__pycache__/configuration_pp_lcnet_v3.cpython-312.pyc,,
+transformers/models/pp_lcnet_v3/__pycache__/modeling_pp_lcnet_v3.cpython-312.pyc,,
+transformers/models/pp_lcnet_v3/__pycache__/modular_pp_lcnet_v3.cpython-312.pyc,,
+transformers/models/pp_lcnet_v3/configuration_pp_lcnet_v3.py,sha256=UDIMBhAanCQ8GdHxgKo4yatAIIpPv670sD9V67os_cM,5514
+transformers/models/pp_lcnet_v3/modeling_pp_lcnet_v3.py,sha256=II8Y-eV27_Y0dzNv_SWZlKaGWdE04QX1yStq7d4EyWg,14417
+transformers/models/pp_lcnet_v3/modular_pp_lcnet_v3.py,sha256=oYuVWs5zx_z_a8TEmWpZwdsILdfqu9NYvpVgsQXaH1g,9615
+transformers/models/pp_lcnet_v4/__init__.py,sha256=Qr0OvUYZ3PQYXnTHo1qTFvXjvhIdxVv9Nym-YKdkpQE,1003
+transformers/models/pp_lcnet_v4/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/pp_lcnet_v4/__pycache__/configuration_pp_lcnet_v4.cpython-312.pyc,,
+transformers/models/pp_lcnet_v4/__pycache__/modeling_pp_lcnet_v4.cpython-312.pyc,,
+transformers/models/pp_lcnet_v4/__pycache__/modular_pp_lcnet_v4.cpython-312.pyc,,
+transformers/models/pp_lcnet_v4/configuration_pp_lcnet_v4.py,sha256=iAFNYtffD0IjlSVhKcJQ-Z4n0-rb1efHCkOhlW5bnvY,6039
+transformers/models/pp_lcnet_v4/modeling_pp_lcnet_v4.py,sha256=2uKiniQANd-IWmuFFvi0B4kxkguSJGY0l0VxcBrLLgI,14544
+transformers/models/pp_lcnet_v4/modular_pp_lcnet_v4.py,sha256=cqIVDICf8dI3faI3M-iACR0g6LxEAXRDDXz63KbyEdM,9985
+transformers/models/pp_ocrv5_mobile_det/__init__.py,sha256=PjiEOxHLq2FrnJRCSAOm6gqahwrpx2lrr6zYQH4W76k,1019
+transformers/models/pp_ocrv5_mobile_det/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/pp_ocrv5_mobile_det/__pycache__/configuration_pp_ocrv5_mobile_det.cpython-312.pyc,,
+transformers/models/pp_ocrv5_mobile_det/__pycache__/modeling_pp_ocrv5_mobile_det.cpython-312.pyc,,
+transformers/models/pp_ocrv5_mobile_det/__pycache__/modular_pp_ocrv5_mobile_det.cpython-312.pyc,,
+transformers/models/pp_ocrv5_mobile_det/configuration_pp_ocrv5_mobile_det.py,sha256=whCuR0XKU-h66Am2LhysIz5U3GNxsHVpbh_s1xWYT6E,4201
+transformers/models/pp_ocrv5_mobile_det/modeling_pp_ocrv5_mobile_det.py,sha256=QdIipFHvz6M38eQYM7cvXHFZOclgH78ZPEPGTYX6wbQ,12182
+transformers/models/pp_ocrv5_mobile_det/modular_pp_ocrv5_mobile_det.py,sha256=wM7Mi0a9iprtuCsinnXMfqApZ7pq5pmvy4JYC3ASNyg,10547
+transformers/models/pp_ocrv5_mobile_rec/__init__.py,sha256=wUUus_9zNrVHlab9e1DWERFeKZAYyP-XND6cDXPjuSY,1021
+transformers/models/pp_ocrv5_mobile_rec/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/pp_ocrv5_mobile_rec/__pycache__/configuration_pp_ocrv5_mobile_rec.cpython-312.pyc,,
+transformers/models/pp_ocrv5_mobile_rec/__pycache__/modeling_pp_ocrv5_mobile_rec.cpython-312.pyc,,
+transformers/models/pp_ocrv5_mobile_rec/__pycache__/modular_pp_ocrv5_mobile_rec.cpython-312.pyc,,
+transformers/models/pp_ocrv5_mobile_rec/configuration_pp_ocrv5_mobile_rec.py,sha256=CfWNc7pobCIDXFFHRd01c7cgeRi6SxtwKMxuyW1DVyI,3998
+transformers/models/pp_ocrv5_mobile_rec/modeling_pp_ocrv5_mobile_rec.py,sha256=nsmE_qupub3b3RS3F36lWjMvujhbSuY2cDyBk0vBMy8,15879
+transformers/models/pp_ocrv5_mobile_rec/modular_pp_ocrv5_mobile_rec.py,sha256=70ho8-b7Zd3tI261bP7UjaAb6q-nrHaAvIRX_lHL1p4,2742
+transformers/models/pp_ocrv5_server_det/__init__.py,sha256=DN8vAhSY13Tv3c08qKb11JBBw3dI_aVl2V030i4nkTs,1075
+transformers/models/pp_ocrv5_server_det/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/pp_ocrv5_server_det/__pycache__/configuration_pp_ocrv5_server_det.cpython-312.pyc,,
+transformers/models/pp_ocrv5_server_det/__pycache__/image_processing_pp_ocrv5_server_det.cpython-312.pyc,,
+transformers/models/pp_ocrv5_server_det/__pycache__/modeling_pp_ocrv5_server_det.cpython-312.pyc,,
+transformers/models/pp_ocrv5_server_det/__pycache__/modular_pp_ocrv5_server_det.cpython-312.pyc,,
+transformers/models/pp_ocrv5_server_det/configuration_pp_ocrv5_server_det.py,sha256=N8NADtikMlWSKpQTiHstfpYJQRObN9MtbuLJ2rrOKpk,4563
+transformers/models/pp_ocrv5_server_det/image_processing_pp_ocrv5_server_det.py,sha256=k7p0tPNHzkYmVOI4nN01iGshyCPPHWJW3BCTwq5-rTY,17673
+transformers/models/pp_ocrv5_server_det/modeling_pp_ocrv5_server_det.py,sha256=3-w68PBvPrqpdeUb1XS6RE9feNhJ-cxeT7pt9kVAtmU,18270
+transformers/models/pp_ocrv5_server_det/modular_pp_ocrv5_server_det.py,sha256=t50rDem6qbUvJS-k5nXzyAq8xqtCtoSM7U_sDhS606g,36520
+transformers/models/pp_ocrv5_server_rec/__init__.py,sha256=qnQkVOP-GnHoLvAdGkmtRmUn98_Ow-6X0DFKMlhnOM8,1077
+transformers/models/pp_ocrv5_server_rec/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/pp_ocrv5_server_rec/__pycache__/configuration_pp_ocrv5_server_rec.cpython-312.pyc,,
+transformers/models/pp_ocrv5_server_rec/__pycache__/image_processing_pp_ocrv5_server_rec.cpython-312.pyc,,
+transformers/models/pp_ocrv5_server_rec/__pycache__/modeling_pp_ocrv5_server_rec.cpython-312.pyc,,
+transformers/models/pp_ocrv5_server_rec/__pycache__/modular_pp_ocrv5_server_rec.cpython-312.pyc,,
+transformers/models/pp_ocrv5_server_rec/configuration_pp_ocrv5_server_rec.py,sha256=Rg54LNoyN0nYzBPM_AGR9yAmIiUWvJyxUrpFqmIqF6g,3473
+transformers/models/pp_ocrv5_server_rec/image_processing_pp_ocrv5_server_rec.py,sha256=uUmiZMEgN-cpBnbMnR8r9VqbXqo-uj6beLyxyXPZZ4A,8030
+transformers/models/pp_ocrv5_server_rec/modeling_pp_ocrv5_server_rec.py,sha256=XJRILbuOL4xmcNS8oH6oabk-HKWBO0YubOq_lH2c-Rk,15283
+transformers/models/pp_ocrv5_server_rec/modular_pp_ocrv5_server_rec.py,sha256=L7ivGS9AAMnXG6fWq753l-g9-fhl02B6MbPkUREbDlo,17471
+transformers/models/pp_ocrv6_medium_det/__init__.py,sha256=F9dZZFIPUI-JeWCLmRWCwQ3ze3qYLeoroFG9tpC8ZIs,1021
+transformers/models/pp_ocrv6_medium_det/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/pp_ocrv6_medium_det/__pycache__/configuration_pp_ocrv6_medium_det.cpython-312.pyc,,
+transformers/models/pp_ocrv6_medium_det/__pycache__/modeling_pp_ocrv6_medium_det.cpython-312.pyc,,
+transformers/models/pp_ocrv6_medium_det/__pycache__/modular_pp_ocrv6_medium_det.cpython-312.pyc,,
+transformers/models/pp_ocrv6_medium_det/configuration_pp_ocrv6_medium_det.py,sha256=Pa42SoTMwIVsFLj86b9ksURW6T-eF-NCXR4It_e_0-w,4167
+transformers/models/pp_ocrv6_medium_det/modeling_pp_ocrv6_medium_det.py,sha256=S7J7FrBAVu4Ad5ORpJQ--ltcJ0XpQx5OmqZSQjsnEhA,16025
+transformers/models/pp_ocrv6_medium_det/modular_pp_ocrv6_medium_det.py,sha256=Fx3YKTZiWFrX6pOZhlEZG47jSLnLhLgM3XmbFw1J2PY,5107
+transformers/models/pp_ocrv6_small_det/__init__.py,sha256=CVWLx-JN-vcw7UArllDPYd64wAhEmxiTYISHq8-SYE0,1019
+transformers/models/pp_ocrv6_small_det/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/pp_ocrv6_small_det/__pycache__/configuration_pp_ocrv6_small_det.cpython-312.pyc,,
+transformers/models/pp_ocrv6_small_det/__pycache__/modeling_pp_ocrv6_small_det.cpython-312.pyc,,
+transformers/models/pp_ocrv6_small_det/__pycache__/modular_pp_ocrv6_small_det.cpython-312.pyc,,
+transformers/models/pp_ocrv6_small_det/configuration_pp_ocrv6_small_det.py,sha256=WApicWeWTGiWasbxo_Lkc8sDmu5bt7lsRxR5XwSOi1U,4210
+transformers/models/pp_ocrv6_small_det/modeling_pp_ocrv6_small_det.py,sha256=YG032nzgfkkWp_nnX2SiBsF7OSXCai7LMCcLoSN2prc,12537
+transformers/models/pp_ocrv6_small_det/modular_pp_ocrv6_small_det.py,sha256=ScYt6zXzSSnClhJSWaxbt5wbmY7OCfW-AhuT6ar2k3Y,6529
+transformers/models/pp_ocrv6_small_rec/__init__.py,sha256=daHJLDRF9zjB-dBzPBtQ5U-SA8yMCK5Bw7AUaH8WHEE,1019
+transformers/models/pp_ocrv6_small_rec/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/pp_ocrv6_small_rec/__pycache__/configuration_pp_ocrv6_small_rec.cpython-312.pyc,,
+transformers/models/pp_ocrv6_small_rec/__pycache__/image_processing_pp_ocrv6_small_rec.cpython-312.pyc,,
+transformers/models/pp_ocrv6_small_rec/__pycache__/modeling_pp_ocrv6_small_rec.cpython-312.pyc,,
+transformers/models/pp_ocrv6_small_rec/__pycache__/modular_pp_ocrv6_small_rec.cpython-312.pyc,,
+transformers/models/pp_ocrv6_small_rec/configuration_pp_ocrv6_small_rec.py,sha256=dXudWzORlPeBG0NmPmr37P8sl7LE3gOebDU6egroC-s,2912
+transformers/models/pp_ocrv6_small_rec/image_processing_pp_ocrv6_small_rec.py,sha256=lpP1UGBVJF1PHKS55ueOQsyHUP-5lGN9TqXL4BldDlU,8259
+transformers/models/pp_ocrv6_small_rec/modeling_pp_ocrv6_small_rec.py,sha256=SWYGvaZn_mGhTyY2s8RHWqONQEx_oXSIMgtrZPcF970,15325
+transformers/models/pp_ocrv6_small_rec/modular_pp_ocrv6_small_rec.py,sha256=v-nZKm4Lhv2gW1bUt7z_52XsNPHwJ-exHo5STQZ7I8A,8364
+transformers/models/pp_ocrv6_tiny_rec/__init__.py,sha256=aSvlHajrycDLbH70RRcHDiAZ-UcPuywE9QB3S58imxU,1017
+transformers/models/pp_ocrv6_tiny_rec/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/pp_ocrv6_tiny_rec/__pycache__/configuration_pp_ocrv6_tiny_rec.cpython-312.pyc,,
+transformers/models/pp_ocrv6_tiny_rec/__pycache__/modeling_pp_ocrv6_tiny_rec.cpython-312.pyc,,
+transformers/models/pp_ocrv6_tiny_rec/__pycache__/modular_pp_ocrv6_tiny_rec.cpython-312.pyc,,
+transformers/models/pp_ocrv6_tiny_rec/configuration_pp_ocrv6_tiny_rec.py,sha256=Q0hbmssoizzDaPE53XSKxtRTKyiqsiwhrMzfR3sA4ZU,2567
+transformers/models/pp_ocrv6_tiny_rec/modeling_pp_ocrv6_tiny_rec.py,sha256=MBozP-FCqNkc-a96Hqqu22W2Y403JuDmHDTbIjnQ4Qo,5737
+transformers/models/pp_ocrv6_tiny_rec/modular_pp_ocrv6_tiny_rec.py,sha256=urR0j-qBKCs2SG0yn8EIBNa87kp6o4vPK35WxHuPu6Q,4508
+transformers/models/prompt_depth_anything/__init__.py,sha256=Cn1pndt_P4RDvfbBvFSlyzNoQriMGo5Y4Bps8EkNY8s,1331
+transformers/models/prompt_depth_anything/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/prompt_depth_anything/__pycache__/configuration_prompt_depth_anything.cpython-312.pyc,,
+transformers/models/prompt_depth_anything/__pycache__/image_processing_pil_prompt_depth_anything.cpython-312.pyc,,
+transformers/models/prompt_depth_anything/__pycache__/image_processing_prompt_depth_anything.cpython-312.pyc,,
+transformers/models/prompt_depth_anything/__pycache__/modeling_prompt_depth_anything.cpython-312.pyc,,
+transformers/models/prompt_depth_anything/__pycache__/modular_prompt_depth_anything.cpython-312.pyc,,
+transformers/models/prompt_depth_anything/configuration_prompt_depth_anything.py,sha256=-vICZs3WiOniM0Aav4OXdFMj3wdxvI7MXxnJ8JolEik,5113
+transformers/models/prompt_depth_anything/image_processing_pil_prompt_depth_anything.py,sha256=cOBRp5Vyp94cTfnbP5H7CH2DhQhj2VNOSENStMOcp8o,12656
+transformers/models/prompt_depth_anything/image_processing_prompt_depth_anything.py,sha256=pntzTv_M6grmEnq_8WRhaSeTgw88EfbIwS95ovfEqyk,13551
+transformers/models/prompt_depth_anything/modeling_prompt_depth_anything.py,sha256=EDHWO5quvmyY5T6VfmuhqG_eor4fVHh77CrMV7OfygA,19697
+transformers/models/prompt_depth_anything/modular_prompt_depth_anything.py,sha256=eUpUP8zrImiLRyUUzOFc42hnhAnfIQDubUzGdiwjkL0,13003
+transformers/models/prophetnet/__init__.py,sha256=TYI21JDlj449kTgKAOtUBpuxVv5L_I70CDjofSZ627M,1044
+transformers/models/prophetnet/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/prophetnet/__pycache__/configuration_prophetnet.cpython-312.pyc,,
+transformers/models/prophetnet/__pycache__/modeling_prophetnet.cpython-312.pyc,,
+transformers/models/prophetnet/__pycache__/tokenization_prophetnet.cpython-312.pyc,,
+transformers/models/prophetnet/configuration_prophetnet.py,sha256=0Q7DZVj4fIURG2IL6skYgLwTZTzxphq58foILrLCnBc,3483
+transformers/models/prophetnet/modeling_prophetnet.py,sha256=wuR7dZ787v8D1xp6_KtAgJpVpNuV_JC05HMZYI2i3O0,86264
+transformers/models/prophetnet/tokenization_prophetnet.py,sha256=nPUW6PS_olcfRbKhJeNpHISbX_mf1ygEayGIwSEACIs,19845
+transformers/models/pvt/__init__.py,sha256=3anhWQYtSqjcJFI6XaTuH9Zg580wmzDbNxrqDJqGr-I,1071
+transformers/models/pvt/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/pvt/__pycache__/configuration_pvt.cpython-312.pyc,,
+transformers/models/pvt/__pycache__/image_processing_pil_pvt.cpython-312.pyc,,
+transformers/models/pvt/__pycache__/image_processing_pvt.cpython-312.pyc,,
+transformers/models/pvt/__pycache__/modeling_pvt.cpython-312.pyc,,
+transformers/models/pvt/configuration_pvt.py,sha256=asylhGt6uiXGvg_QeSzYG2vAV-XxxPmdVbKBHOxhtOg,3388
+transformers/models/pvt/image_processing_pil_pvt.py,sha256=oLPKkN6QKBMinfCr1utsb1EhXu6pj0jQ6vGwpdHyNrQ,1178
+transformers/models/pvt/image_processing_pvt.py,sha256=TAixzMZVwI_aKMD-SV2W3JL2lxrK2Vcf2adIWHf8ukw,1188
+transformers/models/pvt/modeling_pvt.py,sha256=lxYNiiOOAcLaEkkaZvQ9SHI6tU0uyUsANpat7WZ0T-I,22308
+transformers/models/pvt_v2/__init__.py,sha256=LkmqeLd7cZGKTFX_2d9_jU0sj_bDlML042kr_vMJTLw,993
+transformers/models/pvt_v2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/pvt_v2/__pycache__/configuration_pvt_v2.cpython-312.pyc,,
+transformers/models/pvt_v2/__pycache__/modeling_pvt_v2.cpython-312.pyc,,
+transformers/models/pvt_v2/configuration_pvt_v2.py,sha256=y3tPVKZ9QGDPhPMduKIwvZWlnWsi9aMR191qiVcO0bM,4102
+transformers/models/pvt_v2/modeling_pvt_v2.py,sha256=a_YNMMts8yRcm4qyJyK2p4piOuBvStG4v63cEvPdbCA,23445
+transformers/models/qianfan_ocr/__init__.py,sha256=sWTHYRQ2xYeH1iRW66oxskwZXLb2ia5ekTH_-QFLyPI,1045
+transformers/models/qianfan_ocr/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/qianfan_ocr/__pycache__/configuration_qianfan_ocr.cpython-312.pyc,,
+transformers/models/qianfan_ocr/__pycache__/modeling_qianfan_ocr.cpython-312.pyc,,
+transformers/models/qianfan_ocr/__pycache__/modular_qianfan_ocr.cpython-312.pyc,,
+transformers/models/qianfan_ocr/__pycache__/processing_qianfan_ocr.cpython-312.pyc,,
+transformers/models/qianfan_ocr/configuration_qianfan_ocr.py,sha256=lsugBI0-DdFiJxUbC11I5TYCPR31KgQcMTpF4QrBDek,5838
+transformers/models/qianfan_ocr/modeling_qianfan_ocr.py,sha256=e_1Jkn38IMckY2_Qt-CpKkuiri3DRLW0S1gxeawNDeo,36816
+transformers/models/qianfan_ocr/modular_qianfan_ocr.py,sha256=RvFvRbc6uaBvMLIy_zG2Hkh8K00Zn5aVjlYhech3al8,14144
+transformers/models/qianfan_ocr/processing_qianfan_ocr.py,sha256=R5AR3fkd6cW-j22yTb_RF7u_dWTkWJt6twrqyLMjWFY,11509
+transformers/models/qwen2/__init__.py,sha256=e49oEzErXujE0UVl_q_agf5XHzHES4vV2kLwmqdk2kg,1095
+transformers/models/qwen2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/qwen2/__pycache__/configuration_qwen2.cpython-312.pyc,,
+transformers/models/qwen2/__pycache__/modeling_qwen2.cpython-312.pyc,,
+transformers/models/qwen2/__pycache__/modular_qwen2.cpython-312.pyc,,
+transformers/models/qwen2/__pycache__/tokenization_qwen2.cpython-312.pyc,,
+transformers/models/qwen2/configuration_qwen2.py,sha256=KBmG_vM7LFImOJpHkRPrljyDNkZ-duG41J_T0Y7kqII,3435
+transformers/models/qwen2/modeling_qwen2.py,sha256=mfqYxWdmBM9u9QWJK3D9pcHEzYNZcUWfONYQkMzKseQ,21922
+transformers/models/qwen2/modular_qwen2.py,sha256=R0iFAJcmGJsaSJniccbRGpOg9TxnXwi874ZwKX4WP3E,7572
+transformers/models/qwen2/tokenization_qwen2.py,sha256=-sTmV2v-I2lzG-FHpOUw8mK98y8qxQQ2-W8Ni90vxig,3323
+transformers/models/qwen2_5_omni/__init__.py,sha256=YEDAlOoWmhkZ4L6lxmlVqVhe5A0P6aVSJNSziEFSN4E,1071
+transformers/models/qwen2_5_omni/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/qwen2_5_omni/__pycache__/configuration_qwen2_5_omni.cpython-312.pyc,,
+transformers/models/qwen2_5_omni/__pycache__/modeling_qwen2_5_omni.cpython-312.pyc,,
+transformers/models/qwen2_5_omni/__pycache__/modular_qwen2_5_omni.cpython-312.pyc,,
+transformers/models/qwen2_5_omni/__pycache__/processing_qwen2_5_omni.cpython-312.pyc,,
+transformers/models/qwen2_5_omni/configuration_qwen2_5_omni.py,sha256=ll5fmBifiqfSC1ptULzSkTl8ccVt2Q17cZ8aO5BBeC4,26181
+transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py,sha256=ACL2ca_nqTfo0MYHzPRWHzuG4krsTRNBAt7POcFhuUk,174122
+transformers/models/qwen2_5_omni/modular_qwen2_5_omni.py,sha256=wfFH6Xe1UBXUt6ZLqpxps08oWOzcCrVePp_jz3g-GOE,163424
+transformers/models/qwen2_5_omni/processing_qwen2_5_omni.py,sha256=BA7gf6_4rNFgSeA13GCNe4q11CHo06f6b01r8-BtAPc,17745
+transformers/models/qwen2_5_vl/__init__.py,sha256=8-dsgLIeeE3n90n6F0XOu-tBZ-80Wotz89pjZi5GqjQ,1065
+transformers/models/qwen2_5_vl/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/qwen2_5_vl/__pycache__/configuration_qwen2_5_vl.cpython-312.pyc,,
+transformers/models/qwen2_5_vl/__pycache__/modeling_qwen2_5_vl.cpython-312.pyc,,
+transformers/models/qwen2_5_vl/__pycache__/modular_qwen2_5_vl.cpython-312.pyc,,
+transformers/models/qwen2_5_vl/__pycache__/processing_qwen2_5_vl.cpython-312.pyc,,
+transformers/models/qwen2_5_vl/configuration_qwen2_5_vl.py,sha256=CFFgaA5uADhfObPkFOmBjH1FW8qi76ZncLi0As_ZtXE,8803
+transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py,sha256=jsjz62shvdjyTDC8VNvPEOqhbG9_Xjbn-f9qiPvQ5jA,77100
+transformers/models/qwen2_5_vl/modular_qwen2_5_vl.py,sha256=4QUNFK6LRX_qoxnImzP_dbXTCMwiy-yFbCEMMr_Lo6g,32388
+transformers/models/qwen2_5_vl/processing_qwen2_5_vl.py,sha256=RWMYdDoUcr3fNLZ2WusIoL0vyq4ixbz3qog6p_9pbTo,8130
+transformers/models/qwen2_audio/__init__.py,sha256=KaUmP3FK3GdeWvbunzyp1QjBki0USS4E80NlvhaJ3D8,1045
+transformers/models/qwen2_audio/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/qwen2_audio/__pycache__/configuration_qwen2_audio.cpython-312.pyc,,
+transformers/models/qwen2_audio/__pycache__/modeling_qwen2_audio.cpython-312.pyc,,
+transformers/models/qwen2_audio/__pycache__/processing_qwen2_audio.cpython-312.pyc,,
+transformers/models/qwen2_audio/configuration_qwen2_audio.py,sha256=OcTtNrzbiWocYDWfduzdXV4d-jVIshq-VSe7dwXRQKo,4612
+transformers/models/qwen2_audio/modeling_qwen2_audio.py,sha256=PzMStEtu5zRTBTWSyvoQ5VJAIInjj2uRxgDIwcAzGEg,40531
+transformers/models/qwen2_audio/processing_qwen2_audio.py,sha256=HNcynxm64NaFntXKua0rNVevmG9XtzaH12Ke9UH5lrc,9302
+transformers/models/qwen2_moe/__init__.py,sha256=TZM20WtUr1UyV-hDDgq5B-qFT4aUulMpjWwSUNdUs2w,999
+transformers/models/qwen2_moe/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/qwen2_moe/__pycache__/configuration_qwen2_moe.cpython-312.pyc,,
+transformers/models/qwen2_moe/__pycache__/modeling_qwen2_moe.cpython-312.pyc,,
+transformers/models/qwen2_moe/__pycache__/modular_qwen2_moe.cpython-312.pyc,,
+transformers/models/qwen2_moe/configuration_qwen2_moe.py,sha256=DXW1cwF3fIMRFkiVC5aFhT1AbIOjcwHwNmEwpElRWBM,4500
+transformers/models/qwen2_moe/modeling_qwen2_moe.py,sha256=SPpfAv_rOIGlWrBHxUdgD5n9DsrALAveuK0ALXavNE0,32439
+transformers/models/qwen2_moe/modular_qwen2_moe.py,sha256=ExwdwyMGY6OONVkE3LT8klNdP0NQMkf-RtBG-9ze3Wk,10904
+transformers/models/qwen2_vl/__init__.py,sha256=M_GXgDScVAgm6KRoHntqRt41aVC2g0C4UNTjJp8pIjM,1130
+transformers/models/qwen2_vl/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/qwen2_vl/__pycache__/configuration_qwen2_vl.cpython-312.pyc,,
+transformers/models/qwen2_vl/__pycache__/image_processing_pil_qwen2_vl.cpython-312.pyc,,
+transformers/models/qwen2_vl/__pycache__/image_processing_qwen2_vl.cpython-312.pyc,,
+transformers/models/qwen2_vl/__pycache__/modeling_qwen2_vl.cpython-312.pyc,,
+transformers/models/qwen2_vl/__pycache__/processing_qwen2_vl.cpython-312.pyc,,
+transformers/models/qwen2_vl/__pycache__/video_processing_qwen2_vl.cpython-312.pyc,,
+transformers/models/qwen2_vl/configuration_qwen2_vl.py,sha256=_07Q5gRdl2LQQyyo21UJM9Ce-6nuiIpuLe8R3n8DWBk,7079
+transformers/models/qwen2_vl/image_processing_pil_qwen2_vl.py,sha256=ik8bnuSN9gFsKPnjr_ZTiOxRP9c0THE9uMsSPHeKV6w,9903
+transformers/models/qwen2_vl/image_processing_qwen2_vl.py,sha256=8ZSXaFKBQCaR8ASaCrW-gIX5L7XDet_MaA5MzReGOnc,10732
+transformers/models/qwen2_vl/modeling_qwen2_vl.py,sha256=REVtUNrGYBLImU7XM17OCkREOQ2lF9u2rHzA7ZweG_s,72838
+transformers/models/qwen2_vl/processing_qwen2_vl.py,sha256=ouUS8TukPFKqcul3nfHypckBxwgZ3Wj7tp486yFK-U0,6258
+transformers/models/qwen2_vl/video_processing_qwen2_vl.py,sha256=PqYIBz1lwNVRZL1R64Kd394NyaTc75-Ht9cTMGJnLSo,14292
+transformers/models/qwen3/__init__.py,sha256=5JU8uO9x0AmJ-YjY36MxtbMKT_B38dLJkrnAwLyjcTY,1014
+transformers/models/qwen3/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/qwen3/__pycache__/configuration_qwen3.cpython-312.pyc,,
+transformers/models/qwen3/__pycache__/modeling_qwen3.cpython-312.pyc,,
+transformers/models/qwen3/__pycache__/modular_qwen3.cpython-312.pyc,,
+transformers/models/qwen3/configuration_qwen3.py,sha256=SdnM0PKczZd7k9uiAE-EuGeJGz0FCbcf2Lo-0BBU5k0,3624
+transformers/models/qwen3/modeling_qwen3.py,sha256=-9z-6xtUE1yme6ffkk2pL0smThJStRfuot6Ykonrrqs,23353
+transformers/models/qwen3/modular_qwen3.py,sha256=QR9DV4CfBCIU_cSA6EjZo_3BH2Kk_VfGg6DZOetgVR4,5711
+transformers/models/qwen3_5/__init__.py,sha256=4da9M8C_zn94Li0Yb4S8wOQvgmDqyFwQ0Wu3gIZlobU,1035
+transformers/models/qwen3_5/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/qwen3_5/__pycache__/configuration_qwen3_5.cpython-312.pyc,,
+transformers/models/qwen3_5/__pycache__/modeling_qwen3_5.cpython-312.pyc,,
+transformers/models/qwen3_5/__pycache__/modular_qwen3_5.cpython-312.pyc,,
+transformers/models/qwen3_5/__pycache__/tokenization_qwen3_5.cpython-312.pyc,,
+transformers/models/qwen3_5/configuration_qwen3_5.py,sha256=-dYzC8ZYNjMwFn-KiUPf9I8EBWbhqw8pbt2y_7Uk02c,7776
+transformers/models/qwen3_5/modeling_qwen3_5.py,sha256=OVQ5NB6luk3RTBA-gwODyqdWhs-va2k91--1hiIiTaY,93664
+transformers/models/qwen3_5/modular_qwen3_5.py,sha256=eyVwxGgUHGXPUcjEosZczrHO1l_QXN6Do2-4zyKFo-Y,28972
+transformers/models/qwen3_5/tokenization_qwen3_5.py,sha256=PS-Yq8HG7sYeRUgXEoa4j16Bc6xtY5VLj9Ilt-JM8lo,3127
+transformers/models/qwen3_5_moe/__init__.py,sha256=u611HCFpy5zFLNE9U0Ae0BcaT5gOja1Iw_b7M57Ksw0,1003
+transformers/models/qwen3_5_moe/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/qwen3_5_moe/__pycache__/configuration_qwen3_5_moe.cpython-312.pyc,,
+transformers/models/qwen3_5_moe/__pycache__/modeling_qwen3_5_moe.cpython-312.pyc,,
+transformers/models/qwen3_5_moe/__pycache__/modular_qwen3_5_moe.cpython-312.pyc,,
+transformers/models/qwen3_5_moe/configuration_qwen3_5_moe.py,sha256=UVAD02287QxHj0baDWVe6WckND7n115uJHSxD58gP44,8282
+transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py,sha256=9zip60bRNRp1HzahyuX3Q11YnowyGOcxUYJBnEwCMPE,102544
+transformers/models/qwen3_5_moe/modular_qwen3_5_moe.py,sha256=sZd62FUzdRO4azSxfTx8dXT5lwi-tAFtFwhvvXW4BGY,11568
+transformers/models/qwen3_moe/__init__.py,sha256=q5WfIniJecmOju3Lhy277H3Puu7viwc9vUhUWen3UZY,999
+transformers/models/qwen3_moe/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/qwen3_moe/__pycache__/configuration_qwen3_moe.cpython-312.pyc,,
+transformers/models/qwen3_moe/__pycache__/modeling_qwen3_moe.cpython-312.pyc,,
+transformers/models/qwen3_moe/__pycache__/modular_qwen3_moe.cpython-312.pyc,,
+transformers/models/qwen3_moe/configuration_qwen3_moe.py,sha256=0WHp3TexsgjdtAD6ZJ4rtBBWLcakWZR9d3I7UiWoCK8,4693
+transformers/models/qwen3_moe/modeling_qwen3_moe.py,sha256=8Hqxs6F-J2EgBqRHgSuDZnr3qz1Sev4-u9-J3F2sipA,31897
+transformers/models/qwen3_moe/modular_qwen3_moe.py,sha256=omFOX6Dq2HXhBaewjMa9PW5VLLyM86UGvR_b3CUX-24,7257
+transformers/models/qwen3_next/__init__.py,sha256=PuPvF5xcEfBxUKjqiZaWCiHeDeKuTmNdfuI6wvb-cbI,1001
+transformers/models/qwen3_next/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/qwen3_next/__pycache__/configuration_qwen3_next.cpython-312.pyc,,
+transformers/models/qwen3_next/__pycache__/modeling_qwen3_next.cpython-312.pyc,,
+transformers/models/qwen3_next/__pycache__/modular_qwen3_next.cpython-312.pyc,,
+transformers/models/qwen3_next/configuration_qwen3_next.py,sha256=21Kf2dVWw9lkbhvuWjSTqkzAW40zxR82TwThL9QIBdI,5420
+transformers/models/qwen3_next/modeling_qwen3_next.py,sha256=akyH-wpXy7BqoFpmnhqFQwaeTn36eW6H2WONZkmGOPg,52540
+transformers/models/qwen3_next/modular_qwen3_next.py,sha256=GuYzn-O2zuPQG6tmbQN01jSh543oiXG8lh5KENgjqbI,34192
+transformers/models/qwen3_omni_moe/__init__.py,sha256=6xE3okskjamaUt4t3k8qJeJWbTPvLH7MfEjmtKtCC3I,1077
+transformers/models/qwen3_omni_moe/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/qwen3_omni_moe/__pycache__/configuration_qwen3_omni_moe.cpython-312.pyc,,
+transformers/models/qwen3_omni_moe/__pycache__/modeling_qwen3_omni_moe.cpython-312.pyc,,
+transformers/models/qwen3_omni_moe/__pycache__/modular_qwen3_omni_moe.cpython-312.pyc,,
+transformers/models/qwen3_omni_moe/__pycache__/processing_qwen3_omni_moe.cpython-312.pyc,,
+transformers/models/qwen3_omni_moe/configuration_qwen3_omni_moe.py,sha256=730SVSvq9H1kIuLtrh9HIs5IVX0W30MHPNK199wUKoY,27730
+transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py,sha256=rNHBNqHkBKKTQoGWNo8znm5RZr7hN42AlTa1kwxm6x8,180694
+transformers/models/qwen3_omni_moe/modular_qwen3_omni_moe.py,sha256=4vjcOIPB7pPYql-ycfRsGhUo4BgI-kaQuljCD0jK74w,116239
+transformers/models/qwen3_omni_moe/processing_qwen3_omni_moe.py,sha256=UemRUr6_ZEf-AgtGsmZSy5pzXt0xPqft6eEN-QRlWgk,19130
+transformers/models/qwen3_vl/__init__.py,sha256=abVaeHwwKgL-3gVI3c5PSZfroZlU4TxEKXweDd75BXQ,1104
+transformers/models/qwen3_vl/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/qwen3_vl/__pycache__/configuration_qwen3_vl.cpython-312.pyc,,
+transformers/models/qwen3_vl/__pycache__/modeling_qwen3_vl.cpython-312.pyc,,
+transformers/models/qwen3_vl/__pycache__/modular_qwen3_vl.cpython-312.pyc,,
+transformers/models/qwen3_vl/__pycache__/processing_qwen3_vl.cpython-312.pyc,,
+transformers/models/qwen3_vl/__pycache__/video_processing_qwen3_vl.cpython-312.pyc,,
+transformers/models/qwen3_vl/configuration_qwen3_vl.py,sha256=TlGyp0zeJEyxEEBQTDDqeLfJM8wLQrGjlKhdgN2eXDw,6040
+transformers/models/qwen3_vl/modeling_qwen3_vl.py,sha256=85s2If6j91egHS4A69OivjUWt98wSNhio2WYirqfqZQ,74723
+transformers/models/qwen3_vl/modular_qwen3_vl.py,sha256=1sa9Ot7wNlFQHbELlCCla7o9FtBHUEiCY7TBhPV0Tn4,49512
+transformers/models/qwen3_vl/processing_qwen3_vl.py,sha256=rddnyl6VEeHbCmkJHVGx0LIHjIdNWe46WMR0i12QFKQ,9474
+transformers/models/qwen3_vl/video_processing_qwen3_vl.py,sha256=NvaqWlQRcufpfJBMB7zyM7aOt9T_WgrHEHLB9leox8w,11241
+transformers/models/qwen3_vl_moe/__init__.py,sha256=kZX59YLK-ZPItl-fKkUko_3uNM_QthuwE-rfzurn9iY,1028
+transformers/models/qwen3_vl_moe/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/qwen3_vl_moe/__pycache__/configuration_qwen3_vl_moe.cpython-312.pyc,,
+transformers/models/qwen3_vl_moe/__pycache__/modeling_qwen3_vl_moe.cpython-312.pyc,,
+transformers/models/qwen3_vl_moe/__pycache__/modular_qwen3_vl_moe.cpython-312.pyc,,
+transformers/models/qwen3_vl_moe/configuration_qwen3_vl_moe.py,sha256=ojH8VjTg94VlPNEp90P0EvtopSAsESuUfBgIALQIGQc,8165
+transformers/models/qwen3_vl_moe/modeling_qwen3_vl_moe.py,sha256=lNHo1C1DawFbVE-Fw0BHumrb5of3eV6QyKbCYOjO93c,84481
+transformers/models/qwen3_vl_moe/modular_qwen3_vl_moe.py,sha256=q9itQXQvVqtFhK_h5yCenRWc6ELJhNjc2craHUf3kY0,18161
+transformers/models/rag/__init__.py,sha256=IRUxwdcZdE-6fRnJUhqgl8bB_Iu2XaHUa2qDvdK8zMQ,1056
+transformers/models/rag/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/rag/__pycache__/configuration_rag.cpython-312.pyc,,
+transformers/models/rag/__pycache__/modeling_rag.cpython-312.pyc,,
+transformers/models/rag/__pycache__/retrieval_rag.cpython-312.pyc,,
+transformers/models/rag/__pycache__/tokenization_rag.cpython-312.pyc,,
+transformers/models/rag/configuration_rag.py,sha256=f_vfiiGKii9eXSg3l1XptEkDdqymP8O_8IjqiK7q7dg,6728
+transformers/models/rag/modeling_rag.py,sha256=0VNSBBGOHLP_EPbAHtr5f7PNYfsJJuA7d1zPNmywkNI,88583
+transformers/models/rag/retrieval_rag.py,sha256=IdJZDlBfLOdee2tzvDxMFxwwbY4oOk3-NIOvRjCPn9s,29742
+transformers/models/rag/tokenization_rag.py,sha256=tboHOP0AiAEM2O6S4Cjs-mGRn54z29D9ijWCGLXqF6E,2784
+transformers/models/recurrent_gemma/__init__.py,sha256=i86Cydx-eAdwsVMjNc0yG9hGxe_amyfAdvF5Eg-UCGM,1011
+transformers/models/recurrent_gemma/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/recurrent_gemma/__pycache__/configuration_recurrent_gemma.cpython-312.pyc,,
+transformers/models/recurrent_gemma/__pycache__/modeling_recurrent_gemma.cpython-312.pyc,,
+transformers/models/recurrent_gemma/configuration_recurrent_gemma.py,sha256=p8TuEieW_tTPzZjaX-FB8PP-FKIlfJYPz214vrRJ85E,4427
+transformers/models/recurrent_gemma/modeling_recurrent_gemma.py,sha256=BrE2_xWXKS41YfCOxNt_RKKMxMMeIA-QEi2NINam8RQ,35717
+transformers/models/reformer/__init__.py,sha256=hJ-mLQGtig9HdVaq2HBnpc5qAhWb4OBfjdidb55QBrY,1038
+transformers/models/reformer/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/reformer/__pycache__/configuration_reformer.cpython-312.pyc,,
+transformers/models/reformer/__pycache__/modeling_reformer.cpython-312.pyc,,
+transformers/models/reformer/__pycache__/tokenization_reformer.cpython-312.pyc,,
+transformers/models/reformer/configuration_reformer.py,sha256=SQGV1GltV6WXcpbENg8XUHXjEpZbSZWtW_pqPTER9ik,8366
+transformers/models/reformer/modeling_reformer.py,sha256=SXWDN-Oymdr2z7TzSYyaNL2qFogWsTIAnfb_4NGxAuM,113261
+transformers/models/reformer/tokenization_reformer.py,sha256=S-OLmGyWWs1rHVNnak0RBjE8v2_Q5ogvN0ZL5NGgIaQ,4326
+transformers/models/regnet/__init__.py,sha256=ycvH_P4FO9zOsxgrXAXAHtK7FXQCjUJz6EgwLH4JD9c,993
+transformers/models/regnet/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/regnet/__pycache__/configuration_regnet.cpython-312.pyc,,
+transformers/models/regnet/__pycache__/modeling_regnet.cpython-312.pyc,,
+transformers/models/regnet/configuration_regnet.py,sha256=jUd49pFKGNHTcL_MtFhKo780bsSd7Wygu6e04hjPdoA,2605
+transformers/models/regnet/modeling_regnet.py,sha256=mbVG6JDs89CkLYqXZRva_YE8l02NuKVLt1qfX0mAFjI,14327
+transformers/models/rembert/__init__.py,sha256=2-jjTgRWHbTKw873X9XGzooYrv9BlSSIvz7GcemXGbw,1035
+transformers/models/rembert/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/rembert/__pycache__/configuration_rembert.cpython-312.pyc,,
+transformers/models/rembert/__pycache__/modeling_rembert.cpython-312.pyc,,
+transformers/models/rembert/__pycache__/tokenization_rembert.cpython-312.pyc,,
+transformers/models/rembert/configuration_rembert.py,sha256=kD-YVPQr_rwk4U9q5DE2MjSFABjThk-oqhcE431PJN0,2374
+transformers/models/rembert/modeling_rembert.py,sha256=hc74c66XWtAc_LHF4rwWiXjGhH8K8phmOWROeJpdVnE,47858
+transformers/models/rembert/tokenization_rembert.py,sha256=KvTdia7SYOJ2yaOueM2y7oQdF3BSkD_SXTambhzVYb4,7808
+transformers/models/resnet/__init__.py,sha256=fvRmAOL_0o36oByTYgw9MmHL4wB20CHQ7h68S5fDazs,993
+transformers/models/resnet/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/resnet/__pycache__/configuration_resnet.cpython-312.pyc,,
+transformers/models/resnet/__pycache__/modeling_resnet.cpython-312.pyc,,
+transformers/models/resnet/configuration_resnet.py,sha256=kRk1nutscZolsHhMZP4lDIyUy-DSKoTuzxkD-IZ2LGI,3142
+transformers/models/resnet/modeling_resnet.py,sha256=Q1ZA986HgWL8v7zvH4OfT2pgqH8uUIRlxfN2zQKazJA,17021
+transformers/models/rf_detr/__init__.py,sha256=LygpQTBDfW47LNGiNpn3YQRYutfZPaufCZhJ513Fvno,1041
+transformers/models/rf_detr/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/rf_detr/__pycache__/configuration_rf_detr.cpython-312.pyc,,
+transformers/models/rf_detr/__pycache__/image_processing_rf_detr.cpython-312.pyc,,
+transformers/models/rf_detr/__pycache__/modeling_rf_detr.cpython-312.pyc,,
+transformers/models/rf_detr/__pycache__/modular_rf_detr.cpython-312.pyc,,
+transformers/models/rf_detr/configuration_rf_detr.py,sha256=DPqJGFCNgxqTPD7ZUuBiQ33njKw1rVd0--EHLqRO-yA,10851
+transformers/models/rf_detr/image_processing_rf_detr.py,sha256=mt2EAQZy_HexNk37kTDr-VgJDKNghYbWc0VYw2NTmyI,33433
+transformers/models/rf_detr/modeling_rf_detr.py,sha256=az1VKlz2KW0GuXp76Z31PDcwbYMlOcZJiFbZHMtmi24,100226
+transformers/models/rf_detr/modular_rf_detr.py,sha256=jRVlBo-ApddjmKHgT3Ft21i0KouZ8H_QJfMr5c2ecTI,72819
+transformers/models/roberta/__init__.py,sha256=L5plEsZ85q9ufY9TKiQoW0V0xzGOJ12WVI2dFHicq-k,1035
+transformers/models/roberta/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/roberta/__pycache__/configuration_roberta.cpython-312.pyc,,
+transformers/models/roberta/__pycache__/modeling_roberta.cpython-312.pyc,,
+transformers/models/roberta/__pycache__/modular_roberta.cpython-312.pyc,,
+transformers/models/roberta/__pycache__/tokenization_roberta.cpython-312.pyc,,
+transformers/models/roberta/__pycache__/tokenization_roberta_old.cpython-312.pyc,,
+transformers/models/roberta/configuration_roberta.py,sha256=wQI6ZfcyLCvG9Ec7Q4f-_qA1JBUXDt0R2QLbHM-PxRI,2131
+transformers/models/roberta/modeling_roberta.py,sha256=OslkLgvebxXmjGVlvNgds0c38MmPRBZMiKBIUzNu5sk,53520
+transformers/models/roberta/modular_roberta.py,sha256=HiM6kgP-RbxyqjdJT-p6CIL2fBm69fRJsT7YBekrNl8,31605
+transformers/models/roberta/tokenization_roberta.py,sha256=Y5CLVBJtUu7rSugjxvMsSb3B48GkPALEt0fjh1UW-aE,7378
+transformers/models/roberta/tokenization_roberta_old.py,sha256=0-oEwTRx5FxsyVcHmVeofxJpmzNU8qCJTKgwl23uMMg,10935
+transformers/models/roberta_prelayernorm/__init__.py,sha256=oZ3DNaebEY7KXvSEjkOGdDGHzqbtrqk0efDZ-sM3W2k,1021
+transformers/models/roberta_prelayernorm/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/roberta_prelayernorm/__pycache__/configuration_roberta_prelayernorm.cpython-312.pyc,,
+transformers/models/roberta_prelayernorm/__pycache__/modeling_roberta_prelayernorm.cpython-312.pyc,,
+transformers/models/roberta_prelayernorm/configuration_roberta_prelayernorm.py,sha256=56eMoMS0sPFOKoZ_kBPVsegJULBvM0EMkvz1CNKrOic,2442
+transformers/models/roberta_prelayernorm/modeling_roberta_prelayernorm.py,sha256=O-tGyMKAT99fYNQ-L65Toeb8MOJ_NY65gXM5IFJLKB8,57195
+transformers/models/roc_bert/__init__.py,sha256=4CveMGU-dY3nV4E6x-Xpb1jicRniwrPuSOrY8-SHIUI,1038
+transformers/models/roc_bert/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/roc_bert/__pycache__/configuration_roc_bert.cpython-312.pyc,,
+transformers/models/roc_bert/__pycache__/modeling_roc_bert.cpython-312.pyc,,
+transformers/models/roc_bert/__pycache__/tokenization_roc_bert.cpython-312.pyc,,
+transformers/models/roc_bert/configuration_roc_bert.py,sha256=fuZ0qbhNkU8F51lV8F5P1mYi6iA85BPb7nAzPhBERAc,3601
+transformers/models/roc_bert/modeling_roc_bert.py,sha256=U_vz_y0r-DnrpWONACVhZqcB9QhgAGurYm9IotuPcj8,73427
+transformers/models/roc_bert/tokenization_roc_bert.py,sha256=HGUL8avso6HH4kiyVYhQ33L2f2k2_2Pmggi0-f4G1sk,58670
+transformers/models/roformer/__init__.py,sha256=ujlqcOUcpfg7P3ICGkMw00Dv8Z7wldj-8ctGf8zmk4A,1084
+transformers/models/roformer/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/roformer/__pycache__/configuration_roformer.cpython-312.pyc,,
+transformers/models/roformer/__pycache__/modeling_roformer.cpython-312.pyc,,
+transformers/models/roformer/__pycache__/tokenization_roformer.cpython-312.pyc,,
+transformers/models/roformer/__pycache__/tokenization_utils.cpython-312.pyc,,
+transformers/models/roformer/configuration_roformer.py,sha256=3coyFmSs-JlSHnu2xieLxjrOxUaPx5TbbmyDeHga648,2479
+transformers/models/roformer/modeling_roformer.py,sha256=8yydBc0M9tch-qMwfJtXAY-111yNQCe_nGE6AAyUAeE,55658
+transformers/models/roformer/tokenization_roformer.py,sha256=OP7Z4HNkVPShy7llQuwDHfqyZTGshBo0IhwGZPlgyr8,6246
+transformers/models/roformer/tokenization_utils.py,sha256=n5oqaXLHh85OA7sRbcQ9VBYxQEV4Syy8l72Hy7gz0aU,2610
+transformers/models/rt_detr/__init__.py,sha256=o5RHklkVAcHrNI4PPdyOGCM1fS5qjGNKM3foHyoUj5E,1180
+transformers/models/rt_detr/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/rt_detr/__pycache__/configuration_rt_detr.cpython-312.pyc,,
+transformers/models/rt_detr/__pycache__/configuration_rt_detr_resnet.cpython-312.pyc,,
+transformers/models/rt_detr/__pycache__/image_processing_pil_rt_detr.cpython-312.pyc,,
+transformers/models/rt_detr/__pycache__/image_processing_rt_detr.cpython-312.pyc,,
+transformers/models/rt_detr/__pycache__/modeling_rt_detr.cpython-312.pyc,,
+transformers/models/rt_detr/__pycache__/modeling_rt_detr_resnet.cpython-312.pyc,,
+transformers/models/rt_detr/__pycache__/modular_rt_detr.cpython-312.pyc,,
+transformers/models/rt_detr/configuration_rt_detr.py,sha256=pFzfdkY-jh1JbYR4PHbaRinXf3S60Q3orM2xu38kHdM,9032
+transformers/models/rt_detr/configuration_rt_detr_resnet.py,sha256=Uqmjyo3WSPBLy19hswq5J8o_FRh3SHNvdxT0ivHxrnM,3538
+transformers/models/rt_detr/image_processing_pil_rt_detr.py,sha256=aBkdG0feqlO8yUzMaqbmEb_U9xE6yL_YVkmjKWE7VN0,25073
+transformers/models/rt_detr/image_processing_rt_detr.py,sha256=R64vDKJaJ2P09Csn6KJ2C8uwwu8H0PHpeqd5-SGfxVg,24476
+transformers/models/rt_detr/modeling_rt_detr.py,sha256=hH3fFaxp1GCKTModS5G36lCR28knaVH34wVCkV_Cge4,86697
+transformers/models/rt_detr/modeling_rt_detr_resnet.py,sha256=T28jxOxf0UE6AIrpEgMYqCTB4DGx2ZAEo0NW0X72Enw,15948
+transformers/models/rt_detr/modular_rt_detr.py,sha256=G2EjRgsmSRkCjJV8_aeJmn39dd1qQ6-ddVRazc7msNo,97792
+transformers/models/rt_detr_v2/__init__.py,sha256=7RL5U-hsGt3HQZ5SuWn8iZY_L166EYswBvaQXFRkzRc,1003
+transformers/models/rt_detr_v2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/rt_detr_v2/__pycache__/configuration_rt_detr_v2.cpython-312.pyc,,
+transformers/models/rt_detr_v2/__pycache__/modeling_rt_detr_v2.cpython-312.pyc,,
+transformers/models/rt_detr_v2/__pycache__/modular_rt_detr_v2.cpython-312.pyc,,
+transformers/models/rt_detr_v2/configuration_rt_detr_v2.py,sha256=mryVKchI2vRn090_OB8iqOgYM3t5flwb-CHyzvaBKYA,10448
+transformers/models/rt_detr_v2/modeling_rt_detr_v2.py,sha256=lHuqe8ysQ5s4RrM9acZbGjDIZoKmzwB1dWwpJG4MmrM,88756
+transformers/models/rt_detr_v2/modular_rt_detr_v2.py,sha256=671WqAW6v1klG9agAMAnB54QoGs5REYRAAaBwuWDgak,20934
+transformers/models/rwkv/__init__.py,sha256=HAiwEvW1j_xuHj_PbmN25srY9RtA1gLmN_0RWvAyG78,989
+transformers/models/rwkv/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/rwkv/__pycache__/configuration_rwkv.cpython-312.pyc,,
+transformers/models/rwkv/__pycache__/modeling_rwkv.cpython-312.pyc,,
+transformers/models/rwkv/configuration_rwkv.py,sha256=1mkUBFcz17DVwF6rXDr6gYEuvPwRN6PhEk-CQ337Hso,2809
+transformers/models/rwkv/modeling_rwkv.py,sha256=Q_WheF4J3bVPuOTn6e0QY4ZOUy-zjJYcENKHL7y78z4,32121
+transformers/models/sam/__init__.py,sha256=vjnQboLCQa96jLER7fe3zcUcX6DSt4fLVnz4hlucGrc,1105
+transformers/models/sam/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/sam/__pycache__/configuration_sam.cpython-312.pyc,,
+transformers/models/sam/__pycache__/image_processing_pil_sam.cpython-312.pyc,,
+transformers/models/sam/__pycache__/image_processing_sam.cpython-312.pyc,,
+transformers/models/sam/__pycache__/modeling_sam.cpython-312.pyc,,
+transformers/models/sam/__pycache__/processing_sam.cpython-312.pyc,,
+transformers/models/sam/configuration_sam.py,sha256=MILcq7n3bZZgNbwk4dMD532RvYjN9jOGEdbRmPi4kmY,7950
+transformers/models/sam/image_processing_pil_sam.py,sha256=lwagaUXFLEvoHA8tAcvcga6I8UU8eajNZacL237VPr4,31697
+transformers/models/sam/image_processing_sam.py,sha256=Ny3FiwOttqalJkiyaUoJjSwb6PcwA0xGGZav003ot_8,31623
+transformers/models/sam/modeling_sam.py,sha256=68SHa97hH0acEctO7t68sg-_nCDcvcjzIwA32LIUVMY,61318
+transformers/models/sam/processing_sam.py,sha256=hH49ghIKhju1NnWo0aq32kzktpUvcBu_5BA6_6oqMh4,12559
+transformers/models/sam2/__init__.py,sha256=4HpIf7ZEaq1K4HtpbxtS5a7HVx12xoftR_gjZGcq0Gc,1065
+transformers/models/sam2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/sam2/__pycache__/configuration_sam2.cpython-312.pyc,,
+transformers/models/sam2/__pycache__/image_processing_sam2.cpython-312.pyc,,
+transformers/models/sam2/__pycache__/modeling_sam2.cpython-312.pyc,,
+transformers/models/sam2/__pycache__/modular_sam2.cpython-312.pyc,,
+transformers/models/sam2/__pycache__/processing_sam2.cpython-312.pyc,,
+transformers/models/sam2/configuration_sam2.py,sha256=0jlpcyZPEbTLFtWxl5VDPVp5hAhLK4Wq-hXFngcNJ9I,12670
+transformers/models/sam2/image_processing_sam2.py,sha256=dlpz8Ni1_M6f_jpsYjU0uKtt9de_FcxQpNRoWS5Mzmk,28492
+transformers/models/sam2/modeling_sam2.py,sha256=fj7d1mx5HqyokzJkgxPf4VwYJTkfSrejWcC_k824be8,72857
+transformers/models/sam2/modular_sam2.py,sha256=EvtOjuffCPAX48uLEK7QrJ8L11m_fUvvAmS4XeBJb1w,63191
+transformers/models/sam2/processing_sam2.py,sha256=3B53-zcWIYe6X19WZDxx2-HQuJxEHJSXdmzUZjX35hs,22411
+transformers/models/sam2_video/__init__.py,sha256=WFP70wbKsoPQuuR0Aq6sMpFZ9m2cQJwNgdCpngg4C1o,1089
+transformers/models/sam2_video/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/sam2_video/__pycache__/configuration_sam2_video.cpython-312.pyc,,
+transformers/models/sam2_video/__pycache__/modeling_sam2_video.cpython-312.pyc,,
+transformers/models/sam2_video/__pycache__/modular_sam2_video.cpython-312.pyc,,
+transformers/models/sam2_video/__pycache__/processing_sam2_video.cpython-312.pyc,,
+transformers/models/sam2_video/__pycache__/video_processing_sam2_video.cpython-312.pyc,,
+transformers/models/sam2_video/configuration_sam2_video.py,sha256=9U8AxN8iF8tHInvs26aAaQdBcUsmGf2URhkOOUpTZfs,13820
+transformers/models/sam2_video/modeling_sam2_video.py,sha256=hyTT9M82nfUMqaGXDK6Ifwz5JDwZ3cUgXOeU1w9Hx0U,133748
+transformers/models/sam2_video/modular_sam2_video.py,sha256=X7xYoBJjcDBNfmDBYKD3Td3a1y7B5QB8vxSS1VOqXEc,120861
+transformers/models/sam2_video/processing_sam2_video.py,sha256=87Qw8x3OL9lhAKAz85q4RhbipVuZfSBzKQokDpZJzXQ,37447
+transformers/models/sam2_video/video_processing_sam2_video.py,sha256=TZt4Yd149iJBA2wXH8IqkxHEATRZJAom5bE2UxY-0MQ,4868
+transformers/models/sam3/__init__.py,sha256=1VPaUvaBBzkrxMHEMbtWIFr5V5feABrgcg58LCAsGDE,1065
+transformers/models/sam3/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/sam3/__pycache__/configuration_sam3.cpython-312.pyc,,
+transformers/models/sam3/__pycache__/image_processing_sam3.cpython-312.pyc,,
+transformers/models/sam3/__pycache__/modeling_sam3.cpython-312.pyc,,
+transformers/models/sam3/__pycache__/modular_sam3.cpython-312.pyc,,
+transformers/models/sam3/__pycache__/processing_sam3.cpython-312.pyc,,
+transformers/models/sam3/configuration_sam3.py,sha256=qUgOlIvP-tj-3tIixuLW0mcz3iqplUVz6k9VuM-QAo0,10873
+transformers/models/sam3/image_processing_sam3.py,sha256=9IY3zhXS3g4ClfAE84KRRngWnCpw8g1GLVZpLy9kx7M,38759
+transformers/models/sam3/modeling_sam3.py,sha256=PTBFfUyJnrkGXtRNYUqQKALcVYdTZh6A-tBjtCjg1ME,102306
+transformers/models/sam3/modular_sam3.py,sha256=XU8_33IyJ3zpPGTqpa1e3vIPfxU-krLGM8pRWDolun0,11303
+transformers/models/sam3/processing_sam3.py,sha256=yMki9pd4kWsU-05d_lRcsF5aZl4YvGErZZ6BdhKlnjw,28428
+transformers/models/sam3_lite_text/__init__.py,sha256=a1MY8pfoG34RSMHZW1ef38S84JCnmbZfnn8ysvcSQN0,1010
+transformers/models/sam3_lite_text/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/sam3_lite_text/__pycache__/configuration_sam3_lite_text.cpython-312.pyc,,
+transformers/models/sam3_lite_text/__pycache__/modeling_sam3_lite_text.cpython-312.pyc,,
+transformers/models/sam3_lite_text/__pycache__/modular_sam3_lite_text.cpython-312.pyc,,
+transformers/models/sam3_lite_text/configuration_sam3_lite_text.py,sha256=eRouNQXpy13DOaXNC1smhTny3PtnEDmczTTRTtDqWkM,9253
+transformers/models/sam3_lite_text/modeling_sam3_lite_text.py,sha256=BaitXiLbVPwVyeQYC9Gg4aiK4tF5AzStm9cESr7VrfY,94557
+transformers/models/sam3_lite_text/modular_sam3_lite_text.py,sha256=NfWH1dA5sv0NhXsqwDaWR-PPyvf_40w-dDBuzjGm-KA,17721
+transformers/models/sam3_tracker/__init__.py,sha256=TPRKgIS2Z6Wq8WTVACG7_2akZcTNqFNnBYeDOjZF2Aw,1049
+transformers/models/sam3_tracker/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/sam3_tracker/__pycache__/configuration_sam3_tracker.cpython-312.pyc,,
+transformers/models/sam3_tracker/__pycache__/modeling_sam3_tracker.cpython-312.pyc,,
+transformers/models/sam3_tracker/__pycache__/modular_sam3_tracker.cpython-312.pyc,,
+transformers/models/sam3_tracker/__pycache__/processing_sam3_tracker.cpython-312.pyc,,
+transformers/models/sam3_tracker/configuration_sam3_tracker.py,sha256=LfojKhvfdVNc07Rx-jg_JbAwKLBMVnYAKxnLBf_eN58,7269
+transformers/models/sam3_tracker/modeling_sam3_tracker.py,sha256=WsQ7n-Nk2D-xhJN1znVPzIudXdydpqqh1KqwHWWSJ9g,53527
+transformers/models/sam3_tracker/modular_sam3_tracker.py,sha256=VRtPCdsRUEPqUwMLoBL2_TYy3wSSxP6f0_mi6RdwWrM,8116
+transformers/models/sam3_tracker/processing_sam3_tracker.py,sha256=-YcngBfiBJGyd9oq8QQv7XpoNFDS6oWo0lBRzoUyyiY,23144
+transformers/models/sam3_tracker_video/__init__.py,sha256=WEogj5NnwI_O925jgVstv_dAiSqHq1pPTmkWWxGzOiY,1067
+transformers/models/sam3_tracker_video/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/sam3_tracker_video/__pycache__/configuration_sam3_tracker_video.cpython-312.pyc,,
+transformers/models/sam3_tracker_video/__pycache__/modeling_sam3_tracker_video.cpython-312.pyc,,
+transformers/models/sam3_tracker_video/__pycache__/modular_sam3_tracker_video.cpython-312.pyc,,
+transformers/models/sam3_tracker_video/__pycache__/processing_sam3_tracker_video.cpython-312.pyc,,
+transformers/models/sam3_tracker_video/configuration_sam3_tracker_video.py,sha256=yAdih-3v2N22zfLXb3A3r9vb0IL7VSM3GbEmouWV3tA,15116
+transformers/models/sam3_tracker_video/modeling_sam3_tracker_video.py,sha256=oY_FN0Pu8lEmYy3EQKMRqWlKKFfPuJQN40FBYGvhyko,135204
+transformers/models/sam3_tracker_video/modular_sam3_tracker_video.py,sha256=zij3ulcWr-qLuEkdvVXQEojQ9faQQe4TnS9SrakvYqs,21204
+transformers/models/sam3_tracker_video/processing_sam3_tracker_video.py,sha256=4JC7q7aXLBr1kUdhPiAbVvxyR7Hs-oEm5dJ-9KDmaOo,37541
+transformers/models/sam3_video/__init__.py,sha256=-FBW7aAvRRXbmSCE0NRCcjbgaStvq1lgOn4h8-7ZbGE,1042
+transformers/models/sam3_video/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/sam3_video/__pycache__/configuration_sam3_video.cpython-312.pyc,,
+transformers/models/sam3_video/__pycache__/modeling_sam3_video.cpython-312.pyc,,
+transformers/models/sam3_video/__pycache__/processing_sam3_video.cpython-312.pyc,,
+transformers/models/sam3_video/configuration_sam3_video.py,sha256=5f58Z3suekpfZNzCOo9TjfCET4WUB1RBxSO3Sx5dsds,9315
+transformers/models/sam3_video/modeling_sam3_video.py,sha256=dDMvQ2hXGrpNMyKXkxJj4z3uMTjlm49JZTiLaUy8s1g,92966
+transformers/models/sam3_video/processing_sam3_video.py,sha256=TCTPLwLYtn3dQl8sdFJ0gOZjw9Xw_B3Gx8xVaXvtSPY,17822
+transformers/models/sam_hq/__init__.py,sha256=4B3IBWfFKvM9GThbmIj6Ig-KAUbOquWgv0RW3QvNjxM,1030
+transformers/models/sam_hq/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/sam_hq/__pycache__/configuration_sam_hq.cpython-312.pyc,,
+transformers/models/sam_hq/__pycache__/modeling_sam_hq.cpython-312.pyc,,
+transformers/models/sam_hq/__pycache__/modular_sam_hq.cpython-312.pyc,,
+transformers/models/sam_hq/__pycache__/processing_sam_hq.cpython-312.pyc,,
+transformers/models/sam_hq/configuration_sam_hq.py,sha256=didMNZArhllnj6Ooq4PyIU42BHpW-cqzBnQLeXietBk,8024
+transformers/models/sam_hq/modeling_sam_hq.py,sha256=hZ5LnWB-H1oIy3xQGnNIu4iNMWBYMFfy5bHRmjVJ1Vw,68933
+transformers/models/sam_hq/modular_sam_hq.py,sha256=aZ0dTo8351Sq0dD-G7iKmr193mKwDG_EO7HSBu5wps4,28014
+transformers/models/sam_hq/processing_sam_hq.py,sha256=d3HkKI9FLzK7w9BIbXXU7-v6bRrcJuJb1c1kBSthARs,13391
+transformers/models/sapiens2/__init__.py,sha256=WBHMRsTRQuLs3zoXVr_ca8QGKDs3atgVHGdei6U-TQ8,1043
+transformers/models/sapiens2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/sapiens2/__pycache__/configuration_sapiens2.cpython-312.pyc,,
+transformers/models/sapiens2/__pycache__/image_processing_sapiens2.cpython-312.pyc,,
+transformers/models/sapiens2/__pycache__/modeling_sapiens2.cpython-312.pyc,,
+transformers/models/sapiens2/__pycache__/modular_sapiens2.cpython-312.pyc,,
+transformers/models/sapiens2/configuration_sapiens2.py,sha256=jlhkXV-9XfSTI43dhhF83SY26ZJU2aMJpAFArXff_dQ,13446
+transformers/models/sapiens2/image_processing_sapiens2.py,sha256=gOyooaqSea9VlrT8BoRJIK5gPRWAnedQW6q7VNnBPaE,44273
+transformers/models/sapiens2/modeling_sapiens2.py,sha256=PuMhCsFkwQ_7PTjluyW4kVs-mBFgX_a0wfg5oncvvhc,60736
+transformers/models/sapiens2/modular_sapiens2.py,sha256=6VDQbc5jVzVagZpDh-dkplvzAioI25hjD1KI_9geHzY,88882
+transformers/models/seamless_m4t/__init__.py,sha256=aGTGuFUq4FqWWVcwKaf0ehT4bQpECvqA5V0Tcrm1WtY,1144
+transformers/models/seamless_m4t/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/seamless_m4t/__pycache__/configuration_seamless_m4t.cpython-312.pyc,,
+transformers/models/seamless_m4t/__pycache__/feature_extraction_seamless_m4t.cpython-312.pyc,,
+transformers/models/seamless_m4t/__pycache__/modeling_seamless_m4t.cpython-312.pyc,,
+transformers/models/seamless_m4t/__pycache__/processing_seamless_m4t.cpython-312.pyc,,
+transformers/models/seamless_m4t/__pycache__/tokenization_seamless_m4t.cpython-312.pyc,,
+transformers/models/seamless_m4t/configuration_seamless_m4t.py,sha256=E7dg-Y81I5yMfLjXnqQVsR4FmugiCfvrXl_kghISYHg,13729
+transformers/models/seamless_m4t/feature_extraction_seamless_m4t.py,sha256=WivktIwNAFGVIITYRJ6Wm_vuU5zso8QHMrq1IWj3ItY,13477
+transformers/models/seamless_m4t/modeling_seamless_m4t.py,sha256=4s98DeLN11zskaXeyod6ogS12jxOl383QhMNVtmO7H4,184737
+transformers/models/seamless_m4t/processing_seamless_m4t.py,sha256=S7sWW_Ce-nzRLlkziyqfZ3G8E6iw3yjSVfmsEOV9-NY,3119
+transformers/models/seamless_m4t/tokenization_seamless_m4t.py,sha256=abW0ypMlSxwi08aygOfipsvezAWAI0JSpzZriwGGusk,18201
+transformers/models/seamless_m4t_v2/__init__.py,sha256=mMY04PBMrOwTIQLq01RHqZjssvrSYl3UDhP5Y5vFifs,1011
+transformers/models/seamless_m4t_v2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/seamless_m4t_v2/__pycache__/configuration_seamless_m4t_v2.cpython-312.pyc,,
+transformers/models/seamless_m4t_v2/__pycache__/modeling_seamless_m4t_v2.cpython-312.pyc,,
+transformers/models/seamless_m4t_v2/configuration_seamless_m4t_v2.py,sha256=ls94QuI9upoPeVA_UeV9zFt5vo-k3jgtIFGqaZ7vArg,14248
+transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py,sha256=55hrmysRd0o-kB8FwgN6fUgaqVHRVt7PlCWLtSm4tJo,202680
+transformers/models/seed_oss/__init__.py,sha256=ukqpfG-W3jFJvA9UiL5bI_2jl_CTZFynUL0Tq9WD63M,1025
+transformers/models/seed_oss/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/seed_oss/__pycache__/configuration_seed_oss.cpython-312.pyc,,
+transformers/models/seed_oss/__pycache__/modeling_seed_oss.cpython-312.pyc,,
+transformers/models/seed_oss/__pycache__/modular_seed_oss.cpython-312.pyc,,
+transformers/models/seed_oss/configuration_seed_oss.py,sha256=gGRuNxRdPT0PREFR6GdlSCESjQiMXfooVzVzHMCieio,3393
+transformers/models/seed_oss/modeling_seed_oss.py,sha256=gmUoNTu3agbO1_fNNwj9om347z4-w71wuFrpFFYssQI,22400
+transformers/models/seed_oss/modular_seed_oss.py,sha256=BJdLX1PSL810SD0tx2i3Rvzhv7FmuMb4pqVBy-DgsLA,7269
+transformers/models/segformer/__init__.py,sha256=b2SyLppDm5PNYt7sPihm_sWiZ9k6q8zOEzdWq-FegHk,1095
+transformers/models/segformer/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/segformer/__pycache__/configuration_segformer.cpython-312.pyc,,
+transformers/models/segformer/__pycache__/image_processing_pil_segformer.cpython-312.pyc,,
+transformers/models/segformer/__pycache__/image_processing_segformer.cpython-312.pyc,,
+transformers/models/segformer/__pycache__/modeling_segformer.cpython-312.pyc,,
+transformers/models/segformer/__pycache__/modular_segformer.cpython-312.pyc,,
+transformers/models/segformer/configuration_segformer.py,sha256=Cq-e_cpims3EPZGH6K16Ck7aZc4dvzeJZSopKjNf1Es,3261
+transformers/models/segformer/image_processing_pil_segformer.py,sha256=ieoLy1VrwSO4iGJKnig7P6ZNPi6M7pvRj0HJP2yl5bI,8906
+transformers/models/segformer/image_processing_segformer.py,sha256=S7gN7Fs3CJlMhcOJhRLQB8nEJtw6_-IPkB7v1uAXVes,10284
+transformers/models/segformer/modeling_segformer.py,sha256=JiFw_Z32jFq5uepLvgwZ68i2OXbIWhq9F0axH5BVT7I,26735
+transformers/models/segformer/modular_segformer.py,sha256=8C4Y-ZeWmasTBAG-idgxBnX0lIfH2jwcs-SwDNGUgQo,32178
+transformers/models/seggpt/__init__.py,sha256=OXJkee36qaq5j3neB1rm8YRkYcw19GdErm3BQMak0sg,1083
+transformers/models/seggpt/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/seggpt/__pycache__/configuration_seggpt.cpython-312.pyc,,
+transformers/models/seggpt/__pycache__/image_processing_pil_seggpt.cpython-312.pyc,,
+transformers/models/seggpt/__pycache__/image_processing_seggpt.cpython-312.pyc,,
+transformers/models/seggpt/__pycache__/modeling_seggpt.cpython-312.pyc,,
+transformers/models/seggpt/configuration_seggpt.py,sha256=fP7cQYKWP9JhBurNE7hMRbBdaInvfCtaEJ93VGZKGNY,3563
+transformers/models/seggpt/image_processing_pil_seggpt.py,sha256=GuFbbefOH2662PG52yGx2ybXakJtDobO8moA1lqlpiY,12302
+transformers/models/seggpt/image_processing_seggpt.py,sha256=U8L-LtAuHhifnhLuYBDx2Y3mS_-j6KgGOemglV9DDfk,13827
+transformers/models/seggpt/modeling_seggpt.py,sha256=BiRIgjBamlVXQpB9pGf0QQwGv5u86rCW5XDDjuDxORg,43201
+transformers/models/sew/__init__.py,sha256=POCF36ZRa_dr7oQhkDU2X17bsZuLoWI5V8DSihqr_vU,987
+transformers/models/sew/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/sew/__pycache__/configuration_sew.cpython-312.pyc,,
+transformers/models/sew/__pycache__/modeling_sew.cpython-312.pyc,,
+transformers/models/sew/__pycache__/modular_sew.cpython-312.pyc,,
+transformers/models/sew/configuration_sew.py,sha256=xMiuPYKkctcJvo2wyH4SIbZ3GoX1ymrEaapTdv2Q44c,9645
+transformers/models/sew/modeling_sew.py,sha256=l2pKnxT6iGdyuWD0s0rK_fuqxHiIuAVZwQqvwl2cyv8,46157
+transformers/models/sew/modular_sew.py,sha256=3JiVlePxZ3UuU6pvE_Q1qudx2ojoivv2HybxZW3W7Hc,18362
+transformers/models/sew_d/__init__.py,sha256=zE9sw10e_a1d-8-Jsb75z5frCjkFGD0dZMHAXiNgGwk,991
+transformers/models/sew_d/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/sew_d/__pycache__/configuration_sew_d.cpython-312.pyc,,
+transformers/models/sew_d/__pycache__/modeling_sew_d.cpython-312.pyc,,
+transformers/models/sew_d/configuration_sew_d.py,sha256=W9EZYhVnjSbUO4s7jH7-6CBA5Uyd1KliQvfHvLKzzeg,10913
+transformers/models/sew_d/modeling_sew_d.py,sha256=3QIFcTuUPQ3FNScVy3WxrUzlzn2LJyiY3vhW8y3acbo,67568
+transformers/models/shieldgemma2/__init__.py,sha256=B7eqFJSWi0p49QNvKqUGR8NPyFjQuMdBANevIjTsSxw,1048
+transformers/models/shieldgemma2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/shieldgemma2/__pycache__/configuration_shieldgemma2.cpython-312.pyc,,
+transformers/models/shieldgemma2/__pycache__/modeling_shieldgemma2.cpython-312.pyc,,
+transformers/models/shieldgemma2/__pycache__/processing_shieldgemma2.cpython-312.pyc,,
+transformers/models/shieldgemma2/configuration_shieldgemma2.py,sha256=moUQpbm_I5XX9ApwruF5ZgpiYD2FBwwH6oIxofR6_78,3707
+transformers/models/shieldgemma2/modeling_shieldgemma2.py,sha256=X9QRljEWSxq30BWQem9lUzE6Tju2rkmAtpXAlvCbRF4,5546
+transformers/models/shieldgemma2/processing_shieldgemma2.py,sha256=Sti_EJS7lbvJq3yWknpsHbd4Ywss8ir3jOW-HW2CTLY,8428
+transformers/models/siglip/__init__.py,sha256=yG16CW0aC80MP6zty-VZLBxykk_5nwjk97iZaurlR70,1159
+transformers/models/siglip/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/siglip/__pycache__/configuration_siglip.cpython-312.pyc,,
+transformers/models/siglip/__pycache__/image_processing_pil_siglip.cpython-312.pyc,,
+transformers/models/siglip/__pycache__/image_processing_siglip.cpython-312.pyc,,
+transformers/models/siglip/__pycache__/modeling_siglip.cpython-312.pyc,,
+transformers/models/siglip/__pycache__/processing_siglip.cpython-312.pyc,,
+transformers/models/siglip/__pycache__/tokenization_siglip.cpython-312.pyc,,
+transformers/models/siglip/configuration_siglip.py,sha256=CkAupUUqFSetVPUzmIl3RUloj1-EAorzCXm9vEsyIG4,5507
+transformers/models/siglip/image_processing_pil_siglip.py,sha256=Yf8E3BMcUm3V5ji8Ktd4zBGGmJ9HRQe9O_c2jqCfVME,1288
+transformers/models/siglip/image_processing_siglip.py,sha256=9xau3MNebicWYuG-532VRvzzFVpsa9FmhyqHVA6FPEw,1298
+transformers/models/siglip/modeling_siglip.py,sha256=J06v25v_mWB_FetMT7b8RyVrBzWIB2U7qkhTnRM3azE,36056
+transformers/models/siglip/processing_siglip.py,sha256=aOQ5MSoMpf_MFh1vt2truSm1Y0oFpHCSZX77G1oRUIc,915
+transformers/models/siglip/tokenization_siglip.py,sha256=CmnaWyjLTBJ5p5DnFcfNAGz9yQ119FPZ0jUc-4RE9Ho,14286
+transformers/models/siglip2/__init__.py,sha256=Mhb5YVFzKvlVemVVe1FRpmzZprYSfYAAMNkbgUw0jvE,1165
+transformers/models/siglip2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/siglip2/__pycache__/configuration_siglip2.cpython-312.pyc,,
+transformers/models/siglip2/__pycache__/image_processing_pil_siglip2.cpython-312.pyc,,
+transformers/models/siglip2/__pycache__/image_processing_siglip2.cpython-312.pyc,,
+transformers/models/siglip2/__pycache__/modeling_siglip2.cpython-312.pyc,,
+transformers/models/siglip2/__pycache__/modular_siglip2.cpython-312.pyc,,
+transformers/models/siglip2/__pycache__/processing_siglip2.cpython-312.pyc,,
+transformers/models/siglip2/__pycache__/tokenization_siglip2.cpython-312.pyc,,
+transformers/models/siglip2/configuration_siglip2.py,sha256=H7zCFPGe5w02DJ4C49dOIygNZsGABV0zs9EGPKCRPAg,6674
+transformers/models/siglip2/image_processing_pil_siglip2.py,sha256=ms6ZB4yrJEChFLIT8JYckb4YCCZncCK_x7omyQ5jKMM,7790
+transformers/models/siglip2/image_processing_siglip2.py,sha256=YToOnL4gwWJprE2ke5s8_WNVMDmJHf0zNZRSgMnASMo,7659
+transformers/models/siglip2/modeling_siglip2.py,sha256=UQrbHC2nbSsfxstfyTWAhKMDwVePBpFwD_TPJPhCeMc,41340
+transformers/models/siglip2/modular_siglip2.py,sha256=Qv8lhYhgQUP-z5m4SsVW8EaDi0hZfrdrnhRQcZ1QsCE,23068
+transformers/models/siglip2/processing_siglip2.py,sha256=JIEHRW0qhiZyc7jxo52jeIVyNhuCegfXPYN-aN-gxBk,1315
+transformers/models/siglip2/tokenization_siglip2.py,sha256=zeBTm8JyDCQSeMhch6QdUEz7_S-NlsxxX-_uauXT2dc,3910
+transformers/models/slanet/__init__.py,sha256=U_2J5LjW4_SY2Y3XmWhovSVQvB6pZZvVhLH4p7F8a6U,994
+transformers/models/slanet/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/slanet/__pycache__/configuration_slanet.cpython-312.pyc,,
+transformers/models/slanet/__pycache__/modeling_slanet.cpython-312.pyc,,
+transformers/models/slanet/__pycache__/modular_slanet.cpython-312.pyc,,
+transformers/models/slanet/configuration_slanet.py,sha256=h1UcwInJYCZBsnfOBXyvSEPP4owpOnJwjXj3tRrgrZA,3631
+transformers/models/slanet/modeling_slanet.py,sha256=oKKQI4NBTaEHWdViJf2dOtJ9A3QnEiD6s4yqd0Wa1Tc,18450
+transformers/models/slanet/modular_slanet.py,sha256=pR9HOlsxEe9c3DRvrl0dR_-hMyJVfa6-RjLpCfjmXn0,13799
+transformers/models/slanext/__init__.py,sha256=g8zmwTucqfVTm6tcOUfa-5wU9K4s0ZyOGd072sA1iUI,1040
+transformers/models/slanext/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/slanext/__pycache__/configuration_slanext.cpython-312.pyc,,
+transformers/models/slanext/__pycache__/image_processing_slanext.cpython-312.pyc,,
+transformers/models/slanext/__pycache__/modeling_slanext.cpython-312.pyc,,
+transformers/models/slanext/__pycache__/modular_slanext.cpython-312.pyc,,
+transformers/models/slanext/configuration_slanext.py,sha256=Ew95N0YfU5YkLqKkd3H49b2xBYD_pfs3CvtFqU7KzgE,4795
+transformers/models/slanext/image_processing_slanext.py,sha256=Gry7tZ2i4Ber1zO8FQpZOmf4O69CeB0s2BWyjLwbZ-c,12559
+transformers/models/slanext/modeling_slanext.py,sha256=Ejpe66EsdyonZMK1wdPNhHVy84SYtF_ga7WqjGUS89w,28209
+transformers/models/slanext/modular_slanext.py,sha256=ei2ErdTjsx0Xh8C_lfsOzY2y8w5vvvizCwUv16jVwVI,23474
+transformers/models/smollm3/__init__.py,sha256=BZA2MiDpGmv2swg1yO14tkgi_SZ0yVg8ndr-PJwY-fI,1000
+transformers/models/smollm3/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/smollm3/__pycache__/configuration_smollm3.cpython-312.pyc,,
+transformers/models/smollm3/__pycache__/modeling_smollm3.cpython-312.pyc,,
+transformers/models/smollm3/__pycache__/modular_smollm3.cpython-312.pyc,,
+transformers/models/smollm3/configuration_smollm3.py,sha256=6k89-bT6HXu8JcW8xfksV9XN79MNt7jsGYG1j1YwF-I,5006
+transformers/models/smollm3/modeling_smollm3.py,sha256=XuzRjSYU5uDIfOTeW4-jqY77Sik5ElXgXpoggkBdDwY,22862
+transformers/models/smollm3/modular_smollm3.py,sha256=HTUWcIk0CyFPuH8mI8Wms4xn9h-c6fXz2I3FzPr4MmU,7626
+transformers/models/smolvlm/__init__.py,sha256=3gCkQVwjbOz3jRDBtj_mN9Rwo5Nvy-x9KfGga1ge70U,1125
+transformers/models/smolvlm/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/smolvlm/__pycache__/configuration_smolvlm.cpython-312.pyc,,
+transformers/models/smolvlm/__pycache__/image_processing_pil_smolvlm.cpython-312.pyc,,
+transformers/models/smolvlm/__pycache__/image_processing_smolvlm.cpython-312.pyc,,
+transformers/models/smolvlm/__pycache__/modeling_smolvlm.cpython-312.pyc,,
+transformers/models/smolvlm/__pycache__/modular_smolvlm.cpython-312.pyc,,
+transformers/models/smolvlm/__pycache__/processing_smolvlm.cpython-312.pyc,,
+transformers/models/smolvlm/__pycache__/video_processing_smolvlm.cpython-312.pyc,,
+transformers/models/smolvlm/configuration_smolvlm.py,sha256=DQcSlL0lou60nMD8aoXri2ldOrDhZNrEI6jvPnWi5zQ,4860
+transformers/models/smolvlm/image_processing_pil_smolvlm.py,sha256=tyDjd8vCKt7yJYIby_I2cFXU-0zu8lXQAXokj-WyNzI,19501
+transformers/models/smolvlm/image_processing_smolvlm.py,sha256=AvDpezDuLORKkJSVJX0LqRXzoT33iHBc1xS-huy_KR8,23734
+transformers/models/smolvlm/modeling_smolvlm.py,sha256=uwoNh1-SQGx2jneRzKq5BOefAn0xWliaAM1Z5XXkmHs,37748
+transformers/models/smolvlm/modular_smolvlm.py,sha256=LrkUfw6GmGKjD8cf2rYMNxLJvbzKU99vfWH9TyV_2p4,14740
+transformers/models/smolvlm/processing_smolvlm.py,sha256=eyaQX70lQX6nZneOIUlJDQapZZ0daarI88hneDpeHZg,16308
+transformers/models/smolvlm/video_processing_smolvlm.py,sha256=TYYrjnC-1X-87S_0zxMr1eZiG9C9lFqq9b3HXefd4H0,14275
+transformers/models/solar_open/__init__.py,sha256=_IuMoJHTvrxSNxcHGJe1QpLINdHuEUV7BeCLSQkzPgs,1001
+transformers/models/solar_open/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/solar_open/__pycache__/configuration_solar_open.cpython-312.pyc,,
+transformers/models/solar_open/__pycache__/modeling_solar_open.cpython-312.pyc,,
+transformers/models/solar_open/__pycache__/modular_solar_open.cpython-312.pyc,,
+transformers/models/solar_open/configuration_solar_open.py,sha256=w9Y8qbqIwLYAWTTk8VNZzfve1s277_19BZ3b9GrOZhs,3840
+transformers/models/solar_open/modeling_solar_open.py,sha256=si0JQUfboTW2faZxu09sdDyg-_XE1sSL8Z0nUyKIeIo,27381
+transformers/models/solar_open/modular_solar_open.py,sha256=epIsESMhGADCcoBFw0Sp5GuINSj1PfeoCdgn36oH5W4,3131
+transformers/models/speech_encoder_decoder/__init__.py,sha256=YJ8Vz0n_ZDxYjI_2r-G3iRCoKQy58r8C1n4t2s42BSw,1025
+transformers/models/speech_encoder_decoder/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/speech_encoder_decoder/__pycache__/configuration_speech_encoder_decoder.cpython-312.pyc,,
+transformers/models/speech_encoder_decoder/__pycache__/modeling_speech_encoder_decoder.cpython-312.pyc,,
+transformers/models/speech_encoder_decoder/configuration_speech_encoder_decoder.py,sha256=GpmDnzRdZVRLFF4zfuqCsiG6hIanjX-1dVEgrofPVjk,3940
+transformers/models/speech_encoder_decoder/modeling_speech_encoder_decoder.py,sha256=L8cIJn0SOYJXyNHgcXYW1Z1G8ipaPjnekF_e1Vun2d0,24596
+transformers/models/speech_to_text/__init__.py,sha256=HmMO19XDk0Inzvsd1Kgxdr7JYZMA1UrjEEqPT1f9ksI,1154
+transformers/models/speech_to_text/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/speech_to_text/__pycache__/configuration_speech_to_text.cpython-312.pyc,,
+transformers/models/speech_to_text/__pycache__/feature_extraction_speech_to_text.cpython-312.pyc,,
+transformers/models/speech_to_text/__pycache__/modeling_speech_to_text.cpython-312.pyc,,
+transformers/models/speech_to_text/__pycache__/processing_speech_to_text.cpython-312.pyc,,
+transformers/models/speech_to_text/__pycache__/tokenization_speech_to_text.cpython-312.pyc,,
+transformers/models/speech_to_text/configuration_speech_to_text.py,sha256=A1SWOEhcxxNSUsX1A3hI5hSMwrAcz88GTWZ0AnIYwl0,4435
+transformers/models/speech_to_text/feature_extraction_speech_to_text.py,sha256=-e_x4Qob2NkK8Uuy0H7szz9CxlwcZmCJLN7d_vemOXc,13798
+transformers/models/speech_to_text/modeling_speech_to_text.py,sha256=Ya-XzJS92fpnElsi4MBM8K_VxR8mCxe4RHeU6dw3Yk0,40487
+transformers/models/speech_to_text/processing_speech_to_text.py,sha256=EMa7GGoDf3TA-2Xec8TRiate7Lj22VIjmijDtmae-I0,1770
+transformers/models/speech_to_text/tokenization_speech_to_text.py,sha256=r6--tOw4p8U7DkrvzAHsGzUeW59ZzP0RrJnwrbgkUs8,11480
+transformers/models/speecht5/__init__.py,sha256=DploRLnZX4ZO40Z7BstCZ7aNWGuZE06tIeMo0GTyR60,1124
+transformers/models/speecht5/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/speecht5/__pycache__/configuration_speecht5.cpython-312.pyc,,
+transformers/models/speecht5/__pycache__/feature_extraction_speecht5.cpython-312.pyc,,
+transformers/models/speecht5/__pycache__/modeling_speecht5.cpython-312.pyc,,
+transformers/models/speecht5/__pycache__/number_normalizer.cpython-312.pyc,,
+transformers/models/speecht5/__pycache__/processing_speecht5.cpython-312.pyc,,
+transformers/models/speecht5/__pycache__/tokenization_speecht5.cpython-312.pyc,,
+transformers/models/speecht5/configuration_speecht5.py,sha256=SjUR1-tkg16BucdxbQ2dqkVtQBql9E3WzvOP_7qqOGI,15216
+transformers/models/speecht5/feature_extraction_speecht5.py,sha256=xMEQ55FOnnFirIQCFrFYWuhjHDiTI-MAWJtOMFRT7jM,16724
+transformers/models/speecht5/modeling_speecht5.py,sha256=LbO0sIRuclUza4xqo4rUNgTi2UN0xdxIB_6FGm5sEcM,138949
+transformers/models/speecht5/number_normalizer.py,sha256=L9vC3QKmC_27nv978ifR-f4gkCCgw2aMjpqqFrpDJEA,7004
+transformers/models/speecht5/processing_speecht5.py,sha256=rUA2C5j1-VxIbKBaGeFgYChGTVjPPtuEskeYCC8fglY,5373
+transformers/models/speecht5/tokenization_speecht5.py,sha256=39_jjTEYCN-CEqALP6R53KA0ZnaI220gUGf8jNS1T6U,6688
+transformers/models/splinter/__init__.py,sha256=N3tdgJIqZRPK0g3pfLE3p3-HkGJMRf-GQ189anQ51to,1084
+transformers/models/splinter/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/splinter/__pycache__/configuration_splinter.cpython-312.pyc,,
+transformers/models/splinter/__pycache__/modeling_splinter.cpython-312.pyc,,
+transformers/models/splinter/__pycache__/tokenization_splinter.cpython-312.pyc,,
+transformers/models/splinter/configuration_splinter.py,sha256=58FyVPPF1MFLBDo1JdeZClPtJg1xMR_xjh-POE3Sc0M,2076
+transformers/models/splinter/modeling_splinter.py,sha256=hXHTi3hOmbQRaWnu6tpVvzuF6xVlyZc44nwT5XFRsyA,31807
+transformers/models/splinter/tokenization_splinter.py,sha256=hm-SaCCy7IhVgH5ZztphxXctnoOZ8iK7Mqad-P0o44s,6692
+transformers/models/squeezebert/__init__.py,sha256=N2L22551dhssCbWpQgWZJ172TnRjxUdnRlSKr8xW48w,1092
+transformers/models/squeezebert/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/squeezebert/__pycache__/configuration_squeezebert.cpython-312.pyc,,
+transformers/models/squeezebert/__pycache__/modeling_squeezebert.cpython-312.pyc,,
+transformers/models/squeezebert/__pycache__/tokenization_squeezebert.cpython-312.pyc,,
+transformers/models/squeezebert/configuration_squeezebert.py,sha256=RRIoSHh7iq4cExOP8ZBji22oFNH5RsQVlcJFc_xxsRs,2827
+transformers/models/squeezebert/modeling_squeezebert.py,sha256=NQgLt-3EAOVYhpLDq2wK3kViEIrEf0RzcsE_EW3CdBk,36469
+transformers/models/squeezebert/tokenization_squeezebert.py,sha256=U8LyiVJ_oBc5ejnes_tLUB2espGVrNiqDiVZtsrEOqI,1011
+transformers/models/stablelm/__init__.py,sha256=aVgWTcwBuuiGJDp8H_ZU6BvhYqjmNEqCukU7jEfwd_I,997
+transformers/models/stablelm/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/stablelm/__pycache__/configuration_stablelm.cpython-312.pyc,,
+transformers/models/stablelm/__pycache__/modeling_stablelm.cpython-312.pyc,,
+transformers/models/stablelm/configuration_stablelm.py,sha256=GJM7CaXl7css3wnlhlccKJ_6ygeFxzqcnTRP8C7Yf2M,2546
+transformers/models/stablelm/modeling_stablelm.py,sha256=QMLt4LzClC29FThACngERs3HFkVyXLKeFUAQ1p_-Kh0,24643
+transformers/models/starcoder2/__init__.py,sha256=fZ8HHZCGjxRfVgROe7zuoi9ADIAa4SeqxGHkvKUQiQM,1001
+transformers/models/starcoder2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/starcoder2/__pycache__/configuration_starcoder2.cpython-312.pyc,,
+transformers/models/starcoder2/__pycache__/modeling_starcoder2.cpython-312.pyc,,
+transformers/models/starcoder2/__pycache__/modular_starcoder2.cpython-312.pyc,,
+transformers/models/starcoder2/configuration_starcoder2.py,sha256=NBgv-MBiBY1ac5vxJMq7wmwDVXRuFGsNMewWlaGbAg4,2970
+transformers/models/starcoder2/modeling_starcoder2.py,sha256=_t6KpWY9HzMLHFhfP_6DSB1XJ13d7QG_Ie3Z6iTcdcs,21794
+transformers/models/starcoder2/modular_starcoder2.py,sha256=PWA62TupJ0KLmzrOaHXca_Lue9MdxtiTGIfi7RzGVEY,9035
+transformers/models/superglue/__init__.py,sha256=ZQF1Ava32iCXmBhzGMwFoYmdLldU7VAfpybB4o2WWqk,1095
+transformers/models/superglue/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/superglue/__pycache__/configuration_superglue.cpython-312.pyc,,
+transformers/models/superglue/__pycache__/image_processing_pil_superglue.cpython-312.pyc,,
+transformers/models/superglue/__pycache__/image_processing_superglue.cpython-312.pyc,,
+transformers/models/superglue/__pycache__/modeling_superglue.cpython-312.pyc,,
+transformers/models/superglue/configuration_superglue.py,sha256=gHmSaoKlCeiF7ljU6kJ3ApI6lhn4aiJCXZvRXiiFmhA,4068
+transformers/models/superglue/image_processing_pil_superglue.py,sha256=vYZPgIOGwqYC43CEUMI6hybjLas9AdRP_cOCHlGgXi0,11707
+transformers/models/superglue/image_processing_superglue.py,sha256=b2yMxNS91Jin2IzjBL2k-UuBNf4024dJXbPFl8wXpAE,12824
+transformers/models/superglue/modeling_superglue.py,sha256=3-4b0CTLh8y5RiePlSU-cdJna0rGvfj4vVuaMu1vyVE,32573
+transformers/models/superpoint/__init__.py,sha256=cqK0QQFrrY_XcrejiMsyQtXi3rsUVEjmd2960pvH-w8,1099
+transformers/models/superpoint/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/superpoint/__pycache__/configuration_superpoint.cpython-312.pyc,,
+transformers/models/superpoint/__pycache__/image_processing_pil_superpoint.cpython-312.pyc,,
+transformers/models/superpoint/__pycache__/image_processing_superpoint.cpython-312.pyc,,
+transformers/models/superpoint/__pycache__/modeling_superpoint.cpython-312.pyc,,
+transformers/models/superpoint/configuration_superpoint.py,sha256=a_PaxJV-jxoDuRdNaY5NHaCunwJkOwXzMd8Jy4iHxzI,2602
+transformers/models/superpoint/image_processing_pil_superpoint.py,sha256=Rzl28UlBJpBL3vcfzLUd6jErbtdow0Kg7wM3S-aqbnU,6544
+transformers/models/superpoint/image_processing_superpoint.py,sha256=_pklI3WYApI18ty9saFukMhwiirj9WiH0Ah_XJOiCYI,6842
+transformers/models/superpoint/modeling_superpoint.py,sha256=Ctb2-dtCXn5JpYw09jpwINEfX6_EciYHPOChtahJMMI,19486
+transformers/models/swiftformer/__init__.py,sha256=PDcV6Hp4K5CT7w3dsfXb3c9Rd2fgIw7_WLTOH4JQgJU,1003
+transformers/models/swiftformer/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/swiftformer/__pycache__/configuration_swiftformer.cpython-312.pyc,,
+transformers/models/swiftformer/__pycache__/modeling_swiftformer.cpython-312.pyc,,
+transformers/models/swiftformer/configuration_swiftformer.py,sha256=1ruaW_CZdB5KXr-Sr_ZkM8EMzNgqZVcir0up2RRMTUs,3072
+transformers/models/swiftformer/modeling_swiftformer.py,sha256=GuNAYR253QqJcpsrpCQstHNyJeB-xPpchEGJb2Jvkbg,19242
+transformers/models/swin/__init__.py,sha256=upidQvan2_lviVSI8s92-qKh7-Z28XC9Ug9aMV1wnjc,989
+transformers/models/swin/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/swin/__pycache__/configuration_swin.cpython-312.pyc,,
+transformers/models/swin/__pycache__/modeling_swin.cpython-312.pyc,,
+transformers/models/swin/__pycache__/modular_swin.cpython-312.pyc,,
+transformers/models/swin/configuration_swin.py,sha256=W1ARoQm2T4K1iLa15fY83OcGlk_2IyQsQZaHzDoQBOU,3510
+transformers/models/swin/modeling_swin.py,sha256=JTexi4htuW3oqytZ7FqsQ-J3y6ONim5e_1OlFm6rRfQ,50093
+transformers/models/swin/modular_swin.py,sha256=r3Ci80X0pYwxoAvhe_t1AzgzPRhZzpTneTE5DPp2G0c,47857
+transformers/models/swin2sr/__init__.py,sha256=wYH2JUIgqd5GqR1keEfvOJuvwGXscrYCF6XDPEnTXSg,1087
+transformers/models/swin2sr/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/swin2sr/__pycache__/configuration_swin2sr.cpython-312.pyc,,
+transformers/models/swin2sr/__pycache__/image_processing_pil_swin2sr.cpython-312.pyc,,
+transformers/models/swin2sr/__pycache__/image_processing_swin2sr.cpython-312.pyc,,
+transformers/models/swin2sr/__pycache__/modeling_swin2sr.cpython-312.pyc,,
+transformers/models/swin2sr/configuration_swin2sr.py,sha256=xCFG3ju9PzNLEttTM-R7Ynbn-zs5TgMBBvrUxCu0XDE,3751
+transformers/models/swin2sr/image_processing_pil_swin2sr.py,sha256=xVfupa9eNfXuiS5g5Owg1H6GHh9mfqQ-4N1OJAKSlko,3884
+transformers/models/swin2sr/image_processing_swin2sr.py,sha256=97jIfMq7mxnr9d7Yuv4ZAcK4nUKrhwrGiniHtRku-H4,4087
+transformers/models/swin2sr/modeling_swin2sr.py,sha256=Jwb0PdKD-w8E0xh0kCryIcPlWZ1F8YIOeKW6SMv7aG0,44776
+transformers/models/swinv2/__init__.py,sha256=njM902tlEQ82mYRN9ZTMOiXpJn1NHnxKbm_LCvn2I-M,993
+transformers/models/swinv2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/swinv2/__pycache__/configuration_swinv2.cpython-312.pyc,,
+transformers/models/swinv2/__pycache__/modeling_swinv2.cpython-312.pyc,,
+transformers/models/swinv2/configuration_swinv2.py,sha256=iDi_MBqsLCjeyCPwlkN7XK2IJn78rRar7wiK125qwo0,3460
+transformers/models/swinv2/modeling_swinv2.py,sha256=VS_PG3gqDgDDn4oatis8iwvuTSKAKf7BzVUyN-X_6Ss,56030
+transformers/models/switch_transformers/__init__.py,sha256=Iw38A9kfIT5mJ0G00YE-TVN-M_b1DBHYQqb0pEyTZMY,1019
+transformers/models/switch_transformers/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/switch_transformers/__pycache__/configuration_switch_transformers.cpython-312.pyc,,
+transformers/models/switch_transformers/__pycache__/modeling_switch_transformers.cpython-312.pyc,,
+transformers/models/switch_transformers/__pycache__/modular_switch_transformers.cpython-312.pyc,,
+transformers/models/switch_transformers/configuration_switch_transformers.py,sha256=SoRG3MDluVOI9RUyvmfQEolbFsd_xCUzXqTwIFyAdE8,5202
+transformers/models/switch_transformers/modeling_switch_transformers.py,sha256=Kq8ns_n96hgPgSyVovShC-fg_FFXA8_KF__7no7ZzoU,49452
+transformers/models/switch_transformers/modular_switch_transformers.py,sha256=IL2TPxec0ROAcYvng12rdPQFkY-vwclyGytZA3aQ6lI,34603
+transformers/models/t5/__init__.py,sha256=ieynYXP35xsyLPJPIK2Xjq4FtzCq_5aI5Kg7i3kHF44,1020
+transformers/models/t5/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/t5/__pycache__/configuration_t5.cpython-312.pyc,,
+transformers/models/t5/__pycache__/modeling_t5.cpython-312.pyc,,
+transformers/models/t5/__pycache__/tokenization_t5.cpython-312.pyc,,
+transformers/models/t5/configuration_t5.py,sha256=XNzApA_7WGVgkNAh5F_v_lynnE5R5R6LrBGnqroyWdk,3962
+transformers/models/t5/modeling_t5.py,sha256=yT0GgZ4C8nWwxO1_qLuVx5kkwQzEtSyatiYKHm5rJ9E,71456
+transformers/models/t5/tokenization_t5.py,sha256=b6ZpaqK_a_QLzXx66oG1tYHjZa2kXG13aNU2CRdEltU,6540
+transformers/models/t5gemma/__init__.py,sha256=S7m_HiGfMyAtU_CSHx9VTNPtSxcnLp8V67FCSGHpLCs,995
+transformers/models/t5gemma/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/t5gemma/__pycache__/configuration_t5gemma.cpython-312.pyc,,
+transformers/models/t5gemma/__pycache__/modeling_t5gemma.cpython-312.pyc,,
+transformers/models/t5gemma/__pycache__/modular_t5gemma.cpython-312.pyc,,
+transformers/models/t5gemma/configuration_t5gemma.py,sha256=cFkMSGl4vFUUbSoNGpSC2MNPkm1DfXtgZTa048lDNmQ,7237
+transformers/models/t5gemma/modeling_t5gemma.py,sha256=0yUvbPixCsLFRGUTw1NDfVJx2ywFIfVsn7ji1BFqShc,61022
+transformers/models/t5gemma/modular_t5gemma.py,sha256=3p2gS8lCJBxMZmhKg14skZIKPPUFlzqEdio2gTK_U50,52056
+transformers/models/t5gemma2/__init__.py,sha256=AF59388HsGjMPsRnN8iRdDNwYBE-uyTZ-U8zEKnYRyI,997
+transformers/models/t5gemma2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/t5gemma2/__pycache__/configuration_t5gemma2.cpython-312.pyc,,
+transformers/models/t5gemma2/__pycache__/modeling_t5gemma2.cpython-312.pyc,,
+transformers/models/t5gemma2/__pycache__/modular_t5gemma2.cpython-312.pyc,,
+transformers/models/t5gemma2/configuration_t5gemma2.py,sha256=RGJC2mQiQbTqY-wGu6aeQwWkpOyGrAtkbYSSxfssvPw,17475
+transformers/models/t5gemma2/modeling_t5gemma2.py,sha256=Ht1Q2Fxy8V9GD0Nw8V2rAFCCBsBUdY5xL3XhQnC6uuM,68322
+transformers/models/t5gemma2/modular_t5gemma2.py,sha256=zHUHccrTYFjdq_AGVMY6E4zhnBXUlv0C9sXZ0FCLv5I,55965
+transformers/models/table_transformer/__init__.py,sha256=VT-KM0_6LZ6fdOAglbfA8zEhCQuYa6He10Div7WEcD8,1015
+transformers/models/table_transformer/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/table_transformer/__pycache__/configuration_table_transformer.cpython-312.pyc,,
+transformers/models/table_transformer/__pycache__/modeling_table_transformer.cpython-312.pyc,,
+transformers/models/table_transformer/configuration_table_transformer.py,sha256=Q7AWYOQHtNK-jOe3oJ33AEvpeSdvbXJlniiicyOTUKI,4560
+transformers/models/table_transformer/modeling_table_transformer.py,sha256=2FiAiSPW4PrcwKUWmig-jJQHDlnoOa_f1F4w4ch29OI,60001
+transformers/models/tapas/__init__.py,sha256=Q4UNvDF5OHuAeLJFMEeBOGKzgO-ytt4t8x9shTlIb2o,1029
+transformers/models/tapas/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/tapas/__pycache__/configuration_tapas.cpython-312.pyc,,
+transformers/models/tapas/__pycache__/modeling_tapas.cpython-312.pyc,,
+transformers/models/tapas/__pycache__/tokenization_tapas.cpython-312.pyc,,
+transformers/models/tapas/configuration_tapas.py,sha256=pZfhClsUzBpRe7uM8o8ZOIvhcAyvDpaHcUpga2BXXnA,7533
+transformers/models/tapas/modeling_tapas.py,sha256=XsQRCUDm28FvSV7L_g9-bKWyd2F_w__n057aD5iIOqs,96748
+transformers/models/tapas/tokenization_tapas.py,sha256=ax89kJ0A-HAe1P2Yptxdo9fipMNo57NHA4xgz3gVChM,119464
+transformers/models/textnet/__init__.py,sha256=GAmL54kq4C_cJZzSX-Q-yIpLd7eT11-8O_rF89625Eg,1087
+transformers/models/textnet/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/textnet/__pycache__/configuration_textnet.cpython-312.pyc,,
+transformers/models/textnet/__pycache__/image_processing_pil_textnet.cpython-312.pyc,,
+transformers/models/textnet/__pycache__/image_processing_textnet.cpython-312.pyc,,
+transformers/models/textnet/__pycache__/modeling_textnet.cpython-312.pyc,,
+transformers/models/textnet/configuration_textnet.py,sha256=tBrbz6gs4aAUER-Po7Lm2sGGj8pi7fzFThoS5G3HBZc,3835
+transformers/models/textnet/image_processing_pil_textnet.py,sha256=So3Ye_LIKZBi-hcohId24Tju_j10WGwgPlHm4PNb4KY,4718
+transformers/models/textnet/image_processing_textnet.py,sha256=eswPTuvFUOwDsslB_dr2EKNLQHzLuBzuRuXFVsJopZA,5398
+transformers/models/textnet/modeling_textnet.py,sha256=7j8kfF3rX8WStBnYCXzMRaUnqNvQYlFL8I7SHHETc4M,15270
+transformers/models/time_series_transformer/__init__.py,sha256=3A_3Wog-6NDwCoBIMtkzJv9slc_wXpzDzsOo-xBQ8hE,1027
+transformers/models/time_series_transformer/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/time_series_transformer/__pycache__/configuration_time_series_transformer.cpython-312.pyc,,
+transformers/models/time_series_transformer/__pycache__/modeling_time_series_transformer.cpython-312.pyc,,
+transformers/models/time_series_transformer/configuration_time_series_transformer.py,sha256=C-daLrNf0ri6FSrwmvRqxkt6SaX8Tzr8fHeeDlTfXIA,7019
+transformers/models/time_series_transformer/modeling_time_series_transformer.py,sha256=S9c_TQbNzG0VeMNfPozYsW_FBn4Y5YR2Lh18JXgdkO8,74544
+transformers/models/timesfm/__init__.py,sha256=gcfLgRAbwZThFP98fst9wsoTMB0fkR28tzWYoQIs5qU,995
+transformers/models/timesfm/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/timesfm/__pycache__/configuration_timesfm.cpython-312.pyc,,
+transformers/models/timesfm/__pycache__/modeling_timesfm.cpython-312.pyc,,
+transformers/models/timesfm/__pycache__/modular_timesfm.cpython-312.pyc,,
+transformers/models/timesfm/configuration_timesfm.py,sha256=JBQwKAAGZyOF_jtapqqg4wygo2YGyiq2ScvfWMKZC_M,2970
+transformers/models/timesfm/modeling_timesfm.py,sha256=TGa7cUnkYiwv4kVFV7vYKHBqHTIKGfNPd_1vo1w98_4,32845
+transformers/models/timesfm/modular_timesfm.py,sha256=ZBQ9E4bPEIZNMbDOmMaGEHK0z-a49-3cYw6d2MzzLx0,30544
+transformers/models/timesfm2_5/__init__.py,sha256=QZR6P0hlbKuGdlvyWPJG8zbYV_5BC7-5ZEp6L3CdaNw,1002
+transformers/models/timesfm2_5/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/timesfm2_5/__pycache__/configuration_timesfm2_5.cpython-312.pyc,,
+transformers/models/timesfm2_5/__pycache__/modeling_timesfm2_5.cpython-312.pyc,,
+transformers/models/timesfm2_5/__pycache__/modular_timesfm2_5.cpython-312.pyc,,
+transformers/models/timesfm2_5/configuration_timesfm2_5.py,sha256=ggnE9YU9SvdlfufMR_WmwRiurDo9ZhoRhWsvyZhssZY,4297
+transformers/models/timesfm2_5/modeling_timesfm2_5.py,sha256=g8FUIjUS9vKpOmdvTCQVtNTKu15Yhh5ynDbtXFghCas,40368
+transformers/models/timesfm2_5/modular_timesfm2_5.py,sha256=0YGv_vYKziMuVn8idfoUaXCk1UtJ38gtNShilp5g1TQ,26777
+transformers/models/timesformer/__init__.py,sha256=m2lJ7UbMTu50rDQG_UPsmVR6abjatU1EujcsRgUEpAc,1051
+transformers/models/timesformer/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/timesformer/__pycache__/configuration_timesformer.cpython-312.pyc,,
+transformers/models/timesformer/__pycache__/modeling_timesformer.cpython-312.pyc,,
+transformers/models/timesformer/__pycache__/video_processing_timesformer.cpython-312.pyc,,
+transformers/models/timesformer/configuration_timesformer.py,sha256=XsQtAihbPzLjnLpbnszltLDQ_XJYIa8cGQVvlnAppeU,2264
+transformers/models/timesformer/modeling_timesformer.py,sha256=MDAYQHVxfKb1i1aw8b5rQV_Bl0wuqiNuLKVTuiEdhtw,31710
+transformers/models/timesformer/video_processing_timesformer.py,sha256=p445jCmIyiWqbnMG2K5SNhgoCHYSjd_S8b9ixQHU7Zs,1533
+transformers/models/timm_backbone/__init__.py,sha256=s0GlTaJ43Yt9ZdzG9-qjJNlp0Ol4vjN-14S6N7gXLsA,1007
+transformers/models/timm_backbone/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/timm_backbone/__pycache__/configuration_timm_backbone.cpython-312.pyc,,
+transformers/models/timm_backbone/__pycache__/modeling_timm_backbone.cpython-312.pyc,,
+transformers/models/timm_backbone/configuration_timm_backbone.py,sha256=AMLDzPS7Nrd0oJWQbBc19scB92lJMHvgfQZfm6ciYaU,3206
+transformers/models/timm_backbone/modeling_timm_backbone.py,sha256=CdBrkQwayvV7TUis96uhRJbAAaud58unLN3_p5G7pAE,6787
+transformers/models/timm_wrapper/__init__.py,sha256=U19BCtZcAQdmBto5bqG6u69W5rnUBtIyP11EcRh_0Tk,1054
+transformers/models/timm_wrapper/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/timm_wrapper/__pycache__/configuration_timm_wrapper.cpython-312.pyc,,
+transformers/models/timm_wrapper/__pycache__/image_processing_timm_wrapper.cpython-312.pyc,,
+transformers/models/timm_wrapper/__pycache__/modeling_timm_wrapper.cpython-312.pyc,,
+transformers/models/timm_wrapper/configuration_timm_wrapper.py,sha256=aIeOlje21ivY-RToVHN2M9rllwznN0ITg66vKSHvB70,4527
+transformers/models/timm_wrapper/image_processing_timm_wrapper.py,sha256=ER8ITuGx1vIT2LWD4InZpkKZcC0i8RufGGDsGygexUA,5298
+transformers/models/timm_wrapper/modeling_timm_wrapper.py,sha256=i2cVWnQbHVWuwFxCZPQZQxfBgDrYVq-9VRYkFAffpmM,17476
+transformers/models/trocr/__init__.py,sha256=Hllbq_42XbGRZyXsGOzYHcb33MOA5_yfijMRKEXJ4n4,1027
+transformers/models/trocr/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/trocr/__pycache__/configuration_trocr.cpython-312.pyc,,
+transformers/models/trocr/__pycache__/modeling_trocr.cpython-312.pyc,,
+transformers/models/trocr/__pycache__/processing_trocr.cpython-312.pyc,,
+transformers/models/trocr/configuration_trocr.py,sha256=Jw8jRw1wSBKXC_SdHgP_byoRMExob7yP71Vw5Vt8cm4,2754
+transformers/models/trocr/modeling_trocr.py,sha256=CLyjrDnTcZkX8I-b-Im-pS_-OqfnC4AN2dRkiSDzWho,34316
+transformers/models/trocr/processing_trocr.py,sha256=Ua_wrqvHlTgXiPiMSVgAe_axfYz8_IIknqCJaCDgFrc,2376
+transformers/models/tvp/__init__.py,sha256=Cb5W_dv-3RCNcgybJafwoBIYQAZpzSMp9mMargHsMP8,1105
+transformers/models/tvp/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/tvp/__pycache__/configuration_tvp.cpython-312.pyc,,
+transformers/models/tvp/__pycache__/image_processing_pil_tvp.cpython-312.pyc,,
+transformers/models/tvp/__pycache__/image_processing_tvp.cpython-312.pyc,,
+transformers/models/tvp/__pycache__/modeling_tvp.cpython-312.pyc,,
+transformers/models/tvp/__pycache__/processing_tvp.cpython-312.pyc,,
+transformers/models/tvp/configuration_tvp.py,sha256=jiXhuabyFE8hv31LnYbCsUPU7XVXJPhvx2h4c9ZX1UA,3802
+transformers/models/tvp/image_processing_pil_tvp.py,sha256=HYObAEIHqE8pY6Zu7SYFfRv4LX-5XUKZu4BunQRZN8M,9385
+transformers/models/tvp/image_processing_tvp.py,sha256=gynUYvp4YYRVajMNmyP4tGBH-wDVd8LJ1JTf0yhd7o0,8502
+transformers/models/tvp/modeling_tvp.py,sha256=1sCdjTkNOUqn-rje12V11vKcHuXu_k8fBEkHBs27HPw,37862
+transformers/models/tvp/processing_tvp.py,sha256=3pETNxZZvG6cD2JdlWcTU8qu62Pcz4joiPyCGu4J0xE,1973
+transformers/models/udop/__init__.py,sha256=GOiuT5Vm4kOkkZNVQ5AciUkw7BnJLB2quIn9jv9h5Nw,1061
+transformers/models/udop/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/udop/__pycache__/configuration_udop.cpython-312.pyc,,
+transformers/models/udop/__pycache__/modeling_udop.cpython-312.pyc,,
+transformers/models/udop/__pycache__/processing_udop.cpython-312.pyc,,
+transformers/models/udop/__pycache__/tokenization_udop.cpython-312.pyc,,
+transformers/models/udop/configuration_udop.py,sha256=4PF2AD9ieef07JpZ7u8txRNMevHbQV3-17qNX48gD4A,4094
+transformers/models/udop/modeling_udop.py,sha256=DFNODPXJzJKa9ci-POXtEy_7rJVllFOl1Oo_fAwGPs8,78591
+transformers/models/udop/processing_udop.py,sha256=F78VvxPHlSEDUozH9cLrlSIFHCnPQn-QU-znDTKell4,7148
+transformers/models/udop/tokenization_udop.py,sha256=CblxD_A60VDOkDwNyt8Xthockkdi_wI_MyXyOZYFtt4,49668
+transformers/models/umt5/__init__.py,sha256=FKt6Ap3AvOCIKoeOM-5qY84lNEML9IujaDaYROINJMs,989
+transformers/models/umt5/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/umt5/__pycache__/configuration_umt5.cpython-312.pyc,,
+transformers/models/umt5/__pycache__/modeling_umt5.cpython-312.pyc,,
+transformers/models/umt5/configuration_umt5.py,sha256=DM3tlsNBNIYWCwZgRNgRjHjRilTNsF4SoP8hceXToRs,3473
+transformers/models/umt5/modeling_umt5.py,sha256=n9ZoOVAD0P5qJpfke6QeYWV4_9WbbY7UtNWsF7nxDoE,73838
+transformers/models/unispeech/__init__.py,sha256=AXJMExDoYYI71OKNXhAt7lyqcFIvcLHEQ1Fsm171m5w,999
+transformers/models/unispeech/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/unispeech/__pycache__/configuration_unispeech.cpython-312.pyc,,
+transformers/models/unispeech/__pycache__/modeling_unispeech.cpython-312.pyc,,
+transformers/models/unispeech/__pycache__/modular_unispeech.cpython-312.pyc,,
+transformers/models/unispeech/configuration_unispeech.py,sha256=E3onHkhXtWx_3e12ct6UzL4GRe2T8EMDT9sHyKHEJNY,11683
+transformers/models/unispeech/modeling_unispeech.py,sha256=VKpeLvBTov8i_45wmLAWjwJC6W6B6cdKAY8zAjQdWW4,60216
+transformers/models/unispeech/modular_unispeech.py,sha256=E5AEtpVoKJtiSOFtZ9TsKhK8IBdWabjGZTXkR4t2lqg,17552
+transformers/models/unispeech_sat/__init__.py,sha256=P9lCzMg01s4Gj_Pb8t1l36MRAeoOcxUa4d7dbQSe9N4,1007
+transformers/models/unispeech_sat/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/unispeech_sat/__pycache__/configuration_unispeech_sat.cpython-312.pyc,,
+transformers/models/unispeech_sat/__pycache__/modeling_unispeech_sat.cpython-312.pyc,,
+transformers/models/unispeech_sat/__pycache__/modular_unispeech_sat.cpython-312.pyc,,
+transformers/models/unispeech_sat/configuration_unispeech_sat.py,sha256=DV2Fyka0-axtLeE6W02d8ERukdO4OYGCcaHjvcwMpVg,12713
+transformers/models/unispeech_sat/modeling_unispeech_sat.py,sha256=nfSK4XAZ4-Lx8Knjfrela-JTxd3Aa61DZZUjXrROpoI,73248
+transformers/models/unispeech_sat/modular_unispeech_sat.py,sha256=_a1Wwwyln-oRmgrwCES9hXXu8_1v4tMoZjt70vT7lMc,17945
+transformers/models/univnet/__init__.py,sha256=hfHyxyKGEfd58p1fUSA3IxK2q6JkVatkGceVaoKuODk,1041
+transformers/models/univnet/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/univnet/__pycache__/configuration_univnet.cpython-312.pyc,,
+transformers/models/univnet/__pycache__/feature_extraction_univnet.cpython-312.pyc,,
+transformers/models/univnet/__pycache__/modeling_univnet.cpython-312.pyc,,
+transformers/models/univnet/configuration_univnet.py,sha256=BHdH0G1Gbj_gSsJXQZfhCI3VljiATFOro63lG2NmOfg,5240
+transformers/models/univnet/feature_extraction_univnet.py,sha256=fLIbEVY2ItwXSTfwkmqZxC1obyHtDaWIXzJqHACsmK0,22748
+transformers/models/univnet/modeling_univnet.py,sha256=dXH436D_KTI40XPaWkxbEnEtgnIRGAXSTFjiXM8PxMw,25419
+transformers/models/upernet/__init__.py,sha256=Wq3u7yXJul5PLmjalxKgx451sa_WuSXbEM45bZsRv3E,995
+transformers/models/upernet/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/upernet/__pycache__/configuration_upernet.cpython-312.pyc,,
+transformers/models/upernet/__pycache__/modeling_upernet.cpython-312.pyc,,
+transformers/models/upernet/configuration_upernet.py,sha256=PPfx7f8bTDKabjTekLPMIHa76hTPHEJqm0mCwGpF-vU,3476
+transformers/models/upernet/modeling_upernet.py,sha256=L9X7h7Zk3EiAMAfLW1l6NlbXc-GEvKHjSnLpbNo1cZ4,14151
+transformers/models/uvdoc/__init__.py,sha256=7R4_lHfNAFjl4yh36bpmh_57Vyn6zhF-D2wpYArR_30,1035
+transformers/models/uvdoc/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/uvdoc/__pycache__/configuration_uvdoc.cpython-312.pyc,,
+transformers/models/uvdoc/__pycache__/image_processing_uvdoc.cpython-312.pyc,,
+transformers/models/uvdoc/__pycache__/modeling_uvdoc.cpython-312.pyc,,
+transformers/models/uvdoc/__pycache__/modular_uvdoc.cpython-312.pyc,,
+transformers/models/uvdoc/configuration_uvdoc.py,sha256=7GvX_mX_6AbWDkupVldukXH-Bcvefet2XvgHpDbQweE,6259
+transformers/models/uvdoc/image_processing_uvdoc.py,sha256=YTmcp225zlufR15zD5SEzNRvoWwhleU5S0XZfYwsIYc,6608
+transformers/models/uvdoc/modeling_uvdoc.py,sha256=pUSqRtKLjXqlpBx446nw33cJObq6Pxz8TDSqASlO_7E,13453
+transformers/models/uvdoc/modular_uvdoc.py,sha256=SNKJs2utjsJij6cXEhwLCf7CCTfeC3AZ6JVMT45aBQc,21812
+transformers/models/vaultgemma/__init__.py,sha256=d-2ptvRau3FlBamhyOMQnMVX3tvL-dQnfm4CyQJBBRA,1002
+transformers/models/vaultgemma/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/vaultgemma/__pycache__/configuration_vaultgemma.cpython-312.pyc,,
+transformers/models/vaultgemma/__pycache__/modeling_vaultgemma.cpython-312.pyc,,
+transformers/models/vaultgemma/__pycache__/modular_vaultgemma.cpython-312.pyc,,
+transformers/models/vaultgemma/configuration_vaultgemma.py,sha256=5SOoOJWAHsb1c5pmDb_REj0OjgMhC-M0dyHTrAO0ikw,4820
+transformers/models/vaultgemma/modeling_vaultgemma.py,sha256=03GqWJPAXBbkxi9c_Pxkv-hlJUiasTkIowZdijfymu8,23762
+transformers/models/vaultgemma/modular_vaultgemma.py,sha256=9uYyctLaLqMN_q7_N770UiynMq4-M5mRlI2zp4Ol2KA,3733
+transformers/models/vibevoice_acoustic_tokenizer/__init__.py,sha256=B8iNqUEKPRSTqVHk_x8cIYdTtZJz9CyFb9CXxPs2xbQ,1104
+transformers/models/vibevoice_acoustic_tokenizer/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/vibevoice_acoustic_tokenizer/__pycache__/configuration_vibevoice_acoustic_tokenizer.cpython-312.pyc,,
+transformers/models/vibevoice_acoustic_tokenizer/__pycache__/feature_extraction_vibevoice_acoustic_tokenizer.cpython-312.pyc,,
+transformers/models/vibevoice_acoustic_tokenizer/__pycache__/modeling_vibevoice_acoustic_tokenizer.cpython-312.pyc,,
+transformers/models/vibevoice_acoustic_tokenizer/__pycache__/modular_vibevoice_acoustic_tokenizer.cpython-312.pyc,,
+transformers/models/vibevoice_acoustic_tokenizer/configuration_vibevoice_acoustic_tokenizer.py,sha256=lU2izr0BFF1nhel0to7KVVtcKeVI6NUnl34J2grbipA,5969
+transformers/models/vibevoice_acoustic_tokenizer/feature_extraction_vibevoice_acoustic_tokenizer.py,sha256=tALX4Lcj3tOOd2lGM3TpWbU-dEqRFMW-8ifLuotwKzI,6532
+transformers/models/vibevoice_acoustic_tokenizer/modeling_vibevoice_acoustic_tokenizer.py,sha256=KOX5Cu5uTw8jXimZWfkpYoZMsAutvEBrsesjhcVXZeA,24633
+transformers/models/vibevoice_acoustic_tokenizer/modular_vibevoice_acoustic_tokenizer.py,sha256=afd1itNTouEHXEPDDdiRgF8w6WsQ9AeeL3ooykYxKI0,20891
+transformers/models/vibevoice_asr/__init__.py,sha256=aOGnTphzUJ3gePowLi9_HKYbbg__u4OKuaWA8vQk0Bk,1071
+transformers/models/vibevoice_asr/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/vibevoice_asr/__pycache__/configuration_vibevoice_asr.cpython-312.pyc,,
+transformers/models/vibevoice_asr/__pycache__/modeling_vibevoice_asr.cpython-312.pyc,,
+transformers/models/vibevoice_asr/__pycache__/modular_vibevoice_asr.cpython-312.pyc,,
+transformers/models/vibevoice_asr/__pycache__/processing_vibevoice_asr.cpython-312.pyc,,
+transformers/models/vibevoice_asr/configuration_vibevoice_asr.py,sha256=LEKRwAGGvPMoiQB4rpkza3C_U6DZUkR9kOKslhBf-n4,5810
+transformers/models/vibevoice_asr/modeling_vibevoice_asr.py,sha256=tS_12Ugsxj_M8hRWfqG3PImGglnKQgCG9JwMPaTvmBc,22969
+transformers/models/vibevoice_asr/modular_vibevoice_asr.py,sha256=fTwrE5UlyUjEAs47KYUJbVi1NeL9O9V9t_DlMtMnN88,19635
+transformers/models/vibevoice_asr/processing_vibevoice_asr.py,sha256=kCt43_IelZN7nGrGk_F2tZxkqNVc-T-BFqeCgY-mc1o,15851
+transformers/models/video_llama_3/__init__.py,sha256=pY4pIqqEWj1Z9lQ2R24ckUXSEZbVvyPNPlPzWRJWGD8,1205
+transformers/models/video_llama_3/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/video_llama_3/__pycache__/configuration_video_llama_3.cpython-312.pyc,,
+transformers/models/video_llama_3/__pycache__/image_processing_pil_video_llama_3.cpython-312.pyc,,
+transformers/models/video_llama_3/__pycache__/image_processing_video_llama_3.cpython-312.pyc,,
+transformers/models/video_llama_3/__pycache__/modeling_video_llama_3.cpython-312.pyc,,
+transformers/models/video_llama_3/__pycache__/modular_video_llama_3.cpython-312.pyc,,
+transformers/models/video_llama_3/__pycache__/processing_video_llama_3.cpython-312.pyc,,
+transformers/models/video_llama_3/__pycache__/video_processing_video_llama_3.cpython-312.pyc,,
+transformers/models/video_llama_3/configuration_video_llama_3.py,sha256=c0CwxXK2OrJg6iSkNgM9wtp5QdI-15ZXQw4OfQQgnpg,4293
+transformers/models/video_llama_3/image_processing_pil_video_llama_3.py,sha256=gNbcHCLsGARIWTXNDeN_1yhlKzU66th8u4NdNo80I4g,10762
+transformers/models/video_llama_3/image_processing_video_llama_3.py,sha256=YGayu6cRAFMSgjFiyVI_pSWkZsQ8HaGRy5F6dIjYXBY,11497
+transformers/models/video_llama_3/modeling_video_llama_3.py,sha256=1Xno8wPza25ddOB3kUH7PkVjlnGstbxBWr315reeiGE,48091
+transformers/models/video_llama_3/modular_video_llama_3.py,sha256=Xl94kY99fXjVuu8RmFym1mz6wDtOxgSVnwbftktApo0,60820
+transformers/models/video_llama_3/processing_video_llama_3.py,sha256=wRaVLYTjVTNZLJvhlSqfAoA8ZJGFoXVB5p6jAg1ksd8,7761
+transformers/models/video_llama_3/video_processing_video_llama_3.py,sha256=eI2FRaNJrViOpNJM1BfhLp-l3WKXAmIx3PF0S25hxjY,18152
+transformers/models/video_llava/__init__.py,sha256=bsLGp1WBBO_AvNVRxzOn5k7OYQIbX9SqFhESd24FImc,1093
+transformers/models/video_llava/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/video_llava/__pycache__/configuration_video_llava.cpython-312.pyc,,
+transformers/models/video_llava/__pycache__/image_processing_video_llava.cpython-312.pyc,,
+transformers/models/video_llava/__pycache__/modeling_video_llava.cpython-312.pyc,,
+transformers/models/video_llava/__pycache__/processing_video_llava.cpython-312.pyc,,
+transformers/models/video_llava/__pycache__/video_processing_video_llava.cpython-312.pyc,,
+transformers/models/video_llava/configuration_video_llava.py,sha256=H9o30tUV-kHN417WBlszznJ-M_H7nkBHTW0JMJDaEoE,3863
+transformers/models/video_llava/image_processing_video_llava.py,sha256=FiopnKA5a9Sa0ZGfXaYout_cemM5oG1IaeM70dSB9H8,16825
+transformers/models/video_llava/modeling_video_llava.py,sha256=ITP8DuPqEQaPWPDMMWv2LayFU0FH-a9UJzgPOh7RLyk,27566
+transformers/models/video_llava/processing_video_llava.py,sha256=U2IjhsbigW-5CEJIxc0rtsL28IPWiL8SiG57K3JOeD0,7450
+transformers/models/video_llava/video_processing_video_llava.py,sha256=Aomg9TFiRNtufNGT00RZArhv46Dl6FBl3tc3VQZosjg,1320
+transformers/models/videomae/__init__.py,sha256=CjvAakjEKtQPHa7PNd1EJcEcexrkGJzAdK51guAo5fw,1183
+transformers/models/videomae/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/videomae/__pycache__/configuration_videomae.cpython-312.pyc,,
+transformers/models/videomae/__pycache__/image_processing_pil_videomae.cpython-312.pyc,,
+transformers/models/videomae/__pycache__/image_processing_videomae.cpython-312.pyc,,
+transformers/models/videomae/__pycache__/modeling_videomae.cpython-312.pyc,,
+transformers/models/videomae/__pycache__/video_processing_videomae.cpython-312.pyc,,
+transformers/models/videomae/configuration_videomae.py,sha256=o1M44Hp3OWHF1bg0ou8nNaCCcIeUG6O8pN__DBS3Zfg,3102
+transformers/models/videomae/image_processing_pil_videomae.py,sha256=If_TsdAFBpEN1CsAlHkEYRGJee3IgE2WEt7S21d_S48,3542
+transformers/models/videomae/image_processing_videomae.py,sha256=gZE3NlfxbNLaQxDrLyws6gJ9wLvue5qp-2AsgLb0PQ4,4512
+transformers/models/videomae/modeling_videomae.py,sha256=Pc7PYKfTQWJUD1RRZk_mKUWte6XqmNfR-w3jRjR14CU,30786
+transformers/models/videomae/video_processing_videomae.py,sha256=VivwNTSmRKdflwjtm5LTvJFPoQXeY-YmtxFlpR-6c70,1582
+transformers/models/videomt/__init__.py,sha256=YkPFtUNCJVE2vypudQ-0K6RW0qV8MGxhqhqGgDTM6Qg,1040
+transformers/models/videomt/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/videomt/__pycache__/configuration_videomt.cpython-312.pyc,,
+transformers/models/videomt/__pycache__/modeling_videomt.cpython-312.pyc,,
+transformers/models/videomt/__pycache__/modular_videomt.cpython-312.pyc,,
+transformers/models/videomt/__pycache__/video_processing_videomt.cpython-312.pyc,,
+transformers/models/videomt/configuration_videomt.py,sha256=COpx1g4ZYaDHWxu0ArBrEj45XOI9CIn63GUKpb2r-0E,4451
+transformers/models/videomt/modeling_videomt.py,sha256=xoV6grlMm-RdrXgGRGFSWMElAneH7xuVJCKeG3zMPAY,54516
+transformers/models/videomt/modular_videomt.py,sha256=53mLWigCh_p6t-lyTMkIOAMF5yCtUCBgxn-V76f5u7g,10906
+transformers/models/videomt/video_processing_videomt.py,sha256=9iQVTcPcArCtaWL52TcY0Z9Zkn106V8W7D5ZBXt0AXg,15131
+transformers/models/vilt/__init__.py,sha256=wXLTYxA0_y41V2AwsQ2MGwuNYjsn29iV22IBLxurBcY,1153
+transformers/models/vilt/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/vilt/__pycache__/configuration_vilt.cpython-312.pyc,,
+transformers/models/vilt/__pycache__/image_processing_pil_vilt.cpython-312.pyc,,
+transformers/models/vilt/__pycache__/image_processing_vilt.cpython-312.pyc,,
+transformers/models/vilt/__pycache__/modeling_vilt.cpython-312.pyc,,
+transformers/models/vilt/__pycache__/processing_vilt.cpython-312.pyc,,
+transformers/models/vilt/configuration_vilt.py,sha256=qa5V7b0tQtjrYzYYU0w_fxZL6Nv7E0_6312g6T8jrzI,3063
+transformers/models/vilt/image_processing_pil_vilt.py,sha256=D2d_Don1d5g76WQp2UaxiH2nTnp-FlzHtnt1IjfmEHg,8355
+transformers/models/vilt/image_processing_vilt.py,sha256=pVo_2ZJyr6efD5tyFrBlpE2APmMhm6GxNL3tWcaPHww,8911
+transformers/models/vilt/modeling_vilt.py,sha256=-8Zphkj2B2wlMYH_Fe_2BiWbZo5S8XJclrMgSIYZ0rI,53875
+transformers/models/vilt/processing_vilt.py,sha256=ENfJmMX9MAGot1QsNiYnsyDF48iIXqs5eH4XnM74paM,1408
+transformers/models/vipllava/__init__.py,sha256=HJ5mZUNdt_bmaC9l-GycD7mVT2r1oN15prmnlBtz6oA,997
+transformers/models/vipllava/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/vipllava/__pycache__/configuration_vipllava.cpython-312.pyc,,
+transformers/models/vipllava/__pycache__/modeling_vipllava.cpython-312.pyc,,
+transformers/models/vipllava/__pycache__/modular_vipllava.cpython-312.pyc,,
+transformers/models/vipllava/configuration_vipllava.py,sha256=i0Q2Iz20IVvERIeDqfGNVoErKzmInJOoJ1YEFm7a15g,3657
+transformers/models/vipllava/modeling_vipllava.py,sha256=39elQwdwHdHzCU6ALm-yK-PJe4vk-kis3eXbiJecxHI,18963
+transformers/models/vipllava/modular_vipllava.py,sha256=piW8BuJyGCb_PjPJ4xMMEgvmHLAJbhClaXkJd5s8MiU,11880
+transformers/models/vision_encoder_decoder/__init__.py,sha256=noRw3j3TsUX_pmu-lPHZtprgJIRoohYtpDl-Ebwbfgo,1025
+transformers/models/vision_encoder_decoder/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/vision_encoder_decoder/__pycache__/configuration_vision_encoder_decoder.cpython-312.pyc,,
+transformers/models/vision_encoder_decoder/__pycache__/modeling_vision_encoder_decoder.cpython-312.pyc,,
+transformers/models/vision_encoder_decoder/configuration_vision_encoder_decoder.py,sha256=epYbn0sqGDGxBSu0BvvsqbbhuRwuhRCk3ppW7E0mNn4,3915
+transformers/models/vision_encoder_decoder/modeling_vision_encoder_decoder.py,sha256=KNHRYUHfkWzSvuI9J8g_C_L863vRkyiI_M0hCpEHm3k,21907
+transformers/models/vision_text_dual_encoder/__init__.py,sha256=j-CUSG80TkFAaWDzRmQSBgARhrzpHUaKWQUPJ2ZdvIw,1084
+transformers/models/vision_text_dual_encoder/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/vision_text_dual_encoder/__pycache__/configuration_vision_text_dual_encoder.cpython-312.pyc,,
+transformers/models/vision_text_dual_encoder/__pycache__/modeling_vision_text_dual_encoder.cpython-312.pyc,,
+transformers/models/vision_text_dual_encoder/__pycache__/processing_vision_text_dual_encoder.cpython-312.pyc,,
+transformers/models/vision_text_dual_encoder/configuration_vision_text_dual_encoder.py,sha256=DoHfqAFUDAd9_ICYen718uL6uHQywgundtQDwzrMQ-4,4211
+transformers/models/vision_text_dual_encoder/modeling_vision_text_dual_encoder.py,sha256=Iv6xMf_BJmDFOtfM0D1uiMDWabm5-vnPBvVRg4KZTJE,17591
+transformers/models/vision_text_dual_encoder/processing_vision_text_dual_encoder.py,sha256=2EGdP2Ram632GK8HbvjxpKZGwAEDGke9vIZfccaI2hw,1082
+transformers/models/visual_bert/__init__.py,sha256=zZFHfkE7OUMZUwYvB7v4ZIBXVUW9Mboqoa1QdTQURWM,1003
+transformers/models/visual_bert/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/visual_bert/__pycache__/configuration_visual_bert.cpython-312.pyc,,
+transformers/models/visual_bert/__pycache__/modeling_visual_bert.cpython-312.pyc,,
+transformers/models/visual_bert/configuration_visual_bert.py,sha256=UNwACCAXiGxOWUvlJDEHp0H69NRSp6nqYMXAkF6dTyg,3060
+transformers/models/visual_bert/modeling_visual_bert.py,sha256=69KbqCHp5oe7v69moVkAU0W2jN_0HE3QUhaGvT3dv8Q,66962
+transformers/models/vit/__init__.py,sha256=Ita-fCuC3YieMWokmDOnTmcc74Yhq-F33T681BMOyFk,1071
+transformers/models/vit/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/vit/__pycache__/configuration_vit.cpython-312.pyc,,
+transformers/models/vit/__pycache__/image_processing_pil_vit.cpython-312.pyc,,
+transformers/models/vit/__pycache__/image_processing_vit.cpython-312.pyc,,
+transformers/models/vit/__pycache__/modeling_vit.cpython-312.pyc,,
+transformers/models/vit/configuration_vit.py,sha256=DshReU4mkhVEZpFezXNEq3f0K4wcp4MgeL_p5a9eUGw,2548
+transformers/models/vit/image_processing_pil_vit.py,sha256=TQ4jRG5x6Kp_64yMtP3sorODCHoSo5RpZEDCmz9z6VM,1102
+transformers/models/vit/image_processing_vit.py,sha256=V378rqRjAm_qvKkBZzsj5CHPy-NUSnnzr_2tWsOCE8Q,1112
+transformers/models/vit/modeling_vit.py,sha256=1ujhjQ18Mr6qxnK1cB8eg9ct9ieB55-FCMp_PcDbneI,23560
+transformers/models/vit_mae/__init__.py,sha256=yrtk-59bpQGketwQFpVmON5rOe7GOctf8NJJZH09WBk,995
+transformers/models/vit_mae/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/vit_mae/__pycache__/configuration_vit_mae.cpython-312.pyc,,
+transformers/models/vit_mae/__pycache__/modeling_vit_mae.cpython-312.pyc,,
+transformers/models/vit_mae/__pycache__/modular_vit_mae.cpython-312.pyc,,
+transformers/models/vit_mae/configuration_vit_mae.py,sha256=jV9h1-KoWYT9Zj81Y-XajsM9xFKiVc10va0KGzPb4h0,2579
+transformers/models/vit_mae/modeling_vit_mae.py,sha256=jMXLbMCEfsvuA-UgfGX1whbGS4F0RIoKgisqZMsJiDk,35751
+transformers/models/vit_mae/modular_vit_mae.py,sha256=jJHnqj9OKevfvv8SYPoP6saTA1RVAUuG8M8lRDww85g,26311
+transformers/models/vit_msn/__init__.py,sha256=Y1g56VRSNr-PxS-g4Cp2IlRR5M9CiaFGlhAQXwszGHo,995
+transformers/models/vit_msn/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/vit_msn/__pycache__/configuration_vit_msn.cpython-312.pyc,,
+transformers/models/vit_msn/__pycache__/modeling_vit_msn.cpython-312.pyc,,
+transformers/models/vit_msn/__pycache__/modular_vit_msn.cpython-312.pyc,,
+transformers/models/vit_msn/configuration_vit_msn.py,sha256=XpXGCjQ9Rpf9U9DKXh52LKxw6iXPUHQ0KnVKWC4fbkY,1849
+transformers/models/vit_msn/modeling_vit_msn.py,sha256=sQvYLzrpkhv53xPQHtro2slmap3Q1r9MH3pmr61-Goo,19269
+transformers/models/vit_msn/modular_vit_msn.py,sha256=u_78ycDajh2OA-XkxeeGDucf_QIv7Wk-3p_55CCJsB0,7917
+transformers/models/vitdet/__init__.py,sha256=13LNGZwvKK3tBrQWVs43rQbxbgqvxLfnM0uMqomHqhM,993
+transformers/models/vitdet/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/vitdet/__pycache__/configuration_vitdet.cpython-312.pyc,,
+transformers/models/vitdet/__pycache__/modeling_vitdet.cpython-312.pyc,,
+transformers/models/vitdet/configuration_vitdet.py,sha256=DYTlclzspkdKbEOY3-5XgZDN4VIQWSSqZwb7FxxxF0M,3322
+transformers/models/vitdet/modeling_vitdet.py,sha256=N8YMrNJBXYjFE04rYOW7uYWYTduendr8nRHPXVED4Uc,29743
+transformers/models/vitmatte/__init__.py,sha256=4-Uh6Qxw-qpu14KSFlQSAv-9_BDRSzMvelQaUPucCb8,1091
+transformers/models/vitmatte/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/vitmatte/__pycache__/configuration_vitmatte.cpython-312.pyc,,
+transformers/models/vitmatte/__pycache__/image_processing_pil_vitmatte.cpython-312.pyc,,
+transformers/models/vitmatte/__pycache__/image_processing_vitmatte.cpython-312.pyc,,
+transformers/models/vitmatte/__pycache__/modeling_vitmatte.cpython-312.pyc,,
+transformers/models/vitmatte/configuration_vitmatte.py,sha256=mGvvvWPZ3tnH0zAd7ehxbVTk3qtX1wPTSUnW5J41VgE,2673
+transformers/models/vitmatte/image_processing_pil_vitmatte.py,sha256=2oc939KldPwrvfLtbBUvZHux_z4049FYGdBScU3YMVs,5636
+transformers/models/vitmatte/image_processing_vitmatte.py,sha256=-GJjqiQy4rrJ8qW74XV6-27auhBSw_gqUhQMrWLT-VU,5794
+transformers/models/vitmatte/modeling_vitmatte.py,sha256=5X7jPWJ3Xp1vVk7kH8M2-80bsHP2Mx13v4uQpcIlXrE,10875
+transformers/models/vitpose/__init__.py,sha256=PGMZ4xQHHhtqNYuZLaObMqVwYlgIGIY_X8K7tRPw00g,1087
+transformers/models/vitpose/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/vitpose/__pycache__/configuration_vitpose.cpython-312.pyc,,
+transformers/models/vitpose/__pycache__/image_processing_pil_vitpose.cpython-312.pyc,,
+transformers/models/vitpose/__pycache__/image_processing_vitpose.cpython-312.pyc,,
+transformers/models/vitpose/__pycache__/modeling_vitpose.cpython-312.pyc,,
+transformers/models/vitpose/configuration_vitpose.py,sha256=1LlpT3UKxA-dxxdwzPYLZhei7bO0qcSpgT0C9rzrto8,2395
+transformers/models/vitpose/image_processing_pil_vitpose.py,sha256=W9V8f-F6m2pL_x86pAjDSfSYW3HgLFnwXeN_X1d76WI,22522
+transformers/models/vitpose/image_processing_vitpose.py,sha256=BkIf3UL_O-oc2O7w6_8bTRKMUcYUKMg4vzW23MUFsA0,22243
+transformers/models/vitpose/modeling_vitpose.py,sha256=vAX7_tHZ7m8VCnxIVRYi4LgHc4NubLLDLtz9LIO0oJ0,11652
+transformers/models/vitpose_backbone/__init__.py,sha256=W5IjP47Ykg5KRs8S9ztAbtfQ__n6sbJUZG4UDIGdGmA,577
+transformers/models/vitpose_backbone/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/vitpose_backbone/__pycache__/configuration_vitpose_backbone.cpython-312.pyc,,
+transformers/models/vitpose_backbone/__pycache__/modeling_vitpose_backbone.cpython-312.pyc,,
+transformers/models/vitpose_backbone/configuration_vitpose_backbone.py,sha256=WW9-eX206N6uyHMSgC12tBRSrVDwnex2gGYqJ7jI944,2583
+transformers/models/vitpose_backbone/modeling_vitpose_backbone.py,sha256=x1C5rUSDFjNiSmryO2BHM7ZaQZjsPYra7whJDh7MIIY,17247
+transformers/models/vits/__init__.py,sha256=7baZcqGvFlYQxAl721XtMptMZKkzvBOa2ttyOhqhUtk,1026
+transformers/models/vits/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/vits/__pycache__/configuration_vits.cpython-312.pyc,,
+transformers/models/vits/__pycache__/modeling_vits.cpython-312.pyc,,
+transformers/models/vits/__pycache__/tokenization_vits.cpython-312.pyc,,
+transformers/models/vits/configuration_vits.py,sha256=DM7NcXbzSMAYq00P5SSH12ksDikL-9sPdqJ4DJF9AUY,8827
+transformers/models/vits/modeling_vits.py,sha256=UVn4tSlK6VQ555ckZ_R20zHNbc4z1xBjxVTc0-aVJOc,61622
+transformers/models/vits/tokenization_vits.py,sha256=0TjYs-5TIx7K5ujDYCYz-bEl2SEOBrtM6of2chEqXaU,9402
+transformers/models/vivit/__init__.py,sha256=NcvgOiAvEwB5OEb-FVURjqYeumrzls_aqjCscrWkrgg,1075
+transformers/models/vivit/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/vivit/__pycache__/configuration_vivit.cpython-312.pyc,,
+transformers/models/vivit/__pycache__/image_processing_vivit.cpython-312.pyc,,
+transformers/models/vivit/__pycache__/modeling_vivit.cpython-312.pyc,,
+transformers/models/vivit/__pycache__/modular_vivit.cpython-312.pyc,,
+transformers/models/vivit/__pycache__/video_processing_vivit.cpython-312.pyc,,
+transformers/models/vivit/configuration_vivit.py,sha256=m7EQ26S6dCTdP0EjwcR8iMz2cwa4dxLxNBeLxETXr0U,2642
+transformers/models/vivit/image_processing_vivit.py,sha256=joPnjlboVqwtiVLZJ6IwxpJM0LGInpmXH8vxhiJJHPE,18645
+transformers/models/vivit/modeling_vivit.py,sha256=Z3fnLS0PWyj5LIn5C1dbODyalHL_cGFKP8D59C_4b9k,24030
+transformers/models/vivit/modular_vivit.py,sha256=i-5o6jtYCjpa0u2oeEd5bUk5OPKSDFIw1Kh2RzzF6o4,15642
+transformers/models/vivit/video_processing_vivit.py,sha256=4eBfdaYhNLI8dKP_I_f3JnmGA_AW15PPg5IvDintJ_0,1943
+transformers/models/vjepa2/__init__.py,sha256=VpyCyuPpmmGMFjOOK4dG0E14Kb_wv5vn3CWyJ7dG7zk,1041
+transformers/models/vjepa2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/vjepa2/__pycache__/configuration_vjepa2.cpython-312.pyc,,
+transformers/models/vjepa2/__pycache__/modeling_vjepa2.cpython-312.pyc,,
+transformers/models/vjepa2/__pycache__/video_processing_vjepa2.cpython-312.pyc,,
+transformers/models/vjepa2/configuration_vjepa2.py,sha256=NrxwKmwvPKJADvx7WElKOPjuwYj_SWdzWryKDj71HB4,3483
+transformers/models/vjepa2/modeling_vjepa2.py,sha256=xlIWcYeXAhf1CCmWjV2YHDALRZfI5Iv19AYeQ-hjxOM,41607
+transformers/models/vjepa2/video_processing_vjepa2.py,sha256=EAhWf1LAr8WF5cu_QNG34Wa6gDnDP__jyGdrZ-bRpFM,1739
+transformers/models/voxtral/__init__.py,sha256=79Rf85nRl4CR_MQPk1x12SviCaAnMITesrFTeeX4F8g,1038
+transformers/models/voxtral/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/voxtral/__pycache__/configuration_voxtral.cpython-312.pyc,,
+transformers/models/voxtral/__pycache__/modeling_voxtral.cpython-312.pyc,,
+transformers/models/voxtral/__pycache__/modular_voxtral.cpython-312.pyc,,
+transformers/models/voxtral/__pycache__/processing_voxtral.cpython-312.pyc,,
+transformers/models/voxtral/configuration_voxtral.py,sha256=f_TwyxL9iM2mVZMuHW32IXN9PtnyRoKSlt2Re_IIrwo,4708
+transformers/models/voxtral/modeling_voxtral.py,sha256=kYoq78L8rrMF_cOATR1jH71s20m2GLi89bLfmw0vCUQ,24774
+transformers/models/voxtral/modular_voxtral.py,sha256=J88gR2vstk6RevK7FFgpsUNvfiGfZGRIrhZszSk6SlY,15014
+transformers/models/voxtral/processing_voxtral.py,sha256=GOe33EWj3RA_dXJQQLo8nfN-QmvVyyWWfwnOUTAzNHs,17967
+transformers/models/voxtral_realtime/__init__.py,sha256=7xSSVk6n6J-niLQixx6mUsLLsaNU7PEGwibIyIiGBhk,1065
+transformers/models/voxtral_realtime/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/voxtral_realtime/__pycache__/configuration_voxtral_realtime.cpython-312.pyc,,
+transformers/models/voxtral_realtime/__pycache__/feature_extraction_voxtral_realtime.cpython-312.pyc,,
+transformers/models/voxtral_realtime/__pycache__/modeling_voxtral_realtime.cpython-312.pyc,,
+transformers/models/voxtral_realtime/__pycache__/modular_voxtral_realtime.cpython-312.pyc,,
+transformers/models/voxtral_realtime/__pycache__/processing_voxtral_realtime.cpython-312.pyc,,
+transformers/models/voxtral_realtime/configuration_voxtral_realtime.py,sha256=qI1IjXQs3rXNQghWlfImQ-hefpEU7wXUovp92oQCmHs,7173
+transformers/models/voxtral_realtime/feature_extraction_voxtral_realtime.py,sha256=9CQ7XAjgXJ1WWpu3wSPzQGFnJtnyBddt8s6fdHhLR5M,11565
+transformers/models/voxtral_realtime/modeling_voxtral_realtime.py,sha256=RHIUvYk2uTt0_xjgkL8dzIOr2Q4kzbSg-bR5wsoMGWM,56807
+transformers/models/voxtral_realtime/modular_voxtral_realtime.py,sha256=bVXPO_TFKCkgYNlqK6wUU0NtaKlaxOkQ7t91ebTsjwc,38557
+transformers/models/voxtral_realtime/processing_voxtral_realtime.py,sha256=3kk8ePc247IEX39a_-6jda6BtDm38lEYS0r6SjOngKc,9294
+transformers/models/wav2vec2/__init__.py,sha256=jc_01S-UEuKOfO2DY2mzogAoCZnLvrTlS_yDV9SQW5w,1124
+transformers/models/wav2vec2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/wav2vec2/__pycache__/configuration_wav2vec2.cpython-312.pyc,,
+transformers/models/wav2vec2/__pycache__/feature_extraction_wav2vec2.cpython-312.pyc,,
+transformers/models/wav2vec2/__pycache__/modeling_wav2vec2.cpython-312.pyc,,
+transformers/models/wav2vec2/__pycache__/processing_wav2vec2.cpython-312.pyc,,
+transformers/models/wav2vec2/__pycache__/tokenization_wav2vec2.cpython-312.pyc,,
+transformers/models/wav2vec2/configuration_wav2vec2.py,sha256=CYCxx16uhWXRms39ZiOfUr6eqqNLSNX3Imbaz8BrflU,14302
+transformers/models/wav2vec2/feature_extraction_wav2vec2.py,sha256=5emguvcHFv7lA_T2anphMSoTK-mJstfiZJ4FfMvvosw,11461
+transformers/models/wav2vec2/modeling_wav2vec2.py,sha256=xASYLjoGOl9o7oWAk1bIpe0prSTIRB7qHVY0ale12gw,92024
+transformers/models/wav2vec2/processing_wav2vec2.py,sha256=la2vToOYyj1yVw66MpJdzZZO07ACfvmr_x_SRUqW1Vk,4105
+transformers/models/wav2vec2/tokenization_wav2vec2.py,sha256=tPj4CDjkYrxdd7OZiqUAh5vczpUXeSI8lM4Sb3_6aPI,28090
+transformers/models/wav2vec2_bert/__init__.py,sha256=DL010VL3ZV3lAugPH-BOTNSgIedotOEaoy8iHo0sC1Q,1051
+transformers/models/wav2vec2_bert/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/wav2vec2_bert/__pycache__/configuration_wav2vec2_bert.cpython-312.pyc,,
+transformers/models/wav2vec2_bert/__pycache__/modeling_wav2vec2_bert.cpython-312.pyc,,
+transformers/models/wav2vec2_bert/__pycache__/modular_wav2vec2_bert.cpython-312.pyc,,
+transformers/models/wav2vec2_bert/__pycache__/processing_wav2vec2_bert.cpython-312.pyc,,
+transformers/models/wav2vec2_bert/configuration_wav2vec2_bert.py,sha256=9GCZ1OA9fHcMmLO16Ox_RxmFB0HHG04Dcp-vkrwDOXg,11824
+transformers/models/wav2vec2_bert/modeling_wav2vec2_bert.py,sha256=kTtqyfrSSG26fUrCAqPnw5e7EpLmVhz4lix39PNe9B4,66600
+transformers/models/wav2vec2_bert/modular_wav2vec2_bert.py,sha256=Jd58F5KH-6Tr4slaObECfAAO1f8Rng7-zbWjdAQy7RU,45254
+transformers/models/wav2vec2_bert/processing_wav2vec2_bert.py,sha256=EVdhaO29UKL23HTimd5t0a1wTW6O9Vi5WCNGC_HZcsQ,4230
+transformers/models/wav2vec2_conformer/__init__.py,sha256=JBpapW8VF3yck4Bk29xKyUiQZqB_CXLSYtYxXGXAu2Q,1017
+transformers/models/wav2vec2_conformer/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/wav2vec2_conformer/__pycache__/configuration_wav2vec2_conformer.cpython-312.pyc,,
+transformers/models/wav2vec2_conformer/__pycache__/modeling_wav2vec2_conformer.cpython-312.pyc,,
+transformers/models/wav2vec2_conformer/__pycache__/modular_wav2vec2_conformer.cpython-312.pyc,,
+transformers/models/wav2vec2_conformer/configuration_wav2vec2_conformer.py,sha256=SYNCtL6H8Qu0efLZzcyL3TrLdd8TjLjMkNOmsuaOuJk,14641
+transformers/models/wav2vec2_conformer/modeling_wav2vec2_conformer.py,sha256=Rp6Orr-czN8S0w9KUTQ8IjBnizvizDoM-Bg1X4n5K-g,85937
+transformers/models/wav2vec2_conformer/modular_wav2vec2_conformer.py,sha256=dM2lABAaU5qk-Dym5-gXwSJBUSBPuGjLVlOEUiR94l0,30722
+transformers/models/wav2vec2_phoneme/__init__.py,sha256=LV4FKcFYNt0GuJvfsUOwTYVFRVfuzUuclKRybFyN9lk,967
+transformers/models/wav2vec2_phoneme/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/wav2vec2_phoneme/__pycache__/tokenization_wav2vec2_phoneme.cpython-312.pyc,,
+transformers/models/wav2vec2_phoneme/tokenization_wav2vec2_phoneme.py,sha256=ABoQNU_fWDw3SNiYLd2OnUVLXOgt4by88dePK-b0O04,23447
+transformers/models/wav2vec2_with_lm/__init__.py,sha256=yZKHsma85j7AMLB8g8uNXL5D_E5Gc3Vqe-D-V2W15oY,965
+transformers/models/wav2vec2_with_lm/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/wav2vec2_with_lm/__pycache__/processing_wav2vec2_with_lm.cpython-312.pyc,,
+transformers/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.py,sha256=6bEmU89PTxhJNqc_V5LvU6W58DRIg1VilqaIH37NLx8,27463
+transformers/models/wavlm/__init__.py,sha256=wYnYuOpw2e95lauqDbD7u3OC-Pez8yoRsrgExSh_WJQ,991
+transformers/models/wavlm/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/wavlm/__pycache__/configuration_wavlm.cpython-312.pyc,,
+transformers/models/wavlm/__pycache__/modeling_wavlm.cpython-312.pyc,,
+transformers/models/wavlm/__pycache__/modular_wavlm.cpython-312.pyc,,
+transformers/models/wavlm/configuration_wavlm.py,sha256=KrOmZioLKzrH5pY_wZ3y-o91-UQRZODefmllvfy2ELM,13102
+transformers/models/wavlm/modeling_wavlm.py,sha256=SGSDNkHH1CYjBGnq3PleQociv05N0Pm2h6Px7tK4W2M,70077
+transformers/models/wavlm/modular_wavlm.py,sha256=h253S-vcfhHzMjbdUTZA8bPVGiGG9kGeqTp8y5j7IGk,23198
+transformers/models/whisper/__init__.py,sha256=0PLlY8YXw9EADkK4hYK-E8ZaR_46sujYbzefSXOyQD4,1119
+transformers/models/whisper/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/whisper/__pycache__/configuration_whisper.cpython-312.pyc,,
+transformers/models/whisper/__pycache__/english_normalizer.cpython-312.pyc,,
+transformers/models/whisper/__pycache__/feature_extraction_whisper.cpython-312.pyc,,
+transformers/models/whisper/__pycache__/generation_whisper.cpython-312.pyc,,
+transformers/models/whisper/__pycache__/modeling_whisper.cpython-312.pyc,,
+transformers/models/whisper/__pycache__/processing_whisper.cpython-312.pyc,,
+transformers/models/whisper/__pycache__/tokenization_whisper.cpython-312.pyc,,
+transformers/models/whisper/configuration_whisper.py,sha256=x3HTAnnts4VAIF3eImbyieTPufz7ErGu5Dsz3sOTPDg,8252
+transformers/models/whisper/english_normalizer.py,sha256=7MFEktX8DRMyrqNymmzcfExIrqcr7OrPy824R7bBrIM,22804
+transformers/models/whisper/feature_extraction_whisper.py,sha256=NKbYqtn38nSBliKSnk_3S-KhNvzWH4Dslo-eBcRcfzo,16784
+transformers/models/whisper/generation_whisper.py,sha256=8Zdxhb4QeloYS4jzDFajv673WjSQi8Uru_WW4TGGR28,109268
+transformers/models/whisper/modeling_whisper.py,sha256=qQZbAurmCtC0fsLnI3mXHZdCOO5BKELdD4rVh2b0jl0,58774
+transformers/models/whisper/processing_whisper.py,sha256=lAYDAlcpwO0fDd-zO-NzIChkdsIO1UgqvYBuY5oCMNY,2101
+transformers/models/whisper/tokenization_whisper.py,sha256=yJsyKIb6EzErLslIM4pAAbZrajNhRXXpbRppLfIRqvI,57946
+transformers/models/x_clip/__init__.py,sha256=ufjh6w7SNuNAUjAHp_MK3yRcrHm22-SfhZ0ZfbiXhGw,1030
+transformers/models/x_clip/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/x_clip/__pycache__/configuration_x_clip.cpython-312.pyc,,
+transformers/models/x_clip/__pycache__/modeling_x_clip.cpython-312.pyc,,
+transformers/models/x_clip/__pycache__/modular_x_clip.cpython-312.pyc,,
+transformers/models/x_clip/__pycache__/processing_x_clip.cpython-312.pyc,,
+transformers/models/x_clip/configuration_x_clip.py,sha256=FoHTTx10kvsBaEt0icZekct0gg84aBaIr4NyasWn34c,10522
+transformers/models/x_clip/modeling_x_clip.py,sha256=EcVL6z8dxeaUHwoPXVj7Zrz007mLWWGmsxWiVjU5Nvw,50052
+transformers/models/x_clip/modular_x_clip.py,sha256=0HwdttRxpqvMh82lcsQPZAfc94kgRmPwnyIWeRtz1I4,32106
+transformers/models/x_clip/processing_x_clip.py,sha256=AaC-M8E_T81jOsoUkFPKmePxi4bfeNX42VGeg2ZOUOg,1350
+transformers/models/xcodec/__init__.py,sha256=X16pTVB3loZ9OMnqHAaxInF1X5EOhxlmHjyxEvoqSWE,993
+transformers/models/xcodec/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/xcodec/__pycache__/configuration_xcodec.cpython-312.pyc,,
+transformers/models/xcodec/__pycache__/modeling_xcodec.cpython-312.pyc,,
+transformers/models/xcodec/configuration_xcodec.py,sha256=1kJbitzfARoDLPQQjRg_-uLnJXOqSbihFaS3x7uKlY4,5902
+transformers/models/xcodec/modeling_xcodec.py,sha256=IYhBG2keeP1-qKKqYbsmCojt6ODSdOharwmCMI8EIsc,25688
+transformers/models/xglm/__init__.py,sha256=9hKLQSFEPq3h3EOSrIJj7Hex0mtUKMx_OvplVlDmuOA,1026
+transformers/models/xglm/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/xglm/__pycache__/configuration_xglm.cpython-312.pyc,,
+transformers/models/xglm/__pycache__/modeling_xglm.cpython-312.pyc,,
+transformers/models/xglm/__pycache__/tokenization_xglm.cpython-312.pyc,,
+transformers/models/xglm/configuration_xglm.py,sha256=uf6vuLHecMAVo2INS-vZcGhmXbkEIWbZLCNMKhtwM84,2211
+transformers/models/xglm/modeling_xglm.py,sha256=CzWExtjBUfEo9zpE_vWlrvAzkNs39xq1Vz60QQ9wlbA,25389
+transformers/models/xglm/tokenization_xglm.py,sha256=5uQZlWjFNi5fw3KeDqxoUfIujDsRHE6KJxUVtNSFfiM,5185
+transformers/models/xlm/__init__.py,sha256=P7Y7S7kLVM6Ww21JlaJYU7wmWagdieMfBoTycNZ5syU,1023
+transformers/models/xlm/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/xlm/__pycache__/configuration_xlm.cpython-312.pyc,,
+transformers/models/xlm/__pycache__/modeling_xlm.cpython-312.pyc,,
+transformers/models/xlm/__pycache__/tokenization_xlm.cpython-312.pyc,,
+transformers/models/xlm/configuration_xlm.py,sha256=ysvTYuD4GItkwlhfFGXtzj-fLy0vyzd5H5vN9MsWkZo,6475
+transformers/models/xlm/modeling_xlm.py,sha256=A34z7CtFjImg_X6FhRk8bUFkJb38S02jACECk1Gk3bQ,73207
+transformers/models/xlm/tokenization_xlm.py,sha256=g_yHWpJ34iTTN0oOsAzoGgjuWrygv-PLv6NDkxpTXBg,23357
+transformers/models/xlm_roberta/__init__.py,sha256=-FQ--ViqECUGBbnvEqwsodV_ZHis5j565quw2s3ZoU0,1096
+transformers/models/xlm_roberta/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/xlm_roberta/__pycache__/configuration_xlm_roberta.cpython-312.pyc,,
+transformers/models/xlm_roberta/__pycache__/modeling_xlm_roberta.cpython-312.pyc,,
+transformers/models/xlm_roberta/__pycache__/modular_xlm_roberta.cpython-312.pyc,,
+transformers/models/xlm_roberta/__pycache__/tokenization_xlm_roberta.cpython-312.pyc,,
+transformers/models/xlm_roberta/configuration_xlm_roberta.py,sha256=6jBP_CJbY0A5P0sm8rsL-767cZgvn4CsKrp4QGv-LtI,2232
+transformers/models/xlm_roberta/modeling_xlm_roberta.py,sha256=ZRSd0J2wEFXLIsYnxsrk_CvxTgt83erb8Q7UssjyaNU,52959
+transformers/models/xlm_roberta/modular_xlm_roberta.py,sha256=h5gMUNCgRlBoWixb5o4BiKEflVTDqer82zsnwl7Eg30,23214
+transformers/models/xlm_roberta/tokenization_xlm_roberta.py,sha256=i6wWn0MEPhKAGBwq8BeumibFuuHBsThxY8lVHZzZz8Y,4797
+transformers/models/xlm_roberta_xl/__init__.py,sha256=V0fXTKk2hQmf5dKogCJ0HSiRBxVX-rs7c414ZoZIh28,1009
+transformers/models/xlm_roberta_xl/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/xlm_roberta_xl/__pycache__/configuration_xlm_roberta_xl.cpython-312.pyc,,
+transformers/models/xlm_roberta_xl/__pycache__/modeling_xlm_roberta_xl.cpython-312.pyc,,
+transformers/models/xlm_roberta_xl/__pycache__/modular_xlm_roberta_xl.cpython-312.pyc,,
+transformers/models/xlm_roberta_xl/configuration_xlm_roberta_xl.py,sha256=s9e4ySoaRizdBRmpxxLpOij0GWK7vJvHUFyDNs-wdms,2155
+transformers/models/xlm_roberta_xl/modeling_xlm_roberta_xl.py,sha256=8Z-MzsuQj3W8QNEKkjCs6JyN3AchSTASKTDuPcIE3og,50670
+transformers/models/xlm_roberta_xl/modular_xlm_roberta_xl.py,sha256=cXWX6ibWwqyO_TlkUqQfFCKIsWyxSVcQ_Ekok5j9U5Y,29529
+transformers/models/xlnet/__init__.py,sha256=duiSzkjZEX4hcXiYQ6O49FLoa5UMuKtMahrF5QnDM_Y,1029
+transformers/models/xlnet/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/xlnet/__pycache__/configuration_xlnet.cpython-312.pyc,,
+transformers/models/xlnet/__pycache__/modeling_xlnet.cpython-312.pyc,,
+transformers/models/xlnet/__pycache__/tokenization_xlnet.cpython-312.pyc,,
+transformers/models/xlnet/configuration_xlnet.py,sha256=-ft7dQIZiKTW5OwlnmNxqKs4dzXyuX6tzDcs2xcOfZs,7395
+transformers/models/xlnet/modeling_xlnet.py,sha256=WPb_XUVw5OoCq5Pu5E2I-5DlbO-EPM22Tbi1oQkIlvg,97592
+transformers/models/xlnet/tokenization_xlnet.py,sha256=Rrp8n_Gu1yofyNhWkgjpEb7Zs0Iz2kCecCJE1xFPqfM,7668
+transformers/models/xlstm/__init__.py,sha256=-Vfj7bUcDAD3TguoDgKW0zpzZ8KtOmnUNwSkvL6Df8k,1047
+transformers/models/xlstm/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/xlstm/__pycache__/configuration_xlstm.cpython-312.pyc,,
+transformers/models/xlstm/__pycache__/modeling_xlstm.cpython-312.pyc,,
+transformers/models/xlstm/configuration_xlstm.py,sha256=gX8soEBBt8uf3INB9Uq8M3WB6o_n6e7ydJZV61TFT-M,8784
+transformers/models/xlstm/modeling_xlstm.py,sha256=vWpkRte_EnQD129Ebxs7eEpIhQAGUzxkiUFaGVk6Mi8,64486
+transformers/models/xmod/__init__.py,sha256=WLxIbzC8oCEkMrerWHTy7GLopz0mqocSaacdcyb_BhQ,989
+transformers/models/xmod/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/xmod/__pycache__/configuration_xmod.cpython-312.pyc,,
+transformers/models/xmod/__pycache__/modeling_xmod.cpython-312.pyc,,
+transformers/models/xmod/configuration_xmod.py,sha256=bgn19ArFFByKdXvlJguIvo-oMhqW-itSDqYwCLr-aEQ,3606
+transformers/models/xmod/modeling_xmod.py,sha256=RXpxrrpTnvAO9kJQK_U2kdnQKUYHAPHtnQD4r41skHs,58904
+transformers/models/yolos/__init__.py,sha256=aGARuEDHTEmtBPKs9T3yV49dgN-6XxyaHWyVU8p1y10,1123
+transformers/models/yolos/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/yolos/__pycache__/configuration_yolos.cpython-312.pyc,,
+transformers/models/yolos/__pycache__/image_processing_pil_yolos.cpython-312.pyc,,
+transformers/models/yolos/__pycache__/image_processing_yolos.cpython-312.pyc,,
+transformers/models/yolos/__pycache__/modeling_yolos.cpython-312.pyc,,
+transformers/models/yolos/__pycache__/modular_yolos.cpython-312.pyc,,
+transformers/models/yolos/configuration_yolos.py,sha256=Os0ca2K6cK9fQAsHjahINQPh1-eirpcq2IMqxy2--tM,2375
+transformers/models/yolos/image_processing_pil_yolos.py,sha256=gWZ6G6i4w8drEKCk04_wBVpGwN4Cc_wm_5ltrlkbQBw,31696
+transformers/models/yolos/image_processing_yolos.py,sha256=kWDrP4k8j8pO4ozo-NeHH0LRS3a88C8HB8aH5sGDU58,30972
+transformers/models/yolos/modeling_yolos.py,sha256=Jp8xtTdgilXyZllJd0FfQjd5GsOT-4p-jdKtSju0Yxk,27845
+transformers/models/yolos/modular_yolos.py,sha256=8RhdlkJNxG7gazrl2csU7srOIDCieaBxP0zqHlbRCTo,13228
+transformers/models/yoso/__init__.py,sha256=sCXsXYZuOQLFkZMexRb8qY7EJCftR54G_eO7qIUvdss,989
+transformers/models/yoso/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/yoso/__pycache__/configuration_yoso.cpython-312.pyc,,
+transformers/models/yoso/__pycache__/modeling_yoso.cpython-312.pyc,,
+transformers/models/yoso/configuration_yoso.py,sha256=xzal0mp-2h20SPljuzo7malXzPzwT8IqOLsKXHkBrqo,2925
+transformers/models/yoso/modeling_yoso.py,sha256=_OGJ_fdQpKfqoq4KDa2S_TVrRQHjm5YVplWIw0tcnxI,46028
+transformers/models/youtu/__init__.py,sha256=NiHuSA5gdHBMrrsi5C8nCRGL5LRvKkEBf2hAzzT-csU,996
+transformers/models/youtu/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/youtu/__pycache__/configuration_youtu.cpython-312.pyc,,
+transformers/models/youtu/__pycache__/modeling_youtu.cpython-312.pyc,,
+transformers/models/youtu/__pycache__/modular_youtu.cpython-312.pyc,,
+transformers/models/youtu/configuration_youtu.py,sha256=Hs_FZYmo9QYlswxHm8-1n2nSBkVUWTR-a21Spf9xsGA,4648
+transformers/models/youtu/modeling_youtu.py,sha256=-ZPD6711xI1iFaA6LFdaX492waD2BEbkRBKfV7POZ9o,26775
+transformers/models/youtu/modular_youtu.py,sha256=rCRa0ACcaNG_hNqcCUnjUieMGAo0usINMDm5WOskZSU,4718
+transformers/models/zamba/__init__.py,sha256=iqZnf8BQ49TLcB4mYwIfuJeF4aGvYhOBRiGI6_74ZFk,991
+transformers/models/zamba/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/zamba/__pycache__/configuration_zamba.cpython-312.pyc,,
+transformers/models/zamba/__pycache__/modeling_zamba.cpython-312.pyc,,
+transformers/models/zamba/configuration_zamba.py,sha256=2r_T2Kmv0sBEOsbQ5156ixc9AcRrqnS4uZ4rSWLUcg0,5219
+transformers/models/zamba/modeling_zamba.py,sha256=YHxLtmHr8tGhC1BqTLG7OomMMwfsoi1YSD16zEAth6k,46131
+transformers/models/zamba2/__init__.py,sha256=3FgH8KelorllnKF6ncpKGREwZXt6YwsQ7NPS8W6jcmQ,993
+transformers/models/zamba2/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/zamba2/__pycache__/configuration_zamba2.cpython-312.pyc,,
+transformers/models/zamba2/__pycache__/modeling_zamba2.cpython-312.pyc,,
+transformers/models/zamba2/__pycache__/modular_zamba2.cpython-312.pyc,,
+transformers/models/zamba2/configuration_zamba2.py,sha256=71KFo8lR4xJNktM-xkAC5FnMWDtGg7Q6LRRU0npg_KQ,6302
+transformers/models/zamba2/modeling_zamba2.py,sha256=JjkBj0PWfAiSmIORjwDfCd-ikSh4ZVB755JSD2zCqkc,68890
+transformers/models/zamba2/modular_zamba2.py,sha256=u47z1iB7t5iOAyLC1Pr65K8ifI2CZ1eqBROZRxwX87I,50882
+transformers/models/zoedepth/__init__.py,sha256=-pRvtmHlAg4fxJIWt7FH3jdjRe26ds27bQlNh3DpQUA,1091
+transformers/models/zoedepth/__pycache__/__init__.cpython-312.pyc,,
+transformers/models/zoedepth/__pycache__/configuration_zoedepth.cpython-312.pyc,,
+transformers/models/zoedepth/__pycache__/image_processing_pil_zoedepth.cpython-312.pyc,,
+transformers/models/zoedepth/__pycache__/image_processing_zoedepth.cpython-312.pyc,,
+transformers/models/zoedepth/__pycache__/modeling_zoedepth.cpython-312.pyc,,
+transformers/models/zoedepth/configuration_zoedepth.py,sha256=gx4v59i5ylh67kGggXOfgjAtP9bR6aLGqQprNisUVtY,8347
+transformers/models/zoedepth/image_processing_pil_zoedepth.py,sha256=gQ3M0OMByp3LPqZwQb0UbpDmPBsawpzjVR8XTXtdxa4,14682
+transformers/models/zoedepth/image_processing_zoedepth.py,sha256=X8w_iwEka3DNlTUXke28SL-vpsmWrjohDpeFGwcUGv0,14539
+transformers/models/zoedepth/modeling_zoedepth.py,sha256=58Imq0ERBe4M5-tTtIHBMkstqDMYUXUwraoQRACQWpA,54317
+transformers/monkey_patching.py,sha256=uEOoWsO_srjco546jvmcgixW9T03U4KCWjF5UnW0GIY,13972
+transformers/optimization.py,sha256=mF-L72CPpX3SwB6ThpQkrRk__oLwM5DyLP09PKmdrSc,55023
+transformers/pipelines/__init__.py,sha256=EGj1YxrMJ7x8A1D9Dr-zmCXCWryTzkjSiFflgrn35U0,69138
+transformers/pipelines/__pycache__/__init__.cpython-312.pyc,,
+transformers/pipelines/__pycache__/any_to_any.cpython-312.pyc,,
+transformers/pipelines/__pycache__/audio_classification.cpython-312.pyc,,
+transformers/pipelines/__pycache__/audio_utils.cpython-312.pyc,,
+transformers/pipelines/__pycache__/automatic_speech_recognition.cpython-312.pyc,,
+transformers/pipelines/__pycache__/base.cpython-312.pyc,,
+transformers/pipelines/__pycache__/depth_estimation.cpython-312.pyc,,
+transformers/pipelines/__pycache__/document_question_answering.cpython-312.pyc,,
+transformers/pipelines/__pycache__/feature_extraction.cpython-312.pyc,,
+transformers/pipelines/__pycache__/fill_mask.cpython-312.pyc,,
+transformers/pipelines/__pycache__/image_classification.cpython-312.pyc,,
+transformers/pipelines/__pycache__/image_feature_extraction.cpython-312.pyc,,
+transformers/pipelines/__pycache__/image_segmentation.cpython-312.pyc,,
+transformers/pipelines/__pycache__/image_text_to_text.cpython-312.pyc,,
+transformers/pipelines/__pycache__/keypoint_matching.cpython-312.pyc,,
+transformers/pipelines/__pycache__/mask_generation.cpython-312.pyc,,
+transformers/pipelines/__pycache__/object_detection.cpython-312.pyc,,
+transformers/pipelines/__pycache__/pt_utils.cpython-312.pyc,,
+transformers/pipelines/__pycache__/table_question_answering.cpython-312.pyc,,
+transformers/pipelines/__pycache__/text_classification.cpython-312.pyc,,
+transformers/pipelines/__pycache__/text_generation.cpython-312.pyc,,
+transformers/pipelines/__pycache__/text_to_audio.cpython-312.pyc,,
+transformers/pipelines/__pycache__/token_classification.cpython-312.pyc,,
+transformers/pipelines/__pycache__/video_classification.cpython-312.pyc,,
+transformers/pipelines/__pycache__/zero_shot_audio_classification.cpython-312.pyc,,
+transformers/pipelines/__pycache__/zero_shot_classification.cpython-312.pyc,,
+transformers/pipelines/__pycache__/zero_shot_image_classification.cpython-312.pyc,,
+transformers/pipelines/__pycache__/zero_shot_object_detection.cpython-312.pyc,,
+transformers/pipelines/any_to_any.py,sha256=aRklb9FyBtIcKeyTwBbi1RpY0FnNYmS0j2ITPzglBWQ,25677
+transformers/pipelines/audio_classification.py,sha256=8_GyRAEBXcaQmroip7XR_t5c9FSuB4YCTiGci5nhHKk,11091
+transformers/pipelines/audio_utils.py,sha256=WsfwXqFVypl161NslcANX5KSb8yNWZaJ8iMJc74oIqg,12191
+transformers/pipelines/automatic_speech_recognition.py,sha256=OyUvGyXLl90WxIjn1QA65ysZKLaN8Vbfjz1xwuwAdpw,35970
+transformers/pipelines/base.py,sha256=VkOybq3GkCAI2uUZb29dwXBnCs0GQ72QOdgbGiMA7-0,58739
+transformers/pipelines/depth_estimation.py,sha256=DskN8ZSr9fG63bxB2MLoL6baSLd5AnXd8edlHZgyi6U,6115
+transformers/pipelines/document_question_answering.py,sha256=8T_7lmHlUKQK11X5MIis9dpP5nBUXKJtxqdx3xZutNw,29474
+transformers/pipelines/feature_extraction.py,sha256=bvhwET2PwuMMHTXyO-IZTzuy78eoYUm-wO9mNbVyqTU,3406
+transformers/pipelines/fill_mask.py,sha256=3Au1MFhfq2x7fCP_66yKI1rnkvNTQk8TdORtcaulsLc,11064
+transformers/pipelines/image_classification.py,sha256=94dhxM9yixOWl6caJooKU_LkbUE20IqUcqsplVKFlfg,9880
+transformers/pipelines/image_feature_extraction.py,sha256=KdDTJoXMg8tuGGXmGEsXlEN3G_-qNiJB2NoRznjY13w,4794
+transformers/pipelines/image_segmentation.py,sha256=AkJiNMpo5h7P6yAOIrKzhuJqkv6cxT_lZTRVFLd-L_M,9748
+transformers/pipelines/image_text_to_text.py,sha256=m5d8dxF-T9KcJDH0bT56zns6ciJ2mod3qR2zqqpRxa4,22710
+transformers/pipelines/keypoint_matching.py,sha256=yf6w0ru1iPRKhkE3Z11lVGzPfnf_-zUCpTIHliRoa6s,7056
+transformers/pipelines/mask_generation.py,sha256=nj1V99f0Hfn2z99xZDSeYd8TDnmvgQtlLtmrlK136oE,15328
+transformers/pipelines/object_detection.py,sha256=B6iAuT0x5XaZxcZExjyC8fYGykaKDuiaiMMlihQ1F9g,8346
+transformers/pipelines/pt_utils.py,sha256=DtNVgO1ud1n0bYMwJclMvnIJqtoNs9aedcXuCvJL_SM,12816
+transformers/pipelines/table_question_answering.py,sha256=ZAkeA2UISRSkCMph6JEMuPnaoDgyD_7hAixIxO1cD_I,17171
+transformers/pipelines/text_classification.py,sha256=C66ihBlJVY0H-H7YlqY88RdbHhTuBROh7HIOVl4FNPs,9975
+transformers/pipelines/text_generation.py,sha256=ZalwrpfcjLjrRB9h2Bls6IEkcmSkpVZlX_jUR0jJhtQ,25003
+transformers/pipelines/text_to_audio.py,sha256=kF-edXfARjvSZH0v1readQA1DwOMVBXDqnVRsquUv6k,13209
+transformers/pipelines/token_classification.py,sha256=XN9Ddck_SQMqCFPXqn9u1B-_1INa3FgHXRCWrQ2gNZQ,28638
+transformers/pipelines/video_classification.py,sha256=eP-6vHQdT3LGN-cjzfTBMTL9vzC1k-2ZbRgt3W8C-Zg,8970
+transformers/pipelines/zero_shot_audio_classification.py,sha256=iAcpyeO3QLGkliwHe7mha7AlDy2NNGv6WtbI7-5QqIY,6687
+transformers/pipelines/zero_shot_classification.py,sha256=B-0_i7OVYbyBA2wo3izjL__AxiEXW0JoOPNtyxMaqAQ,11976
+transformers/pipelines/zero_shot_image_classification.py,sha256=Ph0sKorUOLy5CZbQHLVZ5YH096vPMXirILFsu9hACCE,7644
+transformers/pipelines/zero_shot_object_detection.py,sha256=g6X6znGVEZYDbXUB1EuaglZgzRQJ_bbCYpbcLwRqs_8,10393
+transformers/processing_utils.py,sha256=Rez-MC0oADKmIVN_DGYiA2zIJsHS7vFTVJyD997fiIY,114634
+transformers/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+transformers/pytorch_utils.py,sha256=HRrgl9LJtKFlFr1YjylByRs-yfiuWt6Q4Y2_qp9YiJQ,10077
+transformers/quantizers/__init__.py,sha256=S_xTSTbkDOvjLgR3jgR4EAkP_sc3NE8e38T-lllAaNo,800
+transformers/quantizers/__pycache__/__init__.cpython-312.pyc,,
+transformers/quantizers/__pycache__/auto.cpython-312.pyc,,
+transformers/quantizers/__pycache__/base.cpython-312.pyc,,
+transformers/quantizers/__pycache__/quantizer_aqlm.cpython-312.pyc,,
+transformers/quantizers/__pycache__/quantizer_auto_round.cpython-312.pyc,,
+transformers/quantizers/__pycache__/quantizer_awq.cpython-312.pyc,,
+transformers/quantizers/__pycache__/quantizer_bitnet.cpython-312.pyc,,
+transformers/quantizers/__pycache__/quantizer_bnb_4bit.cpython-312.pyc,,
+transformers/quantizers/__pycache__/quantizer_bnb_8bit.cpython-312.pyc,,
+transformers/quantizers/__pycache__/quantizer_compressed_tensors.cpython-312.pyc,,
+transformers/quantizers/__pycache__/quantizer_eetq.cpython-312.pyc,,
+transformers/quantizers/__pycache__/quantizer_fbgemm_fp8.cpython-312.pyc,,
+transformers/quantizers/__pycache__/quantizer_finegrained_fp8.cpython-312.pyc,,
+transformers/quantizers/__pycache__/quantizer_fouroversix.cpython-312.pyc,,
+transformers/quantizers/__pycache__/quantizer_fp_quant.cpython-312.pyc,,
+transformers/quantizers/__pycache__/quantizer_gemma.cpython-312.pyc,,
+transformers/quantizers/__pycache__/quantizer_gptq.cpython-312.pyc,,
+transformers/quantizers/__pycache__/quantizer_higgs.cpython-312.pyc,,
+transformers/quantizers/__pycache__/quantizer_hqq.cpython-312.pyc,,
+transformers/quantizers/__pycache__/quantizer_metal.cpython-312.pyc,,
+transformers/quantizers/__pycache__/quantizer_mxfp4.cpython-312.pyc,,
+transformers/quantizers/__pycache__/quantizer_quanto.cpython-312.pyc,,
+transformers/quantizers/__pycache__/quantizer_quark.cpython-312.pyc,,
+transformers/quantizers/__pycache__/quantizer_sinq.cpython-312.pyc,,
+transformers/quantizers/__pycache__/quantizer_spqr.cpython-312.pyc,,
+transformers/quantizers/__pycache__/quantizer_torchao.cpython-312.pyc,,
+transformers/quantizers/__pycache__/quantizer_vptq.cpython-312.pyc,,
+transformers/quantizers/__pycache__/quantizers_utils.cpython-312.pyc,,
+transformers/quantizers/auto.py,sha256=qXQTxYPGnygm9osXVjuF5BTsbaVmayONtUQBSL6PaVw,14857
+transformers/quantizers/base.py,sha256=QU4Uw8H5U-c7qFdieoN3S3HG9xwkuZHZZl-ZVPUyRFg,13608
+transformers/quantizers/quantizer_aqlm.py,sha256=tRWPXukjDmjQew9Sgu2QgPTBjzFQ6ji9iQ4gEi8wj1M,2646
+transformers/quantizers/quantizer_auto_round.py,sha256=VbVkIrKju6WyP5UrhgEVMBap46MWURP_M2WeHqqfpV4,2686
+transformers/quantizers/quantizer_awq.py,sha256=89Fe0GoH0vAb0EWSMhAFiKuqQDiCQ5yKDC34xQwSyFw,3771
+transformers/quantizers/quantizer_bitnet.py,sha256=Q_vbb_Z5q3tW9U1oCehXMzM7TlvXaNaSdluzL0u6lgw,4533
+transformers/quantizers/quantizer_bnb_4bit.py,sha256=KE3udSduVhR3Q8RrFa9MaFW8QW8km1Msn74lq-E6DLw,7270
+transformers/quantizers/quantizer_bnb_8bit.py,sha256=BPQFSQE1ZViSI5qcxzzi8tq6qqdMR0CwkTmbcMWIffc,6923
+transformers/quantizers/quantizer_compressed_tensors.py,sha256=pIv3LbnhZMBszOWqd1xG2M5CcWF6IXimcWlgcUC8DHY,4409
+transformers/quantizers/quantizer_eetq.py,sha256=UQpOQWCFAYoEhiB8Vsi-b40IzTPKsSaBLa-f9lkpT_A,3934
+transformers/quantizers/quantizer_fbgemm_fp8.py,sha256=--Oto-hdz1JBiLsXbvYQ7rzFxNbbToNKGWPLS7O-1Cc,9825
+transformers/quantizers/quantizer_finegrained_fp8.py,sha256=9OLwGkeoMpq7RBaAfg0NFH2Ty5mpaO_uDsrBnFS7jgU,14422
+transformers/quantizers/quantizer_fouroversix.py,sha256=eL_u6i2GvWb5CQeiNEWHf_CcebB5x8FT6zA0OdulQKQ,4144
+transformers/quantizers/quantizer_fp_quant.py,sha256=OA65chvHA8Z7n8SscdwUold6TxHOX3j-8JlJCZCRQN0,6872
+transformers/quantizers/quantizer_gemma.py,sha256=koSWNUChbLI3MSXvk1VtAwgg-g_ZFNGFMi0Zg5PN6-8,2719
+transformers/quantizers/quantizer_gptq.py,sha256=g_0zWDKrYsz5rVwz0oLEfb56gjRGbSRoRp7o-21bU9Q,4503
+transformers/quantizers/quantizer_higgs.py,sha256=7RYLwxhEYxpKAwsTkSWcwpM0G3ItwmvHbSCMwWM0KB8,7485
+transformers/quantizers/quantizer_hqq.py,sha256=B_Dmp_ER6PF9QS_uE1B8337aNqoMtbZG-POgq5mNpu4,11172
+transformers/quantizers/quantizer_metal.py,sha256=K-gyirnXW8vZdVHAbfiphHMZgLvHDJPP4HXYaxwc7M4,4994
+transformers/quantizers/quantizer_mxfp4.py,sha256=gq1Ixshp9Dk-9F5ZKqq-lwM_oahw8jwpfuqmubB1mSo,13273
+transformers/quantizers/quantizer_quanto.py,sha256=Oy2aCvIUtviM9w4oOxS-BFwQVkEZ0aALufO7axi_iKM,4801
+transformers/quantizers/quantizer_quark.py,sha256=TziQpZ4DqlgJ6oy-XX7ekEwfE1eT1mkAih0SpgqoWCA,3844
+transformers/quantizers/quantizer_sinq.py,sha256=2TkNgvkTMUenfIDHvjcI1v6NdxUZBo66wtpx0uD1HDs,9518
+transformers/quantizers/quantizer_spqr.py,sha256=tk98gIZuEjLjpeC_4UlAFtmHNY07fnYBmilXRNHlg30,2781
+transformers/quantizers/quantizer_torchao.py,sha256=q5SrY-XkohvRhu7FQN5ObOqFcDF0YFVQMZDUOXvYqSc,9378
+transformers/quantizers/quantizer_vptq.py,sha256=Uesk-rsBgzXKWt2iWiUl_mf4DtEztA19h2lJTo9FYk0,2509
+transformers/quantizers/quantizers_utils.py,sha256=k6ruOeKFG0dlUEYP0e7jRjVvPvbIv-gB_uH30SkFfyI,2469
+transformers/safetensors_conversion.py,sha256=aBJ_lN7RSXZ5uBQOu1BQY4eqlNkZCGhxIcVHhcsGSoU,4541
+transformers/testing_utils.py,sha256=e1yLE8_GfkWxMRtxwQWwDbb9Z6brfU_IeiUCDZ6prUI,161912
+transformers/time_series_utils.py,sha256=6wfH0kcAucf05T7HJcAAjETE2wcoNneAus2UDQRg_d4,7480
+transformers/tokenization_mistral_common.py,sha256=SeqiaUOpSMiOhmBot8eXwlOXIjcfzHCzwpooLz3t-2U,79888
+transformers/tokenization_python.py,sha256=IOca_9xIoPC8cW6k92ZoZt2jTGUEeGp6P2MpQBoMeXw,62933
+transformers/tokenization_utils_base.py,sha256=D0EQgyCyKUjOPtU9as9VxOiQCGt8qM67WUwjDfWNAVk,176709
+transformers/tokenization_utils_sentencepiece.py,sha256=eVBFeKcNFpODXnAtvHiLQvDk4POE-8BtAimXtAdHF_4,13649
+transformers/tokenization_utils_tokenizers.py,sha256=QUJ2npFHzTcefuSzJw9SEBP8vxMG_JhCqoe7UD-fZPs,66830
+transformers/trainer.py,sha256=waVkI_z8-c_saEdGf_suLIqanozBg2uCyH7QyB5QS-A,217203
+transformers/trainer_callback.py,sha256=qXA7YPPVhWJwVO2Xbso9vqaf3c_U6wGxzBm_9nvM8Ao,34363
+transformers/trainer_jit_checkpoint.py,sha256=0UPaTOmfMyssbS_VPrtB-FIoNOf6jMk8BVymIGQDMaw,5274
+transformers/trainer_optimizer.py,sha256=8mbJ0uivbRo5VvuA2Y2j54K8aNewoYgqQwP8HEbl5p4,23504
+transformers/trainer_pt_utils.py,sha256=7LzAPaoMCCieajZ6cIl_51nuelHhK0AhSsDGf8ywd0E,57264
+transformers/trainer_seq2seq.py,sha256=vsWC9y6KFqR6pOe8F9d5AVcD1wye88GDGqLlHVSjFPE,18217
+transformers/trainer_utils.py,sha256=wwIACyjGo41yjjj-2Djsoh7UQwEFgVoP3cXuouGhZiA,49916
+transformers/training_args.py,sha256=n476FXlU1pHSYPl93VDdKojHoZ2380Vyg8k0kvdUcDU,141713
+transformers/training_args_seq2seq.py,sha256=Cx0RKqvzMAe0KNApHdI2n7jJvwX09I2NsHYP1MdqcRs,4308
+transformers/utils/__init__.py,sha256=r3IuzEgEG2IlLeYX7VD4YQdaw7IIcHboHRnZLqlw7Bk,9669
+transformers/utils/__pycache__/__init__.cpython-312.pyc,,
+transformers/utils/__pycache__/attention_visualizer.cpython-312.pyc,,
+transformers/utils/__pycache__/auto_docstring.cpython-312.pyc,,
+transformers/utils/__pycache__/backbone_utils.cpython-312.pyc,,
+transformers/utils/__pycache__/chat_parsing_utils.cpython-312.pyc,,
+transformers/utils/__pycache__/chat_template_utils.cpython-312.pyc,,
+transformers/utils/__pycache__/constants.cpython-312.pyc,,
+transformers/utils/__pycache__/deprecation.cpython-312.pyc,,
+transformers/utils/__pycache__/doc.cpython-312.pyc,,
+transformers/utils/__pycache__/dummy_detectron2_objects.cpython-312.pyc,,
+transformers/utils/__pycache__/dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects.cpython-312.pyc,,
+transformers/utils/__pycache__/dummy_mistral_common_objects.cpython-312.pyc,,
+transformers/utils/__pycache__/dummy_music_objects.cpython-312.pyc,,
+transformers/utils/__pycache__/dummy_pt_objects.cpython-312.pyc,,
+transformers/utils/__pycache__/dummy_sentencepiece_and_tokenizers_objects.cpython-312.pyc,,
+transformers/utils/__pycache__/dummy_speech_objects.cpython-312.pyc,,
+transformers/utils/__pycache__/dummy_timm_and_torchvision_objects.cpython-312.pyc,,
+transformers/utils/__pycache__/dummy_tokenizers_objects.cpython-312.pyc,,
+transformers/utils/__pycache__/dummy_torchaudio_objects.cpython-312.pyc,,
+transformers/utils/__pycache__/dummy_torchvision_objects.cpython-312.pyc,,
+transformers/utils/__pycache__/dummy_vision_objects.cpython-312.pyc,,
+transformers/utils/__pycache__/generic.cpython-312.pyc,,
+transformers/utils/__pycache__/hp_naming.cpython-312.pyc,,
+transformers/utils/__pycache__/hub.cpython-312.pyc,,
+transformers/utils/__pycache__/import_utils.cpython-312.pyc,,
+transformers/utils/__pycache__/kernel_config.cpython-312.pyc,,
+transformers/utils/__pycache__/loading_report.cpython-312.pyc,,
+transformers/utils/__pycache__/logging.cpython-312.pyc,,
+transformers/utils/__pycache__/network_logging.cpython-312.pyc,,
+transformers/utils/__pycache__/notebook.cpython-312.pyc,,
+transformers/utils/__pycache__/output_capturing.cpython-312.pyc,,
+transformers/utils/__pycache__/peft_utils.cpython-312.pyc,,
+transformers/utils/__pycache__/pytest_helpers.cpython-312.pyc,,
+transformers/utils/__pycache__/quantization_config.cpython-312.pyc,,
+transformers/utils/__pycache__/sentencepiece_model_pb2.cpython-312.pyc,,
+transformers/utils/__pycache__/sentencepiece_model_pb2_new.cpython-312.pyc,,
+transformers/utils/__pycache__/type_validators.cpython-312.pyc,,
+transformers/utils/__pycache__/versions.cpython-312.pyc,,
+transformers/utils/attention_visualizer.py,sha256=3G1i4WtR53NkxOFYWXB9R_t-1rsztOXa9QWl-u7DWLY,10165
+transformers/utils/auto_docstring.py,sha256=HIBwSNudRbRa-aSWCAKvUYa76PgXBZrBY6vqScGH9mA,165700
+transformers/utils/backbone_utils.py,sha256=NBW7XA-8AA280RQ9sZaR6wYqy69bHeq0s_zpYlLN6us,699
+transformers/utils/chat_parsing_utils.py,sha256=LxxaVeD_LfUL5H3cgLHmNYqd3hJ-PHM1CoFy2x9bzTI,14433
+transformers/utils/chat_template_utils.py,sha256=o-bWD8C70lBUX1eWQDp5Ea8bYsNu8-d3uSjFs6vK5kM,26114
+transformers/utils/constants.py,sha256=sZsUwOnA3CbtN1svs9YoaNLTTsAc9RVaITsgpf8K4iI,282
+transformers/utils/deprecation.py,sha256=9eOb1v_hJIypO3SHeyOTCBAnJytxhrvGh8mXn6N6tL8,8031
+transformers/utils/doc.py,sha256=GDFiD2tFxHDC_5nj8U-xv9ZAgJ2wHv0ZNRiwKa05glk,36848
+transformers/utils/dummy_detectron2_objects.py,sha256=n7Pt_7sbVBNfohKGcOARB-ZcPcJRbjEAcoLd2vTXndU,340
+transformers/utils/dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects.py,sha256=n6pY4s7zCII3dzo7Ejd0RviHa_pMateuDEwbbHgsTUY,902
+transformers/utils/dummy_mistral_common_objects.py,sha256=_NEeG5StQyLHKZ_4OyTgvyxkxMBawME8knKX1y8Bqr8,309
+transformers/utils/dummy_music_objects.py,sha256=1lxIebYUOdHJWMQ_T5IQgPgcO_wp_8YM_HGc3skuGVg,458
+transformers/utils/dummy_pt_objects.py,sha256=LUjFUClNbtFkoRN5KCOkmhQ9WqryT5saqMMGgS9Zm1M,11926
+transformers/utils/dummy_sentencepiece_and_tokenizers_objects.py,sha256=BgPLr8Wz8A-17K86x04N21CKXtWNQLJEWx2c4aZRqaA,286
+transformers/utils/dummy_speech_objects.py,sha256=9eFm1cjdsYOPBoAz9JTgP35Bg8WF2C9AZ_y1hFpKZdQ,465
+transformers/utils/dummy_timm_and_torchvision_objects.py,sha256=EFuC5z6IsKOqqowoUGviJ3KgTjzvdTTN7gGQ3it-4t0,324
+transformers/utils/dummy_tokenizers_objects.py,sha256=PFIh5nBDmhWG2XDGuwIyBGldm6b_jdZdL3E8t5A8FsY,304
+transformers/utils/dummy_torchaudio_objects.py,sha256=EG0q0JkedoNb_4ntsf6EyTOE6Nr1whvHOzHPKy1t7x0,847
+transformers/utils/dummy_torchvision_objects.py,sha256=mLSiRl9kW2Vs6XEv_NCbB1CoEIGm0keFnfJBOn46cPQ,475
+transformers/utils/dummy_vision_objects.py,sha256=GDbX7-GrqykExLY91SMhSf508DinS5NSFfavbeDsCMU,630
+transformers/utils/generic.py,sha256=JSoXtz0CDfkBV-QDPi21HcrIwRyf-3mcM9UwKnHElk4,40695
+transformers/utils/hp_naming.py,sha256=vqcOXcDOyqbISWo8-ClUJUOBVbZM1h08EcymTwcRthc,4979
+transformers/utils/hub.py,sha256=dXxhcr3w8FbrU-Mq3XhCtP5X0rH9aKSSyzzAtg__rEw,39871
+transformers/utils/import_utils.py,sha256=hU9qmYoZTBLy6BP3RbYCqeeqeBaw4_QVPaGc-3CLYEY,116503
+transformers/utils/kernel_config.py,sha256=_TqlCUbNcg88ri5uIGHwoPeaQkN-8-V71WH5Kd9U_1M,10476
+transformers/utils/loading_report.py,sha256=3ktYjkVUOcdMKUn8FjWJ98RWJbghrmUvgL4Q518-6Ac,10033
+transformers/utils/logging.py,sha256=TzRj-DjzvCQ3c4req6H1Fp0wqFVb_zoWD5YuTtAp4JQ,13567
+transformers/utils/network_logging.py,sha256=kZ8YGx4d5HkF4rgkY3znHGt2X5bTrO_DS8LDwZChIvY,18667
+transformers/utils/notebook.py,sha256=tVSv51rr1WOrcLzm86ez3YEjxjVLPqiINZOFuoMCmmM,16526
+transformers/utils/output_capturing.py,sha256=ZfqTvP0jFNKmgMCMNpl3Py_-pENA6FzQ5jkmmLg7N7s,12675
+transformers/utils/peft_utils.py,sha256=lgB-0xIz8j1__nDS_ZIk5Uv00x4FTgC3_43RZmg0Giw,4841
+transformers/utils/pytest_helpers.py,sha256=WjWr38_XlTI7DkTdMAkKGo1pcSOYaq0uVwpD-PSV2IU,3571
+transformers/utils/quantization_config.py,sha256=imJBqxpdpxXcvUBHcEXLPYpmCthgLuSIhfQF91sYzQE,89609
+transformers/utils/sentencepiece_model_pb2.py,sha256=WcMZRm2-571XwxSfo-6FZih9fDy_Zl5mMwqrDrC1Dlg,50663
+transformers/utils/sentencepiece_model_pb2_new.py,sha256=ahaV--amhGIL3nXFCTHqezqxuGXm8SHr_C3Zvj7KbAY,6598
+transformers/utils/type_validators.py,sha256=kgcS2UdKeEGHVDnY9QxBEvoLIA7AJRTOmqG_KQC2TAY,10634
+transformers/utils/versions.py,sha256=755iVOeUIvKNgIbaCkO8P0P9xOAZFIf3C9EouPgxxF0,4306
+transformers/video_processing_utils.py,sha256=dryYiDVFwe96OpD30eU6WTpBdC8rUkTeFlVd4cY9FRo,39202
+transformers/video_utils.py,sha256=DRbtqg9VYKf0FTH0InSl3zoS0MZ7XFIgOns1Xty_zYo,34424
+transformers/vision_utils.py,sha256=cdwSYSOvwoSRR1Xmjw_FnQhG8fT0_UiWzkUe5zarMb8,10194
diff --git a/.venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/REQUESTED b/.venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..14a883f292bc96b20c2b76a3081991f2676523a9
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: setuptools (82.0.1)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/.venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/entry_points.txt b/.venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/entry_points.txt
new file mode 100644
index 0000000000000000000000000000000000000000..bf2a3b68e9616562bcdd157626656933ea607c29
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/entry_points.txt
@@ -0,0 +1,2 @@
+[console_scripts]
+transformers = transformers.cli.transformers:main
diff --git a/.venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/licenses/LICENSE b/.venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..68b7d66c97d66c58de883ed0c451af2b3183e6f3
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/licenses/LICENSE
@@ -0,0 +1,203 @@
+Copyright 2018- The Hugging Face team. All rights reserved.
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/.venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/top_level.txt b/.venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..976a2b1f3998279c10c413279a095be86bf69167
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/top_level.txt
@@ -0,0 +1 @@
+transformers
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/__pycache__/modeling_wav2vec2_bert.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/__pycache__/modeling_wav2vec2_bert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9ba1072e9fd79f8f8ecb8bbfd5c9b58ee61805f5
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/__pycache__/modeling_wav2vec2_bert.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/__pycache__/modular_wav2vec2_bert.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/__pycache__/modular_wav2vec2_bert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cd030ab0f6b17dd35d41aea8a74f032f335e3b6d
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/__pycache__/modular_wav2vec2_bert.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/__pycache__/processing_wav2vec2_bert.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/__pycache__/processing_wav2vec2_bert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aef08e1c38535f0357828459567d219b6e1e35a0
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/__pycache__/processing_wav2vec2_bert.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/configuration_wav2vec2_bert.py b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/configuration_wav2vec2_bert.py
new file mode 100644
index 0000000000000000000000000000000000000000..1961e4506f6d791344d841731235cc3454d3e8c8
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/configuration_wav2vec2_bert.py
@@ -0,0 +1,204 @@
+# Copyright 2024 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Wav2Vec2Bert model configuration"""
+
+from typing import Literal
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="facebook/wav2vec2-bert-rel-pos-large")
+@strict
+class Wav2Vec2BertConfig(PreTrainedConfig):
+ r"""
+ feature_projection_input_dim (`int`, *optional*, defaults to 160):
+ Input dimension of this model, i.e the dimension after processing input audios with [`SeamlessM4TFeatureExtractor`] or [`Wav2Vec2BertProcessor`].
+ feat_proj_dropout (`float`, *optional*, defaults to 0.0):
+ The dropout probability for the feature projection.
+ final_dropout (`float`, *optional*, defaults to 0.1):
+ The dropout probability for the final projection layer of [`Wav2Vec2BertForCTC`].
+ apply_spec_augment (`bool`, *optional*, defaults to `True`):
+ Whether to apply *SpecAugment* data augmentation to the outputs of the feature encoder. For reference see
+ [SpecAugment: A Simple Data Augmentation Method for Automatic Speech
+ Recognition](https://huggingface.co/papers/1904.08779).
+ mask_time_prob (`float`, *optional*, defaults to 0.05):
+ Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking
+ procedure generates `mask_time_prob*len(time_axis)/mask_time_length ``independent masks over the axis. If
+ reasoning from the probability of each feature vector to be chosen as the start of the vector span to be
+ masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the
+ actual percentage of masked vectors. This is only relevant if `apply_spec_augment is True`.
+ mask_time_length (`int`, *optional*, defaults to 10):
+ Length of vector span along the time axis.
+ mask_time_min_masks (`int`, *optional*, defaults to 2):
+ The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
+ irrespectively of `mask_feature_prob`. Only relevant if `mask_time_prob*len(time_axis)/mask_time_length <
+ mask_time_min_masks`.
+ mask_feature_prob (`float`, *optional*, defaults to 0.0):
+ Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
+ masking procedure generates `mask_feature_prob*len(feature_axis)/mask_time_length` independent masks over
+ the axis. If reasoning from the probability of each feature vector to be chosen as the start of the vector
+ span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap
+ may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is
+ True`.
+ mask_feature_length (`int`, *optional*, defaults to 10):
+ Length of vector span along the feature axis.
+ mask_feature_min_masks (`int`, *optional*, defaults to 0):
+ The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time
+ step, irrespectively of `mask_feature_prob`. Only relevant if
+ `mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks`.
+ ctc_zero_infinity (`bool`, *optional*, defaults to `False`):
+ Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly
+ occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance
+ of [`Wav2Vec2BertForCTC`].
+ use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):
+ Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an
+ instance of [`Wav2Vec2BertForSequenceClassification`].
+ classifier_proj_size (`int`, *optional*, defaults to 768):
+ Dimensionality of the projection before token mean-pooling for classification.
+ tdnn_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 1500)`):
+ A tuple of integers defining the number of output channels of each 1D convolutional layer in the *TDNN*
+ module of the *XVector* model. The length of *tdnn_dim* defines the number of *TDNN* layers.
+ tdnn_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 3, 3, 1, 1)`):
+ A tuple of integers defining the kernel size of each 1D convolutional layer in the *TDNN* module of the
+ *XVector* model. The length of *tdnn_kernel* has to match the length of *tdnn_dim*.
+ tdnn_dilation (`tuple[int]` or `list[int]`, *optional*, defaults to `(1, 2, 3, 1, 1)`):
+ A tuple of integers defining the dilation factor of each 1D convolutional layer in *TDNN* module of the
+ *XVector* model. The length of *tdnn_dilation* has to match the length of *tdnn_dim*.
+ xvector_output_dim (`int`, *optional*, defaults to 512):
+ Dimensionality of the *XVector* embedding vectors.
+ add_adapter (`bool`, *optional*, defaults to `False`):
+ Whether a convolutional attention network should be stacked on top of the Wav2Vec2Bert Encoder. Can be very
+ useful for warm-starting Wav2Vec2Bert for SpeechEncoderDecoder models.
+ adapter_kernel_size (`int`, *optional*, defaults to 3):
+ Kernel size of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.
+ adapter_stride (`int`, *optional*, defaults to 2):
+ Stride of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.
+ num_adapter_layers (`int`, *optional*, defaults to 1):
+ Number of convolutional layers that should be used in the adapter network. Only relevant if `add_adapter is
+ True`.
+ adapter_act (`str` or `function`, *optional*, defaults to `"relu"`):
+ The non-linear activation function (function or string) in the adapter layers. If string, `"gelu"`,
+ `"relu"`, `"selu"`, `"swish"` and `"gelu_new"` are supported.
+ use_intermediate_ffn_before_adapter (`bool`, *optional*, defaults to `False`):
+ Whether an intermediate feed-forward block should be stacked on top of the Wav2Vec2Bert Encoder and before the adapter network.
+ Only relevant if `add_adapter is True`.
+ output_hidden_size (`int`, *optional*):
+ Dimensionality of the encoder output layer. If not defined, this defaults to *hidden-size*. Only relevant
+ if `add_adapter is True`.
+ position_embeddings_type (`str`, *optional*, defaults to `"relative_key"`):
+ Can be specified to :
+ - `rotary`, for rotary position embeddings.
+ - `relative`, for relative position embeddings.
+ - `relative_key`, for relative position embeddings as defined by Shaw in [Self-Attention
+ with Relative Position Representations (Shaw et al.)](https://huggingface.co/papers/1803.02155).
+ If left to `None`, no relative position embeddings is applied.
+ rotary_embedding_base (`int`, *optional*, defaults to 10000):
+ If `"rotary"` position embeddings are used, defines the size of the embedding base.
+ max_source_positions (`int`, *optional*, defaults to 5000):
+ if `"relative"` position embeddings are used, defines the maximum source input positions.
+ left_max_position_embeddings (`int`, *optional*, defaults to 64):
+ If `"relative_key"` (aka Shaw) position embeddings are used, defines the left clipping value for relative positions.
+ right_max_position_embeddings (`int`, *optional*, defaults to 8):
+ If `"relative_key"` (aka Shaw) position embeddings are used, defines the right clipping value for relative positions.
+ conv_depthwise_kernel_size (`int`, *optional*, defaults to 31):
+ Kernel size of convolutional depthwise 1D layer in Conformer blocks.
+ conformer_conv_dropout (`float`, *optional*, defaults to 0.1):
+ The dropout probability for all convolutional layers in Conformer blocks.
+
+ Example:
+
+ ```python
+ >>> from transformers import Wav2Vec2BertConfig, Wav2Vec2BertModel
+
+ >>> # Initializing a Wav2Vec2Bert facebook/wav2vec2-bert-rel-pos-large style configuration
+ >>> configuration = Wav2Vec2BertConfig()
+
+ >>> # Initializing a model (with random weights) from the facebook/wav2vec2-bert-rel-pos-large style configuration
+ >>> model = Wav2Vec2BertModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "wav2vec2-bert"
+
+ vocab_size: int | None = None
+ hidden_size: int = 1024
+ num_hidden_layers: int = 24
+ num_attention_heads: int = 16
+ intermediate_size: int = 4096
+ feature_projection_input_dim: int = 160
+ hidden_act: str = "swish"
+ hidden_dropout: float | int = 0.0
+ activation_dropout: float | int = 0.0
+ attention_dropout: float | int = 0.0
+ feat_proj_dropout: float | int = 0.0
+ final_dropout: float | int = 0.1
+ layerdrop: float | int = 0.1
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-5
+ apply_spec_augment: bool = True
+ mask_time_prob: float | int = 0.05
+ mask_time_length: int = 10
+ mask_time_min_masks: int = 2
+ mask_feature_prob: float | int = 0.0
+ mask_feature_length: int = 10
+ mask_feature_min_masks: int = 0
+ ctc_loss_reduction: str = "sum"
+ ctc_zero_infinity: bool = False
+ use_weighted_layer_sum: bool = False
+ classifier_proj_size: int = 768
+ tdnn_dim: list[int] | tuple[int, ...] = (512, 512, 512, 512, 1500)
+ tdnn_kernel: list[int] | tuple[int, ...] = (5, 3, 3, 1, 1)
+ tdnn_dilation: list[int] | tuple[int, ...] = (1, 2, 3, 1, 1)
+ xvector_output_dim: int = 512
+ pad_token_id: int | None = 0
+ bos_token_id: int | None = 1
+ eos_token_id: int | list[int] | None = 2
+ add_adapter: bool = False
+ adapter_kernel_size: int = 3
+ adapter_stride: int = 2
+ num_adapter_layers: int = 1
+ adapter_act: str = "relu"
+ use_intermediate_ffn_before_adapter: bool = False
+ output_hidden_size: int | None = None
+ position_embeddings_type: Literal["rotary", "relative", "relative_key"] | None = "relative_key"
+ rotary_embedding_base: int = 10000
+ max_source_positions: int = 5000
+ left_max_position_embeddings: int = 64
+ right_max_position_embeddings: int = 8
+ conv_depthwise_kernel_size: int = 31
+ conformer_conv_dropout: float | int = 0.1
+
+ def __post_init__(self, **kwargs):
+ self.output_hidden_size = self.output_hidden_size or self.hidden_size
+ super().__post_init__(**kwargs)
+
+ def validate_architecture(self):
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
+ if self.use_intermediate_ffn_before_adapter and not self.add_adapter:
+ raise ValueError("`use_intermediate_ffn_before_adapter` is `True` but `add_adapter` is `False`.")
+
+ @property
+ def inputs_to_logits_ratio(self):
+ ratio = self.feature_projection_input_dim * 2
+ if self.add_adapter:
+ ratio = ratio * (self.adapter_stride**self.num_adapter_layers)
+ return ratio
+
+
+__all__ = ["Wav2Vec2BertConfig"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/modeling_wav2vec2_bert.py b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/modeling_wav2vec2_bert.py
new file mode 100644
index 0000000000000000000000000000000000000000..6023d856798b1aed1d64e3c37759be073d292bfc
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/modeling_wav2vec2_bert.py
@@ -0,0 +1,1529 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/wav2vec2_bert/modular_wav2vec2_bert.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_wav2vec2_bert.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+import math
+import warnings
+
+import numpy as np
+import torch
+from torch import nn
+from torch.nn import CrossEntropyLoss
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...integrations.deepspeed import is_deepspeed_zero3_enabled
+from ...integrations.fsdp import is_fsdp_managed_module
+from ...masking_utils import create_bidirectional_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutput,
+ CausalLMOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+ Wav2Vec2BaseModelOutput,
+ XVectorOutput,
+)
+from ...modeling_utils import PreTrainedModel
+from ...utils import auto_docstring, is_peft_available
+from .configuration_wav2vec2_bert import Wav2Vec2BertConfig
+
+
+class Wav2Vec2BertRotaryPositionalEmbedding(nn.Module):
+ """Rotary positional embedding
+ Reference : https://blog.eleuther.ai/rotary-embeddings/ Paper: https://huggingface.co/papers/2104.09864
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ dim = config.hidden_size // config.num_attention_heads
+ base = config.rotary_embedding_base
+
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).float() / dim))
+ # Ignore copy
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.cached_sequence_length = None
+ self.cached_rotary_positional_embedding = None
+
+ def forward(self, hidden_states):
+ sequence_length = hidden_states.shape[1]
+
+ if sequence_length == self.cached_sequence_length and self.cached_rotary_positional_embedding is not None:
+ return self.cached_rotary_positional_embedding
+
+ self.cached_sequence_length = sequence_length
+ # Embeddings are computed in the dtype of the inv_freq constant
+ time_stamps = torch.arange(sequence_length).type_as(self.inv_freq)
+ freqs = torch.einsum("i,j->ij", time_stamps, self.inv_freq)
+ embeddings = torch.cat((freqs, freqs), dim=-1)
+
+ cos_embeddings = embeddings.cos()[:, None, None, :]
+ sin_embeddings = embeddings.sin()[:, None, None, :]
+ # Computed embeddings are cast to the dtype of the hidden state inputs
+ self.cached_rotary_positional_embedding = torch.stack([cos_embeddings, sin_embeddings]).type_as(hidden_states)
+ return self.cached_rotary_positional_embedding
+
+
+class Wav2Vec2BertRelPositionalEmbedding(nn.Module):
+ """Relative positional encoding module."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.max_len = config.max_source_positions
+ self.d_model = config.hidden_size
+ self.register_buffer("pe", self.extend_pe(torch.tensor(0.0).expand(1, self.max_len)), persistent=False)
+
+ def extend_pe(self, x, pe=None):
+ # Reset the positional encodings
+ if pe is not None:
+ # self.pe contains both positive and negative parts
+ # the length of self.pe is 2 * input_len - 1
+ if pe.size(1) >= x.size(1) * 2 - 1:
+ if pe.dtype != x.dtype or pe.device != x.device:
+ pe = pe.to(dtype=x.dtype, device=x.device)
+ return pe
+ # Suppose `i` is the position of query vector and `j` is the
+ # position of key vector. We use positive relative positions when keys
+ # are to the left (i>j) and negative relative positions otherwise (i (batch, 2*channel, dim)
+ hidden_states = self.pointwise_conv1(hidden_states)
+ # => (batch, channel, dim)
+ hidden_states = self.glu(hidden_states)
+
+ # Pad the sequence entirely on the left because of causal convolution.
+ hidden_states = torch.nn.functional.pad(hidden_states, (self.depthwise_conv.kernel_size[0] - 1, 0))
+
+ # 1D Depthwise Conv
+ hidden_states = self.depthwise_conv(hidden_states)
+
+ hidden_states = self.depthwise_layer_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
+
+ hidden_states = self.activation(hidden_states)
+
+ hidden_states = self.pointwise_conv2(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = hidden_states.transpose(1, 2)
+ return hidden_states
+
+
+class Wav2Vec2BertSelfAttention(nn.Module):
+ """Construct an Wav2Vec2BertSelfAttention object.
+ Can be enhanced with rotary or relative position embeddings.
+ """
+
+ def __init__(self, config, is_adapter_attention=False):
+ super().__init__()
+ hidden_size = config.hidden_size if not is_adapter_attention else config.output_hidden_size
+
+ self.head_size = hidden_size // config.num_attention_heads
+ self.num_heads = config.num_attention_heads
+ self.position_embeddings_type = config.position_embeddings_type if not is_adapter_attention else None
+
+ self.linear_q = nn.Linear(hidden_size, hidden_size)
+ self.linear_k = nn.Linear(hidden_size, hidden_size)
+ self.linear_v = nn.Linear(hidden_size, hidden_size)
+ self.linear_out = nn.Linear(hidden_size, hidden_size)
+
+ self.dropout = nn.Dropout(p=config.attention_dropout)
+
+ if self.position_embeddings_type == "relative":
+ # linear transformation for positional encoding
+ self.linear_pos = nn.Linear(hidden_size, hidden_size, bias=False)
+ # these two learnable bias are used in matrix c and matrix d
+ # as described in https://huggingface.co/papers/1901.02860 Section 3.3
+ self.pos_bias_u = nn.Parameter(torch.zeros(self.num_heads, self.head_size))
+ self.pos_bias_v = nn.Parameter(torch.zeros(self.num_heads, self.head_size))
+
+ if self.position_embeddings_type == "relative_key":
+ self.left_max_position_embeddings = config.left_max_position_embeddings
+ self.right_max_position_embeddings = config.right_max_position_embeddings
+ num_positions = self.left_max_position_embeddings + self.right_max_position_embeddings + 1
+ self.distance_embedding = nn.Embedding(num_positions, self.head_size)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ relative_position_embeddings: torch.Tensor | None = None,
+ output_attentions: bool = False,
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
+ # self-attention mechanism
+ batch_size, sequence_length, hidden_size = hidden_states.size()
+
+ # make sure query/key states can be != value states
+ query_key_states = hidden_states
+ value_states = hidden_states
+
+ if self.position_embeddings_type == "rotary":
+ if relative_position_embeddings is None:
+ raise ValueError(
+ "`relative_position_embeddings` has to be defined when `self.position_embeddings_type == 'rotary'"
+ )
+ query_key_states = self._apply_rotary_embedding(query_key_states, relative_position_embeddings)
+
+ # project query_key_states and value_states
+ query = self.linear_q(query_key_states).view(batch_size, -1, self.num_heads, self.head_size)
+ key = self.linear_k(query_key_states).view(batch_size, -1, self.num_heads, self.head_size)
+ value = self.linear_v(value_states).view(batch_size, -1, self.num_heads, self.head_size)
+
+ # => (batch, head, time1, d_k)
+ query = query.transpose(1, 2)
+ key = key.transpose(1, 2)
+ value = value.transpose(1, 2)
+
+ if self.position_embeddings_type == "relative":
+ if relative_position_embeddings is None:
+ raise ValueError(
+ "`relative_position_embeddings` has to be defined when `self.position_embeddings_type =="
+ " 'relative'"
+ )
+ # apply relative_position_embeddings to qk scores
+ # as proposed in Transformer_XL: https://huggingface.co/papers/1901.02860
+ scores = self._apply_relative_embeddings(
+ query=query, key=key, relative_position_embeddings=relative_position_embeddings
+ )
+ else:
+ scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(self.head_size)
+
+ if self.position_embeddings_type == "relative_key":
+ query_length, key_length = query.shape[2], key.shape[2]
+
+ position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
+ position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
+ distance = position_ids_r - position_ids_l
+ distance = torch.clamp(distance, -self.left_max_position_embeddings, self.right_max_position_embeddings)
+
+ positional_embedding = self.distance_embedding(distance + self.left_max_position_embeddings)
+ positional_embedding = positional_embedding.to(dtype=query.dtype) # fp16 compatibility
+
+ relative_position_attn_weights = torch.einsum("bhld,lrd->bhlr", query, positional_embedding)
+ scores = scores + (relative_position_attn_weights / math.sqrt(self.head_size))
+
+ # apply attention_mask if necessary
+ if attention_mask is not None:
+ scores = scores + attention_mask
+
+ # => (batch, head, time1, time2)
+ probs = torch.softmax(scores, dim=-1)
+ probs = self.dropout(probs)
+
+ # => (batch, head, time1, d_k)
+ hidden_states = torch.matmul(probs, value)
+
+ # => (batch, time1, hidden_size)
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, self.num_heads * self.head_size)
+ hidden_states = self.linear_out(hidden_states)
+
+ return hidden_states, probs
+
+ def _apply_rotary_embedding(self, hidden_states, relative_position_embeddings):
+ batch_size, sequence_length, hidden_size = hidden_states.size()
+ hidden_states = hidden_states.view(batch_size, sequence_length, self.num_heads, self.head_size)
+
+ cos = relative_position_embeddings[0, :sequence_length, ...]
+ sin = relative_position_embeddings[1, :sequence_length, ...]
+
+ # rotate hidden_states with rotary embeddings
+ hidden_states = hidden_states.transpose(0, 1)
+ rotated_states_begin = hidden_states[..., : self.head_size // 2]
+ rotated_states_end = hidden_states[..., self.head_size // 2 :]
+ rotated_states = torch.cat((-rotated_states_end, rotated_states_begin), dim=rotated_states_begin.ndim - 1)
+ hidden_states = (hidden_states * cos) + (rotated_states * sin)
+ hidden_states = hidden_states.transpose(0, 1)
+
+ hidden_states = hidden_states.view(batch_size, sequence_length, self.num_heads * self.head_size)
+
+ return hidden_states
+
+ def _apply_relative_embeddings(self, query, key, relative_position_embeddings):
+ # 1. project positional embeddings
+ # => (batch, head, 2*time1-1, d_k)
+ proj_relative_position_embeddings = self.linear_pos(relative_position_embeddings)
+ proj_relative_position_embeddings = proj_relative_position_embeddings.view(
+ relative_position_embeddings.size(0), -1, self.num_heads, self.head_size
+ )
+ proj_relative_position_embeddings = proj_relative_position_embeddings.transpose(1, 2)
+ proj_relative_position_embeddings = proj_relative_position_embeddings.transpose(2, 3)
+
+ # 2. Add bias to query
+ # => (batch, head, time1, d_k)
+ query = query.transpose(1, 2)
+ q_with_bias_u = (query + self.pos_bias_u).transpose(1, 2)
+ q_with_bias_v = (query + self.pos_bias_v).transpose(1, 2)
+
+ # 3. attention score: first compute matrix a and matrix c
+ # as described in https://huggingface.co/papers/1901.02860 Section 3.3
+ # => (batch, head, time1, time2)
+ scores_ac = torch.matmul(q_with_bias_u, key.transpose(-2, -1))
+
+ # 4. then compute matrix b and matrix d
+ # => (batch, head, time1, 2*time1-1)
+ scores_bd = torch.matmul(q_with_bias_v, proj_relative_position_embeddings)
+
+ # 5. shift matrix b and matrix d
+ zero_pad = torch.zeros((*scores_bd.size()[:3], 1), device=scores_bd.device, dtype=scores_bd.dtype)
+ scores_bd_padded = torch.cat([zero_pad, scores_bd], dim=-1)
+ scores_bd_padded_shape = scores_bd.size()[:2] + (scores_bd.shape[3] + 1, scores_bd.shape[2])
+ scores_bd_padded = scores_bd_padded.view(*scores_bd_padded_shape)
+ scores_bd = scores_bd_padded[:, :, 1:].view_as(scores_bd)
+ scores_bd = scores_bd[:, :, :, : scores_bd.size(-1) // 2 + 1]
+
+ # 6. sum matrices
+ # => (batch, head, time1, time2)
+ scores = (scores_ac + scores_bd) / math.sqrt(self.head_size)
+
+ return scores
+
+
+class Wav2Vec2BertEncoderLayer(GradientCheckpointingLayer):
+ """Conformer block based on https://huggingface.co/papers/2005.08100."""
+
+ def __init__(self, config):
+ super().__init__()
+ embed_dim = config.hidden_size
+ dropout = config.attention_dropout
+
+ # Feed-forward 1
+ self.ffn1_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+ self.ffn1 = Wav2Vec2BertFeedForward(config)
+
+ # Self-Attention
+ self.self_attn_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+ self.self_attn_dropout = nn.Dropout(dropout)
+ self.self_attn = Wav2Vec2BertSelfAttention(config)
+
+ # Conformer Convolution
+ self.conv_module = Wav2Vec2BertConvolutionModule(config)
+
+ # Feed-forward 2
+ self.ffn2_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+ self.ffn2 = Wav2Vec2BertFeedForward(config)
+ self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask: torch.Tensor | None = None,
+ relative_position_embeddings: torch.Tensor | None = None,
+ output_attentions: bool = False,
+ conv_attention_mask: torch.Tensor | None = None,
+ ):
+ # 1. Feed-Forward 1 layer
+ residual = hidden_states
+ hidden_states = self.ffn1_layer_norm(hidden_states)
+ hidden_states = self.ffn1(hidden_states)
+ hidden_states = hidden_states * 0.5 + residual
+ residual = hidden_states
+
+ # 2. Self-Attention layer
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+ hidden_states, attn_weigts = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ relative_position_embeddings=relative_position_embeddings,
+ output_attentions=output_attentions,
+ )
+ hidden_states = self.self_attn_dropout(hidden_states)
+ hidden_states = hidden_states + residual
+
+ # 3. Convolutional Layer
+ residual = hidden_states
+ hidden_states = self.conv_module(hidden_states, attention_mask=conv_attention_mask)
+ hidden_states = residual + hidden_states
+
+ # 4. Feed-Forward 2 Layer
+ residual = hidden_states
+ hidden_states = self.ffn2_layer_norm(hidden_states)
+ hidden_states = self.ffn2(hidden_states)
+ hidden_states = hidden_states * 0.5 + residual
+ hidden_states = self.final_layer_norm(hidden_states)
+
+ return hidden_states, attn_weigts
+
+
+class Wav2Vec2BertEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+
+ if config.position_embeddings_type == "relative":
+ self.embed_positions = Wav2Vec2BertRelPositionalEmbedding(config)
+ elif config.position_embeddings_type == "rotary":
+ self.embed_positions = Wav2Vec2BertRotaryPositionalEmbedding(config)
+ else:
+ self.embed_positions = None
+
+ self.dropout = nn.Dropout(config.hidden_dropout)
+ self.layers = nn.ModuleList([Wav2Vec2BertEncoderLayer(config) for _ in range(config.num_hidden_layers)])
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ output_attentions=False,
+ output_hidden_states=False,
+ return_dict=True,
+ ):
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+
+ conv_attention_mask = attention_mask
+ if attention_mask is not None:
+ # make sure padded tokens output 0
+ hidden_states = hidden_states.masked_fill(~attention_mask.bool().unsqueeze(-1), 0.0)
+
+ # extend attention_mask
+ attention_mask = 1.0 - attention_mask[:, None, None, :].to(dtype=hidden_states.dtype)
+ attention_mask = attention_mask * torch.finfo(hidden_states.dtype).min
+ attention_mask = attention_mask.expand(
+ attention_mask.shape[0], 1, attention_mask.shape[-1], attention_mask.shape[-1]
+ )
+
+ hidden_states = self.dropout(hidden_states)
+
+ if self.embed_positions is not None:
+ relative_position_embeddings = self.embed_positions(hidden_states)
+ else:
+ relative_position_embeddings = None
+
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
+
+ for i, layer in enumerate(self.layers):
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
+ dropout_probability = torch.rand([])
+
+ skip_the_layer = self.training and dropout_probability < self.config.layerdrop
+ if not skip_the_layer or synced_gpus:
+ # under fsdp or deepspeed zero3 all gpus must run in sync
+ layer_outputs = layer(
+ hidden_states,
+ attention_mask=attention_mask,
+ relative_position_embeddings=relative_position_embeddings,
+ output_attentions=output_attentions,
+ conv_attention_mask=conv_attention_mask,
+ )
+ hidden_states = layer_outputs[0]
+
+ if skip_the_layer:
+ layer_outputs = (None, None)
+
+ if output_attentions:
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
+ return BaseModelOutput(
+ last_hidden_state=hidden_states,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ )
+
+
+class Wav2Vec2BertAdapter(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ # feature dim might need to be down-projected
+ if config.output_hidden_size != config.hidden_size:
+ self.proj = nn.Linear(config.hidden_size, config.output_hidden_size)
+ self.proj_layer_norm = nn.LayerNorm(config.output_hidden_size, eps=config.layer_norm_eps)
+ else:
+ self.proj = self.proj_layer_norm = None
+ self.layers = nn.ModuleList(Wav2Vec2BertAdapterLayer(config) for _ in range(config.num_adapter_layers))
+ self.layerdrop = config.layerdrop
+
+ self.kernel_size = config.adapter_kernel_size
+ self.stride = config.adapter_stride
+
+ def _compute_sub_sample_lengths_from_attention_mask(self, seq_lens):
+ if seq_lens is None:
+ return seq_lens
+ pad = self.kernel_size // 2
+ seq_lens = ((seq_lens + 2 * pad - self.kernel_size) / self.stride) + 1
+ return seq_lens.floor()
+
+ def forward(self, hidden_states, attention_mask=None):
+ # down project hidden_states if necessary
+ if self.proj is not None and self.proj_layer_norm is not None:
+ hidden_states = self.proj(hidden_states)
+ hidden_states = self.proj_layer_norm(hidden_states)
+
+ sub_sampled_lengths = None
+ if attention_mask is not None:
+ sub_sampled_lengths = (attention_mask.size(1) - (1 - attention_mask.int()).sum(1)).to(hidden_states.device)
+
+ for layer in self.layers:
+ layerdrop_prob = torch.rand([])
+ sub_sampled_lengths = self._compute_sub_sample_lengths_from_attention_mask(sub_sampled_lengths)
+ if not self.training or (layerdrop_prob > self.layerdrop):
+ hidden_states = layer(
+ hidden_states, attention_mask=attention_mask, sub_sampled_lengths=sub_sampled_lengths
+ )
+
+ return hidden_states
+
+
+# Copied from transformers.models.seamless_m4t_v2.modeling_seamless_m4t_v2._compute_new_attention_mask
+def _compute_new_attention_mask(hidden_states: torch.Tensor, seq_lens: torch.Tensor):
+ """
+ Computes an attention mask of the form `(batch, seq_len)` with an attention for each element in the batch that
+ stops at the corresponding element in `seq_lens`.
+ Args:
+ hidden_states (`torch.FloatTensor` of shape `(batch, seq_len, *)`):
+ The sequences to mask, where `*` is any number of sequence-specific dimensions including none.
+ seq_lens (`torch.Tensor` of shape `(batch)`:
+ Each element represents the length of the sequence at the same index in `hidden_states`
+ Returns:
+ `torch.FloatTensor`: The float attention mask of shape `(batch, seq_len)`
+ """
+ batch_size, mask_seq_len = hidden_states.shape[:2]
+
+ indices = torch.arange(mask_seq_len, device=seq_lens.device).expand(batch_size, -1)
+
+ bool_mask = indices >= seq_lens.unsqueeze(1).expand(-1, mask_seq_len)
+
+ mask = hidden_states.new_ones((batch_size, mask_seq_len))
+
+ mask = mask.masked_fill(bool_mask, 0)
+
+ return mask
+
+
+class Wav2Vec2BertAdapterLayer(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+
+ embed_dim = config.output_hidden_size
+ dropout = config.conformer_conv_dropout
+
+ self.kernel_size = config.adapter_kernel_size
+ self.stride = config.adapter_stride
+
+ # 1. residual convolution
+ self.residual_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+ self.residual_conv = nn.Conv1d(
+ embed_dim,
+ 2 * embed_dim,
+ self.kernel_size,
+ stride=self.stride,
+ padding=self.stride // 2,
+ )
+ self.activation = nn.GLU(dim=1)
+
+ # Self-Attention
+ self.self_attn_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+ self.self_attn_conv = nn.Conv1d(
+ embed_dim,
+ 2 * embed_dim,
+ self.kernel_size,
+ stride=self.stride,
+ padding=self.stride // 2,
+ )
+ self.self_attn = Wav2Vec2BertSelfAttention(config, is_adapter_attention=True)
+ self.self_attn_dropout = nn.Dropout(dropout)
+
+ # Feed-forward
+ self.ffn_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+ self.ffn = Wav2Vec2BertFeedForward(config, act_fn=config.adapter_act, hidden_size=embed_dim)
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask: torch.Tensor | None = None,
+ output_attentions: bool = False,
+ sub_sampled_lengths: torch.Tensor | None = None,
+ ):
+ residual = self.residual_layer_norm(hidden_states)
+
+ # Apply pooling to the residual to match the sequence length of the
+ # multi-head attention output.
+ # (batch, seq_len, feature_dim) -> (batch, feature_dim, seq_len)
+ residual = residual.transpose(1, 2)
+ residual = self.residual_conv(residual)
+ residual = self.activation(residual)
+ # (batch, feature_dim, seq_len) -> (batch, seq_len, feature_dim)
+ residual = residual.transpose(1, 2)
+
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+ # Apply pooling before feeding to the multihead-attention layer.
+ # (batch, seq_len, feature_dim) -> (batch, feature_dim, seq_len)
+ hidden_states = hidden_states.transpose(1, 2)
+ hidden_states = self.self_attn_conv(hidden_states)
+ hidden_states = self.activation(hidden_states)
+ # (batch, feature_dim, seq_len) -> (batch, seq_len, feature_dim)
+ hidden_states = hidden_states.transpose(1, 2)
+
+ if attention_mask is not None:
+ attention_mask = _compute_new_attention_mask(hidden_states=hidden_states, seq_lens=sub_sampled_lengths)
+ attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=hidden_states,
+ attention_mask=attention_mask,
+ )
+
+ # The rest of the computation is identical to a vanilla Transformer
+ # encoder layer.
+ hidden_states, attn_weights = self.self_attn(
+ hidden_states,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ )
+ hidden_states = self.self_attn_dropout(hidden_states)
+ hidden_states = hidden_states + residual
+
+ residual = hidden_states
+
+ hidden_states = self.ffn_layer_norm(hidden_states)
+ hidden_states = self.ffn(hidden_states) + residual
+
+ return hidden_states
+
+
+@auto_docstring
+class Wav2Vec2BertPreTrainedModel(PreTrainedModel):
+ config: Wav2Vec2BertConfig
+ base_model_prefix = "wav2vec2_bert"
+ main_input_name = "input_features"
+ input_modalities = "audio"
+ supports_gradient_checkpointing = True
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstance(module, Wav2Vec2BertSelfAttention):
+ if hasattr(module, "pos_bias_u"):
+ init.xavier_uniform_(module.pos_bias_u)
+ if hasattr(module, "pos_bias_v"):
+ init.xavier_uniform_(module.pos_bias_v)
+ elif isinstance(module, Wav2Vec2BertFeatureProjection):
+ k = math.sqrt(1 / module.projection.in_features)
+ init.uniform_(module.projection.weight, a=-k, b=k)
+ init.uniform_(module.projection.bias, a=-k, b=k)
+ elif isinstance(module, nn.Linear):
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
+
+ if module.bias is not None:
+ init.zeros_(module.bias)
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
+ init.zeros_(module.bias)
+ init.ones_(module.weight)
+ elif isinstance(module, nn.Conv1d):
+ init.kaiming_normal_(module.weight)
+
+ if module.bias is not None:
+ k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
+ init.uniform_(module.bias, a=-k, b=k)
+ elif isinstance(module, Wav2Vec2BertModel):
+ if hasattr(module, "masked_spec_embed"):
+ init.uniform_(module.masked_spec_embed)
+ elif isinstance(
+ module,
+ (Wav2Vec2BertForSequenceClassification, Wav2Vec2BertForAudioFrameClassification, Wav2Vec2BertForXVector),
+ ):
+ if hasattr(module, "layer_weights"):
+ init.constant_(module.layer_weights, 1.0 / (self.config.num_hidden_layers + 1))
+ elif isinstance(module, AMSoftmaxLoss): # noqa: F821
+ init.normal_(module.weight)
+ elif isinstance(module, Wav2Vec2BertRotaryPositionalEmbedding):
+ dim = self.config.hidden_size // self.config.num_attention_heads
+ base = self.config.rotary_embedding_base
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).float() / dim))
+ init.copy_(module.inv_freq, inv_freq)
+ elif isinstance(module, Wav2Vec2BertRelPositionalEmbedding):
+ init.copy_(module.pe, module.extend_pe(torch.tensor(0.0).expand(1, module.max_len)))
+
+ # Ignore copy
+ def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor | int, add_adapter: bool | None = None):
+ """
+ Computes the output length of the convolutional layers
+ """
+
+ add_adapter = self.config.add_adapter if add_adapter is None else add_adapter
+
+ def _conv_out_length(input_length, kernel_size, stride, padding):
+ # 1D convolutional layer output length formula taken
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
+ return torch.div(input_length + 2 * padding - kernel_size, stride, rounding_mode="floor") + 1
+
+ if add_adapter:
+ padding = self.config.adapter_kernel_size // 2
+ for _ in range(self.config.num_adapter_layers):
+ input_lengths = _conv_out_length(
+ input_lengths, self.config.adapter_kernel_size, self.config.adapter_stride, padding
+ )
+
+ return input_lengths
+
+ def _get_feature_vector_attention_mask(
+ self, feature_vector_length: int, attention_mask: torch.LongTensor, add_adapter=None
+ ):
+ # Effectively attention_mask.sum(-1), but not inplace to be able to run
+ # on inference mode.
+ non_padded_lengths = attention_mask.cumsum(dim=-1)[:, -1]
+
+ output_lengths = self._get_feat_extract_output_lengths(non_padded_lengths, add_adapter=add_adapter)
+ output_lengths = output_lengths.to(torch.long)
+
+ batch_size = attention_mask.shape[0]
+
+ attention_mask = torch.zeros(
+ (batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device
+ )
+ # these two operations makes sure that all values before the output lengths idxs are attended to
+ attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1
+ attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool()
+ return attention_mask
+
+
+def _compute_mask_indices(
+ shape: tuple[int, int],
+ mask_prob: float,
+ mask_length: int,
+ attention_mask: torch.LongTensor | None = None,
+ min_masks: int = 0,
+) -> np.ndarray:
+ """
+ Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for
+ ASR](https://huggingface.co/papers/1904.08779). Note that this method is not optimized to run on TPU and should be run on
+ CPU as part of the preprocessing during training.
+
+ Args:
+ shape: The shape for which to compute masks. This should be of a tuple of size 2 where
+ the first element is the batch size and the second element is the length of the axis to span.
+ mask_prob: The percentage of the whole axis (between 0 and 1) which will be masked. The number of
+ independently generated mask spans of length `mask_length` is computed by
+ `mask_prob*shape[1]/mask_length`. Note that due to overlaps, `mask_prob` is an upper bound and the
+ actual percentage will be smaller.
+ mask_length: size of the mask
+ min_masks: minimum number of masked spans
+ attention_mask: A (right-padded) attention mask which independently shortens the feature axis of
+ each batch dimension.
+ """
+ batch_size, sequence_length = shape
+
+ if mask_length < 1:
+ raise ValueError("`mask_length` has to be bigger than 0.")
+
+ if mask_length > sequence_length:
+ raise ValueError(
+ f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length}"
+ f" and `sequence_length`: {sequence_length}`"
+ )
+
+ # epsilon is used for probabilistic rounding
+ epsilon = np.random.rand(1).item()
+
+ def compute_num_masked_span(input_length):
+ """Given input length, compute how many spans should be masked"""
+ num_masked_span = int(mask_prob * input_length / mask_length + epsilon)
+ num_masked_span = max(num_masked_span, min_masks)
+
+ # make sure num masked span <= sequence_length
+ if num_masked_span * mask_length > sequence_length:
+ num_masked_span = sequence_length // mask_length
+
+ # make sure num_masked span is also <= input_length - (mask_length - 1)
+ if input_length - (mask_length - 1) < num_masked_span:
+ num_masked_span = max(input_length - (mask_length - 1), 0)
+
+ return num_masked_span
+
+ # compute number of masked spans in batch
+ input_lengths = (
+ attention_mask.detach().sum(-1).tolist()
+ if attention_mask is not None
+ else [sequence_length for _ in range(batch_size)]
+ )
+
+ # SpecAugment mask to fill
+ spec_aug_mask = np.zeros((batch_size, sequence_length), dtype=bool)
+ spec_aug_mask_idxs = []
+
+ max_num_masked_span = compute_num_masked_span(sequence_length)
+
+ if max_num_masked_span == 0:
+ return spec_aug_mask
+
+ for input_length in input_lengths:
+ # compute num of masked spans for this input
+ num_masked_span = compute_num_masked_span(input_length)
+
+ # get random indices to mask
+ spec_aug_mask_idx = np.random.choice(
+ np.arange(input_length - (mask_length - 1)), num_masked_span, replace=False
+ )
+
+ # pick first sampled index that will serve as a dummy index to pad vector
+ # to ensure same dimension for all batches due to probabilistic rounding
+ # Picking first sample just pads those vectors twice.
+ if len(spec_aug_mask_idx) == 0:
+ # this case can only happen if `input_length` is strictly smaller then
+ # `sequence_length` in which case the last token has to be a padding
+ # token which we can use as a dummy mask id
+ dummy_mask_idx = sequence_length - 1
+ else:
+ dummy_mask_idx = spec_aug_mask_idx[0]
+
+ spec_aug_mask_idx = np.concatenate(
+ [spec_aug_mask_idx, np.ones(max_num_masked_span - num_masked_span, dtype=np.int32) * dummy_mask_idx]
+ )
+ spec_aug_mask_idxs.append(spec_aug_mask_idx)
+
+ spec_aug_mask_idxs = np.array(spec_aug_mask_idxs)
+
+ # expand masked indices to masked spans
+ spec_aug_mask_idxs = np.broadcast_to(
+ spec_aug_mask_idxs[:, :, None], (batch_size, max_num_masked_span, mask_length)
+ )
+ spec_aug_mask_idxs = spec_aug_mask_idxs.reshape(batch_size, max_num_masked_span * mask_length)
+
+ # add offset to the starting indexes so that indexes now create a span
+ offsets = np.arange(mask_length)[None, None, :]
+ offsets = np.broadcast_to(offsets, (batch_size, max_num_masked_span, mask_length)).reshape(
+ batch_size, max_num_masked_span * mask_length
+ )
+ spec_aug_mask_idxs = spec_aug_mask_idxs + offsets
+
+ # ensure that we cannot have indices larger than sequence_length
+ if spec_aug_mask_idxs.max() > sequence_length - 1:
+ spec_aug_mask_idxs[spec_aug_mask_idxs > sequence_length - 1] = sequence_length - 1
+
+ # scatter indices to mask
+ np.put_along_axis(spec_aug_mask, spec_aug_mask_idxs, 1, -1)
+
+ return spec_aug_mask
+
+
+Wav2Vec2BertBaseModelOutput = Wav2Vec2BaseModelOutput
+
+
+@auto_docstring
+class Wav2Vec2BertModel(Wav2Vec2BertPreTrainedModel):
+ def __init__(self, config: Wav2Vec2BertConfig):
+ super().__init__(config)
+ self.config = config
+ self.feature_projection = Wav2Vec2BertFeatureProjection(config)
+
+ # model only needs masking vector if mask prob is > 0.0
+ if config.mask_time_prob > 0.0 or config.mask_feature_prob > 0.0:
+ self.masked_spec_embed = nn.Parameter(torch.Tensor(config.hidden_size).uniform_())
+
+ self.encoder = Wav2Vec2BertEncoder(config)
+
+ self.adapter = Wav2Vec2BertAdapter(config) if config.add_adapter else None
+
+ self.intermediate_ffn = None
+ if config.use_intermediate_ffn_before_adapter:
+ self.intermediate_ffn = Wav2Vec2BertFeedForward(config, act_fn="relu")
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def _mask_hidden_states(
+ self,
+ hidden_states: torch.FloatTensor,
+ mask_time_indices: torch.FloatTensor | None = None,
+ attention_mask: torch.LongTensor | None = None,
+ ):
+ """
+ Masks extracted features along time axis and/or along feature axis according to
+ [SpecAugment](https://huggingface.co/papers/1904.08779).
+ """
+
+ # `config.apply_spec_augment` can set masking to False
+ if not getattr(self.config, "apply_spec_augment", True):
+ return hidden_states
+
+ # generate indices & apply SpecAugment along time axis
+ batch_size, sequence_length, hidden_size = hidden_states.size()
+
+ if mask_time_indices is not None:
+ # apply SpecAugment along time axis with given mask_time_indices
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
+ elif self.config.mask_time_prob > 0 and self.training:
+ mask_time_indices = _compute_mask_indices(
+ (batch_size, sequence_length),
+ mask_prob=self.config.mask_time_prob,
+ mask_length=self.config.mask_time_length,
+ attention_mask=attention_mask,
+ min_masks=self.config.mask_time_min_masks,
+ )
+ mask_time_indices = torch.tensor(mask_time_indices, device=hidden_states.device, dtype=torch.bool)
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
+
+ if self.config.mask_feature_prob > 0 and self.training:
+ # generate indices & apply SpecAugment along feature axis
+ mask_feature_indices = _compute_mask_indices(
+ (batch_size, hidden_size),
+ mask_prob=self.config.mask_feature_prob,
+ mask_length=self.config.mask_feature_length,
+ min_masks=self.config.mask_feature_min_masks,
+ )
+ mask_feature_indices = torch.tensor(mask_feature_indices, device=hidden_states.device, dtype=torch.bool)
+ mask_feature_indices = mask_feature_indices[:, None].expand(-1, sequence_length, -1)
+ hidden_states[mask_feature_indices] = 0
+
+ return hidden_states
+
+ @auto_docstring
+ def forward(
+ self,
+ input_features: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ mask_time_indices: torch.FloatTensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | Wav2Vec2BertBaseModelOutput:
+ r"""
+ mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict
+ masked extracted features in *config.proj_codevector_dim* space.
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ hidden_states, extract_features = self.feature_projection(input_features)
+ hidden_states = self._mask_hidden_states(
+ hidden_states, mask_time_indices=mask_time_indices, attention_mask=attention_mask
+ )
+
+ encoder_outputs = self.encoder(
+ hidden_states,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ hidden_states = encoder_outputs[0]
+
+ if self.intermediate_ffn:
+ expanded_hidden_states = self.intermediate_ffn(hidden_states)
+ hidden_states = hidden_states + 0.5 * expanded_hidden_states
+
+ if self.adapter is not None:
+ hidden_states = self.adapter(hidden_states, attention_mask=attention_mask)
+
+ if not return_dict:
+ return (hidden_states, extract_features) + encoder_outputs[1:]
+
+ return Wav2Vec2BertBaseModelOutput(
+ last_hidden_state=hidden_states,
+ extract_features=extract_features,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ )
+
+
+_HIDDEN_STATES_START_POSITION = 2
+
+
+@auto_docstring(
+ custom_intro="""
+ Wav2Vec2Bert Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).
+ """
+)
+class Wav2Vec2BertForCTC(Wav2Vec2BertPreTrainedModel):
+ def __init__(self, config, target_lang: str | None = None):
+ r"""
+ target_lang (`str`, *optional*):
+ Language id of adapter weights. Adapter weights are stored in the format adapter..safetensors or
+ adapter..bin. Only relevant when using an instance of [`UniSpeechSatForCTC`] with adapters. Uses 'eng' by
+ default.
+ """
+ super().__init__(config)
+
+ self.wav2vec2_bert = Wav2Vec2BertModel(config)
+ self.dropout = nn.Dropout(config.final_dropout)
+
+ self.target_lang = target_lang
+
+ if config.vocab_size is None:
+ raise ValueError(
+ f"You are trying to instantiate {self.__class__} with a configuration that "
+ "does not define the vocabulary size of the language model head. Please "
+ "instantiate the model as follows: `Wav2Vec2BertForCTC.from_pretrained(..., vocab_size=vocab_size)`. "
+ "or define `vocab_size` of your model's configuration."
+ )
+ output_hidden_size = (
+ config.output_hidden_size if hasattr(config, "add_adapter") and config.add_adapter else config.hidden_size
+ )
+ self.lm_head = nn.Linear(output_hidden_size, config.vocab_size)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_features: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs,
+ ) -> tuple | CausalLMOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, target_length)`, *optional*):
+ Labels for connectionist temporal classification. Note that `target_length` has to be smaller or equal to
+ the sequence length of the output logits. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`.
+ All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ...,
+ config.vocab_size - 1]`.
+ """
+ if labels is not None and labels.max() >= self.config.vocab_size:
+ raise ValueError(f"Label values must be <= vocab_size: {self.config.vocab_size}")
+
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.wav2vec2_bert(
+ input_features,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ hidden_states = outputs[0]
+ hidden_states = self.dropout(hidden_states)
+
+ logits = self.lm_head(hidden_states)
+
+ loss = None
+ if labels is not None:
+ # retrieve loss input_lengths from attention_mask
+ attention_mask = (
+ attention_mask
+ if attention_mask is not None
+ else torch.ones(input_features.shape[:2], device=input_features.device, dtype=torch.long)
+ )
+ input_lengths = self._get_feat_extract_output_lengths(attention_mask.sum([-1])).to(torch.long)
+
+ # assuming that padded tokens are filled with -100
+ # when not being attended to
+ labels_mask = labels >= 0
+ target_lengths = labels_mask.sum(-1)
+ flattened_targets = labels.masked_select(labels_mask)
+
+ # ctc_loss doesn't support fp16
+ log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)
+
+ with torch.backends.cudnn.flags(enabled=False):
+ loss = nn.functional.ctc_loss(
+ log_probs,
+ flattened_targets,
+ input_lengths,
+ target_lengths,
+ blank=self.config.pad_token_id,
+ reduction=self.config.ctc_loss_reduction,
+ zero_infinity=self.config.ctc_zero_infinity,
+ )
+
+ if not return_dict:
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
+ return ((loss,) + output) if loss is not None else output
+
+ return CausalLMOutput(
+ loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ Wav2Vec2Bert Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like
+ SUPERB Keyword Spotting.
+ """
+)
+class Wav2Vec2BertForSequenceClassification(Wav2Vec2BertPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ if hasattr(config, "add_adapter") and config.add_adapter:
+ raise ValueError(
+ "Sequence classification does not support the use of Wav2Vec2Bert adapters (config.add_adapter=True)"
+ )
+ self.wav2vec2_bert = Wav2Vec2BertModel(config)
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
+ if config.use_weighted_layer_sum:
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
+ self.projector = nn.Linear(config.hidden_size, config.classifier_proj_size)
+ self.classifier = nn.Linear(config.classifier_proj_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def freeze_base_model(self):
+ """
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
+ be updated during training. Only the classification head will be updated.
+ """
+ for param in self.wav2vec2_bert.parameters():
+ param.requires_grad = False
+
+ @auto_docstring
+ def forward(
+ self,
+ input_features: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs,
+ ) -> tuple | SequenceClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
+
+ outputs = self.wav2vec2_bert(
+ input_features,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ if self.config.use_weighted_layer_sum:
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
+ hidden_states = torch.stack(hidden_states, dim=1)
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
+ else:
+ hidden_states = outputs[0]
+
+ hidden_states = self.projector(hidden_states)
+ if attention_mask is None:
+ pooled_output = hidden_states.mean(dim=1)
+ else:
+ padding_mask = self._get_feature_vector_attention_mask(hidden_states.shape[1], attention_mask)
+ expand_padding_mask = padding_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
+ hidden_states[~expand_padding_mask] = 0.0
+ pooled_output = hidden_states.sum(dim=1) / padding_mask.sum(dim=1).view(-1, 1)
+
+ logits = self.classifier(pooled_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
+
+ if not return_dict:
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
+ return ((loss,) + output) if loss is not None else output
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class Wav2Vec2BertForAudioFrameClassification(Wav2Vec2BertPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ if hasattr(config, "add_adapter") and config.add_adapter:
+ raise ValueError(
+ "Audio frame classification does not support the use of Wav2Vec2Bert adapters (config.add_adapter=True)"
+ )
+ self.wav2vec2_bert = Wav2Vec2BertModel(config)
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
+ if config.use_weighted_layer_sum:
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+ self.num_labels = config.num_labels
+
+ self.post_init()
+
+ def freeze_base_model(self):
+ """
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
+ be updated during training. Only the classification head will be updated.
+ """
+ for param in self.wav2vec2_bert.parameters():
+ param.requires_grad = False
+
+ @auto_docstring
+ def forward(
+ self,
+ input_features: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | TokenClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
+
+ outputs = self.wav2vec2_bert(
+ input_features,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ if self.config.use_weighted_layer_sum:
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
+ hidden_states = torch.stack(hidden_states, dim=1)
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
+ else:
+ hidden_states = outputs[0]
+
+ logits = self.classifier(hidden_states)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), torch.argmax(labels.view(-1, self.num_labels), axis=1))
+
+ if not return_dict:
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
+ return output
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+class AMSoftmaxLoss(nn.Module):
+ def __init__(self, input_dim, num_labels, scale=30.0, margin=0.4):
+ super().__init__()
+ self.scale = scale
+ self.margin = margin
+ self.num_labels = num_labels
+ self.weight = nn.Parameter(torch.randn(input_dim, num_labels), requires_grad=True)
+ self.loss = nn.CrossEntropyLoss()
+
+ def forward(self, hidden_states, labels):
+ labels = labels.flatten()
+ weight = nn.functional.normalize(self.weight, dim=0)
+ hidden_states = nn.functional.normalize(hidden_states, dim=1)
+ cos_theta = torch.mm(hidden_states, weight)
+ psi = cos_theta - self.margin
+
+ onehot = nn.functional.one_hot(labels, self.num_labels)
+ logits = self.scale * torch.where(onehot.bool(), psi, cos_theta)
+ loss = self.loss(logits, labels)
+
+ return loss
+
+
+class TDNNLayer(nn.Module):
+ def __init__(self, config, layer_id=0):
+ super().__init__()
+ self.in_conv_dim = config.tdnn_dim[layer_id - 1] if layer_id > 0 else config.tdnn_dim[layer_id]
+ self.out_conv_dim = config.tdnn_dim[layer_id]
+ self.kernel_size = config.tdnn_kernel[layer_id]
+ self.dilation = config.tdnn_dilation[layer_id]
+
+ self.kernel = nn.Linear(self.in_conv_dim * self.kernel_size, self.out_conv_dim)
+ self.activation = nn.ReLU()
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ if is_peft_available():
+ from peft.tuners.lora import LoraLayer
+
+ if is_peft_available():
+ if isinstance(self.kernel, LoraLayer):
+ warnings.warn(
+ "Detected LoRA on TDNNLayer. LoRA weights won't be applied due to optimization. "
+ "You should exclude TDNNLayer from LoRA's target modules.",
+ )
+
+ # for backward compatibility, we keep nn.Linear but call F.conv1d for speed up
+ hidden_states = hidden_states.transpose(1, 2)
+ weight = self.kernel.weight.view(self.out_conv_dim, self.kernel_size, self.in_conv_dim).transpose(1, 2)
+ hidden_states = nn.functional.conv1d(hidden_states, weight, self.kernel.bias, dilation=self.dilation)
+ hidden_states = hidden_states.transpose(1, 2)
+
+ hidden_states = self.activation(hidden_states)
+ return hidden_states
+
+
+@auto_docstring(
+ custom_intro="""
+ Wav2Vec2Bert Model with an XVector feature extraction head on top for tasks like Speaker Verification.
+ """
+)
+class Wav2Vec2BertForXVector(Wav2Vec2BertPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.wav2vec2_bert = Wav2Vec2BertModel(config)
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
+ if config.use_weighted_layer_sum:
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
+ self.projector = nn.Linear(config.hidden_size, config.tdnn_dim[0])
+
+ tdnn_layers = [TDNNLayer(config, i) for i in range(len(config.tdnn_dim))]
+ self.tdnn = nn.ModuleList(tdnn_layers)
+
+ self.feature_extractor = nn.Linear(config.tdnn_dim[-1] * 2, config.xvector_output_dim)
+ self.classifier = nn.Linear(config.xvector_output_dim, config.xvector_output_dim)
+
+ self.objective = AMSoftmaxLoss(config.xvector_output_dim, config.num_labels)
+
+ self.post_init()
+
+ def freeze_base_model(self):
+ """
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
+ be updated during training. Only the classification head will be updated.
+ """
+ for param in self.wav2vec2_bert.parameters():
+ param.requires_grad = False
+
+ def _get_tdnn_output_lengths(self, input_lengths: torch.LongTensor | int):
+ """
+ Computes the output length of the TDNN layers
+ """
+
+ def _conv_out_length(input_length, kernel_size, stride):
+ # 1D convolutional layer output length formula taken
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
+ return (input_length - kernel_size) // stride + 1
+
+ for kernel_size in self.config.tdnn_kernel:
+ input_lengths = _conv_out_length(input_lengths, kernel_size, 1)
+
+ return input_lengths
+
+ @auto_docstring
+ def forward(
+ self,
+ input_features: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs,
+ ) -> tuple | XVectorOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
+
+ outputs = self.wav2vec2_bert(
+ input_features,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ if self.config.use_weighted_layer_sum:
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
+ hidden_states = torch.stack(hidden_states, dim=1)
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
+ else:
+ hidden_states = outputs[0]
+
+ hidden_states = self.projector(hidden_states)
+
+ for tdnn_layer in self.tdnn:
+ hidden_states = tdnn_layer(hidden_states)
+
+ # Statistic Pooling
+ if attention_mask is None:
+ mean_features = hidden_states.mean(dim=1)
+ std_features = hidden_states.std(dim=1)
+ else:
+ feat_extract_output_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(dim=1))
+ tdnn_output_lengths = self._get_tdnn_output_lengths(feat_extract_output_lengths)
+ mean_features = []
+ std_features = []
+ for i, length in enumerate(tdnn_output_lengths):
+ mean_features.append(hidden_states[i, :length].mean(dim=0))
+ std_features.append(hidden_states[i, :length].std(dim=0))
+ mean_features = torch.stack(mean_features)
+ std_features = torch.stack(std_features)
+ statistic_pooling = torch.cat([mean_features, std_features], dim=-1)
+
+ output_embeddings = self.feature_extractor(statistic_pooling)
+ logits = self.classifier(output_embeddings)
+
+ loss = None
+ if labels is not None:
+ loss = self.objective(logits, labels)
+
+ if not return_dict:
+ output = (logits, output_embeddings) + outputs[_HIDDEN_STATES_START_POSITION:]
+ return ((loss,) + output) if loss is not None else output
+
+ return XVectorOutput(
+ loss=loss,
+ logits=logits,
+ embeddings=output_embeddings,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "Wav2Vec2BertForAudioFrameClassification",
+ "Wav2Vec2BertForCTC",
+ "Wav2Vec2BertForSequenceClassification",
+ "Wav2Vec2BertForXVector",
+ "Wav2Vec2BertModel",
+ "Wav2Vec2BertPreTrainedModel",
+]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/modular_wav2vec2_bert.py b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/modular_wav2vec2_bert.py
new file mode 100644
index 0000000000000000000000000000000000000000..710e7a64cea25750a721708512cf559e4a5e3ab6
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/modular_wav2vec2_bert.py
@@ -0,0 +1,1077 @@
+import math
+
+import torch
+from torch import nn
+from torch.nn import CrossEntropyLoss
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...integrations.deepspeed import is_deepspeed_zero3_enabled
+from ...integrations.fsdp import is_fsdp_managed_module
+from ...masking_utils import create_bidirectional_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutput,
+ CausalLMOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+ Wav2Vec2BaseModelOutput,
+ XVectorOutput,
+)
+from ...modeling_utils import PreTrainedModel
+from ...utils import auto_docstring, logging
+from ..wav2vec2.modeling_wav2vec2 import Wav2Vec2FeedForward, Wav2Vec2ForSequenceClassification, Wav2Vec2Model
+from ..wav2vec2_conformer.modeling_wav2vec2_conformer import (
+ Wav2Vec2ConformerForAudioFrameClassification,
+ Wav2Vec2ConformerForCTC,
+ Wav2Vec2ConformerForXVector,
+ Wav2Vec2ConformerRelPositionalEmbedding,
+ Wav2Vec2ConformerRotaryPositionalEmbedding,
+ Wav2Vec2ConformerSelfAttention,
+)
+from .configuration_wav2vec2_bert import Wav2Vec2BertConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+_HIDDEN_STATES_START_POSITION = 2
+
+
+# Copied from transformers.models.seamless_m4t_v2.modeling_seamless_m4t_v2._compute_new_attention_mask
+def _compute_new_attention_mask(hidden_states: torch.Tensor, seq_lens: torch.Tensor):
+ """
+ Computes an attention mask of the form `(batch, seq_len)` with an attention for each element in the batch that
+ stops at the corresponding element in `seq_lens`.
+ Args:
+ hidden_states (`torch.FloatTensor` of shape `(batch, seq_len, *)`):
+ The sequences to mask, where `*` is any number of sequence-specific dimensions including none.
+ seq_lens (`torch.Tensor` of shape `(batch)`:
+ Each element represents the length of the sequence at the same index in `hidden_states`
+ Returns:
+ `torch.FloatTensor`: The float attention mask of shape `(batch, seq_len)`
+ """
+ batch_size, mask_seq_len = hidden_states.shape[:2]
+
+ indices = torch.arange(mask_seq_len, device=seq_lens.device).expand(batch_size, -1)
+
+ bool_mask = indices >= seq_lens.unsqueeze(1).expand(-1, mask_seq_len)
+
+ mask = hidden_states.new_ones((batch_size, mask_seq_len))
+
+ mask = mask.masked_fill(bool_mask, 0)
+
+ return mask
+
+
+class Wav2Vec2BertRotaryPositionalEmbedding(Wav2Vec2ConformerRotaryPositionalEmbedding):
+ def __init__(self, config):
+ nn.Module.__init__(self)
+ dim = config.hidden_size // config.num_attention_heads
+ base = config.rotary_embedding_base
+
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).float() / dim))
+ # Ignore copy
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.cached_sequence_length = None
+ self.cached_rotary_positional_embedding = None
+
+
+class Wav2Vec2BertRelPositionalEmbedding(Wav2Vec2ConformerRelPositionalEmbedding):
+ pass
+
+
+class Wav2Vec2BertFeatureProjection(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.layer_norm = nn.LayerNorm(config.feature_projection_input_dim, eps=config.layer_norm_eps)
+ self.projection = nn.Linear(config.feature_projection_input_dim, config.hidden_size)
+ self.dropout = nn.Dropout(config.feat_proj_dropout)
+
+ def forward(self, hidden_states):
+ # non-projected hidden states are needed for quantization
+ norm_hidden_states = self.layer_norm(hidden_states)
+ hidden_states = self.projection(norm_hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ return hidden_states, norm_hidden_states
+
+
+class Wav2Vec2BertFeedForward(Wav2Vec2FeedForward):
+ def __init__(self, config, act_fn=None, hidden_size=None):
+ nn.Module.__init__(self)
+ act_fn = act_fn if act_fn is not None else config.hidden_act
+ hidden_size = hidden_size if hidden_size is not None else config.hidden_size
+ self.intermediate_dropout = nn.Dropout(config.activation_dropout)
+
+ self.intermediate_dense = nn.Linear(hidden_size, config.intermediate_size)
+ self.intermediate_act_fn = ACT2FN[act_fn] if isinstance(act_fn, str) else act_fn
+
+ self.output_dense = nn.Linear(config.intermediate_size, hidden_size)
+ self.output_dropout = nn.Dropout(config.hidden_dropout)
+
+
+class Wav2Vec2BertConvolutionModule(nn.Module):
+ """Convolution block used in the conformer block"""
+
+ def __init__(self, config):
+ super().__init__()
+ if (config.conv_depthwise_kernel_size - 1) % 2 == 1:
+ raise ValueError("`config.conv_depthwise_kernel_size` should be a odd number for 'SAME' padding")
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.pointwise_conv1 = nn.Conv1d(
+ config.hidden_size,
+ 2 * config.hidden_size,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ bias=False,
+ )
+ self.glu = nn.GLU(dim=1)
+ self.depthwise_conv = nn.Conv1d(
+ config.hidden_size,
+ config.hidden_size,
+ config.conv_depthwise_kernel_size,
+ stride=1,
+ padding=0,
+ groups=config.hidden_size,
+ bias=False,
+ )
+
+ self.depthwise_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.activation = ACT2FN[config.hidden_act]
+ self.pointwise_conv2 = nn.Conv1d(
+ config.hidden_size,
+ config.hidden_size,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ bias=False,
+ )
+ self.dropout = nn.Dropout(config.conformer_conv_dropout)
+
+ def forward(self, hidden_states, attention_mask=None):
+ hidden_states = self.layer_norm(hidden_states)
+
+ # Ensure that we do not leak padded positions in depthwise convolution if attention mask is passed.
+ # Put 0 where necessary
+ if attention_mask is not None:
+ hidden_states = hidden_states.masked_fill(~attention_mask.bool().unsqueeze(-1), 0.0)
+
+ # exchange the temporal dimension and the feature dimension
+ hidden_states = hidden_states.transpose(1, 2)
+
+ # GLU mechanism
+ # => (batch, 2*channel, dim)
+ hidden_states = self.pointwise_conv1(hidden_states)
+ # => (batch, channel, dim)
+ hidden_states = self.glu(hidden_states)
+
+ # Pad the sequence entirely on the left because of causal convolution.
+ hidden_states = torch.nn.functional.pad(hidden_states, (self.depthwise_conv.kernel_size[0] - 1, 0))
+
+ # 1D Depthwise Conv
+ hidden_states = self.depthwise_conv(hidden_states)
+
+ hidden_states = self.depthwise_layer_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
+
+ hidden_states = self.activation(hidden_states)
+
+ hidden_states = self.pointwise_conv2(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = hidden_states.transpose(1, 2)
+ return hidden_states
+
+
+class Wav2Vec2BertSelfAttention(Wav2Vec2ConformerSelfAttention, nn.Module):
+ """Construct an Wav2Vec2BertSelfAttention object.
+ Can be enhanced with rotary or relative position embeddings.
+ """
+
+ def __init__(self, config, is_adapter_attention=False):
+ nn.Module.__init__(self)
+ hidden_size = config.hidden_size if not is_adapter_attention else config.output_hidden_size
+
+ self.head_size = hidden_size // config.num_attention_heads
+ self.num_heads = config.num_attention_heads
+ self.position_embeddings_type = config.position_embeddings_type if not is_adapter_attention else None
+
+ self.linear_q = nn.Linear(hidden_size, hidden_size)
+ self.linear_k = nn.Linear(hidden_size, hidden_size)
+ self.linear_v = nn.Linear(hidden_size, hidden_size)
+ self.linear_out = nn.Linear(hidden_size, hidden_size)
+
+ self.dropout = nn.Dropout(p=config.attention_dropout)
+
+ if self.position_embeddings_type == "relative":
+ # linear transformation for positional encoding
+ self.linear_pos = nn.Linear(hidden_size, hidden_size, bias=False)
+ # these two learnable bias are used in matrix c and matrix d
+ # as described in https://huggingface.co/papers/1901.02860 Section 3.3
+ self.pos_bias_u = nn.Parameter(torch.zeros(self.num_heads, self.head_size))
+ self.pos_bias_v = nn.Parameter(torch.zeros(self.num_heads, self.head_size))
+
+ if self.position_embeddings_type == "relative_key":
+ self.left_max_position_embeddings = config.left_max_position_embeddings
+ self.right_max_position_embeddings = config.right_max_position_embeddings
+ num_positions = self.left_max_position_embeddings + self.right_max_position_embeddings + 1
+ self.distance_embedding = nn.Embedding(num_positions, self.head_size)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ relative_position_embeddings: torch.Tensor | None = None,
+ output_attentions: bool = False,
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
+ # self-attention mechanism
+ batch_size, sequence_length, hidden_size = hidden_states.size()
+
+ # make sure query/key states can be != value states
+ query_key_states = hidden_states
+ value_states = hidden_states
+
+ if self.position_embeddings_type == "rotary":
+ if relative_position_embeddings is None:
+ raise ValueError(
+ "`relative_position_embeddings` has to be defined when `self.position_embeddings_type == 'rotary'"
+ )
+ query_key_states = self._apply_rotary_embedding(query_key_states, relative_position_embeddings)
+
+ # project query_key_states and value_states
+ query = self.linear_q(query_key_states).view(batch_size, -1, self.num_heads, self.head_size)
+ key = self.linear_k(query_key_states).view(batch_size, -1, self.num_heads, self.head_size)
+ value = self.linear_v(value_states).view(batch_size, -1, self.num_heads, self.head_size)
+
+ # => (batch, head, time1, d_k)
+ query = query.transpose(1, 2)
+ key = key.transpose(1, 2)
+ value = value.transpose(1, 2)
+
+ if self.position_embeddings_type == "relative":
+ if relative_position_embeddings is None:
+ raise ValueError(
+ "`relative_position_embeddings` has to be defined when `self.position_embeddings_type =="
+ " 'relative'"
+ )
+ # apply relative_position_embeddings to qk scores
+ # as proposed in Transformer_XL: https://huggingface.co/papers/1901.02860
+ scores = self._apply_relative_embeddings(
+ query=query, key=key, relative_position_embeddings=relative_position_embeddings
+ )
+ else:
+ scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(self.head_size)
+
+ if self.position_embeddings_type == "relative_key":
+ query_length, key_length = query.shape[2], key.shape[2]
+
+ position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
+ position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
+ distance = position_ids_r - position_ids_l
+ distance = torch.clamp(distance, -self.left_max_position_embeddings, self.right_max_position_embeddings)
+
+ positional_embedding = self.distance_embedding(distance + self.left_max_position_embeddings)
+ positional_embedding = positional_embedding.to(dtype=query.dtype) # fp16 compatibility
+
+ relative_position_attn_weights = torch.einsum("bhld,lrd->bhlr", query, positional_embedding)
+ scores = scores + (relative_position_attn_weights / math.sqrt(self.head_size))
+
+ # apply attention_mask if necessary
+ if attention_mask is not None:
+ scores = scores + attention_mask
+
+ # => (batch, head, time1, time2)
+ probs = torch.softmax(scores, dim=-1)
+ probs = self.dropout(probs)
+
+ # => (batch, head, time1, d_k)
+ hidden_states = torch.matmul(probs, value)
+
+ # => (batch, time1, hidden_size)
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, self.num_heads * self.head_size)
+ hidden_states = self.linear_out(hidden_states)
+
+ return hidden_states, probs
+
+
+class Wav2Vec2BertEncoderLayer(GradientCheckpointingLayer):
+ """Conformer block based on https://huggingface.co/papers/2005.08100."""
+
+ def __init__(self, config):
+ super().__init__()
+ embed_dim = config.hidden_size
+ dropout = config.attention_dropout
+
+ # Feed-forward 1
+ self.ffn1_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+ self.ffn1 = Wav2Vec2BertFeedForward(config)
+
+ # Self-Attention
+ self.self_attn_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+ self.self_attn_dropout = nn.Dropout(dropout)
+ self.self_attn = Wav2Vec2BertSelfAttention(config)
+
+ # Conformer Convolution
+ self.conv_module = Wav2Vec2BertConvolutionModule(config)
+
+ # Feed-forward 2
+ self.ffn2_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+ self.ffn2 = Wav2Vec2BertFeedForward(config)
+ self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask: torch.Tensor | None = None,
+ relative_position_embeddings: torch.Tensor | None = None,
+ output_attentions: bool = False,
+ conv_attention_mask: torch.Tensor | None = None,
+ ):
+ # 1. Feed-Forward 1 layer
+ residual = hidden_states
+ hidden_states = self.ffn1_layer_norm(hidden_states)
+ hidden_states = self.ffn1(hidden_states)
+ hidden_states = hidden_states * 0.5 + residual
+ residual = hidden_states
+
+ # 2. Self-Attention layer
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+ hidden_states, attn_weigts = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ relative_position_embeddings=relative_position_embeddings,
+ output_attentions=output_attentions,
+ )
+ hidden_states = self.self_attn_dropout(hidden_states)
+ hidden_states = hidden_states + residual
+
+ # 3. Convolutional Layer
+ residual = hidden_states
+ hidden_states = self.conv_module(hidden_states, attention_mask=conv_attention_mask)
+ hidden_states = residual + hidden_states
+
+ # 4. Feed-Forward 2 Layer
+ residual = hidden_states
+ hidden_states = self.ffn2_layer_norm(hidden_states)
+ hidden_states = self.ffn2(hidden_states)
+ hidden_states = hidden_states * 0.5 + residual
+ hidden_states = self.final_layer_norm(hidden_states)
+
+ return hidden_states, attn_weigts
+
+
+class Wav2Vec2BertEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+
+ if config.position_embeddings_type == "relative":
+ self.embed_positions = Wav2Vec2BertRelPositionalEmbedding(config)
+ elif config.position_embeddings_type == "rotary":
+ self.embed_positions = Wav2Vec2BertRotaryPositionalEmbedding(config)
+ else:
+ self.embed_positions = None
+
+ self.dropout = nn.Dropout(config.hidden_dropout)
+ self.layers = nn.ModuleList([Wav2Vec2BertEncoderLayer(config) for _ in range(config.num_hidden_layers)])
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ output_attentions=False,
+ output_hidden_states=False,
+ return_dict=True,
+ ):
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+
+ conv_attention_mask = attention_mask
+ if attention_mask is not None:
+ # make sure padded tokens output 0
+ hidden_states = hidden_states.masked_fill(~attention_mask.bool().unsqueeze(-1), 0.0)
+
+ # extend attention_mask
+ attention_mask = 1.0 - attention_mask[:, None, None, :].to(dtype=hidden_states.dtype)
+ attention_mask = attention_mask * torch.finfo(hidden_states.dtype).min
+ attention_mask = attention_mask.expand(
+ attention_mask.shape[0], 1, attention_mask.shape[-1], attention_mask.shape[-1]
+ )
+
+ hidden_states = self.dropout(hidden_states)
+
+ if self.embed_positions is not None:
+ relative_position_embeddings = self.embed_positions(hidden_states)
+ else:
+ relative_position_embeddings = None
+
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
+
+ for i, layer in enumerate(self.layers):
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
+ dropout_probability = torch.rand([])
+
+ skip_the_layer = self.training and dropout_probability < self.config.layerdrop
+ if not skip_the_layer or synced_gpus:
+ # under fsdp or deepspeed zero3 all gpus must run in sync
+ layer_outputs = layer(
+ hidden_states,
+ attention_mask=attention_mask,
+ relative_position_embeddings=relative_position_embeddings,
+ output_attentions=output_attentions,
+ conv_attention_mask=conv_attention_mask,
+ )
+ hidden_states = layer_outputs[0]
+
+ if skip_the_layer:
+ layer_outputs = (None, None)
+
+ if output_attentions:
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
+ return BaseModelOutput(
+ last_hidden_state=hidden_states,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ )
+
+
+class Wav2Vec2BertAdapter(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ # feature dim might need to be down-projected
+ if config.output_hidden_size != config.hidden_size:
+ self.proj = nn.Linear(config.hidden_size, config.output_hidden_size)
+ self.proj_layer_norm = nn.LayerNorm(config.output_hidden_size, eps=config.layer_norm_eps)
+ else:
+ self.proj = self.proj_layer_norm = None
+ self.layers = nn.ModuleList(Wav2Vec2BertAdapterLayer(config) for _ in range(config.num_adapter_layers))
+ self.layerdrop = config.layerdrop
+
+ self.kernel_size = config.adapter_kernel_size
+ self.stride = config.adapter_stride
+
+ def _compute_sub_sample_lengths_from_attention_mask(self, seq_lens):
+ if seq_lens is None:
+ return seq_lens
+ pad = self.kernel_size // 2
+ seq_lens = ((seq_lens + 2 * pad - self.kernel_size) / self.stride) + 1
+ return seq_lens.floor()
+
+ def forward(self, hidden_states, attention_mask=None):
+ # down project hidden_states if necessary
+ if self.proj is not None and self.proj_layer_norm is not None:
+ hidden_states = self.proj(hidden_states)
+ hidden_states = self.proj_layer_norm(hidden_states)
+
+ sub_sampled_lengths = None
+ if attention_mask is not None:
+ sub_sampled_lengths = (attention_mask.size(1) - (1 - attention_mask.int()).sum(1)).to(hidden_states.device)
+
+ for layer in self.layers:
+ layerdrop_prob = torch.rand([])
+ sub_sampled_lengths = self._compute_sub_sample_lengths_from_attention_mask(sub_sampled_lengths)
+ if not self.training or (layerdrop_prob > self.layerdrop):
+ hidden_states = layer(
+ hidden_states, attention_mask=attention_mask, sub_sampled_lengths=sub_sampled_lengths
+ )
+
+ return hidden_states
+
+
+class Wav2Vec2BertAdapterLayer(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+
+ embed_dim = config.output_hidden_size
+ dropout = config.conformer_conv_dropout
+
+ self.kernel_size = config.adapter_kernel_size
+ self.stride = config.adapter_stride
+
+ # 1. residual convolution
+ self.residual_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+ self.residual_conv = nn.Conv1d(
+ embed_dim,
+ 2 * embed_dim,
+ self.kernel_size,
+ stride=self.stride,
+ padding=self.stride // 2,
+ )
+ self.activation = nn.GLU(dim=1)
+
+ # Self-Attention
+ self.self_attn_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+ self.self_attn_conv = nn.Conv1d(
+ embed_dim,
+ 2 * embed_dim,
+ self.kernel_size,
+ stride=self.stride,
+ padding=self.stride // 2,
+ )
+ self.self_attn = Wav2Vec2BertSelfAttention(config, is_adapter_attention=True)
+ self.self_attn_dropout = nn.Dropout(dropout)
+
+ # Feed-forward
+ self.ffn_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+ self.ffn = Wav2Vec2BertFeedForward(config, act_fn=config.adapter_act, hidden_size=embed_dim)
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask: torch.Tensor | None = None,
+ output_attentions: bool = False,
+ sub_sampled_lengths: torch.Tensor | None = None,
+ ):
+ residual = self.residual_layer_norm(hidden_states)
+
+ # Apply pooling to the residual to match the sequence length of the
+ # multi-head attention output.
+ # (batch, seq_len, feature_dim) -> (batch, feature_dim, seq_len)
+ residual = residual.transpose(1, 2)
+ residual = self.residual_conv(residual)
+ residual = self.activation(residual)
+ # (batch, feature_dim, seq_len) -> (batch, seq_len, feature_dim)
+ residual = residual.transpose(1, 2)
+
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+ # Apply pooling before feeding to the multihead-attention layer.
+ # (batch, seq_len, feature_dim) -> (batch, feature_dim, seq_len)
+ hidden_states = hidden_states.transpose(1, 2)
+ hidden_states = self.self_attn_conv(hidden_states)
+ hidden_states = self.activation(hidden_states)
+ # (batch, feature_dim, seq_len) -> (batch, seq_len, feature_dim)
+ hidden_states = hidden_states.transpose(1, 2)
+
+ if attention_mask is not None:
+ attention_mask = _compute_new_attention_mask(hidden_states=hidden_states, seq_lens=sub_sampled_lengths)
+ attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=hidden_states,
+ attention_mask=attention_mask,
+ )
+
+ # The rest of the computation is identical to a vanilla Transformer
+ # encoder layer.
+ hidden_states, attn_weights = self.self_attn(
+ hidden_states,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ )
+ hidden_states = self.self_attn_dropout(hidden_states)
+ hidden_states = hidden_states + residual
+
+ residual = hidden_states
+
+ hidden_states = self.ffn_layer_norm(hidden_states)
+ hidden_states = self.ffn(hidden_states) + residual
+
+ return hidden_states
+
+
+@auto_docstring
+class Wav2Vec2BertPreTrainedModel(PreTrainedModel):
+ config: Wav2Vec2BertConfig
+ base_model_prefix = "wav2vec2_bert"
+ main_input_name = "input_features"
+ input_modalities = "audio"
+ supports_gradient_checkpointing = True
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstance(module, Wav2Vec2BertSelfAttention):
+ if hasattr(module, "pos_bias_u"):
+ init.xavier_uniform_(module.pos_bias_u)
+ if hasattr(module, "pos_bias_v"):
+ init.xavier_uniform_(module.pos_bias_v)
+ elif isinstance(module, Wav2Vec2BertFeatureProjection):
+ k = math.sqrt(1 / module.projection.in_features)
+ init.uniform_(module.projection.weight, a=-k, b=k)
+ init.uniform_(module.projection.bias, a=-k, b=k)
+ elif isinstance(module, nn.Linear):
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
+
+ if module.bias is not None:
+ init.zeros_(module.bias)
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
+ init.zeros_(module.bias)
+ init.ones_(module.weight)
+ elif isinstance(module, nn.Conv1d):
+ init.kaiming_normal_(module.weight)
+
+ if module.bias is not None:
+ k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
+ init.uniform_(module.bias, a=-k, b=k)
+ elif isinstance(module, Wav2Vec2BertModel):
+ if hasattr(module, "masked_spec_embed"):
+ init.uniform_(module.masked_spec_embed)
+ elif isinstance(
+ module,
+ (Wav2Vec2BertForSequenceClassification, Wav2Vec2BertForAudioFrameClassification, Wav2Vec2BertForXVector),
+ ):
+ if hasattr(module, "layer_weights"):
+ init.constant_(module.layer_weights, 1.0 / (self.config.num_hidden_layers + 1))
+ elif isinstance(module, AMSoftmaxLoss): # noqa: F821
+ init.normal_(module.weight)
+ elif isinstance(module, Wav2Vec2BertRotaryPositionalEmbedding):
+ dim = self.config.hidden_size // self.config.num_attention_heads
+ base = self.config.rotary_embedding_base
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).float() / dim))
+ init.copy_(module.inv_freq, inv_freq)
+ elif isinstance(module, Wav2Vec2BertRelPositionalEmbedding):
+ init.copy_(module.pe, module.extend_pe(torch.tensor(0.0).expand(1, module.max_len)))
+
+ # Ignore copy
+ def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor | int, add_adapter: bool | None = None):
+ """
+ Computes the output length of the convolutional layers
+ """
+
+ add_adapter = self.config.add_adapter if add_adapter is None else add_adapter
+
+ def _conv_out_length(input_length, kernel_size, stride, padding):
+ # 1D convolutional layer output length formula taken
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
+ return torch.div(input_length + 2 * padding - kernel_size, stride, rounding_mode="floor") + 1
+
+ if add_adapter:
+ padding = self.config.adapter_kernel_size // 2
+ for _ in range(self.config.num_adapter_layers):
+ input_lengths = _conv_out_length(
+ input_lengths, self.config.adapter_kernel_size, self.config.adapter_stride, padding
+ )
+
+ return input_lengths
+
+ def _get_feature_vector_attention_mask(
+ self, feature_vector_length: int, attention_mask: torch.LongTensor, add_adapter=None
+ ):
+ # Effectively attention_mask.sum(-1), but not inplace to be able to run
+ # on inference mode.
+ non_padded_lengths = attention_mask.cumsum(dim=-1)[:, -1]
+
+ output_lengths = self._get_feat_extract_output_lengths(non_padded_lengths, add_adapter=add_adapter)
+ output_lengths = output_lengths.to(torch.long)
+
+ batch_size = attention_mask.shape[0]
+
+ attention_mask = torch.zeros(
+ (batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device
+ )
+ # these two operations makes sure that all values before the output lengths idxs are attended to
+ attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1
+ attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool()
+ return attention_mask
+
+
+Wav2Vec2BertBaseModelOutput = Wav2Vec2BaseModelOutput
+
+
+class Wav2Vec2BertModel(Wav2Vec2Model, Wav2Vec2BertPreTrainedModel):
+ def __init__(self, config: Wav2Vec2BertConfig):
+ Wav2Vec2BertPreTrainedModel.__init__(self, config)
+ self.config = config
+ self.feature_projection = Wav2Vec2BertFeatureProjection(config)
+
+ # model only needs masking vector if mask prob is > 0.0
+ if config.mask_time_prob > 0.0 or config.mask_feature_prob > 0.0:
+ self.masked_spec_embed = nn.Parameter(torch.Tensor(config.hidden_size).uniform_())
+
+ self.encoder = Wav2Vec2BertEncoder(config)
+
+ self.adapter = Wav2Vec2BertAdapter(config) if config.add_adapter else None
+
+ self.intermediate_ffn = None
+ if config.use_intermediate_ffn_before_adapter:
+ self.intermediate_ffn = Wav2Vec2BertFeedForward(config, act_fn="relu")
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def freeze_feature_encoder(self):
+ raise AttributeError("Not needed for Wav2Vec2Bert")
+
+ def forward(
+ self,
+ input_features: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ mask_time_indices: torch.FloatTensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | Wav2Vec2BertBaseModelOutput:
+ r"""
+ mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict
+ masked extracted features in *config.proj_codevector_dim* space.
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ hidden_states, extract_features = self.feature_projection(input_features)
+ hidden_states = self._mask_hidden_states(
+ hidden_states, mask_time_indices=mask_time_indices, attention_mask=attention_mask
+ )
+
+ encoder_outputs = self.encoder(
+ hidden_states,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ hidden_states = encoder_outputs[0]
+
+ if self.intermediate_ffn:
+ expanded_hidden_states = self.intermediate_ffn(hidden_states)
+ hidden_states = hidden_states + 0.5 * expanded_hidden_states
+
+ if self.adapter is not None:
+ hidden_states = self.adapter(hidden_states, attention_mask=attention_mask)
+
+ if not return_dict:
+ return (hidden_states, extract_features) + encoder_outputs[1:]
+
+ return Wav2Vec2BertBaseModelOutput(
+ last_hidden_state=hidden_states,
+ extract_features=extract_features,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ )
+
+
+class Wav2Vec2BertForCTC(Wav2Vec2ConformerForCTC):
+ def __init__(self, config, target_lang: str | None = None):
+ r"""
+ target_lang (`str`, *optional*):
+ Language id of adapter weights. Adapter weights are stored in the format adapter..safetensors or
+ adapter..bin. Only relevant when using an instance of [`UniSpeechSatForCTC`] with adapters. Uses 'eng' by
+ default.
+ """
+ super().__init__(config)
+
+ def freeze_feature_encoder(self):
+ raise AttributeError("Not needed for Wav2Vec2Bert")
+
+ def forward(
+ self,
+ input_features: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs,
+ ) -> tuple | CausalLMOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, target_length)`, *optional*):
+ Labels for connectionist temporal classification. Note that `target_length` has to be smaller or equal to
+ the sequence length of the output logits. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`.
+ All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ...,
+ config.vocab_size - 1]`.
+ """
+ if labels is not None and labels.max() >= self.config.vocab_size:
+ raise ValueError(f"Label values must be <= vocab_size: {self.config.vocab_size}")
+
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.wav2vec2_bert(
+ input_features,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ hidden_states = outputs[0]
+ hidden_states = self.dropout(hidden_states)
+
+ logits = self.lm_head(hidden_states)
+
+ loss = None
+ if labels is not None:
+ # retrieve loss input_lengths from attention_mask
+ attention_mask = (
+ attention_mask
+ if attention_mask is not None
+ else torch.ones(input_features.shape[:2], device=input_features.device, dtype=torch.long)
+ )
+ input_lengths = self._get_feat_extract_output_lengths(attention_mask.sum([-1])).to(torch.long)
+
+ # assuming that padded tokens are filled with -100
+ # when not being attended to
+ labels_mask = labels >= 0
+ target_lengths = labels_mask.sum(-1)
+ flattened_targets = labels.masked_select(labels_mask)
+
+ # ctc_loss doesn't support fp16
+ log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)
+
+ with torch.backends.cudnn.flags(enabled=False):
+ loss = nn.functional.ctc_loss(
+ log_probs,
+ flattened_targets,
+ input_lengths,
+ target_lengths,
+ blank=self.config.pad_token_id,
+ reduction=self.config.ctc_loss_reduction,
+ zero_infinity=self.config.ctc_zero_infinity,
+ )
+
+ if not return_dict:
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
+ return ((loss,) + output) if loss is not None else output
+
+ return CausalLMOutput(
+ loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
+ )
+
+
+class Wav2Vec2BertForSequenceClassification(Wav2Vec2ForSequenceClassification):
+ def __init__(self, config):
+ super().__init__(config)
+
+ def freeze_feature_encoder(self):
+ raise AttributeError("Not needed for Wav2Vec2Bert")
+
+ def freeze_base_model(self):
+ """
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
+ be updated during training. Only the classification head will be updated.
+ """
+ for param in self.wav2vec2_bert.parameters():
+ param.requires_grad = False
+
+ def forward(
+ self,
+ input_features: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs,
+ ) -> tuple | SequenceClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
+
+ outputs = self.wav2vec2_bert(
+ input_features,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ if self.config.use_weighted_layer_sum:
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
+ hidden_states = torch.stack(hidden_states, dim=1)
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
+ else:
+ hidden_states = outputs[0]
+
+ hidden_states = self.projector(hidden_states)
+ if attention_mask is None:
+ pooled_output = hidden_states.mean(dim=1)
+ else:
+ padding_mask = self._get_feature_vector_attention_mask(hidden_states.shape[1], attention_mask)
+ expand_padding_mask = padding_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
+ hidden_states[~expand_padding_mask] = 0.0
+ pooled_output = hidden_states.sum(dim=1) / padding_mask.sum(dim=1).view(-1, 1)
+
+ logits = self.classifier(pooled_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
+
+ if not return_dict:
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
+ return ((loss,) + output) if loss is not None else output
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+class Wav2Vec2BertForAudioFrameClassification(Wav2Vec2ConformerForAudioFrameClassification):
+ def __init__(self, config):
+ super().__init__(config)
+
+ def freeze_feature_encoder(self):
+ raise AttributeError("Not needed for Wav2Vec2Bert")
+
+ def forward(
+ self,
+ input_features: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | TokenClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
+
+ outputs = self.wav2vec2_bert(
+ input_features,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ if self.config.use_weighted_layer_sum:
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
+ hidden_states = torch.stack(hidden_states, dim=1)
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
+ else:
+ hidden_states = outputs[0]
+
+ logits = self.classifier(hidden_states)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), torch.argmax(labels.view(-1, self.num_labels), axis=1))
+
+ if not return_dict:
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
+ return output
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+class Wav2Vec2BertForXVector(Wav2Vec2ConformerForXVector):
+ def __init__(self, config):
+ super().__init__(config)
+
+ def freeze_feature_encoder(self):
+ raise AttributeError("Not needed for Wav2Vec2Bert")
+
+ def forward(
+ self,
+ input_features: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs,
+ ) -> tuple | XVectorOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
+
+ outputs = self.wav2vec2_bert(
+ input_features,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ if self.config.use_weighted_layer_sum:
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
+ hidden_states = torch.stack(hidden_states, dim=1)
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
+ else:
+ hidden_states = outputs[0]
+
+ hidden_states = self.projector(hidden_states)
+
+ for tdnn_layer in self.tdnn:
+ hidden_states = tdnn_layer(hidden_states)
+
+ # Statistic Pooling
+ if attention_mask is None:
+ mean_features = hidden_states.mean(dim=1)
+ std_features = hidden_states.std(dim=1)
+ else:
+ feat_extract_output_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(dim=1))
+ tdnn_output_lengths = self._get_tdnn_output_lengths(feat_extract_output_lengths)
+ mean_features = []
+ std_features = []
+ for i, length in enumerate(tdnn_output_lengths):
+ mean_features.append(hidden_states[i, :length].mean(dim=0))
+ std_features.append(hidden_states[i, :length].std(dim=0))
+ mean_features = torch.stack(mean_features)
+ std_features = torch.stack(std_features)
+ statistic_pooling = torch.cat([mean_features, std_features], dim=-1)
+
+ output_embeddings = self.feature_extractor(statistic_pooling)
+ logits = self.classifier(output_embeddings)
+
+ loss = None
+ if labels is not None:
+ loss = self.objective(logits, labels)
+
+ if not return_dict:
+ output = (logits, output_embeddings) + outputs[_HIDDEN_STATES_START_POSITION:]
+ return ((loss,) + output) if loss is not None else output
+
+ return XVectorOutput(
+ loss=loss,
+ logits=logits,
+ embeddings=output_embeddings,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "Wav2Vec2BertForAudioFrameClassification",
+ "Wav2Vec2BertForCTC",
+ "Wav2Vec2BertForSequenceClassification",
+ "Wav2Vec2BertForXVector",
+ "Wav2Vec2BertModel",
+ "Wav2Vec2BertPreTrainedModel",
+]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/processing_wav2vec2_bert.py b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/processing_wav2vec2_bert.py
new file mode 100644
index 0000000000000000000000000000000000000000..6602c6ec60a8f48973ac8ba172281afb74429eb5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/processing_wav2vec2_bert.py
@@ -0,0 +1,99 @@
+# Copyright 2024 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Speech processor class for Wav2Vec2-BERT
+"""
+
+from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
+from ...tokenization_utils_base import AudioInput, PreTokenizedInput, TextInput
+from ...utils import auto_docstring
+
+
+class Wav2Vec2BertProcessorKwargs(ProcessingKwargs, total=False):
+ _defaults = {}
+
+
+@auto_docstring
+class Wav2Vec2BertProcessor(ProcessorMixin):
+ def __init__(self, feature_extractor, tokenizer):
+ super().__init__(feature_extractor, tokenizer)
+
+ @auto_docstring
+ def __call__(
+ self,
+ audio: AudioInput | None = None,
+ text: str | list[str] | TextInput | PreTokenizedInput | None = None,
+ **kwargs: Unpack[Wav2Vec2BertProcessorKwargs],
+ ):
+ r"""
+ Returns:
+ [`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
+ - **input_features** -- Audio input features to be fed to a model. Returned when `audio` is not `None`.
+ - **attention_mask** -- List of indices specifying which timestamps should be attended to by the model when `audio` is not `None`.
+ When only `text` is specified, returns the token attention mask.
+ - **labels** -- List of token ids to be fed to a model. Returned when both `text` and `audio` are not `None`.
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None` and `audio` is `None`.
+ """
+
+ if audio is None and text is None:
+ raise ValueError("You need to specify either an `audio` or `text` input to process.")
+ output_kwargs = self._merge_kwargs(
+ Wav2Vec2BertProcessorKwargs,
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
+ **kwargs,
+ )
+
+ if audio is not None:
+ inputs = self.feature_extractor(audio, **output_kwargs["audio_kwargs"])
+ if text is not None:
+ encodings = self.tokenizer(text, **output_kwargs["text_kwargs"])
+
+ if text is None:
+ return inputs
+ elif audio is None:
+ return encodings
+ else:
+ inputs["labels"] = encodings["input_ids"]
+ return inputs
+
+ def pad(self, input_features=None, labels=None, **kwargs):
+ """
+ If `input_features` is not `None`, this method forwards the `input_features` and `kwargs` arguments to SeamlessM4TFeatureExtractor's [`~SeamlessM4TFeatureExtractor.pad`] to pad the input features.
+ If `labels` is not `None`, this method forwards the `labels` and `kwargs` arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.pad`] to pad the label(s).
+ Please refer to the docstring of the above two methods for more information.
+ """
+ if input_features is None and labels is None:
+ raise ValueError("You need to specify either an `input_features` or `labels` input to pad.")
+
+ if input_features is not None:
+ input_features = self.feature_extractor.pad(input_features, **kwargs)
+ if labels is not None:
+ labels = self.tokenizer.pad(labels, **kwargs)
+
+ if labels is None:
+ return input_features
+ elif input_features is None:
+ return labels
+ else:
+ input_features["labels"] = labels["input_ids"]
+ return input_features
+
+ @property
+ def model_input_names(self):
+ # The processor doesn't return text ids and the model seems to not need them
+ feature_extractor_input_names = self.feature_extractor.model_input_names
+ return feature_extractor_input_names + ["labels"]
+
+
+__all__ = ["Wav2Vec2BertProcessor"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/__init__.py b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..54d0d9e2c3997c4b2865b5a47e7b64c39ed40b68
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_wav2vec2_conformer import *
+ from .modeling_wav2vec2_conformer import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e2d97a02f07e7ef533634cb590d2e886cd253f5b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/__pycache__/configuration_wav2vec2_conformer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/__pycache__/configuration_wav2vec2_conformer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a8c0324fab0837b46e075c5e4b309d42c2c75585
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/__pycache__/configuration_wav2vec2_conformer.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/__pycache__/modeling_wav2vec2_conformer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/__pycache__/modeling_wav2vec2_conformer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0778e19f9ca927a23417f666dc00b5156d1ba000
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/__pycache__/modeling_wav2vec2_conformer.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/__pycache__/modular_wav2vec2_conformer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/__pycache__/modular_wav2vec2_conformer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7834963444bcdc452491209ba45e075fce8d87d7
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/__pycache__/modular_wav2vec2_conformer.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/configuration_wav2vec2_conformer.py b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/configuration_wav2vec2_conformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..c435a26083751a19121f650be7c4312142bd83ff
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/configuration_wav2vec2_conformer.py
@@ -0,0 +1,249 @@
+# Copyright 2022 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Wav2Vec2Conformer model configuration"""
+
+import functools
+import operator
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="facebook/wav2vec2-conformer-rel-pos-large")
+@strict
+class Wav2Vec2ConformerConfig(PreTrainedConfig):
+ r"""
+ feat_proj_dropout (`float`, *optional*, defaults to 0.0):
+ The dropout probability for output of the feature encoder.
+ feat_quantizer_dropout (`float`, *optional*, defaults to 0.0):
+ The dropout probability for the output of the feature encoder that's used by the quantizer.
+ final_dropout (`float`, *optional*, defaults to 0.1):
+ The dropout probability for the final projection layer of [`Wav2Vec2ConformerForCTC`].
+ feat_extract_norm (`str`, *optional*, defaults to `"group"`):
+ The norm to be applied to 1D convolutional layers in feature encoder. One of `"group"` for group
+ normalization of only the first 1D convolutional layer or `"layer"` for layer normalization of all 1D
+ convolutional layers.
+ feat_extract_activation (`str, `optional`, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the 1D convolutional layers of the feature
+ extractor. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` are supported.
+ conv_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 512, 512, 512)`):
+ A tuple of integers defining the number of input and output channels of each 1D convolutional layer in the
+ feature encoder. The length of *conv_dim* defines the number of 1D convolutional layers.
+ conv_stride (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 2, 2, 2, 2, 2, 2)`):
+ A tuple of integers defining the stride of each 1D convolutional layer in the feature encoder. The length
+ of *conv_stride* defines the number of convolutional layers and has to match the length of *conv_dim*.
+ conv_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(10, 3, 3, 3, 3, 3, 3)`):
+ A tuple of integers defining the kernel size of each 1D convolutional layer in the feature encoder. The
+ length of *conv_kernel* defines the number of convolutional layers and has to match the length of
+ *conv_dim*.
+ conv_bias (`bool`, *optional*, defaults to `False`):
+ Whether the 1D convolutional layers have a bias.
+ num_conv_pos_embeddings (`int`, *optional*, defaults to 128):
+ Number of convolutional positional embeddings. Defines the kernel size of 1D convolutional positional
+ embeddings layer.
+ num_conv_pos_embedding_groups (`int`, *optional*, defaults to 16):
+ Number of groups of 1D convolutional positional embeddings layer.
+ apply_spec_augment (`bool`, *optional*, defaults to `True`):
+ Whether to apply *SpecAugment* data augmentation to the outputs of the feature encoder. For reference see
+ [SpecAugment: A Simple Data Augmentation Method for Automatic Speech
+ Recognition](https://huggingface.co/papers/1904.08779).
+ mask_time_prob (`float`, *optional*, defaults to 0.05):
+ Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking
+ procedure generates ''mask_time_prob*len(time_axis)/mask_time_length'' independent masks over the axis. If
+ reasoning from the probability of each feature vector to be chosen as the start of the vector span to be
+ masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the
+ actual percentage of masked vectors. This is only relevant if `apply_spec_augment is True`.
+ mask_time_length (`int`, *optional*, defaults to 10):
+ Length of vector span along the time axis.
+ mask_time_min_masks (`int`, *optional*, defaults to 2),:
+ The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
+ irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <
+ mask_time_min_masks''
+ mask_feature_prob (`float`, *optional*, defaults to 0.0):
+ Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
+ masking procedure generates ''mask_feature_prob*len(feature_axis)/mask_time_length'' independent masks over
+ the axis. If reasoning from the probability of each feature vector to be chosen as the start of the vector
+ span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap
+ may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is
+ True`.
+ mask_feature_length (`int`, *optional*, defaults to 10):
+ Length of vector span along the feature axis.
+ mask_feature_min_masks (`int`, *optional*, defaults to 0),:
+ The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time
+ step, irrespectively of `mask_feature_prob`. Only relevant if
+ ''mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks''
+ num_codevectors_per_group (`int`, *optional*, defaults to 320):
+ Number of entries in each quantization codebook (group).
+ num_codevectors_per_group (`int`, *optional*, defaults to 320):
+ Number of entries in each quantization codebook (group).
+ num_codevector_groups (`int`, *optional*, defaults to 2):
+ Number of codevector groups for product codevector quantization.
+ contrastive_logits_temperature (`float`, *optional*, defaults to 0.1):
+ The temperature *kappa* in the contrastive loss.
+ num_negatives (`int`, *optional*, defaults to 100):
+ Number of negative samples for the contrastive loss.
+ codevector_dim (`int`, *optional*, defaults to 256):
+ Dimensionality of the quantized feature vectors.
+ proj_codevector_dim (`int`, *optional*, defaults to 256):
+ Dimensionality of the final projection of both the quantized and the transformer features.
+ diversity_loss_weight (`int`, *optional*, defaults to 0.1):
+ The weight of the codebook diversity loss component.
+ ctc_zero_infinity (`bool`, *optional*, defaults to `False`):
+ Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly
+ occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance
+ of [`Wav2Vec2ConformerForCTC`].
+ use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):
+ Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an
+ instance of [`Wav2Vec2ConformerForSequenceClassification`].
+ classifier_proj_size (`int`, *optional*, defaults to 256):
+ Dimensionality of the projection before token mean-pooling for classification.
+ tdnn_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 1500)`):
+ A tuple of integers defining the number of output channels of each 1D convolutional layer in the *TDNN*
+ module of the *XVector* model. The length of *tdnn_dim* defines the number of *TDNN* layers.
+ tdnn_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 3, 3, 1, 1)`):
+ A tuple of integers defining the kernel size of each 1D convolutional layer in the *TDNN* module of the
+ *XVector* model. The length of *tdnn_kernel* has to match the length of *tdnn_dim*.
+ tdnn_dilation (`tuple[int]` or `list[int]`, *optional*, defaults to `(1, 2, 3, 1, 1)`):
+ A tuple of integers defining the dilation factor of each 1D convolutional layer in *TDNN* module of the
+ *XVector* model. The length of *tdnn_dilation* has to match the length of *tdnn_dim*.
+ xvector_output_dim (`int`, *optional*, defaults to 512):
+ Dimensionality of the *XVector* embedding vectors.
+ add_adapter (`bool`, *optional*, defaults to `False`):
+ Whether a convolutional network should be stacked on top of the Wav2Vec2Conformer Encoder. Can be very
+ useful for warm-starting Wav2Vec2Conformer for SpeechEncoderDecoder models.
+ adapter_kernel_size (`int`, *optional*, defaults to 3):
+ Kernel size of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.
+ adapter_stride (`int`, *optional*, defaults to 2):
+ Stride of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.
+ num_adapter_layers (`int`, *optional*, defaults to 3):
+ Number of convolutional layers that should be used in the adapter network. Only relevant if `add_adapter is
+ True`.
+ output_hidden_size (`int`, *optional*):
+ Dimensionality of the encoder output layer. If not defined, this defaults to *hidden-size*. Only relevant
+ if `add_adapter is True`.
+ position_embeddings_type (`str`, *optional*, defaults to `"relative"`):
+ Can be specified to `relative` or `rotary` for relative or rotary position embeddings respectively. If left
+ `None` no relative position embedding is applied.
+ rotary_embedding_base (`int`, *optional*, defaults to 10000):
+ If `"rotary"` position embeddings are used, defines the size of the embedding base.
+ max_source_positions (`int`, *optional*, defaults to 5000):
+ if `"relative"` position embeddings are used, defines the maximum source input positions.
+ conv_depthwise_kernel_size (`int`, *optional*, defaults to 31):
+ Kernel size of convolutional depthwise 1D layer in Conformer blocks.
+ conformer_conv_dropout (`float`, *optional*, defaults to 0.1):
+ The dropout probability for all convolutional layers in Conformer blocks.
+
+ Example:
+
+ ```python
+ >>> from transformers import Wav2Vec2ConformerConfig, Wav2Vec2ConformerModel
+
+ >>> # Initializing a Wav2Vec2Conformer facebook/wav2vec2-conformer-rel-pos-large style configuration
+ >>> configuration = Wav2Vec2ConformerConfig()
+
+ >>> # Initializing a model (with random weights) from the facebook/wav2vec2-conformer-rel-pos-large style configuration
+ >>> model = Wav2Vec2ConformerModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "wav2vec2-conformer"
+
+ vocab_size: int | None = None
+ hidden_size: int = 768
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ intermediate_size: int = 3072
+ hidden_act: str = "gelu"
+ hidden_dropout: float | int = 0.1
+ activation_dropout: float | int = 0.1
+ attention_dropout: float | int = 0.1
+ feat_proj_dropout: float | int = 0.0
+ feat_quantizer_dropout: float | int = 0.0
+ final_dropout: float | int = 0.1
+ layerdrop: float | int = 0.1
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-5
+ feat_extract_norm: str = "group"
+ feat_extract_activation: str = "gelu"
+ conv_dim: list[int] | tuple[int, ...] = (512, 512, 512, 512, 512, 512, 512)
+ conv_stride: list[int] | tuple[int, ...] = (5, 2, 2, 2, 2, 2, 2)
+ conv_kernel: list[int] | tuple[int, ...] = (10, 3, 3, 3, 3, 2, 2)
+ conv_bias: bool = False
+ num_conv_pos_embeddings: int = 128
+ num_conv_pos_embedding_groups: int = 16
+ apply_spec_augment: bool = True
+ mask_time_prob: float | int = 0.05
+ mask_time_length: int = 10
+ mask_time_min_masks: int = 2
+ mask_feature_prob: float | int = 0.0
+ mask_feature_length: int = 10
+ mask_feature_min_masks: int = 0
+ num_codevectors_per_group: int = 320
+ num_codevector_groups: int = 2
+ contrastive_logits_temperature: float = 0.1
+ num_negatives: int = 100
+ codevector_dim: int = 256
+ proj_codevector_dim: int = 256
+ diversity_loss_weight: float = 0.1
+ ctc_loss_reduction: str = "sum"
+ ctc_zero_infinity: bool = False
+ use_weighted_layer_sum: bool = False
+ classifier_proj_size: int = 256
+ tdnn_dim: list[int] | tuple[int, ...] = (512, 512, 512, 512, 1500)
+ tdnn_kernel: list[int] | tuple[int, ...] = (5, 3, 3, 1, 1)
+ tdnn_dilation: list[int] | tuple[int, ...] = (1, 2, 3, 1, 1)
+ xvector_output_dim: int = 512
+ pad_token_id: int | None = 0
+ bos_token_id: int | None = 1
+ eos_token_id: int | list[int] | None = 2
+ add_adapter: bool = False
+ adapter_kernel_size: int = 3
+ adapter_stride: int = 2
+ num_adapter_layers: int = 3
+ output_hidden_size: int | None = None
+ position_embeddings_type: str | None = "relative"
+ rotary_embedding_base: int = 10000
+ max_source_positions: int = 5000
+ conv_depthwise_kernel_size: int = 31
+ conformer_conv_dropout: float | int = 0.1
+
+ def __post_init__(self, **kwargs):
+ self.num_feat_extract_layers = len(self.conv_dim)
+ self.output_hidden_size = self.output_hidden_size or self.hidden_size
+ super().__post_init__(**kwargs)
+
+ def validate_architecture(self):
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
+ if (
+ (len(self.conv_stride) != self.num_feat_extract_layers)
+ or (len(self.conv_kernel) != self.num_feat_extract_layers)
+ or (len(self.conv_dim) != self.num_feat_extract_layers)
+ ):
+ raise ValueError(
+ "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
+ " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
+ f" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,"
+ f" `len(config.conv_kernel) = {len(self.conv_kernel)}`."
+ )
+
+ @property
+ def inputs_to_logits_ratio(self):
+ return functools.reduce(operator.mul, self.conv_stride, 1)
+
+
+__all__ = ["Wav2Vec2ConformerConfig"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/modeling_wav2vec2_conformer.py b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/modeling_wav2vec2_conformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f35e5db42eddb27cda98c94dce4d8250a863150
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/modeling_wav2vec2_conformer.py
@@ -0,0 +1,1942 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/wav2vec2_conformer/modular_wav2vec2_conformer.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_wav2vec2_conformer.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+import math
+import warnings
+from dataclasses import dataclass
+
+import numpy as np
+import torch
+from torch import nn
+from torch.nn import CrossEntropyLoss
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...integrations.deepspeed import is_deepspeed_zero3_enabled
+from ...integrations.fsdp import is_fsdp_managed_module
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutput,
+ CausalLMOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+ Wav2Vec2BaseModelOutput,
+ XVectorOutput,
+)
+from ...modeling_utils import PreTrainedModel
+from ...utils import ModelOutput, auto_docstring, is_peft_available
+from .configuration_wav2vec2_conformer import Wav2Vec2ConformerConfig
+
+
+@auto_docstring(
+ custom_intro="""
+ Output type of [`Wav2Vec2ConformerForPreTraining`], with potential hidden states and attentions.
+ """
+)
+@dataclass
+class Wav2Vec2ConformerForPreTrainingOutput(ModelOutput):
+ r"""
+ loss (*optional*, returned when `sample_negative_indices` are passed, `torch.FloatTensor` of shape `(1,)`):
+ Total loss as the sum of the contrastive loss (L_m) and the diversity loss (L_d) as stated in the [official
+ paper](https://huggingface.co/papers/2006.11477).
+ projected_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`):
+ Hidden-states of the model projected to *config.proj_codevector_dim* that can be used to predict the masked
+ projected quantized states.
+ projected_quantized_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`):
+ Quantized extracted feature vectors projected to *config.proj_codevector_dim* representing the positive
+ target vectors for contrastive loss.
+ codevector_perplexity (`torch.FloatTensor` of shape `(1,)`):
+ The perplexity of the codevector distribution, used to measure the diversity of the codebook.
+ contrastive_loss (*optional*, returned when `sample_negative_indices` are passed, `torch.FloatTensor` of shape `(1,)`):
+ The contrastive loss (L_m) as stated in the [official paper](https://huggingface.co/papers/2006.11477).
+ diversity_loss (*optional*, returned when `sample_negative_indices` are passed, `torch.FloatTensor` of shape `(1,)`):
+ The diversity loss (L_d) as stated in the [official paper](https://huggingface.co/papers/2006.11477).
+ """
+
+ loss: torch.FloatTensor | None = None
+ projected_states: torch.FloatTensor | None = None
+ projected_quantized_states: torch.FloatTensor | None = None
+ codevector_perplexity: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+ contrastive_loss: torch.FloatTensor | None = None
+ diversity_loss: torch.FloatTensor | None = None
+
+
+class Wav2Vec2ConformerSamePadLayer(nn.Module):
+ def __init__(self, num_conv_pos_embeddings):
+ super().__init__()
+ self.num_pad_remove = 1 if num_conv_pos_embeddings % 2 == 0 else 0
+
+ def forward(self, hidden_states):
+ if self.num_pad_remove > 0:
+ hidden_states = hidden_states[:, :, : -self.num_pad_remove]
+ return hidden_states
+
+
+class Wav2Vec2ConformerPositionalConvEmbedding(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.conv = nn.Conv1d(
+ config.hidden_size,
+ config.hidden_size,
+ kernel_size=config.num_conv_pos_embeddings,
+ padding=config.num_conv_pos_embeddings // 2,
+ groups=config.num_conv_pos_embedding_groups,
+ )
+
+ weight_norm = nn.utils.weight_norm
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
+ weight_norm = nn.utils.parametrizations.weight_norm
+
+ if is_deepspeed_zero3_enabled():
+ import deepspeed
+
+ with deepspeed.zero.GatheredParameters(self.conv.weight, modifier_rank=0):
+ self.conv = weight_norm(self.conv, name="weight", dim=2)
+ if hasattr(self.conv, "parametrizations"):
+ weight_g = self.conv.parametrizations.weight.original0
+ weight_v = self.conv.parametrizations.weight.original1
+ else:
+ weight_g = self.conv.weight_g
+ weight_v = self.conv.weight_v
+ deepspeed.zero.register_external_parameter(self, weight_v)
+ deepspeed.zero.register_external_parameter(self, weight_g)
+ else:
+ self.conv = weight_norm(self.conv, name="weight", dim=2)
+
+ self.padding = Wav2Vec2ConformerSamePadLayer(config.num_conv_pos_embeddings)
+ self.activation = ACT2FN[config.feat_extract_activation]
+
+ def forward(self, hidden_states):
+ hidden_states = hidden_states.transpose(1, 2)
+
+ hidden_states = self.conv(hidden_states)
+ hidden_states = self.padding(hidden_states)
+ hidden_states = self.activation(hidden_states)
+
+ hidden_states = hidden_states.transpose(1, 2)
+ return hidden_states
+
+
+class Wav2Vec2ConformerRotaryPositionalEmbedding(nn.Module):
+ """Rotary positional embedding
+ Reference : https://blog.eleuther.ai/rotary-embeddings/ Paper: https://huggingface.co/papers/2104.09864
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ dim = config.hidden_size // config.num_attention_heads
+ base = config.rotary_embedding_base
+
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).float() / dim))
+ self.register_buffer("inv_freq", inv_freq)
+ self.cached_sequence_length = None
+ self.cached_rotary_positional_embedding = None
+
+ def forward(self, hidden_states):
+ sequence_length = hidden_states.shape[1]
+
+ if sequence_length == self.cached_sequence_length and self.cached_rotary_positional_embedding is not None:
+ return self.cached_rotary_positional_embedding
+
+ self.cached_sequence_length = sequence_length
+ # Embeddings are computed in the dtype of the inv_freq constant
+ time_stamps = torch.arange(sequence_length).type_as(self.inv_freq)
+ freqs = torch.einsum("i,j->ij", time_stamps, self.inv_freq)
+ embeddings = torch.cat((freqs, freqs), dim=-1)
+
+ cos_embeddings = embeddings.cos()[:, None, None, :]
+ sin_embeddings = embeddings.sin()[:, None, None, :]
+ # Computed embeddings are cast to the dtype of the hidden state inputs
+ self.cached_rotary_positional_embedding = torch.stack([cos_embeddings, sin_embeddings]).type_as(hidden_states)
+ return self.cached_rotary_positional_embedding
+
+
+class Wav2Vec2ConformerRelPositionalEmbedding(nn.Module):
+ """Relative positional encoding module."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.max_len = config.max_source_positions
+ self.d_model = config.hidden_size
+ self.register_buffer("pe", self.extend_pe(torch.tensor(0.0).expand(1, self.max_len)), persistent=False)
+
+ def extend_pe(self, x, pe=None):
+ # Reset the positional encodings
+ if pe is not None:
+ # self.pe contains both positive and negative parts
+ # the length of self.pe is 2 * input_len - 1
+ if pe.size(1) >= x.size(1) * 2 - 1:
+ if pe.dtype != x.dtype or pe.device != x.device:
+ pe = pe.to(dtype=x.dtype, device=x.device)
+ return pe
+ # Suppose `i` is the position of query vector and `j` is the
+ # position of key vector. We use positive relative positions when keys
+ # are to the left (i>j) and negative relative positions otherwise (i 0 else 1
+ self.out_conv_dim = config.conv_dim[layer_id]
+
+ self.conv = nn.Conv1d(
+ self.in_conv_dim,
+ self.out_conv_dim,
+ kernel_size=config.conv_kernel[layer_id],
+ stride=config.conv_stride[layer_id],
+ bias=config.conv_bias,
+ )
+ self.activation = ACT2FN[config.feat_extract_activation]
+
+ def forward(self, hidden_states):
+ hidden_states = self.conv(hidden_states)
+ hidden_states = self.activation(hidden_states)
+ return hidden_states
+
+
+class Wav2Vec2ConformerLayerNormConvLayer(GradientCheckpointingLayer):
+ def __init__(self, config, layer_id=0):
+ super().__init__()
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
+ self.out_conv_dim = config.conv_dim[layer_id]
+
+ self.conv = nn.Conv1d(
+ self.in_conv_dim,
+ self.out_conv_dim,
+ kernel_size=config.conv_kernel[layer_id],
+ stride=config.conv_stride[layer_id],
+ bias=config.conv_bias,
+ )
+ self.layer_norm = nn.LayerNorm(self.out_conv_dim, elementwise_affine=True)
+ self.activation = ACT2FN[config.feat_extract_activation]
+
+ def forward(self, hidden_states):
+ hidden_states = self.conv(hidden_states)
+
+ hidden_states = hidden_states.transpose(-2, -1)
+ hidden_states = self.layer_norm(hidden_states)
+ hidden_states = hidden_states.transpose(-2, -1)
+
+ hidden_states = self.activation(hidden_states)
+ return hidden_states
+
+
+class Wav2Vec2ConformerGroupNormConvLayer(GradientCheckpointingLayer):
+ def __init__(self, config, layer_id=0):
+ super().__init__()
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
+ self.out_conv_dim = config.conv_dim[layer_id]
+
+ self.conv = nn.Conv1d(
+ self.in_conv_dim,
+ self.out_conv_dim,
+ kernel_size=config.conv_kernel[layer_id],
+ stride=config.conv_stride[layer_id],
+ bias=config.conv_bias,
+ )
+ self.activation = ACT2FN[config.feat_extract_activation]
+
+ self.layer_norm = nn.GroupNorm(num_groups=self.out_conv_dim, num_channels=self.out_conv_dim, affine=True)
+
+ def forward(self, hidden_states):
+ hidden_states = self.conv(hidden_states)
+ hidden_states = self.layer_norm(hidden_states)
+ hidden_states = self.activation(hidden_states)
+ return hidden_states
+
+
+class Wav2Vec2ConformerFeatureEncoder(nn.Module):
+ """Construct the features from raw audio waveform"""
+
+ def __init__(self, config):
+ super().__init__()
+
+ if config.feat_extract_norm == "group":
+ conv_layers = [Wav2Vec2ConformerGroupNormConvLayer(config, layer_id=0)] + [
+ Wav2Vec2ConformerNoLayerNormConvLayer(config, layer_id=i + 1)
+ for i in range(config.num_feat_extract_layers - 1)
+ ]
+ elif config.feat_extract_norm == "layer":
+ conv_layers = [
+ Wav2Vec2ConformerLayerNormConvLayer(config, layer_id=i) for i in range(config.num_feat_extract_layers)
+ ]
+ else:
+ raise ValueError(
+ f"`config.feat_extract_norm` is {config.feat_extract_norm}, but has to be one of ['group', 'layer']"
+ )
+ self.conv_layers = nn.ModuleList(conv_layers)
+ self.gradient_checkpointing = False
+ self._requires_grad = True
+
+ def _freeze_parameters(self):
+ for param in self.parameters():
+ param.requires_grad = False
+ self._requires_grad = False
+
+ def forward(self, input_values):
+ hidden_states = input_values[:, None]
+
+ # make sure hidden_states require grad for gradient_checkpointing
+ if self._requires_grad and self.training:
+ hidden_states.requires_grad = True
+
+ for conv_layer in self.conv_layers:
+ hidden_states = conv_layer(hidden_states)
+
+ return hidden_states
+
+
+class Wav2Vec2ConformerFeatureProjection(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.layer_norm_eps)
+ self.projection = nn.Linear(config.conv_dim[-1], config.hidden_size)
+ self.dropout = nn.Dropout(config.feat_proj_dropout)
+
+ def forward(self, hidden_states):
+ # non-projected hidden states are needed for quantization
+ norm_hidden_states = self.layer_norm(hidden_states)
+ hidden_states = self.projection(norm_hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ return hidden_states, norm_hidden_states
+
+
+class Wav2Vec2ConformerFeedForward(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.intermediate_dropout = nn.Dropout(config.activation_dropout)
+
+ self.intermediate_dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ self.output_dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.output_dropout = nn.Dropout(config.hidden_dropout)
+
+ def forward(self, hidden_states):
+ hidden_states = self.intermediate_dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ hidden_states = self.intermediate_dropout(hidden_states)
+
+ hidden_states = self.output_dense(hidden_states)
+ hidden_states = self.output_dropout(hidden_states)
+ return hidden_states
+
+
+class Wav2Vec2ConformerConvolutionModule(nn.Module):
+ """Convolution block used in the conformer block"""
+
+ def __init__(self, config):
+ super().__init__()
+ if (config.conv_depthwise_kernel_size - 1) % 2 == 1:
+ raise ValueError("`config.conv_depthwise_kernel_size` should be a odd number for 'SAME' padding")
+ self.layer_norm = nn.LayerNorm(config.hidden_size)
+ self.pointwise_conv1 = nn.Conv1d(
+ config.hidden_size,
+ 2 * config.hidden_size,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ bias=False,
+ )
+ self.glu = nn.GLU(dim=1)
+ self.depthwise_conv = nn.Conv1d(
+ config.hidden_size,
+ config.hidden_size,
+ config.conv_depthwise_kernel_size,
+ stride=1,
+ padding=(config.conv_depthwise_kernel_size - 1) // 2,
+ groups=config.hidden_size,
+ bias=False,
+ )
+ self.batch_norm = nn.BatchNorm1d(config.hidden_size)
+ self.activation = ACT2FN[config.hidden_act]
+ self.pointwise_conv2 = nn.Conv1d(
+ config.hidden_size,
+ config.hidden_size,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ bias=False,
+ )
+ self.dropout = nn.Dropout(config.conformer_conv_dropout)
+
+ def forward(self, hidden_states):
+ hidden_states = self.layer_norm(hidden_states)
+ # exchange the temporal dimension and the feature dimension
+ hidden_states = hidden_states.transpose(1, 2)
+
+ # GLU mechanism
+ # => (batch, 2*channel, dim)
+ hidden_states = self.pointwise_conv1(hidden_states)
+ # => (batch, channel, dim)
+ hidden_states = self.glu(hidden_states)
+
+ # 1D Depthwise Conv
+ hidden_states = self.depthwise_conv(hidden_states)
+ hidden_states = self.batch_norm(hidden_states)
+ hidden_states = self.activation(hidden_states)
+
+ hidden_states = self.pointwise_conv2(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = hidden_states.transpose(1, 2)
+ return hidden_states
+
+
+class Wav2Vec2ConformerSelfAttention(nn.Module):
+ """Construct an Wav2Vec2ConformerSelfAttention object.
+ Can be enhanced with rotary or relative position embeddings.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+
+ self.head_size = config.hidden_size // config.num_attention_heads
+ self.num_heads = config.num_attention_heads
+ self.position_embeddings_type = config.position_embeddings_type
+
+ self.linear_q = nn.Linear(config.hidden_size, config.hidden_size)
+ self.linear_k = nn.Linear(config.hidden_size, config.hidden_size)
+ self.linear_v = nn.Linear(config.hidden_size, config.hidden_size)
+ self.linear_out = nn.Linear(config.hidden_size, config.hidden_size)
+
+ self.dropout = nn.Dropout(p=config.attention_dropout)
+
+ if self.position_embeddings_type == "relative":
+ # linear transformation for positional encoding
+ self.linear_pos = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
+ # these two learnable bias are used in matrix c and matrix d
+ # as described in https://huggingface.co/papers/1901.02860 Section 3.3
+ self.pos_bias_u = nn.Parameter(torch.zeros(self.num_heads, self.head_size))
+ self.pos_bias_v = nn.Parameter(torch.zeros(self.num_heads, self.head_size))
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ relative_position_embeddings: torch.Tensor | None = None,
+ output_attentions: bool = False,
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
+ # self-attention mechanism
+ batch_size, sequence_length, hidden_size = hidden_states.size()
+
+ # make sure query/key states can be != value states
+ query_key_states = hidden_states
+ value_states = hidden_states
+
+ if self.position_embeddings_type == "rotary":
+ if relative_position_embeddings is None:
+ raise ValueError(
+ "`relative_position_embeddings` has to be defined when `self.position_embeddings_type == 'rotary'"
+ )
+ query_key_states = self._apply_rotary_embedding(query_key_states, relative_position_embeddings)
+
+ # project query_key_states and value_states
+ query = self.linear_q(query_key_states).view(batch_size, -1, self.num_heads, self.head_size)
+ key = self.linear_k(query_key_states).view(batch_size, -1, self.num_heads, self.head_size)
+ value = self.linear_v(value_states).view(batch_size, -1, self.num_heads, self.head_size)
+
+ # => (batch, head, time1, d_k)
+ query = query.transpose(1, 2)
+ key = key.transpose(1, 2)
+ value = value.transpose(1, 2)
+
+ if self.position_embeddings_type == "relative":
+ if relative_position_embeddings is None:
+ raise ValueError(
+ "`relative_position_embeddings` has to be defined when `self.position_embeddings_type =="
+ " 'relative'"
+ )
+ # apply relative_position_embeddings to qk scores
+ # as proposed in Transformer_XL: https://huggingface.co/papers/1901.02860
+ scores = self._apply_relative_embeddings(
+ query=query, key=key, relative_position_embeddings=relative_position_embeddings
+ )
+ else:
+ scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(self.head_size)
+
+ # apply attention_mask if necessary
+ if attention_mask is not None:
+ scores = scores + attention_mask
+
+ # => (batch, head, time1, time2)
+ probs = torch.softmax(scores, dim=-1)
+ probs = self.dropout(probs)
+
+ # => (batch, head, time1, d_k)
+ hidden_states = torch.matmul(probs, value)
+
+ # => (batch, time1, hidden_size)
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, self.num_heads * self.head_size)
+ hidden_states = self.linear_out(hidden_states)
+
+ return hidden_states, probs
+
+ def _apply_rotary_embedding(self, hidden_states, relative_position_embeddings):
+ batch_size, sequence_length, hidden_size = hidden_states.size()
+ hidden_states = hidden_states.view(batch_size, sequence_length, self.num_heads, self.head_size)
+
+ cos = relative_position_embeddings[0, :sequence_length, ...]
+ sin = relative_position_embeddings[1, :sequence_length, ...]
+
+ # rotate hidden_states with rotary embeddings
+ hidden_states = hidden_states.transpose(0, 1)
+ rotated_states_begin = hidden_states[..., : self.head_size // 2]
+ rotated_states_end = hidden_states[..., self.head_size // 2 :]
+ rotated_states = torch.cat((-rotated_states_end, rotated_states_begin), dim=rotated_states_begin.ndim - 1)
+ hidden_states = (hidden_states * cos) + (rotated_states * sin)
+ hidden_states = hidden_states.transpose(0, 1)
+
+ hidden_states = hidden_states.view(batch_size, sequence_length, self.num_heads * self.head_size)
+
+ return hidden_states
+
+ def _apply_relative_embeddings(self, query, key, relative_position_embeddings):
+ # 1. project positional embeddings
+ # => (batch, head, 2*time1-1, d_k)
+ proj_relative_position_embeddings = self.linear_pos(relative_position_embeddings)
+ proj_relative_position_embeddings = proj_relative_position_embeddings.view(
+ relative_position_embeddings.size(0), -1, self.num_heads, self.head_size
+ )
+ proj_relative_position_embeddings = proj_relative_position_embeddings.transpose(1, 2)
+ proj_relative_position_embeddings = proj_relative_position_embeddings.transpose(2, 3)
+
+ # 2. Add bias to query
+ # => (batch, head, time1, d_k)
+ query = query.transpose(1, 2)
+ q_with_bias_u = (query + self.pos_bias_u).transpose(1, 2)
+ q_with_bias_v = (query + self.pos_bias_v).transpose(1, 2)
+
+ # 3. attention score: first compute matrix a and matrix c
+ # as described in https://huggingface.co/papers/1901.02860 Section 3.3
+ # => (batch, head, time1, time2)
+ scores_ac = torch.matmul(q_with_bias_u, key.transpose(-2, -1))
+
+ # 4. then compute matrix b and matrix d
+ # => (batch, head, time1, 2*time1-1)
+ scores_bd = torch.matmul(q_with_bias_v, proj_relative_position_embeddings)
+
+ # 5. shift matrix b and matrix d
+ zero_pad = torch.zeros((*scores_bd.size()[:3], 1), device=scores_bd.device, dtype=scores_bd.dtype)
+ scores_bd_padded = torch.cat([zero_pad, scores_bd], dim=-1)
+ scores_bd_padded_shape = scores_bd.size()[:2] + (scores_bd.shape[3] + 1, scores_bd.shape[2])
+ scores_bd_padded = scores_bd_padded.view(*scores_bd_padded_shape)
+ scores_bd = scores_bd_padded[:, :, 1:].view_as(scores_bd)
+ scores_bd = scores_bd[:, :, :, : scores_bd.size(-1) // 2 + 1]
+
+ # 6. sum matrices
+ # => (batch, head, time1, time2)
+ scores = (scores_ac + scores_bd) / math.sqrt(self.head_size)
+
+ return scores
+
+
+class Wav2Vec2ConformerEncoderLayer(GradientCheckpointingLayer):
+ """Conformer block based on https://huggingface.co/papers/2005.08100."""
+
+ def __init__(self, config):
+ super().__init__()
+ embed_dim = config.hidden_size
+ dropout = config.attention_dropout
+
+ # Feed-forward 1
+ self.ffn1_layer_norm = nn.LayerNorm(embed_dim)
+ self.ffn1 = Wav2Vec2ConformerFeedForward(config)
+
+ # Self-Attention
+ self.self_attn_layer_norm = nn.LayerNorm(embed_dim)
+ self.self_attn_dropout = nn.Dropout(dropout)
+ self.self_attn = Wav2Vec2ConformerSelfAttention(config)
+
+ # Conformer Convolution
+ self.conv_module = Wav2Vec2ConformerConvolutionModule(config)
+
+ # Feed-forward 2
+ self.ffn2_layer_norm = nn.LayerNorm(embed_dim)
+ self.ffn2 = Wav2Vec2ConformerFeedForward(config)
+ self.final_layer_norm = nn.LayerNorm(embed_dim)
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask: torch.Tensor | None = None,
+ relative_position_embeddings: torch.Tensor | None = None,
+ output_attentions: bool = False,
+ ):
+ # 1. Feed-Forward 1 layer
+ residual = hidden_states
+ hidden_states = self.ffn1_layer_norm(hidden_states)
+ hidden_states = self.ffn1(hidden_states)
+ hidden_states = hidden_states * 0.5 + residual
+ residual = hidden_states
+
+ # 2. Self-Attention layer
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+ hidden_states, attn_weigts = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ relative_position_embeddings=relative_position_embeddings,
+ output_attentions=output_attentions,
+ )
+ hidden_states = self.self_attn_dropout(hidden_states)
+ hidden_states = hidden_states + residual
+
+ # 3. Convolutional Layer
+ residual = hidden_states
+ hidden_states = self.conv_module(hidden_states)
+ hidden_states = residual + hidden_states
+
+ # 4. Feed-Forward 2 Layer
+ residual = hidden_states
+ hidden_states = self.ffn2_layer_norm(hidden_states)
+ hidden_states = self.ffn2(hidden_states)
+ hidden_states = hidden_states * 0.5 + residual
+ hidden_states = self.final_layer_norm(hidden_states)
+
+ return hidden_states, attn_weigts
+
+
+class Wav2Vec2ConformerEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+
+ if config.position_embeddings_type == "relative":
+ self.embed_positions = Wav2Vec2ConformerRelPositionalEmbedding(config)
+ elif config.position_embeddings_type == "rotary":
+ self.embed_positions = Wav2Vec2ConformerRotaryPositionalEmbedding(config)
+ else:
+ self.embed_positions = None
+
+ self.pos_conv_embed = Wav2Vec2ConformerPositionalConvEmbedding(config)
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout)
+ self.layers = nn.ModuleList([Wav2Vec2ConformerEncoderLayer(config) for _ in range(config.num_hidden_layers)])
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ output_attentions=False,
+ output_hidden_states=False,
+ return_dict=True,
+ ):
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+
+ if attention_mask is not None:
+ # make sure padded tokens output 0
+ expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
+ hidden_states[~expand_attention_mask] = 0.0
+
+ # extend attention_mask
+ attention_mask = 1.0 - attention_mask[:, None, None, :].to(dtype=hidden_states.dtype)
+ attention_mask = attention_mask * torch.finfo(hidden_states.dtype).min
+ attention_mask = attention_mask.expand(
+ attention_mask.shape[0], 1, attention_mask.shape[-1], attention_mask.shape[-1]
+ )
+
+ hidden_states = self.dropout(hidden_states)
+
+ if self.embed_positions is not None:
+ relative_position_embeddings = self.embed_positions(hidden_states)
+ else:
+ relative_position_embeddings = None
+
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
+
+ for i, layer in enumerate(self.layers):
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
+ dropout_probability = torch.rand([])
+
+ skip_the_layer = self.training and dropout_probability < self.config.layerdrop
+ if not skip_the_layer or synced_gpus:
+ # under fsdp or deepspeed zero3 all gpus must run in sync
+ layer_outputs = layer(
+ hidden_states,
+ attention_mask=attention_mask,
+ relative_position_embeddings=relative_position_embeddings,
+ output_attentions=output_attentions,
+ )
+ hidden_states = layer_outputs[0]
+
+ if skip_the_layer:
+ layer_outputs = (None, None)
+
+ if output_attentions:
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
+
+ hidden_states = self.layer_norm(hidden_states)
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
+ return BaseModelOutput(
+ last_hidden_state=hidden_states,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ )
+
+
+class Wav2Vec2ConformerGumbelVectorQuantizer(nn.Module):
+ """
+ Vector quantization using gumbel softmax. See `[CATEGORICAL REPARAMETERIZATION WITH
+ GUMBEL-SOFTMAX](https://huggingface.co/papers/1611.01144) for more information.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ self.num_groups = config.num_codevector_groups
+ self.num_vars = config.num_codevectors_per_group
+
+ if config.codevector_dim % self.num_groups != 0:
+ raise ValueError(
+ f"`config.codevector_dim {config.codevector_dim} must be divisible "
+ f"by `config.num_codevector_groups` {self.num_groups} for concatenation"
+ )
+
+ # storage for codebook variables (codewords)
+ self.codevectors = nn.Parameter(
+ torch.FloatTensor(1, self.num_groups * self.num_vars, config.codevector_dim // self.num_groups)
+ )
+ self.weight_proj = nn.Linear(config.conv_dim[-1], self.num_groups * self.num_vars)
+
+ # can be decayed for training
+ self.temperature = 2
+
+ @staticmethod
+ def _compute_perplexity(probs, mask=None):
+ if mask is not None:
+ mask_extended = mask.flatten()[:, None, None].expand(probs.shape)
+ probs = torch.where(mask_extended, probs, torch.zeros_like(probs))
+ marginal_probs = probs.sum(dim=0) / mask.sum()
+ else:
+ marginal_probs = probs.mean(dim=0)
+
+ perplexity = torch.exp(-torch.sum(torch.xlogy(marginal_probs, marginal_probs), dim=-1)).sum()
+ return perplexity
+
+ def forward(self, hidden_states, mask_time_indices=None):
+ batch_size, sequence_length, hidden_size = hidden_states.shape
+
+ # project to codevector dim
+ hidden_states = self.weight_proj(hidden_states)
+ hidden_states = hidden_states.view(batch_size * sequence_length * self.num_groups, -1)
+
+ if self.training:
+ # sample code vector probs via gumbel in differentiateable way
+ codevector_probs = nn.functional.gumbel_softmax(
+ hidden_states.float(), tau=self.temperature, hard=True
+ ).type_as(hidden_states)
+
+ # compute perplexity
+ codevector_soft_dist = torch.softmax(
+ hidden_states.view(batch_size * sequence_length, self.num_groups, -1).float(), dim=-1
+ )
+ perplexity = self._compute_perplexity(codevector_soft_dist, mask_time_indices)
+ else:
+ # take argmax in non-differentiable way
+ # comptute hard codevector distribution (one hot)
+ codevector_idx = hidden_states.argmax(dim=-1)
+ codevector_probs = hidden_states.new_zeros(hidden_states.shape).scatter_(
+ -1, codevector_idx.view(-1, 1), 1.0
+ )
+ codevector_probs = codevector_probs.view(batch_size * sequence_length, self.num_groups, -1)
+
+ perplexity = self._compute_perplexity(codevector_probs, mask_time_indices)
+
+ codevector_probs = codevector_probs.view(batch_size * sequence_length, -1)
+ # use probs to retrieve codevectors
+ codevectors_per_group = codevector_probs.unsqueeze(-1) * self.codevectors
+ codevectors = codevectors_per_group.view(batch_size * sequence_length, self.num_groups, self.num_vars, -1)
+ codevectors = codevectors.sum(-2).view(batch_size, sequence_length, -1)
+
+ return codevectors, perplexity
+
+
+class Wav2Vec2ConformerAdapter(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+
+ # feature dim might need to be down-projected
+ if config.output_hidden_size != config.hidden_size:
+ self.proj = nn.Linear(config.hidden_size, config.output_hidden_size)
+ self.proj_layer_norm = nn.LayerNorm(config.output_hidden_size)
+ else:
+ self.proj = self.proj_layer_norm = None
+
+ self.layers = nn.ModuleList(Wav2Vec2ConformerAdapterLayer(config) for _ in range(config.num_adapter_layers))
+ self.layerdrop = config.layerdrop
+
+ def forward(self, hidden_states):
+ # down project hidden_states if necessary
+ if self.proj is not None and self.proj_layer_norm is not None:
+ hidden_states = self.proj(hidden_states)
+ hidden_states = self.proj_layer_norm(hidden_states)
+
+ hidden_states = hidden_states.transpose(1, 2)
+
+ for layer in self.layers:
+ layerdrop_prob = np.random.random()
+ if not self.training or (layerdrop_prob > self.layerdrop):
+ hidden_states = layer(hidden_states)
+
+ hidden_states = hidden_states.transpose(1, 2)
+ return hidden_states
+
+
+class Wav2Vec2ConformerAdapterLayer(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.conv = nn.Conv1d(
+ config.output_hidden_size,
+ 2 * config.output_hidden_size,
+ config.adapter_kernel_size,
+ stride=config.adapter_stride,
+ padding=1,
+ )
+
+ def forward(self, hidden_states):
+ hidden_states = self.conv(hidden_states)
+ hidden_states = nn.functional.glu(hidden_states, dim=1)
+
+ return hidden_states
+
+
+@auto_docstring
+class Wav2Vec2ConformerPreTrainedModel(PreTrainedModel):
+ config: Wav2Vec2ConformerConfig
+ base_model_prefix = "wav2vec2_conformer"
+ main_input_name = "input_values"
+ input_modalities = "audio"
+ supports_gradient_checkpointing = True
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ # Wav2Vec2ForPreTraining last 2 linear layers need standard Linear init.
+ if isinstance(module, Wav2Vec2ConformerForPreTraining):
+ module.project_hid.reset_parameters()
+ module.project_q.reset_parameters()
+ # gumbel softmax requires special init
+ elif isinstance(module, Wav2Vec2ConformerGumbelVectorQuantizer):
+ init.normal_(module.weight_proj.weight, mean=0.0, std=1)
+ init.zeros_(module.weight_proj.bias)
+ init.uniform_(module.codevectors)
+ elif isinstance(module, Wav2Vec2ConformerSelfAttention):
+ if hasattr(module, "pos_bias_u"):
+ init.xavier_uniform_(module.pos_bias_u)
+ if hasattr(module, "pos_bias_v"):
+ init.xavier_uniform_(module.pos_bias_v)
+ elif isinstance(module, Wav2Vec2ConformerPositionalConvEmbedding):
+ init.normal_(
+ module.conv.weight,
+ mean=0,
+ std=2 * math.sqrt(1 / (module.conv.kernel_size[0] * module.conv.in_channels)),
+ )
+ init.constant_(module.conv.bias, 0)
+ elif isinstance(module, Wav2Vec2ConformerFeatureProjection):
+ k = math.sqrt(1 / module.projection.in_features)
+ init.uniform_(module.projection.weight, a=-k, b=k)
+ init.uniform_(module.projection.bias, a=-k, b=k)
+ elif isinstance(module, nn.Linear):
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
+
+ if module.bias is not None:
+ init.zeros_(module.bias)
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm, nn.BatchNorm1d)):
+ init.zeros_(module.bias)
+ init.ones_(module.weight)
+ if getattr(module, "running_mean", None) is not None:
+ init.zeros_(module.running_mean)
+ init.ones_(module.running_var)
+ init.zeros_(module.num_batches_tracked)
+ elif isinstance(module, nn.Conv1d):
+ init.kaiming_normal_(module.weight)
+
+ if module.bias is not None:
+ k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
+ init.uniform_(module.bias, a=-k, b=k)
+ elif isinstance(module, Wav2Vec2ConformerRotaryPositionalEmbedding):
+ dim = self.config.hidden_size // self.config.num_attention_heads
+ base = self.config.rotary_embedding_base
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).float() / dim))
+ init.copy_(module.inv_freq, inv_freq)
+ elif isinstance(module, Wav2Vec2ConformerRelPositionalEmbedding):
+ init.copy_(module.pe, module.extend_pe(torch.tensor(0.0).expand(1, module.max_len)))
+
+ def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor | int, add_adapter: bool | None = None):
+ """
+ Computes the output length of the convolutional layers
+ """
+
+ add_adapter = self.config.add_adapter if add_adapter is None else add_adapter
+
+ def _conv_out_length(input_length, kernel_size, stride):
+ # 1D convolutional layer output length formula taken
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
+ return torch.div(input_length - kernel_size, stride, rounding_mode="floor") + 1
+
+ for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
+ input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
+
+ if add_adapter:
+ for _ in range(self.config.num_adapter_layers):
+ input_lengths = _conv_out_length(input_lengths, 1, self.config.adapter_stride)
+
+ return input_lengths
+
+ def _get_feature_vector_attention_mask(
+ self, feature_vector_length: int, attention_mask: torch.LongTensor, add_adapter=None
+ ):
+ # Effectively attention_mask.sum(-1), but not inplace to be able to run
+ # on inference mode.
+ non_padded_lengths = attention_mask.cumsum(dim=-1)[:, -1]
+
+ output_lengths = self._get_feat_extract_output_lengths(non_padded_lengths, add_adapter=add_adapter)
+ output_lengths = output_lengths.to(torch.long)
+
+ batch_size = attention_mask.shape[0]
+
+ attention_mask = torch.zeros(
+ (batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device
+ )
+ # these two operations makes sure that all values before the output lengths idxs are attended to
+ attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1
+ attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool()
+ return attention_mask
+
+
+def _compute_mask_indices(
+ shape: tuple[int, int],
+ mask_prob: float,
+ mask_length: int,
+ attention_mask: torch.LongTensor | None = None,
+ min_masks: int = 0,
+) -> np.ndarray:
+ """
+ Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for
+ ASR](https://huggingface.co/papers/1904.08779). Note that this method is not optimized to run on TPU and should be run on
+ CPU as part of the preprocessing during training.
+
+ Args:
+ shape: The shape for which to compute masks. This should be of a tuple of size 2 where
+ the first element is the batch size and the second element is the length of the axis to span.
+ mask_prob: The percentage of the whole axis (between 0 and 1) which will be masked. The number of
+ independently generated mask spans of length `mask_length` is computed by
+ `mask_prob*shape[1]/mask_length`. Note that due to overlaps, `mask_prob` is an upper bound and the
+ actual percentage will be smaller.
+ mask_length: size of the mask
+ min_masks: minimum number of masked spans
+ attention_mask: A (right-padded) attention mask which independently shortens the feature axis of
+ each batch dimension.
+ """
+ batch_size, sequence_length = shape
+
+ if mask_length < 1:
+ raise ValueError("`mask_length` has to be bigger than 0.")
+
+ if mask_length > sequence_length:
+ raise ValueError(
+ f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length}"
+ f" and `sequence_length`: {sequence_length}`"
+ )
+
+ # epsilon is used for probabilistic rounding
+ epsilon = np.random.rand(1).item()
+
+ def compute_num_masked_span(input_length):
+ """Given input length, compute how many spans should be masked"""
+ num_masked_span = int(mask_prob * input_length / mask_length + epsilon)
+ num_masked_span = max(num_masked_span, min_masks)
+
+ # make sure num masked span <= sequence_length
+ if num_masked_span * mask_length > sequence_length:
+ num_masked_span = sequence_length // mask_length
+
+ # make sure num_masked span is also <= input_length - (mask_length - 1)
+ if input_length - (mask_length - 1) < num_masked_span:
+ num_masked_span = max(input_length - (mask_length - 1), 0)
+
+ return num_masked_span
+
+ # compute number of masked spans in batch
+ input_lengths = (
+ attention_mask.detach().sum(-1).tolist()
+ if attention_mask is not None
+ else [sequence_length for _ in range(batch_size)]
+ )
+
+ # SpecAugment mask to fill
+ spec_aug_mask = np.zeros((batch_size, sequence_length), dtype=bool)
+ spec_aug_mask_idxs = []
+
+ max_num_masked_span = compute_num_masked_span(sequence_length)
+
+ if max_num_masked_span == 0:
+ return spec_aug_mask
+
+ for input_length in input_lengths:
+ # compute num of masked spans for this input
+ num_masked_span = compute_num_masked_span(input_length)
+
+ # get random indices to mask
+ spec_aug_mask_idx = np.random.choice(
+ np.arange(input_length - (mask_length - 1)), num_masked_span, replace=False
+ )
+
+ # pick first sampled index that will serve as a dummy index to pad vector
+ # to ensure same dimension for all batches due to probabilistic rounding
+ # Picking first sample just pads those vectors twice.
+ if len(spec_aug_mask_idx) == 0:
+ # this case can only happen if `input_length` is strictly smaller then
+ # `sequence_length` in which case the last token has to be a padding
+ # token which we can use as a dummy mask id
+ dummy_mask_idx = sequence_length - 1
+ else:
+ dummy_mask_idx = spec_aug_mask_idx[0]
+
+ spec_aug_mask_idx = np.concatenate(
+ [spec_aug_mask_idx, np.ones(max_num_masked_span - num_masked_span, dtype=np.int32) * dummy_mask_idx]
+ )
+ spec_aug_mask_idxs.append(spec_aug_mask_idx)
+
+ spec_aug_mask_idxs = np.array(spec_aug_mask_idxs)
+
+ # expand masked indices to masked spans
+ spec_aug_mask_idxs = np.broadcast_to(
+ spec_aug_mask_idxs[:, :, None], (batch_size, max_num_masked_span, mask_length)
+ )
+ spec_aug_mask_idxs = spec_aug_mask_idxs.reshape(batch_size, max_num_masked_span * mask_length)
+
+ # add offset to the starting indexes so that indexes now create a span
+ offsets = np.arange(mask_length)[None, None, :]
+ offsets = np.broadcast_to(offsets, (batch_size, max_num_masked_span, mask_length)).reshape(
+ batch_size, max_num_masked_span * mask_length
+ )
+ spec_aug_mask_idxs = spec_aug_mask_idxs + offsets
+
+ # ensure that we cannot have indices larger than sequence_length
+ if spec_aug_mask_idxs.max() > sequence_length - 1:
+ spec_aug_mask_idxs[spec_aug_mask_idxs > sequence_length - 1] = sequence_length - 1
+
+ # scatter indices to mask
+ np.put_along_axis(spec_aug_mask, spec_aug_mask_idxs, 1, -1)
+
+ return spec_aug_mask
+
+
+Wav2Vec2ConformerBaseModelOutput = Wav2Vec2BaseModelOutput
+
+
+@auto_docstring
+class Wav2Vec2ConformerModel(Wav2Vec2ConformerPreTrainedModel):
+ def __init__(self, config: Wav2Vec2ConformerConfig):
+ super().__init__(config)
+ self.config = config
+ self.feature_extractor = Wav2Vec2ConformerFeatureEncoder(config)
+ self.feature_projection = Wav2Vec2ConformerFeatureProjection(config)
+
+ # model only needs masking vector if mask prob is > 0.0
+ if config.mask_time_prob > 0.0 or config.mask_feature_prob > 0.0:
+ self.masked_spec_embed = nn.Parameter(torch.Tensor(config.hidden_size).uniform_())
+
+ self.encoder = Wav2Vec2ConformerEncoder(config)
+
+ self.adapter = Wav2Vec2ConformerAdapter(config) if config.add_adapter else None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def freeze_feature_encoder(self):
+ """
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
+ not be updated during training.
+ """
+ self.feature_extractor._freeze_parameters()
+
+ def _mask_hidden_states(
+ self,
+ hidden_states: torch.FloatTensor,
+ mask_time_indices: torch.FloatTensor | None = None,
+ attention_mask: torch.LongTensor | None = None,
+ ):
+ """
+ Masks extracted features along time axis and/or along feature axis according to
+ [SpecAugment](https://huggingface.co/papers/1904.08779).
+ """
+
+ # `config.apply_spec_augment` can set masking to False
+ if not getattr(self.config, "apply_spec_augment", True):
+ return hidden_states
+
+ # generate indices & apply SpecAugment along time axis
+ batch_size, sequence_length, hidden_size = hidden_states.size()
+
+ if mask_time_indices is not None:
+ # apply SpecAugment along time axis with given mask_time_indices
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
+ elif self.config.mask_time_prob > 0 and self.training:
+ mask_time_indices = _compute_mask_indices(
+ (batch_size, sequence_length),
+ mask_prob=self.config.mask_time_prob,
+ mask_length=self.config.mask_time_length,
+ attention_mask=attention_mask,
+ min_masks=self.config.mask_time_min_masks,
+ )
+ mask_time_indices = torch.tensor(mask_time_indices, device=hidden_states.device, dtype=torch.bool)
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
+
+ if self.config.mask_feature_prob > 0 and self.training:
+ # generate indices & apply SpecAugment along feature axis
+ mask_feature_indices = _compute_mask_indices(
+ (batch_size, hidden_size),
+ mask_prob=self.config.mask_feature_prob,
+ mask_length=self.config.mask_feature_length,
+ min_masks=self.config.mask_feature_min_masks,
+ )
+ mask_feature_indices = torch.tensor(mask_feature_indices, device=hidden_states.device, dtype=torch.bool)
+ mask_feature_indices = mask_feature_indices[:, None].expand(-1, sequence_length, -1)
+ hidden_states[mask_feature_indices] = 0
+
+ return hidden_states
+
+ @auto_docstring
+ def forward(
+ self,
+ input_values: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ mask_time_indices: torch.FloatTensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | Wav2Vec2ConformerBaseModelOutput:
+ r"""
+ mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict
+ masked extracted features in *config.proj_codevector_dim* space.
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ extract_features = self.feature_extractor(input_values)
+ extract_features = extract_features.transpose(1, 2)
+
+ if attention_mask is not None:
+ # compute reduced attention_mask corresponding to feature vectors
+ attention_mask = self._get_feature_vector_attention_mask(
+ extract_features.shape[1], attention_mask, add_adapter=False
+ )
+
+ hidden_states, extract_features = self.feature_projection(extract_features)
+ hidden_states = self._mask_hidden_states(
+ hidden_states, mask_time_indices=mask_time_indices, attention_mask=attention_mask
+ )
+
+ encoder_outputs = self.encoder(
+ hidden_states,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ hidden_states = encoder_outputs[0]
+
+ if self.adapter is not None:
+ hidden_states = self.adapter(hidden_states)
+
+ if not return_dict:
+ return (hidden_states, extract_features) + encoder_outputs[1:]
+
+ return Wav2Vec2ConformerBaseModelOutput(
+ last_hidden_state=hidden_states,
+ extract_features=extract_features,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ Wav2Vec2Conformer Model with a quantizer and `VQ` head on top.
+ """
+)
+class Wav2Vec2ConformerForPreTraining(Wav2Vec2ConformerPreTrainedModel):
+ def __init__(self, config: Wav2Vec2ConformerConfig):
+ super().__init__(config)
+ self.wav2vec2_conformer = Wav2Vec2ConformerModel(config)
+ self.dropout_features = nn.Dropout(config.feat_quantizer_dropout)
+
+ self.quantizer = Wav2Vec2ConformerGumbelVectorQuantizer(config)
+
+ self.project_hid = nn.Linear(config.hidden_size, config.proj_codevector_dim)
+ self.project_q = nn.Linear(config.codevector_dim, config.proj_codevector_dim)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def set_gumbel_temperature(self, temperature: int):
+ """
+ Set the Gumbel softmax temperature to a given value. Only necessary for training
+ """
+ self.quantizer.temperature = temperature
+
+ def freeze_feature_encoder(self):
+ """
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
+ not be updated during training.
+ """
+ self.wav2vec2_conformer.feature_extractor._freeze_parameters()
+
+ @staticmethod
+ def compute_contrastive_logits(
+ target_features: torch.FloatTensor,
+ negative_features: torch.FloatTensor,
+ predicted_features: torch.FloatTensor,
+ temperature: float = 0.1,
+ ):
+ """
+ Compute logits for contrastive loss based using cosine similarity as the distance measure between
+ `[positive_feature, negative_features]` and `[predicted_features]`. Additionally, temperature can be applied.
+ """
+ target_features = torch.cat([target_features, negative_features], dim=0)
+
+ logits = torch.cosine_similarity(predicted_features.float(), target_features.float(), dim=-1).type_as(
+ target_features
+ )
+
+ # apply temperature
+ logits = logits / temperature
+ return logits
+
+ @auto_docstring
+ def forward(
+ self,
+ input_values: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ mask_time_indices: torch.BoolTensor | None = None,
+ sampled_negative_indices: torch.BoolTensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | Wav2Vec2ConformerForPreTrainingOutput:
+ r"""
+ mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict
+ masked extracted features in *config.proj_codevector_dim* space.
+ sampled_negative_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_negatives)`, *optional*):
+ Indices indicating which quantized target vectors are used as negative sampled vectors in contrastive loss.
+ Required input for pre-training.
+
+ Example:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoFeatureExtractor, Wav2Vec2ConformerForPreTraining
+ >>> from transformers.models.wav2vec2_conformer.modeling_wav2vec2_conformer import _compute_mask_indices, _sample_negative_indices
+ >>> from datasets import load_dataset
+
+ >>> feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2_conformer-base")
+ >>> model = Wav2Vec2ConformerForPreTraining.from_pretrained("facebook/wav2vec2_conformer-base")
+
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
+ >>> input_values = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt").input_values # Batch size 1
+
+ >>> # compute masked indices
+ >>> batch_size, raw_sequence_length = input_values.shape
+ >>> sequence_length = model._get_feat_extract_output_lengths(raw_sequence_length).item()
+ >>> mask_time_indices = _compute_mask_indices(
+ ... shape=(batch_size, sequence_length), mask_prob=0.2, mask_length=2
+ ... )
+ >>> sampled_negative_indices = _sample_negative_indices(
+ ... features_shape=(batch_size, sequence_length),
+ ... num_negatives=model.config.num_negatives,
+ ... mask_time_indices=mask_time_indices,
+ ... )
+ >>> mask_time_indices = torch.tensor(data=mask_time_indices, device=input_values.device, dtype=torch.long)
+ >>> sampled_negative_indices = torch.tensor(
+ ... data=sampled_negative_indices, device=input_values.device, dtype=torch.long
+ ... )
+
+ >>> with torch.no_grad():
+ ... outputs = model(input_values, mask_time_indices=mask_time_indices)
+
+ >>> # compute cosine similarity between predicted (=projected_states) and target (=projected_quantized_states)
+ >>> cosine_sim = torch.cosine_similarity(outputs.projected_states, outputs.projected_quantized_states, dim=-1)
+
+ >>> # show that cosine similarity is much higher than random
+ >>> cosine_sim[mask_time_indices.to(torch.bool)].mean() > 0.5
+ tensor(True)
+
+ >>> # for contrastive loss training model should be put into train mode
+ >>> model = model.train()
+ >>> loss = model(
+ ... input_values, mask_time_indices=mask_time_indices, sampled_negative_indices=sampled_negative_indices
+ ... ).loss
+ ```"""
+
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ if mask_time_indices is not None:
+ mask_time_indices = mask_time_indices.to(torch.bool)
+
+ outputs = self.wav2vec2_conformer(
+ input_values,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ mask_time_indices=mask_time_indices,
+ return_dict=return_dict,
+ )
+
+ # 1. project all transformed features (including masked) to final vq dim
+ transformer_features = self.project_hid(outputs[0])
+
+ # 2. quantize all (unmasked) extracted features and project to final vq dim
+ extract_features = self.dropout_features(outputs[1])
+
+ if attention_mask is not None:
+ # compute reduced attention_mask corresponding to feature vectors
+ attention_mask = self._get_feature_vector_attention_mask(
+ extract_features.shape[1], attention_mask, add_adapter=False
+ )
+
+ quantized_features, codevector_perplexity = self.quantizer(
+ extract_features, mask_time_indices=mask_time_indices
+ )
+
+ quantized_features = quantized_features.to(self.project_q.weight.dtype)
+ quantized_features = self.project_q(quantized_features)
+
+ loss = contrastive_loss = diversity_loss = None
+ if sampled_negative_indices is not None:
+ batch_size, sequence_length, hidden_size = quantized_features.shape
+
+ # for training, we sample negatives
+ # 3. sample K negatives (distractors) quantized states for contrastive loss
+ # if attention_mask is passed, make sure that padded feature vectors cannot be sampled
+ # sample negative quantized vectors BTC => (BxT)C
+ negative_quantized_features = quantized_features.view(-1, hidden_size)[
+ sampled_negative_indices.long().view(-1)
+ ]
+ negative_quantized_features = negative_quantized_features.view(
+ batch_size, sequence_length, -1, hidden_size
+ ).permute(2, 0, 1, 3)
+
+ # 4. compute logits, corresponding to `logs = sim(c_t, [q_t, \sim{q}_t]) / \kappa`
+ # of equation (3) in https://huggingface.co/papers/2006.11477
+ logits = self.compute_contrastive_logits(
+ quantized_features[None, :],
+ negative_quantized_features,
+ transformer_features,
+ self.config.contrastive_logits_temperature,
+ )
+
+ # 5. if a negative vector is identical to the positive (i.e. when codebook utilization is low),
+ # its cosine similarity will be masked
+ neg_is_pos = (quantized_features == negative_quantized_features).all(-1)
+
+ if neg_is_pos.any():
+ logits[1:][neg_is_pos] = float("-inf")
+
+ # 6. compute contrastive loss \mathbf{L}_m = cross_entropy(logs) =
+ # -log(exp(sim(c_t, q_t)/\kappa) / \sum_{\sim{q}} exp(sim(c_t, \sim{q})/\kappa))
+ logits = logits.transpose(0, 2).reshape(-1, logits.size(0))
+ target = ((1 - mask_time_indices.long()) * -100).transpose(0, 1).flatten()
+
+ contrastive_loss = nn.functional.cross_entropy(logits.float(), target, reduction="sum")
+ # 7. compute diversity loss: \mathbf{L}_d
+ num_codevectors = self.config.num_codevectors_per_group * self.config.num_codevector_groups
+ diversity_loss = ((num_codevectors - codevector_perplexity) / num_codevectors) * mask_time_indices.sum()
+
+ # 8. \mathbf{L} = \mathbf{L}_m + \alpha * \mathbf{L}_d
+ loss = contrastive_loss + self.config.diversity_loss_weight * diversity_loss
+
+ if not return_dict:
+ if loss is not None:
+ return (loss, transformer_features, quantized_features, codevector_perplexity) + outputs[2:]
+ return (transformer_features, quantized_features, codevector_perplexity) + outputs[2:]
+
+ return Wav2Vec2ConformerForPreTrainingOutput(
+ loss=loss,
+ projected_states=transformer_features,
+ projected_quantized_states=quantized_features,
+ codevector_perplexity=codevector_perplexity,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ contrastive_loss=contrastive_loss,
+ diversity_loss=diversity_loss,
+ )
+
+
+_HIDDEN_STATES_START_POSITION = 2
+
+
+@auto_docstring(
+ custom_intro="""
+ Wav2Vec2Conformer Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).
+ """
+)
+class Wav2Vec2ConformerForCTC(Wav2Vec2ConformerPreTrainedModel):
+ def __init__(self, config, target_lang: str | None = None):
+ r"""
+ target_lang (`str`, *optional*):
+ Language id of adapter weights. Adapter weights are stored in the format adapter..safetensors or
+ adapter..bin. Only relevant when using an instance of [`UniSpeechSatForCTC`] with adapters. Uses 'eng' by
+ default.
+ """
+ super().__init__(config)
+
+ self.wav2vec2_conformer = Wav2Vec2ConformerModel(config)
+ self.dropout = nn.Dropout(config.final_dropout)
+
+ self.target_lang = target_lang
+
+ if config.vocab_size is None:
+ raise ValueError(
+ f"You are trying to instantiate {self.__class__} with a configuration that "
+ "does not define the vocabulary size of the language model head. Please "
+ "instantiate the model as follows: `Wav2Vec2ConformerForCTC.from_pretrained(..., vocab_size=vocab_size)`. "
+ "or define `vocab_size` of your model's configuration."
+ )
+ output_hidden_size = (
+ config.output_hidden_size if hasattr(config, "add_adapter") and config.add_adapter else config.hidden_size
+ )
+ self.lm_head = nn.Linear(output_hidden_size, config.vocab_size)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def freeze_feature_encoder(self):
+ """
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
+ not be updated during training.
+ """
+ self.wav2vec2_conformer.feature_extractor._freeze_parameters()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_values: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs,
+ ) -> tuple | CausalLMOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, target_length)`, *optional*):
+ Labels for connectionist temporal classification. Note that `target_length` has to be smaller or equal to
+ the sequence length of the output logits. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`.
+ All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ...,
+ config.vocab_size - 1]`.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ if labels is not None and labels.max() >= self.config.vocab_size:
+ raise ValueError(f"Label values must be <= vocab_size: {self.config.vocab_size}")
+
+ outputs = self.wav2vec2_conformer(
+ input_values,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ hidden_states = outputs[0]
+ hidden_states = self.dropout(hidden_states)
+
+ logits = self.lm_head(hidden_states)
+
+ loss = None
+ if labels is not None:
+ # retrieve loss input_lengths from attention_mask
+ attention_mask = (
+ attention_mask if attention_mask is not None else torch.ones_like(input_values, dtype=torch.long)
+ )
+ input_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1)).to(torch.long)
+
+ # assuming that padded tokens are filled with -100
+ # when not being attended to
+ labels_mask = labels >= 0
+ target_lengths = labels_mask.sum(-1)
+ flattened_targets = labels.masked_select(labels_mask)
+
+ # ctc_loss doesn't support fp16
+ log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)
+
+ with torch.backends.cudnn.flags(enabled=False):
+ loss = nn.functional.ctc_loss(
+ log_probs,
+ flattened_targets,
+ input_lengths,
+ target_lengths,
+ blank=self.config.pad_token_id,
+ reduction=self.config.ctc_loss_reduction,
+ zero_infinity=self.config.ctc_zero_infinity,
+ )
+
+ if not return_dict:
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
+ return ((loss,) + output) if loss is not None else output
+
+ return CausalLMOutput(
+ loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ Wav2Vec2Conformer Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like
+ SUPERB Keyword Spotting.
+ """
+)
+class Wav2Vec2ConformerForSequenceClassification(Wav2Vec2ConformerPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ if hasattr(config, "add_adapter") and config.add_adapter:
+ raise ValueError(
+ "Sequence classification does not support the use of Wav2Vec2Conformer adapters (config.add_adapter=True)"
+ )
+ self.wav2vec2_conformer = Wav2Vec2ConformerModel(config)
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
+ if config.use_weighted_layer_sum:
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
+ self.projector = nn.Linear(config.hidden_size, config.classifier_proj_size)
+ self.classifier = nn.Linear(config.classifier_proj_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def freeze_feature_encoder(self):
+ """
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
+ not be updated during training.
+ """
+ self.wav2vec2_conformer.feature_extractor._freeze_parameters()
+
+ def freeze_base_model(self):
+ """
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
+ be updated during training. Only the classification head will be updated.
+ """
+ for param in self.wav2vec2_conformer.parameters():
+ param.requires_grad = False
+
+ @auto_docstring
+ def forward(
+ self,
+ input_values: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs,
+ ) -> tuple | SequenceClassifierOutput:
+ r"""
+ input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
+ Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
+ into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
+ (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
+ To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
+ into a tensor of type `torch.FloatTensor`. See [`Wav2Vec2ConformerProcessor.__call__`] for details.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
+
+ outputs = self.wav2vec2_conformer(
+ input_values,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ if self.config.use_weighted_layer_sum:
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
+ hidden_states = torch.stack(hidden_states, dim=1)
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
+ else:
+ hidden_states = outputs[0]
+
+ hidden_states = self.projector(hidden_states)
+ if attention_mask is None:
+ pooled_output = hidden_states.mean(dim=1)
+ else:
+ padding_mask = self._get_feature_vector_attention_mask(hidden_states.shape[1], attention_mask)
+ expand_padding_mask = padding_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
+ hidden_states[~expand_padding_mask] = 0.0
+ pooled_output = hidden_states.sum(dim=1) / padding_mask.sum(dim=1).view(-1, 1)
+
+ logits = self.classifier(pooled_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
+
+ if not return_dict:
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
+ return ((loss,) + output) if loss is not None else output
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class Wav2Vec2ConformerForAudioFrameClassification(Wav2Vec2ConformerPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ if hasattr(config, "add_adapter") and config.add_adapter:
+ raise ValueError(
+ "Audio frame classification does not support the use of Wav2Vec2Conformer adapters (config.add_adapter=True)"
+ )
+ self.wav2vec2_conformer = Wav2Vec2ConformerModel(config)
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
+ if config.use_weighted_layer_sum:
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+ self.num_labels = config.num_labels
+
+ self.post_init()
+
+ def freeze_feature_encoder(self):
+ """
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
+ not be updated during training.
+ """
+ self.wav2vec2_conformer.feature_extractor._freeze_parameters()
+
+ def freeze_base_model(self):
+ """
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
+ be updated during training. Only the classification head will be updated.
+ """
+ for param in self.wav2vec2_conformer.parameters():
+ param.requires_grad = False
+
+ @auto_docstring
+ def forward(
+ self,
+ input_values: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | TokenClassifierOutput:
+ r"""
+ input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
+ Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
+ into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
+ (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
+ To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
+ into a tensor of type `torch.FloatTensor`. See [`Wav2Vec2ConformerProcessor.__call__`] for details.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
+
+ outputs = self.wav2vec2_conformer(
+ input_values,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ if self.config.use_weighted_layer_sum:
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
+ hidden_states = torch.stack(hidden_states, dim=1)
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
+ else:
+ hidden_states = outputs[0]
+
+ logits = self.classifier(hidden_states)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), torch.argmax(labels.view(-1, self.num_labels), axis=1))
+
+ if not return_dict:
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
+ return output
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+class AMSoftmaxLoss(nn.Module):
+ def __init__(self, input_dim, num_labels, scale=30.0, margin=0.4):
+ super().__init__()
+ self.scale = scale
+ self.margin = margin
+ self.num_labels = num_labels
+ self.weight = nn.Parameter(torch.randn(input_dim, num_labels), requires_grad=True)
+ self.loss = nn.CrossEntropyLoss()
+
+ def forward(self, hidden_states, labels):
+ labels = labels.flatten()
+ weight = nn.functional.normalize(self.weight, dim=0)
+ hidden_states = nn.functional.normalize(hidden_states, dim=1)
+ cos_theta = torch.mm(hidden_states, weight)
+ psi = cos_theta - self.margin
+
+ onehot = nn.functional.one_hot(labels, self.num_labels)
+ logits = self.scale * torch.where(onehot.bool(), psi, cos_theta)
+ loss = self.loss(logits, labels)
+
+ return loss
+
+
+class TDNNLayer(nn.Module):
+ def __init__(self, config, layer_id=0):
+ super().__init__()
+ self.in_conv_dim = config.tdnn_dim[layer_id - 1] if layer_id > 0 else config.tdnn_dim[layer_id]
+ self.out_conv_dim = config.tdnn_dim[layer_id]
+ self.kernel_size = config.tdnn_kernel[layer_id]
+ self.dilation = config.tdnn_dilation[layer_id]
+
+ self.kernel = nn.Linear(self.in_conv_dim * self.kernel_size, self.out_conv_dim)
+ self.activation = nn.ReLU()
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ if is_peft_available():
+ from peft.tuners.lora import LoraLayer
+
+ if is_peft_available():
+ if isinstance(self.kernel, LoraLayer):
+ warnings.warn(
+ "Detected LoRA on TDNNLayer. LoRA weights won't be applied due to optimization. "
+ "You should exclude TDNNLayer from LoRA's target modules.",
+ )
+
+ # for backward compatibility, we keep nn.Linear but call F.conv1d for speed up
+ hidden_states = hidden_states.transpose(1, 2)
+ weight = self.kernel.weight.view(self.out_conv_dim, self.kernel_size, self.in_conv_dim).transpose(1, 2)
+ hidden_states = nn.functional.conv1d(hidden_states, weight, self.kernel.bias, dilation=self.dilation)
+ hidden_states = hidden_states.transpose(1, 2)
+
+ hidden_states = self.activation(hidden_states)
+ return hidden_states
+
+
+@auto_docstring(
+ custom_intro="""
+ Wav2Vec2Conformer Model with an XVector feature extraction head on top for tasks like Speaker Verification.
+ """
+)
+class Wav2Vec2ConformerForXVector(Wav2Vec2ConformerPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.wav2vec2_conformer = Wav2Vec2ConformerModel(config)
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
+ if config.use_weighted_layer_sum:
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
+ self.projector = nn.Linear(config.hidden_size, config.tdnn_dim[0])
+
+ tdnn_layers = [TDNNLayer(config, i) for i in range(len(config.tdnn_dim))]
+ self.tdnn = nn.ModuleList(tdnn_layers)
+
+ self.feature_extractor = nn.Linear(config.tdnn_dim[-1] * 2, config.xvector_output_dim)
+ self.classifier = nn.Linear(config.xvector_output_dim, config.xvector_output_dim)
+
+ self.objective = AMSoftmaxLoss(config.xvector_output_dim, config.num_labels)
+
+ self.post_init()
+
+ def freeze_feature_encoder(self):
+ """
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
+ not be updated during training.
+ """
+ self.wav2vec2_conformer.feature_extractor._freeze_parameters()
+
+ def freeze_base_model(self):
+ """
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
+ be updated during training. Only the classification head will be updated.
+ """
+ for param in self.wav2vec2_conformer.parameters():
+ param.requires_grad = False
+
+ def _get_tdnn_output_lengths(self, input_lengths: torch.LongTensor | int):
+ """
+ Computes the output length of the TDNN layers
+ """
+
+ def _conv_out_length(input_length, kernel_size, stride):
+ # 1D convolutional layer output length formula taken
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
+ return (input_length - kernel_size) // stride + 1
+
+ for kernel_size in self.config.tdnn_kernel:
+ input_lengths = _conv_out_length(input_lengths, kernel_size, 1)
+
+ return input_lengths
+
+ @auto_docstring
+ def forward(
+ self,
+ input_values: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs,
+ ) -> tuple | XVectorOutput:
+ r"""
+ input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
+ Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
+ into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
+ (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
+ To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
+ into a tensor of type `torch.FloatTensor`. See [`Wav2Vec2ConformerProcessor.__call__`] for details.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
+
+ outputs = self.wav2vec2_conformer(
+ input_values,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ if self.config.use_weighted_layer_sum:
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
+ hidden_states = torch.stack(hidden_states, dim=1)
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
+ else:
+ hidden_states = outputs[0]
+
+ hidden_states = self.projector(hidden_states)
+
+ for tdnn_layer in self.tdnn:
+ hidden_states = tdnn_layer(hidden_states)
+
+ # Statistic Pooling
+ if attention_mask is None:
+ mean_features = hidden_states.mean(dim=1)
+ std_features = hidden_states.std(dim=1)
+ else:
+ feat_extract_output_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(dim=1))
+ tdnn_output_lengths = self._get_tdnn_output_lengths(feat_extract_output_lengths)
+ mean_features = []
+ std_features = []
+ for i, length in enumerate(tdnn_output_lengths):
+ mean_features.append(hidden_states[i, :length].mean(dim=0))
+ std_features.append(hidden_states[i, :length].std(dim=0))
+ mean_features = torch.stack(mean_features)
+ std_features = torch.stack(std_features)
+ statistic_pooling = torch.cat([mean_features, std_features], dim=-1)
+
+ output_embeddings = self.feature_extractor(statistic_pooling)
+ logits = self.classifier(output_embeddings)
+
+ loss = None
+ if labels is not None:
+ loss = self.objective(logits, labels)
+
+ if not return_dict:
+ output = (logits, output_embeddings) + outputs[_HIDDEN_STATES_START_POSITION:]
+ return ((loss,) + output) if loss is not None else output
+
+ return XVectorOutput(
+ loss=loss,
+ logits=logits,
+ embeddings=output_embeddings,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "Wav2Vec2ConformerForAudioFrameClassification",
+ "Wav2Vec2ConformerForCTC",
+ "Wav2Vec2ConformerForPreTraining",
+ "Wav2Vec2ConformerForSequenceClassification",
+ "Wav2Vec2ConformerForXVector",
+ "Wav2Vec2ConformerModel",
+ "Wav2Vec2ConformerPreTrainedModel",
+]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/modular_wav2vec2_conformer.py b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/modular_wav2vec2_conformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..f02ce539d228617a286d03119814f95acf18cd6a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/modular_wav2vec2_conformer.py
@@ -0,0 +1,718 @@
+import math
+from dataclasses import dataclass
+
+import torch
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...integrations.deepspeed import is_deepspeed_zero3_enabled
+from ...integrations.fsdp import is_fsdp_managed_module
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutput, Wav2Vec2BaseModelOutput
+from ...modeling_utils import PreTrainedModel
+from ...utils import ModelOutput, auto_docstring, logging
+from ..wav2vec2.modeling_wav2vec2 import (
+ Wav2Vec2Adapter,
+ Wav2Vec2AdapterLayer,
+ Wav2Vec2FeatureEncoder,
+ Wav2Vec2FeatureProjection,
+ Wav2Vec2FeedForward,
+ Wav2Vec2ForAudioFrameClassification,
+ Wav2Vec2ForCTC,
+ Wav2Vec2ForPreTraining,
+ Wav2Vec2ForSequenceClassification,
+ Wav2Vec2ForXVector,
+ Wav2Vec2GumbelVectorQuantizer,
+ Wav2Vec2Model,
+ Wav2Vec2PositionalConvEmbedding,
+)
+from .configuration_wav2vec2_conformer import Wav2Vec2ConformerConfig
+
+
+logger = logging.get_logger(__name__)
+
+_HIDDEN_STATES_START_POSITION = 2
+
+
+@auto_docstring(
+ custom_intro="""
+ Output type of [`Wav2Vec2ConformerForPreTraining`], with potential hidden states and attentions.
+ """
+)
+@dataclass
+class Wav2Vec2ConformerForPreTrainingOutput(ModelOutput):
+ r"""
+ loss (*optional*, returned when `sample_negative_indices` are passed, `torch.FloatTensor` of shape `(1,)`):
+ Total loss as the sum of the contrastive loss (L_m) and the diversity loss (L_d) as stated in the [official
+ paper](https://huggingface.co/papers/2006.11477).
+ projected_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`):
+ Hidden-states of the model projected to *config.proj_codevector_dim* that can be used to predict the masked
+ projected quantized states.
+ projected_quantized_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`):
+ Quantized extracted feature vectors projected to *config.proj_codevector_dim* representing the positive
+ target vectors for contrastive loss.
+ codevector_perplexity (`torch.FloatTensor` of shape `(1,)`):
+ The perplexity of the codevector distribution, used to measure the diversity of the codebook.
+ contrastive_loss (*optional*, returned when `sample_negative_indices` are passed, `torch.FloatTensor` of shape `(1,)`):
+ The contrastive loss (L_m) as stated in the [official paper](https://huggingface.co/papers/2006.11477).
+ diversity_loss (*optional*, returned when `sample_negative_indices` are passed, `torch.FloatTensor` of shape `(1,)`):
+ The diversity loss (L_d) as stated in the [official paper](https://huggingface.co/papers/2006.11477).
+ """
+
+ loss: torch.FloatTensor | None = None
+ projected_states: torch.FloatTensor | None = None
+ projected_quantized_states: torch.FloatTensor | None = None
+ codevector_perplexity: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+ contrastive_loss: torch.FloatTensor | None = None
+ diversity_loss: torch.FloatTensor | None = None
+
+
+class Wav2Vec2ConformerPositionalConvEmbedding(Wav2Vec2PositionalConvEmbedding):
+ pass
+
+
+class Wav2Vec2ConformerRotaryPositionalEmbedding(nn.Module):
+ """Rotary positional embedding
+ Reference : https://blog.eleuther.ai/rotary-embeddings/ Paper: https://huggingface.co/papers/2104.09864
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ dim = config.hidden_size // config.num_attention_heads
+ base = config.rotary_embedding_base
+
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).float() / dim))
+ self.register_buffer("inv_freq", inv_freq)
+ self.cached_sequence_length = None
+ self.cached_rotary_positional_embedding = None
+
+ def forward(self, hidden_states):
+ sequence_length = hidden_states.shape[1]
+
+ if sequence_length == self.cached_sequence_length and self.cached_rotary_positional_embedding is not None:
+ return self.cached_rotary_positional_embedding
+
+ self.cached_sequence_length = sequence_length
+ # Embeddings are computed in the dtype of the inv_freq constant
+ time_stamps = torch.arange(sequence_length).type_as(self.inv_freq)
+ freqs = torch.einsum("i,j->ij", time_stamps, self.inv_freq)
+ embeddings = torch.cat((freqs, freqs), dim=-1)
+
+ cos_embeddings = embeddings.cos()[:, None, None, :]
+ sin_embeddings = embeddings.sin()[:, None, None, :]
+ # Computed embeddings are cast to the dtype of the hidden state inputs
+ self.cached_rotary_positional_embedding = torch.stack([cos_embeddings, sin_embeddings]).type_as(hidden_states)
+ return self.cached_rotary_positional_embedding
+
+
+class Wav2Vec2ConformerRelPositionalEmbedding(nn.Module):
+ """Relative positional encoding module."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.max_len = config.max_source_positions
+ self.d_model = config.hidden_size
+ self.register_buffer("pe", self.extend_pe(torch.tensor(0.0).expand(1, self.max_len)), persistent=False)
+
+ def extend_pe(self, x, pe=None):
+ # Reset the positional encodings
+ if pe is not None:
+ # self.pe contains both positive and negative parts
+ # the length of self.pe is 2 * input_len - 1
+ if pe.size(1) >= x.size(1) * 2 - 1:
+ if pe.dtype != x.dtype or pe.device != x.device:
+ pe = pe.to(dtype=x.dtype, device=x.device)
+ return pe
+ # Suppose `i` is the position of query vector and `j` is the
+ # position of key vector. We use positive relative positions when keys
+ # are to the left (i>j) and negative relative positions otherwise (i (batch, 2*channel, dim)
+ hidden_states = self.pointwise_conv1(hidden_states)
+ # => (batch, channel, dim)
+ hidden_states = self.glu(hidden_states)
+
+ # 1D Depthwise Conv
+ hidden_states = self.depthwise_conv(hidden_states)
+ hidden_states = self.batch_norm(hidden_states)
+ hidden_states = self.activation(hidden_states)
+
+ hidden_states = self.pointwise_conv2(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = hidden_states.transpose(1, 2)
+ return hidden_states
+
+
+class Wav2Vec2ConformerSelfAttention(nn.Module):
+ """Construct an Wav2Vec2ConformerSelfAttention object.
+ Can be enhanced with rotary or relative position embeddings.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+
+ self.head_size = config.hidden_size // config.num_attention_heads
+ self.num_heads = config.num_attention_heads
+ self.position_embeddings_type = config.position_embeddings_type
+
+ self.linear_q = nn.Linear(config.hidden_size, config.hidden_size)
+ self.linear_k = nn.Linear(config.hidden_size, config.hidden_size)
+ self.linear_v = nn.Linear(config.hidden_size, config.hidden_size)
+ self.linear_out = nn.Linear(config.hidden_size, config.hidden_size)
+
+ self.dropout = nn.Dropout(p=config.attention_dropout)
+
+ if self.position_embeddings_type == "relative":
+ # linear transformation for positional encoding
+ self.linear_pos = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
+ # these two learnable bias are used in matrix c and matrix d
+ # as described in https://huggingface.co/papers/1901.02860 Section 3.3
+ self.pos_bias_u = nn.Parameter(torch.zeros(self.num_heads, self.head_size))
+ self.pos_bias_v = nn.Parameter(torch.zeros(self.num_heads, self.head_size))
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ relative_position_embeddings: torch.Tensor | None = None,
+ output_attentions: bool = False,
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
+ # self-attention mechanism
+ batch_size, sequence_length, hidden_size = hidden_states.size()
+
+ # make sure query/key states can be != value states
+ query_key_states = hidden_states
+ value_states = hidden_states
+
+ if self.position_embeddings_type == "rotary":
+ if relative_position_embeddings is None:
+ raise ValueError(
+ "`relative_position_embeddings` has to be defined when `self.position_embeddings_type == 'rotary'"
+ )
+ query_key_states = self._apply_rotary_embedding(query_key_states, relative_position_embeddings)
+
+ # project query_key_states and value_states
+ query = self.linear_q(query_key_states).view(batch_size, -1, self.num_heads, self.head_size)
+ key = self.linear_k(query_key_states).view(batch_size, -1, self.num_heads, self.head_size)
+ value = self.linear_v(value_states).view(batch_size, -1, self.num_heads, self.head_size)
+
+ # => (batch, head, time1, d_k)
+ query = query.transpose(1, 2)
+ key = key.transpose(1, 2)
+ value = value.transpose(1, 2)
+
+ if self.position_embeddings_type == "relative":
+ if relative_position_embeddings is None:
+ raise ValueError(
+ "`relative_position_embeddings` has to be defined when `self.position_embeddings_type =="
+ " 'relative'"
+ )
+ # apply relative_position_embeddings to qk scores
+ # as proposed in Transformer_XL: https://huggingface.co/papers/1901.02860
+ scores = self._apply_relative_embeddings(
+ query=query, key=key, relative_position_embeddings=relative_position_embeddings
+ )
+ else:
+ scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(self.head_size)
+
+ # apply attention_mask if necessary
+ if attention_mask is not None:
+ scores = scores + attention_mask
+
+ # => (batch, head, time1, time2)
+ probs = torch.softmax(scores, dim=-1)
+ probs = self.dropout(probs)
+
+ # => (batch, head, time1, d_k)
+ hidden_states = torch.matmul(probs, value)
+
+ # => (batch, time1, hidden_size)
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, self.num_heads * self.head_size)
+ hidden_states = self.linear_out(hidden_states)
+
+ return hidden_states, probs
+
+ def _apply_rotary_embedding(self, hidden_states, relative_position_embeddings):
+ batch_size, sequence_length, hidden_size = hidden_states.size()
+ hidden_states = hidden_states.view(batch_size, sequence_length, self.num_heads, self.head_size)
+
+ cos = relative_position_embeddings[0, :sequence_length, ...]
+ sin = relative_position_embeddings[1, :sequence_length, ...]
+
+ # rotate hidden_states with rotary embeddings
+ hidden_states = hidden_states.transpose(0, 1)
+ rotated_states_begin = hidden_states[..., : self.head_size // 2]
+ rotated_states_end = hidden_states[..., self.head_size // 2 :]
+ rotated_states = torch.cat((-rotated_states_end, rotated_states_begin), dim=rotated_states_begin.ndim - 1)
+ hidden_states = (hidden_states * cos) + (rotated_states * sin)
+ hidden_states = hidden_states.transpose(0, 1)
+
+ hidden_states = hidden_states.view(batch_size, sequence_length, self.num_heads * self.head_size)
+
+ return hidden_states
+
+ def _apply_relative_embeddings(self, query, key, relative_position_embeddings):
+ # 1. project positional embeddings
+ # => (batch, head, 2*time1-1, d_k)
+ proj_relative_position_embeddings = self.linear_pos(relative_position_embeddings)
+ proj_relative_position_embeddings = proj_relative_position_embeddings.view(
+ relative_position_embeddings.size(0), -1, self.num_heads, self.head_size
+ )
+ proj_relative_position_embeddings = proj_relative_position_embeddings.transpose(1, 2)
+ proj_relative_position_embeddings = proj_relative_position_embeddings.transpose(2, 3)
+
+ # 2. Add bias to query
+ # => (batch, head, time1, d_k)
+ query = query.transpose(1, 2)
+ q_with_bias_u = (query + self.pos_bias_u).transpose(1, 2)
+ q_with_bias_v = (query + self.pos_bias_v).transpose(1, 2)
+
+ # 3. attention score: first compute matrix a and matrix c
+ # as described in https://huggingface.co/papers/1901.02860 Section 3.3
+ # => (batch, head, time1, time2)
+ scores_ac = torch.matmul(q_with_bias_u, key.transpose(-2, -1))
+
+ # 4. then compute matrix b and matrix d
+ # => (batch, head, time1, 2*time1-1)
+ scores_bd = torch.matmul(q_with_bias_v, proj_relative_position_embeddings)
+
+ # 5. shift matrix b and matrix d
+ zero_pad = torch.zeros((*scores_bd.size()[:3], 1), device=scores_bd.device, dtype=scores_bd.dtype)
+ scores_bd_padded = torch.cat([zero_pad, scores_bd], dim=-1)
+ scores_bd_padded_shape = scores_bd.size()[:2] + (scores_bd.shape[3] + 1, scores_bd.shape[2])
+ scores_bd_padded = scores_bd_padded.view(*scores_bd_padded_shape)
+ scores_bd = scores_bd_padded[:, :, 1:].view_as(scores_bd)
+ scores_bd = scores_bd[:, :, :, : scores_bd.size(-1) // 2 + 1]
+
+ # 6. sum matrices
+ # => (batch, head, time1, time2)
+ scores = (scores_ac + scores_bd) / math.sqrt(self.head_size)
+
+ return scores
+
+
+class Wav2Vec2ConformerEncoderLayer(GradientCheckpointingLayer):
+ """Conformer block based on https://huggingface.co/papers/2005.08100."""
+
+ def __init__(self, config):
+ super().__init__()
+ embed_dim = config.hidden_size
+ dropout = config.attention_dropout
+
+ # Feed-forward 1
+ self.ffn1_layer_norm = nn.LayerNorm(embed_dim)
+ self.ffn1 = Wav2Vec2ConformerFeedForward(config)
+
+ # Self-Attention
+ self.self_attn_layer_norm = nn.LayerNorm(embed_dim)
+ self.self_attn_dropout = nn.Dropout(dropout)
+ self.self_attn = Wav2Vec2ConformerSelfAttention(config)
+
+ # Conformer Convolution
+ self.conv_module = Wav2Vec2ConformerConvolutionModule(config)
+
+ # Feed-forward 2
+ self.ffn2_layer_norm = nn.LayerNorm(embed_dim)
+ self.ffn2 = Wav2Vec2ConformerFeedForward(config)
+ self.final_layer_norm = nn.LayerNorm(embed_dim)
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask: torch.Tensor | None = None,
+ relative_position_embeddings: torch.Tensor | None = None,
+ output_attentions: bool = False,
+ ):
+ # 1. Feed-Forward 1 layer
+ residual = hidden_states
+ hidden_states = self.ffn1_layer_norm(hidden_states)
+ hidden_states = self.ffn1(hidden_states)
+ hidden_states = hidden_states * 0.5 + residual
+ residual = hidden_states
+
+ # 2. Self-Attention layer
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+ hidden_states, attn_weigts = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ relative_position_embeddings=relative_position_embeddings,
+ output_attentions=output_attentions,
+ )
+ hidden_states = self.self_attn_dropout(hidden_states)
+ hidden_states = hidden_states + residual
+
+ # 3. Convolutional Layer
+ residual = hidden_states
+ hidden_states = self.conv_module(hidden_states)
+ hidden_states = residual + hidden_states
+
+ # 4. Feed-Forward 2 Layer
+ residual = hidden_states
+ hidden_states = self.ffn2_layer_norm(hidden_states)
+ hidden_states = self.ffn2(hidden_states)
+ hidden_states = hidden_states * 0.5 + residual
+ hidden_states = self.final_layer_norm(hidden_states)
+
+ return hidden_states, attn_weigts
+
+
+class Wav2Vec2ConformerEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+
+ if config.position_embeddings_type == "relative":
+ self.embed_positions = Wav2Vec2ConformerRelPositionalEmbedding(config)
+ elif config.position_embeddings_type == "rotary":
+ self.embed_positions = Wav2Vec2ConformerRotaryPositionalEmbedding(config)
+ else:
+ self.embed_positions = None
+
+ self.pos_conv_embed = Wav2Vec2ConformerPositionalConvEmbedding(config)
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout)
+ self.layers = nn.ModuleList([Wav2Vec2ConformerEncoderLayer(config) for _ in range(config.num_hidden_layers)])
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ output_attentions=False,
+ output_hidden_states=False,
+ return_dict=True,
+ ):
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+
+ if attention_mask is not None:
+ # make sure padded tokens output 0
+ expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
+ hidden_states[~expand_attention_mask] = 0.0
+
+ # extend attention_mask
+ attention_mask = 1.0 - attention_mask[:, None, None, :].to(dtype=hidden_states.dtype)
+ attention_mask = attention_mask * torch.finfo(hidden_states.dtype).min
+ attention_mask = attention_mask.expand(
+ attention_mask.shape[0], 1, attention_mask.shape[-1], attention_mask.shape[-1]
+ )
+
+ hidden_states = self.dropout(hidden_states)
+
+ if self.embed_positions is not None:
+ relative_position_embeddings = self.embed_positions(hidden_states)
+ else:
+ relative_position_embeddings = None
+
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
+
+ for i, layer in enumerate(self.layers):
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
+ dropout_probability = torch.rand([])
+
+ skip_the_layer = self.training and dropout_probability < self.config.layerdrop
+ if not skip_the_layer or synced_gpus:
+ # under fsdp or deepspeed zero3 all gpus must run in sync
+ layer_outputs = layer(
+ hidden_states,
+ attention_mask=attention_mask,
+ relative_position_embeddings=relative_position_embeddings,
+ output_attentions=output_attentions,
+ )
+ hidden_states = layer_outputs[0]
+
+ if skip_the_layer:
+ layer_outputs = (None, None)
+
+ if output_attentions:
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
+
+ hidden_states = self.layer_norm(hidden_states)
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
+ return BaseModelOutput(
+ last_hidden_state=hidden_states,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ )
+
+
+class Wav2Vec2ConformerGumbelVectorQuantizer(Wav2Vec2GumbelVectorQuantizer):
+ pass
+
+
+class Wav2Vec2ConformerAdapter(Wav2Vec2Adapter):
+ pass
+
+
+class Wav2Vec2ConformerAdapterLayer(Wav2Vec2AdapterLayer):
+ pass
+
+
+@auto_docstring
+class Wav2Vec2ConformerPreTrainedModel(PreTrainedModel):
+ config: Wav2Vec2ConformerConfig
+ base_model_prefix = "wav2vec2_conformer"
+ main_input_name = "input_values"
+ input_modalities = "audio"
+ supports_gradient_checkpointing = True
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ # Wav2Vec2ForPreTraining last 2 linear layers need standard Linear init.
+ if isinstance(module, Wav2Vec2ConformerForPreTraining):
+ module.project_hid.reset_parameters()
+ module.project_q.reset_parameters()
+ # gumbel softmax requires special init
+ elif isinstance(module, Wav2Vec2ConformerGumbelVectorQuantizer):
+ init.normal_(module.weight_proj.weight, mean=0.0, std=1)
+ init.zeros_(module.weight_proj.bias)
+ init.uniform_(module.codevectors)
+ elif isinstance(module, Wav2Vec2ConformerSelfAttention):
+ if hasattr(module, "pos_bias_u"):
+ init.xavier_uniform_(module.pos_bias_u)
+ if hasattr(module, "pos_bias_v"):
+ init.xavier_uniform_(module.pos_bias_v)
+ elif isinstance(module, Wav2Vec2ConformerPositionalConvEmbedding):
+ init.normal_(
+ module.conv.weight,
+ mean=0,
+ std=2 * math.sqrt(1 / (module.conv.kernel_size[0] * module.conv.in_channels)),
+ )
+ init.constant_(module.conv.bias, 0)
+ elif isinstance(module, Wav2Vec2ConformerFeatureProjection):
+ k = math.sqrt(1 / module.projection.in_features)
+ init.uniform_(module.projection.weight, a=-k, b=k)
+ init.uniform_(module.projection.bias, a=-k, b=k)
+ elif isinstance(module, nn.Linear):
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
+
+ if module.bias is not None:
+ init.zeros_(module.bias)
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm, nn.BatchNorm1d)):
+ init.zeros_(module.bias)
+ init.ones_(module.weight)
+ if getattr(module, "running_mean", None) is not None:
+ init.zeros_(module.running_mean)
+ init.ones_(module.running_var)
+ init.zeros_(module.num_batches_tracked)
+ elif isinstance(module, nn.Conv1d):
+ init.kaiming_normal_(module.weight)
+
+ if module.bias is not None:
+ k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
+ init.uniform_(module.bias, a=-k, b=k)
+ elif isinstance(module, Wav2Vec2ConformerRotaryPositionalEmbedding):
+ dim = self.config.hidden_size // self.config.num_attention_heads
+ base = self.config.rotary_embedding_base
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).float() / dim))
+ init.copy_(module.inv_freq, inv_freq)
+ elif isinstance(module, Wav2Vec2ConformerRelPositionalEmbedding):
+ init.copy_(module.pe, module.extend_pe(torch.tensor(0.0).expand(1, module.max_len)))
+
+ def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor | int, add_adapter: bool | None = None):
+ """
+ Computes the output length of the convolutional layers
+ """
+
+ add_adapter = self.config.add_adapter if add_adapter is None else add_adapter
+
+ def _conv_out_length(input_length, kernel_size, stride):
+ # 1D convolutional layer output length formula taken
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
+ return torch.div(input_length - kernel_size, stride, rounding_mode="floor") + 1
+
+ for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
+ input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
+
+ if add_adapter:
+ for _ in range(self.config.num_adapter_layers):
+ input_lengths = _conv_out_length(input_lengths, 1, self.config.adapter_stride)
+
+ return input_lengths
+
+ def _get_feature_vector_attention_mask(
+ self, feature_vector_length: int, attention_mask: torch.LongTensor, add_adapter=None
+ ):
+ # Effectively attention_mask.sum(-1), but not inplace to be able to run
+ # on inference mode.
+ non_padded_lengths = attention_mask.cumsum(dim=-1)[:, -1]
+
+ output_lengths = self._get_feat_extract_output_lengths(non_padded_lengths, add_adapter=add_adapter)
+ output_lengths = output_lengths.to(torch.long)
+
+ batch_size = attention_mask.shape[0]
+
+ attention_mask = torch.zeros(
+ (batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device
+ )
+ # these two operations makes sure that all values before the output lengths idxs are attended to
+ attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1
+ attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool()
+ return attention_mask
+
+
+WAV2VEC2_CONFORMER_START_DOCSTRING = None # will be automatically redefined
+
+
+Wav2Vec2ConformerBaseModelOutput = Wav2Vec2BaseModelOutput
+
+
+class Wav2Vec2ConformerModel(Wav2Vec2ConformerPreTrainedModel, Wav2Vec2Model):
+ def __init__(self, config: Wav2Vec2ConformerConfig):
+ Wav2Vec2ConformerPreTrainedModel.__init__(self, config)
+ self.config = config
+ self.feature_extractor = Wav2Vec2ConformerFeatureEncoder(config)
+ self.feature_projection = Wav2Vec2ConformerFeatureProjection(config)
+
+ # model only needs masking vector if mask prob is > 0.0
+ if config.mask_time_prob > 0.0 or config.mask_feature_prob > 0.0:
+ self.masked_spec_embed = nn.Parameter(torch.Tensor(config.hidden_size).uniform_())
+
+ self.encoder = Wav2Vec2ConformerEncoder(config)
+
+ self.adapter = Wav2Vec2ConformerAdapter(config) if config.add_adapter else None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+
+class Wav2Vec2ConformerForPreTraining(Wav2Vec2ForPreTraining):
+ def __init__(self, config: Wav2Vec2ConformerConfig):
+ super().__init__(config)
+
+
+class Wav2Vec2ConformerForCTC(Wav2Vec2ForCTC):
+ def __init__(self, config, target_lang: str | None = None):
+ r"""
+ target_lang (`str`, *optional*):
+ Language id of adapter weights. Adapter weights are stored in the format adapter..safetensors or
+ adapter..bin. Only relevant when using an instance of [`UniSpeechSatForCTC`] with adapters. Uses 'eng' by
+ default.
+ """
+ super().__init__(config)
+
+ def tie_weights(self):
+ raise AttributeError("Not needed for Wav2Vec2Conformer")
+
+ def freeze_base_model(self):
+ raise AttributeError("Not needed for Wav2Vec2Conformer")
+
+
+class Wav2Vec2ConformerForSequenceClassification(Wav2Vec2ForSequenceClassification):
+ def __init__(self, config):
+ super().__init__(config)
+
+
+class Wav2Vec2ConformerForAudioFrameClassification(Wav2Vec2ForAudioFrameClassification):
+ def __init__(self, config):
+ super().__init__(config)
+
+
+class Wav2Vec2ConformerForXVector(Wav2Vec2ForXVector):
+ def __init__(self, config):
+ super().__init__(config)
+
+
+__all__ = [
+ "Wav2Vec2ConformerForAudioFrameClassification",
+ "Wav2Vec2ConformerForCTC",
+ "Wav2Vec2ConformerForPreTraining",
+ "Wav2Vec2ConformerForSequenceClassification",
+ "Wav2Vec2ConformerForXVector",
+ "Wav2Vec2ConformerModel",
+ "Wav2Vec2ConformerPreTrainedModel",
+]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_phoneme/__init__.py b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_phoneme/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..cbddfb4fe92d2c48a3c8f5ee7f8340650616e691
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_phoneme/__init__.py
@@ -0,0 +1,26 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .tokenization_wav2vec2_phoneme import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_phoneme/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_phoneme/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5e894ff1910a7451946c2b1537cad038e84df752
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_phoneme/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_phoneme/__pycache__/tokenization_wav2vec2_phoneme.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_phoneme/__pycache__/tokenization_wav2vec2_phoneme.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6be8470178a8025cccc2590f54521fb51958024d
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_phoneme/__pycache__/tokenization_wav2vec2_phoneme.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_phoneme/tokenization_wav2vec2_phoneme.py b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_phoneme/tokenization_wav2vec2_phoneme.py
new file mode 100644
index 0000000000000000000000000000000000000000..90fcf51fe787800e6c4d1106f80e8d688d06cbcf
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_phoneme/tokenization_wav2vec2_phoneme.py
@@ -0,0 +1,581 @@
+# Copyright 2021 The Facebook Inc. and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization class for Wav2Vec2Phoneme."""
+
+import json
+import os
+from dataclasses import dataclass
+from itertools import groupby
+from typing import TYPE_CHECKING, Any, Union
+
+import numpy as np
+
+from ...tokenization_python import PreTrainedTokenizer
+from ...tokenization_utils_base import AddedToken
+from ...utils import (
+ ModelOutput,
+ logging,
+ requires_backends,
+ to_py_obj,
+)
+
+
+logger = logging.get_logger(__name__)
+
+
+if TYPE_CHECKING:
+ import torch
+
+
+VOCAB_FILES_NAMES = {
+ "vocab_file": "vocab.json",
+ "tokenizer_config_file": "tokenizer_config.json",
+}
+
+
+# Wav2Vec2Phoneme has no max input length
+
+
+ListOfDict = list[dict[str, int | str]]
+
+
+@dataclass
+class Wav2Vec2PhonemeCTCTokenizerOutput(ModelOutput):
+ """
+ Output type of [` Wav2Vec2PhonemeCTCTokenizer`], with transcription.
+
+ Args:
+ text (list of `str` or `str`):
+ Decoded logits in text from. Usually the speech transcription.
+ char_offsets (list of `list[dict[str, Union[int, str]]]` or `list[dict[str, Union[int, str]]]`):
+ Offsets of the decoded characters. In combination with sampling rate and model downsampling rate char
+ offsets can be used to compute time stamps for each character. Total logit score of the beam associated with
+ produced text.
+ """
+
+ text: list[str] | str
+ char_offsets: list[ListOfDict] | ListOfDict = None
+
+
+class Wav2Vec2PhonemeCTCTokenizer(PreTrainedTokenizer):
+ """
+ Constructs a Wav2Vec2PhonemeCTC tokenizer.
+
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains some of the main methods. Users should refer to
+ the superclass for more information regarding such methods.
+
+ Args:
+ vocab_file (`str`):
+ File containing the vocabulary.
+ bos_token (`str`, *optional*, defaults to `""`):
+ The beginning of sentence token.
+ eos_token (`str`, *optional*, defaults to `""`):
+ The end of sentence token.
+ unk_token (`str`, *optional*, defaults to `""`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ pad_token (`str`, *optional*, defaults to `""`):
+ The token used for padding, for example when batching sequences of different lengths.
+ do_phonemize (`bool`, *optional*, defaults to `True`):
+ Whether the tokenizer should phonetize the input or not. Only if a sequence of phonemes is passed to the
+ tokenizer, `do_phonemize` should be set to `False`.
+ phonemizer_lang (`str`, *optional*, defaults to `"en-us"`):
+ The language of the phoneme set to which the tokenizer should phonetize the input text to.
+ phonemizer_backend (`str`, *optional*. defaults to `"espeak"`):
+ The backend phonetization library that shall be used by the phonemizer library. Defaults to `espeak-ng`.
+ See the [phonemizer package](https://github.com/bootphon/phonemizer#readme). for more information.
+
+ **kwargs
+ Additional keyword arguments passed along to [`PreTrainedTokenizer`]
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ model_input_names = ["input_ids", "attention_mask"]
+
+ def __init__(
+ self,
+ vocab_file,
+ bos_token="",
+ eos_token="",
+ unk_token="",
+ pad_token="",
+ phone_delimiter_token=" ",
+ word_delimiter_token=None,
+ do_phonemize=True,
+ phonemizer_lang="en-us",
+ phonemizer_backend="espeak",
+ **kwargs,
+ ):
+ # Recover delimiters from V5 `*_token` auto-promotion; they aren't vocab tokens.
+ model_specific = kwargs.get("model_specific_special_tokens") or {}
+ if "word_delimiter_token" in model_specific:
+ word_delimiter_token = model_specific.pop("word_delimiter_token")
+ if "phone_delimiter_token" in model_specific:
+ phone_delimiter_token = model_specific.pop("phone_delimiter_token")
+ if not model_specific:
+ kwargs.pop("model_specific_special_tokens", None)
+
+ self._word_delimiter_token = word_delimiter_token
+ self._phone_delimiter_token = phone_delimiter_token
+ self.do_phonemize = do_phonemize
+ self.phonemizer_lang = phonemizer_lang
+ self.phonemizer_backend = phonemizer_backend
+
+ if do_phonemize:
+ self.init_backend(self.phonemizer_lang)
+
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
+ self.encoder = json.load(vocab_handle)
+ self.decoder = {v: k for k, v in self.encoder.items()}
+
+ super().__init__(
+ unk_token=unk_token,
+ bos_token=bos_token,
+ eos_token=eos_token,
+ pad_token=pad_token,
+ do_phonemize=do_phonemize,
+ phonemizer_lang=phonemizer_lang,
+ phonemizer_backend=phonemizer_backend,
+ **kwargs,
+ )
+ self.init_kwargs["word_delimiter_token"] = word_delimiter_token
+ self.init_kwargs["phone_delimiter_token"] = phone_delimiter_token
+
+ @property
+ def vocab_size(self) -> int:
+ return len(self.decoder)
+
+ def get_vocab(self) -> dict:
+ vocab = dict(self.encoder.copy())
+ vocab.update(self.added_tokens_encoder)
+ return vocab
+
+ def _add_tokens(self, new_tokens: list[str] | list[AddedToken], special_tokens: bool = False) -> int:
+ # Overwritten to never strip!
+ to_add = []
+ for token in new_tokens:
+ if isinstance(token, str):
+ to_add.append(AddedToken(token, rstrip=False, lstrip=False, normalized=True, special=special_tokens))
+ else:
+ to_add.append(token)
+
+ return super()._add_tokens(to_add, special_tokens)
+
+ def init_backend(self, phonemizer_lang: str):
+ """
+ Initializes the backend.
+
+ Args:
+ phonemizer_lang (`str`): The language to be used.
+ """
+ requires_backends(self, "phonemizer")
+ from phonemizer.backend import BACKENDS
+
+ self._phonemizer_backend = BACKENDS[self.phonemizer_backend](phonemizer_lang, language_switch="remove-flags")
+
+ def prepare_for_tokenization(
+ self,
+ text: str,
+ is_split_into_words: bool = False,
+ phonemizer_lang: str | None = None,
+ do_phonemize: bool | None = None,
+ **kwargs,
+ ) -> tuple[str, dict[str, Any]]:
+ """
+ Performs any necessary transformations before tokenization.
+
+ This method should pop the arguments from kwargs and return the remaining `kwargs` as well. We test the
+ `kwargs` at the end of the encoding process to be sure all the arguments have been used.
+
+ Args:
+ text (`str`):
+ The text to prepare.
+ is_split_into_words (`bool`, *optional*, defaults to `False`):
+ Whether or not the input is already pre-tokenized (e.g., split into words). If set to `True`, the
+ tokenizer assumes the input is already split into words (for instance, by splitting it on whitespace)
+ which it will tokenize. This is useful for NER or token classification.
+ phonemizer_lang (`str`, *optional*):
+ The language of the phoneme set to which the tokenizer should phonetize the input text to.
+ do_phonemize (`bool`, *optional*):
+ Whether the tokenizer should phonetize the input text or not. Only if a sequence of phonemes is passed
+ to the tokenizer, `do_phonemize` should be set to `False`.
+
+
+ Returns:
+ `tuple[str, dict[str, Any]]`: The prepared text and the unused kwargs.
+ """
+ if is_split_into_words:
+ text = " " + text
+
+ # set whether tokenizer should phonemize or not
+ if do_phonemize is not None:
+ self.do_phonemize = do_phonemize
+
+ # set the correct phonemizer language
+ if phonemizer_lang is not None:
+ self.phonemizer_lang = phonemizer_lang
+ self.init_backend(phonemizer_lang)
+
+ return (text, {})
+
+ def _tokenize(self, text, **kwargs):
+ """
+ Converts a string into a sequence of tokens (string), using the tokenizer.
+ """
+
+ # make sure whitespace is stripped to prevent
+ text = text.strip()
+
+ # phonemize
+ if self.do_phonemize:
+ text = text.lower()
+
+ # create list of phonemes
+ text = self.phonemize(text, self.phonemizer_lang)
+
+ # make sure ' ' is between phonemes
+ tokens = text.split(" ")
+
+ tokens = list(filter(lambda p: p.strip() != "", tokens))
+ return tokens
+
+ def phonemize(self, text: str, phonemizer_lang: str | None = None) -> str:
+ from phonemizer.separator import Separator
+
+ word_delimiter = self.word_delimiter_token + " " if self.word_delimiter_token is not None else ""
+ if phonemizer_lang is not None and phonemizer_lang != self.phonemizer_lang:
+ self.init_backend(phonemizer_lang)
+ else:
+ phonemizer_lang = self.phonemizer_lang
+
+ separator = Separator(phone=self.phone_delimiter_token, word=word_delimiter, syllable="")
+ phonemes = self._phonemizer_backend.phonemize(
+ [text],
+ separator=separator,
+ )
+ phonemes = phonemes[0].strip()
+
+ return phonemes
+
+ @property
+ def word_delimiter_token(self) -> str:
+ """
+ `str`: Word delimiter token. Log an error if used while not having been set.
+ """
+ if self._word_delimiter_token is None:
+ if self.verbose:
+ logger.error("Using word_delimiter_token, but it is not set yet.")
+ return None
+ return str(self._word_delimiter_token)
+
+ @property
+ def word_delimiter_token_id(self) -> int | None:
+ """
+ `Optional[int]`: Id of the word_delimiter_token in the vocabulary. Returns `None` if the token has not been
+ set.
+ """
+ if self._word_delimiter_token is None:
+ return None
+ return self.convert_tokens_to_ids(self.word_delimiter_token)
+
+ @word_delimiter_token.setter
+ def word_delimiter_token(self, value):
+ self._word_delimiter_token = value
+
+ @word_delimiter_token_id.setter
+ def word_delimiter_token_id(self, value):
+ self._word_delimiter_token = self.convert_tokens_to_ids(value)
+
+ @property
+ def phone_delimiter_token(self) -> str:
+ """
+ `str`: Word delimiter token. Log an error if used while not having been set.
+ """
+ if self._phone_delimiter_token is None:
+ if self.verbose:
+ logger.error("Using phone_delimiter_token, but it is not set yet.")
+ return None
+ return str(self._phone_delimiter_token)
+
+ @property
+ def phone_delimiter_token_id(self) -> int | None:
+ """
+ `Optional[int]`: Id of the phone_delimiter_token in the vocabulary. Returns `None` if the token has not been
+ set.
+ """
+ if self._phone_delimiter_token is None:
+ return None
+ return self.convert_tokens_to_ids(self.phone_delimiter_token)
+
+ @phone_delimiter_token.setter
+ def phone_delimiter_token(self, value):
+ self._phone_delimiter_token = value
+
+ @phone_delimiter_token_id.setter
+ def phone_delimiter_token_id(self, value):
+ self._phone_delimiter_token = self.convert_tokens_to_ids(value)
+
+ def _convert_token_to_id(self, token: str) -> int:
+ """Converts a token (str) in an index (integer) using the vocab."""
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
+
+ def _convert_id_to_token(self, index: int) -> str:
+ """Converts an index (integer) in a token (str) using the vocab."""
+ result = self.decoder.get(index, self.unk_token)
+ return result
+
+ def convert_tokens_to_string(
+ self,
+ tokens: list[str],
+ group_tokens: bool = True,
+ spaces_between_special_tokens: bool = False,
+ filter_word_delimiter_token: bool = True,
+ output_char_offsets: bool = False,
+ ) -> str:
+ """
+ Converts a connectionist-temporal-classification (CTC) output tokens into a single string.
+ """
+ # group same tokens into non-repeating tokens in CTC style decoding
+ if group_tokens:
+ chars, char_repetitions = zip(*((token, len(list(group_iter))) for token, group_iter in groupby(tokens)))
+ else:
+ chars = tokens
+ char_repetitions = len(tokens) * [1]
+
+ # filter self.pad_token which is used as CTC-blank token
+ processed_chars = list(filter(lambda char: char != self.pad_token, chars))
+
+ # also filter self.word_delimiter_token if not not
+ if filter_word_delimiter_token and self.word_delimiter_token is not None:
+ processed_chars = list(filter(lambda token: token != self.word_delimiter_token, processed_chars))
+
+ # retrieve offsets
+ char_offsets = None
+ if output_char_offsets:
+ word_delimiter_token_for_offsets = (
+ self.word_delimiter_token if filter_word_delimiter_token is True else None
+ )
+ char_offsets = self._compute_offsets(
+ char_repetitions, chars, self.pad_token, word_delimiter_token=word_delimiter_token_for_offsets
+ )
+
+ if len(char_offsets) != len(processed_chars):
+ raise ValueError(
+ f"`char_offsets`: {char_offsets} and `processed_tokens`: {processed_chars}"
+ " have to be of the same length, but are: `len(offsets)`: "
+ f"{len(char_offsets)} and `len(processed_tokens)`: {len(processed_chars)}"
+ )
+
+ # set tokens to correct processed token
+ for i, char in enumerate(processed_chars):
+ char_offsets[i]["char"] = char
+
+ string = " ".join(processed_chars).strip()
+
+ return {"text": string, "char_offsets": char_offsets}
+
+ @staticmethod
+ def _compute_offsets(
+ char_repetitions: list[int], chars: list[str], ctc_token: int, word_delimiter_token: int | None = None
+ ) -> list[dict[str, str | int]]:
+ end_indices = np.asarray(char_repetitions).cumsum()
+ start_indices = np.concatenate(([0], end_indices[:-1]))
+
+ offsets = [
+ {"char": t, "start_offset": s, "end_offset": e} for t, s, e in zip(chars, start_indices, end_indices)
+ ]
+
+ # filter out CTC token
+ offsets = list(filter(lambda offsets: offsets["char"] != ctc_token, offsets))
+
+ # filter out word delimiter token if necessary
+ if word_delimiter_token is not None:
+ offsets = list(filter(lambda offsets: offsets["char"] != word_delimiter_token, offsets))
+
+ return offsets
+
+ def _decode(
+ self,
+ token_ids: list[int],
+ skip_special_tokens: bool = False,
+ clean_up_tokenization_spaces: bool | None = None,
+ group_tokens: bool = True,
+ filter_word_delimiter_token: bool = True,
+ spaces_between_special_tokens: bool = False,
+ output_char_offsets: bool = False,
+ ) -> str:
+ """
+ special _decode function is needed for Wav2Vec2PhonemeTokenizer because added tokens should be treated exactly
+ the same as tokens of the base vocabulary and therefore the function `convert_tokens_to_string` has to be
+ called on the whole token list and not individually on added tokens
+ """
+ filtered_tokens = self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens)
+
+ result = []
+ for token in filtered_tokens:
+ if skip_special_tokens and token in self.all_special_ids:
+ continue
+ result.append(token)
+
+ string_output = self.convert_tokens_to_string(
+ result,
+ group_tokens=group_tokens,
+ spaces_between_special_tokens=spaces_between_special_tokens,
+ filter_word_delimiter_token=filter_word_delimiter_token,
+ output_char_offsets=output_char_offsets,
+ )
+
+ text = string_output["text"]
+
+ clean_up_tokenization_spaces = (
+ clean_up_tokenization_spaces
+ if clean_up_tokenization_spaces is not None
+ else self.clean_up_tokenization_spaces
+ )
+ if clean_up_tokenization_spaces:
+ text = self.clean_up_tokenization(text)
+
+ if output_char_offsets:
+ return Wav2Vec2PhonemeCTCTokenizerOutput(text=text, char_offsets=string_output["char_offsets"])
+ else:
+ return text
+
+ # overwritten from `tokenization_utils_base.py` because we need docs for `output_char_offsets` here
+ def decode(
+ self,
+ token_ids: Union[int, list[int], np.ndarray, "torch.Tensor"],
+ skip_special_tokens: bool = False,
+ clean_up_tokenization_spaces: bool | None = None,
+ output_char_offsets: bool = False,
+ **kwargs,
+ ) -> str:
+ """
+ Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special
+ tokens and clean up tokenization spaces.
+
+ Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.
+
+ Args:
+ token_ids (`Union[int, list[int], np.ndarray, torch.Tensor]`):
+ List of tokenized input ids. Can be obtained using the `__call__` method.
+ skip_special_tokens (`bool`, *optional*, defaults to `False`):
+ Whether or not to remove special tokens in the decoding.
+ clean_up_tokenization_spaces (`bool`, *optional*):
+ Whether or not to clean up the tokenization spaces.
+ output_char_offsets (`bool`, *optional*, defaults to `False`):
+ Whether or not to output character offsets. Character offsets can be used in combination with the
+ sampling rate and model downsampling rate to compute the time-stamps of transcribed characters.
+
+
+
+ Please take a look at the Example of [`~models.wav2vec2.tokenization_wav2vec2.decode`] to better
+ understand how to make use of `output_word_offsets`.
+ [`~model.wav2vec2_phoneme.tokenization_wav2vec2_phoneme.batch_decode`] works the same way with
+ phonemes.
+
+
+
+ kwargs (additional keyword arguments, *optional*):
+ Will be passed to the underlying model specific decode method.
+
+ Returns:
+ `str` or [`~models.wav2vec2.tokenization_wav2vec2_phoneme.Wav2Vec2PhonemeCTCTokenizerOutput`]: The decoded
+ sentence. Will be a [`~models.wav2vec2.tokenization_wav2vec2_phoneme.Wav2Vec2PhonemeCTCTokenizerOutput`]
+ when `output_char_offsets == True`.
+ """
+ # Convert inputs to python lists
+ token_ids = to_py_obj(token_ids)
+
+ return self._decode(
+ token_ids=token_ids,
+ skip_special_tokens=skip_special_tokens,
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
+ output_char_offsets=output_char_offsets,
+ **kwargs,
+ )
+
+ # overwritten from `tokenization_utils_base.py` because tokenizer can output
+ # `ModelOutput` which should not be a list for batched output and because
+ # we need docs for `output_char_offsets` here
+ def batch_decode(
+ self,
+ sequences: Union[list[int], list[list[int]], np.ndarray, "torch.Tensor"],
+ skip_special_tokens: bool = False,
+ clean_up_tokenization_spaces: bool | None = None,
+ output_char_offsets: bool = False,
+ **kwargs,
+ ) -> list[str]:
+ """
+ Convert a list of lists of token ids into a list of strings by calling decode.
+
+ Args:
+ sequences (`Union[list[int], list[list[int]], np.ndarray, torch.Tensor]`):
+ List of tokenized input ids. Can be obtained using the `__call__` method.
+ skip_special_tokens (`bool`, *optional*, defaults to `False`):
+ Whether or not to remove special tokens in the decoding.
+ clean_up_tokenization_spaces (`bool`, *optional*):
+ Whether or not to clean up the tokenization spaces.
+ output_char_offsets (`bool`, *optional*, defaults to `False`):
+ Whether or not to output character offsets. Character offsets can be used in combination with the
+ sampling rate and model downsampling rate to compute the time-stamps of transcribed characters.
+
+
+
+ Please take a look at the Example of [`~models.wav2vec2.tokenization_wav2vec2.decode`] to better
+ understand how to make use of `output_word_offsets`.
+ [`~model.wav2vec2_phoneme.tokenization_wav2vec2_phoneme.batch_decode`] works analogous with phonemes
+ and batched output.
+
+
+
+ kwargs (additional keyword arguments, *optional*):
+ Will be passed to the underlying model specific decode method.
+
+ Returns:
+ `list[str]` or [`~models.wav2vec2.tokenization_wav2vec2_phoneme.Wav2Vec2PhonemeCTCTokenizerOutput`]: The
+ decoded sentence. Will be a
+ [`~models.wav2vec2.tokenization_wav2vec2_phoneme.Wav2Vec2PhonemeCTCTokenizerOutput`] when
+ `output_char_offsets == True`.
+ """
+ batch_decoded = [
+ self.decode(
+ seq,
+ skip_special_tokens=skip_special_tokens,
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
+ output_char_offsets=output_char_offsets,
+ **kwargs,
+ )
+ for seq in sequences
+ ]
+ if output_char_offsets:
+ # transform list of dicts to dict of lists
+ return Wav2Vec2PhonemeCTCTokenizerOutput({k: [d[k] for d in batch_decoded] for k in batch_decoded[0]})
+
+ return batch_decoded
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
+ if not os.path.isdir(save_directory):
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
+ return
+ vocab_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
+ )
+
+ with open(vocab_file, "w", encoding="utf-8") as f:
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
+
+ return (vocab_file,)
+
+
+__all__ = ["Wav2Vec2PhonemeCTCTokenizer"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_with_lm/__init__.py b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_with_lm/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..95fd10dab7092fb8571a332b1ecf2e9a334d8fc4
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_with_lm/__init__.py
@@ -0,0 +1,26 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .processing_wav2vec2_with_lm import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_with_lm/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_with_lm/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ebfe94859c6d6c90a0a099c4462563c4fb88298b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_with_lm/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_with_lm/__pycache__/processing_wav2vec2_with_lm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_with_lm/__pycache__/processing_wav2vec2_with_lm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aca77c143373603ac730cc372de1a569e5ee745f
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_with_lm/__pycache__/processing_wav2vec2_with_lm.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.py b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.py
new file mode 100644
index 0000000000000000000000000000000000000000..68904ee263675a43f4d1379d2816af7c93a15334
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.py
@@ -0,0 +1,610 @@
+# Copyright 2021 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Speech processor class for Wav2Vec2
+"""
+
+import os
+from collections.abc import Iterable
+from contextlib import nullcontext
+from dataclasses import dataclass
+from multiprocessing import get_context, get_start_method
+from multiprocessing.pool import Pool
+from typing import TYPE_CHECKING
+
+import numpy as np
+
+from ...processing_utils import ProcessorMixin
+from ...utils import ModelOutput, auto_docstring, logging, requires_backends
+
+
+logger = logging.get_logger(__name__)
+
+
+if TYPE_CHECKING:
+ from pyctcdecode import BeamSearchDecoderCTC
+
+ from ...feature_extraction_utils import FeatureExtractionMixin
+ from ...tokenization_python import PreTrainedTokenizerBase
+
+
+ListOfDict = list[dict[str, int | str]]
+
+
+@dataclass
+class Wav2Vec2DecoderWithLMOutput(ModelOutput):
+ """
+ Output type of [`Wav2Vec2DecoderWithLM`], with transcription.
+
+ Args:
+ text (list of `str` or `str`):
+ Decoded logits in text from. Usually the speech transcription.
+ logit_score (list of `float` or `float`):
+ Total logit score of the beams associated with produced text.
+ lm_score (list of `float`):
+ Fused lm_score of the beams associated with produced text.
+ word_offsets (list of `list[dict[str, Union[int, str]]]` or `list[dict[str, Union[int, str]]]`):
+ Offsets of the decoded words. In combination with sampling rate and model downsampling rate word offsets
+ can be used to compute time stamps for each word.
+ """
+
+ text: list[list[str]] | list[str] | str
+ logit_score: list[list[float]] | list[float] | float = None
+ lm_score: list[list[float]] | list[float] | float = None
+ word_offsets: list[list[ListOfDict]] | list[ListOfDict] | ListOfDict = None
+
+
+@auto_docstring
+class Wav2Vec2ProcessorWithLM(ProcessorMixin):
+ def __init__(
+ self,
+ feature_extractor: "FeatureExtractionMixin",
+ tokenizer: "PreTrainedTokenizerBase",
+ decoder: "BeamSearchDecoderCTC",
+ ):
+ r"""
+ decoder (`pyctcdecode.BeamSearchDecoderCTC`):
+ An instance of [`pyctcdecode.BeamSearchDecoderCTC`]. The decoder is a required input.
+ """
+ from pyctcdecode import BeamSearchDecoderCTC
+
+ super().__init__(feature_extractor, tokenizer)
+ if not isinstance(decoder, BeamSearchDecoderCTC):
+ raise TypeError(f"`decoder` has to be of type {BeamSearchDecoderCTC.__class__}, but is {type(decoder)}")
+
+ if feature_extractor.__class__.__name__ not in ["Wav2Vec2FeatureExtractor", "SeamlessM4TFeatureExtractor"]:
+ raise ValueError(
+ f"`feature_extractor` has to be of type `Wav2Vec2FeatureExtractor` or `SeamlessM4TFeatureExtractor`, but is {type(feature_extractor)}"
+ )
+
+ # make sure that decoder's alphabet and tokenizer's vocab match in content
+ missing_decoder_tokens = self.get_missing_alphabet_tokens(decoder, tokenizer)
+ if len(missing_decoder_tokens) > 0:
+ raise ValueError(
+ f"The tokens {missing_decoder_tokens} are defined in the tokenizer's "
+ "vocabulary, but not in the decoder's alphabet. "
+ f"Make sure to include {missing_decoder_tokens} in the decoder's alphabet."
+ )
+
+ self.decoder = decoder
+
+ def save_pretrained(self, save_directory):
+ super().save_pretrained(save_directory)
+ self.decoder.save_to_dir(save_directory)
+
+ @classmethod
+ def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
+ r"""
+ Instantiate a [`Wav2Vec2ProcessorWithLM`] from a pretrained Wav2Vec2 processor.
+
+
+
+ This class method is simply calling the feature extractor's
+ [`~feature_extraction_utils.FeatureExtractionMixin.from_pretrained`], Wav2Vec2CTCTokenizer's
+ [`~tokenization_utils_base.PreTrainedTokenizerBase.from_pretrained`], and
+ [`pyctcdecode.BeamSearchDecoderCTC.load_from_hf_hub`].
+
+ Please refer to the docstrings of the methods above for more information.
+
+
+
+ Args:
+ pretrained_model_name_or_path (`str` or `os.PathLike`):
+ This can be either:
+
+ - a string, the *model id* of a pretrained feature_extractor hosted inside a model repo on
+ huggingface.co.
+ - a path to a *directory* containing a feature extractor file saved using the
+ [`~SequenceFeatureExtractor.save_pretrained`] method, e.g., `./my_model_directory/`.
+ - a path to a saved feature extractor JSON *file*, e.g.,
+ `./my_model_directory/preprocessor_config.json`.
+ **kwargs
+ Additional keyword arguments passed along to both [`SequenceFeatureExtractor`] and
+ [`PreTrainedTokenizer`]
+ """
+ requires_backends(cls, "pyctcdecode")
+ from pyctcdecode import BeamSearchDecoderCTC
+
+ feature_extractor, tokenizer = super()._get_arguments_from_pretrained(pretrained_model_name_or_path, **kwargs)
+
+ if os.path.isdir(pretrained_model_name_or_path) or os.path.isfile(pretrained_model_name_or_path):
+ unigram_encoding = kwargs.get("unigram_encoding", "utf-8")
+ decoder = BeamSearchDecoderCTC.load_from_dir(pretrained_model_name_or_path, unigram_encoding)
+ else:
+ # BeamSearchDecoderCTC has no auto class
+ kwargs.pop("_from_auto", None)
+ # snapshot_download has no `trust_remote_code` flag
+ kwargs.pop("trust_remote_code", None)
+
+ # make sure that only relevant filenames are downloaded
+ language_model_filenames = os.path.join(BeamSearchDecoderCTC._LANGUAGE_MODEL_SERIALIZED_DIRECTORY, "*")
+ alphabet_filename = BeamSearchDecoderCTC._ALPHABET_SERIALIZED_FILENAME
+ allow_patterns = [language_model_filenames, alphabet_filename]
+
+ decoder = BeamSearchDecoderCTC.load_from_hf_hub(
+ pretrained_model_name_or_path, allow_patterns=allow_patterns, **kwargs
+ )
+
+ # set language model attributes
+ for attribute in ["alpha", "beta", "unk_score_offset", "score_boundary"]:
+ value = kwargs.pop(attribute, None)
+
+ if value is not None:
+ cls._set_language_model_attribute(decoder, attribute, value)
+
+ # make sure that decoder's alphabet and tokenizer's vocab match in content
+ missing_decoder_tokens = cls.get_missing_alphabet_tokens(decoder, tokenizer)
+ if len(missing_decoder_tokens) > 0:
+ raise ValueError(
+ f"The tokens {missing_decoder_tokens} are defined in the tokenizer's "
+ "vocabulary, but not in the decoder's alphabet. "
+ f"Make sure to include {missing_decoder_tokens} in the decoder's alphabet."
+ )
+
+ return cls(feature_extractor=feature_extractor, tokenizer=tokenizer, decoder=decoder)
+
+ @staticmethod
+ def _set_language_model_attribute(decoder: "BeamSearchDecoderCTC", attribute: str, value: float):
+ setattr(decoder.model_container[decoder._model_key], attribute, value)
+
+ @property
+ def language_model(self):
+ return self.decoder.model_container[self.decoder._model_key]
+
+ @staticmethod
+ def get_missing_alphabet_tokens(decoder, tokenizer):
+ from pyctcdecode.alphabet import BLANK_TOKEN_PTN, UNK_TOKEN, UNK_TOKEN_PTN
+
+ # we need to make sure that all of the tokenizer's except the special tokens
+ # are present in the decoder's alphabet. Retrieve missing alphabet token
+ # from decoder
+ tokenizer_vocab_list = list(tokenizer.get_vocab().keys())
+
+ # replace special tokens
+ for i, token in enumerate(tokenizer_vocab_list):
+ if BLANK_TOKEN_PTN.match(token):
+ tokenizer_vocab_list[i] = ""
+ if token == tokenizer.word_delimiter_token:
+ tokenizer_vocab_list[i] = " "
+ if UNK_TOKEN_PTN.match(token):
+ tokenizer_vocab_list[i] = UNK_TOKEN
+
+ # are any of the extra tokens no special tokenizer tokens?
+ missing_tokens = set(tokenizer_vocab_list) - set(decoder._alphabet.labels)
+
+ return missing_tokens
+
+ @auto_docstring
+ def __call__(self, *args, **kwargs):
+ audio = kwargs.pop("audio", None)
+ sampling_rate = kwargs.pop("sampling_rate", None)
+ text = kwargs.pop("text", None)
+ if len(args) > 0:
+ audio = args[0]
+ args = args[1:]
+
+ if audio is None and text is None:
+ raise ValueError("You need to specify either an `audio` or `text` input to process.")
+
+ if audio is not None:
+ inputs = self.feature_extractor(audio, *args, sampling_rate=sampling_rate, **kwargs)
+ if text is not None:
+ encodings = self.tokenizer(text, **kwargs)
+
+ if text is None:
+ return inputs
+ elif audio is None:
+ return encodings
+ else:
+ inputs["labels"] = encodings["input_ids"]
+ return inputs
+
+ def pad(self, *args, **kwargs):
+ """
+ When used in normal mode, this method forwards all its arguments to the feature extractor's
+ [`~FeatureExtractionMixin.pad`] and returns its output. If used in the context
+ [`~Wav2Vec2ProcessorWithLM.as_target_processor`] this method forwards all its arguments to
+ Wav2Vec2CTCTokenizer's [`~Wav2Vec2CTCTokenizer.pad`]. Please refer to the docstring of the above two methods
+ for more information.
+ """
+ input_features = kwargs.pop("input_features", None)
+ labels = kwargs.pop("labels", None)
+ if len(args) > 0:
+ input_features = args[0]
+ args = args[1:]
+
+ if input_features is not None:
+ input_features = self.feature_extractor.pad(input_features, *args, **kwargs)
+ if labels is not None:
+ labels = self.tokenizer.pad(labels, **kwargs)
+
+ if labels is None:
+ return input_features
+ elif input_features is None:
+ return labels
+ else:
+ input_features["labels"] = labels["input_ids"]
+ return input_features
+
+ def batch_decode(
+ self,
+ logits: np.ndarray,
+ pool: Pool | None = None,
+ num_processes: int | None = None,
+ beam_width: int | None = None,
+ beam_prune_logp: float | None = None,
+ token_min_logp: float | None = None,
+ hotwords: Iterable[str] | None = None,
+ hotword_weight: float | None = None,
+ alpha: float | None = None,
+ beta: float | None = None,
+ unk_score_offset: float | None = None,
+ lm_score_boundary: bool | None = None,
+ output_word_offsets: bool = False,
+ n_best: int = 1,
+ ):
+ """
+ Batch decode output logits to audio transcription with language model support.
+
+
+
+ This function makes use of Python's multiprocessing. Currently, multiprocessing is available only on Unix
+ systems (see this [issue](https://github.com/kensho-technologies/pyctcdecode/issues/65)).
+
+ If you are decoding multiple batches, consider creating a `Pool` and passing it to `batch_decode`. Otherwise,
+ `batch_decode` will be very slow since it will create a fresh `Pool` for each call. See usage example below.
+
+
+
+ Args:
+ logits (`np.ndarray`):
+ The logits output vector of the model representing the log probabilities for each token.
+ pool (`multiprocessing.Pool`, *optional*):
+ An optional user-managed pool. If not set, one will be automatically created and closed. The pool
+ should be instantiated *after* `Wav2Vec2ProcessorWithLM`. Otherwise, the LM won't be available to the
+ pool's sub-processes.
+
+
+
+ Currently, only pools created with a 'fork' context can be used. If a 'spawn' pool is passed, it will
+ be ignored and sequential decoding will be used instead.
+
+
+
+ num_processes (`int`, *optional*):
+ If `pool` is not set, number of processes on which the function should be parallelized over. Defaults
+ to the number of available CPUs.
+ beam_width (`int`, *optional*):
+ Maximum number of beams at each step in decoding. Defaults to pyctcdecode's DEFAULT_BEAM_WIDTH.
+ beam_prune_logp (`int`, *optional*):
+ Beams that are much worse than best beam will be pruned Defaults to pyctcdecode's DEFAULT_PRUNE_LOGP.
+ token_min_logp (`int`, *optional*):
+ Tokens below this logp are skipped unless they are argmax of frame Defaults to pyctcdecode's
+ DEFAULT_MIN_TOKEN_LOGP.
+ hotwords (`list[str]`, *optional*):
+ List of words with extra importance, can be OOV for LM
+ hotword_weight (`int`, *optional*):
+ Weight factor for hotword importance Defaults to pyctcdecode's DEFAULT_HOTWORD_WEIGHT.
+ alpha (`float`, *optional*):
+ Weight for language model during shallow fusion
+ beta (`float`, *optional*):
+ Weight for length score adjustment of during scoring
+ unk_score_offset (`float`, *optional*):
+ Amount of log score offset for unknown tokens
+ lm_score_boundary (`bool`, *optional*):
+ Whether to have kenlm respect boundaries when scoring
+ output_word_offsets (`bool`, *optional*, defaults to `False`):
+ Whether or not to output word offsets. Word offsets can be used in combination with the sampling rate
+ and model downsampling rate to compute the time-stamps of transcribed words.
+ n_best (`int`, *optional*, defaults to `1`):
+ Number of best hypotheses to return. If `n_best` is greater than 1, the returned `text` will be a list
+ of lists of strings, `logit_score` will be a list of lists of floats, and `lm_score` will be a list of
+ lists of floats, where the length of the outer list will correspond to the batch size and the length of
+ the inner list will correspond to the number of returned hypotheses . The value should be >= 1.
+
+
+
+ Please take a look at the Example of [`~Wav2Vec2ProcessorWithLM.decode`] to better understand how to
+ make use of `output_word_offsets`. [`~Wav2Vec2ProcessorWithLM.batch_decode`] works the same way with
+ batched output.
+
+
+
+ Returns:
+ [`~models.wav2vec2.Wav2Vec2DecoderWithLMOutput`].
+
+ Example:
+ See [Decoding multiple audios](#decoding-multiple-audios).
+ """
+
+ from pyctcdecode.constants import (
+ DEFAULT_BEAM_WIDTH,
+ DEFAULT_HOTWORD_WEIGHT,
+ DEFAULT_MIN_TOKEN_LOGP,
+ DEFAULT_PRUNE_LOGP,
+ )
+
+ # set defaults
+ beam_width = beam_width if beam_width is not None else DEFAULT_BEAM_WIDTH
+ beam_prune_logp = beam_prune_logp if beam_prune_logp is not None else DEFAULT_PRUNE_LOGP
+ token_min_logp = token_min_logp if token_min_logp is not None else DEFAULT_MIN_TOKEN_LOGP
+ hotword_weight = hotword_weight if hotword_weight is not None else DEFAULT_HOTWORD_WEIGHT
+
+ # reset params at every forward call. It's just a `set` method in pyctcdecode
+ self.decoder.reset_params(
+ alpha=alpha, beta=beta, unk_score_offset=unk_score_offset, lm_score_boundary=lm_score_boundary
+ )
+
+ # create multiprocessing pool and list numpy arrays
+ # filter out logits padding
+ logits_list = [array[(array != -100.0).all(axis=-1)] for array in logits]
+
+ # create a pool if necessary while also using it as a context manager to close itself
+ if pool is None:
+ # fork is safe to use only on Unix, see "Contexts and start methods" section on
+ # multiprocessing's docs (https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods)
+ default_context = get_start_method()
+
+ if default_context == "fork":
+ cm = pool = get_context().Pool(num_processes)
+ else:
+ logger.warning(
+ "Parallel batch decoding is not currently supported in this platform. "
+ "Falling back to sequential decoding."
+ )
+ cm = nullcontext()
+ else:
+ # pool is managed by the user, so we don't need to close it
+ cm = nullcontext()
+
+ if num_processes is not None:
+ logger.warning(
+ "Parameter `num_process` was passed, but it will be ignored since `pool` was also specified."
+ )
+
+ # pyctcdecode
+ with cm:
+ decoded_beams = self.decoder.decode_beams_batch(
+ pool=pool,
+ logits_list=logits_list,
+ beam_width=beam_width,
+ beam_prune_logp=beam_prune_logp,
+ token_min_logp=token_min_logp,
+ hotwords=hotwords,
+ hotword_weight=hotword_weight,
+ )
+
+ # extract text and scores
+ batch_texts, logit_scores, lm_scores, word_offsets = [], [], [], []
+
+ for d in decoded_beams:
+ batch_texts.append([beam[0] for beam in d])
+ logit_scores.append([beam[-2] for beam in d])
+ lm_scores.append([beam[-1] for beam in d])
+
+ # word_offsets.append([{"word": t[0], "start_offset": t[1][0], "end_offset": t[1][1]} for t in d[0][1]])
+
+ word_offsets.append(
+ [
+ [
+ {"word": word, "start_offset": start_offset, "end_offset": end_offset}
+ for word, (start_offset, end_offset) in beam[1]
+ ]
+ for beam in d
+ ]
+ )
+
+ word_offsets = word_offsets if output_word_offsets else None
+
+ if n_best == 1:
+ return Wav2Vec2DecoderWithLMOutput(
+ text=[hyps[0] for hyps in batch_texts],
+ logit_score=[hyps[0] for hyps in logit_scores],
+ lm_score=[hyps[0] for hyps in lm_scores],
+ word_offsets=[hyps[0] for hyps in word_offsets] if word_offsets is not None else None,
+ )
+ else:
+ return Wav2Vec2DecoderWithLMOutput(
+ text=[hyps[:n_best] for hyps in batch_texts],
+ logit_score=[hyps[:n_best] for hyps in logit_scores],
+ lm_score=[hyps[:n_best] for hyps in lm_scores],
+ word_offsets=[hyps[:n_best] for hyps in word_offsets] if word_offsets is not None else None,
+ )
+
+ def decode(
+ self,
+ logits: np.ndarray,
+ beam_width: int | None = None,
+ beam_prune_logp: float | None = None,
+ token_min_logp: float | None = None,
+ hotwords: Iterable[str] | None = None,
+ hotword_weight: float | None = None,
+ alpha: float | None = None,
+ beta: float | None = None,
+ unk_score_offset: float | None = None,
+ lm_score_boundary: bool | None = None,
+ output_word_offsets: bool = False,
+ n_best: int = 1,
+ ):
+ """
+ Decode output logits to audio transcription with language model support.
+
+ Args:
+ logits (`np.ndarray`):
+ The logits output vector of the model representing the log probabilities for each token.
+ beam_width (`int`, *optional*):
+ Maximum number of beams at each step in decoding. Defaults to pyctcdecode's DEFAULT_BEAM_WIDTH.
+ beam_prune_logp (`int`, *optional*):
+ A threshold to prune beams with log-probs less than best_beam_logp + beam_prune_logp. The value should
+ be <= 0. Defaults to pyctcdecode's DEFAULT_PRUNE_LOGP.
+ token_min_logp (`int`, *optional*):
+ Tokens with log-probs below token_min_logp are skipped unless they are have the maximum log-prob for an
+ utterance. Defaults to pyctcdecode's DEFAULT_MIN_TOKEN_LOGP.
+ hotwords (`list[str]`, *optional*):
+ List of words with extra importance which can be missing from the LM's vocabulary, e.g. ["huggingface"]
+ hotword_weight (`int`, *optional*):
+ Weight multiplier that boosts hotword scores. Defaults to pyctcdecode's DEFAULT_HOTWORD_WEIGHT.
+ alpha (`float`, *optional*):
+ Weight for language model during shallow fusion
+ beta (`float`, *optional*):
+ Weight for length score adjustment of during scoring
+ unk_score_offset (`float`, *optional*):
+ Amount of log score offset for unknown tokens
+ lm_score_boundary (`bool`, *optional*):
+ Whether to have kenlm respect boundaries when scoring
+ output_word_offsets (`bool`, *optional*, defaults to `False`):
+ Whether or not to output word offsets. Word offsets can be used in combination with the sampling rate
+ and model downsampling rate to compute the time-stamps of transcribed words.
+ n_best (`int`, *optional*, defaults to `1`):
+ Number of best hypotheses to return. If `n_best` is greater than 1, the returned `text` will be a list
+ of strings, `logit_score` will be a list of floats, and `lm_score` will be a list of floats, where the
+ length of these lists will correspond to the number of returned hypotheses. The value should be >= 1.
+
+
+
+ Please take a look at the example below to better understand how to make use of `output_word_offsets`.
+
+
+
+ Returns:
+ [`~models.wav2vec2.Wav2Vec2DecoderWithLMOutput`].
+
+ Example:
+
+ ```python
+ >>> # Let's see how to retrieve time steps for a model
+ >>> from transformers import AutoTokenizer, AutoProcessor, AutoModelForCTC
+ >>> from datasets import load_dataset
+ >>> import datasets
+ >>> import torch
+
+ >>> # import model, feature extractor, tokenizer
+ >>> model = AutoModelForCTC.from_pretrained("patrickvonplaten/wav2vec2-base-100h-with-lm")
+ >>> processor = AutoProcessor.from_pretrained("patrickvonplaten/wav2vec2-base-100h-with-lm")
+
+ >>> # load first sample of English common_voice
+ >>> dataset = load_dataset("mozilla-foundation/common_voice_11_0", "en", split="train", streaming=True)
+ >>> dataset = dataset.cast_column("audio", datasets.Audio(sampling_rate=16_000))
+ >>> dataset_iter = iter(dataset)
+ >>> sample = next(dataset_iter)
+
+ >>> # forward sample through model to get greedily predicted transcription ids
+ >>> input_values = processor(sample["audio"]["array"], return_tensors="pt").input_values
+ >>> with torch.no_grad():
+ ... logits = model(input_values).logits[0].cpu().numpy()
+
+ >>> # retrieve word stamps (analogous commands for `output_char_offsets`)
+ >>> outputs = processor.decode(logits, output_word_offsets=True)
+ >>> # compute `time_offset` in seconds as product of downsampling ratio and sampling_rate
+ >>> time_offset = model.config.inputs_to_logits_ratio / processor.feature_extractor.sampling_rate
+
+ >>> word_offsets = [
+ ... {
+ ... "word": d["word"],
+ ... "start_time": round(d["start_offset"] * time_offset, 2),
+ ... "end_time": round(d["end_offset"] * time_offset, 2),
+ ... }
+ ... for d in outputs.word_offsets
+ ... ]
+ >>> # compare word offsets with audio `en_train_0/common_voice_en_19121553.mp3` online on the dataset viewer:
+ >>> # https://huggingface.co/datasets/mozilla-foundation/common_voice_11_0/viewer/en
+ >>> word_offsets[:4]
+ [{'word': 'THE', 'start_time': 0.68, 'end_time': 0.78}, {'word': 'TRACK', 'start_time': 0.88, 'end_time': 1.1}, {'word': 'APPEARS', 'start_time': 1.18, 'end_time': 1.66}, {'word': 'ON', 'start_time': 1.86, 'end_time': 1.92}]
+ ```"""
+
+ from pyctcdecode.constants import (
+ DEFAULT_BEAM_WIDTH,
+ DEFAULT_HOTWORD_WEIGHT,
+ DEFAULT_MIN_TOKEN_LOGP,
+ DEFAULT_PRUNE_LOGP,
+ )
+
+ # set defaults
+ beam_width = beam_width if beam_width is not None else DEFAULT_BEAM_WIDTH
+ beam_prune_logp = beam_prune_logp if beam_prune_logp is not None else DEFAULT_PRUNE_LOGP
+ token_min_logp = token_min_logp if token_min_logp is not None else DEFAULT_MIN_TOKEN_LOGP
+ hotword_weight = hotword_weight if hotword_weight is not None else DEFAULT_HOTWORD_WEIGHT
+
+ # reset params at every forward call. It's just a `set` method in pyctcdecode
+ self.decoder.reset_params(
+ alpha=alpha, beta=beta, unk_score_offset=unk_score_offset, lm_score_boundary=lm_score_boundary
+ )
+
+ # pyctcdecode
+ decoded_beams = self.decoder.decode_beams(
+ logits,
+ beam_width=beam_width,
+ beam_prune_logp=beam_prune_logp,
+ token_min_logp=token_min_logp,
+ hotwords=hotwords,
+ hotword_weight=hotword_weight,
+ )
+
+ word_offsets = None
+ if output_word_offsets:
+ word_offsets = [
+ [
+ {"word": word, "start_offset": start_offset, "end_offset": end_offset}
+ for word, (start_offset, end_offset) in beam[2]
+ ]
+ for beam in decoded_beams
+ ]
+ logit_scores = [beam[-2] for beam in decoded_beams]
+
+ lm_scores = [beam[-1] for beam in decoded_beams]
+
+ hypotheses = [beam[0] for beam in decoded_beams]
+
+ if n_best > len(decoded_beams):
+ logger.info(
+ "N-best size is larger than the number of generated hypotheses, all hypotheses will be returned."
+ )
+
+ if n_best == 1:
+ return Wav2Vec2DecoderWithLMOutput(
+ text=hypotheses[0],
+ logit_score=logit_scores[0],
+ lm_score=lm_scores[0],
+ word_offsets=word_offsets[0] if word_offsets is not None else None,
+ )
+ else:
+ return Wav2Vec2DecoderWithLMOutput(
+ text=hypotheses[:n_best],
+ logit_score=logit_scores[:n_best],
+ lm_score=lm_scores[:n_best],
+ word_offsets=word_offsets[:n_best] if word_offsets is not None else None,
+ )
+
+
+__all__ = ["Wav2Vec2ProcessorWithLM"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wavlm/__init__.py b/.venv/lib/python3.12/site-packages/transformers/models/wavlm/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d230bf3f0924b436e1b9cd9ea509a989cf5bdb8b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/wavlm/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_wavlm import *
+ from .modeling_wavlm import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wavlm/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/wavlm/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..18d95f89bfa537f5dcbb1a05843587f220ee6182
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/wavlm/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wavlm/__pycache__/configuration_wavlm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/wavlm/__pycache__/configuration_wavlm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4d7d8b5d993d7dec6c27fdbfab286c67f5915ea9
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/wavlm/__pycache__/configuration_wavlm.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wavlm/__pycache__/modeling_wavlm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/wavlm/__pycache__/modeling_wavlm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..068ed50c491c620ae2879ea2a6b600365cad2df4
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/wavlm/__pycache__/modeling_wavlm.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wavlm/__pycache__/modular_wavlm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/wavlm/__pycache__/modular_wavlm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c1d950cbe9f443a7f180dc99634fa7c71a4e27ab
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/wavlm/__pycache__/modular_wavlm.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wavlm/configuration_wavlm.py b/.venv/lib/python3.12/site-packages/transformers/models/wavlm/configuration_wavlm.py
new file mode 100644
index 0000000000000000000000000000000000000000..a8f2aef31aa8aa782b565d7e3ddf9c0e1cc1be6f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/wavlm/configuration_wavlm.py
@@ -0,0 +1,239 @@
+# Copyright 2021 The Fairseq Authors, Microsoft Research, and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""WavLM model configuration"""
+
+import functools
+import operator
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="microsoft/wavlm-base")
+@strict
+class WavLMConfig(PreTrainedConfig):
+ r"""
+ feat_proj_dropout (`float`, *optional*, defaults to 0.0):
+ The dropout probability for output of the feature encoder.
+ final_dropout (`float`, *optional*, defaults to 0.1):
+ The dropout probability for the final projection layer of [`WavLMForCTC`].
+ feat_extract_norm (`str`, *optional*, defaults to `"group"`):
+ The norm to be applied to 1D convolutional layers in feature encoder. One of `"group"` for group
+ normalization of only the first 1D convolutional layer or `"layer"` for layer normalization of all 1D
+ convolutional layers.
+ feat_extract_activation (`str, `optional`, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the 1D convolutional layers of the feature
+ extractor. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` are supported.
+ conv_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 512, 512, 512)`):
+ A tuple of integers defining the number of input and output channels of each 1D convolutional layer in the
+ feature encoder. The length of *conv_dim* defines the number of 1D convolutional layers.
+ conv_stride (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 2, 2, 2, 2, 2, 2)`):
+ A tuple of integers defining the stride of each 1D convolutional layer in the feature encoder. The length
+ of *conv_stride* defines the number of convolutional layers and has to match the length of *conv_dim*.
+ conv_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(10, 3, 3, 3, 3, 3, 3)`):
+ A tuple of integers defining the kernel size of each 1D convolutional layer in the feature encoder. The
+ length of *conv_kernel* defines the number of convolutional layers and has to match the length of
+ *conv_dim*.
+ conv_bias (`bool`, *optional*, defaults to `False`):
+ Whether the 1D convolutional layers have a bias.
+ num_conv_pos_embeddings (`int`, *optional*, defaults to 128):
+ Number of convolutional positional embeddings. Defines the kernel size of 1D convolutional positional
+ embeddings layer.
+ num_conv_pos_embedding_groups (`int`, *optional*, defaults to 16):
+ Number of groups of 1D convolutional positional embeddings layer.
+ num_buckets (`int`, *optional*, defaults to 320):
+ The number of buckets to use for each attention layer
+ max_bucket_distance (`int`, *optional*, defaults to 800):
+ Maximum bucket distance
+ do_stable_layer_norm (`bool`, *optional*, defaults to `False`):
+ Whether to apply *stable* layer norm architecture of the Transformer encoder. `do_stable_layer_norm is
+ True` corresponds to applying layer norm before the attention layer, whereas `do_stable_layer_norm is
+ False` corresponds to applying layer norm after the attention layer.
+ apply_spec_augment (`bool`, *optional*, defaults to `True`):
+ Whether to apply *SpecAugment* data augmentation to the outputs of the feature encoder. For reference see
+ [SpecAugment: A Simple Data Augmentation Method for Automatic Speech
+ Recognition](https://huggingface.co/papers/1904.08779).
+ mask_time_prob (`float`, *optional*, defaults to 0.05):
+ Probability of each feature vector along the time axis to be chosen as the start of the vector span to be
+ masked. Approximately `mask_time_prob * sequence_length // mask_time_length` feature vectors will be masked
+ along the time axis. This is only relevant if `apply_spec_augment is True`.
+ mask_time_length (`int`, *optional*, defaults to 10):
+ Length of vector span along the time axis.
+ mask_time_min_masks (`int`, *optional*, defaults to 2),:
+ The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
+ irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <
+ mask_time_min_masks''
+ mask_feature_prob (`float`, *optional*, defaults to 0.0):
+ Probability of each feature vector along the feature axis to be chosen as the start of the vector span to
+ be masked. Approximately `mask_time_prob * hidden_size // mask_time_length` feature vectors will be masked
+ along the time axis. This is only relevant if `apply_spec_augment is True`.
+ mask_feature_length (`int`, *optional*, defaults to 10):
+ Length of vector span along the feature axis.
+ num_codevectors_per_group (`int`, *optional*, defaults to 320):
+ Number of entries in each quantization codebook (group).
+ num_codevector_groups (`int`, *optional*, defaults to 2):
+ Number of codevector groups for product codevector quantization.
+ contrastive_logits_temperature (`float`, *optional*, defaults to 0.1):
+ The temperature *kappa* in the contrastive loss.
+ num_negatives (`int`, *optional*, defaults to 100):
+ Number of negative samples for the contrastive loss.
+ codevector_dim (`int`, *optional*, defaults to 256):
+ Dimensionality of the quantized feature vectors.
+ proj_codevector_dim (`int`, *optional*, defaults to 256):
+ Dimensionality of the final projection of both the quantized and the transformer features.
+ diversity_loss_weight (`int`, *optional*, defaults to 0.1):
+ The weight of the codebook diversity loss component.
+ ctc_zero_infinity (`bool`, *optional*, defaults to `False`):
+ Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly
+ occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance
+ of [`WavLMForCTC`].
+ use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):
+ Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an
+ instance of [`WavLMForSequenceClassification`].
+ classifier_proj_size (`int`, *optional*, defaults to 256):
+ Dimensionality of the projection before token mean-pooling for classification.
+ tdnn_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 1500)`):
+ A tuple of integers defining the number of output channels of each 1D convolutional layer in the *TDNN*
+ module of the *XVector* model. The length of *tdnn_dim* defines the number of *TDNN* layers.
+ tdnn_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 3, 3, 1, 1)`):
+ A tuple of integers defining the kernel size of each 1D convolutional layer in the *TDNN* module of the
+ *XVector* model. The length of *tdnn_kernel* has to match the length of *tdnn_dim*.
+ tdnn_dilation (`tuple[int]` or `list[int]`, *optional*, defaults to `(1, 2, 3, 1, 1)`):
+ A tuple of integers defining the dilation factor of each 1D convolutional layer in *TDNN* module of the
+ *XVector* model. The length of *tdnn_dilation* has to match the length of *tdnn_dim*.
+ xvector_output_dim (`int`, *optional*, defaults to 512):
+ Dimensionality of the *XVector* embedding vectors.
+ num_ctc_classes (`int`, *optional*, defaults to 80):
+ Specifies the number of classes (phoneme tokens and blank token) for phoneme-level CTC loss. Only relevant
+ when using an instance of [`UniSpeechForPreTraining`].
+ add_adapter (`bool`, *optional*, defaults to `False`):
+ Whether a convolutional network should be stacked on top of the Wav2Vec2 Encoder. Can be very useful for
+ warm-starting Wav2Vec2 for SpeechEncoderDecoder models.
+ adapter_kernel_size (`int`, *optional*, defaults to 3):
+ Kernel size of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.
+ adapter_stride (`int`, *optional*, defaults to 2):
+ Stride of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.
+ num_adapter_layers (`int`, *optional*, defaults to 3):
+ Number of convolutional layers that should be used in the adapter network. Only relevant if `add_adapter is
+ True`.
+ output_hidden_size (`int`, *optional*):
+ Dimensionality of the encoder output layer. If not defined, this defaults to *hidden-size*. Only relevant
+ if `add_adapter is True`.
+
+ Example:
+
+ ```python
+
+ ```
+
+ Example:
+
+ ```python
+ >>> from transformers import WavLMConfig, WavLMModel
+
+ >>> # Initializing a WavLM facebook/wavlm-base-960h style configuration
+ >>> configuration = WavLMConfig()
+
+ >>> # Initializing a model (with random weights) from the facebook/wavlm-base-960h style configuration
+ >>> model = WavLMModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "wavlm"
+
+ vocab_size: int = 32
+ hidden_size: int = 768
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ intermediate_size: int = 3072
+ hidden_act: str = "gelu"
+ hidden_dropout: float | int = 0.1
+ activation_dropout: float | int = 0.1
+ attention_dropout: float | int = 0.1
+ feat_proj_dropout: float | int = 0.0
+ final_dropout: float | int = 0.1
+ layerdrop: float | int = 0.1
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-5
+ feat_extract_norm: str = "group"
+ feat_extract_activation: str = "gelu"
+ conv_dim: list[int] | tuple[int, ...] = (512, 512, 512, 512, 512, 512, 512)
+ conv_stride: list[int] | tuple[int, ...] = (5, 2, 2, 2, 2, 2, 2)
+ conv_kernel: list[int] | tuple[int, ...] = (10, 3, 3, 3, 3, 2, 2)
+ conv_bias: bool = False
+ num_conv_pos_embeddings: int = 128
+ num_conv_pos_embedding_groups: int = 16
+ num_buckets: int = 320
+ max_bucket_distance: int = 800
+ do_stable_layer_norm: bool = False
+ apply_spec_augment: bool = True
+ mask_time_prob: float | int = 0.05
+ mask_time_length: int = 10
+ mask_time_min_masks: int = 2
+ mask_feature_prob: float | int = 0.0
+ mask_feature_length: int = 10
+ num_codevectors_per_group: int = 320
+ num_codevector_groups: int = 2
+ contrastive_logits_temperature: float = 0.1
+ num_negatives: int = 100
+ codevector_dim: int = 256
+ proj_codevector_dim: int = 256
+ diversity_loss_weight: float = 0.1
+ ctc_loss_reduction: str = "mean"
+ ctc_zero_infinity: bool = False
+ use_weighted_layer_sum: bool = False
+ classifier_proj_size: int = 256
+ tdnn_dim: list[int] | tuple[int, ...] = (512, 512, 512, 512, 1500)
+ tdnn_kernel: list[int] | tuple[int, ...] = (5, 3, 3, 1, 1)
+ tdnn_dilation: list[int] | tuple[int, ...] = (1, 2, 3, 1, 1)
+ xvector_output_dim: int = 512
+ num_ctc_classes: int = 80
+ pad_token_id: int | None = 0
+ bos_token_id: int | None = 1
+ eos_token_id: int | list[int] | None = 2
+ add_adapter: bool = False
+ adapter_kernel_size: int = 3
+ adapter_stride: int = 2
+ num_adapter_layers: int = 3
+ output_hidden_size: int | None = None
+
+ def __post_init__(self, **kwargs):
+ self.num_feat_extract_layers = len(self.conv_dim)
+ self.output_hidden_size = self.output_hidden_size or self.hidden_size
+ super().__post_init__(**kwargs)
+
+ def validate_architecture(self):
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
+ if (
+ (len(self.conv_stride) != self.num_feat_extract_layers)
+ or (len(self.conv_kernel) != self.num_feat_extract_layers)
+ or (len(self.conv_dim) != self.num_feat_extract_layers)
+ ):
+ raise ValueError(
+ "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
+ " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
+ f" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,"
+ f" `len(config.conv_kernel) = {len(self.conv_kernel)}`."
+ )
+
+ @property
+ def inputs_to_logits_ratio(self):
+ return functools.reduce(operator.mul, self.conv_stride, 1)
+
+
+__all__ = ["WavLMConfig"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wavlm/modeling_wavlm.py b/.venv/lib/python3.12/site-packages/transformers/models/wavlm/modeling_wavlm.py
new file mode 100644
index 0000000000000000000000000000000000000000..18440ebf7d25e6da7237d40add80114747835928
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/wavlm/modeling_wavlm.py
@@ -0,0 +1,1654 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/wavlm/modular_wavlm.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_wavlm.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+import math
+import warnings
+
+import numpy as np
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from torch.nn import CrossEntropyLoss
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...integrations.deepspeed import is_deepspeed_zero3_enabled
+from ...integrations.fsdp import is_fsdp_managed_module
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutput,
+ CausalLMOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+ Wav2Vec2BaseModelOutput,
+ XVectorOutput,
+)
+from ...modeling_utils import PreTrainedModel, get_torch_context_manager_or_global_device
+from ...utils import auto_docstring, is_peft_available, logging
+from .configuration_wavlm import WavLMConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+class WavLMSamePadLayer(nn.Module):
+ def __init__(self, num_conv_pos_embeddings):
+ super().__init__()
+ self.num_pad_remove = 1 if num_conv_pos_embeddings % 2 == 0 else 0
+
+ def forward(self, hidden_states):
+ if self.num_pad_remove > 0:
+ hidden_states = hidden_states[:, :, : -self.num_pad_remove]
+ return hidden_states
+
+
+class WavLMPositionalConvEmbedding(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.conv = nn.Conv1d(
+ config.hidden_size,
+ config.hidden_size,
+ kernel_size=config.num_conv_pos_embeddings,
+ padding=config.num_conv_pos_embeddings // 2,
+ groups=config.num_conv_pos_embedding_groups,
+ )
+
+ weight_norm = nn.utils.weight_norm
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
+ weight_norm = nn.utils.parametrizations.weight_norm
+
+ if is_deepspeed_zero3_enabled():
+ import deepspeed
+
+ with deepspeed.zero.GatheredParameters(self.conv.weight, modifier_rank=0):
+ self.conv = weight_norm(self.conv, name="weight", dim=2)
+ if hasattr(self.conv, "parametrizations"):
+ weight_g = self.conv.parametrizations.weight.original0
+ weight_v = self.conv.parametrizations.weight.original1
+ else:
+ weight_g = self.conv.weight_g
+ weight_v = self.conv.weight_v
+ deepspeed.zero.register_external_parameter(self, weight_v)
+ deepspeed.zero.register_external_parameter(self, weight_g)
+ else:
+ self.conv = weight_norm(self.conv, name="weight", dim=2)
+
+ self.padding = WavLMSamePadLayer(config.num_conv_pos_embeddings)
+ self.activation = ACT2FN[config.feat_extract_activation]
+
+ def forward(self, hidden_states):
+ hidden_states = hidden_states.transpose(1, 2)
+
+ hidden_states = self.conv(hidden_states)
+ hidden_states = self.padding(hidden_states)
+ hidden_states = self.activation(hidden_states)
+
+ hidden_states = hidden_states.transpose(1, 2)
+ return hidden_states
+
+
+class WavLMFeatureProjection(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.layer_norm_eps)
+ self.projection = nn.Linear(config.conv_dim[-1], config.hidden_size)
+ self.dropout = nn.Dropout(config.feat_proj_dropout)
+
+ def forward(self, hidden_states):
+ # non-projected hidden states are needed for quantization
+ norm_hidden_states = self.layer_norm(hidden_states)
+ hidden_states = self.projection(norm_hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ return hidden_states, norm_hidden_states
+
+
+class WavLMAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(
+ self,
+ embed_dim: int,
+ num_heads: int,
+ dropout: float | int = 0.0,
+ num_buckets: int = 320,
+ max_distance: int = 800,
+ has_relative_position_bias: bool = True,
+ ):
+ super().__init__()
+ self.embed_dim = embed_dim
+ self.num_heads = num_heads
+ self.dropout = dropout
+ self.head_dim = embed_dim // num_heads
+
+ if (self.head_dim * num_heads) != self.embed_dim:
+ raise ValueError(
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
+ f" and `num_heads`: {num_heads})."
+ )
+ self.scaling = self.head_dim**-0.5
+
+ self.k_proj = nn.Linear(embed_dim, embed_dim)
+ self.v_proj = nn.Linear(embed_dim, embed_dim)
+ self.q_proj = nn.Linear(embed_dim, embed_dim)
+ self.out_proj = nn.Linear(embed_dim, embed_dim)
+
+ self.num_buckets = num_buckets
+ self.max_distance = max_distance
+
+ self.gru_rel_pos_const = nn.Parameter(torch.ones(1, self.num_heads, 1, 1))
+ self.gru_rel_pos_linear = nn.Linear(self.head_dim, 8)
+
+ if has_relative_position_bias:
+ self.rel_attn_embed = nn.Embedding(self.num_buckets, self.num_heads)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_bias: torch.Tensor | None = None,
+ output_attentions: bool = False,
+ index=0,
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
+ """Attention layer with relative attention"""
+ bsz, tgt_len, _ = hidden_states.size()
+
+ # first pass of attention layer creates position bias
+ if position_bias is None:
+ position_bias = self.compute_bias(tgt_len, tgt_len)
+ position_bias = (
+ position_bias.unsqueeze(0).repeat(bsz, 1, 1, 1).view(bsz * self.num_heads, tgt_len, tgt_len)
+ )
+
+ # Compute relative position bias:
+ # 1) get reshape hidden_states
+ gated_hidden_states = hidden_states.view(hidden_states.shape[:-1] + (self.num_heads, -1))
+ gated_hidden_states = gated_hidden_states.permute(0, 2, 1, 3)
+
+ # 2) project hidden states
+ relative_position_proj = self.gru_rel_pos_linear(gated_hidden_states)
+ relative_position_proj = relative_position_proj.view(gated_hidden_states.shape[:-1] + (2, 4)).sum(-1)
+
+ # 3) compute gate for position bias from projected hidden states
+ gate_a, gate_b = torch.sigmoid(relative_position_proj).chunk(2, dim=-1)
+ gate_output = gate_a * (gate_b * self.gru_rel_pos_const - 1.0) + 2.0
+
+ # 4) apply gate to position bias to compute gated position_bias
+ gated_position_bias = gate_output.view(bsz * self.num_heads, -1, 1) * position_bias
+ gated_position_bias = gated_position_bias.view((-1, tgt_len, tgt_len))
+
+ attn_output, attn_weights = self.torch_multi_head_self_attention(
+ hidden_states, attention_mask, gated_position_bias, output_attentions
+ )
+
+ return attn_output, attn_weights, position_bias
+
+ def torch_multi_head_self_attention(
+ self,
+ hidden_states: torch.FloatTensor,
+ attention_mask: torch.LongTensor | torch.BoolTensor,
+ gated_position_bias: torch.FloatTensor,
+ output_attentions: bool,
+ ) -> tuple[torch.FloatTensor, torch.FloatTensor]:
+ """simple wrapper around torch's multi_head_attention_forward function"""
+ # self-attention assumes q = k = v
+ query = key = value = hidden_states.transpose(0, 1)
+ key_padding_mask = attention_mask.ne(1) if attention_mask is not None else None
+
+ # disable bias and add_zero_attn
+ bias_k = bias_v = None
+ add_zero_attn = False
+
+ # PyTorch 1.3.0 has F.multi_head_attention_forward defined
+ # so no problem with backwards compatibility
+ attn_output, attn_weights = F.multi_head_attention_forward(
+ query,
+ key,
+ value,
+ self.embed_dim,
+ self.num_heads,
+ torch.empty([0]),
+ torch.cat((self.q_proj.bias, self.k_proj.bias, self.v_proj.bias)),
+ bias_k,
+ bias_v,
+ add_zero_attn,
+ self.dropout,
+ self.out_proj.weight,
+ self.out_proj.bias,
+ self.training,
+ key_padding_mask,
+ output_attentions,
+ gated_position_bias,
+ use_separate_proj_weight=True,
+ q_proj_weight=self.q_proj.weight,
+ k_proj_weight=self.k_proj.weight,
+ v_proj_weight=self.v_proj.weight,
+ )
+
+ # [Seq_Len, Batch Size, ...] -> [Batch Size, Seq_Len, ...]
+ attn_output = attn_output.transpose(0, 1)
+
+ if attn_weights is not None:
+ # IMPORTANT: Attention weights are averaged weights
+ # here which should not be the case. This is an open issue
+ # on PyTorch: https://github.com/pytorch/pytorch/issues/32590
+ attn_weights = attn_weights[:, None].broadcast_to(
+ attn_weights.shape[:1] + (self.num_heads,) + attn_weights.shape[1:]
+ )
+
+ return attn_output, attn_weights
+
+ def compute_bias(self, query_length: int, key_length: int) -> torch.FloatTensor:
+ context_position = torch.arange(query_length, dtype=torch.long)[:, None]
+ memory_position = torch.arange(key_length, dtype=torch.long)[None, :]
+ relative_position = memory_position - context_position
+ relative_position_bucket = self._relative_positions_bucket(relative_position)
+ relative_position_bucket = relative_position_bucket.to(self.rel_attn_embed.weight.device)
+ values = self.rel_attn_embed(relative_position_bucket)
+ values = values.permute([2, 0, 1])
+ return values
+
+ def _relative_positions_bucket(self, relative_positions: torch.FloatTensor) -> torch.FloatTensor:
+ num_buckets = self.num_buckets // 2
+
+ relative_buckets = (relative_positions > 0).to(torch.long) * num_buckets
+ relative_positions = torch.abs(relative_positions)
+
+ max_exact = num_buckets // 2
+ is_small = relative_positions < max_exact
+
+ relative_positions_if_large = torch.log(relative_positions.float() / max_exact)
+ relative_positions_if_large = relative_positions_if_large / math.log(self.max_distance / max_exact)
+ relative_positions_if_large = relative_positions_if_large * (num_buckets - max_exact)
+ relative_position_if_large = (max_exact + relative_positions_if_large).to(torch.long)
+ relative_position_if_large = torch.min(
+ relative_position_if_large, torch.full_like(relative_position_if_large, num_buckets - 1)
+ )
+
+ relative_buckets += torch.where(is_small, relative_positions, relative_position_if_large)
+ return relative_buckets
+
+
+class WavLMFeedForward(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.intermediate_dropout = nn.Dropout(config.activation_dropout)
+
+ self.intermediate_dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ self.output_dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.output_dropout = nn.Dropout(config.hidden_dropout)
+
+ def forward(self, hidden_states):
+ hidden_states = self.intermediate_dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ hidden_states = self.intermediate_dropout(hidden_states)
+
+ hidden_states = self.output_dense(hidden_states)
+ hidden_states = self.output_dropout(hidden_states)
+ return hidden_states
+
+
+class WavLMEncoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: WavLMConfig, has_relative_position_bias: bool = True):
+ super().__init__()
+ self.attention = WavLMAttention(
+ embed_dim=config.hidden_size,
+ num_heads=config.num_attention_heads,
+ dropout=config.attention_dropout,
+ num_buckets=config.num_buckets,
+ max_distance=config.max_bucket_distance,
+ has_relative_position_bias=has_relative_position_bias,
+ )
+ self.dropout = nn.Dropout(config.hidden_dropout)
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.feed_forward = WavLMFeedForward(config)
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(self, hidden_states, attention_mask=None, position_bias=None, output_attentions=False, index=0):
+ attn_residual = hidden_states
+ hidden_states, attn_weights, position_bias = self.attention(
+ hidden_states,
+ attention_mask=attention_mask,
+ position_bias=position_bias,
+ output_attentions=output_attentions,
+ index=index,
+ )
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = attn_residual + hidden_states
+
+ hidden_states = self.layer_norm(hidden_states)
+
+ hidden_states = hidden_states + self.feed_forward(hidden_states)
+ hidden_states = self.final_layer_norm(hidden_states)
+
+ outputs = (hidden_states, position_bias)
+
+ if output_attentions:
+ outputs += (attn_weights,)
+
+ return outputs
+
+
+class WavLMEncoderLayerStableLayerNorm(GradientCheckpointingLayer):
+ def __init__(self, config: WavLMConfig, has_relative_position_bias: bool = True):
+ super().__init__()
+ self.attention = WavLMAttention(
+ embed_dim=config.hidden_size,
+ num_heads=config.num_attention_heads,
+ dropout=config.attention_dropout,
+ num_buckets=config.num_buckets,
+ max_distance=config.max_bucket_distance,
+ has_relative_position_bias=has_relative_position_bias,
+ )
+ self.dropout = nn.Dropout(config.hidden_dropout)
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.feed_forward = WavLMFeedForward(config)
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(self, hidden_states, attention_mask=None, position_bias=None, output_attentions=False):
+ attn_residual = hidden_states
+ hidden_states = self.layer_norm(hidden_states)
+ hidden_states, attn_weights, position_bias = self.attention(
+ hidden_states,
+ attention_mask=attention_mask,
+ position_bias=position_bias,
+ output_attentions=output_attentions,
+ )
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = attn_residual + hidden_states
+ hidden_states = hidden_states + self.feed_forward(self.final_layer_norm(hidden_states))
+
+ outputs = (hidden_states, position_bias)
+
+ if output_attentions:
+ outputs += (attn_weights,)
+
+ return outputs
+
+
+class WavLMEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.pos_conv_embed = WavLMPositionalConvEmbedding(config)
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout)
+ self.layers = nn.ModuleList(
+ [WavLMEncoderLayer(config, has_relative_position_bias=(i == 0)) for i in range(config.num_hidden_layers)]
+ )
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ output_attentions=False,
+ output_hidden_states=False,
+ return_dict=True,
+ ):
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+
+ if attention_mask is not None:
+ # make sure padded tokens output 0
+ expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
+ hidden_states[~expand_attention_mask] = 0
+
+ position_embeddings = self.pos_conv_embed(hidden_states)
+ hidden_states = hidden_states + position_embeddings
+ hidden_states = self.layer_norm(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
+ position_bias = None
+
+ for i, layer in enumerate(self.layers):
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
+ dropout_probability = torch.rand([])
+
+ skip_the_layer = self.training and i > 0 and (dropout_probability < self.config.layerdrop)
+ if not skip_the_layer or synced_gpus:
+ # under fsdp or deepspeed zero3 all gpus must run in sync
+ layer_outputs = layer(
+ hidden_states,
+ attention_mask=attention_mask,
+ position_bias=position_bias,
+ output_attentions=output_attentions,
+ index=i,
+ )
+
+ hidden_states, position_bias = layer_outputs[:2]
+
+ if skip_the_layer:
+ layer_outputs = (None, None, None)
+
+ if output_attentions:
+ all_self_attentions = all_self_attentions + (layer_outputs[2],)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
+ return BaseModelOutput(
+ last_hidden_state=hidden_states,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ )
+
+
+class WavLMEncoderStableLayerNorm(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.pos_conv_embed = WavLMPositionalConvEmbedding(config)
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout)
+ self.layers = nn.ModuleList(
+ [
+ WavLMEncoderLayerStableLayerNorm(config, has_relative_position_bias=(i == 0))
+ for i in range(config.num_hidden_layers)
+ ]
+ )
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ output_attentions=False,
+ output_hidden_states=False,
+ return_dict=True,
+ ):
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+
+ if attention_mask is not None:
+ # make sure padded tokens are not attended to
+ expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
+ hidden_states[~expand_attention_mask] = 0
+
+ position_embeddings = self.pos_conv_embed(hidden_states)
+ hidden_states = hidden_states + position_embeddings
+ hidden_states = self.dropout(hidden_states)
+
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
+ position_bias = None
+
+ for i, layer in enumerate(self.layers):
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
+ dropout_probability = torch.rand([])
+
+ skip_the_layer = self.training and i > 0 and (dropout_probability < self.config.layerdrop)
+ if not skip_the_layer or synced_gpus:
+ # under fsdp or deepspeed zero3 all gpus must run in sync
+ # XXX: could optimize this like synced_gpus in generate_utils but not sure if it's worth the code complication
+ layer_outputs = layer(
+ hidden_states,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ position_bias=position_bias,
+ )
+ hidden_states, position_bias = layer_outputs[:2]
+
+ if skip_the_layer:
+ layer_outputs = (None, None, None)
+
+ if output_attentions:
+ all_self_attentions = all_self_attentions + (layer_outputs[2],)
+
+ hidden_states = self.layer_norm(hidden_states)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
+ return BaseModelOutput(
+ last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_self_attentions
+ )
+
+
+class WavLMGumbelVectorQuantizer(nn.Module):
+ """
+ Vector quantization using gumbel softmax. See [CATEGORICAL REPARAMETERIZATION WITH
+ GUMBEL-SOFTMAX](https://huggingface.co/papers/1611.01144) for more information.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ self.num_groups = config.num_codevector_groups
+ self.num_vars = config.num_codevectors_per_group
+
+ if config.codevector_dim % self.num_groups != 0:
+ raise ValueError(
+ f"`config.codevector_dim {config.codevector_dim} must be divisible"
+ f" by `config.num_codevector_groups` {self.num_groups} "
+ "for concatenation."
+ )
+
+ # storage for codebook variables (codewords)
+ self.codevectors = nn.Parameter(
+ torch.FloatTensor(1, self.num_groups * self.num_vars, config.codevector_dim // self.num_groups)
+ )
+ self.weight_proj = nn.Linear(config.conv_dim[-1], self.num_groups * self.num_vars)
+
+ # can be decayed for training
+ self.temperature = 2
+
+ @staticmethod
+ def _compute_perplexity(probs):
+ marginal_probs = probs.mean(dim=0)
+ perplexity = torch.exp(-torch.sum(torch.xlogy(marginal_probs, marginal_probs), dim=-1)).sum()
+ return perplexity
+
+ def forward(self, hidden_states):
+ batch_size, sequence_length, hidden_size = hidden_states.shape
+
+ # project to codevector dim
+ hidden_states = self.weight_proj(hidden_states)
+ hidden_states = hidden_states.view(batch_size * sequence_length * self.num_groups, -1)
+
+ if self.training:
+ # sample code vector probs via gumbel in differentiateable way
+ codevector_probs = nn.functional.gumbel_softmax(hidden_states.float(), tau=self.temperature, hard=True)
+ codevector_probs = codevector_probs.type_as(hidden_states)
+
+ # compute perplexity
+ codevector_soft_dist = torch.softmax(
+ hidden_states.view(batch_size * sequence_length, self.num_groups, -1).float(), dim=-1
+ )
+ perplexity = self._compute_perplexity(codevector_soft_dist)
+ else:
+ # take argmax in non-differentiable way
+ # comptute hard codevector distribution (one hot)
+ codevector_idx = hidden_states.argmax(dim=-1)
+ codevector_probs = hidden_states.new_zeros(*hidden_states.shape).scatter_(
+ -1, codevector_idx.view(-1, 1), 1.0
+ )
+ codevector_probs = codevector_probs.view(batch_size * sequence_length, self.num_groups, -1)
+
+ perplexity = self._compute_perplexity(codevector_probs)
+
+ codevector_probs = codevector_probs.view(batch_size * sequence_length, -1)
+ # use probs to retrieve codevectors
+ codevectors_per_group = codevector_probs.unsqueeze(-1) * self.codevectors
+ codevectors = codevectors_per_group.view(batch_size * sequence_length, self.num_groups, self.num_vars, -1)
+ codevectors = codevectors.sum(-2).view(batch_size, sequence_length, -1)
+
+ return codevectors, perplexity
+
+
+@auto_docstring
+class WavLMPreTrainedModel(PreTrainedModel):
+ config: WavLMConfig
+ base_model_prefix = "wavlm"
+ main_input_name = "input_values"
+ input_modalities = "audio"
+ supports_gradient_checkpointing = True
+ _supports_flash_attn = False
+ _supports_sdpa = False
+ _supports_flex_attn = False
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ # gumbel softmax requires special init
+ if isinstance(module, WavLMGumbelVectorQuantizer):
+ init.normal_(module.weight_proj.weight, mean=0.0, std=1)
+ init.zeros_(module.weight_proj.bias)
+ init.uniform_(module.codevectors)
+ elif isinstance(module, WavLMPositionalConvEmbedding):
+ init.normal_(
+ module.conv.weight,
+ mean=0,
+ std=2 * math.sqrt(1 / (module.conv.kernel_size[0] * module.conv.in_channels)),
+ )
+ init.constant_(module.conv.bias, 0)
+ elif isinstance(module, WavLMFeatureProjection):
+ k = math.sqrt(1 / module.projection.in_features)
+ init.uniform_(module.projection.weight, a=-k, b=k)
+ init.uniform_(module.projection.bias, a=-k, b=k)
+ elif isinstance(module, nn.Linear):
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
+
+ if module.bias is not None:
+ init.zeros_(module.bias)
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
+ init.zeros_(module.bias)
+ init.ones_(module.weight)
+ elif isinstance(module, nn.Conv1d):
+ init.kaiming_normal_(module.weight)
+
+ if module.bias is not None:
+ k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
+ init.uniform_(module.bias, a=-k, b=k)
+
+ def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor | int, add_adapter: bool | None = None):
+ """
+ Computes the output length of the convolutional layers
+ """
+
+ add_adapter = self.config.add_adapter if add_adapter is None else add_adapter
+
+ def _conv_out_length(input_length, kernel_size, stride):
+ # 1D convolutional layer output length formula taken
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
+ return torch.div(input_length - kernel_size, stride, rounding_mode="floor") + 1
+
+ for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
+ input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
+
+ if add_adapter:
+ for _ in range(self.config.num_adapter_layers):
+ input_lengths = _conv_out_length(input_lengths, 1, self.config.adapter_stride)
+
+ return input_lengths
+
+ def _get_feature_vector_attention_mask(
+ self, feature_vector_length: int, attention_mask: torch.LongTensor, add_adapter=None
+ ):
+ # Effectively attention_mask.sum(-1), but not inplace to be able to run
+ # on inference mode.
+ non_padded_lengths = attention_mask.cumsum(dim=-1)[:, -1]
+
+ output_lengths = self._get_feat_extract_output_lengths(non_padded_lengths, add_adapter=add_adapter)
+ output_lengths = output_lengths.to(torch.long)
+
+ batch_size = attention_mask.shape[0]
+
+ attention_mask = torch.zeros(
+ (batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device
+ )
+ # these two operations makes sure that all values before the output lengths idxs are attended to
+ attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1
+ attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool()
+ return attention_mask
+
+
+class WavLMNoLayerNormConvLayer(GradientCheckpointingLayer):
+ def __init__(self, config, layer_id=0):
+ super().__init__()
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
+ self.out_conv_dim = config.conv_dim[layer_id]
+
+ self.conv = nn.Conv1d(
+ self.in_conv_dim,
+ self.out_conv_dim,
+ kernel_size=config.conv_kernel[layer_id],
+ stride=config.conv_stride[layer_id],
+ bias=config.conv_bias,
+ )
+ self.activation = ACT2FN[config.feat_extract_activation]
+
+ def forward(self, hidden_states):
+ hidden_states = self.conv(hidden_states)
+ hidden_states = self.activation(hidden_states)
+ return hidden_states
+
+
+class WavLMLayerNormConvLayer(GradientCheckpointingLayer):
+ def __init__(self, config, layer_id=0):
+ super().__init__()
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
+ self.out_conv_dim = config.conv_dim[layer_id]
+
+ self.conv = nn.Conv1d(
+ self.in_conv_dim,
+ self.out_conv_dim,
+ kernel_size=config.conv_kernel[layer_id],
+ stride=config.conv_stride[layer_id],
+ bias=config.conv_bias,
+ )
+ self.layer_norm = nn.LayerNorm(self.out_conv_dim, elementwise_affine=True)
+ self.activation = ACT2FN[config.feat_extract_activation]
+
+ def forward(self, hidden_states):
+ hidden_states = self.conv(hidden_states)
+
+ hidden_states = hidden_states.transpose(-2, -1)
+ hidden_states = self.layer_norm(hidden_states)
+ hidden_states = hidden_states.transpose(-2, -1)
+
+ hidden_states = self.activation(hidden_states)
+ return hidden_states
+
+
+class WavLMGroupNormConvLayer(GradientCheckpointingLayer):
+ def __init__(self, config, layer_id=0):
+ super().__init__()
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
+ self.out_conv_dim = config.conv_dim[layer_id]
+
+ self.conv = nn.Conv1d(
+ self.in_conv_dim,
+ self.out_conv_dim,
+ kernel_size=config.conv_kernel[layer_id],
+ stride=config.conv_stride[layer_id],
+ bias=config.conv_bias,
+ )
+ self.activation = ACT2FN[config.feat_extract_activation]
+
+ self.layer_norm = nn.GroupNorm(num_groups=self.out_conv_dim, num_channels=self.out_conv_dim, affine=True)
+
+ def forward(self, hidden_states):
+ hidden_states = self.conv(hidden_states)
+ hidden_states = self.layer_norm(hidden_states)
+ hidden_states = self.activation(hidden_states)
+ return hidden_states
+
+
+class WavLMFeatureEncoder(nn.Module):
+ """Construct the features from raw audio waveform"""
+
+ def __init__(self, config):
+ super().__init__()
+
+ if config.feat_extract_norm == "group":
+ conv_layers = [WavLMGroupNormConvLayer(config, layer_id=0)] + [
+ WavLMNoLayerNormConvLayer(config, layer_id=i + 1) for i in range(config.num_feat_extract_layers - 1)
+ ]
+ elif config.feat_extract_norm == "layer":
+ conv_layers = [WavLMLayerNormConvLayer(config, layer_id=i) for i in range(config.num_feat_extract_layers)]
+ else:
+ raise ValueError(
+ f"`config.feat_extract_norm` is {config.feat_extract_norm}, but has to be one of ['group', 'layer']"
+ )
+ self.conv_layers = nn.ModuleList(conv_layers)
+ self.gradient_checkpointing = False
+ self._requires_grad = True
+
+ def _freeze_parameters(self):
+ for param in self.parameters():
+ param.requires_grad = False
+ self._requires_grad = False
+
+ def forward(self, input_values):
+ hidden_states = input_values[:, None]
+
+ # make sure hidden_states require grad for gradient_checkpointing
+ if self._requires_grad and self.training:
+ hidden_states.requires_grad = True
+
+ for conv_layer in self.conv_layers:
+ hidden_states = conv_layer(hidden_states)
+
+ return hidden_states
+
+
+class WavLMAdapterLayer(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.conv = nn.Conv1d(
+ config.output_hidden_size,
+ 2 * config.output_hidden_size,
+ config.adapter_kernel_size,
+ stride=config.adapter_stride,
+ padding=1,
+ )
+
+ def forward(self, hidden_states):
+ hidden_states = self.conv(hidden_states)
+ hidden_states = nn.functional.glu(hidden_states, dim=1)
+
+ return hidden_states
+
+
+class WavLMAdapter(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+
+ # feature dim might need to be down-projected
+ if config.output_hidden_size != config.hidden_size:
+ self.proj = nn.Linear(config.hidden_size, config.output_hidden_size)
+ self.proj_layer_norm = nn.LayerNorm(config.output_hidden_size)
+ else:
+ self.proj = self.proj_layer_norm = None
+
+ self.layers = nn.ModuleList(WavLMAdapterLayer(config) for _ in range(config.num_adapter_layers))
+ self.layerdrop = config.layerdrop
+
+ def forward(self, hidden_states):
+ # down project hidden_states if necessary
+ if self.proj is not None and self.proj_layer_norm is not None:
+ hidden_states = self.proj(hidden_states)
+ hidden_states = self.proj_layer_norm(hidden_states)
+
+ hidden_states = hidden_states.transpose(1, 2)
+
+ for layer in self.layers:
+ layerdrop_prob = np.random.random()
+ if not self.training or (layerdrop_prob > self.layerdrop):
+ hidden_states = layer(hidden_states)
+
+ hidden_states = hidden_states.transpose(1, 2)
+ return hidden_states
+
+
+def _compute_mask_indices(
+ shape: tuple[int, int],
+ mask_prob: float,
+ mask_length: int,
+ attention_mask: torch.LongTensor | None = None,
+ min_masks: int = 0,
+) -> np.ndarray:
+ """
+ Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for
+ ASR](https://huggingface.co/papers/1904.08779). Note that this method is not optimized to run on TPU and should be run on
+ CPU as part of the preprocessing during training.
+
+ Args:
+ shape: The shape for which to compute masks. This should be of a tuple of size 2 where
+ the first element is the batch size and the second element is the length of the axis to span.
+ mask_prob: The percentage of the whole axis (between 0 and 1) which will be masked. The number of
+ independently generated mask spans of length `mask_length` is computed by
+ `mask_prob*shape[1]/mask_length`. Note that due to overlaps, `mask_prob` is an upper bound and the
+ actual percentage will be smaller.
+ mask_length: size of the mask
+ min_masks: minimum number of masked spans
+ attention_mask: A (right-padded) attention mask which independently shortens the feature axis of
+ each batch dimension.
+ """
+ batch_size, sequence_length = shape
+
+ if mask_length < 1:
+ raise ValueError("`mask_length` has to be bigger than 0.")
+
+ if mask_length > sequence_length:
+ raise ValueError(
+ f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length}"
+ f" and `sequence_length`: {sequence_length}`"
+ )
+
+ # epsilon is used for probabilistic rounding
+ epsilon = np.random.rand(1).item()
+
+ def compute_num_masked_span(input_length):
+ """Given input length, compute how many spans should be masked"""
+ num_masked_span = int(mask_prob * input_length / mask_length + epsilon)
+ num_masked_span = max(num_masked_span, min_masks)
+
+ # make sure num masked span <= sequence_length
+ if num_masked_span * mask_length > sequence_length:
+ num_masked_span = sequence_length // mask_length
+
+ # make sure num_masked span is also <= input_length - (mask_length - 1)
+ if input_length - (mask_length - 1) < num_masked_span:
+ num_masked_span = max(input_length - (mask_length - 1), 0)
+
+ return num_masked_span
+
+ # compute number of masked spans in batch
+ input_lengths = (
+ attention_mask.detach().sum(-1).tolist()
+ if attention_mask is not None
+ else [sequence_length for _ in range(batch_size)]
+ )
+
+ # SpecAugment mask to fill
+ spec_aug_mask = np.zeros((batch_size, sequence_length), dtype=bool)
+ spec_aug_mask_idxs = []
+
+ max_num_masked_span = compute_num_masked_span(sequence_length)
+
+ if max_num_masked_span == 0:
+ return spec_aug_mask
+
+ for input_length in input_lengths:
+ # compute num of masked spans for this input
+ num_masked_span = compute_num_masked_span(input_length)
+
+ # get random indices to mask
+ spec_aug_mask_idx = np.random.choice(
+ np.arange(input_length - (mask_length - 1)), num_masked_span, replace=False
+ )
+
+ # pick first sampled index that will serve as a dummy index to pad vector
+ # to ensure same dimension for all batches due to probabilistic rounding
+ # Picking first sample just pads those vectors twice.
+ if len(spec_aug_mask_idx) == 0:
+ # this case can only happen if `input_length` is strictly smaller then
+ # `sequence_length` in which case the last token has to be a padding
+ # token which we can use as a dummy mask id
+ dummy_mask_idx = sequence_length - 1
+ else:
+ dummy_mask_idx = spec_aug_mask_idx[0]
+
+ spec_aug_mask_idx = np.concatenate(
+ [spec_aug_mask_idx, np.ones(max_num_masked_span - num_masked_span, dtype=np.int32) * dummy_mask_idx]
+ )
+ spec_aug_mask_idxs.append(spec_aug_mask_idx)
+
+ spec_aug_mask_idxs = np.array(spec_aug_mask_idxs)
+
+ # expand masked indices to masked spans
+ spec_aug_mask_idxs = np.broadcast_to(
+ spec_aug_mask_idxs[:, :, None], (batch_size, max_num_masked_span, mask_length)
+ )
+ spec_aug_mask_idxs = spec_aug_mask_idxs.reshape(batch_size, max_num_masked_span * mask_length)
+
+ # add offset to the starting indexes so that indexes now create a span
+ offsets = np.arange(mask_length)[None, None, :]
+ offsets = np.broadcast_to(offsets, (batch_size, max_num_masked_span, mask_length)).reshape(
+ batch_size, max_num_masked_span * mask_length
+ )
+ spec_aug_mask_idxs = spec_aug_mask_idxs + offsets
+
+ # ensure that we cannot have indices larger than sequence_length
+ if spec_aug_mask_idxs.max() > sequence_length - 1:
+ spec_aug_mask_idxs[spec_aug_mask_idxs > sequence_length - 1] = sequence_length - 1
+
+ # scatter indices to mask
+ np.put_along_axis(spec_aug_mask, spec_aug_mask_idxs, 1, -1)
+
+ return spec_aug_mask
+
+
+WavLMBaseModelOutput = Wav2Vec2BaseModelOutput
+
+
+@auto_docstring
+class WavLMModel(WavLMPreTrainedModel):
+ def __init__(self, config: WavLMConfig):
+ super().__init__(config)
+ self.config = config
+ self.feature_extractor = WavLMFeatureEncoder(config)
+ self.feature_projection = WavLMFeatureProjection(config)
+
+ # model only needs masking vector if mask prob is > 0.0
+ if config.mask_time_prob > 0.0 or config.mask_feature_prob > 0.0:
+ self.masked_spec_embed = nn.Parameter(torch.Tensor(config.hidden_size).uniform_())
+
+ if config.do_stable_layer_norm:
+ self.encoder = WavLMEncoderStableLayerNorm(config)
+ else:
+ self.encoder = WavLMEncoder(config)
+
+ self.adapter = WavLMAdapter(config) if config.add_adapter else None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def freeze_feature_encoder(self):
+ """
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
+ not be updated during training.
+ """
+ self.feature_extractor._freeze_parameters()
+
+ def _mask_hidden_states(
+ self,
+ hidden_states: torch.FloatTensor,
+ mask_time_indices: torch.FloatTensor | None = None,
+ attention_mask: torch.LongTensor | None = None,
+ ):
+ """
+ Masks extracted features along time axis and/or along feature axis according to
+ [SpecAugment](https://huggingface.co/papers/1904.08779).
+ """
+
+ # `config.apply_spec_augment` can set masking to False
+ if not getattr(self.config, "apply_spec_augment", True):
+ return hidden_states
+
+ # generate indices & apply SpecAugment along time axis
+ batch_size, sequence_length, hidden_size = hidden_states.size()
+
+ if mask_time_indices is not None:
+ # apply SpecAugment along time axis with given mask_time_indices
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
+ elif self.config.mask_time_prob > 0 and self.training:
+ mask_time_indices = _compute_mask_indices(
+ (batch_size, sequence_length),
+ mask_prob=self.config.mask_time_prob,
+ mask_length=self.config.mask_time_length,
+ attention_mask=attention_mask,
+ min_masks=self.config.mask_time_min_masks,
+ )
+ mask_time_indices = torch.tensor(mask_time_indices, device=hidden_states.device, dtype=torch.bool)
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
+
+ if self.config.mask_feature_prob > 0 and self.training:
+ # generate indices & apply SpecAugment along feature axis
+ mask_feature_indices = _compute_mask_indices(
+ (batch_size, hidden_size),
+ mask_prob=self.config.mask_feature_prob,
+ mask_length=self.config.mask_feature_length,
+ min_masks=self.config.mask_feature_min_masks,
+ )
+ mask_feature_indices = torch.tensor(mask_feature_indices, device=hidden_states.device, dtype=torch.bool)
+ mask_feature_indices = mask_feature_indices[:, None].expand(-1, sequence_length, -1)
+ hidden_states[mask_feature_indices] = 0
+
+ return hidden_states
+
+ @auto_docstring
+ def forward(
+ self,
+ input_values: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ mask_time_indices: torch.FloatTensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | WavLMBaseModelOutput:
+ r"""
+ mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict
+ masked extracted features in *config.proj_codevector_dim* space.
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ extract_features = self.feature_extractor(input_values)
+ extract_features = extract_features.transpose(1, 2)
+
+ if attention_mask is not None:
+ # compute reduced attention_mask corresponding to feature vectors
+ attention_mask = self._get_feature_vector_attention_mask(
+ extract_features.shape[1], attention_mask, add_adapter=False
+ )
+
+ hidden_states, extract_features = self.feature_projection(extract_features)
+ hidden_states = self._mask_hidden_states(
+ hidden_states, mask_time_indices=mask_time_indices, attention_mask=attention_mask
+ )
+
+ encoder_outputs = self.encoder(
+ hidden_states,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ hidden_states = encoder_outputs[0]
+
+ if self.adapter is not None:
+ hidden_states = self.adapter(hidden_states)
+
+ if not return_dict:
+ return (hidden_states, extract_features) + encoder_outputs[1:]
+
+ return WavLMBaseModelOutput(
+ last_hidden_state=hidden_states,
+ extract_features=extract_features,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ )
+
+
+_HIDDEN_STATES_START_POSITION = 2
+
+
+@auto_docstring(
+ custom_intro="""
+ WavLM Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).
+ """
+)
+class WavLMForCTC(WavLMPreTrainedModel):
+ def __init__(self, config, target_lang: str | None = None):
+ r"""
+ target_lang (`str`, *optional*):
+ Language id of adapter weights. Adapter weights are stored in the format adapter..safetensors or
+ adapter..bin. Only relevant when using an instance of [`WavLMForCTC`] with adapters. Uses 'eng' by
+ default.
+ """
+ super().__init__(config)
+
+ self.wavlm = WavLMModel(config)
+ self.dropout = nn.Dropout(config.final_dropout)
+
+ self.target_lang = target_lang
+
+ if config.vocab_size is None:
+ raise ValueError(
+ f"You are trying to instantiate {self.__class__} with a configuration that "
+ "does not define the vocabulary size of the language model head. Please "
+ "instantiate the model as follows: `WavLMForCTC.from_pretrained(..., vocab_size=vocab_size)`. "
+ "or define `vocab_size` of your model's configuration."
+ )
+ output_hidden_size = (
+ config.output_hidden_size if hasattr(config, "add_adapter") and config.add_adapter else config.hidden_size
+ )
+ self.lm_head = nn.Linear(output_hidden_size, config.vocab_size)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def tie_weights(self, **kwargs):
+ """
+ This method overwrites [`~PreTrainedModel.tie_weights`] so that adapter weights can be correctly loaded when
+ passing `target_lang=...` to `from_pretrained(...)`.
+
+ This method is **not** supposed to be called by the user and is prone to be changed in the future.
+ """
+
+ if get_torch_context_manager_or_global_device() == torch.device("meta"):
+ return
+
+ # Note that `tie_weights` is usually used to tie input and output embedding weights. The method is re-purposed to
+ # correctly load adapter layers for WavLM so that we do not have to introduce a new API to
+ # [`PreTrainedModel`]. While slightly hacky, WavLM never has to tie input and output embeddings, so that it is
+ # ok to repurpose this function here.
+ target_lang = self.target_lang
+
+ if target_lang is not None and getattr(self.config, "adapter_attn_dim", None) is None:
+ raise ValueError(f"Cannot pass `target_lang`: {target_lang} if `config.adapter_attn_dim` is not defined.")
+ elif target_lang is None and getattr(self.config, "adapter_attn_dim", None) is not None:
+ logger.info("By default `target_lang` is set to 'eng'.")
+ elif target_lang is not None:
+ self.load_adapter(target_lang, force_load=True)
+
+ def freeze_feature_encoder(self):
+ """
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
+ not be updated during training.
+ """
+ self.wavlm.feature_extractor._freeze_parameters()
+
+ def freeze_base_model(self):
+ """
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
+ be updated during training. Only the classification head will be updated.
+ """
+ for param in self.wavlm.parameters():
+ param.requires_grad = False
+
+ @auto_docstring
+ def forward(
+ self,
+ input_values: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs,
+ ) -> tuple | CausalLMOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, target_length)`, *optional*):
+ Labels for connectionist temporal classification. Note that `target_length` has to be smaller or equal to
+ the sequence length of the output logits. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`.
+ All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ...,
+ config.vocab_size - 1]`.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ if labels is not None and labels.max() >= self.config.vocab_size:
+ raise ValueError(f"Label values must be <= vocab_size: {self.config.vocab_size}")
+
+ outputs = self.wavlm(
+ input_values,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ hidden_states = outputs[0]
+ hidden_states = self.dropout(hidden_states)
+
+ logits = self.lm_head(hidden_states)
+
+ loss = None
+ if labels is not None:
+ # retrieve loss input_lengths from attention_mask
+ attention_mask = (
+ attention_mask if attention_mask is not None else torch.ones_like(input_values, dtype=torch.long)
+ )
+ input_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1)).to(torch.long)
+
+ # assuming that padded tokens are filled with -100
+ # when not being attended to
+ labels_mask = labels >= 0
+ target_lengths = labels_mask.sum(-1)
+ flattened_targets = labels.masked_select(labels_mask)
+
+ # ctc_loss doesn't support fp16
+ log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)
+
+ with torch.backends.cudnn.flags(enabled=False):
+ loss = nn.functional.ctc_loss(
+ log_probs,
+ flattened_targets,
+ input_lengths,
+ target_lengths,
+ blank=self.config.pad_token_id,
+ reduction=self.config.ctc_loss_reduction,
+ zero_infinity=self.config.ctc_zero_infinity,
+ )
+
+ if not return_dict:
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
+ return ((loss,) + output) if loss is not None else output
+
+ return CausalLMOutput(
+ loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ WavLM Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like
+ SUPERB Keyword Spotting.
+ """
+)
+class WavLMForSequenceClassification(WavLMPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ if hasattr(config, "add_adapter") and config.add_adapter:
+ raise ValueError(
+ "Sequence classification does not support the use of WavLM adapters (config.add_adapter=True)"
+ )
+ self.wavlm = WavLMModel(config)
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
+ if config.use_weighted_layer_sum:
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
+ self.projector = nn.Linear(config.hidden_size, config.classifier_proj_size)
+ self.classifier = nn.Linear(config.classifier_proj_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def freeze_feature_encoder(self):
+ """
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
+ not be updated during training.
+ """
+ self.wavlm.feature_extractor._freeze_parameters()
+
+ def freeze_base_model(self):
+ """
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
+ be updated during training. Only the classification head will be updated.
+ """
+ for param in self.wavlm.parameters():
+ param.requires_grad = False
+
+ @auto_docstring
+ def forward(
+ self,
+ input_values: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs,
+ ) -> tuple | SequenceClassifierOutput:
+ r"""
+ input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
+ Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
+ into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
+ (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
+ To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
+ into a tensor of type `torch.FloatTensor`. See [`WavLMProcessor.__call__`] for details.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
+
+ outputs = self.wavlm(
+ input_values,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ if self.config.use_weighted_layer_sum:
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
+ hidden_states = torch.stack(hidden_states, dim=1)
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
+ else:
+ hidden_states = outputs[0]
+
+ hidden_states = self.projector(hidden_states)
+ if attention_mask is None:
+ pooled_output = hidden_states.mean(dim=1)
+ else:
+ padding_mask = self._get_feature_vector_attention_mask(hidden_states.shape[1], attention_mask)
+ expand_padding_mask = padding_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
+ hidden_states[~expand_padding_mask] = 0.0
+ pooled_output = hidden_states.sum(dim=1) / padding_mask.sum(dim=1).view(-1, 1)
+
+ logits = self.classifier(pooled_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
+
+ if not return_dict:
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
+ return ((loss,) + output) if loss is not None else output
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class WavLMForAudioFrameClassification(WavLMPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ if hasattr(config, "add_adapter") and config.add_adapter:
+ raise ValueError(
+ "Audio frame classification does not support the use of WavLM adapters (config.add_adapter=True)"
+ )
+ self.wavlm = WavLMModel(config)
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
+ if config.use_weighted_layer_sum:
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+ self.num_labels = config.num_labels
+
+ self.post_init()
+
+ def freeze_feature_encoder(self):
+ """
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
+ not be updated during training.
+ """
+ self.wavlm.feature_extractor._freeze_parameters()
+
+ def freeze_base_model(self):
+ """
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
+ be updated during training. Only the classification head will be updated.
+ """
+ for param in self.wavlm.parameters():
+ param.requires_grad = False
+
+ @auto_docstring
+ def forward(
+ self,
+ input_values: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | TokenClassifierOutput:
+ r"""
+ input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
+ Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
+ into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
+ (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
+ To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
+ into a tensor of type `torch.FloatTensor`. See [`WavLMProcessor.__call__`] for details.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
+
+ outputs = self.wavlm(
+ input_values,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ if self.config.use_weighted_layer_sum:
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
+ hidden_states = torch.stack(hidden_states, dim=1)
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
+ else:
+ hidden_states = outputs[0]
+
+ logits = self.classifier(hidden_states)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), torch.argmax(labels.view(-1, self.num_labels), axis=1))
+
+ if not return_dict:
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
+ return output
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+class AMSoftmaxLoss(nn.Module):
+ def __init__(self, input_dim, num_labels, scale=30.0, margin=0.4):
+ super().__init__()
+ self.scale = scale
+ self.margin = margin
+ self.num_labels = num_labels
+ self.weight = nn.Parameter(torch.randn(input_dim, num_labels), requires_grad=True)
+ self.loss = nn.CrossEntropyLoss()
+
+ def forward(self, hidden_states, labels):
+ labels = labels.flatten()
+ weight = nn.functional.normalize(self.weight, dim=0)
+ hidden_states = nn.functional.normalize(hidden_states, dim=1)
+ cos_theta = torch.mm(hidden_states, weight)
+ psi = cos_theta - self.margin
+
+ onehot = nn.functional.one_hot(labels, self.num_labels)
+ logits = self.scale * torch.where(onehot.bool(), psi, cos_theta)
+ loss = self.loss(logits, labels)
+
+ return loss
+
+
+class TDNNLayer(nn.Module):
+ def __init__(self, config, layer_id=0):
+ super().__init__()
+ self.in_conv_dim = config.tdnn_dim[layer_id - 1] if layer_id > 0 else config.tdnn_dim[layer_id]
+ self.out_conv_dim = config.tdnn_dim[layer_id]
+ self.kernel_size = config.tdnn_kernel[layer_id]
+ self.dilation = config.tdnn_dilation[layer_id]
+
+ self.kernel = nn.Linear(self.in_conv_dim * self.kernel_size, self.out_conv_dim)
+ self.activation = nn.ReLU()
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ if is_peft_available():
+ from peft.tuners.lora import LoraLayer
+
+ if is_peft_available():
+ if isinstance(self.kernel, LoraLayer):
+ warnings.warn(
+ "Detected LoRA on TDNNLayer. LoRA weights won't be applied due to optimization. "
+ "You should exclude TDNNLayer from LoRA's target modules.",
+ )
+
+ # for backward compatibility, we keep nn.Linear but call F.conv1d for speed up
+ hidden_states = hidden_states.transpose(1, 2)
+ weight = self.kernel.weight.view(self.out_conv_dim, self.kernel_size, self.in_conv_dim).transpose(1, 2)
+ hidden_states = nn.functional.conv1d(hidden_states, weight, self.kernel.bias, dilation=self.dilation)
+ hidden_states = hidden_states.transpose(1, 2)
+
+ hidden_states = self.activation(hidden_states)
+ return hidden_states
+
+
+@auto_docstring(
+ custom_intro="""
+ WavLM Model with an XVector feature extraction head on top for tasks like Speaker Verification.
+ """
+)
+class WavLMForXVector(WavLMPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.wavlm = WavLMModel(config)
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
+ if config.use_weighted_layer_sum:
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
+ self.projector = nn.Linear(config.hidden_size, config.tdnn_dim[0])
+
+ tdnn_layers = [TDNNLayer(config, i) for i in range(len(config.tdnn_dim))]
+ self.tdnn = nn.ModuleList(tdnn_layers)
+
+ self.feature_extractor = nn.Linear(config.tdnn_dim[-1] * 2, config.xvector_output_dim)
+ self.classifier = nn.Linear(config.xvector_output_dim, config.xvector_output_dim)
+
+ self.objective = AMSoftmaxLoss(config.xvector_output_dim, config.num_labels)
+
+ self.post_init()
+
+ def freeze_feature_encoder(self):
+ """
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
+ not be updated during training.
+ """
+ self.wavlm.feature_extractor._freeze_parameters()
+
+ def freeze_base_model(self):
+ """
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
+ be updated during training. Only the classification head will be updated.
+ """
+ for param in self.wavlm.parameters():
+ param.requires_grad = False
+
+ def _get_tdnn_output_lengths(self, input_lengths: torch.LongTensor | int):
+ """
+ Computes the output length of the TDNN layers
+ """
+
+ def _conv_out_length(input_length, kernel_size, stride):
+ # 1D convolutional layer output length formula taken
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
+ return (input_length - kernel_size) // stride + 1
+
+ for kernel_size in self.config.tdnn_kernel:
+ input_lengths = _conv_out_length(input_lengths, kernel_size, 1)
+
+ return input_lengths
+
+ @auto_docstring
+ def forward(
+ self,
+ input_values: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs,
+ ) -> tuple | XVectorOutput:
+ r"""
+ input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
+ Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
+ into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
+ (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
+ To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
+ into a tensor of type `torch.FloatTensor`. See [`WavLMProcessor.__call__`] for details.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
+
+ outputs = self.wavlm(
+ input_values,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ if self.config.use_weighted_layer_sum:
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
+ hidden_states = torch.stack(hidden_states, dim=1)
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
+ else:
+ hidden_states = outputs[0]
+
+ hidden_states = self.projector(hidden_states)
+
+ for tdnn_layer in self.tdnn:
+ hidden_states = tdnn_layer(hidden_states)
+
+ # Statistic Pooling
+ if attention_mask is None:
+ mean_features = hidden_states.mean(dim=1)
+ std_features = hidden_states.std(dim=1)
+ else:
+ feat_extract_output_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(dim=1))
+ tdnn_output_lengths = self._get_tdnn_output_lengths(feat_extract_output_lengths)
+ mean_features = []
+ std_features = []
+ for i, length in enumerate(tdnn_output_lengths):
+ mean_features.append(hidden_states[i, :length].mean(dim=0))
+ std_features.append(hidden_states[i, :length].std(dim=0))
+ mean_features = torch.stack(mean_features)
+ std_features = torch.stack(std_features)
+ statistic_pooling = torch.cat([mean_features, std_features], dim=-1)
+
+ output_embeddings = self.feature_extractor(statistic_pooling)
+ logits = self.classifier(output_embeddings)
+
+ loss = None
+ if labels is not None:
+ loss = self.objective(logits, labels)
+
+ if not return_dict:
+ output = (logits, output_embeddings) + outputs[_HIDDEN_STATES_START_POSITION:]
+ return ((loss,) + output) if loss is not None else output
+
+ return XVectorOutput(
+ loss=loss,
+ logits=logits,
+ embeddings=output_embeddings,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "WavLMForAudioFrameClassification",
+ "WavLMForCTC",
+ "WavLMForSequenceClassification",
+ "WavLMForXVector",
+ "WavLMModel",
+ "WavLMPreTrainedModel",
+]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/wavlm/modular_wavlm.py b/.venv/lib/python3.12/site-packages/transformers/models/wavlm/modular_wavlm.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3329e64913d27967886c1c5442e339cdc490002
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/wavlm/modular_wavlm.py
@@ -0,0 +1,590 @@
+import math
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from ... import initialization as init
+from ...integrations.deepspeed import is_deepspeed_zero3_enabled
+from ...integrations.fsdp import is_fsdp_managed_module
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutput, Wav2Vec2BaseModelOutput
+from ...modeling_utils import PreTrainedModel
+from ...utils import logging
+from ..wav2vec2.modeling_wav2vec2 import (
+ Wav2Vec2FeatureProjection,
+ Wav2Vec2FeedForward,
+ Wav2Vec2ForAudioFrameClassification,
+ Wav2Vec2ForCTC,
+ Wav2Vec2ForSequenceClassification,
+ Wav2Vec2ForXVector,
+ Wav2Vec2Model,
+ Wav2Vec2PositionalConvEmbedding,
+ Wav2Vec2PreTrainedModel,
+)
+from .configuration_wavlm import WavLMConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+class WavLMPositionalConvEmbedding(Wav2Vec2PositionalConvEmbedding):
+ pass
+
+
+class WavLMFeatureProjection(Wav2Vec2FeatureProjection):
+ pass
+
+
+class WavLMAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(
+ self,
+ embed_dim: int,
+ num_heads: int,
+ dropout: float | int = 0.0,
+ num_buckets: int = 320,
+ max_distance: int = 800,
+ has_relative_position_bias: bool = True,
+ ):
+ super().__init__()
+ self.embed_dim = embed_dim
+ self.num_heads = num_heads
+ self.dropout = dropout
+ self.head_dim = embed_dim // num_heads
+
+ if (self.head_dim * num_heads) != self.embed_dim:
+ raise ValueError(
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
+ f" and `num_heads`: {num_heads})."
+ )
+ self.scaling = self.head_dim**-0.5
+
+ self.k_proj = nn.Linear(embed_dim, embed_dim)
+ self.v_proj = nn.Linear(embed_dim, embed_dim)
+ self.q_proj = nn.Linear(embed_dim, embed_dim)
+ self.out_proj = nn.Linear(embed_dim, embed_dim)
+
+ self.num_buckets = num_buckets
+ self.max_distance = max_distance
+
+ self.gru_rel_pos_const = nn.Parameter(torch.ones(1, self.num_heads, 1, 1))
+ self.gru_rel_pos_linear = nn.Linear(self.head_dim, 8)
+
+ if has_relative_position_bias:
+ self.rel_attn_embed = nn.Embedding(self.num_buckets, self.num_heads)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_bias: torch.Tensor | None = None,
+ output_attentions: bool = False,
+ index=0,
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
+ """Attention layer with relative attention"""
+ bsz, tgt_len, _ = hidden_states.size()
+
+ # first pass of attention layer creates position bias
+ if position_bias is None:
+ position_bias = self.compute_bias(tgt_len, tgt_len)
+ position_bias = (
+ position_bias.unsqueeze(0).repeat(bsz, 1, 1, 1).view(bsz * self.num_heads, tgt_len, tgt_len)
+ )
+
+ # Compute relative position bias:
+ # 1) get reshape hidden_states
+ gated_hidden_states = hidden_states.view(hidden_states.shape[:-1] + (self.num_heads, -1))
+ gated_hidden_states = gated_hidden_states.permute(0, 2, 1, 3)
+
+ # 2) project hidden states
+ relative_position_proj = self.gru_rel_pos_linear(gated_hidden_states)
+ relative_position_proj = relative_position_proj.view(gated_hidden_states.shape[:-1] + (2, 4)).sum(-1)
+
+ # 3) compute gate for position bias from projected hidden states
+ gate_a, gate_b = torch.sigmoid(relative_position_proj).chunk(2, dim=-1)
+ gate_output = gate_a * (gate_b * self.gru_rel_pos_const - 1.0) + 2.0
+
+ # 4) apply gate to position bias to compute gated position_bias
+ gated_position_bias = gate_output.view(bsz * self.num_heads, -1, 1) * position_bias
+ gated_position_bias = gated_position_bias.view((-1, tgt_len, tgt_len))
+
+ attn_output, attn_weights = self.torch_multi_head_self_attention(
+ hidden_states, attention_mask, gated_position_bias, output_attentions
+ )
+
+ return attn_output, attn_weights, position_bias
+
+ def torch_multi_head_self_attention(
+ self,
+ hidden_states: torch.FloatTensor,
+ attention_mask: torch.LongTensor | torch.BoolTensor,
+ gated_position_bias: torch.FloatTensor,
+ output_attentions: bool,
+ ) -> tuple[torch.FloatTensor, torch.FloatTensor]:
+ """simple wrapper around torch's multi_head_attention_forward function"""
+ # self-attention assumes q = k = v
+ query = key = value = hidden_states.transpose(0, 1)
+ key_padding_mask = attention_mask.ne(1) if attention_mask is not None else None
+
+ # disable bias and add_zero_attn
+ bias_k = bias_v = None
+ add_zero_attn = False
+
+ # PyTorch 1.3.0 has F.multi_head_attention_forward defined
+ # so no problem with backwards compatibility
+ attn_output, attn_weights = F.multi_head_attention_forward(
+ query,
+ key,
+ value,
+ self.embed_dim,
+ self.num_heads,
+ torch.empty([0]),
+ torch.cat((self.q_proj.bias, self.k_proj.bias, self.v_proj.bias)),
+ bias_k,
+ bias_v,
+ add_zero_attn,
+ self.dropout,
+ self.out_proj.weight,
+ self.out_proj.bias,
+ self.training,
+ key_padding_mask,
+ output_attentions,
+ gated_position_bias,
+ use_separate_proj_weight=True,
+ q_proj_weight=self.q_proj.weight,
+ k_proj_weight=self.k_proj.weight,
+ v_proj_weight=self.v_proj.weight,
+ )
+
+ # [Seq_Len, Batch Size, ...] -> [Batch Size, Seq_Len, ...]
+ attn_output = attn_output.transpose(0, 1)
+
+ if attn_weights is not None:
+ # IMPORTANT: Attention weights are averaged weights
+ # here which should not be the case. This is an open issue
+ # on PyTorch: https://github.com/pytorch/pytorch/issues/32590
+ attn_weights = attn_weights[:, None].broadcast_to(
+ attn_weights.shape[:1] + (self.num_heads,) + attn_weights.shape[1:]
+ )
+
+ return attn_output, attn_weights
+
+ def compute_bias(self, query_length: int, key_length: int) -> torch.FloatTensor:
+ context_position = torch.arange(query_length, dtype=torch.long)[:, None]
+ memory_position = torch.arange(key_length, dtype=torch.long)[None, :]
+ relative_position = memory_position - context_position
+ relative_position_bucket = self._relative_positions_bucket(relative_position)
+ relative_position_bucket = relative_position_bucket.to(self.rel_attn_embed.weight.device)
+ values = self.rel_attn_embed(relative_position_bucket)
+ values = values.permute([2, 0, 1])
+ return values
+
+ def _relative_positions_bucket(self, relative_positions: torch.FloatTensor) -> torch.FloatTensor:
+ num_buckets = self.num_buckets // 2
+
+ relative_buckets = (relative_positions > 0).to(torch.long) * num_buckets
+ relative_positions = torch.abs(relative_positions)
+
+ max_exact = num_buckets // 2
+ is_small = relative_positions < max_exact
+
+ relative_positions_if_large = torch.log(relative_positions.float() / max_exact)
+ relative_positions_if_large = relative_positions_if_large / math.log(self.max_distance / max_exact)
+ relative_positions_if_large = relative_positions_if_large * (num_buckets - max_exact)
+ relative_position_if_large = (max_exact + relative_positions_if_large).to(torch.long)
+ relative_position_if_large = torch.min(
+ relative_position_if_large, torch.full_like(relative_position_if_large, num_buckets - 1)
+ )
+
+ relative_buckets += torch.where(is_small, relative_positions, relative_position_if_large)
+ return relative_buckets
+
+
+class WavLMFeedForward(Wav2Vec2FeedForward):
+ pass
+
+
+class WavLMEncoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: WavLMConfig, has_relative_position_bias: bool = True):
+ super().__init__()
+ self.attention = WavLMAttention(
+ embed_dim=config.hidden_size,
+ num_heads=config.num_attention_heads,
+ dropout=config.attention_dropout,
+ num_buckets=config.num_buckets,
+ max_distance=config.max_bucket_distance,
+ has_relative_position_bias=has_relative_position_bias,
+ )
+ self.dropout = nn.Dropout(config.hidden_dropout)
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.feed_forward = WavLMFeedForward(config)
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(self, hidden_states, attention_mask=None, position_bias=None, output_attentions=False, index=0):
+ attn_residual = hidden_states
+ hidden_states, attn_weights, position_bias = self.attention(
+ hidden_states,
+ attention_mask=attention_mask,
+ position_bias=position_bias,
+ output_attentions=output_attentions,
+ index=index,
+ )
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = attn_residual + hidden_states
+
+ hidden_states = self.layer_norm(hidden_states)
+
+ hidden_states = hidden_states + self.feed_forward(hidden_states)
+ hidden_states = self.final_layer_norm(hidden_states)
+
+ outputs = (hidden_states, position_bias)
+
+ if output_attentions:
+ outputs += (attn_weights,)
+
+ return outputs
+
+
+class WavLMEncoderLayerStableLayerNorm(GradientCheckpointingLayer):
+ def __init__(self, config: WavLMConfig, has_relative_position_bias: bool = True):
+ super().__init__()
+ self.attention = WavLMAttention(
+ embed_dim=config.hidden_size,
+ num_heads=config.num_attention_heads,
+ dropout=config.attention_dropout,
+ num_buckets=config.num_buckets,
+ max_distance=config.max_bucket_distance,
+ has_relative_position_bias=has_relative_position_bias,
+ )
+ self.dropout = nn.Dropout(config.hidden_dropout)
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.feed_forward = WavLMFeedForward(config)
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(self, hidden_states, attention_mask=None, position_bias=None, output_attentions=False):
+ attn_residual = hidden_states
+ hidden_states = self.layer_norm(hidden_states)
+ hidden_states, attn_weights, position_bias = self.attention(
+ hidden_states,
+ attention_mask=attention_mask,
+ position_bias=position_bias,
+ output_attentions=output_attentions,
+ )
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = attn_residual + hidden_states
+ hidden_states = hidden_states + self.feed_forward(self.final_layer_norm(hidden_states))
+
+ outputs = (hidden_states, position_bias)
+
+ if output_attentions:
+ outputs += (attn_weights,)
+
+ return outputs
+
+
+class WavLMEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.pos_conv_embed = WavLMPositionalConvEmbedding(config)
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout)
+ self.layers = nn.ModuleList(
+ [WavLMEncoderLayer(config, has_relative_position_bias=(i == 0)) for i in range(config.num_hidden_layers)]
+ )
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ output_attentions=False,
+ output_hidden_states=False,
+ return_dict=True,
+ ):
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+
+ if attention_mask is not None:
+ # make sure padded tokens output 0
+ expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
+ hidden_states[~expand_attention_mask] = 0
+
+ position_embeddings = self.pos_conv_embed(hidden_states)
+ hidden_states = hidden_states + position_embeddings
+ hidden_states = self.layer_norm(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
+ position_bias = None
+
+ for i, layer in enumerate(self.layers):
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
+ dropout_probability = torch.rand([])
+
+ skip_the_layer = self.training and i > 0 and (dropout_probability < self.config.layerdrop)
+ if not skip_the_layer or synced_gpus:
+ # under fsdp or deepspeed zero3 all gpus must run in sync
+ layer_outputs = layer(
+ hidden_states,
+ attention_mask=attention_mask,
+ position_bias=position_bias,
+ output_attentions=output_attentions,
+ index=i,
+ )
+
+ hidden_states, position_bias = layer_outputs[:2]
+
+ if skip_the_layer:
+ layer_outputs = (None, None, None)
+
+ if output_attentions:
+ all_self_attentions = all_self_attentions + (layer_outputs[2],)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
+ return BaseModelOutput(
+ last_hidden_state=hidden_states,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ )
+
+
+class WavLMEncoderStableLayerNorm(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.pos_conv_embed = WavLMPositionalConvEmbedding(config)
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout)
+ self.layers = nn.ModuleList(
+ [
+ WavLMEncoderLayerStableLayerNorm(config, has_relative_position_bias=(i == 0))
+ for i in range(config.num_hidden_layers)
+ ]
+ )
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ output_attentions=False,
+ output_hidden_states=False,
+ return_dict=True,
+ ):
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+
+ if attention_mask is not None:
+ # make sure padded tokens are not attended to
+ expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
+ hidden_states[~expand_attention_mask] = 0
+
+ position_embeddings = self.pos_conv_embed(hidden_states)
+ hidden_states = hidden_states + position_embeddings
+ hidden_states = self.dropout(hidden_states)
+
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
+ position_bias = None
+
+ for i, layer in enumerate(self.layers):
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
+ dropout_probability = torch.rand([])
+
+ skip_the_layer = self.training and i > 0 and (dropout_probability < self.config.layerdrop)
+ if not skip_the_layer or synced_gpus:
+ # under fsdp or deepspeed zero3 all gpus must run in sync
+ # XXX: could optimize this like synced_gpus in generate_utils but not sure if it's worth the code complication
+ layer_outputs = layer(
+ hidden_states,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ position_bias=position_bias,
+ )
+ hidden_states, position_bias = layer_outputs[:2]
+
+ if skip_the_layer:
+ layer_outputs = (None, None, None)
+
+ if output_attentions:
+ all_self_attentions = all_self_attentions + (layer_outputs[2],)
+
+ hidden_states = self.layer_norm(hidden_states)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
+ return BaseModelOutput(
+ last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_self_attentions
+ )
+
+
+class WavLMGumbelVectorQuantizer(nn.Module):
+ """
+ Vector quantization using gumbel softmax. See [CATEGORICAL REPARAMETERIZATION WITH
+ GUMBEL-SOFTMAX](https://huggingface.co/papers/1611.01144) for more information.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ self.num_groups = config.num_codevector_groups
+ self.num_vars = config.num_codevectors_per_group
+
+ if config.codevector_dim % self.num_groups != 0:
+ raise ValueError(
+ f"`config.codevector_dim {config.codevector_dim} must be divisible"
+ f" by `config.num_codevector_groups` {self.num_groups} "
+ "for concatenation."
+ )
+
+ # storage for codebook variables (codewords)
+ self.codevectors = nn.Parameter(
+ torch.FloatTensor(1, self.num_groups * self.num_vars, config.codevector_dim // self.num_groups)
+ )
+ self.weight_proj = nn.Linear(config.conv_dim[-1], self.num_groups * self.num_vars)
+
+ # can be decayed for training
+ self.temperature = 2
+
+ @staticmethod
+ def _compute_perplexity(probs):
+ marginal_probs = probs.mean(dim=0)
+ perplexity = torch.exp(-torch.sum(torch.xlogy(marginal_probs, marginal_probs), dim=-1)).sum()
+ return perplexity
+
+ def forward(self, hidden_states):
+ batch_size, sequence_length, hidden_size = hidden_states.shape
+
+ # project to codevector dim
+ hidden_states = self.weight_proj(hidden_states)
+ hidden_states = hidden_states.view(batch_size * sequence_length * self.num_groups, -1)
+
+ if self.training:
+ # sample code vector probs via gumbel in differentiateable way
+ codevector_probs = nn.functional.gumbel_softmax(hidden_states.float(), tau=self.temperature, hard=True)
+ codevector_probs = codevector_probs.type_as(hidden_states)
+
+ # compute perplexity
+ codevector_soft_dist = torch.softmax(
+ hidden_states.view(batch_size * sequence_length, self.num_groups, -1).float(), dim=-1
+ )
+ perplexity = self._compute_perplexity(codevector_soft_dist)
+ else:
+ # take argmax in non-differentiable way
+ # comptute hard codevector distribution (one hot)
+ codevector_idx = hidden_states.argmax(dim=-1)
+ codevector_probs = hidden_states.new_zeros(*hidden_states.shape).scatter_(
+ -1, codevector_idx.view(-1, 1), 1.0
+ )
+ codevector_probs = codevector_probs.view(batch_size * sequence_length, self.num_groups, -1)
+
+ perplexity = self._compute_perplexity(codevector_probs)
+
+ codevector_probs = codevector_probs.view(batch_size * sequence_length, -1)
+ # use probs to retrieve codevectors
+ codevectors_per_group = codevector_probs.unsqueeze(-1) * self.codevectors
+ codevectors = codevectors_per_group.view(batch_size * sequence_length, self.num_groups, self.num_vars, -1)
+ codevectors = codevectors.sum(-2).view(batch_size, sequence_length, -1)
+
+ return codevectors, perplexity
+
+
+class WavLMPreTrainedModel(PreTrainedModel, Wav2Vec2PreTrainedModel):
+ config: WavLMConfig
+ base_model_prefix = "wavlm"
+ main_input_name = "input_values"
+ input_modalities = "audio"
+ supports_gradient_checkpointing = True
+ _supports_flash_attn = False
+ _supports_sdpa = False
+ _supports_flex_attn = False
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ # gumbel softmax requires special init
+ if isinstance(module, WavLMGumbelVectorQuantizer):
+ init.normal_(module.weight_proj.weight, mean=0.0, std=1)
+ init.zeros_(module.weight_proj.bias)
+ init.uniform_(module.codevectors)
+ elif isinstance(module, WavLMPositionalConvEmbedding):
+ init.normal_(
+ module.conv.weight,
+ mean=0,
+ std=2 * math.sqrt(1 / (module.conv.kernel_size[0] * module.conv.in_channels)),
+ )
+ init.constant_(module.conv.bias, 0)
+ elif isinstance(module, WavLMFeatureProjection):
+ k = math.sqrt(1 / module.projection.in_features)
+ init.uniform_(module.projection.weight, a=-k, b=k)
+ init.uniform_(module.projection.bias, a=-k, b=k)
+ elif isinstance(module, nn.Linear):
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
+
+ if module.bias is not None:
+ init.zeros_(module.bias)
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
+ init.zeros_(module.bias)
+ init.ones_(module.weight)
+ elif isinstance(module, nn.Conv1d):
+ init.kaiming_normal_(module.weight)
+
+ if module.bias is not None:
+ k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
+ init.uniform_(module.bias, a=-k, b=k)
+
+ def _get_adapters(self):
+ raise AttributeError("Not needed for WavLM")
+
+ def init_adapter_layers(self):
+ raise AttributeError("Not needed for WavLM")
+
+ def load_adapter(self):
+ raise AttributeError("Not needed for WavLM")
+
+
+WavLMBaseModelOutput = Wav2Vec2BaseModelOutput
+
+
+class WavLMModel(Wav2Vec2Model):
+ pass
+
+
+class WavLMForCTC(Wav2Vec2ForCTC):
+ pass
+
+
+class WavLMForSequenceClassification(Wav2Vec2ForSequenceClassification):
+ pass
+
+
+class WavLMForAudioFrameClassification(Wav2Vec2ForAudioFrameClassification):
+ pass
+
+
+class WavLMForXVector(Wav2Vec2ForXVector):
+ pass
+
+
+__all__ = [
+ "WavLMForAudioFrameClassification",
+ "WavLMForCTC",
+ "WavLMForSequenceClassification",
+ "WavLMForXVector",
+ "WavLMModel",
+ "WavLMPreTrainedModel",
+]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/whisper/__init__.py b/.venv/lib/python3.12/site-packages/transformers/models/whisper/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..50aec31b3e9fdcf2de1daf47d278491ecee3b1f8
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/whisper/__init__.py
@@ -0,0 +1,30 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_whisper import *
+ from .feature_extraction_whisper import *
+ from .modeling_whisper import *
+ from .processing_whisper import *
+ from .tokenization_whisper import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7c691d6a60ef77b68290df439432688a78a97181
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/configuration_whisper.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/configuration_whisper.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ec6eb99b009f5691f0162b645375157d34033760
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/configuration_whisper.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/english_normalizer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/english_normalizer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e5c76dc5cd9869dd32bf1282d16e33ae335af33f
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/english_normalizer.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/feature_extraction_whisper.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/feature_extraction_whisper.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..20a93723e71625add52dd35b0bb7d49d2e1b81e7
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/feature_extraction_whisper.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/generation_whisper.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/generation_whisper.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..af23a5512dfe95e0fb2476c3e5875e9609df3ef0
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/generation_whisper.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/modeling_whisper.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/modeling_whisper.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..45b4f1461e7c85f6ab223c3c4cc71cc74a064f87
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/modeling_whisper.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/processing_whisper.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/processing_whisper.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..160d3b64a773a60a922bab9ad76b65ded8780841
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/processing_whisper.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/tokenization_whisper.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/tokenization_whisper.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8a22ccb64eac67a3b4b2054d84e009d4f843035a
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/tokenization_whisper.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/whisper/configuration_whisper.py b/.venv/lib/python3.12/site-packages/transformers/models/whisper/configuration_whisper.py
new file mode 100644
index 0000000000000000000000000000000000000000..26150b06f82f445c5117bdaf8419489d374ea260
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/whisper/configuration_whisper.py
@@ -0,0 +1,167 @@
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Whisper model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+# fmt: off
+NON_SPEECH_TOKENS = [
+ 1, 2, 7, 8, 9, 10, 14, 25,
+ 26, 27, 28, 29, 31, 58, 59, 60, 61, 62,
+ 63, 90, 91, 92, 93, 357, 366, 438, 532, 685,
+ 705, 796, 930, 1058, 1220, 1267, 1279, 1303, 1343, 1377,
+ 1391, 1635, 1782, 1875, 2162, 2361, 2488, 3467, 4008, 4211,
+ 4600, 4808, 5299, 5855, 6329, 7203, 9609, 9959, 10563, 10786,
+ 11420, 11709, 11907, 13163, 13697, 13700, 14808, 15306, 16410, 16791,
+ 17992, 19203, 19510, 20724, 22305, 22935, 27007, 30109, 30420, 33409,
+ 34949, 40283, 40493, 40549, 47282, 49146, 50257, 50359, 50360, 50361
+]
+NON_SPEECH_TOKENS_MULTI = [
+ 1, 2, 7, 8, 9, 10, 14, 25,
+ 26, 27, 28, 29, 31, 58, 59, 60, 61, 62,
+ 63, 90, 91, 92, 93, 359, 503, 522, 542, 873,
+ 893, 902, 918, 922, 931, 1350, 1853, 1982, 2460, 2627,
+ 3246, 3253, 3268, 3536, 3846, 3961, 4183, 4667, 6585, 6647,
+ 7273, 9061, 9383, 10428, 10929, 11938, 12033, 12331, 12562, 13793,
+ 14157, 14635, 15265, 15618, 16553, 16604, 18362, 18956, 20075, 21675,
+ 22520, 26130, 26161, 26435, 28279, 29464, 31650, 32302, 32470, 36865,
+ 42863, 47425, 49870, 50254, 50258, 50360, 50361, 50362
+]
+# fmt: on
+
+
+@auto_docstring(checkpoint="openai/whisper-tiny")
+@strict
+class WhisperConfig(PreTrainedConfig):
+ r"""
+ max_source_positions (`int`, *optional*, defaults to 1500):
+ The maximum sequence length of log-mel filter-bank features that this model might ever be used with.
+ max_target_positions (`int`, *optional*, defaults to 448):
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
+ just in case (e.g., 512 or 1024 or 2048).
+ suppress_tokens (`list[int]`, *optional*):
+ A list containing the non-speech tokens that will be used by the logit processor in the `generate`
+ function. NON_SPEECH_TOKENS and NON_SPEECH_TOKENS_MULTI each correspond to the `english-only` and the
+ `multilingual` model.
+ begin_suppress_tokens (`list[int]`, *optional*, defaults to `[220,50256]`):
+ A list containing tokens that will be suppressed at the beginning of the sampling process. Initialized as
+ the token for `" "` (`blank_token_id`) and the `eos_token_id`
+ use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):
+ Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an
+ instance of [`WhisperForAudioClassification`].
+ classifier_proj_size (`int`, *optional*, defaults to 256):
+ Dimensionality of the projection before token mean-pooling for classification. Only relevant when using an
+ instance of [`WhisperForAudioClassification`].
+ apply_spec_augment (`bool`, *optional*, defaults to `False`):
+ Whether to apply *SpecAugment* data augmentation to the outputs of the feature encoder. For reference see
+ [SpecAugment: A Simple Data Augmentation Method for Automatic Speech
+ Recognition](https://huggingface.co/papers/1904.08779).
+ mask_time_prob (`float`, *optional*, defaults to 0.05):
+ Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking
+ procedure generates `mask_time_prob*len(time_axis)/mask_time_length` independent masks over the axis. If
+ reasoning from the probability of each feature vector to be chosen as the start of the vector span to be
+ masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the
+ actual percentage of masked vectors. This is only relevant if `apply_spec_augment == True`.
+ mask_time_length (`int`, *optional*, defaults to 10):
+ Length of vector span along the time axis.
+ mask_time_min_masks (`int`, *optional*, defaults to 2),:
+ The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
+ irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <
+ mask_time_min_masks''
+ mask_feature_prob (`float`, *optional*, defaults to 0.0):
+ Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
+ masking procedure generates `mask_feature_prob*len(feature_axis)/mask_time_length` independent masks over
+ the axis. If reasoning from the probability of each feature vector to be chosen as the start of the vector
+ span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap
+ may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is
+ True`.
+ mask_feature_length (`int`, *optional*, defaults to 10):
+ Length of vector span along the feature axis.
+ mask_feature_min_masks (`int`, *optional*, defaults to 0):
+ The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time
+ step, irrespectively of `mask_feature_prob`. Only relevant if
+ `mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks`.
+ median_filter_width (`int`, *optional*, defaults to 7):
+ Width of the median filter used to smoothen to cross-attention outputs when computing token timestamps.
+ Should be an odd number.
+
+ Example:
+
+ ```python
+ >>> from transformers import WhisperConfig, WhisperModel
+
+ >>> # Initializing a Whisper tiny style configuration
+ >>> configuration = WhisperConfig()
+
+ >>> # Initializing a model (with random weights) from the tiny style configuration
+ >>> model = WhisperModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "whisper"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ attribute_map = {
+ "num_key_value_heads": "encoder_attention_heads",
+ "num_attention_heads": "encoder_attention_heads",
+ "hidden_size": "d_model",
+ "num_hidden_layers": "encoder_layers",
+ }
+
+ vocab_size: int = 51865
+ num_mel_bins: int = 80
+ encoder_layers: int = 4
+ encoder_attention_heads: int = 6
+ decoder_layers: int = 4
+ decoder_attention_heads: int = 6
+ decoder_ffn_dim: int = 1536
+ encoder_ffn_dim: int = 1536
+ encoder_layerdrop: float | int = 0.0
+ decoder_layerdrop: float | int = 0.0
+ decoder_start_token_id: int = 50257
+ use_cache: bool = True
+ is_encoder_decoder: bool = True
+ activation_function: str = "gelu"
+ d_model: int = 384
+ dropout: float | int = 0.0
+ attention_dropout: float | int = 0.0
+ activation_dropout: float | int = 0.0
+ init_std: float = 0.02
+ scale_embedding: bool = False
+ max_source_positions: int = 1500
+ max_target_positions: int = 448
+ pad_token_id: int | None = 50256
+ bos_token_id: int | None = 50256
+ eos_token_id: int | list[int] | None = 50256
+ suppress_tokens: list | None = None
+ begin_suppress_tokens: list[int] | tuple[int, ...] | None = (220, 50256)
+ use_weighted_layer_sum: bool = False
+ classifier_proj_size: int = 256
+ apply_spec_augment: bool = False
+ mask_time_prob: float | int = 0.05
+ mask_time_length: int = 10
+ mask_time_min_masks: int = 2
+ mask_feature_prob: float | int = 0.0
+ mask_feature_length: int = 10
+ mask_feature_min_masks: int = 0
+ median_filter_width: int = 7
+ tie_word_embeddings: bool = True
+
+
+__all__ = ["WhisperConfig"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/whisper/english_normalizer.py b/.venv/lib/python3.12/site-packages/transformers/models/whisper/english_normalizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..99441655067efe1b959426b6c6a255cd7dd326a9
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/whisper/english_normalizer.py
@@ -0,0 +1,596 @@
+# Copyright 2022 The OpenAI team and The HuggingFace Team. All rights reserved.
+# Most of the code is copy pasted from the original whisper repository
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import re
+import unicodedata
+from collections.abc import Iterator
+from fractions import Fraction
+from re import Match
+
+import regex
+
+
+# non-ASCII letters that are not separated by "NFKD" normalization
+ADDITIONAL_DIACRITICS = {
+ "œ": "oe",
+ "Œ": "OE",
+ "ø": "o",
+ "Ø": "O",
+ "æ": "ae",
+ "Æ": "AE",
+ "ß": "ss",
+ "ẞ": "SS",
+ "đ": "d",
+ "Đ": "D",
+ "ð": "d",
+ "Ð": "D",
+ "þ": "th",
+ "Þ": "th",
+ "ł": "l",
+ "Ł": "L",
+}
+
+
+def remove_symbols_and_diacritics(s: str, keep=""):
+ """
+ Replace any other markers, symbols, and punctuations with a space, and drop any diacritics (category 'Mn' and some
+ manual mappings)
+ """
+
+ def replace_character(char):
+ if char in keep:
+ return char
+ elif char in ADDITIONAL_DIACRITICS:
+ return ADDITIONAL_DIACRITICS[char]
+
+ elif unicodedata.category(char) == "Mn":
+ return ""
+
+ elif unicodedata.category(char)[0] in "MSP":
+ return " "
+
+ return char
+
+ return "".join(replace_character(c) for c in unicodedata.normalize("NFKD", s))
+
+
+def remove_symbols(s: str):
+ """
+ Replace any other markers, symbols, punctuations with a space, keeping diacritics
+ """
+ return "".join(" " if unicodedata.category(c)[0] in "MSP" else c for c in unicodedata.normalize("NFKC", s))
+
+
+class BasicTextNormalizer:
+ def __init__(self, remove_diacritics: bool = False, split_letters: bool = False):
+ self.clean = remove_symbols_and_diacritics if remove_diacritics else remove_symbols
+ self.split_letters = split_letters
+
+ def __call__(self, s: str):
+ s = s.lower()
+ s = re.sub(r"[<\[][^>\]]*[>\]]", "", s) # remove words between brackets
+ s = re.sub(r"\(([^)]+?)\)", "", s) # remove words between parenthesis
+ s = self.clean(s).lower()
+
+ if self.split_letters:
+ s = " ".join(regex.findall(r"\X", s, regex.U))
+
+ s = re.sub(r"\s+", " ", s) # replace any successive whitespace characters with a space
+
+ return s
+
+
+class EnglishNumberNormalizer:
+ """
+ Convert any spelled-out numbers into arabic numbers, while handling:
+
+ - remove any commas
+ - keep the suffixes such as: `1960s`, `274th`, `32nd`, etc.
+ - spell out currency symbols after the number. e.g. `$20 million` -> `20000000 dollars`
+ - spell out `one` and `ones`
+ - interpret successive single-digit numbers as nominal: `one oh one` -> `101`
+ """
+
+ def __init__(self):
+ super().__init__()
+
+ self.zeros = {"o", "oh", "zero"}
+ # fmt: off
+ self.ones = {
+ name: i
+ for i, name in enumerate(
+ ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"],
+ start=1,
+ )
+ }
+ # fmt: on
+ self.ones_plural = {
+ "sixes" if name == "six" else name + "s": (value, "s") for name, value in self.ones.items()
+ }
+ self.ones_ordinal = {
+ "zeroth": (0, "th"),
+ "first": (1, "st"),
+ "second": (2, "nd"),
+ "third": (3, "rd"),
+ "fifth": (5, "th"),
+ "twelfth": (12, "th"),
+ **{
+ name + ("h" if name.endswith("t") else "th"): (value, "th")
+ for name, value in self.ones.items()
+ if value > 3 and value != 5 and value != 12
+ },
+ }
+ self.ones_suffixed = {**self.ones_plural, **self.ones_ordinal}
+
+ self.tens = {
+ "twenty": 20,
+ "thirty": 30,
+ "forty": 40,
+ "fifty": 50,
+ "sixty": 60,
+ "seventy": 70,
+ "eighty": 80,
+ "ninety": 90,
+ }
+ self.tens_plural = {name.replace("y", "ies"): (value, "s") for name, value in self.tens.items()}
+ self.tens_ordinal = {name.replace("y", "ieth"): (value, "th") for name, value in self.tens.items()}
+ self.tens_suffixed = {**self.tens_plural, **self.tens_ordinal}
+
+ self.multipliers = {
+ "hundred": 100,
+ "thousand": 1_000,
+ "million": 1_000_000,
+ "billion": 1_000_000_000,
+ "trillion": 1_000_000_000_000,
+ "quadrillion": 1_000_000_000_000_000,
+ "quintillion": 1_000_000_000_000_000_000,
+ "sextillion": 1_000_000_000_000_000_000_000,
+ "septillion": 1_000_000_000_000_000_000_000_000,
+ "octillion": 1_000_000_000_000_000_000_000_000_000,
+ "nonillion": 1_000_000_000_000_000_000_000_000_000_000,
+ "decillion": 1_000_000_000_000_000_000_000_000_000_000_000,
+ }
+ self.multipliers_plural = {name + "s": (value, "s") for name, value in self.multipliers.items()}
+ self.multipliers_ordinal = {name + "th": (value, "th") for name, value in self.multipliers.items()}
+ self.multipliers_suffixed = {**self.multipliers_plural, **self.multipliers_ordinal}
+ self.decimals = {*self.ones, *self.tens, *self.zeros}
+
+ self.preceding_prefixers = {
+ "minus": "-",
+ "negative": "-",
+ "plus": "+",
+ "positive": "+",
+ }
+ self.following_prefixers = {
+ "pound": "£",
+ "pounds": "£",
+ "euro": "€",
+ "euros": "€",
+ "dollar": "$",
+ "dollars": "$",
+ "cent": "¢",
+ "cents": "¢",
+ }
+ self.prefixes = set(list(self.preceding_prefixers.values()) + list(self.following_prefixers.values()))
+ self.suffixers = {
+ "per": {"cent": "%"},
+ "percent": "%",
+ }
+ self.specials = {"and", "double", "triple", "point"}
+
+ self.words = {
+ key
+ for mapping in [
+ self.zeros,
+ self.ones,
+ self.ones_suffixed,
+ self.tens,
+ self.tens_suffixed,
+ self.multipliers,
+ self.multipliers_suffixed,
+ self.preceding_prefixers,
+ self.following_prefixers,
+ self.suffixers,
+ self.specials,
+ ]
+ for key in mapping
+ }
+ self.literal_words = {"one", "ones"}
+
+ def process_words(self, words: list[str]) -> Iterator[str]:
+ prefix: str | None = None
+ value: str | int | None = None
+ skip = False
+
+ def to_fraction(s: str):
+ try:
+ return Fraction(s)
+ except ValueError:
+ return None
+
+ def output(result: str | int):
+ nonlocal prefix, value
+ result = str(result)
+ if prefix is not None:
+ result = prefix + result
+ value = None
+ prefix = None
+ return result
+
+ if len(words) == 0:
+ return
+
+ for i, current in enumerate(words):
+ prev = words[i - 1] if i != 0 else None
+ next = words[i + 1] if i != len(words) - 1 else None
+ if skip:
+ skip = False
+ continue
+
+ next_is_numeric = next is not None and re.match(r"^\d+(\.\d+)?$", next)
+ has_prefix = current[0] in self.prefixes
+ current_without_prefix = current[1:] if has_prefix else current
+ if re.match(r"^\d+(\.\d+)?$", current_without_prefix):
+ # arabic numbers (potentially with signs and fractions)
+ f = to_fraction(current_without_prefix)
+ if f is None:
+ raise ValueError("Converting the fraction failed")
+
+ if value is not None:
+ if isinstance(value, str) and value.endswith("."):
+ # concatenate decimals / ip address components
+ value = str(value) + str(current)
+ continue
+ else:
+ yield output(value)
+
+ prefix = current[0] if has_prefix else prefix
+ if f.denominator == 1:
+ value = f.numerator # store integers as int
+ else:
+ value = current_without_prefix
+ elif current not in self.words:
+ # non-numeric words
+ if value is not None:
+ yield output(value)
+ yield output(current)
+ elif current in self.zeros:
+ value = str(value or "") + "0"
+ elif current in self.ones:
+ ones = self.ones[current]
+
+ if value is None:
+ value = ones
+ elif isinstance(value, str) or prev in self.ones:
+ if prev in self.tens and ones < 10: # replace the last zero with the digit
+ value = value[:-1] + str(ones)
+ else:
+ value = str(value) + str(ones)
+ elif ones < 10:
+ if value % 10 == 0:
+ value += ones
+ else:
+ value = str(value) + str(ones)
+ else: # eleven to nineteen
+ if value % 100 == 0:
+ value += ones
+ else:
+ value = str(value) + str(ones)
+ elif current in self.ones_suffixed:
+ # ordinal or cardinal; yield the number right away
+ ones, suffix = self.ones_suffixed[current]
+ if value is None:
+ yield output(str(ones) + suffix)
+ elif isinstance(value, str) or prev in self.ones:
+ if prev in self.tens and ones < 10:
+ yield output(value[:-1] + str(ones) + suffix)
+ else:
+ yield output(str(value) + str(ones) + suffix)
+ elif ones < 10:
+ if value % 10 == 0:
+ yield output(str(value + ones) + suffix)
+ else:
+ yield output(str(value) + str(ones) + suffix)
+ else: # eleven to nineteen
+ if value % 100 == 0:
+ yield output(str(value + ones) + suffix)
+ else:
+ yield output(str(value) + str(ones) + suffix)
+ value = None
+ elif current in self.tens:
+ tens = self.tens[current]
+ if value is None:
+ value = tens
+ elif isinstance(value, str):
+ value = str(value) + str(tens)
+ else:
+ if value % 100 == 0:
+ value += tens
+ else:
+ value = str(value) + str(tens)
+ elif current in self.tens_suffixed:
+ # ordinal or cardinal; yield the number right away
+ tens, suffix = self.tens_suffixed[current]
+ if value is None:
+ yield output(str(tens) + suffix)
+ elif isinstance(value, str):
+ yield output(str(value) + str(tens) + suffix)
+ else:
+ if value % 100 == 0:
+ yield output(str(value + tens) + suffix)
+ else:
+ yield output(str(value) + str(tens) + suffix)
+ elif current in self.multipliers:
+ multiplier = self.multipliers[current]
+ if value is None:
+ value = multiplier
+ elif isinstance(value, str) or value == 0:
+ f = to_fraction(value)
+ p = f * multiplier if f is not None else None
+ if f is not None and p.denominator == 1:
+ value = p.numerator
+ else:
+ yield output(value)
+ value = multiplier
+ else:
+ before = value // 1000 * 1000
+ residual = value % 1000
+ value = before + residual * multiplier
+ elif current in self.multipliers_suffixed:
+ multiplier, suffix = self.multipliers_suffixed[current]
+ if value is None:
+ yield output(str(multiplier) + suffix)
+ elif isinstance(value, str):
+ f = to_fraction(value)
+ p = f * multiplier if f is not None else None
+ if f is not None and p.denominator == 1:
+ yield output(str(p.numerator) + suffix)
+ else:
+ yield output(value)
+ yield output(str(multiplier) + suffix)
+ else: # int
+ before = value // 1000 * 1000
+ residual = value % 1000
+ value = before + residual * multiplier
+ yield output(str(value) + suffix)
+ value = None
+ elif current in self.preceding_prefixers:
+ # apply prefix (positive, minus, etc.) if it precedes a number
+ if value is not None:
+ yield output(value)
+
+ if next in self.words or next_is_numeric:
+ prefix = self.preceding_prefixers[current]
+ else:
+ yield output(current)
+ elif current in self.following_prefixers:
+ # apply prefix (dollars, cents, etc.) only after a number
+ if value is not None:
+ prefix = self.following_prefixers[current]
+ yield output(value)
+ else:
+ yield output(current)
+ elif current in self.suffixers:
+ # apply suffix symbols (percent -> '%')
+ if value is not None:
+ suffix = self.suffixers[current]
+ if isinstance(suffix, dict):
+ if next in suffix:
+ yield output(str(value) + suffix[next])
+ skip = True
+ else:
+ yield output(value)
+ yield output(current)
+ else:
+ yield output(str(value) + suffix)
+ else:
+ yield output(current)
+ elif current in self.specials:
+ if next not in self.words and not next_is_numeric:
+ # apply special handling only if the next word can be numeric
+ if value is not None:
+ yield output(value)
+ yield output(current)
+ elif current == "and":
+ # ignore "and" after hundreds, thousands, etc.
+ if prev not in self.multipliers:
+ if value is not None:
+ yield output(value)
+ yield output(current)
+ elif current == "double" or current == "triple":
+ if next in self.ones or next in self.zeros:
+ repeats = 2 if current == "double" else 3
+ ones = self.ones.get(next, 0)
+ value = str(value or "") + str(ones) * repeats
+ skip = True
+ else:
+ if value is not None:
+ yield output(value)
+ yield output(current)
+ elif current == "point":
+ if next in self.decimals or next_is_numeric:
+ value = str(value or "") + "."
+ else:
+ # should all have been covered at this point
+ raise ValueError(f"Unexpected token: {current}")
+ else:
+ # all should have been covered at this point
+ raise ValueError(f"Unexpected token: {current}")
+
+ if value is not None:
+ yield output(value)
+
+ def preprocess(self, s: str):
+ # replace " and a half" with " point five"
+ results = []
+
+ segments = re.split(r"\band\s+a\s+half\b", s)
+ for i, segment in enumerate(segments):
+ if len(segment.strip()) == 0:
+ continue
+ if i == len(segments) - 1:
+ results.append(segment)
+ else:
+ results.append(segment)
+ last_word = segment.rsplit(maxsplit=2)[-1]
+ if last_word in self.decimals or last_word in self.multipliers:
+ results.append("point five")
+ else:
+ results.append("and a half")
+
+ s = " ".join(results)
+
+ # put a space at number/letter boundary
+ s = re.sub(r"([a-z])([0-9])", r"\1 \2", s)
+ s = re.sub(r"([0-9])([a-z])", r"\1 \2", s)
+
+ # but remove spaces which could be a suffix
+ s = re.sub(r"([0-9])\s+(st|nd|rd|th|s)\b", r"\1\2", s)
+
+ return s
+
+ def postprocess(self, s: str):
+ def combine_cents(m: Match):
+ try:
+ currency = m.group(1)
+ integer = m.group(2)
+ cents = int(m.group(3))
+ return f"{currency}{integer}.{cents:02d}"
+ except ValueError:
+ return m.string
+
+ def extract_cents(m: Match):
+ try:
+ return f"¢{int(m.group(1))}"
+ except ValueError:
+ return m.string
+
+ # apply currency postprocessing; "$2 and ¢7" -> "$2.07"
+ s = re.sub(r"([€£$])([0-9]+) (?:and )?¢([0-9]{1,2})\b", combine_cents, s)
+ s = re.sub(r"[€£$]0.([0-9]{1,2})\b", extract_cents, s)
+
+ # write "one(s)" instead of "1(s)", just for the readability
+ s = re.sub(r"\b1(s?)\b", r"one\1", s)
+
+ return s
+
+ def __call__(self, s: str):
+ s = self.preprocess(s)
+ s = " ".join(word for word in self.process_words(s.split()) if word is not None)
+ s = self.postprocess(s)
+
+ return s
+
+
+class EnglishSpellingNormalizer:
+ """
+ Applies British-American spelling mappings as listed in [1].
+
+ [1] https://www.tysto.com/uk-us-spelling-list.html
+ """
+
+ def __init__(self, english_spelling_mapping):
+ self.mapping = english_spelling_mapping
+
+ def __call__(self, s: str):
+ return " ".join(self.mapping.get(word, word) for word in s.split())
+
+
+class EnglishTextNormalizer:
+ def __init__(self, english_spelling_mapping):
+ self.ignore_patterns = r"\b(hmm|mm|mhm|mmm|uh|um)\b"
+ self.replacers = {
+ # common contractions
+ r"\bwon't\b": "will not",
+ r"\bcan't\b": "can not",
+ r"\blet's\b": "let us",
+ r"\bain't\b": "aint",
+ r"\by'all\b": "you all",
+ r"\bwanna\b": "want to",
+ r"\bgotta\b": "got to",
+ r"\bgonna\b": "going to",
+ r"\bi'ma\b": "i am going to",
+ r"\bimma\b": "i am going to",
+ r"\bwoulda\b": "would have",
+ r"\bcoulda\b": "could have",
+ r"\bshoulda\b": "should have",
+ r"\bma'am\b": "madam",
+ # contractions in titles/prefixes
+ r"\bmr\b": "mister ",
+ r"\bmrs\b": "missus ",
+ r"\bst\b": "saint ",
+ r"\bdr\b": "doctor ",
+ r"\bprof\b": "professor ",
+ r"\bcapt\b": "captain ",
+ r"\bgov\b": "governor ",
+ r"\bald\b": "alderman ",
+ r"\bgen\b": "general ",
+ r"\bsen\b": "senator ",
+ r"\brep\b": "representative ",
+ r"\bpres\b": "president ",
+ r"\brev\b": "reverend ",
+ r"\bhon\b": "honorable ",
+ r"\basst\b": "assistant ",
+ r"\bassoc\b": "associate ",
+ r"\blt\b": "lieutenant ",
+ r"\bcol\b": "colonel ",
+ r"\bjr\b": "junior ",
+ r"\bsr\b": "senior ",
+ r"\besq\b": "esquire ",
+ # prefect tenses, ideally it should be any past participles, but it's harder..
+ r"'d been\b": " had been",
+ r"'s been\b": " has been",
+ r"'d gone\b": " had gone",
+ r"'s gone\b": " has gone",
+ r"'d done\b": " had done", # "'s done" is ambiguous
+ r"'s got\b": " has got",
+ # general contractions
+ r"n't\b": " not",
+ r"'re\b": " are",
+ r"'s\b": " is",
+ r"'d\b": " would",
+ r"'ll\b": " will",
+ r"'t\b": " not",
+ r"'ve\b": " have",
+ r"'m\b": " am",
+ }
+ self.standardize_numbers = EnglishNumberNormalizer()
+ self.standardize_spellings = EnglishSpellingNormalizer(english_spelling_mapping)
+
+ def __call__(self, s: str):
+ s = s.lower()
+
+ s = re.sub(r"[<\[][^>\]]*[>\]]", "", s) # remove words between brackets
+ s = re.sub(r"\(([^)]+?)\)", "", s) # remove words between parenthesis
+ s = re.sub(self.ignore_patterns, "", s)
+ s = re.sub(r"\s+'", "'", s) # standardize when there's a space before an apostrophe
+
+ for pattern, replacement in self.replacers.items():
+ s = re.sub(pattern, replacement, s)
+
+ s = re.sub(r"(\d),(\d)", r"\1\2", s) # remove commas between digits
+ s = re.sub(r"\.([^0-9]|$)", r" \1", s) # remove periods not followed by numbers
+ s = remove_symbols_and_diacritics(s, keep=".%$¢€£") # keep some symbols for numerics
+
+ s = self.standardize_numbers(s)
+ s = self.standardize_spellings(s)
+
+ # now remove prefix/suffix symbols that are not preceded/followed by numbers
+ s = re.sub(r"[.$¢€£]([^0-9])", r" \1", s)
+ s = re.sub(r"([^0-9])%", r"\1 ", s)
+
+ s = re.sub(r"\s+", " ", s) # replace any successive whitespace characters with a space
+
+ return s
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/whisper/feature_extraction_whisper.py b/.venv/lib/python3.12/site-packages/transformers/models/whisper/feature_extraction_whisper.py
new file mode 100644
index 0000000000000000000000000000000000000000..4151a3824dfdbf3b0fdb6339e71f11e32b5783a8
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/whisper/feature_extraction_whisper.py
@@ -0,0 +1,345 @@
+# Copyright 2022 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Feature extractor class for Whisper
+"""
+
+import numpy as np
+
+from ... import is_torch_available
+from ...audio_utils import mel_filter_bank, spectrogram, window_function
+from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
+from ...feature_extraction_utils import BatchFeature
+from ...utils import TensorType, logging
+
+
+if is_torch_available():
+ import torch
+
+logger = logging.get_logger(__name__)
+
+
+class WhisperFeatureExtractor(SequenceFeatureExtractor):
+ r"""
+ Constructs a Whisper feature extractor.
+
+ This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExtractor`] which contains
+ most of the main methods. Users should refer to this superclass for more information regarding those methods.
+
+ This class extracts mel-filter bank features from raw speech using a custom numpy implementation of the `Short Time
+ Fourier Transform` which should match pytorch's `torch.stft` equivalent.
+
+ Args:
+ feature_size (`int`, *optional*, defaults to 80):
+ The feature dimension of the extracted features.
+ sampling_rate (`int`, *optional*, defaults to 16000):
+ The sampling rate at which the audio files should be digitalized expressed in hertz (Hz).
+ hop_length (`int`, *optional*, defaults to 160):
+ Length of the overlapping windows for the STFT used to obtain the Mel Frequency coefficients.
+ chunk_length (`int`, *optional*, defaults to 30):
+ The maximum number of chunks of `sampling_rate` samples used to trim and pad longer or shorter audio
+ sequences.
+ n_fft (`int`, *optional*, defaults to 400):
+ Size of the Fourier transform.
+ padding_value (`float`, *optional*, defaults to 0.0):
+ Padding value used to pad the audio. Should correspond to silences.
+ dither (`float`, *optional*, defaults to 0.0):
+ Adds dithering. In other words, adds a small Gaussian noise to each frame.
+ E.g. use 0.0001 to add dithering with a normal distribution centered
+ around 0.0 with standard deviation 0.0001 (assuming [-1,+1] range of raw_speech).
+ The value 0.0 means no dithering.
+ Dithering has similar effect as `spectrogram(mel_floor=...)`. It reduces
+ the high log_mel_fbank values for signals with hard-zero sections,
+ when VAD cutoff is present in the signal.
+ """
+
+ model_input_names = ["input_features"]
+
+ def __init__(
+ self,
+ feature_size=80,
+ sampling_rate=16000,
+ hop_length=160,
+ chunk_length=30,
+ n_fft=400,
+ padding_value=0.0,
+ dither=0.0,
+ return_attention_mask=False, # pad inputs to max length with silence token (zero) and no attention mask
+ **kwargs,
+ ):
+ super().__init__(
+ feature_size=feature_size,
+ sampling_rate=sampling_rate,
+ padding_value=padding_value,
+ return_attention_mask=return_attention_mask,
+ **kwargs,
+ )
+ self.n_fft = n_fft
+ self.hop_length = hop_length
+ self.chunk_length = chunk_length
+ self.n_samples = chunk_length * sampling_rate
+ self.nb_max_frames = self.n_samples // hop_length
+ self.sampling_rate = sampling_rate
+ self.dither = dither
+ self.mel_filters = mel_filter_bank(
+ num_frequency_bins=1 + n_fft // 2,
+ num_mel_filters=feature_size,
+ min_frequency=0.0,
+ max_frequency=8000.0,
+ sampling_rate=sampling_rate,
+ norm="slaney",
+ mel_scale="slaney",
+ )
+
+ def _np_extract_fbank_features(self, waveform_batch: np.ndarray, device: str) -> np.ndarray:
+ """
+ Compute the log-mel spectrogram of the provided audio, gives similar results to Whisper's original torch
+ implementation with 1e-5 tolerance.
+ """
+ if device != "cpu":
+ raise ValueError(
+ f"Got device `{device}` for feature extraction, but feature extraction on CUDA accelerator "
+ "devices requires torch, which is not installed. Either set `device='cpu'`, or "
+ "install torch according to the official instructions: https://pytorch.org/get-started/locally/"
+ )
+ log_spec_batch = []
+ for waveform in waveform_batch:
+ log_spec = spectrogram(
+ waveform,
+ window_function(self.n_fft, "hann"),
+ frame_length=self.n_fft,
+ hop_length=self.hop_length,
+ power=2.0,
+ dither=self.dither,
+ mel_filters=self.mel_filters,
+ log_mel="log10",
+ )
+ log_spec = log_spec[:, :-1]
+ log_spec = np.maximum(log_spec, log_spec.max() - 8.0)
+ log_spec = (log_spec + 4.0) / 4.0
+ log_spec_batch.append(log_spec)
+ log_spec_batch = np.array(log_spec_batch)
+ return log_spec_batch
+
+ def _torch_extract_fbank_features(self, waveform: np.ndarray, device: str = "cpu") -> np.ndarray:
+ """
+ Compute the log-mel spectrogram of the audio using PyTorch's GPU-accelerated STFT implementation with batching,
+ yielding results similar to cpu computing with 1e-5 tolerance.
+ """
+ waveform = torch.from_numpy(waveform).to(device, torch.float32)
+ window = torch.hann_window(self.n_fft, device=device)
+
+ # Note: it would be better to dither the chunked waveform,
+ # so overlapping signal does not get the same dithering.
+ # But, chunking is happening inside pytorch, so it is here.
+ if self.dither != 0.0:
+ waveform += self.dither * torch.randn(waveform.shape, dtype=waveform.dtype, device=waveform.device)
+
+ stft = torch.stft(waveform, self.n_fft, self.hop_length, window=window, return_complex=True)
+ magnitudes = stft[..., :-1].abs() ** 2
+
+ mel_filters = torch.from_numpy(self.mel_filters).to(device, torch.float32)
+ mel_spec = mel_filters.T @ magnitudes
+
+ log_spec = torch.clamp(mel_spec, min=1e-10).log10()
+ if waveform.dim() == 2:
+ max_val = log_spec.max(dim=2, keepdim=True)[0].max(dim=1, keepdim=True)[0]
+ log_spec = torch.maximum(log_spec, max_val - 8.0)
+ else:
+ log_spec = torch.maximum(log_spec, log_spec.max() - 8.0)
+ log_spec = (log_spec + 4.0) / 4.0
+ if device != "cpu":
+ log_spec = log_spec.detach().cpu()
+ return log_spec.numpy()
+
+ @staticmethod
+ # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
+ def zero_mean_unit_var_norm(
+ input_values: list[np.ndarray], attention_mask: list[np.ndarray], padding_value: float = 0.0
+ ) -> list[np.ndarray]:
+ """
+ Every array in the list is normalized to have zero mean and unit variance
+ """
+ if attention_mask is not None:
+ attention_mask = np.array(attention_mask, np.int32)
+ normed_input_values = []
+
+ for vector, length in zip(input_values, attention_mask.sum(-1)):
+ normed_slice = (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7)
+ if length < normed_slice.shape[0]:
+ normed_slice[length:] = padding_value
+
+ normed_input_values.append(normed_slice)
+ else:
+ normed_input_values = [(x - x.mean()) / np.sqrt(x.var() + 1e-7) for x in input_values]
+
+ return normed_input_values
+
+ def __call__(
+ self,
+ raw_speech: np.ndarray | list[float] | list[np.ndarray] | list[list[float]],
+ truncation: bool = True,
+ pad_to_multiple_of: int | None = None,
+ return_tensors: str | TensorType | None = None,
+ return_attention_mask: bool | None = None,
+ padding: str | None = "max_length",
+ max_length: int | None = None,
+ sampling_rate: int | None = None,
+ do_normalize: bool | None = None,
+ device: str | None = "cpu",
+ **kwargs,
+ ) -> BatchFeature:
+ """Main method to featurize and prepare for the model one or several sequence(s). Implementation uses PyTorch
+ for the STFT computation if available, otherwise a slower NumPy based one.
+
+ Args:
+ raw_speech (`np.ndarray`, `list[float]`, `list[np.ndarray]`, `list[list[float]]`):
+ The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float
+ values, a list of numpy arrays or a list of list of float values. Must be mono channel audio, not
+ stereo, i.e. single float per timestep.
+ truncation (`bool`, *optional*, default to `True`):
+ Activates truncation to cut input sequences longer than *max_length* to *max_length*.
+ pad_to_multiple_of (`int`, *optional*, defaults to None):
+ If set will pad the sequence to a multiple of the provided value.
+
+ This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
+ `>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128.
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
+ If set, will return tensors instead of list of python integers. Acceptable values are:
+
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
+ - `'np'`: Return Numpy `np.ndarray` objects.
+ return_attention_mask (`bool`, *optional*):
+ Whether to return the attention mask. If left to the default, will return the attention mask according
+ to the specific feature_extractor's default.
+
+ [What are attention masks?](../glossary#attention-mask)
+
+
+
+ For Whisper models, `attention_mask` should always be passed for batched inference, to avoid subtle
+ bugs.
+
+
+ padding (`str` or [`~utils.PaddingStrategy`], *optional*, defaults to `'max_length'`):
+ Activates and controls padding. Accepts the following values:
+
+ - `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence is
+ provided).
+ - `'max_length'` (default): Pad to a maximum length specified with the argument `max_length` or to the
+ maximum acceptable input length for the model if that argument is not provided.
+ - `'do_not_pad'`: No padding (i.e., can output a batch with sequences of different lengths).
+ max_length (`int`, *optional*):
+ Controls the maximum length to use by one of the truncation/padding parameters.
+
+ If left unset or set to `None`, this will use the predefined model maximum length if a maximum length
+ is required by one of the truncation/padding parameters. If the model has no specific maximum input
+ length (like XLNet) truncation/padding to a maximum length will be deactivated.
+ sampling_rate (`int`, *optional*):
+ The sampling rate at which the `raw_speech` input was sampled. It is strongly recommended to pass
+ `sampling_rate` at the forward call to prevent silent errors and allow automatic speech recognition
+ pipeline.
+ do_normalize (`bool`, *optional*, defaults to `False`):
+ Whether or not to zero-mean unit-variance normalize the input. Normalizing can help to significantly
+ improve the performance of the model.
+ device (`str`, *optional*, defaults to `'cpu'`):
+ Specifies the device for computation of the log-mel spectrogram of audio signals in the
+ `_torch_extract_fbank_features` method. (e.g., "cpu", "cuda")
+ **kwargs: Not supported by WhisperFeatureExtractor.__call__() and ignored.
+ """
+ if sampling_rate is not None:
+ if sampling_rate != self.sampling_rate:
+ raise ValueError(
+ f"The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a"
+ f" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input"
+ f" was sampled with {self.sampling_rate} and not {sampling_rate}."
+ )
+ else:
+ logger.warning(
+ f"It is strongly recommended to pass the `sampling_rate` argument to `{self.__class__.__name__}()`. "
+ "Failing to do so can result in silent errors that might be hard to debug."
+ )
+
+ is_batched_numpy = isinstance(raw_speech, np.ndarray) and len(raw_speech.shape) > 1
+ if is_batched_numpy and len(raw_speech.shape) > 2:
+ raise ValueError(f"Only mono-channel audio is supported for input to {self}")
+ is_batched = is_batched_numpy or (
+ isinstance(raw_speech, (list, tuple)) and (isinstance(raw_speech[0], (np.ndarray, tuple, list)))
+ )
+
+ if is_batched:
+ raw_speech = [np.asarray([speech], dtype=np.float32).T for speech in raw_speech]
+ elif not is_batched and not isinstance(raw_speech, np.ndarray):
+ raw_speech = np.asarray(raw_speech, dtype=np.float32)
+ elif isinstance(raw_speech, np.ndarray) and raw_speech.dtype is np.dtype(np.float64):
+ raw_speech = raw_speech.astype(np.float32)
+
+ # always return batch
+ if not is_batched:
+ raw_speech = [np.asarray([raw_speech]).T]
+
+ batched_speech = BatchFeature({"input_features": raw_speech})
+
+ # convert into correct format for padding
+
+ padded_inputs = self.pad(
+ batched_speech,
+ padding=padding,
+ max_length=max_length if max_length else self.n_samples,
+ truncation=truncation,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_attention_mask=return_attention_mask or do_normalize,
+ )
+
+ # zero-mean and unit-variance normalization
+ if do_normalize:
+ padded_inputs["input_features"] = self.zero_mean_unit_var_norm(
+ padded_inputs["input_features"],
+ attention_mask=padded_inputs["attention_mask"],
+ padding_value=self.padding_value,
+ )
+ padded_inputs["input_features"] = np.stack(padded_inputs["input_features"], axis=0)
+
+ # make sure list is in array format
+ input_features = padded_inputs.get("input_features").transpose(2, 0, 1)
+
+ extract_fbank_features = (
+ self._torch_extract_fbank_features if is_torch_available() else self._np_extract_fbank_features
+ )
+ input_features = extract_fbank_features(input_features[0], device)
+
+ if isinstance(input_features[0], list):
+ padded_inputs["input_features"] = [np.asarray(feature, dtype=np.float32) for feature in input_features]
+
+ else:
+ padded_inputs["input_features"] = input_features
+
+ if return_attention_mask:
+ # rescale from sample (48000) to feature (3000)
+ rescaled_attention_mask = padded_inputs["attention_mask"][:, :: self.hop_length]
+
+ # The STFT computation produces L//hop_length + 1 frames, but we skip the last frame (see `_torch_extract_fbank_features`).
+ # This means we need to trim the rescaled attention mask to match the actual number of frames (L//hop_length) when the input length
+ # is not perfectly divisible by the hop length.
+ if padded_inputs["attention_mask"].shape[1] % self.hop_length != 0:
+ rescaled_attention_mask = rescaled_attention_mask[:, :-1]
+ padded_inputs["attention_mask"] = rescaled_attention_mask
+
+ if return_tensors is not None:
+ padded_inputs = padded_inputs.convert_to_tensors(return_tensors)
+
+ return padded_inputs
+
+
+__all__ = ["WhisperFeatureExtractor"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/whisper/generation_whisper.py b/.venv/lib/python3.12/site-packages/transformers/models/whisper/generation_whisper.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f9c9843d34a3887c1f75cef092b53b8a8365f3a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/whisper/generation_whisper.py
@@ -0,0 +1,2073 @@
+# Copyright 2024 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import copy
+import math
+import zlib
+from collections.abc import Callable, Iterator
+
+import numpy as np
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+from transformers.cache_utils import EncoderDecoderCache
+
+from ...generation import GenerationConfig, GenerationMixin
+from ...generation.logits_process import (
+ LogitsProcessorList,
+ SuppressTokensAtBeginLogitsProcessor,
+ SuppressTokensLogitsProcessor,
+ WhisperNoSpeechDetection,
+ WhisperTimeStampLogitsProcessor,
+)
+from ...generation.stopping_criteria import StoppingCriteriaList
+from ...modeling_outputs import BaseModelOutput
+from ...utils import logging
+from .tokenization_whisper import TASK_IDS, TO_LANGUAGE_CODE
+
+
+logger = logging.get_logger(__name__)
+
+
+def _median_filter(inputs: torch.Tensor, filter_width: int) -> torch.Tensor:
+ """
+ Applies a median filter of width `filter_width` along the last dimension of the input.
+
+ The `inputs` tensor is assumed to be 3- or 4-dimensional.
+ """
+ if filter_width <= 0 or filter_width % 2 != 1:
+ raise ValueError("`filter_width` should be an odd number")
+
+ pad_width = filter_width // 2
+ if inputs.shape[-1] <= pad_width:
+ return inputs
+
+ # Pad the left and right edges.
+ inputs = nn.functional.pad(inputs, (pad_width, pad_width, 0, 0), mode="reflect")
+
+ # sort() is faster than torch.median (https://github.com/pytorch/pytorch/issues/51450)
+ result = inputs.unfold(-1, filter_width, 1).sort()[0][..., pad_width]
+ return result
+
+
+def _dynamic_time_warping(matrix: np.ndarray):
+ """
+ Measures similarity between two temporal sequences: the input audio and the output tokens. Used to generate
+ token-level timestamps.
+ """
+ output_length, input_length = matrix.shape
+ cost = np.ones((output_length + 1, input_length + 1), dtype=np.float32) * np.inf
+ trace = -np.ones((output_length + 1, input_length + 1), dtype=np.float32)
+
+ cost[0, 0] = 0
+ for j in range(1, input_length + 1):
+ for i in range(1, output_length + 1):
+ c0 = cost[i - 1, j - 1]
+ c1 = cost[i - 1, j]
+ c2 = cost[i, j - 1]
+
+ if c0 < c1 and c0 < c2:
+ c, t = c0, 0
+ elif c1 < c0 and c1 < c2:
+ c, t = c1, 1
+ else:
+ c, t = c2, 2
+
+ cost[i, j] = matrix[i - 1, j - 1] + c
+ trace[i, j] = t
+
+ # backtrace
+ i = trace.shape[0] - 1
+ j = trace.shape[1] - 1
+ trace[0, :] = 2
+ trace[:, 0] = 1
+
+ text_indices = []
+ time_indices = []
+ while i > 0 or j > 0:
+ text_indices.append(i - 1)
+ time_indices.append(j - 1)
+ if trace[i, j] == 0:
+ i -= 1
+ j -= 1
+ elif trace[i, j] == 1:
+ i -= 1
+ elif trace[i, j] == 2:
+ j -= 1
+ else:
+ raise RuntimeError(
+ f"Internal error in dynamic time warping. Unexpected trace[{i}, {j}]. Please file a bug report."
+ )
+
+ text_indices = np.array(text_indices)[::-1]
+ time_indices = np.array(time_indices)[::-1]
+ return text_indices, time_indices
+
+
+def _get_attr_from_logit_processors(logits_processor, logit_processor_class, attribute_name):
+ if logits_processor is not None:
+ logit_processor = next((cls for cls in logits_processor if isinstance(cls, logit_processor_class)), None)
+ if logit_processor:
+ return getattr(logit_processor, attribute_name, None)
+ return None
+
+
+def _pad_to_max_length(
+ current_segments,
+ pad_token_id,
+ device,
+ padding_side="right",
+ padding="longest",
+ bos_token_tensor=None,
+ cut_off_length=None,
+ return_token_timestamps=False,
+ force_unique_generate_call=False,
+ skip_ending_double_timestamps=False,
+ timestamp_begin=None,
+):
+ """
+ skip_ending_double_timestamps: when the segment ended with two timestamp tokens, whether to ignore the last timestamp token
+ see https://github.com/huggingface/transformers/pull/35750
+
+ _pad_to_max_length is used in different contexts:
+ 1. At the end of generation: we need to keep both ending timestamp tokens in the segment (see https://github.com/huggingface/transformers/pull/34537).
+ 2. In the middle of generation, e.g. when condition_on_prev_tokens=True and we want to use the last generated tokens as decoder_input_ids:
+ we must skip one of the double ending timestamp tokens (see https://github.com/huggingface/transformers/pull/35750).
+ """
+ max_total_length = 0
+ sequences = []
+ token_timestamps_list = []
+
+ if padding_side not in ["right", "left"]:
+ raise ValueError(f"`padding_side` must be either 'right' or 'left', not {padding_side}")
+
+ if padding not in ["longest", "max_length"]:
+ raise ValueError(f"`padding` must be either 'longest' or 'max_length', not {padding}")
+ elif padding == "max_length" and cut_off_length is None:
+ raise ValueError("`cut_off_length` must be specified when `padding='max_length'`")
+
+ if force_unique_generate_call:
+ sequences_list = []
+ timestamps_list = []
+ for segments in current_segments:
+ result = segments[0]["result"]
+ sequences_list.append(result if isinstance(result, torch.Tensor) else result["sequences"])
+ if return_token_timestamps:
+ timestamps_list.append(result["token_timestamps"])
+
+ sequences = torch.stack(sequences_list, dim=0)
+ if return_token_timestamps:
+ token_timestamps = torch.stack(timestamps_list, dim=0)
+ return sequences, token_timestamps
+ return sequences
+
+ for current_segment_list in current_segments:
+ if current_segment_list is not None and len([d["tokens"] for d in current_segment_list]) > 0:
+ sequences_list = []
+ for d in current_segment_list:
+ if skip_ending_double_timestamps and len(d["tokens"]) > 2 and d["tokens"][-2] >= timestamp_begin:
+ # the segment finishes with two timestamp tokens
+ # we need to ignore the last timestamp token
+ # see https://github.com/huggingface/transformers/pull/34537
+ sequences_list.append(d["tokens"][:-1])
+ else:
+ sequences_list.append(d["tokens"])
+ sequence = torch.cat(sequences_list, dim=-1)
+
+ if return_token_timestamps:
+ token_timestamps = torch.cat(
+ [d["result"]["token_timestamps"][d["idxs"][0] : d["idxs"][1]] for d in current_segment_list],
+ dim=-1,
+ )
+
+ if cut_off_length is not None:
+ sequence = sequence[-cut_off_length:]
+ if return_token_timestamps:
+ token_timestamps = token_timestamps[-cut_off_length:]
+
+ if bos_token_tensor is not None:
+ sequence = torch.cat([bos_token_tensor, sequence])
+ if return_token_timestamps:
+ token_timestamps = torch.cat(
+ [torch.ones_like(bos_token_tensor, device=device) * 0.0, token_timestamps]
+ )
+ sequences.append(sequence)
+ if return_token_timestamps:
+ token_timestamps_list.append(token_timestamps)
+ max_total_length = max(max_total_length, len(sequences[-1]))
+ elif bos_token_tensor is not None:
+ sequences.append(bos_token_tensor)
+ if return_token_timestamps:
+ token_timestamps_list.append(torch.ones_like(bos_token_tensor, device=device) * 0.0)
+ else:
+ sequences.append(torch.tensor([], device=device))
+ if return_token_timestamps:
+ token_timestamps_list.append(torch.tensor([], device=device))
+
+ max_total_length = cut_off_length + 1 if padding == "max_length" else max_total_length
+ for i in range(len(current_segments)):
+ pad_length = max_total_length - len(sequences[i])
+ pad = (0, pad_length) if padding_side == "right" else (pad_length, 0)
+
+ sequences[i] = F.pad(sequences[i], pad=pad, value=pad_token_id)
+ if return_token_timestamps:
+ token_timestamps_list[i] = F.pad(
+ token_timestamps_list[i],
+ pad=pad,
+ value=token_timestamps_list[i][-1] if len(token_timestamps_list[i]) > 0 else 0.0,
+ )
+
+ sequences = torch.stack(sequences, dim=0)
+
+ if return_token_timestamps:
+ token_timestamps = torch.stack(token_timestamps_list, dim=0)
+ return sequences, token_timestamps
+ else:
+ return sequences
+
+
+class WhisperGenerationMixin(GenerationMixin):
+ def _extract_token_timestamps(
+ self, generate_outputs, alignment_heads, time_precision=0.02, num_frames=None, num_input_ids=None
+ ):
+ """
+ Calculates token-level timestamps using the encoder-decoder cross-attentions and dynamic time-warping (DTW) to
+ map each output token to a position in the input audio. If `num_frames` is specified, the encoder-decoder
+ cross-attentions will be cropped before applying DTW.
+
+ Returns:
+ tensor containing the timestamps in seconds for each predicted token
+ """
+ # Create a list with `decoder_layers` elements, each a tensor of shape
+ # (batch size * num beams, attention_heads, output length, input length).
+ cross_attentions = []
+ for i in range(self.config.decoder_layers):
+ cross_attentions.append(torch.cat([x[i] for x in generate_outputs.cross_attentions], dim=2))
+
+ # Select specific cross-attention layers and heads. This is a tensor
+ # of shape (batch size * num beams, num selected heads, output length, input length).
+ weights = torch.stack([cross_attentions[l][:, h] for l, h in alignment_heads])
+ weights = weights.permute([1, 0, 2, 3])
+
+ weight_length = None
+
+ if "beam_indices" in generate_outputs:
+ # If beam search was used, the sequence length of the outputs may not be the real sequence length:
+ # beam search may end up returning a sequence that finished a few steps earlier while decoding.
+ # In that case, the `cross_attentions` weights are too long and we have to make sure that they have
+ # the right `output_length`
+
+ # get the real sequence length of the longest sequence, crop the beam_indices to the real length
+ weight_length = (generate_outputs.beam_indices != -1).sum(-1).max()
+ beam_indices = generate_outputs.beam_indices[:, :weight_length]
+
+ # The first forward pass (prefill) may have processed more than one token and, therefore, contain
+ # cross-attention weights for several tokens.
+ # Let's unroll the first `beam_indices` accordingly, so we can use it to gather the weights.
+ if num_input_ids is not None and num_input_ids > 1:
+ # `-1`: `beam_indices` can be used as-is to gather the weights when `num_input_ids` is 1
+ weight_length += num_input_ids - 1
+ beam_indices_first_step_unrolled = (
+ torch.ones(beam_indices.shape[0], num_input_ids - 1, device=beam_indices.device, dtype=torch.long)
+ * (beam_indices[:, 0:1])
+ )
+ unrolled_beam_indices = torch.cat([beam_indices_first_step_unrolled, beam_indices], dim=-1)
+ else:
+ unrolled_beam_indices = beam_indices
+
+ # If beam index is still -1, it means that the associated token id is EOS
+ # We need to replace the index with 0 since index_select gives an error if any of the indexes is -1.
+ unrolled_beam_indices = unrolled_beam_indices.masked_fill(unrolled_beam_indices == -1, 0)
+
+ # Select the cross attention from the right beam for each output sequence, up to the real sequence
+ # length (`weight_length`)
+ weights = torch.stack(
+ [
+ torch.index_select(weights[:, :, i, :], dim=0, index=unrolled_beam_indices[:, i])
+ for i in range(unrolled_beam_indices.shape[1])
+ ],
+ dim=2,
+ )
+
+ # make sure timestamps are as long as weights
+ input_length = weight_length or cross_attentions[0].shape[2]
+ batch_size = generate_outputs.sequences.shape[0]
+ timestamps = torch.zeros(
+ (batch_size, input_length + 1), dtype=torch.float32, device=generate_outputs.sequences.device
+ )
+
+ if num_frames is not None:
+ # two cases:
+ # 1. num_frames is the same for each sample -> compute the DTW matrix for each sample in parallel
+ # 2. num_frames is different, compute the DTW matrix for each sample sequentially
+
+ # we're using np.unique because num_frames can be int/list/tuple
+ if isinstance(num_frames, int):
+ weights = weights[..., : num_frames // 2]
+
+ elif isinstance(num_frames, (list, tuple, np.ndarray)) and len(np.unique(num_frames)) == 1:
+ weights = weights[..., : num_frames[0] // 2]
+
+ elif isinstance(num_frames, (torch.Tensor)) and len(torch.unique(num_frames)) == 1:
+ weights = weights[..., : num_frames[0] // 2]
+
+ else:
+ # num_frames is of shape (batch_size,) whereas batch_size is truly batch_size*num_return_sequences
+ repeat_time = batch_size if isinstance(num_frames, int) else batch_size // len(num_frames)
+ num_frames = num_frames.cpu() if isinstance(num_frames, (torch.Tensor)) else num_frames
+ num_frames = np.repeat(num_frames, repeat_time)
+
+ # let's ignore decoder_input_ids that can negatively impact the DTW while we know they have timestamps 0.0s
+ # (they are not taken into account for the DTW in OAI implementation)
+ if num_input_ids is not None:
+ weights = weights[:, :, num_input_ids:, :]
+
+ # Since we ignore `decoder_input_ids` in the DTW and in the case where we generated only one token (for which we don't have cross attentions, see below comments),
+ # the DTW sequence length is 0 and we should return only 0.0s for the token timestamps
+ if weights.shape[2] == 0:
+ return timestamps
+
+ if num_frames is None or isinstance(num_frames, int):
+ # Normalize and smoothen the weights.
+ std = torch.std(weights, dim=-2, keepdim=True, unbiased=False)
+ mean = torch.mean(weights, dim=-2, keepdim=True)
+ weights = (weights - mean) / std
+ weights = _median_filter(weights, self.config.median_filter_width)
+
+ # Average the different cross-attention heads.
+ weights = weights.mean(dim=1)
+
+ # Perform dynamic time warping on each element of the batch.
+ for batch_idx in range(batch_size):
+ if num_frames is not None and isinstance(num_frames, (tuple, list, np.ndarray, torch.Tensor)):
+ matrix = weights[batch_idx, ..., : num_frames[batch_idx] // 2]
+
+ # Normalize and smoothen the weights.
+ std = torch.std(matrix, dim=-2, keepdim=True, unbiased=False)
+ mean = torch.mean(matrix, dim=-2, keepdim=True)
+ matrix = (matrix - mean) / std
+ matrix = _median_filter(matrix, self.config.median_filter_width)
+
+ # Average the different cross-attention heads.
+ matrix = matrix.mean(dim=0)
+ else:
+ matrix = weights[batch_idx]
+
+ text_indices, time_indices = _dynamic_time_warping(-matrix.cpu().double().numpy())
+ jumps = np.pad(np.diff(text_indices), (1, 0), constant_values=1).astype(bool)
+ jump_times = time_indices[jumps] * time_precision
+
+ # each predicted token has a corresponding timestamp, expect the eos token (or last predicted token) for which we don't retrieve cross attentions
+ # (indeed contrary to OAI that re-run a full forward to retrieve cross attentions for each token and therefore also the last one predicted, we retrieve
+ # cross attentions directly from the auto-regressive generation, so we don't have cross attentiosn for the token at the end of the sequence. Nevertheless,
+ # that is not important since we expect this last token to be the eos token)
+ # 1. for decoder_input_ids, we set the timestamps to 0.0
+ # 2. for the eos token (or last predicted token), we simply duplicate the timestamp of the last non-eos token
+ timestamps[batch_idx] = torch.cat(
+ [torch.zeros(num_input_ids), torch.tensor(jump_times), torch.tensor([jump_times[-1]])]
+ )
+
+ return timestamps
+
+ def generate(
+ self,
+ input_features: torch.Tensor | None = None,
+ generation_config: GenerationConfig | None = None,
+ logits_processor: LogitsProcessorList | None = None,
+ stopping_criteria: StoppingCriteriaList | None = None,
+ prefix_allowed_tokens_fn: Callable[[int, torch.Tensor], list[int]] | None = None,
+ synced_gpus: bool = False,
+ return_timestamps: bool | None = None,
+ task: str | None = None,
+ language: str | list[str] | None = None,
+ is_multilingual: bool | None = None,
+ prompt_ids: torch.Tensor | None = None,
+ prompt_condition_type: str | None = None, # first-segment, all-segments
+ condition_on_prev_tokens: bool | None = None,
+ temperature: float | tuple[float, ...] | None = None,
+ compression_ratio_threshold: float | None = None,
+ logprob_threshold: float | None = None,
+ no_speech_threshold: float | None = None,
+ num_segment_frames: int | None = None,
+ attention_mask: torch.Tensor | None = None,
+ time_precision: float = 0.02,
+ time_precision_features: float = 0.01,
+ return_token_timestamps: bool | None = None,
+ return_segments: bool = False,
+ return_dict_in_generate: bool | None = None,
+ force_unique_generate_call: bool | None = None,
+ monitor_progress: Callable[[torch.Tensor], None] | None = None,
+ **kwargs,
+ ):
+ """
+ Transcribes or translates log-mel input features to a sequence of auto-regressively generated token ids.
+
+
+
+ Most generation-controlling parameters are set in `generation_config` which, if not passed, will be set to the
+ model's default generation configuration. You can override any `generation_config` by passing the corresponding
+ parameters to generate(), e.g. `.generate(inputs, num_beams=4, do_sample=True)`.
+
+ For an overview of generation strategies and code examples, check out the [following
+ guide](../generation_strategies).
+
+
+
+ Parameters:
+ input_features (`torch.Tensor` of shape `(batch_size, feature_size, sequence_length)`, *optional*):
+ Float values of log-mel features extracted from the raw speech waveform. The raw speech waveform can be obtained by
+ loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`,
+ *e.g.* via the torchcodec library (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
+ To prepare the array into `input_features`, the [`AutoFeatureExtractor`] should be used for extracting the mel
+ features, padding and conversion into a tensor of type `torch.FloatTensor`.
+ See [`~WhisperFeatureExtractor.__call__`] for details.
+ generation_config ([`~generation.GenerationConfig`], *optional*):
+ The generation configuration to be used as base parametrization for the generation call. `**kwargs`
+ passed to generate matching the attributes of `generation_config` will override them. If
+ `generation_config` is not provided, the default will be used, which had the following loading
+ priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model
+ configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s
+ default values, whose documentation should be checked to parameterize generation.
+ logits_processor (`LogitsProcessorList`, *optional*):
+ Custom logits processors that complement the default logits processors built from arguments and
+ generation config. If a logit processor is passed that is already created with the arguments or a
+ generation config an error is thrown. This feature is intended for advanced users.
+ stopping_criteria (`StoppingCriteriaList`, *optional*):
+ Custom stopping criteria that complement the default stopping criteria built from arguments and a
+ generation config. If a stopping criteria is passed that is already created with the arguments or a
+ generation config an error is thrown. This feature is intended for advanced users.
+ prefix_allowed_tokens_fn (`Callable[[int, torch.Tensor], list[int]]`, *optional*):
+ If provided, this function constraints the beam search to allowed tokens only at each step. If not
+ provided no constraint is applied. This function takes 2 arguments: the batch ID `batch_id` and
+ `input_ids`. It has to return a list with the allowed tokens for the next generation step conditioned
+ on the batch ID `batch_id` and the previously generated tokens `inputs_ids`. This argument is useful
+ for constrained generation conditioned on the prefix, as described in [Autoregressive Entity
+ Retrieval](https://huggingface.co/papers/2010.00904).
+ synced_gpus (`bool`, *optional*, defaults to `False`):
+ Whether to continue running the while loop until max_length (needed to avoid deadlocking with
+ `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
+ return_timestamps (`bool`, *optional*):
+ Whether to return the timestamps with the text. This enables the `WhisperTimestampsLogitsProcessor`.
+ For audios longer than 30 seconds, it is necessary to set `return_timestamps=True`.
+ task (`str`, *optional*):
+ Task to use for generation, either "translate" or "transcribe".
+ language (`str` or list of `str`, *optional*):
+ Language token to use for generation, can be either in the form of `<|en|>`, `en` or `english`. For
+ batched generation, a list of language tokens can be passed. You can find all the possible language
+ tokens in the `model.generation_config.lang_to_id` dictionary.
+ is_multilingual (`bool`, *optional*):
+ Whether or not the model is multilingual.
+ prompt_ids (`torch.Tensor`, *optional*):
+ Rank-1 tensor of token IDs created by passing text to [`~WhisperProcessor.get_prompt_ids`] that is
+ provided as a prompt to each chunk. This can be used to provide or "prompt-engineer" a context for
+ transcription, e.g. custom vocabularies or proper nouns to make it more likely to predict those words
+ correctly. It cannot be used in conjunction with `decoder_start_token_id` as it overwrites this value.
+ prompt_condition_type (`str`, *optional*):
+ Only relevant for long-form transcription. Condition type of `prompt_ids`. 'first-segment' means only the first segment is conditioned on `prompt_ids`. 'all-segments' means each segment is conditioned on `prompt_ids`. Make sure to enable `condition_on_prev_tokens` for 'all-segments'.
+ Defaults to 'first-segment'. For short-term transcription only 'first-segment' is possible.
+ condition_on_prev_tokens (`bool`, *optional*):
+ Only relevant for long-form transcription. Whether to condition each segment on the previous segment.
+ As shown in the [the Whisper paper](https://cdn.openai.com/papers/whisper.pdf), this can help to improve
+ performance.
+ temperature (`float` or list of `float`, *optional*):
+ The temperature to be used for generation. Passing a single `float` value and `do_sample=True` activates
+ generation using sampling. For long-form transcription, temperature fallback can be activated by passing
+ a list of float values such as (0.0, 0.2, 0.4, 0.6, 0.8, 1.0). As shown in the [the Whisper paper](https://cdn.openai.com/papers/whisper.pdf), this can help to improve
+ performance.
+ compression_ratio_threshold (`float`, *optional*):
+ Only relevant for long-form transcription. If defined, the zlib compression rate of each segment will be computed. If the compression rate of
+ a segment is higher than `compression_ratio_threshold`, temperature fallback is activated: the generated segment is discarded and the generation is
+ repeated using a higher temperature. The intuition behind this feature is that segments with very high compression rates
+ suffer from a lot of repetition. The unwanted repetition can be reduced by injecting more randomness by increasing the temperature. If `compression_ratio_threshold` is defined
+ make sure that `temperature` is a list of values. A common value for `compression_ratio_threshold` is 1.35.
+ As shown in the [the Whisper paper](https://cdn.openai.com/papers/whisper.pdf), this can help to improve
+ performance.
+ logprob_threshold (`float`, *optional*):
+ Only relevant for long-form transcription. If defined, the average log-probability of each segment will be computed. If the log-probability of
+ a given segment is lower than `logprob_threshold`, temperature fallback is activated: the generated segment is discarded and the generation is
+ repeated using a higher temperature. The intuition behind this feature is that segments of low log-probability
+ can be improved by injecting more randomness by increasing the temperature. If `logprob_threshold` is defined
+ make sure that `temperature` is a list of values. A common value for `logprob_threshold` is -1.0.
+ As shown in the [the Whisper paper](https://cdn.openai.com/papers/whisper.pdf), this can help to improve
+ performance.
+ no_speech_threshold (`float`, *optional*):
+ Only relevant for long-form transcription. If defined, the "no-speech" token combined with the `logprob_threshold`
+ is used to determine whether a segment contains only silence. In this case, the transcription for this segment
+ is skipped.
+ As shown in the [the Whisper paper](https://cdn.openai.com/papers/whisper.pdf), this can help to improve
+ performance.
+ num_segment_frames (`int`, *optional*):
+ The number of frames a single segment is made of. If not defined, `num_segment_frames` defaults to the model's stride
+ times the maximum input length.
+ attention_mask (`torch.Tensor`, *optional*):
+ `attention_mask` needs to be passed when doing long-form transcription using a batch size > 1.
+ time_precision (`int`, *optional*, defaults to 0.02):
+ The duration of output token in seconds. *E.g.* 0.02 means that a generated token on average accounts
+ for 20 ms.
+ time_precision_features (`int`, *optional*, defaults to 0.01):
+ The duration represented by a feature frame in seconds.
+ return_token_timestamps (`bool`, *optional*):
+ Whether to return token-level timestamps with the text. This can be used with or without the
+ `return_timestamps` option. To get word-level timestamps, use the tokenizer to group the tokens into
+ words.
+ return_segments (`bool`, *optional*, defaults to `False`):
+ Whether to additionally return a list of all segments. Note that this option can only be enabled
+ when doing long-form transcription.
+ return_dict_in_generate (`bool`, *optional*, defaults to `False`):
+ Whether or not to return a [`~utils.ModelOutput`] instead of just returning the generated tokens.
+ Note that when doing long-form transcription, `return_dict_in_generate` can only be enabled when
+ `return_segments` is set True. In this case the generation outputs of each segment is added to each
+ segment.
+ force_unique_generate_call (`bool`, *optional*):
+ Whether to force a unique call to the underlying GenerationMixin's [`~generation.GenerationMixin.generate`] method. This is useful for assisted decoding and testing purposes to ensure
+ that only one call to [`~generation.GenerationMixin.generate`] is made and therefore decoder input token ids and eos token ids are returned.
+ monitor_progress (`Callable[[torch.Tensor], None]`, *optional*):
+ If provided, this function can be called to report the progress of the audio transcription. The function
+ takes a tensor argument `p` of shape `(n, 2)`, where `n` is the batch size. `p[i, 0]` contains the
+ index of the audio frame that is currently being transcribed for batch item `i`. `p[i, 1]` contains
+ the total number of frames for batch item `i`. No return value is expected.
+ kwargs (`dict[str, Any]`, *optional*):
+ Ad hoc parametrization of `generate_config` and/or additional model-specific kwargs that will be
+ forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder
+ specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with *decoder_*.
+ Return:
+ [`~utils.ModelOutput`] or `dict[str, Any]` or `torch.LongTensor`:
+
+ One of the following:
+ - [`~utils.ModelOutput`] when `return_dict_in_generate=True` and (`return_timestamps=False` or `force_unique_generate_call=True`), including the decoder input ids and end of sequence id.
+ - `dict[str, Any]` when (`return_dict_in_generate=True` and `return_timestamps=True`) or `return_segments=True` or `return_token_timestamps=True`.
+ - `torch.LongTensor` in all other cases, excluding the decoder input ids and end of sequence id.
+
+ The possible [`~utils.ModelOutput`] types are:
+ - [`~generation.GenerateEncoderDecoderOutput`]
+ - [`~generation.GenerateBeamEncoderDecoderOutput`]
+
+ `segments` is a list of lists (one list per batch element) of `segment`.
+ A `segment` is a dictionary with keys `start`, `end`, `tokens`, `idxs`, and `result`.
+ - `start`: the start timestamp of the segment.
+ - `end`: the end timestamp of the segment.
+ - `tokens`: the tokens of the segment, excluding the decoder input ids and end of sequence id.
+ - `idxs`: the start (included) and end (excluded) indices of the `tokens` of the segment in the underlying call to GenerationMixin's [`~generation.GenerationMixin.generate`] (present in `result`).
+ - `result`: the result of the underlying call to GenerationMixin's [`~generation.GenerationMixin.generate`].
+
+ When `return_timestamps=True`, `return_dict_in_generate=True` applies to each call of the underlying GenerationMixin's [`~generation.GenerationMixin.generate`], with outputs stored in `result` of each `segment`.
+
+ Example:
+
+ - *Longform transcription*: To transcribe or translate audios longer than 30 seconds, process the audio files without truncation and pass all mel features at once to generate. It is necessary to set `return_timestamps=True`.
+ Indeed, long-form transcription uses a sequential algorithm based on timestamps predictions, with heuristics like compression ratio threshold, log probability threshold and temperature fallback. This algorithm is described in the [the Whisper original paper](https://cdn.openai.com/papers/whisper.pdf), section *3.8. Long-form Transcription*.
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoProcessor, WhisperForConditionalGeneration
+ >>> from datasets import load_dataset, Audio
+
+ >>> processor = AutoProcessor.from_pretrained("openai/whisper-tiny.en")
+ >>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")
+ >>> model.cuda() # doctest: +IGNORE_RESULT
+
+ >>> # load audios > 30 seconds
+ >>> ds = load_dataset("distil-whisper/meanwhile", "default")["test"]
+ >>> # resample to 16kHz
+ >>> ds = ds.cast_column("audio", Audio(sampling_rate=16000))
+ >>> # take first 8 audios and retrieve array
+ >>> audio = ds[:8]["audio"]
+ >>> audio = [x["array"] for x in audio]
+
+ >>> # make sure to NOT truncate the input audio, to return the `attention_mask` and to pad to the longest audio
+ >>> inputs = processor(audio, return_tensors="pt", truncation=False, padding="longest", return_attention_mask=True, sampling_rate=16_000)
+ >>> inputs = inputs.to("cuda", torch.float32)
+
+ >>> # transcribe audio to ids
+ >>> generated_ids = model.generate(**inputs, return_timestamps=True)
+
+ >>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)
+ >>> transcription[0]
+ " Folks, if you watch the show, you know, I spent a lot of time right over there. Patiently and astutely scrutinizing the boxwood and mahogany chest set of the day's biggest stories developing the central headline pawns, definitely maneuvering an oso topical night to F6, fainting a classic Sicilian, nade door variation on the news, all the while seeing eight moves deep and patiently marshalling the latest press releases into a fisher's shows in Lip Nitsky attack that culminates in the elegant lethal slow-played, all-passant checkmate that is my nightly monologue. But sometimes, sometimes, folks, I. CHEERING AND APPLAUSE Sometimes I startle away, cubside down in the monkey bars of a condemned playground on a super fun site. Get all hept up on goofballs. Rummage that were discarded tag bag of defective toys. Yank out a fist bowl of disembodied doll limbs, toss them on a stained kid's place mat from a defunct dennies. set up a table inside a rusty cargo container down by the Wharf and challenged toothless drifters to the godless bughouse blitz of tournament that is my segment. Meanwhile."
+ ```
+
+ The `monitor_progress` callback can be used to monitor the progress of the transcription:
+ ```python
+ >>> from tqdm import tqdm
+
+ >>> # prepare inputs like above
+
+ >>> # define a callback to monitor the progress of the transcription.
+ >>> with tqdm(desc="Progress") as pbar:
+ >>> def monitor_progress(p_batch):
+ >>> i = torch.argmax(p_batch[:, 1])
+ >>> p = p_batch[i].detach().cpu()
+ >>> pbar.total = int(p[1])
+ >>> pbar.n = int(p[0])
+ >>> pbar.update()
+
+ >>> # transcribe audio to ids
+ >>> generated_ids = model.generate(**inputs, return_timestamps=True, monitor_progress=monitor_progress)
+
+ >>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)
+ >>> transcription[0]
+ Progress: 95%|█████████████████████████████████████████████████████████████████████████████████████████████████▎ | 8497/8901 [00:04<00:00, 2052.79it/s]
+ " Folks, if you watch the show, you know, I spent a lot of time right over there. Patiently and astutely scrutinizing the boxwood and mahogany chest set of the day's biggest stories developing the central headline pawns, definitely maneuvering an oso topical night to F6, fainting a classic Sicilian, nade door variation on the news, all the while seeing eight moves deep and patiently marshalling the latest press releases into a fisher's shows in Lip Nitsky attack that culminates in the elegant lethal slow-played, all-passant checkmate that is my nightly monologue. But sometimes, sometimes, folks, I. CHEERING AND APPLAUSE Sometimes I startle away, cubside down in the monkey bars of a condemned playground on a super fun site. Get all hept up on goofballs. Rummage that were discarded tag bag of defective toys. Yank out a fist bowl of disembodied doll limbs, toss them on a stained kid's place mat from a defunct dennies. set up a table inside a rusty cargo container down by the Wharf and challenged toothless drifters to the godless bughouse blitz of tournament that is my segment. Meanwhile."
+ ```
+
+ - *Shortform transcription*: If passed mel input features are <= 30 seconds, there are two possibilities:
+ - `return_timestamps=False`: the whole audio will be transcribed with a single call to GenerationMixin's [`~generation.GenerationMixin.generate`].
+ - `return_timestamps=True`: the audio will be transcribed using the same logic as long-form transcription.
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoProcessor, WhisperForConditionalGeneration
+ >>> from datasets import load_dataset
+
+ >>> processor = AutoProcessor.from_pretrained("openai/whisper-tiny.en")
+ >>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")
+
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
+
+ >>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
+ >>> input_features = inputs.input_features
+
+ >>> generated_ids = model.generate(inputs=input_features)
+
+ >>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
+ >>> transcription
+ ' Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'
+ ```
+
+ """
+ # 1. prepare generation config
+ generation_config, kwargs = self._prepare_generation_config(generation_config, **kwargs)
+
+ # 2. set global generate variables
+ input_stride = self.model.encoder.conv1.stride[0] * self.model.encoder.conv2.stride[0]
+ num_segment_frames = input_stride * self.config.max_source_positions
+ batch_size, total_input_frames = self._retrieve_total_input_frames(
+ input_features=input_features, input_stride=input_stride, kwargs=kwargs
+ )
+ is_shortform = total_input_frames <= num_segment_frames
+
+ # 3. Make sure generation config is correctly set
+ # Make sure the generation config is correctly set depending on whether timestamps are to be returned or not
+ return_dict_in_generate = self._set_return_outputs(
+ return_dict_in_generate=return_dict_in_generate,
+ return_token_timestamps=return_token_timestamps,
+ logprob_threshold=logprob_threshold,
+ generation_config=generation_config,
+ )
+ timestamp_begin = self._set_return_timestamps(
+ return_timestamps=return_timestamps, is_shortform=is_shortform, generation_config=generation_config
+ )
+ self._set_language_and_task(
+ language=language, task=task, is_multilingual=is_multilingual, generation_config=generation_config
+ )
+ self._set_num_frames(
+ return_token_timestamps=return_token_timestamps,
+ generation_config=generation_config,
+ attention_mask=attention_mask,
+ kwargs=kwargs,
+ )
+ self._set_thresholds_and_condition(
+ generation_config=generation_config,
+ logprob_threshold=logprob_threshold,
+ compression_ratio_threshold=compression_ratio_threshold,
+ no_speech_threshold=no_speech_threshold,
+ condition_on_prev_tokens=condition_on_prev_tokens,
+ )
+ self._set_prompt_condition_type(
+ generation_config=generation_config,
+ prompt_condition_type=prompt_condition_type,
+ )
+
+ # pass self.config for backward compatibility
+ init_tokens = self._retrieve_init_tokens(
+ input_features,
+ batch_size=batch_size,
+ generation_config=generation_config,
+ config=self.config,
+ num_segment_frames=num_segment_frames,
+ kwargs=kwargs,
+ )
+ # passing `decoder_input_ids` is deprecated - the only exception is for assisted generation
+ # where the input ids are handled explicitly by the generate method
+ self._check_decoder_input_ids(kwargs=kwargs)
+ # `output_attentions` is deprecated - we force eager attention if this feature is
+ # indirectly requested, e.g. through return_token_timestamps
+ if return_token_timestamps:
+ self.model.config._attn_implementation = "eager"
+
+ # 3. Retrieve logits processors
+ device = kwargs["encoder_outputs"][0].device if "encoder_outputs" in kwargs else input_features.device
+ begin_index = init_tokens.shape[1]
+ num_beams = kwargs.get(
+ "num_beams",
+ generation_config.num_beams
+ if hasattr(generation_config, "num_beams") and generation_config.num_beams is not None
+ else 1,
+ )
+ if "assistant_model" in kwargs:
+ # speculative decoding: the model should be able to return eos token
+ generation_config.begin_suppress_tokens = None
+
+ logits_processor = self._retrieve_logit_processors(
+ generation_config=generation_config,
+ logits_processor=logits_processor,
+ begin_index=begin_index, # begin index is index of first generated decoder token
+ num_beams=num_beams,
+ device=device,
+ )
+
+ # 4 Set and retrieve global generation variables
+ self._set_condition_on_prev_tokens(
+ condition_on_prev_tokens=condition_on_prev_tokens, generation_config=generation_config
+ )
+
+ temperatures = [temperature] if not isinstance(temperature, (list, tuple)) else temperature
+ temperature = temperatures[0]
+
+ max_frames, seek = self._retrieve_max_frames_and_seek(
+ batch_size=batch_size,
+ attention_mask=attention_mask,
+ total_input_frames=total_input_frames,
+ is_shortform=is_shortform,
+ )
+
+ # 5 Prepare running variables, list for generation
+ num_return_sequences = generation_config.num_return_sequences
+ (
+ batch_idx_map,
+ cur_bsz,
+ input_features,
+ seek,
+ max_frames,
+ init_tokens,
+ do_condition_on_prev_tokens,
+ ) = self._expand_variables_for_generation(
+ input_features=input_features,
+ seek=seek,
+ max_frames=max_frames,
+ init_tokens=init_tokens,
+ batch_size=batch_size,
+ condition_on_prev_tokens=condition_on_prev_tokens,
+ generation_config=generation_config,
+ )
+
+ current_segments = self._prepare_segments(
+ prompt_ids=prompt_ids,
+ batch_size=cur_bsz,
+ generation_config=generation_config,
+ )
+ # 5bis speculative decoding: ensure the assistant model does only one call to generate and therefore returns decoder input token ids and eos token id
+ # we set a flag in the generation config to force the model to make only one call to generate and return the decoder input token ids and eos token id
+ if "assistant_model" in kwargs:
+ assistant_model = kwargs["assistant_model"]
+ assistant_model.generation_config.force_unique_generate_call = True
+
+ if force_unique_generate_call is None:
+ if hasattr(generation_config, "force_unique_generate_call"):
+ force_unique_generate_call = generation_config.force_unique_generate_call
+ elif hasattr(self.generation_config, "force_unique_generate_call"):
+ force_unique_generate_call = self.generation_config.force_unique_generate_call
+ else:
+ force_unique_generate_call = False
+
+ # 6 Transcribe audio until we reach the end of all input audios
+ while (seek < max_frames).any():
+ if monitor_progress is not None:
+ monitor_progress(torch.stack((seek, max_frames), dim=1))
+
+ # 6.1 NOTE: When in longform transcription mode and batch size > 1 we need to dynamically reduce the batch size during the loop
+ # in case one audio finished earlier than another one. Thus, we need to keep a table of "previous-index-2-current-index" in order
+ # to know which original audio is being decoded
+ # Set updated index map, duration of previously decoded chunks and number of max frames of current decoding chunk
+ input_features, cur_bsz, batch_idx_map = self._maybe_reduce_batch(
+ input_features=input_features,
+ seek=seek,
+ max_frames=max_frames,
+ cur_bsz=cur_bsz,
+ batch_idx_map=batch_idx_map,
+ )
+ time_offset = (
+ seek.to(torch.float32 if device.type == "mps" else torch.float64) * time_precision / input_stride
+ )
+ seek_num_frames = (max_frames - seek).clamp(max=num_segment_frames)
+
+ # 6.2 cut out next 30s segment from input features
+ segment_input = self._get_input_segment(
+ input_features=input_features,
+ seek=seek,
+ seek_num_frames=seek_num_frames,
+ num_segment_frames=num_segment_frames,
+ cur_bsz=cur_bsz,
+ batch_idx_map=batch_idx_map,
+ )
+
+ # 6.3 prepare decoder input ids
+ suppress_tokens = _get_attr_from_logit_processors(
+ logits_processor, SuppressTokensLogitsProcessor, "suppress_tokens"
+ )
+
+ decoder_input_ids, kwargs = self._prepare_decoder_input_ids(
+ cur_bsz=cur_bsz,
+ init_tokens=init_tokens,
+ current_segments=current_segments,
+ batch_idx_map=batch_idx_map,
+ do_condition_on_prev_tokens=do_condition_on_prev_tokens,
+ prompt_ids=prompt_ids,
+ generation_config=generation_config,
+ config=self.config,
+ device=init_tokens.device,
+ suppress_tokens=suppress_tokens,
+ timestamp_begin=timestamp_begin,
+ kwargs=kwargs,
+ )
+
+ # 6.4 set max new tokens or max length
+ self._set_max_new_tokens_and_length(
+ config=self.config,
+ decoder_input_ids=decoder_input_ids,
+ generation_config=generation_config,
+ )
+
+ # 6.5 Set current `begin_index` for all logit processors
+ if logits_processor is not None:
+ for proc in logits_processor:
+ if hasattr(proc, "set_begin_index"):
+ proc.set_begin_index(decoder_input_ids.shape[-1])
+
+ # 6.6 Run generate with fallback
+ (
+ seek_sequences,
+ seek_outputs,
+ should_skip,
+ do_condition_on_prev_tokens,
+ model_output_type,
+ ) = self.generate_with_fallback(
+ segment_input=segment_input,
+ decoder_input_ids=decoder_input_ids,
+ cur_bsz=cur_bsz,
+ seek=seek,
+ batch_idx_map=batch_idx_map,
+ temperatures=temperatures,
+ generation_config=generation_config,
+ logits_processor=logits_processor,
+ stopping_criteria=stopping_criteria,
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
+ synced_gpus=synced_gpus,
+ return_token_timestamps=return_token_timestamps,
+ do_condition_on_prev_tokens=do_condition_on_prev_tokens,
+ is_shortform=is_shortform,
+ batch_size=batch_size,
+ attention_mask=attention_mask,
+ kwargs=kwargs,
+ )
+
+ # 6.7 In every generated sequence, split by timestamp tokens and extract segments
+ for i, seek_sequence in enumerate(seek_sequences):
+ prev_i = batch_idx_map[i]
+
+ if should_skip[i]:
+ seek[prev_i] += seek_num_frames[prev_i]
+ continue
+
+ segments, segment_offset = self._retrieve_segment(
+ seek_sequence=seek_sequence,
+ seek_outputs=seek_outputs,
+ time_offset=time_offset,
+ timestamp_begin=timestamp_begin,
+ seek_num_frames=seek_num_frames,
+ time_precision=time_precision,
+ time_precision_features=time_precision_features,
+ input_stride=input_stride,
+ prev_idx=prev_i,
+ idx=i,
+ return_token_timestamps=return_token_timestamps,
+ decoder_input_ids=decoder_input_ids,
+ )
+
+ seek[prev_i] += segment_offset
+
+ current_segments[prev_i] += segments
+
+ if force_unique_generate_call:
+ break
+
+ # 7. Once all segments are added to the list of all segments, called `current_segments`, we extract the predicted
+ # output tokens from the list of dicts. If we use batch size > 1, we make sure to pad the output
+ final_segments = (
+ [x[1:] for x in current_segments]
+ if (prompt_ids is not None and generation_config.prompt_condition_type == "first-segment")
+ else current_segments
+ )
+
+ # if return_dict_in_generate=True and we forced a unique call to generate or return_timestamps=False, meaning we are sure only one call to generate has been made,
+ # -> we can return a ModelOutput
+ # otherwise, return_dict_in_generate is applied in the 'result' of each segment in final_segments
+ if (
+ return_dict_in_generate
+ and generation_config.return_dict_in_generate
+ and (force_unique_generate_call or not return_timestamps)
+ ):
+ # only one call to generate_with_fallback, we can return a ModelOutput
+ outputs = self._stack_split_outputs(seek_outputs, model_output_type, self.device, kwargs)
+ if num_return_sequences > 1:
+ if hasattr(outputs, "encoder_attentions") and outputs.encoder_attentions is not None:
+ outputs.encoder_attentions = tuple(
+ outputs.encoder_attentions[i][::num_return_sequences]
+ for i in range(len(outputs.encoder_attentions))
+ )
+ if hasattr(outputs, "encoder_hidden_states") and outputs.encoder_hidden_states is not None:
+ outputs.encoder_hidden_states = tuple(
+ outputs.encoder_hidden_states[i][::num_return_sequences]
+ for i in range(len(outputs.encoder_hidden_states))
+ )
+ return outputs
+
+ padded_outputs = _pad_to_max_length(
+ current_segments=final_segments,
+ pad_token_id=generation_config.pad_token_id,
+ device=self.device,
+ padding_side="right",
+ return_token_timestamps=return_token_timestamps,
+ force_unique_generate_call=force_unique_generate_call,
+ )
+
+ if return_dict_in_generate and generation_config.return_dict_in_generate:
+ logger.warning_once(
+ "You have passed `return_dict_in_generate=True` and `return_timestamps=True`, this automatically sets `return_segments=True` to access the results of the underlying calls to GenerationMixin's generate in the returned `segments`."
+ )
+ return_segments = True
+ elif not return_segments and not return_token_timestamps:
+ return padded_outputs
+
+ if return_token_timestamps:
+ sequences, token_timestamps = padded_outputs
+ outputs = {
+ "sequences": sequences,
+ "token_timestamps": token_timestamps,
+ }
+ else:
+ sequences = padded_outputs
+ outputs = {
+ "sequences": sequences,
+ }
+
+ if return_segments:
+ outputs["segments"] = final_segments
+
+ return outputs
+
+ def generate_with_fallback(
+ self,
+ segment_input,
+ decoder_input_ids,
+ cur_bsz,
+ seek,
+ batch_idx_map,
+ temperatures,
+ generation_config,
+ logits_processor,
+ stopping_criteria,
+ prefix_allowed_tokens_fn,
+ synced_gpus,
+ return_token_timestamps,
+ do_condition_on_prev_tokens,
+ is_shortform,
+ batch_size,
+ attention_mask,
+ kwargs,
+ ):
+ kwargs = copy.copy(kwargs)
+
+ # 6.6 Batch generate current chunk
+ seek_sequence_list = [None for _ in range(cur_bsz)]
+ seek_outputs_list = [None for _ in range(cur_bsz)]
+ needs_fallback = [False for _ in range(cur_bsz)]
+ should_skip = [False for _ in range(cur_bsz)]
+ fallback_index_map = list(range(cur_bsz))
+ if generation_config.no_speech_threshold is not None:
+ self._setup_no_speech_detection(logits_processor, segment_input, decoder_input_ids, kwargs)
+
+ for fallback_idx, temperature in enumerate(temperatures):
+ generation_config.do_sample = temperature is not None and temperature > 0.0
+ generation_config.temperature = temperature if generation_config.do_sample else 1.0
+ if generation_config.do_sample:
+ generation_config.num_beams = 1
+
+ generate_kwargs = copy.copy(kwargs)
+ for key in ["do_sample", "temperature", "num_beams"]:
+ if key in generate_kwargs:
+ del generate_kwargs[key]
+
+ cur_bsz = decoder_input_ids.shape[0]
+ if generation_config.cache_implementation == "static" and cur_bsz < batch_size:
+ segment_input = F.pad(segment_input, (0, 0, 0, 0, 0, batch_size - cur_bsz), value=0)
+ decoder_input_ids = F.pad(
+ decoder_input_ids, (0, 0, 0, batch_size - cur_bsz), value=generation_config.pad_token_id
+ )
+ if generate_kwargs.get("decoder_attention_mask") is not None:
+ generate_kwargs["decoder_attention_mask"] = F.pad(
+ generate_kwargs["decoder_attention_mask"], (0, 0, 0, batch_size - cur_bsz), value=True
+ )
+ if generate_kwargs.get("encoder_outputs") is not None:
+ generate_kwargs["encoder_outputs"] = F.pad(
+ generate_kwargs["encoder_outputs"], (0, 0, 0, 0, 0, batch_size - cur_bsz), value=0
+ )
+
+ seek_outputs = super().generate(
+ segment_input,
+ generation_config=generation_config,
+ logits_processor=logits_processor,
+ stopping_criteria=stopping_criteria,
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
+ synced_gpus=synced_gpus,
+ decoder_input_ids=decoder_input_ids,
+ attention_mask=attention_mask,
+ **generate_kwargs,
+ )
+
+ model_output_type = type(seek_outputs)
+
+ # post-process sequence tokens and outputs to be in list form
+ seek_sequences, seek_outputs = self._postprocess_outputs(
+ seek_outputs=seek_outputs,
+ decoder_input_ids=decoder_input_ids,
+ return_token_timestamps=return_token_timestamps,
+ generation_config=generation_config,
+ is_shortform=is_shortform,
+ seek=seek,
+ batch_idx_map=batch_idx_map,
+ )
+
+ if cur_bsz < batch_size:
+ seek_sequences = seek_sequences[:cur_bsz]
+ seek_outputs = seek_outputs[:cur_bsz]
+
+ # 6.7 Extract cut sequences from every sequence and check if fallback should be applied
+ # Loop over each decoded audio individually as each decoding can be of a different length
+ new_fallback_index_map = []
+ new_segment_input = []
+ new_decoder_input_ids = []
+ new_decoder_attention_mask = []
+
+ for i, seek_sequence in enumerate(seek_sequences):
+ # remove all padding tokens, except for the eos token
+ if seek_sequence[-1] == generation_config.pad_token_id:
+ num_paddings = (seek_sequence == generation_config.pad_token_id).sum()
+ if generation_config.pad_token_id == generation_config.eos_token_id:
+ # we do not remove the eos token id since it is needed for avg logprob calculation in _need_fallback
+ num_paddings -= 1
+ if num_paddings != 0:
+ seek_sequence = seek_sequence[:-num_paddings]
+
+ # check which sequences in batch need fallback & which should be skipped
+ needs_fallback[i], should_skip[i] = self._need_fallback(
+ seek_sequence,
+ seek_outputs,
+ i,
+ logits_processor,
+ generation_config,
+ self.config.vocab_size,
+ temperature,
+ )
+
+ # remove eos token
+ if seek_sequence[-1] == generation_config.eos_token_id:
+ seek_sequence = seek_sequence[:-1]
+
+ seek_sequence_list[fallback_index_map[i]] = seek_sequence
+ seek_outputs_list[fallback_index_map[i]] = seek_outputs[i]
+ is_low_temperature = temperature is None or temperature < 0.5
+ do_condition_on_prev_tokens[fallback_index_map[i]] = (
+ generation_config.condition_on_prev_tokens and is_low_temperature
+ )
+
+ if needs_fallback[i]:
+ new_fallback_index_map.append(fallback_index_map[i])
+ new_segment_input.append(segment_input[i])
+ new_decoder_input_ids.append(decoder_input_ids[i])
+ if "decoder_attention_mask" in kwargs:
+ new_decoder_attention_mask.append(kwargs["decoder_attention_mask"][i])
+
+ fallback_index_map = new_fallback_index_map
+
+ # if no sequence needs to be run with temperature fallback, we're finished
+ if len(fallback_index_map) == 0 or fallback_idx == len(temperatures) - 1:
+ seek_sequences = seek_sequence_list
+ seek_outputs = seek_outputs_list
+ break
+
+ # if we're still in the loop, make sure that decoder_input_ids and segment inputs are tensors
+ decoder_input_ids = torch.stack(new_decoder_input_ids)
+ segment_input = torch.stack(new_segment_input)
+ if "decoder_attention_mask" in kwargs:
+ kwargs["decoder_attention_mask"] = torch.stack(new_decoder_attention_mask)
+
+ return seek_sequences, seek_outputs, should_skip, do_condition_on_prev_tokens, model_output_type
+
+ @staticmethod
+ def _prepare_segments(prompt_ids, batch_size, generation_config):
+ if prompt_ids is not None and generation_config.prompt_condition_type == "first-segment":
+ prev_sot_token_id = getattr(generation_config, "prev_sot_token_id", None)
+ prompt_ids = prompt_ids[1:] if prompt_ids[0] == prev_sot_token_id else prompt_ids
+ current_segments = [[{"tokens": prompt_ids}] for _ in range(batch_size)]
+ else:
+ current_segments = [[] for _ in range(batch_size)]
+
+ return current_segments
+
+ def _postprocess_outputs(
+ self,
+ seek_outputs,
+ decoder_input_ids,
+ return_token_timestamps,
+ generation_config,
+ is_shortform,
+ seek,
+ batch_idx_map,
+ ):
+ # remove all previously passed decoder input ids
+ # should happen only if it is the first generated segment
+ start_idx = decoder_input_ids.shape[-1]
+
+ if isinstance(seek_outputs, torch.Tensor):
+ return seek_outputs[:, start_idx:], seek_outputs
+
+ if return_token_timestamps and hasattr(generation_config, "alignment_heads"):
+ num_frames = getattr(generation_config, "num_frames")
+ if num_frames is not None:
+ num_frames = num_frames - seek
+ num_frames = num_frames[batch_idx_map]
+
+ seek_outputs["token_timestamps"] = self._extract_token_timestamps(
+ seek_outputs,
+ generation_config.alignment_heads,
+ num_frames=num_frames,
+ num_input_ids=decoder_input_ids.shape[-1],
+ )
+
+ def split_by_batch_index(values, key, batch_idx, is_shortform, beam_indices=None):
+ if beam_indices is not None and key == "scores":
+ return [v[beam_idx].cpu() for (v, beam_idx) in zip(values, beam_indices[batch_idx][: len(values)])]
+ if key in ["scores", "encoder_attentions", "encoder_hidden_states", "logits"]:
+ return [v[batch_idx].cpu() for v in values]
+ if key in ["decoder_attentions", "decoder_hidden_states", "cross_attentions"]:
+ return tuple(tuple(w[batch_idx][None].cpu() for w in v) for v in values)
+ elif key == "past_key_values":
+ if not is_shortform:
+ # we don't save `past_key_values` as this is too costly for longform
+ return None
+ all_past_key_values = []
+ for layer_idx in range(self.config.decoder_layers):
+ layer_cache = (
+ values.self_attention_cache.layers[layer_idx].keys[batch_idx][None].cpu(),
+ values.self_attention_cache.layers[layer_idx].values[batch_idx][None].cpu(),
+ values.cross_attention_cache.layers[layer_idx].keys[batch_idx][None].cpu(),
+ values.cross_attention_cache.layers[layer_idx].values[batch_idx][None].cpu(),
+ )
+ all_past_key_values.append(layer_cache)
+ return EncoderDecoderCache(all_past_key_values)
+
+ return values[batch_idx].cpu()
+
+ sequence_tokens = seek_outputs["sequences"][:, start_idx:]
+ seek_outputs = [
+ {
+ k: split_by_batch_index(v, k, i, is_shortform, beam_indices=seek_outputs.get("beam_indices"))
+ for k, v in seek_outputs.items()
+ }
+ for i in range(sequence_tokens.shape[0])
+ ]
+
+ return sequence_tokens, seek_outputs
+
+ def _stack_split_outputs(self, seek_outputs, model_output_type, device, kwargs):
+ # Stack back seek_outputs tensors after splitting them with the split_by_batch_index method
+ outputs = {}
+ for key in seek_outputs[0]:
+ if key in ["sequences", "beam_indices", "token_timestamps"]:
+ outputs[key] = torch.stack([v[key] for v in seek_outputs], dim=0).to(device)
+ elif key in ["scores", "encoder_attentions", "encoder_hidden_states", "logits"]:
+ outputs[key] = tuple(
+ torch.stack([v[key][i] for v in seek_outputs]).to(device) for i in range(len(seek_outputs[0][key]))
+ )
+ elif key == "sequences_scores":
+ outputs[key] = torch.stack([v[key] for v in seek_outputs], dim=0).to(device)
+ elif key in ["decoder_attentions", "decoder_hidden_states", "cross_attentions"]:
+ outputs[key] = tuple(
+ tuple(
+ torch.stack([v[key][i][j] for v in seek_outputs]).squeeze(1).to(device)
+ for j in range(len(seek_outputs[0][key][0]))
+ )
+ for i in range(len(seek_outputs[0][key]))
+ )
+ elif key == "past_key_values":
+ if seek_outputs[0][key] is not None:
+ all_past_key_values = []
+ for layer_idx in range(len(seek_outputs[0][key])):
+ self_attention_k, self_attention_v, cross_attention_k, cross_attention_v = (
+ torch.stack(
+ [
+ getattr(getattr(sub_output[key], sub_cache).layers[layer_idx], sub_key)
+ for sub_output in seek_outputs
+ ]
+ )
+ .squeeze(1)
+ .to(device)
+ for sub_cache in ["self_attention_cache", "cross_attention_cache"]
+ for sub_key in ["keys", "values"]
+ )
+ all_past_key_values.append(
+ (self_attention_k, self_attention_v, cross_attention_k, cross_attention_v)
+ )
+ outputs[key] = EncoderDecoderCache(tuple(all_past_key_values))
+ else:
+ outputs[key] = None
+
+ token_timestamps = outputs.get("token_timestamps")
+ if token_timestamps is not None:
+ model_output_type = dict
+
+ return model_output_type(**outputs)
+
+ def _need_fallback(
+ self,
+ seek_sequence,
+ seek_outputs,
+ index,
+ logits_processor,
+ generation_config,
+ vocab_size,
+ temperature,
+ ):
+ needs_fallback = False
+ should_skip = False
+ if generation_config.compression_ratio_threshold is not None:
+ compression_ratio = self._retrieve_compression_ratio(seek_sequence, vocab_size)
+
+ if compression_ratio > generation_config.compression_ratio_threshold:
+ needs_fallback = True
+
+ if generation_config.logprob_threshold is not None:
+ if hasattr(seek_outputs[0], "sequences_scores"):
+ logprobs = [s["sequences_scores"] for s in seek_outputs][index]
+ else:
+ scores = seek_outputs[index]["scores"]
+ logprobs = self._retrieve_avg_logprobs(
+ scores,
+ seek_sequence,
+ temperature,
+ )
+
+ if logprobs < generation_config.logprob_threshold:
+ needs_fallback = True
+
+ if generation_config.no_speech_threshold is not None:
+ no_speech_prob = _get_attr_from_logit_processors(
+ logits_processor, WhisperNoSpeechDetection, "no_speech_prob"
+ )
+
+ if (
+ logprobs < generation_config.logprob_threshold
+ and no_speech_prob[index] > generation_config.no_speech_threshold
+ ):
+ needs_fallback = False
+ should_skip = True
+
+ return needs_fallback, should_skip
+
+ def _expand_variables_for_generation(
+ self, input_features, seek, max_frames, init_tokens, batch_size, condition_on_prev_tokens, generation_config
+ ):
+ if generation_config.num_return_sequences is not None and generation_config.num_return_sequences > 1:
+ batch_idx_map = list(range(batch_size * generation_config.num_return_sequences))
+ cur_bsz = len(batch_idx_map)
+ do_condition_on_prev_tokens = [condition_on_prev_tokens for _ in range(len(batch_idx_map))]
+ input_features = input_features.repeat_interleave(generation_config.num_return_sequences, dim=0)
+ seek = seek.repeat_interleave(generation_config.num_return_sequences, dim=0)
+ max_frames = max_frames.repeat_interleave(generation_config.num_return_sequences, dim=0)
+ init_tokens = init_tokens.repeat_interleave(generation_config.num_return_sequences, dim=0)
+ generation_config.num_return_sequences = 1
+ else:
+ cur_bsz = batch_size
+ batch_idx_map = list(range(cur_bsz))
+ do_condition_on_prev_tokens = [condition_on_prev_tokens for _ in range(cur_bsz)]
+
+ return (
+ batch_idx_map,
+ cur_bsz,
+ input_features,
+ seek,
+ max_frames,
+ init_tokens,
+ do_condition_on_prev_tokens,
+ )
+
+ @staticmethod
+ def _setup_no_speech_detection(logits_processor, segment_input, decoder_input_ids, kwargs):
+ set_inputs = _get_attr_from_logit_processors(logits_processor, WhisperNoSpeechDetection, "set_inputs")
+ extra_kwargs = {k: v for k, v in kwargs.items() if torch.is_tensor(v)}
+ set_inputs({"inputs": segment_input, "input_ids": decoder_input_ids, **extra_kwargs})
+
+ @staticmethod
+ def _retrieve_total_input_frames(input_features, input_stride, kwargs):
+ if input_features is not None:
+ return input_features.shape[0], input_features.shape[-1]
+
+ if "encoder_outputs" in kwargs:
+ encoder_outputs_shape = (
+ kwargs["encoder_outputs"][0].shape
+ if isinstance(kwargs["encoder_outputs"], BaseModelOutput)
+ else kwargs["encoder_outputs"].shape
+ )
+ return encoder_outputs_shape[0], encoder_outputs_shape[1] * input_stride
+
+ raise ValueError("Make sure to provide either `input_features` or `encoder_outputs` to `generate`.")
+
+ @staticmethod
+ def _maybe_warn_unused_inputs(
+ condition_on_prev_tokens,
+ temperature,
+ compression_ratio_threshold,
+ logprob_threshold,
+ no_speech_threshold,
+ total_input_frames,
+ ):
+ warning_prefix = (
+ f"Audio input consists of only {total_input_frames}. "
+ "Short-form transcription is activated."
+ "{}, but will be ignored."
+ )
+ if condition_on_prev_tokens is not None:
+ logger.warning(warning_prefix.format(f"condition_on_prev_tokens is set to {condition_on_prev_tokens}"))
+
+ if compression_ratio_threshold is not None:
+ logger.warning(
+ warning_prefix.format(f"compression_ratio_threshold is set to {compression_ratio_threshold}")
+ )
+
+ if logprob_threshold is not None:
+ logger.warning(warning_prefix.format(f"logprob_threshold is set to {logprob_threshold}"))
+
+ if no_speech_threshold is not None:
+ logger.warning(warning_prefix.format(f"no_speech_threshold is set to {no_speech_threshold}"))
+
+ @staticmethod
+ def _set_return_outputs(return_dict_in_generate, return_token_timestamps, logprob_threshold, generation_config):
+ if return_dict_in_generate is None:
+ return_dict_in_generate = generation_config.return_dict_in_generate
+ else:
+ generation_config.return_dict_in_generate = return_dict_in_generate
+
+ generation_config.return_token_timestamps = return_token_timestamps
+ if return_token_timestamps:
+ generation_config.return_dict_in_generate = True
+ generation_config.output_attentions = True
+ generation_config.output_scores = True
+
+ if logprob_threshold is not None:
+ generation_config.return_dict_in_generate = True
+ generation_config.output_scores = True
+
+ return return_dict_in_generate
+
+ def _set_return_timestamps(self, return_timestamps, is_shortform, generation_config):
+ if return_timestamps is None and hasattr(generation_config, "return_timestamps"):
+ return_timestamps = generation_config.return_timestamps
+
+ if not is_shortform:
+ if return_timestamps is False:
+ raise ValueError(
+ "You have passed more than 3000 mel input features (> 30 seconds) which automatically "
+ "enables long-form generation which requires the model to predict timestamp tokens. Please "
+ "either pass `return_timestamps=True` or make sure to pass no more than 3000 mel input features."
+ )
+
+ logger.info("Setting `return_timestamps=True` for long-form generation.")
+ return_timestamps = True
+
+ if return_timestamps and not hasattr(generation_config, "no_timestamps_token_id"):
+ raise ValueError(
+ "You are trying to return timestamps, but the generation config is not properly set. "
+ "Make sure to initialize the generation config with the correct attributes that are needed such as "
+ "`no_timestamps_token_id`. For more details on how to generate the approtiate config, refer to "
+ "https://github.com/huggingface/transformers/issues/21878#issuecomment-1451902363"
+ )
+
+ generation_config.return_timestamps = return_timestamps
+
+ if hasattr(generation_config, "no_timestamps_token_id"):
+ timestamp_begin = generation_config.no_timestamps_token_id + 1
+ else:
+ # BC for models missing the `no_timestamps_token_id` in the generation config when generating short-form
+ # with no timestamps. We set the timestamp begin token larger than the vocab size, such that the
+ # timestamp condition is never met in the decoding loop
+ timestamp_begin = self.config.vocab_size + 1
+
+ return timestamp_begin
+
+ @staticmethod
+ def _set_language_and_task(language, task, is_multilingual, generation_config):
+ if is_multilingual is not None:
+ if not hasattr(generation_config, "is_multilingual"):
+ raise ValueError(
+ "The generation config is outdated and is thus not compatible with the `is_multilingual` argument "
+ "to `generate`. Please update the generation config as per the instructions "
+ "https://github.com/huggingface/transformers/issues/25084#issuecomment-1664398224"
+ )
+ generation_config.is_multilingual = is_multilingual
+
+ if hasattr(generation_config, "is_multilingual") and not generation_config.is_multilingual:
+ if task is not None or language is not None:
+ raise ValueError(
+ "Cannot specify `task` or `language` for an English-only model. If the model is intended to be "
+ "multilingual, pass `is_multilingual=True` to generate, or update the generation config."
+ )
+
+ if language is not None:
+ if not hasattr(generation_config, "lang_to_id"):
+ raise ValueError(
+ "The generation config is outdated and is thus not compatible with the `language` argument "
+ "to `generate`. Please update the generation config as per the instructions "
+ "https://github.com/huggingface/transformers/issues/25084#issuecomment-1664398224"
+ )
+ generation_config.language = language
+
+ if task is not None:
+ if not hasattr(generation_config, "task_to_id"):
+ raise ValueError(
+ "The generation config is outdated and is thus not compatible with the `task` argument "
+ "to `generate`. Please update the generation config as per the instructions "
+ "https://github.com/huggingface/transformers/issues/25084#issuecomment-1664398224"
+ )
+ generation_config.task = task
+
+ def _retrieve_init_tokens(self, input_features, batch_size, generation_config, config, num_segment_frames, kwargs):
+ def replace_or_add(lst: list[int], num: int, itr: Iterator[int]):
+ """short function to replace num with a itr in lst"""
+ found = any(i in lst for i in itr)
+ if found:
+ lst = [num if i in itr else i for i in lst]
+ else:
+ lst.append(num)
+ return lst
+
+ def language_to_id(language: str) -> int:
+ language = language.lower()
+ if language in generation_config.lang_to_id:
+ language_token = language
+ elif language in TO_LANGUAGE_CODE:
+ language_token = f"<|{TO_LANGUAGE_CODE[language]}|>"
+ elif language in TO_LANGUAGE_CODE.values():
+ language_token = f"<|{language}|>"
+ else:
+ is_language_code = len(language) == 2
+ raise ValueError(
+ f"Unsupported language: {language}. Language should be one of:"
+ f" {list(TO_LANGUAGE_CODE.values()) if is_language_code else list(TO_LANGUAGE_CODE.keys())}."
+ )
+ if language_token not in generation_config.lang_to_id:
+ raise ValueError(
+ f"{language_token} is not supported by this specific model as it is not in the "
+ "`generation_config.lang_to_id`. (You should just add it to the generation config)"
+ )
+
+ return generation_config.lang_to_id[language_token]
+
+ task = getattr(generation_config, "task", None)
+ language = getattr(generation_config, "language", None)
+ init_tokens = [generation_config.decoder_start_token_id]
+
+ # TL;DR we silently ignore `forced_decoder_ids` (old flag) when `task` or `language` (new flags) are set.
+ # `forced_decoder_ids` is an old generation config attribute that is now deprecated in favor of `task` and
+ # `language` (see https://github.com/huggingface/transformers/pull/28687). Nevertheless, keep in mind that
+ # the original checkpoints all contain this attribute, and thus we should maintain backwards compatibility.
+ if task is None and language is None:
+ forced_decoder_ids = getattr(generation_config, "forced_decoder_ids", None)
+ # fallback: check the model config for forced_decoder_ids
+ if forced_decoder_ids is None and getattr(config, "forced_decoder_ids", None) is not None:
+ forced_decoder_ids = config.forced_decoder_ids
+
+ if forced_decoder_ids is not None:
+ logger.warning_once(
+ "Using custom `forced_decoder_ids` from the (generation) config. This is deprecated in favor of "
+ "the `task` and `language` flags/config options."
+ )
+
+ if forced_decoder_ids is not None and forced_decoder_ids[0][1] is None:
+ logger.warning_once(
+ "Transcription using a multilingual Whisper will default to language detection followed by "
+ "transcription instead of translation to English. This might be a breaking change for your "
+ "use case. If you want to instead always translate your audio to English, make sure to pass "
+ "`language='en'`. See https://github.com/huggingface/transformers/pull/28687 for more details."
+ )
+
+ if forced_decoder_ids is not None and forced_decoder_ids[0][0] == 1:
+ i = 1
+ while len(forced_decoder_ids) > 0 and forced_decoder_ids[0][0] == i:
+ init_tokens += [forced_decoder_ids[0][1]]
+ forced_decoder_ids = forced_decoder_ids[1:]
+ i += 1
+
+ if len(forced_decoder_ids) > 0:
+ raise ValueError(
+ f"You are using token ids in `forced_decoder_ids` that do not seem to correctly follow "
+ f"the prompt pattern of Whisper. Make sure that {forced_decoder_ids} has an entry for all "
+ f"indices >= 1 and < {forced_decoder_ids[0][0]}.",
+ )
+
+ is_lang_id_undefined = len(init_tokens) <= 1 or (len(init_tokens) > 1 and init_tokens[1] is None)
+
+ # Make sure language is a list of strings of the correct length
+ if isinstance(language, (list, tuple)):
+ if any(l is None for l in language):
+ raise TypeError(
+ "Expected `language` to be `None`, a single string (e.g. `'en'`), or a list of strings with "
+ "length equal to the batch size (e.g. `('en', 'fr')` for a batch size of 2). Got a list "
+ "containing `None`."
+ )
+ if len(language) != batch_size:
+ raise ValueError(
+ "When passing a list of languages, the length of the list must match the batch size. "
+ f"Expected length of {batch_size}, but got {len(language)} languages."
+ )
+ languages = language
+ elif language is None:
+ # Language will be detected for each item in batch
+ languages = [None] * batch_size
+ else:
+ languages = [language] # Use a length-1 list now, broadcast later
+
+ # Separate init_tokens for each language
+ init_tokens = [copy.copy(init_tokens) for _ in languages]
+
+ # Update init_tokens with languages
+ lang_ids = None
+ if language is not None:
+ lang_ids = [language_to_id(l) for l in languages]
+ elif hasattr(generation_config, "lang_to_id") and is_lang_id_undefined:
+ # language is not defined or intentionally set to `None` to trigger language detection
+ lang_ids = self.detect_language(
+ input_features=input_features,
+ encoder_outputs=kwargs.get("encoder_outputs", None),
+ generation_config=generation_config,
+ num_segment_frames=num_segment_frames,
+ ).tolist()
+ if lang_ids is not None:
+ # append or replace lang_ids to init_tokens
+ for i in range(len(init_tokens)):
+ if len(init_tokens[i]) > 1:
+ init_tokens[i][1] = lang_ids[i]
+ else:
+ init_tokens[i].append(lang_ids[i])
+ del languages
+
+ # Update init_tokens with task
+ for i in range(len(init_tokens)):
+ if task is not None:
+ if task in TASK_IDS:
+ init_tokens[i].append(generation_config.task_to_id[generation_config.task])
+ task_id = generation_config.task_to_id[generation_config.task]
+
+ # if task is defined it'll overwrite task ids that might have already been defined via the generation_config
+ replace_or_add(init_tokens[i], task_id, generation_config.task_to_id.values())
+ else:
+ raise ValueError(f"The `{task}` task is not supported. The task should be one of `{TASK_IDS}`")
+ elif language is not None and hasattr(generation_config, "task_to_id"):
+ # if language is defined, but no task id is in `init_tokens`, default to transcribe
+ if not any(ti in init_tokens[i] for ti in generation_config.task_to_id.values()):
+ init_tokens[i].append(generation_config.task_to_id["transcribe"])
+
+ if (
+ not generation_config.return_timestamps
+ and hasattr(generation_config, "no_timestamps_token_id")
+ and init_tokens[i][-1] != generation_config.no_timestamps_token_id
+ ):
+ init_tokens[i].append(generation_config.no_timestamps_token_id)
+ elif (
+ generation_config.return_timestamps and init_tokens[i][-1] == generation_config.no_timestamps_token_id
+ ):
+ logger.info(
+ "<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `'True'`."
+ )
+ init_tokens[i] = init_tokens[i][:-1]
+
+ # let's make sure we don't pass `None` tokens as prompt tokens
+ init_tokens[i] = [t for t in init_tokens[i] if t is not None]
+
+ return torch.as_tensor(init_tokens, dtype=torch.long, device=self.device).expand(batch_size, -1)
+
+ def detect_language(
+ self,
+ input_features: torch.FloatTensor | None = None,
+ encoder_outputs: torch.FloatTensor | BaseModelOutput | None = None,
+ generation_config: GenerationConfig | None = None,
+ num_segment_frames: int = 3000,
+ ) -> torch.Tensor:
+ """
+ Detects language from log-mel input features or encoder_outputs
+
+ Parameters:
+ input_features (`torch.Tensor` of shape `(batch_size, feature_size, sequence_length)`, *optional*):
+ Float values of log-mel features extracted from the raw speech waveform. The raw speech waveform can be obtained by
+ loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via
+ the soundfile library (`pip install soundfile`). To prepare the array into `input_features`, the
+ [`AutoFeatureExtractor`] should be used for extracting the mel features, padding and conversion into a
+ tensor of type `torch.FloatTensor`. See [`~WhisperFeatureExtractor.__call__`] for details.
+ encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
+ Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
+ `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
+ hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
+ generation_config (`~generation.GenerationConfig`, *optional*):
+ The generation configuration to be used as base parametrization for the generation call. `**kwargs`
+ passed to generate matching the attributes of `generation_config` will override them. If
+ `generation_config` is not provided, the default will be used, which had the following loading
+ priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model
+ configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s
+ default values, whose documentation should be checked to parameterize generation.
+ num_segment_frames (`int`, *optional*, defaults to 3000):
+ The number of log-mel frames the model expects
+
+ Return:
+ A `torch.LongTensor` representing the detected language ids.
+ """
+ if input_features is None and encoder_outputs is None:
+ raise ValueError("You have to specify either `input_features` or `encoder_outputs`")
+ elif input_features is not None and encoder_outputs is not None:
+ raise ValueError("Make sure to specify only one of `input_features` or `encoder_outputs` - not both!")
+ elif input_features is not None:
+ inputs = {"input_features": input_features[:, :, :num_segment_frames]}
+ batch_size = input_features.shape[0]
+ elif encoder_outputs is not None:
+ inputs = {"encoder_outputs": encoder_outputs}
+ batch_size = (
+ encoder_outputs[0].shape[0] if isinstance(encoder_outputs, BaseModelOutput) else encoder_outputs[0]
+ )
+
+ generation_config = generation_config or self.generation_config
+ decoder_input_ids = (
+ torch.ones((batch_size, 1), device=self.device, dtype=torch.long)
+ * generation_config.decoder_start_token_id
+ )
+
+ with torch.no_grad():
+ logits = self(**inputs, decoder_input_ids=decoder_input_ids, use_cache=False).logits[:, -1]
+
+ non_lang_mask = torch.ones_like(logits[0], dtype=torch.bool)
+ non_lang_mask[list(generation_config.lang_to_id.values())] = False
+
+ logits[:, non_lang_mask] = -np.inf
+
+ lang_ids = logits.argmax(-1)
+
+ return lang_ids
+
+ @staticmethod
+ def _check_decoder_input_ids(kwargs):
+ decoder_input_ids = kwargs.get("decoder_input_ids", None)
+ assistant_model = kwargs.get("assistant_model", None)
+ if decoder_input_ids is not None and assistant_model is not None:
+ raise ValueError(
+ "Passing `decoder_input_ids` is deprecated. Consider passing `prompt_ids` instead.",
+ )
+
+ @staticmethod
+ def _set_num_frames(return_token_timestamps, generation_config, attention_mask, kwargs):
+ if return_token_timestamps:
+ if getattr(generation_config, "task", None) == "translate":
+ logger.warning("Token-level timestamps may not be reliable for task 'translate'.")
+ if not hasattr(generation_config, "alignment_heads"):
+ raise ValueError(
+ "Model generation config has no `alignment_heads`, token-level timestamps not available. "
+ "See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config."
+ )
+ if attention_mask is not None:
+ generation_config.num_frames = attention_mask.sum(-1).cpu()
+ else:
+ logger.warning_once(
+ "When setting `return_token_timestamps` to `True`, make sure to pass an `attention_mask` to get precise token-level timestamps. You can retrieve the `attention_mask` by doing `processor(audio, ..., return_attention_mask=True)` "
+ )
+ generation_config.num_frames = None
+
+ @staticmethod
+ def _set_thresholds_and_condition(
+ generation_config,
+ logprob_threshold,
+ compression_ratio_threshold,
+ no_speech_threshold,
+ condition_on_prev_tokens,
+ ):
+ generation_config.logprob_threshold = (
+ logprob_threshold
+ if logprob_threshold is not None
+ else getattr(generation_config, "logprob_threshold", None)
+ )
+ generation_config.compression_ratio_threshold = (
+ compression_ratio_threshold
+ if compression_ratio_threshold is not None
+ else getattr(generation_config, "compression_ratio_threshold", None)
+ )
+ generation_config.no_speech_threshold = (
+ no_speech_threshold
+ if no_speech_threshold is not None
+ else getattr(generation_config, "no_speech_threshold", None)
+ )
+ generation_config.condition_on_prev_tokens = (
+ condition_on_prev_tokens
+ if condition_on_prev_tokens is not None
+ else getattr(generation_config, "condition_on_prev_tokens", None)
+ )
+
+ @staticmethod
+ def _set_prompt_condition_type(generation_config, prompt_condition_type):
+ allowed_cond_types = ["first-segment", "all-segments"]
+
+ # default to "first-segment"
+ prompt_condition_type = prompt_condition_type or allowed_cond_types[0]
+
+ if prompt_condition_type not in allowed_cond_types:
+ raise ValueError(
+ f"`prompt_condition_type={prompt_condition_type} does not exist. Make sure to set `prompt_condition_type` to one of {', '.join(allowed_cond_types)}"
+ )
+
+ if generation_config.condition_on_prev_tokens is not True and prompt_condition_type == "all-segments":
+ raise ValueError(
+ "Make sure to set `condition_on_prev_tokens=True` when setting `prompt_condition_type='all-segments'`."
+ )
+
+ generation_config.prompt_condition_type = prompt_condition_type
+
+ @staticmethod
+ def _set_condition_on_prev_tokens(condition_on_prev_tokens, generation_config):
+ condition_on_prev_tokens = (
+ condition_on_prev_tokens
+ if condition_on_prev_tokens is not None
+ else getattr(generation_config, "condition_on_prev_tokens", False)
+ )
+ generation_config.condition_on_prev_tokens = condition_on_prev_tokens
+
+ @staticmethod
+ def _retrieve_max_frames_and_seek(batch_size, attention_mask, total_input_frames, is_shortform):
+ if batch_size > 1 and not is_shortform and attention_mask is None:
+ raise ValueError(
+ "When doing batched long-form audio transcription, make sure to pass an `attention_mask`. You can retrieve the `attention_mask` by doing `processor(audio, ..., return_attention_mask=True)` "
+ )
+ elif batch_size > 1 and not is_shortform:
+ max_frames = attention_mask.sum(-1).cpu().to(torch.long)
+ seek = torch.zeros((batch_size,), dtype=torch.long)
+ else:
+ max_frames = torch.ones((batch_size,), dtype=torch.long) * total_input_frames
+ seek = torch.zeros((batch_size,), dtype=torch.long)
+
+ return max_frames, seek
+
+ def _retrieve_logit_processors(self, generation_config, logits_processor, begin_index, num_beams, device):
+ if generation_config.return_timestamps is True:
+ timestamp_processor = WhisperTimeStampLogitsProcessor(generation_config, begin_index=begin_index)
+ logits_processor = (
+ [timestamp_processor] if logits_processor is None else [timestamp_processor] + logits_processor
+ )
+
+ if generation_config.suppress_tokens is not None:
+ suppress_tokens_processor = SuppressTokensLogitsProcessor(generation_config.suppress_tokens, device=device)
+ logits_processor = (
+ [suppress_tokens_processor]
+ if logits_processor is None
+ else [suppress_tokens_processor] + logits_processor
+ )
+ generation_config.suppress_tokens = None
+
+ if generation_config.begin_suppress_tokens is not None:
+ begin_suppress_processor = SuppressTokensAtBeginLogitsProcessor(
+ generation_config.begin_suppress_tokens, begin_index=begin_index, device=device
+ )
+ logits_processor = (
+ [begin_suppress_processor]
+ if logits_processor is None
+ else [begin_suppress_processor] + logits_processor
+ )
+ generation_config.begin_suppress_tokens = None
+
+ if generation_config.no_speech_threshold is not None:
+ no_speech_detector = WhisperNoSpeechDetection(
+ no_speech_token=generation_config.no_timestamps_token_id - 1,
+ begin_index=begin_index,
+ scores_is_logprobs=num_beams > 1,
+ )
+ logits_processor = (
+ [no_speech_detector] if logits_processor is None else [no_speech_detector] + logits_processor
+ )
+ no_speech_detector.set_model(self)
+
+ return logits_processor
+
+ @staticmethod
+ def _maybe_reduce_batch(input_features, seek, max_frames, cur_bsz, batch_idx_map):
+ prev_bsz = cur_bsz
+ new_batch_idx_map = []
+ for i in range(prev_bsz):
+ prev_i = batch_idx_map[i]
+ if seek[prev_i] >= max_frames[prev_i]:
+ cut_index = i + (cur_bsz - prev_bsz)
+ cur_bsz -= 1
+ input_features = torch.cat([input_features[:cut_index], input_features[cut_index + 1 :]], dim=0)
+ else:
+ # cut out index that goes away
+ new_batch_idx_map.append(prev_i)
+
+ return input_features, cur_bsz, new_batch_idx_map
+
+ @staticmethod
+ def _get_input_segment(input_features, seek, seek_num_frames, num_segment_frames, cur_bsz, batch_idx_map):
+ if input_features is None:
+ return None
+
+ segment_input = []
+ for i in range(cur_bsz):
+ prev_i = batch_idx_map[i]
+ segment_input_slice = input_features[i : i + 1, :, seek[prev_i] : seek[prev_i] + seek_num_frames[prev_i]]
+
+ if segment_input_slice.shape[-1] < num_segment_frames:
+ # pad to 3000 if necessary
+ segment_input_slice = F.pad(
+ segment_input_slice, pad=(0, num_segment_frames - segment_input_slice.shape[-1])
+ )
+
+ segment_input.append(segment_input_slice)
+
+ segment_input = torch.cat(segment_input, dim=0)
+
+ return segment_input
+
+ @staticmethod
+ def _prepare_decoder_input_ids(
+ cur_bsz,
+ init_tokens,
+ current_segments,
+ batch_idx_map,
+ do_condition_on_prev_tokens,
+ prompt_ids,
+ generation_config,
+ config,
+ device,
+ suppress_tokens,
+ timestamp_begin,
+ kwargs,
+ ):
+ if "decoder_input_ids" in kwargs:
+ decoder_input_ids = kwargs.pop("decoder_input_ids")
+
+ return decoder_input_ids, kwargs
+
+ cut_off_length = config.max_target_positions // 2 - 1
+
+ decoder_input_ids = init_tokens[batch_idx_map]
+
+ prev_start_of_text = getattr(generation_config, "prev_sot_token_id", None)
+ if prev_start_of_text is None:
+ if suppress_tokens is not None and len(suppress_tokens) >= 2:
+ prev_start_of_text = suppress_tokens[-2]
+ else:
+ prev_start_of_text = None
+
+ if any(do_condition_on_prev_tokens) and len(current_segments[0]) > 0:
+ # according to https://github.com/openai/whisper/blob/e58f28804528831904c3b6f2c0e473f346223433/whisper/decoding.py#L609
+ active_segments = [current_segments[i] if do_condition_on_prev_tokens[i] else None for i in batch_idx_map]
+
+ if prompt_ids is not None and generation_config.prompt_condition_type == "all-segments":
+ prev_ids = prompt_ids
+ else:
+ one_tensor = torch.ones((cur_bsz, 1), device=device, dtype=torch.long)
+ prev_ids = prev_start_of_text * one_tensor[0] if prev_start_of_text is not None else None
+
+ padding = "max_length" if generation_config.cache_implementation == "static" else "longest"
+
+ prev_tokens = _pad_to_max_length(
+ active_segments,
+ generation_config.pad_token_id,
+ device=device,
+ padding_side="left",
+ padding=padding,
+ bos_token_tensor=prev_ids,
+ cut_off_length=cut_off_length,
+ skip_ending_double_timestamps=True,
+ timestamp_begin=timestamp_begin,
+ )
+ decoder_input_ids = torch.cat([prev_tokens, decoder_input_ids], dim=-1)
+
+ kwargs["decoder_attention_mask"] = decoder_input_ids != generation_config.pad_token_id
+ elif prompt_ids is not None:
+ prev_tokens = prompt_ids[None].repeat(decoder_input_ids.shape[0], 1)
+ decoder_input_ids = torch.cat([prev_tokens, decoder_input_ids], dim=-1)
+ # make sure `"decoder_attention_mask"` is not passed to forward
+ kwargs.pop("decoder_attention_mask", None)
+ else:
+ # make sure `"decoder_attention_mask"` is not passed to forward
+ kwargs.pop("decoder_attention_mask", None)
+
+ return decoder_input_ids, kwargs
+
+ def _set_max_new_tokens_and_length(self, config, decoder_input_ids, generation_config):
+ max_new_tokens = generation_config.max_new_tokens if generation_config.max_new_tokens is not None else 0
+ if max_new_tokens + decoder_input_ids.shape[-1] > self.config.max_target_positions:
+ raise ValueError(
+ f"The length of `decoder_input_ids`, including special start tokens, prompt tokens, and previous tokens, is {decoder_input_ids.shape[-1]}, "
+ f" and `max_new_tokens` is {max_new_tokens}. Thus, the combined length of "
+ f"`decoder_input_ids` and `max_new_tokens` is: {max_new_tokens + decoder_input_ids.shape[-1]}. This exceeds the "
+ f"`max_target_positions` of the Whisper model: {self.config.max_target_positions}. "
+ "You should either reduce the length of your prompt, or reduce the value of `max_new_tokens`, "
+ f"so that their combined length is less than {self.config.max_target_positions}."
+ )
+
+ num_initial_tokens = min(config.max_target_positions // 2 - 1, decoder_input_ids.shape[-1] - 1)
+
+ # Make sure we don't get larger than `max_length`
+ if generation_config.max_length is not None and generation_config.max_new_tokens is None:
+ max_length = min(generation_config.max_length + num_initial_tokens, config.max_target_positions)
+ logger.info(
+ f"Increase max_length from {generation_config.max_length} to {max_length} since input is conditioned on previous segment."
+ )
+ elif (
+ generation_config.max_new_tokens is not None
+ and generation_config.max_new_tokens + decoder_input_ids.shape[-1] > config.max_target_positions
+ ):
+ max_new_tokens = config.max_target_positions - decoder_input_ids.shape[-1]
+ generation_config.max_new_tokens = max_new_tokens
+
+ @staticmethod
+ def _retrieve_compression_ratio(tokens, vocab_size):
+ """Compute byte length of zlib compressed token bytes vs. byte length of raw token bytes"""
+ length = int(math.log2(vocab_size) / 8) + 1
+ token_bytes = b"".join([t.to_bytes(length, "little") for t in tokens.tolist()])
+ compression_ratio = len(token_bytes) / len(zlib.compress(token_bytes))
+
+ return compression_ratio
+
+ @staticmethod
+ def _retrieve_avg_logprobs(scores, tokens, temperature):
+ rescale_temperature = temperature if temperature > 0.0 else 1
+ scores = torch.stack(scores).to(tokens.device)
+
+ if scores.shape[0] > tokens.shape[0]:
+ scores = scores[: tokens.shape[0]]
+ else:
+ tokens = tokens[-scores.shape[0] :]
+
+ logprobs = F.log_softmax((scores * rescale_temperature).float(), dim=-1).to(scores.dtype)
+
+ # retrieve logprob of selected tokens and sum
+ # don't remove the eos token logprob! it counts in avg_logprob calculation in the original implementation
+ sum_logprobs = sum(logprobs[i][tokens[i]] for i in range(logprobs.shape[0]))
+
+ avg_logprobs = sum_logprobs / len(tokens)
+ return avg_logprobs
+
+ @staticmethod
+ def _retrieve_segment(
+ seek_sequence,
+ seek_outputs,
+ time_offset,
+ timestamp_begin,
+ seek_num_frames,
+ time_precision,
+ time_precision_features,
+ input_stride,
+ prev_idx,
+ idx,
+ return_token_timestamps,
+ decoder_input_ids,
+ ):
+ # find the predicted "end of segment" predictions of Whisper
+ # "end of segment" predictions occur whenever Whisper predicts a timestamp token
+ timestamp_tokens: torch.Tensor = seek_sequence.ge(timestamp_begin)
+ single_timestamp_ending = timestamp_tokens[-2:].tolist() == [False, True]
+ timestamp_segment_indices = torch.where(timestamp_tokens[:-1] & timestamp_tokens[1:])[0]
+ timestamp_segment_indices.add_(1)
+ token_timestamps = seek_outputs[idx]["token_timestamps"] if return_token_timestamps else []
+ idx_offset = decoder_input_ids.shape[-1]
+ device = seek_sequence.device
+
+ # If whisper predicted a "end of segment" via a timestep token, let's go ever each
+ # "end of segment" prediction and slice the decoding into segments accordingly
+ if len(timestamp_segment_indices) > 0:
+ # if the output contains two consecutive timestamp tokens
+ slices = timestamp_segment_indices.tolist()
+ segments = []
+ if single_timestamp_ending:
+ slices.append(len(seek_sequence))
+ else:
+ # we want to include the last timestamp token in the last segment to know it was no single ending
+ slices[-1] += 1
+
+ last_slice = 0
+ # Add each segment to list of all segments
+ for i, current_slice in enumerate(slices):
+ is_last_slice = i == len(slices) - 1
+ sliced_tokens = seek_sequence[last_slice:current_slice]
+ start_timestamp_pos = sliced_tokens[0] - timestamp_begin
+ idx_sliced_tokens = -1 if not is_last_slice or single_timestamp_ending else -2
+ end_timestamp_pos = sliced_tokens[idx_sliced_tokens] - timestamp_begin
+ segments.append(
+ {
+ "start": time_offset[prev_idx]
+ + start_timestamp_pos.to(torch.float32 if device.type == "mps" else torch.float64)
+ * time_precision,
+ "end": time_offset[prev_idx]
+ + end_timestamp_pos.to(torch.float32 if device.type == "mps" else torch.float64)
+ * time_precision,
+ "tokens": sliced_tokens,
+ "idxs": (idx_offset + last_slice, idx_offset + current_slice),
+ "result": seek_outputs[idx],
+ }
+ )
+ if return_token_timestamps:
+ segments[-1]["token_timestamps"] = (
+ token_timestamps[idx_offset + last_slice : idx_offset + current_slice] + time_offset[prev_idx]
+ )
+ last_slice = current_slice
+
+ if single_timestamp_ending:
+ # single timestamp at the end means no speech after the last timestamp.
+ segment_offset = seek_num_frames[prev_idx]
+ else:
+ # otherwise, ignore the unfinished segment and seek to the last timestamp
+ # here we throw away all predictions after the last predicted "end of segment"
+ # since we are cutting right in the middle of an audio
+ last_timestamp_pos = seek_sequence[last_slice - 2].item() - timestamp_begin
+ segment_offset = last_timestamp_pos * input_stride
+ else:
+ # If whisper does not predict any "end of segment" token, then
+ # the whole decoding is considered a segment and we add it to the list of segments
+ timestamps = seek_sequence[timestamp_tokens.nonzero().flatten()]
+ last_timestamp_pos = int(seek_num_frames[prev_idx] * time_precision_features / time_precision)
+ if timestamps.numel() > 0 and timestamps[-1] != timestamp_begin:
+ # no consecutive timestamps but it has a timestamp; use the last one.
+ last_timestamp_pos = (timestamps[-1] - timestamp_begin).to(
+ torch.float32 if device.type == "mps" else torch.float64
+ )
+ segments = [
+ {
+ "start": time_offset[prev_idx],
+ "end": time_offset[prev_idx] + last_timestamp_pos * time_precision,
+ "tokens": seek_sequence,
+ "idxs": (idx_offset, idx_offset + len(seek_sequence)),
+ "result": seek_outputs[idx],
+ }
+ ]
+ if return_token_timestamps:
+ segments[-1]["token_timestamps"] = (
+ token_timestamps[idx_offset : idx_offset + len(seek_sequence)] + time_offset[prev_idx]
+ )
+ segment_offset = seek_num_frames[prev_idx]
+
+ return segments, segment_offset
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/whisper/modeling_whisper.py b/.venv/lib/python3.12/site-packages/transformers/models/whisper/modeling_whisper.py
new file mode 100644
index 0000000000000000000000000000000000000000..47f367c4e55e6139ec7528bc697475218d49ba40
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/whisper/modeling_whisper.py
@@ -0,0 +1,1359 @@
+# Copyright 2022 The OpenAI Authors and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch Whisper model."""
+
+import math
+from collections.abc import Callable
+
+import numpy as np
+import torch
+from torch import nn
+from torch.nn import CrossEntropyLoss
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
+from ...generation import GenerationMixin
+from ...masking_utils import create_causal_mask
+from ...modeling_flash_attention_utils import (
+ FlashAttentionKwargs,
+)
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutput,
+ BaseModelOutputWithPastAndCrossAttentions,
+ CausalLMOutputWithCrossAttentions,
+ Seq2SeqLMOutput,
+ Seq2SeqModelOutput,
+ SequenceClassifierOutput,
+)
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
+from ...utils.generic import merge_with_config_defaults
+from ...utils.output_capturing import OutputRecorder, capture_outputs
+from .configuration_whisper import WhisperConfig
+from .generation_whisper import WhisperGenerationMixin
+
+
+logger = logging.get_logger(__name__)
+
+_HIDDEN_STATES_START_POSITION = 1
+
+
+def sinusoids(length: int, channels: int, max_timescale: float = 10000) -> torch.Tensor:
+ """Returns sinusoids for positional embedding"""
+ if channels % 2 != 0:
+ raise ValueError(
+ f"Number of channels has to be divisible by 2 for sinusoidal positional embeddings, got {channels} channels."
+ )
+ log_timescale_increment = math.log(max_timescale) / (channels // 2 - 1)
+ inv_timescales = torch.exp(-log_timescale_increment * torch.arange(channels // 2))
+ scaled_time = torch.arange(length).view(-1, 1) * inv_timescales.view(1, -1)
+ return torch.cat([scaled_time.sin(), scaled_time.cos()], dim=1)
+
+
+# Copied from transformers.models.bart.modeling_bart.shift_tokens_right
+def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
+ """
+ Shift input ids one token to the right.
+ """
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
+ shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
+ shifted_input_ids[:, 0] = decoder_start_token_id
+
+ if pad_token_id is None:
+ raise ValueError("self.model.config.pad_token_id has to be defined.")
+ # replace possible -100 values in labels by `pad_token_id`
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
+
+ return shifted_input_ids
+
+
+# Copied from transformers.models.wav2vec2.modeling_wav2vec2._compute_mask_indices
+def _compute_mask_indices(
+ shape: tuple[int, int],
+ mask_prob: float,
+ mask_length: int,
+ attention_mask: torch.LongTensor | None = None,
+ min_masks: int = 0,
+) -> np.ndarray:
+ """
+ Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for
+ ASR](https://huggingface.co/papers/1904.08779). Note that this method is not optimized to run on TPU and should be run on
+ CPU as part of the preprocessing during training.
+
+ Args:
+ shape: The shape for which to compute masks. This should be of a tuple of size 2 where
+ the first element is the batch size and the second element is the length of the axis to span.
+ mask_prob: The percentage of the whole axis (between 0 and 1) which will be masked. The number of
+ independently generated mask spans of length `mask_length` is computed by
+ `mask_prob*shape[1]/mask_length`. Note that due to overlaps, `mask_prob` is an upper bound and the
+ actual percentage will be smaller.
+ mask_length: size of the mask
+ min_masks: minimum number of masked spans
+ attention_mask: A (right-padded) attention mask which independently shortens the feature axis of
+ each batch dimension.
+ """
+ batch_size, sequence_length = shape
+
+ if mask_length < 1:
+ raise ValueError("`mask_length` has to be bigger than 0.")
+
+ if mask_length > sequence_length:
+ raise ValueError(
+ f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length}"
+ f" and `sequence_length`: {sequence_length}`"
+ )
+
+ # epsilon is used for probabilistic rounding
+ epsilon = np.random.rand(1).item()
+
+ def compute_num_masked_span(input_length):
+ """Given input length, compute how many spans should be masked"""
+ num_masked_span = int(mask_prob * input_length / mask_length + epsilon)
+ num_masked_span = max(num_masked_span, min_masks)
+
+ # make sure num masked span <= sequence_length
+ if num_masked_span * mask_length > sequence_length:
+ num_masked_span = sequence_length // mask_length
+
+ # make sure num_masked span is also <= input_length - (mask_length - 1)
+ if input_length - (mask_length - 1) < num_masked_span:
+ num_masked_span = max(input_length - (mask_length - 1), 0)
+
+ return num_masked_span
+
+ # compute number of masked spans in batch
+ input_lengths = (
+ attention_mask.detach().sum(-1).tolist()
+ if attention_mask is not None
+ else [sequence_length for _ in range(batch_size)]
+ )
+
+ # SpecAugment mask to fill
+ spec_aug_mask = np.zeros((batch_size, sequence_length), dtype=bool)
+ spec_aug_mask_idxs = []
+
+ max_num_masked_span = compute_num_masked_span(sequence_length)
+
+ if max_num_masked_span == 0:
+ return spec_aug_mask
+
+ for input_length in input_lengths:
+ # compute num of masked spans for this input
+ num_masked_span = compute_num_masked_span(input_length)
+
+ # get random indices to mask
+ spec_aug_mask_idx = np.random.choice(
+ np.arange(input_length - (mask_length - 1)), num_masked_span, replace=False
+ )
+
+ # pick first sampled index that will serve as a dummy index to pad vector
+ # to ensure same dimension for all batches due to probabilistic rounding
+ # Picking first sample just pads those vectors twice.
+ if len(spec_aug_mask_idx) == 0:
+ # this case can only happen if `input_length` is strictly smaller then
+ # `sequence_length` in which case the last token has to be a padding
+ # token which we can use as a dummy mask id
+ dummy_mask_idx = sequence_length - 1
+ else:
+ dummy_mask_idx = spec_aug_mask_idx[0]
+
+ spec_aug_mask_idx = np.concatenate(
+ [spec_aug_mask_idx, np.ones(max_num_masked_span - num_masked_span, dtype=np.int32) * dummy_mask_idx]
+ )
+ spec_aug_mask_idxs.append(spec_aug_mask_idx)
+
+ spec_aug_mask_idxs = np.array(spec_aug_mask_idxs)
+
+ # expand masked indices to masked spans
+ spec_aug_mask_idxs = np.broadcast_to(
+ spec_aug_mask_idxs[:, :, None], (batch_size, max_num_masked_span, mask_length)
+ )
+ spec_aug_mask_idxs = spec_aug_mask_idxs.reshape(batch_size, max_num_masked_span * mask_length)
+
+ # add offset to the starting indexes so that indexes now create a span
+ offsets = np.arange(mask_length)[None, None, :]
+ offsets = np.broadcast_to(offsets, (batch_size, max_num_masked_span, mask_length)).reshape(
+ batch_size, max_num_masked_span * mask_length
+ )
+ spec_aug_mask_idxs = spec_aug_mask_idxs + offsets
+
+ # ensure that we cannot have indices larger than sequence_length
+ if spec_aug_mask_idxs.max() > sequence_length - 1:
+ spec_aug_mask_idxs[spec_aug_mask_idxs > sequence_length - 1] = sequence_length - 1
+
+ # scatter indices to mask
+ np.put_along_axis(spec_aug_mask, spec_aug_mask_idxs, 1, -1)
+
+ return spec_aug_mask
+
+
+class WhisperPositionalEmbedding(nn.Embedding):
+ def __init__(self, num_positions: int, embedding_dim: int, padding_idx: int | None = None):
+ super().__init__(num_positions, embedding_dim)
+
+ def forward(self, input_ids, past_key_values_length=0, position_ids=None):
+ if position_ids is None:
+ return self.weight[past_key_values_length : past_key_values_length + input_ids.shape[1]]
+ else:
+ return self.weight[position_ids]
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float | None = None,
+ dropout: float = 0.0,
+ **kwargs,
+):
+ if scaling is None:
+ scaling = query.size(-1) ** -0.5
+
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+class WhisperAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(
+ self,
+ embed_dim: int,
+ num_heads: int,
+ dropout: float = 0.0,
+ is_decoder: bool = False,
+ bias: bool = True,
+ is_causal: bool = False,
+ layer_idx: int | None = None,
+ config: WhisperConfig | None = None,
+ ):
+ super().__init__()
+ self.embed_dim = embed_dim
+ self.num_heads = num_heads
+ self.dropout = dropout
+ self.head_dim = embed_dim // num_heads
+ self.config = config
+
+ if (self.head_dim * num_heads) != self.embed_dim:
+ raise ValueError(
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
+ f" and `num_heads`: {num_heads})."
+ )
+ self.scaling = self.head_dim**-0.5
+ self.is_decoder = is_decoder
+ self.is_causal = is_causal
+
+ if layer_idx is None and is_decoder:
+ logger.warning_once(
+ f"Instantiating a decoder {self.__class__.__name__} without passing `layer_idx` is not recommended and "
+ "will to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
+ "when creating this class."
+ )
+ self.layer_idx = layer_idx
+
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=False)
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ key_value_states: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ attention_mask: torch.Tensor | None = None,
+ output_attentions: bool = False,
+ # TODO: we need a refactor so that the different attention modules can get their specific kwargs
+ # ATM, we have mixed things encoder, decoder, and encoder-decoder attn
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
+ """Input shape: Batch x Time x Channel"""
+
+ # if key_value_states are provided this layer is used as a cross-attention layer
+ # for the decoder
+ is_cross_attention = key_value_states is not None
+
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ # Scaling is susceptible to floating point arithmetics' inprecisions
+ # which can lead to different results (this is dependent from model
+ # to model, e.g. whisper is one such case). We therefore keep the
+ # original order of scaling to follow the original implementation
+ # and enforce no scaling (1.0) in the attention call below.
+ query_states = (self.q_proj(hidden_states) * self.scaling).view(hidden_shape).transpose(1, 2).contiguous()
+
+ # Check is encoder-decoder model is being used. Otherwise we'll get `DynamicCache`
+ if past_key_values is not None and isinstance(past_key_values, EncoderDecoderCache):
+ is_updated = past_key_values.is_updated.get(self.layer_idx)
+ if is_cross_attention:
+ # after the first generated id, we can subsequently re-use all key/value_states from cache
+ past_key_values.is_updated[self.layer_idx] = True
+ past_key_values = past_key_values.cross_attention_cache
+ else:
+ past_key_values = past_key_values.self_attention_cache
+
+ # use key_value_states if cross attention
+ current_states = key_value_states if key_value_states is not None else hidden_states
+ if is_cross_attention and past_key_values and is_updated:
+ # reuse k,v, cross_attentions
+ key_states = past_key_values.layers[self.layer_idx].keys
+ value_states = past_key_values.layers[self.layer_idx].values
+ else:
+ # Use the query's batch dimension for kv view so that a different-batch
+ # encoder output (e.g. in tests) gets absorbed into the sequence axis,
+ # preserving backward-compatible behaviour.
+ kv_shape = (input_shape[0], -1, self.num_heads, self.head_dim)
+ key_states = self.k_proj(current_states).view(kv_shape).transpose(1, 2).contiguous()
+ value_states = self.v_proj(current_states).view(kv_shape).transpose(1, 2).contiguous()
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.dropout,
+ scaling=1.0,
+ output_attentions=output_attentions,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.out_proj(attn_output)
+
+ return attn_output, attn_weights
+
+
+# Copied from transformers.models.mbart.modeling_mbart.MBartEncoderLayer with MBart->Whisper, MBART->WHISPER
+class WhisperEncoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: WhisperConfig):
+ super().__init__()
+ self.embed_dim = config.d_model
+
+ self.self_attn = WhisperAttention(
+ embed_dim=self.embed_dim,
+ num_heads=config.encoder_attention_heads,
+ dropout=config.attention_dropout,
+ config=config,
+ )
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
+ self.dropout = config.dropout
+ self.activation_fn = ACT2FN[config.activation_function]
+ self.activation_dropout = config.activation_dropout
+ self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
+ self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
+ attention_mask (`torch.FloatTensor`): attention mask of size
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
+ """
+ residual = hidden_states
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ **kwargs,
+ )
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+
+ residual = hidden_states
+ hidden_states = self.final_layer_norm(hidden_states)
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
+ hidden_states = self.fc2(hidden_states)
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+
+ if hidden_states.dtype == torch.float16:
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
+
+ return hidden_states
+
+
+class WhisperDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: WhisperConfig, layer_idx: int | None = None):
+ super().__init__()
+ self.embed_dim = config.d_model
+
+ self.self_attn = WhisperAttention(
+ embed_dim=self.embed_dim,
+ num_heads=config.decoder_attention_heads,
+ dropout=config.attention_dropout,
+ is_decoder=True,
+ is_causal=True,
+ layer_idx=layer_idx,
+ config=config,
+ )
+ self.dropout = config.dropout
+ self.activation_fn = ACT2FN[config.activation_function]
+ self.activation_dropout = config.activation_dropout
+
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
+ self.encoder_attn = WhisperAttention(
+ self.embed_dim,
+ config.decoder_attention_heads,
+ dropout=config.attention_dropout,
+ is_decoder=True,
+ layer_idx=layer_idx,
+ config=config,
+ )
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
+ self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
+ self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ past_key_values: EncoderDecoderCache | None = None,
+ use_cache: bool | None = True,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
+ attention_mask (`torch.FloatTensor`): attention mask of size
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
+ encoder_hidden_states (`torch.FloatTensor`):
+ cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
+ past_key_values (`Cache`): cached past key and value projection states
+ """
+ residual = hidden_states
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states,
+ past_key_values=past_key_values,
+ attention_mask=attention_mask,
+ **kwargs,
+ )
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+
+ # Cross-Attention Block
+ if encoder_hidden_states is not None:
+ residual = hidden_states
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
+ hidden_states, _ = self.encoder_attn(
+ hidden_states,
+ key_value_states=encoder_hidden_states,
+ attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.final_layer_norm(hidden_states)
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
+ hidden_states = self.fc2(hidden_states)
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+
+ return hidden_states
+
+
+@auto_docstring
+class WhisperPreTrainedModel(PreTrainedModel):
+ config: WhisperConfig
+ base_model_prefix = "model"
+ main_input_name = "input_features"
+ input_modalities = ("audio", "text")
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["WhisperEncoderLayer", "WhisperDecoderLayer"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+
+ _can_compile_fullgraph = True
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ if isinstance(module, WhisperEncoder):
+ init.copy_(module.embed_positions.weight, sinusoids(*module.embed_positions.weight.shape))
+ elif isinstance(module, WhisperForAudioClassification):
+ if self.config.use_weighted_layer_sum:
+ init.constant_(module.layer_weights, 1.0 / (self.config.num_hidden_layers + 1))
+
+ def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor):
+ """
+ Computes the output length of the convolutional layers
+ """
+ input_lengths = (input_lengths - 1) // 2 + 1
+
+ return input_lengths
+
+
+class WhisperEncoder(WhisperPreTrainedModel):
+ """
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
+ [`WhisperEncoderLayer`].
+
+ Args:
+ config: WhisperConfig
+ """
+
+ _can_record_outputs = {
+ "hidden_states": WhisperEncoderLayer,
+ "attentions": WhisperAttention,
+ }
+ input_modalities = ("audio",)
+
+ def __init__(self, config: WhisperConfig):
+ super().__init__(config)
+ self.dropout = config.dropout
+ self.layerdrop = config.encoder_layerdrop
+
+ embed_dim = config.d_model
+ self.num_mel_bins = config.num_mel_bins
+ self.padding_idx = config.pad_token_id
+ self.max_source_positions = config.max_source_positions
+ self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
+
+ self.conv1 = nn.Conv1d(self.num_mel_bins, embed_dim, kernel_size=3, padding=1)
+ self.conv2 = nn.Conv1d(embed_dim, embed_dim, kernel_size=3, stride=2, padding=1)
+
+ self.embed_positions = nn.Embedding(self.max_source_positions, embed_dim)
+ self.embed_positions.requires_grad_(False)
+
+ self.layers = nn.ModuleList([WhisperEncoderLayer(config) for _ in range(config.encoder_layers)])
+ self.layer_norm = nn.LayerNorm(config.d_model)
+
+ self.gradient_checkpointing = False
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def _freeze_parameters(self):
+ for param in self.parameters():
+ param.requires_grad = False
+ self._requires_grad = False
+
+ def get_input_embeddings(self) -> nn.Module:
+ return self.conv1
+
+ def set_input_embeddings(self, value: nn.Module):
+ self.conv1 = value
+
+ @merge_with_config_defaults
+ @capture_outputs
+ def forward(
+ self,
+ input_features,
+ attention_mask=None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutput:
+ r"""
+ Args:
+ input_features (`torch.LongTensor` of shape `(batch_size, feature_size, sequence_length)`):
+ Float values of mel features extracted from the raw speech waveform. Raw speech waveform can be
+ obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
+ `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
+ the soundfile library (`pip install soundfile`). To prepare the array into
+ `input_features`, the [`AutoFeatureExtractor`] should be used for extracting the mel features, padding
+ and conversion into a tensor of type `torch.FloatTensor`. See [`~WhisperFeatureExtractor.__call__`]
+ attention_mask (`torch.Tensor`)`, *optional*):
+ Whisper does not support masking of the `input_features`, this argument is preserved for compatibility,
+ but it is not used. By default the silence in the input log mel spectrogram are ignored.
+ """
+
+ expected_seq_length = self.config.max_source_positions * self.conv1.stride[0] * self.conv2.stride[0]
+ if input_features.shape[-1] != expected_seq_length:
+ raise ValueError(
+ f"Whisper expects the mel input features to be of length {expected_seq_length}, but found {input_features.shape[-1]}. Make sure to pad the input mel features to {expected_seq_length}."
+ )
+
+ inputs_embeds = nn.functional.gelu(self.conv1(input_features))
+ inputs_embeds = nn.functional.gelu(self.conv2(inputs_embeds))
+
+ inputs_embeds = inputs_embeds.permute(0, 2, 1)
+ all_positions = torch.arange(self.embed_positions.num_embeddings, device=inputs_embeds.device)
+
+ hidden_states = inputs_embeds + self.embed_positions(all_positions)
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+
+ for idx, encoder_layer in enumerate(self.layers):
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
+ to_drop = False
+ if self.training:
+ dropout_probability = torch.rand([])
+ if dropout_probability < self.layerdrop: # skip the layer
+ to_drop = True
+
+ if not to_drop:
+ hidden_states = encoder_layer(
+ hidden_states,
+ None,
+ **kwargs,
+ )
+
+ hidden_states = self.layer_norm(hidden_states)
+
+ return BaseModelOutput(
+ last_hidden_state=hidden_states,
+ )
+
+
+class WhisperDecoder(WhisperPreTrainedModel):
+ """
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`WhisperDecoderLayer`]
+
+ Args:
+ config: WhisperConfig
+ """
+
+ _can_record_outputs = {
+ "hidden_states": WhisperDecoderLayer,
+ "attentions": OutputRecorder(WhisperAttention, index=1, layer_name="self_attn"),
+ "cross_attentions": OutputRecorder(WhisperAttention, index=1, layer_name="encoder_attn"),
+ }
+
+ main_input_name = "input_ids"
+ input_modalities = ("text",)
+
+ def __init__(self, config: WhisperConfig):
+ super().__init__(config)
+ self.dropout = config.dropout
+ self.layerdrop = config.decoder_layerdrop
+ self.padding_idx = config.pad_token_id
+ self.max_target_positions = config.max_target_positions
+ self.max_source_positions = config.max_source_positions
+ self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model, self.padding_idx)
+ self.embed_positions = WhisperPositionalEmbedding(self.max_target_positions, config.d_model)
+
+ self.layers = nn.ModuleList(
+ [WhisperDecoderLayer(config, layer_idx) for layer_idx in range(config.decoder_layers)]
+ )
+
+ self.layer_norm = nn.LayerNorm(config.d_model)
+
+ self.gradient_checkpointing = False
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ def forward(
+ self,
+ input_ids=None,
+ attention_mask=None,
+ encoder_hidden_states=None,
+ past_key_values=None,
+ inputs_embeds=None,
+ position_ids=None,
+ use_cache=None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutputWithPastAndCrossAttentions:
+ r"""
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
+ provide it.
+
+ Indices can be obtained using [`WhisperTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
+ of the decoder.
+ past_key_values (`EncoderDecoderCache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
+
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
+ inputs_embeds (`torch.FloatTensor` of
+ shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing
+ `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more
+ control over how to convert `input_ids` indices into associated vectors than the model's internal
+ embedding lookup matrix.
+ """
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ if use_cache and past_key_values is None:
+ past_key_values = (
+ EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
+ if encoder_hidden_states is not None or self.config.is_encoder_decoder
+ else DynamicCache(config=self.config)
+ )
+
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
+
+ if position_ids is None:
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_key_values_length
+ position_ids = position_ids.unsqueeze(0).repeat(inputs_embeds.shape[0], 1)
+
+ # embed positions
+ if input_ids is not None:
+ positions = self.embed_positions(
+ input_ids, past_key_values_length=past_key_values_length, position_ids=position_ids
+ )
+ else:
+ positions = self.embed_positions(
+ inputs_embeds, past_key_values_length=past_key_values_length, position_ids=position_ids
+ )
+
+ hidden_states = inputs_embeds + positions.to(inputs_embeds.device)
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+
+ causal_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_ids=position_ids,
+ )
+
+ for idx, decoder_layer in enumerate(self.layers):
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
+ if self.training:
+ dropout_probability = torch.rand([])
+ if dropout_probability < self.layerdrop:
+ continue
+
+ hidden_states = decoder_layer(
+ hidden_states,
+ causal_mask,
+ encoder_hidden_states,
+ encoder_attention_mask=None,
+ past_key_values=past_key_values if use_cache else None,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = self.layer_norm(hidden_states)
+
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ )
+
+
+@auto_docstring
+class WhisperModel(WhisperPreTrainedModel):
+ def __init__(self, config: WhisperConfig):
+ super().__init__(config)
+
+ self.encoder = WhisperEncoder(config)
+ self.decoder = WhisperDecoder(config)
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.decoder.embed_tokens
+
+ def set_input_embeddings(self, value):
+ self.decoder.embed_tokens = value
+
+ def freeze_encoder(self):
+ """
+ Calling this function will disable the gradient computation for the Whisper encoder so that its parameters will
+ not be updated during training.
+ """
+ self.encoder._freeze_parameters()
+
+ def _mask_input_features(
+ self,
+ input_features: torch.FloatTensor,
+ attention_mask: torch.LongTensor | None = None,
+ ):
+ """
+ Masks extracted features along time axis and/or along feature axis according to
+ [SpecAugment](https://huggingface.co/papers/1904.08779).
+ """
+
+ # `config.apply_spec_augment` can set masking to False
+ if not getattr(self.config, "apply_spec_augment", True):
+ return input_features
+
+ # generate indices & apply SpecAugment along time axis
+ batch_size, hidden_size, sequence_length = input_features.size()
+
+ if self.config.mask_time_prob > 0 and self.training:
+ # generate indices & apply SpecAugment along time axis
+ mask_time_indices = _compute_mask_indices(
+ (batch_size, sequence_length),
+ mask_prob=self.config.mask_time_prob,
+ mask_length=self.config.mask_time_length,
+ attention_mask=attention_mask,
+ min_masks=self.config.mask_time_min_masks,
+ )
+ mask_time_indices = torch.tensor(mask_time_indices, device=input_features.device, dtype=torch.bool)
+ mask_time_indices = mask_time_indices[:, None].expand(-1, hidden_size, -1)
+ input_features[mask_time_indices] = 0
+
+ if self.config.mask_feature_prob > 0 and self.training:
+ # generate indices & apply SpecAugment along feature axis
+ mask_feature_indices = _compute_mask_indices(
+ (batch_size, hidden_size),
+ mask_prob=self.config.mask_feature_prob,
+ mask_length=self.config.mask_feature_length,
+ min_masks=self.config.mask_feature_min_masks,
+ )
+ mask_feature_indices = torch.tensor(mask_feature_indices, device=input_features.device, dtype=torch.bool)
+ input_features[mask_feature_indices] = 0
+
+ return input_features
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_features: torch.FloatTensor | None = None,
+ attention_mask: torch.LongTensor | None = None,
+ decoder_input_ids: torch.LongTensor | None = None,
+ decoder_attention_mask: torch.LongTensor | None = None,
+ encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
+ past_key_values: Cache | None = None,
+ decoder_inputs_embeds: tuple[torch.FloatTensor] | None = None,
+ decoder_position_ids: tuple[torch.LongTensor] | None = None,
+ use_cache: bool | None = None,
+ **kwargs,
+ ) -> tuple[torch.Tensor] | Seq2SeqModelOutput:
+ r"""
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
+ Indices of decoder input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`WhisperTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
+
+ Whisper uses the `decoder_start_token_id` as the starting token for `decoder_input_ids` generation. If
+ `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
+ `past_key_values`).
+ decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
+ be used by default.
+
+ If you want to change padding behavior, you should read
+ [`modeling_whisper._prepare_decoder_attention_mask`] and modify to your needs. See diagram 1 in [the BART
+ paper](https://huggingface.co/papers/1910.13461) for more information on the default strategy.
+ decoder_position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.n_positions - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+
+ Example:
+ ```python
+ >>> import torch
+ >>> from transformers import AutoFeatureExtractor, WhisperModel
+ >>> from datasets import load_dataset
+
+ >>> model = WhisperModel.from_pretrained("openai/whisper-base")
+ >>> feature_extractor = AutoFeatureExtractor.from_pretrained("openai/whisper-base")
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
+ >>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt")
+ >>> input_features = inputs.input_features
+ >>> decoder_input_ids = torch.tensor([[1, 1]]) * model.config.decoder_start_token_id
+ >>> last_hidden_state = model(input_features, decoder_input_ids=decoder_input_ids).last_hidden_state
+ >>> list(last_hidden_state.shape)
+ [1, 2, 512]
+ ```"""
+ if encoder_outputs is None:
+ input_features = self._mask_input_features(input_features, attention_mask=attention_mask)
+
+ encoder_outputs = self.encoder(
+ input_features,
+ **kwargs,
+ )
+ elif not isinstance(encoder_outputs, BaseModelOutput):
+ encoder_outputs = BaseModelOutput(
+ last_hidden_state=encoder_outputs[0],
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
+ )
+
+ # decoder outputs consists of (dec_features, past_key_values, dec_hidden, dec_attn)
+ decoder_outputs = self.decoder(
+ input_ids=decoder_input_ids,
+ attention_mask=decoder_attention_mask,
+ encoder_hidden_states=encoder_outputs[0],
+ past_key_values=past_key_values,
+ inputs_embeds=decoder_inputs_embeds,
+ position_ids=decoder_position_ids,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ return Seq2SeqModelOutput(
+ last_hidden_state=decoder_outputs.last_hidden_state,
+ past_key_values=decoder_outputs.past_key_values,
+ decoder_hidden_states=decoder_outputs.hidden_states,
+ decoder_attentions=decoder_outputs.attentions,
+ cross_attentions=decoder_outputs.cross_attentions,
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
+ encoder_hidden_states=encoder_outputs.hidden_states,
+ encoder_attentions=encoder_outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ The Whisper Model with a language modeling head. Can be used for automatic speech recognition.
+ """
+)
+class WhisperForConditionalGeneration(WhisperGenerationMixin, WhisperPreTrainedModel):
+ base_model_prefix = "model"
+ _tied_weights_keys = {"proj_out.weight": "model.decoder.embed_tokens.weight"}
+
+ def __init__(self, config: WhisperConfig):
+ super().__init__(config)
+ self.model = WhisperModel(config)
+ self.proj_out = nn.Linear(config.d_model, config.vocab_size, bias=False)
+ self.max_target_positions = config.max_target_positions
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.proj_out
+
+ def set_output_embeddings(self, new_embeddings):
+ self.proj_out = new_embeddings
+
+ def get_input_embeddings(self) -> nn.Module:
+ return self.model.get_input_embeddings()
+
+ def freeze_encoder(self):
+ """
+ Calling this function will disable the gradient computation for the Whisper encoder so that its parameters will
+ not be updated during training.
+ """
+ self.model.encoder._freeze_parameters()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_features: torch.FloatTensor | None = None,
+ attention_mask: torch.LongTensor | None = None,
+ decoder_input_ids: torch.LongTensor | None = None,
+ decoder_attention_mask: torch.LongTensor | None = None,
+ encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
+ past_key_values: Cache | None = None,
+ decoder_inputs_embeds: tuple[torch.FloatTensor] | None = None,
+ decoder_position_ids: tuple[torch.LongTensor] | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs,
+ ) -> tuple[torch.Tensor] | Seq2SeqLMOutput:
+ r"""
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
+ Indices of decoder input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`WhisperTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
+
+ Whisper uses the `decoder_start_token_id` as the starting token for `decoder_input_ids` generation. If
+ `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
+ `past_key_values`).
+ decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
+ be used by default.
+
+ If you want to change padding behavior, you should read
+ [`modeling_whisper._prepare_decoder_attention_mask`] and modify to your needs. See diagram 1 in [the BART
+ paper](https://huggingface.co/papers/1910.13461) for more information on the default strategy.
+ decoder_position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.n_positions - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the language modeling loss. Indices should either be in `[0, ..., config.vocab_size]`
+ or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is
+ only computed for the tokens with labels in `[0, ..., config.vocab_size]`. `sequence_length` should be smaller than or equal to `config.max_target_positions`.
+
+ Example:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoProcessor, WhisperForConditionalGeneration
+ >>> from datasets import load_dataset
+
+ >>> processor = AutoProcessor.from_pretrained("openai/whisper-tiny.en")
+ >>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")
+
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
+
+ >>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
+ >>> input_features = inputs.input_features
+
+ >>> generated_ids = model.generate(inputs=input_features)
+
+ >>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
+ >>> transcription
+ ' Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'
+ ```"""
+ if labels is not None:
+ if labels.shape[1] > self.max_target_positions:
+ raise ValueError(
+ f"Labels' sequence length {labels.shape[1]} cannot exceed the maximum allowed length of {self.max_target_positions} tokens."
+ )
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
+ decoder_input_ids = shift_tokens_right(
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
+ )
+
+ outputs: Seq2SeqModelOutput = self.model(
+ input_features,
+ attention_mask=attention_mask,
+ decoder_input_ids=decoder_input_ids,
+ encoder_outputs=encoder_outputs,
+ decoder_attention_mask=decoder_attention_mask,
+ past_key_values=past_key_values,
+ decoder_inputs_embeds=decoder_inputs_embeds,
+ decoder_position_ids=decoder_position_ids,
+ use_cache=use_cache,
+ **kwargs,
+ )
+ lm_logits = self.proj_out(outputs.last_hidden_state)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ # move labels to correct device to enable PP
+ labels = labels.to(lm_logits.device)
+ loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.reshape(-1))
+
+ return Seq2SeqLMOutput(
+ loss=loss,
+ logits=lm_logits,
+ past_key_values=outputs.past_key_values,
+ decoder_hidden_states=outputs.decoder_hidden_states,
+ decoder_attentions=outputs.decoder_attentions,
+ cross_attentions=outputs.cross_attentions,
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
+ encoder_hidden_states=outputs.encoder_hidden_states,
+ encoder_attentions=outputs.encoder_attentions,
+ )
+
+
+class WhisperDecoderWrapper(WhisperPreTrainedModel):
+ """
+ This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
+ used in combination with the [`EncoderDecoderModel`] framework.
+ """
+
+ def __init__(self, config):
+ super().__init__(config)
+ config.is_encoder_decoder = False
+ self.decoder = WhisperDecoder(config)
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.decoder.embed_tokens
+
+ def set_input_embeddings(self, value):
+ self.decoder.embed_tokens = value
+
+ def forward(self, *args, **kwargs):
+ return self.decoder(*args, **kwargs)
+
+
+@auto_docstring(
+ custom_intro="""
+ Whisper decoder with a language modeling head on top (linear layer with weights tied to the input embeddings).
+ """
+)
+class WhisperForCausalLM(WhisperPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"proj_out.weight": "model.decoder.embed_tokens.weight"}
+ main_input_name = "input_ids"
+
+ def __init__(self, config):
+ super().__init__(config)
+ config.is_encoder_decoder = False
+ self.model = WhisperDecoderWrapper(config)
+
+ self.proj_out = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.proj_out
+
+ def set_output_embeddings(self, new_embeddings):
+ self.proj_out = new_embeddings
+
+ def get_input_embeddings(self) -> nn.Module:
+ return self.model.get_input_embeddings()
+
+ def set_input_embeddings(self, value):
+ self.model.set_input_embeddings(value)
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ encoder_outputs: tuple[torch.FloatTensor] | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs,
+ ) -> tuple | CausalLMOutputWithCrossAttentions:
+ r"""
+ encoder_outputs (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
+ if the model is configured as a decoder.
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ Example:
+
+ ```python
+ >>> from transformers import WhisperForCausalLM, WhisperForConditionalGeneration, WhisperProcessor
+ >>> import torch
+ >>> from datasets import load_dataset
+
+ >>> processor = WhisperProcessor.from_pretrained("openai/whisper-large-v2")
+ >>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-large-v2")
+
+ >>> assistant_model = WhisperForCausalLM.from_pretrained("distil-whisper/distil-large-v2")
+
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
+ >>> sample = ds[0]["audio"]
+ >>> input_features = processor(
+ ... sample["array"], sampling_rate=sample["sampling_rate"], return_tensors="pt"
+ ... ).input_features
+
+ >>> predicted_ids = model.generate(input_features, assistant_model=assistant_model)
+
+ >>> # decode token ids to text
+ >>> transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)[0]
+ >>> transcription
+ ' Mr. Quilter is the apostle of the middle classes and we are glad to welcome his gospel.'
+ ```"""
+ # If the user passed a tuple or `BaseModelOutput` for encoder_outputs, we extract only the hidden states
+ if isinstance(encoder_outputs, (BaseModelOutput, tuple, list)):
+ encoder_outputs = encoder_outputs[0]
+
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
+ outputs = self.model.decoder(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_outputs,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ logits = self.proj_out(outputs[0])
+
+ loss = None
+ if labels is not None:
+ labels = labels.to(logits.device)
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
+
+ return CausalLMOutputWithCrossAttentions(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ Whisper Encoder Model with a sequence classification head on top (a linear layer over the pooled output) for tasks
+ like SUPERB Keyword Spotting.
+ """
+)
+class WhisperForAudioClassification(WhisperPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.encoder = WhisperEncoder(config)
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
+ if config.use_weighted_layer_sum:
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
+ self.projector = nn.Linear(config.hidden_size, config.classifier_proj_size)
+ self.classifier = nn.Linear(config.classifier_proj_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def freeze_encoder(self):
+ """
+ Calling this function will disable the gradient computation for the Whisper encoder so that its parameters will
+ not be updated during training. Only the projection layers and classification head will be updated.
+ """
+ self.encoder._freeze_parameters()
+
+ def get_input_embeddings(self) -> nn.Module:
+ return self.encoder.get_input_embeddings()
+
+ def set_input_embeddings(self, value: nn.Module):
+ self.encoder.set_input_embeddings(value)
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_features: torch.LongTensor | None = None,
+ encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs,
+ ) -> tuple[torch.Tensor] | SequenceClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+
+ Example:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoFeatureExtractor, WhisperForAudioClassification
+ >>> from datasets import load_dataset
+
+ >>> feature_extractor = AutoFeatureExtractor.from_pretrained("sanchit-gandhi/whisper-medium-fleurs-lang-id")
+ >>> model = WhisperForAudioClassification.from_pretrained("sanchit-gandhi/whisper-medium-fleurs-lang-id")
+
+ >>> ds = load_dataset("google/fleurs", "all", split="validation", streaming=True)
+ >>> sample = next(iter(ds))
+
+ >>> inputs = feature_extractor(
+ ... sample["audio"]["array"], sampling_rate=sample["audio"]["sampling_rate"], return_tensors="pt"
+ ... )
+ >>> input_features = inputs.input_features
+
+ >>> with torch.no_grad():
+ ... logits = model(input_features).logits
+
+ >>> predicted_class_ids = torch.argmax(logits).item()
+ >>> predicted_label = model.config.id2label[predicted_class_ids]
+ >>> predicted_label
+ 'Afrikaans'
+ ```"""
+
+ if self.config.use_weighted_layer_sum:
+ kwargs["output_hidden_states"] = True
+
+ if encoder_outputs is None:
+ encoder_outputs = self.encoder(
+ input_features,
+ **kwargs,
+ )
+ elif not isinstance(encoder_outputs, BaseModelOutput):
+ encoder_outputs = BaseModelOutput(
+ last_hidden_state=encoder_outputs[0],
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
+ )
+
+ if self.config.use_weighted_layer_sum:
+ hidden_states = encoder_outputs[_HIDDEN_STATES_START_POSITION]
+ hidden_states = torch.stack(hidden_states, dim=1)
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
+ else:
+ hidden_states = encoder_outputs[0]
+
+ hidden_states = self.projector(hidden_states)
+ pooled_output = hidden_states.mean(dim=1)
+
+ logits = self.classifier(pooled_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ # move labels to correct device to enable PP
+ labels = labels.to(logits.device)
+ loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ )
+
+
+__all__ = [
+ "WhisperForCausalLM",
+ "WhisperForConditionalGeneration",
+ "WhisperModel",
+ "WhisperPreTrainedModel",
+ "WhisperForAudioClassification",
+]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/whisper/processing_whisper.py b/.venv/lib/python3.12/site-packages/transformers/models/whisper/processing_whisper.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d1b33f3c1552db9dd9bdcf9dee463e879009116
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/whisper/processing_whisper.py
@@ -0,0 +1,60 @@
+# Copyright 2022 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Speech processor class for Whisper
+"""
+
+from ...processing_utils import ProcessorMixin
+from ...utils import auto_docstring
+
+
+@auto_docstring
+class WhisperProcessor(ProcessorMixin):
+ def __init__(self, feature_extractor, tokenizer):
+ super().__init__(feature_extractor, tokenizer)
+
+ def get_decoder_prompt_ids(self, task=None, language=None, no_timestamps=True):
+ return self.tokenizer.get_decoder_prompt_ids(task=task, language=language, no_timestamps=no_timestamps)
+
+ @auto_docstring
+ def __call__(self, *args, **kwargs):
+ audio = kwargs.pop("audio", None)
+ sampling_rate = kwargs.pop("sampling_rate", None)
+ text = kwargs.pop("text", None)
+ if len(args) > 0:
+ audio = args[0]
+ args = args[1:]
+
+ if audio is None and text is None:
+ raise ValueError("You need to specify either an `audio` or `text` input to process.")
+
+ if audio is not None:
+ inputs = self.feature_extractor(audio, *args, sampling_rate=sampling_rate, **kwargs)
+ if text is not None:
+ encodings = self.tokenizer(text, **kwargs)
+
+ if text is None:
+ return inputs
+
+ elif audio is None:
+ return encodings
+ else:
+ inputs["labels"] = encodings["input_ids"]
+ return inputs
+
+ def get_prompt_ids(self, text: str, return_tensors="np"):
+ return self.tokenizer.get_prompt_ids(text, return_tensors=return_tensors)
+
+
+__all__ = ["WhisperProcessor"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/whisper/tokenization_whisper.py b/.venv/lib/python3.12/site-packages/transformers/models/whisper/tokenization_whisper.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c56d1da765d035996d1a9a6d2cb5988e364ecda
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/whisper/tokenization_whisper.py
@@ -0,0 +1,1409 @@
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes for Whisper."""
+
+import json
+import os
+import re
+from functools import lru_cache
+
+import numpy as np
+from tokenizers import AddedToken, Tokenizer, decoders, pre_tokenizers, processors
+from tokenizers.models import BPE
+
+from ...tokenization_utils_tokenizers import TokenizersBackend
+from ...utils import logging
+from .english_normalizer import BasicTextNormalizer, EnglishTextNormalizer
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {
+ "vocab_file": "vocab.json",
+ "tokenizer_file": "tokenizer.json",
+ "merges_file": "merges.txt",
+ "normalizer_file": "normalizer.json",
+}
+
+
+LANGUAGES = {
+ "en": "english",
+ "zh": "chinese",
+ "de": "german",
+ "es": "spanish",
+ "ru": "russian",
+ "ko": "korean",
+ "fr": "french",
+ "ja": "japanese",
+ "pt": "portuguese",
+ "tr": "turkish",
+ "pl": "polish",
+ "ca": "catalan",
+ "nl": "dutch",
+ "ar": "arabic",
+ "sv": "swedish",
+ "it": "italian",
+ "id": "indonesian",
+ "hi": "hindi",
+ "fi": "finnish",
+ "vi": "vietnamese",
+ "he": "hebrew",
+ "uk": "ukrainian",
+ "el": "greek",
+ "ms": "malay",
+ "cs": "czech",
+ "ro": "romanian",
+ "da": "danish",
+ "hu": "hungarian",
+ "ta": "tamil",
+ "no": "norwegian",
+ "th": "thai",
+ "ur": "urdu",
+ "hr": "croatian",
+ "bg": "bulgarian",
+ "lt": "lithuanian",
+ "la": "latin",
+ "mi": "maori",
+ "ml": "malayalam",
+ "cy": "welsh",
+ "sk": "slovak",
+ "te": "telugu",
+ "fa": "persian",
+ "lv": "latvian",
+ "bn": "bengali",
+ "sr": "serbian",
+ "az": "azerbaijani",
+ "sl": "slovenian",
+ "kn": "kannada",
+ "et": "estonian",
+ "mk": "macedonian",
+ "br": "breton",
+ "eu": "basque",
+ "is": "icelandic",
+ "hy": "armenian",
+ "ne": "nepali",
+ "mn": "mongolian",
+ "bs": "bosnian",
+ "kk": "kazakh",
+ "sq": "albanian",
+ "sw": "swahili",
+ "gl": "galician",
+ "mr": "marathi",
+ "pa": "punjabi",
+ "si": "sinhala",
+ "km": "khmer",
+ "sn": "shona",
+ "yo": "yoruba",
+ "so": "somali",
+ "af": "afrikaans",
+ "oc": "occitan",
+ "ka": "georgian",
+ "be": "belarusian",
+ "tg": "tajik",
+ "sd": "sindhi",
+ "gu": "gujarati",
+ "am": "amharic",
+ "yi": "yiddish",
+ "lo": "lao",
+ "uz": "uzbek",
+ "fo": "faroese",
+ "ht": "haitian creole",
+ "ps": "pashto",
+ "tk": "turkmen",
+ "nn": "nynorsk",
+ "mt": "maltese",
+ "sa": "sanskrit",
+ "lb": "luxembourgish",
+ "my": "myanmar",
+ "bo": "tibetan",
+ "tl": "tagalog",
+ "mg": "malagasy",
+ "as": "assamese",
+ "tt": "tatar",
+ "haw": "hawaiian",
+ "ln": "lingala",
+ "ha": "hausa",
+ "ba": "bashkir",
+ "jw": "javanese",
+ "su": "sundanese",
+ "yue": "cantonese",
+}
+
+# language code lookup by name, with a few language aliases
+TO_LANGUAGE_CODE = {
+ **{language: code for code, language in LANGUAGES.items()},
+ "burmese": "my",
+ "valencian": "ca",
+ "flemish": "nl",
+ "haitian": "ht",
+ "letzeburgesch": "lb",
+ "pushto": "ps",
+ "panjabi": "pa",
+ "moldavian": "ro",
+ "moldovan": "ro",
+ "sinhalese": "si",
+ "castilian": "es",
+ "mandarin": "zh",
+}
+
+TASK_IDS = ["translate", "transcribe"]
+
+
+class WhisperTokenizer(TokenizersBackend):
+ """
+ Construct a "fast" Whisper tokenizer (backed by HuggingFace's *tokenizers* library).
+
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
+ refer to this superclass for more information regarding those methods.
+
+ Args:
+ vocab_file (`str`, *optional*):
+ Path to the vocabulary file.
+ merges_file (`str`, *optional*):
+ Path to the merges file.
+ normalizer_file (`str`, *optional*):
+ Path to the normalizer_file file.
+ tokenizer_file (`str`, *optional*):
+ Path to [tokenizers](https://github.com/huggingface/tokenizers) file (generally has a .json extension) that
+ contains everything needed to load the tokenizer.
+ unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ bos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
+ The beginning of sequence token. The `decoder_start_token_id` is used to set the first token as
+ `"<|startoftranscript|>"` when generating.
+ eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
+ The end of sequence token.
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
+ other word. (Whisper tokenizer detect beginning of words by the preceding space).
+ language (`str`, *optional*):
+ The language of the transcription text. The corresponding language id token is appended to the start of the
+ sequence for multilingual speech recognition and speech translation tasks, e.g. for Spanish the token
+ `"<|es|>"` is appended to the start of sequence. This should be used for multilingual fine-tuning only.
+ task (`str`, *optional*):
+ Task identifier to append at the start of sequence (if any). This should be used for mulitlingual
+ fine-tuning, with `"transcribe"` for speech recognition and `"translate"` for speech translation.
+ predict_timestamps (`bool`, *optional*, defaults to `False`):
+ Whether to omit the `<|notimestamps|>` token at the start of the sequence.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ model_input_names = ["input_ids", "attention_mask"]
+ model = BPE
+
+ def __init__(
+ self,
+ vocab: str | dict[str, int] | None = None,
+ merges=None,
+ normalizer_file=None,
+ unk_token="<|endoftext|>",
+ bos_token="<|endoftext|>",
+ eos_token="<|endoftext|>",
+ add_prefix_space=False,
+ language=None,
+ task=None,
+ predict_timestamps=False,
+ **kwargs,
+ ):
+ bos_token = (
+ AddedToken(bos_token, lstrip=False, rstrip=False, normalized=False, special=True)
+ if isinstance(bos_token, str)
+ else bos_token
+ )
+ eos_token = (
+ AddedToken(eos_token, lstrip=False, rstrip=False, normalized=False, special=True)
+ if isinstance(eos_token, str)
+ else eos_token
+ )
+ unk_token = (
+ AddedToken(unk_token, lstrip=False, rstrip=False, normalized=False, special=True)
+ if isinstance(unk_token, str)
+ else unk_token
+ )
+
+ self._vocab = vocab if vocab is not None else {}
+ self._merges = merges if merges is not None else []
+
+ self._tokenizer = Tokenizer(
+ BPE(
+ vocab=self._vocab,
+ merges=self._merges,
+ dropout=None,
+ continuing_subword_prefix="",
+ end_of_word_suffix="",
+ fuse_unk=False,
+ )
+ )
+
+ self._tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=add_prefix_space)
+ self._tokenizer.decoder = decoders.ByteLevel()
+
+ super().__init__(
+ unk_token=unk_token,
+ bos_token=bos_token,
+ eos_token=eos_token,
+ add_prefix_space=add_prefix_space,
+ normalizer_file=normalizer_file,
+ language=language,
+ task=task,
+ predict_timestamps=predict_timestamps,
+ **kwargs,
+ )
+
+ if normalizer_file is not None:
+ with open(normalizer_file, encoding="utf-8") as vocab_handle:
+ self.english_spelling_normalizer = json.load(vocab_handle)
+ else:
+ self.english_spelling_normalizer = None
+
+ self.timestamp_pat = re.compile(r"<\|(\d+\.\d+)\|>")
+
+ self.language = language
+ self.task = task
+ self.predict_timestamps = predict_timestamps
+ self.set_prefix_tokens()
+
+ # Copied from transformers.models.whisper.tokenization_whisper.WhisperTokenizer._decode_with_timestamps
+ def _decode_with_timestamps(
+ self, token_ids, skip_special_tokens=False, time_precision=0.02, segment_size=1500
+ ) -> str:
+ """
+ Timestamp tokens are above the special tokens' id range and are ignored by `decode()`. This method decodes
+ given tokens with timestamps tokens annotated, e.g. "<|1.08|>".
+ """
+ timestamp_begin = self.all_special_ids[-1] + 1
+ outputs = [[]]
+
+ cur_max_timestamp = 0.0
+ prev_segments_len = 0.0
+ penultimate_timestamp = 0.0
+
+ for i, token in enumerate(token_ids):
+ if token >= timestamp_begin:
+ timestamp = float((token - timestamp_begin) * time_precision)
+
+ if timestamp < cur_max_timestamp:
+ # next segment has started
+ last_was_single_ending = i >= 2 and not (
+ token_ids[i - 1] >= timestamp_begin and token_ids[i - 2] >= timestamp_begin
+ )
+ if last_was_single_ending:
+ prev_segments_len += time_precision * segment_size
+ else:
+ cur_max_timestamp = penultimate_timestamp
+ prev_segments_len += penultimate_timestamp
+ outputs = outputs[:-2]
+
+ penultimate_timestamp = cur_max_timestamp
+ cur_max_timestamp = timestamp
+
+ outputs.append(f"<|{(timestamp + prev_segments_len):.2f}|>")
+ outputs.append([])
+ else:
+ outputs[-1].append(token)
+ # Decode token sequences outside list comprehension to avoid super() resolution issues
+ decoded_outputs = []
+ for s in outputs:
+ if isinstance(s, str):
+ decoded_outputs.append(s)
+ elif s:
+ decoded_outputs.append(super().decode(s, skip_special_tokens=skip_special_tokens))
+ else:
+ decoded_outputs.append("")
+ return "".join(decoded_outputs)
+
+ # Copied from transformers.models.whisper.tokenization_whisper.WhisperTokenizer._compute_offsets
+ def _compute_offsets(self, token_ids, time_precision=0.02, segment_size=1500):
+ """
+ Compute offsets for a given tokenized input
+
+ Args:
+ token_ids (`Union[int, list[int], np.ndarray, torch.Tensor]`):
+ List of tokenized input ids. Can be obtained using the `__call__` method.
+ time_precision (`float`, *optional*, defaults to 0.02):
+ The time ratio to convert from token to time.
+ segment_size (`int`, *optional*, defaults to 1500):
+ The number of features in the input mel spectrogram.
+ """
+ offsets = []
+ # ensure torch tensor of token ids is placed on cpu
+ if "torch" in str(type(token_ids)) and (hasattr(token_ids, "cpu") and callable(token_ids.cpu)):
+ token_ids = token_ids.cpu()
+ token_ids = np.array(token_ids)
+ if token_ids.shape[0] > 1 and len(token_ids.shape) > 1:
+ raise ValueError("Can only process a single input at a time")
+ timestamp_begin = self.all_special_ids[-1] + 1
+ timestamp_tokens = token_ids >= timestamp_begin
+
+ consecutive = np.where(timestamp_tokens[:-1] & timestamp_tokens[1:])[0] + 1
+ if consecutive.shape[0] == 0 and timestamp_tokens.sum() <= 1:
+ # either there are no timestamps or there are no consecutive ones
+ return []
+ elif np.where(timestamp_tokens)[0][-1] + 1 not in consecutive:
+ # we add the final timestamp if it is not already in the list
+ consecutive = np.append(consecutive, np.where(timestamp_tokens)[0][-1] + 1)
+
+ last_slice = np.where(timestamp_tokens)[0][0]
+ cur_max_timestamp = 0
+ prev_segments_len = 0
+ for current_slice in consecutive:
+ sliced_tokens = token_ids[last_slice:current_slice]
+ if len(sliced_tokens) > 1:
+ start_timestamp_position = sliced_tokens[0].item() - timestamp_begin
+ end_timestamp_position = sliced_tokens[-1].item() - timestamp_begin
+
+ if start_timestamp_position < cur_max_timestamp:
+ # next segment has started
+ is_single_ending = last_slice >= 2 and not (
+ token_ids[last_slice - 2] >= timestamp_begin and token_ids[last_slice - 1] >= timestamp_begin
+ )
+ if is_single_ending:
+ prev_segments_len += segment_size
+ else:
+ prev_segments_len += cur_max_timestamp
+
+ cur_max_timestamp = end_timestamp_position
+
+ # strip timestamp tokens from the text output
+ sliced_tokens = self._preprocess_token_ids(sliced_tokens)
+ text = self._decode(sliced_tokens)
+ text = self._filter_timestamp_ids(text)
+ offsets.append(
+ {
+ "text": text,
+ "timestamp": (
+ start_timestamp_position * time_precision + prev_segments_len * time_precision,
+ end_timestamp_position * time_precision + prev_segments_len * time_precision,
+ ),
+ }
+ )
+ last_slice = current_slice
+
+ return offsets
+
+ @lru_cache
+ # Copied from transformers.models.whisper.tokenization_whisper.WhisperTokenizer.timestamp_ids
+ def timestamp_ids(self, time_precision=0.02):
+ """
+ Compute the timestamp token ids for a given precision and save to least-recently used (LRU) cache.
+
+ Args:
+ time_precision (`float`, *optional*, defaults to 0.02):
+ The time ratio to convert from token to time.
+ """
+ return self.convert_tokens_to_ids([("<|%.2f|>" % (i * time_precision)) for i in range(1500 + 1)])
+
+ # Copied from transformers.models.whisper.tokenization_whisper.WhisperTokenizer._preprocess_token_ids
+ def _preprocess_token_ids(self, token_ids, skip_special_tokens: bool = False):
+ """
+ Pre-process the token ids for decoding by removing the prompt tokens ids and timestamp token ids.
+
+ Args:
+ token_ids (`Union[int, list[int], np.ndarray, torch.Tensor]`):
+ List of tokenized input ids. Typically, obtained using the `__call__` method of the tokenizer.
+ skip_special_tokens (`bool`, *optional*, defaults to `False`):
+ Whether or not to remove special tokens from the token ids. If `True`, the prompt token ids will be
+ removed.
+ """
+ if skip_special_tokens:
+ prompt_token_id = self.convert_tokens_to_ids("<|startofprev|>")
+ decoder_start_token_id = self.convert_tokens_to_ids("<|startoftranscript|>")
+ token_ids = self._strip_prompt(token_ids, prompt_token_id, decoder_start_token_id)
+
+ return token_ids
+
+ # Copied from transformers.models.whisper.tokenization_whisper.WhisperTokenizer._filter_timestamp_ids
+ def _filter_timestamp_ids(self, text):
+ return re.sub(self.timestamp_pat, "", text)
+
+ # Copied from transformers.models.whisper.tokenization_whisper.WhisperTokenizer.decode
+ def decode(
+ self,
+ token_ids,
+ skip_special_tokens: bool = False,
+ clean_up_tokenization_spaces: bool | None = None,
+ output_offsets: bool = False,
+ time_precision: float = 0.02,
+ decode_with_timestamps: bool = False,
+ normalize: bool = False,
+ basic_normalize: bool = False,
+ remove_diacritics: bool = False,
+ **kwargs,
+ ) -> str:
+ """
+ Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special
+ tokens and clean up tokenization spaces.
+
+ Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.
+
+ Args:
+ token_ids (`Union[int, list[int], np.ndarray, torch.Tensor]`):
+ List of tokenized input ids. Can be obtained using the `__call__` method.
+ skip_special_tokens (`bool`, *optional*, defaults to `False`):
+ Whether or not to remove special tokens in the decoding. Will remove the previous tokens (pre-prompt)
+ if present.
+ clean_up_tokenization_spaces (`bool`, *optional*):
+ Whether or not to clean up the tokenization spaces. If `None`, will default to
+ `self.clean_up_tokenization_spaces` (available in the `tokenizer_config`).
+ output_offsets (`bool`, *optional*, defaults to `False`):
+ Whether or not to output the offsets of the tokens. This should only be set if the model predicted
+ timestamps. If there are previous tokens (pre-prompt) to decode, they will only appear in the decoded
+ text if they contain timestamp tokens.
+ time_precision (`float`, *optional*, defaults to 0.02):
+ The time ratio to convert from token to time.
+ decode_with_timestamps (`bool`, *optional*, defaults to `False`):
+ Whether or not to decode with timestamps included in the raw text.
+ normalize (`bool`, *optional*, defaults to `False`):
+ Whether or not to apply the English text normalizer to the decoded text. Only applicable when the
+ target text is in English. Otherwise, the basic text normalizer should be applied.
+ basic_normalize (`bool`, *optional*, defaults to `False`):
+ Whether or not to apply the Basic text normalizer to the decoded text. Applicable to multilingual
+ target text.
+ remove_diacritics (`bool`, *optional*, defaults to `False`):
+ Whether or not to remove diacritics when applying the Basic text normalizer. Removing diacritics may
+ destroy information in the decoded text, hence it should be used with caution.
+ kwargs (additional keyword arguments, *optional*):
+ Will be passed to the underlying model specific decode method.
+ Returns:
+ `str`: The decoded sentence.
+ """
+ filtered_ids = self._preprocess_token_ids(
+ token_ids,
+ skip_special_tokens=skip_special_tokens,
+ )
+
+ text = super().decode(
+ filtered_ids,
+ skip_special_tokens=skip_special_tokens,
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
+ normalize=normalize,
+ basic_normalize=basic_normalize,
+ remove_diacritics=remove_diacritics,
+ **kwargs,
+ )
+ if decode_with_timestamps:
+ # legacy method to decode timestamps when not included in the tokenizer vocabulary
+ text = self._decode_with_timestamps(
+ filtered_ids, time_precision=time_precision, skip_special_tokens=skip_special_tokens
+ )
+ else:
+ # Handle both single string and batch (list of strings) outputs
+ if isinstance(text, list):
+ text = [self._filter_timestamp_ids(t) for t in text]
+ else:
+ text = self._filter_timestamp_ids(text)
+
+ # retrieve offsets
+ if output_offsets:
+ offsets = self._compute_offsets(token_ids, time_precision=time_precision)
+ return {"text": text, "offsets": offsets}
+ return text
+
+ def _decode(
+ self, *args, normalize: bool = False, basic_normalize: bool = False, remove_diacritics: bool = False, **kwargs
+ ) -> str:
+ text = super()._decode(*args, **kwargs)
+
+ if normalize:
+ clean_text = self.normalize(text)
+ return clean_text
+ elif basic_normalize:
+ clean_text = self.basic_normalize(text, remove_diacritics=remove_diacritics)
+ return clean_text
+ else:
+ return text
+
+ def normalize(self, text):
+ """
+ Normalize a given string using the `EnglishTextNormalizer` class, which performs commons transformation on
+ english text.
+ """
+ normalizer = EnglishTextNormalizer(self.english_spelling_normalizer)
+ return normalizer(text)
+
+ @staticmethod
+ def basic_normalize(text, remove_diacritics=False):
+ """
+ Normalize a given string using the `BasicTextNormalizer` class, which performs commons transformation on
+ multilingual text.
+ """
+ normalizer = BasicTextNormalizer(remove_diacritics=remove_diacritics)
+ return normalizer(text)
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
+ if not os.path.isdir(save_directory):
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
+ return
+
+ vocab_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
+ )
+ merge_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
+ )
+ normalizer_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["normalizer_file"]
+ )
+
+ with open(vocab_file, "w", encoding="utf-8") as f:
+ f.write(json.dumps(self._vocab, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
+
+ with open(merge_file, "w", encoding="utf-8") as writer:
+ writer.write("#version: 0.2\n")
+ writer.writelines(" ".join(merge_pair) + "\n" for merge_pair in self._merges)
+
+ if self.english_spelling_normalizer is not None:
+ with open(normalizer_file, "w", encoding="utf-8") as f:
+ f.write(
+ json.dumps(self.english_spelling_normalizer, indent=2, sort_keys=True, ensure_ascii=False) + "\n"
+ )
+
+ return (vocab_file, merge_file, normalizer_file)
+
+ def set_prefix_tokens(
+ self, language: str | None = None, task: str | None = None, predict_timestamps: bool | None = None
+ ):
+ """
+ Override the prefix tokens appended to the start of the label sequence. This method can be used standalone to
+ update the prefix tokens as required when fine-tuning. Example:
+
+ ```python
+ >>> # instantiate the tokenizer and set the prefix token to Spanish
+ >>> tokenizer = WhisperTokenizerFast.from_pretrained("openai/whisper-tiny", language="spanish")
+ >>> # now switch the prefix token from Spanish to French
+ >>> tokenizer.set_prefix_tokens(language="french")
+ ```
+
+ Args:
+ language (`str`, *optional*, defaults to `None`):
+ The language of the transcription text.
+ task (`str`, *optional*, defaults to `None`):
+ Task identifier to append at the start of sequence (if any).
+ predict_timestamps (`bool`, *optional*, defaults to `None`):
+ Whether to omit the `<|notimestamps|>` token at the start of the sequence.
+ """
+ self.language = language if language is not None else self.language
+ self.task = task if task is not None else self.task
+ self.predict_timestamps = predict_timestamps if predict_timestamps is not None else self.predict_timestamps
+
+ prefix_token_ids = self.prefix_tokens
+ prefixes = self.convert_ids_to_tokens(prefix_token_ids)
+ eos = self.eos_token
+ eos_token_id = self.eos_token_id
+ prefix_template = " ".join([f"{token}:0" for token in prefixes])
+ self.backend_tokenizer.post_processor = processors.TemplateProcessing(
+ single=f"{prefix_template} $A:0 {eos}:0",
+ pair=f"{prefix_template} $A:0 $B:1 {eos}:1",
+ special_tokens=[
+ (eos, eos_token_id),
+ *zip(prefixes, prefix_token_ids),
+ ],
+ )
+
+ @property
+ # Copied from transformers.models.whisper.tokenization_whisper.WhisperTokenizer.prefix_tokens
+ def prefix_tokens(self) -> list[int]:
+ bos_token_id = self.convert_tokens_to_ids("<|startoftranscript|>")
+ translate_token_id = self.convert_tokens_to_ids("<|translate|>")
+ transcribe_token_id = self.convert_tokens_to_ids("<|transcribe|>")
+ notimestamps_token_id = self.convert_tokens_to_ids("<|notimestamps|>")
+ langs = tuple(LANGUAGES.keys())
+
+ if self.language is not None:
+ self.language = self.language.lower()
+ if self.language in TO_LANGUAGE_CODE:
+ language_id = TO_LANGUAGE_CODE[self.language]
+ elif self.language in TO_LANGUAGE_CODE.values():
+ language_id = self.language
+ else:
+ is_language_code = len(self.language) == 2
+ raise ValueError(
+ f"Unsupported language: {self.language}. Language should be one of:"
+ f" {list(TO_LANGUAGE_CODE.values()) if is_language_code else list(TO_LANGUAGE_CODE.keys())}."
+ )
+
+ if self.task is not None:
+ if self.task not in TASK_IDS:
+ raise ValueError(f"Unsupported task: {self.task}. Task should be in: {TASK_IDS}")
+
+ bos_sequence = [bos_token_id]
+ if self.language is not None:
+ bos_sequence.append(bos_token_id + 1 + langs.index(language_id))
+ if self.task is not None:
+ bos_sequence.append(transcribe_token_id if self.task == "transcribe" else translate_token_id)
+ if not self.predict_timestamps:
+ bos_sequence.append(notimestamps_token_id)
+ return bos_sequence
+
+ # Copied from transformers.models.whisper.tokenization_whisper.WhisperTokenizer.build_inputs_with_special_tokens
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None) -> list[int]:
+ """Build model inputs from a sequence by appending eos_token_id."""
+ if token_ids_1 is None:
+ return self.prefix_tokens + token_ids_0 + [self.eos_token_id]
+ # We don't expect to process pairs, but leave the pair logic for API consistency
+ return self.prefix_tokens + token_ids_0 + token_ids_1 + [self.eos_token_id]
+
+ # Copied from transformers.models.whisper.tokenization_whisper.WhisperTokenizer.get_special_tokens_mask
+ def get_special_tokens_mask(
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False
+ ) -> list[int]:
+ """
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
+ special tokens using the tokenizer `prepare_for_model` method.
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
+ Whether or not the token list is already formatted with special tokens for the model.
+
+ Returns:
+ `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
+ """
+
+ if already_has_special_tokens:
+ return super().get_special_tokens_mask(
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
+ )
+
+ prefix_ones = [1] * len(self.prefix_tokens)
+ suffix_ones = [1]
+ if token_ids_1 is None:
+ return prefix_ones + ([0] * len(token_ids_0)) + suffix_ones
+ return prefix_ones + ([0] * len(token_ids_0)) + ([0] * len(token_ids_1)) + suffix_ones
+
+ # Copied from transformers.models.whisper.tokenization_whisper.WhisperTokenizer.get_decoder_prompt_ids
+ def get_decoder_prompt_ids(self, task=None, language=None, no_timestamps=True):
+ self.set_prefix_tokens(task=task, language=language, predict_timestamps=not no_timestamps)
+ # prefix tokens are of the form: <|startoftranscript|> <|lang_id|> <|task|> <|notimestamps|>
+ # we don't want to force the bos token at position 1, as this is the starting token
+ # when we generate, so we slice the prefix tokens to: <|lang_id|> <|task|> <|notimestamps|>
+ # to get the forced tokens
+ forced_tokens = self.prefix_tokens[1:]
+ forced_decoder_ids = [(rank + 1, token) for rank, token in enumerate(forced_tokens)]
+ return forced_decoder_ids
+
+ def _decode_asr(self, model_outputs, *, return_timestamps, return_language, time_precision):
+ return _decode_asr(
+ self,
+ model_outputs,
+ return_timestamps=return_timestamps,
+ return_language=return_language,
+ time_precision=time_precision,
+ )
+
+ # Copied from transformers.models.whisper.tokenization_whisper.WhisperTokenizer.get_prompt_ids
+ def get_prompt_ids(self, text: str, return_tensors="np"):
+ """Converts prompt text to IDs that can be passed to [`~WhisperForConditionalGeneration.generate`]."""
+ batch_encoding = self("<|startofprev|>", " " + text.strip(), add_special_tokens=False)
+
+ # Check for special tokens
+ prompt_text_ids = batch_encoding["input_ids"][1:]
+ special_token_id = next((x for x in prompt_text_ids if x >= self.all_special_ids[0]), None)
+ if special_token_id is not None:
+ token = self.convert_ids_to_tokens(special_token_id)
+ raise ValueError(f"Encountered text in the prompt corresponding to disallowed special token: {token}.")
+
+ batch_encoding.convert_to_tensors(tensor_type=return_tensors)
+ return batch_encoding["input_ids"]
+
+ # Copied from transformers.models.whisper.tokenization_whisper.WhisperTokenizer._strip_prompt
+ def _strip_prompt(self, token_ids: list[int], prompt_token_id: int, decoder_start_token_id: int):
+ if not isinstance(token_ids, list):
+ token_ids = self._convert_to_list(token_ids)
+
+ # handle case of empty token_ids for decoding with timestamps.
+ # at this point token_ids is a list, so it is safe to use if not check.
+ if not token_ids:
+ return token_ids
+
+ has_prompt = token_ids[0] == prompt_token_id
+ if has_prompt:
+ if decoder_start_token_id in token_ids:
+ return token_ids[token_ids.index(decoder_start_token_id) :]
+ else:
+ return []
+
+ return token_ids
+
+ @staticmethod
+ # Copied from transformers.models.whisper.tokenization_whisper.WhisperTokenizer._convert_to_list
+ def _convert_to_list(token_ids):
+ # convert type to ndarray if necessary
+ if hasattr(token_ids, "numpy"):
+ token_ids = token_ids.cpu().numpy()
+ # now the token ids are either a numpy array, or a list of lists
+ if isinstance(token_ids, np.ndarray):
+ token_ids = token_ids.tolist()
+ return token_ids
+
+
+def _combine_tokens_into_words(
+ tokenizer,
+ tokens: list[int],
+ language: str | None = None,
+ prepend_punctuations: str = "\"'“¡¿([{-",
+ append_punctuations: str = "\"'.。,,!!??::”)]}、",
+):
+ """
+ Groups tokens by word. Returns a tuple containing a list of strings with the words, and a list of `token_id`
+ sequences with the tokens making up each word.
+ """
+ if language is None:
+ language = tokenizer.language
+ if language is None:
+ language = "english"
+
+ if language in {"chinese", "japanese", "thai", "lao", "myanmar", "cantonese"}:
+ # These languages don't typically use spaces.
+ words, word_tokens, token_indices = _split_tokens_on_unicode(tokenizer, tokens)
+ else:
+ words, word_tokens, token_indices = _split_tokens_on_spaces(tokenizer, tokens)
+
+ _merge_punctuations(words, word_tokens, token_indices, prepend_punctuations, append_punctuations)
+ return words, word_tokens, token_indices
+
+
+def _find_longest_common_sequence(sequences, token_timestamp_sequences=None):
+ # It would be much harder to do O(n) because of fault tolerance.
+ # We actually have a really good property which is that the total sequence
+ # MUST be those subsequences in order.
+ # If token_timestamp_sequences is provided, will split those sequences in
+ # exactly the same way.
+
+ left_sequence = sequences[0]
+ left_length = len(left_sequence)
+ total_sequence = []
+
+ if token_timestamp_sequences:
+ left_token_timestamp_sequence = token_timestamp_sequences[0]
+ total_token_timestamp_sequence = []
+
+ for seq_idx, right_sequence in enumerate(sequences[1:]):
+ # index = 0
+ max_ = 0.0
+ max_indices = (left_length, left_length, 0, 0)
+ # Here we're sliding matches
+ # [a, b, c, d]
+ # [c, d, f]
+ # = [c] == [d]
+ #
+ # [a, b, c, d]
+ # [c, d, f]
+ # = [c, d] == [c, d]
+ #
+ #
+ # [a, b, c, d]
+ # [c, d, f]
+ #
+ # = [b, c, d] == [c, d, f]
+ #
+ # [a, b, c, d]
+ # [c, d, f]
+ #
+ # [a, b, c] == [c, d, f]
+ #
+ # [a, b, c, d]
+ # [d, f]
+ #
+ # [a, b] == [d, f]
+ #
+ # [a, b, c, d]
+ # [f]
+ #
+ # [a] == [f]
+ right_length = len(right_sequence)
+ for i in range(1, left_length + right_length):
+ # epsilon to favor long perfect matches
+ eps = i / 10000.0
+
+ # Slightly convoluted because we don't want out of bound indices
+ # This will be necessary for a small conflict resolution optimization
+ # later
+ left_start = max(0, left_length - i)
+ left_stop = min(left_length, left_length + right_length - i)
+ left = np.array(left_sequence[left_start:left_stop])
+
+ right_start = max(0, i - left_length)
+ right_stop = min(right_length, i)
+ right = np.array(right_sequence[right_start:right_stop])
+
+ # We can only match subsequences of the same size.
+ if len(left) != len(right):
+ raise RuntimeError(
+ "There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference."
+ )
+
+ if token_timestamp_sequences:
+ # Get length of longest subsequence of tokens that match
+ # and have timestamps that are in order
+ matches = sum(
+ 1
+ for idx, elem in enumerate(left)
+ if (
+ elem == right[idx]
+ and left_token_timestamp_sequence[left_start + idx]
+ <= token_timestamp_sequences[seq_idx + 1][right_start + idx]
+ )
+ )
+
+ else:
+ matches = np.sum(left == right)
+
+ matching = matches / i + eps
+ if matches > 1 and matching > max_:
+ max_ = matching
+ max_indices = (left_start, left_stop, right_start, right_stop)
+
+ (left_start, left_stop, right_start, right_stop) = max_indices
+
+ # This is a small conflict optimization since those sequences overlap
+ # in audio.
+ # We're going to give more confidence to the left sequence
+ # for the left of the overlap,
+ # and to the right of the sequence, for the right of the overlap
+ left_mid = (left_stop + left_start) // 2
+ right_mid = (right_stop + right_start) // 2
+ total_sequence.extend(left_sequence[:left_mid])
+ left_sequence = right_sequence[right_mid:]
+ left_length = len(left_sequence)
+
+ if token_timestamp_sequences:
+ total_token_timestamp_sequence.extend(left_token_timestamp_sequence[:left_mid])
+ left_token_timestamp_sequence = token_timestamp_sequences[seq_idx + 1][right_mid:]
+
+ total_sequence.extend(left_sequence)
+
+ if token_timestamp_sequences is None:
+ return total_sequence
+
+ if len(token_timestamp_sequences) > 0:
+ total_token_timestamp_sequence.extend(left_token_timestamp_sequence)
+ return total_sequence, total_token_timestamp_sequence
+ else:
+ return total_sequence, []
+
+
+def _decode_asr(tokenizer, model_outputs, *, return_timestamps, return_language, time_precision, segment_size=1500):
+ """
+ Internal method meant to only be used by asr pipeline. Handles all the little quirks specific to whisper to handle
+ the various options not allowed in other seq2seq models
+ """
+
+ # =========== Overview ============
+ # - iterate over all outputs
+ # - all tokens within output
+ # - Each token can be
+ # - language token
+ # - special token
+ # - timestamp token
+ # - text token
+ # - We accumulate the text tokens.
+ # - We split on end timestamps
+ # - Lots of complexity comes from stride and timestamps
+
+ last_language = None
+
+ def new_chunk():
+ return {"language": last_language, "timestamp": [None, None], "text": ""}
+
+ # Welcome to the state machine !
+ chunks = []
+ chunk = new_chunk()
+ time_offset = 0.0
+ timestamp_begin = tokenizer.convert_tokens_to_ids("<|notimestamps|>") + 1
+ previous_tokens = []
+ previous_token_timestamps = []
+ skip = False
+ right_stride_start = None
+
+ all_special_ids = set(tokenizer.all_special_ids)
+ prompt_token_id = tokenizer.convert_tokens_to_ids("<|startofprev|>")
+ decoder_start_token_id = tokenizer.convert_tokens_to_ids("<|startoftranscript|>")
+ # - iterate over all outputs
+ for chunk_id, output in enumerate(model_outputs):
+ # We can drop everything to Python list, it's going to make
+ # our lives easier
+ token_ids = output["tokens"][0].tolist()
+ # (possibly) remove the prompt from the token ids
+ token_ids = tokenizer._strip_prompt(token_ids, prompt_token_id, decoder_start_token_id)
+ if return_timestamps == "word":
+ token_timestamps = output["token_timestamps"][0].tolist()
+
+ # Those keep track of timestamps within strides
+ # Which need to be skipped and resolve all tokens in a single
+ # chunk.
+ last_timestamp = None
+ first_timestamp = timestamp_begin
+
+ # long form generation: we need to handle the case where the call to generate returns concatenated segments,
+ # with underlying multiple calls to generate
+ cur_max_timestamp = 0.0
+ prev_segments_len = 0.0
+ penultimate_timestamp = 0.0
+
+ if "stride" in output:
+ chunk_len, stride_left, stride_right = output["stride"]
+ # Offset the timings to account for the other `model_outputs`.
+ time_offset -= stride_left
+ right_stride_start = chunk_len - stride_right
+
+ # Keeping track of timestamps within strides
+ # We're going to NOT split on those, and delay until we're
+ # out of BOTH stride. Otherwise lots of issues occur and
+ # corner cases
+ if stride_left:
+ first_timestamp = stride_left / time_precision + timestamp_begin
+ if stride_right:
+ for token in reversed(token_ids):
+ if token >= timestamp_begin:
+ # There can be several token in the right stride
+ # But the last one is ALWAYS going to be skipped
+ if (
+ last_timestamp is not None
+ and (token - timestamp_begin) * time_precision < right_stride_start
+ ):
+ break
+ last_timestamp = token
+
+ current_tokens = []
+ current_token_timestamps = []
+
+ # - all tokens within output
+ for i, token in enumerate(token_ids):
+ # 4 possible states for each token
+ # - 1/ Language code
+ # - 2/ all other special tokens (which we ignore)
+ # - 3/ Timestamp
+ # - 4/ Regular text
+ if token in all_special_ids:
+ # Either language code or other
+ text = tokenizer.decode([token])
+ # Removing outer shell <|XX|>
+ text = text[2:-2]
+ language = LANGUAGES.get(text)
+ if language is not None:
+ # 1/ Indeed some language
+ # TODO Handle when language is different from the previous
+ # one, and we cannot use timestamped tokens to create chunks
+ if last_language and language != last_language and not return_timestamps:
+ previous_tokens.append(current_tokens)
+ resolved_tokens = _find_longest_common_sequence(previous_tokens)
+ resolved_text = tokenizer.decode(resolved_tokens)
+ chunk["text"] = resolved_text
+ chunks.append(chunk)
+
+ # Flush all our temporary context
+ previous_tokens = []
+ current_tokens = []
+ chunk = new_chunk()
+ chunk["language"] = language
+ last_language = language
+ else:
+ # 2/ This is a regular special token, ignoring it
+ pass
+ elif token >= timestamp_begin:
+ # 3/ Timestamp token
+
+ timestamp = float((token - timestamp_begin) * time_precision)
+ if timestamp < cur_max_timestamp:
+ # next segment has started
+ last_was_single_ending = i >= 2 and not (
+ token_ids[i - 1] >= timestamp_begin and token_ids[i - 2] >= timestamp_begin
+ )
+ if last_was_single_ending:
+ prev_segments_len += time_precision * segment_size
+ else:
+ cur_max_timestamp = penultimate_timestamp
+ prev_segments_len += penultimate_timestamp
+
+ penultimate_timestamp = cur_max_timestamp
+ cur_max_timestamp = timestamp
+
+ time = (token - timestamp_begin) * time_precision + time_offset + prev_segments_len
+
+ time = round(time, 2)
+ if last_timestamp and token >= last_timestamp:
+ # Whisper outputted a timestamp token, but it falls within
+ # our stride, so we're going to skip it for the time being
+ # and resolve this later
+ # Skip is necessary because timestamp tokens always come
+ # by pair, so we need to skip the next one too (which would mark the start of another chunk).
+ skip = True
+ elif skip or (previous_tokens and token < first_timestamp):
+ skip = False
+ elif chunk["timestamp"][0] is None:
+ chunk["timestamp"][0] = time
+ else:
+ # This is the end of the timestamp chunk
+ if time == chunk["timestamp"][0]:
+ # This is a bug in timestamp token output
+ # where we're taking the duplicate token
+ # as a stop where it should be a start.
+ # This is an issue in the underlying model output
+ # Let's just skip it so it becomes de-factor
+ # a start again
+ pass
+ else:
+ chunk["timestamp"][1] = time
+ # Handling merges.
+ previous_tokens.append(current_tokens)
+ if return_timestamps == "word":
+ previous_token_timestamps.append(current_token_timestamps)
+ resolved_tokens, resolved_token_timestamps = _find_longest_common_sequence(
+ previous_tokens, previous_token_timestamps
+ )
+ resolved_text = tokenizer.decode(resolved_tokens)
+ chunk["text"] = resolved_text
+ if return_timestamps == "word":
+ chunk["words"] = _collate_word_timestamps(
+ tokenizer, resolved_tokens, resolved_token_timestamps, last_language, return_language
+ )
+ chunks.append(chunk)
+
+ # Flush all our temporary context
+ previous_tokens = []
+ current_tokens = []
+ previous_token_timestamps = []
+ current_token_timestamps = []
+ chunk = new_chunk()
+ else:
+ # 4/ Regular token
+ # We just append to the list of all tokens so we can handle
+ # merges later and decode into text.
+ current_tokens.append(token)
+ if return_timestamps == "word":
+ if i == 0:
+ start_time = round(0.0 + time_offset, 2)
+ else:
+ start_time = round(token_timestamps[i - 1] + time_offset, 2)
+ end_time = round(token_timestamps[i] + time_offset, 2)
+ current_token_timestamps.append((start_time, end_time))
+
+ if "stride" in output:
+ time_offset += chunk_len - stride_right
+
+ # Leftover tokens
+ if current_tokens:
+ previous_tokens.append(current_tokens)
+ if return_timestamps == "word":
+ previous_token_timestamps.append(current_token_timestamps)
+ elif not (any(p for p in previous_tokens)):
+ chunk = new_chunk()
+ previous_tokens = []
+ current_tokens = []
+ previous_token_timestamps = []
+ current_token_timestamps = []
+
+ if previous_tokens:
+ if return_timestamps:
+ logger.warning(
+ "Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. "
+ "Also make sure WhisperTimeStampLogitsProcessor was used during generation."
+ )
+ # Happens when we don't use timestamps
+ resolved_tokens, resolved_token_timestamps = _find_longest_common_sequence(
+ previous_tokens, previous_token_timestamps
+ )
+ resolved_text = tokenizer.decode(resolved_tokens)
+ chunk["text"] = resolved_text
+ if return_timestamps == "word":
+ chunk["words"] = _collate_word_timestamps(
+ tokenizer, resolved_tokens, resolved_token_timestamps, last_language, return_language
+ )
+ chunks.append(chunk)
+
+ # Preparing and cleaning up the pipeline output
+ full_text = "".join(chunk["text"] for chunk in chunks)
+ if return_timestamps or return_language:
+ for chunk in chunks:
+ if not return_timestamps:
+ chunk.pop("timestamp")
+ else:
+ chunk["timestamp"] = tuple(chunk["timestamp"])
+ if not return_language:
+ chunk.pop("language")
+
+ if return_timestamps == "word":
+ new_chunks = []
+ for chunk in chunks:
+ new_chunks.extend(chunk["words"])
+ optional = {"chunks": new_chunks}
+ else:
+ optional = {"chunks": chunks}
+ else:
+ optional = {}
+ return full_text, optional
+
+
+def _find_longest_common_sequence(sequences, token_timestamp_sequences=None):
+ # It would be much harder to do O(n) because of fault tolerance.
+ # We actually have a really good property which is that the total sequence
+ # MUST be those subsequences in order.
+ # If token_timestamp_sequences is provided, will split those sequences in
+ # exactly the same way.
+
+ left_sequence = sequences[0]
+ left_length = len(left_sequence)
+ total_sequence = []
+
+ if token_timestamp_sequences:
+ left_token_timestamp_sequence = token_timestamp_sequences[0]
+ total_token_timestamp_sequence = []
+
+ for seq_idx, right_sequence in enumerate(sequences[1:]):
+ # index = 0
+ max_ = 0.0
+ max_indices = (left_length, left_length, 0, 0)
+ # Here we're sliding matches
+ # [a, b, c, d]
+ # [c, d, f]
+ # = [c] == [d]
+ #
+ # [a, b, c, d]
+ # [c, d, f]
+ # = [c, d] == [c, d]
+ #
+ #
+ # [a, b, c, d]
+ # [c, d, f]
+ #
+ # = [b, c, d] == [c, d, f]
+ #
+ # [a, b, c, d]
+ # [c, d, f]
+ #
+ # [a, b, c] == [c, d, f]
+ #
+ # [a, b, c, d]
+ # [d, f]
+ #
+ # [a, b] == [d, f]
+ #
+ # [a, b, c, d]
+ # [f]
+ #
+ # [a] == [f]
+ right_length = len(right_sequence)
+ for i in range(1, left_length + right_length):
+ # epsilon to favor long perfect matches
+ eps = i / 10000.0
+
+ # Slightly convoluted because we don't want out of bound indices
+ # This will be necessary for a small conflict resolution optimization
+ # later
+ left_start = max(0, left_length - i)
+ left_stop = min(left_length, left_length + right_length - i)
+ left = np.array(left_sequence[left_start:left_stop])
+
+ right_start = max(0, i - left_length)
+ right_stop = min(right_length, i)
+ right = np.array(right_sequence[right_start:right_stop])
+
+ # We can only match subsequences of the same size.
+ if len(left) != len(right):
+ raise RuntimeError(
+ "There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference."
+ )
+
+ if token_timestamp_sequences:
+ # Get length of longest subsequence of tokens that match
+ # and have timestamps that are in order
+ matches = sum(
+ 1
+ for idx, elem in enumerate(left)
+ if (
+ elem == right[idx]
+ and left_token_timestamp_sequence[left_start + idx]
+ <= token_timestamp_sequences[seq_idx + 1][right_start + idx]
+ )
+ )
+
+ else:
+ matches = np.sum(left == right)
+
+ matching = matches / i + eps
+ if matches > 1 and matching > max_:
+ max_ = matching
+ max_indices = (left_start, left_stop, right_start, right_stop)
+
+ (left_start, left_stop, right_start, right_stop) = max_indices
+
+ # This is a small conflict optimization since those sequences overlap
+ # in audio.
+ # We're going to give more confidence to the left sequence
+ # for the left of the overlap,
+ # and to the right of the sequence, for the right of the overlap
+ left_mid = (left_stop + left_start) // 2
+ right_mid = (right_stop + right_start) // 2
+ total_sequence.extend(left_sequence[:left_mid])
+ left_sequence = right_sequence[right_mid:]
+ left_length = len(left_sequence)
+
+ if token_timestamp_sequences:
+ total_token_timestamp_sequence.extend(left_token_timestamp_sequence[:left_mid])
+ left_token_timestamp_sequence = token_timestamp_sequences[seq_idx + 1][right_mid:]
+
+ total_sequence.extend(left_sequence)
+
+ if token_timestamp_sequences is None:
+ return total_sequence
+
+ if len(token_timestamp_sequences) > 0:
+ total_token_timestamp_sequence.extend(left_token_timestamp_sequence)
+ return total_sequence, total_token_timestamp_sequence
+ else:
+ return total_sequence, []
+
+
+def _collate_word_timestamps(tokenizer, tokens, token_timestamps, language, return_language):
+ words, _, token_indices = _combine_tokens_into_words(tokenizer, tokens, language)
+
+ optional_language_field = {"language": language} if return_language else {}
+
+ timings = [
+ {
+ "text": word,
+ "timestamp": (token_timestamps[indices[0]][0], token_timestamps[indices[-1]][1]),
+ **optional_language_field,
+ }
+ for word, indices in zip(words, token_indices)
+ ]
+ return timings
+
+
+def _combine_tokens_into_words(
+ tokenizer,
+ tokens: list[int],
+ language: str | None = None,
+ prepend_punctuations: str = "\"'“¡¿([{-",
+ append_punctuations: str = "\"'.。,,!!??::”)]}、",
+):
+ """
+ Groups tokens by word. Returns a tuple containing a list of strings with the words, and a list of `token_id`
+ sequences with the tokens making up each word.
+ """
+ if language is None:
+ language = tokenizer.language
+ if language is None:
+ language = "english"
+
+ if language in {"chinese", "japanese", "thai", "lao", "myanmar", "cantonese"}:
+ # These languages don't typically use spaces.
+ words, word_tokens, token_indices = _split_tokens_on_unicode(tokenizer, tokens)
+ else:
+ words, word_tokens, token_indices = _split_tokens_on_spaces(tokenizer, tokens)
+
+ _merge_punctuations(words, word_tokens, token_indices, prepend_punctuations, append_punctuations)
+ return words, word_tokens, token_indices
+
+
+def _split_tokens_on_unicode(tokenizer, tokens: list[int]):
+ """Combine tokens into words by splitting at any position where the tokens are decoded as valid unicode points."""
+ decoded_full = tokenizer.decode(tokens, decode_with_timestamps=True)
+ replacement_char = "\ufffd"
+
+ words = []
+ word_tokens = []
+ token_indices = []
+ current_tokens = []
+ current_indices = []
+ unicode_offset = 0
+
+ for token_idx, token in enumerate(tokens):
+ current_tokens.append(token)
+ current_indices.append(token_idx)
+ decoded = tokenizer.decode(current_tokens, decode_with_timestamps=True)
+
+ if (
+ replacement_char not in decoded
+ or unicode_offset + decoded.index(replacement_char) >= len(decoded_full)
+ or decoded_full[unicode_offset + decoded.index(replacement_char)] == replacement_char
+ ):
+ words.append(decoded)
+ word_tokens.append(current_tokens)
+ token_indices.append(current_indices)
+ current_tokens = []
+ current_indices = []
+ unicode_offset += len(decoded)
+
+ return words, word_tokens, token_indices
+
+
+def _split_tokens_on_spaces(tokenizer, tokens: list[int]):
+ """Combine tokens into words by splitting at whitespace and punctuation tokens."""
+ subwords, subword_tokens_list, subword_indices_list = _split_tokens_on_unicode(tokenizer, tokens)
+ words = []
+ word_tokens = []
+ token_indices = []
+
+ for subword, subword_tokens, subword_indices in zip(subwords, subword_tokens_list, subword_indices_list):
+ special = subword_tokens[0] >= tokenizer.eos_token_id
+ with_space = subword.startswith(" ")
+ punctuation = subword.strip() in "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
+
+ if special or with_space or punctuation or len(words) == 0:
+ words.append(subword)
+ word_tokens.append(subword_tokens)
+ token_indices.append(subword_indices)
+ else:
+ words[-1] = words[-1] + subword
+ word_tokens[-1].extend(subword_tokens)
+ token_indices[-1].extend(subword_indices)
+
+ return words, word_tokens, token_indices
+
+
+def _merge_punctuations(words, tokens, indices, prepended, appended):
+ """Merges punctuation tokens with neighboring words."""
+ # prepend punctuations
+ i = len(words) - 2
+ j = len(words) - 1
+ while i >= 0:
+ if words[i].startswith(" ") and words[i].strip() in prepended:
+ words[j] = words[i] + words[j]
+ tokens[j] = tokens[i] + tokens[j]
+ indices[j] = indices[i] + indices[j]
+ words[i] = ""
+ tokens[i] = []
+ indices[i] = []
+ else:
+ j = i
+ i -= 1
+
+ # append punctuations
+ i = 0
+ j = 1
+ while j < len(words):
+ if not words[i].endswith(" ") and words[j] in appended:
+ words[i] += words[j]
+ tokens[i] += tokens[j]
+ indices[i] += indices[j]
+ words[j] = ""
+ tokens[j] = []
+ indices[j] = []
+ else:
+ i = j
+ j += 1
+
+ # remove elements that are now empty
+ words[:] = [word for word in words if word]
+ tokens[:] = [token for token in tokens if token]
+ indices[:] = [idx for idx in indices if idx]
+
+
+__all__ = ["WhisperTokenizer"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/x_clip/__init__.py b/.venv/lib/python3.12/site-packages/transformers/models/x_clip/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d9c5fea1b3147333041a432f8d50861104dc9140
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/x_clip/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_x_clip import *
+ from .modeling_x_clip import *
+ from .processing_x_clip import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/x_clip/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/x_clip/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c615a9ccaecc7957e2926222df4e8f606c5fa9e8
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/x_clip/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/x_clip/__pycache__/configuration_x_clip.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/x_clip/__pycache__/configuration_x_clip.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2b1039ed1ea43459d6f2a9d160cb97d3100a0c53
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/x_clip/__pycache__/configuration_x_clip.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/x_clip/__pycache__/modeling_x_clip.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/x_clip/__pycache__/modeling_x_clip.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d9ddc6e7c8d88dcc3b1c4c877acdf23e26b6acc1
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/x_clip/__pycache__/modeling_x_clip.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/x_clip/__pycache__/modular_x_clip.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/x_clip/__pycache__/modular_x_clip.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1b92b0c41becb7ce3e84b171a77471b991892676
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/x_clip/__pycache__/modular_x_clip.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/x_clip/__pycache__/processing_x_clip.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/x_clip/__pycache__/processing_x_clip.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bff5a333537e1638c8b211f0ab788ba37011e75c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/x_clip/__pycache__/processing_x_clip.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/x_clip/configuration_x_clip.py b/.venv/lib/python3.12/site-packages/transformers/models/x_clip/configuration_x_clip.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b7316b4b1b758e6d8430413e948c78a9550cd19
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/x_clip/configuration_x_clip.py
@@ -0,0 +1,235 @@
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""X-CLIP model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring, logging
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(checkpoint="microsoft/xclip-base-patch32")
+@strict
+class XCLIPTextConfig(PreTrainedConfig):
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import XCLIPTextModel, XCLIPTextConfig
+
+ >>> # Initializing a XCLIPTextModel with microsoft/xclip-base-patch32 style configuration
+ >>> configuration = XCLIPTextConfig()
+
+ >>> # Initializing a XCLIPTextConfig from the microsoft/xclip-base-patch32 style configuration
+ >>> model = XCLIPTextModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "xclip_text_model"
+ base_config_key = "text_config"
+
+ vocab_size: int = 49408
+ hidden_size: int = 512
+ intermediate_size: int = 2048
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 8
+ max_position_embeddings: int = 77
+ hidden_act: str = "quick_gelu"
+ layer_norm_eps: float = 1e-5
+ attention_dropout: float | int = 0.0
+ initializer_range: float = 0.02
+ initializer_factor: float = 1.0
+ pad_token_id: int | None = 1
+ bos_token_id: int | None = 0
+ eos_token_id: int | list[int] | None = 2
+
+
+@auto_docstring(checkpoint="microsoft/xclip-base-patch32")
+@strict
+class XCLIPVisionConfig(PreTrainedConfig):
+ r"""
+ mit_hidden_size (`int`, *optional*, defaults to 512):
+ Dimensionality of the encoder layers of the Multiframe Integration Transformer (MIT).
+ mit_intermediate_size (`int`, *optional*, defaults to 2048):
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Multiframe Integration Transformer
+ (MIT).
+ mit_num_hidden_layers (`int`, *optional*, defaults to 1):
+ Number of hidden layers in the Multiframe Integration Transformer (MIT).
+ mit_num_attention_heads (`int`, *optional*, defaults to 8):
+ Number of attention heads for each attention layer in the Multiframe Integration Transformer (MIT).
+ num_frames (`int`, *optional*, defaults to 8):
+ The number of frames in each video.
+
+ Example:
+
+ ```python
+ >>> from transformers import XCLIPVisionModel, XCLIPVisionConfig
+
+ >>> # Initializing a XCLIPVisionModel with microsoft/xclip-base-patch32 style configuration
+ >>> configuration = XCLIPVisionConfig()
+
+ >>> # Initializing a XCLIPVisionModel model from the microsoft/xclip-base-patch32 style configuration
+ >>> model = XCLIPVisionModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "xclip_vision_model"
+ base_config_key = "vision_config"
+
+ hidden_size: int = 768
+ intermediate_size: int = 3072
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ mit_hidden_size: int = 512
+ mit_intermediate_size: int = 2048
+ mit_num_hidden_layers: int = 1
+ mit_num_attention_heads: int = 8
+ num_channels: int = 3
+ image_size: int | list[int] | tuple[int, int] = 224
+ patch_size: int | list[int] | tuple[int, int] = 32
+ num_frames: int = 8
+ hidden_act: str = "quick_gelu"
+ layer_norm_eps: float = 1e-5
+ attention_dropout: float | int = 0.0
+ initializer_range: float = 0.02
+ initializer_factor: float = 1.0
+ drop_path_rate: float | int = 0.0
+
+
+@auto_docstring(checkpoint="microsoft/xclip-base-patch32")
+@strict
+class XCLIPConfig(PreTrainedConfig):
+ r"""
+ prompt_layers (`int`, *optional*, defaults to 2):
+ Number of layers in the video specific prompt generator.
+ prompt_alpha (`float`, *optional*, defaults to 0.1):
+ Alpha value to use in the video specific prompt generator.
+ prompt_hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
+ The non-linear activation function (function or string) in the video specific prompt generator. If string,
+ `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
+ prompt_num_attention_heads (`int`, *optional*, defaults to 8):
+ Number of attention heads in the cross-attention of the video specific prompt generator.
+ prompt_attention_dropout (`float`, *optional*, defaults to 0.0):
+ The dropout probability for the attention layers in the video specific prompt generator.
+ prompt_projection_dropout (`float`, *optional*, defaults to 0.0):
+ The dropout probability for the projection layers in the video specific prompt generator.
+ """
+
+ model_type = "xclip"
+ sub_configs = {"text_config": XCLIPTextConfig, "vision_config": XCLIPVisionConfig}
+
+ text_config: dict | PreTrainedConfig | None = None
+ vision_config: dict | PreTrainedConfig | None = None
+ projection_dim: int = 512
+ prompt_layers: int = 2
+ prompt_alpha: float = 0.1
+ prompt_hidden_act: str = "quick_gelu"
+ prompt_num_attention_heads: int = 8
+ prompt_attention_dropout: float | int = 0.0
+ prompt_projection_dropout: float | int = 0.0
+ logit_scale_init_value: float = 2.6592
+ initializer_factor: float = 1.0
+
+ def __post_init__(self, **kwargs):
+ if self.text_config is None:
+ text_config = {}
+ logger.info("`text_config` is `None`. Initializing the `XCLIPTextConfig` with default values.")
+ elif isinstance(self.text_config, XCLIPTextConfig):
+ text_config = self.text_config.to_dict()
+ else:
+ text_config = self.text_config
+
+ if self.vision_config is None:
+ vision_config = {}
+ logger.info("`vision_config` is `None`. initializing the `XCLIPVisionConfig` with default values.")
+ elif isinstance(self.vision_config, XCLIPVisionConfig):
+ vision_config = self.vision_config.to_dict()
+ else:
+ vision_config = self.vision_config
+
+ # For backward compatibility check keyword args
+ # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
+ # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
+ # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
+ text_config_dict = kwargs.pop("text_config_dict", None)
+ vision_config_dict = kwargs.pop("vision_config_dict", None)
+
+ if text_config_dict is not None:
+ # This is the complete result when using `text_config_dict`.
+ _text_config_dict = XCLIPTextConfig(**text_config_dict).to_dict()
+
+ # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
+ for key, value in _text_config_dict.items():
+ if key in text_config and value != text_config[key] and key != "transformers_version":
+ # If specified in `text_config_dict`
+ if key in text_config_dict:
+ message = (
+ f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "
+ f'The value `text_config_dict["{key}"]` will be used instead.'
+ )
+ # If inferred from default argument values (just to be super careful)
+ else:
+ message = (
+ f"`text_config_dict` is provided which will be used to initialize `XCLIPTextConfig`. The "
+ f'value `text_config["{key}"]` will be overridden.'
+ )
+ logger.info(message)
+
+ # Update all values in `text_config` with the ones in `_text_config_dict`.
+ text_config.update(_text_config_dict)
+
+ if vision_config_dict is not None:
+ # This is the complete result when using `vision_config_dict`.
+ _vision_config_dict = XCLIPVisionConfig(**vision_config_dict).to_dict()
+ # convert keys to string instead of integer
+ if "id2label" in _vision_config_dict:
+ _vision_config_dict["id2label"] = {
+ str(key): value for key, value in _vision_config_dict["id2label"].items()
+ }
+
+ # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
+ for key, value in _vision_config_dict.items():
+ if key in vision_config and value != vision_config[key] and key != "transformers_version":
+ # If specified in `vision_config_dict`
+ if key in vision_config_dict:
+ message = (
+ f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different "
+ f'values. The value `vision_config_dict["{key}"]` will be used instead.'
+ )
+ # If inferred from default argument values (just to be super careful)
+ else:
+ message = (
+ f"`vision_config_dict` is provided which will be used to initialize `XCLIPVisionConfig`. "
+ f'The value `vision_config["{key}"]` will be overridden.'
+ )
+ logger.info(message)
+
+ # Update all values in `vision_config` with the ones in `_vision_config_dict`.
+ vision_config.update(_vision_config_dict)
+
+ # Finally we can convert back our unified text/vision configs to `PretrainedConfig`
+ self.text_config = XCLIPTextConfig(**text_config)
+ self.vision_config = XCLIPVisionConfig(**vision_config)
+
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["XCLIPConfig", "XCLIPTextConfig", "XCLIPVisionConfig"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/x_clip/modeling_x_clip.py b/.venv/lib/python3.12/site-packages/transformers/models/x_clip/modeling_x_clip.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe6ff0207fbb41c813308705ad9410ee17476f45
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/x_clip/modeling_x_clip.py
@@ -0,0 +1,1240 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/x_clip/modular_x_clip.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_x_clip.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2022 Microsoft Research and The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import copy
+from collections.abc import Callable
+from dataclasses import dataclass
+from typing import Any
+
+import torch
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...masking_utils import create_causal_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import ModelOutput, TransformersKwargs, auto_docstring, torch_int
+from ...utils.generic import can_return_tuple, merge_with_config_defaults
+from ...utils.output_capturing import OutputRecorder, capture_outputs
+from .configuration_x_clip import XCLIPConfig, XCLIPTextConfig, XCLIPVisionConfig
+
+
+@auto_docstring
+@dataclass
+class XCLIPOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
+ Contrastive loss for video-text similarity.
+ logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, video_batch_size)`):
+ The scaled dot product scores between `text_embeds` and `video_embeds`. This represents the text-video
+ similarity scores.
+ text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
+ The text embeddings obtained by applying the projection layer to the pooled output of [`XCLIPTextModel`].
+ text_model_output (`BaseModelOutputWithPooling`):
+ The output of the [`XCLIPTextModel`].
+ vision_model_output (`BaseModelOutputWithPooling`):
+ The output of the [`XCLIPVisionModel`].
+ logits_per_video (`torch.FloatTensor` of shape `(video_batch_size, text_batch_size)`):
+ The scaled dot product scores between `video_embeds` and `text_embeds`. This represents the video-text
+ similarity scores.
+ video_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
+ The video embeddings obtained by applying the projection layer to the pooled output of
+ [`XCLIPVisionModel`].
+ mit_output (`BaseModelOutputWithPooling`):
+ The output of `XCLIPMultiframeIntegrationTransformer` (MIT for short).
+ """
+
+ loss: torch.FloatTensor | None = None
+ logits_per_text: torch.FloatTensor | None = None
+ text_embeds: torch.FloatTensor | None = None
+ text_model_output: BaseModelOutputWithPooling = None
+ vision_model_output: BaseModelOutputWithPooling = None
+
+ logits_per_video: torch.FloatTensor | None = None
+ video_embeds: torch.FloatTensor | None = None
+ mit_output: BaseModelOutputWithPooling = None
+
+ def to_tuple(self) -> tuple[Any]:
+ return tuple(
+ self[k]
+ if k not in ["text_model_output", "vision_model_output", "mit_output"]
+ else getattr(self, k).to_tuple()
+ for k in self.keys()
+ )
+
+
+class XCLIPVisionEmbeddings(nn.Module):
+ def __init__(self, config: XCLIPVisionConfig):
+ super().__init__()
+ self.config = config
+ self.embed_dim = config.hidden_size
+ self.image_size = config.image_size
+ self.patch_size = config.patch_size
+
+ self.class_embedding = nn.Parameter(torch.randn(self.embed_dim))
+
+ self.patch_embedding = nn.Conv2d(
+ in_channels=config.num_channels,
+ out_channels=self.embed_dim,
+ kernel_size=self.patch_size,
+ stride=self.patch_size,
+ bias=False,
+ )
+
+ self.num_patches = (self.image_size // self.patch_size) ** 2
+ self.num_positions = self.num_patches + 1
+ self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
+ self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
+
+ def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
+ """
+ This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
+ images. This method is also adapted to support torch.jit tracing.
+
+ Adapted from:
+ - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
+ - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
+ """
+
+ num_patches = embeddings.shape[1] - 1
+ position_embedding = self.position_embedding.weight.unsqueeze(0)
+ num_positions = position_embedding.shape[1] - 1
+
+ # always interpolate when tracing to ensure the exported model works for dynamic input shapes
+ if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
+ return self.position_embedding(self.position_ids)
+
+ class_pos_embed = position_embedding[:, :1]
+ patch_pos_embed = position_embedding[:, 1:]
+
+ dim = embeddings.shape[-1]
+
+ new_height = height // self.patch_size
+ new_width = width // self.patch_size
+
+ sqrt_num_positions = torch_int(num_positions**0.5)
+ patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
+ patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
+
+ patch_pos_embed = nn.functional.interpolate(
+ patch_pos_embed,
+ size=(new_height, new_width),
+ mode="bicubic",
+ align_corners=False,
+ )
+
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
+
+ return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
+
+ def forward(self, pixel_values: torch.FloatTensor, interpolate_pos_encoding=False) -> torch.Tensor:
+ batch_size, _, height, width = pixel_values.shape
+ if not interpolate_pos_encoding and (height != self.image_size or width != self.image_size):
+ raise ValueError(
+ f"Input image size ({height}*{width}) doesn't match model ({self.image_size}*{self.image_size})."
+ )
+ target_dtype = self.patch_embedding.weight.dtype
+ patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
+
+ class_embeds = self.class_embedding.expand(batch_size, 1, -1)
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
+ if interpolate_pos_encoding:
+ embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
+ else:
+ embeddings = embeddings + self.position_embedding(self.position_ids)
+ return embeddings
+
+
+class XCLIPTextEmbeddings(nn.Module):
+ def __init__(self, config: XCLIPTextConfig):
+ super().__init__()
+ embed_dim = config.hidden_size
+
+ self.token_embedding = nn.Embedding(config.vocab_size, embed_dim)
+ self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim)
+
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
+ self.register_buffer(
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
+ )
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ ) -> torch.Tensor:
+ seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2]
+ max_position_embedding = self.position_embedding.weight.shape[0]
+
+ if seq_length > max_position_embedding:
+ raise ValueError(
+ f"Sequence length must be less than max_position_embeddings (got `sequence length`: "
+ f"{seq_length} and max_position_embeddings: {max_position_embedding}"
+ )
+
+ if position_ids is None:
+ position_ids = self.position_ids[:, :seq_length]
+
+ if inputs_embeds is None:
+ inputs_embeds = self.token_embedding(input_ids)
+
+ position_embeddings = self.position_embedding(position_ids)
+ embeddings = inputs_embeds + position_embeddings
+
+ return embeddings
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+ return attn_output, attn_weights
+
+
+class XCLIPAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: XCLIPVisionConfig | XCLIPTextConfig):
+ super().__init__()
+ self.config = config
+ self.embed_dim = config.hidden_size
+ self.num_heads = config.num_attention_heads
+ self.head_dim = self.embed_dim // self.num_heads
+ self.scale = self.head_dim**-0.5
+ self.dropout = config.attention_dropout
+ self.is_causal = False
+
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
+ """Input shape: Batch x Time x Channel"""
+
+ input_shape = hidden_states.shape[:-1]
+
+ hidden_shape = (*input_shape, -1, self.head_dim)
+ queries = self.q_proj(hidden_states)
+ keys = self.k_proj(hidden_states)
+ values = self.v_proj(hidden_states)
+
+ queries = queries.view(hidden_shape).transpose(1, 2)
+ keys = keys.view(hidden_shape).transpose(1, 2)
+ values = values.view(hidden_shape).transpose(1, 2)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ queries,
+ keys,
+ values,
+ attention_mask,
+ scaling=self.scale,
+ dropout=0.0 if not self.training else self.dropout,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.out_proj(attn_output)
+
+ return attn_output, attn_weights
+
+
+class XCLIPMLP(nn.Module):
+ def __init__(self, config: XCLIPVisionConfig | XCLIPTextConfig):
+ super().__init__()
+ self.config = config
+ self.activation_fn = ACT2FN[config.hidden_act]
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.fc1(hidden_states)
+ hidden_states = self.activation_fn(hidden_states)
+ hidden_states = self.fc2(hidden_states)
+ return hidden_states
+
+
+class XCLIPEncoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: XCLIPVisionConfig):
+ super().__init__()
+ self.embed_dim = config.hidden_size
+ self.self_attn = XCLIPAttention(config)
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
+ self.mlp = XCLIPMLP(config)
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.FloatTensor:
+ residual = hidden_states
+
+ hidden_states = self.layer_norm1(hidden_states)
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ residual = hidden_states
+ hidden_states = self.layer_norm2(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+
+ return hidden_states
+
+
+class XCLIPDropPath(nn.Module):
+ """Stochastic depth (DropPath) per sample, for residual blocks.
+
+ Identity when ``drop_prob`` is 0 or outside training. See `Deep Networks with Stochastic Depth
+ `_.
+ """
+
+ def __init__(self, drop_prob: float = 0.0) -> None:
+ super().__init__()
+ self.drop_prob = drop_prob
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ if self.drop_prob == 0.0 or not self.training:
+ return hidden_states
+ keep_prob = 1 - self.drop_prob
+ shape = (hidden_states.shape[0],) + (1,) * (hidden_states.ndim - 1)
+ random_tensor = torch.rand(shape, dtype=hidden_states.dtype, device=hidden_states.device)
+ random_tensor = torch.floor(random_tensor + keep_prob)
+ return hidden_states.div(keep_prob) * random_tensor
+
+ def extra_repr(self) -> str:
+ return f"p={self.drop_prob}"
+
+
+class XCLIPVisionEncoderLayer(GradientCheckpointingLayer):
+ """
+ This corresponds to the `CrossFramelAttentionBlock` class in the original implementation.
+ """
+
+ def __init__(self, config: XCLIPConfig):
+ super().__init__()
+ self.embed_dim = config.hidden_size
+ self.self_attn = XCLIPAttention(config)
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
+ self.mlp = XCLIPMLP(config)
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
+ self.num_frames = config.num_frames
+ self.message_fc = nn.Linear(self.embed_dim, self.embed_dim)
+ self.message_ln = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
+ self.message_attn = XCLIPAttention(config)
+ self.drop_path = XCLIPDropPath(config.drop_path_rate) if config.drop_path_rate > 0.0 else nn.Identity()
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.FloatTensor, torch.Tensor | None]:
+ batch_time, seq_length, hidden_size = hidden_states.size()
+ batch_size = batch_time // self.num_frames
+ msg_token = self.message_fc(hidden_states[:, 0, :])
+ msg_token = msg_token.view(batch_size, self.num_frames, hidden_size)
+
+ msg_token = msg_token + self.drop_path(self.message_attn(self.message_ln(msg_token), **kwargs)[0])
+ # add dummy sequence dimension
+ msg_token = msg_token.view(-1, 1, hidden_size)
+
+ hidden_states = torch.cat([hidden_states, msg_token], dim=1)
+
+ residual = hidden_states
+
+ hidden_states = self.layer_norm1(hidden_states)
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ hidden_states = hidden_states[:, :seq_length, :]
+
+ residual = hidden_states
+ hidden_states = self.layer_norm2(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+
+ return hidden_states
+
+
+@auto_docstring
+class XCLIPPreTrainedModel(PreTrainedModel):
+ config: XCLIPConfig
+ base_model_prefix = "x_clip"
+ input_modalities = ("image", "text")
+ _no_split_modules = [
+ "XCLIPTextEmbeddings",
+ "XCLIPEncoderLayer",
+ "XCLIPVisionEmbeddings",
+ "XCLIPVisionEncoderLayer",
+ ]
+
+ supports_gradient_checkpointing = True
+ _supports_sdpa = True
+ _supports_flash_attn = True
+ _supports_flex_attn = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": [XCLIPEncoderLayer, XCLIPVisionEncoderLayer],
+ "attentions": OutputRecorder(XCLIPAttention, layer_name="self_attn", index=1),
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ factor = self.config.initializer_factor
+ if isinstance(module, XCLIPTextEmbeddings):
+ init.normal_(module.token_embedding.weight, mean=0.0, std=factor * 0.02)
+ init.normal_(module.position_embedding.weight, mean=0.0, std=factor * 0.02)
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
+ elif isinstance(module, XCLIPVisionEmbeddings):
+ init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor)
+ init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor)
+ init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor)
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
+ elif isinstance(module, XCLIPAttention):
+ in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
+ out_proj_std = (module.embed_dim**-0.5) * factor
+ init.normal_(module.q_proj.weight, std=in_proj_std)
+ init.normal_(module.k_proj.weight, std=in_proj_std)
+ init.normal_(module.v_proj.weight, std=in_proj_std)
+ init.normal_(module.out_proj.weight, std=out_proj_std)
+ elif isinstance(module, XCLIPMLP):
+ in_proj_std = (module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
+ fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
+ init.normal_(module.fc1.weight, std=fc_std)
+ init.normal_(module.fc2.weight, std=in_proj_std)
+ elif isinstance(module, XCLIPModel):
+ init.normal_(
+ module.text_projection.weight,
+ std=module.text_embed_dim**-0.5 * factor,
+ )
+ init.normal_(
+ module.visual_projection.weight,
+ std=module.vision_embed_dim**-0.5 * factor,
+ )
+ init.normal_(module.prompts_visual_projection, mean=0.0, std=module.vision_embed_dim**-0.5 * factor)
+ elif isinstance(module, XCLIPMultiframeIntegrationTransformer):
+ init.normal_(module.position_embedding, std=factor)
+
+ if isinstance(module, nn.LayerNorm):
+ init.zeros_(module.bias)
+ init.ones_(module.weight)
+ if isinstance(module, nn.Linear):
+ init.normal_(module.weight, mean=0.0, std=factor)
+ if module.bias is not None:
+ init.zeros_(module.bias)
+
+
+class XCLIPEncoder(nn.Module):
+ """
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
+ [`XCLIPEncoderLayer`].
+
+ Args:
+ config: XCLIPConfig
+ """
+
+ def __init__(self, config: XCLIPConfig):
+ super().__init__()
+ self.config = config
+ self.layers = nn.ModuleList([XCLIPEncoderLayer(config) for _ in range(config.num_hidden_layers)])
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ inputs_embeds,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutput:
+ hidden_states = inputs_embeds
+ for encoder_layer in self.layers:
+ hidden_states = encoder_layer(
+ hidden_states,
+ attention_mask,
+ **kwargs,
+ )
+
+ return BaseModelOutput(
+ last_hidden_state=hidden_states,
+ )
+
+
+class XCLIPVisionEncoder(nn.Module):
+ """
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
+ [`XCLIPVisionEncoderLayer`].
+
+ Args:
+ config: XCLIPVisionConfig
+ """
+
+ def __init__(self, config: XCLIPVisionConfig):
+ super().__init__()
+ self.config = config
+ self.layers = nn.ModuleList([XCLIPVisionEncoderLayer(config) for _ in range(config.num_hidden_layers)])
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ inputs_embeds,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutput:
+ hidden_states = inputs_embeds
+ for encoder_layer in self.layers:
+ hidden_states = encoder_layer(
+ hidden_states,
+ attention_mask,
+ **kwargs,
+ )
+
+ return BaseModelOutput(
+ last_hidden_state=hidden_states,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ The text model from XCLIP without any head or projection on top.
+ """
+)
+class XCLIPTextModel(XCLIPPreTrainedModel):
+ config: XCLIPTextConfig
+ input_modalities = ("text",)
+ _input_embed_layer = "token_embedding"
+
+ def __init__(self, config: XCLIPTextConfig):
+ super().__init__(config)
+ embed_dim = config.hidden_size
+ self.embeddings = XCLIPTextEmbeddings(config)
+ self.encoder = XCLIPEncoder(config)
+ self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+ self.eos_token_id = 2 # Force legacy behaviour
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs(tie_last_hidden_states=False)
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, XCLIPTextModel
+
+ >>> model = XCLIPTextModel.from_pretrained("microsoft/xclip-base-patch32")
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/xclip-base-patch32")
+
+ >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
+
+ >>> outputs = model(**inputs)
+ >>> last_hidden_state = outputs.last_hidden_state
+ >>> pooled_output = outputs.pooler_output # pooled (EOS token) states
+ ```"""
+ if input_ids is None:
+ raise ValueError("You have to specify input_ids")
+
+ input_shape = input_ids.size()
+ input_ids = input_ids.view(-1, input_shape[-1])
+
+ hidden_states = self.embeddings(input_ids=input_ids, position_ids=position_ids)
+
+ attention_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=hidden_states,
+ attention_mask=attention_mask,
+ past_key_values=None,
+ )
+
+ kwargs.pop("is_causal", None)
+ encoder_outputs: BaseModelOutput = self.encoder(
+ inputs_embeds=hidden_states,
+ attention_mask=attention_mask,
+ is_causal=True,
+ **kwargs,
+ )
+
+ last_hidden_state = encoder_outputs.last_hidden_state
+ last_hidden_state = self.final_layer_norm(last_hidden_state)
+
+ if self.eos_token_id == 2:
+ # The `eos_token_id` was incorrect before PR #24773: Let's keep what have been done here.
+ # A XCLIP model with such `eos_token_id` in the config can't work correctly with extra new tokens added
+ # ------------------------------------------------------------
+ # text_embeds.shape = [batch_size, sequence_length, transformer.width]
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
+ # casting to torch.int for onnx compatibility: argmax doesn't support int64 inputs with opset 14
+ pooled_output = last_hidden_state[
+ torch.arange(last_hidden_state.shape[0], device=last_hidden_state.device),
+ input_ids.to(dtype=torch.int, device=last_hidden_state.device).argmax(dim=-1),
+ ]
+ else:
+ # The config gets updated `eos_token_id` from PR #24773 (so the use of extra new tokens is possible)
+ pooled_output = last_hidden_state[
+ torch.arange(last_hidden_state.shape[0], device=last_hidden_state.device),
+ # We need to get the first position of `eos_token_id` value (`pad_token_ids` might equal to `eos_token_id`)
+ # Note: we assume each sequence (along batch dim.) contains an `eos_token_id` (e.g. prepared by the tokenizer)
+ (input_ids.to(dtype=torch.int, device=last_hidden_state.device) == self.eos_token_id)
+ .int()
+ .argmax(dim=-1),
+ ]
+
+ return BaseModelOutputWithPooling(
+ last_hidden_state=last_hidden_state,
+ pooler_output=pooled_output,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ The vision model from XCLIP without any head or projection on top.
+ """
+)
+class XCLIPVisionModel(XCLIPPreTrainedModel):
+ config: XCLIPVisionConfig
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+ _input_embed_layer = "patch_embedding"
+
+ def __init__(self, config: XCLIPVisionConfig):
+ super().__init__(config)
+ embed_dim = config.hidden_size
+
+ self.embeddings = XCLIPVisionEmbeddings(config)
+ self.encoder = XCLIPVisionEncoder(config)
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+ self.pre_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs(tie_last_hidden_states=False)
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor | None,
+ interpolate_pos_encoding: bool | None = False,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ Examples:
+
+ ```python
+ >>> import av
+ >>> import torch
+ >>> import numpy as np
+
+ >>> from transformers import AutoProcessor, XCLIPVisionModel
+ >>> from huggingface_hub import hf_hub_download
+
+ >>> np.random.seed(0)
+
+
+ >>> def read_video_pyav(container, indices):
+ ... '''
+ ... Decode the video with PyAV decoder.
+ ... Args:
+ ... container (`av.container.input.InputContainer`): PyAV container.
+ ... indices (`list[int]`): List of frame indices to decode.
+ ... Returns:
+ ... result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
+ ... '''
+ ... frames = []
+ ... container.seek(0)
+ ... start_index = indices[0]
+ ... end_index = indices[-1]
+ ... for i, frame in enumerate(container.decode(video=0)):
+ ... if i > end_index:
+ ... break
+ ... if i >= start_index and i in indices:
+ ... frames.append(frame)
+ ... return np.stack([x.to_ndarray(format="rgb24") for x in frames])
+
+
+ >>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
+ ... '''
+ ... Sample a given number of frame indices from the video.
+ ... Args:
+ ... clip_len (`int`): Total number of frames to sample.
+ ... frame_sample_rate (`int`): Sample every n-th frame.
+ ... seg_len (`int`): Maximum allowed index of sample's last frame.
+ ... Returns:
+ ... indices (`list[int]`): List of sampled frame indices
+ ... '''
+ ... converted_len = int(clip_len * frame_sample_rate)
+ ... end_idx = np.random.randint(converted_len, seg_len)
+ ... start_idx = end_idx - converted_len
+ ... indices = np.linspace(start_idx, end_idx, num=clip_len)
+ ... indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
+ ... return indices
+
+
+ >>> # video clip consists of 300 frames (10 seconds at 30 FPS)
+ >>> file_path = hf_hub_download(
+ ... repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
+ ... )
+ >>> container = av.open(file_path)
+
+ >>> # sample 16 frames
+ >>> indices = sample_frame_indices(clip_len=8, frame_sample_rate=1, seg_len=container.streams.video[0].frames)
+ >>> video = read_video_pyav(container, indices)
+
+ >>> processor = AutoProcessor.from_pretrained("microsoft/xclip-base-patch32")
+ >>> model = XCLIPVisionModel.from_pretrained("microsoft/xclip-base-patch32")
+
+ >>> pixel_values = processor(videos=list(video), return_tensors="pt").pixel_values
+
+ >>> batch_size, num_frames, num_channels, height, width = pixel_values.shape
+ >>> pixel_values = pixel_values.reshape(-1, num_channels, height, width)
+
+ >>> outputs = model(pixel_values)
+ >>> last_hidden_state = outputs.last_hidden_state
+ ```"""
+ hidden_states = self.embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
+ hidden_states = self.pre_layernorm(hidden_states)
+
+ encoder_outputs: BaseModelOutput = self.encoder(
+ inputs_embeds=hidden_states,
+ **kwargs,
+ )
+
+ last_hidden_state = encoder_outputs.last_hidden_state
+ pooled_output = last_hidden_state[:, 0, :]
+ pooled_output = self.post_layernorm(pooled_output)
+
+ return BaseModelOutputWithPooling(
+ last_hidden_state=last_hidden_state,
+ pooler_output=pooled_output,
+ )
+
+
+class XCLIPMultiframeIntegrationTransformer(nn.Module):
+ """
+ This corresponds to the `MultiframeIntegrationTransformer` class in the original implementation.
+ """
+
+ def __init__(self, config: XCLIPVisionConfig):
+ super().__init__()
+
+ self.position_embedding = nn.Parameter(torch.empty(1, config.num_frames, config.hidden_size))
+ self.encoder = XCLIPEncoder(config)
+
+ def forward(
+ self,
+ hidden_states,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutput:
+ residual = hidden_states
+
+ # add position embeddings
+ hidden_states = hidden_states + self.position_embedding
+
+ encoder_outputs = self.encoder(
+ inputs_embeds=hidden_states,
+ **kwargs,
+ )
+ last_hidden_state = encoder_outputs[0]
+
+ last_hidden_state = last_hidden_state.type(hidden_states.dtype) + residual
+
+ pooled_output = last_hidden_state.mean(dim=1, keepdim=False)
+
+ return BaseModelOutputWithPooling(
+ last_hidden_state=last_hidden_state,
+ pooler_output=pooled_output,
+ )
+
+
+class XCLIPCrossAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.embed_dim = config.projection_dim
+
+ self.num_heads = config.prompt_num_attention_heads
+ self.head_dim = self.embed_dim // self.num_heads
+ self.scale = self.head_dim**-0.5
+ self.is_causal = False
+
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, False)
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, False)
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, False)
+
+ self.attn_drop = config.prompt_attention_dropout
+ self.proj = nn.Linear(self.embed_dim, self.embed_dim)
+ self.proj_drop = nn.Dropout(config.prompt_projection_dropout)
+
+ def forward(
+ self,
+ queries: torch.Tensor,
+ keys: torch.Tensor,
+ values: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
+ """Input shape: Batch x Time x Channel"""
+ batch_size, query_seq_len, hidden_size = queries.shape
+ batch_size, key_seq_len, hidden_size = keys.shape
+
+ query_shape = (batch_size, query_seq_len, -1, self.head_dim)
+ key_shape = (batch_size, key_seq_len, -1, self.head_dim)
+
+ queries = self.q_proj(queries).view(*query_shape).transpose(1, 2)
+ keys = self.k_proj(keys).view(*key_shape).transpose(1, 2)
+ values = self.v_proj(values).view(*key_shape).transpose(1, 2)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ queries,
+ keys,
+ values,
+ attention_mask=None,
+ scaling=self.scale,
+ dropout=0.0 if not self.training else self.attn_drop,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(batch_size, query_seq_len, -1).contiguous()
+ attn_output = self.proj(attn_output)
+ attn_output = self.proj_drop(attn_output)
+
+ return attn_output
+
+
+class PromptGeneratorLayer(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+
+ embed_dim = config.projection_dim
+ self.cross_attn = XCLIPCrossAttention(config)
+ self.norm1 = nn.LayerNorm(embed_dim, eps=config.text_config.layer_norm_eps)
+ self.norm3 = nn.LayerNorm(embed_dim, eps=config.text_config.layer_norm_eps)
+ self.mlp = nn.Sequential(
+ nn.Linear(embed_dim, embed_dim * 4),
+ ACT2FN[config.prompt_hidden_act],
+ nn.Dropout(config.prompt_attention_dropout),
+ nn.Linear(embed_dim * 4, embed_dim),
+ )
+
+ def forward(self, hidden_states, visual):
+ hidden_states = hidden_states + self.cross_attn(self.norm1(hidden_states), visual, visual)
+ hidden_states = hidden_states + self.mlp(self.norm3(hidden_states))
+ return hidden_states
+
+
+class XCLIPPromptGenerator(nn.Module):
+ """This corresponds to the `VideoSpecificPrompt` class in the original implementation."""
+
+ def __init__(self, config):
+ super().__init__()
+ embed_dim = config.projection_dim
+ self.layernorm = nn.LayerNorm(embed_dim, eps=config.vision_config.layer_norm_eps)
+ self.decoder = nn.ModuleList([PromptGeneratorLayer(config) for _ in range(config.prompt_layers)])
+ self.alpha = nn.Parameter(torch.ones(embed_dim) * config.prompt_alpha)
+
+ def forward(self, text, visual):
+ visual = self.layernorm(visual)
+ for layer in self.decoder:
+ text = layer(text, visual)
+
+ return self.alpha * text
+
+
+# contrastive loss function, adapted from
+# https://sachinruk.github.io/blog/2021-03-07-x_clip.html
+def contrastive_loss(logits: torch.Tensor) -> torch.Tensor:
+ return nn.functional.cross_entropy(logits, torch.arange(len(logits), device=logits.device))
+
+
+def image_text_contrastive_loss(similarity: torch.Tensor) -> torch.Tensor:
+ caption_loss = contrastive_loss(similarity)
+ image_loss = contrastive_loss(similarity.T)
+ return (caption_loss + image_loss) / 2.0
+
+
+@auto_docstring
+class XCLIPModel(XCLIPPreTrainedModel):
+ config: XCLIPConfig
+
+ def __init__(self, config: XCLIPConfig):
+ super().__init__(config)
+ text_config = self.config.text_config
+ vision_config = self.config.vision_config
+
+ self.projection_dim = config.projection_dim
+ self.text_embed_dim = text_config.hidden_size
+ self.vision_embed_dim = vision_config.hidden_size
+
+ self.text_model = XCLIPTextModel(text_config)
+ self.vision_model = XCLIPVisionModel(vision_config)
+
+ self.visual_projection = nn.Linear(self.vision_embed_dim, self.projection_dim, bias=False)
+ self.text_projection = nn.Linear(self.text_embed_dim, self.projection_dim, bias=False)
+ self.logit_scale = nn.Parameter(torch.tensor(self.config.logit_scale_init_value))
+
+ self.prompts_visual_layernorm = nn.LayerNorm(self.vision_embed_dim, eps=config.vision_config.layer_norm_eps)
+ self.prompts_visual_projection = nn.Parameter(torch.randn(self.vision_embed_dim, self.projection_dim))
+ mit_config = copy.copy(vision_config)
+ mit_config.hidden_size = vision_config.mit_hidden_size
+ mit_config.intermediate_size = vision_config.mit_intermediate_size
+ mit_config.num_hidden_layers = vision_config.mit_num_hidden_layers
+ mit_config.num_attention_heads = vision_config.mit_num_attention_heads
+ self.mit = XCLIPMultiframeIntegrationTransformer(mit_config)
+ self.prompts_generator = XCLIPPromptGenerator(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def get_text_features(
+ self,
+ input_ids: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ Examples:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoTokenizer, AutoModel
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/xclip-base-patch32")
+ >>> model = AutoModel.from_pretrained("microsoft/xclip-base-patch32")
+
+ >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
+ >>> with torch.inference_mode():
+ ... text_features = model.get_text_features(**inputs)
+ ```"""
+ text_outputs: BaseModelOutputWithPooling = self.text_model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ return_dict=True,
+ **kwargs,
+ )
+ pooled_output = text_outputs.pooler_output
+ text_outputs.pooler_output = self.text_projection(pooled_output)
+
+ return text_outputs
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ pixel_values: torch.FloatTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ return_loss: bool | None = None,
+ interpolate_pos_encoding: bool = False,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | XCLIPOutput:
+ r"""
+ return_loss (`bool`, *optional*):
+ Whether or not to return the contrastive loss.
+
+ Examples:
+
+ ```python
+ >>> import av
+ >>> import torch
+ >>> import numpy as np
+
+ >>> from transformers import AutoProcessor, AutoModel
+ >>> from huggingface_hub import hf_hub_download
+
+ >>> np.random.seed(0)
+
+
+ >>> def read_video_pyav(container, indices):
+ ... '''
+ ... Decode the video with PyAV decoder.
+ ... Args:
+ ... container (`av.container.input.InputContainer`): PyAV container.
+ ... indices (`list[int]`): List of frame indices to decode.
+ ... Returns:
+ ... result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
+ ... '''
+ ... frames = []
+ ... container.seek(0)
+ ... start_index = indices[0]
+ ... end_index = indices[-1]
+ ... for i, frame in enumerate(container.decode(video=0)):
+ ... if i > end_index:
+ ... break
+ ... if i >= start_index and i in indices:
+ ... frames.append(frame)
+ ... return np.stack([x.to_ndarray(format="rgb24") for x in frames])
+
+
+ >>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
+ ... '''
+ ... Sample a given number of frame indices from the video.
+ ... Args:
+ ... clip_len (`int`): Total number of frames to sample.
+ ... frame_sample_rate (`int`): Sample every n-th frame.
+ ... seg_len (`int`): Maximum allowed index of sample's last frame.
+ ... Returns:
+ ... indices (`list[int]`): List of sampled frame indices
+ ... '''
+ ... converted_len = int(clip_len * frame_sample_rate)
+ ... end_idx = np.random.randint(converted_len, seg_len)
+ ... start_idx = end_idx - converted_len
+ ... indices = np.linspace(start_idx, end_idx, num=clip_len)
+ ... indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
+ ... return indices
+
+
+ >>> # video clip consists of 300 frames (10 seconds at 30 FPS)
+ >>> file_path = hf_hub_download(
+ ... repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
+ ... )
+ >>> container = av.open(file_path)
+
+ >>> # sample 8 frames
+ >>> indices = sample_frame_indices(clip_len=8, frame_sample_rate=1, seg_len=container.streams.video[0].frames)
+ >>> video = read_video_pyav(container, indices)
+
+ >>> processor = AutoProcessor.from_pretrained("microsoft/xclip-base-patch32")
+ >>> model = AutoModel.from_pretrained("microsoft/xclip-base-patch32")
+
+ >>> inputs = processor(
+ ... text=["playing sports", "eating spaghetti", "go shopping"],
+ ... videos=list(video),
+ ... return_tensors="pt",
+ ... padding=True,
+ ... )
+
+ >>> # forward pass
+ >>> with torch.no_grad():
+ ... outputs = model(**inputs)
+
+ >>> logits_per_video = outputs.logits_per_video # this is the video-text similarity score
+ >>> probs = logits_per_video.softmax(dim=1) # we can take the softmax to get the label probabilities
+ >>> print(probs)
+ tensor([[1.9496e-04, 9.9960e-01, 2.0825e-04]])
+ ```"""
+ batch_size, num_frames, num_channels, height, width = pixel_values.shape
+ pixel_values = pixel_values.reshape(-1, num_channels, height, width)
+
+ vision_outputs = self.vision_model(
+ pixel_values=pixel_values,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ **kwargs,
+ )
+
+ video_embeds = vision_outputs[1]
+ video_embeds = self.visual_projection(video_embeds)
+
+ cls_features = video_embeds.view(batch_size, num_frames, -1)
+
+ mit_outputs = self.mit(
+ cls_features,
+ **kwargs,
+ )
+ video_embeds = mit_outputs[1]
+
+ img_features = vision_outputs[0][:, 1:, :]
+ img_features = self.prompts_visual_layernorm(img_features)
+ img_features = img_features @ self.prompts_visual_projection
+ img_features = img_features.view(batch_size, num_frames, -1, video_embeds.shape[-1])
+ img_features = img_features.mean(dim=1, keepdim=False)
+
+ text_outputs = self.text_model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ **kwargs,
+ )
+
+ text_embeds = text_outputs[1]
+ text_embeds = self.text_projection(text_embeds)
+
+ text_embeds = text_embeds.unsqueeze(0).expand(batch_size, -1, -1)
+ text_embeds = text_embeds + self.prompts_generator(text_embeds, img_features)
+
+ # normalized features
+ video_embeds = video_embeds / video_embeds.norm(p=2, dim=-1, keepdim=True)
+ text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
+
+ # cosine similarity as logits
+ logit_scale = self.logit_scale.exp()
+ logits_per_video = torch.einsum("bd,bkd->bk", video_embeds, logit_scale * text_embeds)
+ logits_per_text = logits_per_video.T
+
+ loss = None
+ if return_loss:
+ loss = image_text_contrastive_loss(logits_per_text)
+
+ return XCLIPOutput(
+ loss=loss,
+ logits_per_video=logits_per_video,
+ logits_per_text=logits_per_text,
+ text_embeds=text_embeds,
+ video_embeds=video_embeds,
+ text_model_output=text_outputs,
+ vision_model_output=vision_outputs,
+ mit_output=mit_outputs,
+ )
+
+ @can_return_tuple
+ @auto_docstring
+ def get_video_features(
+ self,
+ pixel_values: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ Examples:
+
+ ```python
+ >>> import av
+ >>> import torch
+ >>> import numpy as np
+
+ >>> from transformers import AutoProcessor, AutoModel
+ >>> from huggingface_hub import hf_hub_download
+
+ >>> np.random.seed(0)
+
+
+ >>> def read_video_pyav(container, indices):
+ ... '''
+ ... Decode the video with PyAV decoder.
+ ... Args:
+ ... container (`av.container.input.InputContainer`): PyAV container.
+ ... indices (`list[int]`): List of frame indices to decode.
+ ... Returns:
+ ... result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
+ ... '''
+ ... frames = []
+ ... container.seek(0)
+ ... start_index = indices[0]
+ ... end_index = indices[-1]
+ ... for i, frame in enumerate(container.decode(video=0)):
+ ... if i > end_index:
+ ... break
+ ... if i >= start_index and i in indices:
+ ... frames.append(frame)
+ ... return np.stack([x.to_ndarray(format="rgb24") for x in frames])
+
+
+ >>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
+ ... '''
+ ... Sample a given number of frame indices from the video.
+ ... Args:
+ ... clip_len (`int`): Total number of frames to sample.
+ ... frame_sample_rate (`int`): Sample every n-th frame.
+ ... seg_len (`int`): Maximum allowed index of sample's last frame.
+ ... Returns:
+ ... indices (`list[int]`): List of sampled frame indices
+ ... '''
+ ... converted_len = int(clip_len * frame_sample_rate)
+ ... end_idx = np.random.randint(converted_len, seg_len)
+ ... start_idx = end_idx - converted_len
+ ... indices = np.linspace(start_idx, end_idx, num=clip_len)
+ ... indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
+ ... return indices
+
+
+ >>> # video clip consists of 300 frames (10 seconds at 30 FPS)
+ >>> file_path = hf_hub_download(
+ ... repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
+ ... )
+ >>> container = av.open(file_path)
+
+ >>> # sample 8 frames
+ >>> indices = sample_frame_indices(clip_len=8, frame_sample_rate=1, seg_len=container.streams.video[0].frames)
+ >>> video = read_video_pyav(container, indices)
+
+ >>> processor = AutoProcessor.from_pretrained("microsoft/xclip-base-patch32")
+ >>> model = AutoModel.from_pretrained("microsoft/xclip-base-patch32")
+
+ >>> inputs = processor(videos=list(video), return_tensors="pt")
+
+ >>> video_features = model.get_video_features(**inputs)
+ ```"""
+ batch_size, num_frames, num_channels, height, width = pixel_values.shape
+ pixel_values = pixel_values.reshape(-1, num_channels, height, width)
+
+ video_outputs: BaseModelOutputWithPooling = self.vision_model(pixel_values=pixel_values, **kwargs)
+ video_embeds = video_outputs.pooler_output
+ video_embeds = self.visual_projection(video_embeds)
+
+ cls_features = video_embeds.view(batch_size, num_frames, -1)
+ mit_outputs: BaseModelOutputWithPooling = self.mit(cls_features, **kwargs)
+ video_outputs.pooler_output = mit_outputs.pooler_output
+
+ return video_outputs
+
+
+__all__ = ["XCLIPModel", "XCLIPPreTrainedModel", "XCLIPTextModel", "XCLIPVisionModel"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/x_clip/modular_x_clip.py b/.venv/lib/python3.12/site-packages/transformers/models/x_clip/modular_x_clip.py
new file mode 100644
index 0000000000000000000000000000000000000000..5980e8b68e07f9925d7d2408e106f842feaae457
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/x_clip/modular_x_clip.py
@@ -0,0 +1,810 @@
+# Copyright 2022 Microsoft Research and The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch X-CLIP model."""
+
+import copy
+from collections.abc import Callable
+from typing import Any
+
+import torch
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring
+from ...utils.generic import can_return_tuple
+from ...utils.output_capturing import OutputRecorder
+from ..altclip.modeling_altclip import AltCLIPEncoder, AltCLIPEncoderLayer
+from ..beit.modeling_beit import BeitDropPath
+from ..clip.modeling_clip import (
+ CLIPMLP,
+ CLIPAttention,
+ CLIPEncoder,
+ CLIPEncoderLayer,
+ CLIPModel,
+ CLIPOutput,
+ CLIPPreTrainedModel,
+ CLIPTextEmbeddings,
+ CLIPTextModel,
+ CLIPVisionEmbeddings,
+ CLIPVisionModel,
+ eager_attention_forward,
+ image_text_contrastive_loss,
+)
+from .configuration_x_clip import XCLIPConfig, XCLIPTextConfig, XCLIPVisionConfig
+
+
+class XCLIPOutput(CLIPOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
+ Contrastive loss for video-text similarity.
+ logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, video_batch_size)`):
+ The scaled dot product scores between `text_embeds` and `video_embeds`. This represents the text-video
+ similarity scores.
+ text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
+ The text embeddings obtained by applying the projection layer to the pooled output of [`XCLIPTextModel`].
+ text_model_output (`BaseModelOutputWithPooling`):
+ The output of the [`XCLIPTextModel`].
+ vision_model_output (`BaseModelOutputWithPooling`):
+ The output of the [`XCLIPVisionModel`].
+ logits_per_video (`torch.FloatTensor` of shape `(video_batch_size, text_batch_size)`):
+ The scaled dot product scores between `video_embeds` and `text_embeds`. This represents the video-text
+ similarity scores.
+ video_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
+ The video embeddings obtained by applying the projection layer to the pooled output of
+ [`XCLIPVisionModel`].
+ mit_output (`BaseModelOutputWithPooling`):
+ The output of `XCLIPMultiframeIntegrationTransformer` (MIT for short).
+ """
+
+ logits_per_video: torch.FloatTensor | None = None
+ video_embeds: torch.FloatTensor | None = None
+ mit_output: BaseModelOutputWithPooling = None
+ logits_per_image = AttributeError()
+ image_embeds = AttributeError()
+
+ def to_tuple(self) -> tuple[Any]:
+ return tuple(
+ self[k]
+ if k not in ["text_model_output", "vision_model_output", "mit_output"]
+ else getattr(self, k).to_tuple()
+ for k in self.keys()
+ )
+
+
+class XCLIPVisionEmbeddings(CLIPVisionEmbeddings):
+ def __init__(self, config: XCLIPVisionConfig):
+ super().__init__(config)
+
+
+class XCLIPTextEmbeddings(CLIPTextEmbeddings):
+ def __init__(self, config: XCLIPTextConfig):
+ super().__init__(config)
+
+
+class XCLIPAttention(CLIPAttention):
+ def __init__(self, config: XCLIPVisionConfig | XCLIPTextConfig):
+ super().__init__(config)
+
+
+class XCLIPMLP(CLIPMLP):
+ def __init__(self, config: XCLIPVisionConfig | XCLIPTextConfig):
+ super().__init__(config)
+
+
+class XCLIPEncoderLayer(AltCLIPEncoderLayer):
+ def __init__(self, config: XCLIPVisionConfig):
+ super().__init__()
+ self.self_attn = XCLIPAttention(config)
+ self.mlp = XCLIPMLP(config)
+
+
+class XCLIPDropPath(BeitDropPath):
+ pass
+
+
+class XCLIPVisionEncoderLayer(CLIPEncoderLayer):
+ """
+ This corresponds to the `CrossFramelAttentionBlock` class in the original implementation.
+ """
+
+ def __init__(self, config: XCLIPConfig):
+ super().__init__()
+ self.self_attn = XCLIPAttention(config)
+ self.mlp = XCLIPMLP(config)
+ self.num_frames = config.num_frames
+ self.message_fc = nn.Linear(self.embed_dim, self.embed_dim)
+ self.message_ln = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
+ self.message_attn = XCLIPAttention(config)
+ self.drop_path = XCLIPDropPath(config.drop_path_rate) if config.drop_path_rate > 0.0 else nn.Identity()
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.FloatTensor, torch.Tensor | None]:
+ batch_time, seq_length, hidden_size = hidden_states.size()
+ batch_size = batch_time // self.num_frames
+ msg_token = self.message_fc(hidden_states[:, 0, :])
+ msg_token = msg_token.view(batch_size, self.num_frames, hidden_size)
+
+ msg_token = msg_token + self.drop_path(self.message_attn(self.message_ln(msg_token), **kwargs)[0])
+ # add dummy sequence dimension
+ msg_token = msg_token.view(-1, 1, hidden_size)
+
+ hidden_states = torch.cat([hidden_states, msg_token], dim=1)
+
+ residual = hidden_states
+
+ hidden_states = self.layer_norm1(hidden_states)
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ hidden_states = hidden_states[:, :seq_length, :]
+
+ residual = hidden_states
+ hidden_states = self.layer_norm2(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+
+ return hidden_states
+
+
+@auto_docstring
+class XCLIPPreTrainedModel(CLIPPreTrainedModel):
+ config: XCLIPConfig
+ base_model_prefix = "x_clip"
+ _no_split_modules = [
+ "XCLIPTextEmbeddings",
+ "XCLIPEncoderLayer",
+ "XCLIPVisionEmbeddings",
+ "XCLIPVisionEncoderLayer",
+ ]
+ _can_record_outputs = {
+ "hidden_states": [XCLIPEncoderLayer, XCLIPVisionEncoderLayer],
+ "attentions": OutputRecorder(XCLIPAttention, layer_name="self_attn", index=1),
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ factor = self.config.initializer_factor
+ if isinstance(module, XCLIPTextEmbeddings):
+ init.normal_(module.token_embedding.weight, mean=0.0, std=factor * 0.02)
+ init.normal_(module.position_embedding.weight, mean=0.0, std=factor * 0.02)
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
+ elif isinstance(module, XCLIPVisionEmbeddings):
+ init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor)
+ init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor)
+ init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor)
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
+ elif isinstance(module, XCLIPAttention):
+ in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
+ out_proj_std = (module.embed_dim**-0.5) * factor
+ init.normal_(module.q_proj.weight, std=in_proj_std)
+ init.normal_(module.k_proj.weight, std=in_proj_std)
+ init.normal_(module.v_proj.weight, std=in_proj_std)
+ init.normal_(module.out_proj.weight, std=out_proj_std)
+ elif isinstance(module, XCLIPMLP):
+ in_proj_std = (module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
+ fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
+ init.normal_(module.fc1.weight, std=fc_std)
+ init.normal_(module.fc2.weight, std=in_proj_std)
+ elif isinstance(module, XCLIPModel):
+ init.normal_(
+ module.text_projection.weight,
+ std=module.text_embed_dim**-0.5 * factor,
+ )
+ init.normal_(
+ module.visual_projection.weight,
+ std=module.vision_embed_dim**-0.5 * factor,
+ )
+ init.normal_(module.prompts_visual_projection, mean=0.0, std=module.vision_embed_dim**-0.5 * factor)
+ elif isinstance(module, XCLIPMultiframeIntegrationTransformer):
+ init.normal_(module.position_embedding, std=factor)
+
+ if isinstance(module, nn.LayerNorm):
+ init.zeros_(module.bias)
+ init.ones_(module.weight)
+ if isinstance(module, nn.Linear):
+ init.normal_(module.weight, mean=0.0, std=factor)
+ if module.bias is not None:
+ init.zeros_(module.bias)
+
+
+class XCLIPEncoder(AltCLIPEncoder):
+ def __init__(self, config: XCLIPConfig):
+ super().__init__()
+ self.layers = nn.ModuleList([XCLIPEncoderLayer(config) for _ in range(config.num_hidden_layers)])
+
+
+class XCLIPVisionEncoder(CLIPEncoder):
+ def __init__(self, config: XCLIPVisionConfig):
+ super().__init__()
+ self.layers = nn.ModuleList([XCLIPVisionEncoderLayer(config) for _ in range(config.num_hidden_layers)])
+
+
+class XCLIPTextModel(CLIPTextModel, XCLIPPreTrainedModel):
+ config: XCLIPTextConfig
+
+ def __init__(self, config: XCLIPTextConfig):
+ super().__init__(config)
+ self.embeddings = XCLIPTextEmbeddings(config)
+ self.encoder = XCLIPEncoder(config)
+ self.eos_token_id = 2 # Force legacy behaviour
+
+ def forward(self, **super_kwargs) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, XCLIPTextModel
+
+ >>> model = XCLIPTextModel.from_pretrained("microsoft/xclip-base-patch32")
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/xclip-base-patch32")
+
+ >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
+
+ >>> outputs = model(**inputs)
+ >>> last_hidden_state = outputs.last_hidden_state
+ >>> pooled_output = outputs.pooler_output # pooled (EOS token) states
+ ```"""
+ return super().forward(**super_kwargs)
+
+
+class XCLIPVisionModel(CLIPVisionModel, XCLIPPreTrainedModel):
+ config: XCLIPVisionConfig
+
+ def __init__(self, config: XCLIPVisionConfig):
+ super().__init__(config)
+ # TODO: fix typos across all models and add in conversion mapping
+ del self.pre_layrnorm
+ embed_dim = config.hidden_size
+
+ self.embeddings = XCLIPVisionEmbeddings(config)
+ self.pre_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+ self.encoder = XCLIPVisionEncoder(config)
+
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor | None,
+ interpolate_pos_encoding: bool | None = False,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ Examples:
+
+ ```python
+ >>> import av
+ >>> import torch
+ >>> import numpy as np
+
+ >>> from transformers import AutoProcessor, XCLIPVisionModel
+ >>> from huggingface_hub import hf_hub_download
+
+ >>> np.random.seed(0)
+
+
+ >>> def read_video_pyav(container, indices):
+ ... '''
+ ... Decode the video with PyAV decoder.
+ ... Args:
+ ... container (`av.container.input.InputContainer`): PyAV container.
+ ... indices (`list[int]`): List of frame indices to decode.
+ ... Returns:
+ ... result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
+ ... '''
+ ... frames = []
+ ... container.seek(0)
+ ... start_index = indices[0]
+ ... end_index = indices[-1]
+ ... for i, frame in enumerate(container.decode(video=0)):
+ ... if i > end_index:
+ ... break
+ ... if i >= start_index and i in indices:
+ ... frames.append(frame)
+ ... return np.stack([x.to_ndarray(format="rgb24") for x in frames])
+
+
+ >>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
+ ... '''
+ ... Sample a given number of frame indices from the video.
+ ... Args:
+ ... clip_len (`int`): Total number of frames to sample.
+ ... frame_sample_rate (`int`): Sample every n-th frame.
+ ... seg_len (`int`): Maximum allowed index of sample's last frame.
+ ... Returns:
+ ... indices (`list[int]`): List of sampled frame indices
+ ... '''
+ ... converted_len = int(clip_len * frame_sample_rate)
+ ... end_idx = np.random.randint(converted_len, seg_len)
+ ... start_idx = end_idx - converted_len
+ ... indices = np.linspace(start_idx, end_idx, num=clip_len)
+ ... indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
+ ... return indices
+
+
+ >>> # video clip consists of 300 frames (10 seconds at 30 FPS)
+ >>> file_path = hf_hub_download(
+ ... repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
+ ... )
+ >>> container = av.open(file_path)
+
+ >>> # sample 16 frames
+ >>> indices = sample_frame_indices(clip_len=8, frame_sample_rate=1, seg_len=container.streams.video[0].frames)
+ >>> video = read_video_pyav(container, indices)
+
+ >>> processor = AutoProcessor.from_pretrained("microsoft/xclip-base-patch32")
+ >>> model = XCLIPVisionModel.from_pretrained("microsoft/xclip-base-patch32")
+
+ >>> pixel_values = processor(videos=list(video), return_tensors="pt").pixel_values
+
+ >>> batch_size, num_frames, num_channels, height, width = pixel_values.shape
+ >>> pixel_values = pixel_values.reshape(-1, num_channels, height, width)
+
+ >>> outputs = model(pixel_values)
+ >>> last_hidden_state = outputs.last_hidden_state
+ ```"""
+ hidden_states = self.embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
+ hidden_states = self.pre_layernorm(hidden_states)
+
+ encoder_outputs: BaseModelOutput = self.encoder(
+ inputs_embeds=hidden_states,
+ **kwargs,
+ )
+
+ last_hidden_state = encoder_outputs.last_hidden_state
+ pooled_output = last_hidden_state[:, 0, :]
+ pooled_output = self.post_layernorm(pooled_output)
+
+ return BaseModelOutputWithPooling(
+ last_hidden_state=last_hidden_state,
+ pooler_output=pooled_output,
+ )
+
+
+class XCLIPMultiframeIntegrationTransformer(nn.Module):
+ """
+ This corresponds to the `MultiframeIntegrationTransformer` class in the original implementation.
+ """
+
+ def __init__(self, config: XCLIPVisionConfig):
+ super().__init__()
+
+ self.position_embedding = nn.Parameter(torch.empty(1, config.num_frames, config.hidden_size))
+ self.encoder = XCLIPEncoder(config)
+
+ def forward(
+ self,
+ hidden_states,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutput:
+ residual = hidden_states
+
+ # add position embeddings
+ hidden_states = hidden_states + self.position_embedding
+
+ encoder_outputs = self.encoder(
+ inputs_embeds=hidden_states,
+ **kwargs,
+ )
+ last_hidden_state = encoder_outputs[0]
+
+ last_hidden_state = last_hidden_state.type(hidden_states.dtype) + residual
+
+ pooled_output = last_hidden_state.mean(dim=1, keepdim=False)
+
+ return BaseModelOutputWithPooling(
+ last_hidden_state=last_hidden_state,
+ pooler_output=pooled_output,
+ )
+
+
+class XCLIPCrossAttention(CLIPAttention):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config):
+ super().__init__()
+ del self.dropout
+ del self.out_proj
+
+ self.num_heads = config.prompt_num_attention_heads
+ self.embed_dim = config.projection_dim
+
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, False)
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, False)
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, False)
+
+ self.attn_drop = config.prompt_attention_dropout
+ self.proj = nn.Linear(self.embed_dim, self.embed_dim)
+ self.proj_drop = nn.Dropout(config.prompt_projection_dropout)
+
+ def forward(
+ self,
+ queries: torch.Tensor,
+ keys: torch.Tensor,
+ values: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
+ """Input shape: Batch x Time x Channel"""
+ batch_size, query_seq_len, hidden_size = queries.shape
+ batch_size, key_seq_len, hidden_size = keys.shape
+
+ query_shape = (batch_size, query_seq_len, -1, self.head_dim)
+ key_shape = (batch_size, key_seq_len, -1, self.head_dim)
+
+ queries = self.q_proj(queries).view(*query_shape).transpose(1, 2)
+ keys = self.k_proj(keys).view(*key_shape).transpose(1, 2)
+ values = self.v_proj(values).view(*key_shape).transpose(1, 2)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ queries,
+ keys,
+ values,
+ attention_mask=None,
+ scaling=self.scale,
+ dropout=0.0 if not self.training else self.attn_drop,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(batch_size, query_seq_len, -1).contiguous()
+ attn_output = self.proj(attn_output)
+ attn_output = self.proj_drop(attn_output)
+
+ return attn_output
+
+
+class PromptGeneratorLayer(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+
+ embed_dim = config.projection_dim
+ self.cross_attn = XCLIPCrossAttention(config)
+ self.norm1 = nn.LayerNorm(embed_dim, eps=config.text_config.layer_norm_eps)
+ self.norm3 = nn.LayerNorm(embed_dim, eps=config.text_config.layer_norm_eps)
+ self.mlp = nn.Sequential(
+ nn.Linear(embed_dim, embed_dim * 4),
+ ACT2FN[config.prompt_hidden_act],
+ nn.Dropout(config.prompt_attention_dropout),
+ nn.Linear(embed_dim * 4, embed_dim),
+ )
+
+ def forward(self, hidden_states, visual):
+ hidden_states = hidden_states + self.cross_attn(self.norm1(hidden_states), visual, visual)
+ hidden_states = hidden_states + self.mlp(self.norm3(hidden_states))
+ return hidden_states
+
+
+class XCLIPPromptGenerator(nn.Module):
+ """This corresponds to the `VideoSpecificPrompt` class in the original implementation."""
+
+ def __init__(self, config):
+ super().__init__()
+ embed_dim = config.projection_dim
+ self.layernorm = nn.LayerNorm(embed_dim, eps=config.vision_config.layer_norm_eps)
+ self.decoder = nn.ModuleList([PromptGeneratorLayer(config) for _ in range(config.prompt_layers)])
+ self.alpha = nn.Parameter(torch.ones(embed_dim) * config.prompt_alpha)
+
+ def forward(self, text, visual):
+ visual = self.layernorm(visual)
+ for layer in self.decoder:
+ text = layer(text, visual)
+
+ return self.alpha * text
+
+
+class XCLIPModel(CLIPModel, XCLIPPreTrainedModel):
+ config: XCLIPConfig
+
+ def __init__(self, config: XCLIPConfig):
+ super().__init__(config)
+ vision_config = self.config.vision_config
+ text_config = self.config.text_config
+
+ self.text_model = XCLIPTextModel(text_config)
+ self.vision_model = XCLIPVisionModel(vision_config)
+
+ self.prompts_visual_layernorm = nn.LayerNorm(self.vision_embed_dim, eps=config.vision_config.layer_norm_eps)
+ self.prompts_visual_projection = nn.Parameter(torch.randn(self.vision_embed_dim, self.projection_dim))
+ mit_config = copy.copy(vision_config)
+ mit_config.hidden_size = vision_config.mit_hidden_size
+ mit_config.intermediate_size = vision_config.mit_intermediate_size
+ mit_config.num_hidden_layers = vision_config.mit_num_hidden_layers
+ mit_config.num_attention_heads = vision_config.mit_num_attention_heads
+ self.mit = XCLIPMultiframeIntegrationTransformer(mit_config)
+ self.prompts_generator = XCLIPPromptGenerator(config)
+
+ def get_text_features(self, **super_kwargs):
+ r"""
+ Examples:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoTokenizer, AutoModel
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/xclip-base-patch32")
+ >>> model = AutoModel.from_pretrained("microsoft/xclip-base-patch32")
+
+ >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
+ >>> with torch.inference_mode():
+ ... text_features = model.get_text_features(**inputs)
+ ```"""
+ return super().get_text_features(**super_kwargs)
+
+ @can_return_tuple
+ @auto_docstring
+ def get_video_features(
+ self,
+ pixel_values: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ Examples:
+
+ ```python
+ >>> import av
+ >>> import torch
+ >>> import numpy as np
+
+ >>> from transformers import AutoProcessor, AutoModel
+ >>> from huggingface_hub import hf_hub_download
+
+ >>> np.random.seed(0)
+
+
+ >>> def read_video_pyav(container, indices):
+ ... '''
+ ... Decode the video with PyAV decoder.
+ ... Args:
+ ... container (`av.container.input.InputContainer`): PyAV container.
+ ... indices (`list[int]`): List of frame indices to decode.
+ ... Returns:
+ ... result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
+ ... '''
+ ... frames = []
+ ... container.seek(0)
+ ... start_index = indices[0]
+ ... end_index = indices[-1]
+ ... for i, frame in enumerate(container.decode(video=0)):
+ ... if i > end_index:
+ ... break
+ ... if i >= start_index and i in indices:
+ ... frames.append(frame)
+ ... return np.stack([x.to_ndarray(format="rgb24") for x in frames])
+
+
+ >>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
+ ... '''
+ ... Sample a given number of frame indices from the video.
+ ... Args:
+ ... clip_len (`int`): Total number of frames to sample.
+ ... frame_sample_rate (`int`): Sample every n-th frame.
+ ... seg_len (`int`): Maximum allowed index of sample's last frame.
+ ... Returns:
+ ... indices (`list[int]`): List of sampled frame indices
+ ... '''
+ ... converted_len = int(clip_len * frame_sample_rate)
+ ... end_idx = np.random.randint(converted_len, seg_len)
+ ... start_idx = end_idx - converted_len
+ ... indices = np.linspace(start_idx, end_idx, num=clip_len)
+ ... indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
+ ... return indices
+
+
+ >>> # video clip consists of 300 frames (10 seconds at 30 FPS)
+ >>> file_path = hf_hub_download(
+ ... repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
+ ... )
+ >>> container = av.open(file_path)
+
+ >>> # sample 8 frames
+ >>> indices = sample_frame_indices(clip_len=8, frame_sample_rate=1, seg_len=container.streams.video[0].frames)
+ >>> video = read_video_pyav(container, indices)
+
+ >>> processor = AutoProcessor.from_pretrained("microsoft/xclip-base-patch32")
+ >>> model = AutoModel.from_pretrained("microsoft/xclip-base-patch32")
+
+ >>> inputs = processor(videos=list(video), return_tensors="pt")
+
+ >>> video_features = model.get_video_features(**inputs)
+ ```"""
+ batch_size, num_frames, num_channels, height, width = pixel_values.shape
+ pixel_values = pixel_values.reshape(-1, num_channels, height, width)
+
+ video_outputs: BaseModelOutputWithPooling = self.vision_model(pixel_values=pixel_values, **kwargs)
+ video_embeds = video_outputs.pooler_output
+ video_embeds = self.visual_projection(video_embeds)
+
+ cls_features = video_embeds.view(batch_size, num_frames, -1)
+ mit_outputs: BaseModelOutputWithPooling = self.mit(cls_features, **kwargs)
+ video_outputs.pooler_output = mit_outputs.pooler_output
+
+ return video_outputs
+
+ def get_image_features(self):
+ raise AttributeError("XCLIP doesn't support images")
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ pixel_values: torch.FloatTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ return_loss: bool | None = None,
+ interpolate_pos_encoding: bool = False,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | XCLIPOutput:
+ r"""
+ return_loss (`bool`, *optional*):
+ Whether or not to return the contrastive loss.
+
+ Examples:
+
+ ```python
+ >>> import av
+ >>> import torch
+ >>> import numpy as np
+
+ >>> from transformers import AutoProcessor, AutoModel
+ >>> from huggingface_hub import hf_hub_download
+
+ >>> np.random.seed(0)
+
+
+ >>> def read_video_pyav(container, indices):
+ ... '''
+ ... Decode the video with PyAV decoder.
+ ... Args:
+ ... container (`av.container.input.InputContainer`): PyAV container.
+ ... indices (`list[int]`): List of frame indices to decode.
+ ... Returns:
+ ... result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
+ ... '''
+ ... frames = []
+ ... container.seek(0)
+ ... start_index = indices[0]
+ ... end_index = indices[-1]
+ ... for i, frame in enumerate(container.decode(video=0)):
+ ... if i > end_index:
+ ... break
+ ... if i >= start_index and i in indices:
+ ... frames.append(frame)
+ ... return np.stack([x.to_ndarray(format="rgb24") for x in frames])
+
+
+ >>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
+ ... '''
+ ... Sample a given number of frame indices from the video.
+ ... Args:
+ ... clip_len (`int`): Total number of frames to sample.
+ ... frame_sample_rate (`int`): Sample every n-th frame.
+ ... seg_len (`int`): Maximum allowed index of sample's last frame.
+ ... Returns:
+ ... indices (`list[int]`): List of sampled frame indices
+ ... '''
+ ... converted_len = int(clip_len * frame_sample_rate)
+ ... end_idx = np.random.randint(converted_len, seg_len)
+ ... start_idx = end_idx - converted_len
+ ... indices = np.linspace(start_idx, end_idx, num=clip_len)
+ ... indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
+ ... return indices
+
+
+ >>> # video clip consists of 300 frames (10 seconds at 30 FPS)
+ >>> file_path = hf_hub_download(
+ ... repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
+ ... )
+ >>> container = av.open(file_path)
+
+ >>> # sample 8 frames
+ >>> indices = sample_frame_indices(clip_len=8, frame_sample_rate=1, seg_len=container.streams.video[0].frames)
+ >>> video = read_video_pyav(container, indices)
+
+ >>> processor = AutoProcessor.from_pretrained("microsoft/xclip-base-patch32")
+ >>> model = AutoModel.from_pretrained("microsoft/xclip-base-patch32")
+
+ >>> inputs = processor(
+ ... text=["playing sports", "eating spaghetti", "go shopping"],
+ ... videos=list(video),
+ ... return_tensors="pt",
+ ... padding=True,
+ ... )
+
+ >>> # forward pass
+ >>> with torch.no_grad():
+ ... outputs = model(**inputs)
+
+ >>> logits_per_video = outputs.logits_per_video # this is the video-text similarity score
+ >>> probs = logits_per_video.softmax(dim=1) # we can take the softmax to get the label probabilities
+ >>> print(probs)
+ tensor([[1.9496e-04, 9.9960e-01, 2.0825e-04]])
+ ```"""
+ batch_size, num_frames, num_channels, height, width = pixel_values.shape
+ pixel_values = pixel_values.reshape(-1, num_channels, height, width)
+
+ vision_outputs = self.vision_model(
+ pixel_values=pixel_values,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ **kwargs,
+ )
+
+ video_embeds = vision_outputs[1]
+ video_embeds = self.visual_projection(video_embeds)
+
+ cls_features = video_embeds.view(batch_size, num_frames, -1)
+
+ mit_outputs = self.mit(
+ cls_features,
+ **kwargs,
+ )
+ video_embeds = mit_outputs[1]
+
+ img_features = vision_outputs[0][:, 1:, :]
+ img_features = self.prompts_visual_layernorm(img_features)
+ img_features = img_features @ self.prompts_visual_projection
+ img_features = img_features.view(batch_size, num_frames, -1, video_embeds.shape[-1])
+ img_features = img_features.mean(dim=1, keepdim=False)
+
+ text_outputs = self.text_model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ **kwargs,
+ )
+
+ text_embeds = text_outputs[1]
+ text_embeds = self.text_projection(text_embeds)
+
+ text_embeds = text_embeds.unsqueeze(0).expand(batch_size, -1, -1)
+ text_embeds = text_embeds + self.prompts_generator(text_embeds, img_features)
+
+ # normalized features
+ video_embeds = video_embeds / video_embeds.norm(p=2, dim=-1, keepdim=True)
+ text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
+
+ # cosine similarity as logits
+ logit_scale = self.logit_scale.exp()
+ logits_per_video = torch.einsum("bd,bkd->bk", video_embeds, logit_scale * text_embeds)
+ logits_per_text = logits_per_video.T
+
+ loss = None
+ if return_loss:
+ loss = image_text_contrastive_loss(logits_per_text)
+
+ return XCLIPOutput(
+ loss=loss,
+ logits_per_video=logits_per_video,
+ logits_per_text=logits_per_text,
+ text_embeds=text_embeds,
+ video_embeds=video_embeds,
+ text_model_output=text_outputs,
+ vision_model_output=vision_outputs,
+ mit_output=mit_outputs,
+ )
+
+
+__all__ = ["XCLIPModel", "XCLIPPreTrainedModel", "XCLIPTextModel", "XCLIPVisionModel"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/x_clip/processing_x_clip.py b/.venv/lib/python3.12/site-packages/transformers/models/x_clip/processing_x_clip.py
new file mode 100644
index 0000000000000000000000000000000000000000..57ed01f9950653960328d43df06c7b75820f779c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/x_clip/processing_x_clip.py
@@ -0,0 +1,36 @@
+# Copyright 2022 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Image/Text processor class for XCLIP
+"""
+
+from ...processing_utils import ProcessorMixin
+from ...utils import auto_docstring
+
+
+@auto_docstring
+class XCLIPProcessor(ProcessorMixin):
+ def __init__(self, image_processor=None, tokenizer=None, **kwargs):
+ super().__init__(image_processor, tokenizer)
+ self.video_processor = self.image_processor
+
+ def __call__(self, images=None, text=None, videos=None, **kwargs):
+ # X-CLIP uses the image_processor for video frames. Map videos to images
+ # so the base class processes them through image_processor.
+ if videos is not None and images is None:
+ images = videos
+ return super().__call__(images=images, text=text, **kwargs)
+
+
+__all__ = ["XCLIPProcessor"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xcodec/__init__.py b/.venv/lib/python3.12/site-packages/transformers/models/xcodec/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..17c79e8aeeed547655d59eb8543333b0b7425319
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xcodec/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2025 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_xcodec import *
+ from .modeling_xcodec import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xcodec/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xcodec/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1833508868497dbf982e34daa677c1ab87b73444
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xcodec/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xcodec/__pycache__/configuration_xcodec.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xcodec/__pycache__/configuration_xcodec.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..255035e3d710e23e42fd87121a9e91c1ca9afd52
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xcodec/__pycache__/configuration_xcodec.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xcodec/__pycache__/modeling_xcodec.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xcodec/__pycache__/modeling_xcodec.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9b8568b76367884b4d3749eb61435232f4fd49a2
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xcodec/__pycache__/modeling_xcodec.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xcodec/configuration_xcodec.py b/.venv/lib/python3.12/site-packages/transformers/models/xcodec/configuration_xcodec.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b96089790f038e5a980492665297d1f55cbfa2c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xcodec/configuration_xcodec.py
@@ -0,0 +1,147 @@
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Xcodec model configuration"""
+
+import math
+
+import numpy as np
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+from ..auto import CONFIG_MAPPING, AutoConfig
+
+
+@auto_docstring(checkpoint="Manel/X-Codec")
+@strict
+class XcodecConfig(PreTrainedConfig):
+ r"""
+ target_bandwidths (`List[float]`, *optional*, defaults to `[0.5, 1, 1.5, 2, 4]`):
+ The range of different bandwidths (in kbps) the model can encode audio with.
+ channel_ratios (`List[float]`, *optional*, defaults to `[1, 1]`):
+ Expansion factors for the number of output channels in each semantic block.
+ strides (`List[int]`, *optional*, defaults to `[1, 1]`):
+ Strides for each semantic encoder block.
+ block_dilations (`List[int]`, *optional*, defaults to `[1, 1]`):
+ Dilation factors for the residual units in semantic blocks.
+ unit_kernel_size (`int`, *optional*, defaults to 3):
+ Kernel size inside each ResidualUnit in semantic blocks.
+ acoustic_model_config (`Union[Dict, DacConfig]`, *optional*):
+ An instance of the configuration for the acoustic (DAC) model.
+ semantic_model_config (`Union[Dict, HubertConfig, WavLMConfig]`, *optional*):
+ An instance of the configuration object for the semantic (HuBERT) model.
+
+ Example:
+
+ ```python
+ >>> from transformers import XcodecModel, XcodecConfig
+
+ >>> # Initializing configuration
+ >>> configuration = XcodecConfig()
+
+ >>> # Initializing a model (with random weights) from the configuration
+ >>> model = XcodecModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "xcodec"
+
+ sub_configs = {
+ "acoustic_model_config": AutoConfig,
+ "semantic_model_config": AutoConfig,
+ }
+
+ _default_acoustic_model_config_kwargs = {
+ "encoder_hidden_size": 64,
+ # NOTE: original DAC uses [2, 4, 8, 8] `downsampling ratios`, namely reverse of `upsampling_ratios`
+ # (not sure if intentional by Xcodec but we keep it)
+ "downsampling_ratios": [8, 5, 4, 2],
+ "decoder_hidden_size": 1024,
+ "upsampling_ratios": [8, 5, 4, 2],
+ "hidden_size": 256,
+ }
+
+ _default_semantic_model_config_kwargs = {}
+
+ target_bandwidths: list[int | float] | tuple[int | float, ...] = (0.5, 1, 1.5, 2, 4)
+ sample_rate: int = 16000
+ kernel_size: int = 3
+ channel_ratios: list[int] | tuple[int, ...] = (1, 1)
+ strides: list[int] | tuple[int, ...] = (1, 1)
+ block_dilations: list[int] | tuple[int, ...] = (1, 1)
+ unit_kernel_size: int = 3
+ codebook_size: int = 1024
+ codebook_dim: int | None = None
+ initializer_range: float = 0.02
+ acoustic_model_config: dict | PreTrainedConfig | None = None
+ semantic_model_config: dict | PreTrainedConfig | None = None
+
+ def __post_init__(self, **kwargs):
+ if self.acoustic_model_config is None:
+ self.acoustic_model_config = CONFIG_MAPPING["dac"](
+ encoder_hidden_size=64,
+ # NOTE: original DAC uses [2, 4, 8, 8] `downsampling ratios`, namely reverse of `upsampling_ratios`
+ # (not sure if intentional by Xcodec but we keep it)
+ downsampling_ratios=[8, 5, 4, 2],
+ decoder_hidden_size=1024,
+ upsampling_ratios=[8, 5, 4, 2],
+ hidden_size=256,
+ )
+ elif isinstance(self.acoustic_model_config, dict):
+ self.acoustic_model_config["model_type"] = self.acoustic_model_config.get("model_type", "dac")
+ self.acoustic_model_config = CONFIG_MAPPING[self.acoustic_model_config["model_type"]](
+ **{**self._default_acoustic_model_config_kwargs, **self.acoustic_model_config}
+ )
+
+ if self.semantic_model_config is None:
+ self.semantic_model_config = CONFIG_MAPPING["hubert"]()
+ elif isinstance(self.semantic_model_config, dict):
+ self.semantic_model_config["model_type"] = self.semantic_model_config.get("model_type", "hubert")
+ self.semantic_model_config = CONFIG_MAPPING[self.semantic_model_config["model_type"]](
+ **{**self._default_semantic_model_config_kwargs, **self.semantic_model_config}
+ )
+
+ if self.codebook_dim is None:
+ self.codebook_dim = self.acoustic_model_config.hidden_size + self.semantic_model_config.hidden_size
+
+ super().__post_init__(**kwargs)
+
+ @property
+ def frame_rate(self) -> int:
+ return math.ceil(self.sample_rate / self.hop_length)
+
+ @property
+ def semantic_hidden_size(self) -> int:
+ return self.semantic_model_config.hidden_size
+
+ @property
+ def hop_length(self) -> int:
+ return int(np.prod(self.acoustic_model_config.downsampling_ratios))
+
+ @property
+ def codebook_nbits(self) -> int:
+ return math.ceil(math.log2(self.codebook_size))
+
+ @property
+ def hidden_size(self) -> int:
+ return self.acoustic_model_config.hidden_size + self.semantic_model_config.hidden_size
+
+ @property
+ def num_quantizers(self) -> int:
+ return int(1000 * self.target_bandwidths[-1] // (self.frame_rate * self.codebook_nbits))
+
+
+__all__ = ["XcodecConfig"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xcodec/modeling_xcodec.py b/.venv/lib/python3.12/site-packages/transformers/models/xcodec/modeling_xcodec.py
new file mode 100644
index 0000000000000000000000000000000000000000..846067375310b22e4e19794c4b7bf1bd8eb66f65
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xcodec/modeling_xcodec.py
@@ -0,0 +1,623 @@
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Transformers Xcodec model."""
+
+import math
+from dataclasses import dataclass
+from functools import lru_cache
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from ... import initialization as init
+from ...audio_utils import conv1d_output_length
+from ...modeling_utils import PreTrainedAudioTokenizerBase
+from ...utils import ModelOutput, auto_docstring
+from ..auto import AutoModel
+from .configuration_xcodec import XcodecConfig
+
+
+@dataclass
+class XcodecOutput(ModelOutput):
+ """
+ Args:
+ audio_codes (`torch.LongTensor` of shape `(batch_size, num_quantizers, codes_length)`, *optional*):
+ Discrete code indices computed using `model.encode`.
+ audio_values (`torch.FloatTensor` of shape `(batch_size, channels, num_samples)`, *optional*)
+ Decoded audio values obtained using the decoder part of Xcodec.
+ """
+
+ audio_codes: torch.LongTensor | None = None
+ audio_values: torch.FloatTensor | None = None
+
+
+@dataclass
+class XcodecEncoderOutput(ModelOutput):
+ """
+ Args:
+ audio_codes (`torch.LongTensor` of shape `(batch_size, num_quantizers, codes_length)`, *optional*):
+ Discrete code indices computed using `model.encode`.
+ """
+
+ audio_codes: torch.LongTensor | None = None
+
+
+@dataclass
+class XcodecDecoderOutput(ModelOutput):
+ """
+ Args:
+ audio_values (`torch.FloatTensor` of shape `(batch_size, channels, num_samples)`, *optional*):
+ Decoded audio values obtained using the decoder part of Xcodec.
+ """
+
+ audio_values: torch.FloatTensor | None = None
+
+
+class XcodecResidualUnit(nn.Module):
+ """Residual block for SemanticEncoder and SemanticDecoder used in Xcodec."""
+
+ def __init__(self, config: XcodecConfig, in_channels: int, out_channels: int, dilation: int):
+ super().__init__()
+ self.activation = nn.ELU()
+ padding = ((config.unit_kernel_size - 1) // 2) * dilation
+ self.conv1 = nn.Conv1d(
+ in_channels,
+ out_channels,
+ config.unit_kernel_size,
+ stride=1,
+ padding=padding,
+ dilation=dilation,
+ groups=1,
+ bias=False,
+ )
+ self.conv2 = nn.Conv1d(in_channels=out_channels, out_channels=out_channels, kernel_size=1, bias=False)
+
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ output_tensor = self.activation(hidden_state)
+ output_tensor = self.conv1(output_tensor)
+ output_tensor = self.activation(output_tensor)
+ output_tensor = self.conv2(output_tensor)
+ return hidden_state + output_tensor
+
+
+class XcodecSemanticEncoderBlock(nn.Module):
+ def __init__(self, config: XcodecConfig, in_channels: int, out_channels: int, stride: int):
+ super().__init__()
+ self.res_units = nn.ModuleList(
+ [XcodecResidualUnit(config, in_channels, in_channels, dilation) for dilation in config.block_dilations]
+ )
+
+ # special case: stride=1, do not use kernel=2
+ kernel = 3 if stride == 1 else (2 * stride)
+ padding = (kernel - 1) // 2
+ self.conv = nn.Conv1d(in_channels, out_channels, kernel_size=kernel, stride=stride, padding=padding, bias=True)
+
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ for unit in self.res_units:
+ hidden_state = unit(hidden_state)
+ hidden_state = self.conv(hidden_state)
+ return hidden_state
+
+
+class SemanticEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ if len(config.strides) != len(config.channel_ratios):
+ raise ValueError("Number of strides must match the number of channel_ratios.")
+ self.conv = nn.Conv1d(
+ config.semantic_hidden_size,
+ config.semantic_hidden_size,
+ config.kernel_size,
+ 1,
+ config.kernel_size // 2,
+ bias=False,
+ )
+
+ in_channels = config.semantic_hidden_size
+ conv_blocks = []
+ for i, stride in enumerate(config.strides):
+ out_channels = int(config.semantic_hidden_size * config.channel_ratios[i])
+ conv_blocks += [XcodecSemanticEncoderBlock(config, in_channels, out_channels, stride)]
+ in_channels = out_channels
+
+ self.conv_blocks = nn.ModuleList(conv_blocks)
+
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ hidden_state = self.conv(hidden_state)
+ for block in self.conv_blocks:
+ hidden_state = block(hidden_state)
+ return hidden_state
+
+
+class SemanticDecoderBlock(nn.Module):
+ def __init__(self, config: XcodecConfig, in_channels: int, out_channels: int, stride: int):
+ super().__init__()
+ if stride == 1:
+ self.conv = nn.Conv1d(
+ in_channels,
+ out_channels,
+ kernel_size=3,
+ stride=1,
+ padding=1,
+ bias=True,
+ )
+ else:
+ kernel_size = 2 * stride
+ padding = (stride + 1) // 2
+ output_padding = 1 if stride % 2 == 1 else 0
+ self.conv = nn.ConvTranspose1d(
+ in_channels, out_channels, kernel_size, stride, padding, output_padding, bias=False
+ )
+
+ self.res_units = nn.ModuleList(
+ [XcodecResidualUnit(config, out_channels, out_channels, dilation) for dilation in config.block_dilations]
+ )
+
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ hidden_state = self.conv(hidden_state)
+ for unit in self.res_units:
+ hidden_state = unit(hidden_state)
+ return hidden_state
+
+
+class SemanticDecoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.conv1 = nn.Conv1d(
+ in_channels=config.semantic_hidden_size,
+ out_channels=int(config.semantic_hidden_size * config.channel_ratios[0]),
+ kernel_size=config.kernel_size,
+ stride=1,
+ padding=config.kernel_size // 2,
+ bias=False,
+ )
+ conv_blocks = []
+ for i, stride in enumerate(config.strides):
+ in_channels = int(config.semantic_hidden_size * config.channel_ratios[i])
+
+ if i < (len(config.channel_ratios) - 1):
+ out_channels = int(config.semantic_hidden_size * config.channel_ratios[i + 1])
+ else:
+ out_channels = config.semantic_hidden_size
+
+ conv_blocks += [SemanticDecoderBlock(config, in_channels, out_channels, stride)]
+
+ self.conv_blocks = nn.ModuleList(conv_blocks)
+ self.conv2 = nn.Conv1d(
+ config.semantic_hidden_size,
+ config.semantic_hidden_size,
+ config.kernel_size,
+ stride=1,
+ padding=config.kernel_size // 2,
+ bias=False,
+ )
+
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ hidden_state = self.conv1(hidden_state)
+ for block in self.conv_blocks:
+ hidden_state = block(hidden_state)
+ hidden_state = self.conv2(hidden_state)
+ return hidden_state
+
+
+class XcodecEuclideanCodebook(nn.Module):
+ """Codebook with Euclidean distance."""
+
+ def __init__(self, config):
+ super().__init__()
+ embed = torch.zeros(config.codebook_size, config.codebook_dim)
+ self.codebook_size = config.codebook_size
+ self.register_buffer("inited", torch.Tensor([True]))
+ self.register_buffer("cluster_size", torch.zeros(config.codebook_size))
+ self.register_buffer("embed", embed)
+ self.register_buffer("embed_avg", embed.clone())
+
+ # Copied from transformers.models.encodec.modeling_encodec.EncodecEuclideanCodebook.quantize
+ def quantize(self, hidden_states):
+ embed = self.embed.t()
+ scaled_states = hidden_states.pow(2).sum(1, keepdim=True)
+ dist = -(scaled_states - 2 * hidden_states @ embed + embed.pow(2).sum(0, keepdim=True))
+ embed_ind = dist.max(dim=-1).indices
+ return embed_ind
+
+ def encode(self, hidden_states):
+ shape = hidden_states.shape
+ hidden_states = hidden_states.reshape((-1, shape[-1]))
+ embed_ind = self.quantize(hidden_states)
+ embed_ind = embed_ind.view(*shape[:-1])
+ return embed_ind
+
+ def decode(self, embed_ind):
+ quantized = F.embedding(embed_ind.to(self.embed.device), self.embed)
+ return quantized
+
+
+class XcodecVectorQuantization(nn.Module):
+ """
+ Vector quantization implementation. Currently supports only euclidean distance.
+ """
+
+ def __init__(self, config: XcodecConfig):
+ super().__init__()
+ self.codebook = XcodecEuclideanCodebook(config)
+
+ # Copied from transformers.models.encodec.modeling_encodec.EncodecVectorQuantization.encode
+ def encode(self, hidden_states):
+ hidden_states = hidden_states.permute(0, 2, 1)
+ embed_in = self.codebook.encode(hidden_states)
+ return embed_in
+
+ # Copied from transformers.models.encodec.modeling_encodec.EncodecVectorQuantization.decode
+ def decode(self, embed_ind):
+ quantize = self.codebook.decode(embed_ind)
+ quantize = quantize.permute(0, 2, 1)
+ return quantize
+
+
+class XcodecResidualVectorQuantization(nn.Module):
+ """
+ Residual vector quantization implementation. Follows Algorithm 1 in https://huggingface.co/papers/2107.03312
+ """
+
+ def __init__(self, config: XcodecConfig):
+ super().__init__()
+ self.quantizers = nn.ModuleList([XcodecVectorQuantization(config) for _ in range(config.num_quantizers)])
+ self.frame_rate = config.frame_rate
+ self.codebook_size = config.codebook_size
+ self.num_quantizers = config.num_quantizers
+
+ def get_bandwidth_per_quantizer(self):
+ """Return bandwidth per quantizer."""
+ return math.log2(self.codebook_size) * self.frame_rate / 1000
+
+ def get_num_quantizers_for_bandwidth(self, bandwidth=None) -> int:
+ """Return num_quantizers based on specified target bandwidth."""
+ bw_per_q = self.get_bandwidth_per_quantizer()
+ num_quantizers = self.num_quantizers
+ if bandwidth is not None and bandwidth > 0.0:
+ num_quantizers = int(max(1, math.floor(bandwidth / bw_per_q)))
+ return num_quantizers
+
+ def encode(self, embeddings: torch.Tensor, bandwidth=None) -> torch.Tensor:
+ """
+ Encode the input tensor into discrete indices using RVQ, with the number of quantizers selected based on the given bandwidth.
+ Each quantizer /codebook residually quantizes the input and returns the nearest indices in terms of Euclidian distance.
+ """
+ num_quantizers = self.get_num_quantizers_for_bandwidth(bandwidth)
+ residual = embeddings
+ all_indices = []
+ for quantizer in self.quantizers[:num_quantizers]:
+ indices = quantizer.encode(residual)
+ quantized = quantizer.decode(indices)
+ residual = residual - quantized
+ all_indices.append(indices)
+ out_indices = torch.stack(all_indices)
+ return out_indices
+
+ def decode(self, codes: torch.Tensor) -> torch.Tensor:
+ """Decode the given codes to their quantized representation."""
+ quantized_out = torch.tensor(0.0, device=codes.device)
+ for i, indices in enumerate(codes):
+ quantizer = self.quantizers[i]
+ quantized = quantizer.decode(indices)
+ quantized_out = quantized_out + quantized.to(codes.device)
+ return quantized_out
+
+
+@auto_docstring
+class XcodecPreTrainedModel(PreTrainedAudioTokenizerBase):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config_class = XcodecConfig
+ base_model_prefix = "xcodec"
+ main_input_name = "input_values"
+ input_modalities = "audio"
+ _no_split_modules = ["XcodecResidualVectorQuantization"]
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstance(module, nn.Linear):
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
+ if module.bias is not None:
+ init.zeros_(module.bias)
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
+ init.zeros_(module.bias)
+ init.ones_(module.weight)
+ elif isinstance(module, nn.Conv1d):
+ init.kaiming_normal_(module.weight)
+ if module.bias is not None:
+ k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
+ init.uniform_(module.bias, a=-k, b=k)
+ elif module.__class__.__name__ == "Snake1d":
+ init.ones_(module.alpha)
+ elif isinstance(module, nn.ConvTranspose1d):
+ module.reset_parameters()
+ elif isinstance(module, nn.Embedding):
+ init.normal_(module.weight, mean=0.0, std=0.02)
+ elif isinstance(module, XcodecModel):
+ # The conv1d are not handled correctly, as `self.acoustic_encoder/decoder` are initialized from a PreTrainedModel,
+ # but then only the submodules are used (which are not PreTrainedModels...) -> here we reinit them as in DacModel
+ for submodule in module.acoustic_encoder.modules():
+ if isinstance(submodule, nn.Conv1d):
+ init.trunc_normal_(submodule.weight, std=0.02)
+ init.constant_(submodule.bias, 0)
+ for submodule in module.acoustic_decoder.modules():
+ if isinstance(submodule, nn.Conv1d):
+ init.trunc_normal_(submodule.weight, std=0.02)
+ init.constant_(submodule.bias, 0)
+ elif isinstance(module, XcodecEuclideanCodebook):
+ init.copy_(module.inited, torch.Tensor([True]))
+ init.zeros_(module.cluster_size)
+ init.zeros_(module.embed)
+ init.zeros_(module.embed_avg)
+
+ def apply_weight_norm(self):
+ """Apply weight norm in the acoustic encoder and decoder because the original checkpoint has weight norm applied."""
+ weight_norm = torch.nn.utils.parametrizations.weight_norm
+
+ weight_norm(self.acoustic_encoder.conv1)
+ weight_norm(self.acoustic_encoder.conv2)
+
+ for block in self.acoustic_encoder.block:
+ weight_norm(block.conv1)
+ for res_unit in (block.res_unit1, block.res_unit2, block.res_unit3):
+ weight_norm(res_unit.conv1)
+ weight_norm(res_unit.conv2)
+
+ weight_norm(self.acoustic_decoder.conv1, name="weight")
+ weight_norm(self.acoustic_decoder.conv2, name="weight")
+
+ for block in self.acoustic_decoder.block:
+ weight_norm(block.conv_t1, name="weight")
+ for res_unit in (block.res_unit1, block.res_unit2, block.res_unit3):
+ weight_norm(res_unit.conv1, name="weight")
+ weight_norm(res_unit.conv2, name="weight")
+
+ def remove_weight_norm(self):
+ """Remove the weight norm from the acoustic encoder and decoder."""
+ for module in (self.acoustic_encoder, self.acoustic_decoder):
+ for m in module.modules():
+ try:
+ torch.nn.utils.remove_weight_norm(m, name="weight")
+ except (ValueError, AttributeError):
+ pass
+ if hasattr(m, "parametrizations") and "weight" in m.parametrizations:
+ torch.nn.utils.parametrize.remove_parametrizations(m, "weight", leave_parametrized=True)
+
+ @lru_cache
+ def _get_conv1d_layers(self, module):
+ """
+ Recursively iterate to fetch all Conv1d layers.
+ """
+
+ def get_conv1d_layers_recursive(module: nn.Module):
+ params_list = []
+
+ if isinstance(module, nn.Conv1d):
+ params_list.append(module)
+
+ # Recursively check all child modules
+ for child in module.children():
+ params_list.extend(get_conv1d_layers_recursive(child))
+
+ return params_list
+
+ return tuple(get_conv1d_layers_recursive(module))
+
+ def _get_conv1d_output_lengths(self, input_length, module=None):
+ """
+ For a given module, compute the output length that would be obtained after all Conv1d layers.
+ """
+ if module is None:
+ module = self
+
+ conv1d_layers = self._get_conv1d_layers(module)
+
+ for layer in conv1d_layers:
+ input_length = conv1d_output_length(layer, input_length)
+
+ return input_length
+
+
+@auto_docstring(custom_intro="""The Xcodec neural audio codec model.""")
+class XcodecModel(XcodecPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.config = config
+ self.pad = config.hop_length // 2
+ acoustic_model = AutoModel.from_config(config.acoustic_model_config)
+ self.acoustic_encoder = acoustic_model.encoder
+ self.acoustic_decoder = acoustic_model.decoder
+ self._adjust_dac_decoder(self.acoustic_decoder)
+ self.encoder_semantic = SemanticEncoder(config)
+ self.decoder_semantic = SemanticDecoder(config)
+ self.semantic_model = AutoModel.from_config(config.semantic_model_config).eval()
+ self.fc = nn.Linear(config.hidden_size, config.hidden_size)
+ self.fc1 = nn.Linear(config.hidden_size, config.semantic_model_config.hidden_size)
+ self.fc2 = nn.Linear(config.hidden_size, config.acoustic_model_config.hidden_size)
+ self.quantizer = XcodecResidualVectorQuantization(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @staticmethod
+ def _adjust_dac_decoder(decoder: nn.Module):
+ r"""
+ DAC implemented in Xcodec is slightly different from the HF version.
+ DAC in Xcodec adjusts the output padding in every ConvTranspose1d in the decoder and removes
+ the final `nn.Tanh` activation function.
+ """
+ for module in decoder.modules():
+ if isinstance(module, nn.ConvTranspose1d):
+ stride = module.stride[0] if isinstance(module.stride, tuple) else module.stride
+ module.output_padding = (stride % 2,)
+ if hasattr(decoder, "tanh") and isinstance(decoder.tanh, nn.Tanh):
+ decoder.tanh = nn.Identity()
+
+ def _extract_semantic_features(self, input_values: torch.FloatTensor) -> torch.FloatTensor:
+ input_values = input_values[:, 0, :]
+ input_values = F.pad(input_values, (self.pad, self.pad))
+ with torch.no_grad():
+ outputs = self.semantic_model(input_values, output_hidden_states=True)
+ hidden_states = outputs.hidden_states
+
+ stacked = torch.stack(hidden_states, dim=1)
+ return stacked.mean(dim=1)
+
+ @auto_docstring
+ def encode(
+ self,
+ input_values: torch.Tensor,
+ bandwidth: float | None = None,
+ return_dict: bool | None = None,
+ ) -> torch.Tensor | XcodecEncoderOutput:
+ r"""
+ input_values (`torch.FloatTensor` of shape `(batch_size, channels, num_samples)`):
+ Float values of the input audio waveform.
+ bandwidth (`float`, *optional*):
+ The target bandwidth in (kbps) supports only values in `config.target_bandwidths`.
+ Defaults to the highest available bandwidth `4.0` kbps.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`].
+
+ Returns:
+ `torch.LongTensor` of shape `(batch_size, num_quantizers, codes_length)` containing the discrete encoded audio codes.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ channels = input_values.shape[1]
+ if channels != 1:
+ raise ValueError(f"Audio must be mono, but got {channels}")
+
+ if bandwidth is None:
+ bandwidth = self.config.target_bandwidths[-1]
+ elif bandwidth not in self.config.target_bandwidths:
+ raise ValueError(
+ f"This model doesn't support the bandwidth {bandwidth}. Select one of {self.config.target_bandwidths}."
+ )
+
+ e_semantic_input = self._extract_semantic_features(input_values).detach()
+ e_semantic = self.encoder_semantic(e_semantic_input.transpose(1, 2))
+
+ # original codebase infer to get the output length, but we can directly infer it
+ # from the model and know whether we should pad
+ if self._get_conv1d_output_lengths(input_values.shape[2], self.acoustic_encoder) != e_semantic.shape[2]:
+ e_acoustic = self.acoustic_encoder(F.pad(input_values, (self.pad, self.pad)))
+ else:
+ e_acoustic = self.acoustic_encoder(input_values)
+
+ embeddings = torch.cat([e_acoustic.to(e_semantic.device), e_semantic], dim=1)
+ embeddings = self.fc(embeddings.transpose(1, 2)).transpose(1, 2)
+ audio_codes = self.quantizer.encode(embeddings, bandwidth)
+ audio_codes = audio_codes.transpose(0, 1)
+
+ if not return_dict:
+ return audio_codes
+
+ return XcodecEncoderOutput(audio_codes)
+
+ @auto_docstring
+ def decode(
+ self,
+ audio_codes: torch.Tensor,
+ return_dict: bool | None = None,
+ ) -> torch.Tensor | XcodecDecoderOutput:
+ r"""
+ audio_codes (`torch.LongTensor` of shape `(batch_size, num_quantizers, codes_length)`):
+ Discrete code indices computed using `model.encode`.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`]
+
+ Returns:
+ Decoded audio values of shape `(batch_size, channels, num_samples)` obtained using the decoder part of
+ Xcodec.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ audio_codes = audio_codes.transpose(0, 1)
+ quantized = self.quantizer.decode(audio_codes)
+ quantized_acoustic = self.fc2(quantized.transpose(1, 2)).transpose(1, 2)
+ audio_values = self.acoustic_decoder(quantized_acoustic)
+
+ if not return_dict:
+ return audio_values
+
+ return XcodecDecoderOutput(audio_values)
+
+ @auto_docstring
+ def forward(
+ self,
+ input_values: torch.Tensor,
+ audio_codes: torch.Tensor | None = None,
+ bandwidth: float | None = None,
+ return_dict: bool | None = None,
+ ) -> tuple[torch.Tensor, torch.Tensor] | XcodecOutput:
+ r"""
+ input_values (`torch.FloatTensor` of shape `(batch_size, channels, num_samples)`):
+ The raw float values of the input audio waveform.
+ audio_codes (`torch.LongTensor` of shape `(batch_size, num_quantizers, codes_length)`:
+ Discrete code indices computed using `model.encode`.
+ bandwidth (`float`, *optional*):
+ Target bandwidth in kbps. Must be one of `config.target_bandwidths`. Defaults to the highest available bandwidth.
+ bandwidth (`float`, *optional*):
+ Target bandwidth in kbps. Must be one of `config.target_bandwidths`. Defaults to the highest available bandwidth.
+ return_dict (`bool`, *optional*):
+ Whether to return a [`XcodecOutput`] instead of a plain tuple.
+
+ Returns:
+ `XcodecOutput` or tuple `(audio_codes, audio_values)`:
+ - `audio_codes` of shape `(batch_size, num_quantizers, codes_length)`: the quantized discrete codes.
+ - `audio_values` of shape `(batch_size, channels, num_samples)`: the reconstructed audio waveform given the codes.
+
+ Example:
+
+ ```python
+ >>> from datasets import load_dataset
+ >>> from transformers import AutoFeatureExtractor, XcodecModel
+
+ >>> model_id = "hf-audio/xcodec-hubert-librispeech"
+ >>> model = XcodecModel.from_pretrained(model_id)
+ >>> feature_extractor = AutoFeatureExtractor.from_pretrained(model_id)
+
+ >>> dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
+ >>> dataset = dataset.cast_column("audio", Audio(sampling_rate=feature_extractor.sampling_rate))
+ >>> audio_sample = dataset[0]['audio']['array']
+
+ >>> inputs = feature_extractor(raw_audio=audio_sample, return_tensors="pt")
+
+ >>> outputs = model(**inputs)
+ >>> audio_codes = outputs.audio_codes
+ >>> audio_values = outputs.audio_values
+ ```
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ length = input_values.shape[-1]
+
+ if audio_codes is None:
+ audio_codes = self.encode(input_values, bandwidth, return_dict=False)
+
+ audio_values = self.decode(audio_codes, return_dict=return_dict)[0][..., :length]
+
+ if not return_dict:
+ return (audio_codes, audio_values)
+
+ return XcodecOutput(audio_codes=audio_codes, audio_values=audio_values)
+
+
+__all__ = ["XcodecModel", "XcodecPreTrainedModel"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xglm/__init__.py b/.venv/lib/python3.12/site-packages/transformers/models/xglm/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..33e620386f469fc4f97bd52697254d69b8c54f3a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xglm/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_xglm import *
+ from .modeling_xglm import *
+ from .tokenization_xglm import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xglm/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xglm/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d585d90bde4d6e0a2b419d85025f2d1c1676d4c3
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xglm/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xglm/__pycache__/configuration_xglm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xglm/__pycache__/configuration_xglm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..46fca45e79591e69560db2591676a81d77ceb710
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xglm/__pycache__/configuration_xglm.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xglm/__pycache__/modeling_xglm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xglm/__pycache__/modeling_xglm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e3eacd878c197655dbf906e673e56ca6a369aa0d
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xglm/__pycache__/modeling_xglm.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xglm/__pycache__/tokenization_xglm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xglm/__pycache__/tokenization_xglm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0e0363a03f6f83b0812260d6ea6e9ef2354d3ee7
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xglm/__pycache__/tokenization_xglm.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xglm/configuration_xglm.py b/.venv/lib/python3.12/site-packages/transformers/models/xglm/configuration_xglm.py
new file mode 100644
index 0000000000000000000000000000000000000000..2cff0d226003bba8e894b1915dd590a8a89fe639
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xglm/configuration_xglm.py
@@ -0,0 +1,72 @@
+# Copyright The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""XGLM model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="facebook/xglm-564M")
+@strict
+class XGLMConfig(PreTrainedConfig):
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import XGLMModel, XGLMConfig
+
+ >>> # Initializing a XGLM facebook/xglm-564M style configuration
+ >>> configuration = XGLMConfig()
+
+ >>> # Initializing a model from the facebook/xglm-564M style configuration
+ >>> model = XGLMModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "xglm"
+ keys_to_ignore_at_inference = ["past_key_values"]
+
+ attribute_map = {
+ "num_attention_heads": "attention_heads",
+ "hidden_size": "d_model",
+ "num_hidden_layers": "num_layers",
+ }
+
+ vocab_size: int = 256008
+ max_position_embeddings: int = 2048
+ d_model: int = 1024
+ ffn_dim: int = 4096
+ num_layers: int = 24
+ attention_heads: int = 16
+ activation_function: str = "gelu"
+ dropout: float | int = 0.1
+ attention_dropout: float | int = 0.1
+ activation_dropout: float | int = 0.0
+ layerdrop: float | int = 0.0
+ init_std: float = 0.02
+ scale_embedding: bool = True
+ use_cache: bool = True
+ decoder_start_token_id: int = 2
+ pad_token_id: int | None = 1
+ bos_token_id: int | None = 0
+ eos_token_id: int | list[int] | None = 2
+ add_cross_attention: bool = False
+ tie_word_embeddings: bool = True
+
+
+__all__ = ["XGLMConfig"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xglm/modeling_xglm.py b/.venv/lib/python3.12/site-packages/transformers/models/xglm/modeling_xglm.py
new file mode 100644
index 0000000000000000000000000000000000000000..48f75a3436e5e98c1e2ee6e04b4c56c7df90542f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xglm/modeling_xglm.py
@@ -0,0 +1,577 @@
+# Copyright 2021 The Fairseq Authors The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch XGLM model."""
+
+import math
+
+import torch
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
+from ...generation import GenerationMixin
+from ...masking_utils import create_bidirectional_mask, create_causal_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutputWithPastAndCrossAttentions, CausalLMOutputWithCrossAttentions
+from ...modeling_utils import PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, logging
+from ...utils.generic import merge_with_config_defaults
+from ...utils.output_capturing import OutputRecorder, capture_outputs
+from .configuration_xglm import XGLMConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+# Copied from transformers.models.bart.modeling_bart.BartScaledWordEmbedding with Bart->XGLM
+class XGLMScaledWordEmbedding(nn.Embedding):
+ """
+ This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
+ """
+
+ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: float | None = 1.0):
+ super().__init__(num_embeddings, embedding_dim, padding_idx)
+ self.embed_scale = embed_scale
+
+ def forward(self, input_ids: torch.Tensor):
+ return super().forward(input_ids) * self.embed_scale
+
+
+class XGLMSinusoidalPositionalEmbedding(nn.Module):
+ """This module produces sinusoidal positional embeddings of any length."""
+
+ def __init__(self, num_positions: int, embedding_dim: int, padding_idx: int | None = None):
+ super().__init__()
+ self.offset = 2
+ self.num_positions = num_positions
+ self.embedding_dim = embedding_dim
+ self.padding_idx = padding_idx
+ self.make_weights(num_positions + self.offset, embedding_dim, padding_idx)
+
+ def make_weights(self, num_embeddings: int, embedding_dim: int, padding_idx: int | None = None):
+ emb_weights = self.get_embedding(num_embeddings, embedding_dim, padding_idx)
+ if hasattr(self, "weights"):
+ # in forward put the weights on the correct dtype and device of the param
+ emb_weights = emb_weights.to(dtype=self.weights.dtype, device=self.weights.device)
+
+ self.register_buffer("weights", emb_weights, persistent=False)
+
+ @staticmethod
+ def get_embedding(num_embeddings: int, embedding_dim: int, padding_idx: int | None = None):
+ """
+ Build sinusoidal embeddings.
+
+ This matches the implementation in tensor2tensor, but differs slightly from the description in Section 3.5 of
+ "Attention Is All You Need".
+ """
+ half_dim = embedding_dim // 2
+ emb = math.log(10000) / (half_dim - 1)
+ emb = torch.exp(torch.arange(half_dim, dtype=torch.int64).float() * -emb)
+ emb = torch.arange(num_embeddings, dtype=torch.int64).float().unsqueeze(1) * emb.unsqueeze(0)
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1)
+ if embedding_dim % 2 == 1:
+ # zero pad
+ emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1)
+ if padding_idx is not None:
+ emb[padding_idx, :] = 0
+
+ return emb.to(torch.get_default_dtype())
+
+ @torch.no_grad()
+ def forward(self, position_ids: torch.Tensor | None = None, past_key_values_length: int = 0):
+ bsz, seq_len = position_ids.size()
+ position_ids = position_ids + self.offset
+
+ max_pos = 2 + seq_len + past_key_values_length
+ if max_pos > self.weights.size(0):
+ self.make_weights(max_pos, self.embedding_dim, self.padding_idx)
+
+ return self.weights.index_select(0, position_ids.view(-1)).view(bsz, seq_len, self.weights.shape[-1]).detach()
+
+
+class XGLMAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(
+ self,
+ embed_dim: int,
+ num_heads: int,
+ dropout: float | None = 0.0,
+ is_decoder: bool | None = False,
+ bias: bool | None = True,
+ layer_idx: bool | None = None,
+ ):
+ super().__init__()
+ self.embed_dim = embed_dim
+ self.num_heads = num_heads
+ self.dropout = dropout
+ self.head_dim = embed_dim // num_heads
+
+ if (self.head_dim * num_heads) != self.embed_dim:
+ raise ValueError(
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
+ f" and `num_heads`: {num_heads})."
+ )
+ self.scaling = self.head_dim**-0.5
+ self.is_decoder = is_decoder
+ self.layer_idx = layer_idx
+
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ key_value_states: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
+ """Input shape: Batch x Time x Channel"""
+
+ # if key_value_states are provided this layer is used as a cross-attention layer
+ # for the decoder
+ is_cross_attention = key_value_states is not None
+
+ bsz, tgt_len, _ = hidden_states.size()
+ src_len = key_value_states.shape[1] if is_cross_attention else tgt_len
+
+ # get query proj
+ query_states = self.q_proj(hidden_states) * self.scaling
+
+ is_updated = False
+ if past_key_values is not None:
+ if isinstance(past_key_values, EncoderDecoderCache):
+ is_updated = past_key_values.is_updated.get(self.layer_idx)
+ if is_cross_attention:
+ # after the first generated id, we can subsequently re-use all key/value_states from cache
+ curr_past_key_values = past_key_values.cross_attention_cache
+ else:
+ curr_past_key_values = past_key_values.self_attention_cache
+ else:
+ curr_past_key_values = past_key_values
+
+ current_states = key_value_states if is_cross_attention else hidden_states
+ if is_cross_attention and past_key_values is not None and is_updated:
+ # reuse k,v, cross_attentions
+ key_states = curr_past_key_values.layers[self.layer_idx].keys
+ value_states = curr_past_key_values.layers[self.layer_idx].values
+ else:
+ key_states = self.k_proj(current_states)
+ value_states = self.v_proj(current_states)
+ key_states = key_states.view(bsz, src_len, -1, self.head_dim).transpose(1, 2)
+ value_states = value_states.view(bsz, src_len, -1, self.head_dim).transpose(1, 2)
+
+ if past_key_values is not None:
+ # save all key/value_states to cache to be re-used for fast auto-regressive generation
+ key_states, value_states = curr_past_key_values.update(key_states, value_states, self.layer_idx)
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
+ if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
+ past_key_values.is_updated[self.layer_idx] = True
+
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
+ query_states = query_states.view(bsz, tgt_len, self.num_heads, self.head_dim).transpose(1, 2)
+ query_states = query_states.reshape(*proj_shape)
+ key_states = key_states.reshape(*proj_shape)
+ value_states = value_states.reshape(*proj_shape)
+
+ src_len = key_states.size(1)
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
+
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
+ raise ValueError(
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
+ f" {attn_weights.size()}"
+ )
+
+ if attention_mask is not None:
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
+ raise ValueError(
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
+ )
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
+ attn_weights = torch.max(
+ attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min, device=attn_weights.device)
+ )
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
+
+ # upcast to fp32 if the weights are in fp16. Please see https://github.com/huggingface/transformers/pull/17437
+ if attn_weights.dtype == torch.float16:
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(torch.float16)
+ else:
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+
+ # this operation is a bit awkward, but it's required to
+ # make sure that attn_weights keeps its gradient.
+ # In order to do so, attn_weights have to be reshaped
+ # twice and have to be reused in the following
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
+
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
+
+ attn_output = torch.bmm(attn_probs, value_states)
+
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
+ raise ValueError(
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
+ f" {attn_output.size()}"
+ )
+
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
+ attn_output = attn_output.transpose(1, 2)
+
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
+ # partitioned across GPUs when using tensor-parallelism.
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
+
+ attn_output = self.out_proj(attn_output)
+
+ return attn_output, attn_weights_reshaped
+
+
+class XGLMDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: XGLMConfig, layer_idx=None):
+ super().__init__()
+ self.embed_dim = config.d_model
+
+ self.self_attn = XGLMAttention(
+ embed_dim=self.embed_dim,
+ num_heads=config.attention_heads,
+ dropout=config.attention_dropout,
+ is_decoder=True,
+ layer_idx=layer_idx,
+ )
+ self.dropout = config.dropout
+ self.activation_fn = ACT2FN[config.activation_function]
+ self.activation_dropout = config.activation_dropout
+
+ if config.add_cross_attention:
+ self.encoder_attn = XGLMAttention(
+ embed_dim=self.embed_dim,
+ num_heads=config.attention_heads,
+ dropout=config.attention_dropout,
+ is_decoder=True,
+ layer_idx=layer_idx,
+ )
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
+
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
+ self.fc1 = nn.Linear(self.embed_dim, config.ffn_dim)
+ self.fc2 = nn.Linear(config.ffn_dim, self.embed_dim)
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
+
+ # Copied from transformers.models.musicgen.modeling_musicgen.MusicgenDecoderLayer.forward
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = True,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
+ attention_mask (`torch.FloatTensor`): attention mask of size
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
+ encoder_hidden_states (`torch.FloatTensor`):
+ cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
+ past_key_values (`Cache`): cached past key and value projection states
+ """
+ residual = hidden_states
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states,
+ past_key_values=past_key_values,
+ attention_mask=attention_mask,
+ **kwargs,
+ )
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+
+ # Cross-Attention Block
+ if encoder_hidden_states is not None:
+ residual = hidden_states
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
+
+ hidden_states, _ = self.encoder_attn(
+ hidden_states,
+ key_value_states=encoder_hidden_states,
+ attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.final_layer_norm(hidden_states)
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
+ hidden_states = self.fc2(hidden_states)
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+
+ return hidden_states
+
+
+@auto_docstring
+class XGLMPreTrainedModel(PreTrainedModel):
+ config: XGLMConfig
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["XGLMDecoderLayer"]
+
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ if isinstance(module, XGLMSinusoidalPositionalEmbedding):
+ emb_weights = module.get_embedding(
+ module.num_positions + module.offset, module.embedding_dim, module.padding_idx
+ )
+ init.copy_(module.weights, emb_weights)
+
+
+@auto_docstring
+class XGLMModel(XGLMPreTrainedModel):
+ _can_record_outputs = {
+ "hidden_states": XGLMDecoderLayer,
+ "attentions": OutputRecorder(XGLMAttention, index=1, layer_name="self_attn"),
+ "cross_attentions": OutputRecorder(XGLMAttention, index=1, layer_name="encoder_attn"),
+ }
+
+ def __init__(self, config: XGLMConfig):
+ super().__init__(config)
+ self.dropout = config.dropout
+ self.layerdrop = config.layerdrop
+ self.padding_idx = config.pad_token_id
+ self.max_target_positions = config.max_position_embeddings
+ embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
+
+ self.embed_tokens = XGLMScaledWordEmbedding(
+ config.vocab_size, config.d_model, self.padding_idx, embed_scale=embed_scale
+ )
+
+ self.embed_positions = XGLMSinusoidalPositionalEmbedding(
+ config.max_position_embeddings,
+ config.d_model,
+ config.pad_token_id,
+ )
+ self.layers = nn.ModuleList([XGLMDecoderLayer(config, layer_idx=i) for i in range(config.num_layers)])
+ self.layer_norm = nn.LayerNorm(config.d_model)
+
+ self.gradient_checkpointing = False
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPastAndCrossAttentions:
+ r"""
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of
+ the decoder.
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
+ selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ """
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ # initialize `past_key_values`
+ if use_cache and past_key_values is None:
+ past_key_values = (
+ EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
+ if encoder_hidden_states is not None or self.config.is_encoder_decoder
+ else DynamicCache(config=self.config)
+ )
+
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
+
+ attention_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ )
+
+ if position_ids is None:
+ position_ids = torch.arange(
+ past_key_values_length,
+ inputs_embeds.shape[1] + past_key_values_length,
+ dtype=torch.long,
+ device=input_ids.device if input_ids is not None else inputs_embeds.device,
+ )
+ position_ids = position_ids.unsqueeze(0)
+
+ # expand encoder attention mask
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
+ encoder_attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=encoder_attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ )
+
+ hidden_states = inputs_embeds + self.embed_positions(position_ids, past_key_values_length).to(
+ inputs_embeds.device
+ )
+ hidden_states = nn.functional.dropout(hidden_states, p=float(self.dropout), training=self.training)
+
+ for idx, decoder_layer in enumerate(self.layers):
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
+ if self.training:
+ dropout_probability = torch.rand([])
+ if dropout_probability < self.layerdrop:
+ continue
+
+ hidden_states = decoder_layer(
+ hidden_states,
+ attention_mask,
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = self.layer_norm(hidden_states)
+
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ The XGLM Model transformer with a language modeling head on top (linear layer with weights tied to the input
+ embeddings).
+ """
+)
+class XGLMForCausalLM(XGLMPreTrainedModel, GenerationMixin):
+ base_model_prefix = "model"
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.model = XGLMModel(config)
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | CausalLMOutputWithCrossAttentions:
+ r"""
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of
+ the decoder.
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
+ selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+ """
+
+ outputs: BaseModelOutputWithPastAndCrossAttentions = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(
+ logits,
+ labels,
+ vocab_size=self.config.vocab_size,
+ pad_token_id=self.config.pad_token_id,
+ )
+
+ return CausalLMOutputWithCrossAttentions(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+
+__all__ = ["XGLMForCausalLM", "XGLMModel", "XGLMPreTrainedModel"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xglm/tokenization_xglm.py b/.venv/lib/python3.12/site-packages/transformers/models/xglm/tokenization_xglm.py
new file mode 100644
index 0000000000000000000000000000000000000000..d106c16ab0548efc6e93029bd1a883ce73d6ccb5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xglm/tokenization_xglm.py
@@ -0,0 +1,126 @@
+# Copyright The HuggingFace Team and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes for XGLM."""
+
+from tokenizers import Regex, Tokenizer, decoders, normalizers, pre_tokenizers, processors
+from tokenizers.models import Unigram
+
+from ...tokenization_utils_tokenizers import TokenizersBackend
+from ...utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {"tokenizer_file": "tokenizer.json"}
+
+
+class XGLMTokenizer(TokenizersBackend):
+ """
+ Construct a XGLM tokenizer (backed by HuggingFace's tokenizers library). Based on BPE.
+
+ This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should
+ refer to this superclass for more information regarding those methods.
+
+ Args:
+ tokenizer_file (`str`, *optional*):
+ Path to a tokenizers JSON file containing the serialization of a tokenizer.
+ bos_token (`str`, *optional*, defaults to `""`):
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
+ eos_token (`str`, *optional*, defaults to `""`):
+ The end of sequence token.
+ sep_token (`str`, *optional*, defaults to `""`):
+ The separator token, which is used when building a sequence from multiple sequences.
+ cls_token (`str`, *optional*, defaults to `""`):
+ The classifier token which is used when doing sequence classification.
+ unk_token (`str`, *optional*, defaults to `""`):
+ The unknown token.
+ pad_token (`str`, *optional*, defaults to `""`):
+ The token used for padding.
+ vocab (`str`, `dict` or `list`, *optional*):
+ Custom vocabulary dictionary. If not provided, a minimal vocabulary is created.
+ merges (`list[tuple[str, str]]`, *optional*):
+ Custom merge rules for BPE. If not provided, merges are generated from the vocabulary.
+ add_prefix_space (`bool`, *optional*, defaults to `True`):
+ Whether to add a prefix space before encoding.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ model_input_names = ["input_ids", "attention_mask"]
+ model = Unigram
+
+ def __init__(
+ self,
+ vocab: str | list[tuple[str, float]] | None = None,
+ bos_token: str = "",
+ eos_token: str = "",
+ sep_token: str = "",
+ cls_token: str = "",
+ unk_token: str = "",
+ pad_token: str = "",
+ add_prefix_space: bool = True,
+ **kwargs,
+ ):
+ self.num_madeup_words = 7
+ madeup_words = [f"" for i in range(self.num_madeup_words)]
+ kwargs["additional_special_tokens"] = kwargs.get("additional_special_tokens", []) or []
+ kwargs["additional_special_tokens"] += [
+ word for word in madeup_words if word not in kwargs["additional_special_tokens"]
+ ]
+
+ self.add_prefix_space = add_prefix_space
+
+ if vocab is not None:
+ self._vocab = vocab
+ else:
+ self._vocab = [
+ (str(bos_token), 0.0),
+ (str(pad_token), 0.0),
+ (str(eos_token), 0.0),
+ (str(unk_token), 0.0),
+ ]
+
+ self._tokenizer = Tokenizer(Unigram(vocab=self._vocab, unk_id=3, byte_fallback=False))
+
+ self._tokenizer.normalizer = normalizers.Sequence(
+ [
+ normalizers.Replace(Regex(r"[\n\r\t]"), " "),
+ normalizers.NFKC(),
+ normalizers.Replace(Regex(r" {2,}"), " "),
+ ]
+ )
+ prepend_scheme = "always" if add_prefix_space else "never"
+ self._tokenizer.pre_tokenizer = pre_tokenizers.Metaspace(replacement="▁", prepend_scheme=prepend_scheme)
+ self._tokenizer.decoder = decoders.Metaspace(replacement="▁", prepend_scheme=prepend_scheme)
+ super().__init__(
+ bos_token=bos_token,
+ eos_token=eos_token,
+ sep_token=sep_token,
+ cls_token=cls_token,
+ unk_token=unk_token,
+ pad_token=pad_token,
+ add_prefix_space=add_prefix_space,
+ **kwargs,
+ )
+
+ self._tokenizer.post_processor = processors.TemplateProcessing(
+ single=f"{self.eos_token} $A {self.eos_token}",
+ pair=f"{self.eos_token} $A {self.eos_token} {self.eos_token} $B {self.eos_token}",
+ special_tokens=[
+ (self.bos_token, self.bos_token_id),
+ (self.eos_token, self.eos_token_id),
+ ],
+ )
+
+
+__all__ = ["XGLMTokenizer"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlm/__init__.py b/.venv/lib/python3.12/site-packages/transformers/models/xlm/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6ad3ff9c90d9c716a750cec50e2c96a7b538bbf
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xlm/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_xlm import *
+ from .modeling_xlm import *
+ from .tokenization_xlm import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlm/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xlm/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8681f0b76e754131a03ea4aa839795e57381c60b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xlm/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlm/__pycache__/configuration_xlm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xlm/__pycache__/configuration_xlm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d965afc127a3d7a482bd92ad5494e2721b0a351f
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xlm/__pycache__/configuration_xlm.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlm/__pycache__/modeling_xlm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xlm/__pycache__/modeling_xlm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d19a153bf0af9a5f503d20a0d05292a54db8bf21
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xlm/__pycache__/modeling_xlm.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlm/__pycache__/tokenization_xlm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xlm/__pycache__/tokenization_xlm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d22503e1c0935b6328eac1c8c0b85806fac64e32
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xlm/__pycache__/tokenization_xlm.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlm/configuration_xlm.py b/.venv/lib/python3.12/site-packages/transformers/models/xlm/configuration_xlm.py
new file mode 100644
index 0000000000000000000000000000000000000000..7876692981b01cef2eb770fc3137a76af8e9693e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xlm/configuration_xlm.py
@@ -0,0 +1,139 @@
+# Copyright 2019-present, Facebook, Inc and the HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""XLM configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="FacebookAI/xlm-mlm-en-2048")
+@strict
+class XLMConfig(PreTrainedConfig):
+ r"""
+ gelu_activation (`bool`, *optional*, defaults to `True`):
+ Whether or not to use *gelu* for the activations instead of *relu*.
+ sinusoidal_embeddings (`bool`, *optional*, defaults to `False`):
+ Whether or not to use sinusoidal positional embeddings instead of absolute positional embeddings.
+ causal (`bool`, *optional*, defaults to `False`):
+ Whether or not the model should behave in a causal manner. Causal models use a triangular attention mask in
+ order to only attend to the left-side context instead if a bidirectional context.
+ asm (`bool`, *optional*, defaults to `False`):
+ Whether or not to use an adaptive log softmax projection layer instead of a linear layer for the prediction
+ layer.
+ n_langs (`int`, *optional*, defaults to 1):
+ The number of languages the model handles. Set to 1 for monolingual models.
+ use_lang_emb (`bool`, *optional*, defaults to `True`):
+ Whether to use language embeddings. Some models use additional language embeddings, see [the multilingual
+ models page](http://huggingface.co/transformers/multilingual.html#xlm-language-embeddings) for information
+ on how to use them.
+ embed_init_std (`float`, *optional*, defaults to 2048^-0.5):
+ The standard deviation of the truncated_normal_initializer for initializing the embedding matrices.
+ unk_index (`int`, *optional*, defaults to 3):
+ The index of the unknown token in the vocabulary.
+ mask_index (`int`, *optional*, defaults to 5):
+ The index of the masking token in the vocabulary.
+ is_encoder (`bool`, *optional*, defaults to `True`):
+ Whether or not the initialized model should be a transformer encoder or decoder as seen in Vaswani et al.
+ summary_type (`string`, *optional*, defaults to "first"):
+ Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.
+ Has to be one of the following options:
+ - `"last"`: Take the last token hidden state (like XLNet).
+ - `"first"`: Take the first token hidden state (like BERT).
+ - `"mean"`: Take the mean of all tokens hidden states.
+ - `"cls_index"`: Supply a Tensor of classification token position (like GPT/GPT-2).
+ - `"attn"`: Not implemented now, use multi-head attention.
+ summary_use_proj (`bool`, *optional*, defaults to `True`):
+ Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.
+ Whether or not to add a projection after the vector extraction.
+ summary_activation (`str`, *optional*):
+ Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.
+ Pass `"tanh"` for a tanh activation to the output, any other value will result in no activation.
+ summary_proj_to_labels (`bool`, *optional*, defaults to `True`):
+ Used in the sequence classification and multiple choice models.
+ Whether the projection outputs should have `config.num_labels` or `config.hidden_size` classes.
+ summary_first_dropout (`float`, *optional*, defaults to 0.1):
+ Used in the sequence classification and multiple choice models.
+ The dropout ratio to be used after the projection and activation.
+ start_n_top (`int`, *optional*, defaults to 5):
+ Used in the SQuAD evaluation script.
+ end_n_top (`int`, *optional*, defaults to 5):
+ Used in the SQuAD evaluation script.
+ mask_token_id (`int`, *optional*, defaults to 0):
+ Model agnostic parameter to identify masked tokens when generating text in an MLM context.
+ lang_id (`int`, *optional*, defaults to 1):
+ The ID of the language used by the model. This parameter is used when generating text in a given language.
+
+ Examples:
+
+ ```python
+ >>> from transformers import XLMConfig, XLMModel
+
+ >>> # Initializing a XLM configuration
+ >>> configuration = XLMConfig()
+
+ >>> # Initializing a model (with random weights) from the configuration
+ >>> model = XLMModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "xlm"
+ attribute_map = {
+ "hidden_size": "emb_dim",
+ "num_attention_heads": "n_heads",
+ "num_hidden_layers": "n_layers",
+ "n_words": "vocab_size", # For backward compatibility
+ "bos_index": "bos_token_id",
+ "eos_index": "eos_token_id",
+ "pad_index": "pad_token_id",
+ }
+
+ vocab_size: int = 30145
+ emb_dim: int = 2048
+ n_layers: int = 12
+ n_heads: int = 16
+ dropout: float | int = 0.1
+ attention_dropout: float | int = 0.1
+ gelu_activation: bool = True
+ sinusoidal_embeddings: bool = False
+ causal: bool = False
+ asm: bool = False
+ n_langs: int = 1
+ use_lang_emb: bool = True
+ max_position_embeddings: int = 512
+ embed_init_std: float = 2048**-0.5
+ layer_norm_eps: float = 1e-12
+ init_std: float = 0.02
+ unk_index: int = 3
+ mask_index: int = 5
+ is_encoder: bool = True
+ summary_type: str = "first"
+ summary_use_proj: bool = True
+ summary_activation: str | None = None
+ summary_proj_to_labels: bool = True
+ summary_first_dropout: float | int = 0.1
+ start_n_top: int = 5
+ end_n_top: int = 5
+ mask_token_id: int | None = 0
+ lang_id: int = 0
+ pad_token_id: int | None = 2
+ bos_token_id: int | None = 0
+ eos_token_id: int | list[int] | None = 1
+ tie_word_embeddings: bool = True
+
+
+__all__ = ["XLMConfig"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlm/modeling_xlm.py b/.venv/lib/python3.12/site-packages/transformers/models/xlm/modeling_xlm.py
new file mode 100644
index 0000000000000000000000000000000000000000..7466f5d959600ddf1b44eece7137daa7129e10fa
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xlm/modeling_xlm.py
@@ -0,0 +1,1601 @@
+# Copyright 2019-present, Facebook, Inc and the HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+PyTorch XLM model.
+"""
+
+import math
+from collections.abc import Callable
+from dataclasses import dataclass
+
+import numpy as np
+import torch
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ... import initialization as init
+from ...activations import gelu, get_activation
+from ...cache_utils import DynamicCache, EncoderDecoderCache
+from ...generation import GenerationMixin
+from ...modeling_outputs import (
+ BaseModelOutput,
+ MaskedLMOutput,
+ MultipleChoiceModelOutput,
+ QuestionAnsweringModelOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+)
+from ...modeling_utils import PreTrainedModel
+from ...pytorch_utils import apply_chunking_to_forward
+from ...utils import ModelOutput, auto_docstring, logging
+from .configuration_xlm import XLMConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+def create_sinusoidal_embeddings(n_pos, dim, out):
+ position_enc = np.array([[pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)] for pos in range(n_pos)])
+ out.requires_grad = False
+ out[:, 0::2] = torch.FloatTensor(np.sin(position_enc[:, 0::2]))
+ out[:, 1::2] = torch.FloatTensor(np.cos(position_enc[:, 1::2]))
+ out.detach_()
+ return out
+
+
+def get_masks(slen, lengths, causal, padding_mask=None):
+ """
+ Generate hidden states mask, and optionally an attention mask.
+ """
+ alen = torch.arange(slen, dtype=torch.long, device=lengths.device)
+ if padding_mask is not None:
+ mask = padding_mask
+ else:
+ assert lengths.max().item() <= slen
+ mask = alen < lengths[:, None]
+
+ # attention mask is the same as mask, or triangular inferior attention (causal)
+ bs = lengths.size(0)
+ if causal:
+ attn_mask = alen[None, None, :].repeat(bs, slen, 1) <= alen[None, :, None]
+ else:
+ attn_mask = mask
+
+ # sanity check
+ assert mask.size() == (bs, slen)
+ assert causal is False or attn_mask.size() == (bs, slen, slen)
+
+ return mask, attn_mask
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for outputs of question answering models using a [`~modeling_utils.XLMSQuADHead`].
+ """
+)
+@dataclass
+class XLMSquadHeadOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned if both `start_positions` and `end_positions` are provided):
+ Classification loss as the sum of start token, end token (and is_impossible if provided) classification
+ losses.
+ start_top_log_probs (`torch.FloatTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Log probabilities for the top config.start_n_top start token possibilities (beam-search).
+ start_top_index (`torch.LongTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Indices for the top config.start_n_top start token possibilities (beam-search).
+ end_top_log_probs (`torch.FloatTensor` of shape `(batch_size, config.start_n_top * config.end_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Log probabilities for the top `config.start_n_top * config.end_n_top` end token possibilities
+ (beam-search).
+ end_top_index (`torch.LongTensor` of shape `(batch_size, config.start_n_top * config.end_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Indices for the top `config.start_n_top * config.end_n_top` end token possibilities (beam-search).
+ cls_logits (`torch.FloatTensor` of shape `(batch_size,)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Log probabilities for the `is_impossible` label of the answers.
+ """
+
+ loss: torch.FloatTensor | None = None
+ start_top_log_probs: torch.FloatTensor | None = None
+ start_top_index: torch.LongTensor | None = None
+ end_top_log_probs: torch.FloatTensor | None = None
+ end_top_index: torch.LongTensor | None = None
+ cls_logits: torch.FloatTensor | None = None
+
+
+class XLMPoolerStartLogits(nn.Module):
+ """
+ Compute SQuAD start logits from sequence hidden states.
+
+ Args:
+ config ([`XLMConfig`]):
+ The config used by the model, will be used to grab the `hidden_size` of the model.
+ """
+
+ def __init__(self, config: XLMConfig):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, 1)
+
+ def forward(self, hidden_states: torch.FloatTensor, p_mask: torch.FloatTensor | None = None) -> torch.FloatTensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`):
+ The final hidden states of the model.
+ p_mask (`torch.FloatTensor` of shape `(batch_size, seq_len)`, *optional*):
+ Mask for tokens at invalid position, such as query and special symbols (PAD, SEP, CLS). 1.0 means token
+ should be masked.
+
+ Returns:
+ `torch.FloatTensor`: The start logits for SQuAD.
+ """
+ x = self.dense(hidden_states).squeeze(-1)
+
+ if p_mask is not None:
+ if p_mask.dtype == torch.float16:
+ x = x * (1 - p_mask) - 65500 * p_mask
+ else:
+ x = x * (1 - p_mask) - 1e30 * p_mask
+
+ return x
+
+
+class XLMPoolerEndLogits(nn.Module):
+ """
+ Compute SQuAD end logits from sequence hidden states.
+
+ Args:
+ config ([`XLMConfig`]):
+ The config used by the model, will be used to grab the `hidden_size` of the model and the `layer_norm_eps`
+ to use.
+ """
+
+ def __init__(self, config: XLMConfig):
+ super().__init__()
+ self.dense_0 = nn.Linear(config.hidden_size * 2, config.hidden_size)
+ self.activation = nn.Tanh()
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dense_1 = nn.Linear(config.hidden_size, 1)
+
+ def forward(
+ self,
+ hidden_states: torch.FloatTensor,
+ start_states: torch.FloatTensor | None = None,
+ start_positions: torch.LongTensor | None = None,
+ p_mask: torch.FloatTensor | None = None,
+ ) -> torch.FloatTensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`):
+ The final hidden states of the model.
+ start_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`, *optional*):
+ The hidden states of the first tokens for the labeled span.
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ The position of the first token for the labeled span.
+ p_mask (`torch.FloatTensor` of shape `(batch_size, seq_len)`, *optional*):
+ Mask for tokens at invalid position, such as query and special symbols (PAD, SEP, CLS). 1.0 means token
+ should be masked.
+
+
+
+ One of `start_states` or `start_positions` should be not `None`. If both are set, `start_positions` overrides
+ `start_states`.
+
+
+
+ Returns:
+ `torch.FloatTensor`: The end logits for SQuAD.
+ """
+ assert start_states is not None or start_positions is not None, (
+ "One of start_states, start_positions should be not None"
+ )
+ if start_positions is not None:
+ slen, hsz = hidden_states.shape[-2:]
+ start_positions = start_positions[:, None, None].expand(-1, -1, hsz) # shape (bsz, 1, hsz)
+ start_states = hidden_states.gather(-2, start_positions) # shape (bsz, 1, hsz)
+ start_states = start_states.expand(-1, slen, -1) # shape (bsz, slen, hsz)
+
+ x = self.dense_0(torch.cat([hidden_states, start_states], dim=-1))
+ x = self.activation(x)
+ x = self.LayerNorm(x)
+ x = self.dense_1(x).squeeze(-1)
+
+ if p_mask is not None:
+ if p_mask.dtype == torch.float16:
+ x = x * (1 - p_mask) - 65500 * p_mask
+ else:
+ x = x * (1 - p_mask) - 1e30 * p_mask
+
+ return x
+
+
+class XLMPoolerAnswerClass(nn.Module):
+ """
+ Compute SQuAD 2.0 answer class from classification and start tokens hidden states.
+
+ Args:
+ config ([`XLMConfig`]):
+ The config used by the model, will be used to grab the `hidden_size` of the model.
+ """
+
+ def __init__(self, config: XLMConfig):
+ super().__init__()
+ self.dense_0 = nn.Linear(config.hidden_size * 2, config.hidden_size)
+ self.activation = nn.Tanh()
+ self.dense_1 = nn.Linear(config.hidden_size, 1, bias=False)
+
+ def forward(
+ self,
+ hidden_states: torch.FloatTensor,
+ start_states: torch.FloatTensor | None = None,
+ start_positions: torch.LongTensor | None = None,
+ cls_index: torch.LongTensor | None = None,
+ ) -> torch.FloatTensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`):
+ The final hidden states of the model.
+ start_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`, *optional*):
+ The hidden states of the first tokens for the labeled span.
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ The position of the first token for the labeled span.
+ cls_index (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Position of the CLS token for each sentence in the batch. If `None`, takes the last token.
+
+
+
+ One of `start_states` or `start_positions` should be not `None`. If both are set, `start_positions` overrides
+ `start_states`.
+
+
+
+ Returns:
+ `torch.FloatTensor`: The SQuAD 2.0 answer class.
+ """
+ # No dependency on end_feature so that we can obtain one single `cls_logits` for each sample.
+ hsz = hidden_states.shape[-1]
+ assert start_states is not None or start_positions is not None, (
+ "One of start_states, start_positions should be not None"
+ )
+ if start_positions is not None:
+ start_positions = start_positions[:, None, None].expand(-1, -1, hsz) # shape (bsz, 1, hsz)
+ start_states = hidden_states.gather(-2, start_positions).squeeze(-2) # shape (bsz, hsz)
+
+ if cls_index is not None:
+ cls_index = cls_index[:, None, None].expand(-1, -1, hsz) # shape (bsz, 1, hsz)
+ cls_token_state = hidden_states.gather(-2, cls_index).squeeze(-2) # shape (bsz, hsz)
+ else:
+ cls_token_state = hidden_states[:, -1, :] # shape (bsz, hsz)
+
+ x = self.dense_0(torch.cat([start_states, cls_token_state], dim=-1))
+ x = self.activation(x)
+ x = self.dense_1(x).squeeze(-1)
+
+ return x
+
+
+class XLMSQuADHead(nn.Module):
+ r"""
+ A SQuAD head inspired by XLNet.
+
+ Args:
+ config ([`XLMConfig`]):
+ The config used by the model, will be used to grab the `hidden_size` of the model and the `layer_norm_eps`
+ to use.
+ """
+
+ def __init__(self, config: XLMConfig):
+ super().__init__()
+ self.start_n_top = config.start_n_top
+ self.end_n_top = config.end_n_top
+
+ self.start_logits = XLMPoolerStartLogits(config)
+ self.end_logits = XLMPoolerEndLogits(config)
+ self.answer_class = XLMPoolerAnswerClass(config)
+
+ @auto_docstring
+ def forward(
+ self,
+ hidden_states: torch.FloatTensor,
+ start_positions: torch.LongTensor | None = None,
+ end_positions: torch.LongTensor | None = None,
+ cls_index: torch.LongTensor | None = None,
+ is_impossible: torch.LongTensor | None = None,
+ p_mask: torch.FloatTensor | None = None,
+ return_dict: bool = False,
+ ) -> XLMSquadHeadOutput | tuple[torch.FloatTensor]:
+ r"""
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`):
+ Final hidden states of the model on the sequence tokens.
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Positions of the first token for the labeled span.
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Positions of the last token for the labeled span.
+ cls_index (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Position of the CLS token for each sentence in the batch. If `None`, takes the last token.
+ is_impossible (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Whether the question has a possible answer in the paragraph or not.
+ p_mask (`torch.FloatTensor` of shape `(batch_size, seq_len)`, *optional*):
+ Mask for tokens at invalid position, such as query and special symbols (PAD, SEP, CLS). 1.0 means token
+ should be masked.
+ """
+ start_logits = self.start_logits(hidden_states, p_mask=p_mask)
+
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, let's remove the dimension added by batch splitting
+ for x in (start_positions, end_positions, cls_index, is_impossible):
+ if x is not None and x.dim() > 1:
+ x.squeeze_(-1)
+
+ # during training, compute the end logits based on the ground truth of the start position
+ end_logits = self.end_logits(hidden_states, start_positions=start_positions, p_mask=p_mask)
+
+ loss_fct = CrossEntropyLoss()
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ if cls_index is not None and is_impossible is not None:
+ # Predict answerability from the representation of CLS and START
+ cls_logits = self.answer_class(hidden_states, start_positions=start_positions, cls_index=cls_index)
+ loss_fct_cls = nn.BCEWithLogitsLoss()
+ cls_loss = loss_fct_cls(cls_logits, is_impossible)
+
+ # note(zhiliny): by default multiply the loss by 0.5 so that the scale is comparable to start_loss and end_loss
+ total_loss += cls_loss * 0.5
+
+ return XLMSquadHeadOutput(loss=total_loss) if return_dict else (total_loss,)
+
+ else:
+ # during inference, compute the end logits based on beam search
+ bsz, slen, hsz = hidden_states.size()
+ start_log_probs = nn.functional.softmax(start_logits, dim=-1) # shape (bsz, slen)
+
+ start_top_log_probs, start_top_index = torch.topk(
+ start_log_probs, self.start_n_top, dim=-1
+ ) # shape (bsz, start_n_top)
+ start_top_index_exp = start_top_index.unsqueeze(-1).expand(-1, -1, hsz) # shape (bsz, start_n_top, hsz)
+ start_states = torch.gather(hidden_states, -2, start_top_index_exp) # shape (bsz, start_n_top, hsz)
+ start_states = start_states.unsqueeze(1).expand(-1, slen, -1, -1) # shape (bsz, slen, start_n_top, hsz)
+
+ hidden_states_expanded = hidden_states.unsqueeze(2).expand_as(
+ start_states
+ ) # shape (bsz, slen, start_n_top, hsz)
+ p_mask = p_mask.unsqueeze(-1) if p_mask is not None else None
+ end_logits = self.end_logits(hidden_states_expanded, start_states=start_states, p_mask=p_mask)
+ end_log_probs = nn.functional.softmax(end_logits, dim=1) # shape (bsz, slen, start_n_top)
+
+ end_top_log_probs, end_top_index = torch.topk(
+ end_log_probs, self.end_n_top, dim=1
+ ) # shape (bsz, end_n_top, start_n_top)
+ end_top_log_probs = end_top_log_probs.view(-1, self.start_n_top * self.end_n_top)
+ end_top_index = end_top_index.view(-1, self.start_n_top * self.end_n_top)
+
+ start_states = torch.einsum("blh,bl->bh", hidden_states, start_log_probs)
+ cls_logits = self.answer_class(hidden_states, start_states=start_states, cls_index=cls_index)
+
+ if not return_dict:
+ return (start_top_log_probs, start_top_index, end_top_log_probs, end_top_index, cls_logits)
+ else:
+ return XLMSquadHeadOutput(
+ start_top_log_probs=start_top_log_probs,
+ start_top_index=start_top_index,
+ end_top_log_probs=end_top_log_probs,
+ end_top_index=end_top_index,
+ cls_logits=cls_logits,
+ )
+
+
+class XLMSequenceSummary(nn.Module):
+ r"""
+ Compute a single vector summary of a sequence hidden states.
+
+ Args:
+ config ([`XLMConfig`]):
+ The config used by the model. Relevant arguments in the config class of the model are (refer to the actual
+ config class of your model for the default values it uses):
+
+ - **summary_type** (`str`) -- The method to use to make this summary. Accepted values are:
+
+ - `"last"` -- Take the last token hidden state (like XLNet)
+ - `"first"` -- Take the first token hidden state (like Bert)
+ - `"mean"` -- Take the mean of all tokens hidden states
+ - `"cls_index"` -- Supply a Tensor of classification token position (GPT/GPT-2)
+ - `"attn"` -- Not implemented now, use multi-head attention
+
+ - **summary_use_proj** (`bool`) -- Add a projection after the vector extraction.
+ - **summary_proj_to_labels** (`bool`) -- If `True`, the projection outputs to `config.num_labels` classes
+ (otherwise to `config.hidden_size`).
+ - **summary_activation** (`Optional[str]`) -- Set to `"tanh"` to add a tanh activation to the output,
+ another string or `None` will add no activation.
+ - **summary_first_dropout** (`float`) -- Optional dropout probability before the projection and activation.
+ - **summary_last_dropout** (`float`)-- Optional dropout probability after the projection and activation.
+ """
+
+ def __init__(self, config: XLMConfig):
+ super().__init__()
+
+ self.summary_type = getattr(config, "summary_type", "last")
+ if self.summary_type == "attn":
+ # We should use a standard multi-head attention module with absolute positional embedding for that.
+ # Cf. https://github.com/zihangdai/xlnet/blob/master/modeling.py#L253-L276
+ # We can probably just use the multi-head attention module of PyTorch >=1.1.0
+ raise NotImplementedError
+
+ self.summary = nn.Identity()
+ if hasattr(config, "summary_use_proj") and config.summary_use_proj:
+ if hasattr(config, "summary_proj_to_labels") and config.summary_proj_to_labels and config.num_labels > 0:
+ num_classes = config.num_labels
+ else:
+ num_classes = config.hidden_size
+ self.summary = nn.Linear(config.hidden_size, num_classes)
+
+ activation_string = getattr(config, "summary_activation", None)
+ self.activation: Callable = get_activation(activation_string) if activation_string else nn.Identity()
+
+ self.first_dropout = nn.Identity()
+ if hasattr(config, "summary_first_dropout") and config.summary_first_dropout > 0:
+ self.first_dropout = nn.Dropout(config.summary_first_dropout)
+
+ self.last_dropout = nn.Identity()
+ if hasattr(config, "summary_last_dropout") and config.summary_last_dropout > 0:
+ self.last_dropout = nn.Dropout(config.summary_last_dropout)
+
+ def forward(
+ self, hidden_states: torch.FloatTensor, cls_index: torch.LongTensor | None = None
+ ) -> torch.FloatTensor:
+ """
+ Compute a single vector summary of a sequence hidden states.
+
+ Args:
+ hidden_states (`torch.FloatTensor` of shape `[batch_size, seq_len, hidden_size]`):
+ The hidden states of the last layer.
+ cls_index (`torch.LongTensor` of shape `[batch_size]` or `[batch_size, ...]` where ... are optional leading dimensions of `hidden_states`, *optional*):
+ Used if `summary_type == "cls_index"` and takes the last token of the sequence as classification token.
+
+ Returns:
+ `torch.FloatTensor`: The summary of the sequence hidden states.
+ """
+ if self.summary_type == "last":
+ output = hidden_states[:, -1]
+ elif self.summary_type == "first":
+ output = hidden_states[:, 0]
+ elif self.summary_type == "mean":
+ output = hidden_states.mean(dim=1)
+ elif self.summary_type == "cls_index":
+ if cls_index is None:
+ cls_index = torch.full_like(
+ hidden_states[..., :1, :],
+ hidden_states.shape[-2] - 1,
+ dtype=torch.long,
+ )
+ else:
+ cls_index = cls_index.unsqueeze(-1).unsqueeze(-1)
+ cls_index = cls_index.expand((-1,) * (cls_index.dim() - 1) + (hidden_states.size(-1),))
+ # shape of cls_index: (bsz, XX, 1, hidden_size) where XX are optional leading dim of hidden_states
+ output = hidden_states.gather(-2, cls_index).squeeze(-2) # shape (bsz, XX, hidden_size)
+ elif self.summary_type == "attn":
+ raise NotImplementedError
+
+ output = self.first_dropout(output)
+ output = self.summary(output)
+ output = self.activation(output)
+ output = self.last_dropout(output)
+
+ return output
+
+
+class MultiHeadAttention(nn.Module):
+ def __init__(self, n_heads, dim, config, layer_idx: int = 0):
+ super().__init__()
+ self.layer_id = layer_idx
+ self.dim = dim
+ self.n_heads = n_heads
+ self.head_dim = dim // n_heads
+ self.dropout = config.attention_dropout
+ assert self.dim % self.n_heads == 0
+
+ self.q_lin = nn.Linear(dim, dim)
+ self.k_lin = nn.Linear(dim, dim)
+ self.v_lin = nn.Linear(dim, dim)
+ self.out_lin = nn.Linear(dim, dim)
+
+ def forward(
+ self,
+ input,
+ mask,
+ kv=None,
+ cache=None,
+ output_attentions=False,
+ **kwargs,
+ ):
+ """
+ Self-attention (if kv is None) or attention over source sentence (provided by kv).
+ """
+ # Input is (bs, qlen, dim)
+ # Mask is (bs, klen) (non-causal) or (bs, klen, klen)
+ bs, qlen, dim = input.size()
+ is_cross_attention = kv is not None
+ mask_reshape = (bs, 1, qlen, -1) if mask.dim() == 3 else (bs, 1, 1, -1)
+
+ q = self.q_lin(input).view(bs, -1, self.n_heads, self.head_dim).transpose(1, 2)
+ if cache is not None:
+ if isinstance(cache, EncoderDecoderCache):
+ is_updated = cache.is_updated.get(self.layer_id)
+ if is_cross_attention:
+ # after the first generated id, we can subsequently re-use all key/value_states from cache
+ curr_past_key_values = cache.cross_attention_cache
+ else:
+ curr_past_key_values = cache.self_attention_cache
+ else:
+ curr_past_key_values = cache
+
+ current_states = kv if is_cross_attention else input
+ if is_cross_attention and cache is not None and is_updated:
+ # reuse k,v, cross_attentions
+ k = curr_past_key_values.key_cache[self.layer_id]
+ v = curr_past_key_values.value_cache[self.layer_id]
+ else:
+ k = self.k_lin(current_states)
+ v = self.v_lin(current_states)
+ k = k.view(bs, -1, self.n_heads, self.head_dim).transpose(1, 2)
+ v = v.view(bs, -1, self.n_heads, self.head_dim).transpose(1, 2)
+
+ if cache is not None:
+ # save all key/value_states to cache to be re-used for fast auto-regressive generation
+ k, v = curr_past_key_values.update(k, v, self.layer_id)
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
+ if is_cross_attention:
+ cache.is_updated[self.layer_id] = True
+
+ q = q / math.sqrt(self.head_dim) # (bs, n_heads, qlen, head_dim)
+ scores = torch.matmul(q, k.transpose(2, 3)) # (bs, n_heads, qlen, klen)
+ mask = (mask == 0).view(mask_reshape).expand_as(scores) # (bs, n_heads, qlen, klen)
+ scores.masked_fill_(mask, torch.finfo(scores.dtype).min) # (bs, n_heads, qlen, klen)
+
+ weights = nn.functional.softmax(scores.float(), dim=-1).type_as(scores) # (bs, n_heads, qlen, klen)
+ weights = nn.functional.dropout(weights, p=self.dropout, training=self.training) # (bs, n_heads, qlen, klen)
+
+ context = torch.matmul(weights, v) # (bs, n_heads, qlen, head_dim)
+ context = context.transpose(1, 2).contiguous().view(bs, -1, self.n_heads * self.head_dim)
+
+ outputs = (self.out_lin(context),)
+ if output_attentions:
+ outputs = outputs + (weights,)
+ return outputs
+
+
+class TransformerFFN(nn.Module):
+ def __init__(self, in_dim, dim_hidden, out_dim, config):
+ super().__init__()
+ self.dropout = config.dropout
+ self.lin1 = nn.Linear(in_dim, dim_hidden)
+ self.lin2 = nn.Linear(dim_hidden, out_dim)
+ self.act = gelu if config.gelu_activation else nn.functional.relu
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+
+ def forward(self, input):
+ return apply_chunking_to_forward(self.ff_chunk, self.chunk_size_feed_forward, self.seq_len_dim, input)
+
+ def ff_chunk(self, input):
+ x = self.lin1(input)
+ x = self.act(x)
+ x = self.lin2(x)
+ x = nn.functional.dropout(x, p=self.dropout, training=self.training)
+ return x
+
+
+@auto_docstring
+class XLMPreTrainedModel(PreTrainedModel):
+ config: XLMConfig
+ base_model_prefix = "transformer"
+
+ @property
+ def dummy_inputs(self):
+ inputs_list = torch.tensor([[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]])
+ attns_list = torch.tensor([[1, 1, 0, 0, 1], [1, 1, 1, 0, 0], [1, 0, 0, 1, 1]])
+ if self.config.use_lang_emb and self.config.n_langs > 1:
+ langs_list = torch.tensor([[1, 1, 0, 0, 1], [1, 1, 1, 0, 0], [1, 0, 0, 1, 1]])
+ else:
+ langs_list = None
+ return {"input_ids": inputs_list, "attention_mask": attns_list, "langs": langs_list}
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights."""
+ if isinstance(module, nn.Embedding):
+ if self.config is not None and self.config.embed_init_std is not None:
+ init.normal_(module.weight, mean=0, std=self.config.embed_init_std)
+ # Here we need the check explicitly, as we slice the weight in the `zeros_` call, so it looses the flag
+ if module.padding_idx is not None and not getattr(module.weight, "_is_hf_initialized", False):
+ init.zeros_(module.weight[module.padding_idx])
+ if isinstance(module, nn.Linear):
+ if self.config is not None and self.config.init_std is not None:
+ init.normal_(module.weight, mean=0, std=self.config.init_std)
+ if module.bias is not None:
+ init.constant_(module.bias, 0.0)
+ if isinstance(module, nn.LayerNorm):
+ init.zeros_(module.bias)
+ init.ones_(module.weight)
+ if isinstance(module, XLMModel):
+ if self.config.sinusoidal_embeddings:
+ init.copy_(
+ module.position_embeddings.weight,
+ create_sinusoidal_embeddings(
+ self.config.max_position_embeddings,
+ self.config.emb_dim,
+ out=torch.empty_like(module.position_embeddings.weight),
+ ),
+ )
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for outputs of question answering models using a `XLMSQuADHead`.
+ """
+)
+@dataclass
+class XLMForQuestionAnsweringOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned if both `start_positions` and `end_positions` are provided):
+ Classification loss as the sum of start token, end token (and is_impossible if provided) classification
+ losses.
+ start_top_log_probs (`torch.FloatTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Log probabilities for the top config.start_n_top start token possibilities (beam-search).
+ start_top_index (`torch.LongTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Indices for the top config.start_n_top start token possibilities (beam-search).
+ end_top_log_probs (`torch.FloatTensor` of shape `(batch_size, config.start_n_top * config.end_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Log probabilities for the top `config.start_n_top * config.end_n_top` end token possibilities
+ (beam-search).
+ end_top_index (`torch.LongTensor` of shape `(batch_size, config.start_n_top * config.end_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Indices for the top `config.start_n_top * config.end_n_top` end token possibilities (beam-search).
+ cls_logits (`torch.FloatTensor` of shape `(batch_size,)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Log probabilities for the `is_impossible` label of the answers.
+ """
+
+ loss: torch.FloatTensor | None = None
+ start_top_log_probs: torch.FloatTensor | None = None
+ start_top_index: torch.LongTensor | None = None
+ end_top_log_probs: torch.FloatTensor | None = None
+ end_top_index: torch.LongTensor | None = None
+ cls_logits: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
+ attentions: tuple[torch.FloatTensor, ...] | None = None
+
+
+@auto_docstring
+class XLMModel(XLMPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ # encoder / decoder, output layer
+ self.is_encoder = config.is_encoder
+ self.is_decoder = not config.is_encoder
+ if self.is_decoder:
+ raise NotImplementedError("Currently XLM can only be used as an encoder")
+ # self.with_output = with_output
+ self.causal = config.causal
+
+ # dictionary / languages
+ self.n_langs = config.n_langs
+ self.use_lang_emb = config.use_lang_emb
+ self.n_words = config.n_words
+ self.eos_index = config.eos_index
+ self.pad_index = config.pad_index
+ # self.dico = dico
+ # self.id2lang = config.id2lang
+ # self.lang2id = config.lang2id
+ # assert len(self.dico) == self.n_words
+ # assert len(self.id2lang) == len(self.lang2id) == self.n_langs
+
+ # model parameters
+ self.dim = config.emb_dim # 512 by default
+ self.hidden_dim = self.dim * 4 # 2048 by default
+ self.n_heads = config.n_heads # 8 by default
+ self.n_layers = config.n_layers
+ self.dropout = config.dropout
+ self.attention_dropout = config.attention_dropout
+ assert self.dim % self.n_heads == 0, "transformer dim must be a multiple of n_heads"
+
+ # embeddings
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, self.dim)
+ if config.n_langs > 1 and config.use_lang_emb:
+ self.lang_embeddings = nn.Embedding(self.n_langs, self.dim)
+ self.embeddings = nn.Embedding(self.n_words, self.dim, padding_idx=self.pad_index)
+ self.layer_norm_emb = nn.LayerNorm(self.dim, eps=config.layer_norm_eps)
+
+ # transformer layers
+ self.attentions = nn.ModuleList()
+ self.layer_norm1 = nn.ModuleList()
+ self.ffns = nn.ModuleList()
+ self.layer_norm2 = nn.ModuleList()
+ # if self.is_decoder:
+ # self.layer_norm15 = nn.ModuleList()
+ # self.encoder_attn = nn.ModuleList()
+
+ for i in range(self.n_layers):
+ self.attentions.append(MultiHeadAttention(self.n_heads, self.dim, config=config, layer_idx=i))
+ self.layer_norm1.append(nn.LayerNorm(self.dim, eps=config.layer_norm_eps))
+ # if self.is_decoder:
+ # self.layer_norm15.append(nn.LayerNorm(self.dim, eps=config.layer_norm_eps))
+ # self.encoder_attn.append(MultiHeadAttention(self.n_heads, self.dim, dropout=self.attention_dropout))
+ self.ffns.append(TransformerFFN(self.dim, self.hidden_dim, self.dim, config=config))
+ self.layer_norm2.append(nn.LayerNorm(self.dim, eps=config.layer_norm_eps))
+
+ # Initialize weights and apply final processing
+ self.register_buffer(
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
+ )
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings
+
+ def set_input_embeddings(self, new_embeddings):
+ self.embeddings = new_embeddings
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ langs: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ lengths: torch.Tensor | None = None,
+ cache: dict[str, torch.Tensor] | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs, # Dummy kwargs for now
+ ) -> tuple | BaseModelOutput:
+ r"""
+ langs (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are
+ languages ids which can be obtained from the language names by using two conversion mappings provided in
+ the configuration of the model (only provided for multilingual models). More precisely, the *language name
+ to language id* mapping is in `model.config.lang2id` (which is a dictionary string to int) and the
+ *language id to language name* mapping is in `model.config.id2lang` (dictionary int to string).
+
+ See usage examples detailed in the [multilingual documentation](../multilingual).
+ lengths (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Length of each sentence that can be used to avoid performing attention on padding token indices. You can
+ also use *attention_mask* for the same result (see above), kept here for compatibility. Indices selected in
+ `[0, ..., input_ids.size(-1)]`.
+ cache (`dict[str, torch.FloatTensor]`, *optional*):
+ Instance of `EncoderDecoderCache` that contains precomputed KV states. Can be used to speed up sequential
+ decoding.
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ if input_ids is not None:
+ bs, slen = input_ids.size()
+ else:
+ bs, slen = inputs_embeds.size()[:-1]
+
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
+
+ if cache is None:
+ cache = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
+
+ if lengths is None:
+ if input_ids is not None:
+ lengths = (input_ids != self.pad_index).sum(dim=1).long()
+ else:
+ lengths = torch.full((bs,), slen, device=device, dtype=torch.long)
+
+ # check inputs
+ assert lengths.size(0) == bs
+ assert lengths.max().item() <= slen
+
+ # generate masks
+ mask, attn_mask = get_masks(slen, lengths, self.causal, padding_mask=attention_mask)
+
+ # position_ids
+ if position_ids is None:
+ position_ids = self.position_ids[:, :slen]
+ else:
+ assert position_ids.size() == (bs, slen) # (slen, bs)
+
+ # langs
+ if langs is not None:
+ assert langs.size() == (bs, slen) # (slen, bs)
+
+ # do not recompute cached elements
+ if cache is not None and input_ids is not None:
+ _slen = slen - cache.get_seq_length()
+ input_ids = input_ids[:, -_slen:]
+ position_ids = position_ids[:, -_slen:]
+ if langs is not None:
+ langs = langs[:, -_slen:]
+ mask = mask[:, -_slen:]
+ attn_mask = attn_mask[:, -_slen:]
+
+ # embeddings
+ if inputs_embeds is None:
+ inputs_embeds = self.embeddings(input_ids)
+
+ tensor = inputs_embeds + self.position_embeddings(position_ids).expand_as(inputs_embeds)
+ if langs is not None and self.use_lang_emb and self.n_langs > 1:
+ tensor = tensor + self.lang_embeddings(langs)
+ if token_type_ids is not None:
+ tensor = tensor + self.embeddings(token_type_ids)
+ tensor = self.layer_norm_emb(tensor)
+ tensor = nn.functional.dropout(tensor, p=self.dropout, training=self.training)
+ tensor *= mask.unsqueeze(-1).to(tensor.dtype)
+
+ # transformer layers
+ hidden_states = () if output_hidden_states else None
+ attentions = () if output_attentions else None
+ for i in range(self.n_layers):
+ if output_hidden_states:
+ hidden_states = hidden_states + (tensor,)
+
+ # self attention
+ attn_outputs = self.attentions[i](
+ tensor,
+ attn_mask,
+ cache=cache,
+ output_attentions=output_attentions,
+ )
+ attn = attn_outputs[0]
+ if output_attentions:
+ attentions = attentions + (attn_outputs[1],)
+ attn = nn.functional.dropout(attn, p=self.dropout, training=self.training)
+ tensor = tensor + attn
+ tensor = self.layer_norm1[i](tensor)
+
+ # FFN
+ tensor = tensor + self.ffns[i](tensor)
+ tensor = self.layer_norm2[i](tensor)
+ tensor *= mask.unsqueeze(-1).to(tensor.dtype)
+
+ # Add last hidden state
+ if output_hidden_states:
+ hidden_states = hidden_states + (tensor,)
+
+ if not return_dict:
+ return tuple(v for v in [tensor, hidden_states, attentions] if v is not None)
+ return BaseModelOutput(last_hidden_state=tensor, hidden_states=hidden_states, attentions=attentions)
+
+
+class XLMPredLayer(nn.Module):
+ """
+ Prediction layer (cross_entropy or adaptive_softmax).
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ self.asm = config.asm
+ self.n_words = config.n_words
+ self.pad_index = config.pad_index
+ dim = config.emb_dim
+
+ if config.asm is False:
+ self.proj = nn.Linear(dim, config.n_words, bias=True)
+ else:
+ self.proj = nn.AdaptiveLogSoftmaxWithLoss(
+ in_features=dim,
+ n_classes=config.n_words,
+ cutoffs=config.asm_cutoffs,
+ div_value=config.asm_div_value,
+ head_bias=True, # default is False
+ )
+
+ def forward(self, x, y=None):
+ """Compute the loss, and optionally the scores."""
+ outputs = ()
+ if self.asm is False:
+ scores = self.proj(x)
+ outputs = (scores,) + outputs
+ if y is not None:
+ loss = nn.functional.cross_entropy(scores.view(-1, self.n_words), y.view(-1), reduction="mean")
+ outputs = (loss,) + outputs
+ else:
+ scores = self.proj.log_prob(x)
+ outputs = (scores,) + outputs
+ if y is not None:
+ _, loss = self.proj(x, y)
+ outputs = (loss,) + outputs
+
+ return outputs
+
+
+@auto_docstring(
+ custom_intro="""
+ The XLM Model transformer with a language modeling head on top (linear layer with weights tied to the input
+ embeddings).
+ """
+)
+class XLMWithLMHeadModel(XLMPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"pred_layer.proj.weight": "transformer.embeddings.weight"}
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.transformer = XLMModel(config)
+ self.pred_layer = XLMPredLayer(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.pred_layer.proj
+
+ def set_output_embeddings(self, new_embeddings):
+ self.pred_layer.proj = new_embeddings
+
+ def prepare_inputs_for_generation(self, input_ids, is_first_iteration=False, **kwargs):
+ # Overwritten -- this model uses config options to prepare inputs
+
+ mask_token_id = self.config.mask_token_id
+ lang_id = self.config.lang_id
+
+ effective_batch_size = input_ids.shape[0]
+ mask_token = torch.full((effective_batch_size, 1), mask_token_id, dtype=torch.long, device=input_ids.device)
+ input_ids = torch.cat([input_ids, mask_token], dim=1)
+ if lang_id is not None:
+ langs = torch.full_like(input_ids, lang_id)
+ else:
+ langs = None
+ model_inputs = {"input_ids": input_ids, "langs": langs}
+
+ # They are calculated on the fly on XLMModel.forward()
+ kwargs.pop("token_type_ids", None)
+ kwargs.pop("attention_mask", None)
+ kwargs.pop("position_ids", None)
+
+ # Forward ALL kwargs that are uninitialized (e.g. `use_cache`).
+ for key, value in kwargs.items():
+ if key not in model_inputs:
+ model_inputs[key] = value
+
+ return model_inputs
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ langs: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ lengths: torch.Tensor | None = None,
+ cache: dict[str, torch.Tensor] | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs,
+ ) -> tuple | MaskedLMOutput:
+ r"""
+ langs (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are
+ languages ids which can be obtained from the language names by using two conversion mappings provided in
+ the configuration of the model (only provided for multilingual models). More precisely, the *language name
+ to language id* mapping is in `model.config.lang2id` (which is a dictionary string to int) and the
+ *language id to language name* mapping is in `model.config.id2lang` (dictionary int to string).
+
+ See usage examples detailed in the [multilingual documentation](../multilingual).
+ lengths (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Length of each sentence that can be used to avoid performing attention on padding token indices. You can
+ also use *attention_mask* for the same result (see above), kept here for compatibility. Indices selected in
+ `[0, ..., input_ids.size(-1)]`.
+ cache (`dict[str, torch.FloatTensor]`, *optional*):
+ Instance of `EncoderDecoderCache` that contains precomputed KV states. Can be used to speed up sequential
+ decoding.
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ transformer_outputs = self.transformer(
+ input_ids,
+ attention_mask=attention_mask,
+ langs=langs,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ lengths=lengths,
+ cache=cache,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ **kwargs,
+ )
+
+ hidden_states = transformer_outputs[0]
+ # Only compute necessary logits
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ outputs = self.pred_layer(
+ hidden_states[:, slice_indices, :],
+ labels,
+ ) # (loss, logits) or (logits,) depending on if labels are provided.
+
+ if not return_dict:
+ return outputs + transformer_outputs[1:]
+
+ return MaskedLMOutput(
+ loss=outputs[0] if labels is not None else None,
+ logits=outputs[0] if labels is None else outputs[1],
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ XLM Model with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g.
+ for GLUE tasks.
+ """
+)
+class XLMForSequenceClassification(XLMPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.config = config
+
+ self.transformer = XLMModel(config)
+ self.sequence_summary = XLMSequenceSummary(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ langs: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ lengths: torch.Tensor | None = None,
+ cache: dict[str, torch.Tensor] | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | SequenceClassifierOutput:
+ r"""
+ langs (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are
+ languages ids which can be obtained from the language names by using two conversion mappings provided in
+ the configuration of the model (only provided for multilingual models). More precisely, the *language name
+ to language id* mapping is in `model.config.lang2id` (which is a dictionary string to int) and the
+ *language id to language name* mapping is in `model.config.id2lang` (dictionary int to string).
+
+ See usage examples detailed in the [multilingual documentation](../multilingual).
+ lengths (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Length of each sentence that can be used to avoid performing attention on padding token indices. You can
+ also use *attention_mask* for the same result (see above), kept here for compatibility. Indices selected in
+ `[0, ..., input_ids.size(-1)]`.
+ cache (`dict[str, torch.FloatTensor]`, *optional*):
+ Instance of `EncoderDecoderCache` that contains precomputed KV states. Can be used to speed up sequential
+ decoding.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ transformer_outputs = self.transformer(
+ input_ids,
+ attention_mask=attention_mask,
+ langs=langs,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ lengths=lengths,
+ cache=cache,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ output = transformer_outputs[0]
+ logits = self.sequence_summary(output)
+
+ loss = None
+ if labels is not None:
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ if not return_dict:
+ output = (logits,) + transformer_outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ XLM Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
+ """
+)
+class XLMForQuestionAnsweringSimple(XLMPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.transformer = XLMModel(config)
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ langs: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ lengths: torch.Tensor | None = None,
+ cache: dict[str, torch.Tensor] | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ start_positions: torch.Tensor | None = None,
+ end_positions: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | QuestionAnsweringModelOutput:
+ r"""
+ langs (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are
+ languages ids which can be obtained from the language names by using two conversion mappings provided in
+ the configuration of the model (only provided for multilingual models). More precisely, the *language name
+ to language id* mapping is in `model.config.lang2id` (which is a dictionary string to int) and the
+ *language id to language name* mapping is in `model.config.id2lang` (dictionary int to string).
+
+ See usage examples detailed in the [multilingual documentation](../multilingual).
+ lengths (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Length of each sentence that can be used to avoid performing attention on padding token indices. You can
+ also use *attention_mask* for the same result (see above), kept here for compatibility. Indices selected in
+ `[0, ..., input_ids.size(-1)]`.
+ cache (`dict[str, torch.FloatTensor]`, *optional*):
+ Instance of `EncoderDecoderCache` that contains precomputed KV states. Can be used to speed up sequential
+ decoding.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ transformer_outputs = self.transformer(
+ input_ids,
+ attention_mask=attention_mask,
+ langs=langs,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ lengths=lengths,
+ cache=cache,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = transformer_outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1).contiguous()
+ end_logits = end_logits.squeeze(-1).contiguous()
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ if not return_dict:
+ output = (start_logits, end_logits) + transformer_outputs[1:]
+ return ((total_loss,) + output) if total_loss is not None else output
+
+ return QuestionAnsweringModelOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+@auto_docstring
+class XLMForQuestionAnswering(XLMPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.transformer = XLMModel(config)
+ self.qa_outputs = XLMSQuADHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ langs: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ lengths: torch.Tensor | None = None,
+ cache: dict[str, torch.Tensor] | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ start_positions: torch.Tensor | None = None,
+ end_positions: torch.Tensor | None = None,
+ is_impossible: torch.Tensor | None = None,
+ cls_index: torch.Tensor | None = None,
+ p_mask: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | XLMForQuestionAnsweringOutput:
+ r"""
+ langs (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are
+ languages ids which can be obtained from the language names by using two conversion mappings provided in
+ the configuration of the model (only provided for multilingual models). More precisely, the *language name
+ to language id* mapping is in `model.config.lang2id` (which is a dictionary string to int) and the
+ *language id to language name* mapping is in `model.config.id2lang` (dictionary int to string).
+
+ See usage examples detailed in the [multilingual documentation](../multilingual).
+ lengths (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Length of each sentence that can be used to avoid performing attention on padding token indices. You can
+ also use *attention_mask* for the same result (see above), kept here for compatibility. Indices selected in
+ `[0, ..., input_ids.size(-1)]`.
+ cache (`dict[str, torch.FloatTensor]`, *optional*):
+ Instance of `EncoderDecoderCache` that contains precomputed KV states. Can be used to speed up sequential
+ decoding.
+ is_impossible (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels whether a question has an answer or no answer (SQuAD 2.0)
+ cls_index (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for position (index) of the classification token to use as input for computing plausibility of the
+ answer.
+ p_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Optional mask of tokens which can't be in answers (e.g. [CLS], [PAD], ...). 1.0 means token should be
+ masked. 0.0 mean token is not masked.
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, XLMForQuestionAnswering
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("FacebookAI/xlm-mlm-en-2048")
+ >>> model = XLMForQuestionAnswering.from_pretrained("FacebookAI/xlm-mlm-en-2048")
+
+ >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(
+ ... 0
+ ... ) # Batch size 1
+ >>> start_positions = torch.tensor([1])
+ >>> end_positions = torch.tensor([3])
+
+ >>> outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions)
+ >>> loss = outputs.loss
+ ```"""
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ transformer_outputs = self.transformer(
+ input_ids,
+ attention_mask=attention_mask,
+ langs=langs,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ lengths=lengths,
+ cache=cache,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ output = transformer_outputs[0]
+
+ outputs = self.qa_outputs(
+ output,
+ start_positions=start_positions,
+ end_positions=end_positions,
+ cls_index=cls_index,
+ is_impossible=is_impossible,
+ p_mask=p_mask,
+ return_dict=return_dict,
+ )
+
+ if not return_dict:
+ return outputs + transformer_outputs[1:]
+
+ return XLMForQuestionAnsweringOutput(
+ loss=outputs.loss,
+ start_top_log_probs=outputs.start_top_log_probs,
+ start_top_index=outputs.start_top_index,
+ end_top_log_probs=outputs.end_top_log_probs,
+ end_top_index=outputs.end_top_index,
+ cls_logits=outputs.cls_logits,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+@auto_docstring
+class XLMForTokenClassification(XLMPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.transformer = XLMModel(config)
+ self.dropout = nn.Dropout(config.dropout)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ langs: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ lengths: torch.Tensor | None = None,
+ cache: dict[str, torch.Tensor] | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | TokenClassifierOutput:
+ r"""
+ langs (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are
+ languages ids which can be obtained from the language names by using two conversion mappings provided in
+ the configuration of the model (only provided for multilingual models). More precisely, the *language name
+ to language id* mapping is in `model.config.lang2id` (which is a dictionary string to int) and the
+ *language id to language name* mapping is in `model.config.id2lang` (dictionary int to string).
+
+ See usage examples detailed in the [multilingual documentation](../multilingual).
+ lengths (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Length of each sentence that can be used to avoid performing attention on padding token indices. You can
+ also use *attention_mask* for the same result (see above), kept here for compatibility. Indices selected in
+ `[0, ..., input_ids.size(-1)]`.
+ cache (`dict[str, torch.FloatTensor]`, *optional*):
+ Instance of `EncoderDecoderCache` that contains precomputed KV states. Can be used to speed up sequential
+ decoding.
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.transformer(
+ input_ids,
+ attention_mask=attention_mask,
+ langs=langs,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ lengths=lengths,
+ cache=cache,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ sequence_output = self.dropout(sequence_output)
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ if not return_dict:
+ output = (logits,) + outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class XLMForMultipleChoice(XLMPreTrainedModel):
+ def __init__(self, config, *inputs, **kwargs):
+ super().__init__(config, *inputs, **kwargs)
+
+ self.transformer = XLMModel(config)
+ self.sequence_summary = XLMSequenceSummary(config)
+ self.logits_proj = nn.Linear(config.num_labels, 1)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ langs: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ lengths: torch.Tensor | None = None,
+ cache: dict[str, torch.Tensor] | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | MultipleChoiceModelOutput:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ langs (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are
+ languages ids which can be obtained from the language names by using two conversion mappings provided in
+ the configuration of the model (only provided for multilingual models). More precisely, the *language name
+ to language id* mapping is in `model.config.lang2id` (which is a dictionary string to int) and the
+ *language id to language name* mapping is in `model.config.id2lang` (dictionary int to string).
+
+ See usage examples detailed in the [multilingual documentation](../multilingual).
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
+ 1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ lengths (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Length of each sentence that can be used to avoid performing attention on padding token indices. You can
+ also use *attention_mask* for the same result (see above), kept here for compatibility. Indices selected in
+ `[0, ..., input_ids.size(-1)]`.
+ cache (`dict[str, torch.FloatTensor]`, *optional*):
+ Instance of `EncoderDecoderCache` that contains precomputed KV states. Can be used to speed up sequential
+ decoding.
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
+ `input_ids` above)
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
+
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
+ langs = langs.view(-1, langs.size(-1)) if langs is not None else None
+ inputs_embeds = (
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
+ if inputs_embeds is not None
+ else None
+ )
+
+ if lengths is not None:
+ logger.warning(
+ "The `lengths` parameter cannot be used with the XLM multiple choice models. Please use the "
+ "attention mask instead."
+ )
+ lengths = None
+
+ transformer_outputs = self.transformer(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ langs=langs,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ lengths=lengths,
+ cache=cache,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ output = transformer_outputs[0]
+ logits = self.sequence_summary(output)
+ logits = self.logits_proj(logits)
+ reshaped_logits = logits.view(-1, num_choices)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(reshaped_logits, labels)
+
+ if not return_dict:
+ output = (reshaped_logits,) + transformer_outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return MultipleChoiceModelOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+__all__ = [
+ "XLMForMultipleChoice",
+ "XLMForQuestionAnswering",
+ "XLMForQuestionAnsweringSimple",
+ "XLMForSequenceClassification",
+ "XLMForTokenClassification",
+ "XLMModel",
+ "XLMPreTrainedModel",
+ "XLMWithLMHeadModel",
+]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlm/tokenization_xlm.py b/.venv/lib/python3.12/site-packages/transformers/models/xlm/tokenization_xlm.py
new file mode 100644
index 0000000000000000000000000000000000000000..b4efc1665227a30f1fec42ffe155a71e8f680619
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xlm/tokenization_xlm.py
@@ -0,0 +1,577 @@
+# Copyright 2019 The Open AI Team Authors and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes for XLM."""
+
+import json
+import os
+import re
+import sys
+import unicodedata
+
+from ...tokenization_python import PreTrainedTokenizer
+from ...utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {
+ "vocab_file": "vocab.json",
+ "merges_file": "merges.txt",
+}
+
+
+def get_pairs(word):
+ """
+ Return set of symbol pairs in a word. word is represented as tuple of symbols (symbols being variable-length
+ strings)
+ """
+ pairs = set()
+ prev_char = word[0]
+ for char in word[1:]:
+ pairs.add((prev_char, char))
+ prev_char = char
+ return pairs
+
+
+def lowercase_and_remove_accent(text):
+ """
+ Lowercase and strips accents from a piece of text based on
+ https://github.com/facebookresearch/XLM/blob/master/tools/lowercase_and_remove_accent.py
+ """
+ text = " ".join(text)
+ text = text.lower()
+ text = unicodedata.normalize("NFD", text)
+ output = []
+ for char in text:
+ cat = unicodedata.category(char)
+ if cat == "Mn":
+ continue
+ output.append(char)
+ return "".join(output).lower().split(" ")
+
+
+def replace_unicode_punct(text):
+ """
+ Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/replace-unicode-punctuation.perl
+ """
+ text = text.replace(",", ",")
+ text = re.sub(r"。\s*", ". ", text)
+ text = text.replace("、", ",")
+ text = text.replace("”", '"')
+ text = text.replace("“", '"')
+ text = text.replace("∶", ":")
+ text = text.replace(":", ":")
+ text = text.replace("?", "?")
+ text = text.replace("《", '"')
+ text = text.replace("》", '"')
+ text = text.replace(")", ")")
+ text = text.replace("!", "!")
+ text = text.replace("(", "(")
+ text = text.replace(";", ";")
+ text = text.replace("1", "1")
+ text = text.replace("」", '"')
+ text = text.replace("「", '"')
+ text = text.replace("0", "0")
+ text = text.replace("3", "3")
+ text = text.replace("2", "2")
+ text = text.replace("5", "5")
+ text = text.replace("6", "6")
+ text = text.replace("9", "9")
+ text = text.replace("7", "7")
+ text = text.replace("8", "8")
+ text = text.replace("4", "4")
+ text = re.sub(r".\s*", ". ", text)
+ text = text.replace("~", "~")
+ text = text.replace("’", "'")
+ text = text.replace("…", "...")
+ text = text.replace("━", "-")
+ text = text.replace("〈", "<")
+ text = text.replace("〉", ">")
+ text = text.replace("【", "[")
+ text = text.replace("】", "]")
+ text = text.replace("%", "%")
+ return text
+
+
+def remove_non_printing_char(text):
+ """
+ Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/remove-non-printing-char.perl
+ """
+ output = []
+ for char in text:
+ cat = unicodedata.category(char)
+ if cat.startswith("C"):
+ continue
+ output.append(char)
+ return "".join(output)
+
+
+def romanian_preprocessing(text):
+ """Sennrich's WMT16 scripts for Romanian preprocessing, used by model `FacebookAI/xlm-mlm-enro-1024`"""
+ # https://github.com/rsennrich/wmt16-scripts/blob/master/preprocess/normalise-romanian.py
+ text = text.replace("\u015e", "\u0218").replace("\u015f", "\u0219")
+ text = text.replace("\u0162", "\u021a").replace("\u0163", "\u021b")
+ # https://github.com/rsennrich/wmt16-scripts/blob/master/preprocess/remove-diacritics.py
+ text = text.replace("\u0218", "S").replace("\u0219", "s") # s-comma
+ text = text.replace("\u021a", "T").replace("\u021b", "t") # t-comma
+ text = text.replace("\u0102", "A").replace("\u0103", "a")
+ text = text.replace("\u00c2", "A").replace("\u00e2", "a")
+ text = text.replace("\u00ce", "I").replace("\u00ee", "i")
+ return text
+
+
+class XLMTokenizer(PreTrainedTokenizer):
+ """
+ Construct an XLM tokenizer. Based on Byte-Pair Encoding. The tokenization process is the following:
+
+ - Moses preprocessing and tokenization for most supported languages.
+ - Language specific tokenization for Chinese (Jieba), Japanese (KyTea) and Thai (PyThaiNLP).
+ - Optionally lowercases and normalizes all inputs text.
+ - The arguments `special_tokens` and the function `set_special_tokens`, can be used to add additional symbols (like
+ "__classify__") to a vocabulary.
+ - The `lang2id` attribute maps the languages supported by the model with their IDs if provided (automatically set
+ for pretrained vocabularies).
+ - The `id2lang` attributes does reverse mapping if provided (automatically set for pretrained vocabularies).
+
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
+ this superclass for more information regarding those methods.
+
+ Args:
+ vocab_file (`str`):
+ Vocabulary file.
+ merges_file (`str`):
+ Merges file.
+ unk_token (`str`, *optional*, defaults to `""`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ bos_token (`str`, *optional*, defaults to `""`):
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
+ sequence. The token used is the `cls_token`.
+
+
+
+ sep_token (`str`, *optional*, defaults to `""`):
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
+ sequence classification or for a text and a question for question answering. It is also used as the last
+ token of a sequence built with special tokens.
+ pad_token (`str`, *optional*, defaults to `""`):
+ The token used for padding, for example when batching sequences of different lengths.
+ cls_token (`str`, *optional*, defaults to `""`):
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
+ mask_token (`str`, *optional*, defaults to `""`):
+ The token used for masking values. This is the token used when training this model with masked language
+ modeling. This is the token which the model will try to predict.
+ additional_special_tokens (`List[str]`, *optional*, defaults to `['', '', '', '', '', '', '', '', '', '']`):
+ List of additional special tokens.
+ lang2id (`Dict[str, int]`, *optional*):
+ Dictionary mapping languages string identifiers to their IDs.
+ id2lang (`Dict[int, str]`, *optional*):
+ Dictionary mapping language IDs to their string identifiers.
+ do_lowercase_and_remove_accent (`bool`, *optional*, defaults to `True`):
+ Whether to lowercase and remove accents when tokenizing.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+
+ def __init__(
+ self,
+ vocab_file,
+ merges_file,
+ unk_token="",
+ bos_token="",
+ sep_token="",
+ pad_token="",
+ cls_token="",
+ mask_token="",
+ additional_special_tokens=[
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ ],
+ lang2id=None,
+ id2lang=None,
+ do_lowercase_and_remove_accent=True,
+ **kwargs,
+ ):
+ try:
+ import sacremoses
+ except ImportError:
+ raise ImportError(
+ "You need to install sacremoses to use XLMTokenizer. "
+ "See https://pypi.org/project/sacremoses/ for installation."
+ )
+
+ self.sm = sacremoses
+
+ # cache of sm.MosesPunctNormalizer instance
+ self.cache_moses_punct_normalizer = {}
+ # cache of sm.MosesTokenizer instance
+ self.cache_moses_tokenizer = {}
+ self.lang_with_custom_tokenizer = {"zh", "th", "ja"}
+ # True for current supported model (v1.2.0), False for XLM-17 & 100
+ self.do_lowercase_and_remove_accent = do_lowercase_and_remove_accent
+ self.lang2id = lang2id
+ self.id2lang = id2lang
+ if lang2id is not None and id2lang is not None:
+ assert len(lang2id) == len(id2lang)
+
+ self.ja_word_tokenizer = None
+ self.zh_word_tokenizer = None
+
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
+ self.encoder = json.load(vocab_handle)
+ self.decoder = {v: k for k, v in self.encoder.items()}
+ with open(merges_file, encoding="utf-8") as merges_handle:
+ merges = merges_handle.read().split("\n")[:-1]
+ merges = [tuple(merge.split()[:2]) for merge in merges]
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
+ self.cache = {}
+ super().__init__(
+ unk_token=unk_token,
+ bos_token=bos_token,
+ sep_token=sep_token,
+ pad_token=pad_token,
+ cls_token=cls_token,
+ mask_token=mask_token,
+ additional_special_tokens=additional_special_tokens,
+ lang2id=lang2id,
+ id2lang=id2lang,
+ do_lowercase_and_remove_accent=do_lowercase_and_remove_accent,
+ **kwargs,
+ )
+
+ @property
+ def do_lower_case(self):
+ return self.do_lowercase_and_remove_accent
+
+ def moses_punct_norm(self, text, lang):
+ if lang not in self.cache_moses_punct_normalizer:
+ punct_normalizer = self.sm.MosesPunctNormalizer(lang=lang)
+ self.cache_moses_punct_normalizer[lang] = punct_normalizer
+ else:
+ punct_normalizer = self.cache_moses_punct_normalizer[lang]
+ return punct_normalizer.normalize(text)
+
+ def moses_tokenize(self, text, lang):
+ if lang not in self.cache_moses_tokenizer:
+ moses_tokenizer = self.sm.MosesTokenizer(lang=lang)
+ self.cache_moses_tokenizer[lang] = moses_tokenizer
+ else:
+ moses_tokenizer = self.cache_moses_tokenizer[lang]
+ return moses_tokenizer.tokenize(text, return_str=False, escape=False)
+
+ def moses_pipeline(self, text, lang):
+ text = replace_unicode_punct(text)
+ text = self.moses_punct_norm(text, lang)
+ text = remove_non_printing_char(text)
+ return text
+
+ def ja_tokenize(self, text):
+ if self.ja_word_tokenizer is None:
+ try:
+ import Mykytea
+
+ self.ja_word_tokenizer = Mykytea.Mykytea(
+ f"-model {os.path.expanduser('~')}/local/share/kytea/model.bin"
+ )
+ except (AttributeError, ImportError):
+ logger.error(
+ "Make sure you install KyTea (https://github.com/neubig/kytea) and it's python wrapper"
+ " (https://github.com/chezou/Mykytea-python) with the following steps"
+ )
+ logger.error("1. git clone git@github.com:neubig/kytea.git && cd kytea")
+ logger.error("2. autoreconf -i")
+ logger.error("3. ./configure --prefix=$HOME/local")
+ logger.error("4. make && make install")
+ logger.error("5. pip install kytea")
+ raise
+ return list(self.ja_word_tokenizer.getWS(text))
+
+ @property
+ def vocab_size(self):
+ return len(self.encoder)
+
+ def get_vocab(self):
+ return dict(self.encoder, **self.added_tokens_encoder)
+
+ def bpe(self, token):
+ word = tuple(token[:-1]) + (token[-1] + "",)
+ if token in self.cache:
+ return self.cache[token]
+ pairs = get_pairs(word)
+
+ if not pairs:
+ return token + ""
+
+ while True:
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
+ if bigram not in self.bpe_ranks:
+ break
+ first, second = bigram
+ new_word = []
+ i = 0
+ while i < len(word):
+ try:
+ j = word.index(first, i)
+ except ValueError:
+ new_word.extend(word[i:])
+ break
+ else:
+ new_word.extend(word[i:j])
+ i = j
+
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
+ new_word.append(first + second)
+ i += 2
+ else:
+ new_word.append(word[i])
+ i += 1
+ new_word = tuple(new_word)
+ word = new_word
+ if len(word) == 1:
+ break
+ else:
+ pairs = get_pairs(word)
+ word = " ".join(word)
+ if word == "\n ":
+ word = "\n"
+ self.cache[token] = word
+ return word
+
+ def _tokenize(self, text, lang="en", bypass_tokenizer=False):
+ """
+ Tokenize a string given language code. For Chinese, Japanese and Thai, we use a language specific tokenizer.
+ Otherwise, we use Moses.
+
+ Details of tokenization:
+
+ - [sacremoses](https://github.com/alvations/sacremoses): port of Moses
+ - Install with `pip install sacremoses`
+ - [pythainlp](https://github.com/PyThaiNLP/pythainlp): Thai tokenizer
+ - Install with `pip install pythainlp`
+ - [kytea](https://github.com/chezou/Mykytea-python): Japanese tokenizer, wrapper of
+ [KyTea](https://github.com/neubig/kytea)
+ - Install with the following steps:
+
+ ::
+
+ git clone git@github.com:neubig/kytea.git && cd kytea autoreconf -i ./configure --prefix=$HOME/local
+ make && make install pip install kytea
+
+ - [rjieba](https://github.com/messense/rjieba-py): Chinese tokenizer (*)
+ - Install with `pip install rjieba`
+
+ (*) The original XLM used [Stanford
+ Segmenter](https://nlp.stanford.edu/software/stanford-segmenter-2018-10-16.zip). However, the wrapper
+ (`nltk.tokenize.stanford_segmenter`) is slow due to JVM overhead, and it will be deprecated. Jieba is a lot
+ faster and pip-installable. Note there is some mismatch with the Stanford Segmenter. It should be fine if you
+ fine-tune the model with Chinese supervisionself. If you want the same exact behaviour, use the original XLM
+ [preprocessing script](https://github.com/facebookresearch/XLM/tree/master/tools) to tokenize the sentence
+ externally, and set `bypass_tokenizer=True` to bypass the tokenizer.
+
+ Args:
+ - lang: ISO language code (default = 'en') (string). Languages should belong of the model supported
+ languages. However, we don't enforce it.
+ - bypass_tokenizer: Allow users to preprocess and tokenize the sentences externally (default = False)
+ (bool). If True, we only apply BPE.
+
+ Returns:
+ List of tokens.
+ """
+ if lang and self.lang2id and lang not in self.lang2id:
+ logger.error(
+ "Supplied language code not found in lang2id mapping. Please check that your language is supported by"
+ " the loaded pretrained model."
+ )
+ if bypass_tokenizer:
+ text = text.split()
+ elif lang not in self.lang_with_custom_tokenizer:
+ text = self.moses_pipeline(text, lang=lang)
+ # TODO: make sure we are using `FacebookAI/xlm-mlm-enro-1024`, since XLM-100 doesn't have this step
+ if lang == "ro":
+ text = romanian_preprocessing(text)
+ text = self.moses_tokenize(text, lang=lang)
+ elif lang == "th":
+ text = self.moses_pipeline(text, lang=lang)
+ try:
+ if "pythainlp" not in sys.modules:
+ from pythainlp.tokenize import word_tokenize as th_word_tokenize
+ else:
+ th_word_tokenize = sys.modules["pythainlp"].word_tokenize
+ except (AttributeError, ImportError):
+ logger.error(
+ "Make sure you install PyThaiNLP (https://github.com/PyThaiNLP/pythainlp) with the following steps"
+ )
+ logger.error("1. pip install pythainlp")
+ raise
+ text = th_word_tokenize(text)
+ elif lang == "zh":
+ try:
+ if "rjieba" not in sys.modules:
+ import rjieba
+ else:
+ rjieba = sys.modules["rjieba"]
+ except (AttributeError, ImportError):
+ logger.error(
+ "Make sure you install rjieba (https://github.com/messense/rjieba-py) with the following steps"
+ )
+ logger.error("1. pip install rjieba")
+ raise
+ text = " ".join(rjieba.cut(text))
+ text = self.moses_pipeline(text, lang=lang)
+ text = text.split()
+ elif lang == "ja":
+ text = self.moses_pipeline(text, lang=lang)
+ text = self.ja_tokenize(text)
+ else:
+ raise ValueError("It should not reach here")
+
+ if self.do_lowercase_and_remove_accent and not bypass_tokenizer:
+ text = lowercase_and_remove_accent(text)
+
+ split_tokens = []
+ for token in text:
+ if token:
+ split_tokens.extend(list(self.bpe(token).split(" ")))
+
+ return split_tokens
+
+ def _convert_token_to_id(self, token):
+ """Converts a token (str) in an id using the vocab."""
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
+
+ def _convert_id_to_token(self, index):
+ """Converts an index (integer) in a token (str) using the vocab."""
+ return self.decoder.get(index, self.unk_token)
+
+ def convert_tokens_to_string(self, tokens):
+ """Converts a sequence of tokens (string) in a single string."""
+ out_string = "".join(tokens).replace("", " ").strip()
+ return out_string
+
+ def build_inputs_with_special_tokens(
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None
+ ) -> list[int]:
+ """
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
+ adding special tokens. An XLM sequence has the following format:
+
+ - single sequence: ` X `
+ - pair of sequences: ` A B `
+
+ Args:
+ token_ids_0 (`List[int]`):
+ List of IDs to which the special tokens will be added.
+ token_ids_1 (`List[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
+
+ """
+ bos = [self.bos_token_id]
+ sep = [self.sep_token_id]
+
+ if token_ids_1 is None:
+ return bos + token_ids_0 + sep
+ return bos + token_ids_0 + sep + token_ids_1 + sep
+
+ def get_special_tokens_mask(
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False
+ ) -> list[int]:
+ """
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
+ special tokens using the tokenizer `prepare_for_model` method.
+
+ Args:
+ token_ids_0 (`List[int]`):
+ List of IDs.
+ token_ids_1 (`List[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
+ Whether or not the token list is already formatted with special tokens for the model.
+
+ Returns:
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
+ """
+
+ if already_has_special_tokens:
+ return super().get_special_tokens_mask(
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
+ )
+
+ if token_ids_1 is not None:
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
+ return [1] + ([0] * len(token_ids_0)) + [1]
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
+ if not os.path.isdir(save_directory):
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
+ return
+ vocab_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
+ )
+ merge_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
+ )
+
+ with open(vocab_file, "w", encoding="utf-8") as f:
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
+
+ index = 0
+ with open(merge_file, "w", encoding="utf-8") as writer:
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
+ if index != token_index:
+ logger.warning(
+ f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
+ " Please check that the tokenizer is not corrupted!"
+ )
+ index = token_index
+ writer.write(" ".join(bpe_tokens) + "\n")
+ index += 1
+
+ return vocab_file, merge_file
+
+ def __getstate__(self):
+ state = self.__dict__.copy()
+ state["sm"] = None
+ return state
+
+ def __setstate__(self, d):
+ self.__dict__ = d
+
+ try:
+ import sacremoses
+ except ImportError:
+ raise ImportError(
+ "You need to install sacremoses to use XLMTokenizer. "
+ "See https://pypi.org/project/sacremoses/ for installation."
+ )
+
+ self.sm = sacremoses
+
+
+__all__ = ["XLMTokenizer"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/__init__.py b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1706e6dbefae2f08f1785222092336386e9cf8f0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/__init__.py
@@ -0,0 +1,29 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_xlm_roberta import *
+ from .modeling_xlm_roberta import *
+ from .tokenization_xlm_roberta import *
+ from .tokenization_xlm_roberta_fast import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..394ab638ff387440b6550f2c3b8106d0b89f289c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/__pycache__/configuration_xlm_roberta.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/__pycache__/configuration_xlm_roberta.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2d27da33f7224efc36ce877467c571371396bf01
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/__pycache__/configuration_xlm_roberta.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/__pycache__/modeling_xlm_roberta.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/__pycache__/modeling_xlm_roberta.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fdba6c020b50b47879ec76f18f11e5e0f3520306
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/__pycache__/modeling_xlm_roberta.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/__pycache__/modular_xlm_roberta.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/__pycache__/modular_xlm_roberta.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..541cd71d2a969bf0a138fb796f582398ecfae80c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/__pycache__/modular_xlm_roberta.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/__pycache__/tokenization_xlm_roberta.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/__pycache__/tokenization_xlm_roberta.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..20c7d91760eb00976db5b010bd2758a11a7488e0
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/__pycache__/tokenization_xlm_roberta.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/configuration_xlm_roberta.py b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/configuration_xlm_roberta.py
new file mode 100644
index 0000000000000000000000000000000000000000..463aa9f53509aa507a0792f179a19f0bb474aa1e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/configuration_xlm_roberta.py
@@ -0,0 +1,66 @@
+# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""XLM-RoBERTa configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="FacebookAI/xlm-mlm-en-2048")
+@strict
+class XLMRobertaConfig(PreTrainedConfig):
+ r"""
+ Examples:
+
+ ```python
+ >>> from transformers import XLMRobertaConfig, XLMRobertaModel
+
+ >>> # Initializing a XLM-RoBERTa FacebookAI/xlm-roberta-base style configuration
+ >>> configuration = XLMRobertaConfig()
+
+ >>> # Initializing a model (with random weights) from the FacebookAI/xlm-roberta-base style configuration
+ >>> model = XLMRobertaModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "xlm-roberta"
+
+ vocab_size: int = 30522
+ hidden_size: int = 768
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ intermediate_size: int = 3072
+ hidden_act: str = "gelu"
+ hidden_dropout_prob: float | int = 0.1
+ attention_probs_dropout_prob: float | int = 0.1
+ max_position_embeddings: int = 512
+ type_vocab_size: int = 2
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-12
+ pad_token_id: int | None = 1
+ bos_token_id: int | None = 0
+ eos_token_id: int | list[int] | None = 2
+ use_cache: bool = True
+ classifier_dropout: float | int | None = None
+ is_decoder: bool = False
+ add_cross_attention: bool = False
+ tie_word_embeddings: bool = True
+
+
+__all__ = ["XLMRobertaConfig"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/modeling_xlm_roberta.py b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/modeling_xlm_roberta.py
new file mode 100644
index 0000000000000000000000000000000000000000..bce50bffb07af74fee917d11f8983f7e9cc6365f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/modeling_xlm_roberta.py
@@ -0,0 +1,1259 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/xlm_roberta/modular_xlm_roberta.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_xlm_roberta.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2019 Facebook AI Research and the HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from collections.abc import Callable
+
+import torch
+import torch.nn as nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ... import initialization as init
+from ...activations import ACT2FN, gelu
+from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
+from ...generation import GenerationMixin
+from ...masking_utils import create_bidirectional_mask, create_causal_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutputWithPastAndCrossAttentions,
+ BaseModelOutputWithPoolingAndCrossAttentions,
+ CausalLMOutputWithCrossAttentions,
+ MaskedLMOutput,
+ MultipleChoiceModelOutput,
+ QuestionAnsweringModelOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+)
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...pytorch_utils import apply_chunking_to_forward
+from ...utils import TransformersKwargs, auto_docstring, logging
+from ...utils.generic import can_return_tuple, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_xlm_roberta import XLMRobertaConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+class XLMRobertaEmbeddings(nn.Module):
+ """Construct the embeddings from word, position and token_type embeddings."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
+
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
+ self.register_buffer(
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
+ )
+ self.register_buffer(
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
+ )
+
+ self.padding_idx = config.pad_token_id
+ self.position_embeddings = nn.Embedding(
+ config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
+ )
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ past_key_values_length: int = 0,
+ ) -> torch.Tensor:
+ if position_ids is None:
+ if input_ids is not None:
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
+ position_ids = self.create_position_ids_from_input_ids(
+ input_ids, self.padding_idx, past_key_values_length
+ )
+ else:
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds, self.padding_idx)
+
+ if input_ids is not None:
+ input_shape = input_ids.size()
+ else:
+ input_shape = inputs_embeds.size()[:-1]
+
+ batch_size, seq_length = input_shape
+
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
+ # issue #5664
+ if token_type_ids is None:
+ if hasattr(self, "token_type_ids"):
+ # NOTE: We assume either pos ids to have bsz == 1 (broadcastable) or bsz == effective bsz (input_shape[0])
+ buffered_token_type_ids = self.token_type_ids.to(position_ids.device).expand(position_ids.shape[0], -1)
+ buffered_token_type_ids = torch.gather(buffered_token_type_ids, dim=1, index=position_ids)
+ token_type_ids = buffered_token_type_ids.expand(batch_size, seq_length)
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
+
+ if inputs_embeds is None:
+ inputs_embeds = self.word_embeddings(input_ids)
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
+ embeddings = inputs_embeds + token_type_embeddings
+
+ position_embeddings = self.position_embeddings(position_ids)
+ embeddings = embeddings + position_embeddings
+
+ embeddings = self.LayerNorm(embeddings)
+ embeddings = self.dropout(embeddings)
+ return embeddings
+
+ @staticmethod
+ def create_position_ids_from_inputs_embeds(inputs_embeds, padding_idx):
+ """
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
+
+ Args:
+ inputs_embeds: torch.Tensor
+
+ Returns: torch.Tensor
+ """
+ input_shape = inputs_embeds.size()[:-1]
+ sequence_length = input_shape[1]
+
+ position_ids = torch.arange(
+ padding_idx + 1, sequence_length + padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
+ )
+ return position_ids.unsqueeze(0).expand(input_shape)
+
+ @staticmethod
+ def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
+ """
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
+ are ignored. This is modified from fairseq's `utils.make_positions`.
+
+ Args:
+ x: torch.Tensor x:
+
+ Returns: torch.Tensor
+ """
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
+ mask = input_ids.ne(padding_idx).int()
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
+ return incremental_indices.long() + padding_idx
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float | None = None,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ if scaling is None:
+ scaling = query.size(-1) ** -0.5
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
+
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+class XLMRobertaSelfAttention(nn.Module):
+ def __init__(self, config, is_causal=False, layer_idx=None):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({config.num_attention_heads})"
+ )
+ self.config = config
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+ self.scaling = self.attention_head_size**-0.5
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+
+ self.is_decoder = config.is_decoder
+ self.is_causal = is_causal
+ self.layer_idx = layer_idx
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
+
+ # get all proj
+ query_layer = self.query(hidden_states).view(*hidden_shape).transpose(1, 2)
+ key_layer = self.key(hidden_states).view(*hidden_shape).transpose(1, 2)
+ value_layer = self.value(hidden_states).view(*hidden_shape).transpose(1, 2)
+
+ if past_key_values is not None:
+ # decoder-only xlm_roberta can have a simple dynamic cache for example
+ current_past_key_values = past_key_values
+ if isinstance(past_key_values, EncoderDecoderCache):
+ current_past_key_values = past_key_values.self_attention_cache
+
+ # save all key/value_layer to cache to be re-used for fast auto-regressive generation
+ key_layer, value_layer = current_past_key_values.update(key_layer, value_layer, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_layer,
+ key_layer,
+ value_layer,
+ attention_mask,
+ dropout=0.0 if not self.training else self.dropout.p,
+ scaling=self.scaling,
+ **kwargs,
+ )
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ return attn_output, attn_weights
+
+
+class XLMRobertaCrossAttention(nn.Module):
+ def __init__(self, config, is_causal=False, layer_idx=None):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({config.num_attention_heads})"
+ )
+ self.config = config
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+ self.scaling = self.attention_head_size**-0.5
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+
+ self.is_causal = is_causal
+ self.layer_idx = layer_idx
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ past_key_values: EncoderDecoderCache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor]:
+ # determine input shapes
+ input_shape = hidden_states.shape[:-1]
+
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
+
+ # get query proj
+ query_layer = self.query(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ is_updated = past_key_values.is_updated.get(self.layer_idx) if past_key_values is not None else False
+ if past_key_values is not None and is_updated:
+ # reuse k,v, cross_attentions
+ key_layer = past_key_values.cross_attention_cache.layers[self.layer_idx].keys
+ value_layer = past_key_values.cross_attention_cache.layers[self.layer_idx].values
+ else:
+ kv_shape = (*encoder_hidden_states.shape[:-1], -1, self.attention_head_size)
+ key_layer = self.key(encoder_hidden_states).view(kv_shape).transpose(1, 2)
+ value_layer = self.value(encoder_hidden_states).view(kv_shape).transpose(1, 2)
+
+ if past_key_values is not None:
+ # save all states to the cache
+ key_layer, value_layer = past_key_values.cross_attention_cache.update(
+ key_layer, value_layer, self.layer_idx
+ )
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
+ past_key_values.is_updated[self.layer_idx] = True
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_layer,
+ key_layer,
+ value_layer,
+ attention_mask,
+ dropout=0.0 if not self.training else self.dropout.p,
+ scaling=self.scaling,
+ **kwargs,
+ )
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ return attn_output, attn_weights
+
+
+class XLMRobertaSelfOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+class XLMRobertaAttention(nn.Module):
+ def __init__(self, config, is_causal=False, layer_idx=None, is_cross_attention=False):
+ super().__init__()
+ self.is_cross_attention = is_cross_attention
+ attention_class = XLMRobertaCrossAttention if is_cross_attention else XLMRobertaSelfAttention
+ self.self = attention_class(config, is_causal=is_causal, layer_idx=layer_idx)
+ self.output = XLMRobertaSelfOutput(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor]:
+ attention_mask = attention_mask if not self.is_cross_attention else encoder_attention_mask
+ attention_output, attn_weights = self.self(
+ hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ attention_output = self.output(attention_output, hidden_states)
+ return attention_output, attn_weights
+
+
+class XLMRobertaIntermediate(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ return hidden_states
+
+
+class XLMRobertaOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+class XLMRobertaLayer(GradientCheckpointingLayer):
+ def __init__(self, config, layer_idx=None):
+ super().__init__()
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+ self.attention = XLMRobertaAttention(config, is_causal=config.is_decoder, layer_idx=layer_idx)
+ self.is_decoder = config.is_decoder
+ self.add_cross_attention = config.add_cross_attention
+ if self.add_cross_attention:
+ if not self.is_decoder:
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
+ self.crossattention = XLMRobertaAttention(
+ config,
+ is_causal=False,
+ layer_idx=layer_idx,
+ is_cross_attention=True,
+ )
+ self.intermediate = XLMRobertaIntermediate(config)
+ self.output = XLMRobertaOutput(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ self_attention_output, _ = self.attention(
+ hidden_states,
+ attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ attention_output = self_attention_output
+
+ if self.is_decoder and encoder_hidden_states is not None:
+ if not hasattr(self, "crossattention"):
+ raise ValueError(
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
+ " by setting `config.add_cross_attention=True`"
+ )
+
+ cross_attention_output, _ = self.crossattention(
+ self_attention_output,
+ None, # attention_mask
+ encoder_hidden_states,
+ encoder_attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ attention_output = cross_attention_output
+
+ layer_output = apply_chunking_to_forward(
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
+ )
+ return layer_output
+
+ def feed_forward_chunk(self, attention_output):
+ intermediate_output = self.intermediate(attention_output)
+ layer_output = self.output(intermediate_output, attention_output)
+ return layer_output
+
+
+class XLMRobertaLMHead(nn.Module):
+ """XLMRoberta Head for masked language modeling."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
+
+ def forward(self, features, **kwargs):
+ x = self.dense(features)
+ x = gelu(x)
+ x = self.layer_norm(x)
+
+ # project back to size of vocabulary with bias
+ x = self.decoder(x)
+
+ return x
+
+
+@auto_docstring
+class XLMRobertaPreTrainedModel(PreTrainedModel):
+ config_class = XLMRobertaConfig
+ base_model_prefix = "roberta"
+ supports_gradient_checkpointing = True
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": XLMRobertaLayer,
+ "attentions": XLMRobertaSelfAttention,
+ "cross_attentions": XLMRobertaCrossAttention,
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ super()._init_weights(module)
+ if isinstance(module, XLMRobertaLMHead):
+ init.zeros_(module.bias)
+ elif isinstance(module, XLMRobertaEmbeddings):
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
+ init.zeros_(module.token_type_ids)
+
+
+class XLMRobertaEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList([XLMRobertaLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPastAndCrossAttentions:
+ for i, layer_module in enumerate(self.layer):
+ hidden_states = layer_module(
+ hidden_states,
+ attention_mask,
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values if use_cache else None,
+ )
+
+
+class XLMRobertaPooler(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.activation = nn.Tanh()
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ # We "pool" the model by simply taking the hidden state corresponding
+ # to the first token.
+ first_token_tensor = hidden_states[:, 0]
+ pooled_output = self.dense(first_token_tensor)
+ pooled_output = self.activation(pooled_output)
+ return pooled_output
+
+
+@auto_docstring
+class XLMRobertaModel(XLMRobertaPreTrainedModel):
+ _no_split_modules = ["XLMRobertaEmbeddings", "XLMRobertaLayer"]
+
+ def __init__(self, config, add_pooling_layer=True):
+ r"""
+ add_pooling_layer (bool, *optional*, defaults to `True`):
+ Whether to add a pooling layer
+ """
+ super().__init__(config)
+ self.config = config
+ self.gradient_checkpointing = False
+
+ self.embeddings = XLMRobertaEmbeddings(config)
+ self.encoder = XLMRobertaEncoder(config)
+
+ self.pooler = XLMRobertaPooler(config) if add_pooling_layer else None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.embeddings.word_embeddings = value
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPoolingAndCrossAttentions:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if self.config.is_decoder:
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+ else:
+ use_cache = False
+
+ if use_cache and past_key_values is None:
+ past_key_values = (
+ EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
+ if encoder_hidden_states is not None or self.config.is_encoder_decoder
+ else DynamicCache(config=self.config)
+ )
+
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
+
+ embedding_output = self.embeddings(
+ input_ids=input_ids,
+ position_ids=position_ids,
+ token_type_ids=token_type_ids,
+ inputs_embeds=inputs_embeds,
+ past_key_values_length=past_key_values_length,
+ )
+
+ attention_mask, encoder_attention_mask = self._create_attention_masks(
+ attention_mask=attention_mask,
+ encoder_attention_mask=encoder_attention_mask,
+ embedding_output=embedding_output,
+ encoder_hidden_states=encoder_hidden_states,
+ past_key_values=past_key_values,
+ )
+
+ encoder_outputs = self.encoder(
+ embedding_output,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_ids=position_ids,
+ **kwargs,
+ )
+ sequence_output = encoder_outputs.last_hidden_state
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
+
+ return BaseModelOutputWithPoolingAndCrossAttentions(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ past_key_values=encoder_outputs.past_key_values,
+ )
+
+ def _create_attention_masks(
+ self,
+ attention_mask,
+ encoder_attention_mask,
+ embedding_output,
+ encoder_hidden_states,
+ past_key_values,
+ ):
+ if self.config.is_decoder:
+ attention_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ )
+ else:
+ attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=attention_mask,
+ )
+
+ if encoder_attention_mask is not None:
+ encoder_attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=encoder_attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ )
+
+ return attention_mask, encoder_attention_mask
+
+
+@auto_docstring(
+ custom_intro="""
+ XLM-RoBERTa Model with a `language modeling` head on top for CLM fine-tuning.
+ """
+)
+class XLMRobertaForCausalLM(XLMRobertaPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {
+ "lm_head.decoder.weight": "roberta.embeddings.word_embeddings.weight",
+ "lm_head.decoder.bias": "lm_head.bias",
+ }
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ if not config.is_decoder:
+ logger.warning("If you want to use `XLMRobertaLMHeadModel` as a standalone, add `is_decoder=True.`")
+ self.lm_head = XLMRobertaLMHead(config)
+ self.roberta = XLMRobertaModel(config, add_pooling_layer=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.lm_head.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head.decoder = new_embeddings
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ past_key_values: tuple[tuple[torch.FloatTensor]] | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | CausalLMOutputWithCrossAttentions:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
+ ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, XLMRobertaForCausalLM, AutoConfig
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("FacebookAI/roberta-base")
+ >>> config = AutoConfig.from_pretrained("FacebookAI/roberta-base")
+ >>> config.is_decoder = True
+ >>> model = XLMRobertaForCausalLM.from_pretrained("FacebookAI/roberta-base", config=config)
+
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
+ >>> outputs = model(**inputs)
+
+ >>> prediction_logits = outputs.logits
+ ```"""
+ if labels is not None:
+ use_cache = False
+
+ outputs: BaseModelOutputWithPoolingAndCrossAttentions = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ return_dict=True,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return CausalLMOutputWithCrossAttentions(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+
+@auto_docstring
+class XLMRobertaForMaskedLM(XLMRobertaPreTrainedModel):
+ _tied_weights_keys = {
+ "lm_head.decoder.weight": "roberta.embeddings.word_embeddings.weight",
+ "lm_head.decoder.bias": "lm_head.bias",
+ }
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ if config.is_decoder:
+ logger.warning(
+ "If you want to use `XLMRobertaForMaskedLM` make sure `config.is_decoder=False` for "
+ "bi-directional self-attention."
+ )
+ self.lm_head = XLMRobertaLMHead(config)
+
+ self.roberta = XLMRobertaModel(config, add_pooling_layer=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.lm_head.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head.decoder = new_embeddings
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | MaskedLMOutput:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ return_dict=True,
+ **kwargs,
+ )
+ sequence_output = outputs[0]
+ prediction_scores = self.lm_head(sequence_output)
+
+ masked_lm_loss = None
+ if labels is not None:
+ # move labels to correct device
+ labels = labels.to(prediction_scores.device)
+ loss_fct = CrossEntropyLoss()
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
+
+ return MaskedLMOutput(
+ loss=masked_lm_loss,
+ logits=prediction_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+class XLMRobertaClassificationHead(nn.Module):
+ """Head for sentence-level classification tasks."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
+
+ def forward(self, features, **kwargs):
+ x = features[:, 0, :] # take token (equiv. to [CLS])
+ x = self.dropout(x)
+ x = self.dense(x)
+ x = torch.tanh(x)
+ x = self.dropout(x)
+ x = self.out_proj(x)
+ return x
+
+
+@auto_docstring(
+ custom_intro="""
+ XLM-RoBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the
+ pooled output) e.g. for GLUE tasks.
+ """
+)
+class XLMRobertaForSequenceClassification(XLMRobertaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.config = config
+ self.classifier = XLMRobertaClassificationHead(config)
+
+ self.roberta = XLMRobertaModel(config, add_pooling_layer=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | SequenceClassifierOutput:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+ sequence_output = outputs[0]
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ # move labels to correct device
+ labels = labels.to(logits.device)
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class XLMRobertaForMultipleChoice(XLMRobertaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.classifier = nn.Linear(config.hidden_size, 1)
+
+ self.roberta = XLMRobertaModel(config, add_pooling_layer=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | MultipleChoiceModelOutput:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
+ `input_ids` above)
+ position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ """
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
+
+ flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
+ flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
+ flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
+ flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
+ flat_inputs_embeds = (
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
+ if inputs_embeds is not None
+ else None
+ )
+
+ outputs = self.roberta(
+ flat_input_ids,
+ position_ids=flat_position_ids,
+ token_type_ids=flat_token_type_ids,
+ attention_mask=flat_attention_mask,
+ inputs_embeds=flat_inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+ pooled_output = outputs[1]
+
+ pooled_output = self.dropout(pooled_output)
+ logits = self.classifier(pooled_output)
+ reshaped_logits = logits.view(-1, num_choices)
+
+ loss = None
+ if labels is not None:
+ # move labels to correct device
+ labels = labels.to(reshaped_logits.device)
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(reshaped_logits, labels)
+
+ return MultipleChoiceModelOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class XLMRobertaForTokenClassification(XLMRobertaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ self.roberta = XLMRobertaModel(config, add_pooling_layer=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | TokenClassifierOutput:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+
+ sequence_output = self.dropout(sequence_output)
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ # move labels to correct device
+ labels = labels.to(logits.device)
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class XLMRobertaForQuestionAnswering(XLMRobertaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
+
+ self.roberta = XLMRobertaModel(config, add_pooling_layer=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ start_positions: torch.LongTensor | None = None,
+ end_positions: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | QuestionAnsweringModelOutput:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1).contiguous()
+ end_logits = end_logits.squeeze(-1).contiguous()
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ return QuestionAnsweringModelOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "XLMRobertaForCausalLM",
+ "XLMRobertaForMaskedLM",
+ "XLMRobertaForMultipleChoice",
+ "XLMRobertaForQuestionAnswering",
+ "XLMRobertaForSequenceClassification",
+ "XLMRobertaForTokenClassification",
+ "XLMRobertaModel",
+ "XLMRobertaPreTrainedModel",
+]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/modular_xlm_roberta.py b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/modular_xlm_roberta.py
new file mode 100644
index 0000000000000000000000000000000000000000..f9404c0d79934eaa293705273c2b69aca82c9e95
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/modular_xlm_roberta.py
@@ -0,0 +1,550 @@
+# Copyright 2019 Facebook AI Research and the HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch XLM-RoBERTa model."""
+
+import torch
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ...modeling_outputs import (
+ BaseModelOutputWithPoolingAndCrossAttentions,
+ CausalLMOutputWithCrossAttentions,
+ MaskedLMOutput,
+ MultipleChoiceModelOutput,
+ QuestionAnsweringModelOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+)
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring
+from ...utils.generic import can_return_tuple
+from ..roberta.modeling_roberta import (
+ RobertaForCausalLM,
+ RobertaForMaskedLM,
+ RobertaForMultipleChoice,
+ RobertaForQuestionAnswering,
+ RobertaForSequenceClassification,
+ RobertaForTokenClassification,
+ RobertaModel,
+ RobertaPreTrainedModel,
+)
+
+
+@auto_docstring
+class XLMRobertaPreTrainedModel(RobertaPreTrainedModel):
+ base_model_prefix = "roberta"
+
+
+@auto_docstring
+class XLMRobertaModel(RobertaModel):
+ pass
+
+
+@auto_docstring(
+ custom_intro="""
+ XLM-RoBERTa Model with a `language modeling` head on top for CLM fine-tuning.
+ """
+)
+class XLMRobertaForCausalLM(RobertaForCausalLM):
+ _tied_weights_keys = {
+ "lm_head.decoder.weight": "roberta.embeddings.word_embeddings.weight",
+ "lm_head.decoder.bias": "lm_head.bias",
+ }
+
+ def __init__(self, config):
+ super().__init__(config)
+ del self.xlm_roberta
+ self.roberta = XLMRobertaModel(config, add_pooling_layer=False)
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ past_key_values: tuple[tuple[torch.FloatTensor]] | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | CausalLMOutputWithCrossAttentions:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
+ ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, XLMRobertaForCausalLM, AutoConfig
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("FacebookAI/roberta-base")
+ >>> config = AutoConfig.from_pretrained("FacebookAI/roberta-base")
+ >>> config.is_decoder = True
+ >>> model = XLMRobertaForCausalLM.from_pretrained("FacebookAI/roberta-base", config=config)
+
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
+ >>> outputs = model(**inputs)
+
+ >>> prediction_logits = outputs.logits
+ ```"""
+ if labels is not None:
+ use_cache = False
+
+ outputs: BaseModelOutputWithPoolingAndCrossAttentions = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ return_dict=True,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return CausalLMOutputWithCrossAttentions(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+
+@auto_docstring
+class XLMRobertaForMaskedLM(RobertaForMaskedLM):
+ _tied_weights_keys = {
+ "lm_head.decoder.weight": "roberta.embeddings.word_embeddings.weight",
+ "lm_head.decoder.bias": "lm_head.bias",
+ }
+
+ def __init__(self, config):
+ super().__init__(config)
+ del self.xlm_roberta
+
+ self.roberta = XLMRobertaModel(config, add_pooling_layer=False)
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | MaskedLMOutput:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ return_dict=True,
+ **kwargs,
+ )
+ sequence_output = outputs[0]
+ prediction_scores = self.lm_head(sequence_output)
+
+ masked_lm_loss = None
+ if labels is not None:
+ # move labels to correct device
+ labels = labels.to(prediction_scores.device)
+ loss_fct = CrossEntropyLoss()
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
+
+ return MaskedLMOutput(
+ loss=masked_lm_loss,
+ logits=prediction_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ XLM-RoBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the
+ pooled output) e.g. for GLUE tasks.
+ """
+)
+class XLMRobertaForSequenceClassification(RobertaForSequenceClassification):
+ def __init__(self, config):
+ super().__init__(config)
+ del self.xlm_roberta
+
+ self.roberta = XLMRobertaModel(config, add_pooling_layer=False)
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | SequenceClassifierOutput:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+ sequence_output = outputs[0]
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ # move labels to correct device
+ labels = labels.to(logits.device)
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class XLMRobertaForMultipleChoice(RobertaForMultipleChoice):
+ def __init__(self, config):
+ super().__init__(config)
+ del self.xlm_roberta
+
+ self.roberta = XLMRobertaModel(config, add_pooling_layer=False)
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | MultipleChoiceModelOutput:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
+ `input_ids` above)
+ position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ """
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
+
+ flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
+ flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
+ flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
+ flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
+ flat_inputs_embeds = (
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
+ if inputs_embeds is not None
+ else None
+ )
+
+ outputs = self.roberta(
+ flat_input_ids,
+ position_ids=flat_position_ids,
+ token_type_ids=flat_token_type_ids,
+ attention_mask=flat_attention_mask,
+ inputs_embeds=flat_inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+ pooled_output = outputs[1]
+
+ pooled_output = self.dropout(pooled_output)
+ logits = self.classifier(pooled_output)
+ reshaped_logits = logits.view(-1, num_choices)
+
+ loss = None
+ if labels is not None:
+ # move labels to correct device
+ labels = labels.to(reshaped_logits.device)
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(reshaped_logits, labels)
+
+ return MultipleChoiceModelOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class XLMRobertaForTokenClassification(RobertaForTokenClassification):
+ def __init__(self, config):
+ super().__init__(config)
+ del self.xlm_roberta
+
+ self.roberta = XLMRobertaModel(config, add_pooling_layer=False)
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | TokenClassifierOutput:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+
+ sequence_output = self.dropout(sequence_output)
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ # move labels to correct device
+ labels = labels.to(logits.device)
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class XLMRobertaForQuestionAnswering(RobertaForQuestionAnswering):
+ def __init__(self, config):
+ super().__init__(config)
+ del self.xlm_roberta
+
+ self.roberta = XLMRobertaModel(config, add_pooling_layer=False)
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ start_positions: torch.LongTensor | None = None,
+ end_positions: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | QuestionAnsweringModelOutput:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1).contiguous()
+ end_logits = end_logits.squeeze(-1).contiguous()
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ return QuestionAnsweringModelOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "XLMRobertaForCausalLM",
+ "XLMRobertaForMaskedLM",
+ "XLMRobertaForMultipleChoice",
+ "XLMRobertaForQuestionAnswering",
+ "XLMRobertaForSequenceClassification",
+ "XLMRobertaForTokenClassification",
+ "XLMRobertaModel",
+ "XLMRobertaPreTrainedModel",
+]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/tokenization_xlm_roberta.py b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/tokenization_xlm_roberta.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0339e408c2af5fdbb895cabf92d7900759a7421
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/tokenization_xlm_roberta.py
@@ -0,0 +1,116 @@
+# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License
+"""Tokenization classes for XLM-RoBERTa model (Tokenizers backend)."""
+
+from tokenizers import Tokenizer, decoders, normalizers, pre_tokenizers, processors
+from tokenizers.models import Unigram
+
+from ...tokenization_utils_tokenizers import TokenizersBackend
+from ...utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"}
+
+
+class XLMRobertaTokenizer(TokenizersBackend):
+ r"""
+ Construct an XLM-RoBERTa tokenizer (backed by HuggingFace's tokenizers library). Based on SentencePiece.
+
+ This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should refer to
+ this superclass for more information regarding those methods.
+
+ Args:
+ vocab_file (`str`, optional): Path to the vocabulary file.
+ merges_file (`str`, optional): Path to the merges file.
+ tokenizer_file (`str`, optional): Path to a tokenizers JSON file containing the serialization of a tokenizer.
+ bos_token (`str`, optional, defaults to `""`): The beginning of sequence token.
+ eos_token (`str`, optional, defaults to `""`): The end of sequence token.
+ sep_token (`str`, optional, defaults to `""`): The separator token.
+ cls_token (`str`, optional, defaults to `""`): The classifier token.
+ unk_token (`str`, optional, defaults to `""`): The unknown token.
+ pad_token (`str`, optional, defaults to `""`): The padding token.
+ mask_token (`str`, optional, defaults to `""`): The mask token.
+ add_prefix_space (`bool`, optional, defaults to `True`): Whether to add an initial space.
+ vocab (`str`, `dict` or `list`, optional): Custom vocabulary dictionary.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ model_input_names = ["input_ids", "attention_mask"]
+ model = Unigram
+
+ def __init__(
+ self,
+ vocab: str | list[tuple[str, float]] | None = None,
+ add_prefix_space: bool = True,
+ bos_token: str = "",
+ eos_token: str = "",
+ sep_token: str = "",
+ cls_token: str = "",
+ unk_token: str = "",
+ pad_token: str = "",
+ mask_token: str = "",
+ _spm_precompiled_charsmap: str | None = None,
+ **kwargs,
+ ):
+ self.add_prefix_space = add_prefix_space
+
+ if vocab is not None:
+ self._vocab = vocab
+ else:
+ self._vocab = [
+ (str(bos_token), 0.0),
+ (str(pad_token), 0.0),
+ (str(eos_token), 0.0),
+ (str(unk_token), 0.0),
+ (str(mask_token), 0.0),
+ ]
+
+ self._tokenizer = Tokenizer(Unigram(vocab=self._vocab, unk_id=3, byte_fallback=False))
+
+ if _spm_precompiled_charsmap is not None:
+ self._tokenizer.normalizer = normalizers.Precompiled(_spm_precompiled_charsmap)
+
+ prepend_scheme = "always" if add_prefix_space else "never"
+ self._tokenizer.pre_tokenizer = pre_tokenizers.Sequence(
+ [
+ pre_tokenizers.WhitespaceSplit(),
+ pre_tokenizers.Metaspace(replacement="▁", prepend_scheme=prepend_scheme),
+ ]
+ )
+ self._tokenizer.decoder = decoders.Metaspace(replacement="▁", prepend_scheme=prepend_scheme)
+ super().__init__(
+ bos_token=bos_token,
+ eos_token=eos_token,
+ sep_token=sep_token,
+ cls_token=cls_token,
+ unk_token=unk_token,
+ pad_token=pad_token,
+ mask_token=mask_token,
+ add_prefix_space=add_prefix_space,
+ **kwargs,
+ )
+
+ self._tokenizer.post_processor = processors.TemplateProcessing(
+ single=[str(bos_token), "$A", str(eos_token)],
+ pair=[str(bos_token), "$A", str(eos_token), str(eos_token), "$B", str(eos_token)],
+ special_tokens=[
+ (str(bos_token), self.bos_token_id),
+ (str(eos_token), self.eos_token_id),
+ ],
+ )
+
+
+__all__ = ["XLMRobertaTokenizer"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/__init__.py b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..57aaceadacea8342c64364f5b712089228a0ab66
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_xlm_roberta_xl import *
+ from .modeling_xlm_roberta_xl import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..308ca00a191aad9fed623e9e35f1b087269f6739
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/__pycache__/configuration_xlm_roberta_xl.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/__pycache__/configuration_xlm_roberta_xl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e244f89fc2a9844ef889148c839544d0ebf8c115
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/__pycache__/configuration_xlm_roberta_xl.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/__pycache__/modeling_xlm_roberta_xl.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/__pycache__/modeling_xlm_roberta_xl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1022fc231fab9f72268cf43b65cebbeb7e3ddf39
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/__pycache__/modeling_xlm_roberta_xl.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/__pycache__/modular_xlm_roberta_xl.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/__pycache__/modular_xlm_roberta_xl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ca4cdf0bca71965403655d6a58c625b62d90a610
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/__pycache__/modular_xlm_roberta_xl.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/configuration_xlm_roberta_xl.py b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/configuration_xlm_roberta_xl.py
new file mode 100644
index 0000000000000000000000000000000000000000..b6c128a58fcc37d0112a3f152cbd7a15b635c0dc
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/configuration_xlm_roberta_xl.py
@@ -0,0 +1,65 @@
+# Copyright 2022 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""XLM_ROBERTa_XL configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="FacebookAI/xlm-roberta-xl")
+@strict
+class XLMRobertaXLConfig(PreTrainedConfig):
+ r"""
+ Examples:
+
+ ```python
+ >>> from transformers import XLMRobertaXLConfig, XLMRobertaXLModel
+
+ >>> # Initializing a XLM_ROBERTA_XL google-bert/bert-base-uncased style configuration
+ >>> configuration = XLMRobertaXLConfig()
+
+ >>> # Initializing a model (with random weights) from the google-bert/bert-base-uncased style configuration
+ >>> model = XLMRobertaXLModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "xlm-roberta-xl"
+
+ vocab_size: int = 250880
+ hidden_size: int = 2560
+ num_hidden_layers: int = 36
+ num_attention_heads: int = 32
+ intermediate_size: int = 10240
+ hidden_act: str = "gelu"
+ hidden_dropout_prob: float | int = 0.1
+ attention_probs_dropout_prob: float | int = 0.1
+ max_position_embeddings: int = 514
+ type_vocab_size: int = 1
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-05
+ pad_token_id: int | None = 1
+ bos_token_id: int | None = 0
+ eos_token_id: int | list[int] | None = 2
+ use_cache: bool = True
+ classifier_dropout: float | int | None = None
+ is_decoder: bool = False
+ add_cross_attention: bool = False
+ tie_word_embeddings: bool = True
+
+
+__all__ = ["XLMRobertaXLConfig"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/modeling_xlm_roberta_xl.py b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/modeling_xlm_roberta_xl.py
new file mode 100644
index 0000000000000000000000000000000000000000..1234db3074b352797d389b55390a82659acb4e29
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/modeling_xlm_roberta_xl.py
@@ -0,0 +1,1219 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/xlm_roberta_xl/modular_xlm_roberta_xl.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_xlm_roberta_xl.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# coding=utf-8
+# Copyright 2022 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from collections.abc import Callable
+
+import torch
+import torch.nn as nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ... import initialization as init
+from ...activations import ACT2FN, gelu
+from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
+from ...generation import GenerationMixin
+from ...masking_utils import create_bidirectional_mask, create_causal_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutputWithPastAndCrossAttentions,
+ BaseModelOutputWithPoolingAndCrossAttentions,
+ CausalLMOutputWithCrossAttentions,
+ MaskedLMOutput,
+ MultipleChoiceModelOutput,
+ QuestionAnsweringModelOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+)
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...pytorch_utils import apply_chunking_to_forward
+from ...utils import TransformersKwargs, auto_docstring, logging
+from ...utils.generic import can_return_tuple, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_xlm_roberta_xl import XLMRobertaXLConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+class XLMRobertaXLEmbeddings(nn.Module):
+ """Construct the embeddings from word, position and token_type embeddings."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
+ self.register_buffer(
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
+ )
+ self.register_buffer(
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
+ )
+
+ self.padding_idx = config.pad_token_id
+ self.position_embeddings = nn.Embedding(
+ config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
+ )
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ past_key_values_length: int = 0,
+ ) -> torch.Tensor:
+ if position_ids is None:
+ if input_ids is not None:
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
+ position_ids = self.create_position_ids_from_input_ids(
+ input_ids, self.padding_idx, past_key_values_length
+ )
+ else:
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds, self.padding_idx)
+
+ if input_ids is not None:
+ input_shape = input_ids.size()
+ else:
+ input_shape = inputs_embeds.size()[:-1]
+
+ batch_size, seq_length = input_shape
+
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
+ # issue #5664
+ if token_type_ids is None:
+ if hasattr(self, "token_type_ids"):
+ # NOTE: We assume either pos ids to have bsz == 1 (broadcastable) or bsz == effective bsz (input_shape[0])
+ buffered_token_type_ids = self.token_type_ids.expand(position_ids.shape[0], -1)
+ buffered_token_type_ids = torch.gather(buffered_token_type_ids, dim=1, index=position_ids)
+ token_type_ids = buffered_token_type_ids.expand(batch_size, seq_length)
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
+
+ if inputs_embeds is None:
+ inputs_embeds = self.word_embeddings(input_ids)
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
+ embeddings = inputs_embeds + token_type_embeddings
+
+ position_embeddings = self.position_embeddings(position_ids)
+ embeddings = embeddings + position_embeddings
+
+ embeddings = self.dropout(embeddings)
+ return embeddings
+
+ @staticmethod
+ def create_position_ids_from_inputs_embeds(inputs_embeds, padding_idx):
+ """
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
+
+ Args:
+ inputs_embeds: torch.Tensor
+
+ Returns: torch.Tensor
+ """
+ input_shape = inputs_embeds.size()[:-1]
+ sequence_length = input_shape[1]
+
+ position_ids = torch.arange(
+ padding_idx + 1, sequence_length + padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
+ )
+ return position_ids.unsqueeze(0).expand(input_shape)
+
+ @staticmethod
+ def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
+ """
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
+ are ignored. This is modified from fairseq's `utils.make_positions`.
+
+ Args:
+ x: torch.Tensor x:
+
+ Returns: torch.Tensor
+ """
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
+ mask = input_ids.ne(padding_idx).int()
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
+ return incremental_indices.long() + padding_idx
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float | None = None,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ if scaling is None:
+ scaling = query.size(-1) ** -0.5
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
+
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+class XLMRobertaXLSelfAttention(nn.Module):
+ def __init__(self, config, is_causal=False, layer_idx=None):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({config.num_attention_heads})"
+ )
+ self.config = config
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+ self.scaling = self.attention_head_size**-0.5
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+
+ self.is_decoder = config.is_decoder
+ self.is_causal = is_causal
+ self.layer_idx = layer_idx
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
+
+ # get all proj
+ query_layer = self.query(hidden_states).view(*hidden_shape).transpose(1, 2)
+ key_layer = self.key(hidden_states).view(*hidden_shape).transpose(1, 2)
+ value_layer = self.value(hidden_states).view(*hidden_shape).transpose(1, 2)
+
+ if past_key_values is not None:
+ # decoder-only xlm_roberta_xl can have a simple dynamic cache for example
+ current_past_key_values = past_key_values
+ if isinstance(past_key_values, EncoderDecoderCache):
+ current_past_key_values = past_key_values.self_attention_cache
+
+ # save all key/value_layer to cache to be re-used for fast auto-regressive generation
+ key_layer, value_layer = current_past_key_values.update(key_layer, value_layer, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_layer,
+ key_layer,
+ value_layer,
+ attention_mask,
+ dropout=0.0 if not self.training else self.dropout.p,
+ scaling=self.scaling,
+ **kwargs,
+ )
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ return attn_output, attn_weights
+
+
+class XLMRobertaXLCrossAttention(nn.Module):
+ def __init__(self, config, is_causal=False, layer_idx=None):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({config.num_attention_heads})"
+ )
+ self.config = config
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+ self.scaling = self.attention_head_size**-0.5
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+
+ self.is_causal = is_causal
+ self.layer_idx = layer_idx
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ past_key_values: EncoderDecoderCache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor]:
+ # determine input shapes
+ input_shape = hidden_states.shape[:-1]
+
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
+
+ # get query proj
+ query_layer = self.query(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ is_updated = past_key_values.is_updated.get(self.layer_idx) if past_key_values is not None else False
+ if past_key_values is not None and is_updated:
+ # reuse k,v, cross_attentions
+ key_layer = past_key_values.cross_attention_cache.layers[self.layer_idx].keys
+ value_layer = past_key_values.cross_attention_cache.layers[self.layer_idx].values
+ else:
+ kv_shape = (*encoder_hidden_states.shape[:-1], -1, self.attention_head_size)
+ key_layer = self.key(encoder_hidden_states).view(kv_shape).transpose(1, 2)
+ value_layer = self.value(encoder_hidden_states).view(kv_shape).transpose(1, 2)
+
+ if past_key_values is not None:
+ # save all states to the cache
+ key_layer, value_layer = past_key_values.cross_attention_cache.update(
+ key_layer, value_layer, self.layer_idx
+ )
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
+ past_key_values.is_updated[self.layer_idx] = True
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_layer,
+ key_layer,
+ value_layer,
+ attention_mask,
+ dropout=0.0 if not self.training else self.dropout.p,
+ scaling=self.scaling,
+ **kwargs,
+ )
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ return attn_output, attn_weights
+
+
+class XLMRobertaXLSelfOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = hidden_states + input_tensor
+ return hidden_states
+
+
+class XLMRobertaXLAttention(nn.Module):
+ def __init__(self, config, is_causal=False, layer_idx=None, is_cross_attention=False):
+ super().__init__()
+ self.is_cross_attention = is_cross_attention
+ attention_class = XLMRobertaXLCrossAttention if is_cross_attention else XLMRobertaXLSelfAttention
+ self.self = attention_class(config, is_causal=is_causal, layer_idx=layer_idx)
+ self.output = XLMRobertaXLSelfOutput(config)
+
+ self.self_attn_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ past_key_values: tuple[tuple[torch.FloatTensor]] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor]:
+ intermediate = self.self_attn_layer_norm(hidden_states)
+ attention_mask = attention_mask if not self.is_cross_attention else encoder_attention_mask
+ attention_output, attn_weights = self.self(
+ intermediate,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ attention_output = self.output(attention_output, hidden_states)
+ return attention_output, attn_weights
+
+
+class XLMRobertaXLOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+
+ def forward(self, hidden_states, input_tensor):
+ hidden_states = self.dense(hidden_states)
+ hidden_states = hidden_states + input_tensor
+ return hidden_states
+
+
+class XLMRobertaXLIntermediate(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ return hidden_states
+
+
+class XLMRobertaXLLayer(GradientCheckpointingLayer):
+ def __init__(self, config, layer_idx=None):
+ super().__init__()
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+ self.attention = XLMRobertaXLAttention(config, is_causal=config.is_decoder, layer_idx=layer_idx)
+ self.is_decoder = config.is_decoder
+ self.add_cross_attention = config.add_cross_attention
+ if self.add_cross_attention:
+ if not self.is_decoder:
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
+ self.crossattention = XLMRobertaXLAttention(
+ config,
+ is_causal=False,
+ layer_idx=layer_idx,
+ is_cross_attention=True,
+ )
+ self.intermediate = XLMRobertaXLIntermediate(config)
+ self.output = XLMRobertaXLOutput(config)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ self_attention_output, _ = self.attention(
+ hidden_states,
+ attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ attention_output = self_attention_output
+
+ if self.is_decoder and encoder_hidden_states is not None:
+ if not hasattr(self, "crossattention"):
+ raise ValueError(
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
+ " by setting `config.add_cross_attention=True`"
+ )
+
+ cross_attention_output, _ = self.crossattention(
+ self_attention_output,
+ None, # attention_mask
+ encoder_hidden_states,
+ encoder_attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ attention_output = cross_attention_output
+
+ layer_output = apply_chunking_to_forward(
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
+ )
+ return layer_output
+
+ def feed_forward_chunk(self, attention_output):
+ intermediate_output = self.LayerNorm(attention_output)
+ intermediate_output = self.intermediate(intermediate_output)
+ layer_output = self.output(intermediate_output, attention_output)
+ return layer_output
+
+
+class XLMRobertaXLEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList([XLMRobertaXLLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPastAndCrossAttentions:
+ for i, layer_module in enumerate(self.layer):
+ hidden_states = layer_module(
+ hidden_states,
+ attention_mask,
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+
+ # Extra layernorm at the end (causes high fluctuations between different attentions)
+ hidden_states = self.LayerNorm(hidden_states)
+
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values if use_cache else None,
+ )
+
+
+@auto_docstring
+class XLMRobertaXLPreTrainedModel(PreTrainedModel):
+ config_class = XLMRobertaXLConfig
+ base_model_prefix = "roberta"
+ supports_gradient_checkpointing = True
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": XLMRobertaXLLayer,
+ "attentions": XLMRobertaXLSelfAttention,
+ "cross_attentions": XLMRobertaXLCrossAttention,
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ super()._init_weights(module)
+ if isinstance(module, XLMRobertaXLLMHead):
+ init.zeros_(module.bias)
+ elif isinstance(module, XLMRobertaXLEmbeddings):
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
+ init.zeros_(module.token_type_ids)
+
+
+class XLMRobertaXLPooler(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.activation = nn.Tanh()
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ # We "pool" the model by simply taking the hidden state corresponding
+ # to the first token.
+ first_token_tensor = hidden_states[:, 0]
+ pooled_output = self.dense(first_token_tensor)
+ pooled_output = self.activation(pooled_output)
+ return pooled_output
+
+
+@auto_docstring(
+ custom_intro="""
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
+ all you need](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
+
+ To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
+ to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
+ """
+)
+class XLMRobertaXLModel(XLMRobertaXLPreTrainedModel):
+ _no_split_modules = ["XLMRobertaXLEmbeddings", "XLMRobertaXLLayer"]
+
+ def __init__(self, config, add_pooling_layer=True):
+ r"""
+ add_pooling_layer (bool, *optional*, defaults to `True`):
+ Whether to add a pooling layer
+ """
+ super().__init__(config)
+ self.config = config
+ self.gradient_checkpointing = False
+
+ self.embeddings = XLMRobertaXLEmbeddings(config)
+ self.encoder = XLMRobertaXLEncoder(config)
+
+ self.pooler = XLMRobertaXLPooler(config) if add_pooling_layer else None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.embeddings.word_embeddings = value
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPoolingAndCrossAttentions:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if self.config.is_decoder:
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+ else:
+ use_cache = False
+
+ if use_cache and past_key_values is None:
+ past_key_values = (
+ EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
+ if encoder_hidden_states is not None or self.config.is_encoder_decoder
+ else DynamicCache(config=self.config)
+ )
+
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
+
+ embedding_output = self.embeddings(
+ input_ids=input_ids,
+ position_ids=position_ids,
+ token_type_ids=token_type_ids,
+ inputs_embeds=inputs_embeds,
+ past_key_values_length=past_key_values_length,
+ )
+
+ attention_mask, encoder_attention_mask = self._create_attention_masks(
+ attention_mask=attention_mask,
+ encoder_attention_mask=encoder_attention_mask,
+ embedding_output=embedding_output,
+ encoder_hidden_states=encoder_hidden_states,
+ past_key_values=past_key_values,
+ )
+
+ encoder_outputs = self.encoder(
+ embedding_output,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_ids=position_ids,
+ **kwargs,
+ )
+ sequence_output = encoder_outputs.last_hidden_state
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
+
+ return BaseModelOutputWithPoolingAndCrossAttentions(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ past_key_values=encoder_outputs.past_key_values,
+ )
+
+ def _create_attention_masks(
+ self,
+ attention_mask,
+ encoder_attention_mask,
+ embedding_output,
+ encoder_hidden_states,
+ past_key_values,
+ ):
+ if self.config.is_decoder:
+ attention_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ )
+ else:
+ attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=attention_mask,
+ )
+
+ if encoder_attention_mask is not None:
+ encoder_attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=encoder_attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ )
+
+ return attention_mask, encoder_attention_mask
+
+
+class XLMRobertaXLLMHead(nn.Module):
+ """XLM-RoBERTa-XL Head for masked language modeling."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
+
+ def forward(self, features, **kwargs):
+ x = self.dense(features)
+ x = gelu(x)
+ x = self.layer_norm(x)
+
+ # project back to size of vocabulary with bias
+ x = self.decoder(x)
+
+ return x
+
+
+class XLMRobertaXLClassificationHead(nn.Module):
+ """Head for sentence-level classification tasks."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
+
+ def forward(self, features, **kwargs):
+ x = features[:, 0, :] # take token (equiv. to [CLS])
+ x = self.dropout(x)
+ x = self.dense(x)
+ x = torch.tanh(x)
+ x = self.dropout(x)
+ x = self.out_proj(x)
+ return x
+
+
+@auto_docstring(
+ custom_intro="""
+ XLM-RoBERTa-XL Model with a `language modeling` head on top for CLM fine-tuning.
+ """
+)
+class XLMRobertaXLForCausalLM(XLMRobertaXLPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {
+ "lm_head.decoder.weight": "roberta.embeddings.word_embeddings.weight",
+ "lm_head.decoder.bias": "lm_head.bias",
+ }
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ if not config.is_decoder:
+ logger.warning("If you want to use `RobertaLMHeadModel` as a standalone, add `is_decoder=True.`")
+
+ self.roberta = XLMRobertaXLModel(config, add_pooling_layer=False)
+ self.lm_head = XLMRobertaXLLMHead(config)
+
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.lm_head.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head.decoder = new_embeddings
+ self.lm_head.bias = new_embeddings.bias
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ past_key_values: tuple[tuple[torch.FloatTensor]] | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | CausalLMOutputWithCrossAttentions:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
+ ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, RobertaForCausalLM, RobertaConfig
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("FacebookAI/roberta-base")
+ >>> config = RobertaConfig.from_pretrained("FacebookAI/roberta-base")
+ >>> config.is_decoder = True
+ >>> model = RobertaForCausalLM.from_pretrained("FacebookAI/roberta-base", config=config)
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
+ >>> outputs = model(**inputs)
+ >>> prediction_logits = outputs.logits
+ ```
+ """
+ if labels is not None:
+ use_cache = False
+
+ outputs: BaseModelOutputWithPoolingAndCrossAttentions = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return CausalLMOutputWithCrossAttentions(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+
+@auto_docstring
+class XLMRobertaXLForMaskedLM(XLMRobertaXLPreTrainedModel):
+ _tied_weights_keys = {
+ "lm_head.decoder.weight": "roberta.embeddings.word_embeddings.weight",
+ "lm_head.decoder.bias": "lm_head.bias",
+ }
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ if config.is_decoder:
+ logger.warning(
+ "If you want to use `RobertaForMaskedLM` make sure `config.is_decoder=False` for "
+ "bi-directional self-attention."
+ )
+
+ self.roberta = XLMRobertaXLModel(config, add_pooling_layer=False)
+ self.lm_head = XLMRobertaXLLMHead(config)
+
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.lm_head.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head.decoder = new_embeddings
+ self.lm_head.bias = new_embeddings.bias
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | MaskedLMOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ return_dict=True,
+ **kwargs,
+ )
+ sequence_output = outputs[0]
+ prediction_scores = self.lm_head(sequence_output)
+
+ masked_lm_loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
+
+ return MaskedLMOutput(
+ loss=masked_lm_loss,
+ logits=prediction_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ XLM-RoBERTa-XL Model transformer with a sequence classification/regression head on top (a linear layer on top
+ of the pooled output) e.g. for GLUE tasks.
+ """
+)
+class XLMRobertaXLForSequenceClassification(XLMRobertaXLPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.config = config
+
+ self.roberta = XLMRobertaXLModel(config, add_pooling_layer=False)
+ self.classifier = XLMRobertaXLClassificationHead(config)
+
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | SequenceClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+ sequence_output = outputs[0]
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class XLMRobertaXLForMultipleChoice(XLMRobertaXLPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.roberta = XLMRobertaXLModel(config)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.classifier = nn.Linear(config.hidden_size, 1)
+
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | MultipleChoiceModelOutput:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See
+ [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input
+ IDs?](../glossary#input-ids)
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
+ 1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
+ `input_ids` above)
+ position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`. [What are position IDs?](../glossary#position-ids)
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ """
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
+
+ flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
+ flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
+ flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
+ flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
+ flat_inputs_embeds = (
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
+ if inputs_embeds is not None
+ else None
+ )
+
+ outputs = self.roberta(
+ flat_input_ids,
+ position_ids=flat_position_ids,
+ token_type_ids=flat_token_type_ids,
+ attention_mask=flat_attention_mask,
+ inputs_embeds=flat_inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+ pooled_output = outputs[1]
+
+ pooled_output = self.dropout(pooled_output)
+ logits = self.classifier(pooled_output)
+ reshaped_logits = logits.view(-1, num_choices)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(reshaped_logits, labels)
+
+ return MultipleChoiceModelOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class XLMRobertaXLForTokenClassification(XLMRobertaXLPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.roberta = XLMRobertaXLModel(config, add_pooling_layer=False)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | TokenClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+
+ sequence_output = self.dropout(sequence_output)
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ # Only keep active parts of the loss
+ if attention_mask is not None:
+ active_loss = attention_mask.view(-1) == 1
+ active_logits = logits.view(-1, self.num_labels)
+ active_labels = torch.where(
+ active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels)
+ )
+ loss = loss_fct(active_logits, active_labels)
+ else:
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class XLMRobertaXLForQuestionAnswering(XLMRobertaXLPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.roberta = XLMRobertaXLModel(config, add_pooling_layer=False)
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
+
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ start_positions: torch.LongTensor | None = None,
+ end_positions: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | QuestionAnsweringModelOutput:
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1).contiguous()
+ end_logits = end_logits.squeeze(-1).contiguous()
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ return QuestionAnsweringModelOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "XLMRobertaXLForCausalLM",
+ "XLMRobertaXLForMaskedLM",
+ "XLMRobertaXLForMultipleChoice",
+ "XLMRobertaXLForQuestionAnswering",
+ "XLMRobertaXLForSequenceClassification",
+ "XLMRobertaXLForTokenClassification",
+ "XLMRobertaXLModel",
+ "XLMRobertaXLPreTrainedModel",
+]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/modular_xlm_roberta_xl.py b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/modular_xlm_roberta_xl.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c6e5cd8d5fc8e852a8695a19c6e41c656d5c6a7
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/modular_xlm_roberta_xl.py
@@ -0,0 +1,742 @@
+# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# coding=utf-8
+# Copyright 2022 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch XLM RoBERTa xl,xxl model."""
+
+import torch
+import torch.nn as nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ...activations import gelu
+from ...cache_utils import Cache
+from ...generation import GenerationMixin
+from ...modeling_outputs import (
+ BaseModelOutputWithPastAndCrossAttentions,
+ BaseModelOutputWithPoolingAndCrossAttentions,
+ CausalLMOutputWithCrossAttentions,
+ MaskedLMOutput,
+ MultipleChoiceModelOutput,
+ QuestionAnsweringModelOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+)
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, logging
+from ...utils.generic import can_return_tuple
+from ..bert.modeling_bert import (
+ BertAttention,
+ BertCrossAttention,
+ BertLayer,
+ BertModel,
+ BertSelfAttention,
+)
+from ..roberta.modeling_roberta import (
+ RobertaClassificationHead,
+ RobertaEmbeddings,
+ RobertaPreTrainedModel,
+)
+
+
+logger = logging.get_logger(__name__)
+
+
+class XLMRobertaXLEmbeddings(RobertaEmbeddings):
+ def __init__(self, config):
+ super().__init__(config)
+ del self.LayerNorm
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ past_key_values_length: int = 0,
+ ) -> torch.Tensor:
+ if position_ids is None:
+ if input_ids is not None:
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
+ position_ids = self.create_position_ids_from_input_ids(
+ input_ids, self.padding_idx, past_key_values_length
+ )
+ else:
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds, self.padding_idx)
+
+ if input_ids is not None:
+ input_shape = input_ids.size()
+ else:
+ input_shape = inputs_embeds.size()[:-1]
+
+ batch_size, seq_length = input_shape
+
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
+ # issue #5664
+ if token_type_ids is None:
+ if hasattr(self, "token_type_ids"):
+ # NOTE: We assume either pos ids to have bsz == 1 (broadcastable) or bsz == effective bsz (input_shape[0])
+ buffered_token_type_ids = self.token_type_ids.expand(position_ids.shape[0], -1)
+ buffered_token_type_ids = torch.gather(buffered_token_type_ids, dim=1, index=position_ids)
+ token_type_ids = buffered_token_type_ids.expand(batch_size, seq_length)
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
+
+ if inputs_embeds is None:
+ inputs_embeds = self.word_embeddings(input_ids)
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
+ embeddings = inputs_embeds + token_type_embeddings
+
+ position_embeddings = self.position_embeddings(position_ids)
+ embeddings = embeddings + position_embeddings
+
+ embeddings = self.dropout(embeddings)
+ return embeddings
+
+
+class XLMRobertaXLSelfAttention(BertSelfAttention):
+ pass
+
+
+class XLMRobertaXLCrossAttention(BertCrossAttention):
+ pass
+
+
+class XLMRobertaXLSelfOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = hidden_states + input_tensor
+ return hidden_states
+
+
+class XLMRobertaXLAttention(BertAttention):
+ def __init__(self, config, is_causal=False, layer_idx=None, is_cross_attention=False):
+ super().__init__(config, is_causal, layer_idx, is_cross_attention)
+ del self.LayerNorm
+
+ self.self_attn_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ past_key_values: tuple[tuple[torch.FloatTensor]] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor]:
+ intermediate = self.self_attn_layer_norm(hidden_states)
+ attention_mask = attention_mask if not self.is_cross_attention else encoder_attention_mask
+ attention_output, attn_weights = self.self(
+ intermediate,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ attention_output = self.output(attention_output, hidden_states)
+ return attention_output, attn_weights
+
+
+class XLMRobertaXLOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+
+ def forward(self, hidden_states, input_tensor):
+ hidden_states = self.dense(hidden_states)
+ hidden_states = hidden_states + input_tensor
+ return hidden_states
+
+
+class XLMRobertaXLLayer(BertLayer):
+ def __init__(self, config, layer_idx=None):
+ super().__init__(config, layer_idx)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def feed_forward_chunk(self, attention_output):
+ intermediate_output = self.LayerNorm(attention_output)
+ intermediate_output = self.intermediate(intermediate_output)
+ layer_output = self.output(intermediate_output, attention_output)
+ return layer_output
+
+
+class XLMRobertaXLEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList([XLMRobertaXLLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPastAndCrossAttentions:
+ for i, layer_module in enumerate(self.layer):
+ hidden_states = layer_module(
+ hidden_states,
+ attention_mask,
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+
+ # Extra layernorm at the end (causes high fluctuations between different attentions)
+ hidden_states = self.LayerNorm(hidden_states)
+
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values if use_cache else None,
+ )
+
+
+@auto_docstring
+class XLMRobertaXLPreTrainedModel(RobertaPreTrainedModel):
+ base_model_prefix = "roberta"
+
+
+class XLMRobertaXLModel(BertModel):
+ pass
+
+
+class XLMRobertaXLLMHead(nn.Module):
+ """XLM-RoBERTa-XL Head for masked language modeling."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
+
+ def forward(self, features, **kwargs):
+ x = self.dense(features)
+ x = gelu(x)
+ x = self.layer_norm(x)
+
+ # project back to size of vocabulary with bias
+ x = self.decoder(x)
+
+ return x
+
+
+class XLMRobertaXLClassificationHead(RobertaClassificationHead):
+ pass
+
+
+@auto_docstring(
+ custom_intro="""
+ XLM-RoBERTa-XL Model with a `language modeling` head on top for CLM fine-tuning.
+ """
+)
+class XLMRobertaXLForCausalLM(XLMRobertaXLPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {
+ "lm_head.decoder.weight": "roberta.embeddings.word_embeddings.weight",
+ "lm_head.decoder.bias": "lm_head.bias",
+ }
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ if not config.is_decoder:
+ logger.warning("If you want to use `RobertaLMHeadModel` as a standalone, add `is_decoder=True.`")
+
+ self.roberta = XLMRobertaXLModel(config, add_pooling_layer=False)
+ self.lm_head = XLMRobertaXLLMHead(config)
+
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.lm_head.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head.decoder = new_embeddings
+ self.lm_head.bias = new_embeddings.bias
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ past_key_values: tuple[tuple[torch.FloatTensor]] | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | CausalLMOutputWithCrossAttentions:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
+ ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, RobertaForCausalLM, RobertaConfig
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("FacebookAI/roberta-base")
+ >>> config = RobertaConfig.from_pretrained("FacebookAI/roberta-base")
+ >>> config.is_decoder = True
+ >>> model = RobertaForCausalLM.from_pretrained("FacebookAI/roberta-base", config=config)
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
+ >>> outputs = model(**inputs)
+ >>> prediction_logits = outputs.logits
+ ```
+ """
+ if labels is not None:
+ use_cache = False
+
+ outputs: BaseModelOutputWithPoolingAndCrossAttentions = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return CausalLMOutputWithCrossAttentions(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+
+@auto_docstring
+class XLMRobertaXLForMaskedLM(XLMRobertaXLPreTrainedModel):
+ _tied_weights_keys = {
+ "lm_head.decoder.weight": "roberta.embeddings.word_embeddings.weight",
+ "lm_head.decoder.bias": "lm_head.bias",
+ }
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ if config.is_decoder:
+ logger.warning(
+ "If you want to use `RobertaForMaskedLM` make sure `config.is_decoder=False` for "
+ "bi-directional self-attention."
+ )
+
+ self.roberta = XLMRobertaXLModel(config, add_pooling_layer=False)
+ self.lm_head = XLMRobertaXLLMHead(config)
+
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.lm_head.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head.decoder = new_embeddings
+ self.lm_head.bias = new_embeddings.bias
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | MaskedLMOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ return_dict=True,
+ **kwargs,
+ )
+ sequence_output = outputs[0]
+ prediction_scores = self.lm_head(sequence_output)
+
+ masked_lm_loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
+
+ return MaskedLMOutput(
+ loss=masked_lm_loss,
+ logits=prediction_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ XLM-RoBERTa-XL Model transformer with a sequence classification/regression head on top (a linear layer on top
+ of the pooled output) e.g. for GLUE tasks.
+ """
+)
+class XLMRobertaXLForSequenceClassification(XLMRobertaXLPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.config = config
+
+ self.roberta = XLMRobertaXLModel(config, add_pooling_layer=False)
+ self.classifier = XLMRobertaXLClassificationHead(config)
+
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | SequenceClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+ sequence_output = outputs[0]
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class XLMRobertaXLForMultipleChoice(XLMRobertaXLPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.roberta = XLMRobertaXLModel(config)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.classifier = nn.Linear(config.hidden_size, 1)
+
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | MultipleChoiceModelOutput:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See
+ [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input
+ IDs?](../glossary#input-ids)
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
+ 1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
+ `input_ids` above)
+ position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`. [What are position IDs?](../glossary#position-ids)
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ """
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
+
+ flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
+ flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
+ flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
+ flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
+ flat_inputs_embeds = (
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
+ if inputs_embeds is not None
+ else None
+ )
+
+ outputs = self.roberta(
+ flat_input_ids,
+ position_ids=flat_position_ids,
+ token_type_ids=flat_token_type_ids,
+ attention_mask=flat_attention_mask,
+ inputs_embeds=flat_inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+ pooled_output = outputs[1]
+
+ pooled_output = self.dropout(pooled_output)
+ logits = self.classifier(pooled_output)
+ reshaped_logits = logits.view(-1, num_choices)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(reshaped_logits, labels)
+
+ return MultipleChoiceModelOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class XLMRobertaXLForTokenClassification(XLMRobertaXLPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.roberta = XLMRobertaXLModel(config, add_pooling_layer=False)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | TokenClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+
+ sequence_output = self.dropout(sequence_output)
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ # Only keep active parts of the loss
+ if attention_mask is not None:
+ active_loss = attention_mask.view(-1) == 1
+ active_logits = logits.view(-1, self.num_labels)
+ active_labels = torch.where(
+ active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels)
+ )
+ loss = loss_fct(active_logits, active_labels)
+ else:
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class XLMRobertaXLForQuestionAnswering(XLMRobertaXLPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.roberta = XLMRobertaXLModel(config, add_pooling_layer=False)
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
+
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ start_positions: torch.LongTensor | None = None,
+ end_positions: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | QuestionAnsweringModelOutput:
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1).contiguous()
+ end_logits = end_logits.squeeze(-1).contiguous()
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ return QuestionAnsweringModelOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "XLMRobertaXLForCausalLM",
+ "XLMRobertaXLForMaskedLM",
+ "XLMRobertaXLForMultipleChoice",
+ "XLMRobertaXLForQuestionAnswering",
+ "XLMRobertaXLForSequenceClassification",
+ "XLMRobertaXLForTokenClassification",
+ "XLMRobertaXLModel",
+ "XLMRobertaXLPreTrainedModel",
+]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlnet/__init__.py b/.venv/lib/python3.12/site-packages/transformers/models/xlnet/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5734b98957c6e6424f41f839592fbf9c21bfc40f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xlnet/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_xlnet import *
+ from .modeling_xlnet import *
+ from .tokenization_xlnet import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlnet/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xlnet/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2ff72f305a89197f03fb82499c9341c6ff85faa1
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xlnet/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlnet/__pycache__/configuration_xlnet.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xlnet/__pycache__/configuration_xlnet.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..78dc7fc81e57c6a1b321517e4e07851f39fc882c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xlnet/__pycache__/configuration_xlnet.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlnet/__pycache__/modeling_xlnet.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xlnet/__pycache__/modeling_xlnet.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2d6b95160b41c66d859c2f0abe0b4735a07fca7f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xlnet/__pycache__/modeling_xlnet.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:42e47262a3870db70b9911a5d9fc71e1a4fa0092c59d458107bd4483554e7fd9
+size 100942
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlnet/__pycache__/tokenization_xlnet.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xlnet/__pycache__/tokenization_xlnet.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..889f22a42b4e0136d75361edddc50a68e1220474
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xlnet/__pycache__/tokenization_xlnet.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlnet/configuration_xlnet.py b/.venv/lib/python3.12/site-packages/transformers/models/xlnet/configuration_xlnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..24fc0cbb6f96c152d1a6cbf310068090b0b7a2e1
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xlnet/configuration_xlnet.py
@@ -0,0 +1,161 @@
+# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""XLNet configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring, logging
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(checkpoint="xlnet/xlnet-large-cased")
+@strict
+class XLNetConfig(PreTrainedConfig):
+ r"""
+ ff_activation (`str` or `Callable`, *optional*, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the If string, `"gelu"`, `"relu"`, `"silu"` and
+ `"gelu_new"` are supported.
+ attn_type (`str`, *optional*, defaults to `"bi"`):
+ The attention type used by the model. Set `"bi"` for XLNet, `"uni"` for Transformer-XL.
+ mem_len (`int` or `None`, *optional*):
+ The number of tokens to cache. The key/value pairs that have already been pre-computed in a previous
+ forward pass won't be re-computed. See the
+ [quickstart](https://huggingface.co/transformers/quickstart.html#using-the-past) for more information.
+ reuse_len (`int`, *optional*):
+ The number of tokens in the current batch to be cached and reused in the future.
+ use_mems_eval (`bool`, *optional*, defaults to `True`):
+ Whether or not the model should make use of the recurrent memory mechanism in evaluation mode.
+ use_mems_train (`bool`, *optional*, defaults to `False`):
+ Whether or not the model should make use of the recurrent memory mechanism in train mode.
+
+ For pretraining, it is recommended to set `use_mems_train` to `True`. For fine-tuning, it is recommended to
+ set `use_mems_train` to `False` as discussed
+ [here](https://github.com/zihangdai/xlnet/issues/41#issuecomment-505102587). If `use_mems_train` is set to
+ `True`, one has to make sure that the train batches are correctly pre-processed, *e.g.* `batch_1 = [[This
+ line is], [This is the]]` and `batch_2 = [[ the first line], [ second line]]` and that all batches are of
+ equal size.
+
+ bi_data (`bool`, *optional*, defaults to `False`):
+ Whether or not to use bidirectional input pipeline. Usually set to `True` during pretraining and `False`
+ during finetuning.
+ clamp_len (`int`, *optional*, defaults to -1):
+ Clamp all relative distances larger than clamp_len. Setting this attribute to -1 means no clamping.
+ same_length (`bool`, *optional*, defaults to `False`):
+ Whether or not to use the same attention length for each token.
+ summary_type (`str`, *optional*, defaults to "last"):
+ Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.
+ Has to be one of the following options:
+ - `"last"`: Take the last token hidden state (like XLNet).
+ - `"first"`: Take the first token hidden state (like BERT).
+ - `"mean"`: Take the mean of all tokens hidden states.
+ - `"cls_index"`: Supply a Tensor of classification token position (like GPT/GPT-2).
+ - `"attn"`: Not implemented now, use multi-head attention.
+ summary_use_proj (`bool`, *optional*, defaults to `True`):
+ Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.
+ Whether or not to add a projection after the vector extraction.
+ summary_activation (`str`, *optional*):
+ Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.
+ Pass `"tanh"` for a tanh activation to the output, any other value will result in no activation.
+ summary_last_dropout (`float`, *optional*, defaults to 0.1):
+ Used in the sequence classification and multiple choice models.
+ The dropout ratio to be used after the projection and activation.
+ start_n_top (`int`, *optional*, defaults to 5):
+ Used in the SQuAD evaluation script.
+ end_n_top (`int`, *optional*, defaults to 5):
+ Used in the SQuAD evaluation script.
+
+ Examples:
+
+ ```python
+ >>> from transformers import XLNetConfig, XLNetModel
+
+ >>> # Initializing a XLNet configuration
+ >>> configuration = XLNetConfig()
+
+ >>> # Initializing a model (with random weights) from the configuration
+ >>> model = XLNetModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "xlnet"
+ keys_to_ignore_at_inference = ["mems"]
+ attribute_map = {
+ "n_token": "vocab_size", # Backward compatibility
+ "hidden_size": "d_model",
+ "num_attention_heads": "n_head",
+ "num_hidden_layers": "n_layer",
+ }
+
+ vocab_size: int = 32000
+ d_model: int = 1024
+ n_layer: int = 24
+ n_head: int = 16
+ d_inner: int = 4096
+ d_head: int | None = None
+ ff_activation: str = "gelu"
+ attn_type: str = "bi"
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-12
+ dropout: float | int = 0.1
+ mem_len: int | None = 512
+ reuse_len: int | None = None
+ use_mems_eval: bool = True
+ use_mems_train: bool = False
+ bi_data: bool = False
+ clamp_len: int = -1
+ same_length: bool = False
+ summary_type: str = "last"
+ summary_use_proj: bool = True
+ summary_activation: str = "tanh"
+ summary_last_dropout: float | int = 0.1
+ start_n_top: int = 5
+ end_n_top: int = 5
+ pad_token_id: int | None = 5
+ bos_token_id: int | None = 1
+ eos_token_id: int | list[int] | None = 2
+ tie_word_embeddings: bool = True
+
+ def __post_init__(self, **kwargs):
+ self.d_head = self.d_head or self.d_model // self.n_head
+ super().__post_init__(**kwargs)
+
+ def validate_architecture(self):
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
+ if self.d_model % self.n_head != 0:
+ raise ValueError(f"'d_model % n_head' ({self.d_model % self.n_head}) should be equal to 0")
+ if self.d_head != self.d_model // self.n_head:
+ raise ValueError(
+ f"`d_head` ({self.d_head}) should be equal to `d_model // n_head` ({self.d_model // self.n_head})"
+ )
+
+ @property
+ def max_position_embeddings(self):
+ logger.info(f"The model {self.model_type} is one of the few models that has no sequence length limit.")
+ return -1
+
+ @max_position_embeddings.setter
+ def max_position_embeddings(self, value):
+ # Message copied from Transformer-XL documentation
+ raise NotImplementedError(
+ f"The model {self.model_type} is one of the few models that has no sequence length limit."
+ )
+
+
+__all__ = ["XLNetConfig"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlnet/modeling_xlnet.py b/.venv/lib/python3.12/site-packages/transformers/models/xlnet/modeling_xlnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce29b5dea44b7d506f9293f403f951fe76afe6cd
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xlnet/modeling_xlnet.py
@@ -0,0 +1,2171 @@
+# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+PyTorch XLNet model.
+"""
+
+from collections.abc import Callable
+from dataclasses import dataclass
+
+import torch
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ... import initialization as init
+from ...activations import ACT2FN, get_activation
+from ...generation import GenerationMixin
+from ...modeling_utils import PreTrainedModel
+from ...pytorch_utils import apply_chunking_to_forward
+from ...utils import ModelOutput, auto_docstring, logging
+from .configuration_xlnet import XLNetConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+class XLNetRelativeAttention(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+
+ if config.d_model % config.n_head != 0:
+ raise ValueError(
+ f"The hidden size ({config.d_model}) is not a multiple of the number of attention "
+ f"heads ({config.n_head}"
+ )
+
+ self.n_head = config.n_head
+ self.d_head = config.d_head
+ self.d_model = config.d_model
+ self.scale = 1 / (config.d_head**0.5)
+
+ self.q = nn.Parameter(torch.FloatTensor(config.d_model, self.n_head, self.d_head))
+ self.k = nn.Parameter(torch.FloatTensor(config.d_model, self.n_head, self.d_head))
+ self.v = nn.Parameter(torch.FloatTensor(config.d_model, self.n_head, self.d_head))
+ self.o = nn.Parameter(torch.FloatTensor(config.d_model, self.n_head, self.d_head))
+ self.r = nn.Parameter(torch.FloatTensor(config.d_model, self.n_head, self.d_head))
+
+ self.r_r_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
+ self.r_s_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
+ self.r_w_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
+ self.seg_embed = nn.Parameter(torch.FloatTensor(2, self.n_head, self.d_head))
+
+ self.layer_norm = nn.LayerNorm(config.d_model, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.dropout)
+
+ @staticmethod
+ def rel_shift(x, klen=-1):
+ """perform relative shift to form the relative attention score."""
+ x_size = x.shape
+
+ x = x.reshape(x_size[1], x_size[0], x_size[2], x_size[3])
+ x = x[1:, ...]
+ x = x.reshape(x_size[0], x_size[1] - 1, x_size[2], x_size[3])
+ # x = x[:, 0:klen, :, :]
+ x = torch.index_select(x, 1, torch.arange(klen, device=x.device, dtype=torch.long))
+
+ return x
+
+ @staticmethod
+ def rel_shift_bnij(x, klen=-1):
+ x_size = x.shape
+
+ x = x.reshape(x_size[0], x_size[1], x_size[3], x_size[2])
+ x = x[:, :, 1:, :]
+ x = x.reshape(x_size[0], x_size[1], x_size[2], x_size[3] - 1)
+ # Note: the tensor-slice form was faster in my testing than torch.index_select
+ # However, tracing doesn't like the nature of the slice, and if klen changes
+ # during the run then it'll fail, whereas index_select will be fine.
+ x = torch.index_select(x, 3, torch.arange(klen, device=x.device, dtype=torch.long))
+ # x = x[:, :, :, :klen]
+
+ return x
+
+ def rel_attn_core(
+ self,
+ q_head,
+ k_head_h,
+ v_head_h,
+ k_head_r,
+ seg_mat=None,
+ attn_mask=None,
+ output_attentions=False,
+ ):
+ """Core relative positional attention operations."""
+
+ # content based attention score
+ ac = torch.einsum("ibnd,jbnd->bnij", q_head + self.r_w_bias, k_head_h)
+
+ # position based attention score
+ bd = torch.einsum("ibnd,jbnd->bnij", q_head + self.r_r_bias, k_head_r)
+ bd = self.rel_shift_bnij(bd, klen=ac.shape[3])
+
+ # segment based attention score
+ if seg_mat is None:
+ ef = 0
+ else:
+ ef = torch.einsum("ibnd,snd->ibns", q_head + self.r_s_bias, self.seg_embed)
+ ef = torch.einsum("ijbs,ibns->bnij", seg_mat, ef)
+
+ # merge attention scores and perform masking
+ attn_score = (ac + bd + ef) * self.scale
+ if attn_mask is not None:
+ # attn_score = attn_score * (1 - attn_mask) - 1e30 * attn_mask
+ if attn_mask.dtype == torch.float16:
+ attn_score = attn_score - 65500 * torch.einsum("ijbn->bnij", attn_mask)
+ else:
+ attn_score = attn_score - 1e30 * torch.einsum("ijbn->bnij", attn_mask)
+
+ # attention probability
+ attn_prob = nn.functional.softmax(attn_score, dim=3)
+ attn_prob = self.dropout(attn_prob)
+
+ # attention output
+ attn_vec = torch.einsum("bnij,jbnd->ibnd", attn_prob, v_head_h)
+
+ if output_attentions:
+ return attn_vec, torch.einsum("bnij->ijbn", attn_prob)
+
+ return attn_vec
+
+ def post_attention(self, h, attn_vec, residual=True):
+ """Post-attention processing."""
+ # post-attention projection (back to `d_model`)
+ attn_out = torch.einsum("ibnd,hnd->ibh", attn_vec, self.o)
+
+ attn_out = self.dropout(attn_out)
+ if residual:
+ attn_out = attn_out + h
+ output = self.layer_norm(attn_out)
+
+ return output
+
+ def forward(
+ self,
+ h,
+ g,
+ attn_mask_h,
+ attn_mask_g,
+ r,
+ seg_mat,
+ mems=None,
+ target_mapping=None,
+ output_attentions=False,
+ ):
+ if g is not None:
+ # Two-stream attention with relative positional encoding.
+ # content based attention score
+ if mems is not None and mems.dim() > 1:
+ cat = torch.cat([mems, h], dim=0)
+ else:
+ cat = h
+
+ # content-based key head
+ k_head_h = torch.einsum("ibh,hnd->ibnd", cat, self.k)
+
+ # content-based value head
+ v_head_h = torch.einsum("ibh,hnd->ibnd", cat, self.v)
+
+ # position-based key head
+ k_head_r = torch.einsum("ibh,hnd->ibnd", r, self.r)
+
+ # h-stream
+ # content-stream query head
+ q_head_h = torch.einsum("ibh,hnd->ibnd", h, self.q)
+
+ # core attention ops
+ attn_vec_h = self.rel_attn_core(
+ q_head_h,
+ k_head_h,
+ v_head_h,
+ k_head_r,
+ seg_mat=seg_mat,
+ attn_mask=attn_mask_h,
+ output_attentions=output_attentions,
+ )
+
+ if output_attentions:
+ attn_vec_h, attn_prob_h = attn_vec_h
+
+ # post processing
+ output_h = self.post_attention(h, attn_vec_h)
+
+ # g-stream
+ # query-stream query head
+ q_head_g = torch.einsum("ibh,hnd->ibnd", g, self.q)
+
+ # core attention ops
+ if target_mapping is not None:
+ q_head_g = torch.einsum("mbnd,mlb->lbnd", q_head_g, target_mapping)
+ attn_vec_g = self.rel_attn_core(
+ q_head_g,
+ k_head_h,
+ v_head_h,
+ k_head_r,
+ seg_mat=seg_mat,
+ attn_mask=attn_mask_g,
+ output_attentions=output_attentions,
+ )
+
+ if output_attentions:
+ attn_vec_g, attn_prob_g = attn_vec_g
+
+ attn_vec_g = torch.einsum("lbnd,mlb->mbnd", attn_vec_g, target_mapping)
+ else:
+ attn_vec_g = self.rel_attn_core(
+ q_head_g,
+ k_head_h,
+ v_head_h,
+ k_head_r,
+ seg_mat=seg_mat,
+ attn_mask=attn_mask_g,
+ output_attentions=output_attentions,
+ )
+
+ if output_attentions:
+ attn_vec_g, attn_prob_g = attn_vec_g
+
+ # post processing
+ output_g = self.post_attention(g, attn_vec_g)
+
+ if output_attentions:
+ attn_prob = attn_prob_h, attn_prob_g
+
+ else:
+ # Multi-head attention with relative positional encoding
+ if mems is not None and mems.dim() > 1:
+ cat = torch.cat([mems, h], dim=0)
+ else:
+ cat = h
+
+ # content heads
+ q_head_h = torch.einsum("ibh,hnd->ibnd", h, self.q)
+ k_head_h = torch.einsum("ibh,hnd->ibnd", cat, self.k)
+ v_head_h = torch.einsum("ibh,hnd->ibnd", cat, self.v)
+
+ # positional heads
+ # type casting for fp16 support
+ k_head_r = torch.einsum("ibh,hnd->ibnd", r.type(self.r.dtype), self.r)
+
+ # core attention ops
+ attn_vec = self.rel_attn_core(
+ q_head_h,
+ k_head_h,
+ v_head_h,
+ k_head_r,
+ seg_mat=seg_mat,
+ attn_mask=attn_mask_h,
+ output_attentions=output_attentions,
+ )
+
+ if output_attentions:
+ attn_vec, attn_prob = attn_vec
+
+ # post processing
+ output_h = self.post_attention(h, attn_vec)
+ output_g = None
+
+ outputs = (output_h, output_g)
+ if output_attentions:
+ outputs = outputs + (attn_prob,)
+ return outputs
+
+
+class XLNetFeedForward(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.layer_norm = nn.LayerNorm(config.d_model, eps=config.layer_norm_eps)
+ self.layer_1 = nn.Linear(config.d_model, config.d_inner)
+ self.layer_2 = nn.Linear(config.d_inner, config.d_model)
+ self.dropout = nn.Dropout(config.dropout)
+ if isinstance(config.ff_activation, str):
+ self.activation_function = ACT2FN[config.ff_activation]
+ else:
+ self.activation_function = config.ff_activation
+
+ def forward(self, inp):
+ output = inp
+ output = self.layer_1(output)
+ output = self.activation_function(output)
+ output = self.dropout(output)
+ output = self.layer_2(output)
+ output = self.dropout(output)
+ output = self.layer_norm(output + inp)
+ return output
+
+
+class XLNetLayer(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.rel_attn = XLNetRelativeAttention(config)
+ self.ff = XLNetFeedForward(config)
+ self.dropout = nn.Dropout(config.dropout)
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+
+ def forward(
+ self,
+ output_h,
+ output_g,
+ attn_mask_h,
+ attn_mask_g,
+ r,
+ seg_mat,
+ mems=None,
+ target_mapping=None,
+ output_attentions=False,
+ ):
+ outputs = self.rel_attn(
+ output_h,
+ output_g,
+ attn_mask_h,
+ attn_mask_g,
+ r,
+ seg_mat,
+ mems=mems,
+ target_mapping=target_mapping,
+ output_attentions=output_attentions,
+ )
+ output_h, output_g = outputs[:2]
+
+ if output_g is not None:
+ output_g = apply_chunking_to_forward(
+ self.ff_chunk, self.chunk_size_feed_forward, self.seq_len_dim, output_g
+ )
+ output_h = apply_chunking_to_forward(self.ff_chunk, self.chunk_size_feed_forward, self.seq_len_dim, output_h)
+
+ outputs = (output_h, output_g) + outputs[2:] # Add again attentions if there are there
+ return outputs
+
+ def ff_chunk(self, output_x):
+ output_x = self.ff(output_x)
+ return output_x
+
+
+# Copied from transformers.models.xlm.modeling_xlm.XLMPoolerStartLogits with XLM->XLNet
+class XLNetPoolerStartLogits(nn.Module):
+ """
+ Compute SQuAD start logits from sequence hidden states.
+
+ Args:
+ config ([`XLNetConfig`]):
+ The config used by the model, will be used to grab the `hidden_size` of the model.
+ """
+
+ def __init__(self, config: XLNetConfig):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, 1)
+
+ def forward(self, hidden_states: torch.FloatTensor, p_mask: torch.FloatTensor | None = None) -> torch.FloatTensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`):
+ The final hidden states of the model.
+ p_mask (`torch.FloatTensor` of shape `(batch_size, seq_len)`, *optional*):
+ Mask for tokens at invalid position, such as query and special symbols (PAD, SEP, CLS). 1.0 means token
+ should be masked.
+
+ Returns:
+ `torch.FloatTensor`: The start logits for SQuAD.
+ """
+ x = self.dense(hidden_states).squeeze(-1)
+
+ if p_mask is not None:
+ if p_mask.dtype == torch.float16:
+ x = x * (1 - p_mask) - 65500 * p_mask
+ else:
+ x = x * (1 - p_mask) - 1e30 * p_mask
+
+ return x
+
+
+# Copied from transformers.models.xlm.modeling_xlm.XLMPoolerEndLogits with XLM->XLNet
+class XLNetPoolerEndLogits(nn.Module):
+ """
+ Compute SQuAD end logits from sequence hidden states.
+
+ Args:
+ config ([`XLNetConfig`]):
+ The config used by the model, will be used to grab the `hidden_size` of the model and the `layer_norm_eps`
+ to use.
+ """
+
+ def __init__(self, config: XLNetConfig):
+ super().__init__()
+ self.dense_0 = nn.Linear(config.hidden_size * 2, config.hidden_size)
+ self.activation = nn.Tanh()
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dense_1 = nn.Linear(config.hidden_size, 1)
+
+ def forward(
+ self,
+ hidden_states: torch.FloatTensor,
+ start_states: torch.FloatTensor | None = None,
+ start_positions: torch.LongTensor | None = None,
+ p_mask: torch.FloatTensor | None = None,
+ ) -> torch.FloatTensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`):
+ The final hidden states of the model.
+ start_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`, *optional*):
+ The hidden states of the first tokens for the labeled span.
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ The position of the first token for the labeled span.
+ p_mask (`torch.FloatTensor` of shape `(batch_size, seq_len)`, *optional*):
+ Mask for tokens at invalid position, such as query and special symbols (PAD, SEP, CLS). 1.0 means token
+ should be masked.
+
+
+
+ One of `start_states` or `start_positions` should be not `None`. If both are set, `start_positions` overrides
+ `start_states`.
+
+
+
+ Returns:
+ `torch.FloatTensor`: The end logits for SQuAD.
+ """
+ assert start_states is not None or start_positions is not None, (
+ "One of start_states, start_positions should be not None"
+ )
+ if start_positions is not None:
+ slen, hsz = hidden_states.shape[-2:]
+ start_positions = start_positions[:, None, None].expand(-1, -1, hsz) # shape (bsz, 1, hsz)
+ start_states = hidden_states.gather(-2, start_positions) # shape (bsz, 1, hsz)
+ start_states = start_states.expand(-1, slen, -1) # shape (bsz, slen, hsz)
+
+ x = self.dense_0(torch.cat([hidden_states, start_states], dim=-1))
+ x = self.activation(x)
+ x = self.LayerNorm(x)
+ x = self.dense_1(x).squeeze(-1)
+
+ if p_mask is not None:
+ if p_mask.dtype == torch.float16:
+ x = x * (1 - p_mask) - 65500 * p_mask
+ else:
+ x = x * (1 - p_mask) - 1e30 * p_mask
+
+ return x
+
+
+# Copied from transformers.models.xlm.modeling_xlm.XLMPoolerAnswerClass with XLM->XLNet
+class XLNetPoolerAnswerClass(nn.Module):
+ """
+ Compute SQuAD 2.0 answer class from classification and start tokens hidden states.
+
+ Args:
+ config ([`XLNetConfig`]):
+ The config used by the model, will be used to grab the `hidden_size` of the model.
+ """
+
+ def __init__(self, config: XLNetConfig):
+ super().__init__()
+ self.dense_0 = nn.Linear(config.hidden_size * 2, config.hidden_size)
+ self.activation = nn.Tanh()
+ self.dense_1 = nn.Linear(config.hidden_size, 1, bias=False)
+
+ def forward(
+ self,
+ hidden_states: torch.FloatTensor,
+ start_states: torch.FloatTensor | None = None,
+ start_positions: torch.LongTensor | None = None,
+ cls_index: torch.LongTensor | None = None,
+ ) -> torch.FloatTensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`):
+ The final hidden states of the model.
+ start_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`, *optional*):
+ The hidden states of the first tokens for the labeled span.
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ The position of the first token for the labeled span.
+ cls_index (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Position of the CLS token for each sentence in the batch. If `None`, takes the last token.
+
+
+
+ One of `start_states` or `start_positions` should be not `None`. If both are set, `start_positions` overrides
+ `start_states`.
+
+
+
+ Returns:
+ `torch.FloatTensor`: The SQuAD 2.0 answer class.
+ """
+ # No dependency on end_feature so that we can obtain one single `cls_logits` for each sample.
+ hsz = hidden_states.shape[-1]
+ assert start_states is not None or start_positions is not None, (
+ "One of start_states, start_positions should be not None"
+ )
+ if start_positions is not None:
+ start_positions = start_positions[:, None, None].expand(-1, -1, hsz) # shape (bsz, 1, hsz)
+ start_states = hidden_states.gather(-2, start_positions).squeeze(-2) # shape (bsz, hsz)
+
+ if cls_index is not None:
+ cls_index = cls_index[:, None, None].expand(-1, -1, hsz) # shape (bsz, 1, hsz)
+ cls_token_state = hidden_states.gather(-2, cls_index).squeeze(-2) # shape (bsz, hsz)
+ else:
+ cls_token_state = hidden_states[:, -1, :] # shape (bsz, hsz)
+
+ x = self.dense_0(torch.cat([start_states, cls_token_state], dim=-1))
+ x = self.activation(x)
+ x = self.dense_1(x).squeeze(-1)
+
+ return x
+
+
+# Copied from transformers.models.xlm.modeling_xlm.XLMSequenceSummary with XLM->XLNet
+class XLNetSequenceSummary(nn.Module):
+ r"""
+ Compute a single vector summary of a sequence hidden states.
+
+ Args:
+ config ([`XLNetConfig`]):
+ The config used by the model. Relevant arguments in the config class of the model are (refer to the actual
+ config class of your model for the default values it uses):
+
+ - **summary_type** (`str`) -- The method to use to make this summary. Accepted values are:
+
+ - `"last"` -- Take the last token hidden state (like XLNet)
+ - `"first"` -- Take the first token hidden state (like Bert)
+ - `"mean"` -- Take the mean of all tokens hidden states
+ - `"cls_index"` -- Supply a Tensor of classification token position (GPT/GPT-2)
+ - `"attn"` -- Not implemented now, use multi-head attention
+
+ - **summary_use_proj** (`bool`) -- Add a projection after the vector extraction.
+ - **summary_proj_to_labels** (`bool`) -- If `True`, the projection outputs to `config.num_labels` classes
+ (otherwise to `config.hidden_size`).
+ - **summary_activation** (`Optional[str]`) -- Set to `"tanh"` to add a tanh activation to the output,
+ another string or `None` will add no activation.
+ - **summary_first_dropout** (`float`) -- Optional dropout probability before the projection and activation.
+ - **summary_last_dropout** (`float`)-- Optional dropout probability after the projection and activation.
+ """
+
+ def __init__(self, config: XLNetConfig):
+ super().__init__()
+
+ self.summary_type = getattr(config, "summary_type", "last")
+ if self.summary_type == "attn":
+ # We should use a standard multi-head attention module with absolute positional embedding for that.
+ # Cf. https://github.com/zihangdai/xlnet/blob/master/modeling.py#L253-L276
+ # We can probably just use the multi-head attention module of PyTorch >=1.1.0
+ raise NotImplementedError
+
+ self.summary = nn.Identity()
+ if hasattr(config, "summary_use_proj") and config.summary_use_proj:
+ if hasattr(config, "summary_proj_to_labels") and config.summary_proj_to_labels and config.num_labels > 0:
+ num_classes = config.num_labels
+ else:
+ num_classes = config.hidden_size
+ self.summary = nn.Linear(config.hidden_size, num_classes)
+
+ activation_string = getattr(config, "summary_activation", None)
+ self.activation: Callable = get_activation(activation_string) if activation_string else nn.Identity()
+
+ self.first_dropout = nn.Identity()
+ if hasattr(config, "summary_first_dropout") and config.summary_first_dropout > 0:
+ self.first_dropout = nn.Dropout(config.summary_first_dropout)
+
+ self.last_dropout = nn.Identity()
+ if hasattr(config, "summary_last_dropout") and config.summary_last_dropout > 0:
+ self.last_dropout = nn.Dropout(config.summary_last_dropout)
+
+ def forward(
+ self, hidden_states: torch.FloatTensor, cls_index: torch.LongTensor | None = None
+ ) -> torch.FloatTensor:
+ """
+ Compute a single vector summary of a sequence hidden states.
+
+ Args:
+ hidden_states (`torch.FloatTensor` of shape `[batch_size, seq_len, hidden_size]`):
+ The hidden states of the last layer.
+ cls_index (`torch.LongTensor` of shape `[batch_size]` or `[batch_size, ...]` where ... are optional leading dimensions of `hidden_states`, *optional*):
+ Used if `summary_type == "cls_index"` and takes the last token of the sequence as classification token.
+
+ Returns:
+ `torch.FloatTensor`: The summary of the sequence hidden states.
+ """
+ if self.summary_type == "last":
+ output = hidden_states[:, -1]
+ elif self.summary_type == "first":
+ output = hidden_states[:, 0]
+ elif self.summary_type == "mean":
+ output = hidden_states.mean(dim=1)
+ elif self.summary_type == "cls_index":
+ if cls_index is None:
+ cls_index = torch.full_like(
+ hidden_states[..., :1, :],
+ hidden_states.shape[-2] - 1,
+ dtype=torch.long,
+ )
+ else:
+ cls_index = cls_index.unsqueeze(-1).unsqueeze(-1)
+ cls_index = cls_index.expand((-1,) * (cls_index.dim() - 1) + (hidden_states.size(-1),))
+ # shape of cls_index: (bsz, XX, 1, hidden_size) where XX are optional leading dim of hidden_states
+ output = hidden_states.gather(-2, cls_index).squeeze(-2) # shape (bsz, XX, hidden_size)
+ elif self.summary_type == "attn":
+ raise NotImplementedError
+
+ output = self.first_dropout(output)
+ output = self.summary(output)
+ output = self.activation(output)
+ output = self.last_dropout(output)
+
+ return output
+
+
+@auto_docstring
+class XLNetPreTrainedModel(PreTrainedModel):
+ config: XLNetConfig
+ base_model_prefix = "transformer"
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights."""
+ super()._init_weights(module)
+ if isinstance(module, XLNetRelativeAttention):
+ for param in [
+ module.q,
+ module.k,
+ module.v,
+ module.o,
+ module.r,
+ module.r_r_bias,
+ module.r_s_bias,
+ module.r_w_bias,
+ module.seg_embed,
+ ]:
+ init.normal_(param, mean=0.0, std=self.config.initializer_range)
+ elif isinstance(module, XLNetModel):
+ init.normal_(module.mask_emb, mean=0.0, std=self.config.initializer_range)
+
+
+@auto_docstring(
+ custom_intro="""
+ Output type of [`XLNetModel`].
+ """
+)
+@dataclass
+class XLNetModelOutput(ModelOutput):
+ r"""
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_predict, hidden_size)`):
+ Sequence of hidden-states at the last layer of the model.
+
+ `num_predict` corresponds to `target_mapping.shape[1]`. If `target_mapping` is `None`, then `num_predict`
+ corresponds to `sequence_length`.
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
+ token ids which have their past given to this model should not be passed as `input_ids` as they have
+ already been computed.
+ """
+
+ last_hidden_state: torch.FloatTensor
+ mems: list[torch.FloatTensor] | None = None
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
+ attentions: tuple[torch.FloatTensor, ...] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Output type of [`XLNetLMHeadModel`].
+ """
+)
+@dataclass
+class XLNetLMHeadModelOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape *(1,)*, *optional*, returned when `labels` is provided):
+ Language modeling loss (for next-token prediction).
+ logits (`torch.FloatTensor` of shape `(batch_size, num_predict, config.vocab_size)`):
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
+
+ `num_predict` corresponds to `target_mapping.shape[1]`. If `target_mapping` is `None`, then `num_predict`
+ corresponds to `sequence_length`.
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
+ token ids which have their past given to this model should not be passed as `input_ids` as they have
+ already been computed.
+ """
+
+ loss: torch.FloatTensor | None = None
+ logits: torch.FloatTensor | None = None
+ mems: list[torch.FloatTensor] | None = None
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
+ attentions: tuple[torch.FloatTensor, ...] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Output type of [`XLNetForSequenceClassification`].
+ """
+)
+@dataclass
+class XLNetForSequenceClassificationOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `label` is provided):
+ Classification (or regression if config.num_labels==1) loss.
+ logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
+ Classification (or regression if config.num_labels==1) scores (before SoftMax).
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
+ token ids which have their past given to this model should not be passed as `input_ids` as they have
+ already been computed.
+ """
+
+ loss: torch.FloatTensor | None = None
+ logits: torch.FloatTensor | None = None
+ mems: list[torch.FloatTensor] | None = None
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
+ attentions: tuple[torch.FloatTensor, ...] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Output type of [`XLNetForTokenClassificationOutput`].
+ """
+)
+@dataclass
+class XLNetForTokenClassificationOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Classification loss.
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`):
+ Classification scores (before SoftMax).
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
+ token ids which have their past given to this model should not be passed as `input_ids` as they have
+ already been computed.
+ """
+
+ loss: torch.FloatTensor | None = None
+ logits: torch.FloatTensor | None = None
+ mems: list[torch.FloatTensor] | None = None
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
+ attentions: tuple[torch.FloatTensor, ...] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Output type of [`XLNetForMultipleChoice`].
+ """
+)
+@dataclass
+class XLNetForMultipleChoiceOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape *(1,)*, *optional*, returned when `labels` is provided):
+ Classification loss.
+ logits (`torch.FloatTensor` of shape `(batch_size, num_choices)`):
+ *num_choices* is the second dimension of the input tensors. (see *input_ids* above).
+
+ Classification scores (before SoftMax).
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
+ token ids which have their past given to this model should not be passed as `input_ids` as they have
+ already been computed.
+ """
+
+ loss: torch.FloatTensor | None = None
+ logits: torch.FloatTensor | None = None
+ mems: list[torch.FloatTensor] | None = None
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
+ attentions: tuple[torch.FloatTensor, ...] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Output type of [`XLNetForQuestionAnsweringSimple`].
+ """
+)
+@dataclass
+class XLNetForQuestionAnsweringSimpleOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.
+ start_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length,)`):
+ Span-start scores (before SoftMax).
+ end_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length,)`):
+ Span-end scores (before SoftMax).
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
+ token ids which have their past given to this model should not be passed as `input_ids` as they have
+ already been computed.
+ """
+
+ loss: torch.FloatTensor | None = None
+ start_logits: torch.FloatTensor | None = None
+ end_logits: torch.FloatTensor | None = None
+ mems: list[torch.FloatTensor] | None = None
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
+ attentions: tuple[torch.FloatTensor, ...] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Output type of [`XLNetForQuestionAnswering`].
+ """
+)
+@dataclass
+class XLNetForQuestionAnsweringOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned if both `start_positions` and `end_positions` are provided):
+ Classification loss as the sum of start token, end token (and is_impossible if provided) classification
+ losses.
+ start_top_log_probs (`torch.FloatTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Log probabilities for the top config.start_n_top start token possibilities (beam-search).
+ start_top_index (`torch.LongTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Indices for the top config.start_n_top start token possibilities (beam-search).
+ end_top_log_probs (`torch.FloatTensor` of shape `(batch_size, config.start_n_top * config.end_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Log probabilities for the top `config.start_n_top * config.end_n_top` end token possibilities
+ (beam-search).
+ end_top_index (`torch.LongTensor` of shape `(batch_size, config.start_n_top * config.end_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Indices for the top `config.start_n_top * config.end_n_top` end token possibilities (beam-search).
+ cls_logits (`torch.FloatTensor` of shape `(batch_size,)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Log probabilities for the `is_impossible` label of the answers.
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
+ token ids which have their past given to this model should not be passed as `input_ids` as they have
+ already been computed.
+ """
+
+ loss: torch.FloatTensor | None = None
+ start_top_log_probs: torch.FloatTensor | None = None
+ start_top_index: torch.LongTensor | None = None
+ end_top_log_probs: torch.FloatTensor | None = None
+ end_top_index: torch.LongTensor | None = None
+ cls_logits: torch.FloatTensor | None = None
+ mems: list[torch.FloatTensor] | None = None
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
+ attentions: tuple[torch.FloatTensor, ...] | None = None
+
+
+@auto_docstring
+class XLNetModel(XLNetPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.mem_len = config.mem_len
+ self.reuse_len = config.reuse_len
+ self.d_model = config.d_model
+ self.same_length = config.same_length
+ self.attn_type = config.attn_type
+ self.bi_data = config.bi_data
+ self.clamp_len = config.clamp_len
+ self.n_layer = config.n_layer
+
+ self.word_embedding = nn.Embedding(config.vocab_size, config.d_model)
+ self.mask_emb = nn.Parameter(torch.FloatTensor(1, 1, config.d_model))
+ self.layer = nn.ModuleList([XLNetLayer(config) for _ in range(config.n_layer)])
+ self.dropout = nn.Dropout(config.dropout)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.word_embedding
+
+ def set_input_embeddings(self, new_embeddings):
+ self.word_embedding = new_embeddings
+
+ def create_mask(self, qlen, mlen):
+ """
+ Creates causal attention mask. Float mask where 1.0 indicates masked, 0.0 indicates not-masked.
+
+ Args:
+ qlen: Sequence length
+ mlen: Mask length
+
+ ::
+
+ same_length=False: same_length=True: < qlen > < qlen >
+ ^ [0 0 0 0 0 1 1 1 1] [0 0 0 0 0 1 1 1 1]
+ [0 0 0 0 0 0 1 1 1] [1 0 0 0 0 0 1 1 1]
+ qlen [0 0 0 0 0 0 0 1 1] [1 1 0 0 0 0 0 1 1]
+ [0 0 0 0 0 0 0 0 1] [1 1 1 0 0 0 0 0 1]
+ v [0 0 0 0 0 0 0 0 0] [1 1 1 1 0 0 0 0 0]
+
+ """
+ mask = torch.ones((qlen, qlen + mlen), device=self.device)
+ if self.same_length:
+ mask_lo = mask[:, :qlen].tril(-1)
+ mask.triu_(mlen + 1)
+ mask[:, :qlen] += mask_lo
+ else:
+ mask.triu_(mlen + 1)
+
+ return mask
+
+ def cache_mem(self, curr_out, prev_mem):
+ # cache hidden states into memory.
+ if self.reuse_len is not None and self.reuse_len > 0:
+ curr_out = curr_out[: self.reuse_len]
+
+ if self.mem_len is None or self.mem_len == 0:
+ # If `use_mems` is active but no `mem_len` is defined, the model behaves like GPT-2 at inference time
+ # and returns all of the past and current hidden states.
+ cutoff = 0
+ else:
+ # If `use_mems` is active and `mem_len` is defined, the model returns the last `mem_len` hidden
+ # states. This is the preferred setting for training and long-form generation.
+ cutoff = -self.mem_len
+ if prev_mem is None:
+ # if `use_mems` is active and `mem_len` is defined, the model
+ new_mem = curr_out[cutoff:]
+ else:
+ new_mem = torch.cat([prev_mem, curr_out], dim=0)[cutoff:]
+
+ return new_mem.detach()
+
+ @staticmethod
+ def positional_embedding(pos_seq, inv_freq, bsz=None):
+ sinusoid_inp = torch.einsum("i,d->id", pos_seq, inv_freq)
+ pos_emb = torch.cat([torch.sin(sinusoid_inp), torch.cos(sinusoid_inp)], dim=-1)
+ pos_emb = pos_emb[:, None, :]
+
+ if bsz is not None:
+ pos_emb = pos_emb.expand(-1, bsz, -1)
+
+ return pos_emb
+
+ def relative_positional_encoding(self, qlen, klen, bsz=None, device=None):
+ # create relative positional encoding.
+ freq_seq = torch.arange(0, self.d_model, 2.0, dtype=torch.int64, device=device).float()
+ inv_freq = 1 / torch.pow(10000, (freq_seq / self.d_model))
+
+ if self.attn_type == "bi":
+ # beg, end = klen - 1, -qlen
+ beg, end = klen, -qlen
+ elif self.attn_type == "uni":
+ # beg, end = klen - 1, -1
+ beg, end = klen, -1
+ else:
+ raise ValueError(f"Unknown `attn_type` {self.attn_type}.")
+
+ if self.bi_data:
+ fwd_pos_seq = torch.arange(beg, end, -1.0, dtype=torch.int64, device=device).float()
+ bwd_pos_seq = torch.arange(-beg, -end, 1.0, dtype=torch.int64, device=device).float()
+
+ if self.clamp_len > 0:
+ fwd_pos_seq = fwd_pos_seq.clamp(-self.clamp_len, self.clamp_len)
+ bwd_pos_seq = bwd_pos_seq.clamp(-self.clamp_len, self.clamp_len)
+
+ if bsz is not None:
+ fwd_pos_emb = self.positional_embedding(fwd_pos_seq, inv_freq, bsz // 2)
+ bwd_pos_emb = self.positional_embedding(bwd_pos_seq, inv_freq, bsz // 2)
+ else:
+ fwd_pos_emb = self.positional_embedding(fwd_pos_seq, inv_freq)
+ bwd_pos_emb = self.positional_embedding(bwd_pos_seq, inv_freq)
+
+ pos_emb = torch.cat([fwd_pos_emb, bwd_pos_emb], dim=1)
+ else:
+ fwd_pos_seq = torch.arange(beg, end, -1.0, dtype=torch.int64, device=device).float()
+ if self.clamp_len > 0:
+ fwd_pos_seq = fwd_pos_seq.clamp(-self.clamp_len, self.clamp_len)
+ pos_emb = self.positional_embedding(fwd_pos_seq, inv_freq, bsz)
+
+ return pos_emb
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ mems: torch.Tensor | None = None,
+ perm_mask: torch.Tensor | None = None,
+ target_mapping: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ input_mask: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ use_mems: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs, # delete after depreciation warning is removed
+ ) -> tuple | XLNetModelOutput:
+ r"""
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
+ decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
+ they have already been computed.
+
+ `use_mems` has to be set to `True` to make use of `mems`.
+ perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
+ Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:
+
+ - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
+ - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.
+
+ If not set, each token attends to all the others (full bidirectional attention). Only used during
+ pretraining (to define factorization order) or for sequential decoding (generation).
+ target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
+ Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
+ on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
+ (generation).
+ input_mask (`torch.FloatTensor` of shape `batch_size, sequence_length`, *optional*):
+ Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
+ real tokens and 1 for padding which is kept for compatibility with the original code base.
+
+ Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **masked**,
+ - 0 for tokens that are **not masked**.
+
+ You can only uses one of `input_mask` and `attention_mask`.
+ use_mems (`bool`, *optional*):
+ Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
+ states from previous forward passes to compute attention, which can significantly improve performance for
+ sequential decoding tasks.
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ if self.training:
+ use_mems = use_mems if use_mems is not None else self.config.use_mems_train
+ else:
+ use_mems = use_mems if use_mems is not None else self.config.use_mems_eval
+
+ # the original code for XLNet uses shapes [len, bsz] with the batch dimension at the end
+ # but we want a unified interface in the library with the batch size on the first dimension
+ # so we move here the first dimension (batch) to the end
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ input_ids = input_ids.transpose(0, 1).contiguous()
+ qlen, bsz = input_ids.shape[0], input_ids.shape[1]
+ elif inputs_embeds is not None:
+ inputs_embeds = inputs_embeds.transpose(0, 1).contiguous()
+ qlen, bsz = inputs_embeds.shape[0], inputs_embeds.shape[1]
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ token_type_ids = token_type_ids.transpose(0, 1).contiguous() if token_type_ids is not None else None
+ input_mask = input_mask.transpose(0, 1).contiguous() if input_mask is not None else None
+ attention_mask = attention_mask.transpose(0, 1).contiguous() if attention_mask is not None else None
+ perm_mask = perm_mask.permute(1, 2, 0).contiguous() if perm_mask is not None else None
+ target_mapping = target_mapping.permute(1, 2, 0).contiguous() if target_mapping is not None else None
+
+ mlen = mems[0].shape[0] if mems is not None and mems[0] is not None else 0
+ klen = mlen + qlen
+
+ dtype_float = self.dtype
+ device = self.device
+
+ # Attention mask
+ # causal attention mask
+ if self.attn_type == "uni":
+ attn_mask = self.create_mask(qlen, mlen)
+ attn_mask = attn_mask[:, :, None, None]
+ elif self.attn_type == "bi":
+ attn_mask = None
+ else:
+ raise ValueError(f"Unsupported attention type: {self.attn_type}")
+
+ # data mask: input mask & perm mask
+ assert input_mask is None or attention_mask is None, "You can only use one of input_mask (uses 1 for padding) "
+ "or attention_mask (uses 0 for padding, added for compatibility with BERT). Please choose one."
+ if input_mask is None and attention_mask is not None:
+ input_mask = 1.0 - attention_mask
+ if input_mask is not None and perm_mask is not None:
+ data_mask = input_mask[None] + perm_mask
+ elif input_mask is not None and perm_mask is None:
+ data_mask = input_mask[None]
+ elif input_mask is None and perm_mask is not None:
+ data_mask = perm_mask
+ else:
+ data_mask = None
+
+ if data_mask is not None:
+ # all mems can be attended to
+ if mlen > 0:
+ mems_mask = torch.zeros([data_mask.shape[0], mlen, bsz]).to(data_mask)
+ data_mask = torch.cat([mems_mask, data_mask], dim=1)
+ if attn_mask is None:
+ attn_mask = data_mask[:, :, :, None]
+ else:
+ attn_mask += data_mask[:, :, :, None]
+
+ if attn_mask is not None:
+ attn_mask = (attn_mask > 0).to(dtype_float)
+
+ if attn_mask is not None:
+ non_tgt_mask = -torch.eye(qlen).to(attn_mask)
+ if mlen > 0:
+ non_tgt_mask = torch.cat([torch.zeros([qlen, mlen]).to(attn_mask), non_tgt_mask], dim=-1)
+ non_tgt_mask = ((attn_mask + non_tgt_mask[:, :, None, None]) > 0).to(attn_mask)
+ else:
+ non_tgt_mask = None
+
+ # Word embeddings and prepare h & g hidden states
+ if inputs_embeds is not None:
+ word_emb_k = inputs_embeds
+ else:
+ word_emb_k = self.word_embedding(input_ids)
+ output_h = self.dropout(word_emb_k)
+ if target_mapping is not None:
+ word_emb_q = self.mask_emb.expand(target_mapping.shape[0], bsz, -1)
+ # else: # We removed the inp_q input which was same as target mapping
+ # inp_q_ext = inp_q[:, :, None]
+ # word_emb_q = inp_q_ext * self.mask_emb + (1 - inp_q_ext) * word_emb_k
+ output_g = self.dropout(word_emb_q)
+ else:
+ output_g = None
+
+ # Segment embedding
+ if token_type_ids is not None:
+ # Convert `token_type_ids` to one-hot `seg_mat`
+ if mlen > 0:
+ mem_pad = torch.zeros([mlen, bsz], dtype=torch.long, device=device)
+ cat_ids = torch.cat([mem_pad, token_type_ids], dim=0)
+ else:
+ cat_ids = token_type_ids
+
+ # `1` indicates not in the same segment [qlen x klen x bsz]
+ seg_mat = (token_type_ids[:, None] != cat_ids[None, :]).long()
+ seg_mat = nn.functional.one_hot(seg_mat, num_classes=2).to(dtype_float)
+ else:
+ seg_mat = None
+
+ # Positional encoding
+ pos_emb = self.relative_positional_encoding(qlen, klen, bsz=bsz, device=output_h.device)
+ pos_emb = self.dropout(pos_emb)
+
+ new_mems = ()
+ if mems is None:
+ mems = [None] * len(self.layer)
+
+ attentions = [] if output_attentions else None
+ hidden_states = [] if output_hidden_states else None
+ for i, layer_module in enumerate(self.layer):
+ if use_mems:
+ # cache new mems
+ new_mems = new_mems + (self.cache_mem(output_h, mems[i]),)
+ if output_hidden_states:
+ hidden_states.append((output_h, output_g) if output_g is not None else output_h)
+
+ outputs = layer_module(
+ output_h,
+ output_g,
+ attn_mask_h=non_tgt_mask,
+ attn_mask_g=attn_mask,
+ r=pos_emb,
+ seg_mat=seg_mat,
+ mems=mems[i],
+ target_mapping=target_mapping,
+ output_attentions=output_attentions,
+ )
+ output_h, output_g = outputs[:2]
+ if output_attentions:
+ attentions.append(outputs[2])
+
+ # Add last hidden state
+ if output_hidden_states:
+ hidden_states.append((output_h, output_g) if output_g is not None else output_h)
+
+ output = self.dropout(output_g if output_g is not None else output_h)
+
+ # Prepare outputs, we transpose back here to shape [bsz, len, hidden_dim] (cf. beginning of forward() method)
+ output = output.permute(1, 0, 2).contiguous()
+
+ if not use_mems:
+ new_mems = None
+
+ if output_hidden_states:
+ if output_g is not None:
+ hidden_states = tuple(h.permute(1, 0, 2).contiguous() for hs in hidden_states for h in hs)
+ else:
+ hidden_states = tuple(hs.permute(1, 0, 2).contiguous() for hs in hidden_states)
+
+ if output_attentions:
+ if target_mapping is not None:
+ # when target_mapping is provided, there are 2-tuple of attentions
+ attentions = tuple(
+ tuple(att_stream.permute(2, 3, 0, 1).contiguous() for att_stream in t) for t in attentions
+ )
+ else:
+ attentions = tuple(t.permute(2, 3, 0, 1).contiguous() for t in attentions)
+
+ if not return_dict:
+ return tuple(v for v in [output, new_mems, hidden_states, attentions] if v is not None)
+
+ return XLNetModelOutput(
+ last_hidden_state=output, mems=new_mems, hidden_states=hidden_states, attentions=attentions
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ XLNet Model with a language modeling head on top (linear layer with weights tied to the input embeddings).
+ """
+)
+class XLNetLMHeadModel(XLNetPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_loss.weight": "transformer.word_embedding.weight"}
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.attn_type = config.attn_type
+ self.same_length = config.same_length
+
+ self.transformer = XLNetModel(config)
+ self.lm_loss = nn.Linear(config.d_model, config.vocab_size, bias=True)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.lm_loss
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_loss = new_embeddings
+
+ def prepare_inputs_for_generation(
+ self, input_ids, past_key_values=None, use_mems=None, is_first_iteration=False, **kwargs
+ ):
+ # Overwritten -- this model has unique input preparation
+
+ # Add dummy token at the end (no attention on this one)
+
+ effective_batch_size = input_ids.shape[0]
+ dummy_token = torch.zeros((effective_batch_size, 1), dtype=torch.long, device=input_ids.device)
+
+ # At every pass, the attention values for the new token and the two last generated tokens
+ # are computed, the rest is reloaded from the `past` cache. A purely auto-regressive model would have
+ # offset = 1; offset = 2 seems to have slightly better computation.
+ offset = 2
+
+ if past_key_values:
+ input_ids = torch.cat([input_ids[:, -offset:], dummy_token], dim=1)
+ else:
+ input_ids = torch.cat([input_ids, dummy_token], dim=1)
+
+ # Build permutation mask so that previous tokens don't see last token
+ sequence_length = input_ids.shape[1]
+ perm_mask = torch.zeros(
+ (effective_batch_size, sequence_length, sequence_length), dtype=torch.float, device=input_ids.device
+ )
+ perm_mask[:, :, -1] = 1.0
+
+ # We'll only predict the last token
+ target_mapping = torch.zeros(
+ (effective_batch_size, 1, sequence_length), dtype=torch.float, device=input_ids.device
+ )
+ target_mapping[:, 0, -1] = 1.0
+
+ model_inputs = {
+ "input_ids": input_ids,
+ "perm_mask": perm_mask,
+ "target_mapping": target_mapping,
+ "use_mems": use_mems,
+ }
+
+ # if past is defined in model kwargs then use it for faster decoding
+ if past_key_values:
+ model_inputs["mems"] = tuple(layer_past[:-offset, :, :] for layer_past in past_key_values)
+
+ # Attention mask is computed on the fly on XLNetModel.forward()
+ kwargs.pop("attention_mask", None)
+ # TODO: Ignoring use_cache should not happen, fixme.
+ kwargs.pop("use_cache", None)
+ # Forward ALL kwargs that are uninitialized (e.g. `use_cache`).
+ for key, value in kwargs.items():
+ if key not in model_inputs:
+ model_inputs[key] = value
+
+ return model_inputs
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ mems: torch.Tensor | None = None,
+ perm_mask: torch.Tensor | None = None,
+ target_mapping: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ input_mask: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ use_mems: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs, # delete when `use_cache` is removed in XLNetModel
+ ) -> tuple | XLNetLMHeadModelOutput:
+ r"""
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
+ decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
+ they have already been computed.
+
+ `use_mems` has to be set to `True` to make use of `mems`.
+ perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
+ Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:
+
+ - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
+ - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.
+
+ If not set, each token attends to all the others (full bidirectional attention). Only used during
+ pretraining (to define factorization order) or for sequential decoding (generation).
+ target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
+ Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
+ on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
+ (generation).
+ input_mask (`torch.FloatTensor` of shape `batch_size, sequence_length`, *optional*):
+ Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
+ real tokens and 1 for padding which is kept for compatibility with the original code base.
+
+ Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **masked**,
+ - 0 for tokens that are **not masked**.
+
+ You can only uses one of `input_mask` and `attention_mask`.
+ labels (`torch.LongTensor` of shape `(batch_size, num_predict)`, *optional*):
+ Labels for masked language modeling. `num_predict` corresponds to `target_mapping.shape[1]`. If
+ `target_mapping` is `None`, then `num_predict` corresponds to `sequence_length`.
+
+ The labels should correspond to the masked input words that should be predicted and depends on
+ `target_mapping`. Note in order to perform standard auto-regressive language modeling a ** token has
+ to be added to the `input_ids` (see the `prepare_inputs_for_generation` function and examples below)
+
+ Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100` are ignored, the loss
+ is only computed for labels in `[0, ..., config.vocab_size]`
+ use_mems (`bool`, *optional*):
+ Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
+ states from previous forward passes to compute attention, which can significantly improve performance for
+ sequential decoding tasks.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, XLNetLMHeadModel
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("xlnet/xlnet-large-cased")
+ >>> model = XLNetLMHeadModel.from_pretrained("xlnet/xlnet-large-cased")
+
+ >>> # We show how to setup inputs to predict a next token using a bi-directional context.
+ >>> input_ids = torch.tensor(
+ ... tokenizer.encode("Hello, my dog is very ", add_special_tokens=False)
+ ... ).unsqueeze(
+ ... 0
+ ... ) # We will predict the masked token
+ >>> perm_mask = torch.zeros((1, input_ids.shape[1], input_ids.shape[1]), dtype=torch.float)
+ >>> perm_mask[:, :, -1] = 1.0 # Previous tokens don't see last token
+ >>> target_mapping = torch.zeros(
+ ... (1, 1, input_ids.shape[1]), dtype=torch.float
+ ... ) # Shape [1, 1, seq_length] => let's predict one token
+ >>> target_mapping[
+ ... 0, 0, -1
+ ... ] = 1.0 # Our first (and only) prediction will be the last token of the sequence (the masked token)
+
+ >>> outputs = model(input_ids, perm_mask=perm_mask, target_mapping=target_mapping)
+ >>> next_token_logits = outputs[
+ ... 0
+ ... ] # Output has shape [target_mapping.size(0), target_mapping.size(1), config.vocab_size]
+
+ >>> # The same way can the XLNetLMHeadModel be used to be trained by standard auto-regressive language modeling.
+ >>> input_ids = torch.tensor(
+ ... tokenizer.encode("Hello, my dog is very ", add_special_tokens=False)
+ ... ).unsqueeze(
+ ... 0
+ ... ) # We will predict the masked token
+ >>> labels = torch.tensor(tokenizer.encode("cute", add_special_tokens=False)).unsqueeze(0)
+ >>> assert labels.shape[0] == 1, "only one word will be predicted"
+ >>> perm_mask = torch.zeros((1, input_ids.shape[1], input_ids.shape[1]), dtype=torch.float)
+ >>> perm_mask[
+ ... :, :, -1
+ ... ] = 1.0 # Previous tokens don't see last token as is done in standard auto-regressive lm training
+ >>> target_mapping = torch.zeros(
+ ... (1, 1, input_ids.shape[1]), dtype=torch.float
+ ... ) # Shape [1, 1, seq_length] => let's predict one token
+ >>> target_mapping[
+ ... 0, 0, -1
+ ... ] = 1.0 # Our first (and only) prediction will be the last token of the sequence (the masked token)
+
+ >>> outputs = model(input_ids, perm_mask=perm_mask, target_mapping=target_mapping, labels=labels)
+ >>> loss = outputs.loss
+ >>> next_token_logits = (
+ ... outputs.logits
+ ... ) # Logits have shape [target_mapping.size(0), target_mapping.size(1), config.vocab_size]
+ ```"""
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ transformer_outputs = self.transformer(
+ input_ids,
+ attention_mask=attention_mask,
+ mems=mems,
+ perm_mask=perm_mask,
+ target_mapping=target_mapping,
+ token_type_ids=token_type_ids,
+ input_mask=input_mask,
+ inputs_embeds=inputs_embeds,
+ use_mems=use_mems,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ **kwargs,
+ )
+
+ hidden_states = transformer_outputs[0]
+ # Only compute necessary logits
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_loss(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ # Flatten the tokens
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, logits.size(-1)), labels.view(-1))
+
+ if not return_dict:
+ output = (logits,) + transformer_outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return XLNetLMHeadModelOutput(
+ loss=loss,
+ logits=logits,
+ mems=transformer_outputs.mems,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+ @staticmethod
+ def _reorder_cache(mems: list[torch.Tensor], beam_idx: torch.Tensor) -> list[torch.Tensor]:
+ """
+ This function is used to re-order the `mems` cache if [`~PreTrainedModel.beam_search`] or
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `mems` with the correct beam_idx at every
+ generation step.
+ """
+ return [layer_past.index_select(1, beam_idx.to(layer_past.device)) for layer_past in mems]
+
+
+@auto_docstring(
+ custom_intro="""
+ XLNet Model with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g.
+ for GLUE tasks.
+ """
+)
+class XLNetForSequenceClassification(XLNetPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.config = config
+
+ self.transformer = XLNetModel(config)
+ self.sequence_summary = XLNetSequenceSummary(config)
+ self.logits_proj = nn.Linear(config.d_model, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ mems: torch.Tensor | None = None,
+ perm_mask: torch.Tensor | None = None,
+ target_mapping: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ input_mask: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ use_mems: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs, # delete when `use_cache` is removed in XLNetModel
+ ) -> tuple | XLNetForSequenceClassificationOutput:
+ r"""
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
+ decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
+ they have already been computed.
+
+ `use_mems` has to be set to `True` to make use of `mems`.
+ perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
+ Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:
+
+ - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
+ - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.
+
+ If not set, each token attends to all the others (full bidirectional attention). Only used during
+ pretraining (to define factorization order) or for sequential decoding (generation).
+ target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
+ Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
+ on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
+ (generation).
+ input_mask (`torch.FloatTensor` of shape `batch_size, sequence_length`, *optional*):
+ Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
+ real tokens and 1 for padding which is kept for compatibility with the original code base.
+
+ Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **masked**,
+ - 0 for tokens that are **not masked**.
+
+ You can only uses one of `input_mask` and `attention_mask`.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ use_mems (`bool`, *optional*):
+ Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
+ states from previous forward passes to compute attention, which can significantly improve performance for
+ sequential decoding tasks.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ transformer_outputs = self.transformer(
+ input_ids,
+ attention_mask=attention_mask,
+ mems=mems,
+ perm_mask=perm_mask,
+ target_mapping=target_mapping,
+ token_type_ids=token_type_ids,
+ input_mask=input_mask,
+ inputs_embeds=inputs_embeds,
+ use_mems=use_mems,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ **kwargs,
+ )
+ output = transformer_outputs[0]
+
+ output = self.sequence_summary(output)
+ logits = self.logits_proj(output)
+
+ loss = None
+ if labels is not None:
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ if not return_dict:
+ output = (logits,) + transformer_outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return XLNetForSequenceClassificationOutput(
+ loss=loss,
+ logits=logits,
+ mems=transformer_outputs.mems,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+@auto_docstring
+class XLNetForTokenClassification(XLNetPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.transformer = XLNetModel(config)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ mems: torch.Tensor | None = None,
+ perm_mask: torch.Tensor | None = None,
+ target_mapping: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ input_mask: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ use_mems: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs, # delete when `use_cache` is removed in XLNetModel
+ ) -> tuple | XLNetForTokenClassificationOutput:
+ r"""
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
+ decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
+ they have already been computed.
+
+ `use_mems` has to be set to `True` to make use of `mems`.
+ perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
+ Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:
+
+ - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
+ - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.
+
+ If not set, each token attends to all the others (full bidirectional attention). Only used during
+ pretraining (to define factorization order) or for sequential decoding (generation).
+ target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
+ Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
+ on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
+ (generation).
+ input_mask (`torch.FloatTensor` of shape `batch_size, sequence_length`, *optional*):
+ Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
+ real tokens and 1 for padding which is kept for compatibility with the original code base.
+
+ Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **masked**,
+ - 0 for tokens that are **not masked**.
+
+ You can only uses one of `input_mask` and `attention_mask`.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
+ where *num_choices* is the size of the second dimension of the input tensors. (see *input_ids* above)
+ use_mems (`bool`, *optional*):
+ Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
+ states from previous forward passes to compute attention, which can significantly improve performance for
+ sequential decoding tasks.emory states to speed up sequential decoding. If set to `True`, the model will use the hidden
+ states from previous forward passes to compute attention, which can significantly improve performance for
+ sequential decoding tasks.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.transformer(
+ input_ids,
+ attention_mask=attention_mask,
+ mems=mems,
+ perm_mask=perm_mask,
+ target_mapping=target_mapping,
+ token_type_ids=token_type_ids,
+ input_mask=input_mask,
+ inputs_embeds=inputs_embeds,
+ use_mems=use_mems,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ if not return_dict:
+ output = (logits,) + outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return XLNetForTokenClassificationOutput(
+ loss=loss,
+ logits=logits,
+ mems=outputs.mems,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class XLNetForMultipleChoice(XLNetPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.transformer = XLNetModel(config)
+ self.sequence_summary = XLNetSequenceSummary(config)
+ self.logits_proj = nn.Linear(config.d_model, 1)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ input_mask: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ mems: torch.Tensor | None = None,
+ perm_mask: torch.Tensor | None = None,
+ target_mapping: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ use_mems: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs, # delete when `use_cache` is removed in XLNetModel
+ ) -> tuple | XLNetForMultipleChoiceOutput:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
+ 1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ input_mask (`torch.FloatTensor` of shape `batch_size, num_choices, sequence_length`, *optional*):
+ Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
+ real tokens and 1 for padding which is kept for compatibility with the original code base.
+
+ Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **masked**,
+ - 0 for tokens that are **not masked**.
+
+ You can only uses one of `input_mask` and `attention_mask`.
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
+ decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
+ they have already been computed.
+
+ `use_mems` has to be set to `True` to make use of `mems`.
+ perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
+ Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:
+
+ - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
+ - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.
+
+ If not set, each token attends to all the others (full bidirectional attention). Only used during
+ pretraining (to define factorization order) or for sequential decoding (generation).
+ target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
+ Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
+ on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
+ (generation).
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
+ use_mems (`bool`, *optional*):
+ Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
+ states from previous forward passes to compute attention, which can significantly improve performance for
+ sequential decoding tasks.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
+
+ flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
+ flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
+ flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
+ flat_input_mask = input_mask.view(-1, input_mask.size(-1)) if input_mask is not None else None
+ flat_inputs_embeds = (
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
+ if inputs_embeds is not None
+ else None
+ )
+
+ transformer_outputs = self.transformer(
+ flat_input_ids,
+ token_type_ids=flat_token_type_ids,
+ input_mask=flat_input_mask,
+ attention_mask=flat_attention_mask,
+ mems=mems,
+ perm_mask=perm_mask,
+ target_mapping=target_mapping,
+ inputs_embeds=flat_inputs_embeds,
+ use_mems=use_mems,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ **kwargs,
+ )
+
+ output = transformer_outputs[0]
+
+ output = self.sequence_summary(output)
+ logits = self.logits_proj(output)
+ reshaped_logits = logits.view(-1, num_choices)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(reshaped_logits, labels.view(-1))
+
+ if not return_dict:
+ output = (reshaped_logits,) + transformer_outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return XLNetForMultipleChoiceOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ mems=transformer_outputs.mems,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ XLNet Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
+ """
+)
+class XLNetForQuestionAnsweringSimple(XLNetPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.transformer = XLNetModel(config)
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ mems: torch.Tensor | None = None,
+ perm_mask: torch.Tensor | None = None,
+ target_mapping: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ input_mask: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ start_positions: torch.Tensor | None = None,
+ end_positions: torch.Tensor | None = None,
+ use_mems: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs, # delete when `use_cache` is removed in XLNetModel
+ ) -> tuple | XLNetForQuestionAnsweringSimpleOutput:
+ r"""
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
+ decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
+ they have already been computed.
+
+ `use_mems` has to be set to `True` to make use of `mems`.
+ perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
+ Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:
+
+ - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
+ - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.
+
+ If not set, each token attends to all the others (full bidirectional attention). Only used during
+ pretraining (to define factorization order) or for sequential decoding (generation).
+ target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
+ Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
+ on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
+ (generation).
+ input_mask (`torch.FloatTensor` of shape `batch_size, sequence_length`, *optional*):
+ Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
+ real tokens and 1 for padding which is kept for compatibility with the original code base.
+
+ Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **masked**,
+ - 0 for tokens that are **not masked**.
+
+ You can only uses one of `input_mask` and `attention_mask`.
+ use_mems (`bool`, *optional*):
+ Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
+ states from previous forward passes to compute attention, which can significantly improve performance for
+ sequential decoding tasks.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.transformer(
+ input_ids,
+ attention_mask=attention_mask,
+ mems=mems,
+ perm_mask=perm_mask,
+ target_mapping=target_mapping,
+ token_type_ids=token_type_ids,
+ input_mask=input_mask,
+ inputs_embeds=inputs_embeds,
+ use_mems=use_mems,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1).contiguous()
+ end_logits = end_logits.squeeze(-1).contiguous()
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ if not return_dict:
+ output = (start_logits, end_logits) + outputs[1:]
+ return ((total_loss,) + output) if total_loss is not None else output
+
+ return XLNetForQuestionAnsweringSimpleOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ mems=outputs.mems,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class XLNetForQuestionAnswering(XLNetPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.start_n_top = config.start_n_top
+ self.end_n_top = config.end_n_top
+
+ self.transformer = XLNetModel(config)
+ self.start_logits = XLNetPoolerStartLogits(config)
+ self.end_logits = XLNetPoolerEndLogits(config)
+ self.answer_class = XLNetPoolerAnswerClass(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ mems: torch.Tensor | None = None,
+ perm_mask: torch.Tensor | None = None,
+ target_mapping: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ input_mask: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ start_positions: torch.Tensor | None = None,
+ end_positions: torch.Tensor | None = None,
+ is_impossible: torch.Tensor | None = None,
+ cls_index: torch.Tensor | None = None,
+ p_mask: torch.Tensor | None = None,
+ use_mems: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs, # delete when `use_cache` is removed in XLNetModel
+ ) -> tuple | XLNetForQuestionAnsweringOutput:
+ r"""
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
+ decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
+ they have already been computed.
+
+ `use_mems` has to be set to `True` to make use of `mems`.
+ perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
+ Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:
+
+ - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
+ - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.
+
+ If not set, each token attends to all the others (full bidirectional attention). Only used during
+ pretraining (to define factorization order) or for sequential decoding (generation).
+ target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
+ Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
+ on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
+ (generation).
+ input_mask (`torch.FloatTensor` of shape `batch_size, sequence_length`, *optional*):
+ Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
+ real tokens and 1 for padding which is kept for compatibility with the original code base.
+
+ Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **masked**,
+ - 0 for tokens that are **not masked**.
+
+ You can only uses one of `input_mask` and `attention_mask`.
+ is_impossible (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels whether a question has an answer or no answer (SQuAD 2.0)
+ cls_index (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for position (index) of the classification token to use as input for computing plausibility of the
+ answer.
+ p_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Optional mask of tokens which can't be in answers (e.g. [CLS], [PAD], ...). 1.0 means token should be
+ masked. 0.0 mean token is not masked.
+ use_mems (`bool`, *optional*):
+ Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
+ states from previous forward passes to compute attention, which can significantly improve performance for
+ sequential decoding tasks.
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, XLNetForQuestionAnswering
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("xlnet/xlnet-base-cased")
+ >>> model = XLNetForQuestionAnswering.from_pretrained("xlnet/xlnet-base-cased")
+
+ >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(
+ ... 0
+ ... ) # Batch size 1
+ >>> start_positions = torch.tensor([1])
+ >>> end_positions = torch.tensor([3])
+ >>> outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions)
+
+ >>> loss = outputs.loss
+ ```"""
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ transformer_outputs = self.transformer(
+ input_ids,
+ attention_mask=attention_mask,
+ mems=mems,
+ perm_mask=perm_mask,
+ target_mapping=target_mapping,
+ token_type_ids=token_type_ids,
+ input_mask=input_mask,
+ inputs_embeds=inputs_embeds,
+ use_mems=use_mems,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ **kwargs,
+ )
+ hidden_states = transformer_outputs[0]
+ start_logits = self.start_logits(hidden_states, p_mask=p_mask)
+
+ outputs = transformer_outputs[1:] # Keep mems, hidden states, attentions if there are in it
+
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, let's remove the dimension added by batch splitting
+ for x in (start_positions, end_positions, cls_index, is_impossible):
+ if x is not None and x.dim() > 1:
+ x.squeeze_(-1)
+
+ # during training, compute the end logits based on the ground truth of the start position
+ end_logits = self.end_logits(hidden_states, start_positions=start_positions, p_mask=p_mask)
+
+ loss_fct = CrossEntropyLoss()
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ if cls_index is not None and is_impossible is not None:
+ # Predict answerability from the representation of CLS and START
+ cls_logits = self.answer_class(hidden_states, start_positions=start_positions, cls_index=cls_index)
+ loss_fct_cls = nn.BCEWithLogitsLoss()
+ cls_loss = loss_fct_cls(cls_logits, is_impossible)
+
+ # note(zhiliny): by default multiply the loss by 0.5 so that the scale is comparable to start_loss and end_loss
+ total_loss += cls_loss * 0.5
+
+ if not return_dict:
+ return (total_loss,) + transformer_outputs[1:]
+ else:
+ return XLNetForQuestionAnsweringOutput(
+ loss=total_loss,
+ mems=transformer_outputs.mems,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+ else:
+ # during inference, compute the end logits based on beam search
+ bsz, slen, hsz = hidden_states.size()
+ start_log_probs = nn.functional.softmax(start_logits, dim=-1) # shape (bsz, slen)
+
+ start_top_log_probs, start_top_index = torch.topk(
+ start_log_probs, self.start_n_top, dim=-1
+ ) # shape (bsz, start_n_top)
+ start_top_index_exp = start_top_index.unsqueeze(-1).expand(-1, -1, hsz) # shape (bsz, start_n_top, hsz)
+ start_states = torch.gather(hidden_states, -2, start_top_index_exp) # shape (bsz, start_n_top, hsz)
+ start_states = start_states.unsqueeze(1).expand(-1, slen, -1, -1) # shape (bsz, slen, start_n_top, hsz)
+
+ hidden_states_expanded = hidden_states.unsqueeze(2).expand_as(
+ start_states
+ ) # shape (bsz, slen, start_n_top, hsz)
+ p_mask = p_mask.unsqueeze(-1) if p_mask is not None else None
+ end_logits = self.end_logits(hidden_states_expanded, start_states=start_states, p_mask=p_mask)
+ end_log_probs = nn.functional.softmax(end_logits, dim=1) # shape (bsz, slen, start_n_top)
+
+ end_top_log_probs, end_top_index = torch.topk(
+ end_log_probs, self.end_n_top, dim=1
+ ) # shape (bsz, end_n_top, start_n_top)
+ end_top_log_probs = end_top_log_probs.view(-1, self.start_n_top * self.end_n_top)
+ end_top_index = end_top_index.view(-1, self.start_n_top * self.end_n_top)
+
+ start_states = torch.einsum(
+ "blh,bl->bh", hidden_states, start_log_probs
+ ) # get the representation of START as weighted sum of hidden states
+ cls_logits = self.answer_class(
+ hidden_states, start_states=start_states, cls_index=cls_index
+ ) # Shape (batch size,): one single `cls_logits` for each sample
+
+ if not return_dict:
+ outputs = (start_top_log_probs, start_top_index, end_top_log_probs, end_top_index, cls_logits)
+ return outputs + transformer_outputs[1:]
+ else:
+ return XLNetForQuestionAnsweringOutput(
+ start_top_log_probs=start_top_log_probs,
+ start_top_index=start_top_index,
+ end_top_log_probs=end_top_log_probs,
+ end_top_index=end_top_index,
+ cls_logits=cls_logits,
+ mems=transformer_outputs.mems,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+__all__ = [
+ "XLNetForMultipleChoice",
+ "XLNetForQuestionAnswering",
+ "XLNetForQuestionAnsweringSimple",
+ "XLNetForSequenceClassification",
+ "XLNetForTokenClassification",
+ "XLNetLMHeadModel",
+ "XLNetModel",
+ "XLNetPreTrainedModel",
+]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlnet/tokenization_xlnet.py b/.venv/lib/python3.12/site-packages/transformers/models/xlnet/tokenization_xlnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b682564bffd0be1b3cab092595ca0030ed07614
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xlnet/tokenization_xlnet.py
@@ -0,0 +1,187 @@
+# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes for XLNet model."""
+
+from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, processors
+from tokenizers.models import Unigram
+
+from ...tokenization_utils_base import _get_prepend_scheme
+from ...tokenization_utils_tokenizers import TokenizersBackend
+from ...utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}
+
+SPIECE_UNDERLINE = "▁"
+
+# Segments (not really needed)
+SEG_ID_A = 0
+SEG_ID_B = 1
+SEG_ID_CLS = 2
+SEG_ID_SEP = 3
+SEG_ID_PAD = 4
+
+
+class XLNetTokenizer(TokenizersBackend):
+ """
+ Construct a XLNet tokenizer (backed by HuggingFace's *tokenizers* library). Based on
+ [Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models).
+
+ This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should
+ refer to this superclass for more information regarding those methods.
+
+ Args:
+ vocab (`list of tuples`, *optional*):
+ List of (token, score) tuples for Unigram model. If not provided, an empty list is used.
+ unk_id (`int`, *optional*, defaults to 0):
+ The ID of the unknown token in the vocabulary.
+ do_lower_case (`bool`, *optional*, defaults to `False`):
+ Whether to lowercase the input when tokenizing.
+ remove_space (`bool`, *optional*, defaults to `True`):
+ Whether to strip the text when tokenizing (removing excess spaces before and after the string).
+ keep_accents (`bool`, *optional*, defaults to `False`):
+ Whether to keep accents when tokenizing.
+ bos_token (`str`, *optional*, defaults to `""`):
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
+ sequence. The token used is the `cls_token`.
+
+
+
+ eos_token (`str`, *optional*, defaults to `""`):
+ The end of sequence token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
+ The token used is the `sep_token`.
+
+
+
+ unk_token (`str`, *optional*, defaults to `""`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ sep_token (`str`, *optional*, defaults to `""`):
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
+ sequence classification or for a text and a question for question answering. It is also used as the last
+ token of a sequence built with special tokens.
+ pad_token (`str`, *optional*, defaults to `""`):
+ The token used for padding, for example when batching sequences of different lengths.
+ cls_token (`str`, *optional*, defaults to `""`):
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
+ mask_token (`str`, *optional*, defaults to `""`):
+ The token used for masking values. This is the token used when training this model with masked language
+ modeling. This is the token which the model will try to predict.
+ additional_special_tokens (`list[str]`, *optional*, defaults to `["", ""]`):
+ Additional special tokens used by the tokenizer.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ padding_side = "left"
+ model = Unigram
+
+ def __init__(
+ self,
+ vocab: str | list[tuple[str, float]] | None = None,
+ unk_id: int = 0,
+ do_lower_case=False,
+ remove_space=True,
+ keep_accents=False,
+ bos_token="",
+ eos_token="",
+ unk_token="",
+ sep_token="",
+ pad_token="",
+ cls_token="",
+ mask_token="",
+ additional_special_tokens=None,
+ **kwargs,
+ ):
+ if additional_special_tokens is None:
+ additional_special_tokens = ["", ""]
+
+ if vocab is not None:
+ self._vocab = vocab
+ else:
+ self._vocab = [(str(unk_token), 0.0)]
+
+ self._tokenizer = Tokenizer(
+ Unigram(
+ self._vocab,
+ unk_id=unk_id,
+ byte_fallback=False,
+ )
+ )
+
+ list_normalizers = [
+ normalizers.Replace("``", '"'),
+ normalizers.Replace("''", '"'),
+ ]
+ # if not keep_accents:
+ list_normalizers.append(normalizers.NFKD())
+ list_normalizers.append(normalizers.StripAccents())
+ if do_lower_case:
+ list_normalizers.append(normalizers.Lowercase())
+
+ list_normalizers.append(normalizers.Replace(Regex(" {2,}"), " "))
+ self._tokenizer.normalizer = normalizers.Sequence(list_normalizers)
+
+ add_prefix_space = True
+ prepend_scheme = _get_prepend_scheme(add_prefix_space, self)
+ self._tokenizer.pre_tokenizer = pre_tokenizers.Sequence(
+ [
+ pre_tokenizers.WhitespaceSplit(),
+ pre_tokenizers.Metaspace(replacement="▁", prepend_scheme=prepend_scheme),
+ ]
+ )
+
+ self._tokenizer.decoder = decoders.Metaspace(replacement="▁", prepend_scheme=prepend_scheme)
+ self._pad_token_type_id = 3
+ self.do_lower_case = do_lower_case
+ self.remove_space = remove_space
+ self.keep_accents = keep_accents
+ mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
+ super().__init__(
+ unk_id=unk_id,
+ do_lower_case=do_lower_case,
+ remove_space=remove_space,
+ keep_accents=keep_accents,
+ bos_token=bos_token,
+ eos_token=eos_token,
+ unk_token=unk_token,
+ sep_token=sep_token,
+ pad_token=pad_token,
+ cls_token=cls_token,
+ mask_token=mask_token,
+ additional_special_tokens=additional_special_tokens,
+ **kwargs,
+ )
+
+ self._tokenizer.post_processor = processors.TemplateProcessing(
+ single=f"$A:0 {str(self.sep_token)}:0 {str(self.cls_token)}:2",
+ pair=f"$A:0 {str(self.sep_token)}:0 $B:1 {str(self.sep_token)}:1 {str(self.cls_token)}:2",
+ special_tokens=[
+ (str(self.sep_token), self.sep_token_id),
+ (str(self.cls_token), self.cls_token_id),
+ ],
+ )
+
+
+__all__ = ["XLNetTokenizer"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlstm/__init__.py b/.venv/lib/python3.12/site-packages/transformers/models/xlstm/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..00e206973a908d82e9b8fe38a3d016fcced9ecd3
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xlstm/__init__.py
@@ -0,0 +1,31 @@
+# Copyright 2025 NXAI GmbH. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import (
+ OptionalDependencyNotAvailable,
+ _LazyModule,
+ is_torch_available,
+)
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from configuration_xlstm import *
+ from modeling_xlstm import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlstm/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xlstm/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f570000cf7fb2998d72c38e4eb48e5a801e470fb
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xlstm/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlstm/__pycache__/configuration_xlstm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xlstm/__pycache__/configuration_xlstm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5884accd3fbfb74ab74ecc73a6d0e9a951add126
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xlstm/__pycache__/configuration_xlstm.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlstm/__pycache__/modeling_xlstm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xlstm/__pycache__/modeling_xlstm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..888de98d77b77403ab304356d1624b77a16f7030
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xlstm/__pycache__/modeling_xlstm.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlstm/configuration_xlstm.py b/.venv/lib/python3.12/site-packages/transformers/models/xlstm/configuration_xlstm.py
new file mode 100644
index 0000000000000000000000000000000000000000..ebac2353d7071cecf1eb1d1464ece18f5ec5ee5a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xlstm/configuration_xlstm.py
@@ -0,0 +1,218 @@
+# Copyright 2025 NXAI GmbH. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""xLSTM configuration."""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring, is_xlstm_available
+
+
+if is_xlstm_available():
+ from xlstm.xlstm_large.model import (
+ BackendModeType,
+ ChunkwiseKernelType,
+ DtypeType,
+ SequenceKernelType,
+ StepKernelType,
+ WeightModeType,
+ round_up_to_next_multiple_of,
+ xLSTMLargeConfig,
+ )
+
+ external_xlstm = True
+else:
+ from typing import Literal
+
+ BackendModeType = Literal["train", "train_with_padding", "inference"]
+ ChunkwiseKernelType = Literal[
+ "chunkwise--native_autograd",
+ "parallel--native_autograd",
+ ]
+ DtypeType = Literal["float32", "bfloat16", "float16"]
+ SequenceKernelType = Literal["native_sequence__native"]
+ StepKernelType = Literal["native"]
+ WeightModeType = Literal["single", "fused"]
+
+ def round_up_to_next_multiple_of(x: int, multiple_of: int) -> int:
+ """Rounds up x to the next multiple of multiple_of."""
+ return int(((x + multiple_of - 1) // multiple_of) * multiple_of)
+
+ external_xlstm = False
+
+
+@auto_docstring(checkpoint="NX-AI/xLSTM-7b")
+@strict
+class xLSTMConfig(PreTrainedConfig):
+ r"""
+ num_blocks (int, optional, *optional*, defaults to 32):
+ Number of blocks of the xLSTM model, use num_hidden_layers if None.
+ num_heads (int, optional, *optional*, defaults to 8):
+ Number of heads for the xLSTM Layer/Cell.
+ use_bias (bool, optional, *optional*, defaults to `False`):
+ Whether to use biases in the xLSTM model.
+ norm_reduction_force_float32 (bool, optional, *optional*, defaults to `True`):
+ Whether to force the float32 norm reduction op to be done in fp32 precision.
+ add_out_norm (bool, optional, *optional*, defaults to `True`):
+ Whether to add an output norm after the blocks before the LMHead.
+ qk_dim_factor (float, optional, *optional*, defaults to 0.5):
+ Scale factor for the query and key dimension.
+ v_dim_factor (float, optional, *optional*, defaults to 1.0):
+ Scale factor for the value dimension.
+ chunkwise_kernel (ChunkwiseKernelType, optional, *optional*, defaults to `"chunkwise--native_autograd"`):
+ Kernel type for chunkwise processing mode.
+ sequence_kernel (SequenceKernelType, optional, *optional*, defaults to `"native_sequence__native"`):
+ Kernel type for sequence processing mode.
+ step_kernel (StepKernelType, optional, *optional*, defaults to `"native"`):
+ Kernel type for step processing mode.
+ mode (BackendModeType, optional, *optional*, defaults to `"inference"`):
+ Operation mode (inference is needed for generation).
+ chunk_size (int, optional, *optional*, defaults to 64):
+ Internal chunk size.
+ return_last_states (bool, optional, *optional*, defaults to `True`):
+ If to return the last states / cache internally. Needed as True for generation.
+ autocast_kernel_dtype (DtypeType, optional, *optional*, defaults to `"bfloat16"`):
+ Kernel dtype for the states.
+ inference_state_dtype (DtypeType, optional, *optional*, defaults to `"float32"`):
+ Kernel dtype for states in inference.
+ ffn_proj_factor (float, optional, *optional*, defaults to 2.667):
+ Size factor of the post-up projection gated Feed Forward network.
+ ffn_round_up_to_multiple_of (int, optional, *optional*, defaults to 64):
+ Size factor round value of the post-up projection gated Feed Forward network.
+ gate_soft_cap (float, optional, *optional*, defaults to 15.0):
+ Gate soft cap scale.
+ output_logit_soft_cap (float, optional, *optional*, defaults to 30.0):
+ Output logit soft cap scale.
+ weight_mode (`Literal`, *optional*, defaults to `"single"`):
+ Whether parallel linear layers are separated or fused (single).
+ max_inference_chunksize (int, optional, *optional*, defaults to 16384):
+ Limit the chunk size for inference to save memory.
+
+ Example:
+
+ ```python
+ >>> from transformers import xLSTMConfig, xLSTMModel
+
+ >>> # Initializing a xLSTM configuration
+ >>> configuration = xLSTMConfig()
+
+ >>> # Initializing a model (with random weights) from the configuration
+ >>> model = xLSTMModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "xlstm"
+
+ vocab_size: int = 50304
+ hidden_size: int = 4096
+ embedding_dim: int | None = None
+ num_hidden_layers: int = 32
+ num_blocks: int | None = None
+ num_heads: int = 8
+ use_bias: bool = False
+ norm_reduction_force_float32: bool = True
+ tie_word_embeddings: bool = False
+ add_out_norm: bool = True
+ norm_eps: float = 1e-6
+ qk_dim_factor: float = 0.5
+ v_dim_factor: float = 1.0
+ chunkwise_kernel: ChunkwiseKernelType = "chunkwise--native_autograd"
+ sequence_kernel: SequenceKernelType = "native_sequence__native"
+ step_kernel: StepKernelType = "native"
+ mode: BackendModeType = "inference"
+ chunk_size: int = 64
+ return_last_states: bool = True
+ autocast_kernel_dtype: DtypeType = "bfloat16"
+ eps: float = 1e-6
+ inference_state_dtype: DtypeType = "float32"
+ ffn_proj_factor: float = 2.667
+ ffn_round_up_to_multiple_of: int = 64
+ gate_soft_cap: float = 15.0
+ output_logit_soft_cap: float = 30.0
+ weight_mode: WeightModeType = "single"
+ use_cache: bool = True
+ pad_token_id: int | None = 1
+ bos_token_id: int | None = 0
+ eos_token_id: int | list[int] | None = 2
+ max_inference_chunksize: int = 16384
+
+ def __post_init__(self, **kwargs):
+ self.hidden_size = self.hidden_size if self.hidden_size is not None else self.embedding_dim
+ self.embedding_dim = self.embedding_dim if self.embedding_dim is not None else self.hidden_size
+ self.num_hidden_layers = self.num_hidden_layers if self.num_hidden_layers is not None else self.num_blocks
+ self.num_blocks = self.num_blocks if self.num_blocks is not None else self.num_hidden_layers
+ super().__post_init__(**kwargs)
+
+ @property
+ def qk_dim(self):
+ return round_up_to_next_multiple_of(
+ self.hidden_size * self.qk_dim_factor,
+ multiple_of=64,
+ )
+
+ @property
+ def v_dim(self):
+ return round_up_to_next_multiple_of(
+ self.hidden_size * self.v_dim_factor,
+ multiple_of=64,
+ )
+
+ @property
+ def qk_head_dim(self):
+ return self.qk_dim // self.num_heads
+
+ @property
+ def v_head_dim(self):
+ return self.v_dim // self.num_heads
+
+ def to_xlstm_block_config(self):
+ if external_xlstm:
+ return xLSTMLargeConfig(
+ vocab_size=self.vocab_size,
+ embedding_dim=self.hidden_size,
+ num_blocks=self.num_hidden_layers,
+ num_heads=self.num_heads,
+ use_bias=self.use_bias,
+ add_out_norm=self.add_out_norm,
+ norm_eps=self.norm_eps,
+ norm_reduction_force_float32=self.norm_reduction_force_float32,
+ # mlstm_layer
+ qk_dim_factor=self.qk_dim_factor,
+ v_dim_factor=self.v_dim_factor,
+ # mlstm backend
+ chunkwise_kernel=self.chunkwise_kernel,
+ sequence_kernel=self.sequence_kernel,
+ step_kernel=self.step_kernel,
+ mode=self.mode,
+ chunk_size=self.chunk_size,
+ return_last_states=self.return_last_states,
+ autocast_kernel_dtype=self.autocast_kernel_dtype,
+ eps=self.eps,
+ inference_state_dtype=self.inference_state_dtype,
+ # feedforward
+ ffn_proj_factor=self.ffn_proj_factor,
+ ffn_round_up_to_multiple_of=self.ffn_round_up_to_multiple_of,
+ # capping
+ gate_soft_cap=self.gate_soft_cap,
+ output_logit_soft_cap=self.output_logit_soft_cap,
+ weight_mode=self.weight_mode,
+ )
+ else:
+ return self
+
+
+__all__ = ["xLSTMConfig"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xlstm/modeling_xlstm.py b/.venv/lib/python3.12/site-packages/transformers/models/xlstm/modeling_xlstm.py
new file mode 100644
index 0000000000000000000000000000000000000000..84eeeb7c45149a714eda76a029da2d8b569334fd
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xlstm/modeling_xlstm.py
@@ -0,0 +1,1600 @@
+# Copyright 2025 NXAI GmbH. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch xLSTM Model."""
+
+from dataclasses import dataclass
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+from torch.nn import CrossEntropyLoss
+
+from ... import initialization as init
+from ...generation import GenerationMixin
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_utils import PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import ModelOutput, TransformersKwargs, auto_docstring, can_return_tuple, is_xlstm_available
+from ...utils.generic import merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_xlstm import xLSTMConfig
+
+
+if is_xlstm_available():
+ from xlstm.xlstm_large.model import RMSNorm as xLSTMRMSNorm
+ from xlstm.xlstm_large.model import mLSTMBlock, mLSTMStateType, soft_cap
+
+ external_xlstm = True
+
+ class xLSTMBlock(GradientCheckpointingLayer, mLSTMBlock):
+ pass
+
+else:
+ from collections.abc import Callable
+ from functools import partial
+ from typing import Literal
+
+ from .configuration_xlstm import round_up_to_next_multiple_of
+
+ mLSTMLayerStateType = tuple[torch.Tensor, torch.Tensor, torch.Tensor]
+ mLSTMStateType = dict[int, mLSTMLayerStateType]
+
+ external_xlstm = False
+
+ def soft_cap(values: torch.Tensor, cap_value: float | torch.Tensor | None = None) -> torch.Tensor:
+ """
+ Soft caps a tensor to a value.
+
+ Performs a tanh operation on the logits and scales the result to the cap value. Common technique in attention
+ and output language heads to prevent large logits from dominating the softmax. See for example Gemma2:
+ https://huggingface.co/papers/2408.00118
+
+ Args:
+ values: The tensor to cap.
+ cap_value: The value to cap the values to. If None, no cap is applied.
+
+ Returns:
+ The capped values.
+ """
+ if cap_value is None:
+ return values
+ return cap_value * torch.tanh(values / cap_value)
+
+ def mlstm_chunkwise_recurrent_fw_C(
+ matK: torch.Tensor,
+ matV: torch.Tensor,
+ vecB: torch.Tensor,
+ vecI: torch.Tensor,
+ matC_states: torch.Tensor | None = None,
+ vecN_states: torch.Tensor | None = None,
+ scaMinter_states: torch.Tensor | None = None,
+ matC_initial: torch.Tensor | None = None,
+ vecN_initial: torch.Tensor | None = None,
+ scaMinter_initial: torch.Tensor | None = None,
+ qk_scale: float | None = None,
+ chunk_size: int = 64,
+ num_chunks: int = 1,
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ batch_size, nh, _, dhqk, dhhv = *matK.shape, matV.shape[-1]
+ nc = num_chunks
+ _dtype, _device = matK.dtype, matK.device
+
+ if qk_scale is None:
+ qk_scale = dhqk**-0.5
+
+ # initialize the states tensors
+ if matC_states is None:
+ matC_states = torch.zeros((batch_size, nh, (nc + 1) * dhqk, dhhv), dtype=_dtype, device=_device)
+ if vecN_states is None:
+ vecN_states = torch.zeros((batch_size, nh, (nc + 1) * dhqk), dtype=_dtype, device=_device)
+ if scaMinter_states is None:
+ scaMinter_states = torch.zeros((batch_size, nh, (nc + 1)), dtype=_dtype, device=_device)
+
+ # assign the initial states to the running states
+ matC_k = (
+ torch.zeros((batch_size, nh, dhqk, dhhv), dtype=_dtype, device=_device)
+ if matC_initial is None
+ else matC_initial
+ )
+ vecN_k = (
+ torch.zeros((batch_size, nh, dhqk), dtype=_dtype, device=_device) if vecN_initial is None else vecN_initial
+ )
+ scaM_inter_k = (
+ torch.zeros((batch_size, nh, 1), dtype=_dtype, device=_device)
+ if scaMinter_initial is None
+ else scaMinter_initial
+ )
+ vecA = vecB[..., -1, None] - vecB + vecI
+ scaG = vecB[..., -1]
+ scaA_max = vecA.max(-1).values
+
+ scaM_inter_k = scaM_inter_k.squeeze(-1)
+
+ for key in range(0, num_chunks):
+ # store the states from the previous iteration before updating them
+ # in the first iteration, these are the initial states
+ matC_states[:, :, key * dhqk : (key + 1) * dhqk, :] = matC_k
+ vecN_states[:, :, key * dhqk : (key + 1) * dhqk] = vecN_k
+ scaMinter_states[:, :, key] = scaM_inter_k
+
+ # m_k update
+ scaA_max_k = scaA_max[:, :, key]
+ scaG_k = scaG[:, :, key]
+ scaM_inter_k_next = torch.max(scaG_k + scaM_inter_k, scaA_max_k)
+ # C_k update
+ matK_chunk = matK[:, :, key * chunk_size : (key + 1) * chunk_size, :] # * qk_scale
+ matV_chunk = matV[:, :, key * chunk_size : (key + 1) * chunk_size, :]
+ vecA_k = vecA[:, :, key, :]
+
+ vecAbar_k = torch.exp(vecA_k - scaM_inter_k_next[..., None])[:, :, :, None]
+
+ matK_chunk_gated = matK_chunk * vecAbar_k
+
+ scaGbar_k = torch.exp(scaG_k + scaM_inter_k - scaM_inter_k_next)[:, :, None]
+
+ # NOTE: no update in-place (i.e. +=) as this gives error for autograd backward
+ matC_k_next = scaGbar_k[..., None] * matC_k + matK_chunk_gated.transpose(-2, -1) @ (matV_chunk)
+
+ # n_k update
+ vecN_k_next = scaGbar_k * vecN_k + matK_chunk_gated.transpose(-2, -1).sum(-1)
+
+ # move to the next iteration
+ scaM_inter_k = scaM_inter_k_next
+ matC_k = matC_k_next
+ vecN_k = vecN_k_next
+
+ # store the states from the last iteration
+ matC_states[:, :, -dhqk:, :] = matC_k
+ vecN_states[:, :, -dhqk:] = vecN_k
+ scaMinter_states[:, :, -1] = scaM_inter_k
+
+ return matC_states, vecN_states, scaMinter_states
+
+ def mlstm_chunkwise_parallel_fw_H(
+ matQ: torch.Tensor,
+ matK: torch.Tensor,
+ matV: torch.Tensor,
+ # these states must be all states up to the last chunk, i.e. :-1
+ matC_states: torch.Tensor,
+ vecN_states: torch.Tensor,
+ scaMinter_states: torch.Tensor,
+ vecI: torch.Tensor,
+ vecB: torch.Tensor,
+ qk_scale: float,
+ chunk_size: int = 64,
+ num_chunks: int = 1,
+ eps: float = 1e-6,
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ _device = matQ.device
+ nc = num_chunks
+ batch_size, nh, dqk, dhv = matC_states.shape
+ dhqk = dqk // nc
+ matC_k_states = matC_states.view(batch_size, nh, nc, dhqk, dhv)
+ vecN_k_states = vecN_states.view(batch_size, nh, nc, dhqk)
+ scaMinter_k_states = scaMinter_states
+
+ matQ = matQ.view(batch_size, nh, nc, chunk_size, dhqk)
+ matK = matK.view(batch_size, nh, nc, chunk_size, dhqk)
+ matV = matV.view(batch_size, nh, nc, chunk_size, dhv)
+
+ ltr = torch.tril(
+ torch.ones(
+ (chunk_size, chunk_size),
+ dtype=torch.bool,
+ device=_device,
+ )
+ )
+
+ # Compute intra chunk contribution: H_intra
+ matF_logsig_chunk = vecB[:, :, :, :, None] - vecB[:, :, :, None, :]
+
+ matF_logsig_mask_chunk = torch.where(ltr, matF_logsig_chunk, -float("inf"))
+
+ matLogD_chunk = matF_logsig_mask_chunk + vecI[:, :, :, None, :]
+
+ # max_state intra
+ vecMintra_k = torch.max(matLogD_chunk, dim=-1, keepdim=False).values
+
+ # max_state combined
+ vecM_b_inter = vecB + scaMinter_k_states[:, :, :, None]
+ vecM_k_combine = torch.maximum(vecM_b_inter, vecMintra_k)
+
+ vecM_k_combine = vecM_k_combine[:, :, :, :, None]
+ vecM_b_inter = vecM_b_inter[:, :, :, :, None]
+
+ matLogD_stabilized_chunk = matLogD_chunk - vecM_k_combine
+ matD_chunk = torch.exp(matLogD_stabilized_chunk)
+
+ matS_chunk = (matQ @ matK.transpose(-2, -1)) * qk_scale
+
+ matM_chunk = matS_chunk * matD_chunk
+
+ # ? Combine H_intra with H_inter
+ vecBbar = torch.exp(vecM_b_inter - vecM_k_combine)
+ matQ_chunk_gated = matQ * vecBbar * qk_scale
+
+ matNumerator_common = matQ_chunk_gated @ matC_k_states + matM_chunk @ matV
+
+ vecDenom_l_common = matQ_chunk_gated @ vecN_k_states.unsqueeze(-1) + matM_chunk.sum(dim=-1, keepdim=True)
+
+ vecDenom_max_common = torch.maximum(torch.abs(vecDenom_l_common), torch.exp(-vecM_k_combine))
+
+ matH_k_chunk = matNumerator_common / (vecDenom_max_common + eps)
+
+ matH_out = matH_k_chunk.view(batch_size, nh, nc * chunk_size, dhv)
+
+ # we need the denominator and the overall max state for the backward pass
+ vecN_out = vecDenom_max_common.reshape(batch_size, nh, nc * chunk_size)
+ vecM_out = vecM_k_combine.reshape(batch_size, nh, nc * chunk_size)
+ return matH_out, vecN_out, vecM_out
+
+ def mlstm_chunkwise_fw(
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ igate: torch.Tensor,
+ fgate: torch.Tensor,
+ cstate: torch.Tensor | None = None,
+ nstate: torch.Tensor | None = None,
+ mstate: torch.Tensor | None = None,
+ qk_scale: float | None = None,
+ return_last_states: bool = False,
+ return_all_states: bool = False,
+ chunk_size: int = 64,
+ eps: float = 1e-6,
+ ) -> tuple[
+ torch.Tensor,
+ torch.Tensor,
+ torch.Tensor,
+ tuple[torch.Tensor, torch.Tensor, torch.Tensor] | None,
+ tuple[torch.Tensor, torch.Tensor, torch.Tensor] | None,
+ ]:
+ batch_size, nh, sequence_length, dhqk = query.shape
+ if sequence_length % chunk_size != 0:
+ raise ValueError(f"Sequence length {sequence_length} is not divisible by chunk size {chunk_size}.")
+ nc = sequence_length // chunk_size
+
+ vecI = igate.view(batch_size, nh, nc, chunk_size)
+ vecF = fgate.view(batch_size, nh, nc, chunk_size)
+
+ # compute the gates, the g and the a and b vectors
+ vecF_logsig = fgate.logsigmoid(vecF)
+ vecB = vecF_logsig.cumsum(-1)
+
+ if qk_scale is None:
+ qk_scale = dhqk**-0.5
+
+ #! materialize the C_k, n_k, m_k states for each chunk
+ matC_k_states, vecN_k_states, scaMinter_k_states = mlstm_chunkwise_recurrent_fw_C(
+ matK=key,
+ matV=value,
+ vecB=vecB,
+ vecI=vecI,
+ matC_initial=cstate,
+ vecN_initial=nstate,
+ scaMinter_initial=mstate,
+ qk_scale=qk_scale,
+ chunk_size=chunk_size,
+ num_chunks=nc,
+ )
+
+ #! compute the outputs within each chunk
+ matH_out, vecN_out, vecM_out = mlstm_chunkwise_parallel_fw_H(
+ matQ=query,
+ matK=key,
+ matV=value,
+ matC_states=matC_k_states[:, :, :-dhqk, :],
+ vecN_states=vecN_k_states[:, :, :-dhqk],
+ scaMinter_states=scaMinter_k_states[:, :, :-1],
+ vecI=vecI,
+ vecB=vecB,
+ qk_scale=qk_scale,
+ chunk_size=chunk_size,
+ num_chunks=nc,
+ eps=eps,
+ )
+
+ ret_tuple = (matH_out, vecN_out, vecM_out)
+ if return_last_states:
+ ret_tuple += (
+ (matC_k_states[:, :, -dhqk:, :], vecN_k_states[:, :, -dhqk:], scaMinter_k_states[:, :, -1:]),
+ )
+ else:
+ ret_tuple += (None,)
+
+ if return_all_states:
+ ret_tuple += ((matC_k_states, vecN_k_states, scaMinter_k_states),)
+ else:
+ ret_tuple += (None,)
+
+ return ret_tuple
+
+ def mlstm_chunkwise_native_autograd(
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ igate: torch.Tensor,
+ fgate: torch.Tensor,
+ c_initial: torch.Tensor | None = None,
+ n_initial: torch.Tensor | None = None,
+ m_initial: torch.Tensor | None = None,
+ return_last_states: bool = False,
+ eps: float = 1e-6,
+ chunk_size: int = 64,
+ **kwargs,
+ ) -> torch.Tensor | tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor, torch.Tensor]]:
+ batch_size, nh, sequence_length, dhqk = query.shape
+ if sequence_length % chunk_size != 0:
+ raise ValueError(f"Sequence length {sequence_length} is not divisible by chunk size {chunk_size}.")
+ nc = sequence_length // chunk_size
+
+ vecI = igate.view(batch_size, nh, nc, chunk_size)
+ vecF = fgate.view(batch_size, nh, nc, chunk_size)
+
+ # compute the gates, the g and the a and b vectors
+ vecF_logsig = F.logsigmoid(vecF)
+ vecB = vecF_logsig.cumsum(-1)
+
+ qk_scale = dhqk**-0.5
+
+ #! materialize the C_k, n_k, m_k states for each chunk
+ matC_k_states, vecN_k_states, scaMinter_k_states = mlstm_chunkwise_recurrent_fw_C(
+ matK=key,
+ matV=value,
+ vecB=vecB,
+ vecI=vecI,
+ matC_initial=c_initial,
+ vecN_initial=n_initial,
+ scaMinter_initial=m_initial,
+ qk_scale=qk_scale,
+ chunk_size=chunk_size,
+ num_chunks=nc,
+ )
+
+ #! compute the outputs within each chunk
+ matH_out, vecN_out, vecM_out = mlstm_chunkwise_parallel_fw_H(
+ matQ=query,
+ matK=key,
+ matV=value,
+ matC_states=matC_k_states[:, :, :-dhqk, :],
+ vecN_states=vecN_k_states[:, :, :-dhqk],
+ scaMinter_states=scaMinter_k_states[:, :, :-1],
+ vecI=vecI,
+ vecB=vecB,
+ qk_scale=qk_scale,
+ chunk_size=chunk_size,
+ num_chunks=nc,
+ eps=eps,
+ )
+
+ last_states = (matC_k_states[:, :, -dhqk:, :], vecN_k_states[:, :, -dhqk:], scaMinter_k_states[:, :, -1:])
+
+ if return_last_states:
+ return matH_out, last_states
+ else:
+ return matH_out
+
+ def mlstm_recurrent_step_native(
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ igate: torch.Tensor,
+ fgate: torch.Tensor,
+ cstate: torch.Tensor,
+ nstate: torch.Tensor,
+ mstate: torch.Tensor,
+ eps: float = 1e-6,
+ dtype_state: torch.dtype = torch.float32,
+ **kwargs,
+ ) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor, torch.Tensor]]:
+ """This is a single step of the mLSTM operation in recurrent form."""
+ dtype_qkv = query.dtype
+ matC_old = cstate.to(dtype=dtype_state)
+ vecN_old = nstate.to(dtype=dtype_state)
+ scaM_old = mstate.to(dtype=dtype_state)
+
+ batch_size, nh, dhqk = query.shape
+ _, _, dhhv = value.shape
+ if query.shape != key.shape:
+ raise ValueError("query and key must have the same shape")
+ if matC_old.shape != (batch_size, nh, dhqk, dhhv):
+ raise ValueError(f"matC_old has wrong shape, got {matC_old.shape}")
+ if vecN_old.shape != (batch_size, nh, dhqk):
+ raise ValueError(f"vecN_old has wrong shape, got {vecN_old.shape}")
+ if scaM_old.shape != (batch_size, nh, 1):
+ raise ValueError(f"scaM_old has wrong shape, got {scaM_old.shape}")
+ if igate.shape != (batch_size, nh, 1):
+ raise ValueError(f"scaI has wrong shape, got {igate.shape}")
+ if fgate.shape != (batch_size, nh, 1):
+ raise ValueError(f"scaF has wrong shape, got {fgate.shape}")
+
+ # gates
+ scaF_log = torch.nn.functional.logsigmoid(fgate)
+
+ # update rule
+ scaM_state_new = torch.max(scaF_log + scaM_old, igate)
+
+ scaF_act = torch.exp(scaF_log + scaM_old - scaM_state_new)
+ scaI_act = torch.exp(igate - scaM_state_new)
+
+ vecQ_scaled = query * (dhqk ** (-0.5))
+ matC_state_new = scaF_act[:, :, :, None] * matC_old.clone() + scaI_act[:, :, :, None] * (
+ key[:, :, :, None] @ value[:, :, None, :]
+ )
+ vecN_state_new = scaF_act * vecN_old.clone() + scaI_act * key
+ h_num = vecQ_scaled[:, :, None, :] @ matC_state_new.to(dtype=dtype_qkv)
+ h_num = h_num.squeeze(2).to(dtype=dtype_state)
+
+ qn_dotproduct = vecQ_scaled[:, :, None, :] @ vecN_state_new[:, :, :, None].to(dtype=dtype_qkv)
+ qn_dotproduct = qn_dotproduct.squeeze(2)
+ max_val = torch.exp(-scaM_state_new)
+ h_denom = (torch.maximum(qn_dotproduct.abs(), max_val) + eps).to(dtype=dtype_state)
+ h = h_num / h_denom
+
+ h = h.to(dtype=dtype_qkv)
+ matC_state_new = matC_state_new.to(dtype=dtype_state)
+ vecN_state_new = vecN_state_new.to(dtype=dtype_state)
+ scaM_state_new = scaM_state_new.to(dtype=dtype_state)
+ return h, (matC_state_new, vecN_state_new, scaM_state_new)
+
+ def mlstm_recurrent_sequence_native(
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ igate: torch.Tensor,
+ fgate: torch.Tensor,
+ c_initial: torch.Tensor | None = None,
+ n_initial: torch.Tensor | None = None,
+ m_initial: torch.Tensor | None = None,
+ return_last_states: bool = False,
+ eps: float = 1e-6,
+ dtype_state: torch.dtype = torch.float32,
+ **kwargs,
+ ) -> tuple[
+ torch.Tensor,
+ torch.Tensor,
+ torch.Tensor,
+ tuple[torch.Tensor, torch.Tensor, torch.Tensor] | None,
+ tuple[torch.Tensor, torch.Tensor, torch.Tensor] | None,
+ ]:
+ batch_size, nh, sequence_length, dhqk = query.shape
+ dhv = value.shape[-1]
+ device = query.device
+
+ if c_initial is not None:
+ if n_initial is None or m_initial is None:
+ raise ValueError("Initial states must be provided together.")
+ if n_initial is None or m_initial is None:
+ raise ValueError("Initial states must be provided together.")
+ matC_state, vecN_state, vecM_state = (
+ c_initial.to(dtype=dtype_state),
+ n_initial.to(dtype=dtype_state),
+ m_initial.to(dtype=dtype_state),
+ )
+ else:
+ # memory state
+ matC_state = torch.zeros((batch_size, nh, dhqk, dhv), dtype=dtype_state, device=device)
+ # normalizer state
+ vecN_state = torch.zeros((batch_size, nh, dhqk), dtype=dtype_state, device=device)
+ # max state
+ vecM_state = torch.zeros((batch_size, nh, 1), dtype=dtype_state, device=device)
+
+ vecH_list = []
+ for t in range(sequence_length):
+ # gates
+ vecF_t, vecI_t = fgate[:, :, t, None], igate[:, :, t, None]
+
+ # projections
+ vecQ_t, vecK_t, vecV_t = query[:, :, t, :], key[:, :, t, :], value[:, :, t, :]
+
+ # step
+ vecH, (matC_state, vecN_state, vecM_state) = mlstm_recurrent_step_native(
+ cstate=matC_state,
+ nstate=vecN_state,
+ mstate=vecM_state,
+ query=vecQ_t,
+ key=vecK_t,
+ value=vecV_t,
+ igate=vecI_t,
+ fgate=vecF_t,
+ eps=eps,
+ dtype_state=dtype_state,
+ **kwargs,
+ )
+ vecH_list.append(vecH)
+
+ matH = torch.stack(vecH_list, dim=-2)
+
+ if return_last_states:
+ return matH, (matC_state, vecN_state, vecM_state)
+ else:
+ return matH
+
+ def wrap_chunkwise_pad_zeros(
+ mlstm_chunkwise_kernel: Callable,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ fgate: torch.Tensor,
+ igate: torch.Tensor,
+ c_initial: torch.Tensor | None = None,
+ n_initial: torch.Tensor | None = None,
+ m_initial: torch.Tensor | None = None,
+ return_last_states: bool = False,
+ eps: float = 1e-6,
+ autocast_kernel_dtype: torch.dtype = torch.bfloat16,
+ chunk_size: int = 64,
+ **kwargs,
+ ) -> torch.Tensor | tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor, torch.Tensor]]:
+ if return_last_states:
+ raise ValueError(
+ "We are padding zeros, so we cannot return last states,",
+ "as they would be not the true last states.",
+ )
+
+ batch_size, nh, sequence_length, dhqk = query.shape
+ S_unpadded = sequence_length
+ # padding to chunk size for kernels
+ if sequence_length % chunk_size != 0:
+ S_padded = ((sequence_length + chunk_size - 1) // chunk_size) * chunk_size
+ q_pad = query.new_zeros(batch_size, nh, S_padded, query.shape[3])
+ k_pad = key.new_zeros(batch_size, nh, S_padded, key.shape[3])
+ v_pad = value.new_zeros(batch_size, nh, S_padded, value.shape[3])
+ i_pad = igate.new_zeros(batch_size, nh, S_padded)
+ f_pad = fgate.new_zeros(batch_size, nh, S_padded)
+ q_pad[:, :, :S_unpadded, :] = query
+ k_pad[:, :, :S_unpadded, :] = key
+ v_pad[:, :, :S_unpadded, :] = value
+ i_pad[:, :, :S_unpadded] = igate
+ f_pad[:, :, :S_unpadded] = fgate
+ else:
+ q_pad = query
+ k_pad = key
+ v_pad = value
+ i_pad = igate
+ f_pad = fgate
+
+ matH = mlstm_chunkwise_kernel(
+ query=q_pad,
+ key=k_pad,
+ value=v_pad,
+ igate=i_pad,
+ fgate=f_pad,
+ c_initial=c_initial,
+ n_initial=n_initial,
+ m_initial=m_initial,
+ return_last_states=return_last_states,
+ eps=eps,
+ autocast_kernel_dtype=autocast_kernel_dtype,
+ chunk_size=chunk_size,
+ **kwargs,
+ )
+ matH = matH[:, :, :S_unpadded, :]
+ return matH
+
+ def wrap_chunkwise_arbitrary_sequence_length(
+ mlstm_chunkwise_kernel: Callable,
+ mlstm_sequence_kernel: Callable,
+ mlstm_step_kernel: Callable,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ fgate: torch.Tensor,
+ igate: torch.Tensor,
+ c_initial: torch.Tensor | None = None,
+ n_initial: torch.Tensor | None = None,
+ m_initial: torch.Tensor | None = None,
+ return_last_states: bool = True,
+ eps: float = 1e-6,
+ autocast_kernel_dtype: torch.dtype = torch.bfloat16,
+ chunk_size: int = 64,
+ enable_logging: bool = False,
+ ) -> torch.Tensor | tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor, torch.Tensor]]:
+ """This function computes the last hidden state and matH outputs of the mLSTM, independently of the sequence length.
+
+ For this it uses three kernels:
+ - mlstm_chunkwise_kernel: mlstm chunkwise kernels that processes chunks of a given chunk size in parallel.
+ - mlstm_sequence_kernel: mlstm kernel that processes the remaining sequence length in a single step recurrence.
+ - mlstm_step_kernel: mlstm kernel that processes a sequence length of 1 in a single step.
+
+ It tries to maximize the chunksizes to improve performance.
+ It will start with the given chunk size and then divides the chunksize by 2 until the chunk size is smaller than 16.
+ At every chunksize it will process the maximal number of chunks that fit into the remaining sequence length.
+
+ E.g. for chunk_size = 64, this function will try the chunksizes [64, 32, 16] if necessary.
+
+ For the remaining sequence length, which is smaller than 16, we use a different kernel that computes the mLSTM
+ in a single step and loop over this in pytorch.
+
+ Args:
+ mlstm_chunkwise_kernel: The mLSTM chunkwise kernel that processes chunks of a given chunk size in parallel
+ mlstm_sequence_kernel: The mLSTM kernel that processes the remaining sequence length in a single step recurrence
+ query: The query tensor (batch_size, nh, sequence_length, dhqk)
+ key: The key tensor (batch_size, nh, sequence_length, dhqk)
+ value: The value tensor (batch_size, nh, sequence_length, dhhv)
+ fgate: The forget gate tensor (batch_size, nh, sequence_length)
+ igate: The input gate tensor (batch_size, nh, sequence_length)
+ c_initial: The initial cell state tensor (batch_size, nh, dhqk, dhhv)
+ n_initial: The initial hidden state tensor (batch_size, nh, dhqk)
+ m_initial: The initial memory state tensor (batch_size, nh, 1)
+ return_last_states: If True, the function will return the last states of the mLSTM
+ eps: The epsilon value used for numerical stability
+ autocast_kernel_dtype: The dtype used for the kernel computation
+ chunk_size: The chunk size used for the chunkwise kernel
+ enable_logging: If True, the function will log debug information. Default is False.
+
+ Returns:
+ The last hidden state tensor (batch_size, nh, sequence_length, dhhv) or a tuple containing the last hidden state tensor and the last states of the mLSTM
+ Last states are (cstate (batch_size, nh, dhqk, dhhv), nstate (batch_size, nh, dhqk), mstate (batch_size, nh, 1)).
+ """
+
+ batch_size, nh, sequence_length, dhqk = key.shape
+ dhhv = value.shape[-1]
+
+ c_state = (
+ c_initial
+ if c_initial is not None
+ else torch.zeros(batch_size, nh, dhqk, dhhv, device=key.device, dtype=torch.float32)
+ )
+ n_state = (
+ n_initial
+ if n_initial is not None
+ else torch.zeros(batch_size, nh, dhqk, device=key.device, dtype=torch.float32)
+ )
+ m_state = (
+ m_initial
+ if m_initial is not None
+ else torch.zeros(batch_size, nh, 1, device=key.device, dtype=torch.float32)
+ )
+
+ if sequence_length > 1:
+ # process the sequence length in chunks
+ h_outs = []
+ seq_len_start_idx = 0
+ remaining_seq_len = sequence_length - seq_len_start_idx
+ num_chunks = remaining_seq_len // chunk_size
+ if num_chunks > 0:
+ iter_seq_len = chunk_size * num_chunks
+ seq_len_idx = seq_len_start_idx + iter_seq_len
+ h_out, (c_state, n_state, m_state) = mlstm_chunkwise_kernel(
+ query=query[..., seq_len_start_idx:seq_len_idx, :].contiguous(),
+ key=key[..., seq_len_start_idx:seq_len_idx, :].contiguous(),
+ value=value[..., seq_len_start_idx:seq_len_idx, :].contiguous(),
+ fgate=fgate[..., seq_len_start_idx:seq_len_idx].contiguous(),
+ igate=igate[..., seq_len_start_idx:seq_len_idx].contiguous(),
+ c_initial=c_state,
+ n_initial=n_state,
+ m_initial=m_state,
+ chunk_size=chunk_size,
+ return_last_states=True,
+ autocast_kernel_dtype=autocast_kernel_dtype,
+ eps=eps,
+ )
+ seq_len_start_idx += iter_seq_len
+ h_outs.append(h_out)
+
+ remaining_seq_len = sequence_length - seq_len_start_idx
+
+ if remaining_seq_len > 0:
+ # we use here matK as query as this kernel does not need a query, since we do not care about the outputs only about the last state
+ h_out, (c_state, n_state, m_state) = mlstm_sequence_kernel(
+ query=query[..., seq_len_start_idx:sequence_length, :].contiguous(),
+ key=key[..., seq_len_start_idx:sequence_length, :].contiguous(),
+ value=value[..., seq_len_start_idx:sequence_length, :].contiguous(),
+ igate=igate[..., seq_len_start_idx:sequence_length].contiguous(),
+ fgate=fgate[..., seq_len_start_idx:sequence_length].contiguous(),
+ c_initial=c_state,
+ n_initial=n_state,
+ m_initial=m_state,
+ return_last_states=True,
+ eps=eps,
+ )
+ h_outs.append(h_out)
+ h_out = torch.concatenate(h_outs, dim=2)
+
+ else:
+ if sequence_length != 1:
+ raise ValueError(
+ f"Received empty sequence (sequence_length={sequence_length}), require at least single element in the sequence."
+ )
+ # process the sequence length in a single step
+ # while this case is also captured by the regular mode above,
+ # it avoids the overhead of the loop and calls the step kernel directly
+ # The step function does not want a sequence dimension
+ # qkv shape is (batch_size, nh, dhqk/dhv)
+ # igate, fgate shape is (batch_size, nh, 1)
+ h_out, (c_state, n_state, m_state) = mlstm_step_kernel(
+ query=query.squeeze(2),
+ key=key.squeeze(2),
+ value=value.squeeze(2),
+ igate=igate,
+ fgate=fgate,
+ cstate=c_state,
+ nstate=n_state,
+ mstate=m_state,
+ eps=eps,
+ )
+ h_out = h_out[:, :, None, :]
+
+ if return_last_states:
+ return h_out, (c_state, n_state, m_state)
+ else:
+ return h_out
+
+ class xLSTMBackend(nn.Module):
+ """xLSTM Backend Module for PyTorch.
+
+ This module wraps the xLSTM kernels and provides a high-level interface for training and inference.
+ """
+
+ config_class = xLSTMConfig
+
+ def __init__(self, config: xLSTMConfig):
+ super().__init__()
+ self.config = config
+ self.chunkwise_kernel_fn = mlstm_chunkwise_native_autograd
+ self.sequence_kernel_fn = mlstm_recurrent_sequence_native
+ self.step_kernel_fn = mlstm_recurrent_step_native
+
+ self._inference_fn = partial(
+ wrap_chunkwise_arbitrary_sequence_length,
+ mlstm_chunkwise_kernel=self.chunkwise_kernel_fn,
+ mlstm_sequence_kernel=partial(
+ self.sequence_kernel_fn,
+ dtype_state=getattr(torch, config.inference_state_dtype),
+ ),
+ mlstm_step_kernel=partial(
+ self.step_kernel_fn,
+ dtype_state=getattr(torch, config.inference_state_dtype),
+ ),
+ chunk_size=config.chunk_size,
+ eps=config.eps,
+ autocast_kernel_dtype=getattr(torch, config.autocast_kernel_dtype),
+ return_last_states=True,
+ )
+
+ train_kernel_fn = partial(
+ self.chunkwise_kernel_fn,
+ autocast_kernel_dtype=getattr(torch, config.autocast_kernel_dtype),
+ eps=config.eps,
+ chunk_size=config.chunk_size,
+ )
+ if "with_padding" in config.mode:
+ train_kernel_fn = partial(wrap_chunkwise_pad_zeros, mlstm_chunkwise_kernel=train_kernel_fn)
+ self._train_fn = train_kernel_fn
+
+ def forward(
+ self,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ igate: torch.Tensor,
+ fgate: torch.Tensor,
+ c_initial: torch.Tensor | None = None,
+ n_initial: torch.Tensor | None = None,
+ m_initial: torch.Tensor | None = None,
+ return_last_states: bool | None = None,
+ mode: Literal["train", "inference"] | None = None,
+ ) -> torch.Tensor | tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor, torch.Tensor]]:
+ """Forward pass of the mLSTM backend.
+
+ Depending on the configured mode, this method will call the appropriate kernel function.
+
+ Args:
+ query: The query tensor of shape (batch_size, nh, sequence_length, dhqk).
+ key: The key tensor of shape (batch_size, nh, sequence_length, dhqk).
+ value: The value tensor of shape (batch_size, nh, sequence_length, dhhv).
+ igate: The input gate preactivation tensor of shape (batch_size, nh, sequence_length).
+ fgate: The forget gate preactivation tensor of shape (batch_size, nh, sequence_length).
+ c_initial: The initial cell state tensor of shape (batch_size, nh, dhqk, dhhv).
+ Defaults to None.
+ n_initial: The initial hidden state tensor of shape (batch_size, nh, dhqk). Defaults to None.
+ m_initial: The initial memory tensor of shape (batch_size, nh, 1). Defaults to None.
+ return_last_states: Whether to return the last states of the sequence. Defaults to None.
+ If None, the value from the config is used.
+
+ Returns:
+ hidden states of shape (batch_size, nh, sequence_length, dhhv)
+ hidden states and last states the last states are the cell state cstate (batch_size, nh, dhqk, dhhv),
+ the normalizer state nstate (batch_size, nh, dhqk), and the max state mstate (batch_size, nh, 1)
+ """
+ if mode is None:
+ mode = self.config.mode
+
+ if "train" in mode:
+ if return_last_states is None:
+ return_last_states = self.config.return_last_states
+
+ if self.config.mode == "train_with_padding":
+ if return_last_states:
+ raise ValueError("return_last_states=True is not supported with train_with_padding mode.")
+
+ return self._train_fn(
+ query=query,
+ key=key,
+ value=value,
+ igate=igate,
+ fgate=fgate,
+ c_initial=c_initial,
+ n_initial=n_initial,
+ m_initial=m_initial,
+ return_last_states=return_last_states,
+ )
+
+ elif "inference" in mode:
+ # inference mode always returns the last states
+ return self._inference_fn(
+ query=query,
+ key=key,
+ value=value,
+ igate=igate,
+ fgate=fgate,
+ c_initial=c_initial,
+ n_initial=n_initial,
+ m_initial=m_initial,
+ )
+ else:
+ raise ValueError(f"Unknown mode: {self.config.mode}")
+
+ def extra_repr(self) -> str:
+ return f"{self.config}"
+
+ class xLSTMRMSNorm(nn.Module):
+ """Root mean square normalization layer implementation similar
+ to https://pytorch.org/docs/stable/generated/torch.nn.RMSNorm.html.
+
+ It normalizes the input tensor by the root mean square of the last dimension.
+
+ Args:
+ num_features: The number of features in the input tensor.
+ eps: A small value to avoid division by zero.
+ use_weight: Whether to use a learnable weight.
+ use_bias: Whether to use a learnable bias.
+ force_float32_reductions: Whether to force float32 reductions.
+ """
+
+ def __init__(
+ self,
+ num_features: int,
+ eps: float = 1e-6,
+ use_weight: bool = True,
+ use_bias: bool = False,
+ force_float32_reductions: bool = True,
+ ):
+ super().__init__()
+ self.num_features = num_features
+ self.eps = eps
+ self.force_float32_reductions = force_float32_reductions
+
+ if use_weight:
+ self.weight = nn.Parameter(torch.ones(num_features))
+ else:
+ self.weight = None
+
+ if use_bias:
+ self.bias = nn.Parameter(torch.zeros(num_features))
+ else:
+ self.bias = None
+
+ def _apply_weight_bias(self, x: torch.Tensor) -> torch.Tensor:
+ if self.weight is not None:
+ x = x * self.weight
+ if self.bias is not None:
+ x = x + self.bias
+ return x
+
+ def _rms_normalize(self, x: torch.Tensor) -> torch.Tensor:
+ # apply rms norm over the last dimension, i.e. HD dimension
+ in_dtype = x.dtype
+ if self.force_float32_reductions:
+ x = x.float()
+ x = x * torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps)
+ return x.to(in_dtype)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ x = self._rms_normalize(x)
+ x = self._apply_weight_bias(x)
+ return x
+
+ class xLSTMMultiHeadLayerNorm(nn.Module):
+ """Multi-head version of the LayerNorm layer.
+
+ It normalizes the last dimension of the input tensor.
+
+ The input is assumed to have the shape (batch_size, sequence_length, nh, DH), where:
+ batch_size: batch size
+ sequence_length: sequence length
+ nh: number of heads
+ DH: head dimension
+
+ The normalization is applied over the last dimension (DH) of the input tensor.
+
+ Args:
+ num_heads: The number of heads.
+ head_dim: The head dimension.
+ eps: A small value to avoid division by zero.
+ use_weight: Whether to use a learnable weight.
+ use_bias: Whether to use a learnable bias.
+ force_float32_reductions: Whether to force float32 reductions
+
+ Returns:
+ The normalized tensor with the shape (batch_size, sequence_length, nh * DH).
+ """
+
+ def __init__(
+ self,
+ num_heads: int,
+ head_dim: int,
+ eps: float = 1e-6,
+ use_weight: bool = True,
+ use_bias: bool = False,
+ force_float32_reductions: bool = True,
+ ):
+ super().__init__()
+ self.num_features = num_heads * head_dim
+ self.eps = eps
+ self.force_float32_reductions = force_float32_reductions
+
+ if use_weight:
+ self.weight = nn.Parameter(torch.ones(self.num_features))
+ else:
+ self.weight = None
+
+ if use_bias:
+ self.bias = nn.Parameter(torch.zeros(self.num_features))
+ else:
+ self.bias = None
+ self.num_heads = num_heads
+ self.head_dim = head_dim
+
+ def _apply_weight_bias(self, x: torch.Tensor) -> torch.Tensor:
+ if self.weight is not None:
+ x = x * self.weight
+ if self.bias is not None:
+ x = x + self.bias
+ return x
+
+ def _layer_normalize(self, x: torch.Tensor) -> torch.Tensor:
+ # apply layer norm over the last dimension, i.e. HD dimension
+ in_dtype = x.dtype
+ if self.force_float32_reductions:
+ x = x.float()
+ x_centered = x - x.mean(dim=-1, keepdim=True)
+ y = x_centered * torch.rsqrt(x.var(dim=-1, keepdim=True, unbiased=False) + self.eps)
+ return y.to(in_dtype)
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ ) -> torch.Tensor:
+ batch_size, sequence_length, nh, DH = x.shape
+ if nh != self.num_heads:
+ raise ValueError(f"Expected {self.num_heads} heads, got {nh}, input shape: {x.shape}")
+ if self.head_dim != DH:
+ raise ValueError(f"Expected {self.head_dim} head dimension, got {DH}, input shape: {x.shape}")
+
+ x = self._layer_normalize(x)
+ x = x.reshape(batch_size, sequence_length, -1)
+ x = self._apply_weight_bias(x)
+ return x
+
+ class xLSTMFeedForward(nn.Module):
+ def __init__(self, config: xLSTMConfig):
+ super().__init__()
+ self.config = config
+
+ self.up_proj_dim = round_up_to_next_multiple_of(
+ config.hidden_size * config.ffn_proj_factor,
+ config.ffn_round_up_to_multiple_of,
+ )
+
+ if self.config.weight_mode == "single":
+ self.proj_up_gate = nn.Linear(
+ in_features=config.hidden_size,
+ out_features=self.up_proj_dim,
+ bias=self.config.use_bias,
+ )
+ self.proj_up = nn.Linear(
+ in_features=config.hidden_size,
+ out_features=self.up_proj_dim,
+ bias=self.config.use_bias,
+ )
+ elif self.config.weight_mode == "fused":
+ self.proj_up_gate_z = nn.Linear(
+ in_features=config.hidden_size,
+ out_features=2 * self.up_proj_dim,
+ bias=self.config.use_bias,
+ )
+
+ self.proj_down = nn.Linear(
+ in_features=self.up_proj_dim,
+ out_features=config.hidden_size,
+ bias=self.config.use_bias,
+ )
+
+ self.act_fn = nn.SiLU()
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ if self.config.weight_mode == "single":
+ x = self.act_fn(self.proj_up_gate(x)) * self.proj_up(x)
+ elif self.config.weight_mode == "fused":
+ x = self.proj_up_gate_z(x)
+ gate, z = torch.tensor_split(x, (self.up_proj_dim,), dim=-1)
+ x = self.act_fn(gate) * z
+
+ y = self.proj_down(x)
+ return y
+
+ class xLSTMLayer(nn.Module):
+ def __init__(self, config: xLSTMConfig):
+ super().__init__()
+ self.config = config
+
+ self.v_dim = int(config.hidden_size * config.v_dim_factor)
+ self.qk_dim = int(config.hidden_size * config.qk_dim_factor)
+
+ if self.config.weight_mode == "single":
+ self.q = nn.Linear(
+ in_features=self.config.hidden_size,
+ out_features=self.qk_dim,
+ bias=self.config.use_bias,
+ )
+ self.k = nn.Linear(
+ in_features=self.config.hidden_size,
+ out_features=self.qk_dim,
+ bias=self.config.use_bias,
+ )
+ self.v = nn.Linear(
+ in_features=self.config.hidden_size,
+ out_features=self.v_dim,
+ bias=self.config.use_bias,
+ )
+
+ self.ogate_preact = nn.Linear(
+ in_features=self.config.hidden_size,
+ out_features=self.v_dim,
+ bias=self.config.use_bias,
+ )
+ self.igate_preact = nn.Linear(
+ in_features=self.config.hidden_size,
+ out_features=self.config.num_heads,
+ bias=True,
+ )
+ self.fgate_preact = nn.Linear(
+ in_features=self.config.hidden_size,
+ out_features=self.config.num_heads,
+ bias=True,
+ )
+ elif self.config.weight_mode == "fused":
+ self.qkv_opreact = nn.Linear(
+ in_features=self.config.hidden_size,
+ out_features=2 * self.qk_dim + 2 * self.v_dim,
+ bias=self.config.use_bias,
+ )
+ self.ifgate_preact = nn.Linear(
+ in_features=self.config.hidden_size,
+ out_features=2 * self.config.num_heads,
+ bias=True,
+ )
+
+ self.ogate_act_fn = nn.Sigmoid()
+ self.mlstm_backend = xLSTMBackend(config=self.config)
+
+ self.multihead_norm = xLSTMMultiHeadLayerNorm(
+ num_heads=self.config.num_heads,
+ head_dim=self.v_dim // self.config.num_heads,
+ eps=self.config.norm_eps,
+ use_weight=True,
+ use_bias=self.config.use_bias,
+ force_float32_reductions=self.config.norm_reduction_force_float32,
+ )
+ self.out_proj = nn.Linear(
+ in_features=self.v_dim,
+ out_features=self.config.hidden_size,
+ bias=self.config.use_bias,
+ )
+
+ def forward(
+ self, x: torch.Tensor, state: mLSTMLayerStateType | None = None
+ ) -> tuple[torch.Tensor, mLSTMLayerStateType | None]:
+ if x.ndim != 3:
+ raise ValueError(f"Input must have shape [batch_size, sequence_length, HD], got {x.shape}")
+ batch_size, sequence_length, _ = x.shape
+ if self.config.weight_mode == "single":
+ query = self.q(x)
+ key = self.k(x)
+ value = self.v(x)
+ o_preact = self.ogate_preact(x)
+ i_preact = soft_cap(self.igate_preact(x), cap_value=self.config.gate_soft_cap)
+ f_preact = soft_cap(self.fgate_preact(x), cap_value=self.config.gate_soft_cap)
+
+ elif self.config.weight_mode == "fused":
+ qkv_opreact = self.qkv_opreact(x)
+ query, key, value, o_preact = torch.tensor_split(
+ qkv_opreact,
+ (
+ self.qk_dim,
+ 2 * self.qk_dim,
+ 2 * self.qk_dim + self.v_dim,
+ ),
+ dim=-1,
+ )
+
+ if_preact = soft_cap(self.ifgate_preact(x), cap_value=self.config.gate_soft_cap)
+ i_preact, f_preact = torch.tensor_split(if_preact, (self.config.num_heads,), dim=-1)
+
+ query = query.reshape(batch_size, sequence_length, self.config.num_heads, -1).transpose(1, 2)
+ key = key.reshape(batch_size, sequence_length, self.config.num_heads, -1).transpose(1, 2)
+ value = value.reshape(batch_size, sequence_length, self.config.num_heads, -1).transpose(1, 2)
+ i_preact = i_preact.transpose(1, 2)
+ f_preact = f_preact.transpose(1, 2)
+ if state is None:
+ c_initial, n_initial, m_initial = None, None, None
+ else:
+ c_initial, n_initial, m_initial = state
+
+ h, state = self.mlstm_backend(
+ query=query,
+ key=key,
+ value=value,
+ igate=i_preact,
+ fgate=f_preact,
+ c_initial=c_initial,
+ n_initial=n_initial,
+ m_initial=m_initial,
+ )
+ expected_h_shape = (
+ batch_size,
+ self.config.num_heads,
+ sequence_length,
+ self.v_dim // self.config.num_heads,
+ )
+ if h.shape != expected_h_shape:
+ raise ValueError(f"Got {h.shape}, expected {expected_h_shape}")
+
+ h = h.transpose(1, 2)
+ h_norm = self.multihead_norm(h)
+ h_norm = h_norm.reshape(batch_size, sequence_length, -1)
+
+ h_out = self.ogate_act_fn(o_preact) * h_norm
+
+ y = self.out_proj(h_out)
+ return y, state
+
+ class xLSTMBlock(GradientCheckpointingLayer):
+ def __init__(self, config: xLSTMConfig):
+ super().__init__()
+ self.config = config
+ self.norm_mlstm = xLSTMRMSNorm(
+ num_features=config.hidden_size,
+ eps=config.norm_eps,
+ use_weight=True,
+ use_bias=config.use_bias,
+ force_float32_reductions=config.norm_reduction_force_float32,
+ )
+ self.mlstm_layer = xLSTMLayer(config)
+ self.norm_ffn = xLSTMRMSNorm(
+ num_features=config.hidden_size,
+ eps=config.norm_eps,
+ use_weight=True,
+ use_bias=config.use_bias,
+ force_float32_reductions=config.norm_reduction_force_float32,
+ )
+ self.ffn = xLSTMFeedForward(config)
+
+ def forward(self, x: torch.Tensor, state: mLSTMStateType | None = None) -> tuple[torch.Tensor, mLSTMStateType]:
+ x_mlstm = self.norm_mlstm(x)
+ x_mlstm, state = self.mlstm_layer(x_mlstm, state)
+ x = x + x_mlstm
+
+ x_ffn = self.norm_ffn(x)
+ x_ffn = self.ffn(x_ffn)
+ x = x + x_ffn
+
+ return x, state
+
+
+def small_init_method(dim):
+ """
+ Adapted from: https://github.com/EleutherAI/gpt-neox/blob/main/megatron/model/init_functions.py
+ Fills the input Tensor with values according to the method described in Transformers without Tears: Improving
+ the Normalization of Self-Attention - Nguyen, T. & Salazar, J. (2019), using a normal distribution."""
+ std = (2 / (5 * dim)) ** (1 / 2)
+
+ def init_(tensor):
+ return init.normal_(tensor, mean=0.0, std=std)
+
+ return init_
+
+
+def wang_init_method(n_layers, dim):
+ """
+ Adapted from https://github.com/EleutherAI/gpt-neox/blob/main/megatron/model/init_functions.py
+ """
+ std = 2 / n_layers / dim ** (1 / 2)
+
+ def init_(tensor):
+ return init.normal_(tensor, mean=0.0, std=std)
+
+ return init_
+
+
+class xLSTMPreTrainedModel(PreTrainedModel):
+ """
+ An abstract class for an interface to loading a pre-trained xLSTM model.
+ """
+
+ config_class = xLSTMConfig
+ base_model_prefix = "backbone"
+ _no_split_modules = ["xLSTMBlock"]
+ supports_gradient_checkpointing = True
+ _is_stateful = True
+ _can_record_outputs = {
+ "hidden_states": xLSTMBlock,
+ }
+
+ def _module_name_map(self, module):
+ for name, mod in self.named_modules():
+ if mod is module:
+ return name
+ return ""
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ if isinstance(module, nn.Embedding):
+ small_init_method(self.config.hidden_size)(self.embeddings.weight)
+ elif isinstance(module, nn.Linear):
+ if module.bias is not None:
+ init.zeros_(module.bias)
+ if self.config.weight_mode == "single" and "gate" in self._module_name_map(module):
+ init.zeros_(module.weight)
+
+ if "igate" in self._module_name_map(module):
+ init.copy_(module.bias, -10.0 * torch.ones_like(module.bias))
+ elif "fgate" in self._module_name_map(module):
+ init.copy_(
+ module.bias,
+ torch.linspace(
+ 3.0,
+ 6.0,
+ module.bias.shape[-1],
+ ).to(
+ device=module.bias.device,
+ dtype=module.bias.dtype,
+ ),
+ )
+ elif self.config.weight_mode == "fused" and "gate" in self._module_name_map(module):
+ init.zeros_(module.weight)
+
+ init.copy_(
+ module.bias[: self.config.num_heads],
+ module.bias[: self.config.num_heads]
+ - module.bias[: self.config.num_heads]
+ - 10.0 * torch.ones_like(module.bias),
+ )
+ init.copy_(
+ module.bias[: self.config.num_heads],
+ module.bias[: self.config.num_heads]
+ - module.bias[self.config.num_heads :]
+ + torch.linspace(
+ 3.0,
+ 6.0,
+ module.bias.shape[-1],
+ ).to(
+ device=module.bias.device,
+ dtype=module.bias.dtype,
+ ),
+ )
+ elif "proj_down" in self._module_name_map(module):
+ wang_init_method(dim=module.weight.shape[1], n_layers=self.config.num_hidden_layers)(module.weight)
+ elif "out_proj" in self._module_name_map(module):
+ wang_init_method(dim=self.config.hidden_size, n_layers=self.config.num_hidden_layers)(module.weight)
+ elif module.weight is not None:
+ small_init_method(self.config.hidden_size)(module.weight)
+ elif isinstance(module, xLSTMRMSNorm) or hasattr(module, "_layer_normalize"):
+ init.ones_(module.weight)
+ if hasattr(module, "bias") and module.bias is not None:
+ init.zeros_(module.bias)
+
+
+class xLSTMCache:
+ """
+ Cache for xLSTM model which does not have attention mechanism and key value states.
+
+ Arguments:
+ config (`PreTrainedConfig):
+ The configuration file defining the shape-related attributes required to initialize the static cache.
+ max_batch_size (`int`):
+ The batch size with which the model will be used.
+ dtype (`torch.dtype`, *optional*, defaults to `torch.bfloat16`):
+ The default `dtype` to use when initializing the layer.
+ device (`torch.device` or `str`, *optional*):
+ The device on which the cache should be initialized. Should be the same as the layer.
+
+ Attributes:
+ seqlen_offset: int
+ dtype: torch.dtype
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, xLSTMForCausalLM, xLSTMCache
+
+ >>> model = xLSTMForCausalLM.from_pretrained("NX-AI/xLSTM-7b")
+ >>> tokenizer = xLSTMTokenizer.from_pretrained("NX-AI/xLSTM-7b")
+
+ >>> inputs = tokenizer(text="I am an xLSTM", return_tensors="pt")
+
+ >>> # Prepare a cache class and pass it to model's forward
+ >>> cache_params = xLSTMCache(config=model.config, max_batch_size=1, device=model.device, dtype=model.dtype)
+ >>> outputs = model(**inputs, cache_params=cache_params, use_cache=True)
+ >>> outputs.cache_params
+ xLSTMCache()
+ """
+
+ def __init__(
+ self,
+ config: xLSTMConfig,
+ max_batch_size: int,
+ dtype: torch.dtype = torch.bfloat16,
+ device: str | None = None,
+ **kwargs,
+ ):
+ self.seqlen_offset = 0
+ self.dtype = dtype
+ self.config = config
+ self.rnn_state = {
+ layer: (
+ torch.zeros(
+ [max_batch_size, config.num_heads, config.qk_head_dim, config.v_head_dim],
+ dtype=dtype,
+ device=device,
+ ),
+ torch.zeros([max_batch_size, config.num_heads, config.qk_head_dim], dtype=dtype, device=device),
+ torch.zeros([max_batch_size, config.num_heads, 1], dtype=dtype, device=device),
+ )
+ for layer in range(config.num_hidden_layers)
+ }
+
+ def reset(self):
+ self.rnn_state = {
+ layer: (
+ torch.zeros_like(self.rnn_state[layer][0]),
+ torch.zeros_like(self.rnn_state[layer][1]),
+ torch.zeros_like(self.rnn_state[layer][2]),
+ )
+ for layer in self.rnn_state
+ }
+
+
+@auto_docstring
+@dataclass
+class xLSTMOutput(ModelOutput):
+ r"""
+ cache_params (`xLSTMCache`):
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
+ avoid providing the old `input_ids`.
+ """
+
+ last_hidden_state: torch.FloatTensor | None
+ cache_params: xLSTMCache | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+
+
+@auto_docstring
+class xLSTMModel(xLSTMPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ # use embbeding_dim and num_blocks once here to make use of them
+ self.embeddings = nn.Embedding(config.vocab_size, config.embedding_dim)
+ self.blocks = nn.ModuleList([xLSTMBlock(config) for _ in range(config.num_blocks)])
+ self.out_norm = xLSTMRMSNorm(config.hidden_size, eps=config.norm_eps)
+ self.gradient_checkpointing = False
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings
+
+ def set_input_embeddings(self, new_embedding):
+ self.embeddings = new_embedding
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.LongTensor | None = None,
+ cache_params: xLSTMCache | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | xLSTMOutput:
+ r"""
+ cache_params (`xLSTMCache`, *optional*):
+ The xLSTMCache that carries the RNN states.
+ """
+ # Resolved here (not just by @capture_outputs) because the chunked inference path below
+ # is incompatible with hidden state collection and we need the value to pick the right branch.
+ output_hidden_states = kwargs.get("output_hidden_states")
+ if output_hidden_states is None:
+ output_hidden_states = self.config.output_hidden_states
+
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embeddings(input_ids)
+
+ if use_cache and cache_params is None:
+ cache_params = xLSTMCache(
+ self.config, inputs_embeds.size(0), device=inputs_embeds.device, dtype=inputs_embeds.dtype
+ )
+
+ hidden_states = inputs_embeds
+
+ if (
+ not self.training
+ and self.config.max_inference_chunksize < hidden_states.shape[1]
+ and not output_hidden_states
+ ):
+ offset = 0
+ with torch.no_grad():
+ if cache_params is None:
+ cache_params = xLSTMCache(config=self.config, max_batch_size=hidden_states.shape[0])
+ final_state = torch.zeros_like(hidden_states)
+ while offset < hidden_states.shape[1]:
+ hidden_states_chunk = hidden_states[
+ :, offset : min(offset + self.config.max_inference_chunksize, hidden_states.shape[1])
+ ]
+ for layer_idx, xlstm_block in enumerate(self.blocks):
+ hidden_states_chunk, rnn_state = xlstm_block(
+ hidden_states_chunk,
+ state=cache_params.rnn_state[layer_idx],
+ )
+ for state_idx in range(len(cache_params.rnn_state[layer_idx])):
+ local_rnn_state = rnn_state[state_idx]
+ cache_params.rnn_state[layer_idx][state_idx].copy_(local_rnn_state)
+ cache_params.rnn_state_initial = False
+ final_state[
+ :, offset : min(offset + self.config.max_inference_chunksize, hidden_states.shape[1])
+ ] = hidden_states_chunk
+ offset += self.config.max_inference_chunksize
+ hidden_states = final_state
+ else:
+ for layer_idx, xlstm_block in enumerate(self.blocks):
+ hidden_states, rnn_state = xlstm_block(
+ hidden_states,
+ cache_params.rnn_state[layer_idx] if cache_params is not None else None,
+ )
+
+ if cache_params:
+ for state_idx in range(len(cache_params.rnn_state[layer_idx])):
+ local_rnn_state = rnn_state[state_idx]
+ cache_params.rnn_state[layer_idx][state_idx].copy_(local_rnn_state)
+ cache_params.rnn_state_initial = False
+
+ if use_cache:
+ cache_params.seqlen_offset += inputs_embeds.shape[1]
+
+ hidden_states = self.out_norm(hidden_states)
+
+ return xLSTMOutput(
+ last_hidden_state=hidden_states,
+ cache_params=cache_params,
+ )
+
+
+@auto_docstring
+@dataclass
+class xLSTMCausalLMOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Language modeling loss (for next-token prediction).
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
+ cache_params (`xLSTMCache`, *optional*, carrying the RNN states):
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
+ avoid providing the old `input_ids`.
+ """
+
+ loss: torch.FloatTensor | None = None
+ logits: torch.FloatTensor | None = None
+ cache_params: xLSTMCache | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+
+
+@auto_docstring
+class xLSTMForCausalLM(xLSTMPreTrainedModel, GenerationMixin):
+ def __init__(self, config):
+ super().__init__(config)
+ self.backbone = xLSTMModel(config)
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.lm_head
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head = new_embeddings
+
+ def get_input_embeddings(self):
+ return self.backbone.get_input_embeddings()
+
+ def set_input_embeddings(self, new_embeddings):
+ return self.backbone.set_input_embeddings(new_embeddings)
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ cache_params: xLSTMCache | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | xLSTMCausalLMOutput:
+ r"""
+ cache_params (`xLSTMCache`, *optional*):
+ The xLSTMCache that carries the RNN states.
+ """
+ xlstm_outputs = self.backbone(
+ input_ids,
+ cache_params=cache_params,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+ hidden_states = xlstm_outputs[0]
+
+ logits = self.lm_head(hidden_states.to(self.lm_head.weight.dtype)).float()
+
+ if not self.training and self.config.max_inference_chunksize < logits.shape[1]:
+ offset = 0
+ with torch.no_grad():
+ while offset < logits.shape[1]:
+ logits[:, offset : min(offset + self.config.max_inference_chunksize, logits.shape[1])] = soft_cap(
+ logits[:, offset : min(offset + self.config.max_inference_chunksize, logits.shape[1])],
+ self.config.output_logit_soft_cap,
+ )
+ offset += self.config.max_inference_chunksize
+ else:
+ logits = soft_cap(logits, self.config.output_logit_soft_cap)
+
+ loss = None
+ if labels is not None:
+ # move labels to correct device
+ labels = labels.to(logits.device)
+ # Shift so that tokens < nstate predict nstate
+ shift_logits = logits[..., :-1, :].contiguous()
+ shift_labels = labels[..., 1:].contiguous()
+ # Flatten the tokens
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
+
+ return xLSTMCausalLMOutput(
+ loss=loss,
+ logits=logits,
+ cache_params=xlstm_outputs.cache_params,
+ hidden_states=xlstm_outputs.hidden_states,
+ )
+
+
+__all__ = [
+ "xLSTMForCausalLM",
+ "xLSTMModel",
+ "xLSTMPreTrainedModel",
+]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xmod/__init__.py b/.venv/lib/python3.12/site-packages/transformers/models/xmod/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..13cf20cbe49cbafadbcaa3b8aa8eba9d34238f14
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xmod/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_xmod import *
+ from .modeling_xmod import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xmod/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xmod/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5c4dc6deeada1b222965a58855dfb8ee56a7f923
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xmod/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xmod/__pycache__/configuration_xmod.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xmod/__pycache__/configuration_xmod.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..88dfcd20b5b734c3beff4ca8cc4e191a136108db
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xmod/__pycache__/configuration_xmod.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xmod/__pycache__/modeling_xmod.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/xmod/__pycache__/modeling_xmod.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b1e9c840b42efc558c06d6ee2e41b1b39836c030
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/xmod/__pycache__/modeling_xmod.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xmod/configuration_xmod.py b/.venv/lib/python3.12/site-packages/transformers/models/xmod/configuration_xmod.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac8d34b143463346dd7b7a1bb5ae1dcd7867f9f5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xmod/configuration_xmod.py
@@ -0,0 +1,89 @@
+# Copyright 2023 The Meta AI Team Authors and The HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""X-MOD configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="facebook/xmod-base")
+@strict
+class XmodConfig(PreTrainedConfig):
+ r"""
+ pre_norm (`bool`, *optional*, defaults to `False`):
+ Whether to apply layer normalization before each block.
+ adapter_reduction_factor (`int` or `float`, *optional*, defaults to 2):
+ The factor by which the dimensionality of the adapter is reduced relative to `hidden_size`.
+ adapter_layer_norm (`bool`, *optional*, defaults to `False`):
+ Whether to apply a new layer normalization before the adapter modules (shared across all adapters).
+ adapter_reuse_layer_norm (`bool`, *optional*, defaults to `True`):
+ Whether to reuse the second layer normalization and apply it before the adapter modules as well.
+ ln_before_adapter (`bool`, *optional*, defaults to `True`):
+ Whether to apply the layer normalization before the residual connection around the adapter module.
+ languages (`Iterable[str]`, *optional*, defaults to `["en_XX"]`):
+ An iterable of language codes for which adapter modules should be initialized.
+ default_language (`str`, *optional*):
+ Language code of a default language. It will be assumed that the input is in this language if no language
+ codes are explicitly passed to the forward method.
+
+ Examples:
+
+ ```python
+ >>> from transformers import XmodConfig, XmodModel
+
+ >>> # Initializing an X-MOD facebook/xmod-base style configuration
+ >>> configuration = XmodConfig()
+
+ >>> # Initializing a model (with random weights) from the facebook/xmod-base style configuration
+ >>> model = XmodModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "xmod"
+
+ vocab_size: int = 30522
+ hidden_size: int = 768
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ intermediate_size: int = 3072
+ hidden_act: str = "gelu"
+ hidden_dropout_prob: float | int = 0.1
+ attention_probs_dropout_prob: float | int = 0.1
+ max_position_embeddings: int = 512
+ type_vocab_size: int = 2
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-12
+ pad_token_id: int | None = 1
+ bos_token_id: int | None = 0
+ eos_token_id: int | list[int] | None = 2
+ use_cache: bool = True
+ classifier_dropout: float | int | None = None
+ pre_norm: bool = False
+ adapter_reduction_factor: int = 2
+ adapter_layer_norm: bool = False
+ adapter_reuse_layer_norm: bool = True
+ ln_before_adapter: bool = True
+ languages: list[str] | tuple[str, ...] = ("en_XX",)
+ default_language: str | None = None
+ is_decoder: bool = False
+ add_cross_attention: bool = False
+ tie_word_embeddings: bool = True
+
+
+__all__ = ["XmodConfig"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/xmod/modeling_xmod.py b/.venv/lib/python3.12/site-packages/transformers/models/xmod/modeling_xmod.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e77ecc3d611ff8fa32d8398443a37ffaa45eeaf
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/xmod/modeling_xmod.py
@@ -0,0 +1,1390 @@
+# Copyright 2023 Meta AI Team and the HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch X-MOD model."""
+
+from collections.abc import Callable
+
+import torch
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ... import initialization as init
+from ...activations import ACT2FN, gelu
+from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
+from ...generation import GenerationMixin
+from ...masking_utils import create_bidirectional_mask, create_causal_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutputWithPastAndCrossAttentions,
+ BaseModelOutputWithPoolingAndCrossAttentions,
+ CausalLMOutputWithCrossAttentions,
+ MaskedLMOutput,
+ MultipleChoiceModelOutput,
+ QuestionAnsweringModelOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+)
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...pytorch_utils import apply_chunking_to_forward
+from ...utils import TransformersKwargs, auto_docstring, logging
+from ...utils.generic import can_return_tuple, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_xmod import XmodConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+# Copied from transformers.models.roberta.modeling_roberta.RobertaEmbeddings with Roberta->Xmod
+class XmodEmbeddings(nn.Module):
+ """Construct the embeddings from word, position and token_type embeddings."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
+
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
+ self.register_buffer(
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
+ )
+ self.register_buffer(
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
+ )
+
+ self.padding_idx = config.pad_token_id
+ self.position_embeddings = nn.Embedding(
+ config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
+ )
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ past_key_values_length: int = 0,
+ ) -> torch.Tensor:
+ if position_ids is None:
+ if input_ids is not None:
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
+ position_ids = self.create_position_ids_from_input_ids(
+ input_ids, self.padding_idx, past_key_values_length
+ )
+ else:
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds, self.padding_idx)
+
+ if input_ids is not None:
+ input_shape = input_ids.size()
+ else:
+ input_shape = inputs_embeds.size()[:-1]
+
+ batch_size, seq_length = input_shape
+
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
+ # issue #5664
+ if token_type_ids is None:
+ if hasattr(self, "token_type_ids"):
+ # NOTE: We assume either pos ids to have bsz == 1 (broadcastable) or bsz == effective bsz (input_shape[0])
+ buffered_token_type_ids = self.token_type_ids.to(position_ids.device).expand(position_ids.shape[0], -1)
+ buffered_token_type_ids = torch.gather(buffered_token_type_ids, dim=1, index=position_ids)
+ token_type_ids = buffered_token_type_ids.expand(batch_size, seq_length)
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
+
+ if inputs_embeds is None:
+ inputs_embeds = self.word_embeddings(input_ids)
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
+ embeddings = inputs_embeds + token_type_embeddings
+
+ position_embeddings = self.position_embeddings(position_ids)
+ embeddings = embeddings + position_embeddings
+
+ embeddings = self.LayerNorm(embeddings)
+ embeddings = self.dropout(embeddings)
+ return embeddings
+
+ @staticmethod
+ def create_position_ids_from_inputs_embeds(inputs_embeds, padding_idx):
+ """
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
+
+ Args:
+ inputs_embeds: torch.Tensor
+
+ Returns: torch.Tensor
+ """
+ input_shape = inputs_embeds.size()[:-1]
+ sequence_length = input_shape[1]
+
+ position_ids = torch.arange(
+ padding_idx + 1, sequence_length + padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
+ )
+ return position_ids.unsqueeze(0).expand(input_shape)
+
+ @staticmethod
+ def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
+ """
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
+ are ignored. This is modified from fairseq's `utils.make_positions`.
+
+ Args:
+ x: torch.Tensor x:
+
+ Returns: torch.Tensor
+ """
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
+ mask = input_ids.ne(padding_idx).int()
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
+ return incremental_indices.long() + padding_idx
+
+
+# Copied from transformers.models.bert.modeling_bert.eager_attention_forward
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float | None = None,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ if scaling is None:
+ scaling = query.size(-1) ** -0.5
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
+
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+# Copied from transformers.models.roberta.modeling_roberta.RobertaSelfAttention with Roberta->Xmod
+class XmodSelfAttention(nn.Module):
+ def __init__(self, config, is_causal=False, layer_idx=None):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({config.num_attention_heads})"
+ )
+ self.config = config
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+ self.scaling = self.attention_head_size**-0.5
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+
+ self.is_decoder = config.is_decoder
+ self.is_causal = is_causal
+ self.layer_idx = layer_idx
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
+
+ # get all proj
+ query_layer = self.query(hidden_states).view(*hidden_shape).transpose(1, 2)
+ key_layer = self.key(hidden_states).view(*hidden_shape).transpose(1, 2)
+ value_layer = self.value(hidden_states).view(*hidden_shape).transpose(1, 2)
+
+ if past_key_values is not None:
+ # decoder-only roberta can have a simple dynamic cache for example
+ current_past_key_values = past_key_values
+ if isinstance(past_key_values, EncoderDecoderCache):
+ current_past_key_values = past_key_values.self_attention_cache
+
+ # save all key/value_layer to cache to be re-used for fast auto-regressive generation
+ key_layer, value_layer = current_past_key_values.update(key_layer, value_layer, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_layer,
+ key_layer,
+ value_layer,
+ attention_mask,
+ dropout=0.0 if not self.training else self.dropout.p,
+ scaling=self.scaling,
+ **kwargs,
+ )
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ return attn_output, attn_weights
+
+
+# Copied from transformers.models.bert.modeling_bert.BertCrossAttention with Bert->Xmod
+class XmodCrossAttention(nn.Module):
+ def __init__(self, config, is_causal=False, layer_idx=None):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({config.num_attention_heads})"
+ )
+ self.config = config
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+ self.scaling = self.attention_head_size**-0.5
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+
+ self.is_causal = is_causal
+ self.layer_idx = layer_idx
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ past_key_values: EncoderDecoderCache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor]:
+ # determine input shapes
+ input_shape = hidden_states.shape[:-1]
+
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
+
+ # get query proj
+ query_layer = self.query(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ is_updated = past_key_values.is_updated.get(self.layer_idx) if past_key_values is not None else False
+ if past_key_values is not None and is_updated:
+ # reuse k,v, cross_attentions
+ key_layer = past_key_values.cross_attention_cache.layers[self.layer_idx].keys
+ value_layer = past_key_values.cross_attention_cache.layers[self.layer_idx].values
+ else:
+ kv_shape = (*encoder_hidden_states.shape[:-1], -1, self.attention_head_size)
+ key_layer = self.key(encoder_hidden_states).view(kv_shape).transpose(1, 2)
+ value_layer = self.value(encoder_hidden_states).view(kv_shape).transpose(1, 2)
+
+ if past_key_values is not None:
+ # save all states to the cache
+ key_layer, value_layer = past_key_values.cross_attention_cache.update(
+ key_layer, value_layer, self.layer_idx
+ )
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
+ past_key_values.is_updated[self.layer_idx] = True
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_layer,
+ key_layer,
+ value_layer,
+ attention_mask,
+ dropout=0.0 if not self.training else self.dropout.p,
+ scaling=self.scaling,
+ **kwargs,
+ )
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ return attn_output, attn_weights
+
+
+class XmodSelfOutput(nn.Module):
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaSelfOutput.__init__
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = hidden_states + input_tensor
+ return hidden_states
+
+
+class XmodAttention(nn.Module):
+ def __init__(self, config, is_causal=False, layer_idx=None, is_cross_attention=False):
+ super().__init__()
+ self.is_cross_attention = is_cross_attention
+ attention_class = XmodCrossAttention if is_cross_attention else XmodSelfAttention
+ self.self = attention_class(config, is_causal=is_causal, layer_idx=layer_idx)
+ self.output = XmodSelfOutput(config)
+
+ self.pre_norm = config.pre_norm
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ past_key_values: tuple[tuple[torch.FloatTensor]] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor]:
+ residual = hidden_states
+ if self.pre_norm:
+ hidden_states = self.output.LayerNorm(hidden_states)
+
+ attention_mask = attention_mask if not self.is_cross_attention else encoder_attention_mask
+ attention_output, attn_weights = self.self(
+ hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ attention_output = self.output(attention_output, residual)
+
+ if not self.pre_norm:
+ attention_output = self.output.LayerNorm(attention_output)
+
+ return attention_output, attn_weights
+
+
+# Copied from transformers.models.roberta.modeling_roberta.RobertaIntermediate
+class XmodIntermediate(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ return hidden_states
+
+
+class XmodAdapter(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.bottleneck_size = config.hidden_size // config.adapter_reduction_factor
+ self.dense1 = nn.Linear(config.hidden_size, self.bottleneck_size)
+ self.dense2 = nn.Linear(self.bottleneck_size, config.hidden_size)
+ if isinstance(config.hidden_act, str):
+ self.adapter_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.adapter_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense1(hidden_states)
+ hidden_states = self.adapter_act_fn(hidden_states)
+ hidden_states = self.dense2(hidden_states)
+ return hidden_states
+
+
+class XmodOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.ln_before_adapter = config.ln_before_adapter
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ if config.adapter_layer_norm:
+ self.adapter_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ else:
+ self.adapter_layer_norm = None
+ self.adapter_reuse_layer_norm = config.adapter_reuse_layer_norm
+ self.adapter_modules = nn.ModuleDict({})
+ for language in config.languages:
+ self.adapter_modules[str(language)] = XmodAdapter(config)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor, lang_ids: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = hidden_states + input_tensor
+ hidden_states = self.lang_adapter(lang_ids, hidden_states)
+ return hidden_states
+
+ def lang_adapter(self, lang_ids: torch.Tensor, hidden_states: torch.Tensor):
+ if not self.ln_before_adapter:
+ residual = hidden_states
+
+ if self.adapter_layer_norm is not None:
+ hidden_states = self.adapter_layer_norm(hidden_states)
+ elif self.adapter_reuse_layer_norm:
+ hidden_states = self.LayerNorm(hidden_states)
+
+ if self.ln_before_adapter:
+ residual = hidden_states
+
+ new_hidden_states = torch.zeros_like(hidden_states)
+ for adapter_idx, lang_key in enumerate(self.adapter_modules.keys()):
+ lang_mask = lang_ids == adapter_idx
+ lang_hidden_states = hidden_states[lang_mask]
+ adapted_lang_hidden_states = self.adapter_modules[lang_key](lang_hidden_states)
+ new_hidden_states[lang_mask] = adapted_lang_hidden_states
+
+ hidden_states = self.dropout(new_hidden_states)
+ hidden_states += residual
+ return hidden_states
+
+
+class XmodLayer(GradientCheckpointingLayer):
+ def __init__(self, config, layer_idx=None):
+ super().__init__()
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+ self.attention = XmodAttention(config, is_causal=config.is_decoder, layer_idx=layer_idx)
+ self.is_decoder = config.is_decoder
+ self.add_cross_attention = config.add_cross_attention
+ if self.add_cross_attention:
+ if not self.is_decoder:
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
+ self.crossattention = XmodAttention(
+ config,
+ is_causal=False,
+ layer_idx=layer_idx,
+ is_cross_attention=True,
+ )
+ self.intermediate = XmodIntermediate(config)
+ self.output = XmodOutput(config)
+ self.pre_norm = config.pre_norm
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ lang_ids: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ past_key_values: tuple[tuple[torch.FloatTensor]] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ self_attention_output, _ = self.attention(
+ hidden_states,
+ attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ attention_output = self_attention_output
+
+ if self.is_decoder and encoder_hidden_states is not None:
+ if not hasattr(self, "crossattention"):
+ raise ValueError(
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
+ " by setting `config.add_cross_attention=True`"
+ )
+
+ cross_attention_output, _ = self.crossattention(
+ attention_output,
+ None, # attention_mask
+ encoder_hidden_states,
+ encoder_attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ attention_output = cross_attention_output
+
+ residual = attention_output
+ if self.pre_norm:
+ attention_output = self.output.LayerNorm(attention_output)
+ intermediate_output = apply_chunking_to_forward(
+ self.feed_forward_chunk,
+ self.chunk_size_feed_forward,
+ self.seq_len_dim,
+ attention_output,
+ )
+ layer_output = self.output(intermediate_output, residual, lang_ids)
+ if not self.pre_norm:
+ layer_output = self.output.LayerNorm(layer_output)
+
+ return layer_output
+
+ def feed_forward_chunk(self, attention_output):
+ return self.intermediate(attention_output)
+
+
+class XmodEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList([XmodLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
+ self.is_pre_norm = config.pre_norm
+ if self.is_pre_norm:
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ lang_ids: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ past_key_values: tuple[tuple[torch.FloatTensor]] | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPastAndCrossAttentions:
+ for i, layer_module in enumerate(self.layer):
+ hidden_states = layer_module(
+ hidden_states,
+ lang_ids,
+ attention_mask,
+ encoder_hidden_states,
+ encoder_attention_mask,
+ past_key_values,
+ **kwargs,
+ )
+
+ if self.is_pre_norm:
+ hidden_states = self.LayerNorm(hidden_states)
+
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values if use_cache else None,
+ )
+
+
+# Copied from transformers.models.roberta.modeling_roberta.RobertaPooler
+class XmodPooler(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.activation = nn.Tanh()
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ # We "pool" the model by simply taking the hidden state corresponding
+ # to the first token.
+ first_token_tensor = hidden_states[:, 0]
+ pooled_output = self.dense(first_token_tensor)
+ pooled_output = self.activation(pooled_output)
+ return pooled_output
+
+
+@auto_docstring
+class XmodPreTrainedModel(PreTrainedModel):
+ config_class = XmodConfig
+ base_model_prefix = "roberta"
+ supports_gradient_checkpointing = True
+ no_split_modules = ["XmodEmbeddings", "XmodSelfAttention", "XmodCrossAttention"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": XmodLayer,
+ "attentions": XmodSelfAttention,
+ "cross_attentions": XmodCrossAttention,
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ super()._init_weights(module)
+ if isinstance(module, XmodLMHead):
+ init.zeros_(module.bias)
+ elif isinstance(module, XmodEmbeddings):
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
+ init.zeros_(module.token_type_ids)
+
+ def set_default_language(self, language: str):
+ """
+ Set the default language code for the model. This is used when the language is not specified in the input.
+
+ Args:
+ language (`str`): The language code, such as `"en_XX"` or `"de_DE"`.
+ """
+ if language not in self.config.languages:
+ raise ValueError(
+ f"{self} does not have an adapter for {language}. Supported languages: {list(self.config.languages)}"
+ )
+ self.config.default_language = language
+
+ def freeze_embeddings_and_language_adapters(self):
+ """
+ Freeze the embeddings and language adapters of the model. Usually, this is applied before the model is
+ fine-tuned on a downstream task.
+ """
+ logger.info("Freezing embeddings")
+ for parameter in self.roberta.embeddings.parameters():
+ parameter.requires_grad = False
+ logger.info("Freezing adapters")
+ for layer in self.roberta.encoder.layer:
+ if layer.output.adapter_layer_norm is not None:
+ for parameter in layer.output.adapter_layer_norm.parameters():
+ parameter.requires_grad = False
+ for parameter in layer.output.adapter_modules.parameters():
+ parameter.requires_grad = False
+
+
+@auto_docstring(
+ custom_intro="""
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
+ cross-attention is added between the self-attention layers, following the architecture described in *Attention is
+ all you need*_ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz
+ Kaiser and Illia Polosukhin.
+
+ To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
+ to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
+
+ .. _*Attention is all you need*: https://huggingface.co/papers/1706.03762
+ """
+)
+class XmodModel(XmodPreTrainedModel):
+ def __init__(self, config, add_pooling_layer=True):
+ r"""
+ add_pooling_layer (bool, *optional*, defaults to `True`):
+ Whether to add a pooling layer
+ """
+ super().__init__(config)
+ self.config = config
+ self.gradient_checkpointing = False
+
+ self.embeddings = XmodEmbeddings(config)
+ self.encoder = XmodEncoder(config)
+
+ self.pooler = XmodPooler(config) if add_pooling_layer else None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaModel.get_input_embeddings
+ def get_input_embeddings(self):
+ return self.embeddings.word_embeddings
+
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaModel.set_input_embeddings
+ def set_input_embeddings(self, value):
+ self.embeddings.word_embeddings = value
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ lang_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ past_key_values: list[torch.FloatTensor] | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPoolingAndCrossAttentions:
+ r"""
+ lang_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of the language adapters that should be activated for each sample, respectively. Default: the index
+ that corresponds to `self.config.default_language`.
+ """
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if self.config.is_decoder:
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+ else:
+ use_cache = False
+
+ if use_cache and past_key_values is None:
+ past_key_values = (
+ EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
+ if encoder_hidden_states is not None or self.config.is_encoder_decoder
+ else DynamicCache(config=self.config)
+ )
+
+ batch_size = input_ids.shape[0] if input_ids is not None else inputs_embeds.shape[0]
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
+
+ if lang_ids is None:
+ if self.config.default_language is None:
+ raise ValueError("Input language unknown. Please call `XmodPreTrainedModel.set_default_language()`")
+ adapter_languages = list(self.encoder.layer[0].output.adapter_modules.keys())
+ default_lang_id = adapter_languages.index(self.config.default_language)
+ lang_ids = default_lang_id * torch.ones(batch_size, device=device)
+
+ embedding_output = self.embeddings(
+ input_ids=input_ids,
+ position_ids=position_ids,
+ token_type_ids=token_type_ids,
+ inputs_embeds=inputs_embeds,
+ past_key_values_length=past_key_values_length,
+ )
+
+ attention_mask, encoder_attention_mask = self._create_attention_masks(
+ attention_mask=attention_mask,
+ encoder_attention_mask=encoder_attention_mask,
+ embedding_output=embedding_output,
+ encoder_hidden_states=encoder_hidden_states,
+ past_key_values=past_key_values,
+ )
+
+ encoder_outputs = self.encoder(
+ embedding_output,
+ lang_ids=lang_ids,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_ids=position_ids,
+ **kwargs,
+ )
+ sequence_output = encoder_outputs[0]
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
+
+ return BaseModelOutputWithPoolingAndCrossAttentions(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ past_key_values=encoder_outputs.past_key_values,
+ )
+
+ # Copied from transformers.models.bert.modeling_bert.BertModel._create_attention_masks
+ def _create_attention_masks(
+ self,
+ attention_mask,
+ encoder_attention_mask,
+ embedding_output,
+ encoder_hidden_states,
+ past_key_values,
+ ):
+ if self.config.is_decoder:
+ attention_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ )
+ else:
+ attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=attention_mask,
+ )
+
+ if encoder_attention_mask is not None:
+ encoder_attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=encoder_attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ )
+
+ return attention_mask, encoder_attention_mask
+
+
+@auto_docstring(
+ custom_intro="""
+ X-MOD Model with a `language modeling` head on top for CLM fine-tuning.
+ """
+)
+class XmodForCausalLM(XmodPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {
+ "lm_head.decoder.weight": "roberta.embeddings.word_embeddings.weight",
+ "lm_head.decoder.bias": "lm_head.bias",
+ }
+
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForCausalLM.__init__ with Roberta->Xmod
+ def __init__(self, config):
+ super().__init__(config)
+
+ if not config.is_decoder:
+ logger.warning("If you want to use `XmodLMHeadModel` as a standalone, add `is_decoder=True.`")
+
+ self.roberta = XmodModel(config, add_pooling_layer=False)
+ self.lm_head = XmodLMHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForCausalLM.get_output_embeddings
+ def get_output_embeddings(self):
+ return self.lm_head.decoder
+
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForCausalLM.set_output_embeddings
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head.decoder = new_embeddings
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ lang_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ past_key_values: tuple[tuple[torch.FloatTensor]] | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | CausalLMOutputWithCrossAttentions:
+ r"""
+ lang_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of the language adapters that should be activated for each sample, respectively. Default: the index
+ that corresponds to `self.config.default_language`.
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
+ ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, XmodForCausalLM, AutoConfig
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("FacebookAI/xlm-roberta-base")
+ >>> config = AutoConfig.from_pretrained("facebook/xmod-base")
+ >>> config.is_decoder = True
+ >>> model = XmodForCausalLM.from_pretrained("facebook/xmod-base", config=config)
+ >>> model.set_default_language("en_XX")
+
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
+ >>> outputs = model(**inputs)
+
+ >>> prediction_logits = outputs.logits
+ ```"""
+ if labels is not None:
+ use_cache = False
+
+ outputs: BaseModelOutputWithPoolingAndCrossAttentions = self.roberta(
+ input_ids,
+ lang_ids=lang_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ return_dict=True,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return CausalLMOutputWithCrossAttentions(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+
+@auto_docstring
+class XmodForMaskedLM(XmodPreTrainedModel):
+ _tied_weights_keys = {
+ "lm_head.decoder.weight": "roberta.embeddings.word_embeddings.weight",
+ "lm_head.decoder.bias": "lm_head.bias",
+ }
+
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForMaskedLM.__init__ with Roberta->Xmod
+ def __init__(self, config):
+ super().__init__(config)
+
+ if config.is_decoder:
+ logger.warning(
+ "If you want to use `XmodForMaskedLM` make sure `config.is_decoder=False` for "
+ "bi-directional self-attention."
+ )
+
+ self.roberta = XmodModel(config, add_pooling_layer=False)
+ self.lm_head = XmodLMHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForMaskedLM.get_output_embeddings
+ def get_output_embeddings(self):
+ return self.lm_head.decoder
+
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForMaskedLM.set_output_embeddings
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head.decoder = new_embeddings
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ lang_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | MaskedLMOutput:
+ r"""
+ lang_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of the language adapters that should be activated for each sample, respectively. Default: the index
+ that corresponds to `self.config.default_language`.
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ """
+ outputs = self.roberta(
+ input_ids,
+ lang_ids=lang_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ return_dict=True,
+ **kwargs,
+ )
+ sequence_output = outputs[0]
+ prediction_scores = self.lm_head(sequence_output)
+
+ masked_lm_loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
+
+ return MaskedLMOutput(
+ loss=masked_lm_loss,
+ logits=prediction_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+# Copied from transformers.models.roberta.modeling_roberta.RobertaLMHead
+class XmodLMHead(nn.Module):
+ """Roberta Head for masked language modeling."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
+
+ def forward(self, features, **kwargs):
+ x = self.dense(features)
+ x = gelu(x)
+ x = self.layer_norm(x)
+
+ # project back to size of vocabulary with bias
+ x = self.decoder(x)
+
+ return x
+
+
+@auto_docstring(
+ custom_intro="""
+ X-MOD Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
+ output) e.g. for GLUE tasks.
+ """
+)
+class XmodForSequenceClassification(XmodPreTrainedModel):
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForSequenceClassification.__init__ with Roberta->Xmod
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.config = config
+
+ self.roberta = XmodModel(config, add_pooling_layer=False)
+ self.classifier = XmodClassificationHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ lang_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | SequenceClassifierOutput:
+ r"""
+ lang_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of the language adapters that should be activated for each sample, respectively. Default: the index
+ that corresponds to `self.config.default_language`.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ outputs = self.roberta(
+ input_ids,
+ lang_ids=lang_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+ sequence_output = outputs[0]
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class XmodForMultipleChoice(XmodPreTrainedModel):
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForMultipleChoice.__init__ with Roberta->Xmod
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.roberta = XmodModel(config)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.classifier = nn.Linear(config.hidden_size, 1)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ lang_ids: torch.LongTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | MultipleChoiceModelOutput:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ lang_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Indices of the language adapters that should be activated for each sample, respectively. Default: the index
+ that corresponds to `self.config.default_language`.
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
+ 1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
+ `input_ids` above)
+ position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ """
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
+
+ flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
+ flat_lang_ids = lang_ids.repeat(input_ids.size(0) * input_ids.size(1)) if lang_ids is not None else None
+ flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
+ flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
+ flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
+ flat_inputs_embeds = (
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
+ if inputs_embeds is not None
+ else None
+ )
+
+ outputs = self.roberta(
+ flat_input_ids,
+ lang_ids=flat_lang_ids,
+ position_ids=flat_position_ids,
+ token_type_ids=flat_token_type_ids,
+ attention_mask=flat_attention_mask,
+ inputs_embeds=flat_inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+ pooled_output = outputs[1]
+
+ pooled_output = self.dropout(pooled_output)
+ logits = self.classifier(pooled_output)
+ reshaped_logits = logits.view(-1, num_choices)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(reshaped_logits, labels)
+
+ return MultipleChoiceModelOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class XmodForTokenClassification(XmodPreTrainedModel):
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForTokenClassification.__init__ with Roberta->Xmod
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.roberta = XmodModel(config, add_pooling_layer=False)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ lang_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | TokenClassifierOutput:
+ r"""
+ lang_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of the language adapters that should be activated for each sample, respectively. Default: the index
+ that corresponds to `self.config.default_language`.
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+ outputs = self.roberta(
+ input_ids,
+ lang_ids=lang_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+
+ sequence_output = self.dropout(sequence_output)
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+# Copied from transformers.models.roberta.modeling_roberta.RobertaClassificationHead
+class XmodClassificationHead(nn.Module):
+ """Head for sentence-level classification tasks."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
+
+ def forward(self, features, **kwargs):
+ x = features[:, 0, :] # take token (equiv. to [CLS])
+ x = self.dropout(x)
+ x = self.dense(x)
+ x = torch.tanh(x)
+ x = self.dropout(x)
+ x = self.out_proj(x)
+ return x
+
+
+@auto_docstring
+class XmodForQuestionAnswering(XmodPreTrainedModel):
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForQuestionAnswering.__init__ with Roberta->Xmod
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.roberta = XmodModel(config, add_pooling_layer=False)
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ lang_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ start_positions: torch.LongTensor | None = None,
+ end_positions: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | QuestionAnsweringModelOutput:
+ r"""
+ lang_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of the language adapters that should be activated for each sample, respectively. Default: the index
+ that corresponds to `self.config.default_language`.
+ """
+ outputs = self.roberta(
+ input_ids,
+ lang_ids=lang_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1).contiguous()
+ end_logits = end_logits.squeeze(-1).contiguous()
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ return QuestionAnsweringModelOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "XmodForCausalLM",
+ "XmodForMaskedLM",
+ "XmodForMultipleChoice",
+ "XmodForQuestionAnswering",
+ "XmodForSequenceClassification",
+ "XmodForTokenClassification",
+ "XmodModel",
+ "XmodPreTrainedModel",
+]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/yolos/__init__.py b/.venv/lib/python3.12/site-packages/transformers/models/yolos/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ae5ae3635ee0face750183ebaff76b634c0b50c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/yolos/__init__.py
@@ -0,0 +1,30 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_yolos import *
+ from .feature_extraction_yolos import *
+ from .image_processing_pil_yolos import *
+ from .image_processing_yolos import *
+ from .modeling_yolos import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/yolos/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/yolos/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3a2efd9f51a0f349d8043a2c65632d7cd62102e7
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/yolos/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/yolos/__pycache__/configuration_yolos.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/yolos/__pycache__/configuration_yolos.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a7651370372942ac793f75f90b1281a02858ccef
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/yolos/__pycache__/configuration_yolos.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/yolos/__pycache__/image_processing_pil_yolos.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/yolos/__pycache__/image_processing_pil_yolos.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..280caf606bc845194ca0bbdd9bf51eccf9472324
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/yolos/__pycache__/image_processing_pil_yolos.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/yolos/__pycache__/image_processing_yolos.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/yolos/__pycache__/image_processing_yolos.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f80245724d814731cffac142762a2444a5657203
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/yolos/__pycache__/image_processing_yolos.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/yolos/__pycache__/modeling_yolos.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/yolos/__pycache__/modeling_yolos.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bc4418440e3226e9848c0752f3d670411d0ad8a0
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/yolos/__pycache__/modeling_yolos.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/yolos/__pycache__/modular_yolos.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/yolos/__pycache__/modular_yolos.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2f691a1dfbe231f25c5138c0f4b8e5ab8e6e23b5
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/yolos/__pycache__/modular_yolos.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/yolos/configuration_yolos.py b/.venv/lib/python3.12/site-packages/transformers/models/yolos/configuration_yolos.py
new file mode 100644
index 0000000000000000000000000000000000000000..28d088229dd9f9486887c55db4c543c01eccf480
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/yolos/configuration_yolos.py
@@ -0,0 +1,72 @@
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""YOLOS model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="hustvl/yolos-base")
+@strict
+class YolosConfig(PreTrainedConfig):
+ r"""
+ num_detection_tokens (`int`, *optional*, defaults to 100):
+ The number of detection tokens.
+ use_mid_position_embeddings (`bool`, *optional*, defaults to `True`):
+ Whether to use the mid-layer position encodings.
+
+ Example:
+
+ ```python
+ >>> from transformers import YolosConfig, YolosModel
+
+ >>> # Initializing a YOLOS hustvl/yolos-base style configuration
+ >>> configuration = YolosConfig()
+
+ >>> # Initializing a model (with random weights) from the hustvl/yolos-base style configuration
+ >>> model = YolosModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "yolos"
+
+ hidden_size: int = 768
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ intermediate_size: int = 3072
+ hidden_act: str = "gelu"
+ hidden_dropout_prob: float | int = 0.0
+ attention_probs_dropout_prob: float | int = 0.0
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-12
+ image_size: list[int] | tuple[int, ...] = (512, 864)
+ patch_size: int | list[int] | tuple[int, int] = 16
+ num_channels: int = 3
+ qkv_bias: bool = True
+ num_detection_tokens: int = 100
+ use_mid_position_embeddings: bool = True
+ auxiliary_loss: bool = False
+ class_cost: int = 1
+ bbox_cost: int = 5
+ giou_cost: int = 2
+ bbox_loss_coefficient: int = 5
+ giou_loss_coefficient: int = 2
+ eos_coefficient: float = 0.1
+
+
+__all__ = ["YolosConfig"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/yolos/image_processing_pil_yolos.py b/.venv/lib/python3.12/site-packages/transformers/models/yolos/image_processing_pil_yolos.py
new file mode 100644
index 0000000000000000000000000000000000000000..f42fb5a6370104133cc7021bae5b702a43461133
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/yolos/image_processing_pil_yolos.py
@@ -0,0 +1,760 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/yolos/modular_yolos.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_yolos.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+import pathlib
+from typing import Any, Optional
+
+import numpy as np
+
+from ...image_processing_backends import PilBackend
+from ...image_processing_utils import BatchFeature
+from ...image_transforms import (
+ PaddingMode,
+ center_to_corners_format,
+ corners_to_center_format,
+ pad,
+ resize,
+ safe_squeeze,
+)
+from ...image_utils import (
+ IMAGENET_DEFAULT_MEAN,
+ IMAGENET_DEFAULT_STD,
+ AnnotationFormat,
+ AnnotationType,
+ ChannelDimension,
+ ImageInput,
+ PILImageResampling,
+ SizeDict,
+ get_image_size,
+ get_image_size_for_max_height_width,
+ get_max_height_width,
+ validate_annotations,
+)
+from ...processing_utils import ImagesKwargs, Unpack
+from ...utils import TensorType, auto_docstring, is_torch_available, is_vision_available, requires_backends
+from ...utils.import_utils import requires
+
+
+if is_vision_available():
+ import PIL.Image
+if is_torch_available():
+ import torch
+ from torch import nn
+
+SUPPORTED_ANNOTATION_FORMATS = (AnnotationFormat.COCO_DETECTION, AnnotationFormat.COCO_PANOPTIC)
+
+
+class YolosImageProcessorKwargs(ImagesKwargs, total=False):
+ r"""
+ format (`str`, *optional*, defaults to `AnnotationFormat.COCO_DETECTION`):
+ Data format of the annotations. One of "coco_detection" or "coco_panoptic".
+ do_convert_annotations (`bool`, *optional*, defaults to `True`):
+ Controls whether to convert the annotations to the format expected by the YOLOS model. Converts the
+ bounding boxes to the format `(center_x, center_y, width, height)` and in the range `[0, 1]`.
+ Can be overridden by the `do_convert_annotations` parameter in the `preprocess` method.
+ """
+
+ format: str | AnnotationFormat
+ do_convert_annotations: bool
+
+
+# inspired by https://github.com/facebookresearch/yolos/blob/master/datasets/coco.py#L33
+def convert_coco_poly_to_mask(segmentations, height: int, width: int) -> np.ndarray:
+ """
+ Convert a COCO polygon annotation to a mask.
+
+ Args:
+ segmentations (`list[list[float]]`):
+ List of polygons, each polygon represented by a list of x-y coordinates.
+ height (`int`):
+ Height of the mask.
+ width (`int`):
+ Width of the mask.
+ """
+ try:
+ from pycocotools import mask as coco_mask
+ except ImportError:
+ raise ImportError("Pycocotools is not installed in your environment.")
+
+ masks = []
+ for polygons in segmentations:
+ rles = coco_mask.frPyObjects(polygons, height, width)
+ mask = coco_mask.decode(rles)
+ if len(mask.shape) < 3:
+ mask = mask[..., None]
+ mask = np.asarray(mask, dtype=np.uint8)
+ mask = np.any(mask, axis=2)
+ masks.append(mask)
+ if masks:
+ masks = np.stack(masks, axis=0)
+ else:
+ masks = np.zeros((0, height, width), dtype=np.uint8)
+
+ return masks
+
+
+# inspired by https://github.com/facebookresearch/yolos/blob/master/datasets/coco.py#L50
+def prepare_coco_detection_annotation(
+ image,
+ target,
+ return_segmentation_masks: bool = False,
+ input_data_format: ChannelDimension | str | None = None,
+):
+ """
+ Convert the target in COCO format into the format expected by YOLOS.
+ """
+ image_height, image_width = get_image_size(image, channel_dim=input_data_format)
+
+ image_id = target["image_id"]
+ image_id = np.asarray([image_id], dtype=np.int64)
+
+ # Get all COCO annotations for the given image.
+ annotations = target["annotations"]
+ annotations = [obj for obj in annotations if "iscrowd" not in obj or obj["iscrowd"] == 0]
+
+ classes = [obj["category_id"] for obj in annotations]
+ classes = np.asarray(classes, dtype=np.int64)
+
+ # for conversion to coco api
+ area = np.asarray([obj["area"] for obj in annotations], dtype=np.float32)
+ iscrowd = np.asarray([obj.get("iscrowd", 0) for obj in annotations], dtype=np.int64)
+
+ boxes = [obj["bbox"] for obj in annotations]
+ # guard against no boxes via resizing
+ boxes = np.asarray(boxes, dtype=np.float32).reshape(-1, 4)
+ boxes[:, 2:] += boxes[:, :2]
+ boxes[:, 0::2] = boxes[:, 0::2].clip(min=0, max=image_width)
+ boxes[:, 1::2] = boxes[:, 1::2].clip(min=0, max=image_height)
+
+ keep = (boxes[:, 3] > boxes[:, 1]) & (boxes[:, 2] > boxes[:, 0])
+
+ new_target = {}
+ new_target["image_id"] = image_id
+ new_target["class_labels"] = classes[keep]
+ new_target["boxes"] = boxes[keep]
+ new_target["area"] = area[keep]
+ new_target["iscrowd"] = iscrowd[keep]
+ new_target["orig_size"] = np.asarray([int(image_height), int(image_width)], dtype=np.int64)
+
+ if annotations and "keypoints" in annotations[0]:
+ keypoints = [obj["keypoints"] for obj in annotations]
+ # Converting the filtered keypoints list to a numpy array
+ keypoints = np.asarray(keypoints, dtype=np.float32)
+ # Apply the keep mask here to filter the relevant annotations
+ keypoints = keypoints[keep]
+ num_keypoints = keypoints.shape[0]
+ keypoints = keypoints.reshape((-1, 3)) if num_keypoints else keypoints
+ new_target["keypoints"] = keypoints
+
+ if return_segmentation_masks:
+ segmentation_masks = [obj["segmentation"] for obj in annotations]
+ masks = convert_coco_poly_to_mask(segmentation_masks, image_height, image_width)
+ new_target["masks"] = masks[keep]
+
+ return new_target
+
+
+def masks_to_boxes(masks: np.ndarray) -> np.ndarray:
+ """
+ Compute the bounding boxes around the provided panoptic segmentation masks.
+
+ Args:
+ masks: masks in format `[number_masks, height, width]` where N is the number of masks
+
+ Returns:
+ boxes: bounding boxes in format `[number_masks, 4]` in xyxy format
+ """
+ if masks.size == 0:
+ return np.zeros((0, 4))
+
+ h, w = masks.shape[-2:]
+ y = np.arange(0, h, dtype=np.float32)
+ x = np.arange(0, w, dtype=np.float32)
+ # see https://github.com/pytorch/pytorch/issues/50276
+ y, x = np.meshgrid(y, x, indexing="ij")
+
+ x_mask = masks * np.expand_dims(x, axis=0)
+ x_max = x_mask.reshape(x_mask.shape[0], -1).max(-1)
+ x = np.ma.array(x_mask, mask=~(np.array(masks, dtype=bool)))
+ x_min = x.filled(fill_value=1e8)
+ x_min = x_min.reshape(x_min.shape[0], -1).min(-1)
+
+ y_mask = masks * np.expand_dims(y, axis=0)
+ y_max = y_mask.reshape(x_mask.shape[0], -1).max(-1)
+ y = np.ma.array(y_mask, mask=~(np.array(masks, dtype=bool)))
+ y_min = y.filled(fill_value=1e8)
+ y_min = y_min.reshape(y_min.shape[0], -1).min(-1)
+
+ return np.stack([x_min, y_min, x_max, y_max], 1)
+
+
+# 2 functions below adapted from https://github.com/cocodataset/panopticapi/blob/master/panopticapi/utils.py
+# Copyright (c) 2018, Alexander Kirillov
+# All rights reserved.
+def rgb_to_id(color):
+ """
+ Converts RGB color to unique ID.
+ """
+ if isinstance(color, np.ndarray) and len(color.shape) == 3:
+ if color.dtype == np.uint8:
+ color = color.astype(np.int32)
+ return color[:, :, 0] + 256 * color[:, :, 1] + 256 * 256 * color[:, :, 2]
+ return int(color[0] + 256 * color[1] + 256 * 256 * color[2])
+
+
+def prepare_coco_panoptic_annotation(
+ image: np.ndarray,
+ target: dict,
+ masks_path: str | pathlib.Path,
+ return_masks: bool = True,
+ input_data_format: ChannelDimension | str = None,
+) -> dict:
+ """
+ Prepare a coco panoptic annotation for YOLOS.
+ """
+ image_height, image_width = get_image_size(image, channel_dim=input_data_format)
+ annotation_path = pathlib.Path(masks_path) / target["file_name"]
+
+ new_target = {}
+ new_target["image_id"] = np.asarray([target["image_id"] if "image_id" in target else target["id"]], dtype=np.int64)
+ new_target["size"] = np.asarray([image_height, image_width], dtype=np.int64)
+ new_target["orig_size"] = np.asarray([image_height, image_width], dtype=np.int64)
+
+ if "segments_info" in target:
+ masks = np.asarray(PIL.Image.open(annotation_path), dtype=np.uint32)
+ masks = rgb_to_id(masks)
+
+ ids = np.array([segment_info["id"] for segment_info in target["segments_info"]])
+ masks = masks == ids[:, None, None]
+ masks = masks.astype(np.uint8)
+ if return_masks:
+ new_target["masks"] = masks
+ new_target["boxes"] = masks_to_boxes(masks)
+ new_target["class_labels"] = np.array(
+ [segment_info["category_id"] for segment_info in target["segments_info"]], dtype=np.int64
+ )
+ new_target["iscrowd"] = np.asarray(
+ [segment_info["iscrowd"] for segment_info in target["segments_info"]], dtype=np.int64
+ )
+ new_target["area"] = np.asarray(
+ [segment_info["area"] for segment_info in target["segments_info"]], dtype=np.float32
+ )
+
+ return new_target
+
+
+def get_size_with_aspect_ratio_yolos(
+ image_size: tuple[int, int], size: int, max_size: int | None = None, mod_size: int = 16
+) -> tuple[int, int]:
+ """
+ Computes the output image size given the input image size and the desired output size, while ensuring that both
+ height and width are multiples of `mod_size`.
+
+ This mirrors the YOLOS-specific behavior used in the torch/fast backends and is required so that all YOLOS
+ image processing backends (PIL, torchvision, fast) produce identical output shapes.
+ """
+ height, width = image_size
+ raw_size = None
+ if max_size is not None:
+ min_original_size = float(min((height, width)))
+ max_original_size = float(max((height, width)))
+ if max_original_size / min_original_size * size > max_size:
+ raw_size = max_size * min_original_size / max_original_size
+ size = int(round(raw_size))
+
+ if width < height:
+ ow = size
+ if max_size is not None and raw_size is not None:
+ oh = int(raw_size * height / width)
+ else:
+ oh = int(size * height / width)
+ elif (height <= width and height == size) or (width <= height and width == size):
+ oh, ow = height, width
+ else:
+ oh = size
+ if max_size is not None and raw_size is not None:
+ ow = int(raw_size * width / height)
+ else:
+ ow = int(size * width / height)
+
+ if mod_size is not None:
+ ow = ow - (ow % mod_size)
+ oh = oh - (oh % mod_size)
+
+ return (oh, ow)
+
+
+@auto_docstring
+class YolosImageProcessorPil(PilBackend):
+ resample = PILImageResampling.BILINEAR
+ image_mean = IMAGENET_DEFAULT_MEAN
+ image_std = IMAGENET_DEFAULT_STD
+ format = AnnotationFormat.COCO_DETECTION
+ do_resize = True
+ do_rescale = True
+ do_normalize = True
+ do_pad = True
+ size = {"shortest_edge": 800, "longest_edge": 1333}
+ default_to_square = False
+ model_input_names = ["pixel_values", "pixel_mask"]
+ valid_kwargs = YolosImageProcessorKwargs
+
+ def __init__(self, **kwargs: Unpack[YolosImageProcessorKwargs]) -> None:
+ kwargs.setdefault("do_pad", kwargs.pop("pad_and_return_pixel_mask", self.do_pad))
+
+ size = kwargs.pop("size", None)
+ max_size = None if size is None else kwargs.pop("max_size", 1333)
+ size = size if size is not None else {"shortest_edge": 800, "longest_edge": 1333}
+ # Convert size dict for backwards compat with max_size parameter
+ if size is not None:
+ from ...image_processing_utils import get_size_dict
+
+ kwargs["size"] = get_size_dict(size, max_size=max_size, default_to_square=False)
+
+ # Backwards compatibility
+ do_convert_annotations = kwargs.get("do_convert_annotations")
+ do_normalize = kwargs.get("do_normalize")
+ if do_convert_annotations is None and getattr(self, "do_convert_annotations", None) is None:
+ self.do_convert_annotations = do_normalize if do_normalize is not None else self.do_normalize
+
+ super().__init__(**kwargs)
+
+ def prepare_annotation(
+ self,
+ image: np.ndarray,
+ target: dict,
+ format: AnnotationFormat | None = None,
+ return_segmentation_masks: bool | None = None,
+ masks_path: str | pathlib.Path | None = None,
+ input_data_format: str | ChannelDimension | None = None,
+ ) -> dict:
+ """
+ Prepare an annotation for feeding into YOLOS model.
+ """
+ format = format if format is not None else self.format
+
+ if format == AnnotationFormat.COCO_DETECTION:
+ return_segmentation_masks = False if return_segmentation_masks is None else return_segmentation_masks
+ target = prepare_coco_detection_annotation(
+ image, target, return_segmentation_masks, input_data_format=input_data_format
+ )
+ elif format == AnnotationFormat.COCO_PANOPTIC:
+ return_segmentation_masks = True if return_segmentation_masks is None else return_segmentation_masks
+ target = prepare_coco_panoptic_annotation(
+ image,
+ target,
+ masks_path=masks_path,
+ return_masks=return_segmentation_masks,
+ input_data_format=input_data_format,
+ )
+ else:
+ raise ValueError(f"Format {format} is not supported.")
+ return target
+
+ def resize(
+ self,
+ image: np.ndarray,
+ size: SizeDict,
+ resample: Optional["PILImageResampling"] = None,
+ **kwargs,
+ ) -> np.ndarray:
+ """
+ Resize the image to the given size. Size can be `min_size` (scalar) or `(height, width)` tuple. If size is an
+ int, smaller edge of the image will be matched to this number.
+
+ Args:
+ image (`np.ndarray`):
+ Image to resize.
+ size (`SizeDict`):
+ Size of the image's `(height, width)` dimensions after resizing. Available options are:
+ - `{"height": int, "width": int}`: The image will be resized to the exact size `(height, width)`.
+ Do NOT keep the aspect ratio.
+ - `{"shortest_edge": int, "longest_edge": int}`: The image will be resized to a maximum size respecting
+ the aspect ratio and keeping the shortest edge less or equal to `shortest_edge` and the longest edge
+ less or equal to `longest_edge`.
+ - `{"max_height": int, "max_width": int}`: The image will be resized to the maximum size respecting the
+ aspect ratio and keeping the height less or equal to `max_height` and the width less or equal to
+ `max_width`.
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
+ Resampling filter to use if resizing the image.
+ """
+ resample = resample if resample is not None else self.resample
+
+ if size.shortest_edge and size.longest_edge:
+ # Resize the image so that the shortest edge or the longest edge is of the given size
+ # while maintaining the aspect ratio of the original image.
+ new_size = get_size_with_aspect_ratio_yolos(
+ image.shape[-2:],
+ size.shortest_edge,
+ size.longest_edge or size.shortest_edge,
+ )
+ elif size.max_height and size.max_width:
+ new_size = get_image_size_for_max_height_width(image.shape[-2:], size.max_height, size.max_width)
+ elif size.height and size.width:
+ new_size = (size.height, size.width)
+ else:
+ raise ValueError(
+ f"Size must contain 'height' and 'width' keys or 'shortest_edge' and 'longest_edge' keys. Got {size}."
+ )
+
+ image = super().resize(
+ image,
+ size=SizeDict(height=new_size[0], width=new_size[1]),
+ resample=resample,
+ **kwargs,
+ )
+ return image
+
+ def resize_annotation(
+ self,
+ annotation: dict[str, Any],
+ orig_size: tuple[int, int],
+ target_size: tuple[int, int],
+ threshold: float = 0.5,
+ resample: Optional["PILImageResampling"] = PILImageResampling.NEAREST,
+ ):
+ """
+ Resizes an annotation to a target size.
+
+ Args:
+ annotation (`dict[str, Any]`):
+ The annotation dictionary.
+ orig_size (`tuple[int, int]`):
+ The original size of the input image.
+ target_size (`tuple[int, int]`):
+ The target size of the image, as returned by the preprocessing `resize` step.
+ threshold (`float`, *optional*, defaults to 0.5):
+ The threshold used to binarize the segmentation masks.
+ resample (`PILImageResampling`, defaults to `PILImageResampling.NEAREST`):
+ The resampling filter to use when resizing the masks.
+ """
+ ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(target_size, orig_size))
+ ratio_height, ratio_width = ratios
+
+ new_annotation = {}
+ new_annotation["size"] = target_size
+
+ for key, value in annotation.items():
+ if key == "boxes":
+ boxes = value
+ scaled_boxes = boxes * np.asarray(
+ [ratio_width, ratio_height, ratio_width, ratio_height], dtype=np.float32
+ )
+ new_annotation["boxes"] = scaled_boxes
+ elif key == "area":
+ area = value
+ scaled_area = area * (ratio_width * ratio_height)
+ new_annotation["area"] = scaled_area
+ elif key == "masks":
+ masks = value[:, None]
+ masks = np.array([resize(mask, target_size, resample=resample) for mask in masks])
+ masks = masks.astype(np.float32)
+ masks = masks[:, 0] > threshold
+ new_annotation["masks"] = masks
+ elif key == "size":
+ new_annotation["size"] = target_size
+ else:
+ new_annotation[key] = value
+
+ return new_annotation
+
+ def normalize_annotation(self, annotation: dict, image_size: tuple[int, int]) -> dict:
+ image_height, image_width = image_size
+ norm_annotation = {}
+ for key, value in annotation.items():
+ if key == "boxes":
+ boxes = value
+ boxes = corners_to_center_format(boxes)
+ boxes /= np.asarray([image_width, image_height, image_width, image_height], dtype=np.float32)
+ norm_annotation[key] = boxes
+ else:
+ norm_annotation[key] = value
+ return norm_annotation
+
+ def _update_annotation_for_padded_image(
+ self,
+ annotation: dict,
+ input_image_size: tuple[int, int],
+ output_image_size: tuple[int, int],
+ padding,
+ update_bboxes,
+ ) -> dict:
+ """
+ Update the annotation for a padded image.
+ """
+ new_annotation = {}
+ new_annotation["size"] = output_image_size
+ ratio_height, ratio_width = (input / output for output, input in zip(output_image_size, input_image_size))
+
+ for key, value in annotation.items():
+ if key == "masks":
+ masks = value
+ masks = pad(
+ masks,
+ padding,
+ mode=PaddingMode.CONSTANT,
+ constant_values=0,
+ input_data_format=ChannelDimension.FIRST,
+ )
+ masks = safe_squeeze(masks, 1)
+ new_annotation["masks"] = masks
+ elif key == "boxes" and update_bboxes:
+ boxes = value
+ boxes *= np.asarray(
+ [
+ input_image_size[1] / output_image_size[1],
+ input_image_size[0] / output_image_size[0],
+ input_image_size[1] / output_image_size[1],
+ input_image_size[0] / output_image_size[0],
+ ]
+ )
+ new_annotation["boxes"] = boxes
+ elif key == "size":
+ new_annotation["size"] = output_image_size
+ else:
+ new_annotation[key] = value
+ return new_annotation
+
+ def pad(
+ self,
+ image: np.ndarray,
+ padded_size: tuple[int, int],
+ annotation: dict[str, Any] | None = None,
+ update_bboxes: bool = True,
+ fill: int = 0,
+ ):
+ input_height, input_width = get_image_size(image, channel_dim=ChannelDimension.FIRST)
+ output_height, output_width = padded_size
+ padding_bottom = output_height - input_height
+ padding_right = output_width - input_width
+ if padding_bottom < 0 or padding_right < 0:
+ raise ValueError(
+ f"Padding dimensions are negative. Please make sure that the padded size is larger than the "
+ f"original size. Got padded size: {padded_size}, original size: {(input_height, input_width)}."
+ )
+ if (input_height, input_width) != padded_size:
+ padding = ((0, padding_bottom), (0, padding_right))
+ image = pad(
+ image,
+ padding,
+ mode=PaddingMode.CONSTANT,
+ constant_values=fill,
+ data_format=ChannelDimension.FIRST,
+ input_data_format=ChannelDimension.FIRST,
+ )
+ if annotation is not None:
+ annotation = self._update_annotation_for_padded_image(
+ annotation, (input_height, input_width), (output_height, output_width), padding, update_bboxes
+ )
+
+ # Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding.
+ pixel_mask = np.zeros(padded_size, dtype=np.int64)
+ pixel_mask[:input_height, :input_width] = 1
+
+ return image, pixel_mask, annotation
+
+ @auto_docstring
+ def preprocess(
+ self,
+ images: ImageInput,
+ annotations: AnnotationType | list[AnnotationType] | None = None,
+ return_segmentation_masks: bool | None = None,
+ masks_path: str | pathlib.Path | None = None,
+ **kwargs: Unpack[YolosImageProcessorKwargs],
+ ) -> BatchFeature:
+ r"""
+ annotations (`AnnotationType` or `list[AnnotationType]`, *optional*):
+ Annotations to transform according to the padding that is applied to the images.
+ return_segmentation_masks (`bool`, *optional*, defaults to `self.return_segmentation_masks`):
+ Whether to return segmentation masks.
+ masks_path (`str` or `pathlib.Path`, *optional*):
+ Path to the directory containing the segmentation masks.
+ """
+ return super().preprocess(images, annotations, return_segmentation_masks, masks_path, **kwargs)
+
+ def _preprocess(
+ self,
+ images: list[np.ndarray],
+ annotations: AnnotationType | list[AnnotationType] | None,
+ return_segmentation_masks: bool,
+ masks_path: str | pathlib.Path | None,
+ do_resize: bool,
+ size: SizeDict,
+ resample: "PILImageResampling | None",
+ do_rescale: bool,
+ rescale_factor: float,
+ do_normalize: bool,
+ do_convert_annotations: bool,
+ image_mean: float | list[float] | None,
+ image_std: float | list[float] | None,
+ do_pad: bool,
+ pad_size: SizeDict | None,
+ format: str | AnnotationFormat | None,
+ return_tensors: str | TensorType | None,
+ **kwargs,
+ ) -> BatchFeature:
+ """
+ Preprocess an image or a batch of images so that it can be used by the model.
+ """
+ if annotations is not None and isinstance(annotations, dict):
+ annotations = [annotations]
+
+ if annotations is not None and len(images) != len(annotations):
+ raise ValueError(
+ f"The number of images ({len(images)}) and annotations ({len(annotations)}) do not match."
+ )
+
+ format = AnnotationFormat(format)
+ if annotations is not None:
+ validate_annotations(format, SUPPORTED_ANNOTATION_FORMATS, annotations)
+
+ if (
+ masks_path is not None
+ and format == AnnotationFormat.COCO_PANOPTIC
+ and not isinstance(masks_path, (pathlib.Path, str))
+ ):
+ raise ValueError(
+ "The path to the directory containing the mask PNG files should be provided as a"
+ f" `pathlib.Path` or string object, but is {type(masks_path)} instead."
+ )
+
+ data = {}
+
+ # Import torch if needed for tensor conversion
+ if return_tensors == "pt":
+ if not is_torch_available():
+ raise ImportError("PyTorch is required for tensor conversion.")
+
+ processed_images = []
+ processed_annotations = []
+ pixel_masks = [] # Initialize pixel_masks here
+ for image, annotation in zip(images, annotations if annotations is not None else [None] * len(images)):
+ # prepare (COCO annotations as a list of Dict -> YOLOS target as a single Dict per image)
+ if annotations is not None:
+ annotation = self.prepare_annotation(
+ image,
+ annotation,
+ format,
+ return_segmentation_masks=return_segmentation_masks,
+ masks_path=masks_path,
+ input_data_format=ChannelDimension.FIRST,
+ )
+
+ if do_resize:
+ resized_image = self.resize(image, size=size, resample=resample)
+ if annotations is not None:
+ annotation = self.resize_annotation(
+ annotation,
+ orig_size=get_image_size(image, channel_dim=ChannelDimension.FIRST),
+ target_size=get_image_size(resized_image, channel_dim=ChannelDimension.FIRST),
+ )
+ image = resized_image
+
+ if do_rescale:
+ image = self.rescale(image, rescale_factor)
+ if do_normalize:
+ image = self.normalize(image, image_mean, image_std)
+
+ if do_convert_annotations and annotations is not None:
+ annotation = self.normalize_annotation(annotation, get_image_size(image, ChannelDimension.FIRST))
+
+ processed_images.append(image)
+ processed_annotations.append(annotation)
+ images = processed_images
+ annotations = processed_annotations if annotations is not None else None
+
+ if do_pad:
+ # depends on all resized image shapes so we need another loop
+ if pad_size is not None:
+ padded_size = (pad_size.height, pad_size.width)
+ else:
+ padded_size = get_max_height_width(images, input_data_format=ChannelDimension.FIRST)
+
+ padded_images = []
+ padded_annotations = []
+ for image, annotation in zip(images, annotations if annotations is not None else [None] * len(images)):
+ # Pads images and returns their mask: {'pixel_values': ..., 'pixel_mask': ...}
+ image_height, image_width = get_image_size(image, channel_dim=ChannelDimension.FIRST)
+ if padded_size == (image_height, image_width):
+ padded_images.append(image)
+ pixel_masks.append(np.ones(padded_size, dtype=np.int64))
+ padded_annotations.append(annotation)
+ continue
+ image, pixel_mask, annotation = self.pad(
+ image, padded_size, annotation=annotation, update_bboxes=do_convert_annotations
+ )
+ padded_images.append(image)
+ padded_annotations.append(annotation)
+ pixel_masks.append(pixel_mask)
+ images = padded_images
+ annotations = padded_annotations if annotations is not None else None
+ data.update({"pixel_mask": pixel_masks})
+
+ data.update({"pixel_values": images})
+ encoded_inputs = BatchFeature(data, tensor_type=return_tensors)
+ if annotations is not None:
+ encoded_inputs["labels"] = [
+ BatchFeature(annotation, tensor_type=return_tensors) for annotation in annotations
+ ]
+ return encoded_inputs
+
+ @requires(backends=("torch",))
+ def post_process_object_detection(
+ self, outputs, threshold: float = 0.5, target_sizes: TensorType | list[tuple] = None
+ ):
+ """
+ Converts the raw output of [`YolosForObjectDetection`] into final bounding boxes in (top_left_x, top_left_y,
+ bottom_right_x, bottom_right_y) format. Only supports PyTorch.
+
+ Args:
+ outputs ([`YolosObjectDetectionOutput`]):
+ Raw outputs of the model.
+ threshold (`float`, *optional*):
+ Score threshold to keep object detection predictions.
+ target_sizes (`torch.Tensor` or `list[tuple[int, int]]`, *optional*):
+ Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the target size
+ `(height, width)` of each image in the batch. If unset, predictions will not be resized.
+ Returns:
+ `list[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
+ in the batch as predicted by the model.
+ """
+ requires_backends(self, ["torch"])
+ out_logits, out_bbox = outputs.logits, outputs.pred_boxes
+
+ if target_sizes is not None:
+ if len(out_logits) != len(target_sizes):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
+ )
+
+ prob = nn.functional.softmax(out_logits, -1)
+ scores, labels = prob[..., :-1].max(-1)
+
+ # Convert to [x0, y0, x1, y1] format
+ boxes = center_to_corners_format(out_bbox)
+
+ # Convert from relative [0, 1] to absolute [0, height] coordinates
+ if target_sizes is not None:
+ if isinstance(target_sizes, list):
+ img_h = torch.Tensor([i[0] for i in target_sizes])
+ img_w = torch.Tensor([i[1] for i in target_sizes])
+ else:
+ img_h, img_w = target_sizes.unbind(1)
+
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1).to(boxes.device)
+ boxes = boxes * scale_fct[:, None, :]
+
+ results = []
+ for s, l, b in zip(scores, labels, boxes):
+ score = s[s > threshold]
+ label = l[s > threshold]
+ box = b[s > threshold]
+ results.append({"scores": score, "labels": label, "boxes": box})
+
+ return results
+
+
+__all__ = ["YolosImageProcessorPil"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/yolos/image_processing_yolos.py b/.venv/lib/python3.12/site-packages/transformers/models/yolos/image_processing_yolos.py
new file mode 100644
index 0000000000000000000000000000000000000000..52c9232aa16901d88fbaf4146f23be5f0dcc7a00
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/yolos/image_processing_yolos.py
@@ -0,0 +1,726 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/yolos/modular_yolos.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_yolos.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+import pathlib
+from typing import Any, Optional
+
+import torch
+from torch import nn
+from torchvision.io import read_image
+from torchvision.transforms.v2 import functional as tvF
+
+from ...image_processing_backends import TorchvisionBackend
+from ...image_processing_utils import BatchFeature, get_size_dict
+from ...image_transforms import center_to_corners_format, corners_to_center_format, safe_squeeze
+from ...image_utils import (
+ IMAGENET_DEFAULT_MEAN,
+ IMAGENET_DEFAULT_STD,
+ AnnotationFormat,
+ AnnotationType,
+ ChannelDimension,
+ ImageInput,
+ PILImageResampling,
+ SizeDict,
+ get_image_size,
+ get_image_size_for_max_height_width,
+ get_max_height_width,
+ validate_annotations,
+)
+from ...processing_utils import ImagesKwargs, Unpack
+from ...utils import TensorType, auto_docstring
+
+
+class YolosImageProcessorKwargs(ImagesKwargs, total=False):
+ r"""
+ format (`str`, *optional*, defaults to `AnnotationFormat.COCO_DETECTION`):
+ Data format of the annotations. One of "coco_detection" or "coco_panoptic".
+ do_convert_annotations (`bool`, *optional*, defaults to `True`):
+ Controls whether to convert the annotations to the format expected by the YOLOS model. Converts the
+ bounding boxes to the format `(center_x, center_y, width, height)` and in the range `[0, 1]`.
+ Can be overridden by the `do_convert_annotations` parameter in the `preprocess` method.
+ """
+
+ format: str | AnnotationFormat
+ do_convert_annotations: bool
+
+
+SUPPORTED_ANNOTATION_FORMATS = (AnnotationFormat.COCO_DETECTION, AnnotationFormat.COCO_PANOPTIC)
+
+
+# inspired by https://github.com/facebookresearch/yolos/blob/master/datasets/coco.py#L33
+def convert_coco_poly_to_mask(segmentations, height: int, width: int, device: torch.device) -> torch.Tensor:
+ """
+ Convert a COCO polygon annotation to a mask.
+
+ Args:
+ segmentations (`list[list[float]]`):
+ List of polygons, each polygon represented by a list of x-y coordinates.
+ height (`int`):
+ Height of the mask.
+ width (`int`):
+ Width of the mask.
+ """
+ try:
+ from pycocotools import mask as coco_mask
+ except ImportError:
+ raise ImportError("Pycocotools is not installed in your environment.")
+
+ masks = []
+ for polygons in segmentations:
+ rles = coco_mask.frPyObjects(polygons, height, width)
+ mask = coco_mask.decode(rles)
+ if len(mask.shape) < 3:
+ mask = mask[..., None]
+ mask = torch.as_tensor(mask, dtype=torch.uint8, device=device)
+ mask = torch.any(mask, axis=2)
+ masks.append(mask)
+ if masks:
+ masks = torch.stack(masks, axis=0)
+ else:
+ masks = torch.zeros((0, height, width), dtype=torch.uint8, device=device)
+
+ return masks
+
+
+# inspired by https://github.com/facebookresearch/yolos/blob/master/datasets/coco.py#L50
+def prepare_coco_detection_annotation(
+ image,
+ target,
+ return_segmentation_masks: bool = False,
+ input_data_format: ChannelDimension | str | None = None,
+):
+ """
+ Convert the target in COCO format into the format expected by YOLOS.
+ """
+ image_height, image_width = image.size()[-2:]
+
+ image_id = target["image_id"]
+ image_id = torch.as_tensor([image_id], dtype=torch.int64, device=image.device)
+
+ # Get all COCO annotations for the given image.
+ annotations = target["annotations"]
+ classes = []
+ area = []
+ boxes = []
+ keypoints = []
+ for obj in annotations:
+ if "iscrowd" not in obj or obj["iscrowd"] == 0:
+ classes.append(obj["category_id"])
+ area.append(obj["area"])
+ boxes.append(obj["bbox"])
+ if "keypoints" in obj:
+ keypoints.append(obj["keypoints"])
+
+ classes = torch.as_tensor(classes, dtype=torch.int64, device=image.device)
+ area = torch.as_tensor(area, dtype=torch.float32, device=image.device)
+ iscrowd = torch.zeros_like(classes, dtype=torch.int64, device=image.device)
+ # guard against no boxes via resizing
+ boxes = torch.as_tensor(boxes, dtype=torch.float32, device=image.device).reshape(-1, 4)
+ boxes[:, 2:] += boxes[:, :2]
+ boxes[:, 0::2] = boxes[:, 0::2].clip(min=0, max=image_width)
+ boxes[:, 1::2] = boxes[:, 1::2].clip(min=0, max=image_height)
+
+ keep = (boxes[:, 3] > boxes[:, 1]) & (boxes[:, 2] > boxes[:, 0])
+
+ new_target = {
+ "image_id": image_id,
+ "class_labels": classes[keep],
+ "boxes": boxes[keep],
+ "area": area[keep],
+ "iscrowd": iscrowd[keep],
+ "orig_size": torch.as_tensor([int(image_height), int(image_width)], dtype=torch.int64, device=image.device),
+ }
+
+ if keypoints:
+ keypoints = torch.as_tensor(keypoints, dtype=torch.float32, device=image.device)
+ # Apply the keep mask here to filter the relevant annotations
+ keypoints = keypoints[keep]
+ num_keypoints = keypoints.shape[0]
+ keypoints = keypoints.reshape((-1, 3)) if num_keypoints else keypoints
+ new_target["keypoints"] = keypoints
+
+ if return_segmentation_masks:
+ segmentation_masks = [obj["segmentation"] for obj in annotations]
+ masks = convert_coco_poly_to_mask(segmentation_masks, image_height, image_width, device=image.device)
+ new_target["masks"] = masks[keep]
+
+ return new_target
+
+
+def masks_to_boxes(masks: torch.Tensor) -> torch.Tensor:
+ """
+ Compute the bounding boxes around the provided panoptic segmentation masks.
+
+ Args:
+ masks: masks in format `[number_masks, height, width]` where N is the number of masks
+
+ Returns:
+ boxes: bounding boxes in format `[number_masks, 4]` in xyxy format
+ """
+ if masks.numel() == 0:
+ return torch.zeros((0, 4), device=masks.device)
+
+ h, w = masks.shape[-2:]
+ y = torch.arange(0, h, dtype=torch.float32, device=masks.device)
+ x = torch.arange(0, w, dtype=torch.float32, device=masks.device)
+ # see https://github.com/pytorch/pytorch/issues/50276
+ y, x = torch.meshgrid(y, x, indexing="ij")
+
+ x_mask = masks * torch.unsqueeze(x, 0)
+ x_max = x_mask.view(x_mask.shape[0], -1).max(-1)[0]
+ x_min = (
+ torch.where(masks, x.unsqueeze(0), torch.tensor(1e8, device=masks.device)).view(masks.shape[0], -1).min(-1)[0]
+ )
+
+ y_mask = masks * torch.unsqueeze(y, 0)
+ y_max = y_mask.view(y_mask.shape[0], -1).max(-1)[0]
+ y_min = (
+ torch.where(masks, y.unsqueeze(0), torch.tensor(1e8, device=masks.device)).view(masks.shape[0], -1).min(-1)[0]
+ )
+
+ return torch.stack([x_min, y_min, x_max, y_max], 1)
+
+
+# 2 functions below adapted from https://github.com/cocodataset/panopticapi/blob/master/panopticapi/utils.py
+# Copyright (c) 2018, Alexander Kirillov
+# All rights reserved.
+def rgb_to_id(color):
+ """
+ Converts RGB color to unique ID.
+ """
+ if isinstance(color, torch.Tensor) and len(color.shape) == 3:
+ if color.dtype == torch.uint8:
+ color = color.to(torch.int32)
+ return color[:, :, 0] + 256 * color[:, :, 1] + 256 * 256 * color[:, :, 2]
+ return int(color[0] + 256 * color[1] + 256 * 256 * color[2])
+
+
+def prepare_coco_panoptic_annotation(
+ image: torch.Tensor,
+ target: dict,
+ masks_path: str | pathlib.Path,
+ return_masks: bool = True,
+ input_data_format: ChannelDimension | str = None,
+) -> dict:
+ """
+ Prepare a coco panoptic annotation for YOLOS.
+ """
+ image_height, image_width = get_image_size(image, channel_dim=input_data_format)
+ annotation_path = pathlib.Path(masks_path) / target["file_name"]
+
+ new_target = {}
+ new_target["image_id"] = torch.as_tensor(
+ [target["image_id"] if "image_id" in target else target["id"]], dtype=torch.int64, device=image.device
+ )
+ new_target["size"] = torch.as_tensor([image_height, image_width], dtype=torch.int64, device=image.device)
+ new_target["orig_size"] = torch.as_tensor([image_height, image_width], dtype=torch.int64, device=image.device)
+
+ if "segments_info" in target:
+ masks = read_image(annotation_path).permute(1, 2, 0).to(dtype=torch.int32, device=image.device)
+ masks = rgb_to_id(masks)
+
+ ids = torch.as_tensor([segment_info["id"] for segment_info in target["segments_info"]], device=image.device)
+ masks = masks == ids[:, None, None]
+ masks = masks.to(torch.bool)
+ if return_masks:
+ new_target["masks"] = masks
+ new_target["boxes"] = masks_to_boxes(masks)
+ new_target["class_labels"] = torch.as_tensor(
+ [segment_info["category_id"] for segment_info in target["segments_info"]],
+ dtype=torch.int64,
+ device=image.device,
+ )
+ new_target["iscrowd"] = torch.as_tensor(
+ [segment_info["iscrowd"] for segment_info in target["segments_info"]],
+ dtype=torch.int64,
+ device=image.device,
+ )
+ new_target["area"] = torch.as_tensor(
+ [segment_info["area"] for segment_info in target["segments_info"]],
+ dtype=torch.float32,
+ device=image.device,
+ )
+
+ return new_target
+
+
+def get_size_with_aspect_ratio_yolos(
+ image_size: tuple[int, int], size: int, max_size: int | None = None, mod_size: int = 16
+) -> tuple[int, int]:
+ """
+ Computes the output image size given the input image size and the desired output size, while ensuring that both
+ height and width are multiples of `mod_size`.
+
+ This mirrors the YOLOS-specific behavior used in the torch/fast backends and is required so that all YOLOS
+ image processing backends (PIL, torchvision, fast) produce identical output shapes.
+ """
+ height, width = image_size
+ raw_size = None
+ if max_size is not None:
+ min_original_size = float(min((height, width)))
+ max_original_size = float(max((height, width)))
+ if max_original_size / min_original_size * size > max_size:
+ raw_size = max_size * min_original_size / max_original_size
+ size = int(round(raw_size))
+
+ if width < height:
+ ow = size
+ if max_size is not None and raw_size is not None:
+ oh = int(raw_size * height / width)
+ else:
+ oh = int(size * height / width)
+ elif (height <= width and height == size) or (width <= height and width == size):
+ oh, ow = height, width
+ else:
+ oh = size
+ if max_size is not None and raw_size is not None:
+ ow = int(raw_size * width / height)
+ else:
+ ow = int(size * width / height)
+
+ if mod_size is not None:
+ ow = ow - (ow % mod_size)
+ oh = oh - (oh % mod_size)
+
+ return (oh, ow)
+
+
+@auto_docstring
+class YolosImageProcessor(TorchvisionBackend):
+ valid_kwargs = YolosImageProcessorKwargs
+ resample = PILImageResampling.BILINEAR
+ image_mean = IMAGENET_DEFAULT_MEAN
+ image_std = IMAGENET_DEFAULT_STD
+ format = AnnotationFormat.COCO_DETECTION
+ do_resize = True
+ do_rescale = True
+ do_normalize = True
+ do_pad = True
+ size = {"shortest_edge": 800, "longest_edge": 1333}
+ default_to_square = False
+ model_input_names = ["pixel_values", "pixel_mask"]
+
+ def __init__(self, **kwargs: Unpack[YolosImageProcessorKwargs]) -> None:
+ kwargs.setdefault("do_pad", kwargs.pop("pad_and_return_pixel_mask", self.do_pad))
+
+ size = kwargs.pop("size", None)
+ max_size = None if size is None else kwargs.pop("max_size", 1333)
+ size = size if size is not None else {"shortest_edge": 800, "longest_edge": 1333}
+ # Convert size dict for backwards compat with max_size parameter
+ kwargs["size"] = get_size_dict(size, max_size=max_size, default_to_square=False)
+
+ # Backwards compatibility
+ do_convert_annotations = kwargs.get("do_convert_annotations")
+ do_normalize = kwargs.get("do_normalize")
+ if do_convert_annotations is None and getattr(self, "do_convert_annotations", None) is None:
+ self.do_convert_annotations = do_normalize if do_normalize is not None else self.do_normalize
+
+ super().__init__(**kwargs)
+
+ def prepare_annotation(
+ self,
+ image: torch.Tensor,
+ target: dict,
+ format: AnnotationFormat | None = None,
+ return_segmentation_masks: bool | None = None,
+ masks_path: str | pathlib.Path | None = None,
+ input_data_format: str | ChannelDimension | None = None,
+ ) -> dict:
+ """
+ Prepare an annotation for feeding into YOLOS model.
+ """
+ format = format if format is not None else self.format
+
+ if format == AnnotationFormat.COCO_DETECTION:
+ return_segmentation_masks = False if return_segmentation_masks is None else return_segmentation_masks
+ target = prepare_coco_detection_annotation(
+ image, target, return_segmentation_masks, input_data_format=input_data_format
+ )
+ elif format == AnnotationFormat.COCO_PANOPTIC:
+ return_segmentation_masks = True if return_segmentation_masks is None else return_segmentation_masks
+ target = prepare_coco_panoptic_annotation(
+ image,
+ target,
+ masks_path=masks_path,
+ return_masks=return_segmentation_masks,
+ input_data_format=input_data_format,
+ )
+ else:
+ raise ValueError(f"Format {format} is not supported.")
+ return target
+
+ def resize(
+ self,
+ image: torch.Tensor,
+ size: SizeDict,
+ resample: Optional["PILImageResampling | tvF.InterpolationMode | int"] = None,
+ **kwargs,
+ ) -> torch.Tensor:
+ """
+ Resize the image to the given size. Size can be `min_size` (scalar) or `(height, width)` tuple. If size is an
+ int, smaller edge of the image will be matched to this number.
+
+ Args:
+ image (`torch.Tensor`):
+ Image to resize.
+ size (`SizeDict`):
+ Size of the image's `(height, width)` dimensions after resizing. Available options are:
+ - `{"height": int, "width": int}`: The image will be resized to the exact size `(height, width)`.
+ Do NOT keep the aspect ratio.
+ - `{"shortest_edge": int, "longest_edge": int}`: The image will be resized to a maximum size respecting
+ the aspect ratio and keeping the shortest edge less or equal to `shortest_edge` and the longest edge
+ less or equal to `longest_edge`.
+ - `{"max_height": int, "max_width": int}`: The image will be resized to the maximum size respecting the
+ aspect ratio and keeping the height less or equal to `max_height` and the width less or equal to
+ `max_width`.
+ resample (`PILImageResampling | tvF.InterpolationMode | int`, *optional*, defaults to `PILImageResampling.BILINEAR`):
+ Resampling filter to use if resizing the image.
+ """
+ if size.shortest_edge and size.longest_edge:
+ # Resize the image so that the shortest edge or the longest edge is of the given size
+ # while maintaining the aspect ratio of the original image.
+ new_size = get_size_with_aspect_ratio_yolos(image.shape[-2:], size.shortest_edge, size.longest_edge)
+ elif size.max_height and size.max_width:
+ new_size = get_image_size_for_max_height_width(image.shape[-2:], size.max_height, size.max_width)
+ elif size.height and size.width:
+ new_size = (size.height, size.width)
+ else:
+ raise ValueError(
+ f"Size must contain 'height' and 'width' keys or 'shortest_edge' and 'longest_edge' keys. Got {size}."
+ )
+
+ image = super().resize(
+ image, size=SizeDict(height=new_size[0], width=new_size[1]), resample=resample, **kwargs
+ )
+ return image
+
+ def resize_annotation(
+ self,
+ annotation: dict[str, Any],
+ orig_size: tuple[int, int],
+ target_size: tuple[int, int],
+ threshold: float = 0.5,
+ resample: Optional["PILImageResampling | tvF.InterpolationMode | int"] = PILImageResampling.NEAREST,
+ ):
+ """
+ Resizes an annotation to a target size.
+
+ Args:
+ annotation (`dict[str, Any]`):
+ The annotation dictionary.
+ orig_size (`tuple[int, int]`):
+ The original size of the input image.
+ target_size (`tuple[int, int]`):
+ The target size of the image, as returned by the preprocessing `resize` step.
+ threshold (`float`, *optional*, defaults to 0.5):
+ The threshold used to binarize the segmentation masks.
+ resample (`PILImageResampling | tvF.InterpolationMode | int`, defaults to `tvF.InterpolationMode.NEAREST_EXACT`):
+ The resampling filter to use when resizing the masks.
+ """
+ ratio_height, ratio_width = [target / orig for target, orig in zip(target_size, orig_size)]
+
+ new_annotation = {}
+ new_annotation["size"] = target_size
+
+ for key, value in annotation.items():
+ if key == "boxes":
+ boxes = value
+ scaled_boxes = boxes * torch.as_tensor(
+ [ratio_width, ratio_height, ratio_width, ratio_height], dtype=torch.float32, device=boxes.device
+ )
+ new_annotation["boxes"] = scaled_boxes
+ elif key == "area":
+ area = value
+ scaled_area = area * (ratio_width * ratio_height)
+ new_annotation["area"] = scaled_area
+ elif key == "masks":
+ masks = value[:, None]
+ masks = [
+ super(YolosImageProcessor, self).resize(
+ mask, size=SizeDict(height=target_size[0], width=target_size[1]), resample=resample
+ )
+ for mask in masks
+ ]
+ masks = torch.stack(masks).to(torch.float32)
+ masks = masks[:, 0] > threshold
+ new_annotation["masks"] = masks
+ elif key == "size":
+ new_annotation["size"] = target_size
+ else:
+ new_annotation[key] = value
+
+ return new_annotation
+
+ def normalize_annotation(self, annotation: dict, image_size: tuple[int, int]) -> dict:
+ image_height, image_width = image_size
+ norm_annotation = {}
+ for key, value in annotation.items():
+ if key == "boxes":
+ boxes = value
+ boxes = corners_to_center_format(boxes)
+ boxes /= torch.as_tensor(
+ [image_width, image_height, image_width, image_height], dtype=torch.float32, device=boxes.device
+ )
+ norm_annotation[key] = boxes
+ else:
+ norm_annotation[key] = value
+ return norm_annotation
+
+ def _update_annotation_for_padded_image(
+ self,
+ annotation: dict,
+ input_image_size: tuple[int, int],
+ output_image_size: tuple[int, int],
+ padding,
+ update_bboxes,
+ ) -> dict:
+ """
+ Update the annotation for a padded image.
+ """
+ new_annotation = {}
+ new_annotation["size"] = output_image_size
+ ratio_height, ratio_width = (input / output for output, input in zip(output_image_size, input_image_size))
+
+ for key, value in annotation.items():
+ if key == "masks":
+ masks = value
+ masks = tvF.pad(
+ masks,
+ padding,
+ fill=0,
+ )
+ masks = safe_squeeze(masks, 1)
+ new_annotation["masks"] = masks
+ elif key == "boxes" and update_bboxes:
+ boxes = value
+ boxes *= torch.as_tensor([ratio_width, ratio_height, ratio_width, ratio_height], device=boxes.device)
+ new_annotation["boxes"] = boxes
+ elif key == "size":
+ new_annotation["size"] = output_image_size
+ else:
+ new_annotation[key] = value
+ return new_annotation
+
+ def pad(
+ self,
+ image: torch.Tensor,
+ padded_size: tuple[int, int],
+ annotation: dict[str, Any] | None = None,
+ update_bboxes: bool = True,
+ fill: int = 0,
+ ):
+ original_size = image.size()[-2:]
+ padding_bottom = padded_size[0] - original_size[0]
+ padding_right = padded_size[1] - original_size[1]
+ if padding_bottom < 0 or padding_right < 0:
+ raise ValueError(
+ f"Padding dimensions are negative. Please make sure that the padded size is larger than the "
+ f"original size. Got padded size: {padded_size}, original size: {original_size}."
+ )
+ if original_size != padded_size:
+ padding = [0, 0, padding_right, padding_bottom]
+ image = tvF.pad(image, padding, fill=fill)
+ if annotation is not None:
+ annotation = self._update_annotation_for_padded_image(
+ annotation, original_size, padded_size, padding, update_bboxes
+ )
+
+ # Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding.
+ pixel_mask = torch.zeros(padded_size, dtype=torch.int64, device=image.device)
+ pixel_mask[: original_size[0], : original_size[1]] = 1
+
+ return image, pixel_mask, annotation
+
+ @auto_docstring
+ def preprocess(
+ self,
+ images: ImageInput,
+ annotations: AnnotationType | list[AnnotationType] | None = None,
+ return_segmentation_masks: bool | None = None,
+ masks_path: str | pathlib.Path | None = None,
+ **kwargs: Unpack[YolosImageProcessorKwargs],
+ ) -> BatchFeature:
+ r"""
+ annotations (`AnnotationType` or `list[AnnotationType]`, *optional*):
+ Annotations to transform according to the padding that is applied to the images.
+ return_segmentation_masks (`bool`, *optional*, defaults to `self.return_segmentation_masks`):
+ Whether to return segmentation masks.
+ masks_path (`str` or `pathlib.Path`, *optional*):
+ Path to the directory containing the segmentation masks.
+ """
+ return super().preprocess(images, annotations, return_segmentation_masks, masks_path, **kwargs)
+
+ def _preprocess(
+ self,
+ images: list["torch.Tensor"],
+ annotations: AnnotationType | list[AnnotationType] | None,
+ return_segmentation_masks: bool,
+ masks_path: str | pathlib.Path | None,
+ do_resize: bool,
+ size: SizeDict,
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None",
+ do_rescale: bool,
+ rescale_factor: float,
+ do_normalize: bool,
+ do_convert_annotations: bool,
+ image_mean: float | list[float] | None,
+ image_std: float | list[float] | None,
+ do_pad: bool,
+ pad_size: SizeDict | None,
+ format: str | AnnotationFormat | None,
+ return_tensors: str | TensorType | None,
+ **kwargs,
+ ) -> BatchFeature:
+ """
+ Preprocess an image or a batch of images so that it can be used by the model.
+ """
+ if annotations is not None and isinstance(annotations, dict):
+ annotations = [annotations]
+
+ if annotations is not None and len(images) != len(annotations):
+ raise ValueError(
+ f"The number of images ({len(images)}) and annotations ({len(annotations)}) do not match."
+ )
+
+ format = AnnotationFormat(format)
+ if annotations is not None:
+ validate_annotations(format, SUPPORTED_ANNOTATION_FORMATS, annotations)
+
+ if (
+ masks_path is not None
+ and format == AnnotationFormat.COCO_PANOPTIC
+ and not isinstance(masks_path, (pathlib.Path, str))
+ ):
+ raise ValueError(
+ "The path to the directory containing the mask PNG files should be provided as a"
+ f" `pathlib.Path` or string object, but is {type(masks_path)} instead."
+ )
+
+ data = {}
+
+ processed_images = []
+ processed_annotations = []
+ pixel_masks = [] # Initialize pixel_masks here
+ for image, annotation in zip(images, annotations if annotations is not None else [None] * len(images)):
+ # prepare (COCO annotations as a list of Dict -> YOLOS target as a single Dict per image)
+ if annotations is not None:
+ annotation = self.prepare_annotation(
+ image,
+ annotation,
+ format,
+ return_segmentation_masks=return_segmentation_masks,
+ masks_path=masks_path,
+ input_data_format=ChannelDimension.FIRST,
+ )
+
+ if do_resize:
+ resized_image = self.resize(image, size=size, resample=resample)
+ if annotations is not None:
+ annotation = self.resize_annotation(
+ annotation,
+ orig_size=image.size()[-2:],
+ target_size=resized_image.size()[-2:],
+ )
+ image = resized_image
+ # Fused rescale and normalize
+ image = self.rescale_and_normalize(image, do_rescale, rescale_factor, do_normalize, image_mean, image_std)
+ if do_convert_annotations and annotations is not None:
+ annotation = self.normalize_annotation(annotation, get_image_size(image, ChannelDimension.FIRST))
+
+ processed_images.append(image)
+ processed_annotations.append(annotation)
+ images = processed_images
+ annotations = processed_annotations if annotations is not None else None
+
+ if do_pad:
+ # depends on all resized image shapes so we need another loop
+ if pad_size is not None:
+ padded_size = (pad_size.height, pad_size.width)
+ else:
+ padded_size = get_max_height_width(images)
+
+ padded_images = []
+ padded_annotations = []
+ for image, annotation in zip(images, annotations if annotations is not None else [None] * len(images)):
+ # Pads images and returns their mask: {'pixel_values': ..., 'pixel_mask': ...}
+ if padded_size == image.size()[-2:]:
+ padded_images.append(image)
+ pixel_masks.append(torch.ones(padded_size, dtype=torch.int64, device=image.device))
+ padded_annotations.append(annotation)
+ continue
+ image, pixel_mask, annotation = self.pad(
+ image, padded_size, annotation=annotation, update_bboxes=do_convert_annotations
+ )
+ padded_images.append(image)
+ padded_annotations.append(annotation)
+ pixel_masks.append(pixel_mask)
+ images = padded_images
+ annotations = padded_annotations if annotations is not None else None
+ data.update({"pixel_mask": torch.stack(pixel_masks, dim=0)})
+
+ data.update({"pixel_values": torch.stack(images, dim=0)})
+ encoded_inputs = BatchFeature(data, tensor_type=return_tensors)
+ if annotations is not None:
+ encoded_inputs["labels"] = [
+ BatchFeature(annotation, tensor_type=return_tensors) for annotation in annotations
+ ]
+ return encoded_inputs
+
+ def post_process_object_detection(
+ self, outputs, threshold: float = 0.5, target_sizes: TensorType | list[tuple] = None
+ ):
+ """
+ Converts the raw output of [`YolosForObjectDetection`] into final bounding boxes in (top_left_x, top_left_y,
+ bottom_right_x, bottom_right_y) format. Only supports PyTorch.
+
+ Args:
+ outputs ([`YolosObjectDetectionOutput`]):
+ Raw outputs of the model.
+ threshold (`float`, *optional*):
+ Score threshold to keep object detection predictions.
+ target_sizes (`torch.Tensor` or `list[tuple[int, int]]`, *optional*):
+ Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the target size
+ `(height, width)` of each image in the batch. If unset, predictions will not be resized.
+ Returns:
+ `list[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
+ in the batch as predicted by the model.
+ """
+ out_logits, out_bbox = outputs.logits, outputs.pred_boxes
+
+ if target_sizes is not None:
+ if len(out_logits) != len(target_sizes):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
+ )
+
+ prob = nn.functional.softmax(out_logits, -1)
+ scores, labels = prob[..., :-1].max(-1)
+
+ # Convert to [x0, y0, x1, y1] format
+ boxes = center_to_corners_format(out_bbox)
+
+ # Convert from relative [0, 1] to absolute [0, height] coordinates
+ if target_sizes is not None:
+ if isinstance(target_sizes, list):
+ img_h = torch.Tensor([i[0] for i in target_sizes])
+ img_w = torch.Tensor([i[1] for i in target_sizes])
+ else:
+ img_h, img_w = target_sizes.unbind(1)
+
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1).to(boxes.device)
+ boxes = boxes * scale_fct[:, None, :]
+
+ results = []
+ for s, l, b in zip(scores, labels, boxes):
+ score = s[s > threshold]
+ label = l[s > threshold]
+ box = b[s > threshold]
+ results.append({"scores": score, "labels": label, "boxes": box})
+
+ return results
+
+
+__all__ = ["YolosImageProcessor"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/yolos/modeling_yolos.py b/.venv/lib/python3.12/site-packages/transformers/models/yolos/modeling_yolos.py
new file mode 100644
index 0000000000000000000000000000000000000000..7afb818322b6219114029623e73755d8638bf9f9
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/yolos/modeling_yolos.py
@@ -0,0 +1,655 @@
+# Copyright 2022 School of EIC, Huazhong University of Science & Technology and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch YOLOS model."""
+
+import collections.abc
+from collections.abc import Callable
+from dataclasses import dataclass
+
+import torch
+from torch import nn
+
+from ...activations import ACT2FN
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import ModelOutput, TransformersKwargs, auto_docstring, logging
+from ...utils.generic import can_return_tuple, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_yolos import YolosConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(
+ custom_intro="""
+ Output type of [`YolosForObjectDetection`].
+ """
+)
+@dataclass
+class YolosObjectDetectionOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` are provided)):
+ Total loss as a linear combination of a negative log-likehood (cross-entropy) for class prediction and a
+ bounding box loss. The latter is defined as a linear combination of the L1 loss and the generalized
+ scale-invariant IoU loss.
+ loss_dict (`Dict`, *optional*):
+ A dictionary containing the individual losses. Useful for logging.
+ logits (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes + 1)`):
+ Classification logits (including no-object) for all queries.
+ pred_boxes (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
+ Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These
+ values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding
+ possible padding). You can use [`~YolosImageProcessor.post_process`] to retrieve the unnormalized bounding
+ boxes.
+ auxiliary_outputs (`list[Dict]`, *optional*):
+ Optional, only returned when auxiliary losses are activated (i.e. `config.auxiliary_loss` is set to `True`)
+ and labels are provided. It is a list of dictionaries containing the two above keys (`logits` and
+ `pred_boxes`) for each decoder layer.
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the decoder of the model.
+ """
+
+ loss: torch.FloatTensor | None = None
+ loss_dict: dict | None = None
+ logits: torch.FloatTensor | None = None
+ pred_boxes: torch.FloatTensor | None = None
+ auxiliary_outputs: list[dict] | None = None
+ last_hidden_state: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+
+
+class YolosEmbeddings(nn.Module):
+ """
+ Construct the CLS token, detection tokens, position and patch embeddings.
+
+ """
+
+ def __init__(self, config: YolosConfig) -> None:
+ super().__init__()
+
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
+ self.detection_tokens = nn.Parameter(torch.zeros(1, config.num_detection_tokens, config.hidden_size))
+ self.patch_embeddings = YolosPatchEmbeddings(config)
+ num_patches = self.patch_embeddings.num_patches
+ self.position_embeddings = nn.Parameter(
+ torch.zeros(1, num_patches + config.num_detection_tokens + 1, config.hidden_size)
+ )
+
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.interpolation = InterpolateInitialPositionEmbeddings(config)
+ self.config = config
+
+ def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
+ batch_size, num_channels, height, width = pixel_values.shape
+ embeddings = self.patch_embeddings(pixel_values)
+
+ batch_size, seq_len, _ = embeddings.size()
+
+ # add the [CLS] and detection tokens to the embedded patch tokens
+ cls_tokens = self.cls_token.expand(batch_size, -1, -1)
+ detection_tokens = self.detection_tokens.expand(batch_size, -1, -1)
+ embeddings = torch.cat((cls_tokens, embeddings, detection_tokens), dim=1)
+
+ # add positional encoding to each token
+ # this might require interpolation of the existing position embeddings
+ position_embeddings = self.interpolation(self.position_embeddings, (height, width))
+
+ embeddings = embeddings + position_embeddings
+ embeddings = self.dropout(embeddings)
+
+ return embeddings
+
+
+class InterpolateInitialPositionEmbeddings(nn.Module):
+ def __init__(self, config) -> None:
+ super().__init__()
+ self.config = config
+
+ def forward(self, pos_embed, img_size=(800, 1344)) -> torch.Tensor:
+ cls_pos_embed = pos_embed[:, 0, :]
+ cls_pos_embed = cls_pos_embed[:, None]
+ det_pos_embed = pos_embed[:, -self.config.num_detection_tokens :, :]
+ patch_pos_embed = pos_embed[:, 1 : -self.config.num_detection_tokens, :]
+ patch_pos_embed = patch_pos_embed.transpose(1, 2)
+ batch_size, hidden_size, seq_len = patch_pos_embed.shape
+
+ patch_height, patch_width = (
+ self.config.image_size[0] // self.config.patch_size,
+ self.config.image_size[1] // self.config.patch_size,
+ )
+ patch_pos_embed = patch_pos_embed.view(batch_size, hidden_size, patch_height, patch_width)
+
+ height, width = img_size
+ new_patch_height, new_patch_width = height // self.config.patch_size, width // self.config.patch_size
+ patch_pos_embed = nn.functional.interpolate(
+ patch_pos_embed, size=(new_patch_height, new_patch_width), mode="bicubic", align_corners=False
+ )
+ patch_pos_embed = patch_pos_embed.flatten(2).transpose(1, 2)
+ scale_pos_embed = torch.cat((cls_pos_embed, patch_pos_embed, det_pos_embed), dim=1)
+ return scale_pos_embed
+
+
+class InterpolateMidPositionEmbeddings(nn.Module):
+ def __init__(self, config) -> None:
+ super().__init__()
+ self.config = config
+
+ def forward(self, pos_embed, img_size=(800, 1344)) -> torch.Tensor:
+ cls_pos_embed = pos_embed[:, :, 0, :]
+ cls_pos_embed = cls_pos_embed[:, None]
+ det_pos_embed = pos_embed[:, :, -self.config.num_detection_tokens :, :]
+ patch_pos_embed = pos_embed[:, :, 1 : -self.config.num_detection_tokens, :]
+ patch_pos_embed = patch_pos_embed.transpose(2, 3)
+ depth, batch_size, hidden_size, seq_len = patch_pos_embed.shape
+
+ patch_height, patch_width = (
+ self.config.image_size[0] // self.config.patch_size,
+ self.config.image_size[1] // self.config.patch_size,
+ )
+ patch_pos_embed = patch_pos_embed.view(depth * batch_size, hidden_size, patch_height, patch_width)
+ height, width = img_size
+ new_patch_height, new_patch_width = height // self.config.patch_size, width // self.config.patch_size
+ patch_pos_embed = nn.functional.interpolate(
+ patch_pos_embed, size=(new_patch_height, new_patch_width), mode="bicubic", align_corners=False
+ )
+ patch_pos_embed = (
+ patch_pos_embed.flatten(2)
+ .transpose(1, 2)
+ .contiguous()
+ .view(depth, batch_size, new_patch_height * new_patch_width, hidden_size)
+ )
+ scale_pos_embed = torch.cat((cls_pos_embed, patch_pos_embed, det_pos_embed), dim=2)
+ return scale_pos_embed
+
+
+class YolosPatchEmbeddings(nn.Module):
+ """
+ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
+ `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
+ Transformer.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ image_size, patch_size = config.image_size, config.patch_size
+ num_channels, hidden_size = config.num_channels, config.hidden_size
+
+ image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
+ self.image_size = image_size
+ self.patch_size = patch_size
+ self.num_channels = num_channels
+ self.num_patches = num_patches
+
+ self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
+
+ def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
+ batch_size, num_channels, height, width = pixel_values.shape
+ if num_channels != self.num_channels:
+ raise ValueError(
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
+ )
+
+ embeddings = self.projection(pixel_values).flatten(2).transpose(1, 2)
+ return embeddings
+
+
+# Copied from transformers.models.bert.modeling_bert.eager_attention_forward
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float | None = None,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ if scaling is None:
+ scaling = query.size(-1) ** -0.5
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
+
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.vit.modeling_vit.ViTAttention with ViT->Yolos
+class YolosSelfAttention(nn.Module):
+ def __init__(self, config: YolosConfig):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size {config.hidden_size} is not a multiple of the number of attention "
+ f"heads {config.num_attention_heads}."
+ )
+
+ self.config = config
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+ self.dropout_prob = config.attention_probs_dropout_prob
+ self.scaling = self.attention_head_size**-0.5
+ self.is_causal = False
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ batch_size = hidden_states.shape[0]
+ new_shape = batch_size, -1, self.num_attention_heads, self.attention_head_size
+
+ key_layer = self.key(hidden_states).view(*new_shape).transpose(1, 2)
+ value_layer = self.value(hidden_states).view(*new_shape).transpose(1, 2)
+ query_layer = self.query(hidden_states).view(*new_shape).transpose(1, 2)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ context_layer, attention_probs = attention_interface(
+ self,
+ query_layer,
+ key_layer,
+ value_layer,
+ None,
+ is_causal=self.is_causal,
+ scaling=self.scaling,
+ dropout=0.0 if not self.training else self.dropout_prob,
+ **kwargs,
+ )
+
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.reshape(new_context_layer_shape)
+
+ return context_layer, attention_probs
+
+
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.vit.modeling_vit.ViTAttention with ViT->Yolos
+class YolosSelfOutput(nn.Module):
+ """
+ The residual connection is defined in YolosLayer instead of here (as is the case with other models), due to the
+ layernorm applied before each block.
+ """
+
+ def __init__(self, config: YolosConfig):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ return hidden_states
+
+
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.vit.modeling_vit.ViTAttention with ViT->Yolos
+class YolosAttention(nn.Module):
+ def __init__(self, config: YolosConfig):
+ super().__init__()
+ self.attention = YolosSelfAttention(config)
+ self.output = YolosSelfOutput(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ self_attn_output, _ = self.attention(hidden_states, **kwargs)
+ output = self.output(self_attn_output, hidden_states)
+ return output
+
+
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.vit.modeling_vit.ViTMLP with ViT->Yolos
+class YolosIntermediate(nn.Module):
+ def __init__(self, config: YolosConfig):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ return hidden_states
+
+
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.vit.modeling_vit.ViTMLP with ViT->Yolos
+class YolosOutput(nn.Module):
+ def __init__(self, config: YolosConfig):
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = hidden_states + input_tensor
+ return hidden_states
+
+
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.vit.modeling_vit.ViTLayer with ViT->Yolos,VIT->YOLOS
+class YolosLayer(GradientCheckpointingLayer):
+ """This corresponds to the Block class in the timm implementation."""
+
+ def __init__(self, config: YolosConfig):
+ super().__init__()
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+ self.attention = YolosAttention(config)
+ self.intermediate = YolosIntermediate(config)
+ self.output = YolosOutput(config)
+ self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ hidden_states_norm = self.layernorm_before(hidden_states)
+ attention_output = self.attention(hidden_states_norm, **kwargs)
+
+ # first residual connection
+ hidden_states = attention_output + hidden_states
+
+ # in Yolos, layernorm is also applied after self-attention
+ layer_output = self.layernorm_after(hidden_states)
+ layer_output = self.intermediate(layer_output)
+
+ # second residual connection is done here
+ layer_output = self.output(layer_output, hidden_states)
+
+ return layer_output
+
+
+class YolosEncoder(nn.Module):
+ def __init__(self, config: YolosConfig) -> None:
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList([YolosLayer(config) for _ in range(config.num_hidden_layers)])
+ self.gradient_checkpointing = False
+
+ seq_length = (
+ 1 + (config.image_size[0] * config.image_size[1] // config.patch_size**2) + config.num_detection_tokens
+ )
+ self.mid_position_embeddings = (
+ nn.Parameter(
+ torch.zeros(
+ config.num_hidden_layers - 1,
+ 1,
+ seq_length,
+ config.hidden_size,
+ )
+ )
+ if config.use_mid_position_embeddings
+ else None
+ )
+
+ self.interpolation = InterpolateMidPositionEmbeddings(config) if config.use_mid_position_embeddings else None
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ height: int,
+ width: int,
+ ) -> BaseModelOutput:
+ if self.config.use_mid_position_embeddings:
+ interpolated_mid_position_embeddings = self.interpolation(self.mid_position_embeddings, (height, width))
+
+ for i, layer_module in enumerate(self.layer):
+ hidden_states = layer_module(hidden_states)
+
+ if self.config.use_mid_position_embeddings:
+ if i < (self.config.num_hidden_layers - 1):
+ hidden_states = hidden_states + interpolated_mid_position_embeddings[i]
+
+ return BaseModelOutput(last_hidden_state=hidden_states)
+
+
+@auto_docstring
+class YolosPreTrainedModel(PreTrainedModel):
+ config: YolosConfig
+ base_model_prefix = "vit"
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+ supports_gradient_checkpointing = True
+ _no_split_modules = []
+ _supports_sdpa = True
+ _supports_flash_attn = True
+ _supports_flex_attn = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": YolosLayer,
+ "attentions": YolosSelfAttention,
+ }
+
+
+@auto_docstring
+class YolosModel(YolosPreTrainedModel):
+ def __init__(self, config: YolosConfig, add_pooling_layer: bool = True):
+ r"""
+ add_pooling_layer (bool, *optional*, defaults to `True`):
+ Whether to add a pooling layer
+ """
+ super().__init__(config)
+ self.config = config
+
+ self.embeddings = YolosEmbeddings(config)
+ self.encoder = YolosEncoder(config)
+
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.pooler = YolosPooler(config) if add_pooling_layer else None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self) -> YolosPatchEmbeddings:
+ return self.embeddings.patch_embeddings
+
+ @merge_with_config_defaults
+ @capture_outputs(tie_last_hidden_states=False)
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutputWithPooling:
+ if pixel_values is None:
+ raise ValueError("You have to specify pixel_values")
+
+ embedding_output = self.embeddings(pixel_values)
+
+ height, width = pixel_values.shape[-2:]
+ encoder_outputs: BaseModelOutput = self.encoder(embedding_output, height=height, width=width)
+ sequence_output = encoder_outputs.last_hidden_state
+ sequence_output = self.layernorm(sequence_output)
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
+
+ return BaseModelOutputWithPooling(last_hidden_state=sequence_output, pooler_output=pooled_output)
+
+
+class YolosPooler(nn.Module):
+ def __init__(self, config: YolosConfig):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.activation = nn.Tanh()
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ # We "pool" the model by simply taking the hidden state corresponding
+ # to the first token.
+ first_token_tensor = hidden_states[:, 0]
+ pooled_output = self.dense(first_token_tensor)
+ pooled_output = self.activation(pooled_output)
+ return pooled_output
+
+
+# Copied from transformers.models.detr.modeling_detr.DetrMLPPredictionHead with Detr->Yolos
+class YolosMLPPredictionHead(nn.Module):
+ """
+ Very simple multi-layer perceptron (MLP, also called FFN), used to predict the normalized center coordinates,
+ height and width of a bounding box w.r.t. an image.
+
+ """
+
+ def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
+ super().__init__()
+ self.num_layers = num_layers
+ h = [hidden_dim] * (num_layers - 1)
+ self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
+
+ def forward(self, x):
+ for i, layer in enumerate(self.layers):
+ x = nn.functional.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
+ return x
+
+
+@auto_docstring(
+ custom_intro="""
+ YOLOS Model (consisting of a ViT encoder) with object detection heads on top, for tasks such as COCO detection.
+ """
+)
+class YolosForObjectDetection(YolosPreTrainedModel):
+ def __init__(self, config: YolosConfig):
+ super().__init__(config)
+
+ # YOLOS (ViT) encoder model
+ self.vit = YolosModel(config, add_pooling_layer=False)
+
+ # Object detection heads
+ # We add one for the "no object" class
+ self.class_labels_classifier = YolosMLPPredictionHead(
+ input_dim=config.hidden_size, hidden_dim=config.hidden_size, output_dim=config.num_labels + 1, num_layers=3
+ )
+ self.bbox_predictor = YolosMLPPredictionHead(
+ input_dim=config.hidden_size, hidden_dim=config.hidden_size, output_dim=4, num_layers=3
+ )
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ # taken from https://github.com/facebookresearch/detr/blob/master/models/detr.py
+ def _set_aux_loss(self, outputs_class, outputs_coord):
+ return [{"logits": a, "pred_boxes": b} for a, b in zip(outputs_class[:-1], outputs_coord[:-1])]
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ labels: list[dict] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> YolosObjectDetectionOutput:
+ r"""
+ labels (`list[Dict]` of len `(batch_size,)`, *optional*):
+ Labels for computing the bipartite matching loss. List of dicts, each dictionary containing at least the
+ following 2 keys: `'class_labels'` and `'boxes'` (the class labels and bounding boxes of an image in the
+ batch respectively). The class labels themselves should be a `torch.LongTensor` of len `(number of bounding
+ boxes in the image,)` and the boxes a `torch.FloatTensor` of shape `(number of bounding boxes in the image,
+ 4)`.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoImageProcessor, AutoModelForObjectDetection
+ >>> import torch
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> image_processor = AutoImageProcessor.from_pretrained("hustvl/yolos-tiny")
+ >>> model = AutoModelForObjectDetection.from_pretrained("hustvl/yolos-tiny")
+
+ >>> inputs = image_processor(images=image, return_tensors="pt")
+ >>> outputs = model(**inputs)
+
+ >>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
+ >>> target_sizes = torch.tensor([image.size[::-1]])
+ >>> results = image_processor.post_process_object_detection(outputs, threshold=0.9, target_sizes=target_sizes)[
+ ... 0
+ ... ]
+
+ >>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
+ ... box = [round(i, 2) for i in box.tolist()]
+ ... print(
+ ... f"Detected {model.config.id2label[label.item()]} with confidence "
+ ... f"{round(score.item(), 3)} at location {box}"
+ ... )
+ Detected remote with confidence 0.991 at location [46.48, 72.78, 178.98, 119.3]
+ Detected remote with confidence 0.908 at location [336.48, 79.27, 368.23, 192.36]
+ Detected cat with confidence 0.934 at location [337.18, 18.06, 638.14, 373.09]
+ Detected cat with confidence 0.979 at location [10.93, 53.74, 313.41, 470.67]
+ Detected remote with confidence 0.974 at location [41.63, 72.23, 178.09, 119.99]
+ ```"""
+
+ # First, sent images through YOLOS base model to obtain hidden states
+ outputs: BaseModelOutputWithPooling = self.vit(pixel_values, **kwargs)
+ sequence_output = outputs.last_hidden_state
+
+ # Take the final hidden states of the detection tokens
+ sequence_output = sequence_output[:, -self.config.num_detection_tokens :, :]
+
+ # Class logits + predicted bounding boxes
+ logits = self.class_labels_classifier(sequence_output)
+ pred_boxes = self.bbox_predictor(sequence_output).sigmoid()
+
+ loss, loss_dict, auxiliary_outputs = None, None, None
+ if labels is not None:
+ outputs_class, outputs_coord = None, None
+ if self.config.auxiliary_loss:
+ intermediate = outputs.hidden_states
+ outputs_class = self.class_labels_classifier(intermediate)
+ outputs_coord = self.bbox_predictor(intermediate).sigmoid()
+ loss, loss_dict, auxiliary_outputs = self.loss_function(
+ logits, labels, self.device, pred_boxes, self.config, outputs_class, outputs_coord
+ )
+
+ return YolosObjectDetectionOutput(
+ loss=loss,
+ loss_dict=loss_dict,
+ logits=logits,
+ pred_boxes=pred_boxes,
+ auxiliary_outputs=auxiliary_outputs,
+ last_hidden_state=outputs.last_hidden_state,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = ["YolosForObjectDetection", "YolosModel", "YolosPreTrainedModel"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/yolos/modular_yolos.py b/.venv/lib/python3.12/site-packages/transformers/models/yolos/modular_yolos.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ae8a90e6109a197a567b5bc56e90d7bfd18b6ad
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/yolos/modular_yolos.py
@@ -0,0 +1,288 @@
+from typing import Optional
+
+import numpy as np
+import torch
+from torch import nn
+from torchvision.transforms.v2 import functional as tvF
+
+from transformers.models.detr.image_processing_detr import DetrImageProcessor
+from transformers.models.detr.image_processing_pil_detr import DetrImageProcessorPil
+
+from ...image_transforms import center_to_corners_format
+from ...image_utils import PILImageResampling, SizeDict, get_image_size_for_max_height_width
+from ...utils import TensorType, logging, requires_backends
+
+
+logger = logging.get_logger(__name__)
+
+
+def get_size_with_aspect_ratio_yolos(
+ image_size: tuple[int, int], size: int, max_size: int | None = None, mod_size: int = 16
+) -> tuple[int, int]:
+ """
+ Computes the output image size given the input image size and the desired output size, while ensuring that both
+ height and width are multiples of `mod_size`.
+
+ This mirrors the YOLOS-specific behavior used in the torch/fast backends and is required so that all YOLOS
+ image processing backends (PIL, torchvision, fast) produce identical output shapes.
+ """
+ height, width = image_size
+ raw_size = None
+ if max_size is not None:
+ min_original_size = float(min((height, width)))
+ max_original_size = float(max((height, width)))
+ if max_original_size / min_original_size * size > max_size:
+ raw_size = max_size * min_original_size / max_original_size
+ size = int(round(raw_size))
+
+ if width < height:
+ ow = size
+ if max_size is not None and raw_size is not None:
+ oh = int(raw_size * height / width)
+ else:
+ oh = int(size * height / width)
+ elif (height <= width and height == size) or (width <= height and width == size):
+ oh, ow = height, width
+ else:
+ oh = size
+ if max_size is not None and raw_size is not None:
+ ow = int(raw_size * width / height)
+ else:
+ ow = int(size * width / height)
+
+ if mod_size is not None:
+ ow = ow - (ow % mod_size)
+ oh = oh - (oh % mod_size)
+
+ return (oh, ow)
+
+
+class YolosImageProcessor(DetrImageProcessor):
+ def resize(
+ self,
+ image: torch.Tensor,
+ size: SizeDict,
+ resample: Optional["PILImageResampling | tvF.InterpolationMode | int"] = None,
+ **kwargs,
+ ) -> torch.Tensor:
+ """
+ Resize the image to the given size. Size can be `min_size` (scalar) or `(height, width)` tuple. If size is an
+ int, smaller edge of the image will be matched to this number.
+
+ Args:
+ image (`torch.Tensor`):
+ Image to resize.
+ size (`SizeDict`):
+ Size of the image's `(height, width)` dimensions after resizing. Available options are:
+ - `{"height": int, "width": int}`: The image will be resized to the exact size `(height, width)`.
+ Do NOT keep the aspect ratio.
+ - `{"shortest_edge": int, "longest_edge": int}`: The image will be resized to a maximum size respecting
+ the aspect ratio and keeping the shortest edge less or equal to `shortest_edge` and the longest edge
+ less or equal to `longest_edge`.
+ - `{"max_height": int, "max_width": int}`: The image will be resized to the maximum size respecting the
+ aspect ratio and keeping the height less or equal to `max_height` and the width less or equal to
+ `max_width`.
+ resample (`PILImageResampling | tvF.InterpolationMode | int`, *optional*, defaults to `PILImageResampling.BILINEAR`):
+ Resampling filter to use if resizing the image.
+ """
+ if size.shortest_edge and size.longest_edge:
+ # Resize the image so that the shortest edge or the longest edge is of the given size
+ # while maintaining the aspect ratio of the original image.
+ new_size = get_size_with_aspect_ratio_yolos(image.shape[-2:], size.shortest_edge, size.longest_edge)
+ elif size.max_height and size.max_width:
+ new_size = get_image_size_for_max_height_width(image.shape[-2:], size.max_height, size.max_width)
+ elif size.height and size.width:
+ new_size = (size.height, size.width)
+ else:
+ raise ValueError(
+ f"Size must contain 'height' and 'width' keys or 'shortest_edge' and 'longest_edge' keys. Got {size}."
+ )
+
+ image = super().resize(
+ image, size=SizeDict(height=new_size[0], width=new_size[1]), resample=resample, **kwargs
+ )
+ return image
+
+ def post_process_object_detection(
+ self, outputs, threshold: float = 0.5, target_sizes: TensorType | list[tuple] = None
+ ):
+ """
+ Converts the raw output of [`YolosForObjectDetection`] into final bounding boxes in (top_left_x, top_left_y,
+ bottom_right_x, bottom_right_y) format. Only supports PyTorch.
+
+ Args:
+ outputs ([`YolosObjectDetectionOutput`]):
+ Raw outputs of the model.
+ threshold (`float`, *optional*):
+ Score threshold to keep object detection predictions.
+ target_sizes (`torch.Tensor` or `list[tuple[int, int]]`, *optional*):
+ Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the target size
+ `(height, width)` of each image in the batch. If unset, predictions will not be resized.
+ Returns:
+ `list[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
+ in the batch as predicted by the model.
+ """
+ out_logits, out_bbox = outputs.logits, outputs.pred_boxes
+
+ if target_sizes is not None:
+ if len(out_logits) != len(target_sizes):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
+ )
+
+ prob = nn.functional.softmax(out_logits, -1)
+ scores, labels = prob[..., :-1].max(-1)
+
+ # Convert to [x0, y0, x1, y1] format
+ boxes = center_to_corners_format(out_bbox)
+
+ # Convert from relative [0, 1] to absolute [0, height] coordinates
+ if target_sizes is not None:
+ if isinstance(target_sizes, list):
+ img_h = torch.Tensor([i[0] for i in target_sizes])
+ img_w = torch.Tensor([i[1] for i in target_sizes])
+ else:
+ img_h, img_w = target_sizes.unbind(1)
+
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1).to(boxes.device)
+ boxes = boxes * scale_fct[:, None, :]
+
+ results = []
+ for s, l, b in zip(scores, labels, boxes):
+ score = s[s > threshold]
+ label = l[s > threshold]
+ box = b[s > threshold]
+ results.append({"scores": score, "labels": label, "boxes": box})
+
+ return results
+
+ def post_process_instance_segmentation(self):
+ raise NotImplementedError("Segmentation post-processing is not implemented for Deformable DETR yet.")
+
+ def post_process_semantic_segmentation(self):
+ raise NotImplementedError("Semantic segmentation post-processing is not implemented for Deformable DETR yet.")
+
+ def post_process_panoptic_segmentation(self):
+ raise NotImplementedError("Panoptic segmentation post-processing is not implemented for Deformable DETR yet.")
+
+
+class YolosImageProcessorPil(DetrImageProcessorPil):
+ def resize(
+ self,
+ image: np.ndarray,
+ size: SizeDict,
+ resample: Optional["PILImageResampling"] = None,
+ **kwargs,
+ ) -> np.ndarray:
+ """
+ Resize the image to the given size. Size can be `min_size` (scalar) or `(height, width)` tuple. If size is an
+ int, smaller edge of the image will be matched to this number.
+
+ Args:
+ image (`np.ndarray`):
+ Image to resize.
+ size (`SizeDict`):
+ Size of the image's `(height, width)` dimensions after resizing. Available options are:
+ - `{"height": int, "width": int}`: The image will be resized to the exact size `(height, width)`.
+ Do NOT keep the aspect ratio.
+ - `{"shortest_edge": int, "longest_edge": int}`: The image will be resized to a maximum size respecting
+ the aspect ratio and keeping the shortest edge less or equal to `shortest_edge` and the longest edge
+ less or equal to `longest_edge`.
+ - `{"max_height": int, "max_width": int}`: The image will be resized to the maximum size respecting the
+ aspect ratio and keeping the height less or equal to `max_height` and the width less or equal to
+ `max_width`.
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
+ Resampling filter to use if resizing the image.
+ """
+ resample = resample if resample is not None else self.resample
+
+ if size.shortest_edge and size.longest_edge:
+ # Resize the image so that the shortest edge or the longest edge is of the given size
+ # while maintaining the aspect ratio of the original image.
+ new_size = get_size_with_aspect_ratio_yolos(
+ image.shape[-2:],
+ size.shortest_edge,
+ size.longest_edge or size.shortest_edge,
+ )
+ elif size.max_height and size.max_width:
+ new_size = get_image_size_for_max_height_width(image.shape[-2:], size.max_height, size.max_width)
+ elif size.height and size.width:
+ new_size = (size.height, size.width)
+ else:
+ raise ValueError(
+ f"Size must contain 'height' and 'width' keys or 'shortest_edge' and 'longest_edge' keys. Got {size}."
+ )
+
+ image = super().resize(
+ image,
+ size=SizeDict(height=new_size[0], width=new_size[1]),
+ resample=resample,
+ **kwargs,
+ )
+ return image
+
+ def post_process_object_detection(
+ self, outputs, threshold: float = 0.5, target_sizes: TensorType | list[tuple] = None
+ ):
+ """
+ Converts the raw output of [`YolosForObjectDetection`] into final bounding boxes in (top_left_x, top_left_y,
+ bottom_right_x, bottom_right_y) format. Only supports PyTorch.
+
+ Args:
+ outputs ([`YolosObjectDetectionOutput`]):
+ Raw outputs of the model.
+ threshold (`float`, *optional*):
+ Score threshold to keep object detection predictions.
+ target_sizes (`torch.Tensor` or `list[tuple[int, int]]`, *optional*):
+ Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the target size
+ `(height, width)` of each image in the batch. If unset, predictions will not be resized.
+ Returns:
+ `list[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
+ in the batch as predicted by the model.
+ """
+ requires_backends(self, ["torch"])
+ out_logits, out_bbox = outputs.logits, outputs.pred_boxes
+
+ if target_sizes is not None:
+ if len(out_logits) != len(target_sizes):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
+ )
+
+ prob = nn.functional.softmax(out_logits, -1)
+ scores, labels = prob[..., :-1].max(-1)
+
+ # Convert to [x0, y0, x1, y1] format
+ boxes = center_to_corners_format(out_bbox)
+
+ # Convert from relative [0, 1] to absolute [0, height] coordinates
+ if target_sizes is not None:
+ if isinstance(target_sizes, list):
+ img_h = torch.Tensor([i[0] for i in target_sizes])
+ img_w = torch.Tensor([i[1] for i in target_sizes])
+ else:
+ img_h, img_w = target_sizes.unbind(1)
+
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1).to(boxes.device)
+ boxes = boxes * scale_fct[:, None, :]
+
+ results = []
+ for s, l, b in zip(scores, labels, boxes):
+ score = s[s > threshold]
+ label = l[s > threshold]
+ box = b[s > threshold]
+ results.append({"scores": score, "labels": label, "boxes": box})
+
+ return results
+
+ def post_process_instance_segmentation(self):
+ raise NotImplementedError("Segmentation post-processing is not implemented for Deformable DETR yet.")
+
+ def post_process_semantic_segmentation(self):
+ raise NotImplementedError("Semantic segmentation post-processing is not implemented for Deformable DETR yet.")
+
+ def post_process_panoptic_segmentation(self):
+ raise NotImplementedError("Panoptic segmentation post-processing is not implemented for Deformable DETR yet.")
+
+
+__all__ = ["YolosImageProcessor", "YolosImageProcessorPil"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/yoso/__init__.py b/.venv/lib/python3.12/site-packages/transformers/models/yoso/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b865cb93ce1134a1a8761bafd1b3498931d7c83
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/yoso/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_yoso import *
+ from .modeling_yoso import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/yoso/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/yoso/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7a726e014ae8e8b0036234c6bc636d1cd87250bd
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/yoso/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/yoso/__pycache__/configuration_yoso.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/yoso/__pycache__/configuration_yoso.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fe8ce6c4dc02562fc684a40eedbde8188a9c1a3e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/yoso/__pycache__/configuration_yoso.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/yoso/__pycache__/modeling_yoso.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/yoso/__pycache__/modeling_yoso.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d5a679a6a3a57f450e272af67c75bbeccdc2394f
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/yoso/__pycache__/modeling_yoso.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/yoso/configuration_yoso.py b/.venv/lib/python3.12/site-packages/transformers/models/yoso/configuration_yoso.py
new file mode 100644
index 0000000000000000000000000000000000000000..379660d4d4d267ce3027856e8edb4b26bf64df6b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/yoso/configuration_yoso.py
@@ -0,0 +1,81 @@
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""YOSO model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="uw-madison/yoso-4096")
+@strict
+class YosoConfig(PreTrainedConfig):
+ r"""
+ use_expectation (`bool`, *optional*, defaults to `True`):
+ Whether or not to use YOSO Expectation. Overrides any effect of num_hash.
+ hash_code_len (`int`, *optional*, defaults to 9):
+ The length of hashes generated by the hash functions.
+ num_hash (`int`, *optional*, defaults to 64):
+ Number of hash functions used in [`YosoSelfAttention`].
+ conv_window (`int`, *optional*):
+ Kernel size of depth-wise convolution.
+ use_fast_hash (`bool`, *optional*, defaults to `False`):
+ Whether or not to use custom cuda kernels which perform fast random projection via hadamard transform.
+ lsh_backward (`bool`, *optional*, defaults to `True`):
+ Whether or not to perform backpropagation using Locality Sensitive Hashing.
+
+ Example:
+
+ ```python
+ >>> from transformers import YosoConfig, YosoModel
+
+ >>> # Initializing a YOSO uw-madison/yoso-4096 style configuration
+ >>> configuration = YosoConfig()
+
+ >>> # Initializing a model (with random weights) from the uw-madison/yoso-4096 style configuration
+ >>> model = YosoModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "yoso"
+
+ vocab_size: int = 50265
+ hidden_size: int = 768
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ intermediate_size: int = 3072
+ hidden_act: str = "gelu"
+ hidden_dropout_prob: float | int = 0.1
+ attention_probs_dropout_prob: float | int = 0.1
+ max_position_embeddings: int = 4096
+ type_vocab_size: int = 1
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-12
+ use_expectation: bool = True
+ hash_code_len: int = 9
+ num_hash: int = 64
+ conv_window: int | None = None
+ use_fast_hash: bool = True
+ lsh_backward: bool = True
+ pad_token_id: int | None = 1
+ bos_token_id: int | None = 0
+ eos_token_id: int | list[int] | None = 2
+ add_cross_attention: bool = False
+ tie_word_embeddings: bool = True
+
+
+__all__ = ["YosoConfig"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/yoso/modeling_yoso.py b/.venv/lib/python3.12/site-packages/transformers/models/yoso/modeling_yoso.py
new file mode 100644
index 0000000000000000000000000000000000000000..b8c2c6dc6c416f3b57c00f7145b2e9549ba25ec5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/yoso/modeling_yoso.py
@@ -0,0 +1,1155 @@
+# Copyright 2022 University of Wisconsin-Madison and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch YOSO model."""
+
+import math
+
+import torch
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutputWithCrossAttentions,
+ MaskedLMOutput,
+ MultipleChoiceModelOutput,
+ QuestionAnsweringModelOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+)
+from ...modeling_utils import PreTrainedModel
+from ...pytorch_utils import apply_chunking_to_forward
+from ...utils import (
+ auto_docstring,
+ is_kernels_available,
+ is_ninja_available,
+ is_torch_cuda_available,
+ logging,
+)
+from .configuration_yoso import YosoConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+lsh_cumulation = None
+
+
+def load_cuda_kernels():
+ global lsh_cumulation
+ if not is_kernels_available():
+ raise ImportError("kernels is not installed, please install it with `pip install kernels`")
+ from ...integrations.hub_kernels import get_kernel
+
+ yoso = get_kernel("kernels-community/yoso")
+ lsh_cumulation = yoso.lsh_cumulation
+
+
+def to_contiguous(input_tensors):
+ if isinstance(input_tensors, list):
+ out = []
+ for tensor in input_tensors:
+ if not tensor.is_contiguous():
+ tensor = tensor.contiguous()
+ out.append(tensor)
+ return out
+ else:
+ if not input_tensors.is_contiguous():
+ input_tensors = input_tensors.contiguous()
+ return input_tensors
+
+
+def normalize(input_tensors):
+ if isinstance(input_tensors, list):
+ out = []
+ for tensor in input_tensors:
+ out.append(nn.functional.normalize(tensor, p=2, dim=-1))
+ return out
+ else:
+ return nn.functional.normalize(input_tensors, p=2, dim=-1)
+
+
+def hashing(query, key, num_hash, hash_len):
+ if len(query.size()) != 3:
+ raise ValueError("Query has incorrect size.")
+ if len(key.size()) != 3:
+ raise ValueError("Key has incorrect size.")
+
+ rmat = torch.randn(query.size(0), query.size(2), num_hash * hash_len, device=query.device)
+ raise_pow = 2 ** torch.arange(hash_len, device=query.device)
+
+ query_projection = torch.matmul(query, rmat).reshape(query.size(0), query.size(1), num_hash, hash_len)
+ key_projection = torch.matmul(key, rmat).reshape(key.size(0), key.size(1), num_hash, hash_len)
+ query_binary = (query_projection > 0).int()
+ key_binary = (key_projection > 0).int()
+ query_hash = torch.sum(query_binary * raise_pow, dim=-1)
+ query_hash = torch.sum(key_binary * raise_pow, dim=-1)
+
+ return query_hash.int(), query_hash.int()
+
+
+class YosoCumulation(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, query_mask, key_mask, query, key, value, config):
+ hash_code_len = config["hash_code_len"]
+
+ expectation = (1 - torch.acos(torch.matmul(query, key.transpose(-1, -2))) / math.pi) ** hash_code_len
+ expectation = expectation * query_mask[:, :, None] * key_mask[:, None, :]
+ cumulation_value = torch.matmul(expectation, value)
+
+ ctx.save_for_backward(query_mask, key_mask, expectation, query, key, value)
+ ctx.config = config
+
+ return cumulation_value
+
+ @staticmethod
+ def backward(ctx, grad):
+ grad = to_contiguous(grad)
+
+ query_mask, key_mask, expectation, query, key, value = ctx.saved_tensors
+ config = ctx.config
+
+ hash_code_len = config["hash_code_len"]
+
+ weighted_exp = torch.matmul(grad, value.transpose(-1, -2)) * expectation
+ grad_query = torch.matmul(weighted_exp, (hash_code_len / 2) * key)
+ grad_key = torch.matmul(weighted_exp.transpose(-1, -2), (hash_code_len / 2) * query)
+ grad_value = torch.matmul(expectation.transpose(-1, -2), grad)
+
+ return None, None, grad_query, grad_key, grad_value, None
+
+
+class YosoLSHCumulation(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, query_mask, key_mask, query, key, value, config):
+ if query_mask.size(0) != key_mask.size(0):
+ raise ValueError("Query mask and Key mask differ in sizes in dimension 0")
+ if query_mask.size(0) != query.size(0):
+ raise ValueError("Query mask and Query differ in sizes in dimension 0")
+ if query_mask.size(0) != key.size(0):
+ raise ValueError("Query mask and Key differ in sizes in dimension 0")
+ if query_mask.size(0) != value.size(0):
+ raise ValueError("Query mask and Value mask differ in sizes in dimension 0")
+ if key.size(1) != value.size(1):
+ raise ValueError("Key and Value differ in sizes in dimension 1")
+ if query.size(2) != key.size(2):
+ raise ValueError("Query and Key differ in sizes in dimension 2")
+
+ query_mask, key_mask, query, key, value = to_contiguous([query_mask, key_mask, query, key, value])
+
+ use_cuda = query_mask.is_cuda
+ num_hash = config["num_hash"]
+ hash_code_len = config["hash_code_len"]
+ hashtable_capacity = int(2**hash_code_len)
+
+ if config["use_fast_hash"]:
+ query_hash_code, key_hash_code = lsh_cumulation.fast_hash(
+ query_mask, query, key_mask, key, num_hash, hash_code_len, use_cuda, 1
+ )
+ else:
+ query_hash_code, key_hash_code = hashing(query, key, num_hash, hash_code_len)
+
+ cumulation_value = lsh_cumulation.lsh_cumulation(
+ query_mask, query_hash_code, key_mask, key_hash_code, value, hashtable_capacity, use_cuda, 1
+ )
+
+ ctx.save_for_backward(query_mask, key_mask, query_hash_code, key_hash_code, query, key, value)
+ ctx.config = config
+
+ return cumulation_value
+
+ @staticmethod
+ def backward(ctx, grad):
+ grad = to_contiguous(grad)
+
+ query_mask, key_mask, query_hash_code, key_hash_code, query, key, value = ctx.saved_tensors
+ config = ctx.config
+
+ use_cuda = grad.is_cuda
+ hash_code_len = config["hash_code_len"]
+ hashtable_capacity = int(2**hash_code_len)
+
+ if config["lsh_backward"]:
+ grad_value = lsh_cumulation.lsh_cumulation(
+ key_mask, key_hash_code, query_mask, query_hash_code, grad, hashtable_capacity, use_cuda, 1
+ )
+ grad_query = lsh_cumulation.lsh_weighted_cumulation(
+ query_mask,
+ query_hash_code,
+ grad,
+ key_mask,
+ key_hash_code,
+ value,
+ (hash_code_len / 2) * key,
+ hashtable_capacity,
+ use_cuda,
+ 4,
+ )
+ grad_key = lsh_cumulation.lsh_weighted_cumulation(
+ key_mask,
+ key_hash_code,
+ value,
+ query_mask,
+ query_hash_code,
+ grad,
+ (hash_code_len / 2) * query,
+ hashtable_capacity,
+ use_cuda,
+ 4,
+ )
+ else:
+ expectation = (1 - torch.acos(torch.matmul(query, key.transpose(-1, -2))) / math.pi) ** hash_code_len
+ expectation = expectation * query_mask[:, :, None] * key_mask[:, None, :]
+ weighted_exp = torch.matmul(grad, value.transpose(-1, -2)) * expectation
+ grad_query = torch.matmul(weighted_exp, (hash_code_len / 2) * key)
+ grad_key = torch.matmul(weighted_exp.transpose(-1, -2), (hash_code_len / 2) * query)
+ grad_value = torch.matmul(expectation.transpose(-1, -2), grad)
+
+ return None, None, grad_query, grad_key, grad_value, None
+
+
+# Copied from transformers.models.nystromformer.modeling_nystromformer.NystromformerEmbeddings
+class YosoEmbeddings(nn.Module):
+ """Construct the embeddings from word, position and token_type embeddings."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings + 2, config.hidden_size)
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
+
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
+ self.register_buffer(
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)) + 2, persistent=False
+ )
+ self.register_buffer(
+ "token_type_ids",
+ torch.zeros(self.position_ids.size(), dtype=torch.long, device=self.position_ids.device),
+ persistent=False,
+ )
+
+ def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None):
+ if input_ids is not None:
+ input_shape = input_ids.size()
+ else:
+ input_shape = inputs_embeds.size()[:-1]
+
+ seq_length = input_shape[1]
+
+ if position_ids is None:
+ position_ids = self.position_ids[:, :seq_length]
+
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
+ # issue #5664
+ if token_type_ids is None:
+ if hasattr(self, "token_type_ids"):
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
+ token_type_ids = buffered_token_type_ids_expanded
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
+
+ if inputs_embeds is None:
+ inputs_embeds = self.word_embeddings(input_ids)
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
+ embeddings = inputs_embeds + token_type_embeddings
+
+ position_embeddings = self.position_embeddings(position_ids)
+ embeddings += position_embeddings
+
+ embeddings = self.LayerNorm(embeddings)
+ embeddings = self.dropout(embeddings)
+ return embeddings
+
+
+class YosoSelfAttention(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({config.num_attention_heads})"
+ )
+ kernel_loaded = lsh_cumulation is not None
+ if is_torch_cuda_available() and is_ninja_available() and not kernel_loaded:
+ try:
+ load_cuda_kernels()
+ except Exception as e:
+ logger.warning(f"Could not load the custom kernel for multi-scale deformable attention: {e}")
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+
+ self.use_expectation = config.use_expectation
+ self.hash_code_len = config.hash_code_len
+ self.use_conv = config.conv_window is not None
+ self.use_fast_hash = config.use_fast_hash
+ self.num_hash = config.num_hash
+ self.lsh_backward = config.lsh_backward
+
+ self.lsh_config = {
+ "hash_code_len": self.hash_code_len,
+ "use_fast_hash": self.use_fast_hash,
+ "num_hash": self.num_hash,
+ "lsh_backward": self.lsh_backward,
+ }
+
+ if config.conv_window is not None:
+ self.conv = nn.Conv2d(
+ in_channels=config.num_attention_heads,
+ out_channels=config.num_attention_heads,
+ kernel_size=(config.conv_window, 1),
+ padding=(config.conv_window // 2, 0),
+ bias=False,
+ groups=config.num_attention_heads,
+ )
+
+ def forward(self, hidden_states, attention_mask=None, output_attentions=False):
+ batch_size, seq_length, _ = hidden_states.shape
+ query_layer = (
+ self.query(hidden_states)
+ .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
+ .transpose(1, 2)
+ )
+ key_layer = (
+ self.key(hidden_states)
+ .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
+ .transpose(1, 2)
+ )
+ value_layer = (
+ self.value(hidden_states)
+ .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
+ .transpose(1, 2)
+ )
+
+ if self.use_conv:
+ conv_value_layer = self.conv(value_layer * attention_mask[:, None, :, None])
+
+ batch_size, num_heads, seq_len, head_dim = query_layer.size()
+
+ query_layer = query_layer.reshape(batch_size * num_heads, seq_len, head_dim)
+ key_layer = key_layer.reshape(batch_size * num_heads, seq_len, head_dim)
+ value_layer = value_layer.reshape(batch_size * num_heads, seq_len, head_dim)
+
+ attention_mask = 1.0 + attention_mask / 10000.0
+ attention_mask = (
+ attention_mask.unsqueeze(1)
+ .repeat_interleave(num_heads, dim=1)
+ .reshape(batch_size * num_heads, seq_len)
+ .int()
+ )
+
+ # The CUDA kernels are most efficient with inputs whose size is a multiple of a GPU's warp size (32). Inputs
+ # smaller than this are padded with zeros.
+ gpu_warp_size = 32
+
+ if (not self.use_expectation) and head_dim < gpu_warp_size:
+ pad_size = batch_size * num_heads, seq_len, gpu_warp_size - head_dim
+
+ query_layer = torch.cat(
+ [
+ query_layer,
+ torch.zeros(pad_size, device=query_layer.device),
+ ],
+ dim=-1,
+ )
+ key_layer = torch.cat(
+ [
+ key_layer,
+ torch.zeros(pad_size, device=key_layer.device),
+ ],
+ dim=-1,
+ )
+ value_layer = torch.cat(
+ [
+ value_layer,
+ torch.zeros(pad_size, device=value_layer.device),
+ ],
+ dim=-1,
+ )
+
+ if self.use_expectation or self.training:
+ query_layer, key_layer = normalize([query_layer, key_layer])
+
+ if self.use_expectation:
+ context_layer = YosoCumulation.apply(
+ attention_mask, attention_mask, query_layer, key_layer, value_layer, self.lsh_config
+ )
+ else:
+ context_layer = YosoLSHCumulation.apply(
+ attention_mask, attention_mask, query_layer, key_layer, value_layer, self.lsh_config
+ )
+
+ if (not self.use_expectation) and head_dim < gpu_warp_size:
+ context_layer = context_layer[:, :, :head_dim]
+
+ context_layer = normalize(context_layer)
+
+ context_layer = context_layer.reshape(batch_size, num_heads, seq_len, head_dim)
+
+ if self.use_conv:
+ context_layer += conv_value_layer
+
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.view(*new_context_layer_shape)
+
+ outputs = (context_layer, context_layer) if output_attentions else (context_layer,)
+
+ return outputs
+
+
+# Copied from transformers.models.bert.modeling_bert.BertSelfOutput
+class YosoSelfOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+class YosoAttention(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.self = YosoSelfAttention(config)
+ self.output = YosoSelfOutput(config)
+
+ def forward(self, hidden_states, attention_mask=None, output_attentions=False):
+ self_outputs = self.self(hidden_states, attention_mask, output_attentions)
+ attention_output = self.output(self_outputs[0], hidden_states)
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
+ return outputs
+
+
+# Copied from transformers.models.bert.modeling_bert.BertIntermediate
+class YosoIntermediate(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.bert.modeling_bert.BertOutput
+class YosoOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+class YosoLayer(GradientCheckpointingLayer):
+ def __init__(self, config):
+ super().__init__()
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+ self.attention = YosoAttention(config)
+ self.add_cross_attention = config.add_cross_attention
+ self.intermediate = YosoIntermediate(config)
+ self.output = YosoOutput(config)
+
+ def forward(self, hidden_states, attention_mask=None, output_attentions=False):
+ self_attention_outputs = self.attention(hidden_states, attention_mask, output_attentions=output_attentions)
+ attention_output = self_attention_outputs[0]
+
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
+
+ layer_output = apply_chunking_to_forward(
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
+ )
+ outputs = (layer_output,) + outputs
+
+ return outputs
+
+ def feed_forward_chunk(self, attention_output):
+ intermediate_output = self.intermediate(attention_output)
+ layer_output = self.output(intermediate_output, attention_output)
+ return layer_output
+
+
+class YosoEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList([YosoLayer(config) for _ in range(config.num_hidden_layers)])
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ output_attentions=False,
+ output_hidden_states=False,
+ return_dict=True,
+ ):
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+
+ for i, layer_module in enumerate(self.layer):
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ layer_outputs = layer_module(hidden_states, attention_mask, output_attentions)
+
+ hidden_states = layer_outputs[0]
+ if output_attentions:
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
+ return BaseModelOutputWithCrossAttentions(
+ last_hidden_state=hidden_states,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ )
+
+
+# Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform
+class YosoPredictionHeadTransform(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ if isinstance(config.hidden_act, str):
+ self.transform_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.transform_act_fn = config.hidden_act
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.transform_act_fn(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->Yoso
+class YosoLMPredictionHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.transform = YosoPredictionHeadTransform(config)
+
+ # The output weights are the same as the input embeddings, but there is
+ # an output-only bias for each token.
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
+
+ def forward(self, hidden_states):
+ hidden_states = self.transform(hidden_states)
+ hidden_states = self.decoder(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert->Yoso
+class YosoOnlyMLMHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.predictions = YosoLMPredictionHead(config)
+
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
+ prediction_scores = self.predictions(sequence_output)
+ return prediction_scores
+
+
+@auto_docstring
+class YosoPreTrainedModel(PreTrainedModel):
+ config: YosoConfig
+ base_model_prefix = "yoso"
+ supports_gradient_checkpointing = True
+
+ @torch.no_grad()
+ def _init_weights(self, module: nn.Module):
+ """Initialize the weights"""
+ super()._init_weights(module)
+ if isinstance(module, YosoLMPredictionHead):
+ init.zeros_(module.bias)
+ elif isinstance(module, YosoEmbeddings):
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)) + 2)
+ init.zeros_(module.token_type_ids)
+
+
+@auto_docstring
+class YosoModel(YosoPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.config = config
+
+ self.embeddings = YosoEmbeddings(config)
+ self.encoder = YosoEncoder(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.embeddings.word_embeddings = value
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | BaseModelOutputWithCrossAttentions:
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
+ input_shape = input_ids.size()
+ elif inputs_embeds is not None:
+ input_shape = inputs_embeds.size()[:-1]
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ batch_size, seq_length = input_shape
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
+
+ if attention_mask is None:
+ attention_mask = torch.ones(((batch_size, seq_length)), device=device)
+
+ if token_type_ids is None:
+ if hasattr(self.embeddings, "token_type_ids"):
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
+ token_type_ids = buffered_token_type_ids_expanded
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
+
+ embedding_output = self.embeddings(
+ input_ids=input_ids,
+ position_ids=position_ids,
+ token_type_ids=token_type_ids,
+ inputs_embeds=inputs_embeds,
+ )
+ encoder_outputs = self.encoder(
+ embedding_output,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ sequence_output = encoder_outputs[0]
+
+ if not return_dict:
+ return (sequence_output,) + encoder_outputs[1:]
+
+ return BaseModelOutputWithCrossAttentions(
+ last_hidden_state=sequence_output,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ cross_attentions=encoder_outputs.cross_attentions,
+ )
+
+
+@auto_docstring
+class YosoForMaskedLM(YosoPreTrainedModel):
+ _tied_weights_keys = {
+ "cls.predictions.decoder.bias": "cls.predictions.bias",
+ "cls.predictions.decoder.weight": "yoso.embeddings.word_embeddings.weight",
+ }
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.yoso = YosoModel(config)
+ self.cls = YosoOnlyMLMHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.cls.predictions.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.cls.predictions.decoder = new_embeddings
+ self.cls.predictions.bias = new_embeddings.bias
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | MaskedLMOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.yoso(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+ prediction_scores = self.cls(sequence_output)
+
+ masked_lm_loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
+
+ if not return_dict:
+ output = (prediction_scores,) + outputs[1:]
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
+
+ return MaskedLMOutput(
+ loss=masked_lm_loss,
+ logits=prediction_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+class YosoClassificationHead(nn.Module):
+ """Head for sentence-level classification tasks."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
+
+ self.config = config
+
+ def forward(self, features, **kwargs):
+ x = features[:, 0, :] # take token (equiv. to [CLS])
+ x = self.dropout(x)
+ x = self.dense(x)
+ x = ACT2FN[self.config.hidden_act](x)
+ x = self.dropout(x)
+ x = self.out_proj(x)
+ return x
+
+
+@auto_docstring(
+ custom_intro="""
+ YOSO Model transformer with a sequence classification/regression head on top (a linear layer on top of
+ the pooled output) e.g. for GLUE tasks.
+ """
+)
+class YosoForSequenceClassification(YosoPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.yoso = YosoModel(config)
+ self.classifier = YosoClassificationHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | SequenceClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.yoso(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+ if not return_dict:
+ output = (logits,) + outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class YosoForMultipleChoice(YosoPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.yoso = YosoModel(config)
+ self.pre_classifier = nn.Linear(config.hidden_size, config.hidden_size)
+ self.classifier = nn.Linear(config.hidden_size, 1)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | MultipleChoiceModelOutput:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
+ 1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
+ `input_ids` above)
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
+
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
+ inputs_embeds = (
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
+ if inputs_embeds is not None
+ else None
+ )
+
+ outputs = self.yoso(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ hidden_state = outputs[0] # (bs * num_choices, seq_len, dim)
+ pooled_output = hidden_state[:, 0] # (bs * num_choices, dim)
+ pooled_output = self.pre_classifier(pooled_output) # (bs * num_choices, dim)
+ pooled_output = nn.ReLU()(pooled_output) # (bs * num_choices, dim)
+ logits = self.classifier(pooled_output)
+
+ reshaped_logits = logits.view(-1, num_choices)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(reshaped_logits, labels)
+
+ if not return_dict:
+ output = (reshaped_logits,) + outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return MultipleChoiceModelOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class YosoForTokenClassification(YosoPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.yoso = YosoModel(config)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | TokenClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.yoso(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ sequence_output = self.dropout(sequence_output)
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ # Only keep active parts of the loss
+ if attention_mask is not None:
+ active_loss = attention_mask.view(-1) == 1
+ active_logits = logits.view(-1, self.num_labels)
+ active_labels = torch.where(
+ active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels)
+ )
+ loss = loss_fct(active_logits, active_labels)
+ else:
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ if not return_dict:
+ output = (logits,) + outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class YosoForQuestionAnswering(YosoPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ config.num_labels = 2
+ self.num_labels = config.num_labels
+
+ self.yoso = YosoModel(config)
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ start_positions: torch.Tensor | None = None,
+ end_positions: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | QuestionAnsweringModelOutput:
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.yoso(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1)
+ end_logits = end_logits.squeeze(-1)
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ if not return_dict:
+ output = (start_logits, end_logits) + outputs[1:]
+ return ((total_loss,) + output) if total_loss is not None else output
+
+ return QuestionAnsweringModelOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "YosoForMaskedLM",
+ "YosoForMultipleChoice",
+ "YosoForQuestionAnswering",
+ "YosoForSequenceClassification",
+ "YosoForTokenClassification",
+ "YosoLayer",
+ "YosoModel",
+ "YosoPreTrainedModel",
+]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/youtu/__init__.py b/.venv/lib/python3.12/site-packages/transformers/models/youtu/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e02875ac5badcbe10150953b5a6c8d9b7077531d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/youtu/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_youtu import *
+ from .modeling_youtu import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/youtu/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/youtu/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1ac9b61900e5821d34695a8e4614c06e8f2b8eca
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/youtu/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/youtu/__pycache__/configuration_youtu.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/youtu/__pycache__/configuration_youtu.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f562d7466276d919a091c63c482f0a5425a2085c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/youtu/__pycache__/configuration_youtu.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/youtu/__pycache__/modeling_youtu.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/youtu/__pycache__/modeling_youtu.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..51c0f2b8984e104378ec19e52b6f2abb13c64080
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/youtu/__pycache__/modeling_youtu.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/youtu/__pycache__/modular_youtu.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/youtu/__pycache__/modular_youtu.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0809fa0c704472dbf623dbd97f562c245986c572
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/youtu/__pycache__/modular_youtu.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/youtu/configuration_youtu.py b/.venv/lib/python3.12/site-packages/transformers/models/youtu/configuration_youtu.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d9f2cef1f9633554f95ce68a30fc5ec47483807
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/youtu/configuration_youtu.py
@@ -0,0 +1,107 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/youtu/modular_youtu.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_youtu.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2026 the Tencent and HuggingFace Inc. team. All rights reserved.
+#
+# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
+# and OPT implementations in this library. It has been modified from its
+# original forms to accommodate minor architectural differences compared
+# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...modeling_rope_utils import RopeParameters
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="tencent/Youtu-LLM-2B")
+@strict
+class YoutuConfig(PreTrainedConfig):
+ r"""
+ rope_interleave (`bool`, *optional*, defaults to `True`):
+ Whether to interleave the rotary position embeddings.
+ embedding_initializer_range (`float`, *optional*):
+ The standard deviation of the truncated_normal_initializer for initializing all embedding matrices.
+
+ ```python
+ >>> from transformers import YoutuModel, YoutuConfig
+ >>> # Initializing a Youtu-LLM-2B style configuration
+ >>> configuration = YoutuConfig()
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "youtu"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ base_model_tp_plan = {
+ "layers.*.mlp.gate_proj": "colwise",
+ "layers.*.mlp.up_proj": "colwise",
+ "layers.*.mlp.down_proj": "rowwise",
+ }
+ base_model_pp_plan = {
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
+ "norm": (["hidden_states"], ["hidden_states"]),
+ }
+ attribute_map = {}
+
+ vocab_size: int = 128256
+ hidden_size: int = 2048
+ intermediate_size: int = 6144
+ num_hidden_layers: int = 32
+ num_attention_heads: int = 16
+ num_key_value_heads: int = 16
+ kv_lora_rank: int = 512
+ q_lora_rank: int | None = 1536
+ qk_rope_head_dim: int = 64
+ v_head_dim: int | None = 128
+ qk_nope_head_dim: int = 128
+ hidden_act: str = "silu"
+ max_position_embeddings: int = 131072
+ initializer_range: float | None = None
+ rms_norm_eps: float = 1e-6
+ use_cache: bool = True
+ pad_token_id: int | None = None
+ bos_token_id: int | None = 128000
+ eos_token_id: int | list[int] | None = 128001
+ tie_word_embeddings: bool = True
+ rope_parameters: RopeParameters | dict | None = None
+ rope_interleave: bool | None = True
+ attention_bias: bool = False
+ attention_dropout: float | int | None = 0.0
+ embedding_initializer_range: float | None = None
+
+ def __post_init__(self, **kwargs):
+ if self.initializer_range is None:
+ if self.hidden_size != 0:
+ self.initializer_range = 2.0 / (5.0 * self.hidden_size) ** 0.5
+ else:
+ self.initializer_range = 0.02
+
+ self.embedding_initializer_range = self.embedding_initializer_range or 2.0 * self.initializer_range
+ if self.num_key_value_heads is None:
+ self.num_key_value_heads = self.num_attention_heads
+
+ self.qk_head_dim = self.qk_nope_head_dim + self.qk_rope_head_dim
+ self.head_dim = self.qk_rope_head_dim
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["YoutuConfig"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/youtu/modeling_youtu.py b/.venv/lib/python3.12/site-packages/transformers/models/youtu/modeling_youtu.py
new file mode 100644
index 0000000000000000000000000000000000000000..f293235f5cbbf41fc1ec55c4fdab61412db23332
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/youtu/modeling_youtu.py
@@ -0,0 +1,608 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/youtu/modular_youtu.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_youtu.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2026 the Tencent and HuggingFace Inc. team. All rights reserved.
+#
+# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
+# and OPT implementations in this library. It has been modified from its
+# original forms to accommodate minor architectural differences compared
+# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import math
+from collections.abc import Callable
+from typing import Optional
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache
+from ...generation import GenerationMixin
+from ...integrations import use_kernel_forward_from_hub, use_kernel_func_from_hub
+from ...masking_utils import create_causal_mask
+from ...modeling_flash_attention_utils import FlashAttentionKwargs
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
+from ...utils.generic import is_flash_attention_requested, maybe_autocast, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_youtu import YoutuConfig
+
+
+@use_kernel_forward_from_hub("RMSNorm")
+class YoutuRMSNorm(nn.Module):
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
+ """
+ YoutuRMSNorm is equivalent to T5LayerNorm
+ """
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+ return self.weight * hidden_states.to(input_dtype)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
+
+
+class YoutuRotaryEmbedding(nn.Module):
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
+
+ def __init__(self, config: YoutuConfig, device=None):
+ super().__init__()
+ self.max_seq_len_cached = config.max_position_embeddings
+ self.original_max_seq_len = config.max_position_embeddings
+
+ self.config = config
+
+ self.rope_type = self.config.rope_parameters["rope_type"]
+ rope_init_fn: Callable = self.compute_default_rope_parameters
+ if self.rope_type != "default":
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
+
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
+
+ @staticmethod
+ def compute_default_rope_parameters(
+ config: YoutuConfig | None = None,
+ device: Optional["torch.device"] = None,
+ seq_len: int | None = None,
+ ) -> tuple["torch.Tensor", float]:
+ """
+ Computes the inverse frequencies according to the original RoPE implementation
+ Args:
+ config ([`~transformers.PreTrainedConfig`]):
+ The model configuration.
+ device (`torch.device`):
+ The device to use for initialization of the inverse frequencies.
+ seq_len (`int`, *optional*):
+ The current sequence length. Unused for this type of RoPE.
+ Returns:
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
+ """
+ base = config.rope_parameters["rope_theta"]
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
+
+ attention_factor = 1.0 # Unused in this type of RoPE
+
+ # Compute the inverse frequencies
+ inv_freq = 1.0 / (
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
+ )
+ return inv_freq, attention_factor
+
+ @torch.no_grad()
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
+ def forward(self, x, position_ids):
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
+ position_ids_expanded = position_ids[:, None, :].float()
+
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
+ emb = torch.cat((freqs, freqs), dim=-1)
+ cos = emb.cos() * self.attention_scaling
+ sin = emb.sin() * self.attention_scaling
+
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
+
+
+class YoutuMLP(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = config.intermediate_size
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(self, x):
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
+ return down_proj
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., : x.shape[-1] // 2]
+ x2 = x[..., x.shape[-1] // 2 :]
+ return torch.cat((-x2, x1), dim=-1)
+
+
+@use_kernel_func_from_hub("rotary_pos_emb")
+def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+ q_embed = (q * cos) + (rotate_half(q) * sin)
+ k_embed = (k * cos) + (rotate_half(k) * sin)
+ return q_embed, k_embed
+
+
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ key_states = repeat_kv(key, module.num_key_value_groups)
+ value_states = repeat_kv(value, module.num_key_value_groups)
+
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+ attn_output = torch.matmul(attn_weights, value_states)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+def apply_rotary_pos_emb_interleave(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
+ r"""
+ Applies interleaved Rotary Position Embedding to the query and key tensors.
+
+ DeepSeek lays the rotary dimensions out in interleaved pairs `(x0, x1), (x2, x3), ...`, each rotated by a
+ single frequency. We compute that rotation directly on the even/odd slices instead of de-interleaving with a
+ `view`/`transpose`/`reshape`; the output is bit-identical to the de-interleaved `rotate_half` formulation while
+ avoiding the extra contiguous copy.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ position_ids (`torch.Tensor`):
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
+ used to pass offsetted position ids when working with a KV-cache.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ # `cos`/`sin` are `cat(freqs, freqs)`; the first half holds the per-pair angle.
+ cos = cos[..., : cos.shape[-1] // 2].unsqueeze(unsqueeze_dim)
+ sin = sin[..., : sin.shape[-1] // 2].unsqueeze(unsqueeze_dim)
+
+ q1, q2 = q[..., 0::2], q[..., 1::2]
+ k1, k2 = k[..., 0::2], k[..., 1::2]
+
+ q_embed = torch.cat([q1 * cos - q2 * sin, q2 * cos + q1 * sin], dim=-1)
+ k_embed = torch.cat([k1 * cos - k2 * sin, k2 * cos + k1 * sin], dim=-1)
+ return q_embed, k_embed
+
+
+def yarn_get_mscale(scale=1, mscale=1):
+ if scale <= 1:
+ return 1.0
+ return 0.1 * mscale * math.log(scale) + 1.0
+
+
+class YoutuAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: YoutuConfig, layer_idx: int):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.attention_dropout = config.attention_dropout
+ self.num_heads = config.num_attention_heads
+
+ self.q_lora_rank = config.q_lora_rank
+ self.qk_rope_head_dim = config.qk_rope_head_dim
+ self.kv_lora_rank = config.kv_lora_rank
+ self.v_head_dim = config.v_head_dim
+ self.qk_nope_head_dim = config.qk_nope_head_dim
+ self.qk_head_dim = config.qk_head_dim
+
+ self.is_causal = True
+ if self.q_lora_rank is None:
+ self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.qk_head_dim, bias=False)
+ else:
+ self.q_a_proj = nn.Linear(config.hidden_size, config.q_lora_rank, bias=config.attention_bias)
+ self.q_a_layernorm = YoutuRMSNorm(config.q_lora_rank)
+ self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.qk_head_dim, bias=False)
+
+ self.kv_a_proj_with_mqa = nn.Linear(
+ config.hidden_size,
+ self.kv_lora_rank + self.qk_rope_head_dim,
+ bias=config.attention_bias,
+ )
+ self.kv_a_layernorm = YoutuRMSNorm(self.kv_lora_rank)
+ self.kv_b_proj = nn.Linear(
+ self.kv_lora_rank,
+ self.num_heads * (self.qk_nope_head_dim + self.v_head_dim),
+ bias=False,
+ )
+
+ self.o_proj = nn.Linear(
+ self.num_heads * self.v_head_dim,
+ config.hidden_size,
+ bias=config.attention_bias,
+ )
+
+ self.scaling = self.qk_head_dim ** (-0.5)
+ if self.config.rope_parameters.get("rope_type", "default") != "default":
+ mscale_all_dim = self.config.rope_parameters.get("mscale_all_dim", 0)
+ scaling_factor = self.config.rope_parameters["factor"]
+ if mscale_all_dim:
+ mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
+ self.scaling = self.scaling * mscale * mscale
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
+ attention_mask: torch.Tensor | None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
+ batch_size, seq_length = hidden_states.shape[:-1]
+ query_shape = (batch_size, seq_length, -1, self.qk_head_dim)
+ key_shape = (batch_size, seq_length, -1, self.qk_nope_head_dim + self.v_head_dim)
+
+ if self.q_lora_rank is None:
+ q_states = self.q_proj(hidden_states)
+ else:
+ q_states = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
+ q_states = q_states.view(query_shape).transpose(1, 2)
+ q_pass, q_rot = torch.split(q_states, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
+
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
+ k_pass, k_rot = torch.split(compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
+
+ k_pass = self.kv_b_proj(self.kv_a_layernorm(k_pass)).view(key_shape).transpose(1, 2)
+ k_pass, value_states = torch.split(k_pass, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)
+
+ k_rot = k_rot.view(batch_size, 1, seq_length, self.qk_rope_head_dim)
+
+ cos, sin = position_embeddings
+ if self.config.rope_interleave: # support using interleaved weights for efficiency
+ q_rot, k_rot = apply_rotary_pos_emb_interleave(q_rot, k_rot, cos, sin)
+ else:
+ q_rot, k_rot = apply_rotary_pos_emb(q_rot, k_rot, cos, sin)
+ k_rot = k_rot.expand(*k_pass.shape[:-1], -1)
+
+ query_states = torch.cat((q_pass, q_rot), dim=-1)
+ key_states = torch.cat((k_pass, k_rot), dim=-1)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ if is_flash_attention_requested(self.config) and self.qk_head_dim != self.v_head_dim:
+ value_states = F.pad(value_states, [0, self.qk_head_dim - self.v_head_dim])
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ if is_flash_attention_requested(self.config) and self.qk_head_dim != self.v_head_dim:
+ attn_output = attn_output[:, :, :, : self.v_head_dim]
+
+ attn_output = attn_output.reshape(batch_size, seq_length, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class YoutuDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: YoutuConfig, layer_idx: int):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+
+ self.self_attn = YoutuAttention(config=config, layer_idx=layer_idx)
+
+ self.mlp = YoutuMLP(config)
+ self.input_layernorm = YoutuRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_attention_layernorm = YoutuRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ residual = hidden_states
+ hidden_states = self.input_layernorm(hidden_states)
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.post_attention_layernorm(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+ return hidden_states
+
+
+@auto_docstring
+class YoutuPreTrainedModel(PreTrainedModel):
+ config: YoutuConfig
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["YoutuDecoderLayer"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+
+ _can_compile_fullgraph = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": YoutuDecoderLayer,
+ "attentions": YoutuAttention,
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ std = getattr(self.config, "initializer_range", 0.02)
+ embed_std = getattr(self.config, "embedding_initializer_range", 2 * std)
+ if isinstance(module, nn.Embedding):
+ init.normal_(module.weight, mean=0.0, std=embed_std)
+ if module.padding_idx is not None:
+ init.zeros_(module.weight.data[module.padding_idx])
+
+
+@auto_docstring
+class YoutuModel(YoutuPreTrainedModel):
+ def __init__(self, config: YoutuConfig):
+ super().__init__(config)
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
+ self.layers = nn.ModuleList(
+ [YoutuDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+ self.norm = YoutuRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.rotary_emb = YoutuRotaryEmbedding(config=config)
+ self.gradient_checkpointing = False
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ causal_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_ids=position_ids,
+ )
+
+ hidden_states = inputs_embeds
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
+
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
+ hidden_states = decoder_layer(
+ hidden_states,
+ attention_mask=causal_mask,
+ position_embeddings=position_embeddings,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = self.norm(hidden_states)
+ return BaseModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ )
+
+
+@auto_docstring
+class YoutuForCausalLM(YoutuPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
+ _tp_plan = {"lm_head": "colwise_gather_output"}
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.model = YoutuModel(config)
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> CausalLMOutputWithPast:
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, YoutuForCausalLM
+
+ >>> model = YoutuForCausalLM.from_pretrained("meta-youtu/Youtu-2-7b-hf")
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-youtu/Youtu-2-7b-hf")
+
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
+ ```"""
+ outputs: BaseModelOutputWithPast = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return CausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = ["YoutuPreTrainedModel", "YoutuModel", "YoutuForCausalLM"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/youtu/modular_youtu.py b/.venv/lib/python3.12/site-packages/transformers/models/youtu/modular_youtu.py
new file mode 100644
index 0000000000000000000000000000000000000000..b2de3a2df0a5425b862099e67a7c13d86a1faaad
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/youtu/modular_youtu.py
@@ -0,0 +1,151 @@
+# Copyright 2026 the Tencent and HuggingFace Inc. team. All rights reserved.
+#
+# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
+# and OPT implementations in this library. It has been modified from its
+# original forms to accommodate minor architectural differences compared
+# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import torch
+from huggingface_hub.dataclasses import strict
+from torch import nn
+
+from ... import initialization as init
+from ...modeling_utils import PreTrainedModel
+from ...utils import auto_docstring, logging
+from ..deepseek_v3.configuration_deepseek_v3 import DeepseekV3Config
+from ..deepseek_v3.modeling_deepseek_v3 import DeepseekV3Attention
+from ..llama.modeling_llama import (
+ LlamaDecoderLayer,
+ LlamaForCausalLM,
+ LlamaModel,
+ LlamaPreTrainedModel,
+ LlamaRMSNorm,
+ LlamaRotaryEmbedding,
+)
+from ..qwen3.modeling_qwen3 import Qwen3MLP
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(checkpoint="tencent/Youtu-LLM-2B")
+@strict
+class YoutuConfig(DeepseekV3Config):
+ r"""
+ rope_interleave (`bool`, *optional*, defaults to `True`):
+ Whether to interleave the rotary position embeddings.
+ embedding_initializer_range (`float`, *optional*):
+ The standard deviation of the truncated_normal_initializer for initializing all embedding matrices.
+
+ ```python
+ >>> from transformers import YoutuModel, YoutuConfig
+ >>> # Initializing a Youtu-LLM-2B style configuration
+ >>> configuration = YoutuConfig()
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "youtu"
+ base_model_tp_plan = {
+ "layers.*.mlp.gate_proj": "colwise",
+ "layers.*.mlp.up_proj": "colwise",
+ "layers.*.mlp.down_proj": "rowwise",
+ }
+ attribute_map = {}
+
+ vocab_size: int = 128256
+ hidden_size: int = 2048
+ intermediate_size: int = 6144
+ num_hidden_layers: int = 32
+ num_attention_heads: int = 16
+ num_key_value_heads: int = 16
+ max_position_embeddings: int = 131072
+ initializer_range: float | None = None
+ embedding_initializer_range: float | None = None
+ pad_token_id: int | None = None
+ bos_token_id: int | None = 128000
+ eos_token_id: int | list[int] | None = 128001
+ tie_word_embeddings: bool = True
+
+ # remove unused attribute
+ n_shared_experts = AttributeError()
+ n_routed_experts = AttributeError()
+ routed_scaling_factor = AttributeError()
+ n_group = AttributeError()
+ topk_group = AttributeError()
+ num_experts_per_tok = AttributeError()
+ first_k_dense_replace = AttributeError()
+ norm_topk_prob = AttributeError()
+ pretraining_tp = AttributeError()
+ moe_intermediate_size = AttributeError()
+
+ def __post_init__(self, **kwargs):
+ if self.initializer_range is None:
+ if self.hidden_size != 0:
+ self.initializer_range = 2.0 / (5.0 * self.hidden_size) ** 0.5
+ else:
+ self.initializer_range = 0.02
+
+ self.embedding_initializer_range = self.embedding_initializer_range or 2.0 * self.initializer_range
+ super().__post_init__(**kwargs)
+
+
+class YoutuRMSNorm(LlamaRMSNorm):
+ pass
+
+
+class YoutuRotaryEmbedding(LlamaRotaryEmbedding):
+ pass
+
+
+class YoutuMLP(Qwen3MLP):
+ pass
+
+
+class YoutuAttention(DeepseekV3Attention):
+ pass
+
+
+class YoutuDecoderLayer(LlamaDecoderLayer):
+ pass
+
+
+class YoutuPreTrainedModel(LlamaPreTrainedModel, PreTrainedModel):
+ @torch.no_grad()
+ def _init_weights(self, module):
+ PreTrainedModel._init_weights(self, module)
+ std = getattr(self.config, "initializer_range", 0.02)
+ embed_std = getattr(self.config, "embedding_initializer_range", 2 * std)
+ if isinstance(module, nn.Embedding):
+ init.normal_(module.weight, mean=0.0, std=embed_std)
+ if module.padding_idx is not None:
+ init.zeros_(module.weight.data[module.padding_idx])
+
+
+class YoutuModel(LlamaModel):
+ pass
+
+
+class YoutuForCausalLM(LlamaForCausalLM):
+ pass
+
+
+__all__ = [
+ "YoutuConfig",
+ "YoutuPreTrainedModel",
+ "YoutuModel",
+ "YoutuForCausalLM",
+]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/zamba/__init__.py b/.venv/lib/python3.12/site-packages/transformers/models/zamba/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..48a233755de26862db8489d083ffc7f2809e821d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/zamba/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_zamba import *
+ from .modeling_zamba import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/zamba/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/zamba/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..77042a8c72f7c316408921abd511647907fa0df9
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/zamba/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/zamba/__pycache__/configuration_zamba.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/zamba/__pycache__/configuration_zamba.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5849a97bfa45c1af95ba7fa84aad51730fe08ddd
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/zamba/__pycache__/configuration_zamba.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/zamba/__pycache__/modeling_zamba.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/zamba/__pycache__/modeling_zamba.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d0cf052d647840822868acedb883234c6bc1509c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/zamba/__pycache__/modeling_zamba.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/zamba/configuration_zamba.py b/.venv/lib/python3.12/site-packages/transformers/models/zamba/configuration_zamba.py
new file mode 100644
index 0000000000000000000000000000000000000000..5432da30b90fb7fe828803a2949a0cf7f71b626f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/zamba/configuration_zamba.py
@@ -0,0 +1,115 @@
+# Copyright 2024 Zyphra Technologies and the HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Zamba model configuration"""
+
+import math
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="Zyphra/Zamba-7B-v1")
+@strict
+class ZambaConfig(PreTrainedConfig):
+ r"""
+ attention_hidden_size (`int`, *optional*):
+ Dimension of the hidden representations of the inputs to the Attention layer.
+ attention_head_dim (`int`, *optional*):
+ Dimension of the attention head in the Transformer decoder.
+ n_mamba_heads (`int`, *optional*, defaults to 2):
+ Number of mamba heads for each mamba layer.
+ hidden_mamba_act (`str` or `function`, *optional*, defaults to `"silu"`):
+ The non-linear activation function (function or string) in the mamba layer.
+ num_logits_to_keep (`int` or `None`, *optional*, defaults to 1):
+ Number of prompt logits to calculate during generation. If `None`, all logits will be calculated. If an
+ integer value, only last `num_logits_to_keep` logits will be calculated. Default is 1 because only the
+ logits of the last prompt token are needed for generation. For long sequences, the logits for the entire
+ sequence may use a lot of memory so, setting `num_logits_to_keep=1` will reduce memory footprint
+ significantly.
+ attn_layer_period (`int`, *optional*, defaults to 6):
+ Once in this many layers, we will have a shared attention layer
+ attn_layer_offset (`int`, *optional*, defaults to 4):
+ Offset of the shared attention layer
+ use_mamba_kernels (`bool`, *optional*, defaults to `True`):
+ Flag indicating whether or not to use the fast mamba kernels. These are available only if `mamba-ssm` and
+ `causal-conv1d` are installed, and the mamba modules are running on a CUDA device. Raises ValueError if
+ `True` and kernels are not available
+ mamba_dt_rank (`Union[int,str]`, *optional*, defaults to `"auto"`):
+ Rank of the mamba discretization projection matrix. `"auto"` means that it will default to `math.ceil(self.hidden_size / 16)`
+ """
+
+ model_type = "zamba"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ attribute_map = {"layer_types": "layers_block_type", "head_dim": "attention_head_dim"}
+
+ vocab_size: int = 32000
+ tie_word_embeddings: bool = True
+ hidden_size: int = 3712
+ attention_hidden_size: int | None = None
+ intermediate_size: int = 14848
+ num_hidden_layers: int = 76
+ num_attention_heads: int = 16
+ attention_head_dim: int | None = None
+ num_key_value_heads: int = 16
+ n_mamba_heads: int = 2
+ hidden_act: str = "gelu"
+ hidden_mamba_act: str = "silu"
+ initializer_range: float = 0.02
+ rms_norm_eps: float = 1e-5
+ use_cache: bool = True
+ num_logits_to_keep: int = 1
+ pad_token_id: int | None = 0
+ bos_token_id: int | None = 1
+ eos_token_id: int | list[int] | None = 2
+ max_position_embeddings: int = 4096
+ attention_dropout: float | int = 0.0
+ attn_layer_period: int = 6
+ attn_layer_offset: int = 4
+ use_mamba_kernels: bool = True
+ mamba_d_state: int = 16
+ mamba_d_conv: int = 4
+ mamba_expand: int = 2
+ mamba_dt_rank: str | int = "auto"
+ time_step_min: float = 0.001
+ time_step_max: float = 0.1
+ time_step_floor: float = 1e-4
+ mamba_conv_bias: bool = True
+ mamba_proj_bias: bool = False
+
+ def __post_init__(self, **kwargs):
+ self.attention_hidden_size = self.attention_hidden_size or 2 * self.hidden_size
+ self.attention_head_dim = self.attention_head_dim or 2 * self.hidden_size // self.num_attention_heads
+ self.mamba_dt_rank = math.ceil(self.hidden_size / 16) if self.mamba_dt_rank == "auto" else self.mamba_dt_rank
+ self.layers_block_type = self._layers_block_type(
+ self.num_hidden_layers, self.attn_layer_period, self.attn_layer_offset
+ )
+ super().__post_init__(**kwargs)
+
+ def validate_architecture(self):
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
+ if (self.mamba_expand * self.hidden_size) % self.n_mamba_heads != 0:
+ raise ValueError("`intermediate_size` should be divisible by `n_mamba_heads`.")
+
+ def _layers_block_type(self, num_hidden_layers, attn_layer_period, attn_layer_offset):
+ layers = [
+ "mamba",
+ "mamba",
+ "hybrid",
+ ] + ["hybrid" if i % attn_layer_period == attn_layer_offset else "mamba" for i in range(num_hidden_layers - 3)]
+ return layers
+
+
+__all__ = ["ZambaConfig"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/zamba/modeling_zamba.py b/.venv/lib/python3.12/site-packages/transformers/models/zamba/modeling_zamba.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec50bec6d400b6c7ea72e23ad9939924eac2c642
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/zamba/modeling_zamba.py
@@ -0,0 +1,996 @@
+# Copyright 2024 Zyphra Technologies and the HuggingFace Inc. team. All rights reserved.
+#
+# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
+# and OPT implementations in this library. It has been modified from its
+# original forms to accommodate minor architectural differences compared
+# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch Zamba model."""
+
+import math
+from collections.abc import Callable
+
+import torch
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache
+from ...generation import GenerationMixin
+from ...integrations.hub_kernels import lazy_load_kernel
+from ...masking_utils import create_causal_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
+from ...utils.generic import merge_with_config_defaults
+from ...utils.import_utils import resolve_internal_import
+from ...utils.output_capturing import capture_outputs
+from .configuration_zamba import ZambaConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+# Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Zamba
+class ZambaRMSNorm(nn.Module):
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
+ """
+ ZambaRMSNorm is equivalent to T5LayerNorm
+ """
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+ return self.weight * hidden_states.to(input_dtype)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
+
+
+# Copied from transformers.models.llama.modeling_llama.repeat_kv
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs,
+):
+ key_states = repeat_kv(key, module.num_key_value_groups)
+ value_states = repeat_kv(value, module.num_key_value_groups)
+
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+ attn_output = torch.matmul(attn_weights, value_states)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+class ZambaAttention(nn.Module):
+ """
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
+ and "Generating Long Sequences with Sparse Transformers".
+
+ Adapted from transformers.models.mistral.modeling_mistral.MistralAttention:
+ The input dimension here is attention_hidden_size = 2 * hidden_size, and head_dim = attention_hidden_size // num_heads.
+ The extra factor of 2 comes from the input being the concatenation of original_hidden_states with the output of the previous (mamba) layer
+ (see fig. 2 in https://huggingface.co/papers/2405.16712).
+ Additionally, replaced
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) with
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim/2)
+ """
+
+ def __init__(self, config: ZambaConfig, layer_idx: int):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+
+ self.attention_hidden_size = config.attention_hidden_size
+ self.head_dim = config.attention_head_dim
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.max_position_embeddings = config.max_position_embeddings
+ self.scaling = (self.head_dim / 2) ** -0.5
+ self.is_causal = True
+ self.attention_dropout = config.attention_dropout
+
+ self.q_proj = nn.Linear(config.attention_hidden_size, config.num_attention_heads * self.head_dim, bias=False)
+ self.k_proj = nn.Linear(config.attention_hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
+ self.v_proj = nn.Linear(config.attention_hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ layer_idx: int,
+ attention_mask: torch.Tensor | None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class ZambaMambaMixer(nn.Module):
+ """
+ Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
+ A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
+ ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
+ and is why Mamba is called **selective** state spaces)
+
+ This module differs from `transformers.models.mamba.modeling_mamba.MambaMixer` in two ways:
+ - Added multi-head: the output of `self.in_proj` is split into `self.n_mamba_heads` heads, and each head
+ undergoes an independent forward pass, identical to the original `MambaMixer`, up until the pre-activations of
+ `self.out_proj`. The pre-activations, coming from different mamba heads, are then concatenated and fed into `self.out_proj`.
+ """
+
+ def __init__(self, config: ZambaConfig, layer_idx):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.hidden_size = config.hidden_size
+ self.ssm_state_size = config.mamba_d_state
+ self.conv_kernel_size = config.mamba_d_conv
+ self.intermediate_size = config.mamba_expand * config.hidden_size
+ self.time_step_rank = config.mamba_dt_rank
+ self.n_mamba_heads = config.n_mamba_heads
+ self.mamba_head_dim = self.intermediate_size // self.n_mamba_heads
+ self.use_conv_bias = config.mamba_conv_bias
+ self.use_bias = config.mamba_proj_bias
+ self.conv1d = nn.Conv1d(
+ in_channels=self.intermediate_size,
+ out_channels=self.intermediate_size,
+ bias=self.use_conv_bias,
+ kernel_size=self.conv_kernel_size,
+ groups=self.intermediate_size,
+ padding=self.conv_kernel_size - 1,
+ )
+
+ self.activation = config.hidden_mamba_act
+ self.act = ACT2FN[config.hidden_mamba_act]
+
+ self.use_fast_kernels = config.use_mamba_kernels
+
+ # projection of the input hidden states
+ self.in_proj = nn.Linear(self.hidden_size, self.intermediate_size * 2, bias=self.use_bias)
+ # weight associated to the selective projection used to make dt, B and C input dependent
+ # each mamba head is processed independently
+ self.x_proj_weight = nn.Parameter(
+ torch.zeros(
+ self.n_mamba_heads,
+ self.time_step_rank + self.ssm_state_size * 2,
+ self.mamba_head_dim,
+ )
+ )
+ # time step projection (discretization)
+ self.dt_proj_weight = nn.Parameter(
+ (torch.zeros(self.n_mamba_heads, self.mamba_head_dim, self.time_step_rank) - 0.5)
+ * 2
+ / self.time_step_rank**0.5
+ )
+ self.dt_proj_bias = nn.Parameter(torch.zeros(self.n_mamba_heads, self.mamba_head_dim))
+
+ # S4D real initialization. These are not discretized!
+ # The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
+ A = torch.arange(1, self.ssm_state_size + 1, dtype=torch.float32)[None, :]
+ A = A.expand(self.intermediate_size, -1).contiguous()
+ self.A_log = nn.Parameter(torch.log(A).reshape(self.n_mamba_heads, self.mamba_head_dim, -1))
+ self.D = nn.Parameter(torch.ones(self.n_mamba_heads, self.mamba_head_dim))
+ self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=self.use_bias)
+
+ global causal_conv1d, causal_conv1d_update, causal_conv1d_fn
+ causal_conv1d = lazy_load_kernel("causal-conv1d")
+ causal_conv1d_update = getattr(causal_conv1d, "causal_conv1d_update", None)
+ causal_conv1d_fn = getattr(causal_conv1d, "causal_conv1d_fn", None)
+
+ global mamba_ssm, selective_state_update, selective_scan_fn, mamba_inner_fn
+ mamba_ssm = lazy_load_kernel("mamba-ssm")
+ selective_state_update = resolve_internal_import(
+ mamba_ssm, chained_path="ops.triton.selective_state_update.selective_state_update"
+ )
+ selective_scan_fn = getattr(mamba_ssm, "selective_scan_fn", None)
+ mamba_inner_fn = getattr(mamba_ssm, "mamba_inner_fn", None)
+
+ global is_fast_path_available
+ is_fast_path_available = all(
+ (selective_state_update, selective_scan_fn, causal_conv1d_fn, causal_conv1d_update, mamba_inner_fn)
+ )
+
+ if not is_fast_path_available:
+ logger.warning_once(
+ "The fast path is not available because one of `(selective_state_update, selective_scan_fn, causal_conv1d_fn, causal_conv1d_update, mamba_inner_fn)`"
+ " is None. To install follow https://github.com/state-spaces/mamba/#installation and"
+ " https://github.com/Dao-AILab/causal-conv1d. If you want to use the naive implementation, set `use_mamba_kernels=False` in the model config"
+ )
+
+ def cuda_kernels_forward(
+ self, hidden_states: torch.Tensor, cache_params: Cache | None = None, attention_mask=None
+ ):
+ batch_size, seq_len, _ = hidden_states.shape
+ use_precomputed_states = cache_params is not None and cache_params.has_previous_state and seq_len == 1
+
+ # 1. Gated linear projection
+ projected_states = self.in_proj(hidden_states).transpose(1, 2)
+
+ hidden_states, gate = projected_states.view(batch_size, -1, 2, seq_len).chunk(2, dim=2)
+ hidden_states = hidden_states.squeeze(2).contiguous()
+ gate = gate.squeeze(2)
+ gate = gate.reshape(batch_size, self.n_mamba_heads, -1, seq_len).transpose(0, 1)
+
+ # 2. Convolution sequence transformation
+ conv_weights = self.conv1d.weight.view(self.conv1d.weight.size(0), self.conv1d.weight.size(2))
+ if use_precomputed_states:
+ hidden_states = causal_conv1d_update(
+ hidden_states.squeeze(-1),
+ cache_params.layers[self.layer_idx].conv_states,
+ conv_weights,
+ self.conv1d.bias,
+ self.activation,
+ )
+ hidden_states = hidden_states.unsqueeze(-1)
+ else:
+ if attention_mask is not None and not torch.all(attention_mask == 1):
+ hidden_states = hidden_states * attention_mask.unsqueeze(1)
+ if cache_params is not None:
+ conv_states = nn.functional.pad(hidden_states, (self.conv_kernel_size - hidden_states.shape[-1], 0))
+ conv_states = cache_params.update_conv_state(conv_states, self.layer_idx)
+ hidden_states = causal_conv1d_fn(hidden_states, conv_weights, self.conv1d.bias, activation=self.activation)
+ if attention_mask is not None and not torch.all(attention_mask == 1):
+ hidden_states = hidden_states * attention_mask.unsqueeze(1)
+
+ # 3. SSM sequence transformation
+ # 3.a. input varying initialization of time_step, B and C
+
+ hidden_states = hidden_states.reshape(-1, self.n_mamba_heads, self.mamba_head_dim, seq_len).transpose(0, 1)
+ ssm_parameters = (self.x_proj_weight[:, None, :, :] @ hidden_states).transpose(-1, -2)
+
+ time_step, B, C = torch.split(
+ ssm_parameters, [self.time_step_rank, self.ssm_state_size, self.ssm_state_size], dim=-1
+ )
+
+ discrete_time_step = self.dt_proj_weight[:, None] @ time_step.transpose(-1, -2)
+
+ A = -torch.exp(self.A_log.float())
+
+ # 3.c perform the recurrence y ← SSM(A, B, C)(x)
+ time_proj_bias = self.dt_proj_bias.float() if self.dt_proj_bias is not None else None
+ scan_outputs = torch.empty((batch_size, 0, seq_len), device=hidden_states.device, dtype=hidden_states.dtype)
+
+ if use_precomputed_states:
+ for n in range(self.n_mamba_heads):
+ scan_outputs_ = selective_state_update(
+ cache_params.layers[self.layer_idx].recurrent_states[:, n],
+ hidden_states[n, ..., 0],
+ discrete_time_step[n, ..., 0],
+ A[n],
+ B[n, :, 0],
+ C[n, :, 0],
+ self.D[n],
+ gate[n, ..., 0],
+ time_proj_bias[n],
+ dt_softplus=True,
+ ).unsqueeze(-1)
+ scan_outputs = torch.cat((scan_outputs, scan_outputs_), dim=1)
+
+ else:
+ ssm_state = torch.empty(
+ (batch_size, 0, self.mamba_head_dim, self.ssm_state_size),
+ device=hidden_states.device,
+ dtype=hidden_states.dtype,
+ )
+ for n in range(self.n_mamba_heads):
+ scan_outputs_, ssm_state_ = selective_scan_fn(
+ hidden_states[n],
+ discrete_time_step[n],
+ A[n],
+ B[n].transpose(1, 2),
+ C[n].transpose(1, 2),
+ self.D[n].float(),
+ gate[n],
+ time_proj_bias[n],
+ delta_softplus=True,
+ return_last_state=True,
+ )
+ scan_outputs = torch.cat((scan_outputs, scan_outputs_), dim=1).contiguous()
+ ssm_state = torch.cat((ssm_state, ssm_state_.unsqueeze(1)), dim=1)
+ if ssm_state is not None and cache_params is not None:
+ cache_params.update_recurrent_state(ssm_state, self.layer_idx)
+
+ # 4. Final linear projection
+ contextualized_states = self.out_proj(scan_outputs.transpose(1, 2))
+ return contextualized_states
+
+ def slow_forward(self, input_states, cache_params: Cache | None = None, attention_mask=None):
+ batch_size, seq_len, _ = input_states.shape
+ dtype = input_states.dtype
+ # 1. Gated linear projection
+ projected_states = self.in_proj(input_states).transpose(1, 2)
+
+ hidden_states, gate = projected_states.view(batch_size, -1, 2, seq_len).chunk(2, dim=2)
+ hidden_states = hidden_states.squeeze(2).contiguous()
+ gate = gate.squeeze(2)
+ gate = gate.reshape(batch_size, self.n_mamba_heads, -1, seq_len).transpose(0, 1)
+
+ if cache_params is not None and cache_params.has_previous_state(self.layer_idx):
+ # In training mode, we don't want to perform in-place operations on ssm_state so we can compute the backwards pass
+ ssm_state = cache_params.layers[self.layer_idx].recurrent_states.clone()
+ else:
+ ssm_state = torch.zeros(
+ (batch_size, self.n_mamba_heads, self.mamba_head_dim, self.ssm_state_size),
+ device=hidden_states.device,
+ dtype=dtype,
+ )
+
+ # 2. Convolution sequence transformation
+ if cache_params is not None:
+ if cache_params.has_previous_state(self.layer_idx) and seq_len == 1:
+ conv_state = cache_params.update_conv_state(hidden_states, self.layer_idx)
+ hidden_states = torch.sum(conv_state * self.conv1d.weight[:, 0, :], dim=-1)
+ if self.use_conv_bias:
+ hidden_states += self.conv1d.bias
+ hidden_states = self.act(hidden_states).to(dtype).unsqueeze(-1)
+ else:
+ if attention_mask is not None:
+ hidden_states = hidden_states * attention_mask[:, -hidden_states.shape[-1] :].unsqueeze(1)
+ conv_state = nn.functional.pad(hidden_states, (self.conv_kernel_size - hidden_states.shape[-1], 0))
+ conv_state = cache_params.update_conv_state(conv_state, self.layer_idx)
+ hidden_states = self.act(self.conv1d(hidden_states)[..., :seq_len])
+ if attention_mask is not None:
+ hidden_states = hidden_states * attention_mask[:, -hidden_states.shape[-1] :].unsqueeze(1)
+ else:
+ if attention_mask is not None:
+ hidden_states = hidden_states * attention_mask.unsqueeze(1)
+ hidden_states = self.act(self.conv1d(hidden_states)[..., :seq_len])
+ if attention_mask is not None:
+ hidden_states = hidden_states * attention_mask.unsqueeze(1)
+
+ # 3. State Space Model sequence transformation
+ # 3.a. Selection: [batch, seq_len, self.time_step_rank + self.ssm_state_size * 2]
+ hidden_states = hidden_states.reshape(-1, self.n_mamba_heads, self.mamba_head_dim, seq_len).transpose(0, 1)
+ ssm_parameters = (self.x_proj_weight[:, None, :, :] @ hidden_states).transpose(-1, -2)
+
+ time_step, B, C = torch.split(
+ ssm_parameters, [self.time_step_rank, self.ssm_state_size, self.ssm_state_size], dim=-1
+ )
+ discrete_time_step = (self.dt_proj_weight[:, None] @ time_step.transpose(-1, -2)) + self.dt_proj_bias[
+ :, None, :, None
+ ]
+
+ discrete_time_step = nn.functional.softplus(discrete_time_step)
+
+ # 3.b. Discretization: B and C to [batch, seq_len, intermediate_size, ssm_state_size] (SRAM)
+ A = -torch.exp(self.A_log.float())
+ discrete_A = torch.exp(A[:, None, :, None, :] * discrete_time_step[:, :, :, :, None])
+ discrete_B = discrete_time_step[:, :, :, :, None] * B[:, :, None, :, :].float()
+ deltaB_u = discrete_B * hidden_states[:, :, :, :, None].float()
+ # 3.c perform the recurrence y ← SSM(A, B, C)(x)
+ scan_outputs = []
+ for i in range(seq_len):
+ ssm_state = discrete_A[:, :, :, i, :].transpose(0, 1) * ssm_state + deltaB_u[:, :, :, i, :].transpose(0, 1)
+ scan_output = torch.matmul(ssm_state.transpose(0, 1).to(dtype), C[:, :, i, :].unsqueeze(-1))
+ scan_outputs.append(scan_output[:, :, :, 0])
+ scan_output = torch.stack(scan_outputs, dim=-1)
+ scan_output = scan_output + (hidden_states * self.D[:, None, :, None])
+ scan_output = scan_output * self.act(gate)
+
+ if cache_params is not None:
+ cache_params.update_recurrent_state(ssm_state, self.layer_idx)
+
+ # 4. Final linear projection
+ contextualized_states = self.out_proj(
+ scan_output.transpose(0, 1).reshape(batch_size, -1, seq_len).transpose(1, 2)
+ )
+ return contextualized_states
+
+ def forward(self, hidden_states, cache_params: Cache | None = None, attention_mask=None, **kwargs):
+ is_fast_path_available = all(
+ (selective_state_update, selective_scan_fn, causal_conv1d_fn, causal_conv1d_update, mamba_inner_fn)
+ )
+
+ if self.use_fast_kernels:
+ if not is_fast_path_available or "cuda" not in self.x_proj_weight.device.type:
+ raise ValueError(
+ "Fast Mamba kernels are not available. Make sure to they are installed and that "
+ "the mamba module is on a CUDA device. lease run 'pip install causal-conv1d>=1.2.0' "
+ "and 'pip install mamba-ssm', or set use_mamba_kernels=False in the model's config."
+ )
+ return self.cuda_kernels_forward(hidden_states, cache_params, attention_mask=attention_mask)
+ return self.slow_forward(hidden_states, cache_params, attention_mask=attention_mask)
+
+
+# Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Zamba
+class ZambaMLP(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = config.intermediate_size
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(self, x):
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
+ return down_proj
+
+
+class ZambaAttentionDecoderLayer(nn.Module):
+ def __init__(self, config: ZambaConfig, layer_idx: int | None = None):
+ super().__init__()
+ self.self_attn = ZambaAttention(config, layer_idx)
+
+ self.feed_forward = ZambaMLP(config)
+ self.input_layernorm = ZambaRMSNorm(config.attention_hidden_size, eps=config.rms_norm_eps)
+ self.pre_ff_layernorm = ZambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ original_hidden_states: torch.Tensor,
+ layer_idx: int,
+ attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): output of previous Mamba layer of shape `(batch, seq_len, embed_dim)`
+ original_hidden_states (`torch.FloatTensor`): word embedding output of shape `(batch, seq_len, embed_dim)`.
+ This is concatenated with `hidden_states` (which is the output of the previous (mamba) layer). The
+ concatenated tensor is then used as input of the pre-attention RMSNorm
+ (see fig. 2 in https://huggingface.co/papers/2405.16712).
+ layer_idx (`int`): layer_idx in the forward pass. Used to distinguish Zamba's tied transformer layers.
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
+ `(batch, sequence_length)` where padding elements are indicated by 0.
+ past_key_values (`Cache`, *optional*): cached past key and value projection states
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
+ (see `past_key_values`).
+ """
+ hidden_states = torch.concatenate([hidden_states, original_hidden_states], dim=-1)
+ hidden_states = self.input_layernorm(hidden_states)
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ layer_idx=layer_idx,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ **kwargs,
+ )
+ # feed-forward (MLP)
+ hidden_states = self.pre_ff_layernorm(hidden_states)
+ hidden_states = self.feed_forward(hidden_states)
+
+ return hidden_states
+
+
+class ZambaMambaDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: ZambaConfig, layer_idx: int):
+ super().__init__()
+ self.mamba = ZambaMambaMixer(config=config, layer_idx=layer_idx)
+ self.input_layernorm = ZambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.layer_idx = layer_idx
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ original_hidden_states: torch.Tensor | None = None,
+ layer_idx: int | None = None,
+ attention_mask: torch.Tensor | None = None,
+ causal_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ position_ids: torch.LongTensor | None = None,
+ transformer_hidden_states: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
+ `(batch, sequence_length)` where padding elements are indicated by 0.
+ past_key_values (`Cache`, *optional*): cached past key and value projection states
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
+ (see `past_key_values`).
+ """
+
+ residual = hidden_states
+
+ # `transformer_hidden_states` is the output from shared transformer + linear layer (see fig. 2 in https://huggingface.co/papers/2405.16712).
+ # `transformer_hidden_states` is then added to the input to the mamba layer below (as described in eq. (6) of https://huggingface.co/papers/2405.16712).
+ hidden_states = (
+ hidden_states + transformer_hidden_states if transformer_hidden_states is not None else hidden_states
+ )
+ hidden_states = self.input_layernorm(hidden_states)
+
+ hidden_states = self.mamba(
+ hidden_states=hidden_states,
+ cache_params=past_key_values,
+ attention_mask=attention_mask,
+ **kwargs,
+ )
+ # residual connection after mamba
+ hidden_states = residual + hidden_states
+
+ return hidden_states
+
+
+class ZambaHybridLayer(GradientCheckpointingLayer):
+ def __init__(self, shared_transf: ZambaAttentionDecoderLayer, linear: nn.Linear, mamba: ZambaMambaDecoderLayer):
+ super().__init__()
+ self.shared_transf = shared_transf
+ self.linear = linear
+ self.mamba_decoder = mamba
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ original_hidden_states: torch.Tensor | None = None,
+ layer_idx: int | None = None,
+ attention_mask: torch.Tensor | None = None,
+ causal_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
+ original_hidden_states (`torch.FloatTensor`): word embedding output that will be concatenated with
+ hidden activations to form the input of the shared transformer layer.
+ layer_idx (`int`): layer number.
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
+ `(batch, sequence_length)` where padding elements are indicated by 0.
+ past_key_values (`Cache`, *optional*): cached past key and value projection states
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
+ (see `past_key_values`).
+ """
+
+ transformer_hidden_states = self.shared_transf(
+ hidden_states,
+ original_hidden_states=original_hidden_states,
+ layer_idx=layer_idx,
+ attention_mask=causal_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ **kwargs,
+ )
+ transformer_hidden_states = self.linear(transformer_hidden_states)
+
+ hidden_states = self.mamba_decoder(
+ hidden_states,
+ transformer_hidden_states=transformer_hidden_states,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ return hidden_states
+
+
+@auto_docstring
+class ZambaPreTrainedModel(PreTrainedModel):
+ config: ZambaConfig
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["ZambaHybridLayer", "ZambaMambaDecoderLayer"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _is_stateful = True
+ _can_record_outputs = {
+ "hidden_states": ZambaMambaDecoderLayer,
+ "attentions": ZambaAttention,
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ std = self.config.initializer_range
+ super()._init_weights(module)
+ if isinstance(module, ZambaMambaMixer):
+ init.normal_(module.x_proj_weight, mean=0.0, std=std)
+ dt_init_std = self.config.mamba_dt_rank**-0.5
+ init.uniform_(module.dt_proj_weight, -dt_init_std, dt_init_std)
+
+ mamba_head_dim = self.config.mamba_expand * self.config.hidden_size // self.config.n_mamba_heads
+ dt = torch.exp(
+ torch.rand(self.config.n_mamba_heads, mamba_head_dim)
+ * (math.log(self.config.time_step_max) - math.log(self.config.time_step_min))
+ + math.log(self.config.time_step_min)
+ ).clamp(min=self.config.time_step_floor)
+ # # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
+ init.copy_(module.dt_proj_bias, inv_dt)
+
+ A = torch.arange(1, module.ssm_state_size + 1, dtype=torch.float32)[None, :]
+ A = A.expand(module.intermediate_size, -1).contiguous()
+ init.copy_(module.A_log, torch.log(A).reshape(module.n_mamba_heads, module.mamba_head_dim, -1))
+ init.ones_(module.D)
+
+
+@auto_docstring
+class ZambaModel(ZambaPreTrainedModel):
+ """
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`ZambaDecoderLayer`]
+
+ Args:
+ config: ZambaConfig
+ """
+
+ def __init__(self, config: ZambaConfig):
+ super().__init__(config)
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
+ self.layers_block_type = config.layers_block_type
+ layers = []
+ self._tied_weights_keys = None
+ for layer_id, layer_type in enumerate(self.layers_block_type):
+ mamba = ZambaMambaDecoderLayer(config, layer_idx=layer_id)
+ if layer_type == "hybrid":
+ linear = nn.Linear(self.config.hidden_size, self.config.hidden_size, bias=False)
+ layers.append(ZambaHybridLayer(ZambaAttentionDecoderLayer(config), linear, mamba))
+ if self._tied_weights_keys is None:
+ self._tied_weights_keys = {
+ rf"layers.(?!{layer_id}\.)\d+.shared_transf": f"layers.{layer_id}.shared_transf"
+ }
+ else:
+ layers.append(mamba)
+ self.layers = nn.ModuleList(layers)
+
+ self.final_layernorm = ZambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ self.gradient_checkpointing = False
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError(
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
+ )
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ hidden_states = inputs_embeds
+
+ original_hidden_states = torch.clone(inputs_embeds)
+ # original_hidden_states: word embedding output that will be concatenated with hidden activations to form the input of the shared transformer layer
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(hidden_states.shape[1], device=hidden_states.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ causal_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_ids=position_ids,
+ )
+
+ for layer_idx, layer in enumerate(self.layers):
+ hidden_states = layer(
+ hidden_states,
+ original_hidden_states,
+ layer_idx,
+ attention_mask,
+ causal_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = self.final_layernorm(hidden_states)
+
+ return BaseModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values if use_cache else None,
+ )
+
+
+# Adapted from transformers.models.jamba.modeling_jamba.JambaForCausalLM with Jamba->Zamba, JAMBA->ZAMBA
+class ZambaForCausalLM(ZambaPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
+
+ def __init__(self, config: ZambaConfig):
+ super().__init__(config)
+ self.model = ZambaModel(config)
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | CausalLMOutputWithPast:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, ZambaForCausalLM
+
+ >>> model = ZambaForCausalLM.from_pretrained("Zyphra/Zamba-7B-v1")
+ >>> tokenizer = AutoTokenizer.from_pretrained("Zyphra/Zamba-7B-v1")
+
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
+ ```"""
+ outputs: BaseModelOutputWithPast = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(
+ logits,
+ labels,
+ self.vocab_size,
+ **kwargs,
+ )
+
+ return CausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+ def prepare_inputs_for_generation(
+ self,
+ input_ids,
+ past_key_values=None,
+ attention_mask=None,
+ inputs_embeds=None,
+ position_ids=None,
+ use_cache=True,
+ is_first_iteration=False,
+ **kwargs,
+ ):
+ kwargs["logits_to_keep"] = self.config.num_logits_to_keep
+ model_inputs = super().prepare_inputs_for_generation(
+ input_ids,
+ past_key_values=past_key_values,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ position_ids=position_ids,
+ use_cache=use_cache,
+ is_first_iteration=is_first_iteration,
+ **kwargs,
+ )
+
+ return model_inputs
+
+
+@auto_docstring(
+ custom_intro="""
+ The Zamba Model with a sequence classification head on top (linear layer).
+
+ [`ZambaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
+ (e.g. GPT-2) do.
+
+ Since it does classification on the last token, it requires to know the position of the last token. If a
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
+ each row of the batch).
+ """
+)
+class ZambaForSequenceClassification(ZambaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.model = ZambaModel(config)
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | SequenceClassifierOutputWithPast:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ transformer_outputs: BaseModelOutputWithPast = self.model(
+ input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+ hidden_states = transformer_outputs.last_hidden_state
+ logits = self.score(hidden_states)
+
+ if input_ids is not None:
+ batch_size = input_ids.shape[0]
+ else:
+ batch_size = inputs_embeds.shape[0]
+
+ if self.config.pad_token_id is None and batch_size != 1:
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
+ if self.config.pad_token_id is None:
+ last_non_pad_token = -1
+ elif input_ids is not None:
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
+ else:
+ last_non_pad_token = -1
+ logger.warning_once(
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
+ )
+
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
+
+ loss = None
+ if labels is not None:
+ labels = labels.to(logits.device)
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(pooled_logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(pooled_logits, labels)
+
+ return SequenceClassifierOutputWithPast(
+ loss=loss,
+ logits=pooled_logits,
+ past_key_values=transformer_outputs.past_key_values,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+__all__ = ["ZambaForCausalLM", "ZambaForSequenceClassification", "ZambaModel", "ZambaPreTrainedModel"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/zamba2/__init__.py b/.venv/lib/python3.12/site-packages/transformers/models/zamba2/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..00db458c72ebd5513d8e8cf1b186f49886745a2a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/zamba2/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_zamba2 import *
+ from .modeling_zamba2 import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/zamba2/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/zamba2/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..43926daeab0091c9bb283613830d19ddd8dd1ee8
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/zamba2/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/zamba2/__pycache__/configuration_zamba2.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/zamba2/__pycache__/configuration_zamba2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f55e3b413fb25e1f3e53e3d9d4130ac4b7024cbd
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/zamba2/__pycache__/configuration_zamba2.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/zamba2/__pycache__/modeling_zamba2.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/zamba2/__pycache__/modeling_zamba2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..10fd0856052caa9155b4c43efefcd63e543161cd
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/zamba2/__pycache__/modeling_zamba2.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/zamba2/__pycache__/modular_zamba2.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/zamba2/__pycache__/modular_zamba2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a70a6e4ad52e168f9998bbb2d31b747df9a735e4
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/zamba2/__pycache__/modular_zamba2.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/zamba2/configuration_zamba2.py b/.venv/lib/python3.12/site-packages/transformers/models/zamba2/configuration_zamba2.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d754d1ecf7a704af552e5fcc60dff3bdfe7feed
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/zamba2/configuration_zamba2.py
@@ -0,0 +1,142 @@
+# Copyright 2024 Zyphra Technologies and the HuggingFace Inc. team. All rights reserved.
+#
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...modeling_rope_utils import RopeParameters
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="Zyphra/Zamba2-2.7B")
+@strict
+class Zamba2Config(PreTrainedConfig):
+ r"""
+ mamba_ngroups (`int`, *optional*, defaults to 1):
+ Number of groups for the evolution matrices of mamba 2.
+ n_mamba_heads (`int`, *optional*, defaults to 8):
+ Number of heads for the evolution matrices of mamba 2.
+ use_mamba_kernels (`bool`, *optional*, defaults to `True`):
+ Flag indicating whether or not to use the fast mamba kernels.
+ use_conv_bias (`bool`, *optional*, defaults to `True`):
+ Whether or not to use bias in the convolution layer of the mixer block.
+ chunk_size (`int`, *optional*, defaults to 256):
+ Size of the chunks that will comprise the sequence.
+ use_mem_eff_path (`bool`, *optional*, defaults to `False`):
+ Whether or not to use the fused conv1d and scan in mamba2 layers.
+ add_bias_linear (`bool`, *optional*, defaults to `False`):
+ Flag indicating whether or not to use bias in various layers
+ num_mem_blocks (`int`, *optional*, defaults to 1):
+ Number of unshared transformer blocks.
+ use_shared_attention_adapter (`bool`, *optional*, defaults to `False`):
+ If True, unshared adapters (formally the same as LoRA but used in the base model) will be added to the q, k, v projectors in the shared attention layers.
+ adapter_rank (`int`, *optional*, defaults to 128):
+ Rank of the adapter in the shared MLP and shared attention layers.
+ use_mem_rope (`bool`, *optional*, defaults to `False`):
+ If True, includes RoPE in the shared attention layers.
+ num_logits_to_keep (`int` or `None`, *optional*, defaults to 1):
+ Number of prompt logits to calculate during generation. If `None`, all logits will be calculated. If an
+ integer value, only last `num_logits_to_keep` logits will be calculated. Default is 1 because only the
+ logits of the last prompt token are needed for generation. For long sequences, the logits for the entire
+ sequence may use a lot of memory so, setting `num_logits_to_keep=1` will reduce memory footprint
+ significantly.
+ use_long_context (`bool`, *optional*, defaults to `False`):
+ Activates the context-extended version of Zamba by modifying RoPE.
+
+ Example:
+ ```python
+ >>> from transformers import Zamba2Model, Zamba2Config
+ >>> # Initializing a Zamba2-2.7B style configuration
+ >>> configuration = Zamba2Config()
+ >>> # Initializing a model from the Zamba2-2.7B style configuration
+ >>> model = Zamba2Model(configuration)
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "zamba2"
+ attribute_map = {"layer_types": "layers_block_type", "head_dim": "attention_head_dim"}
+ keys_to_ignore_at_inference = ["past_key_values"]
+
+ vocab_size: int = 32000
+ max_position_embeddings: int = 4096
+ hidden_size: int = 2560
+ num_hidden_layers: int = 54
+ layers_block_type: list[str] | None = None
+ mamba_d_state: int = 64
+ mamba_d_conv: int = 4
+ mamba_expand: int = 2
+ mamba_ngroups: int = 1
+ time_step_min: float = 0.001
+ time_step_max: float = 0.1
+ time_step_floor: float = 1e-4
+ time_step_limit: list[float] | tuple[float, ...] | None = None
+ n_mamba_heads: int = 8
+ use_mamba_kernels: bool = True
+ use_conv_bias: bool = True
+ chunk_size: int = 256
+ use_mem_eff_path: bool = False
+ add_bias_linear: bool = False
+ intermediate_size: int | None = None
+ hidden_act: str = "gelu"
+ num_attention_heads: int = 32
+ num_key_value_heads: int | None = None
+ attention_dropout: float | int = 0.0
+ num_mem_blocks: int = 1
+ use_shared_attention_adapter: bool = False
+ adapter_rank: int = 128
+ use_mem_rope: bool = False
+ rope_parameters: RopeParameters | dict | None = None
+ initializer_range: float = 0.02
+ rms_norm_eps: float = 1e-5
+ use_cache: bool = True
+ num_logits_to_keep: int = 1
+ pad_token_id: int | None = 0
+ bos_token_id: int | None = 1
+ eos_token_id: int | list[int] | None = 2
+ use_long_context: bool = False
+ tie_word_embeddings: bool = True
+
+ def __post_init__(self, **kwargs):
+ self.intermediate_size = self.intermediate_size or 4 * self.hidden_size
+ self.attention_hidden_size = 2 * self.hidden_size
+ self.attention_head_dim = 2 * self.hidden_size // self.num_attention_heads
+ self.mamba_headdim = int(self.mamba_expand * self.hidden_size) // self.n_mamba_heads
+ if self.use_long_context:
+ self.max_position_embeddings = 16384
+
+ if self.num_key_value_heads is None:
+ self.num_key_value_heads = self.num_attention_heads
+
+ self.kv_channels = self.hidden_size // self.num_attention_heads
+ self.num_query_groups = self.num_attention_heads
+
+ # Below, "mamba" stands for mamba layer, "hybrid" stands for hybrid layer (composed by a shared transformer followed by mamba layer)
+ if self.layers_block_type is None:
+ self.layers_block_type = (
+ ["mamba"]
+ + (["mamba"] * 5 + ["hybrid"]) * 7
+ + ["mamba"] * 4
+ + ["hybrid"]
+ + ["mamba"] * 3
+ + ["hybrid"]
+ + ["mamba"] * 2
+ )
+ self.hybrid_layer_ids = [index for index, type in enumerate(self.layers_block_type) if type == "hybrid"]
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["Zamba2Config"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/zamba2/modeling_zamba2.py b/.venv/lib/python3.12/site-packages/transformers/models/zamba2/modeling_zamba2.py
new file mode 100644
index 0000000000000000000000000000000000000000..be8fb86a3c686f2b437047390feff713e85be799
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/zamba2/modeling_zamba2.py
@@ -0,0 +1,1447 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/zamba2/modular_zamba2.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_zamba2.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2024 Zyphra Technologies and the HuggingFace Inc. team. All rights reserved.
+#
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import math
+from collections.abc import Callable
+from itertools import cycle
+from typing import Optional
+
+import torch
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache
+from ...generation import GenerationMixin
+from ...integrations import use_kernel_func_from_hub
+from ...integrations.hub_kernels import lazy_load_kernel
+from ...masking_utils import create_causal_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, is_torchdynamo_compiling, logging
+from ...utils.generic import maybe_autocast, merge_with_config_defaults
+from ...utils.import_utils import resolve_internal_import
+from ...utils.output_capturing import capture_outputs
+from .configuration_zamba2 import Zamba2Config
+
+
+logger = logging.get_logger(__name__)
+
+
+class Zamba2RMSNormGated(torch.nn.Module):
+ def __init__(self, hidden_size, group_size, eps=1e-6):
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+ self.group_size = group_size
+
+ def forward(self, hidden_states, gate=None):
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ if gate is not None:
+ hidden_states = hidden_states * nn.functional.silu(gate.to(torch.float32))
+ *prefix_dims, last_dim = hidden_states.shape
+ group_count = last_dim // self.group_size
+ hidden_states_group = hidden_states.view(*prefix_dims, group_count, self.group_size)
+ variance = hidden_states_group.pow(2).mean(-1, keepdim=True)
+ hidden_states_group = hidden_states_group * torch.rsqrt(variance + self.variance_epsilon)
+ hidden_states = hidden_states_group.view(*prefix_dims, group_count * self.group_size)
+ return self.weight * hidden_states.to(input_dtype)
+
+
+class Zamba2RMSNorm(nn.Module):
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
+ """
+ Zamba2RMSNorm is equivalent to T5LayerNorm
+ """
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+ return self.weight * hidden_states.to(input_dtype)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
+
+
+class Zamba2RotaryEmbedding(nn.Module):
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
+
+ def __init__(self, config: Zamba2Config, device=None):
+ super().__init__()
+ self.max_seq_len_cached = config.max_position_embeddings
+ self.original_max_seq_len = config.max_position_embeddings
+
+ self.config = config
+
+ self.rope_type = self.config.rope_parameters["rope_type"]
+ rope_init_fn: Callable = self.compute_default_rope_parameters
+ if self.rope_type != "default":
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
+
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
+
+ @staticmethod
+ def compute_default_rope_parameters(
+ config: Zamba2Config | None = None,
+ device: Optional["torch.device"] = None,
+ seq_len: int | None = None,
+ ) -> tuple["torch.Tensor", float]:
+ """
+ Computes the inverse frequencies according to the original RoPE implementation
+ Args:
+ config ([`~transformers.PreTrainedConfig`]):
+ The model configuration.
+ device (`torch.device`):
+ The device to use for initialization of the inverse frequencies.
+ seq_len (`int`, *optional*):
+ The current sequence length. Unused for this type of RoPE.
+ Returns:
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
+ """
+ base = config.rope_parameters["rope_theta"]
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
+
+ attention_factor = 1.0 # Unused in this type of RoPE
+
+ # Compute the inverse frequencies
+ inv_freq = 1.0 / (
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
+ )
+ return inv_freq, attention_factor
+
+ @torch.no_grad()
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
+ def forward(self, x, position_ids):
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
+ position_ids_expanded = position_ids[:, None, :].float()
+
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
+ emb = torch.cat((freqs, freqs), dim=-1)
+ cos = emb.cos() * self.attention_scaling
+ sin = emb.sin() * self.attention_scaling
+
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
+
+
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs,
+):
+ key_states = repeat_kv(key, module.num_key_value_groups)
+ value_states = repeat_kv(value, module.num_key_value_groups)
+
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+ attn_output = torch.matmul(attn_weights, value_states)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., : x.shape[-1] // 2]
+ x2 = x[..., x.shape[-1] // 2 :]
+ return torch.cat((-x2, x1), dim=-1)
+
+
+@use_kernel_func_from_hub("rotary_pos_emb")
+def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+ q_embed = (q * cos) + (rotate_half(q) * sin)
+ k_embed = (k * cos) + (rotate_half(k) * sin)
+ return q_embed, k_embed
+
+
+class Zamba2Attention(nn.Module):
+ """
+ Multi-headed attention from 'Attention Is All You Need' paper.
+
+ Adapted from transformers.models.mistral.modeling_mistral.MistralAttention:
+ The input dimension here is attention_hidden_size = 2 * hidden_size, and head_dim = attention_hidden_size // num_heads.
+ The extra factor of 2 comes from the input being the concatenation of original_hidden_states with the output of the previous (mamba) layer
+ (see fig. 2 in https://huggingface.co/papers/2405.16712).
+ Additionally, replaced
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) with
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim/2)
+ Finally, this attention layer contributes to tied transformer blocks aimed to increasing compute without increasing model size. Because this
+ layer is tied, un-tied adapters (formally the same as LoRA but used in the base model) modules are added to the q, k, v projectors to increase
+ expressivity with a small memory overhead (see Fig. 2 of https://huggingface.co/papers/2411.15242).
+ """
+
+ def __init__(
+ self,
+ config: Zamba2Config,
+ layer_idx: int | None = None,
+ num_fwd_mem_blocks: int | None = None,
+ block_id: int | None = None,
+ ):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+
+ self.attention_hidden_size = config.attention_hidden_size
+ self.head_dim = config.attention_head_dim
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.max_position_embeddings = config.max_position_embeddings
+ self.scaling = (self.head_dim / 2) ** -0.5
+ self.is_causal = True
+ self.attention_dropout = config.attention_dropout
+
+ self.q_proj = nn.Linear(config.attention_hidden_size, config.num_attention_heads * self.head_dim, bias=False)
+ self.k_proj = nn.Linear(config.attention_hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
+ self.v_proj = nn.Linear(config.attention_hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
+ self.num_fwd_mem_blocks = num_fwd_mem_blocks
+ self.layer_block_map = config.hybrid_layer_ids
+ self.block_id = block_id
+
+ if config.use_shared_attention_adapter:
+ self.linear_q_adapter_list = nn.ModuleList([])
+ self.linear_k_adapter_list = nn.ModuleList([])
+ self.linear_v_adapter_list = nn.ModuleList([])
+
+ for i in range(self.num_fwd_mem_blocks):
+ if i % config.num_mem_blocks == block_id:
+ linear_q_adapter = nn.Sequential(
+ nn.Linear(self.attention_hidden_size, self.config.adapter_rank, bias=False),
+ nn.Linear(self.config.adapter_rank, self.attention_hidden_size, bias=False),
+ )
+ linear_k_adapter = nn.Sequential(
+ nn.Linear(self.attention_hidden_size, self.config.adapter_rank, bias=False),
+ nn.Linear(self.config.adapter_rank, self.attention_hidden_size, bias=False),
+ )
+ linear_v_adapter = nn.Sequential(
+ nn.Linear(self.attention_hidden_size, self.config.adapter_rank, bias=False),
+ nn.Linear(self.config.adapter_rank, self.attention_hidden_size, bias=False),
+ )
+ else:
+ linear_q_adapter = nn.Identity()
+ linear_k_adapter = nn.Identity()
+ linear_v_adapter = nn.Identity()
+ self.linear_q_adapter_list.append(linear_q_adapter)
+ self.linear_k_adapter_list.append(linear_k_adapter)
+ self.linear_v_adapter_list.append(linear_v_adapter)
+
+ self.layer_dic = {value: index for index, value in enumerate(self.layer_block_map)}
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ layer_idx: int,
+ attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_proj(hidden_states)
+ key_states = self.k_proj(hidden_states)
+ value_states = self.v_proj(hidden_states)
+ if self.config.use_shared_attention_adapter:
+ adapter_layer_idx = self.layer_dic[layer_idx]
+ query_states = query_states + self.linear_q_adapter_list[adapter_layer_idx](hidden_states)
+ key_states = key_states + self.linear_k_adapter_list[adapter_layer_idx](hidden_states)
+ value_states = value_states + self.linear_v_adapter_list[adapter_layer_idx](hidden_states)
+
+ query_states = query_states.view(hidden_shape).transpose(1, 2)
+ key_states = key_states.view(hidden_shape).transpose(1, 2)
+ value_states = value_states.view(hidden_shape).transpose(1, 2)
+
+ if self.config.use_mem_rope:
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+# Helper methods for segment sum computation
+
+
+def pad_tensor_by_size(input_tensor: torch.Tensor, pad_size: int):
+ """
+ Padding x tensor with `pad_size` on the seq_len dim (dim=1)
+
+ Assumes that we only have tensors of either size 4 or 3
+ """
+ pad_shape = (0, 0, 0, 0, 0, pad_size, 0, 0) if len(input_tensor.shape) == 4 else (0, 0, 0, pad_size, 0, 0)
+
+ return torch.nn.functional.pad(input_tensor, pad_shape, mode="constant", value=0)
+
+
+def reshape_into_chunks(input_tensor, pad_size, chunk_size):
+ """
+ Padding input_tensor with `pad_size` on the seq_len dim (dim=1) and
+ simultaneously splitting it into chunk sequences.
+
+ Assumes that we only have tensors of either size 4 or 3
+ """
+ # [bsz, seq_len, ...] -> [bsz, seq_len multiple of chunk_size, ...]
+ input_tensor = pad_tensor_by_size(input_tensor, pad_size)
+
+ if len(input_tensor.shape) == 3:
+ # [bsz, seq_len multiple of chunk_size, num_heads] -> [bsz, -1, chunk_size, num_heads]
+ return input_tensor.reshape(input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2])
+ else:
+ # [bsz, seq_len multiple of chunk_size, num_heads, head_dim or state_size] -> [bsz, -1, chunk_size, num_heads, head_dim or state_size]
+ return input_tensor.reshape(
+ input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2], input_tensor.shape[3]
+ )
+
+
+def segment_sum(input_tensor):
+ """
+ More stable segment sum calculation. Uses cumulative sums and masking instead of direct subtractions.
+ """
+ chunk_size = input_tensor.size(-1)
+ # 1. expand input tensor to have an additional dimension and repeat along that dimension
+ # [..., chunk_size] -> [..., chunk_size, chunk_size]
+ input_tensor = input_tensor[..., None].expand(*input_tensor.size(), chunk_size)
+ # 2. create a lower triangular mask with the diagonal set to 0 to 0 out elements above diag
+ mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=-1)
+ input_tensor = input_tensor.masked_fill(~mask, 0)
+ # 3. compute actual cumsum
+ tensor_segsum = torch.cumsum(input_tensor, dim=-2)
+
+ # 4. apply mask to keep only the lower triangular part of the cumulative sum result (incl diagonal this time)
+ mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=0)
+ tensor_segsum = tensor_segsum.masked_fill(~mask, -torch.inf)
+ return tensor_segsum
+
+
+class Zamba2MambaMixer(nn.Module):
+ """
+ Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
+ A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
+ ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
+ and is why Mamba is called **selective** state spaces)
+ """
+
+ def __init__(self, config: Zamba2Config, layer_idx: int | None = None):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.ssm_state_size = config.mamba_d_state
+ self.conv_kernel_size = config.mamba_d_conv
+ self.intermediate_size = int(config.mamba_expand * self.hidden_size)
+ self.layer_idx = layer_idx
+ self.use_conv_bias = config.use_conv_bias
+ self.activation = "silu"
+ self.act = nn.SiLU()
+ self.use_mem_eff_path = config.use_mem_eff_path
+
+ self.n_groups = config.mamba_ngroups
+ self.head_dim = config.mamba_headdim
+ self.num_heads = self.config.n_mamba_heads
+ self.chunk_size = config.chunk_size
+
+ self.time_step_limit = config.time_step_limit
+ self.time_step_min = config.time_step_min
+ self.time_step_max = config.time_step_max
+
+ self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size
+ self.conv1d = nn.Conv1d(
+ in_channels=self.conv_dim,
+ out_channels=self.conv_dim,
+ bias=True,
+ kernel_size=config.mamba_d_conv,
+ groups=self.conv_dim,
+ padding=config.mamba_d_conv - 1,
+ )
+
+ # projection of the input hidden states
+ projection_size = self.intermediate_size + self.conv_dim + self.num_heads
+ self.in_proj = nn.Linear(
+ self.hidden_size,
+ projection_size,
+ bias=config.add_bias_linear,
+ )
+ # selective projection used to make dt, B and C input dependent
+
+ # time step projection (discretization)
+ # instantiate once and copy inv_dt in init_weights of PretrainedModel
+ self.dt_bias = nn.Parameter(torch.ones(self.num_heads))
+
+ # S4D real initialization. These are not discretized!
+ # The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
+ A = torch.arange(1, self.num_heads + 1)
+ self.A_log = nn.Parameter(torch.log(A))
+ self.norm = Zamba2RMSNormGated(
+ self.intermediate_size, group_size=self.intermediate_size // self.n_groups, eps=1e-5
+ )
+ self.D = nn.Parameter(torch.ones(self.num_heads))
+
+ self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.add_bias_linear)
+
+ global causal_conv1d_update, causal_conv1d_fn
+ global selective_state_update, mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined
+ global is_fast_path_available
+
+ if config.use_mamba_kernels:
+ causal_conv1d = lazy_load_kernel("causal-conv1d")
+ causal_conv1d_update = getattr(causal_conv1d, "causal_conv1d_update", None)
+ causal_conv1d_fn = getattr(causal_conv1d, "causal_conv1d_fn", None)
+
+ mamba_ssm = lazy_load_kernel("mamba-ssm")
+ selective_state_update = resolve_internal_import(
+ mamba_ssm, chained_path="ops.triton.selective_state_update.selective_state_update"
+ )
+ mamba_chunk_scan_combined = resolve_internal_import(
+ mamba_ssm, chained_path="ops.triton.ssd_combined.mamba_chunk_scan_combined"
+ )
+ mamba_split_conv1d_scan_combined = resolve_internal_import(
+ mamba_ssm, chained_path="ops.triton.ssd_combined.mamba_split_conv1d_scan_combined"
+ )
+
+ is_fast_path_available = all(
+ (
+ selective_state_update,
+ mamba_chunk_scan_combined,
+ mamba_split_conv1d_scan_combined,
+ causal_conv1d_fn,
+ causal_conv1d_update,
+ )
+ )
+ else:
+ causal_conv1d_update = None
+ causal_conv1d_fn = None
+ selective_state_update = None
+ mamba_chunk_scan_combined = None
+ mamba_split_conv1d_scan_combined = None
+ is_fast_path_available = False
+
+ if getattr(config, "use_mamba_kernels", True) and not is_fast_path_available:
+ logger.warning_once(
+ "The fast path is not available because one of `(selective_state_update, causal_conv1d_fn, causal_conv1d_update)`"
+ " is None. Falling back to the naive implementation. To install follow https://github.com/state-spaces/mamba/#installation and"
+ " https://github.com/Dao-AILab/causal-conv1d"
+ )
+
+ def cuda_kernels_forward(
+ self,
+ hidden_states: torch.Tensor,
+ cache_params: Cache | None = None,
+ attention_mask: torch.Tensor | None = None,
+ ):
+ # set up dimensions for reshapes later
+
+ batch_size, seq_len, _ = hidden_states.shape
+ groups_time_state_size = self.n_groups * self.ssm_state_size
+ d_to_remove = 2 * self.intermediate_size + 2 * self.n_groups * self.ssm_state_size + self.num_heads
+
+ # getting projected states from cache if it exists
+ if cache_params is not None and cache_params.has_previous_state(self.layer_idx):
+ in_projected_states = self.in_proj(hidden_states.squeeze(1)) # (B 2D)
+ d_mlp = (in_projected_states.shape[-1] - d_to_remove) // 2
+ split_projection_dim = [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads]
+ _, _, gate, hidden_states_B_C, dt = torch.split(in_projected_states, split_projection_dim, dim=-1)
+
+ hidden_states_B_C = causal_conv1d_update(
+ hidden_states_B_C,
+ cache_params.layers[self.layer_idx].conv_states,
+ self.conv1d.weight.squeeze(1),
+ self.conv1d.bias,
+ self.activation,
+ )
+
+ hidden_states, B, C = torch.split(
+ hidden_states_B_C,
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
+ dim=-1,
+ )
+ A = -torch.exp(self.A_log.float()) # (nheads,)
+
+ A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
+ dt = dt[:, :, None].expand(-1, -1, self.head_dim)
+ dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
+ D = self.D[:, None, ...].expand(-1, self.head_dim)
+ B = B.view(batch_size, self.n_groups, B.shape[1] // self.n_groups)
+ C = C.view(batch_size, self.n_groups, C.shape[1] // self.n_groups)
+ hidden_states_reshaped = hidden_states.view(batch_size, self.num_heads, self.head_dim)
+ hidden_states = selective_state_update(
+ cache_params.layers[self.layer_idx].recurrent_states,
+ hidden_states_reshaped,
+ dt,
+ A,
+ B,
+ C,
+ D,
+ z=None,
+ dt_bias=dt_bias,
+ dt_softplus=True,
+ )
+ hidden_states = hidden_states.view(batch_size, self.num_heads * self.head_dim)
+ hidden_states = self.norm(hidden_states, gate)
+ # The SSM kernels return fp32 regardless of the module dtype; cast back to the
+ # projection weight dtype so the matmul does not fail when out_proj.weight is a
+ # narrower dtype than the activations (e.g. fp32 activations with a bf16 out_proj).
+ out = self.out_proj(hidden_states.to(self.out_proj.weight.dtype))[:, None, ...]
+ # if no cache is found, calling the kernel
+ else:
+ if attention_mask is not None and not torch.all(attention_mask == 1):
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
+ dtype = hidden_states.dtype
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
+ # 1. Gated MLP's linear projection
+ projected_states = self.in_proj(hidden_states)
+ A = -torch.exp(self.A_log.float()) # (num_heads) or (intermediate_size, state_size)
+ dt_limit_kwargs = {} if self.time_step_limit is None else {"dt_limit": self.time_step_limit}
+ if attention_mask is not None:
+ input_not_masked = torch.all(attention_mask == 1)
+ else:
+ input_not_masked = True
+
+ if self.use_mem_eff_path and self.training and cache_params is None and input_not_masked:
+ out, ssm_state = mamba_split_conv1d_scan_combined(
+ projected_states,
+ self.conv1d.weight.squeeze(1),
+ self.conv1d.bias,
+ self.dt_bias,
+ A,
+ D=self.D,
+ chunk_size=self.chunk_size,
+ seq_idx=None,
+ activation=self.activation,
+ rmsnorm_weight=self.norm.weight,
+ rmsnorm_eps=self.norm.variance_epsilon,
+ outproj_weight=self.out_proj.weight,
+ outproj_bias=self.out_proj.bias,
+ headdim=self.head_dim,
+ ngroups=self.n_groups,
+ norm_before_gate=False,
+ return_final_states=True,
+ **dt_limit_kwargs,
+ )
+
+ else:
+ gate, hidden_states_B_C, time_step = torch.split(
+ projected_states,
+ [self.intermediate_size, self.conv_dim, self.num_heads],
+ dim=-1,
+ )
+
+ # 1D Convolution
+ if cache_params is not None:
+ hidden_states_B_C_t = hidden_states_B_C.transpose(1, 2)
+ conv_state = nn.functional.pad(
+ hidden_states_B_C_t, (self.conv_kernel_size - hidden_states_B_C_t.shape[-1], 0)
+ )
+ conv_state = cache_params.update_conv_state(conv_state, self.layer_idx)
+ if causal_conv1d_fn is None or self.activation not in ["silu", "swish"]:
+ hidden_states_B_C = self.act(
+ self.conv1d(hidden_states_B_C.transpose(1, 2)).transpose(1, 2)[:, :seq_len]
+ ) # (B, L, self.d_inner + 2 * ngroups * d_state)
+ else:
+ hidden_states_B_C = causal_conv1d_fn(
+ x=hidden_states_B_C.transpose(1, 2),
+ weight=self.conv1d.weight.squeeze(1),
+ bias=self.conv1d.bias,
+ activation=self.activation,
+ ).transpose(1, 2)[:, :seq_len]
+ hidden_states, B, C = torch.split(
+ hidden_states_B_C,
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
+ dim=-1,
+ )
+ if attention_mask is not None and not torch.all(attention_mask == 1):
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
+ dtype = hidden_states.dtype
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
+ scan_output, ssm_state = mamba_chunk_scan_combined(
+ hidden_states.view(batch_size, seq_len, -1, self.head_dim),
+ time_step,
+ A,
+ B.view(batch_size, seq_len, self.n_groups, -1),
+ C.view(batch_size, seq_len, self.n_groups, -1),
+ chunk_size=self.chunk_size,
+ D=self.D,
+ z=None,
+ seq_idx=None,
+ return_final_states=True,
+ dt_bias=self.dt_bias,
+ dt_softplus=True,
+ **dt_limit_kwargs,
+ )
+ if ssm_state is not None and cache_params is not None:
+ cache_params.update_recurrent_state(ssm_state, self.layer_idx)
+ scan_output = scan_output.view(batch_size, seq_len, -1)
+ # Multiply "gate" branch and apply extra normalization layer
+ scan_output = self.norm(scan_output, gate)
+ # The SSM kernels return fp32 regardless of the module dtype; cast back to the
+ # projection weight dtype so the matmul does not fail when out_proj.weight is a
+ # narrower dtype than the activations (e.g. fp32 activations with a bf16 out_proj).
+ out = self.out_proj(scan_output.to(self.out_proj.weight.dtype))
+ return out
+
+ # fmt: off
+ def torch_forward(self, input_states, cache_params: Cache | None=None, attention_mask: torch.Tensor | None = None):
+ batch_size, seq_len, _ = input_states.shape
+ dtype = input_states.dtype
+ # Gated MLP's linear projection
+ if cache_params is not None and cache_params.has_previous_state(self.layer_idx):
+ projected_states = self.in_proj(input_states)
+ else:
+ if attention_mask is not None:
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
+ input_states = (input_states * attention_mask[:, :, None]).to(dtype)
+ projected_states = self.in_proj(input_states)
+ d_mlp = (projected_states.shape[-1] - 2 * self.intermediate_size - 2 * self.n_groups * self.ssm_state_size- self.num_heads) // 2
+ _, _, gate, hidden_states, dt = projected_states.split(
+ [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
+ )
+ hidden_states = hidden_states.transpose(1, 2)
+
+ use_precomputed_state = cache_params is not None and cache_params.has_previous_state(self.layer_idx)
+
+ # Convolution sequence transformation
+ if use_precomputed_state:
+ conv_state = cache_params.update_conv_state(hidden_states, self.layer_idx)
+ hidden_states = torch.sum(conv_state * self.conv1d.weight[:, 0, :], dim=-1)
+ if self.use_conv_bias:
+ hidden_states += self.conv1d.bias
+ hidden_states = self.act(hidden_states).to(dtype)[:, None, ...] # [batch, 1, intermediate_size] : decoding
+ else:
+ if cache_params is not None:
+ conv_state = nn.functional.pad(
+ hidden_states,
+ (self.conv_kernel_size - hidden_states.shape[-1], 0)
+ )
+ conv_state = cache_params.update_conv_state(conv_state, self.layer_idx)
+
+ hidden_states = self.act(self.conv1d(hidden_states)[..., :seq_len].transpose(1, 2))
+ if attention_mask is not None:
+ dtype = hidden_states.dtype
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
+
+ hidden_states, B, C = torch.split(hidden_states, [self.intermediate_size, self.n_groups * self.ssm_state_size, self.n_groups * self.ssm_state_size], dim=-1)
+ A = -torch.exp(self.A_log.float()) # [num_heads]
+ if use_precomputed_state:
+ # Note: there is no need to pad parameter matrices here, as there is just one new token
+ # for batched generation
+ dt = dt[:, None, ...] if dt.ndim == 2 else dt[:, 0, :][:, None, ...]
+ dt = dt.transpose(1, 2).expand(batch_size, dt.shape[-1], self.head_dim)
+ # [num_heads] -> [num_heads, head_dim]
+ dt_bias = self.dt_bias[..., None].expand(self.dt_bias.shape[0], self.head_dim)
+
+ dt = torch.nn.functional.softplus(dt + dt_bias.to(dt.dtype))
+ dt = torch.clamp(dt, self.time_step_min) #, self.time_step_max)
+ A = A[..., None, None].expand(self.num_heads, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
+ # [bsz, num_heads, head_dim, state_size]
+ dA = torch.exp(dt[..., None] * A)
+
+ # Discretize B
+ # [bsz, n_groups * state_size] -> [bsz, n_groups, 1, state_size] ->
+ # -> [bsz, n_groups, group to head repetition factor, state_size] -> [bsz, num_heads, state_size]
+ B = B.reshape(batch_size, self.n_groups, -1)[..., None, :]
+ B = B.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, B.shape[-1]).contiguous()
+ B = B.reshape(batch_size, -1, B.shape[-1])
+ # [bsz, num_heads, head_dim, state_size]
+ dB = dt[..., None] * B[..., None, :]
+
+ # Discretize x into dB
+ # [bsz, intermediate_size] -> [bsz, num_heads, head_dim]
+ hidden_states = hidden_states.reshape(batch_size, -1, self.head_dim)
+ dBx = dB * hidden_states[..., None]
+
+ # State calculation
+ ssm_states = cache_params.layers[self.layer_idx].recurrent_states.clone()
+ ssm_states = ssm_states * dA + dBx
+ ssm_states = cache_params.update_recurrent_state(ssm_states, self.layer_idx)
+
+ # Subsequent output
+ # [bsz, n_groups * state_size] -> [bsz, num_heads, state_size]
+ C = C.reshape(batch_size, self.n_groups, -1)[..., None, :]
+ C = C.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, C.shape[-1]).contiguous()
+ C = C.reshape(batch_size, -1, C.shape[-1])
+ # [bsz, num_heads, head_dim]
+
+ ssm_states = ssm_states.to(C.dtype) # Shape: [b, h, d, n]
+ # Reshape ssm_states to merge the first two dimensions
+ ssm_states_reshaped = ssm_states.view(batch_size * self.num_heads, self.head_dim, self.ssm_state_size) # Shape: [b*h, d, n]
+ C_reshaped = C.view(batch_size * self.num_heads, self.ssm_state_size, 1) # Shape: [b*h, n, 1]
+ y = torch.bmm(ssm_states_reshaped, C_reshaped)
+ y = y.view(batch_size, self.num_heads, self.head_dim)
+
+ # D skip connection
+ # [num_heads] -> [num_heads, head_dim]
+ D = self.D[..., None].expand(self.D.shape[0], self.head_dim)
+ y = (y + hidden_states * D).to(y.dtype)
+
+ # [bsz, num_heads, head_dim] -> [bsz, 1, intermediate_size]
+ y = y.reshape(batch_size, -1)[:, None, ...]
+ else:
+ # begin ssd naive implementation without einsums
+ dt = nn.functional.softplus(dt + self.dt_bias)
+ dt = torch.clamp(dt, self.time_step_min)
+ hidden_states = hidden_states.reshape(batch_size, seq_len, -1, self.head_dim).float()
+ B = B.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
+ C = C.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
+ B = B.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
+ C = C.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
+ pad_size = (self.chunk_size - seq_len % self.chunk_size) % self.chunk_size
+
+ D_residual = self.D[..., None] * pad_tensor_by_size(hidden_states, pad_size)
+
+ # Discretize x and A
+ hidden_states = hidden_states * dt[..., None]
+ A = A.to(hidden_states.dtype) * dt
+
+ # Rearrange into blocks/chunks
+ hidden_states, A, B, C = [reshape_into_chunks(t, pad_size, self.chunk_size) for t in (hidden_states, A, B, C)]
+
+
+ # [bsz, -1, chunk_size, num_heads] -> [bsz, num_heads, -1, chunk_size]
+ A = A.permute(0, 3, 1, 2)
+ A_cumsum = torch.cumsum(A, dim=-1)
+
+ # 1. Compute the output for each intra-chunk (diagonal blocks)
+ # This is the analog of a causal mask
+ L = torch.exp(segment_sum(A))
+
+ # First, contraction of C and B to get G (attention-weights like)
+ G_intermediate = C[:, :, :, None, :, :] * B[:, :, None, :, : ,:] # shape: (b, c, l, s, h, n)
+ G = G_intermediate.sum(dim=-1) # shape: (b, c, l, s, h)
+
+
+ # Step 2: Compute M, equivalent to applying attention mask to weights
+ M_intermediate = G[..., None] * L.permute(0, 2, 3, 4, 1)[..., None]
+ M = M_intermediate.sum(dim=-1)
+
+ # Step 3: Compute Y_diag (apply to values)
+ Y_diag = (M[..., None] * hidden_states[:, :, None]).sum(3)
+
+ # (right term of low-rank factorization of off-diagonal blocks; B terms)
+
+ decay_states = torch.exp(A_cumsum[:, :, :, -1:] - A_cumsum)
+ B_decay_contraction = B * decay_states.permute(0, 2, 3, 1)[..., None]
+ # permute back B * decay states
+ states = (B_decay_contraction.permute(0, 1, 3, 2, 4)[..., None] * hidden_states.permute(0, 1, 3, 2, 4)[..., None, :]).sum(dim=3).permute(0, 1, 2, 4, 3)
+ previous_states = torch.zeros_like(states[:, :1])
+ states = torch.cat([previous_states, states], dim=1)
+ decay_chunk = torch.exp(segment_sum(nn.functional.pad(A_cumsum[:, :, :, -1], (1, 0))))
+
+ states_permuted = states.permute(0, 2, 1, 3, 4)
+ result = (decay_chunk[..., None, None] * states_permuted[:, :, None, ...]).sum(dim=2)
+ new_states = result.permute(0, 2, 1, 3, 4)
+ states, ssm_state = new_states[:, :-1], new_states[:, -1]
+
+ # Compute state -> output conversion per chunk
+ # (left term of low-rank factorization of off-diagonal blocks; C terms)
+ state_decay_out = torch.exp(A_cumsum)
+ # compute Yoff
+ C_times_states = (C[..., None, :] * states[:, :, None, ...])
+ state_decay_out_permuted = state_decay_out.permute(0, 2, 3, 1)
+ Y_off = (C_times_states.sum(-1) * state_decay_out_permuted[..., None])
+ # Add output of intra-chunk and inter-chunk terms (diagonal and off-diagonal blocks)
+
+ y = Y_diag + Y_off
+ # [bsz, -1, self.chunk_size, num_heads, head_dim] -> [bsz, (padded) seq_len, num_heads, head_dim]
+ y = y.reshape(batch_size, -1, self.num_heads, self.head_dim)
+
+ y = y + D_residual
+ # Cutting off padded chunks
+ if pad_size > 0:
+ y = y[:, :seq_len, :, :]
+ y = y.reshape(batch_size, seq_len, -1)
+ if ssm_state is not None and cache_params is not None:
+ cache_params.update_recurrent_state(ssm_state, self.layer_idx)
+
+ scan_output = self.norm(y, gate)
+
+ # end ssd naive
+
+ # 4. Final linear projection
+ contextualized_states = self.out_proj(scan_output.to(dtype)) # [batch, seq_len, hidden_size]
+ return contextualized_states
+ # fmt: on
+
+ def forward(
+ self,
+ hidden_states,
+ cache_params: Cache | None = None,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs,
+ ):
+ if is_fast_path_available and "cuda" in self.in_proj.weight.device.type and not is_torchdynamo_compiling():
+ return self.cuda_kernels_forward(hidden_states, cache_params, attention_mask)
+
+ return self.torch_forward(hidden_states, cache_params, attention_mask)
+
+
+class Zamba2MLP(nn.Module):
+ def __init__(self, config: Zamba2Config, num_fwd_mem_blocks=None, block_id: int | None = None):
+ """
+ This MLP layer contributes to tied transformer blocks aimed to increasing compute without increasing model size. Because this layer
+ is tied, un-tied adapter modules (formally same as LoRA, but used in the base model) are added to the up and gate projectors to increase expressivity with a small memory overhead.
+ """
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = config.intermediate_size
+ self.num_fwd_mem_blocks = num_fwd_mem_blocks
+ self.block_id = block_id
+
+ self.gate_up_proj = nn.Linear(self.hidden_size, 2 * self.intermediate_size, bias=config.add_bias_linear)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.add_bias_linear)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ self.gate_up_proj_adapter_list = nn.ModuleList([])
+ for i in range(self.num_fwd_mem_blocks):
+ if i % config.num_mem_blocks == block_id:
+ gate_up_proj_adapter = nn.Sequential(
+ nn.Linear(self.config.hidden_size, self.config.adapter_rank, bias=False),
+ nn.Linear(self.config.adapter_rank, 2 * self.intermediate_size, bias=False),
+ )
+ else:
+ gate_up_proj_adapter = nn.Identity()
+ self.gate_up_proj_adapter_list.append(gate_up_proj_adapter)
+
+ layer_block_map = config.hybrid_layer_ids
+ self.layer_dic = {value: index for index, value in enumerate(layer_block_map)}
+
+ def forward(self, hidden_state, layer_idx=None):
+ gate_up_state = self.gate_up_proj(hidden_state)
+ layer_idx = self.layer_dic[layer_idx]
+ gate_up_state = gate_up_state + self.gate_up_proj_adapter_list[layer_idx](hidden_state)
+
+ gate_up_state = torch.chunk(gate_up_state, 2, dim=-1)
+ hidden_state = self.act_fn(gate_up_state[0]) * gate_up_state[1]
+ output = self.down_proj(hidden_state)
+ return output
+
+
+class Zamba2AttentionDecoderLayer(nn.Module):
+ def __init__(self, config: Zamba2Config, block_id: int | None = None, layer_idx: int | None = None):
+ super().__init__()
+ self.block_id = block_id
+ num_gs = len(config.hybrid_layer_ids)
+ self.self_attn = Zamba2Attention(config, layer_idx=-1, num_fwd_mem_blocks=num_gs, block_id=block_id)
+ self.feed_forward = Zamba2MLP(config, num_fwd_mem_blocks=num_gs, block_id=block_id)
+ self.input_layernorm = Zamba2RMSNorm(config.attention_hidden_size, eps=config.rms_norm_eps)
+ self.pre_ff_layernorm = Zamba2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ original_hidden_states: torch.Tensor,
+ layer_idx: int,
+ attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ position_embeddings: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.FloatTensor]:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): output of previous Mamba layer of shape `(batch, seq_len, embed_dim)`
+ original_hidden_states (`torch.FloatTensor`): word embedding output of shape `(batch, seq_len, embed_dim)`.
+ This is concatenated with `hidden_states` (which is the output of the previous (mamba) layer). The
+ concatenated tensor is then used as input of the pre-attention RMSNorm
+ (see fig. 2 in https://huggingface.co/papers/2405.16712).
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
+ `(batch, sequence_length)` where padding elements are indicated by 0.
+ past_key_values (`Cache`, *optional*): cached past key and value projection states
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
+ (see `past_key_values`).
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
+ with `head_dim` being the embedding dimension of each attention head.
+ """
+ hidden_states = torch.concatenate([hidden_states, original_hidden_states], dim=-1)
+ hidden_states = self.input_layernorm(hidden_states)
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ layer_idx=layer_idx,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+
+ hidden_states = self.pre_ff_layernorm(hidden_states)
+ hidden_states = self.feed_forward(hidden_states, layer_idx)
+
+ return hidden_states
+
+
+class Zamba2MambaDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: Zamba2Config, layer_idx: int):
+ super().__init__()
+ self.mamba = Zamba2MambaMixer(config=config, layer_idx=layer_idx)
+ self.input_layernorm = Zamba2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.layer_idx = layer_idx
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ original_hidden_states: torch.Tensor | None = None,
+ layer_idx: int | None = None,
+ attention_mask: torch.Tensor | None = None,
+ causal_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ position_ids: torch.LongTensor | None = None,
+ transformer_hidden_states: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
+ `(batch, sequence_length)` where padding elements are indicated by 0.
+ past_key_values (`Cache`, *optional*): cached past key and value projection states
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
+ (see `past_key_values`).
+ """
+
+ residual = hidden_states
+
+ # `transformer_hidden_states` is the output from shared transformer + linear layer (see fig. 2 in https://huggingface.co/papers/2405.16712).
+ # `transformer_hidden_states` is then added to the input to the mamba layer below (as described in eq. (6) of https://huggingface.co/papers/2405.16712).
+ hidden_states = (
+ hidden_states + transformer_hidden_states if transformer_hidden_states is not None else hidden_states
+ )
+ hidden_states = self.input_layernorm(hidden_states)
+
+ hidden_states = self.mamba(
+ hidden_states=hidden_states,
+ cache_params=past_key_values,
+ attention_mask=attention_mask,
+ **kwargs,
+ )
+ # residual connection after mamba
+ hidden_states = residual + hidden_states
+
+ return hidden_states
+
+
+class Zamba2HybridLayer(GradientCheckpointingLayer):
+ def __init__(
+ self, shared_transformer: Zamba2AttentionDecoderLayer, linear: nn.Linear, mamba: Zamba2MambaDecoderLayer
+ ):
+ super().__init__()
+ self.linear = linear
+ self.mamba_decoder = mamba
+ self.shared_transformer = shared_transformer
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ original_hidden_states: torch.Tensor | None = None,
+ layer_idx: int | None = None,
+ attention_mask: torch.Tensor | None = None,
+ causal_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ position_embeddings: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
+ original_hidden_states (`torch.FloatTensor`): word embedding output that will be concatenated with
+ hidden activations to form the input of the shared transformer layer.
+ layer_idx (`int`): layer number.
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
+ `(batch, sequence_length)` where padding elements are indicated by 0.
+ past_key_values (`Cache`, *optional*): cached past key and value projection states
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
+ (see `past_key_values`).
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
+ with `head_dim` being the embedding dimension of each attention head.
+ """
+
+ transformer_hidden_states = self.shared_transformer(
+ hidden_states,
+ original_hidden_states=original_hidden_states,
+ layer_idx=layer_idx,
+ attention_mask=causal_mask,
+ past_key_values=past_key_values,
+ position_embeddings=position_embeddings,
+ position_ids=position_ids,
+ **kwargs,
+ )
+ transformer_hidden_states = self.linear(transformer_hidden_states)
+
+ hidden_states = self.mamba_decoder(
+ hidden_states,
+ transformer_hidden_states=transformer_hidden_states,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+
+ return hidden_states
+
+
+@auto_docstring
+class Zamba2PreTrainedModel(PreTrainedModel):
+ config: Zamba2Config
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["Zamba2HybridLayer", "Zamba2MambaDecoderLayer"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = True
+ _supports_flex_attn = True
+ _supports_sdpa = True
+ _is_stateful = True
+ _can_record_outputs = {
+ "hidden_states": Zamba2MambaDecoderLayer,
+ "attentions": Zamba2Attention,
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ if isinstance(module, Zamba2MambaMixer):
+ dt = torch.exp(
+ torch.rand(self.config.n_mamba_heads)
+ * (math.log(self.config.time_step_max) - math.log(self.config.time_step_min))
+ + math.log(self.config.time_step_min)
+ ).clamp(min=self.config.time_step_floor)
+ # # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
+ init.copy_(module.dt_bias, inv_dt)
+
+ A = torch.arange(1, module.num_heads + 1)
+ init.copy_(module.A_log, torch.log(A))
+ init.ones_(module.D)
+
+
+@auto_docstring
+class Zamba2Model(Zamba2PreTrainedModel):
+ """
+ Model consisting of *config.num_hidden_layers* layers.
+
+ Args:
+ config: Zamba2Config
+ """
+
+ def __init__(self, config: Zamba2Config):
+ super().__init__(config)
+ self.config = config
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
+ self.layers_block_type = config.layers_block_type
+ self.layers = self.get_layers()
+
+ self._attn_implementation = config._attn_implementation
+ self.final_layernorm = Zamba2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ if config.use_mem_rope:
+ if config.use_long_context:
+ logger.warning_once(
+ "`use_long_context` set to `True`: using rescaled `rope_theta` and extended `max_position_embeddings`."
+ )
+ self.rotary_emb = Zamba2RotaryEmbedding(config)
+ self.gradient_checkpointing = False
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError(
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
+ )
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ hidden_states = inputs_embeds
+
+ original_hidden_states = torch.clone(inputs_embeds)
+ # original_hidden_states: word embedding output that will be concatenated with hidden activations to form the input of the shared transformer layer
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ causal_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_ids=position_ids,
+ )
+
+ # create position embeddings to be shared across the decoder layers
+ if self.config.use_mem_rope:
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
+ else:
+ position_embeddings = None
+
+ for layer_idx, layer in enumerate(self.layers):
+ hidden_states = layer(
+ hidden_states,
+ original_hidden_states,
+ layer_idx,
+ attention_mask,
+ causal_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ position_ids=position_ids,
+ **kwargs,
+ )
+
+ hidden_states = self.final_layernorm(hidden_states)
+
+ return BaseModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values if use_cache else None,
+ )
+
+ def get_layers(self):
+ layers = []
+ self._tied_weights_keys = {}
+ self.first_transformer_layer_id = 0
+ unique_hybrid_blocks = []
+
+ for layer_id, layer_type in enumerate(self.layers_block_type):
+ mamba_layer = Zamba2MambaDecoderLayer(self.config, layer_idx=layer_id)
+ if layer_type == "hybrid":
+ prefix_pattern = f"layers.{layer_id}.shared_transformer"
+
+ # Zamba ties Hybrid module weights by repeating blocks after every
+ # `num_mem_blocks`. So if `num_mem_blocks=2`, the blocks looks like
+ # [1, 2, 1, 2, 1, 2] where all "ones" share the same set of weights.
+ if (
+ not isinstance(unique_hybrid_blocks, list)
+ or len(unique_hybrid_blocks) >= self.config.num_mem_blocks
+ ):
+ if isinstance(unique_hybrid_blocks, list):
+ unique_hybrid_blocks = cycle(unique_hybrid_blocks)
+ target_pattern = next(unique_hybrid_blocks)
+ self._tied_weights_keys.update({prefix_pattern: target_pattern})
+ else:
+ # Store source patterns to which the subsequent modules will be tied
+ unique_hybrid_blocks.append(prefix_pattern)
+
+ block_id = layer_id % self.config.num_mem_blocks
+ attn_block = Zamba2AttentionDecoderLayer(self.config, block_id=block_id)
+ linear_layer = nn.Linear(self.config.hidden_size, self.config.hidden_size, bias=False)
+ layers.append(Zamba2HybridLayer(attn_block, linear_layer, mamba_layer))
+ else:
+ layers.append(mamba_layer)
+ return nn.ModuleList(layers)
+
+
+# Adapted from transformers.models.jamba.modeling_jamba.JambaForCausalLM with Jamba->Zamba2, JAMBA->ZAMBA2
+class Zamba2ForCausalLM(Zamba2PreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
+
+ def __init__(self, config: Zamba2Config):
+ super().__init__(config)
+ self.model = Zamba2Model(config)
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | CausalLMOutputWithPast:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, Zamba2ForCausalLM
+
+ >>> model = Zamba2ForCausalLM.from_pretrained("Zyphra/Zamba2-7B-v1")
+ >>> tokenizer = AutoTokenizer.from_pretrained("Zyphra/Zamba2-7B-v1")
+
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
+ ```"""
+ outputs: BaseModelOutputWithPast = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(
+ logits,
+ labels,
+ self.vocab_size,
+ **kwargs,
+ )
+
+ return CausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+ def prepare_inputs_for_generation(
+ self,
+ input_ids,
+ past_key_values=None,
+ attention_mask=None,
+ inputs_embeds=None,
+ position_ids=None,
+ use_cache=True,
+ is_first_iteration=False,
+ **kwargs,
+ ):
+ kwargs["logits_to_keep"] = self.config.num_logits_to_keep
+ model_inputs = super().prepare_inputs_for_generation(
+ input_ids,
+ past_key_values=past_key_values,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ position_ids=position_ids,
+ use_cache=use_cache,
+ is_first_iteration=is_first_iteration,
+ **kwargs,
+ )
+
+ return model_inputs
+
+
+@auto_docstring(
+ custom_intro="""
+ The Zamba2 Model with a sequence classification head on top (linear layer).
+
+ [`Zamba2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
+ (e.g. GPT-2) do.
+
+ Since it does classification on the last token, it requires to know the position of the last token. If a
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
+ each row of the batch).
+ """
+)
+class Zamba2ForSequenceClassification(Zamba2PreTrainedModel):
+ def __init__(self, config: Zamba2Config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.model = Zamba2Model(config)
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | SequenceClassifierOutputWithPast:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ transformer_outputs: BaseModelOutputWithPast = self.model(
+ input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+ hidden_states = transformer_outputs[0]
+ logits = self.score(hidden_states)
+
+ if input_ids is not None:
+ batch_size = input_ids.shape[0]
+ else:
+ batch_size = inputs_embeds.shape[0]
+
+ if self.config.pad_token_id is None and batch_size != 1:
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
+ if self.config.pad_token_id is None:
+ last_non_pad_token = -1
+ elif input_ids is not None:
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
+ else:
+ last_non_pad_token = -1
+ logger.warning_once(
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
+ )
+
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(
+ logits=pooled_logits, labels=labels, pooled_logits=pooled_logits, config=self.config, **kwargs
+ )
+
+ return SequenceClassifierOutputWithPast(
+ loss=loss,
+ logits=pooled_logits,
+ past_key_values=transformer_outputs.past_key_values,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+__all__ = ["Zamba2ForCausalLM", "Zamba2ForSequenceClassification", "Zamba2Model", "Zamba2PreTrainedModel"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/zamba2/modular_zamba2.py b/.venv/lib/python3.12/site-packages/transformers/models/zamba2/modular_zamba2.py
new file mode 100644
index 0000000000000000000000000000000000000000..f40514df0188954414cc2b3ff68dc4334b6ed636
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/zamba2/modular_zamba2.py
@@ -0,0 +1,1073 @@
+# Copyright 2024 Zyphra Technologies and the HuggingFace Inc. team. All rights reserved.
+#
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import math
+from collections.abc import Callable
+from itertools import cycle
+
+import torch
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache
+from ...integrations.hub_kernels import lazy_load_kernel
+from ...masking_utils import create_causal_mask
+from ...modeling_outputs import BaseModelOutputWithPast, SequenceClassifierOutputWithPast
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, is_torchdynamo_compiling, logging
+from ...utils.generic import merge_with_config_defaults
+from ...utils.import_utils import resolve_internal_import
+from ...utils.output_capturing import capture_outputs
+from ..llama.modeling_llama import LlamaRotaryEmbedding, apply_rotary_pos_emb
+from ..mamba2.modeling_mamba2 import pad_tensor_by_size, reshape_into_chunks, segment_sum
+from ..zamba.modeling_zamba import (
+ ZambaAttention,
+ ZambaAttentionDecoderLayer,
+ ZambaForCausalLM,
+ ZambaForSequenceClassification,
+ ZambaHybridLayer,
+ ZambaMambaDecoderLayer,
+ ZambaModel,
+ ZambaRMSNorm,
+ eager_attention_forward,
+)
+from .configuration_zamba2 import Zamba2Config
+
+
+_CONFIG_FOR_DOC = "Zyphra/Zamba2-2.7B"
+
+logger = logging.get_logger(__name__)
+
+
+class Zamba2RMSNormGated(torch.nn.Module):
+ def __init__(self, hidden_size, group_size, eps=1e-6):
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+ self.group_size = group_size
+
+ def forward(self, hidden_states, gate=None):
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ if gate is not None:
+ hidden_states = hidden_states * nn.functional.silu(gate.to(torch.float32))
+ *prefix_dims, last_dim = hidden_states.shape
+ group_count = last_dim // self.group_size
+ hidden_states_group = hidden_states.view(*prefix_dims, group_count, self.group_size)
+ variance = hidden_states_group.pow(2).mean(-1, keepdim=True)
+ hidden_states_group = hidden_states_group * torch.rsqrt(variance + self.variance_epsilon)
+ hidden_states = hidden_states_group.view(*prefix_dims, group_count * self.group_size)
+ return self.weight * hidden_states.to(input_dtype)
+
+
+class Zamba2RMSNorm(ZambaRMSNorm):
+ pass
+
+
+class Zamba2RotaryEmbedding(LlamaRotaryEmbedding):
+ pass
+
+
+class Zamba2Attention(ZambaAttention):
+ """
+ Multi-headed attention from 'Attention Is All You Need' paper.
+
+ Adapted from transformers.models.mistral.modeling_mistral.MistralAttention:
+ The input dimension here is attention_hidden_size = 2 * hidden_size, and head_dim = attention_hidden_size // num_heads.
+ The extra factor of 2 comes from the input being the concatenation of original_hidden_states with the output of the previous (mamba) layer
+ (see fig. 2 in https://huggingface.co/papers/2405.16712).
+ Additionally, replaced
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) with
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim/2)
+ Finally, this attention layer contributes to tied transformer blocks aimed to increasing compute without increasing model size. Because this
+ layer is tied, un-tied adapters (formally the same as LoRA but used in the base model) modules are added to the q, k, v projectors to increase
+ expressivity with a small memory overhead (see Fig. 2 of https://huggingface.co/papers/2411.15242).
+ """
+
+ def __init__(
+ self,
+ config: Zamba2Config,
+ layer_idx: int | None = None,
+ num_fwd_mem_blocks: int | None = None,
+ block_id: int | None = None,
+ ):
+ super().__init__(config, layer_idx)
+ self.num_fwd_mem_blocks = num_fwd_mem_blocks
+ self.layer_block_map = config.hybrid_layer_ids
+ self.block_id = block_id
+
+ if config.use_shared_attention_adapter:
+ self.linear_q_adapter_list = nn.ModuleList([])
+ self.linear_k_adapter_list = nn.ModuleList([])
+ self.linear_v_adapter_list = nn.ModuleList([])
+
+ for i in range(self.num_fwd_mem_blocks):
+ if i % config.num_mem_blocks == block_id:
+ linear_q_adapter = nn.Sequential(
+ nn.Linear(self.attention_hidden_size, self.config.adapter_rank, bias=False),
+ nn.Linear(self.config.adapter_rank, self.attention_hidden_size, bias=False),
+ )
+ linear_k_adapter = nn.Sequential(
+ nn.Linear(self.attention_hidden_size, self.config.adapter_rank, bias=False),
+ nn.Linear(self.config.adapter_rank, self.attention_hidden_size, bias=False),
+ )
+ linear_v_adapter = nn.Sequential(
+ nn.Linear(self.attention_hidden_size, self.config.adapter_rank, bias=False),
+ nn.Linear(self.config.adapter_rank, self.attention_hidden_size, bias=False),
+ )
+ else:
+ linear_q_adapter = nn.Identity()
+ linear_k_adapter = nn.Identity()
+ linear_v_adapter = nn.Identity()
+ self.linear_q_adapter_list.append(linear_q_adapter)
+ self.linear_k_adapter_list.append(linear_k_adapter)
+ self.linear_v_adapter_list.append(linear_v_adapter)
+
+ self.layer_dic = {value: index for index, value in enumerate(self.layer_block_map)}
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ layer_idx: int,
+ attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_proj(hidden_states)
+ key_states = self.k_proj(hidden_states)
+ value_states = self.v_proj(hidden_states)
+ if self.config.use_shared_attention_adapter:
+ adapter_layer_idx = self.layer_dic[layer_idx]
+ query_states = query_states + self.linear_q_adapter_list[adapter_layer_idx](hidden_states)
+ key_states = key_states + self.linear_k_adapter_list[adapter_layer_idx](hidden_states)
+ value_states = value_states + self.linear_v_adapter_list[adapter_layer_idx](hidden_states)
+
+ query_states = query_states.view(hidden_shape).transpose(1, 2)
+ key_states = key_states.view(hidden_shape).transpose(1, 2)
+ value_states = value_states.view(hidden_shape).transpose(1, 2)
+
+ if self.config.use_mem_rope:
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class Zamba2MambaMixer(nn.Module):
+ """
+ Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
+ A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
+ ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
+ and is why Mamba is called **selective** state spaces)
+ """
+
+ def __init__(self, config: Zamba2Config, layer_idx: int | None = None):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.ssm_state_size = config.mamba_d_state
+ self.conv_kernel_size = config.mamba_d_conv
+ self.intermediate_size = int(config.mamba_expand * self.hidden_size)
+ self.layer_idx = layer_idx
+ self.use_conv_bias = config.use_conv_bias
+ self.activation = "silu"
+ self.act = nn.SiLU()
+ self.use_mem_eff_path = config.use_mem_eff_path
+
+ self.n_groups = config.mamba_ngroups
+ self.head_dim = config.mamba_headdim
+ self.num_heads = self.config.n_mamba_heads
+ self.chunk_size = config.chunk_size
+
+ self.time_step_limit = config.time_step_limit
+ self.time_step_min = config.time_step_min
+ self.time_step_max = config.time_step_max
+
+ self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size
+ self.conv1d = nn.Conv1d(
+ in_channels=self.conv_dim,
+ out_channels=self.conv_dim,
+ bias=True,
+ kernel_size=config.mamba_d_conv,
+ groups=self.conv_dim,
+ padding=config.mamba_d_conv - 1,
+ )
+
+ # projection of the input hidden states
+ projection_size = self.intermediate_size + self.conv_dim + self.num_heads
+ self.in_proj = nn.Linear(
+ self.hidden_size,
+ projection_size,
+ bias=config.add_bias_linear,
+ )
+ # selective projection used to make dt, B and C input dependent
+
+ # time step projection (discretization)
+ # instantiate once and copy inv_dt in init_weights of PretrainedModel
+ self.dt_bias = nn.Parameter(torch.ones(self.num_heads))
+
+ # S4D real initialization. These are not discretized!
+ # The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
+ A = torch.arange(1, self.num_heads + 1)
+ self.A_log = nn.Parameter(torch.log(A))
+ self.norm = Zamba2RMSNormGated(
+ self.intermediate_size, group_size=self.intermediate_size // self.n_groups, eps=1e-5
+ )
+ self.D = nn.Parameter(torch.ones(self.num_heads))
+
+ self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.add_bias_linear)
+
+ global causal_conv1d_update, causal_conv1d_fn
+ global selective_state_update, mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined
+ global is_fast_path_available
+
+ if config.use_mamba_kernels:
+ causal_conv1d = lazy_load_kernel("causal-conv1d")
+ causal_conv1d_update = getattr(causal_conv1d, "causal_conv1d_update", None)
+ causal_conv1d_fn = getattr(causal_conv1d, "causal_conv1d_fn", None)
+
+ mamba_ssm = lazy_load_kernel("mamba-ssm")
+ selective_state_update = resolve_internal_import(
+ mamba_ssm, chained_path="ops.triton.selective_state_update.selective_state_update"
+ )
+ mamba_chunk_scan_combined = resolve_internal_import(
+ mamba_ssm, chained_path="ops.triton.ssd_combined.mamba_chunk_scan_combined"
+ )
+ mamba_split_conv1d_scan_combined = resolve_internal_import(
+ mamba_ssm, chained_path="ops.triton.ssd_combined.mamba_split_conv1d_scan_combined"
+ )
+
+ is_fast_path_available = all(
+ (
+ selective_state_update,
+ mamba_chunk_scan_combined,
+ mamba_split_conv1d_scan_combined,
+ causal_conv1d_fn,
+ causal_conv1d_update,
+ )
+ )
+ else:
+ causal_conv1d_update = None
+ causal_conv1d_fn = None
+ selective_state_update = None
+ mamba_chunk_scan_combined = None
+ mamba_split_conv1d_scan_combined = None
+ is_fast_path_available = False
+
+ if getattr(config, "use_mamba_kernels", True) and not is_fast_path_available:
+ logger.warning_once(
+ "The fast path is not available because one of `(selective_state_update, causal_conv1d_fn, causal_conv1d_update)`"
+ " is None. Falling back to the naive implementation. To install follow https://github.com/state-spaces/mamba/#installation and"
+ " https://github.com/Dao-AILab/causal-conv1d"
+ )
+
+ def cuda_kernels_forward(
+ self,
+ hidden_states: torch.Tensor,
+ cache_params: Cache | None = None,
+ attention_mask: torch.Tensor | None = None,
+ ):
+ # set up dimensions for reshapes later
+
+ batch_size, seq_len, _ = hidden_states.shape
+ groups_time_state_size = self.n_groups * self.ssm_state_size
+ d_to_remove = 2 * self.intermediate_size + 2 * self.n_groups * self.ssm_state_size + self.num_heads
+
+ # getting projected states from cache if it exists
+ if cache_params is not None and cache_params.has_previous_state(self.layer_idx):
+ in_projected_states = self.in_proj(hidden_states.squeeze(1)) # (B 2D)
+ d_mlp = (in_projected_states.shape[-1] - d_to_remove) // 2
+ split_projection_dim = [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads]
+ _, _, gate, hidden_states_B_C, dt = torch.split(in_projected_states, split_projection_dim, dim=-1)
+
+ hidden_states_B_C = causal_conv1d_update(
+ hidden_states_B_C,
+ cache_params.layers[self.layer_idx].conv_states,
+ self.conv1d.weight.squeeze(1),
+ self.conv1d.bias,
+ self.activation,
+ )
+
+ hidden_states, B, C = torch.split(
+ hidden_states_B_C,
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
+ dim=-1,
+ )
+ A = -torch.exp(self.A_log.float()) # (nheads,)
+
+ A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
+ dt = dt[:, :, None].expand(-1, -1, self.head_dim)
+ dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
+ D = self.D[:, None, ...].expand(-1, self.head_dim)
+ B = B.view(batch_size, self.n_groups, B.shape[1] // self.n_groups)
+ C = C.view(batch_size, self.n_groups, C.shape[1] // self.n_groups)
+ hidden_states_reshaped = hidden_states.view(batch_size, self.num_heads, self.head_dim)
+ hidden_states = selective_state_update(
+ cache_params.layers[self.layer_idx].recurrent_states,
+ hidden_states_reshaped,
+ dt,
+ A,
+ B,
+ C,
+ D,
+ z=None,
+ dt_bias=dt_bias,
+ dt_softplus=True,
+ )
+ hidden_states = hidden_states.view(batch_size, self.num_heads * self.head_dim)
+ hidden_states = self.norm(hidden_states, gate)
+ # The SSM kernels return fp32 regardless of the module dtype; cast back to the
+ # projection weight dtype so the matmul does not fail when out_proj.weight is a
+ # narrower dtype than the activations (e.g. fp32 activations with a bf16 out_proj).
+ out = self.out_proj(hidden_states.to(self.out_proj.weight.dtype))[:, None, ...]
+ # if no cache is found, calling the kernel
+ else:
+ if attention_mask is not None and not torch.all(attention_mask == 1):
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
+ dtype = hidden_states.dtype
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
+ # 1. Gated MLP's linear projection
+ projected_states = self.in_proj(hidden_states)
+ A = -torch.exp(self.A_log.float()) # (num_heads) or (intermediate_size, state_size)
+ dt_limit_kwargs = {} if self.time_step_limit is None else {"dt_limit": self.time_step_limit}
+ if attention_mask is not None:
+ input_not_masked = torch.all(attention_mask == 1)
+ else:
+ input_not_masked = True
+
+ if self.use_mem_eff_path and self.training and cache_params is None and input_not_masked:
+ out, ssm_state = mamba_split_conv1d_scan_combined(
+ projected_states,
+ self.conv1d.weight.squeeze(1),
+ self.conv1d.bias,
+ self.dt_bias,
+ A,
+ D=self.D,
+ chunk_size=self.chunk_size,
+ seq_idx=None,
+ activation=self.activation,
+ rmsnorm_weight=self.norm.weight,
+ rmsnorm_eps=self.norm.variance_epsilon,
+ outproj_weight=self.out_proj.weight,
+ outproj_bias=self.out_proj.bias,
+ headdim=self.head_dim,
+ ngroups=self.n_groups,
+ norm_before_gate=False,
+ return_final_states=True,
+ **dt_limit_kwargs,
+ )
+
+ else:
+ gate, hidden_states_B_C, time_step = torch.split(
+ projected_states,
+ [self.intermediate_size, self.conv_dim, self.num_heads],
+ dim=-1,
+ )
+
+ # 1D Convolution
+ if cache_params is not None:
+ hidden_states_B_C_t = hidden_states_B_C.transpose(1, 2)
+ conv_state = nn.functional.pad(
+ hidden_states_B_C_t, (self.conv_kernel_size - hidden_states_B_C_t.shape[-1], 0)
+ )
+ conv_state = cache_params.update_conv_state(conv_state, self.layer_idx)
+ if causal_conv1d_fn is None or self.activation not in ["silu", "swish"]:
+ hidden_states_B_C = self.act(
+ self.conv1d(hidden_states_B_C.transpose(1, 2)).transpose(1, 2)[:, :seq_len]
+ ) # (B, L, self.d_inner + 2 * ngroups * d_state)
+ else:
+ hidden_states_B_C = causal_conv1d_fn(
+ x=hidden_states_B_C.transpose(1, 2),
+ weight=self.conv1d.weight.squeeze(1),
+ bias=self.conv1d.bias,
+ activation=self.activation,
+ ).transpose(1, 2)[:, :seq_len]
+ hidden_states, B, C = torch.split(
+ hidden_states_B_C,
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
+ dim=-1,
+ )
+ if attention_mask is not None and not torch.all(attention_mask == 1):
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
+ dtype = hidden_states.dtype
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
+ scan_output, ssm_state = mamba_chunk_scan_combined(
+ hidden_states.view(batch_size, seq_len, -1, self.head_dim),
+ time_step,
+ A,
+ B.view(batch_size, seq_len, self.n_groups, -1),
+ C.view(batch_size, seq_len, self.n_groups, -1),
+ chunk_size=self.chunk_size,
+ D=self.D,
+ z=None,
+ seq_idx=None,
+ return_final_states=True,
+ dt_bias=self.dt_bias,
+ dt_softplus=True,
+ **dt_limit_kwargs,
+ )
+ if ssm_state is not None and cache_params is not None:
+ cache_params.update_recurrent_state(ssm_state, self.layer_idx)
+ scan_output = scan_output.view(batch_size, seq_len, -1)
+ # Multiply "gate" branch and apply extra normalization layer
+ scan_output = self.norm(scan_output, gate)
+ # The SSM kernels return fp32 regardless of the module dtype; cast back to the
+ # projection weight dtype so the matmul does not fail when out_proj.weight is a
+ # narrower dtype than the activations (e.g. fp32 activations with a bf16 out_proj).
+ out = self.out_proj(scan_output.to(self.out_proj.weight.dtype))
+ return out
+
+ # fmt: off
+ def torch_forward(self, input_states, cache_params: Cache | None=None, attention_mask: torch.Tensor | None = None):
+ batch_size, seq_len, _ = input_states.shape
+ dtype = input_states.dtype
+ # Gated MLP's linear projection
+ if cache_params is not None and cache_params.has_previous_state(self.layer_idx):
+ projected_states = self.in_proj(input_states)
+ else:
+ if attention_mask is not None:
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
+ input_states = (input_states * attention_mask[:, :, None]).to(dtype)
+ projected_states = self.in_proj(input_states)
+ d_mlp = (projected_states.shape[-1] - 2 * self.intermediate_size - 2 * self.n_groups * self.ssm_state_size- self.num_heads) // 2
+ _, _, gate, hidden_states, dt = projected_states.split(
+ [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
+ )
+ hidden_states = hidden_states.transpose(1, 2)
+
+ use_precomputed_state = cache_params is not None and cache_params.has_previous_state(self.layer_idx)
+
+ # Convolution sequence transformation
+ if use_precomputed_state:
+ conv_state = cache_params.update_conv_state(hidden_states, self.layer_idx)
+ hidden_states = torch.sum(conv_state * self.conv1d.weight[:, 0, :], dim=-1)
+ if self.use_conv_bias:
+ hidden_states += self.conv1d.bias
+ hidden_states = self.act(hidden_states).to(dtype)[:, None, ...] # [batch, 1, intermediate_size] : decoding
+ else:
+ if cache_params is not None:
+ conv_state = nn.functional.pad(
+ hidden_states,
+ (self.conv_kernel_size - hidden_states.shape[-1], 0)
+ )
+ conv_state = cache_params.update_conv_state(conv_state, self.layer_idx)
+
+ hidden_states = self.act(self.conv1d(hidden_states)[..., :seq_len].transpose(1, 2))
+ if attention_mask is not None:
+ dtype = hidden_states.dtype
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
+
+ hidden_states, B, C = torch.split(hidden_states, [self.intermediate_size, self.n_groups * self.ssm_state_size, self.n_groups * self.ssm_state_size], dim=-1)
+ A = -torch.exp(self.A_log.float()) # [num_heads]
+ if use_precomputed_state:
+ # Note: there is no need to pad parameter matrices here, as there is just one new token
+ # for batched generation
+ dt = dt[:, None, ...] if dt.ndim == 2 else dt[:, 0, :][:, None, ...]
+ dt = dt.transpose(1, 2).expand(batch_size, dt.shape[-1], self.head_dim)
+ # [num_heads] -> [num_heads, head_dim]
+ dt_bias = self.dt_bias[..., None].expand(self.dt_bias.shape[0], self.head_dim)
+
+ dt = torch.nn.functional.softplus(dt + dt_bias.to(dt.dtype))
+ dt = torch.clamp(dt, self.time_step_min) #, self.time_step_max)
+ A = A[..., None, None].expand(self.num_heads, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
+ # [bsz, num_heads, head_dim, state_size]
+ dA = torch.exp(dt[..., None] * A)
+
+ # Discretize B
+ # [bsz, n_groups * state_size] -> [bsz, n_groups, 1, state_size] ->
+ # -> [bsz, n_groups, group to head repetition factor, state_size] -> [bsz, num_heads, state_size]
+ B = B.reshape(batch_size, self.n_groups, -1)[..., None, :]
+ B = B.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, B.shape[-1]).contiguous()
+ B = B.reshape(batch_size, -1, B.shape[-1])
+ # [bsz, num_heads, head_dim, state_size]
+ dB = dt[..., None] * B[..., None, :]
+
+ # Discretize x into dB
+ # [bsz, intermediate_size] -> [bsz, num_heads, head_dim]
+ hidden_states = hidden_states.reshape(batch_size, -1, self.head_dim)
+ dBx = dB * hidden_states[..., None]
+
+ # State calculation
+ ssm_states = cache_params.layers[self.layer_idx].recurrent_states.clone()
+ ssm_states = ssm_states * dA + dBx
+ ssm_states = cache_params.update_recurrent_state(ssm_states, self.layer_idx)
+
+ # Subsequent output
+ # [bsz, n_groups * state_size] -> [bsz, num_heads, state_size]
+ C = C.reshape(batch_size, self.n_groups, -1)[..., None, :]
+ C = C.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, C.shape[-1]).contiguous()
+ C = C.reshape(batch_size, -1, C.shape[-1])
+ # [bsz, num_heads, head_dim]
+
+ ssm_states = ssm_states.to(C.dtype) # Shape: [b, h, d, n]
+ # Reshape ssm_states to merge the first two dimensions
+ ssm_states_reshaped = ssm_states.view(batch_size * self.num_heads, self.head_dim, self.ssm_state_size) # Shape: [b*h, d, n]
+ C_reshaped = C.view(batch_size * self.num_heads, self.ssm_state_size, 1) # Shape: [b*h, n, 1]
+ y = torch.bmm(ssm_states_reshaped, C_reshaped)
+ y = y.view(batch_size, self.num_heads, self.head_dim)
+
+ # D skip connection
+ # [num_heads] -> [num_heads, head_dim]
+ D = self.D[..., None].expand(self.D.shape[0], self.head_dim)
+ y = (y + hidden_states * D).to(y.dtype)
+
+ # [bsz, num_heads, head_dim] -> [bsz, 1, intermediate_size]
+ y = y.reshape(batch_size, -1)[:, None, ...]
+ else:
+ # begin ssd naive implementation without einsums
+ dt = nn.functional.softplus(dt + self.dt_bias)
+ dt = torch.clamp(dt, self.time_step_min)
+ hidden_states = hidden_states.reshape(batch_size, seq_len, -1, self.head_dim).float()
+ B = B.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
+ C = C.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
+ B = B.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
+ C = C.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
+ pad_size = (self.chunk_size - seq_len % self.chunk_size) % self.chunk_size
+
+ D_residual = self.D[..., None] * pad_tensor_by_size(hidden_states, pad_size)
+
+ # Discretize x and A
+ hidden_states = hidden_states * dt[..., None]
+ A = A.to(hidden_states.dtype) * dt
+
+ # Rearrange into blocks/chunks
+ hidden_states, A, B, C = [reshape_into_chunks(t, pad_size, self.chunk_size) for t in (hidden_states, A, B, C)]
+
+
+ # [bsz, -1, chunk_size, num_heads] -> [bsz, num_heads, -1, chunk_size]
+ A = A.permute(0, 3, 1, 2)
+ A_cumsum = torch.cumsum(A, dim=-1)
+
+ # 1. Compute the output for each intra-chunk (diagonal blocks)
+ # This is the analog of a causal mask
+ L = torch.exp(segment_sum(A))
+
+ # First, contraction of C and B to get G (attention-weights like)
+ G_intermediate = C[:, :, :, None, :, :] * B[:, :, None, :, : ,:] # shape: (b, c, l, s, h, n)
+ G = G_intermediate.sum(dim=-1) # shape: (b, c, l, s, h)
+
+
+ # Step 2: Compute M, equivalent to applying attention mask to weights
+ M_intermediate = G[..., None] * L.permute(0, 2, 3, 4, 1)[..., None]
+ M = M_intermediate.sum(dim=-1)
+
+ # Step 3: Compute Y_diag (apply to values)
+ Y_diag = (M[..., None] * hidden_states[:, :, None]).sum(3)
+
+ # (right term of low-rank factorization of off-diagonal blocks; B terms)
+
+ decay_states = torch.exp(A_cumsum[:, :, :, -1:] - A_cumsum)
+ B_decay_contraction = B * decay_states.permute(0, 2, 3, 1)[..., None]
+ # permute back B * decay states
+ states = (B_decay_contraction.permute(0, 1, 3, 2, 4)[..., None] * hidden_states.permute(0, 1, 3, 2, 4)[..., None, :]).sum(dim=3).permute(0, 1, 2, 4, 3)
+ previous_states = torch.zeros_like(states[:, :1])
+ states = torch.cat([previous_states, states], dim=1)
+ decay_chunk = torch.exp(segment_sum(nn.functional.pad(A_cumsum[:, :, :, -1], (1, 0))))
+
+ states_permuted = states.permute(0, 2, 1, 3, 4)
+ result = (decay_chunk[..., None, None] * states_permuted[:, :, None, ...]).sum(dim=2)
+ new_states = result.permute(0, 2, 1, 3, 4)
+ states, ssm_state = new_states[:, :-1], new_states[:, -1]
+
+ # Compute state -> output conversion per chunk
+ # (left term of low-rank factorization of off-diagonal blocks; C terms)
+ state_decay_out = torch.exp(A_cumsum)
+ # compute Yoff
+ C_times_states = (C[..., None, :] * states[:, :, None, ...])
+ state_decay_out_permuted = state_decay_out.permute(0, 2, 3, 1)
+ Y_off = (C_times_states.sum(-1) * state_decay_out_permuted[..., None])
+ # Add output of intra-chunk and inter-chunk terms (diagonal and off-diagonal blocks)
+
+ y = Y_diag + Y_off
+ # [bsz, -1, self.chunk_size, num_heads, head_dim] -> [bsz, (padded) seq_len, num_heads, head_dim]
+ y = y.reshape(batch_size, -1, self.num_heads, self.head_dim)
+
+ y = y + D_residual
+ # Cutting off padded chunks
+ if pad_size > 0:
+ y = y[:, :seq_len, :, :]
+ y = y.reshape(batch_size, seq_len, -1)
+ if ssm_state is not None and cache_params is not None:
+ cache_params.update_recurrent_state(ssm_state, self.layer_idx)
+
+ scan_output = self.norm(y, gate)
+
+ # end ssd naive
+
+ # 4. Final linear projection
+ contextualized_states = self.out_proj(scan_output.to(dtype)) # [batch, seq_len, hidden_size]
+ return contextualized_states
+ # fmt: on
+
+ def forward(
+ self,
+ hidden_states,
+ cache_params: Cache | None = None,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs,
+ ):
+ if is_fast_path_available and "cuda" in self.in_proj.weight.device.type and not is_torchdynamo_compiling():
+ return self.cuda_kernels_forward(hidden_states, cache_params, attention_mask)
+
+ return self.torch_forward(hidden_states, cache_params, attention_mask)
+
+
+class Zamba2MLP(nn.Module):
+ def __init__(self, config: Zamba2Config, num_fwd_mem_blocks=None, block_id: int | None = None):
+ """
+ This MLP layer contributes to tied transformer blocks aimed to increasing compute without increasing model size. Because this layer
+ is tied, un-tied adapter modules (formally same as LoRA, but used in the base model) are added to the up and gate projectors to increase expressivity with a small memory overhead.
+ """
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = config.intermediate_size
+ self.num_fwd_mem_blocks = num_fwd_mem_blocks
+ self.block_id = block_id
+
+ self.gate_up_proj = nn.Linear(self.hidden_size, 2 * self.intermediate_size, bias=config.add_bias_linear)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.add_bias_linear)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ self.gate_up_proj_adapter_list = nn.ModuleList([])
+ for i in range(self.num_fwd_mem_blocks):
+ if i % config.num_mem_blocks == block_id:
+ gate_up_proj_adapter = nn.Sequential(
+ nn.Linear(self.config.hidden_size, self.config.adapter_rank, bias=False),
+ nn.Linear(self.config.adapter_rank, 2 * self.intermediate_size, bias=False),
+ )
+ else:
+ gate_up_proj_adapter = nn.Identity()
+ self.gate_up_proj_adapter_list.append(gate_up_proj_adapter)
+
+ layer_block_map = config.hybrid_layer_ids
+ self.layer_dic = {value: index for index, value in enumerate(layer_block_map)}
+
+ def forward(self, hidden_state, layer_idx=None):
+ gate_up_state = self.gate_up_proj(hidden_state)
+ layer_idx = self.layer_dic[layer_idx]
+ gate_up_state = gate_up_state + self.gate_up_proj_adapter_list[layer_idx](hidden_state)
+
+ gate_up_state = torch.chunk(gate_up_state, 2, dim=-1)
+ hidden_state = self.act_fn(gate_up_state[0]) * gate_up_state[1]
+ output = self.down_proj(hidden_state)
+ return output
+
+
+class Zamba2AttentionDecoderLayer(ZambaAttentionDecoderLayer):
+ def __init__(self, config: Zamba2Config, block_id: int | None = None, layer_idx: int | None = None):
+ self.block_id = block_id
+ num_gs = len(config.hybrid_layer_ids)
+ super().__init__(config, layer_idx)
+ self.self_attn = Zamba2Attention(config, layer_idx=-1, num_fwd_mem_blocks=num_gs, block_id=block_id)
+ self.feed_forward = Zamba2MLP(config, num_fwd_mem_blocks=num_gs, block_id=block_id)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ original_hidden_states: torch.Tensor,
+ layer_idx: int,
+ attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ position_embeddings: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.FloatTensor]:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): output of previous Mamba layer of shape `(batch, seq_len, embed_dim)`
+ original_hidden_states (`torch.FloatTensor`): word embedding output of shape `(batch, seq_len, embed_dim)`.
+ This is concatenated with `hidden_states` (which is the output of the previous (mamba) layer). The
+ concatenated tensor is then used as input of the pre-attention RMSNorm
+ (see fig. 2 in https://huggingface.co/papers/2405.16712).
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
+ `(batch, sequence_length)` where padding elements are indicated by 0.
+ past_key_values (`Cache`, *optional*): cached past key and value projection states
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
+ (see `past_key_values`).
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
+ with `head_dim` being the embedding dimension of each attention head.
+ """
+ hidden_states = torch.concatenate([hidden_states, original_hidden_states], dim=-1)
+ hidden_states = self.input_layernorm(hidden_states)
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ layer_idx=layer_idx,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+
+ hidden_states = self.pre_ff_layernorm(hidden_states)
+ hidden_states = self.feed_forward(hidden_states, layer_idx)
+
+ return hidden_states
+
+
+class Zamba2MambaDecoderLayer(ZambaMambaDecoderLayer):
+ def __init__(self, config: Zamba2Config, layer_idx: int):
+ super().__init__(config, layer_idx)
+ self.mamba = Zamba2MambaMixer(config=config, layer_idx=layer_idx)
+ self.input_layernorm = Zamba2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+
+class Zamba2HybridLayer(ZambaHybridLayer):
+ def __init__(
+ self, shared_transformer: Zamba2AttentionDecoderLayer, linear: nn.Linear, mamba: Zamba2MambaDecoderLayer
+ ):
+ super().__init__(shared_transformer, linear, mamba)
+ del self.shared_transf
+ self.shared_transformer = shared_transformer
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ original_hidden_states: torch.Tensor | None = None,
+ layer_idx: int | None = None,
+ attention_mask: torch.Tensor | None = None,
+ causal_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ position_embeddings: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
+ original_hidden_states (`torch.FloatTensor`): word embedding output that will be concatenated with
+ hidden activations to form the input of the shared transformer layer.
+ layer_idx (`int`): layer number.
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
+ `(batch, sequence_length)` where padding elements are indicated by 0.
+ past_key_values (`Cache`, *optional*): cached past key and value projection states
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
+ (see `past_key_values`).
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
+ with `head_dim` being the embedding dimension of each attention head.
+ """
+
+ transformer_hidden_states = self.shared_transformer(
+ hidden_states,
+ original_hidden_states=original_hidden_states,
+ layer_idx=layer_idx,
+ attention_mask=causal_mask,
+ past_key_values=past_key_values,
+ position_embeddings=position_embeddings,
+ position_ids=position_ids,
+ **kwargs,
+ )
+ transformer_hidden_states = self.linear(transformer_hidden_states)
+
+ hidden_states = self.mamba_decoder(
+ hidden_states,
+ transformer_hidden_states=transformer_hidden_states,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+
+ return hidden_states
+
+
+@auto_docstring
+class Zamba2PreTrainedModel(PreTrainedModel):
+ config: Zamba2Config
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["Zamba2HybridLayer", "Zamba2MambaDecoderLayer"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = True
+ _supports_flex_attn = True
+ _supports_sdpa = True
+ _is_stateful = True
+ _can_record_outputs = {
+ "hidden_states": Zamba2MambaDecoderLayer,
+ "attentions": Zamba2Attention,
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ if isinstance(module, Zamba2MambaMixer):
+ dt = torch.exp(
+ torch.rand(self.config.n_mamba_heads)
+ * (math.log(self.config.time_step_max) - math.log(self.config.time_step_min))
+ + math.log(self.config.time_step_min)
+ ).clamp(min=self.config.time_step_floor)
+ # # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
+ init.copy_(module.dt_bias, inv_dt)
+
+ A = torch.arange(1, module.num_heads + 1)
+ init.copy_(module.A_log, torch.log(A))
+ init.ones_(module.D)
+
+
+class Zamba2Model(ZambaModel, Zamba2PreTrainedModel):
+ """
+ Model consisting of *config.num_hidden_layers* layers.
+
+ Args:
+ config: Zamba2Config
+ """
+
+ def __init__(self, config: Zamba2Config):
+ Zamba2PreTrainedModel.__init__(self, config)
+ self.config = config
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
+ self.layers_block_type = config.layers_block_type
+ self.layers = self.get_layers()
+
+ self._attn_implementation = config._attn_implementation
+ self.final_layernorm = Zamba2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ if config.use_mem_rope:
+ if config.use_long_context:
+ logger.warning_once(
+ "`use_long_context` set to `True`: using rescaled `rope_theta` and extended `max_position_embeddings`."
+ )
+ self.rotary_emb = Zamba2RotaryEmbedding(config)
+ self.gradient_checkpointing = False
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_layers(self):
+ layers = []
+ self._tied_weights_keys = {}
+ self.first_transformer_layer_id = 0
+ unique_hybrid_blocks = []
+
+ for layer_id, layer_type in enumerate(self.layers_block_type):
+ mamba_layer = Zamba2MambaDecoderLayer(self.config, layer_idx=layer_id)
+ if layer_type == "hybrid":
+ prefix_pattern = f"layers.{layer_id}.shared_transformer"
+
+ # Zamba ties Hybrid module weights by repeating blocks after every
+ # `num_mem_blocks`. So if `num_mem_blocks=2`, the blocks looks like
+ # [1, 2, 1, 2, 1, 2] where all "ones" share the same set of weights.
+ if (
+ not isinstance(unique_hybrid_blocks, list)
+ or len(unique_hybrid_blocks) >= self.config.num_mem_blocks
+ ):
+ if isinstance(unique_hybrid_blocks, list):
+ unique_hybrid_blocks = cycle(unique_hybrid_blocks)
+ target_pattern = next(unique_hybrid_blocks)
+ self._tied_weights_keys.update({prefix_pattern: target_pattern})
+ else:
+ # Store source patterns to which the subsequent modules will be tied
+ unique_hybrid_blocks.append(prefix_pattern)
+
+ block_id = layer_id % self.config.num_mem_blocks
+ attn_block = Zamba2AttentionDecoderLayer(self.config, block_id=block_id)
+ linear_layer = nn.Linear(self.config.hidden_size, self.config.hidden_size, bias=False)
+ layers.append(Zamba2HybridLayer(attn_block, linear_layer, mamba_layer))
+ else:
+ layers.append(mamba_layer)
+ return nn.ModuleList(layers)
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError(
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
+ )
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ hidden_states = inputs_embeds
+
+ original_hidden_states = torch.clone(inputs_embeds)
+ # original_hidden_states: word embedding output that will be concatenated with hidden activations to form the input of the shared transformer layer
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ causal_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_ids=position_ids,
+ )
+
+ # create position embeddings to be shared across the decoder layers
+ if self.config.use_mem_rope:
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
+ else:
+ position_embeddings = None
+
+ for layer_idx, layer in enumerate(self.layers):
+ hidden_states = layer(
+ hidden_states,
+ original_hidden_states,
+ layer_idx,
+ attention_mask,
+ causal_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ position_ids=position_ids,
+ **kwargs,
+ )
+
+ hidden_states = self.final_layernorm(hidden_states)
+
+ return BaseModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values if use_cache else None,
+ )
+
+
+class Zamba2ForCausalLM(ZambaForCausalLM):
+ def __init__(self, config: Zamba2Config):
+ super().__init__(config)
+ self.model = Zamba2Model(config)
+ self.post_init()
+
+
+class Zamba2ForSequenceClassification(ZambaForSequenceClassification):
+ def __init__(self, config: Zamba2Config):
+ super().__init__(config)
+ self.model = Zamba2Model(config)
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | SequenceClassifierOutputWithPast:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ transformer_outputs: BaseModelOutputWithPast = self.model(
+ input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+ hidden_states = transformer_outputs[0]
+ logits = self.score(hidden_states)
+
+ if input_ids is not None:
+ batch_size = input_ids.shape[0]
+ else:
+ batch_size = inputs_embeds.shape[0]
+
+ if self.config.pad_token_id is None and batch_size != 1:
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
+ if self.config.pad_token_id is None:
+ last_non_pad_token = -1
+ elif input_ids is not None:
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
+ else:
+ last_non_pad_token = -1
+ logger.warning_once(
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
+ )
+
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(
+ logits=pooled_logits, labels=labels, pooled_logits=pooled_logits, config=self.config, **kwargs
+ )
+
+ return SequenceClassifierOutputWithPast(
+ loss=loss,
+ logits=pooled_logits,
+ past_key_values=transformer_outputs.past_key_values,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+__all__ = [
+ "Zamba2ForCausalLM",
+ "Zamba2ForSequenceClassification",
+ "Zamba2Model",
+ "Zamba2PreTrainedModel",
+]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/__init__.py b/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a67ba1338d4f05ad57a462777310406c0c77ce84
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/__init__.py
@@ -0,0 +1,29 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_zoedepth import *
+ from .image_processing_pil_zoedepth import *
+ from .image_processing_zoedepth import *
+ from .modeling_zoedepth import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..da45b4100474ffadb9962656827f18f899bba662
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/__pycache__/configuration_zoedepth.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/__pycache__/configuration_zoedepth.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3d1cda7de1ca269763516c0538a2031cd5ea0a6b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/__pycache__/configuration_zoedepth.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/__pycache__/image_processing_pil_zoedepth.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/__pycache__/image_processing_pil_zoedepth.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..39f2849e95e81838f759e47165856de0f03f1c81
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/__pycache__/image_processing_pil_zoedepth.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/__pycache__/image_processing_zoedepth.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/__pycache__/image_processing_zoedepth.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..313e38b351bb13ce4c85581fd006e37164af6484
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/__pycache__/image_processing_zoedepth.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/__pycache__/modeling_zoedepth.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/__pycache__/modeling_zoedepth.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bd1958a3450099b8c1a805d7a1d1807bf5023b3b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/__pycache__/modeling_zoedepth.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/configuration_zoedepth.py b/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/configuration_zoedepth.py
new file mode 100644
index 0000000000000000000000000000000000000000..666264acc02147a46d2be107be5290dbc1dc88f0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/configuration_zoedepth.py
@@ -0,0 +1,163 @@
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""ZoeDepth model configuration"""
+
+from typing import Literal
+
+from huggingface_hub.dataclasses import strict
+
+from ...backbone_utils import consolidate_backbone_kwargs_to_config
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+from ..auto.configuration_auto import AutoConfig
+
+
+ZOEDEPTH_PRETRAINED_CONFIG_ARCHIVE_MAP = {
+ "Intel/zoedepth-nyu": "https://huggingface.co/Intel/zoedepth-nyu/resolve/main/config.json",
+}
+
+
+@auto_docstring(checkpoint="Intel/zoedepth-nyu")
+@strict
+class ZoeDepthConfig(PreTrainedConfig):
+ r"""
+ readout_type (`str`, *optional*, defaults to `"project"`):
+ The readout type to use when processing the readout token (CLS token) of the intermediate hidden states of
+ the ViT backbone. Can be one of [`"ignore"`, `"add"`, `"project"`].
+ - "ignore" simply ignores the CLS token.
+ - "add" passes the information from the CLS token to all other tokens by adding the representations.
+ - "project" passes information to the other tokens by concatenating the readout to all other tokens before
+ projecting the
+ representation to the original feature dimension D using a linear layer followed by a GELU non-linearity.
+ reassemble_factors (`list[int]`, *optional*, defaults to `[4, 2, 1, 0.5]`):
+ The up/downsampling factors of the reassemble layers.
+ neck_hidden_sizes (`list[str]`, *optional*, defaults to `[96, 192, 384, 768]`):
+ The hidden sizes to project to for the feature maps of the backbone.
+ fusion_hidden_size (`int`, *optional*, defaults to 256):
+ The number of channels before fusion.
+ head_in_index (`int`, *optional*, defaults to -1):
+ The index of the features to use in the heads.
+ use_batch_norm_in_fusion_residual (`bool`, *optional*, defaults to `False`):
+ Whether to use batch normalization in the pre-activate residual units of the fusion blocks.
+ use_bias_in_fusion_residual (`bool`, *optional*, defaults to `True`):
+ Whether to use bias in the pre-activate residual units of the fusion blocks.
+ num_relative_features (`int`, *optional*, defaults to 32):
+ The number of features to use in the relative depth estimation head.
+ add_projection (`bool`, *optional*, defaults to `False`):
+ Whether to add a projection layer before the depth estimation head.
+ bottleneck_features (`int`, *optional*, defaults to 256):
+ The number of features in the bottleneck layer.
+ num_attractors (`list[int], *optional*, defaults to `[16, 8, 4, 1]`):
+ The number of attractors to use in each stage.
+ bin_embedding_dim (`int`, *optional*, defaults to 128):
+ The dimension of the bin embeddings.
+ attractor_alpha (`int`, *optional*, defaults to 1000):
+ The alpha value to use in the attractor.
+ attractor_gamma (`int`, *optional*, defaults to 2):
+ The gamma value to use in the attractor.
+ attractor_kind (`str`, *optional*, defaults to `"mean"`):
+ The kind of attractor to use. Can be one of [`"mean"`, `"sum"`].
+ min_temp (`float`, *optional*, defaults to 0.0212):
+ The minimum temperature value to consider.
+ max_temp (`float`, *optional*, defaults to 50.0):
+ The maximum temperature value to consider.
+ bin_centers_type (`str`, *optional*, defaults to `"softplus"`):
+ Activation type used for bin centers. Can be "normed" or "softplus". For "normed" bin centers, linear normalization trick
+ is applied. This results in bounded bin centers. For "softplus", softplus activation is used and thus are unbounded.
+ bin_configurations (`list[dict]`, *optional*, defaults to `[{'n_bins': 64, 'min_depth': 0.001, 'max_depth': 10.0}]`):
+ Configuration for each of the bin heads.
+ Each configuration should consist of the following keys:
+ - name (`str`): The name of the bin head - only required in case of multiple bin configurations.
+ - `n_bins` (`int`): The number of bins to use.
+ - `min_depth` (`float`): The minimum depth value to consider.
+ - `max_depth` (`float`): The maximum depth value to consider.
+ In case only a single configuration is passed, the model will use a single head with the specified configuration.
+ In case multiple configurations are passed, the model will use multiple heads with the specified configurations.
+ num_patch_transformer_layers (`int`, *optional*):
+ The number of transformer layers to use in the patch transformer. Only used in case of multiple bin configurations.
+ patch_transformer_hidden_size (`int`, *optional*):
+ The hidden size to use in the patch transformer. Only used in case of multiple bin configurations.
+ patch_transformer_intermediate_size (`int`, *optional*):
+ The intermediate size to use in the patch transformer. Only used in case of multiple bin configurations.
+ patch_transformer_num_attention_heads (`int`, *optional*):
+ The number of attention heads to use in the patch transformer. Only used in case of multiple bin configurations.
+
+ Example:
+
+ ```python
+ >>> from transformers import ZoeDepthConfig, ZoeDepthForDepthEstimation
+
+ >>> # Initializing a ZoeDepth zoedepth-large style configuration
+ >>> configuration = ZoeDepthConfig()
+
+ >>> # Initializing a model from the zoedepth-large style configuration
+ >>> model = ZoeDepthForDepthEstimation(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "zoedepth"
+ sub_configs = {"backbone_config": AutoConfig}
+
+ backbone_config: dict | PreTrainedConfig | None = None
+ hidden_act: str = "gelu"
+ initializer_range: float = 0.02
+ batch_norm_eps: float = 1e-05
+ readout_type: Literal["ignore", "add", "project"] = "project"
+ reassemble_factors: list[int | float] | tuple[int | float, ...] = (4, 2, 1, 0.5)
+ neck_hidden_sizes: list[int] | tuple[int, ...] = (96, 192, 384, 768)
+ fusion_hidden_size: int = 256
+ head_in_index: int = -1
+ use_batch_norm_in_fusion_residual: bool = False
+ use_bias_in_fusion_residual: bool | None = None
+ num_relative_features: int = 32
+ add_projection: bool = False
+ bottleneck_features: int = 256
+ num_attractors: list[int] | tuple[int, ...] = (16, 8, 4, 1)
+ bin_embedding_dim: int = 128
+ attractor_alpha: int = 1000
+ attractor_gamma: int = 2
+ attractor_kind: Literal["mean", "sum"] = "mean"
+ min_temp: float = 0.0212
+ max_temp: float = 50.0
+ bin_centers_type: str = "softplus"
+ bin_configurations: list[dict] | None = None
+ num_patch_transformer_layers: int | None = None
+ patch_transformer_hidden_size: int | None = None
+ patch_transformer_intermediate_size: int | None = None
+ patch_transformer_num_attention_heads: int | None = None
+
+ def __post_init__(self, **kwargs):
+ self.backbone_config, kwargs = consolidate_backbone_kwargs_to_config(
+ backbone_config=self.backbone_config,
+ default_config_type="beit",
+ default_config_kwargs={
+ "image_size": 384,
+ "num_hidden_layers": 24,
+ "hidden_size": 1024,
+ "intermediate_size": 4096,
+ "num_attention_heads": 16,
+ "use_relative_position_bias": True,
+ "reshape_hidden_states": False,
+ "out_features": ["stage6", "stage12", "stage18", "stage24"],
+ },
+ **kwargs,
+ )
+ self.bin_configurations = self.bin_configurations or [{"n_bins": 64, "min_depth": 0.001, "max_depth": 10.0}]
+
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["ZOEDEPTH_PRETRAINED_CONFIG_ARCHIVE_MAP", "ZoeDepthConfig"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/image_processing_pil_zoedepth.py b/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/image_processing_pil_zoedepth.py
new file mode 100644
index 0000000000000000000000000000000000000000..6be12be7698e876a0d63b684dc51546b284651f2
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/image_processing_pil_zoedepth.py
@@ -0,0 +1,344 @@
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Image processor class for ZoeDepth."""
+
+import math
+from collections.abc import Iterable
+from typing import TYPE_CHECKING, Union
+
+import numpy as np
+
+from ...image_processing_backends import PilBackend
+from ...image_processing_utils import BatchFeature
+from ...image_transforms import PaddingMode
+from ...image_transforms import pad as np_pad
+from ...image_utils import (
+ IMAGENET_STANDARD_MEAN,
+ IMAGENET_STANDARD_STD,
+ ChannelDimension,
+ ImageInput,
+ PILImageResampling,
+ SizeDict,
+ get_image_size,
+)
+from ...processing_utils import ImagesKwargs, Unpack
+from ...utils import TensorType, auto_docstring, is_torch_available, is_torchvision_available, requires_backends
+from ...utils.import_utils import requires
+
+
+if TYPE_CHECKING:
+ from .modeling_zoedepth import ZoeDepthDepthEstimatorOutput
+
+if is_torch_available():
+ import torch
+ from torch import nn
+
+if is_torchvision_available():
+ import torchvision.transforms.v2.functional as tvF
+
+
+# Adapted from transformers.models.zoedepth.image_processing_zoedepth.ZoeDepthImageProcessorKwargs
+class ZoeDepthImageProcessorKwargs(ImagesKwargs, total=False):
+ r"""
+ keep_aspect_ratio (`bool`, *optional*, defaults to `self.keep_aspect_ratio`):
+ If `True`, the image is resized by choosing the smaller of the height and width scaling factors and using it
+ for both dimensions. This ensures that the image is scaled down as little as possible while still fitting
+ within the desired output size. In case `ensure_multiple_of` is also set, the image is further resized to a
+ size that is a multiple of this value by flooring the height and width to the nearest multiple of this value.
+ Can be overridden by `keep_aspect_ratio` in `preprocess`.
+ ensure_multiple_of (`int`, *optional*, defaults to `self.ensure_multiple_of`):
+ If `do_resize` is `True`, the image is resized to a size that is a multiple of this value. Works by flooring
+ the height and width to the nearest multiple of this value.
+ Works both with and without `keep_aspect_ratio` being set to `True`.
+ Can be overridden by `ensure_multiple_of` in `preprocess`.
+ """
+
+ keep_aspect_ratio: bool
+ ensure_multiple_of: int
+
+
+# Adapted from transformers.models.zoedepth.image_processing_zoedepth.get_resize_output_image_size
+def get_resize_output_image_size(
+ input_image: "torch.Tensor | np.ndarray",
+ output_size: int | Iterable[int],
+ keep_aspect_ratio: bool,
+ multiple: int,
+ input_data_format: str | ChannelDimension | None = None,
+) -> tuple[int, int]:
+ def constrain_to_multiple_of(val, multiple, min_val=0):
+ x = (np.round(val / multiple) * multiple).astype(int)
+
+ if x < min_val:
+ x = math.ceil(val / multiple) * multiple
+
+ return x
+
+ output_size = (output_size, output_size) if isinstance(output_size, int) else output_size
+
+ input_height, input_width = get_image_size(input_image, input_data_format)
+ output_height, output_width = output_size
+
+ # determine new height and width
+ scale_height = output_height / input_height
+ scale_width = output_width / input_width
+
+ if keep_aspect_ratio:
+ # scale as little as possible
+ if abs(1 - scale_width) < abs(1 - scale_height):
+ # fit width
+ scale_height = scale_width
+ else:
+ # fit height
+ scale_width = scale_height
+
+ new_height = constrain_to_multiple_of(scale_height * input_height, multiple=multiple)
+ new_width = constrain_to_multiple_of(scale_width * input_width, multiple=multiple)
+
+ return (new_height, new_width)
+
+
+@auto_docstring
+@requires(backends=("torch",))
+class ZoeDepthImageProcessorPil(PilBackend):
+ valid_kwargs = ZoeDepthImageProcessorKwargs
+ do_pad = True
+ do_rescale = True
+ do_normalize = True
+ image_mean = IMAGENET_STANDARD_MEAN
+ image_std = IMAGENET_STANDARD_STD
+ do_resize = True
+ size = {"height": 384, "width": 512}
+ resample = PILImageResampling.BILINEAR
+ keep_aspect_ratio = True
+ ensure_multiple_of = 1 / 32
+
+ def __init__(self, **kwargs: Unpack[ZoeDepthImageProcessorKwargs]) -> None:
+ super().__init__(**kwargs)
+
+ @auto_docstring
+ def preprocess(self, images: ImageInput, **kwargs: Unpack[ZoeDepthImageProcessorKwargs]) -> BatchFeature:
+ return super().preprocess(images, **kwargs)
+
+ def resize(
+ self,
+ image: np.ndarray,
+ size: SizeDict,
+ keep_aspect_ratio: bool = False,
+ ensure_multiple_of: int = 1,
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
+ ) -> np.ndarray:
+ """
+ Resize an image to target size `(size.height, size.width)`. If `keep_aspect_ratio` is `True`, the image
+ is resized to the largest possible size such that the aspect ratio is preserved. If `ensure_multiple_of` is
+ set, the image is resized to a size that is a multiple of this value.
+
+ Args:
+ image (`np.ndarray`):
+ Image to resize.
+ size (`SizeDict`):
+ Target size of the output image.
+ keep_aspect_ratio (`bool`, *optional*, defaults to `False`):
+ If `True`, the image is resized to the largest possible size such that the aspect ratio is preserved.
+ ensure_multiple_of (`int`, *optional*, defaults to 1):
+ The image is resized to a size that is a multiple of this value.
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
+ Defines the resampling filter to use if resizing the image. Otherwise, the image is resized to size
+ specified in `size`.
+ """
+ if not size.height or not size.width:
+ raise ValueError(f"The size dictionary must contain the keys 'height' and 'width'. Got {size}")
+ height, width = get_resize_output_image_size(
+ image,
+ output_size=(size.height, size.width),
+ keep_aspect_ratio=keep_aspect_ratio,
+ multiple=ensure_multiple_of,
+ input_data_format=ChannelDimension.FIRST,
+ )
+
+ torch_image = torch.from_numpy(image).unsqueeze(0)
+ # TODO support align_corners=True in image_transforms.resize
+ requires_backends(self, "torch")
+ resample_to_mode = {PILImageResampling.BILINEAR: "bilinear", PILImageResampling.BICUBIC: "bicubic"}
+ mode = resample_to_mode[resample]
+ resized_image = nn.functional.interpolate(
+ torch_image, (int(height), int(width)), mode=mode, align_corners=True
+ )
+ resized_image = resized_image.squeeze().numpy()
+
+ return resized_image
+
+ def pad_image(
+ self,
+ image: np.ndarray,
+ ):
+ """
+ Args:
+ image (`np.ndarray`):
+ Image to pad.
+ """
+ height, width = get_image_size(image, channel_dim=ChannelDimension.FIRST)
+
+ pad_height = int(np.sqrt(height / 2) * 3)
+ pad_width = int(np.sqrt(width / 2) * 3)
+
+ return np_pad(
+ image,
+ padding=((pad_height, pad_height), (pad_width, pad_width)),
+ mode=PaddingMode.REFLECT,
+ data_format=ChannelDimension.FIRST,
+ input_data_format=ChannelDimension.FIRST,
+ )
+
+ def _preprocess(
+ self,
+ images: list[np.ndarray],
+ do_resize: bool,
+ size: SizeDict,
+ keep_aspect_ratio: bool | None,
+ ensure_multiple_of: int | None,
+ resample: PILImageResampling | None,
+ do_pad: bool,
+ do_rescale: bool,
+ rescale_factor: float | None,
+ do_normalize: bool,
+ image_mean: float | list[float] | None,
+ image_std: float | list[float] | None,
+ return_tensors: str | TensorType | None = None,
+ **kwargs,
+ ) -> BatchFeature:
+ processed_images = []
+ for image in images:
+ if do_rescale:
+ image = self.rescale(image, rescale_factor)
+ if do_pad:
+ image = self.pad_image(image)
+ if do_resize:
+ image = self.resize(image, size, keep_aspect_ratio, ensure_multiple_of, resample)
+ if do_normalize:
+ image = self.normalize(image, image_mean, image_std)
+ processed_images.append(image)
+
+ return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors)
+
+ def post_process_depth_estimation(
+ self,
+ outputs: "ZoeDepthDepthEstimatorOutput",
+ source_sizes: TensorType | list[tuple[int, int]] | None | None = None,
+ target_sizes: TensorType | list[tuple[int, int]] | None | None = None,
+ outputs_flipped: Union["ZoeDepthDepthEstimatorOutput", None] | None = None,
+ do_remove_padding: bool | None | None = None,
+ ) -> list[dict[str, TensorType]]:
+ """
+ Converts the raw output of [`ZoeDepthDepthEstimatorOutput`] into final depth predictions and depth PIL images.
+ Only supports PyTorch.
+
+ Args:
+ outputs ([`ZoeDepthDepthEstimatorOutput`]):
+ Raw outputs of the model.
+ source_sizes (`TensorType` or `list[tuple[int, int]]`, *optional*):
+ Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the source size
+ (height, width) of each image in the batch before preprocessing. This argument should be dealt as
+ "required" unless the user passes `do_remove_padding=False` as input to this function.
+ target_sizes (`TensorType` or `list[tuple[int, int]]`, *optional*):
+ Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the target size
+ (height, width) of each image in the batch. If left to None, predictions will not be resized.
+ outputs_flipped ([`ZoeDepthDepthEstimatorOutput`], *optional*):
+ Raw outputs of the model from flipped input (averaged out in the end).
+ do_remove_padding (`bool`, *optional*):
+ By default ZoeDepth adds padding equal to `int(√(height / 2) * 3)` (and similarly for width) to fix the
+ boundary artifacts in the output depth map, so we need remove this padding during post_processing. The
+ parameter exists here in case the user changed the image preprocessing to not include padding.
+
+ Returns:
+ `list[dict[str, TensorType]]`: A list of dictionaries of tensors representing the processed depth
+ predictions.
+ """
+ requires_backends(self, "torch")
+
+ predicted_depth = outputs.predicted_depth
+
+ if (outputs_flipped is not None) and (predicted_depth.shape != outputs_flipped.predicted_depth.shape):
+ raise ValueError("Make sure that `outputs` and `outputs_flipped` have the same shape")
+
+ if (target_sizes is not None) and (len(predicted_depth) != len(target_sizes)):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the predicted depth"
+ )
+
+ if do_remove_padding is None:
+ do_remove_padding = self.do_pad
+
+ if source_sizes is None and do_remove_padding:
+ raise ValueError(
+ "Either `source_sizes` should be passed in, or `do_remove_padding` should be set to False"
+ )
+
+ if (source_sizes is not None) and (len(predicted_depth) != len(source_sizes)):
+ raise ValueError(
+ "Make sure that you pass in as many source image sizes as the batch dimension of the logits"
+ )
+
+ if outputs_flipped is not None:
+ predicted_depth = (predicted_depth + torch.flip(outputs_flipped.predicted_depth, dims=[-1])) / 2
+
+ predicted_depth = predicted_depth.unsqueeze(1)
+
+ # Zoe Depth model adds padding around the images to fix the boundary artifacts in the output depth map
+ # The padding length is `int(np.sqrt(img_h/2) * fh)` for the height and similar for the width
+ # fh (and fw respectively) are equal to '3' by default
+ # Check [here](https://github.com/isl-org/ZoeDepth/blob/edb6daf45458569e24f50250ef1ed08c015f17a7/zoedepth/models/depth_model.py#L57)
+ # for the original implementation.
+ # In this section, we remove this padding to get the final depth image and depth prediction
+ padding_factor_h = padding_factor_w = 3
+
+ results = []
+ target_sizes = [None] * len(predicted_depth) if target_sizes is None else target_sizes
+ source_sizes = [None] * len(predicted_depth) if source_sizes is None else source_sizes
+ for depth, target_size, source_size in zip(predicted_depth, target_sizes, source_sizes):
+ # depth.shape = [1, H, W]
+ if source_size is not None:
+ pad_h = pad_w = 0
+
+ if do_remove_padding:
+ pad_h = int(np.sqrt(source_size[0] / 2) * padding_factor_h)
+ pad_w = int(np.sqrt(source_size[1] / 2) * padding_factor_w)
+
+ depth = tvF.resize(
+ depth,
+ size=[source_size[0] + 2 * pad_h, source_size[1] + 2 * pad_w],
+ interpolation=tvF.InterpolationMode.BICUBIC,
+ antialias=False,
+ )
+
+ if pad_h > 0:
+ depth = depth[:, pad_h:-pad_h, :]
+ if pad_w > 0:
+ depth = depth[:, :, pad_w:-pad_w]
+
+ if target_size is not None:
+ target_size = [target_size[0], target_size[1]]
+ depth = tvF.resize(
+ depth,
+ size=target_size,
+ interpolation=tvF.InterpolationMode.BICUBIC,
+ antialias=False,
+ )
+ depth = depth.squeeze(0)
+ # depth.shape = [H, W]
+ results.append({"predicted_depth": depth})
+
+ return results
+
+
+__all__ = ["ZoeDepthImageProcessorPil"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/image_processing_zoedepth.py b/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/image_processing_zoedepth.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd1c0f9f79d5f6adeec8b798c59725134e377122
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/image_processing_zoedepth.py
@@ -0,0 +1,333 @@
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Image processor class for ZoeDepth."""
+
+import math
+from collections.abc import Iterable
+from typing import TYPE_CHECKING, Union
+
+import numpy as np
+import torch
+
+from ...image_processing_backends import TorchvisionBackend
+from ...image_processing_utils import BatchFeature
+from ...image_transforms import group_images_by_shape, reorder_images
+from ...image_utils import (
+ IMAGENET_STANDARD_MEAN,
+ IMAGENET_STANDARD_STD,
+ ChannelDimension,
+ ImageInput,
+ PILImageResampling,
+ SizeDict,
+ get_image_size,
+ pil_torch_interpolation_mapping,
+)
+from ...processing_utils import ImagesKwargs, Unpack
+from ...utils import TensorType, auto_docstring, requires_backends
+
+
+if TYPE_CHECKING:
+ from .modeling_zoedepth import ZoeDepthDepthEstimatorOutput
+
+from torchvision.transforms.v2 import functional as tvF
+
+
+class ZoeDepthImageProcessorKwargs(ImagesKwargs, total=False):
+ r"""
+ keep_aspect_ratio (`bool`, *optional*, defaults to `self.keep_aspect_ratio`):
+ If `True`, the image is resized by choosing the smaller of the height and width scaling factors and using it
+ for both dimensions. This ensures that the image is scaled down as little as possible while still fitting
+ within the desired output size. In case `ensure_multiple_of` is also set, the image is further resized to a
+ size that is a multiple of this value by flooring the height and width to the nearest multiple of this value.
+ Can be overridden by `keep_aspect_ratio` in `preprocess`.
+ ensure_multiple_of (`int`, *optional*, defaults to `self.ensure_multiple_of`):
+ If `do_resize` is `True`, the image is resized to a size that is a multiple of this value. Works by flooring
+ the height and width to the nearest multiple of this value.
+ Works both with and without `keep_aspect_ratio` being set to `True`.
+ Can be overridden by `ensure_multiple_of` in `preprocess`.
+ """
+
+ keep_aspect_ratio: bool
+ ensure_multiple_of: int
+
+
+def get_resize_output_image_size(
+ input_image: "torch.Tensor | np.ndarray",
+ output_size: int | Iterable[int],
+ keep_aspect_ratio: bool,
+ multiple: int,
+ input_data_format: str | ChannelDimension | None = None,
+) -> tuple[int, int]:
+ def constrain_to_multiple_of(val, multiple, min_val=0):
+ x = (np.round(val / multiple) * multiple).astype(int)
+
+ if x < min_val:
+ x = math.ceil(val / multiple) * multiple
+
+ return x
+
+ output_size = (output_size, output_size) if isinstance(output_size, int) else output_size
+
+ input_height, input_width = get_image_size(input_image, input_data_format)
+ output_height, output_width = output_size
+
+ # determine new height and width
+ scale_height = output_height / input_height
+ scale_width = output_width / input_width
+
+ if keep_aspect_ratio:
+ # scale as little as possible
+ if abs(1 - scale_width) < abs(1 - scale_height):
+ # fit width
+ scale_height = scale_width
+ else:
+ # fit height
+ scale_width = scale_height
+
+ new_height = constrain_to_multiple_of(scale_height * input_height, multiple=multiple)
+ new_width = constrain_to_multiple_of(scale_width * input_width, multiple=multiple)
+
+ return (new_height, new_width)
+
+
+@auto_docstring
+class ZoeDepthImageProcessor(TorchvisionBackend):
+ valid_kwargs = ZoeDepthImageProcessorKwargs
+ do_pad = True
+ do_rescale = True
+ do_normalize = True
+ image_mean = IMAGENET_STANDARD_MEAN
+ image_std = IMAGENET_STANDARD_STD
+ do_resize = True
+ size = {"height": 384, "width": 512}
+ resample = PILImageResampling.BILINEAR
+ keep_aspect_ratio = True
+ ensure_multiple_of = 1 / 32
+
+ def __init__(self, **kwargs: Unpack[ZoeDepthImageProcessorKwargs]) -> None:
+ super().__init__(**kwargs)
+
+ @auto_docstring
+ def preprocess(self, images: ImageInput, **kwargs: Unpack[ZoeDepthImageProcessorKwargs]) -> BatchFeature:
+ return super().preprocess(images, **kwargs)
+
+ def resize(
+ self,
+ images: "torch.Tensor",
+ size: SizeDict,
+ keep_aspect_ratio: bool = False,
+ ensure_multiple_of: int = 1,
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None" = None,
+ ) -> "torch.Tensor":
+ """
+ Resize an image or batched images to target size `(size.height, size.width)`. If `keep_aspect_ratio` is `True`, the image
+ is resized to the largest possible size such that the aspect ratio is preserved. If `ensure_multiple_of` is
+ set, the image is resized to a size that is a multiple of this value.
+
+ Args:
+ images (`torch.Tensor`):
+ Images to resize.
+ size (`SizeDict`):
+ Target size of the output image.
+ keep_aspect_ratio (`bool`, *optional*, defaults to `False`):
+ If `True`, the image is resized to the largest possible size such that the aspect ratio is preserved.
+ ensure_multiple_of (`int`, *optional*, defaults to 1):
+ The image is resized to a size that is a multiple of this value.
+ resample (`tvF.InterpolationMode`, *optional*, defaults to `InterpolationMode.BILINEAR`):
+ Defines the resampling filter to use if resizing the image. Otherwise, the image is resized to size
+ specified in `size`.
+ """
+ if not size.height or not size.width:
+ raise ValueError(f"The size dictionary must contain the keys 'height' and 'width'. Got {size}")
+ output_size = get_resize_output_image_size(
+ images,
+ output_size=(size.height, size.width),
+ keep_aspect_ratio=keep_aspect_ratio,
+ multiple=ensure_multiple_of,
+ input_data_format=ChannelDimension.FIRST,
+ )
+ height, width = output_size
+
+ # Convert resample to string mode for torch.nn.functional.interpolate
+ if not isinstance(resample, tvF.InterpolationMode):
+ interpolation = pil_torch_interpolation_mapping[resample]
+
+ resized_images = torch.nn.functional.interpolate(
+ images, (int(height), int(width)), mode=interpolation.value, align_corners=True
+ )
+
+ return resized_images
+
+ def _pad_images(
+ self,
+ images: "torch.Tensor",
+ ):
+ """
+ Args:
+ images (`torch.Tensor`):
+ Image to pad.
+ """
+ height, width = get_image_size(images, channel_dim=ChannelDimension.FIRST)
+
+ pad_height = int(np.sqrt(height / 2) * 3)
+ pad_width = int(np.sqrt(width / 2) * 3)
+
+ return tvF.pad(images, padding=(pad_width, pad_height), padding_mode="reflect")
+
+ def _preprocess(
+ self,
+ images: list["torch.Tensor"],
+ do_resize: bool,
+ size: SizeDict,
+ keep_aspect_ratio: bool | None,
+ ensure_multiple_of: int | None,
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None",
+ do_pad: bool,
+ do_rescale: bool,
+ rescale_factor: float | None,
+ do_normalize: bool,
+ image_mean: float | list[float] | None,
+ image_std: float | list[float] | None,
+ disable_grouping: bool | None,
+ return_tensors: str | TensorType | None = None,
+ **kwargs,
+ ) -> BatchFeature:
+ # Group images by size for batched resizing
+ grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
+ resized_images_grouped = {}
+ for shape, stacked_images in grouped_images.items():
+ if do_rescale:
+ stacked_images = self.rescale(stacked_images, rescale_factor)
+ if do_pad:
+ stacked_images = self._pad_images(images=stacked_images)
+ if do_resize:
+ stacked_images = self.resize(stacked_images, size, keep_aspect_ratio, ensure_multiple_of, resample)
+ if do_normalize:
+ stacked_images = self.normalize(stacked_images, image_mean, image_std)
+ resized_images_grouped[shape] = stacked_images
+ processed_images = reorder_images(resized_images_grouped, grouped_images_index)
+
+ return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors)
+
+ def post_process_depth_estimation(
+ self,
+ outputs: "ZoeDepthDepthEstimatorOutput",
+ source_sizes: TensorType | list[tuple[int, int]] | None | None = None,
+ target_sizes: TensorType | list[tuple[int, int]] | None | None = None,
+ outputs_flipped: Union["ZoeDepthDepthEstimatorOutput", None] | None = None,
+ do_remove_padding: bool | None | None = None,
+ ) -> list[dict[str, TensorType]]:
+ """
+ Converts the raw output of [`ZoeDepthDepthEstimatorOutput`] into final depth predictions and depth PIL images.
+ Only supports PyTorch.
+
+ Args:
+ outputs ([`ZoeDepthDepthEstimatorOutput`]):
+ Raw outputs of the model.
+ source_sizes (`TensorType` or `list[tuple[int, int]]`, *optional*):
+ Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the source size
+ (height, width) of each image in the batch before preprocessing. This argument should be dealt as
+ "required" unless the user passes `do_remove_padding=False` as input to this function.
+ target_sizes (`TensorType` or `list[tuple[int, int]]`, *optional*):
+ Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the target size
+ (height, width) of each image in the batch. If left to None, predictions will not be resized.
+ outputs_flipped ([`ZoeDepthDepthEstimatorOutput`], *optional*):
+ Raw outputs of the model from flipped input (averaged out in the end).
+ do_remove_padding (`bool`, *optional*):
+ By default ZoeDepth adds padding equal to `int(√(height / 2) * 3)` (and similarly for width) to fix the
+ boundary artifacts in the output depth map, so we need remove this padding during post_processing. The
+ parameter exists here in case the user changed the image preprocessing to not include padding.
+
+ Returns:
+ `list[dict[str, TensorType]]`: A list of dictionaries of tensors representing the processed depth
+ predictions.
+ """
+ requires_backends(self, "torch")
+
+ predicted_depth = outputs.predicted_depth
+
+ if (outputs_flipped is not None) and (predicted_depth.shape != outputs_flipped.predicted_depth.shape):
+ raise ValueError("Make sure that `outputs` and `outputs_flipped` have the same shape")
+
+ if (target_sizes is not None) and (len(predicted_depth) != len(target_sizes)):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the predicted depth"
+ )
+
+ if do_remove_padding is None:
+ do_remove_padding = self.do_pad
+
+ if source_sizes is None and do_remove_padding:
+ raise ValueError(
+ "Either `source_sizes` should be passed in, or `do_remove_padding` should be set to False"
+ )
+
+ if (source_sizes is not None) and (len(predicted_depth) != len(source_sizes)):
+ raise ValueError(
+ "Make sure that you pass in as many source image sizes as the batch dimension of the logits"
+ )
+
+ if outputs_flipped is not None:
+ predicted_depth = (predicted_depth + torch.flip(outputs_flipped.predicted_depth, dims=[-1])) / 2
+
+ predicted_depth = predicted_depth.unsqueeze(1)
+
+ # Zoe Depth model adds padding around the images to fix the boundary artifacts in the output depth map
+ # The padding length is `int(np.sqrt(img_h/2) * fh)` for the height and similar for the width
+ # fh (and fw respectively) are equal to '3' by default
+ # Check [here](https://github.com/isl-org/ZoeDepth/blob/edb6daf45458569e24f50250ef1ed08c015f17a7/zoedepth/models/depth_model.py#L57)
+ # for the original implementation.
+ # In this section, we remove this padding to get the final depth image and depth prediction
+ padding_factor_h = padding_factor_w = 3
+
+ results = []
+ target_sizes = [None] * len(predicted_depth) if target_sizes is None else target_sizes
+ source_sizes = [None] * len(predicted_depth) if source_sizes is None else source_sizes
+ for depth, target_size, source_size in zip(predicted_depth, target_sizes, source_sizes):
+ # depth.shape = [1, H, W]
+ if source_size is not None:
+ pad_h = pad_w = 0
+
+ if do_remove_padding:
+ pad_h = int(np.sqrt(source_size[0] / 2) * padding_factor_h)
+ pad_w = int(np.sqrt(source_size[1] / 2) * padding_factor_w)
+
+ depth = tvF.resize(
+ depth,
+ size=[source_size[0] + 2 * pad_h, source_size[1] + 2 * pad_w],
+ interpolation=tvF.InterpolationMode.BICUBIC,
+ antialias=False,
+ )
+
+ if pad_h > 0:
+ depth = depth[:, pad_h:-pad_h, :]
+ if pad_w > 0:
+ depth = depth[:, :, pad_w:-pad_w]
+
+ if target_size is not None:
+ target_size = [target_size[0], target_size[1]]
+ depth = tvF.resize(
+ depth,
+ size=target_size,
+ interpolation=tvF.InterpolationMode.BICUBIC,
+ antialias=False,
+ )
+ depth = depth.squeeze(0)
+ # depth.shape = [H, W]
+ results.append({"predicted_depth": depth})
+
+ return results
+
+
+__all__ = ["ZoeDepthImageProcessor"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/modeling_zoedepth.py b/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/modeling_zoedepth.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c107022a595e53db57836121113d8e2fc62b65f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/modeling_zoedepth.py
@@ -0,0 +1,1349 @@
+# Copyright 2024 Intel Labs and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch ZoeDepth model."""
+
+import math
+from dataclasses import dataclass
+
+import torch
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...backbone_utils import load_backbone
+from ...modeling_outputs import DepthEstimatorOutput
+from ...modeling_utils import PreTrainedModel
+from ...utils import ModelOutput, auto_docstring, logging
+from .configuration_zoedepth import ZoeDepthConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(
+ custom_intro="""
+ Extension of `DepthEstimatorOutput` to include domain logits (ZoeDepth specific).
+ """
+)
+@dataclass
+class ZoeDepthDepthEstimatorOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Classification (or regression if config.num_labels==1) loss.
+ domain_logits (`torch.FloatTensor` of shape `(batch_size, num_domains)`):
+ Logits for each domain (e.g. NYU and KITTI) in case multiple metric heads are used.
+ """
+
+ loss: torch.FloatTensor | None = None
+ predicted_depth: torch.FloatTensor | None = None
+ domain_logits: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
+ attentions: tuple[torch.FloatTensor, ...] | None = None
+
+
+class ZoeDepthReassembleStage(nn.Module):
+ """
+ This class reassembles the hidden states of the backbone into image-like feature representations at various
+ resolutions.
+
+ This happens in 3 stages:
+ 1. Map the N + 1 tokens to a set of N tokens, by taking into account the readout ([CLS]) token according to
+ `config.readout_type`.
+ 2. Project the channel dimension of the hidden states according to `config.neck_hidden_sizes`.
+ 3. Resizing the spatial dimensions (height, width).
+
+ Args:
+ config (`[ZoeDepthConfig]`):
+ Model configuration class defining the model architecture.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+
+ self.readout_type = config.readout_type
+ self.layers = nn.ModuleList()
+
+ for neck_hidden_size, factor in zip(config.neck_hidden_sizes, config.reassemble_factors):
+ self.layers.append(ZoeDepthReassembleLayer(config, channels=neck_hidden_size, factor=factor))
+
+ if config.readout_type == "project":
+ self.readout_projects = nn.ModuleList()
+ hidden_size = config.backbone_hidden_size
+ for _ in config.neck_hidden_sizes:
+ self.readout_projects.append(
+ nn.Sequential(nn.Linear(2 * hidden_size, hidden_size), ACT2FN[config.hidden_act])
+ )
+
+ def forward(self, hidden_states: list[torch.Tensor], patch_height, patch_width) -> list[torch.Tensor]:
+ """
+ Args:
+ hidden_states (`list[torch.FloatTensor]`, each of shape `(batch_size, sequence_length + 1, hidden_size)`):
+ List of hidden states from the backbone.
+ """
+ batch_size = hidden_states[0].shape[0]
+
+ # stack along batch dimension
+ # shape (batch_size*num_stages, sequence_length + 1, hidden_size)
+ hidden_states = torch.cat(hidden_states, dim=0)
+
+ cls_token, hidden_states = hidden_states[:, 0], hidden_states[:, 1:]
+ # reshape hidden_states to (batch_size*num_stages, num_channels, height, width)
+ total_batch_size, sequence_length, num_channels = hidden_states.shape
+ hidden_states = hidden_states.reshape(total_batch_size, patch_height, patch_width, num_channels)
+ hidden_states = hidden_states.permute(0, 3, 1, 2).contiguous()
+
+ if self.readout_type == "project":
+ # reshape to (batch_size*num_stages, height*width, num_channels)
+ hidden_states = hidden_states.flatten(2).permute((0, 2, 1))
+ readout = cls_token.unsqueeze(dim=1).expand_as(hidden_states)
+ # concatenate the readout token to the hidden states
+ # to get (batch_size*num_stages, height*width, 2*num_channels)
+ hidden_states = torch.cat((hidden_states, readout), -1)
+ elif self.readout_type == "add":
+ hidden_states = hidden_states + cls_token.unsqueeze(-1)
+
+ out = []
+ for stage_idx, hidden_state in enumerate(hidden_states.split(batch_size, dim=0)):
+ if self.readout_type == "project":
+ hidden_state = self.readout_projects[stage_idx](hidden_state)
+
+ # reshape back to (batch_size, num_channels, height, width)
+ hidden_state = hidden_state.permute(0, 2, 1).reshape(batch_size, -1, patch_height, patch_width)
+ hidden_state = self.layers[stage_idx](hidden_state)
+ out.append(hidden_state)
+
+ return out
+
+
+class ZoeDepthReassembleLayer(nn.Module):
+ def __init__(self, config, channels, factor):
+ super().__init__()
+ # projection
+ hidden_size = config.backbone_hidden_size
+ self.projection = nn.Conv2d(in_channels=hidden_size, out_channels=channels, kernel_size=1)
+
+ # up/down sampling depending on factor
+ if factor > 1:
+ self.resize = nn.ConvTranspose2d(channels, channels, kernel_size=factor, stride=factor, padding=0)
+ elif factor == 1:
+ self.resize = nn.Identity()
+ elif factor < 1:
+ # so should downsample
+ self.resize = nn.Conv2d(channels, channels, kernel_size=3, stride=int(1 / factor), padding=1)
+
+ # Copied from transformers.models.dpt.modeling_dpt.DPTReassembleLayer.forward with DPT->ZoeDepth
+ def forward(self, hidden_state):
+ hidden_state = self.projection(hidden_state)
+ hidden_state = self.resize(hidden_state)
+ return hidden_state
+
+
+# Copied from transformers.models.dpt.modeling_dpt.DPTFeatureFusionStage with DPT->ZoeDepth
+class ZoeDepthFeatureFusionStage(nn.Module):
+ def __init__(self, config: ZoeDepthConfig):
+ super().__init__()
+ self.layers = nn.ModuleList()
+ for _ in range(len(config.neck_hidden_sizes)):
+ self.layers.append(ZoeDepthFeatureFusionLayer(config))
+
+ def forward(self, hidden_states):
+ # reversing the hidden_states, we start from the last
+ hidden_states = hidden_states[::-1]
+
+ fused_hidden_states = []
+ fused_hidden_state = None
+ for hidden_state, layer in zip(hidden_states, self.layers):
+ if fused_hidden_state is None:
+ # first layer only uses the last hidden_state
+ fused_hidden_state = layer(hidden_state)
+ else:
+ fused_hidden_state = layer(fused_hidden_state, hidden_state)
+ fused_hidden_states.append(fused_hidden_state)
+
+ return fused_hidden_states
+
+
+# Copied from transformers.models.dpt.modeling_dpt.DPTPreActResidualLayer with DPT->ZoeDepth
+class ZoeDepthPreActResidualLayer(nn.Module):
+ """
+ ResidualConvUnit, pre-activate residual unit.
+
+ Args:
+ config (`[ZoeDepthConfig]`):
+ Model configuration class defining the model architecture.
+ """
+
+ # Ignore copy
+ def __init__(self, config):
+ super().__init__()
+
+ self.use_batch_norm = config.use_batch_norm_in_fusion_residual
+ use_bias_in_fusion_residual = (
+ config.use_bias_in_fusion_residual
+ if config.use_bias_in_fusion_residual is not None
+ else not self.use_batch_norm
+ )
+
+ self.activation1 = nn.ReLU()
+ self.convolution1 = nn.Conv2d(
+ config.fusion_hidden_size,
+ config.fusion_hidden_size,
+ kernel_size=3,
+ stride=1,
+ padding=1,
+ bias=use_bias_in_fusion_residual,
+ )
+
+ self.activation2 = nn.ReLU()
+ self.convolution2 = nn.Conv2d(
+ config.fusion_hidden_size,
+ config.fusion_hidden_size,
+ kernel_size=3,
+ stride=1,
+ padding=1,
+ bias=use_bias_in_fusion_residual,
+ )
+
+ if self.use_batch_norm:
+ self.batch_norm1 = nn.BatchNorm2d(config.fusion_hidden_size, eps=config.batch_norm_eps)
+ self.batch_norm2 = nn.BatchNorm2d(config.fusion_hidden_size, eps=config.batch_norm_eps)
+
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ residual = hidden_state
+ hidden_state = self.activation1(hidden_state)
+
+ hidden_state = self.convolution1(hidden_state)
+
+ if self.use_batch_norm:
+ hidden_state = self.batch_norm1(hidden_state)
+
+ hidden_state = self.activation2(hidden_state)
+ hidden_state = self.convolution2(hidden_state)
+
+ if self.use_batch_norm:
+ hidden_state = self.batch_norm2(hidden_state)
+
+ return hidden_state + residual
+
+
+# Copied from transformers.models.dpt.modeling_dpt.DPTFeatureFusionLayer with DPT->ZoeDepth
+class ZoeDepthFeatureFusionLayer(nn.Module):
+ """Feature fusion layer, merges feature maps from different stages.
+
+ Args:
+ config (`[ZoeDepthConfig]`):
+ Model configuration class defining the model architecture.
+ align_corners (`bool`, *optional*, defaults to `True`):
+ The align_corner setting for bilinear upsample.
+ """
+
+ def __init__(self, config: ZoeDepthConfig, align_corners: bool = True):
+ super().__init__()
+
+ self.align_corners = align_corners
+
+ self.projection = nn.Conv2d(config.fusion_hidden_size, config.fusion_hidden_size, kernel_size=1, bias=True)
+
+ self.residual_layer1 = ZoeDepthPreActResidualLayer(config)
+ self.residual_layer2 = ZoeDepthPreActResidualLayer(config)
+
+ def forward(self, hidden_state: torch.Tensor, residual: torch.Tensor | None = None) -> torch.Tensor:
+ if residual is not None:
+ if hidden_state.shape != residual.shape:
+ residual = nn.functional.interpolate(
+ residual, size=(hidden_state.shape[2], hidden_state.shape[3]), mode="bilinear", align_corners=False
+ )
+ hidden_state = hidden_state + self.residual_layer1(residual)
+
+ hidden_state = self.residual_layer2(hidden_state)
+ hidden_state = nn.functional.interpolate(
+ hidden_state, scale_factor=2, mode="bilinear", align_corners=self.align_corners
+ )
+ hidden_state = self.projection(hidden_state)
+
+ return hidden_state
+
+
+class ZoeDepthNeck(nn.Module):
+ """
+ ZoeDepthNeck. A neck is a module that is normally used between the backbone and the head. It takes a list of tensors as
+ input and produces another list of tensors as output. For ZoeDepth, it includes 2 stages:
+
+ * ZoeDepthReassembleStage
+ * ZoeDepthFeatureFusionStage.
+
+ Args:
+ config (dict): config dict.
+ """
+
+ # Copied from transformers.models.dpt.modeling_dpt.DPTNeck.__init__ with DPT->ZoeDepth
+ def __init__(self, config: ZoeDepthConfig):
+ super().__init__()
+ self.config = config
+
+ # postprocessing: only required in case of a non-hierarchical backbone (e.g. ViT, BEiT)
+ if config.backbone_config is not None and config.backbone_config.model_type == "swinv2":
+ self.reassemble_stage = None
+ else:
+ self.reassemble_stage = ZoeDepthReassembleStage(config)
+
+ self.convs = nn.ModuleList()
+ for channel in config.neck_hidden_sizes:
+ self.convs.append(nn.Conv2d(channel, config.fusion_hidden_size, kernel_size=3, padding=1, bias=False))
+
+ # fusion
+ self.fusion_stage = ZoeDepthFeatureFusionStage(config)
+
+ def forward(self, hidden_states: list[torch.Tensor], patch_height, patch_width) -> list[torch.Tensor]:
+ """
+ Args:
+ hidden_states (`list[torch.FloatTensor]`, each of shape `(batch_size, sequence_length, hidden_size)` or `(batch_size, hidden_size, height, width)`):
+ List of hidden states from the backbone.
+ """
+ if not isinstance(hidden_states, (tuple, list)):
+ raise TypeError("hidden_states should be a tuple or list of tensors")
+
+ if len(hidden_states) != len(self.config.neck_hidden_sizes):
+ raise ValueError("The number of hidden states should be equal to the number of neck hidden sizes.")
+
+ # postprocess hidden states
+ if self.reassemble_stage is not None:
+ hidden_states = self.reassemble_stage(hidden_states, patch_height, patch_width)
+
+ features = [self.convs[i](feature) for i, feature in enumerate(hidden_states)]
+
+ # fusion blocks
+ output = self.fusion_stage(features)
+
+ return output, features[-1]
+
+
+class ZoeDepthRelativeDepthEstimationHead(nn.Module):
+ """
+ Relative depth estimation head consisting of 3 convolutional layers. It progressively halves the feature dimension and upsamples
+ the predictions to the input resolution after the first convolutional layer (details can be found in DPT's paper's
+ supplementary material).
+ """
+
+ def __init__(self, config):
+ super().__init__()
+
+ self.head_in_index = config.head_in_index
+
+ self.projection = None
+ if config.add_projection:
+ self.projection = nn.Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
+
+ features = config.fusion_hidden_size
+ self.conv1 = nn.Conv2d(features, features // 2, kernel_size=3, stride=1, padding=1)
+ self.upsample = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=True)
+ self.conv2 = nn.Conv2d(features // 2, config.num_relative_features, kernel_size=3, stride=1, padding=1)
+ self.conv3 = nn.Conv2d(config.num_relative_features, 1, kernel_size=1, stride=1, padding=0)
+
+ def forward(self, hidden_states: list[torch.Tensor]) -> torch.Tensor:
+ # use last features
+ hidden_states = hidden_states[self.head_in_index]
+
+ if self.projection is not None:
+ hidden_states = self.projection(hidden_states)
+ hidden_states = nn.ReLU()(hidden_states)
+
+ hidden_states = self.conv1(hidden_states)
+ hidden_states = self.upsample(hidden_states)
+ hidden_states = self.conv2(hidden_states)
+ hidden_states = nn.ReLU()(hidden_states)
+ # we need the features here (after second conv + ReLu)
+ features = hidden_states
+ hidden_states = self.conv3(hidden_states)
+ hidden_states = nn.ReLU()(hidden_states)
+
+ predicted_depth = hidden_states.squeeze(dim=1)
+
+ return predicted_depth, features
+
+
+def log_binom(n, k, eps=1e-7):
+ """log(nCk) using stirling approximation"""
+ n = n + eps
+ k = k + eps
+ return n * torch.log(n) - k * torch.log(k) - (n - k) * torch.log(n - k + eps)
+
+
+class LogBinomialSoftmax(nn.Module):
+ def __init__(self, n_classes=256, act=torch.softmax):
+ """Compute log binomial distribution for n_classes
+
+ Args:
+ n_classes (`int`, *optional*, defaults to 256):
+ Number of output classes.
+ act (`torch.nn.Module`, *optional*, defaults to `torch.softmax`):
+ Activation function to apply to the output.
+ """
+ super().__init__()
+ self.k = n_classes
+ self.act = act
+ self.register_buffer("k_idx", torch.arange(0, n_classes).view(1, -1, 1, 1), persistent=False)
+ self.register_buffer("k_minus_1", torch.tensor([self.k - 1]).view(1, -1, 1, 1), persistent=False)
+
+ def forward(self, probabilities, temperature=1.0, eps=1e-4):
+ """Compute the log binomial distribution for probabilities.
+
+ Args:
+ probabilities (`torch.Tensor` of shape `(batch_size, num_channels, height, width)`):
+ Tensor containing probabilities of each class.
+ temperature (`float` or `torch.Tensor` of shape `(batch_size, num_channels, height, width)`, *optional*, defaults to 1):
+ Temperature of distribution.
+ eps (`float`, *optional*, defaults to 1e-4):
+ Small number for numerical stability.
+
+ Returns:
+ `torch.Tensor` of shape `(batch_size, num_channels, height, width)`:
+ Log binomial distribution logbinomial(p;t).
+ """
+ if probabilities.ndim == 3:
+ probabilities = probabilities.unsqueeze(1) # make it (batch_size, num_channels, height, width)
+
+ one_minus_probabilities = torch.clamp(1 - probabilities, eps, 1)
+ probabilities = torch.clamp(probabilities, eps, 1)
+ y = (
+ log_binom(self.k_minus_1, self.k_idx)
+ + self.k_idx * torch.log(probabilities)
+ + (self.k_minus_1 - self.k_idx) * torch.log(one_minus_probabilities)
+ )
+ return self.act(y / temperature, dim=1)
+
+
+class ZoeDepthConditionalLogBinomialSoftmax(nn.Module):
+ def __init__(
+ self,
+ config,
+ in_features,
+ condition_dim,
+ n_classes=256,
+ bottleneck_factor=2,
+ ):
+ """Per-pixel MLP followed by a Conditional Log Binomial softmax.
+
+ Args:
+ in_features (`int`):
+ Number of input channels in the main feature.
+ condition_dim (`int`):
+ Number of input channels in the condition feature.
+ n_classes (`int`, *optional*, defaults to 256):
+ Number of classes.
+ bottleneck_factor (`int`, *optional*, defaults to 2):
+ Hidden dim factor.
+
+ """
+ super().__init__()
+
+ bottleneck = (in_features + condition_dim) // bottleneck_factor
+ self.mlp = nn.Sequential(
+ nn.Conv2d(in_features + condition_dim, bottleneck, kernel_size=1, stride=1, padding=0),
+ nn.GELU(),
+ # 2 for probabilities linear norm, 2 for temperature linear norm
+ nn.Conv2d(bottleneck, 2 + 2, kernel_size=1, stride=1, padding=0),
+ nn.Softplus(),
+ )
+
+ self.p_eps = 1e-4
+ self.max_temp = config.max_temp
+ self.min_temp = config.min_temp
+ self.log_binomial_transform = LogBinomialSoftmax(n_classes, act=torch.softmax)
+
+ def forward(self, main_feature, condition_feature):
+ """
+ Args:
+ main_feature (`torch.Tensor` of shape `(batch_size, num_channels, height, width)`):
+ Main feature.
+ condition_feature (torch.Tensor of shape `(batch_size, num_channels, height, width)`):
+ Condition feature.
+
+ Returns:
+ `torch.Tensor`:
+ Output log binomial distribution
+ """
+ probabilities_and_temperature = self.mlp(torch.concat((main_feature, condition_feature), dim=1))
+ probabilities, temperature = (
+ probabilities_and_temperature[:, :2, ...],
+ probabilities_and_temperature[:, 2:, ...],
+ )
+
+ probabilities = probabilities + self.p_eps
+ probabilities = probabilities[:, 0, ...] / (probabilities[:, 0, ...] + probabilities[:, 1, ...])
+
+ temperature = temperature + self.p_eps
+ temperature = temperature[:, 0, ...] / (temperature[:, 0, ...] + temperature[:, 1, ...])
+ temperature = temperature.unsqueeze(1)
+ temperature = (self.max_temp - self.min_temp) * temperature + self.min_temp
+
+ return self.log_binomial_transform(probabilities, temperature)
+
+
+class ZoeDepthSeedBinRegressor(nn.Module):
+ def __init__(self, config, n_bins=16, mlp_dim=256, min_depth=1e-3, max_depth=10):
+ """Bin center regressor network.
+
+ Can be "normed" or "unnormed". If "normed", bin centers are bounded on the (min_depth, max_depth) interval.
+
+ Args:
+ config (`int`):
+ Model configuration.
+ n_bins (`int`, *optional*, defaults to 16):
+ Number of bin centers.
+ mlp_dim (`int`, *optional*, defaults to 256):
+ Hidden dimension.
+ min_depth (`float`, *optional*, defaults to 1e-3):
+ Min depth value.
+ max_depth (`float`, *optional*, defaults to 10):
+ Max depth value.
+ """
+ super().__init__()
+
+ self.in_features = config.bottleneck_features
+ self.bin_centers_type = config.bin_centers_type
+ self.min_depth = min_depth
+ self.max_depth = max_depth
+
+ self.conv1 = nn.Conv2d(self.in_features, mlp_dim, 1, 1, 0)
+ self.act1 = nn.ReLU(inplace=True)
+ self.conv2 = nn.Conv2d(mlp_dim, n_bins, 1, 1, 0)
+ self.act2 = nn.ReLU(inplace=True) if self.bin_centers_type == "normed" else nn.Softplus()
+
+ def forward(self, x):
+ """
+ Returns tensor of bin_width vectors (centers). One vector b for every pixel
+ """
+ x = self.conv1(x)
+ x = self.act1(x)
+ x = self.conv2(x)
+ bin_centers = self.act2(x)
+
+ if self.bin_centers_type == "normed":
+ bin_centers = bin_centers + 1e-3
+ bin_widths_normed = bin_centers / bin_centers.sum(dim=1, keepdim=True)
+ # shape (batch_size, num_channels, height, width)
+ bin_widths = (self.max_depth - self.min_depth) * bin_widths_normed
+ # pad has the form (left, right, top, bottom, front, back)
+ bin_widths = nn.functional.pad(bin_widths, (0, 0, 0, 0, 1, 0), mode="constant", value=self.min_depth)
+ # shape (batch_size, num_channels, height, width)
+ bin_edges = torch.cumsum(bin_widths, dim=1)
+
+ bin_centers = 0.5 * (bin_edges[:, :-1, ...] + bin_edges[:, 1:, ...])
+ return bin_widths_normed, bin_centers
+
+ else:
+ return bin_centers, bin_centers
+
+
+@torch.jit.script
+def inv_attractor(dx, alpha: float = 300, gamma: int = 2):
+ """Inverse attractor: dc = dx / (1 + alpha*dx^gamma), where dx = a - c, a = attractor point, c = bin center, dc = shift in bin center
+ This is the default one according to the accompanying paper.
+
+ Args:
+ dx (`torch.Tensor`):
+ The difference tensor dx = Ai - Cj, where Ai is the attractor point and Cj is the bin center.
+ alpha (`float`, *optional*, defaults to 300):
+ Proportional Attractor strength. Determines the absolute strength. Lower alpha = greater attraction.
+ gamma (`int`, *optional*, defaults to 2):
+ Exponential Attractor strength. Determines the "region of influence" and indirectly number of bin centers affected.
+ Lower gamma = farther reach.
+
+ Returns:
+ torch.Tensor: Delta shifts - dc; New bin centers = Old bin centers + dc
+ """
+ return dx.div(1 + alpha * dx.pow(gamma))
+
+
+class ZoeDepthAttractorLayer(nn.Module):
+ def __init__(
+ self,
+ config,
+ n_bins,
+ n_attractors=16,
+ min_depth=1e-3,
+ max_depth=10,
+ memory_efficient=False,
+ ):
+ """
+ Attractor layer for bin centers. Bin centers are bounded on the interval (min_depth, max_depth)
+ """
+ super().__init__()
+
+ self.alpha = config.attractor_alpha
+ self.gemma = config.attractor_gamma
+ self.kind = config.attractor_kind
+
+ self.n_attractors = n_attractors
+ self.n_bins = n_bins
+ self.min_depth = min_depth
+ self.max_depth = max_depth
+ self.memory_efficient = memory_efficient
+
+ # MLP to predict attractor points
+ in_features = mlp_dim = config.bin_embedding_dim
+ self.conv1 = nn.Conv2d(in_features, mlp_dim, 1, 1, 0)
+ self.act1 = nn.ReLU(inplace=True)
+ self.conv2 = nn.Conv2d(mlp_dim, n_attractors * 2, 1, 1, 0) # x2 for linear norm
+ self.act2 = nn.ReLU(inplace=True)
+
+ def forward(self, x, prev_bin, prev_bin_embedding=None, interpolate=True):
+ """
+ The forward pass of the attractor layer. This layer predicts the new bin centers based on the previous bin centers
+ and the attractor points (the latter are predicted by the MLP).
+
+ Args:
+ x (`torch.Tensor` of shape `(batch_size, num_channels, height, width)`):
+ Feature block.
+ prev_bin (`torch.Tensor` of shape `(batch_size, prev_number_of_bins, height, width)`):
+ Previous bin centers normed.
+ prev_bin_embedding (`torch.Tensor`, *optional*):
+ Optional previous bin embeddings.
+ interpolate (`bool`, *optional*, defaults to `True`):
+ Whether to interpolate the previous bin embeddings to the size of the input features.
+
+ Returns:
+ `tuple[`torch.Tensor`, `torch.Tensor`]:
+ New bin centers normed and scaled.
+ """
+ if prev_bin_embedding is not None:
+ if interpolate:
+ prev_bin_embedding = nn.functional.interpolate(
+ prev_bin_embedding, x.shape[-2:], mode="bilinear", align_corners=True
+ )
+ x = x + prev_bin_embedding
+
+ x = self.conv1(x)
+ x = self.act1(x)
+ x = self.conv2(x)
+ attractors = self.act2(x)
+
+ attractors = attractors + 1e-3
+ batch_size, _, height, width = attractors.shape
+ attractors = attractors.view(batch_size, self.n_attractors, 2, height, width)
+ # batch_size, num_attractors, 2, height, width
+ # note: original repo had a bug here: https://github.com/isl-org/ZoeDepth/blame/edb6daf45458569e24f50250ef1ed08c015f17a7/zoedepth/models/layers/attractor.py#L105C9-L106C50
+ # we include the bug to maintain compatibility with the weights
+ attractors_normed = attractors[:, :, 0, ...] # batch_size, batch_size*num_attractors, height, width
+
+ bin_centers = nn.functional.interpolate(prev_bin, (height, width), mode="bilinear", align_corners=True)
+
+ # note: only attractor_type = "exp" is supported here, since no checkpoints were released with other attractor types
+
+ if not self.memory_efficient:
+ func = {"mean": torch.mean, "sum": torch.sum}[self.kind]
+ # shape (batch_size, num_bins, height, width)
+ delta_c = func(inv_attractor(attractors_normed.unsqueeze(2) - bin_centers.unsqueeze(1)), dim=1)
+ else:
+ delta_c = torch.zeros_like(bin_centers, device=bin_centers.device)
+ for i in range(self.n_attractors):
+ # shape (batch_size, num_bins, height, width)
+ delta_c += inv_attractor(attractors_normed[:, i, ...].unsqueeze(1) - bin_centers)
+
+ if self.kind == "mean":
+ delta_c = delta_c / self.n_attractors
+
+ bin_new_centers = bin_centers + delta_c
+ bin_centers = (self.max_depth - self.min_depth) * bin_new_centers + self.min_depth
+ bin_centers, _ = torch.sort(bin_centers, dim=1)
+ bin_centers = torch.clip(bin_centers, self.min_depth, self.max_depth)
+ return bin_new_centers, bin_centers
+
+
+class ZoeDepthAttractorLayerUnnormed(nn.Module):
+ def __init__(
+ self,
+ config,
+ n_bins,
+ n_attractors=16,
+ min_depth=1e-3,
+ max_depth=10,
+ memory_efficient=True,
+ ):
+ """
+ Attractor layer for bin centers. Bin centers are unbounded
+ """
+ super().__init__()
+
+ self.n_attractors = n_attractors
+ self.n_bins = n_bins
+ self.min_depth = min_depth
+ self.max_depth = max_depth
+ self.alpha = config.attractor_alpha
+ self.gamma = config.attractor_alpha
+ self.kind = config.attractor_kind
+ self.memory_efficient = memory_efficient
+
+ in_features = mlp_dim = config.bin_embedding_dim
+ self.conv1 = nn.Conv2d(in_features, mlp_dim, 1, 1, 0)
+ self.act1 = nn.ReLU(inplace=True)
+ self.conv2 = nn.Conv2d(mlp_dim, n_attractors, 1, 1, 0)
+ self.act2 = nn.Softplus()
+
+ def forward(self, x, prev_bin, prev_bin_embedding=None, interpolate=True):
+ """
+ The forward pass of the attractor layer. This layer predicts the new bin centers based on the previous bin centers
+ and the attractor points (the latter are predicted by the MLP).
+
+ Args:
+ x (`torch.Tensor` of shape (batch_size, num_channels, height, width)`):
+ Feature block.
+ prev_bin (`torch.Tensor` of shape (batch_size, prev_num_bins, height, width)`):
+ Previous bin centers normed.
+ prev_bin_embedding (`torch.Tensor`, *optional*):
+ Optional previous bin embeddings.
+ interpolate (`bool`, *optional*, defaults to `True`):
+ Whether to interpolate the previous bin embeddings to the size of the input features.
+
+ Returns:
+ `tuple[`torch.Tensor`, `torch.Tensor`]:
+ New bin centers unbounded. Two outputs just to keep the API consistent with the normed version.
+ """
+ if prev_bin_embedding is not None:
+ if interpolate:
+ prev_bin_embedding = nn.functional.interpolate(
+ prev_bin_embedding, x.shape[-2:], mode="bilinear", align_corners=True
+ )
+ x = x + prev_bin_embedding
+
+ x = self.conv1(x)
+ x = self.act1(x)
+ x = self.conv2(x)
+ attractors = self.act2(x)
+
+ height, width = attractors.shape[-2:]
+
+ bin_centers = nn.functional.interpolate(prev_bin, (height, width), mode="bilinear", align_corners=True)
+
+ if not self.memory_efficient:
+ func = {"mean": torch.mean, "sum": torch.sum}[self.kind]
+ # shape batch_size, num_bins, height, width
+ delta_c = func(inv_attractor(attractors.unsqueeze(2) - bin_centers.unsqueeze(1)), dim=1)
+ else:
+ delta_c = torch.zeros_like(bin_centers, device=bin_centers.device)
+ for i in range(self.n_attractors):
+ # shape batch_size, num_bins, height, width
+ delta_c += inv_attractor(attractors[:, i, ...].unsqueeze(1) - bin_centers)
+
+ if self.kind == "mean":
+ delta_c = delta_c / self.n_attractors
+
+ bin_new_centers = bin_centers + delta_c
+ bin_centers = bin_new_centers
+
+ return bin_new_centers, bin_centers
+
+
+class ZoeDepthProjector(nn.Module):
+ def __init__(self, in_features, out_features, mlp_dim=128):
+ """Projector MLP.
+
+ Args:
+ in_features (`int`):
+ Number of input channels.
+ out_features (`int`):
+ Number of output channels.
+ mlp_dim (`int`, *optional*, defaults to 128):
+ Hidden dimension.
+ """
+ super().__init__()
+
+ self.conv1 = nn.Conv2d(in_features, mlp_dim, 1, 1, 0)
+ self.act = nn.ReLU(inplace=True)
+ self.conv2 = nn.Conv2d(mlp_dim, out_features, 1, 1, 0)
+
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ hidden_state = self.conv1(hidden_state)
+ hidden_state = self.act(hidden_state)
+ hidden_state = self.conv2(hidden_state)
+
+ return hidden_state
+
+
+# Copied from transformers.models.grounding_dino.modeling_grounding_dino.GroundingDinoMultiheadAttention with GroundingDino->ZoeDepth
+class ZoeDepthMultiheadAttention(nn.Module):
+ """Equivalent implementation of nn.MultiheadAttention with `batch_first=True`."""
+
+ # Ignore copy
+ def __init__(self, hidden_size, num_attention_heads, dropout):
+ super().__init__()
+ if hidden_size % num_attention_heads != 0:
+ raise ValueError(
+ f"The hidden size ({hidden_size}) is not a multiple of the number of attention "
+ f"heads ({num_attention_heads})"
+ )
+
+ self.num_attention_heads = num_attention_heads
+ self.attention_head_size = int(hidden_size / num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+
+ self.query = nn.Linear(hidden_size, self.all_head_size)
+ self.key = nn.Linear(hidden_size, self.all_head_size)
+ self.value = nn.Linear(hidden_size, self.all_head_size)
+
+ self.out_proj = nn.Linear(hidden_size, hidden_size)
+
+ self.dropout = nn.Dropout(dropout)
+
+ def forward(
+ self,
+ queries: torch.Tensor,
+ keys: torch.Tensor,
+ values: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ output_attentions: bool | None = False,
+ ) -> tuple[torch.Tensor]:
+ batch_size, seq_length, _ = queries.shape
+ query_layer = (
+ self.query(queries)
+ .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
+ .transpose(1, 2)
+ )
+ key_layer = (
+ self.key(keys).view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(1, 2)
+ )
+ value_layer = (
+ self.value(values).view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(1, 2)
+ )
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
+
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
+ if attention_mask is not None:
+ # Apply the attention mask is (precomputed for all layers in ZoeDepthModel forward() function)
+ attention_scores = attention_scores + attention_mask
+
+ # Normalize the attention scores to probabilities.
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
+
+ # This is actually dropping out entire tokens to attend to, which might
+ # seem a bit unusual, but is taken from the original Transformer paper.
+ attention_probs = self.dropout(attention_probs)
+
+ context_layer = torch.matmul(attention_probs, value_layer)
+
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.view(new_context_layer_shape)
+
+ context_layer = self.out_proj(context_layer)
+
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
+
+ return outputs
+
+
+class ZoeDepthTransformerEncoderLayer(nn.Module):
+ def __init__(self, config, dropout=0.1, activation="relu"):
+ super().__init__()
+
+ hidden_size = config.patch_transformer_hidden_size
+ intermediate_size = config.patch_transformer_intermediate_size
+ num_attention_heads = config.patch_transformer_num_attention_heads
+
+ self.self_attn = ZoeDepthMultiheadAttention(hidden_size, num_attention_heads, dropout=dropout)
+
+ self.linear1 = nn.Linear(hidden_size, intermediate_size)
+ self.dropout = nn.Dropout(dropout)
+ self.linear2 = nn.Linear(intermediate_size, hidden_size)
+
+ self.norm1 = nn.LayerNorm(hidden_size)
+ self.norm2 = nn.LayerNorm(hidden_size)
+ self.dropout1 = nn.Dropout(dropout)
+ self.dropout2 = nn.Dropout(dropout)
+
+ self.activation = ACT2FN[activation]
+
+ def forward(
+ self,
+ src,
+ src_mask: torch.Tensor | None = None,
+ ):
+ queries = keys = src
+ src2 = self.self_attn(queries=queries, keys=keys, values=src, attention_mask=src_mask)[0]
+ src = src + self.dropout1(src2)
+ src = self.norm1(src)
+ src2 = self.linear2(self.dropout(self.activation(self.linear1(src))))
+ src = src + self.dropout2(src2)
+ src = self.norm2(src)
+ return src
+
+
+class ZoeDepthPatchTransformerEncoder(nn.Module):
+ def __init__(self, config):
+ """ViT-like transformer block
+
+ Args:
+ config (`ZoeDepthConfig`):
+ Model configuration class defining the model architecture.
+ """
+ super().__init__()
+
+ in_channels = config.bottleneck_features
+
+ self.transformer_encoder = nn.ModuleList(
+ [ZoeDepthTransformerEncoderLayer(config) for _ in range(config.num_patch_transformer_layers)]
+ )
+
+ self.embedding_convPxP = nn.Conv2d(
+ in_channels, config.patch_transformer_hidden_size, kernel_size=1, stride=1, padding=0
+ )
+
+ def positional_encoding_1d(self, batch_size, sequence_length, embedding_dim, device="cpu", dtype=torch.float32):
+ """Generate positional encodings
+
+ Args:
+ sequence_length (int): Sequence length
+ embedding_dim (int): Embedding dimension
+
+ Returns:
+ torch.Tensor: Positional encodings.
+ """
+ position = torch.arange(0, sequence_length, dtype=dtype, device=device).unsqueeze(1)
+ index = torch.arange(0, embedding_dim, 2, dtype=dtype, device=device).unsqueeze(0)
+ div_term = torch.exp(index * (-torch.log(torch.tensor(10000.0, device=device)) / embedding_dim))
+ pos_encoding = position * div_term
+ pos_encoding = torch.cat([torch.sin(pos_encoding), torch.cos(pos_encoding)], dim=1)
+ pos_encoding = pos_encoding.unsqueeze(dim=0).repeat(batch_size, 1, 1)
+ return pos_encoding
+
+ def forward(self, x):
+ """Forward pass
+
+ Args:
+ x (torch.Tensor - NCHW): Input feature tensor
+
+ Returns:
+ torch.Tensor - Transformer output embeddings of shape (batch_size, sequence_length, embedding_dim)
+ """
+ embeddings = self.embedding_convPxP(x).flatten(2) # shape (batch_size, num_channels, sequence_length)
+ # add an extra special CLS token at the start for global accumulation
+ embeddings = nn.functional.pad(embeddings, (1, 0))
+
+ embeddings = embeddings.permute(0, 2, 1)
+ batch_size, sequence_length, embedding_dim = embeddings.shape
+ embeddings = embeddings + self.positional_encoding_1d(
+ batch_size, sequence_length, embedding_dim, device=embeddings.device, dtype=embeddings.dtype
+ )
+
+ for i in range(4):
+ embeddings = self.transformer_encoder[i](embeddings)
+
+ return embeddings
+
+
+class ZoeDepthMLPClassifier(nn.Module):
+ def __init__(self, in_features, out_features) -> None:
+ super().__init__()
+
+ hidden_features = in_features
+ self.linear1 = nn.Linear(in_features, hidden_features)
+ self.activation = nn.ReLU()
+ self.linear2 = nn.Linear(hidden_features, out_features)
+
+ def forward(self, hidden_state):
+ hidden_state = self.linear1(hidden_state)
+ hidden_state = self.activation(hidden_state)
+ domain_logits = self.linear2(hidden_state)
+
+ return domain_logits
+
+
+class ZoeDepthMultipleMetricDepthEstimationHeads(nn.Module):
+ """
+ Multiple metric depth estimation heads. A MLP classifier is used to route between 2 different heads.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+
+ bin_embedding_dim = config.bin_embedding_dim
+ n_attractors = config.num_attractors
+ self.bin_configurations = config.bin_configurations
+ self.bin_centers_type = config.bin_centers_type
+
+ # Bottleneck convolution
+ bottleneck_features = config.bottleneck_features
+ self.conv2 = nn.Conv2d(bottleneck_features, bottleneck_features, kernel_size=1, stride=1, padding=0)
+
+ # Transformer classifier on the bottleneck
+ self.patch_transformer = ZoeDepthPatchTransformerEncoder(config)
+ # MLP classifier
+ self.mlp_classifier = ZoeDepthMLPClassifier(in_features=128, out_features=2)
+
+ # Regressor and attractor
+ if self.bin_centers_type == "normed":
+ Attractor = ZoeDepthAttractorLayer
+ elif self.bin_centers_type == "softplus":
+ Attractor = ZoeDepthAttractorLayerUnnormed
+ # We have bins for each bin configuration
+ # Create a map (ModuleDict) of 'name' -> seed_bin_regressor
+ self.seed_bin_regressors = nn.ModuleDict(
+ {
+ conf["name"]: ZoeDepthSeedBinRegressor(
+ config,
+ n_bins=conf["n_bins"],
+ mlp_dim=bin_embedding_dim // 2,
+ min_depth=conf["min_depth"],
+ max_depth=conf["max_depth"],
+ )
+ for conf in config.bin_configurations
+ }
+ )
+
+ self.seed_projector = ZoeDepthProjector(
+ in_features=bottleneck_features, out_features=bin_embedding_dim, mlp_dim=bin_embedding_dim // 2
+ )
+ self.projectors = nn.ModuleList(
+ [
+ ZoeDepthProjector(
+ in_features=config.fusion_hidden_size,
+ out_features=bin_embedding_dim,
+ mlp_dim=bin_embedding_dim // 2,
+ )
+ for _ in range(4)
+ ]
+ )
+
+ # Create a map (ModuleDict) of 'name' -> attractors (ModuleList)
+ self.attractors = nn.ModuleDict(
+ {
+ configuration["name"]: nn.ModuleList(
+ [
+ Attractor(
+ config,
+ n_bins=n_attractors[i],
+ min_depth=configuration["min_depth"],
+ max_depth=configuration["max_depth"],
+ )
+ for i in range(len(n_attractors))
+ ]
+ )
+ for configuration in config.bin_configurations
+ }
+ )
+
+ last_in = config.num_relative_features
+ # conditional log binomial for each bin configuration
+ self.conditional_log_binomial = nn.ModuleDict(
+ {
+ configuration["name"]: ZoeDepthConditionalLogBinomialSoftmax(
+ config,
+ last_in,
+ bin_embedding_dim,
+ configuration["n_bins"],
+ bottleneck_factor=4,
+ )
+ for configuration in config.bin_configurations
+ }
+ )
+
+ def forward(self, outconv_activation, bottleneck, feature_blocks, relative_depth):
+ x = self.conv2(bottleneck)
+
+ # Predict which path to take
+ # Embedding is of shape (batch_size, hidden_size)
+ embedding = self.patch_transformer(x)[:, 0, :]
+
+ # MLP classifier to get logits of shape (batch_size, 2)
+ domain_logits = self.mlp_classifier(embedding)
+ domain_vote = torch.softmax(domain_logits.sum(dim=0, keepdim=True), dim=-1)
+
+ # Get the path
+ names = [configuration["name"] for configuration in self.bin_configurations]
+ bin_configurations_name = names[torch.argmax(domain_vote, dim=-1).squeeze().item()]
+
+ try:
+ conf = [config for config in self.bin_configurations if config["name"] == bin_configurations_name][0]
+ except IndexError:
+ raise ValueError(f"bin_configurations_name {bin_configurations_name} not found in bin_configurationss")
+
+ min_depth = conf["min_depth"]
+ max_depth = conf["max_depth"]
+
+ seed_bin_regressor = self.seed_bin_regressors[bin_configurations_name]
+ _, seed_bin_centers = seed_bin_regressor(x)
+ if self.bin_centers_type in ["normed", "hybrid2"]:
+ prev_bin = (seed_bin_centers - min_depth) / (max_depth - min_depth)
+ else:
+ prev_bin = seed_bin_centers
+ prev_bin_embedding = self.seed_projector(x)
+
+ attractors = self.attractors[bin_configurations_name]
+ for projector, attractor, feature in zip(self.projectors, attractors, feature_blocks):
+ bin_embedding = projector(feature)
+ bin, bin_centers = attractor(bin_embedding, prev_bin, prev_bin_embedding, interpolate=True)
+ prev_bin = bin
+ prev_bin_embedding = bin_embedding
+
+ last = outconv_activation
+
+ bin_centers = nn.functional.interpolate(bin_centers, last.shape[-2:], mode="bilinear", align_corners=True)
+ bin_embedding = nn.functional.interpolate(bin_embedding, last.shape[-2:], mode="bilinear", align_corners=True)
+
+ conditional_log_binomial = self.conditional_log_binomial[bin_configurations_name]
+ x = conditional_log_binomial(last, bin_embedding)
+
+ # Now depth value is Sum px * cx , where cx are bin_centers from the last bin tensor
+ out = torch.sum(x * bin_centers, dim=1, keepdim=True)
+
+ return out, domain_logits
+
+
+class ZoeDepthMetricDepthEstimationHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+
+ bin_configuration = config.bin_configurations[0]
+ n_bins = bin_configuration["n_bins"]
+ min_depth = bin_configuration["min_depth"]
+ max_depth = bin_configuration["max_depth"]
+ bin_embedding_dim = config.bin_embedding_dim
+ n_attractors = config.num_attractors
+ bin_centers_type = config.bin_centers_type
+
+ self.min_depth = min_depth
+ self.max_depth = max_depth
+ self.bin_centers_type = bin_centers_type
+
+ # Bottleneck convolution
+ bottleneck_features = config.bottleneck_features
+ self.conv2 = nn.Conv2d(bottleneck_features, bottleneck_features, kernel_size=1, stride=1, padding=0)
+
+ # Regressor and attractor
+ if self.bin_centers_type == "normed":
+ Attractor = ZoeDepthAttractorLayer
+ elif self.bin_centers_type == "softplus":
+ Attractor = ZoeDepthAttractorLayerUnnormed
+
+ self.seed_bin_regressor = ZoeDepthSeedBinRegressor(
+ config, n_bins=n_bins, min_depth=min_depth, max_depth=max_depth
+ )
+ self.seed_projector = ZoeDepthProjector(in_features=bottleneck_features, out_features=bin_embedding_dim)
+
+ self.projectors = nn.ModuleList(
+ [
+ ZoeDepthProjector(in_features=config.fusion_hidden_size, out_features=bin_embedding_dim)
+ for _ in range(4)
+ ]
+ )
+ self.attractors = nn.ModuleList(
+ [
+ Attractor(
+ config,
+ n_bins=n_bins,
+ n_attractors=n_attractors[i],
+ min_depth=min_depth,
+ max_depth=max_depth,
+ )
+ for i in range(4)
+ ]
+ )
+
+ last_in = config.num_relative_features + 1 # +1 for relative depth
+
+ # use log binomial instead of softmax
+ self.conditional_log_binomial = ZoeDepthConditionalLogBinomialSoftmax(
+ config,
+ last_in,
+ bin_embedding_dim,
+ n_classes=n_bins,
+ )
+
+ def forward(self, outconv_activation, bottleneck, feature_blocks, relative_depth):
+ x = self.conv2(bottleneck)
+ _, seed_bin_centers = self.seed_bin_regressor(x)
+
+ if self.bin_centers_type in ["normed", "hybrid2"]:
+ prev_bin = (seed_bin_centers - self.min_depth) / (self.max_depth - self.min_depth)
+ else:
+ prev_bin = seed_bin_centers
+
+ prev_bin_embedding = self.seed_projector(x)
+
+ # unroll this loop for better performance
+ for projector, attractor, feature in zip(self.projectors, self.attractors, feature_blocks):
+ bin_embedding = projector(feature)
+ bin, bin_centers = attractor(bin_embedding, prev_bin, prev_bin_embedding, interpolate=True)
+ prev_bin = bin.clone()
+ prev_bin_embedding = bin_embedding.clone()
+
+ last = outconv_activation
+
+ # concatenative relative depth with last. First interpolate relative depth to last size
+ relative_conditioning = relative_depth.unsqueeze(1)
+ relative_conditioning = nn.functional.interpolate(
+ relative_conditioning, size=last.shape[2:], mode="bilinear", align_corners=True
+ )
+ last = torch.cat([last, relative_conditioning], dim=1)
+
+ bin_embedding = nn.functional.interpolate(bin_embedding, last.shape[-2:], mode="bilinear", align_corners=True)
+ x = self.conditional_log_binomial(last, bin_embedding)
+
+ # Now depth value is Sum px * cx , where cx are bin_centers from the last bin tensor
+ bin_centers = nn.functional.interpolate(bin_centers, x.shape[-2:], mode="bilinear", align_corners=True)
+ out = torch.sum(x * bin_centers, dim=1, keepdim=True)
+
+ return out, None
+
+
+# Modified from transformers.models.dpt.modeling_dpt.DPTPreTrainedModel with DPT->ZoeDepth,dpt->zoedepth
+# avoiding sdpa and flash_attn_2 support, it's done int the backend
+@auto_docstring
+class ZoeDepthPreTrainedModel(PreTrainedModel):
+ config: ZoeDepthConfig
+ base_model_prefix = "zoedepth"
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+ supports_gradient_checkpointing = True
+
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ if isinstance(module, LogBinomialSoftmax):
+ init.copy_(module.k_idx, torch.arange(0, module.k).view(1, -1, 1, 1))
+ init.copy_(module.k_minus_1, torch.tensor([module.k - 1]).view(1, -1, 1, 1))
+
+
+@auto_docstring(
+ custom_intro="""
+ ZoeDepth model with one or multiple metric depth estimation head(s) on top.
+ """
+)
+class ZoeDepthForDepthEstimation(ZoeDepthPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.backbone = load_backbone(config)
+
+ if hasattr(self.backbone.config, "hidden_size") and hasattr(self.backbone.config, "patch_size"):
+ config.backbone_hidden_size = self.backbone.config.hidden_size
+ self.patch_size = self.backbone.config.patch_size
+ else:
+ raise ValueError(
+ "ZoeDepth assumes the backbone's config to have `hidden_size` and `patch_size` attributes"
+ )
+
+ self.neck = ZoeDepthNeck(config)
+ self.relative_head = ZoeDepthRelativeDepthEstimationHead(config)
+
+ self.metric_head = (
+ ZoeDepthMultipleMetricDepthEstimationHeads(config)
+ if len(config.bin_configurations) > 1
+ else ZoeDepthMetricDepthEstimationHead(config)
+ )
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ labels: torch.LongTensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple[torch.Tensor] | DepthEstimatorOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
+ Ground truth depth estimation maps for computing the loss.
+
+ Examples:
+ ```python
+ >>> from transformers import AutoImageProcessor, ZoeDepthForDepthEstimation
+ >>> import torch
+ >>> import numpy as np
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> image_processor = AutoImageProcessor.from_pretrained("Intel/zoedepth-nyu-kitti")
+ >>> model = ZoeDepthForDepthEstimation.from_pretrained("Intel/zoedepth-nyu-kitti")
+
+ >>> # prepare image for the model
+ >>> inputs = image_processor(images=image, return_tensors="pt")
+
+ >>> with torch.no_grad():
+ ... outputs = model(**inputs)
+
+ >>> # interpolate to original size
+ >>> post_processed_output = image_processor.post_process_depth_estimation(
+ ... outputs,
+ ... source_sizes=[(image.height, image.width)],
+ ... )
+
+ >>> # visualize the prediction
+ >>> predicted_depth = post_processed_output[0]["predicted_depth"]
+ >>> depth = predicted_depth * 255 / predicted_depth.max()
+ >>> depth = depth.detach().cpu().numpy()
+ >>> depth = Image.fromarray(depth.astype("uint8"))
+ ```"""
+ loss = None
+ if labels is not None:
+ raise NotImplementedError("Training is not implemented yet")
+
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+
+ outputs = self.backbone.forward_with_filtered_kwargs(
+ pixel_values, output_hidden_states=output_hidden_states, output_attentions=output_attentions
+ )
+ hidden_states = outputs.feature_maps
+
+ _, _, height, width = pixel_values.shape
+ patch_size = self.patch_size
+ patch_height = height // patch_size
+ patch_width = width // patch_size
+
+ hidden_states, features = self.neck(hidden_states, patch_height, patch_width)
+
+ out = [features] + hidden_states
+
+ relative_depth, features = self.relative_head(hidden_states)
+
+ out = [features] + out
+
+ metric_depth, domain_logits = self.metric_head(
+ outconv_activation=out[0], bottleneck=out[1], feature_blocks=out[2:], relative_depth=relative_depth
+ )
+ metric_depth = metric_depth.squeeze(dim=1)
+
+ if not return_dict:
+ if domain_logits is not None:
+ output = (metric_depth, domain_logits) + outputs[1:]
+ else:
+ output = (metric_depth,) + outputs[1:]
+
+ return ((loss,) + output) if loss is not None else output
+
+ return ZoeDepthDepthEstimatorOutput(
+ loss=loss,
+ predicted_depth=metric_depth,
+ domain_logits=domain_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = ["ZoeDepthForDepthEstimation", "ZoeDepthPreTrainedModel"]
diff --git a/.venv/lib/python3.12/site-packages/transformers/monkey_patching.py b/.venv/lib/python3.12/site-packages/transformers/monkey_patching.py
new file mode 100644
index 0000000000000000000000000000000000000000..c64124c289fa21e05f0744fa3f781be5bfc88c8d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/monkey_patching.py
@@ -0,0 +1,357 @@
+# Copyright 2026 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import re
+import sys
+import threading
+from contextlib import contextmanager
+
+from .utils import is_torch_available, logging
+from .utils.output_capturing import OutputRecorder
+
+
+if is_torch_available():
+ import torch.nn as nn
+
+logger = logging.get_logger(__name__)
+
+_monkey_patch_mapping_cache: dict[str, type[nn.Module]] = {}
+_compiled_patterns_cache: dict[str, re.Pattern] = {}
+_monkey_patch_lock = threading.Lock()
+
+
+def _compile_pattern(pattern: str) -> re.Pattern | None:
+ """
+ Compile a regex pattern and cache it. Returns None if pattern is invalid.
+
+ Args:
+ pattern: The regex pattern string to compile
+
+ Returns:
+ Compiled regex pattern or None if invalid
+ """
+ if pattern in _compiled_patterns_cache:
+ return _compiled_patterns_cache[pattern]
+
+ try:
+ compiled = re.compile(pattern)
+ _compiled_patterns_cache[pattern] = compiled
+ return compiled
+ except re.error as e:
+ logger.warning(f"Invalid regex pattern '{pattern}': {e}. Treating as non-pattern.")
+ return None
+
+
+def _find_replacement_class(class_name: str, mapping: dict[str, type[nn.Module]]) -> type[nn.Module] | None:
+ """
+ Find replacement class for a given class name, checking exact matches first, then regex patterns.
+
+ Args:
+ class_name: The class name to find a replacement for
+ mapping: Dictionary of patterns/names to replacement classes
+
+ Returns:
+ The replacement class if found, None otherwise
+ """
+ # First check for exact match (highest priority)
+ if class_name in mapping:
+ return mapping[class_name]
+
+ # Then check regex patterns
+ for pattern, replacement_class in mapping.items():
+ # Skip if already matched as exact
+ if pattern == class_name:
+ continue
+
+ # Try to compile and match as regex
+ compiled_pattern = _compile_pattern(pattern)
+ if compiled_pattern is not None and compiled_pattern.search(class_name):
+ return replacement_class
+
+ return None
+
+
+def register_patch_mapping(mapping: dict[str, type[nn.Module]], overwrite: bool = False) -> None:
+ """
+ Register patch mappings to enable automatic patching during model creation using `from_pretrained`,
+ `from_config` or within the `apply_patches` context manager.
+
+ Use this to register class replacements that will be automatically applied when loading any model.
+ This is useful for quantization library compatibility, structural optimizations, and architectural
+ experimentation. The mapping is global, can grow with multiple calls, and can be cleared entirely.
+
+ Args:
+ mapping (`Dict[str, type[nn.Module]]`):
+ Mapping from original class names (or regex patterns) to replacement classes. Supports:
+ - Exact class names: `"Qwen2MoeExperts"` → `CustomExperts`
+ - Regex patterns: `".*Attention"` matches `LlamaAttention`, `MistralAttention`, etc.,
+ or `"^Llama\\d+Attention$"` matches `Llama2Attention`, `Llama3Attention`, etc.
+
+ Exact matches take precedence over patterns. Patterns are matched using `re.search()`,
+ so they can match anywhere in the class name unless you use anchors (`^` for start, `$` for end).
+ overwrite (`bool`, *optional*, defaults to `False`):
+ Whether to overwrite existing mappings for class names that are already registered.
+
+ Example:
+ ```python
+ from transformers import AutoModelForCausalLM
+ from transformers.monkey_patching import register_patch_mapping
+
+ # Define custom expert implementation
+ class SequentialExperts(nn.Module):
+ ...
+
+ # Register exact class name
+ register_patch_mapping(
+ mapping={"Qwen2MoeExperts": SequentialExperts}
+ )
+
+ # Register with regex pattern to match multiple classes
+ register_patch_mapping(
+ mapping={".*Attention": CustomAttention} # Matches LlamaAttention, MistralAttention, etc.
+ )
+
+ # Match specific model versions
+ register_patch_mapping(
+ mapping={"^Llama\\d+Attention$": CustomLlamaAttention} # Matches Llama2Attention, Llama3Attention
+ )
+
+ # The patch will be automatically applied during loading
+ model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-1B")
+ ```
+
+ Note:
+ For weight conversions, use [`~transformers.register_checkpoint_conversion_mapping`] instead.
+ """
+ global _monkey_patch_mapping_cache
+ with _monkey_patch_lock:
+ for class_name, replacement_class in mapping.items():
+ # Validate that replacement_class is actually a class and is a subclass of nn.Module
+ if not isinstance(replacement_class, type):
+ raise TypeError(
+ f"Replacement for '{class_name}' must be a class, got {type(replacement_class).__name__}"
+ )
+ if not issubclass(replacement_class, nn.Module):
+ raise TypeError(
+ f"Replacement class for '{class_name}' must be a subclass of nn.Module, "
+ f"got {replacement_class.__name__} which inherits from {[c.__name__ for c in replacement_class.__mro__[1:]]}"
+ )
+
+ if class_name in _monkey_patch_mapping_cache and not overwrite:
+ raise ValueError(
+ f"Class '{class_name}' already has a patch mapping registered. Use overwrite=True to replace it."
+ )
+ _monkey_patch_mapping_cache[class_name] = replacement_class
+
+
+def unregister_patch_mapping(keys: list[str]) -> None:
+ """
+ Unregister patch mappings to disable automatic patching.
+
+ This removes specified mappings from the global registry, preventing them from being applied
+ during model loading. You must provide the exact same name or pattern that was used during registration.
+
+ Args:
+ keys (`List[str]`):
+ List of mapping keys (class names or regex patterns) to remove from the patch mapping
+ (e.g., `["Qwen2MoeExperts"]` or `[".*Attention"]`).
+
+ Example:
+ ```python
+ from transformers import AutoModelForCausalLM
+ from transformers.monkey_patching import register_patch_mapping, unregister_patch_mapping
+
+ # Register a patch
+ register_patch_mapping(
+ mapping={"Qwen2MoeExperts": CustomExperts}
+ )
+
+ # Unregister the patch
+ unregister_patch_mapping(["Qwen2MoeExperts"])
+
+ # The patch will no longer be applied during loading
+ model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen1.5-MoE-A2.7B")
+ ```
+ """
+ global _monkey_patch_mapping_cache
+ with _monkey_patch_lock:
+ for key in keys:
+ if key not in _monkey_patch_mapping_cache:
+ raise ValueError(
+ f"Class or pattern '{key}' not found in monkey patch mapping cache. "
+ f"Cannot unregister a class that is not registered."
+ )
+ del _monkey_patch_mapping_cache[key]
+
+
+def get_patch_mapping() -> dict[str, type[nn.Module]]:
+ """
+ Get all registered patch mappings.
+
+ Returns:
+ `Dict[str, type[nn.Module]]`: Dictionary mapping class names or patterns to replacement classes.
+ """
+ with _monkey_patch_lock:
+ return _monkey_patch_mapping_cache.copy()
+
+
+def clear_patch_mapping() -> None:
+ """
+ Clear all registered patch mappings.
+
+ This removes all registered mappings from the global registry.
+
+ Example:
+ ```python
+ from transformers.monkey_patching import register_patch_mapping, clear_patch_mapping
+
+ # Register some patches
+ register_patch_mapping(
+ mapping={"Qwen2MoeExperts": CustomExperts}
+ )
+
+ # Clear all patches
+ clear_patch_mapping()
+ ```
+ """
+ global _monkey_patch_mapping_cache
+ with _monkey_patch_lock:
+ _monkey_patch_mapping_cache.clear()
+
+
+@contextmanager
+def apply_patches():
+ """
+ Context manager to apply registered monkey patches within a block of code.
+
+ This temporarily replaces original classes with their registered replacements during the execution of the block, and restores the original classes afterward.
+
+ Example:
+ ```python
+ from transformers import Qwen2MoeModel, Qwen2MoeConfig
+ from transformers.monkey_patching import register_patch_mapping, apply_patches
+
+ # Register a patch
+ register_patch_mapping(
+ mapping={"Qwen2MoeExperts": CustomExperts}
+ )
+
+ # Apply patches within the context
+ with apply_patches():
+ # The model will use CustomExperts instead of Qwen2MoeExperts
+ model = Qwen2MoeModel(Qwen2MoeConfig())
+
+ # Outside the context, original classes are restored
+ # The model will use Qwen2MoeExperts again
+ model = Qwen2MoeModel(Qwen2MoeConfig())
+ ```
+ """
+ mapping = get_patch_mapping()
+ if not mapping:
+ yield
+ return
+
+ original_classes = {}
+
+ # Create list to avoid dict changed during iteration
+ for module in list(sys.modules.values()):
+ if module is None or not hasattr(module, "__name__"):
+ continue
+ if not module.__name__.startswith("transformers"):
+ continue
+
+ # Iterate through all attributes in transformers modules
+ for attr_name in dir(module):
+ # Check if this attribute name matches any pattern before accessing it
+ replacement_class = _find_replacement_class(attr_name, mapping)
+ if replacement_class is None:
+ continue
+
+ try:
+ attr = getattr(module, attr_name)
+ # Check if it's a class
+ if not isinstance(attr, type):
+ continue
+
+ original_classes[(module.__name__, attr_name)] = attr
+ setattr(module, attr_name, replacement_class)
+ except (AttributeError, TypeError, ImportError):
+ # Skip attributes that can't be accessed or modules that can't be imported
+ continue
+
+ yield
+
+ for (module_name, class_name), original_class in original_classes.items():
+ module = sys.modules[module_name]
+ setattr(module, class_name, original_class)
+
+
+# _can_record_outputs is a class attribute so patching and unpatching it in the class won't work
+# since the model instance will still reference the original class's _can_record_outputs.
+def patch_output_recorders(model: nn.Module) -> None:
+ """
+ Patch the model instance's output recorders to use the registered replacement classes.
+
+ This function updates output recorders in a model's submodules to use monkey-patched replacement
+ classes. Output recorders are used by the transformers library to track intermediate outputs during
+ forward passes (via the `_can_record_outputs` attribute). When classes are monkey-patched, these
+ recorders need to be updated to reference the new classes.
+
+ This is automatically called during model initialization when loading with `from_pretrained` or
+ `from_config`. You typically don't need to call this manually unless you're constructing models
+ in custom ways.
+
+ Note:
+ The `_can_record_outputs` attribute is a class-level attribute that maps output names to either:
+ - `OutputRecorder` instances that have a `target_class` attribute
+ - Class types directly
+
+ This function patches both cases to use the replacement classes from the monkey patch registry.
+
+ Args:
+ model (`nn.Module`):
+ The model instance whose output recorders should be patched. All submodules will be
+ traversed to find and patch their `_can_record_outputs` attributes.
+
+ Example:
+ ```python
+ from transformers import AutoModelForCausalLM
+ from transformers.monkey_patching import register_patch_mapping, patch_output_recorders
+
+ # Register a patch
+ register_patch_mapping(mapping={"Qwen2MoeExperts": CustomExperts})
+
+ # If you construct a model manually (without from_pretrained), patch recorders
+ model = Qwen2MoeModel(config)
+ patch_output_recorders(model) # Updates output recorders to use CustomExperts
+ ```
+ """
+
+ mapping = get_patch_mapping()
+ if not mapping:
+ return
+
+ for submodule in model.modules():
+ if hasattr(submodule, "_can_record_outputs") and submodule._can_record_outputs is not None:
+ for output, recorder in submodule._can_record_outputs.items():
+ if isinstance(recorder, OutputRecorder):
+ # Check if target class matches any registered pattern or exact name
+ replacement_class = _find_replacement_class(recorder.target_class.__name__, mapping)
+ if replacement_class is not None:
+ recorder.target_class = replacement_class
+ elif isinstance(recorder, type):
+ # Check if class type matches any registered pattern or exact name
+ replacement_class = _find_replacement_class(recorder.__name__, mapping)
+ if replacement_class is not None:
+ submodule._can_record_outputs[output] = replacement_class
diff --git a/.venv/lib/python3.12/site-packages/transformers/optimization.py b/.venv/lib/python3.12/site-packages/transformers/optimization.py
new file mode 100644
index 0000000000000000000000000000000000000000..64559c9b591059431a6274f7f2d970c768b94dea
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/optimization.py
@@ -0,0 +1,1342 @@
+# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch optimization for BERT model."""
+
+from __future__ import annotations
+
+import math
+import warnings
+from functools import partial
+from typing import Any
+
+import torch
+from torch.optim import Optimizer
+from torch.optim.lr_scheduler import LambdaLR, ReduceLROnPlateau
+
+from .trainer_pt_utils import LayerWiseDummyOptimizer, LayerWiseDummyScheduler
+from .trainer_utils import SchedulerType
+from .utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+def _get_constant_lambda(_=None):
+ return 1
+
+
+def get_constant_schedule(optimizer: Optimizer, last_epoch: int = -1):
+ """
+ Create a schedule with a constant learning rate, using the learning rate set in optimizer.
+
+ Args:
+ optimizer ([`~torch.optim.Optimizer`]):
+ The optimizer for which to schedule the learning rate.
+ last_epoch (`int`, *optional*, defaults to -1):
+ The index of the last epoch when resuming training.
+
+ Return:
+ `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
+ """
+
+ return LambdaLR(optimizer, _get_constant_lambda, last_epoch=last_epoch)
+
+
+def get_reduce_on_plateau_schedule(optimizer: Optimizer, **kwargs):
+ """
+ Create a schedule with a constant learning rate that decreases when a metric has stopped improving.
+
+ Args:
+ optimizer ([`~torch.optim.Optimizer`]):
+ The optimizer for which to schedule the learning rate.
+ kwargs (`dict`, *optional*):
+ Extra parameters to be passed to the scheduler. See `torch.optim.lr_scheduler.ReduceLROnPlateau`
+ for possible parameters.
+
+ Return:
+ `torch.optim.lr_scheduler.ReduceLROnPlateau` with the appropriate schedule.
+ """
+
+ return ReduceLROnPlateau(optimizer, **kwargs)
+
+
+def _get_constant_schedule_with_warmup_lr_lambda(current_step: int, *, num_warmup_steps: int):
+ if current_step < num_warmup_steps:
+ return float(current_step) / float(max(1.0, num_warmup_steps))
+ return 1.0
+
+
+def get_constant_schedule_with_warmup(optimizer: Optimizer, num_warmup_steps: int, last_epoch: int = -1):
+ """
+ Create a schedule with a constant learning rate preceded by a warmup period during which the learning rate
+ increases linearly between 0 and the initial lr set in the optimizer.
+
+ Args:
+ optimizer ([`~torch.optim.Optimizer`]):
+ The optimizer for which to schedule the learning rate.
+ num_warmup_steps (`int`):
+ The number of steps for the warmup phase.
+ last_epoch (`int`, *optional*, defaults to -1):
+ The index of the last epoch when resuming training.
+
+ Return:
+ `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
+ """
+
+ lr_lambda = partial(_get_constant_schedule_with_warmup_lr_lambda, num_warmup_steps=num_warmup_steps)
+ return LambdaLR(optimizer, lr_lambda, last_epoch=last_epoch)
+
+
+def _get_linear_schedule_with_warmup_lr_lambda(current_step: int, *, num_warmup_steps: int, num_training_steps: int):
+ if current_step < num_warmup_steps:
+ return float(current_step) / float(max(1, num_warmup_steps))
+ return max(0.0, float(num_training_steps - current_step) / float(max(1, num_training_steps - num_warmup_steps)))
+
+
+def get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, last_epoch=-1):
+ """
+ Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0, after
+ a warmup period during which it increases linearly from 0 to the initial lr set in the optimizer.
+
+ Args:
+ optimizer ([`~torch.optim.Optimizer`]):
+ The optimizer for which to schedule the learning rate.
+ num_warmup_steps (`int`):
+ The number of steps for the warmup phase.
+ num_training_steps (`int`):
+ The total number of training steps.
+ last_epoch (`int`, *optional*, defaults to -1):
+ The index of the last epoch when resuming training.
+
+ Return:
+ `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
+ """
+
+ lr_lambda = partial(
+ _get_linear_schedule_with_warmup_lr_lambda,
+ num_warmup_steps=num_warmup_steps,
+ num_training_steps=num_training_steps,
+ )
+ return LambdaLR(optimizer, lr_lambda, last_epoch)
+
+
+def _get_cosine_schedule_with_warmup_lr_lambda(
+ current_step: int, *, num_warmup_steps: int, num_training_steps: int, num_cycles: float
+):
+ if current_step < num_warmup_steps:
+ return float(current_step) / float(max(1, num_warmup_steps))
+ progress = float(current_step - num_warmup_steps) / float(max(1, num_training_steps - num_warmup_steps))
+ return max(0.0, 0.5 * (1.0 + math.cos(math.pi * float(num_cycles) * 2.0 * progress)))
+
+
+def get_cosine_schedule_with_warmup(
+ optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, num_cycles: float = 0.5, last_epoch: int = -1
+):
+ """
+ Create a schedule with a learning rate that decreases following the values of the cosine function between the
+ initial lr set in the optimizer to 0, after a warmup period during which it increases linearly between 0 and the
+ initial lr set in the optimizer.
+
+ Args:
+ optimizer ([`~torch.optim.Optimizer`]):
+ The optimizer for which to schedule the learning rate.
+ num_warmup_steps (`int`):
+ The number of steps for the warmup phase.
+ num_training_steps (`int`):
+ The total number of training steps.
+ num_cycles (`float`, *optional*, defaults to 0.5):
+ The number of waves in the cosine schedule (the defaults is to just decrease from the max value to 0
+ following a half-cosine).
+ last_epoch (`int`, *optional*, defaults to -1):
+ The index of the last epoch when resuming training.
+
+ Return:
+ `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
+ """
+
+ lr_lambda = partial(
+ _get_cosine_schedule_with_warmup_lr_lambda,
+ num_warmup_steps=num_warmup_steps,
+ num_training_steps=num_training_steps,
+ num_cycles=num_cycles,
+ )
+ return LambdaLR(optimizer, lr_lambda, last_epoch)
+
+
+def _get_cosine_with_hard_restarts_schedule_with_warmup_lr_lambda(
+ current_step: int, *, num_warmup_steps: int, num_training_steps: int, num_cycles: int
+):
+ if current_step < num_warmup_steps:
+ return float(current_step) / float(max(1, num_warmup_steps))
+ progress = float(current_step - num_warmup_steps) / float(max(1, num_training_steps - num_warmup_steps))
+ if progress >= 1.0:
+ return 0.0
+ return max(0.0, 0.5 * (1.0 + math.cos(math.pi * ((float(num_cycles) * progress) % 1.0))))
+
+
+def get_cosine_with_hard_restarts_schedule_with_warmup(
+ optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, num_cycles: int = 1, last_epoch: int = -1
+):
+ """
+ Create a schedule with a learning rate that decreases following the values of the cosine function between the
+ initial lr set in the optimizer to 0, with several hard restarts, after a warmup period during which it increases
+ linearly between 0 and the initial lr set in the optimizer.
+
+ Args:
+ optimizer ([`~torch.optim.Optimizer`]):
+ The optimizer for which to schedule the learning rate.
+ num_warmup_steps (`int`):
+ The number of steps for the warmup phase.
+ num_training_steps (`int`):
+ The total number of training steps.
+ num_cycles (`int`, *optional*, defaults to 1):
+ The number of hard restarts to use.
+ last_epoch (`int`, *optional*, defaults to -1):
+ The index of the last epoch when resuming training.
+
+ Return:
+ `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
+ """
+
+ lr_lambda = partial(
+ _get_cosine_with_hard_restarts_schedule_with_warmup_lr_lambda,
+ num_warmup_steps=num_warmup_steps,
+ num_training_steps=num_training_steps,
+ num_cycles=num_cycles,
+ )
+ return LambdaLR(optimizer, lr_lambda, last_epoch)
+
+
+def _get_polynomial_decay_schedule_with_warmup_lr_lambda(
+ current_step: int,
+ *,
+ num_warmup_steps: int,
+ num_training_steps: int,
+ lr_end: float,
+ power: float,
+ lr_init: int,
+):
+ if current_step < num_warmup_steps:
+ return float(current_step) / float(max(1, num_warmup_steps))
+ elif current_step > num_training_steps:
+ return lr_end / lr_init # as LambdaLR multiplies by lr_init
+ else:
+ lr_range = lr_init - lr_end
+ decay_steps = num_training_steps - num_warmup_steps
+ pct_remaining = 1 - (current_step - num_warmup_steps) / decay_steps
+ decay = lr_range * pct_remaining**power + lr_end
+ return decay / lr_init # as LambdaLR multiplies by lr_init
+
+
+def get_polynomial_decay_schedule_with_warmup(
+ optimizer, num_warmup_steps, num_training_steps, lr_end=1e-7, power=1.0, last_epoch=-1
+):
+ """
+ Create a schedule with a learning rate that decreases as a polynomial decay from the initial lr set in the
+ optimizer to end lr defined by *lr_end*, after a warmup period during which it increases linearly from 0 to the
+ initial lr set in the optimizer.
+
+ Args:
+ optimizer ([`~torch.optim.Optimizer`]):
+ The optimizer for which to schedule the learning rate.
+ num_warmup_steps (`int`):
+ The number of steps for the warmup phase.
+ num_training_steps (`int`):
+ The total number of training steps.
+ lr_end (`float`, *optional*, defaults to 1e-7):
+ The end LR.
+ power (`float`, *optional*, defaults to 1.0):
+ Power factor.
+ last_epoch (`int`, *optional*, defaults to -1):
+ The index of the last epoch when resuming training.
+
+ Note: *power* defaults to 1.0 as in the fairseq implementation, which in turn is based on the original BERT
+ implementation at
+ https://github.com/google-research/bert/blob/f39e881b169b9d53bea03d2d341b31707a6c052b/optimization.py#L37
+
+ Return:
+ `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
+
+ """
+
+ lr_init = optimizer.defaults["lr"]
+ if not (lr_init > lr_end):
+ raise ValueError(f"lr_end ({lr_end}) must be smaller than initial lr ({lr_init})")
+
+ lr_lambda = partial(
+ _get_polynomial_decay_schedule_with_warmup_lr_lambda,
+ num_warmup_steps=num_warmup_steps,
+ num_training_steps=num_training_steps,
+ lr_end=lr_end,
+ power=power,
+ lr_init=lr_init,
+ )
+ return LambdaLR(optimizer, lr_lambda, last_epoch)
+
+
+def _get_inverse_sqrt_schedule_lr_lambda(current_step: int, *, num_warmup_steps: int, timescale: int | None = None):
+ if current_step < num_warmup_steps:
+ return float(current_step) / float(max(1, num_warmup_steps))
+ shift = timescale - num_warmup_steps
+ decay = 1.0 / math.sqrt((current_step + shift) / timescale)
+ return decay
+
+
+def get_inverse_sqrt_schedule(
+ optimizer: Optimizer, num_warmup_steps: int, timescale: int | None = None, last_epoch: int = -1
+):
+ """
+ Create a schedule with an inverse square-root learning rate, from the initial lr set in the optimizer, after a
+ warmup period which increases lr linearly from 0 to the initial lr set in the optimizer.
+
+ Args:
+ optimizer ([`~torch.optim.Optimizer`]):
+ The optimizer for which to schedule the learning rate.
+ num_warmup_steps (`int`):
+ The number of steps for the warmup phase.
+ timescale (`int`, *optional*, defaults to `num_warmup_steps`):
+ Time scale.
+ last_epoch (`int`, *optional*, defaults to -1):
+ The index of the last epoch when resuming training.
+
+ Return:
+ `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
+ """
+ # Note: this implementation is adapted from
+ # https://github.com/google-research/big_vision/blob/f071ce68852d56099437004fd70057597a95f6ef/big_vision/utils.py#L930
+
+ if timescale is None:
+ timescale = num_warmup_steps or 10_000
+
+ lr_lambda = partial(_get_inverse_sqrt_schedule_lr_lambda, num_warmup_steps=num_warmup_steps, timescale=timescale)
+ return LambdaLR(optimizer, lr_lambda, last_epoch=last_epoch)
+
+
+def _get_cosine_schedule_with_warmup_lr_lambda(
+ current_step: int, *, num_warmup_steps: int, num_training_steps: int, num_cycles: float, min_lr_rate: float = 0.0
+):
+ if current_step < num_warmup_steps:
+ return float(current_step) / float(max(1, num_warmup_steps))
+ progress = float(current_step - num_warmup_steps) / float(max(1, num_training_steps - num_warmup_steps))
+ factor = 0.5 * (1.0 + math.cos(math.pi * float(num_cycles) * 2.0 * progress))
+ factor = factor * (1 - min_lr_rate) + min_lr_rate
+ return max(0, factor)
+
+
+def get_cosine_with_min_lr_schedule_with_warmup(
+ optimizer: Optimizer,
+ num_warmup_steps: int,
+ num_training_steps: int,
+ num_cycles: float = 0.5,
+ last_epoch: int = -1,
+ min_lr: float | None = None,
+ min_lr_rate: float | None = None,
+):
+ """
+ Create a schedule with a learning rate that decreases following the values of the cosine function between the
+ initial lr set in the optimizer to min_lr, after a warmup period during which it increases linearly between 0 and the
+ initial lr set in the optimizer.
+
+ Args:
+ optimizer ([`~torch.optim.Optimizer`]):
+ The optimizer for which to schedule the learning rate.
+ num_warmup_steps (`int`):
+ The number of steps for the warmup phase.
+ num_training_steps (`int`):
+ The total number of training steps.
+ num_cycles (`float`, *optional*, defaults to 0.5):
+ The number of waves in the cosine schedule (the defaults is to just decrease from the max value to 0
+ following a half-cosine).
+ last_epoch (`int`, *optional*, defaults to -1):
+ The index of the last epoch when resuming training.
+ min_lr (`float`, *optional*):
+ The minimum learning rate to reach after the cosine schedule.
+ min_lr_rate (`float`, *optional*):
+ The minimum learning rate as a ratio of the initial learning rate. If set, `min_lr` should not be set.
+
+ Return:
+ `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
+ """
+
+ if min_lr is not None and min_lr_rate is not None:
+ raise ValueError("Only one of min_lr or min_lr_rate should be set")
+ elif min_lr is not None:
+ min_lr_rate = min_lr / optimizer.defaults["lr"]
+ elif min_lr_rate is None:
+ raise ValueError("One of min_lr or min_lr_rate should be set through the `lr_scheduler_kwargs`")
+
+ lr_lambda = partial(
+ _get_cosine_schedule_with_warmup_lr_lambda,
+ num_warmup_steps=num_warmup_steps,
+ num_training_steps=num_training_steps,
+ num_cycles=num_cycles,
+ min_lr_rate=min_lr_rate,
+ )
+ return LambdaLR(optimizer, lr_lambda, last_epoch)
+
+
+def _get_cosine_with_min_lr_schedule_with_warmup_lr_rate_lambda(
+ current_step: int,
+ *,
+ num_warmup_steps: int,
+ num_training_steps: int,
+ num_cycles: float,
+ min_lr_rate: float = 0.0,
+ warmup_lr_rate: float | None = None,
+):
+ current_step = float(current_step)
+ num_warmup_steps = float(num_warmup_steps)
+ num_training_steps = float(num_training_steps)
+
+ if current_step < num_warmup_steps:
+ if warmup_lr_rate is None:
+ return (current_step + 1.0) / max(1.0, num_warmup_steps)
+ else:
+ warmup_lr_rate = float(warmup_lr_rate)
+ return warmup_lr_rate + (1.0 - warmup_lr_rate) * (current_step) / (max(1, num_warmup_steps - 1))
+ progress = (current_step - num_warmup_steps + 1.0) / (max(1.0, num_training_steps - num_warmup_steps))
+ factor = 0.5 * (1.0 + math.cos(math.pi * num_cycles * 2.0 * progress))
+ factor = factor * (1 - min_lr_rate) + min_lr_rate
+ return max(0, factor)
+
+
+def get_cosine_with_min_lr_schedule_with_warmup_lr_rate(
+ optimizer: Optimizer,
+ num_warmup_steps: int,
+ num_training_steps: int,
+ num_cycles: float = 0.5,
+ last_epoch: int = -1,
+ min_lr: float | None = None,
+ min_lr_rate: float | None = None,
+ warmup_lr_rate: float | None = None,
+):
+ """
+ Create a schedule with a learning rate that decreases following the values of the cosine function between the
+ initial lr set in the optimizer to min_lr, after a warmup period during which it increases linearly between 0 and the
+ initial lr set in the optimizer.
+
+ Args:
+ optimizer ([`~torch.optim.Optimizer`]):
+ The optimizer for which to schedule the learning rate.
+ num_warmup_steps (`int`):
+ The number of steps for the warmup phase.
+ num_training_steps (`int`):
+ The total number of training steps.
+ num_cycles (`float`, *optional*, defaults to 0.5):
+ The number of waves in the cosine schedule (the defaults is to just decrease from the max value to 0
+ following a half-cosine).
+ last_epoch (`int`, *optional*, defaults to -1):
+ The index of the last epoch when resuming training.
+ min_lr (`float`, *optional*):
+ The minimum learning rate to reach after the cosine schedule.
+ min_lr_rate (`float`, *optional*):
+ The minimum learning rate as a ratio of the initial learning rate. If set, `min_lr` should not be set.
+ warmup_lr_rate (`float`, *optional*):
+ The minimum learning rate as a ratio of the start learning rate. If not set, `warmup_lr_rate` will be treated as float(1/num_warmup_steps).
+
+ Return:
+ `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
+ """
+
+ if min_lr is not None and min_lr_rate is not None:
+ raise ValueError("Only one of min_lr or min_lr_rate should be set")
+ elif min_lr is not None:
+ min_lr_rate = min_lr / optimizer.defaults["lr"]
+ elif min_lr_rate is None:
+ raise ValueError("One of min_lr or min_lr_rate should be set through the `lr_scheduler_kwargs`")
+
+ lr_lambda = partial(
+ _get_cosine_with_min_lr_schedule_with_warmup_lr_rate_lambda,
+ num_warmup_steps=num_warmup_steps,
+ num_training_steps=num_training_steps,
+ num_cycles=num_cycles,
+ min_lr_rate=min_lr_rate,
+ warmup_lr_rate=warmup_lr_rate,
+ )
+ return LambdaLR(optimizer, lr_lambda, last_epoch)
+
+
+def _get_wsd_scheduler_lambda(
+ current_step: int,
+ *,
+ num_warmup_steps: int,
+ num_stable_steps: int,
+ num_decay_steps: int,
+ warmup_type: str,
+ decay_type: str,
+ min_lr_ratio: float,
+ num_cycles: float,
+):
+ if current_step < num_warmup_steps:
+ progress = float(current_step) / float(max(1, num_warmup_steps))
+ if warmup_type == "linear":
+ factor = progress
+ elif warmup_type == "cosine":
+ factor = 0.5 * (1.0 - math.cos(math.pi * progress))
+ elif warmup_type == "1-sqrt":
+ factor = 1.0 - math.sqrt(1.0 - progress)
+ factor = factor * (1.0 - min_lr_ratio) + min_lr_ratio
+ return max(0.0, factor)
+
+ if current_step < num_warmup_steps + num_stable_steps:
+ return 1.0
+
+ if current_step < num_warmup_steps + num_stable_steps + num_decay_steps:
+ progress = float(current_step - num_warmup_steps - num_stable_steps) / float(max(1, num_decay_steps))
+ if decay_type == "linear":
+ factor = 1.0 - progress
+ elif decay_type == "cosine":
+ factor = 0.5 * (1.0 + math.cos(math.pi * float(num_cycles) * 2.0 * progress))
+ elif decay_type == "1-sqrt":
+ factor = 1.0 - math.sqrt(progress)
+ factor = factor * (1.0 - min_lr_ratio) + min_lr_ratio
+ return max(0.0, factor)
+ return min_lr_ratio
+
+
+def get_wsd_schedule(
+ optimizer: Optimizer,
+ num_warmup_steps: int,
+ num_decay_steps: int,
+ num_training_steps: int | None = None,
+ num_stable_steps: int | None = None,
+ warmup_type: str = "linear",
+ decay_type: str = "cosine",
+ min_lr_ratio: float = 0,
+ num_cycles: float = 0.5,
+ last_epoch: int = -1,
+):
+ """
+ Create a schedule with a learning rate that has three stages:
+ 1. warmup: increase from min_lr_ratio times the initial learning rate to the initial learning rate following a warmup_type.
+ 2. stable: constant learning rate.
+ 3. decay: decrease from the initial learning rate to min_lr_ratio times the initial learning rate following a decay_type.
+
+ Args:
+ optimizer ([`~torch.optim.Optimizer`]):
+ The optimizer for which to schedule the learning rate.
+ num_warmup_steps (`int`):
+ The number of steps for the warmup phase.
+ num_decay_steps (`int`):
+ The number of steps for the decay phase.
+ num_training_steps (`int`, *optional*):
+ The total number of training steps. This is the sum of the warmup, stable and decay steps. If `num_stable_steps` is not provided, the stable phase will be `num_training_steps - num_warmup_steps - num_decay_steps`.
+ num_stable_steps (`int`, *optional*):
+ The number of steps for the stable phase. Please ensure that `num_warmup_steps + num_stable_steps + num_decay_steps` equals `num_training_steps`, otherwise the other steps will default to the minimum learning rate.
+ warmup_type (`str`, *optional*, defaults to "linear"):
+ The type of warmup to use. Can be 'linear', 'cosine' or '1-sqrt'.
+ decay_type (`str`, *optional*, defaults to "cosine"):
+ The type of decay to use. Can be 'linear', 'cosine' or '1-sqrt'.
+ min_lr_ratio (`float`, *optional*, defaults to 0):
+ The minimum learning rate as a ratio of the initial learning rate.
+ num_cycles (`float`, *optional*, defaults to 0.5):
+ The number of waves in the cosine schedule (the defaults is to just decrease from the max value to 0
+ following a half-cosine).
+ last_epoch (`int`, *optional*, defaults to -1):
+ The index of the last epoch when resuming training.
+
+ Return:
+ `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
+ """
+
+ if num_training_steps is None and num_stable_steps is None:
+ raise ValueError("Either num_training_steps or num_stable_steps must be specified.")
+
+ if num_training_steps is not None and num_stable_steps is not None:
+ warnings.warn("Both num_training_steps and num_stable_steps are specified. num_stable_steps will be used.")
+
+ if warmup_type not in ["linear", "cosine", "1-sqrt"]:
+ raise ValueError(f"Unknown warmup type: {warmup_type}, expected 'linear', 'cosine' or '1-sqrt'")
+
+ if decay_type not in ["linear", "cosine", "1-sqrt"]:
+ raise ValueError(f"Unknown decay type: {decay_type}, expected 'linear', 'cosine' or '1-sqrt'")
+
+ if num_stable_steps is None:
+ num_stable_steps = num_training_steps - num_warmup_steps - num_decay_steps
+
+ lr_lambda = partial(
+ _get_wsd_scheduler_lambda,
+ num_warmup_steps=num_warmup_steps,
+ num_stable_steps=num_stable_steps,
+ num_decay_steps=num_decay_steps,
+ warmup_type=warmup_type,
+ decay_type=decay_type,
+ min_lr_ratio=min_lr_ratio,
+ num_cycles=num_cycles,
+ )
+ return LambdaLR(optimizer, lr_lambda, last_epoch)
+
+
+class StreamingAverage:
+ """Rolling window average for smoothing metric values.
+
+ Maintains a sliding window of values and computes their average,
+ useful for smoothing noisy metric values before making learning rate decisions.
+
+ Args:
+ window_size (`int`):
+ The maximum number of values to keep in the rolling window.
+ """
+
+ def __init__(self, window_size: int) -> None:
+ self.window_size: int = window_size
+ self.values: list[float] = []
+ self.sum: float = 0.0
+
+ def streamavg(self, value: float) -> float:
+ """Add a value and return the current rolling average."""
+ self.values.append(value)
+ self.sum += value
+
+ if len(self.values) > self.window_size:
+ removed = self.values.pop(0)
+ self.sum -= removed
+
+ return self.sum / len(self.values)
+
+ def state_dict(self) -> dict[str, Any]:
+ return {
+ "window_size": self.window_size,
+ "values": self.values.copy(),
+ "sum": self.sum,
+ }
+
+ def load_state_dict(self, state_dict: dict[str, Any]) -> None:
+ self.window_size = state_dict.get("window_size", self.window_size)
+ self.values = state_dict.get("values", []).copy()
+ self.sum = state_dict.get("sum", 0.0)
+
+
+class GreedyLR:
+ """Adaptive learning rate scheduler that responds to training metrics.
+
+ GreedyLR dynamically adjusts the learning rate based on training performance:
+ - Increases LR when metrics improve consistently (divides by factor)
+ - Decreases LR when metrics plateau (multiplies by factor)
+
+ This differs from traditional schedulers like cosine annealing by responding
+ to actual training dynamics rather than following a predetermined schedule.
+
+ Reference: `GreedyLR: A Novel Adaptive Learning Rate Scheduler `_
+
+ Args:
+ optimizer ([`~torch.optim.Optimizer`]):
+ The optimizer for which to schedule the learning rate.
+ mode (`str`, *optional*, defaults to `"min"`):
+ One of 'min' or 'max'. In 'min' mode, LR will be reduced when the
+ metric has stopped decreasing; in 'max' mode when it has stopped increasing.
+ factor (`float`, *optional*, defaults to 0.95):
+ Factor by which the learning rate will be adjusted. LR is multiplied by
+ factor on plateau and divided by factor on improvement. Must be < 1.0.
+ patience (`int`, *optional*, defaults to 10):
+ Number of epochs with no improvement after which learning rate will be adjusted.
+ threshold (`float`, *optional*, defaults to 1e-06):
+ Threshold for measuring the new optimum.
+ threshold_mode (`str`, *optional*, defaults to `"abs"`):
+ One of 'rel' or 'abs'.
+ cooldown (`int`, *optional*, defaults to 0):
+ Number of epochs to wait before resuming normal operation after LR has been reduced.
+ warmup (`int`, *optional*, defaults to 0):
+ Number of epochs to wait before resuming normal operation after LR has been increased.
+ min_lr (`float` or `list[float]`, *optional*, defaults to 0.001):
+ A lower bound on the learning rate.
+ max_lr (`float` or `list[float]`, *optional*, defaults to 1.0):
+ An upper bound on the learning rate.
+ eps (`float`, *optional*, defaults to 1e-08):
+ Minimal decay applied to lr.
+ verbose (`bool`, *optional*, defaults to `False`):
+ If True, prints a message to stdout for each update.
+ smooth (`bool`, *optional*, defaults to `False`):
+ If True, applies streaming average smoothing to metrics.
+ window_size (`int`, *optional*, defaults to 50):
+ The window size for the streaming average when smooth=True.
+ reset_start (`int`, *optional*, defaults to 500):
+ Number of steps to wait at min_lr before resetting to initial state.
+
+ Example:
+ ```python
+ >>> optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
+ >>> scheduler = GreedyLR(optimizer, mode="min", patience=10)
+ >>> for epoch in range(100):
+ ... train(...)
+ ... val_loss = validate(...)
+ ... scheduler.step(val_loss)
+ ```
+ """
+
+ def __init__(
+ self,
+ optimizer: Optimizer,
+ mode: str = "min",
+ factor: float = 0.95,
+ patience: int = 10,
+ threshold: float = 1e-6,
+ threshold_mode: str = "abs",
+ cooldown: int = 0,
+ warmup: int = 0,
+ min_lr: float | list[float] = 1e-3,
+ max_lr: float | list[float] = 1.0,
+ eps: float = 1e-8,
+ verbose: bool = False,
+ smooth: bool = False,
+ window_size: int = 50,
+ reset_start: int = 500,
+ ) -> None:
+ if factor >= 1.0:
+ raise ValueError("Factor should be < 1.0.")
+ if not isinstance(optimizer, Optimizer):
+ raise TypeError(f"{type(optimizer).__name__} is not an Optimizer")
+
+ self.optimizer = optimizer
+ self.factor = factor
+ self.patience = patience
+ self.verbose = verbose
+ self.cooldown = cooldown
+ self.warmup = warmup
+ self.cooldown_counter = 0
+ self.warmup_counter = 0
+ self.mode = mode
+ self.threshold = threshold
+ self.threshold_mode = threshold_mode
+ self.eps = eps
+ self.smooth = smooth
+ self.window_size = window_size
+ self.reset_start = reset_start
+ self.reset_start_original = reset_start
+ self.last_epoch = 0
+
+ if isinstance(min_lr, (list, tuple)):
+ if len(min_lr) != len(optimizer.param_groups):
+ raise ValueError(f"expected {len(optimizer.param_groups)} min_lrs, got {len(min_lr)}")
+ self.min_lrs = list(min_lr)
+ else:
+ self.min_lrs = [min_lr] * len(optimizer.param_groups)
+
+ if isinstance(max_lr, (list, tuple)):
+ if len(max_lr) != len(optimizer.param_groups):
+ raise ValueError(f"expected {len(optimizer.param_groups)} max_lrs, got {len(max_lr)}")
+ self.max_lrs = list(max_lr)
+ else:
+ self.max_lrs = [max_lr] * len(optimizer.param_groups)
+
+ self._init_lrs = [group["lr"] for group in optimizer.param_groups]
+ self._last_lr = self._init_lrs.copy()
+
+ self.best: float = float("inf") if mode == "min" else float("-inf")
+ self.num_bad_epochs = 0
+ self.num_good_epochs = 0
+
+ if mode not in ("min", "max"):
+ raise ValueError(f"mode {mode} is unknown!")
+ if threshold_mode not in ("rel", "abs"):
+ raise ValueError(f"threshold mode {threshold_mode} is unknown!")
+
+ self._streaming_avg: StreamingAverage | None = None
+ if smooth:
+ self._streaming_avg = StreamingAverage(window_size)
+
+ def step(self, metrics: float, epoch: int | None = None) -> None:
+ """Perform a scheduler step based on the given metrics.
+
+ Args:
+ metrics (`float`):
+ The metric value to use for LR adjustment decisions.
+ epoch (`int`, *optional*):
+ The current epoch number. If None, uses internal counter.
+ """
+ current = float(metrics)
+
+ if self.smooth and self._streaming_avg is not None:
+ current = self._streaming_avg.streamavg(current)
+
+ if epoch is None:
+ epoch = self.last_epoch + 1
+ self.last_epoch = epoch
+
+ if self.cooldown_counter > 0:
+ self.cooldown_counter -= 1
+ self.num_bad_epochs = 0
+ self.num_good_epochs = 0
+ elif self.warmup_counter > 0:
+ self.warmup_counter -= 1
+ self.num_bad_epochs = 0
+ self.num_good_epochs = 0
+ else:
+ if self.is_better(current, self.best):
+ self.best = current
+ self.num_bad_epochs = 0
+ self.num_good_epochs += 1
+ else:
+ self.num_bad_epochs += 1
+ self.num_good_epochs = 0
+
+ if self.num_good_epochs > self.patience:
+ self._increase_lr(epoch)
+ self.warmup_counter = self.warmup
+ self.num_good_epochs = 0
+ elif self.num_bad_epochs > self.patience:
+ self._reduce_lr(epoch)
+ self.cooldown_counter = self.cooldown
+ self.num_bad_epochs = 0
+
+ self._last_lr = [group["lr"] for group in self.optimizer.param_groups]
+
+ def is_better(self, current: float, best: float) -> bool:
+ if self.mode == "min":
+ if self.threshold_mode == "rel":
+ return current < best * (1.0 - self.threshold)
+ else:
+ return current < best - self.threshold
+ else:
+ if self.threshold_mode == "rel":
+ return current > best * (1.0 + self.threshold)
+ else:
+ return current > best + self.threshold
+
+ def _reduce_lr(self, epoch: int) -> None:
+ all_at_min = True
+ for i, param_group in enumerate(self.optimizer.param_groups):
+ old_lr = float(param_group["lr"])
+ new_lr = max(old_lr * self.factor, self.min_lrs[i])
+
+ if old_lr - new_lr > self.eps:
+ param_group["lr"] = new_lr
+ if self.verbose:
+ print(f"Epoch {epoch}: reducing learning rate of group {i} to {new_lr:.4e}.")
+
+ if param_group["lr"] > self.min_lrs[i]:
+ all_at_min = False
+
+ if all_at_min:
+ self.reset_start -= 1
+ if self.reset_start <= 0:
+ self._reset()
+
+ def _increase_lr(self, epoch: int) -> None:
+ for i, param_group in enumerate(self.optimizer.param_groups):
+ old_lr = float(param_group["lr"])
+ new_lr = min(old_lr / self.factor, self.max_lrs[i])
+
+ if new_lr - old_lr > self.eps:
+ param_group["lr"] = new_lr
+ if self.verbose:
+ print(f"Epoch {epoch}: increasing learning rate of group {i} to {new_lr:.4e}.")
+
+ self.reset_start = self.reset_start_original
+
+ def _reset(self) -> None:
+ for i, param_group in enumerate(self.optimizer.param_groups):
+ param_group["lr"] = self._init_lrs[i]
+
+ self.best = float("inf") if self.mode == "min" else float("-inf")
+ self.num_bad_epochs = 0
+ self.num_good_epochs = 0
+ self.cooldown_counter = 0
+ self.warmup_counter = 0
+ self.reset_start = self.reset_start_original
+
+ if self.smooth and self._streaming_avg is not None:
+ self._streaming_avg = StreamingAverage(self.window_size)
+
+ if self.verbose:
+ print("Scheduler reset to initial state.")
+
+ def get_last_lr(self) -> list[float]:
+ """Return last computed learning rate by current scheduler."""
+ return self._last_lr
+
+ def state_dict(self) -> dict[str, Any]:
+ """Return the state of the scheduler as a dictionary."""
+ state = {
+ "factor": self.factor,
+ "min_lrs": self.min_lrs,
+ "max_lrs": self.max_lrs,
+ "patience": self.patience,
+ "verbose": self.verbose,
+ "cooldown": self.cooldown,
+ "warmup": self.warmup,
+ "cooldown_counter": self.cooldown_counter,
+ "warmup_counter": self.warmup_counter,
+ "mode": self.mode,
+ "threshold": self.threshold,
+ "threshold_mode": self.threshold_mode,
+ "best": self.best,
+ "num_bad_epochs": self.num_bad_epochs,
+ "num_good_epochs": self.num_good_epochs,
+ "eps": self.eps,
+ "last_epoch": self.last_epoch,
+ "smooth": self.smooth,
+ "window_size": self.window_size,
+ "reset_start": self.reset_start,
+ "reset_start_original": self.reset_start_original,
+ "_last_lr": self._last_lr,
+ "_init_lrs": self._init_lrs,
+ }
+
+ if self.smooth and self._streaming_avg is not None:
+ state["_streaming_avg"] = self._streaming_avg.state_dict()
+
+ return state
+
+ def load_state_dict(self, state_dict: dict[str, Any]) -> None:
+ """Load state from a dictionary."""
+ self.factor = state_dict.get("factor", self.factor)
+ self.min_lrs = state_dict.get("min_lrs", self.min_lrs)
+ self.max_lrs = state_dict.get("max_lrs", self.max_lrs)
+ self.patience = state_dict.get("patience", self.patience)
+ self.verbose = state_dict.get("verbose", self.verbose)
+ self.cooldown = state_dict.get("cooldown", self.cooldown)
+ self.warmup = state_dict.get("warmup", self.warmup)
+ self.cooldown_counter = state_dict.get("cooldown_counter", self.cooldown_counter)
+ self.warmup_counter = state_dict.get("warmup_counter", self.warmup_counter)
+ self.mode = state_dict.get("mode", self.mode)
+ self.threshold = state_dict.get("threshold", self.threshold)
+ self.threshold_mode = state_dict.get("threshold_mode", self.threshold_mode)
+ self.best = state_dict.get("best", self.best)
+ self.num_bad_epochs = state_dict.get("num_bad_epochs", self.num_bad_epochs)
+ self.num_good_epochs = state_dict.get("num_good_epochs", self.num_good_epochs)
+ self.eps = state_dict.get("eps", self.eps)
+ self.last_epoch = state_dict.get("last_epoch", self.last_epoch)
+ self.smooth = state_dict.get("smooth", self.smooth)
+ self.window_size = state_dict.get("window_size", self.window_size)
+ self.reset_start = state_dict.get("reset_start", self.reset_start)
+ self.reset_start_original = state_dict.get("reset_start_original", self.reset_start_original)
+ self._last_lr = state_dict.get("_last_lr", self._last_lr)
+ self._init_lrs = state_dict.get("_init_lrs", self._init_lrs)
+
+ if "_streaming_avg" in state_dict:
+ if self._streaming_avg is None:
+ self._streaming_avg = StreamingAverage(self.window_size)
+ self._streaming_avg.load_state_dict(state_dict["_streaming_avg"])
+
+ if "_last_lr" in state_dict:
+ for param_group, lr in zip(self.optimizer.param_groups, self._last_lr):
+ param_group["lr"] = lr
+
+
+def get_greedy_schedule(optimizer: Optimizer, **kwargs):
+ """
+ Create an adaptive learning rate scheduler that adjusts LR based on training metrics.
+
+ Args:
+ optimizer ([`~torch.optim.Optimizer`]):
+ The optimizer for which to schedule the learning rate.
+ kwargs (`dict`, *optional*):
+ Extra parameters passed to the scheduler. See [`GreedyLR`] for possible parameters.
+
+ Return:
+ [`GreedyLR`] with the appropriate schedule.
+ """
+ return GreedyLR(optimizer, **kwargs)
+
+
+TYPE_TO_SCHEDULER_FUNCTION = {
+ SchedulerType.LINEAR: get_linear_schedule_with_warmup,
+ SchedulerType.COSINE: get_cosine_schedule_with_warmup,
+ SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup,
+ SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup,
+ SchedulerType.CONSTANT: get_constant_schedule,
+ SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup,
+ SchedulerType.INVERSE_SQRT: get_inverse_sqrt_schedule,
+ SchedulerType.REDUCE_ON_PLATEAU: get_reduce_on_plateau_schedule,
+ SchedulerType.COSINE_WITH_MIN_LR: get_cosine_with_min_lr_schedule_with_warmup,
+ SchedulerType.COSINE_WARMUP_WITH_MIN_LR: get_cosine_with_min_lr_schedule_with_warmup_lr_rate,
+ SchedulerType.WARMUP_STABLE_DECAY: get_wsd_schedule,
+ SchedulerType.GREEDY: get_greedy_schedule,
+}
+
+
+def get_scheduler(
+ name: str | SchedulerType,
+ optimizer: Optimizer,
+ num_warmup_steps: int | None = None,
+ num_training_steps: int | None = None,
+ scheduler_specific_kwargs: dict | None = None,
+):
+ """
+ Unified API to get any scheduler from its name.
+
+ Args:
+ name (`str` or `SchedulerType`):
+ The name of the scheduler to use.
+ optimizer (`torch.optim.Optimizer`):
+ The optimizer that will be used during training.
+ num_warmup_steps (`int`, *optional*):
+ The number of warmup steps to do. This is not required by all schedulers (hence the argument being
+ optional), the function will raise an error if it's unset and the scheduler type requires it.
+ num_training_steps (`int``, *optional*):
+ The number of training steps to do. This is not required by all schedulers (hence the argument being
+ optional), the function will raise an error if it's unset and the scheduler type requires it.
+ scheduler_specific_kwargs (`dict`, *optional*):
+ Extra parameters for schedulers such as cosine with restarts. Mismatched scheduler types and scheduler
+ parameters will cause the scheduler function to raise a TypeError.
+ """
+ name = SchedulerType(name)
+ schedule_func = TYPE_TO_SCHEDULER_FUNCTION[name]
+
+ # If a `LayerWiseDummyOptimizer` is passed we extract the optimizer dict and
+ # recursively call `get_scheduler` to get the proper schedulers on each parameter
+ if optimizer is not None and isinstance(optimizer, LayerWiseDummyOptimizer):
+ optimizer_dict = optimizer.optimizer_dict
+ scheduler_dict = {}
+
+ for param in optimizer_dict:
+ scheduler_dict[param] = get_scheduler(
+ name,
+ optimizer=optimizer_dict[param],
+ num_warmup_steps=num_warmup_steps,
+ num_training_steps=num_training_steps,
+ scheduler_specific_kwargs=scheduler_specific_kwargs,
+ )
+
+ def scheduler_hook(param):
+ # Since the optimizer hook has been already attached we only need to
+ # attach the scheduler hook, the gradients have been zeroed here
+ scheduler_dict[param].step()
+
+ for param in optimizer_dict:
+ if param.requires_grad:
+ param.register_post_accumulate_grad_hook(scheduler_hook)
+
+ return LayerWiseDummyScheduler(optimizer_dict=optimizer_dict, lr=optimizer.defaults["lr"])
+
+ if name == SchedulerType.CONSTANT:
+ return schedule_func(optimizer)
+
+ if scheduler_specific_kwargs is None:
+ scheduler_specific_kwargs = {}
+
+ if name == SchedulerType.REDUCE_ON_PLATEAU:
+ return schedule_func(optimizer, **scheduler_specific_kwargs)
+
+ if name == SchedulerType.GREEDY:
+ return schedule_func(optimizer, **scheduler_specific_kwargs)
+
+ # All other schedulers require `num_warmup_steps`
+ if num_warmup_steps is None:
+ raise ValueError(f"{name} requires `num_warmup_steps`, please provide that argument.")
+
+ if name == SchedulerType.CONSTANT_WITH_WARMUP:
+ return schedule_func(optimizer, num_warmup_steps=num_warmup_steps)
+
+ if name == SchedulerType.INVERSE_SQRT:
+ return schedule_func(optimizer, num_warmup_steps=num_warmup_steps, **scheduler_specific_kwargs)
+
+ # wsd scheduler requires either num_training_steps or num_stable_steps
+ if name == SchedulerType.WARMUP_STABLE_DECAY:
+ return schedule_func(
+ optimizer,
+ num_warmup_steps=num_warmup_steps,
+ num_training_steps=num_training_steps,
+ **scheduler_specific_kwargs,
+ )
+
+ # All other schedulers require `num_training_steps`
+ if num_training_steps is None:
+ raise ValueError(f"{name} requires `num_training_steps`, please provide that argument.")
+
+ return schedule_func(
+ optimizer,
+ num_warmup_steps=num_warmup_steps,
+ num_training_steps=num_training_steps,
+ **scheduler_specific_kwargs,
+ )
+
+
+class Adafactor(Optimizer):
+ """
+ AdaFactor pytorch implementation can be used as a drop in replacement for Adam original fairseq code:
+ https://github.com/pytorch/fairseq/blob/master/fairseq/optim/adafactor.py
+
+ Paper: *Adafactor: Adaptive Learning Rates with Sublinear Memory Cost* https://huggingface.co/papers/1804.04235 Note that
+ this optimizer internally adjusts the learning rate depending on the `scale_parameter`, `relative_step` and
+ `warmup_init` options. To use a manual (external) learning rate schedule you should set `scale_parameter=False` and
+ `relative_step=False`.
+
+ Arguments:
+ params (`Iterable[nn.parameter.Parameter]`):
+ Iterable of parameters to optimize or dictionaries defining parameter groups.
+ lr (`float`, *optional*):
+ The external learning rate.
+ eps (`tuple[float, float]`, *optional*, defaults to `(1e-30, 0.001)`):
+ Regularization constants for square gradient and parameter scale respectively
+ clip_threshold (`float`, *optional*, defaults to 1.0):
+ Threshold of root mean square of final gradient update
+ decay_rate (`float`, *optional*, defaults to -0.8):
+ Coefficient used to compute running averages of square
+ beta1 (`float`, *optional*):
+ Coefficient used for computing running averages of gradient
+ weight_decay (`float`, *optional*, defaults to 0.0):
+ Weight decay (L2 penalty)
+ scale_parameter (`bool`, *optional*, defaults to `True`):
+ If True, learning rate is scaled by root mean square
+ relative_step (`bool`, *optional*, defaults to `True`):
+ If True, time-dependent learning rate is computed instead of external learning rate
+ warmup_init (`bool`, *optional*, defaults to `False`):
+ Time-dependent learning rate computation depends on whether warm-up initialization is being used
+
+ This implementation handles low-precision (FP16, bfloat) values, but we have not thoroughly tested.
+
+ Recommended T5 finetuning settings (https://discuss.huggingface.co/t/t5-finetuning-tips/684/3):
+
+ - Training without LR warmup or clip_threshold is not recommended.
+
+ - use scheduled LR warm-up to fixed LR
+ - use clip_threshold=1.0 (https://huggingface.co/papers/1804.04235)
+ - Disable relative updates
+ - Use scale_parameter=False
+ - Additional optimizer operations like gradient clipping should not be used alongside Adafactor
+
+ Example:
+
+ ```python
+ Adafactor(model.parameters(), scale_parameter=False, relative_step=False, warmup_init=False, lr=1e-3)
+ ```
+
+ Others reported the following combination to work well:
+
+ ```python
+ Adafactor(model.parameters(), scale_parameter=True, relative_step=True, warmup_init=True, lr=None)
+ ```
+
+ When using `lr=None` with [`Trainer`] you will most likely need to use [`~optimization.AdafactorSchedule`]
+ scheduler as following:
+
+ ```python
+ from transformers.optimization import Adafactor, AdafactorSchedule
+
+ optimizer = Adafactor(model.parameters(), scale_parameter=True, relative_step=True, warmup_init=True, lr=None)
+ lr_scheduler = AdafactorSchedule(optimizer)
+ trainer = Trainer(..., optimizers=(optimizer, lr_scheduler))
+ ```
+
+ Usage:
+
+ ```python
+ # replace AdamW with Adafactor
+ optimizer = Adafactor(
+ model.parameters(),
+ lr=1e-3,
+ eps=(1e-30, 1e-3),
+ clip_threshold=1.0,
+ decay_rate=-0.8,
+ beta1=None,
+ weight_decay=0.0,
+ relative_step=False,
+ scale_parameter=False,
+ warmup_init=False,
+ )
+ ```"""
+
+ def __init__(
+ self,
+ params,
+ lr=None,
+ eps=(1e-30, 1e-3),
+ clip_threshold=1.0,
+ decay_rate=-0.8,
+ beta1=None,
+ weight_decay=0.0,
+ scale_parameter=True,
+ relative_step=True,
+ warmup_init=False,
+ ):
+ if lr is not None and relative_step:
+ raise ValueError("Cannot combine manual `lr` and `relative_step=True` options")
+ if warmup_init and not relative_step:
+ raise ValueError("`warmup_init=True` requires `relative_step=True`")
+
+ defaults = {
+ "lr": lr,
+ "eps": eps,
+ "clip_threshold": clip_threshold,
+ "decay_rate": decay_rate,
+ "beta1": beta1,
+ "weight_decay": weight_decay,
+ "scale_parameter": scale_parameter,
+ "relative_step": relative_step,
+ "warmup_init": warmup_init,
+ }
+ super().__init__(params, defaults)
+
+ @staticmethod
+ def _get_lr(param_group, param_state):
+ rel_step_sz = param_group["lr"]
+ if param_group["relative_step"]:
+ min_step = 1e-6 * param_state["step"] if param_group["warmup_init"] else 1e-2
+ rel_step_sz = min(min_step, 1.0 / math.sqrt(param_state["step"]))
+ param_scale = 1.0
+ if param_group["scale_parameter"]:
+ param_scale = max(param_group["eps"][1], param_state["RMS"])
+ return param_scale * rel_step_sz
+
+ @staticmethod
+ def _get_options(param_group, param_shape):
+ factored = len(param_shape) >= 2
+ use_first_moment = param_group["beta1"] is not None
+ return factored, use_first_moment
+
+ @staticmethod
+ def _rms(tensor):
+ return tensor.norm(2) / (tensor.numel() ** 0.5)
+
+ @staticmethod
+ def _approx_sq_grad(exp_avg_sq_row, exp_avg_sq_col):
+ # copy from fairseq's adafactor implementation:
+ # https://github.com/huggingface/transformers/blob/8395f14de6068012787d83989c3627c3df6a252b/src/transformers/optimization.py#L505
+ r_factor = (exp_avg_sq_row / exp_avg_sq_row.mean(dim=-1, keepdim=True)).rsqrt_().unsqueeze(-1)
+ c_factor = exp_avg_sq_col.unsqueeze(-2).rsqrt()
+ return torch.mul(r_factor, c_factor)
+
+ @torch.no_grad()
+ def step(self, closure=None):
+ """
+ Performs a single optimization step
+
+ Arguments:
+ closure (callable, optional): A closure that reevaluates the model
+ and returns the loss.
+ """
+ loss = None
+ if closure is not None:
+ loss = closure()
+
+ for group in self.param_groups:
+ for p in group["params"]:
+ if p.grad is None:
+ continue
+ grad = p.grad
+ if grad.dtype in {torch.float16, torch.bfloat16}:
+ grad = grad.float()
+ if grad.is_sparse:
+ raise RuntimeError("Adafactor does not support sparse gradients.")
+
+ state = self.state[p]
+ grad_shape = grad.shape
+
+ factored, use_first_moment = self._get_options(group, grad_shape)
+ # State Initialization
+ if len(state) == 0:
+ state["step"] = 0
+
+ if use_first_moment:
+ # Exponential moving average of gradient values
+ state["exp_avg"] = torch.zeros_like(grad)
+ if factored:
+ state["exp_avg_sq_row"] = torch.zeros(grad_shape[:-1]).to(grad)
+ state["exp_avg_sq_col"] = torch.zeros(grad_shape[:-2] + grad_shape[-1:]).to(grad)
+ else:
+ state["exp_avg_sq"] = torch.zeros_like(grad)
+
+ state["RMS"] = 0
+ else:
+ if use_first_moment:
+ state["exp_avg"] = state["exp_avg"].to(grad)
+ if factored:
+ state["exp_avg_sq_row"] = state["exp_avg_sq_row"].to(grad)
+ state["exp_avg_sq_col"] = state["exp_avg_sq_col"].to(grad)
+ else:
+ state["exp_avg_sq"] = state["exp_avg_sq"].to(grad)
+
+ p_data_fp32 = p
+ if p.dtype in {torch.float16, torch.bfloat16}:
+ p_data_fp32 = p_data_fp32.float()
+
+ state["step"] += 1
+ state["RMS"] = self._rms(p_data_fp32)
+ lr = self._get_lr(group, state)
+
+ beta2t = 1.0 - math.pow(state["step"], group["decay_rate"])
+ update = (grad**2) + group["eps"][0]
+ if factored:
+ exp_avg_sq_row = state["exp_avg_sq_row"]
+ exp_avg_sq_col = state["exp_avg_sq_col"]
+
+ exp_avg_sq_row.mul_(beta2t).add_(update.mean(dim=-1), alpha=(1.0 - beta2t))
+ exp_avg_sq_col.mul_(beta2t).add_(update.mean(dim=-2), alpha=(1.0 - beta2t))
+
+ # Approximation of exponential moving average of square of gradient
+ update = self._approx_sq_grad(exp_avg_sq_row, exp_avg_sq_col)
+ update.mul_(grad)
+ else:
+ exp_avg_sq = state["exp_avg_sq"]
+
+ exp_avg_sq.mul_(beta2t).add_(update, alpha=(1.0 - beta2t))
+ update = exp_avg_sq.rsqrt().mul_(grad)
+
+ update.div_((self._rms(update) / group["clip_threshold"]).clamp_(min=1.0))
+ update.mul_(lr)
+
+ if use_first_moment:
+ exp_avg = state["exp_avg"]
+ exp_avg.mul_(group["beta1"]).add_(update, alpha=(1 - group["beta1"]))
+ update = exp_avg
+
+ if group["weight_decay"] != 0:
+ p_data_fp32.add_(p_data_fp32, alpha=(-group["weight_decay"] * lr))
+
+ p_data_fp32.add_(-update)
+
+ if p.dtype in {torch.float16, torch.bfloat16}:
+ p.copy_(p_data_fp32)
+
+ return loss
+
+
+class AdafactorSchedule(LambdaLR):
+ """
+ Since [`~optimization.Adafactor`] performs its own scheduling, if the training loop relies on a scheduler (e.g.,
+ for logging), this class creates a proxy object that retrieves the current lr values from the optimizer.
+
+ It returns `initial_lr` during startup and the actual `lr` during stepping.
+ """
+
+ def __init__(self, optimizer, initial_lr=0.0):
+ def lr_lambda(_):
+ return initial_lr
+
+ for group in optimizer.param_groups:
+ group["initial_lr"] = initial_lr
+ super().__init__(optimizer, lr_lambda)
+ for group in optimizer.param_groups:
+ del group["initial_lr"]
+
+ def get_lr(self):
+ opt = self.optimizer
+ lrs = [
+ opt._get_lr(group, opt.state[group["params"][0]])
+ for group in opt.param_groups
+ if group["params"][0].grad is not None
+ ]
+ if len(lrs) == 0:
+ lrs = self.base_lrs # if called before stepping
+ return lrs
+
+
+def get_adafactor_schedule(optimizer, initial_lr=0.0):
+ """
+ Get a proxy schedule for [`~optimization.Adafactor`]
+
+ Args:
+ optimizer ([`~torch.optim.Optimizer`]):
+ The optimizer for which to schedule the learning rate.
+ initial_lr (`float`, *optional*, defaults to 0.0):
+ Initial lr
+
+ Return:
+ [`~optimization.Adafactor`] proxy schedule object.
+
+
+ """
+ return AdafactorSchedule(optimizer, initial_lr)
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__init__.py b/.venv/lib/python3.12/site-packages/transformers/pipelines/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d4a033d8b807985cac6f2cd62cb44bb7c4ee08a0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/pipelines/__init__.py
@@ -0,0 +1,1124 @@
+# Copyright 2018 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from __future__ import annotations
+
+import json
+import os
+import warnings
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Optional, Union
+
+from huggingface_hub import is_offline_mode
+
+from ..configuration_utils import PreTrainedConfig
+from ..dynamic_module_utils import get_class_from_dynamic_module
+from ..feature_extraction_utils import FeatureExtractionMixin
+from ..image_processing_utils import BaseImageProcessor
+from ..models.auto.configuration_auto import AutoConfig
+from ..models.auto.feature_extraction_auto import FEATURE_EXTRACTOR_MAPPING, AutoFeatureExtractor
+from ..models.auto.image_processing_auto import IMAGE_PROCESSOR_MAPPING, AutoImageProcessor
+from ..models.auto.modeling_auto import AutoModelForDepthEstimation, AutoModelForImageToImage
+from ..models.auto.processing_auto import PROCESSOR_MAPPING, AutoProcessor
+from ..models.auto.tokenization_auto import TOKENIZER_MAPPING, AutoTokenizer
+from ..models.auto.video_processing_auto import AutoVideoProcessor
+from ..processing_utils import ProcessorMixin
+from ..tokenization_python import PreTrainedTokenizer
+from ..utils import (
+ CONFIG_NAME,
+ cached_file,
+ extract_commit_hash,
+ find_adapter_config_file,
+ hf_api,
+ is_kenlm_available,
+ is_peft_available,
+ is_pyctcdecode_available,
+ is_torch_available,
+ logging,
+)
+from ..video_processing_utils import BaseVideoProcessor
+from .any_to_any import AnyToAnyPipeline
+from .audio_classification import AudioClassificationPipeline
+from .automatic_speech_recognition import AutomaticSpeechRecognitionPipeline
+from .base import (
+ ArgumentHandler,
+ CsvPipelineDataFormat,
+ JsonPipelineDataFormat,
+ PipedPipelineDataFormat,
+ Pipeline,
+ PipelineDataFormat,
+ PipelineException,
+ PipelineRegistry,
+ get_default_model_and_revision,
+ load_model,
+)
+from .depth_estimation import DepthEstimationPipeline
+from .document_question_answering import DocumentQuestionAnsweringPipeline
+from .feature_extraction import FeatureExtractionPipeline
+from .fill_mask import FillMaskPipeline
+from .image_classification import ImageClassificationPipeline
+from .image_feature_extraction import ImageFeatureExtractionPipeline
+from .image_segmentation import ImageSegmentationPipeline
+from .image_text_to_text import ImageTextToTextPipeline
+from .keypoint_matching import KeypointMatchingPipeline
+from .mask_generation import MaskGenerationPipeline
+from .object_detection import ObjectDetectionPipeline
+from .table_question_answering import TableQuestionAnsweringArgumentHandler, TableQuestionAnsweringPipeline
+from .text_classification import TextClassificationPipeline
+from .text_generation import TextGenerationPipeline
+from .text_to_audio import TextToAudioPipeline
+from .token_classification import (
+ AggregationStrategy,
+ NerPipeline,
+ TokenClassificationArgumentHandler,
+ TokenClassificationPipeline,
+)
+from .video_classification import VideoClassificationPipeline
+from .zero_shot_audio_classification import ZeroShotAudioClassificationPipeline
+from .zero_shot_classification import ZeroShotClassificationArgumentHandler, ZeroShotClassificationPipeline
+from .zero_shot_image_classification import ZeroShotImageClassificationPipeline
+from .zero_shot_object_detection import ZeroShotObjectDetectionPipeline
+
+
+if is_torch_available():
+ import torch
+
+ from ..models.auto.modeling_auto import (
+ AutoModel,
+ AutoModelForAudioClassification,
+ AutoModelForCausalLM,
+ AutoModelForCTC,
+ AutoModelForDocumentQuestionAnswering,
+ AutoModelForImageClassification,
+ AutoModelForImageSegmentation,
+ AutoModelForImageTextToText,
+ AutoModelForKeypointMatching,
+ AutoModelForMaskedLM,
+ AutoModelForMaskGeneration,
+ AutoModelForMultimodalLM,
+ AutoModelForObjectDetection,
+ AutoModelForQuestionAnswering,
+ AutoModelForSemanticSegmentation,
+ AutoModelForSeq2SeqLM,
+ AutoModelForSequenceClassification,
+ AutoModelForSpeechSeq2Seq,
+ AutoModelForTableQuestionAnswering,
+ AutoModelForTDT,
+ AutoModelForTextToSpectrogram,
+ AutoModelForTextToWaveform,
+ AutoModelForTokenClassification,
+ AutoModelForVideoClassification,
+ AutoModelForVisualQuestionAnswering,
+ AutoModelForZeroShotImageClassification,
+ AutoModelForZeroShotObjectDetection,
+ )
+
+
+if TYPE_CHECKING:
+ from ..modeling_utils import PreTrainedModel
+ from ..tokenization_utils_tokenizers import PreTrainedTokenizerFast
+
+
+logger = logging.get_logger(__name__)
+
+
+# Register all the supported tasks here
+TASK_ALIASES = {
+ "sentiment-analysis": "text-classification",
+ "ner": "token-classification",
+ "text-to-speech": "text-to-audio",
+}
+SUPPORTED_TASKS = {
+ "audio-classification": {
+ "impl": AudioClassificationPipeline,
+ "pt": (AutoModelForAudioClassification,) if is_torch_available() else (),
+ "default": {"model": ("superb/wav2vec2-base-superb-ks", "372e048")},
+ "type": "audio",
+ },
+ "automatic-speech-recognition": {
+ "impl": AutomaticSpeechRecognitionPipeline,
+ "pt": (AutoModelForCTC, AutoModelForTDT, AutoModelForSpeechSeq2Seq) if is_torch_available() else (),
+ "default": {"model": ("facebook/wav2vec2-base-960h", "22aad52")},
+ "type": "multimodal",
+ },
+ "text-to-audio": {
+ "impl": TextToAudioPipeline,
+ "pt": (AutoModelForTextToWaveform, AutoModelForTextToSpectrogram) if is_torch_available() else (),
+ "default": {"model": ("suno/bark-small", "1dbd7a1")},
+ "type": "text",
+ },
+ "feature-extraction": {
+ "impl": FeatureExtractionPipeline,
+ "pt": (AutoModel,) if is_torch_available() else (),
+ "default": {"model": ("distilbert/distilbert-base-cased", "6ea8117")},
+ "type": "text",
+ },
+ "text-classification": {
+ "impl": TextClassificationPipeline,
+ "pt": (AutoModelForSequenceClassification,) if is_torch_available() else (),
+ "default": {"model": ("distilbert/distilbert-base-uncased-finetuned-sst-2-english", "714eb0f")},
+ "type": "text",
+ },
+ "token-classification": {
+ "impl": TokenClassificationPipeline,
+ "pt": (AutoModelForTokenClassification,) if is_torch_available() else (),
+ "default": {"model": ("dbmdz/bert-large-cased-finetuned-conll03-english", "4c53496")},
+ "type": "text",
+ },
+ "table-question-answering": {
+ "impl": TableQuestionAnsweringPipeline,
+ "pt": (AutoModelForTableQuestionAnswering,) if is_torch_available() else (),
+ "default": {"model": ("google/tapas-base-finetuned-wtq", "e3dde19")},
+ "type": "text",
+ },
+ "document-question-answering": {
+ "impl": DocumentQuestionAnsweringPipeline,
+ "pt": (AutoModelForDocumentQuestionAnswering,) if is_torch_available() else (),
+ "default": {"model": ("impira/layoutlm-document-qa", "beed3c4")},
+ "type": "multimodal",
+ },
+ "fill-mask": {
+ "impl": FillMaskPipeline,
+ "pt": (AutoModelForMaskedLM,) if is_torch_available() else (),
+ "default": {"model": ("distilbert/distilroberta-base", "fb53ab8")},
+ "type": "text",
+ },
+ "text-generation": {
+ "impl": TextGenerationPipeline,
+ "pt": (AutoModelForCausalLM,) if is_torch_available() else (),
+ "default": {"model": ("HuggingFaceTB/SmolLM3-3B", "a07cc9a")},
+ "type": "text",
+ },
+ "zero-shot-classification": {
+ "impl": ZeroShotClassificationPipeline,
+ "pt": (AutoModelForSequenceClassification,) if is_torch_available() else (),
+ "default": {
+ "model": ("facebook/bart-large-mnli", "d7645e1"),
+ "config": ("facebook/bart-large-mnli", "d7645e1"),
+ },
+ "type": "text",
+ },
+ "zero-shot-image-classification": {
+ "impl": ZeroShotImageClassificationPipeline,
+ "pt": (AutoModelForZeroShotImageClassification,) if is_torch_available() else (),
+ "default": {"model": ("openai/clip-vit-base-patch32", "3d74acf")},
+ "type": "multimodal",
+ },
+ "zero-shot-audio-classification": {
+ "impl": ZeroShotAudioClassificationPipeline,
+ "pt": (AutoModel,) if is_torch_available() else (),
+ "default": {"model": ("laion/clap-htsat-fused", "cca9e28")},
+ "type": "multimodal",
+ },
+ "image-classification": {
+ "impl": ImageClassificationPipeline,
+ "pt": (AutoModelForImageClassification,) if is_torch_available() else (),
+ "default": {"model": ("google/vit-base-patch16-224", "3f49326")},
+ "type": "image",
+ },
+ "image-feature-extraction": {
+ "impl": ImageFeatureExtractionPipeline,
+ "pt": (AutoModel,) if is_torch_available() else (),
+ "default": {"model": ("google/vit-base-patch16-224", "3f49326")},
+ "type": "image",
+ },
+ "image-segmentation": {
+ "impl": ImageSegmentationPipeline,
+ "pt": (AutoModelForImageSegmentation, AutoModelForSemanticSegmentation) if is_torch_available() else (),
+ "default": {"model": ("facebook/detr-resnet-50-panoptic", "d53b52a")},
+ "type": "multimodal",
+ },
+ "image-text-to-text": {
+ "impl": ImageTextToTextPipeline,
+ "pt": (AutoModelForImageTextToText,) if is_torch_available() else (),
+ "default": {"model": ("Qwen/Qwen3-VL-2B-Instruct", "8964489")},
+ "type": "multimodal",
+ },
+ "object-detection": {
+ "impl": ObjectDetectionPipeline,
+ "pt": (AutoModelForObjectDetection,) if is_torch_available() else (),
+ "default": {"model": ("facebook/detr-resnet-50", "1d5f47b")},
+ "type": "multimodal",
+ },
+ "zero-shot-object-detection": {
+ "impl": ZeroShotObjectDetectionPipeline,
+ "pt": (AutoModelForZeroShotObjectDetection,) if is_torch_available() else (),
+ "default": {"model": ("google/owlvit-base-patch32", "cbc355f")},
+ "type": "multimodal",
+ },
+ "depth-estimation": {
+ "impl": DepthEstimationPipeline,
+ "pt": (AutoModelForDepthEstimation,) if is_torch_available() else (),
+ "default": {"model": ("Intel/dpt-large", "bc15f29")},
+ "type": "image",
+ },
+ "video-classification": {
+ "impl": VideoClassificationPipeline,
+ "pt": (AutoModelForVideoClassification,) if is_torch_available() else (),
+ "default": {"model": ("MCG-NJU/videomae-base-finetuned-kinetics", "488eb9a")},
+ "type": "video",
+ },
+ "mask-generation": {
+ "impl": MaskGenerationPipeline,
+ "pt": (AutoModelForMaskGeneration,) if is_torch_available() else (),
+ "default": {"model": ("facebook/sam-vit-huge", "87aecf0")},
+ "type": "multimodal",
+ },
+ "keypoint-matching": {
+ "impl": KeypointMatchingPipeline,
+ "pt": (AutoModelForKeypointMatching,) if is_torch_available() else (),
+ "default": {"model": ("magic-leap-community/superglue_outdoor", "f4041f8")},
+ "type": "image",
+ },
+ "any-to-any": {
+ "impl": AnyToAnyPipeline,
+ "tf": (),
+ "pt": (AutoModelForMultimodalLM,) if is_torch_available() else (),
+ "default": {
+ "model": {
+ "pt": ("google/gemma-3n-E4B-it", "c1221e9"),
+ }
+ },
+ "type": "multimodal",
+ },
+}
+
+PIPELINE_REGISTRY = PipelineRegistry(supported_tasks=SUPPORTED_TASKS, task_aliases=TASK_ALIASES)
+
+
+def get_supported_tasks() -> list[str]:
+ """
+ Returns a list of supported task strings.
+ """
+ return PIPELINE_REGISTRY.get_supported_tasks()
+
+
+def get_task(model: str, token: str | None = None, **deprecated_kwargs) -> str:
+ if is_offline_mode():
+ raise RuntimeError("You cannot infer task automatically within `pipeline` when using offline mode")
+ try:
+ info = hf_api().model_info(model, token=token)
+ except Exception as e:
+ raise RuntimeError(f"Instantiating a pipeline without a task set raised an error: {e}")
+ if not info.pipeline_tag:
+ raise RuntimeError(
+ f"The model {model} does not seem to have a correct `pipeline_tag` set to infer the task automatically"
+ )
+ if getattr(info, "library_name", "transformers") not in {"transformers", "timm"}:
+ raise RuntimeError(f"This model is meant to be used with {info.library_name} not with transformers")
+ task = info.pipeline_tag
+ return task
+
+
+def check_task(task: str) -> tuple[str, dict, Any]:
+ """
+ Checks an incoming task string, to validate it's correct and return the default Pipeline and Model classes, and
+ default models if they exist.
+
+ Args:
+ task (`str`):
+ The task defining which pipeline will be returned. Currently accepted tasks are:
+ - `"audio-classification"`
+ - `"automatic-speech-recognition"`
+ - `"conversational"`
+ - `"depth-estimation"`
+ - `"document-question-answering"`
+ - `"feature-extraction"`
+ - `"fill-mask"`
+ - `"image-classification"`
+ - `"image-feature-extraction"`
+ - `"image-segmentation"`
+ - `"keypoint-matching"`
+ - `"object-detection"`
+ - `"table-question-answering"`
+ - `"text-classification"` (alias `"sentiment-analysis"` available)
+ - `"text-generation"`
+ - `"text-to-audio"` (alias `"text-to-speech"` available)
+ - `"token-classification"` (alias `"ner"` available)
+ - `"video-classification"`
+ - `"zero-shot-classification"`
+ - `"zero-shot-image-classification"`
+ - `"zero-shot-object-detection"`
+
+ Returns:
+ (normalized_task: `str`, task_defaults: `dict`, task_options: (`tuple`, None)) The normalized task name
+ (removed alias and options).
+
+
+ """
+ return PIPELINE_REGISTRY.check_task(task)
+
+
+def clean_custom_task(task_info):
+ import transformers
+
+ if "impl" not in task_info:
+ raise RuntimeError("This model introduces a custom pipeline without specifying its implementation.")
+ pt_class_names = task_info.get("pt", ())
+ if isinstance(pt_class_names, str):
+ pt_class_names = [pt_class_names]
+ task_info["pt"] = tuple(getattr(transformers, c) for c in pt_class_names)
+ return task_info, None
+
+
+#
+# fmt: off
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# The part of the file below was automatically generated from the code.
+# Do NOT edit this part of the file manually as any edits will be overwritten by the generation
+# of the file. If any change should be done, please apply the changes to the `pipeline` function
+# below and run `python utils/check_pipeline_typing.py --fix_and_overwrite` to update the file.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+
+from typing import Literal, overload
+
+
+@overload
+def pipeline(task: Literal[None], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> Pipeline: ...
+@overload
+def pipeline(task: Literal["any-to-any"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> AnyToAnyPipeline: ...
+@overload
+def pipeline(task: Literal["audio-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> AudioClassificationPipeline: ...
+@overload
+def pipeline(task: Literal["automatic-speech-recognition"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> AutomaticSpeechRecognitionPipeline: ...
+@overload
+def pipeline(task: Literal["depth-estimation"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> DepthEstimationPipeline: ...
+@overload
+def pipeline(task: Literal["document-question-answering"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> DocumentQuestionAnsweringPipeline: ...
+@overload
+def pipeline(task: Literal["feature-extraction"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> FeatureExtractionPipeline: ...
+@overload
+def pipeline(task: Literal["fill-mask"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> FillMaskPipeline: ...
+@overload
+def pipeline(task: Literal["image-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ImageClassificationPipeline: ...
+@overload
+def pipeline(task: Literal["image-feature-extraction"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ImageFeatureExtractionPipeline: ...
+@overload
+def pipeline(task: Literal["image-segmentation"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ImageSegmentationPipeline: ...
+@overload
+def pipeline(task: Literal["image-text-to-text"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ImageTextToTextPipeline: ...
+@overload
+def pipeline(task: Literal["keypoint-matching"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> KeypointMatchingPipeline: ...
+@overload
+def pipeline(task: Literal["mask-generation"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> MaskGenerationPipeline: ...
+@overload
+def pipeline(task: Literal["object-detection"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ObjectDetectionPipeline: ...
+@overload
+def pipeline(task: Literal["table-question-answering"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> TableQuestionAnsweringPipeline: ...
+@overload
+def pipeline(task: Literal["text-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> TextClassificationPipeline: ...
+@overload
+def pipeline(task: Literal["text-generation"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> TextGenerationPipeline: ...
+@overload
+def pipeline(task: Literal["text-to-audio"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> TextToAudioPipeline: ...
+@overload
+def pipeline(task: Literal["token-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> TokenClassificationPipeline: ...
+@overload
+def pipeline(task: Literal["video-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> VideoClassificationPipeline: ...
+@overload
+def pipeline(task: Literal["zero-shot-audio-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ZeroShotAudioClassificationPipeline: ...
+@overload
+def pipeline(task: Literal["zero-shot-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ZeroShotClassificationPipeline: ...
+@overload
+def pipeline(task: Literal["zero-shot-image-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ZeroShotImageClassificationPipeline: ...
+@overload
+def pipeline(task: Literal["zero-shot-object-detection"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ZeroShotObjectDetectionPipeline: ...
+
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# The part of the file above was automatically generated from the code.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# fmt: on
+#
+
+
+def _load_pipeline_component(load_flag, component, loader):
+ """Load an optional pipeline component, preserving the original soft-failure behavior."""
+ if not (load_flag or load_flag is None):
+ return component
+
+ try:
+ return loader(component)
+ except Exception:
+ if load_flag:
+ raise
+ return None
+
+
+def _infer_pipeline_component(
+ component,
+ model_name,
+ config,
+ error_message,
+ fallback_component=None,
+):
+ """Infer a component identifier from explicit input, then model/config fallbacks."""
+ if component is not None:
+ return component
+ if isinstance(model_name, str):
+ return model_name
+ if isinstance(config, str):
+ return config
+ if fallback_component is not None:
+ return fallback_component
+ raise Exception(error_message)
+
+
+def _get_tokenizer_loading_kwargs(tokenizer, use_fast, model_kwargs):
+ """Normalize tokenizer tuple/string inputs into `AutoTokenizer.from_pretrained` kwargs."""
+ if isinstance(tokenizer, tuple):
+ tokenizer_identifier = tokenizer[0]
+ tokenizer_kwargs = tokenizer[1].copy()
+ tokenizer_use_fast = tokenizer_kwargs.pop("use_fast", use_fast)
+ else:
+ tokenizer_identifier = tokenizer
+ tokenizer_kwargs = model_kwargs.copy()
+ tokenizer_kwargs.pop("torch_dtype", None)
+ tokenizer_kwargs.pop("dtype", None)
+ tokenizer_use_fast = use_fast
+
+ return tokenizer_identifier, tokenizer_kwargs, tokenizer_use_fast
+
+
+def _resolve_tokenizer(tokenizer, load_tokenizer, use_fast, model_name, config, task, hub_kwargs, model_kwargs):
+ """Resolve and optionally load the tokenizer required by the pipeline class."""
+
+ def load(tokenizer):
+ tokenizer = _infer_pipeline_component(
+ tokenizer,
+ model_name,
+ config,
+ "Impossible to guess which tokenizer to use. "
+ "Please provide a PreTrainedTokenizer class or a path/identifier to a pretrained tokenizer.",
+ )
+
+ if not isinstance(tokenizer, (str, tuple)):
+ return tokenizer
+
+ tokenizer_identifier, tokenizer_kwargs, tokenizer_use_fast = _get_tokenizer_loading_kwargs(
+ tokenizer, use_fast, model_kwargs
+ )
+ return AutoTokenizer.from_pretrained(
+ tokenizer_identifier,
+ use_fast=tokenizer_use_fast,
+ _from_pipeline=task,
+ **hub_kwargs,
+ **tokenizer_kwargs,
+ )
+
+ return _load_pipeline_component(load_tokenizer, tokenizer, load)
+
+
+def _resolve_image_processor(
+ image_processor,
+ feature_extractor,
+ load_image_processor,
+ model_name,
+ config,
+ task,
+ hub_kwargs,
+ model_kwargs,
+):
+ """Resolve and optionally load the image processor for vision-capable pipelines."""
+
+ def load(image_processor):
+ image_processor = _infer_pipeline_component(
+ image_processor,
+ model_name,
+ config,
+ "Impossible to guess which image processor to use. "
+ "Please provide a PreTrainedImageProcessor class or a path/identifier to a pretrained image processor.",
+ fallback_component=feature_extractor if isinstance(feature_extractor, BaseImageProcessor) else None,
+ )
+
+ if not isinstance(image_processor, (str, tuple)):
+ return image_processor
+
+ return AutoImageProcessor.from_pretrained(image_processor, _from_pipeline=task, **hub_kwargs, **model_kwargs)
+
+ return _load_pipeline_component(load_image_processor, image_processor, load)
+
+
+def _resolve_video_processor(
+ video_processor,
+ load_video_processor,
+ model_name,
+ config,
+ task,
+ hub_kwargs,
+ model_kwargs,
+):
+ def load(video_processor):
+ video_processor = _infer_pipeline_component(
+ video_processor,
+ model_name,
+ config,
+ "Impossible to guess which video processor to use. "
+ "Please provide a BaseVideoProcessor class or a path/identifier to a pretrained video processor.",
+ )
+
+ if not isinstance(video_processor, str):
+ return video_processor
+
+ return AutoVideoProcessor.from_pretrained(video_processor, _from_pipeline=task, **hub_kwargs, **model_kwargs)
+
+ return _load_pipeline_component(load_video_processor, video_processor, load)
+
+
+def _maybe_load_ctc_decoder(model_name, hub_kwargs, kwargs, pretrained_model_name_or_path):
+ """Attach a pyctcdecode decoder when the loaded feature extractor declares an LM-backed processor."""
+ config_dict, _ = FeatureExtractionMixin.get_feature_extractor_dict(
+ pretrained_model_name_or_path or model_name,
+ **hub_kwargs,
+ )
+ processor_class = config_dict.get("processor_class", None)
+
+ if processor_class is None or not processor_class.endswith("WithLM") or not isinstance(model_name, str):
+ return
+
+ try:
+ import kenlm # to trigger `ImportError` if not installed
+ from pyctcdecode import BeamSearchDecoderCTC
+
+ if os.path.isdir(model_name) or os.path.isfile(model_name):
+ decoder = BeamSearchDecoderCTC.load_from_dir(model_name)
+ else:
+ language_model_glob = os.path.join(BeamSearchDecoderCTC._LANGUAGE_MODEL_SERIALIZED_DIRECTORY, "*")
+ alphabet_filename = BeamSearchDecoderCTC._ALPHABET_SERIALIZED_FILENAME
+ allow_patterns = [language_model_glob, alphabet_filename]
+ decoder = BeamSearchDecoderCTC.load_from_hf_hub(model_name, allow_patterns=allow_patterns)
+
+ kwargs["decoder"] = decoder
+ except ImportError as error:
+ logger.warning(f"Could not load the `decoder` for {model_name}. Defaulting to raw CTC. Error: {error}")
+ if not is_kenlm_available():
+ logger.warning("Try to install `kenlm`: `pip install kenlm")
+
+ if not is_pyctcdecode_available():
+ logger.warning("Try to install `pyctcdecode`: `pip install pyctcdecode")
+
+
+def _resolve_feature_extractor(
+ feature_extractor,
+ load_feature_extractor,
+ model_name,
+ config,
+ task,
+ hub_kwargs,
+ model_kwargs,
+ kwargs,
+ pretrained_model_name_or_path,
+):
+ """Resolve and optionally load the feature extractor, including CTC decoder side-loading."""
+
+ def load(feature_extractor):
+ feature_extractor = _infer_pipeline_component(
+ feature_extractor,
+ model_name,
+ config,
+ "Impossible to guess which feature extractor to use. "
+ "Please provide a PreTrainedFeatureExtractor class or a path/identifier to a pretrained feature extractor.",
+ )
+
+ if not isinstance(feature_extractor, (str, tuple)):
+ return feature_extractor
+
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
+ feature_extractor, _from_pipeline=task, **hub_kwargs, **model_kwargs
+ )
+ _maybe_load_ctc_decoder(model_name, hub_kwargs, kwargs, pretrained_model_name_or_path)
+ return feature_extractor
+
+ return _load_pipeline_component(load_feature_extractor, feature_extractor, load)
+
+
+def _resolve_processor(processor, load_processor, model_name, config, task, hub_kwargs, model_kwargs):
+ """Resolve and optionally load a multimodal processor."""
+
+ def load(processor):
+ processor = _infer_pipeline_component(
+ processor,
+ model_name,
+ config,
+ "Impossible to guess which processor to use. "
+ "Please provide a processor instance or a path/identifier to a processor.",
+ )
+
+ if not isinstance(processor, (str, tuple)):
+ return processor
+
+ processor = AutoProcessor.from_pretrained(processor, _from_pipeline=task, **hub_kwargs, **model_kwargs)
+ if not isinstance(processor, ProcessorMixin):
+ raise TypeError(
+ "Processor was loaded, but it is not an instance of `ProcessorMixin`. "
+ f"Got type `{type(processor)}` instead. Please check that you specified "
+ "correct pipeline task for the model and model has processor implemented and saved."
+ )
+ return processor
+
+ return _load_pipeline_component(load_processor, processor, load)
+
+
+def pipeline(
+ task: str | None = None,
+ model: str | PreTrainedModel | None = None,
+ config: str | PreTrainedConfig | None = None,
+ tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None,
+ feature_extractor: str | FeatureExtractionMixin | None = None,
+ image_processor: str | BaseImageProcessor | None = None,
+ video_processor: str | BaseVideoProcessor | None = None,
+ processor: str | ProcessorMixin | None = None,
+ revision: str | None = None,
+ use_fast: bool = True,
+ token: str | bool | None = None,
+ device: int | str | torch.device | None = None,
+ device_map: str | dict[str, int | str] | None = None,
+ dtype: str | torch.dtype | None = "auto",
+ trust_remote_code: bool | None = None,
+ model_kwargs: dict[str, Any] | None = None,
+ pipeline_class: Any | None = None,
+ **kwargs: Any,
+) -> Pipeline:
+ """
+ Utility factory method to build a [`Pipeline`].
+
+ A pipeline consists of:
+
+ - One or more components for pre-processing model inputs, such as a [tokenizer](tokenizer),
+ [image_processor](image_processor), [feature_extractor](feature_extractor), or [processor](processors).
+ - A [model](model) that generates predictions from the inputs.
+ - Optional post-processing steps to refine the model's output, which can also be handled by processors.
+
+
+ While there are such optional arguments as `tokenizer`, `feature_extractor`, `image_processor`, and `processor`,
+ they shouldn't be specified all at once. If these components are not provided, `pipeline` will try to load
+ required ones automatically. In case you want to provide these components explicitly, please refer to a
+ specific pipeline in order to get more details regarding what components are required.
+
+
+ Args:
+ task (`str`):
+ The task defining which pipeline will be returned. Currently accepted tasks are:
+
+ - `"audio-classification"`: will return a [`AudioClassificationPipeline`].
+ - `"automatic-speech-recognition"`: will return a [`AutomaticSpeechRecognitionPipeline`].
+ - `"depth-estimation"`: will return a [`DepthEstimationPipeline`].
+ - `"document-question-answering"`: will return a [`DocumentQuestionAnsweringPipeline`].
+ - `"feature-extraction"`: will return a [`FeatureExtractionPipeline`].
+ - `"fill-mask"`: will return a [`FillMaskPipeline`]:.
+ - `"image-classification"`: will return a [`ImageClassificationPipeline`].
+ - `"image-feature-extraction"`: will return an [`ImageFeatureExtractionPipeline`].
+ - `"image-segmentation"`: will return a [`ImageSegmentationPipeline`].
+ - `"image-text-to-text"`: will return a [`ImageTextToTextPipeline`].
+ - `"keypoint-matching"`: will return a [`KeypointMatchingPipeline`].
+ - `"mask-generation"`: will return a [`MaskGenerationPipeline`].
+ - `"object-detection"`: will return a [`ObjectDetectionPipeline`].
+ - `"table-question-answering"`: will return a [`TableQuestionAnsweringPipeline`].
+ - `"text-classification"` (alias `"sentiment-analysis"` available): will return a
+ [`TextClassificationPipeline`].
+ - `"text-generation"`: will return a [`TextGenerationPipeline`]:.
+ - `"text-to-audio"` (alias `"text-to-speech"` available): will return a [`TextToAudioPipeline`]:.
+ - `"token-classification"` (alias `"ner"` available): will return a [`TokenClassificationPipeline`].
+ - `"video-classification"`: will return a [`VideoClassificationPipeline`].
+ - `"zero-shot-classification"`: will return a [`ZeroShotClassificationPipeline`].
+ - `"zero-shot-image-classification"`: will return a [`ZeroShotImageClassificationPipeline`].
+ - `"zero-shot-audio-classification"`: will return a [`ZeroShotAudioClassificationPipeline`].
+ - `"zero-shot-object-detection"`: will return a [`ZeroShotObjectDetectionPipeline`].
+
+ model (`str` or [`PreTrainedModel`], *optional*):
+ The model that will be used by the pipeline to make predictions. This can be a model identifier or an
+ actual instance of a pretrained model inheriting from [`PreTrainedModel`].
+
+ If not provided, the default for the `task` will be loaded.
+ config (`str` or [`PreTrainedConfig`], *optional*):
+ The configuration that will be used by the pipeline to instantiate the model. This can be a model
+ identifier or an actual pretrained model configuration inheriting from [`PreTrainedConfig`].
+
+ If not provided, the default configuration file for the requested model will be used. That means that if
+ `model` is given, its default configuration will be used. However, if `model` is not supplied, this
+ `task`'s default model's config is used instead.
+ tokenizer (`str` or [`PreTrainedTokenizer`], *optional*):
+ The tokenizer that will be used by the pipeline to encode data for the model. This can be a model
+ identifier or an actual pretrained tokenizer inheriting from [`PreTrainedTokenizer`].
+
+ If not provided, the default tokenizer for the given `model` will be loaded (if it is a string). If `model`
+ is not specified or not a string, then the default tokenizer for `config` is loaded (if it is a string).
+ However, if `config` is also not given or not a string, then the default tokenizer for the given `task`
+ will be loaded.
+ feature_extractor (`str` or [`FeatureExtractionMixin`], *optional*):
+ The feature extractor that will be used by the pipeline to encode data for the model. This can be a model
+ identifier or an actual pretrained feature extractor inheriting from [`FeatureExtractionMixin`].
+
+ Feature extractors are used for non-NLP models, such as Speech or Vision models as well as multi-modal
+ models. Multi-modal models will also require a tokenizer to be passed.
+
+ If not provided, the default feature extractor for the given `model` will be loaded (if it is a string). If
+ `model` is not specified or not a string, then the default feature extractor for `config` is loaded (if it
+ is a string). However, if `config` is also not given or not a string, then the default feature extractor
+ for the given `task` will be loaded.
+ image_processor (`str` or [`BaseImageProcessor`], *optional*):
+ The image processor that will be used by the pipeline to preprocess images for the model. This can be a
+ model identifier or an actual image processor inheriting from [`BaseImageProcessor`].
+
+ Image processors are used for Vision models and multi-modal models that require image inputs. Multi-modal
+ models will also require a tokenizer to be passed.
+
+ If not provided, the default image processor for the given `model` will be loaded (if it is a string). If
+ `model` is not specified or not a string, then the default image processor for `config` is loaded (if it is
+ a string).
+ processor (`str` or [`ProcessorMixin`], *optional*):
+ The processor that will be used by the pipeline to preprocess data for the model. This can be a model
+ identifier or an actual processor inheriting from [`ProcessorMixin`].
+
+ Processors are used for multi-modal models that require multi-modal inputs, for example, a model that
+ requires both text and image inputs.
+
+ If not provided, the default processor for the given `model` will be loaded (if it is a string). If `model`
+ is not specified or not a string, then the default processor for `config` is loaded (if it is a string).
+ revision (`str`, *optional*, defaults to `"main"`):
+ When passing a task name or a string model identifier: The specific model version to use. It can be a
+ branch name, a tag name, or a commit id, since we use a git-based system for storing models and other
+ artifacts on huggingface.co, so `revision` can be any identifier allowed by git.
+ use_fast (`bool`, *optional*, defaults to `True`):
+ Whether or not to use a Fast tokenizer if possible (a [`PreTrainedTokenizerFast`]).
+ token (`str` or *bool*, *optional*):
+ The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
+ when running `hf auth login`.
+ device (`int` or `str` or `torch.device`):
+ Defines the device (*e.g.*, `"cpu"`, `"cuda:1"`, `"mps"`, or a GPU ordinal rank like `1`) on which this
+ pipeline will be allocated.
+ device_map (`str` or `dict[str, Union[int, str, torch.device]`, *optional*):
+ Sent directly as `model_kwargs` (just a simpler shortcut). When `accelerate` library is present, set
+ `device_map="auto"` to compute the most optimized `device_map` automatically (see
+ [here](https://huggingface.co/docs/accelerate/main/en/package_reference/big_modeling#accelerate.cpu_offload)
+ for more information).
+
+
+
+ Do not use `device_map` AND `device` at the same time as they will conflict
+
+
+
+ dtype (`str` or `torch.dtype`, *optional*):
+ Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model
+ (`torch.float16`, `torch.bfloat16`, ... or `"auto"`).
+ trust_remote_code (`bool`, *optional*, defaults to `False`):
+ Whether or not to allow for custom code defined on the Hub in their own modeling, configuration,
+ tokenization or even pipeline files. This option should only be set to `True` for repositories you trust
+ and in which you have read the code, as it will execute code present on the Hub on your local machine.
+ model_kwargs (`dict[str, Any]`, *optional*):
+ Additional dictionary of keyword arguments passed along to the model's `from_pretrained(...,
+ **model_kwargs)` function.
+ kwargs (`dict[str, Any]`, *optional*):
+ Additional keyword arguments passed along to the specific pipeline init (see the documentation for the
+ corresponding pipeline class for possible values).
+
+ Returns:
+ [`Pipeline`]: A suitable pipeline for the task.
+
+ Examples:
+
+ ```python
+ >>> from transformers import pipeline, AutoModelForTokenClassification, AutoTokenizer
+
+ >>> # Sentiment analysis pipeline
+ >>> analyzer = pipeline("sentiment-analysis")
+
+ >>> # Named entity recognition pipeline, passing in a specific model and tokenizer
+ >>> model = AutoModelForTokenClassification.from_pretrained("dbmdz/bert-large-cased-finetuned-conll03-english")
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased")
+ >>> recognizer = pipeline("ner", model=model, tokenizer=tokenizer)
+ ```"""
+ if model_kwargs is None:
+ model_kwargs = {}
+
+ code_revision = kwargs.pop("code_revision", None)
+ commit_hash = kwargs.pop("_commit_hash", None)
+ local_files_only = kwargs.get("local_files_only", False)
+
+ hub_kwargs = {
+ "revision": revision,
+ "token": token,
+ "trust_remote_code": trust_remote_code,
+ "_commit_hash": commit_hash,
+ "local_files_only": local_files_only,
+ }
+
+ if task is None and model is None:
+ raise RuntimeError(
+ "Impossible to instantiate a pipeline without either a task or a model "
+ "being specified. "
+ "Please provide a task class or a model"
+ )
+
+ if model is None and tokenizer is not None:
+ raise RuntimeError(
+ "Impossible to instantiate a pipeline with tokenizer specified but not the model as the provided tokenizer"
+ " may not be compatible with the default model. Please provide a PreTrainedModel class or a"
+ " path/identifier to a pretrained model when providing tokenizer."
+ )
+ if model is None and feature_extractor is not None:
+ raise RuntimeError(
+ "Impossible to instantiate a pipeline with feature_extractor specified but not the model as the provided"
+ " feature_extractor may not be compatible with the default model. Please provide a PreTrainedModel class"
+ " or a path/identifier to a pretrained model when providing feature_extractor."
+ )
+ if isinstance(model, Path):
+ model = str(model)
+
+ pretrained_model_name_or_path = None
+ if commit_hash is None:
+ if isinstance(config, str):
+ pretrained_model_name_or_path = config
+ elif config is None and isinstance(model, str):
+ pretrained_model_name_or_path = model
+
+ if not isinstance(config, PreTrainedConfig) and pretrained_model_name_or_path is not None:
+ # We make a call to the config file first (which may be absent) to get the commit hash as soon as possible
+ resolved_config_file = cached_file(
+ pretrained_model_name_or_path,
+ CONFIG_NAME,
+ _raise_exceptions_for_gated_repo=False,
+ _raise_exceptions_for_missing_entries=False,
+ _raise_exceptions_for_connection_errors=False,
+ cache_dir=model_kwargs.get("cache_dir"),
+ **hub_kwargs,
+ )
+ hub_kwargs["_commit_hash"] = extract_commit_hash(resolved_config_file, commit_hash)
+ else:
+ hub_kwargs["_commit_hash"] = getattr(config, "_commit_hash", None)
+
+ # Config is the primordial information item.
+ # Instantiate config if needed
+ adapter_path = None
+ if isinstance(config, str):
+ config = AutoConfig.from_pretrained(
+ config, _from_pipeline=task, code_revision=code_revision, **hub_kwargs, **model_kwargs
+ )
+ hub_kwargs["_commit_hash"] = config._commit_hash
+ elif config is None and isinstance(model, str):
+ # Check for an adapter file in the model path if PEFT is available
+ if is_peft_available():
+ # `find_adapter_config_file` doesn't accept `trust_remote_code`
+ _hub_kwargs = {k: v for k, v in hub_kwargs.items() if k != "trust_remote_code"}
+ maybe_adapter_path = find_adapter_config_file(
+ model,
+ token=hub_kwargs["token"],
+ revision=hub_kwargs["revision"],
+ _commit_hash=hub_kwargs["_commit_hash"],
+ )
+
+ if maybe_adapter_path is not None:
+ with open(maybe_adapter_path, "r", encoding="utf-8") as f:
+ adapter_config = json.load(f)
+ adapter_path = model
+ # Only override the model name/path if the current value doesn't point to a
+ # complete model with an embedded adapter so that local models with embedded
+ # adapters will load from the local base model rather than pull the base
+ # model named in the adapter's config from the hub.
+ if not os.path.exists(model) or not os.path.exists(os.path.join(model, CONFIG_NAME)):
+ model = adapter_config["base_model_name_or_path"]
+
+ config = AutoConfig.from_pretrained(
+ model, _from_pipeline=task, code_revision=code_revision, **hub_kwargs, **model_kwargs
+ )
+ hub_kwargs["_commit_hash"] = config._commit_hash
+
+ custom_tasks = {}
+ if config is not None and len(getattr(config, "custom_pipelines", {})) > 0:
+ custom_tasks = config.custom_pipelines
+ if task is None and trust_remote_code is not False:
+ if len(custom_tasks) == 1:
+ task = list(custom_tasks.keys())[0]
+ else:
+ raise RuntimeError(
+ "We can't infer the task automatically for this model as there are multiple tasks available. Pick "
+ f"one in {', '.join(custom_tasks.keys())}"
+ )
+
+ if task is None and model is not None:
+ if not isinstance(model, str):
+ raise RuntimeError(
+ "Inferring the task automatically requires to check the hub with a model_id defined as a `str`. "
+ f"{model} is not a valid model_id."
+ )
+ task = get_task(model, token)
+
+ # Retrieve the task
+ if task in custom_tasks:
+ targeted_task, task_options = clean_custom_task(custom_tasks[task])
+ if pipeline_class is None:
+ if not trust_remote_code:
+ raise ValueError(
+ "Loading this pipeline requires you to execute the code in the pipeline file in that"
+ " repo on your local machine. Make sure you have read the code there to avoid malicious use, then"
+ " set the option `trust_remote_code=True` to remove this error."
+ )
+ class_ref = targeted_task["impl"]
+ pipeline_class = get_class_from_dynamic_module(
+ class_ref,
+ model,
+ code_revision=code_revision,
+ **hub_kwargs,
+ )
+ else:
+ normalized_task, targeted_task, task_options = check_task(task)
+ if pipeline_class is None:
+ pipeline_class = targeted_task["impl"]
+
+ # Use default model/config/tokenizer for the task if no model is provided
+ if model is None:
+ model, default_revision = get_default_model_and_revision(targeted_task, task_options)
+ revision = revision if revision is not None else default_revision
+ logger.warning(
+ f"No model was supplied, defaulted to {model} and revision {revision}.\n"
+ "Using a pipeline without specifying a model name and revision in production is not recommended."
+ )
+ hub_kwargs["revision"] = revision
+ if config is None and isinstance(model, str):
+ config = AutoConfig.from_pretrained(model, _from_pipeline=task, **hub_kwargs, **model_kwargs)
+ hub_kwargs["_commit_hash"] = config._commit_hash
+
+ if device_map is not None:
+ if "device_map" in model_kwargs:
+ raise ValueError(
+ 'You cannot use both `pipeline(... device_map=..., model_kwargs={"device_map":...})` as those'
+ " arguments might conflict, use only one.)"
+ )
+ if device is not None:
+ logger.warning(
+ "Both `device` and `device_map` are specified. `device` will override `device_map`. You"
+ " will most likely encounter unexpected behavior. Please remove `device` and keep `device_map`."
+ )
+ model_kwargs["device_map"] = device_map
+
+ # BC for the `torch_dtype` argument
+ if (torch_dtype := kwargs.get("torch_dtype")) is not None:
+ logger.warning_once("`torch_dtype` is deprecated! Use `dtype` instead!")
+ # If both are provided, keep `dtype`
+ dtype = torch_dtype if dtype == "auto" else dtype
+ if "torch_dtype" in model_kwargs or "dtype" in model_kwargs:
+ if "torch_dtype" in model_kwargs:
+ logger.warning_once("`torch_dtype` is deprecated! Use `dtype` instead!")
+ # If the user did not explicitly provide `dtype` (i.e. the function default "auto" is still
+ # present) but a value is supplied inside `model_kwargs`, we silently defer to the latter instead of
+ # raising. This prevents false positives like providing `dtype` only via `model_kwargs` while the
+ # top-level argument keeps its default value "auto".
+ if dtype == "auto":
+ dtype = None
+ else:
+ raise ValueError(
+ 'You cannot use both `pipeline(... dtype=..., model_kwargs={"dtype":...})` as those'
+ " arguments might conflict, use only one.)"
+ )
+ if dtype is not None:
+ if isinstance(dtype, str) and hasattr(torch, dtype):
+ dtype = getattr(torch, dtype)
+ model_kwargs["dtype"] = dtype
+
+ model_name = model if isinstance(model, str) else None
+
+ # Load the correct model if possible
+ if isinstance(model, str):
+ model_classes = targeted_task["pt"]
+ model = load_model(
+ adapter_path if adapter_path is not None else model,
+ model_classes=model_classes,
+ config=config,
+ task=task,
+ **hub_kwargs,
+ **model_kwargs,
+ )
+
+ hub_kwargs["_commit_hash"] = model.config._commit_hash
+
+ if pipeline_class is None:
+ raise RuntimeError("Failed to resolve a pipeline class.")
+
+ load_tokenizer = getattr(pipeline_class, "_load_tokenizer")
+ load_image_processor = getattr(pipeline_class, "_load_image_processor")
+ load_video_processor = getattr(pipeline_class, "_load_video_processor")
+ load_feature_extractor = getattr(pipeline_class, "_load_feature_extractor")
+ load_processor = getattr(pipeline_class, "_load_processor")
+
+ tokenizer = _resolve_tokenizer(
+ tokenizer=tokenizer,
+ load_tokenizer=load_tokenizer,
+ use_fast=use_fast,
+ model_name=model_name,
+ config=config,
+ task=task,
+ hub_kwargs=hub_kwargs,
+ model_kwargs=model_kwargs,
+ )
+ image_processor = _resolve_image_processor(
+ image_processor=image_processor,
+ feature_extractor=feature_extractor,
+ load_image_processor=load_image_processor,
+ model_name=model_name,
+ config=config,
+ task=task,
+ hub_kwargs=hub_kwargs,
+ model_kwargs=model_kwargs,
+ )
+ feature_extractor = _resolve_feature_extractor(
+ feature_extractor=feature_extractor,
+ load_feature_extractor=load_feature_extractor,
+ model_name=model_name,
+ config=config,
+ task=task,
+ hub_kwargs=hub_kwargs,
+ model_kwargs=model_kwargs,
+ kwargs=kwargs,
+ pretrained_model_name_or_path=pretrained_model_name_or_path,
+ )
+ processor = _resolve_processor(
+ processor=processor,
+ load_processor=load_processor,
+ model_name=model_name,
+ config=config,
+ task=task,
+ hub_kwargs=hub_kwargs,
+ model_kwargs=model_kwargs,
+ )
+ video_processor = _resolve_video_processor(
+ video_processor=video_processor,
+ load_video_processor=load_video_processor,
+ model_name=model_name,
+ config=config,
+ task=task,
+ hub_kwargs=hub_kwargs,
+ model_kwargs=model_kwargs,
+ )
+
+ if tokenizer is not None:
+ kwargs["tokenizer"] = tokenizer
+
+ if feature_extractor is not None:
+ kwargs["feature_extractor"] = feature_extractor
+
+ if dtype is not None:
+ kwargs["dtype"] = dtype
+
+ if image_processor is not None:
+ kwargs["image_processor"] = image_processor
+
+ if video_processor is not None:
+ kwargs["video_processor"] = video_processor
+
+ if device is not None:
+ kwargs["device"] = device
+
+ if processor is not None:
+ kwargs["processor"] = processor
+
+ return pipeline_class(model=model, task=task, **kwargs)
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..45ac749cb24968664222119eeadfec306dc52fc1
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/any_to_any.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/any_to_any.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..36f2319710040ae462dc1c09a210daa876a77b16
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/any_to_any.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/audio_classification.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/audio_classification.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cac6bcec54c5d05f26482bd165f8ac088efc4485
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/audio_classification.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/audio_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/audio_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7ca7963f584c97a8e8399309f0641705396d2514
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/audio_utils.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/automatic_speech_recognition.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/automatic_speech_recognition.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1ed9917b76b22ed9e8d3be1526be7dcf8641b492
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/automatic_speech_recognition.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/base.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/base.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7a4eb4336c3469c81896d46c7978ef98b5fc1f4a
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/base.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/depth_estimation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/depth_estimation.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..71f3c0f85f212df9b2a10e4844237fb21498f2dd
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/depth_estimation.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/document_question_answering.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/document_question_answering.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..273e71b66bacc40dd47a7254a9fa33e6aa9bfc4f
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/document_question_answering.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/feature_extraction.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/feature_extraction.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..24379e34dfe725d843baff86bd8f0540d8699a0f
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/feature_extraction.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/fill_mask.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/fill_mask.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ad0f3feea332e3dd9b96c6e5356556109f533f1c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/fill_mask.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/image_classification.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/image_classification.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..31497853b265eb0a69e1bbc5358f71287cb25fa0
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/image_classification.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/image_feature_extraction.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/image_feature_extraction.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..53feb0854d939614de8b7452c0238979cbbcfcb7
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/image_feature_extraction.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/image_segmentation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/image_segmentation.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..31287d993bcb0197490116d3a12c5ab0f07732c9
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/image_segmentation.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/image_text_to_text.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/image_text_to_text.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..793a4d202123f6bb80b894d7fb642d5f3010a331
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/image_text_to_text.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/keypoint_matching.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/keypoint_matching.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..56af71f3f9c66e374170f2ec3a59252719a8e57a
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/keypoint_matching.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/mask_generation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/mask_generation.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..709b91e2bc7e03d1ee8125a2918a53fe954154bf
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/mask_generation.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/object_detection.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/object_detection.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..619bcde3c540bda4899db516ad58edfea9e8518b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/object_detection.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/pt_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/pt_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ff6926ef5fe3ef108b9524e9892550519b0556fe
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/pt_utils.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/table_question_answering.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/table_question_answering.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a71788f0e4af3466f19d7b3d3f91e9e2f89106b7
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/table_question_answering.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/text_classification.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/text_classification.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ee35ad36a6f1445122e9731a89eb8a7b25e44004
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/text_classification.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/text_generation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/text_generation.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1955a953959cb80c31e97d4b514a472687cc48ce
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/text_generation.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/text_to_audio.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/text_to_audio.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..add62b5c81224b910fd50ce8fe29c335879ac287
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/text_to_audio.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/token_classification.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/token_classification.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..30f2c49c3098dc1fc79b018be253bd0a012ad062
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/token_classification.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/video_classification.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/video_classification.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ac23b55217f4c93e0ca8289f72c9bd2e8f0add8e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/video_classification.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/zero_shot_audio_classification.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/zero_shot_audio_classification.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f782ce466e39b898865e8229658333a1b70c5ced
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/zero_shot_audio_classification.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/zero_shot_classification.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/zero_shot_classification.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f42ae3e7ecc74276848ae6b9ac0fa96d8a2dc71b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/zero_shot_classification.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/zero_shot_image_classification.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/zero_shot_image_classification.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..103665b11f6fb488ffa9a05bcb0b5c73f2694214
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/zero_shot_image_classification.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/zero_shot_object_detection.cpython-312.pyc b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/zero_shot_object_detection.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b34a5cf52a4f3e7cb8d47eef32e6fe3ece86d827
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/transformers/pipelines/__pycache__/zero_shot_object_detection.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/any_to_any.py b/.venv/lib/python3.12/site-packages/transformers/pipelines/any_to_any.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ae91d5a176f19ab0aec3ab042be1d8c45030c47
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/pipelines/any_to_any.py
@@ -0,0 +1,514 @@
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import enum
+import re
+from typing import Any, Union, overload
+
+import numpy as np
+
+from ..audio_utils import AudioInput
+from ..generation import GenerationConfig
+from ..image_utils import ImageInput
+from ..processing_utils import ProcessingKwargs, Unpack
+from ..utils import (
+ add_end_docstrings,
+ is_torch_available,
+ is_vision_available,
+ logging,
+ requires_backends,
+)
+from ..video_utils import VideoInput
+from .base import Pipeline, build_pipeline_init_args
+
+
+if is_torch_available():
+ import torch
+
+ from ..models.auto.modeling_auto import MODEL_FOR_MULTIMODAL_LM_MAPPING_NAMES
+ from .pt_utils import KeyDataset
+
+if is_vision_available():
+ from PIL import Image
+
+logger = logging.get_logger(__name__)
+
+
+class ReturnType(enum.Enum):
+ TENSORS = 0
+ NEW_TEXT = 1
+ FULL_TEXT = 2
+
+
+class Chat:
+ """This class is intended to just be used internally in this pipeline and not exposed to users. We convert chats
+ to this format because the rest of the pipeline code tends to assume that lists of messages are
+ actually a batch of samples rather than messages in the same conversation."""
+
+ def __init__(self, messages: list[dict]):
+ for message in messages:
+ if not ("role" in message and "content" in message):
+ raise ValueError("When passing chat dicts as input, each dict must have a 'role' and 'content' key.")
+ self.messages = messages
+
+
+@add_end_docstrings(build_pipeline_init_args(has_processor=True))
+class AnyToAnyPipeline(Pipeline):
+ """
+ Multimodal Generation pipeline using an `AutoModelForMultimodalLM`. This pipeline generates text given any
+ combination of multimodal data and text.When the underlying model is a conversational model, it can also
+ accept one or more chats, in which case the pipeline will operate in chat mode and will continue the
+ chat(s) by adding its response(s). Each chat takes the form of a list of dicts, where each dict contains
+ "role" and "content" keys.
+
+ Unless the model you're using explicitly sets these generation parameters in its configuration files
+ (`generation_config.json`), the following default values will be used:
+ - max_new_tokens: 256
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> pipe = pipeline(task="any-to-any", model="google/gemma-3n-E4B-it")
+ >>> pipe("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", text="A photo of")
+ [{'generated_text': 'a photo of two birds'}]
+ ```
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> pipe = pipeline("any-to-any", model="google/gemma-3n-E4B-it")
+ >>> messages = [
+ >>> {
+ >>> "role": "user",
+ >>> "content": [
+ >>> {
+ >>> "type": "image",
+ >>> "url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg",
+ >>> },
+ >>> {"type": "text", "text": "Describe this image."},
+ >>> ],
+ >>> },
+ >>> {
+ >>> "role": "assistant",
+ >>> "content": [
+ >>> {"type": "text", "text": "There is a dog and"},
+ >>> ],
+ >>> },
+ >>> ]
+ >>> pipe(text=messages, max_new_tokens=20, return_full_text=False)
+ [{'input_text': [{'role': 'user',
+ 'content': [{'type': 'image',
+ 'url': 'https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg'},
+ {'type': 'text', 'text': 'Describe this image.'}]},
+ {'role': 'assistant',
+ 'content': [{'type': 'text', 'text': 'There is a dog and'}]}],
+ 'generated_text': ' a person in the image. The dog is sitting on the sand, and the person is sitting on'}]
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This multimodal pipeline can currently be loaded from pipeline() using the following task identifier:
+ "any-to-any".
+
+ See the list of available models on
+ [huggingface.co/models](https://huggingface.co/models?pipeline_tag=any-to-any).
+ """
+
+ _load_processor = True
+ _load_image_processor = False
+ _load_feature_extractor = False
+ _load_tokenizer = False
+
+ _pipeline_calls_generate = True
+ # Make sure the docstring is updated when the default generation config is changed
+ _default_generation_config = GenerationConfig(
+ max_new_tokens=256,
+ )
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ if "image" in self.model.input_modalities or "video" in self.model.input_modalities:
+ requires_backends(self, "vision")
+ requires_backends(self, "torchvision")
+ if "audio" in self.model.input_modalities:
+ requires_backends(self, "librosa")
+ self.check_model_type(MODEL_FOR_MULTIMODAL_LM_MAPPING_NAMES)
+
+ def _sanitize_parameters(
+ self,
+ max_new_tokens=None,
+ generate_kwargs=None,
+ timeout=None,
+ return_full_text=None,
+ return_tensors=None,
+ return_type=None,
+ clean_up_tokenization_spaces=None,
+ stop_sequence=None,
+ continue_final_message=None,
+ skip_special_tokens=None,
+ generation_mode=None,
+ processor_kwargs=None,
+ **kwargs: Unpack[ProcessingKwargs],
+ ):
+ forward_kwargs = {}
+ preprocess_params = {}
+ postprocess_params = {}
+
+ # Preprocess params
+ preprocess_params.update(kwargs)
+ if timeout is not None:
+ preprocess_params["timeout"] = timeout
+ if continue_final_message is not None:
+ preprocess_params["continue_final_message"] = continue_final_message
+ if processor_kwargs is not None:
+ preprocess_params["processor_kwargs"] = processor_kwargs
+
+ # Forward kwargs
+ forward_kwargs["generate_kwargs"] = generate_kwargs or {}
+ if generation_mode is not None and generation_mode != "text":
+ forward_kwargs["generate_kwargs"]["generation_mode"] = generation_mode
+ # Qwen-Omni models need to know the origin of audio, to align mm position ids
+ if kwargs.get("load_audio_from_video") and re.search(r"qwen\domni", self.model.__class__.__name__.lower()):
+ forward_kwargs["generate_kwargs"]["use_audio_in_video"] = True
+ if stop_sequence is not None:
+ if isinstance(stop_sequence, str):
+ stop_sequence = [stop_sequence]
+ forward_kwargs["generate_kwargs"]["stop_strings"] = stop_sequence
+ forward_kwargs["generate_kwargs"]["tokenizer"] = self.processor.tokenizer
+
+ if max_new_tokens is not None:
+ if generate_kwargs is not None and "max_new_tokens" in generate_kwargs:
+ raise ValueError(
+ "'max_new_tokens' is defined twice, once in 'generate_kwargs' and "
+ "once as a direct argument. Please use only one."
+ )
+ forward_kwargs["generate_kwargs"]["max_new_tokens"] = max_new_tokens
+
+ if return_full_text is not None and return_type is None:
+ if return_tensors is not None:
+ raise ValueError("`return_full_text` is mutually exclusive with `return_tensors`")
+ return_type = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT
+ elif return_tensors is not None and return_type is None:
+ return_type = ReturnType.TENSORS
+ # We don't want to set the global default to FULLTEXT at init time. That is why
+ # `_postprocess_params` is checked before setting the default value
+ elif return_type is None and generation_mode in [None, "text"] and hasattr(self, "_postprocess_params"):
+ return_type = ReturnType.FULL_TEXT
+
+ # Postprocess params
+ if generation_mode not in [None, "text"] and return_type is not None:
+ raise ValueError(
+ f"`return_type` cannot be set to {return_type} when generation_mode={generation_mode}. "
+ "Set `return_type=None` or generation_mode='text'"
+ )
+ if generation_mode not in [None, "text", "image", "audio"]:
+ raise ValueError(
+ f"`generation_mode` can be only one of the `text`, `audio`, `image` but got generation_mode[={generation_mode}]"
+ )
+ elif generation_mode is not None and generation_mode not in self.model.output_modalities:
+ raise ValueError(
+ f"`generation_mode={generation_mode}` is not supported for {self.model.__class__.__name__}. "
+ f"The model can only output the following modalities: {self.model.output_modalities}"
+ )
+
+ if return_type is not None:
+ postprocess_params["return_type"] = return_type
+ if continue_final_message is not None:
+ postprocess_params["continue_final_message"] = continue_final_message
+ if clean_up_tokenization_spaces is not None:
+ postprocess_params["clean_up_tokenization_spaces"] = clean_up_tokenization_spaces
+ if skip_special_tokens is not None:
+ postprocess_params["skip_special_tokens"] = skip_special_tokens
+ postprocess_params["generation_mode"] = generation_mode
+ return preprocess_params, forward_kwargs, postprocess_params
+
+ @overload
+ def __call__(
+ self,
+ text: str | None = None,
+ images: Union[str, "Image.Image"] | None = None,
+ videos: Union[str, "np.ndarray", "torch.Tensor"] | None = None,
+ audio: Union[str, "np.ndarray"] | None = None,
+ **kwargs: Any,
+ ) -> list[dict[str, Any]]: ...
+
+ @overload
+ def __call__(
+ self,
+ text: list[str] | None = None,
+ images: list[str] | list["Image.Image"] | None = None,
+ videos: list[str] | list["np.ndarray"] | list["torch.Tensor"] | None = None,
+ audio: list[str] | list["np.ndarray"] | None = None,
+ **kwargs: Any,
+ ) -> list[list[dict[str, Any]]]: ...
+
+ def __call__(
+ self,
+ text: str | list[str] | list[dict],
+ images: str | list[str] | list[list[str]] | ImageInput | None = None,
+ videos: str | list[str] | VideoInput | None = None,
+ audio: str | list[str] | AudioInput | None = None,
+ **kwargs,
+ ) -> list[dict[str, Any]] | list[list[dict[str, Any]]]:
+ """
+ Generate a text given text and optionally multimodal data passed as inputs.
+
+ Args:
+ text (`str`, `list[str]`, `list[dict]`):
+ The text to be used for generation. If a list of strings is passed, the length of the list should be
+ the same as the number of images. Text can also follow the chat format: a list of dictionaries where
+ each dictionary represents a message in a conversation. Each dictionary should have two keys: 'role'
+ and 'content'. 'role' should be one of 'user', 'system' or 'assistant'. 'content' should be a list of
+ dictionary containing the text of the message and the type of the message.
+ images (`str`, `list[str]`, `ImageInput`):
+ The pipeline handles three types of images:
+
+ - A string containing a HTTP(s) link pointing to an image
+ - A string containing a local path to an image
+ - An image loaded in PIL directly
+
+ The pipeline accepts either a single image or a batch of images. Finally, this pipeline also supports
+ the chat format (see `text`) containing images and text in this argument.
+ videos (`str`, `list[str]`, `VideoInput`):
+ The pipeline handles three types of videos:
+
+ - A string containing a HTTP(s) link pointing to a video
+ - A string containing a local path to a video
+ - A video loaded and decoded to array format
+
+ The pipeline accepts either a single video or a batch of videos. Finally, this pipeline also supports
+ the chat format (see `text`) containing videos and text in this argument.
+ audio (`str`, `list[str]`, `AudioInput`):
+ The pipeline handles three types of audios:
+
+ - A string containing a HTTP(s) link pointing to an audio
+ - A string containing a local path to an audio
+ - An audio loaded in PIL directly
+
+ The pipeline accepts either a single audios or a batch of audios. Finally, this pipeline also supports
+ the chat format (see `text`) containing audios and text in this argument.
+ return_tensors (`bool`, *optional*, defaults to `False`):
+ Returns the tensors of predictions (as token indices) in the outputs. If set to
+ `True`, the decoded text is not returned.
+ return_text (`bool`, *optional*):
+ Returns the decoded texts in the outputs.
+ return_full_text (`bool`, *optional*, defaults to `True`):
+ If set to `False` only added text is returned, otherwise the full text is returned. Cannot be
+ specified at the same time as `return_text`.
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`):
+ Whether or not to clean up the potential extra spaces in the text output.
+ continue_final_message( `bool`, *optional*): This indicates that you want the model to continue the
+ last message in the input chat rather than starting a new one, allowing you to "prefill" its response.
+ By default this is `True` when the final message in the input chat has the `assistant` role and
+ `False` otherwise, but you can manually override that behaviour by setting this flag.
+
+ Return:
+ A list or a list of list of `dict`: Each result comes as a dictionary with the following key (cannot
+ return a combination of both `generated_text` and `generated_token_ids`):
+
+ - **generated_text** (`str`, present when `return_text=True` and `generation_mode="text"`) -- The generated text.
+ - **generated_audio** (`np.ndarray`, present when `generation_mode="audio"`) -- The generated audio.
+ - **generated_image** (`PIL.Image.Image`, present when `generation_mode="image"`) -- The generated image.
+ - **generated_token_ids** (`torch.Tensor`, present when `return_tensors=True` and `generation_mode="text"`) -- The token
+ ids of the generated text.
+ - **input_text** (`str`) -- The input text.
+ """
+ if images is None and text is None:
+ raise ValueError("You must at least provide either text or images.")
+
+ if isinstance(text, (list, tuple, KeyDataset)) and isinstance(text[0], (list, tuple, dict)):
+ # We have one or more prompts in list-of-dicts format, so this is chat mode
+ if isinstance(text[0], dict) and "role" in text[0]:
+ return super().__call__(Chat(text), **kwargs)
+ elif isinstance(text[0], (list, tuple)) and isinstance(text[0][0], dict) and "role" in text[0][0]:
+ chats = [Chat(chat) for chat in text] # 🐈 🐈 🐈
+ return super().__call__(chats, **kwargs)
+
+ if text is not None and not (isinstance(text, str) or (isinstance(text, list) and isinstance(text[0], str))):
+ """
+ Supports the following format
+ - {"text": text, "image": image, "video": video, "audio": audio}
+ - [{"text": text, "image": image, "video": video, "audio": audio}]
+ - Generator and datasets
+ This is a common pattern in other multimodal pipelines, so we support it here as well.
+ """
+ return super().__call__(text, **kwargs)
+
+ # encourage the user to use the chat format if supported
+ if getattr(self.processor, "chat_template", None) is not None:
+ logger.warning_once(
+ "The input data was not formatted as a chat with dicts containing 'role' and 'content' keys, even "
+ "though this model supports chat. Consider using the chat format for better results. For more "
+ "information, see https://huggingface.co/docs/transformers/en/chat_templating"
+ )
+
+ return super().__call__({"text": text, "images": images, "video": videos, "audio": audio}, **kwargs)
+
+ def preprocess(self, inputs=None, timeout=None, continue_final_message=None, **processing_kwargs):
+ if isinstance(inputs, Chat):
+ # If the user passes a chat that ends in an assistant message, we treat it as a prefill by default
+ # because very few models support multiple separate, consecutive assistant messages
+ if continue_final_message is None:
+ continue_final_message = inputs.messages[-1]["role"] == "assistant"
+
+ # Processor kwargs are passed separately from jinja kwargs to chat template
+ # but it was added only in https://github.com/huggingface/transformers/pull/44881
+ processor_kwargs = processing_kwargs.pop("processor_kwargs", None) or {}
+
+ chat_template_kwargs = {
+ "continue_final_message": continue_final_message,
+ "return_tensors": "pt",
+ "tokenize": True,
+ "return_dict": True,
+ "add_generation_prompt": not continue_final_message,
+ "processor_kwargs": processor_kwargs,
+ **processing_kwargs,
+ }
+
+ # Handle Mistral tokenizer which does not accept processing kwargs
+ if self.processor.tokenizer.__class__.__name__ == "MistralCommonBackend":
+ chat_template_kwargs = {
+ k: v for k, v in chat_template_kwargs.items() if k in ["padding", "truncation", "max_length"]
+ }
+
+ model_inputs = self.processor.apply_chat_template(
+ inputs.messages,
+ **chat_template_kwargs,
+ ).to(dtype=self.dtype)
+ model_inputs["text"] = inputs
+ return model_inputs
+
+ # In case we only have text inputs
+ if isinstance(inputs, (list, tuple, str)):
+ text = inputs
+ inputs = {}
+ else:
+ inputs = inputs.copy() # avoid in-place changes if users passed dict
+ text = inputs.pop("text")
+
+ # Feature extractor do not load audio files and expect a decoded array
+ if inputs.get("audio", None) is not None and hasattr(self.processor, "feature_extractor"):
+ inputs["audio"] = self.processor.feature_extractor.fetch_audio(inputs["audio"])
+
+ # If batched text inputs, we set padding to True unless specified otherwise
+ processor_kwargs = processing_kwargs.pop("processor_kwargs", None) or processing_kwargs
+ if isinstance(text, (list, tuple)) and len(text) > 1:
+ processor_kwargs.setdefault("padding", True)
+ model_inputs = self.processor(text=text, **inputs, return_tensors="pt", **processor_kwargs).to(
+ dtype=self.dtype
+ )
+ model_inputs["text"] = text
+ return model_inputs
+
+ def _forward(self, model_inputs, generate_kwargs=None):
+ generate_kwargs = {} if generate_kwargs is None else generate_kwargs
+ prompt_text = model_inputs.pop("text")
+ input_ids = model_inputs.get("input_ids", model_inputs.get("decoder_input_ids"))
+
+ # User-defined `generation_config` passed to the pipeline call take precedence
+ if "generation_config" not in generate_kwargs:
+ generate_kwargs["generation_config"] = self.generation_config
+
+ generated_sequence = self.model.generate(**model_inputs, **generate_kwargs)
+ return {"generated_sequence": generated_sequence, "prompt_text": prompt_text, "input_ids": input_ids}
+
+ def postprocess(
+ self,
+ model_outputs,
+ return_type=None,
+ continue_final_message=None,
+ skip_special_tokens=None,
+ **postprocess_kwargs,
+ ):
+ input_texts = model_outputs["prompt_text"]
+ input_texts = [input_texts] if isinstance(input_texts, (str, Chat)) else input_texts
+ generated_sequence = model_outputs["generated_sequence"]
+ input_ids = model_outputs["input_ids"]
+ if return_type == ReturnType.TENSORS:
+ return [
+ {"input_text": input_texts[i], "generated_token_ids": generated_sequence[i]}
+ for i in range(len(input_texts))
+ ]
+
+ # Decode inputs and outputs the same way to remove input text from generated text if present
+ skip_special_tokens = skip_special_tokens if skip_special_tokens is not None else True
+ if getattr(self.tokenizer, "response_schema", False):
+ skip_special_tokens = False
+ generation_mode = postprocess_kwargs["generation_mode"] or "text"
+ if generation_mode == "image" and hasattr(self.model, "decode_image_tokens"):
+ generated_sequence = self.model.decode_image_tokens(generated_sequence.to(self.model.device))
+ generated_outputs = self.processor.post_process_multimodal_output(
+ generated_sequence, skip_special_tokens=skip_special_tokens, **postprocess_kwargs
+ )
+
+ # Force consistent behavior for including the input text in the output
+ if return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
+ # Remove the input text from the generated text if the generated text starts with the input text
+ # (accounting for the possibility of a space between the input and generated text)
+ new_generated_texts = []
+ postprocess_kwargs["generation_mode"] = "text"
+ decoded_inputs = self.processor.post_process_multimodal_output(
+ input_ids, skip_special_tokens=skip_special_tokens, **postprocess_kwargs
+ )
+ for text_generated, decoded_input in zip(generated_outputs, decoded_inputs):
+ # There can be added characters before the input text, so we need to find the beginning of the input text in the generated text
+ index_input_text = text_generated.find(decoded_input)
+ # Limit the search to 2 residual characters, like spaces or new lines, to avoid removing a large part of the answer
+ if 0 <= index_input_text <= 2:
+ # If the input text is found, we remove it
+ new_generated_texts.append(text_generated[index_input_text + len(decoded_input) :])
+ else:
+ new_generated_texts.append(text_generated)
+ generated_outputs = new_generated_texts
+ if return_type == ReturnType.FULL_TEXT:
+ full_texts = []
+ for prompt_text, generated_text in zip(input_texts, generated_outputs):
+ if isinstance(prompt_text, str):
+ generated_text = prompt_text + generated_text
+ elif isinstance(prompt_text, Chat):
+ if continue_final_message is None:
+ # If the user passes a chat ending in an assistant message, we treat it as a prefill by
+ # default because very few models support multiple separate, consecutive assistant messages
+ continue_final_message = prompt_text.messages[-1]["role"] == "assistant"
+ if continue_final_message:
+ # With assistant prefill, concat onto the end of the last message
+ new_text = dict(prompt_text.messages[-1]["content"][-1].items())
+ new_text["text"] += generated_text
+ generated_text = list(prompt_text.messages)[:-1] + [
+ {
+ "role": prompt_text.messages[-1]["role"],
+ "content": prompt_text.messages[-1]["content"][:-1] + [new_text],
+ }
+ ]
+ else:
+ # When we're not starting from a prefill, the output is a new assistant message
+ if getattr(self.tokenizer, "response_schema", False):
+ assistant_message = self.tokenizer.parse_response(generated_text)
+ else:
+ assistant_message = {"role": "assistant", "content": generated_text}
+ generated_text = list(prompt_text.messages) + [assistant_message]
+ full_texts.append(generated_text)
+ generated_outputs = full_texts
+
+ records = [
+ {
+ "input_text": input_text.messages if isinstance(input_text, Chat) else input_text,
+ f"generated_{generation_mode}": generated_output,
+ }
+ for input_text, generated_output in zip(input_texts, generated_outputs)
+ ]
+
+ return records
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/audio_classification.py b/.venv/lib/python3.12/site-packages/transformers/pipelines/audio_classification.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e173111aa860dd2dd313b3c613cb04334a3ac72
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/pipelines/audio_classification.py
@@ -0,0 +1,260 @@
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import subprocess
+from typing import Any
+
+import httpx
+import numpy as np
+
+from ..utils import add_end_docstrings, is_torch_available, is_torchaudio_available, is_torchcodec_available, logging
+from .base import Pipeline, build_pipeline_init_args
+
+
+if is_torch_available():
+ from ..models.auto.modeling_auto import MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES
+
+logger = logging.get_logger(__name__)
+
+
+def ffmpeg_read(bpayload: bytes, sampling_rate: int) -> np.ndarray:
+ """
+ Helper function to read an audio file through ffmpeg.
+ """
+ ar = f"{sampling_rate}"
+ ac = "1"
+ format_for_conversion = "f32le"
+ ffmpeg_command = [
+ "ffmpeg",
+ "-i",
+ "pipe:0",
+ "-ac",
+ ac,
+ "-ar",
+ ar,
+ "-f",
+ format_for_conversion,
+ "-hide_banner",
+ "-loglevel",
+ "quiet",
+ "pipe:1",
+ ]
+
+ try:
+ ffmpeg_process = subprocess.Popen(ffmpeg_command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
+ except FileNotFoundError:
+ raise ValueError("ffmpeg was not found but is required to load audio files from filename")
+ output_stream = ffmpeg_process.communicate(bpayload)
+ out_bytes = output_stream[0]
+
+ audio = np.frombuffer(out_bytes, np.float32)
+ if audio.shape[0] == 0:
+ raise ValueError("Malformed soundfile")
+ return audio
+
+
+@add_end_docstrings(build_pipeline_init_args(has_feature_extractor=True))
+class AudioClassificationPipeline(Pipeline):
+ # no-format
+ """
+ Audio classification pipeline using any `AutoModelForAudioClassification`. This pipeline predicts the class of a
+ raw waveform or an audio file. In case of an audio file, ffmpeg should be installed to support multiple audio
+ formats.
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> classifier = pipeline(model="superb/wav2vec2-base-superb-ks")
+ >>> classifier("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac")
+ [{'score': 0.997, 'label': '_unknown_'}, {'score': 0.002, 'label': 'left'}, {'score': 0.0, 'label': 'yes'}, {'score': 0.0, 'label': 'down'}, {'score': 0.0, 'label': 'stop'}]
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+
+ This pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"audio-classification"`.
+
+ See the list of available models on
+ [huggingface.co/models](https://huggingface.co/models?filter=audio-classification).
+ """
+
+ _load_processor = False
+ _load_image_processor = False
+ _load_feature_extractor = True
+ _load_tokenizer = False
+
+ def __init__(self, *args, **kwargs):
+ # Only set default top_k if explicitly provided
+ if "top_k" in kwargs and kwargs["top_k"] is None:
+ kwargs["top_k"] = None
+ elif "top_k" not in kwargs:
+ kwargs["top_k"] = 5
+ super().__init__(*args, **kwargs)
+
+ self.check_model_type(MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES)
+
+ def __call__(self, inputs: np.ndarray | bytes | str | dict, **kwargs: Any) -> list[dict[str, Any]]:
+ """
+ Classify the sequence(s) given as inputs. See the [`AutomaticSpeechRecognitionPipeline`] documentation for more
+ information.
+
+ Args:
+ inputs (`np.ndarray` or `bytes` or `str` or `dict`):
+ The inputs is either :
+ - `str` that is the filename of the audio file, the file will be read at the correct sampling rate
+ to get the waveform using *ffmpeg*. This requires *ffmpeg* to be installed on the system.
+ - `bytes` it is supposed to be the content of an audio file and is interpreted by *ffmpeg* in the
+ same way.
+ - (`np.ndarray` of shape (n, ) of type `np.float32` or `np.float64`)
+ Raw audio at the correct sampling rate (no further check will be done)
+ - `dict` form can be used to pass raw audio sampled at arbitrary `sampling_rate` and let this
+ pipeline do the resampling. The dict must be either be in the format `{"sampling_rate": int,
+ "raw": np.array}`, or `{"sampling_rate": int, "array": np.array}`, where the key `"raw"` or
+ `"array"` is used to denote the raw audio waveform.
+ top_k (`int`, *optional*, defaults to None):
+ The number of top labels that will be returned by the pipeline. If the provided number is `None` or
+ higher than the number of labels available in the model configuration, it will default to the number of
+ labels.
+ function_to_apply (`str`, *optional*, defaults to "softmax"):
+ The function to apply to the model output. By default, the pipeline will apply the softmax function to
+ the output of the model. Valid options: ["softmax", "sigmoid", "none"]. Note that passing Python's
+ built-in `None` will default to "softmax", so you need to pass the string "none" to disable any
+ post-processing.
+
+ Return:
+ A list of `dict` with the following keys:
+
+ - **label** (`str`) -- The label predicted.
+ - **score** (`float`) -- The corresponding probability.
+ """
+ return super().__call__(inputs, **kwargs)
+
+ def _sanitize_parameters(self, top_k=None, function_to_apply=None, **kwargs):
+ postprocess_params = {}
+
+ # If top_k is None, use all labels
+ if top_k is None:
+ postprocess_params["top_k"] = self.model.config.num_labels
+ else:
+ if top_k > self.model.config.num_labels:
+ top_k = self.model.config.num_labels
+ postprocess_params["top_k"] = top_k
+
+ if function_to_apply is not None:
+ if function_to_apply not in ["softmax", "sigmoid", "none"]:
+ raise ValueError(
+ f"Invalid value for `function_to_apply`: {function_to_apply}. "
+ "Valid options are ['softmax', 'sigmoid', 'none']"
+ )
+ postprocess_params["function_to_apply"] = function_to_apply
+ else:
+ postprocess_params["function_to_apply"] = "softmax"
+ return {}, {}, postprocess_params
+
+ def preprocess(self, inputs):
+ if isinstance(inputs, str):
+ if inputs.startswith("http://") or inputs.startswith("https://"):
+ # We need to actually check for a real protocol, otherwise it's impossible to use a local file
+ # like http_huggingface_co.png
+ inputs = httpx.get(inputs, follow_redirects=True).content
+ else:
+ with open(inputs, "rb") as f:
+ inputs = f.read()
+
+ if isinstance(inputs, bytes):
+ inputs = ffmpeg_read(inputs, self.feature_extractor.sampling_rate)
+
+ if is_torch_available():
+ import torch
+
+ if isinstance(inputs, torch.Tensor):
+ inputs = inputs.cpu().numpy()
+
+ if is_torchcodec_available():
+ import torch
+ import torchcodec
+
+ if isinstance(inputs, torchcodec.decoders.AudioDecoder):
+ _audio_samples = inputs.get_all_samples()
+ _array = _audio_samples.data
+ inputs = {"array": _array, "sampling_rate": _audio_samples.sample_rate}
+
+ if isinstance(inputs, dict):
+ inputs = inputs.copy() # So we don't mutate the original dictionary outside the pipeline
+ # Accepting `"array"` which is the key defined in `datasets` for
+ # better integration
+ if not ("sampling_rate" in inputs and ("raw" in inputs or "array" in inputs)):
+ raise ValueError(
+ "When passing a dictionary to AudioClassificationPipeline, the dict needs to contain a "
+ '"raw" key containing the numpy array or torch tensor representing the audio and a "sampling_rate" key, '
+ "containing the sampling_rate associated with that array"
+ )
+
+ _inputs = inputs.pop("raw", None)
+ if _inputs is None:
+ # Remove path which will not be used from `datasets`.
+ inputs.pop("path", None)
+ _inputs = inputs.pop("array", None)
+ in_sampling_rate = inputs.pop("sampling_rate")
+ inputs = _inputs
+ if in_sampling_rate != self.feature_extractor.sampling_rate:
+ import torch
+
+ if is_torchaudio_available():
+ from torchaudio import functional as F
+ else:
+ raise ImportError(
+ "torchaudio is required to resample audio samples in AudioClassificationPipeline. "
+ "The torchaudio package can be installed through: `pip install torchaudio`."
+ )
+
+ inputs = F.resample(
+ torch.from_numpy(inputs) if isinstance(inputs, np.ndarray) else inputs,
+ in_sampling_rate,
+ self.feature_extractor.sampling_rate,
+ ).numpy()
+
+ if not isinstance(inputs, np.ndarray):
+ raise TypeError("We expect a numpy ndarray or torch tensor as input")
+ if len(inputs.shape) != 1:
+ raise ValueError("We expect a single channel audio input for AudioClassificationPipeline")
+
+ processed = self.feature_extractor(
+ inputs, sampling_rate=self.feature_extractor.sampling_rate, return_tensors="pt"
+ )
+ if self.dtype is not None:
+ processed = processed.to(dtype=self.dtype)
+ return processed
+
+ def _forward(self, model_inputs):
+ model_outputs = self.model(**model_inputs)
+ return model_outputs
+
+ def postprocess(self, model_outputs, top_k=5, function_to_apply="softmax"):
+ if function_to_apply == "softmax":
+ probs = model_outputs.logits[0].softmax(-1)
+ elif function_to_apply == "sigmoid":
+ probs = model_outputs.logits[0].sigmoid()
+ else:
+ probs = model_outputs.logits[0]
+ scores, ids = probs.topk(top_k)
+
+ scores = scores.tolist()
+ ids = ids.tolist()
+
+ labels = [{"score": score, "label": self.model.config.id2label[_id]} for score, _id in zip(scores, ids)]
+
+ return labels
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/audio_utils.py b/.venv/lib/python3.12/site-packages/transformers/pipelines/audio_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e3e0bcd521572f751202c4f618e0a0be0251a16
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/pipelines/audio_utils.py
@@ -0,0 +1,295 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+import datetime
+import platform
+import subprocess
+
+import numpy as np
+
+
+def ffmpeg_read(bpayload: bytes, sampling_rate: int) -> np.ndarray:
+ """
+ Helper function to read an audio file through ffmpeg.
+ """
+ ar = f"{sampling_rate}"
+ ac = "1"
+ format_for_conversion = "f32le"
+ ffmpeg_command = [
+ "ffmpeg",
+ "-i",
+ "pipe:0",
+ "-ac",
+ ac,
+ "-ar",
+ ar,
+ "-f",
+ format_for_conversion,
+ "-hide_banner",
+ "-loglevel",
+ "quiet",
+ "pipe:1",
+ ]
+
+ try:
+ with subprocess.Popen(ffmpeg_command, stdin=subprocess.PIPE, stdout=subprocess.PIPE) as ffmpeg_process:
+ output_stream = ffmpeg_process.communicate(bpayload)
+ except FileNotFoundError as error:
+ raise ValueError("ffmpeg was not found but is required to load audio files from filename") from error
+ out_bytes = output_stream[0]
+ audio = np.frombuffer(out_bytes, np.float32)
+ if audio.shape[0] == 0:
+ raise ValueError(
+ "Soundfile is either not in the correct format or is malformed. Ensure that the soundfile has "
+ "a valid audio file extension (e.g. wav, flac or mp3) and is not corrupted. If reading from a remote "
+ "URL, ensure that the URL is the full address to **download** the audio file."
+ )
+ return audio
+
+
+def ffmpeg_microphone(
+ sampling_rate: int,
+ chunk_length_s: float,
+ format_for_conversion: str = "f32le",
+ ffmpeg_input_device: str | None = None,
+ ffmpeg_additional_args: list[str] | None = None,
+):
+ """
+ Helper function to read audio from a microphone using ffmpeg. The default input device will be used unless another
+ input device is specified using the `ffmpeg_input_device` argument. Uses 'alsa' on Linux, 'avfoundation' on MacOS and
+ 'dshow' on Windows.
+
+ Arguments:
+ sampling_rate (`int`):
+ The sampling_rate to use when reading the data from the microphone. Try using the model's sampling_rate to
+ avoid resampling later.
+ chunk_length_s (`float` or `int`):
+ The length of the maximum chunk of audio to be sent returned.
+ format_for_conversion (`str`, defaults to `f32le`):
+ The name of the format of the audio samples to be returned by ffmpeg. The standard is `f32le`, `s16le`
+ could also be used.
+ ffmpeg_input_device (`str`, *optional*):
+ The identifier of the input device to be used by ffmpeg (i.e. ffmpeg's '-i' argument). If unset,
+ the default input device will be used. See `https://www.ffmpeg.org/ffmpeg-devices.html#Input-Devices`
+ for how to specify and list input devices.
+ ffmpeg_additional_args (`list[str]`, *optional*):
+ Additional arguments to pass to ffmpeg, can include arguments like -nostdin for running as a background
+ process. For example, to pass -nostdin to the ffmpeg process, pass in ["-nostdin"]. If passing in flags
+ with multiple arguments, use the following convention (eg ["flag", "arg1", "arg2]).
+
+ Returns:
+ A generator yielding audio chunks of `chunk_length_s` seconds as `bytes` objects of length
+ `int(round(sampling_rate * chunk_length_s)) * size_of_sample`.
+ """
+ ar = f"{sampling_rate}"
+ ac = "1"
+ if format_for_conversion == "s16le":
+ size_of_sample = 2
+ elif format_for_conversion == "f32le":
+ size_of_sample = 4
+ else:
+ raise ValueError(f"Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`")
+
+ system = platform.system()
+
+ if system == "Linux":
+ format_ = "alsa"
+ input_ = ffmpeg_input_device or "default"
+ elif system == "Darwin":
+ format_ = "avfoundation"
+ input_ = ffmpeg_input_device or ":default"
+ elif system == "Windows":
+ format_ = "dshow"
+ input_ = ffmpeg_input_device or _get_microphone_name()
+
+ ffmpeg_additional_args = [] if ffmpeg_additional_args is None else ffmpeg_additional_args
+
+ ffmpeg_command = [
+ "ffmpeg",
+ "-f",
+ format_,
+ "-i",
+ input_,
+ "-ac",
+ ac,
+ "-ar",
+ ar,
+ "-f",
+ format_for_conversion,
+ "-fflags",
+ "nobuffer",
+ "-hide_banner",
+ "-loglevel",
+ "quiet",
+ "pipe:1",
+ ]
+
+ ffmpeg_command.extend(ffmpeg_additional_args)
+
+ chunk_len = int(round(sampling_rate * chunk_length_s)) * size_of_sample
+ iterator = _ffmpeg_stream(ffmpeg_command, chunk_len)
+ yield from iterator
+
+
+def ffmpeg_microphone_live(
+ sampling_rate: int,
+ chunk_length_s: float,
+ stream_chunk_s: int | None = None,
+ stride_length_s: tuple[float, float] | float | None = None,
+ format_for_conversion: str = "f32le",
+ ffmpeg_input_device: str | None = None,
+ ffmpeg_additional_args: list[str] | None = None,
+):
+ """
+ Helper function to read audio from a microphone using ffmpeg. This will output `partial` overlapping chunks starting
+ from `stream_chunk_s` (if it is defined) until `chunk_length_s` is reached. It will make use of striding to avoid
+ errors on the "sides" of the various chunks. The default input device will be used unless another input device is
+ specified using the `ffmpeg_input_device` argument. Uses 'alsa' on Linux, 'avfoundation' on MacOS and 'dshow' on Windows.
+
+ Arguments:
+ sampling_rate (`int`):
+ The sampling_rate to use when reading the data from the microphone. Try using the model's sampling_rate to
+ avoid resampling later.
+ chunk_length_s (`float` or `int`):
+ The length of the maximum chunk of audio to be sent returned. This includes the eventual striding.
+ stream_chunk_s (`float` or `int`):
+ The length of the minimal temporary audio to be returned.
+ stride_length_s (`float` or `int` or `(float, float)`, *optional*):
+ The length of the striding to be used. Stride is used to provide context to a model on the (left, right) of
+ an audio sample but without using that part to actually make the prediction. Setting this does not change
+ the length of the chunk.
+ format_for_conversion (`str`, *optional*, defaults to `f32le`):
+ The name of the format of the audio samples to be returned by ffmpeg. The standard is `f32le`, `s16le`
+ could also be used.
+ ffmpeg_input_device (`str`, *optional*):
+ The identifier of the input device to be used by ffmpeg (i.e. ffmpeg's '-i' argument). If unset,
+ the default input device will be used. See `https://www.ffmpeg.org/ffmpeg-devices.html#Input-Devices`
+ for how to specify and list input devices.
+ ffmpeg_additional_args (`list[str]`, *optional*):
+ Additional arguments to pass to ffmpeg, can include arguments like -nostdin for running as a background
+ process. For example, to pass -nostdin to the ffmpeg process, pass in ["-nostdin"]. If passing in flags
+ with multiple arguments, use the following convention (eg ["flag", "arg1", "arg2]).
+
+ Return:
+ A generator yielding dictionaries of the following form
+
+ `{"sampling_rate": int, "raw": np.ndarray, "partial" bool}` With optionally a `"stride" (int, int)` key if
+ `stride_length_s` is defined.
+
+ `stride` and `raw` are all expressed in `samples`, and `partial` is a boolean saying if the current yield item
+ is a whole chunk, or a partial temporary result to be later replaced by another larger chunk.
+ """
+ if stream_chunk_s is not None:
+ chunk_s = stream_chunk_s
+ else:
+ chunk_s = chunk_length_s
+
+ microphone = ffmpeg_microphone(
+ sampling_rate,
+ chunk_s,
+ format_for_conversion=format_for_conversion,
+ ffmpeg_input_device=ffmpeg_input_device,
+ ffmpeg_additional_args=[] if ffmpeg_additional_args is None else ffmpeg_additional_args,
+ )
+
+ if format_for_conversion == "s16le":
+ dtype = np.int16
+ size_of_sample = 2
+ elif format_for_conversion == "f32le":
+ dtype = np.float32
+ size_of_sample = 4
+ else:
+ raise ValueError(f"Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`")
+
+ if stride_length_s is None:
+ stride_length_s = chunk_length_s / 6
+ chunk_len = int(round(sampling_rate * chunk_length_s)) * size_of_sample
+ if isinstance(stride_length_s, (int, float)):
+ stride_length_s = [stride_length_s, stride_length_s]
+
+ stride_left = int(round(sampling_rate * stride_length_s[0])) * size_of_sample
+ stride_right = int(round(sampling_rate * stride_length_s[1])) * size_of_sample
+ audio_time = datetime.datetime.now()
+ delta = datetime.timedelta(seconds=chunk_s)
+ for item in chunk_bytes_iter(microphone, chunk_len, stride=(stride_left, stride_right), stream=True):
+ # Put everything back in numpy scale
+ item["raw"] = np.frombuffer(item["raw"], dtype=dtype)
+ item["stride"] = (
+ item["stride"][0] // size_of_sample,
+ item["stride"][1] // size_of_sample,
+ )
+ item["sampling_rate"] = sampling_rate
+ audio_time += delta
+ if datetime.datetime.now() > audio_time + 10 * delta:
+ # We're late !! SKIP
+ continue
+ yield item
+
+
+def chunk_bytes_iter(iterator, chunk_len: int, stride: tuple[int, int], stream: bool = False):
+ """
+ Reads raw bytes from an iterator and does chunks of length `chunk_len`. Optionally adds `stride` to each chunks to
+ get overlaps. `stream` is used to return partial results even if a full `chunk_len` is not yet available.
+ """
+ acc = b""
+ stride_left, stride_right = stride
+ if stride_left + stride_right >= chunk_len:
+ raise ValueError(
+ f"Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}"
+ )
+ _stride_left = 0
+ for raw in iterator:
+ acc += raw
+ if stream and len(acc) < chunk_len:
+ stride = (_stride_left, 0)
+ yield {"raw": acc[:chunk_len], "stride": stride, "partial": True}
+ else:
+ while len(acc) >= chunk_len:
+ # We are flushing the accumulator
+ stride = (_stride_left, stride_right)
+ item = {"raw": acc[:chunk_len], "stride": stride}
+ if stream:
+ item["partial"] = False
+ yield item
+ _stride_left = stride_left
+ acc = acc[chunk_len - stride_left - stride_right :]
+ # Last chunk
+ if len(acc) > stride_left:
+ item = {"raw": acc, "stride": (_stride_left, 0)}
+ if stream:
+ item["partial"] = False
+ yield item
+
+
+def _ffmpeg_stream(ffmpeg_command, buflen: int):
+ """
+ Internal function to create the generator of data through ffmpeg
+ """
+ bufsize = 2**24 # 16Mo
+ try:
+ with subprocess.Popen(ffmpeg_command, stdout=subprocess.PIPE, bufsize=bufsize) as ffmpeg_process:
+ while True:
+ raw = ffmpeg_process.stdout.read(buflen)
+ if raw == b"":
+ break
+ yield raw
+ except FileNotFoundError as error:
+ raise ValueError("ffmpeg was not found but is required to stream audio files from filename") from error
+
+
+def _get_microphone_name():
+ """
+ Retrieve the microphone name in Windows .
+ """
+ command = ["ffmpeg", "-list_devices", "true", "-f", "dshow", "-i", ""]
+
+ try:
+ ffmpeg_devices = subprocess.run(command, text=True, stderr=subprocess.PIPE, encoding="utf-8")
+ microphone_lines = [line for line in ffmpeg_devices.stderr.splitlines() if "(audio)" in line]
+
+ if microphone_lines:
+ microphone_name = microphone_lines[0].split('"')[1]
+ print(f"Using microphone: {microphone_name}")
+ return f"audio={microphone_name}"
+ except FileNotFoundError:
+ print("ffmpeg was not found. Please install it or make sure it is in your system PATH.")
+
+ return "default"
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/automatic_speech_recognition.py b/.venv/lib/python3.12/site-packages/transformers/pipelines/automatic_speech_recognition.py
new file mode 100644
index 0000000000000000000000000000000000000000..63f7e718909b3d85ae855bfd537d584c741d7a53
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/pipelines/automatic_speech_recognition.py
@@ -0,0 +1,710 @@
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from collections import defaultdict
+from typing import TYPE_CHECKING, Any, Union
+
+import httpx
+import numpy as np
+
+from ..generation import GenerationConfig
+from ..tokenization_python import PreTrainedTokenizer
+from ..utils import is_torch_available, is_torchaudio_available, is_torchcodec_available, logging
+from .audio_utils import ffmpeg_read
+from .base import ChunkPipeline
+
+
+if TYPE_CHECKING:
+ from pyctcdecode import BeamSearchDecoderCTC
+
+ from ..feature_extraction_sequence_utils import SequenceFeatureExtractor
+ from ..modeling_utils import PreTrainedModel
+
+logger = logging.get_logger(__name__)
+
+if is_torch_available():
+ import torch
+
+ from ..models.auto.modeling_auto import MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES
+
+
+def rescale_stride(stride, ratio):
+ """
+ Rescales the stride values from audio space to tokens/logits space.
+
+ (160_000, 16_000, 16_000) -> (2000, 200, 200) for instance.
+ """
+ # Shape is [B, SEQ] for tokens
+ # [B, SEQ, V] for logits
+
+ new_strides = []
+ for input_n, left, right in stride:
+ token_n = int(round(input_n * ratio))
+ left = int(round(left / input_n * token_n))
+ right = int(round(right / input_n * token_n))
+ new_stride = (token_n, left, right)
+ new_strides.append(new_stride)
+
+ return new_strides
+
+
+def chunk_iter(inputs, feature_extractor, chunk_len, stride_left, stride_right, dtype=None):
+ inputs_len = inputs.shape[0]
+ step = chunk_len - stride_left - stride_right
+ for chunk_start_idx in range(0, inputs_len, step):
+ chunk_end_idx = chunk_start_idx + chunk_len
+ chunk = inputs[chunk_start_idx:chunk_end_idx]
+ processed = feature_extractor(
+ chunk,
+ sampling_rate=feature_extractor.sampling_rate,
+ return_tensors="pt",
+ return_attention_mask=True,
+ )
+ if dtype is not None:
+ processed = processed.to(dtype=dtype)
+ _stride_left = 0 if chunk_start_idx == 0 else stride_left
+ is_last = chunk_end_idx >= inputs_len
+ _stride_right = 0 if is_last else stride_right
+
+ chunk_len = chunk.shape[0]
+ stride = (chunk_len, _stride_left, _stride_right)
+ if chunk.shape[0] > _stride_left:
+ yield {"is_last": is_last, "stride": stride, **processed}
+ if is_last:
+ break
+
+
+def _find_longest_common_sequence(sequences, tokenizer):
+ # TODO Use a faster algorithm this can probably be done in O(n)
+ # using suffix array.
+ # It might be tedious to do because of fault tolerance.
+ # We actually have a really good property which is that the total sequence
+ # MUST be those subsequences in order.
+ # Also the algorithm should be more tolerant to errors.
+ sequence = [tok_id for tok_id in sequences[0][0].tolist() if tok_id not in tokenizer.all_special_ids]
+ for new_seq in sequences[1:]:
+ new_sequence = [tok_id for tok_id in new_seq[0].tolist() if tok_id not in tokenizer.all_special_ids]
+
+ index = 0
+ max_ = 0.0
+ for i in range(1, len(new_sequence) + 1):
+ # epsilon to favor long perfect matches
+ eps = i / 10000.0
+ matches = np.sum(np.array(sequence[-i:]) == np.array(new_sequence[:i]))
+ matching = matches / i + eps
+ if matches > 1 and matching > max_:
+ index = i
+ max_ = matching
+ sequence.extend(new_sequence[index:])
+ return np.array(sequence)
+
+
+class AutomaticSpeechRecognitionPipeline(ChunkPipeline):
+ """
+ Pipeline that aims at extracting spoken text contained within some audio.
+
+ The input can be either a raw waveform or a audio file. In case of the audio file, ffmpeg should be installed for
+ to support multiple audio formats
+
+ Unless the model you're using explicitly sets these generation parameters in its configuration files
+ (`generation_config.json`), the following default values will be used:
+ - max_new_tokens: 256
+ - num_beams: 5
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> transcriber = pipeline(model="openai/whisper-base")
+ >>> transcriber("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac")
+ {'text': ' He hoped there would be stew for dinner, turnips and carrots and bruised potatoes and fat mutton pieces to be ladled out in thick, peppered flour-fatten sauce.'}
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ Arguments:
+ model ([`PreTrainedModel`]):
+ The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from
+ [`PreTrainedModel`].
+ feature_extractor ([`SequenceFeatureExtractor`], *optional*):
+ The feature extractor that will be used by the pipeline to encode waveform for the model.
+ tokenizer ([`PreTrainedTokenizer`], *optional*):
+ The tokenizer that will be used by the pipeline to encode data for the model. This object inherits from
+ [`PreTrainedTokenizer`].
+ decoder (`pyctcdecode.BeamSearchDecoderCTC`, *optional*):
+ [PyCTCDecode's
+ BeamSearchDecoderCTC](https://github.com/kensho-technologies/pyctcdecode/blob/2fd33dc37c4111417e08d89ccd23d28e9b308d19/pyctcdecode/decoder.py#L180)
+ can be passed for language model boosted decoding. See [`Wav2Vec2ProcessorWithLM`] for more information.
+ device (Union[`int`, `torch.device`], *optional*):
+ Device ordinal for CPU/GPU supports. Setting this to `None` will leverage CPU, a positive will run the
+ model on the associated CUDA device id.
+ """
+
+ _pipeline_calls_generate = True
+ _load_processor = False
+ _load_image_processor = False
+ _load_feature_extractor = True
+ _load_tokenizer = True
+ # Make sure the docstring is updated when the default generation config is changed
+ _default_generation_config = GenerationConfig(
+ max_new_tokens=256,
+ num_beams=5, # follows openai's whisper implementation
+ )
+
+ def __init__(
+ self,
+ model: "PreTrainedModel",
+ feature_extractor: Union["SequenceFeatureExtractor", str] | None = None,
+ tokenizer: PreTrainedTokenizer | None = None,
+ decoder: Union["BeamSearchDecoderCTC", str] | None = None,
+ device: Union[int, "torch.device"] | None = None,
+ **kwargs,
+ ):
+ # set the model type so we can check we have the right pre- and post-processing parameters
+ if model.config.model_type == "whisper":
+ self.type = "seq2seq_whisper"
+ elif model.__class__.__name__ in MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES.values():
+ self.type = "seq2seq"
+ elif model.config.model_type in ("parakeet_tdt", "parakeet_rnnt"):
+ # Both Parakeet transducers decode the same way (generate -> sequences); "tdt" is the transducer path.
+ self.type = "tdt"
+ elif decoder is not None:
+ self.decoder = decoder
+ self.type = "ctc_with_lm"
+ else:
+ self.type = "ctc"
+
+ super().__init__(model, tokenizer, feature_extractor, device=device, **kwargs)
+
+ def __call__(self, inputs: np.ndarray | bytes | str | dict, **kwargs: Any) -> list[dict[str, Any]]:
+ """
+ Transcribe the audio sequence(s) given as inputs to text. See the [`AutomaticSpeechRecognitionPipeline`]
+ documentation for more information.
+
+ Args:
+ inputs (`np.ndarray` or `bytes` or `str` or `dict`):
+ The inputs is either :
+ - `str` that is either the filename of a local audio file, or a public URL address to download the
+ audio file. The file will be read at the correct sampling rate to get the waveform using
+ *ffmpeg*. This requires *ffmpeg* to be installed on the system.
+ - `bytes` it is supposed to be the content of an audio file and is interpreted by *ffmpeg* in the
+ same way.
+ - (`np.ndarray` of shape (n, ) of type `np.float32` or `np.float64`)
+ Raw audio at the correct sampling rate (no further check will be done)
+ - `dict` form can be used to pass raw audio sampled at arbitrary `sampling_rate` and let this
+ pipeline do the resampling. The dict must be in the format `{"sampling_rate": int, "raw":
+ np.array}` with optionally a `"stride": (left: int, right: int)` than can ask the pipeline to
+ treat the first `left` samples and last `right` samples to be ignored in decoding (but used at
+ inference to provide more context to the model). Only use `stride` with CTC models.
+ return_timestamps (*optional*, `str` or `bool`):
+ Only available for pure CTC models (Wav2Vec2, HuBERT, etc) and the Whisper model. Not available for
+ other sequence-to-sequence models.
+
+ For CTC models, timestamps can take one of two formats:
+ - `"char"`: the pipeline will return timestamps along the text for every character in the text. For
+ instance, if you get `[{"text": "h", "timestamp": (0.5, 0.6)}, {"text": "i", "timestamp": (0.7,
+ 0.9)}]`, then it means the model predicts that the letter "h" was spoken after `0.5` and before
+ `0.6` seconds.
+ - `"word"`: the pipeline will return timestamps along the text for every word in the text. For
+ instance, if you get `[{"text": "hi ", "timestamp": (0.5, 0.9)}, {"text": "there", "timestamp":
+ (1.0, 1.5)}]`, then it means the model predicts that the word "hi" was spoken after `0.5` and
+ before `0.9` seconds.
+
+ For the Whisper model, timestamps can take one of two formats:
+ - `"word"`: same as above for word-level CTC timestamps. Word-level timestamps are predicted
+ through the *dynamic-time warping (DTW)* algorithm, an approximation to word-level timestamps
+ by inspecting the cross-attention weights.
+ - `True`: the pipeline will return timestamps along the text for *segments* of words in the text.
+ For instance, if you get `[{"text": " Hi there!", "timestamp": (0.5, 1.5)}]`, then it means the
+ model predicts that the segment "Hi there!" was spoken after `0.5` and before `1.5` seconds.
+ Note that a segment of text refers to a sequence of one or more words, rather than individual
+ words as with word-level timestamps.
+ generate_kwargs (`dict`, *optional*):
+ The dictionary of ad-hoc parametrization of `generate_config` to be used for the generation call. For a
+ complete overview of generate, check the [following
+ guide](https://huggingface.co/docs/transformers/en/main_classes/text_generation).
+
+ Return:
+ `Dict`: A dictionary with the following keys:
+ - **text** (`str`): The recognized text.
+ - **chunks** (*optional(, `list[Dict]`)
+ When using `return_timestamps`, the `chunks` will become a list containing all the various text
+ chunks identified by the model, *e.g.* `[{"text": "hi ", "timestamp": (0.5, 0.9)}, {"text":
+ "there", "timestamp": (1.0, 1.5)}]`. The original full text can roughly be recovered by doing
+ `"".join(chunk["text"] for chunk in output["chunks"])`.
+ """
+ return super().__call__(inputs, **kwargs)
+
+ def _sanitize_parameters(
+ self,
+ chunk_length_s=None,
+ stride_length_s=None,
+ ignore_warning=None,
+ decoder_kwargs=None,
+ return_timestamps=None,
+ return_language=None,
+ **generate_kwargs,
+ ):
+ preprocess_params = {}
+ forward_params = {}
+ postprocess_params = {}
+
+ # Preprocess params
+ if chunk_length_s is not None:
+ if self.type in ["seq2seq", "seq2seq_whisper"] and not ignore_warning:
+ type_warning = (
+ "Using `chunk_length_s` is very experimental with seq2seq models. The results will not necessarily"
+ " be entirely accurate and will have caveats. More information:"
+ " https://github.com/huggingface/transformers/pull/20104. Ignore this warning with pipeline(...,"
+ " ignore_warning=True)."
+ )
+ if self.type == "seq2seq_whisper":
+ type_warning += (
+ " To use Whisper for long-form transcription, use rather the model's `generate` method directly "
+ "as the model relies on it's own chunking mechanism (cf. Whisper original paper, section 3.8. "
+ "Long-form Transcription)."
+ )
+ logger.warning(type_warning)
+ preprocess_params["chunk_length_s"] = chunk_length_s
+ if stride_length_s is not None:
+ preprocess_params["stride_length_s"] = stride_length_s
+
+ # Forward params
+ # BC: accept a dictionary of generation kwargs (as opposed to **generate_kwargs)
+ if "generate_kwargs" in generate_kwargs:
+ forward_params.update(generate_kwargs.pop("generate_kwargs"))
+ # Default use for kwargs: they are generation-time kwargs
+ forward_params.update(generate_kwargs)
+
+ if getattr(self, "assistant_model", None) is not None:
+ forward_params["assistant_model"] = self.assistant_model
+ if getattr(self, "assistant_tokenizer", None) is not None:
+ forward_params["tokenizer"] = self.tokenizer
+ forward_params["assistant_tokenizer"] = self.assistant_tokenizer
+
+ # Postprocess params
+ if decoder_kwargs is not None:
+ postprocess_params["decoder_kwargs"] = decoder_kwargs
+ if return_language is not None:
+ if self.type != "seq2seq_whisper":
+ raise ValueError("Only Whisper can return language for now.")
+ postprocess_params["return_language"] = return_language
+ forward_params["return_language"] = return_language
+
+ # Parameter used in more than one place
+ # in some models like whisper, the generation config has a `return_timestamps` key
+ if hasattr(self, "generation_config") and hasattr(self.generation_config, "return_timestamps"):
+ return_timestamps = return_timestamps or self.generation_config.return_timestamps
+
+ if return_timestamps is not None:
+ # Check whether we have a valid setting for return_timestamps and throw an error before we perform a forward pass
+ if self.type == "seq2seq" and return_timestamps:
+ raise ValueError("We cannot return_timestamps yet on non-CTC models apart from Whisper!")
+ if self.type == "ctc_with_lm" and return_timestamps != "word":
+ raise ValueError("CTC with LM can only predict word level timestamps, set `return_timestamps='word'`")
+ if self.type == "ctc" and return_timestamps not in ["char", "word"]:
+ raise ValueError(
+ "CTC can either predict character level timestamps, or word level timestamps. "
+ "Set `return_timestamps='char'` or `return_timestamps='word'` as required."
+ )
+ if self.type == "seq2seq_whisper" and return_timestamps == "char":
+ raise ValueError(
+ "Whisper cannot return `char` timestamps, only word level or segment level timestamps. "
+ "Use `return_timestamps='word'` or `return_timestamps=True` respectively."
+ )
+ forward_params["return_timestamps"] = return_timestamps
+ postprocess_params["return_timestamps"] = return_timestamps
+
+ return preprocess_params, forward_params, postprocess_params
+
+ @property
+ def _align_to(self):
+ """Sample stride per output."""
+ # XXX: Carefully, this variable will not exist in `seq2seq` setting.
+ # Currently chunking is not possible at this level for `seq2seq` so
+ # it's ok.
+ align_to = getattr(self.model.config, "inputs_to_logits_ratio", 1)
+ if self.model.config.model_type == "lasr_ctc":
+ # TODO: find a standard for that but not easy because input length -> mel length depends on the feature extractor
+ # specific way of doing it
+ # means the model take mel features as input, we align according to the hop length
+ align_to *= self.feature_extractor.hop_length
+ return align_to
+
+ def preprocess(self, inputs, chunk_length_s=0, stride_length_s=None):
+ if isinstance(inputs, str):
+ if inputs.startswith("http://") or inputs.startswith("https://"):
+ # We need to actually check for a real protocol, otherwise it's impossible to use a local file
+ # like http_huggingface_co.png
+ inputs = httpx.get(inputs, follow_redirects=True).content
+ else:
+ with open(inputs, "rb") as f:
+ inputs = f.read()
+
+ if isinstance(inputs, bytes):
+ inputs = ffmpeg_read(inputs, self.feature_extractor.sampling_rate)
+
+ stride = None
+ extra = {}
+
+ if is_torch_available():
+ import torch
+
+ if isinstance(inputs, torch.Tensor):
+ inputs = inputs.cpu().numpy()
+
+ if is_torchcodec_available():
+ import torchcodec
+
+ if isinstance(inputs, torchcodec.decoders.AudioDecoder):
+ _audio_samples = inputs.get_all_samples()
+
+ # torchcodec always returns (num_channels, num_samples)
+ # while before (datasets < 4.0) we had (2, num_samples) if stereo, (num_samples,) if mono
+ _array = _audio_samples.data
+ _array = _array[0] if _array.ndim == 2 and _array.shape[0] == 1 else _array
+ inputs = {"array": _array, "sampling_rate": _audio_samples.sample_rate}
+
+ if isinstance(inputs, dict):
+ stride = inputs.pop("stride", None)
+ # Accepting `"array"` which is the key defined in `datasets` for
+ # better integration
+ if not ("sampling_rate" in inputs and ("raw" in inputs or "array" in inputs)):
+ raise ValueError(
+ "When passing a dictionary to AutomaticSpeechRecognitionPipeline, the dict needs to contain a "
+ '"raw" key containing the numpy array or torch tensor representing the audio and a "sampling_rate" key, '
+ "containing the sampling_rate associated with that array"
+ )
+
+ _inputs = inputs.pop("raw", None)
+ if _inputs is None:
+ # Remove path which will not be used from `datasets`.
+ inputs.pop("path", None)
+ _inputs = inputs.pop("array", None)
+ in_sampling_rate = inputs.pop("sampling_rate")
+ extra = inputs
+ inputs = _inputs
+ if in_sampling_rate != self.feature_extractor.sampling_rate:
+ if is_torchaudio_available():
+ from torchaudio import functional as F
+ else:
+ raise ImportError(
+ "torchaudio is required to resample audio samples in AutomaticSpeechRecognitionPipeline. "
+ "The torchaudio package can be installed through: `pip install torchaudio`."
+ )
+
+ inputs = F.resample(
+ torch.from_numpy(inputs) if isinstance(inputs, np.ndarray) else inputs,
+ in_sampling_rate,
+ self.feature_extractor.sampling_rate,
+ ).numpy()
+ ratio = self.feature_extractor.sampling_rate / in_sampling_rate
+ else:
+ ratio = 1
+ if stride is not None:
+ if stride[0] + stride[1] > inputs.shape[0]:
+ raise ValueError("Stride is too large for input")
+
+ # Stride needs to get the chunk length here, it's going to get
+ # swallowed by the `feature_extractor` later, and then batching
+ # can add extra data in the inputs, so we need to keep track
+ # of the original length in the stride so we can cut properly.
+ stride = (inputs.shape[0], int(round(stride[0] * ratio)), int(round(stride[1] * ratio)))
+ if not isinstance(inputs, (np.ndarray, torch.Tensor)):
+ raise TypeError(f"We expect a numpy ndarray or torch tensor as input, got `{type(inputs)}`")
+ if inputs.ndim != 1:
+ logger.warning(
+ f"We expect a single channel audio input for AutomaticSpeechRecognitionPipeline, got {inputs.ndim}. Taking the mean of the channels for mono conversion."
+ )
+ inputs = inputs.mean(axis=0)
+
+ if chunk_length_s:
+ if stride_length_s is None:
+ stride_length_s = chunk_length_s / 6
+
+ if isinstance(stride_length_s, (int, float)):
+ stride_length_s = [stride_length_s, stride_length_s]
+
+ align_to = self._align_to
+ chunk_len = int(round(chunk_length_s * self.feature_extractor.sampling_rate / align_to) * align_to)
+ stride_left = int(round(stride_length_s[0] * self.feature_extractor.sampling_rate / align_to) * align_to)
+ stride_right = int(round(stride_length_s[1] * self.feature_extractor.sampling_rate / align_to) * align_to)
+
+ if chunk_len < stride_left + stride_right:
+ raise ValueError("Chunk length must be superior to stride length")
+
+ for item in chunk_iter(inputs, self.feature_extractor, chunk_len, stride_left, stride_right, self.dtype):
+ yield {**item, **extra}
+ else:
+ if self.type == "seq2seq_whisper" and inputs.shape[0] > self.feature_extractor.n_samples:
+ processed = self.feature_extractor(
+ inputs,
+ sampling_rate=self.feature_extractor.sampling_rate,
+ truncation=False,
+ padding="longest",
+ return_tensors="pt",
+ return_attention_mask=True,
+ )
+ else:
+ if self.type == "seq2seq_whisper" and stride is None:
+ processed = self.feature_extractor(
+ inputs,
+ sampling_rate=self.feature_extractor.sampling_rate,
+ return_tensors="pt",
+ return_attention_mask=True,
+ )
+ else:
+ processed = self.feature_extractor(
+ inputs,
+ sampling_rate=self.feature_extractor.sampling_rate,
+ return_tensors="pt",
+ return_attention_mask=True,
+ )
+ if self.dtype is not None:
+ processed = processed.to(dtype=self.dtype)
+ if stride is not None:
+ if self.type == "seq2seq":
+ raise ValueError("Stride is only usable with CTC models, try removing it !")
+
+ processed["stride"] = stride
+ yield {"is_last": True, **processed, **extra}
+
+ def _forward(self, model_inputs, return_timestamps=False, return_language=None, **generate_kwargs):
+ attention_mask = model_inputs.pop("attention_mask", None)
+ stride = model_inputs.pop("stride", None)
+ num_frames = model_inputs.pop("num_frames", None)
+ is_last = model_inputs.pop("is_last")
+
+ if stride is not None and num_frames is not None:
+ raise ValueError("num_frames must be used only when stride is None")
+
+ if self.type in {"seq2seq", "seq2seq_whisper"}:
+ # Consume values so we can let extra information flow freely through
+ # the pipeline (important for `partial` in microphone)
+ if "input_features" in model_inputs:
+ inputs = model_inputs.pop("input_features")
+ elif "input_values" in model_inputs:
+ inputs = model_inputs.pop("input_values")
+ else:
+ raise ValueError(
+ "Seq2Seq speech recognition model requires either a "
+ f"`input_features` or `input_values` key, but only has {model_inputs.keys()}"
+ )
+
+ # custom processing for Whisper timestamps and word-level timestamps
+ return_timestamps = return_timestamps or getattr(self.generation_config, "return_timestamps", False)
+ if return_timestamps and self.type == "seq2seq_whisper":
+ generate_kwargs["return_timestamps"] = bool(return_timestamps)
+ if return_timestamps == "word":
+ generate_kwargs["return_token_timestamps"] = True
+ generate_kwargs["return_segments"] = True
+
+ # User-defined `generation_config` passed to the pipeline call take precedence
+ if "generation_config" not in generate_kwargs:
+ generate_kwargs["generation_config"] = self.generation_config
+
+ main_input_name = self.model.main_input_name if hasattr(self.model, "main_input_name") else "inputs"
+ generate_kwargs = {
+ main_input_name: inputs,
+ "attention_mask": attention_mask,
+ **generate_kwargs,
+ }
+ # When return_language is requested, use return_segments to retrieve
+ # the full generated sequences (including init tokens with the language token)
+ # since generate() strips them from the main output.
+ if return_language and self.type == "seq2seq_whisper":
+ generate_kwargs["return_segments"] = True
+
+ tokens = self.model.generate(**generate_kwargs)
+
+ # whisper longform generation stores timestamps in "segments"
+ if return_timestamps == "word" and self.type == "seq2seq_whisper":
+ if "segments" not in tokens:
+ out = {"tokens": tokens["sequences"], "token_timestamps": tokens["token_timestamps"]}
+ else:
+ token_timestamps = [
+ torch.cat([segment["token_timestamps"] for segment in segment_list])
+ for segment_list in tokens["segments"]
+ ]
+ out = {"tokens": tokens["sequences"], "token_timestamps": token_timestamps}
+ elif isinstance(tokens, dict) and "sequences" in tokens:
+ out = {"tokens": tokens["sequences"]}
+ else:
+ out = {"tokens": tokens}
+ if self.type == "seq2seq_whisper":
+ if stride is not None:
+ out["stride"] = stride
+ if return_language and isinstance(tokens, dict) and "segments" in tokens:
+ # Extract the language token from the full unstripped sequence
+ # stored in segments[batch][segment]["result"]. The result is either
+ # a 1D tensor (full sequence) or a dict with a "sequences" key.
+ segments = tokens["segments"]
+ if segments and segments[0]:
+ result = segments[0][0]["result"]
+ full_seq = result["sequences"] if isinstance(result, dict) else result
+ gen_config = generate_kwargs.get("generation_config", self.generation_config)
+ if hasattr(gen_config, "lang_to_id"):
+ lang_ids = set(gen_config.lang_to_id.values())
+ for token_id in full_seq.tolist():
+ if token_id in lang_ids:
+ out["lang_id"] = torch.tensor([token_id])
+ break
+
+ elif self.type in {"ctc", "ctc_with_lm"}:
+ inputs = {
+ self.model.main_input_name: model_inputs.pop(self.model.main_input_name),
+ "attention_mask": attention_mask,
+ }
+ outputs = self.model(**inputs)
+ logits = outputs.logits
+
+ if self.type == "ctc_with_lm":
+ out = {"logits": logits}
+ else:
+ out = {"tokens": logits.argmax(dim=-1)}
+ if stride is not None:
+ # Send stride to `postprocess`.
+ # it needs to be handled there where
+ # the pieces are to be concatenated.
+ ratio = 1 / self._align_to
+ if isinstance(stride, tuple):
+ out["stride"] = rescale_stride([stride], ratio)[0]
+ else:
+ out["stride"] = rescale_stride(stride, ratio)
+ elif self.type == "tdt":
+ inputs = {
+ self.model.main_input_name: model_inputs.pop(self.model.main_input_name),
+ }
+ if "attention_mask" in model_inputs:
+ inputs["attention_mask"] = model_inputs.pop("attention_mask")
+ outputs = self.model.generate(**inputs)
+ out = {"tokens": outputs.sequences}
+ else:
+ raise ValueError(f"Unsupported model type {self.type}.")
+
+ # Leftover
+ extra = model_inputs
+ return {"is_last": is_last, **out, **extra}
+
+ def postprocess(
+ self, model_outputs, decoder_kwargs: dict | None = None, return_timestamps=None, return_language=None
+ ):
+ # Optional return types
+ optional = {}
+
+ final_items = []
+ key = "logits" if self.type == "ctc_with_lm" else "tokens"
+ stride = None
+ for outputs in model_outputs:
+ if outputs[key].dtype in (torch.bfloat16, torch.float16):
+ items = outputs[key].to(torch.float32).numpy()
+ else:
+ items = outputs[key].numpy()
+ stride = outputs.get("stride", None)
+ if stride is not None and self.type in {"ctc", "ctc_with_lm"}:
+ total_n, left, right = stride
+ # Total_n might be < logits.shape[1]
+ # because of padding, that's why
+ # we need to reconstruct this information
+ # This won't work with left padding (which doesn't exist right now)
+ right_n = total_n - right
+ items = items[:, left:right_n]
+ final_items.append(items)
+
+ if stride and self.type == "seq2seq":
+ items = _find_longest_common_sequence(final_items, self.tokenizer)
+ elif self.type == "seq2seq_whisper":
+ time_precision = self.feature_extractor.chunk_length / self.model.config.max_source_positions
+ # Send the chunking back to seconds, it's easier to handle in whisper
+ sampling_rate = self.feature_extractor.sampling_rate
+ for output in model_outputs:
+ if "stride" in output:
+ chunk_len, stride_left, stride_right = output["stride"]
+ # Go back in seconds
+ chunk_len /= sampling_rate
+ stride_left /= sampling_rate
+ stride_right /= sampling_rate
+ output["stride"] = chunk_len, stride_left, stride_right
+
+ # Since Whisper's generate() strips init tokens (including the language token)
+ # from the output, we need to re-prepend the detected language token so that
+ # _decode_asr can find it and populate the language field in chunks.
+ if return_language:
+ for output in model_outputs:
+ if "lang_id" in output:
+ lang_id = output["lang_id"]
+ if lang_id.dim() == 0:
+ lang_id = lang_id.unsqueeze(0)
+ lang_token = lang_id.unsqueeze(0).to(dtype=output["tokens"].dtype)
+ output["tokens"] = torch.cat([lang_token, output["tokens"]], dim=-1)
+
+ text, optional = self.tokenizer._decode_asr(
+ model_outputs,
+ return_timestamps=return_timestamps,
+ return_language=return_language,
+ time_precision=time_precision,
+ )
+ else:
+ items = np.concatenate(final_items, axis=1)
+ items = items.squeeze(0)
+
+ if self.type == "ctc_with_lm":
+ if decoder_kwargs is None:
+ decoder_kwargs = {}
+ beams = self.decoder.decode_beams(items, **decoder_kwargs)
+ text = beams[0][0]
+ if return_timestamps:
+ # Simply cast from pyctcdecode format to wav2vec2 format to leverage
+ # pre-existing code later
+ chunk_offset = beams[0][2]
+ offsets = []
+ for word, (start_offset, end_offset) in chunk_offset:
+ offsets.append({"word": word, "start_offset": start_offset, "end_offset": end_offset})
+ elif self.type != "seq2seq_whisper":
+ skip_special_tokens = self.type != "ctc"
+ # CTC collapses consecutive identical tokens (a token repeated across frames is one emission); the
+ # Parakeet transducers ("tdt") emit each token explicitly and must keep legitimate repeats.
+ decode_kwargs = {"group_tokens": False} if self.type == "tdt" else {}
+ text = self.tokenizer.decode(items, skip_special_tokens=skip_special_tokens, **decode_kwargs)
+ if return_timestamps:
+ offsets = self.tokenizer.decode(
+ items, skip_special_tokens=skip_special_tokens, output_char_offsets=True, **decode_kwargs
+ )["char_offsets"]
+ if return_timestamps == "word":
+ offsets = self.tokenizer._get_word_offsets(offsets, self.tokenizer.replace_word_delimiter_char)
+
+ if return_timestamps and self.type not in {"seq2seq", "seq2seq_whisper"}:
+ chunks = []
+ align_to = self._align_to
+ for item in offsets:
+ start = item["start_offset"] * align_to
+ start /= self.feature_extractor.sampling_rate
+
+ stop = item["end_offset"] * align_to
+ stop /= self.feature_extractor.sampling_rate
+
+ chunks.append({"text": item[return_timestamps], "timestamp": (start, stop)})
+ optional["chunks"] = chunks
+
+ extra = defaultdict(list)
+ for output in model_outputs:
+ output.pop("tokens", None)
+ output.pop("logits", None)
+ output.pop("is_last", None)
+ output.pop("stride", None)
+ output.pop("token_timestamps", None)
+ output.pop("lang_id", None)
+ for k, v in output.items():
+ extra[k].append(v)
+ return {"text": text, **optional, **extra}
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/base.py b/.venv/lib/python3.12/site-packages/transformers/pipelines/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f05f2a4cb6ee42731a4f64f31552ce48f480a21
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/pipelines/base.py
@@ -0,0 +1,1382 @@
+# Copyright 2018 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from __future__ import annotations
+
+import collections
+import copy
+import csv
+import importlib
+import json
+import os
+import pickle
+import sys
+import traceback
+import types
+from abc import ABC, abstractmethod
+from collections import UserDict
+from contextlib import contextmanager
+from os.path import abspath, exists
+from typing import TYPE_CHECKING, Any, Union
+
+from ..dynamic_module_utils import custom_object_save
+from ..feature_extraction_utils import PreTrainedFeatureExtractor
+from ..generation import GenerationConfig
+from ..image_processing_utils import BaseImageProcessor
+from ..models.auto import AutoConfig, AutoTokenizer
+from ..processing_utils import ProcessorMixin
+from ..tokenization_python import PreTrainedTokenizer
+from ..utils import (
+ ModelOutput,
+ PushToHubMixin,
+ add_end_docstrings,
+ copy_func,
+ is_torch_available,
+ is_torch_cuda_available,
+ is_torch_hpu_available,
+ is_torch_mlu_available,
+ is_torch_mps_available,
+ is_torch_musa_available,
+ is_torch_npu_available,
+ is_torch_xpu_available,
+ logging,
+)
+from ..utils.chat_template_utils import Chat, is_valid_message
+from ..video_processing_utils import BaseVideoProcessor
+
+
+GenericTensor = Union[list["GenericTensor"], "torch.Tensor"]
+
+if is_torch_available() or TYPE_CHECKING:
+ import torch
+ from torch.utils.data import DataLoader, Dataset
+
+ from ..modeling_utils import PreTrainedModel
+ from .pt_utils import KeyDataset
+else:
+ Dataset = None
+
+
+logger = logging.get_logger(__name__)
+
+
+def no_collate_fn(items):
+ if len(items) != 1:
+ raise ValueError("This collate_fn is meant to be used with batch_size=1")
+ return items[0]
+
+
+def _pad(items, key, padding_value, padding_side):
+ batch_size = len(items)
+ if isinstance(items[0][key], torch.Tensor):
+ # Others include `attention_mask` etc...
+ shape = items[0][key].shape
+ dim = items[0][key].ndim
+ if dim == 1:
+ # We have a list of 1-dim torch tensors, which can be stacked without padding
+ return torch.cat([item[key] for item in items], dim=0)
+ if key in ["pixel_values", "image"]:
+ # This is probable image so padding shouldn't be necessary
+ # B, C, H, W
+ return torch.cat([item[key] for item in items], dim=0)
+ elif dim == 4 and key == "input_features":
+ # this is probably a mel spectrogram batched
+ return torch.cat([item[key] for item in items], dim=0)
+ max_length = max(item[key].shape[1] for item in items)
+ min_length = min(item[key].shape[1] for item in items)
+ dtype = items[0][key].dtype
+
+ if dim == 2 and max_length == min_length:
+ # Bypass for `ImageGPT` which doesn't provide a padding value, yet
+ # we can consistently pad since the size should be matching
+ return torch.cat([item[key] for item in items], dim=0)
+ else:
+ tensor = torch.full([batch_size, max_length] + list(shape[2:]), fill_value=padding_value, dtype=dtype)
+
+ for i, item in enumerate(items):
+ if padding_side == "left":
+ tensor[i, -len(item[key][0]) :] = item[key][0]
+ else:
+ tensor[i, : len(item[key][0])] = item[key][0]
+
+ return tensor
+ else:
+ return [item[key] for item in items]
+
+
+def pad_collate_fn(tokenizer, feature_extractor):
+ # Tokenizer
+ t_padding_side = None
+ # Feature extractor
+ f_padding_side = None
+ if tokenizer is None and feature_extractor is None:
+ raise ValueError("Pipeline without tokenizer or feature_extractor cannot do batching")
+ if tokenizer is not None:
+ if tokenizer.pad_token_id is None:
+ raise ValueError(
+ "Pipeline with tokenizer without pad_token cannot do batching. You can try to set it with "
+ "`pipe.tokenizer.pad_token_id = model.config.eos_token_id`."
+ )
+ else:
+ t_padding_value = tokenizer.pad_token_id
+ t_padding_side = tokenizer.padding_side
+ if feature_extractor is not None:
+ # Feature extractor can be images, where no padding is expected
+ f_padding_value = getattr(feature_extractor, "padding_value", None)
+ f_padding_side = getattr(feature_extractor, "padding_side", None)
+
+ if t_padding_side is not None and f_padding_side is not None and t_padding_side != f_padding_side:
+ raise ValueError(
+ f"The feature extractor, and tokenizer don't agree on padding side {t_padding_side} != {f_padding_side}"
+ )
+ padding_side = "right"
+ if t_padding_side is not None:
+ padding_side = t_padding_side
+ if f_padding_side is not None:
+ padding_side = f_padding_side
+
+ def inner(items):
+ keys = set(items[0].keys())
+ for item in items:
+ if set(item.keys()) != keys:
+ raise ValueError(
+ f"The elements of the batch contain different keys. Cannot batch them ({set(item.keys())} !="
+ f" {keys})"
+ )
+ # input_values, input_pixels, input_ids, ...
+ padded = {}
+ for key in keys:
+ if key == "input_ids":
+ # ImageGPT uses a feature extractor
+ if tokenizer is None and feature_extractor is not None:
+ _padding_value = f_padding_value
+ else:
+ _padding_value = t_padding_value
+ elif key in {"input_values", "pixel_values", "input_features"}:
+ _padding_value = f_padding_value
+ elif key in {"p_mask", "special_tokens_mask"}:
+ _padding_value = 1
+ elif key in {"attention_mask", "token_type_ids"}:
+ _padding_value = 0
+ else:
+ # This is likely another random key maybe even user provided
+ _padding_value = 0
+ padded[key] = _pad(items, key, _padding_value, padding_side)
+ return padded
+
+ return inner
+
+
+def load_model(
+ model,
+ config: AutoConfig,
+ model_classes: tuple[type, ...] | None = None,
+ task: str | None = None,
+ **model_kwargs,
+):
+ """
+ Load a model.
+
+ If `model` is instantiated, this function will just return it. Otherwise `model` is
+ actually a checkpoint name and this method will try to instantiate it using `model_classes`. Since we don't want to
+ instantiate the model twice, this model is returned for use by the pipeline.
+
+ Args:
+ model (`str`, or [`PreTrainedModel`]):
+ If `str`, a checkpoint name. The model to load.
+ config ([`AutoConfig`]):
+ The config associated with the model to help using the correct class
+ model_classes (`tuple[type]`, *optional*):
+ A tuple of model classes.
+ task (`str`):
+ The task defining which pipeline will be returned.
+ model_kwargs:
+ Additional dictionary of keyword arguments passed along to the model's `from_pretrained(...,
+ **model_kwargs)` function.
+
+ Returns:
+ The model.
+ """
+ if not is_torch_available():
+ raise RuntimeError("PyTorch should be installed. Please follow the instructions at https://pytorch.org/.")
+
+ if isinstance(model, str):
+ model_kwargs["_from_pipeline"] = task
+ class_tuple = model_classes if model_classes is not None else ()
+ if config.architectures:
+ classes = []
+ for architecture in config.architectures:
+ transformers_module = importlib.import_module("transformers")
+ _class = getattr(transformers_module, architecture, None)
+ if _class is not None:
+ classes.append(_class)
+ class_tuple = class_tuple + tuple(classes)
+
+ if len(class_tuple) == 0:
+ raise ValueError(f"Pipeline cannot infer suitable model classes from {model}")
+
+ all_traceback = {}
+ for model_class in class_tuple:
+ kwargs = model_kwargs.copy()
+
+ try:
+ model = model_class.from_pretrained(model, **kwargs)
+ # Stop loading on the first successful load.
+ break
+ except (OSError, ValueError, TypeError, RuntimeError):
+ # `from_pretrained` may raise a `TypeError` or `RuntimeError` when the requested `dtype`
+ # is not supported on the execution device (e.g. bf16 on a consumer GPU). We capture those so
+ # we can transparently retry the load in float32 before surfacing an error to the user.
+ fallback_tried = False
+ if "dtype" in kwargs:
+ import torch
+
+ fallback_tried = True
+ fp32_kwargs = kwargs.copy()
+ fp32_kwargs["dtype"] = torch.float32
+
+ try:
+ model = model_class.from_pretrained(model, **fp32_kwargs)
+ logger.warning(
+ "Falling back to torch.float32 because loading with the original dtype failed on the"
+ " target device."
+ )
+ break
+ except Exception:
+ # If it still fails, capture the traceback and continue to the next class.
+ all_traceback[model_class.__name__] = traceback.format_exc()
+ continue
+
+ # If no fallback was attempted or it also failed, record the original traceback.
+ if not fallback_tried:
+ all_traceback[model_class.__name__] = traceback.format_exc()
+ continue
+
+ if isinstance(model, str):
+ error = ""
+ for class_name, trace in all_traceback.items():
+ error += f"while loading with {class_name}, an error is thrown:\n{trace}\n"
+ raise ValueError(
+ f"Could not load model {model} with any of the following classes: {class_tuple}. See the original errors:\n\n{error}\n"
+ )
+
+ return model
+
+
+def get_default_model_and_revision(targeted_task: dict, task_options: Any | None) -> tuple[str, str]:
+ """
+ Select a default model to use for a given task.
+
+ Args:
+ targeted_task (`Dict`):
+ Dictionary representing the given task, that should contain default models
+
+ task_options (`Any`, None)
+ Any further value required by the task to get fully specified.
+
+ Returns
+
+ Tuple:
+ - `str` The model string representing the default model for this pipeline.
+ - `str` The revision of the model.
+ """
+ defaults = targeted_task["default"]
+ if task_options:
+ if task_options not in defaults:
+ raise ValueError(f"The task does not provide any default models for options {task_options}")
+ default_models = defaults[task_options]["model"]
+ elif "model" in defaults:
+ default_models = targeted_task["default"]["model"]
+ else:
+ raise ValueError("The task defaults can't be correctly selected.")
+
+ return default_models
+
+
+def load_assistant_model(
+ model: PreTrainedModel,
+ assistant_model: str | PreTrainedModel | None,
+ assistant_tokenizer: PreTrainedTokenizer | None,
+) -> tuple[PreTrainedModel | None, PreTrainedTokenizer | None]:
+ """
+ Prepares the assistant model and the assistant tokenizer for a pipeline whose model that can call `generate`.
+
+ Args:
+ model ([`PreTrainedModel`]):
+ The main model that will be used by the pipeline to make predictions.
+ assistant_model (`str` or [`PreTrainedModel`], *optional*):
+ The assistant model that will be used by the pipeline to make predictions.
+ assistant_tokenizer ([`PreTrainedTokenizer`], *optional*):
+ The assistant tokenizer that will be used by the pipeline to encode data for the model.
+
+ Returns:
+ Tuple: The loaded assistant model and (optionally) the loaded tokenizer.
+ """
+ if not model.can_generate() or assistant_model is None:
+ return None, None
+
+ # If the model is passed as a string, load the model and the corresponding tokenizer
+ if isinstance(assistant_model, str):
+ assistant_config = AutoConfig.from_pretrained(assistant_model)
+ loaded_assistant_model = load_model(assistant_model, config=assistant_config)
+ loaded_assistant_model = loaded_assistant_model.to(device=model.device, dtype=model.dtype)
+ loaded_assistant_tokenizer = AutoTokenizer.from_pretrained(assistant_model)
+ else:
+ loaded_assistant_model = assistant_model
+ loaded_assistant_tokenizer = assistant_tokenizer
+
+ # Finally, let's check the tokenizers: if the two models have different tokenizers, we need to keep the assistant
+ # tokenizer
+ model_text_config = model.config.get_text_config()
+ assistant_text_config = loaded_assistant_model.config.get_text_config()
+ same_vocab_size = model_text_config.vocab_size == assistant_text_config.vocab_size
+ same_special_tokens = all(
+ getattr(model_text_config, token) == getattr(assistant_text_config, token)
+ for token in ("eos_token_id", "pad_token_id", "bos_token_id")
+ )
+ if same_vocab_size and same_special_tokens:
+ loaded_assistant_tokenizer = None
+ elif loaded_assistant_tokenizer is None:
+ raise ValueError(
+ "The assistant model has a different tokenizer than the main model. You should pass the assistant "
+ "tokenizer."
+ )
+
+ return loaded_assistant_model, loaded_assistant_tokenizer
+
+
+class PipelineException(Exception):
+ """
+ Raised by a [`Pipeline`] when handling __call__.
+
+ Args:
+ task (`str`): The task of the pipeline.
+ model (`str`): The model used by the pipeline.
+ reason (`str`): The error message to display.
+ """
+
+ def __init__(self, task: str, model: str, reason: str):
+ super().__init__(reason)
+
+ self.task = task
+ self.model = model
+
+
+class ArgumentHandler(ABC):
+ """
+ Base interface for handling arguments for each [`~pipelines.Pipeline`].
+ """
+
+ @abstractmethod
+ def __call__(self, *args, **kwargs):
+ raise NotImplementedError()
+
+
+class PipelineDataFormat:
+ """
+ Base class for all the pipeline supported data format both for reading and writing. Supported data formats
+ currently includes:
+
+ - JSON
+ - CSV
+ - stdin/stdout (pipe)
+
+ `PipelineDataFormat` also includes some utilities to work with multi-columns like mapping from datasets columns to
+ pipelines keyword arguments through the `dataset_kwarg_1=dataset_column_1` format.
+
+ Args:
+ output_path (`str`): Where to save the outgoing data.
+ input_path (`str`): Where to look for the input data.
+ column (`str`): The column to read.
+ overwrite (`bool`, *optional*, defaults to `False`):
+ Whether or not to overwrite the `output_path`.
+ """
+
+ SUPPORTED_FORMATS = ["json", "csv", "pipe"]
+
+ def __init__(
+ self,
+ output_path: str | None,
+ input_path: str | None,
+ column: str | None,
+ overwrite: bool = False,
+ ):
+ self.output_path = output_path
+ self.input_path = input_path
+ self.column = column.split(",") if column is not None else [""]
+ self.is_multi_columns = len(self.column) > 1
+
+ if self.is_multi_columns:
+ self.column = [tuple(c.split("=")) if "=" in c else (c, c) for c in self.column]
+
+ if output_path is not None and not overwrite:
+ if exists(abspath(self.output_path)):
+ raise OSError(f"{self.output_path} already exists on disk")
+
+ if input_path is not None:
+ if not exists(abspath(self.input_path)):
+ raise OSError(f"{self.input_path} doesn't exist on disk")
+
+ @abstractmethod
+ def __iter__(self):
+ raise NotImplementedError()
+
+ @abstractmethod
+ def save(self, data: dict | list[dict]):
+ """
+ Save the provided data object with the representation for the current [`~pipelines.PipelineDataFormat`].
+
+ Args:
+ data (`dict` or list of `dict`): The data to store.
+ """
+ raise NotImplementedError()
+
+ def save_binary(self, data: dict | list[dict]) -> str:
+ """
+ Save the provided data object as a pickle-formatted binary data on the disk.
+
+ Args:
+ data (`dict` or list of `dict`): The data to store.
+
+ Returns:
+ `str`: Path where the data has been saved.
+ """
+ path, _ = os.path.splitext(self.output_path)
+ binary_path = os.path.extsep.join((path, "pickle"))
+
+ with open(binary_path, "wb+") as f_output:
+ pickle.dump(data, f_output)
+
+ return binary_path
+
+ @staticmethod
+ def from_str(
+ format: str,
+ output_path: str | None,
+ input_path: str | None,
+ column: str | None,
+ overwrite=False,
+ ) -> PipelineDataFormat:
+ """
+ Creates an instance of the right subclass of [`~pipelines.PipelineDataFormat`] depending on `format`.
+
+ Args:
+ format (`str`):
+ The format of the desired pipeline. Acceptable values are `"json"`, `"csv"` or `"pipe"`.
+ output_path (`str`, *optional*):
+ Where to save the outgoing data.
+ input_path (`str`, *optional*):
+ Where to look for the input data.
+ column (`str`, *optional*):
+ The column to read.
+ overwrite (`bool`, *optional*, defaults to `False`):
+ Whether or not to overwrite the `output_path`.
+
+ Returns:
+ [`~pipelines.PipelineDataFormat`]: The proper data format.
+ """
+ if format == "json":
+ return JsonPipelineDataFormat(output_path, input_path, column, overwrite=overwrite)
+ elif format == "csv":
+ return CsvPipelineDataFormat(output_path, input_path, column, overwrite=overwrite)
+ elif format == "pipe":
+ return PipedPipelineDataFormat(output_path, input_path, column, overwrite=overwrite)
+ else:
+ raise KeyError(f"Unknown reader {format} (Available reader are json/csv/pipe)")
+
+
+class CsvPipelineDataFormat(PipelineDataFormat):
+ """
+ Support for pipelines using CSV data format.
+
+ Args:
+ output_path (`str`): Where to save the outgoing data.
+ input_path (`str`): Where to look for the input data.
+ column (`str`): The column to read.
+ overwrite (`bool`, *optional*, defaults to `False`):
+ Whether or not to overwrite the `output_path`.
+ """
+
+ def __init__(
+ self,
+ output_path: str | None,
+ input_path: str | None,
+ column: str | None,
+ overwrite=False,
+ ):
+ super().__init__(output_path, input_path, column, overwrite=overwrite)
+
+ def __iter__(self):
+ with open(self.input_path, "r") as f:
+ reader = csv.DictReader(f)
+ for row in reader:
+ if self.is_multi_columns:
+ yield {k: row[c] for k, c in self.column}
+ else:
+ yield row[self.column[0]]
+
+ def save(self, data: list[dict]):
+ """
+ Save the provided data object with the representation for the current [`~pipelines.PipelineDataFormat`].
+
+ Args:
+ data (`list[dict]`): The data to store.
+ """
+ with open(self.output_path, "w") as f:
+ if len(data) > 0:
+ writer = csv.DictWriter(f, list(data[0].keys()))
+ writer.writeheader()
+ writer.writerows(data)
+
+
+class JsonPipelineDataFormat(PipelineDataFormat):
+ """
+ Support for pipelines using JSON file format.
+
+ Args:
+ output_path (`str`): Where to save the outgoing data.
+ input_path (`str`): Where to look for the input data.
+ column (`str`): The column to read.
+ overwrite (`bool`, *optional*, defaults to `False`):
+ Whether or not to overwrite the `output_path`.
+ """
+
+ def __init__(
+ self,
+ output_path: str | None,
+ input_path: str | None,
+ column: str | None,
+ overwrite=False,
+ ):
+ super().__init__(output_path, input_path, column, overwrite=overwrite)
+
+ with open(input_path, "r") as f:
+ self._entries = json.load(f)
+
+ def __iter__(self):
+ for entry in self._entries:
+ if self.is_multi_columns:
+ yield {k: entry[c] for k, c in self.column}
+ else:
+ yield entry[self.column[0]]
+
+ def save(self, data: dict):
+ """
+ Save the provided data object in a json file.
+
+ Args:
+ data (`dict`): The data to store.
+ """
+ with open(self.output_path, "w") as f:
+ json.dump(data, f)
+
+
+class PipedPipelineDataFormat(PipelineDataFormat):
+ """
+ Read data from piped input to the python process. For multi columns data, columns should separated by \t
+
+ If columns are provided, then the output will be a dictionary with {column_x: value_x}
+
+ Args:
+ output_path (`str`): Where to save the outgoing data.
+ input_path (`str`): Where to look for the input data.
+ column (`str`): The column to read.
+ overwrite (`bool`, *optional*, defaults to `False`):
+ Whether or not to overwrite the `output_path`.
+ """
+
+ def __iter__(self):
+ for line in sys.stdin:
+ # Split for multi-columns
+ if "\t" in line:
+ line = line.split("\t")
+ if self.column:
+ # Dictionary to map arguments
+ yield {kwargs: l for (kwargs, _), l in zip(self.column, line)}
+ else:
+ yield tuple(line)
+
+ # No dictionary to map arguments
+ else:
+ yield line
+
+ def save(self, data: dict):
+ """
+ Print the data.
+
+ Args:
+ data (`dict`): The data to store.
+ """
+ print(data)
+
+ def save_binary(self, data: dict | list[dict]) -> str:
+ if self.output_path is None:
+ raise KeyError(
+ "When using piped input on pipeline outputting large object requires an output file path. "
+ "Please provide such output path through --output argument."
+ )
+
+ return super().save_binary(data)
+
+
+class _ScikitCompat(ABC):
+ """
+ Interface layer for the Scikit and Keras compatibility.
+ """
+
+ @abstractmethod
+ def transform(self, X):
+ raise NotImplementedError()
+
+ @abstractmethod
+ def predict(self, X):
+ raise NotImplementedError()
+
+
+def build_pipeline_init_args(
+ has_tokenizer: bool = False,
+ has_feature_extractor: bool = False,
+ has_image_processor: bool = False,
+ has_video_processor: bool = False,
+ has_processor: bool = False,
+ supports_binary_output: bool = True,
+) -> str:
+ docstring = r"""
+ Arguments:
+ model ([`PreTrainedModel`]):
+ The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from
+ [`PreTrainedModel`]."""
+ if has_tokenizer:
+ docstring += r"""
+ tokenizer ([`PreTrainedTokenizer`]):
+ The tokenizer that will be used by the pipeline to encode data for the model. This object inherits from
+ [`PreTrainedTokenizer`]."""
+ if has_feature_extractor:
+ docstring += r"""
+ feature_extractor ([`SequenceFeatureExtractor`]):
+ The feature extractor that will be used by the pipeline to encode data for the model. This object inherits from
+ [`SequenceFeatureExtractor`]."""
+ if has_image_processor:
+ docstring += r"""
+ image_processor ([`BaseImageProcessor`]):
+ The image processor that will be used by the pipeline to encode data for the model. This object inherits from
+ [`BaseImageProcessor`]."""
+ if has_video_processor:
+ docstring += r"""
+ video_processor ([`BaseVideoProcessor`]):
+ The video processor that will be used by the pipeline to encode video data for the model. This object
+ inherits from [`BaseVideoProcessor`]."""
+ if has_processor:
+ docstring += r"""
+ processor ([`ProcessorMixin`]):
+ The processor that will be used by the pipeline to encode data for the model. This object inherits from
+ [`ProcessorMixin`]. Processor is a composite object that might contain `tokenizer`, `feature_extractor`, and
+ `image_processor`."""
+ docstring += r"""
+ task (`str`, defaults to `""`):
+ A task-identifier for the pipeline.
+ num_workers (`int`, *optional*, defaults to 8):
+ When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the number of
+ workers to be used.
+ batch_size (`int`, *optional*, defaults to 1):
+ When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the size of
+ the batch to use, for inference this is not always beneficial, please read [Batching with
+ pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) .
+ args_parser ([`~pipelines.ArgumentHandler`], *optional*):
+ Reference to the object in charge of parsing supplied pipeline parameters.
+ device (`int`, *optional*, defaults to -1):
+ Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on
+ the associated CUDA device id. You can pass native `torch.device` or a `str` too
+ dtype (`str` or `torch.dtype`, *optional*):
+ Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model
+ (`torch.float16`, `torch.bfloat16`, ... or `"auto"`)"""
+ if supports_binary_output:
+ docstring += r"""
+ binary_output (`bool`, *optional*, defaults to `False`):
+ Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as
+ the raw output data e.g. text."""
+ return docstring
+
+
+PIPELINE_INIT_ARGS = build_pipeline_init_args(
+ has_tokenizer=True,
+ has_feature_extractor=True,
+ has_image_processor=True,
+ has_processor=True,
+ supports_binary_output=True,
+)
+
+SUPPORTED_PEFT_TASKS = {
+ "document-question-answering": ["PeftModelForQuestionAnswering"],
+ "feature-extraction": ["PeftModelForFeatureExtraction", "PeftModel"],
+ "summarization": ["PeftModelForSeq2SeqLM"],
+ "table-question-answering": ["PeftModelForQuestionAnswering"],
+ "text-classification": ["PeftModelForSequenceClassification"],
+ "sentiment-analysis": ["PeftModelForSequenceClassification"],
+ "text-generation": ["PeftModelForCausalLM"],
+ "token-classification": ["PeftModelForTokenClassification"],
+ "ner": ["PeftModelForTokenClassification"],
+ "zero-shot-classification": ["PeftModelForSequenceClassification"],
+}
+
+if is_torch_available():
+ from transformers.pipelines.pt_utils import (
+ PipelineChunkIterator,
+ PipelineDataset,
+ PipelineIterator,
+ PipelinePackIterator,
+ )
+
+
+@add_end_docstrings(
+ build_pipeline_init_args(
+ has_tokenizer=True, has_feature_extractor=True, has_image_processor=True, has_processor=True
+ )
+)
+class Pipeline(_ScikitCompat, PushToHubMixin):
+ """
+ The Pipeline class is the class from which all pipelines inherit. Refer to this class for methods shared across
+ different pipelines.
+
+ Base class implementing pipelined operations. Pipeline workflow is defined as a sequence of the following
+ operations:
+
+ Input -> Tokenization -> Model Inference -> Post-Processing (task dependent) -> Output
+
+ Pipeline supports running on CPU or GPU through the device argument (see below).
+
+ Some pipeline, like for instance [`FeatureExtractionPipeline`] (`'feature-extraction'`) output large tensor object
+ as nested-lists. In order to avoid dumping such large structure as textual data we provide the `binary_output`
+ constructor argument. If set to `True`, the output will be stored in the pickle format.
+ """
+
+ # These flags should be overridden for downstream pipelines. They indicate which preprocessing classes are
+ # used by each pipeline. The possible values are:
+ # - True (the class is mandatory, raise an error if it's not present in the repo)
+ # - None (the class is optional; it should be loaded if present in the repo but the pipeline can work without it)
+ # - False (the class is never used by the pipeline and should not be loaded even if present)
+ _load_processor = None
+ _load_image_processor = None
+ _load_video_processor = None
+ _load_feature_extractor = None
+ _load_tokenizer = None
+
+ # Pipelines that call `generate` have shared logic, e.g. preparing the generation config.
+ _pipeline_calls_generate = False
+
+ default_input_names = None
+
+ def __init__(
+ self,
+ model: PreTrainedModel,
+ tokenizer: PreTrainedTokenizer | None = None,
+ feature_extractor: PreTrainedFeatureExtractor | None = None,
+ image_processor: BaseImageProcessor | None = None,
+ video_processor: BaseVideoProcessor | None = None,
+ processor: ProcessorMixin | None = None,
+ task: str = "",
+ device: int | torch.device | None = None,
+ binary_output: bool = False,
+ **kwargs,
+ ):
+ # We need to pop them for _sanitize_parameters call later
+ _, _, _ = kwargs.pop("args_parser", None), kwargs.pop("torch_dtype", None), kwargs.pop("dtype", None)
+
+ self.task = task
+ self.model = model
+ self.tokenizer = tokenizer
+ self.feature_extractor = feature_extractor
+ self.image_processor = image_processor
+ self.video_processor = video_processor
+ self.processor = processor
+
+ # `accelerate` device map
+ hf_device_map = getattr(self.model, "hf_device_map", None)
+
+ if hf_device_map is not None and device is not None:
+ raise ValueError(
+ "The model has been loaded with `accelerate` and therefore cannot be moved to a specific device. Please "
+ "discard the `device` argument when creating your pipeline object."
+ )
+
+ if device is None:
+ if hf_device_map is not None:
+ # Take the first device used by `accelerate`.
+ device = next(iter(hf_device_map.values()))
+ else:
+ device = 0
+
+ if device == -1 and self.model.device is not None:
+ device = self.model.device
+ if isinstance(device, torch.device):
+ if (device.type == "xpu" and not is_torch_xpu_available(check_device=True)) or (
+ device.type == "hpu" and not is_torch_hpu_available()
+ ):
+ raise ValueError(f'{device} is not available, you should use device="cpu" instead')
+
+ self.device = device
+ elif isinstance(device, str):
+ if ("xpu" in device and not is_torch_xpu_available(check_device=True)) or (
+ "hpu" in device and not is_torch_hpu_available()
+ ):
+ raise ValueError(f'{device} is not available, you should use device="cpu" instead')
+
+ self.device = torch.device(device)
+ elif device < 0:
+ self.device = torch.device("cpu")
+ elif is_torch_mlu_available():
+ self.device = torch.device(f"mlu:{device}")
+ elif is_torch_musa_available():
+ self.device = torch.device(f"musa:{device}")
+ elif is_torch_cuda_available():
+ self.device = torch.device(f"cuda:{device}")
+ elif is_torch_npu_available():
+ self.device = torch.device(f"npu:{device}")
+ elif is_torch_hpu_available():
+ self.device = torch.device(f"hpu:{device}")
+ elif is_torch_xpu_available(check_device=True):
+ self.device = torch.device(f"xpu:{device}")
+ elif is_torch_mps_available():
+ self.device = torch.device(f"mps:{device}")
+ else:
+ self.device = torch.device("cpu")
+
+ if torch.distributed.is_available() and torch.distributed.is_initialized():
+ self.device = self.model.device
+ logger.debug(f"Device set to use {self.device}")
+
+ self.binary_output = binary_output
+
+ # We shouldn't call `model.to()` for models loaded with accelerate as well as the case that model is already on device
+ if (
+ self.model.device != self.device
+ and not (isinstance(self.device, int) and self.device < 0)
+ and hf_device_map is None
+ ):
+ self.model.to(self.device)
+
+ # If it's a generation pipeline and the model can generate:
+ # 1 - create a local generation config. This is done to avoid side-effects on the model as we apply local
+ # tweaks to the generation config.
+ # 2 - load the assistant model if it is passed.
+ if self._pipeline_calls_generate and self.model.can_generate():
+ self.assistant_model, self.assistant_tokenizer = load_assistant_model(
+ self.model, kwargs.pop("assistant_model", None), kwargs.pop("assistant_tokenizer", None)
+ )
+ self.prefix = self.model.config.prefix if hasattr(self.model.config, "prefix") else None
+ # each pipeline with text generation capabilities should define its own default generation in a
+ # `_default_generation_config` class attribute
+ default_pipeline_generation_config = getattr(self, "_default_generation_config", GenerationConfig())
+ if hasattr(self.model, "_prepare_generation_config"):
+ # Uses `generate`'s logic to enforce the following priority of arguments:
+ # 1. user-defined config options in `**kwargs`
+ # 2. model's generation config values
+ # 3. pipeline's default generation config values
+ # NOTE: _prepare_generation_config creates a deep copy of the generation config before updating it,
+ # and returns all kwargs that were not used to update the generation config
+ prepared_generation_config, kwargs = self.model._prepare_generation_config(
+ generation_config=default_pipeline_generation_config, **kwargs
+ )
+ self.generation_config = prepared_generation_config
+ # if the `max_new_tokens` is set to the pipeline default, but `max_length` is set to a non-default
+ # value: let's honor `max_length`. E.g. we want Whisper's default `max_length=448` take precedence
+ # over over the pipeline's length default.
+ if (
+ default_pipeline_generation_config.max_new_tokens is not None # there's a pipeline default
+ and self.generation_config.max_new_tokens == default_pipeline_generation_config.max_new_tokens
+ and self.generation_config.max_length is not None
+ and self.generation_config.max_length != 20 # global default
+ ):
+ self.generation_config.max_new_tokens = None
+ else:
+ # TODO (joao): no PT model should reach this line. However, some audio models with complex
+ # inheritance patterns do. Streamline those models such that this line is no longer needed.
+ # In those models, the default generation config is not (yet) used.
+ self.generation_config = copy.deepcopy(self.model.generation_config)
+ # Update the generation config with task specific params if they exist.
+ # NOTE: 1. `prefix` is pipeline-specific and doesn't exist in the generation config.
+ # 2. `task_specific_params` is a legacy feature and should be removed in a future version.
+ task_specific_params = getattr(self.model.config, "task_specific_params", None)
+ if task_specific_params is not None and task in task_specific_params:
+ this_task_params = task_specific_params.get(task)
+ if "prefix" in this_task_params:
+ self.prefix = this_task_params.pop("prefix")
+ self.generation_config.update(**this_task_params)
+ # If the tokenizer has a pad token but the model doesn't, set it so that `generate` is aware of it.
+ if (
+ self.tokenizer is not None
+ and self.tokenizer.pad_token_id is not None
+ and self.generation_config.pad_token_id is None
+ ):
+ self.generation_config.pad_token_id = self.tokenizer.pad_token_id
+
+ self.call_count = 0
+ self._batch_size = kwargs.pop("batch_size", None)
+ self._num_workers = kwargs.pop("num_workers", None)
+ self._preprocess_params, self._forward_params, self._postprocess_params = self._sanitize_parameters(**kwargs)
+
+ # In processor only mode, we can get the modality processors from the processor
+ if self.processor is not None and all(
+ [self.tokenizer is None, self.feature_extractor is None, self.image_processor is None]
+ ):
+ self.tokenizer = getattr(self.processor, "tokenizer", None)
+ self.feature_extractor = getattr(self.processor, "feature_extractor", None)
+ self.image_processor = getattr(self.processor, "image_processor", None)
+
+ if self.image_processor is None and self.feature_extractor is not None:
+ if isinstance(self.feature_extractor, BaseImageProcessor):
+ # Backward compatible change, if users called
+ # ImageSegmentationPipeline(.., feature_extractor=MyFeatureExtractor())
+ # then we should keep working
+ self.image_processor = self.feature_extractor
+
+ def __repr__(self):
+ pipe_information = {
+ "model": self.model.__class__.__name__,
+ "dtype": str(self.dtype).split(".")[-1],
+ "device": self.device.type,
+ "input_modalities": self.model.input_modalities,
+ }
+ if self.model.can_generate():
+ pipe_information["output_modalities"] = self.model.output_modalities
+ return f"{self.__class__.__name__}: {pipe_information}"
+
+ def save_pretrained(self, save_directory: str | os.PathLike, **kwargs: Any):
+ """
+ Save the pipeline's model and tokenizer.
+
+ Args:
+ save_directory (`str` or `os.PathLike`):
+ A path to the directory where to saved. It will be created if it doesn't exist.
+ kwargs (`dict[str, Any]`, *optional*):
+ Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
+ """
+ if os.path.isfile(save_directory):
+ logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
+ return
+ os.makedirs(save_directory, exist_ok=True)
+
+ if hasattr(self, "_registered_impl"):
+ # Add info to the config
+ pipeline_info = self._registered_impl.copy()
+ custom_pipelines = {}
+ for task, info in pipeline_info.items():
+ if info["impl"] != self.__class__:
+ continue
+
+ info = info.copy()
+ module_name = info["impl"].__module__
+ last_module = module_name.split(".")[-1]
+ # Change classes into their names/full names
+ info["impl"] = f"{last_module}.{info['impl'].__name__}"
+ info["pt"] = tuple(c.__name__ for c in info["pt"])
+
+ custom_pipelines[task] = info
+ self.model.config.custom_pipelines = custom_pipelines
+ # Save the pipeline custom code
+ custom_object_save(self, save_directory)
+
+ self.model.save_pretrained(save_directory, **kwargs)
+
+ if self.tokenizer is not None:
+ self.tokenizer.save_pretrained(save_directory, **kwargs)
+
+ if self.feature_extractor is not None:
+ self.feature_extractor.save_pretrained(save_directory, **kwargs)
+
+ if self.image_processor is not None:
+ self.image_processor.save_pretrained(save_directory, **kwargs)
+
+ def transform(self, X):
+ """
+ Scikit / Keras interface to transformers' pipelines. This method will forward to __call__().
+ """
+ return self(X)
+
+ def predict(self, X):
+ """
+ Scikit / Keras interface to transformers' pipelines. This method will forward to __call__().
+ """
+ return self(X)
+
+ @property
+ def dtype(self) -> torch.dtype | None:
+ """
+ Dtype of the model (if it's Pytorch model), `None` otherwise.
+ """
+ return getattr(self.model, "dtype", None)
+
+ @property
+ def torch_dtype(self) -> torch.dtype | None:
+ """
+ Torch dtype of the model (if it's Pytorch model), `None` otherwise.
+ """
+ logger.warning_once("`torch_dtype` attribute is deprecated. Use `dtype` instead!")
+ return getattr(self.model, "dtype", None)
+
+ @contextmanager
+ def device_placement(self):
+ """
+ Context Manager allowing tensor allocation on the user-specified device.
+
+ Returns:
+ Context manager
+
+ Examples:
+
+ ```python
+ # Explicitly ask for tensor allocation on CUDA device :0
+ pipe = pipeline(..., device=0)
+ with pipe.device_placement():
+ # Every tensor allocation will be done on the request device
+ output = pipe(...)
+ ```"""
+ if self.device.type == "cuda":
+ with torch.cuda.device(self.device):
+ yield
+ elif self.device.type == "mlu":
+ with torch.mlu.device(self.device):
+ yield
+ elif self.device.type == "musa":
+ with torch.musa.device(self.device):
+ yield
+ elif self.device.type == "xpu":
+ with torch.xpu.device(self.device):
+ yield
+ else:
+ yield
+
+ def ensure_tensor_on_device(self, **inputs):
+ """
+ Ensure PyTorch tensors are on the specified device.
+
+ Args:
+ inputs (keyword arguments that should be `torch.Tensor`, the rest is ignored):
+ The tensors to place on `self.device`.
+ Recursive on lists **only**.
+
+ Return:
+ `dict[str, torch.Tensor]`: The same as `inputs` but on the proper device.
+ """
+ return self._ensure_tensor_on_device(inputs, self.device)
+
+ def _ensure_tensor_on_device(self, inputs, device):
+ if isinstance(inputs, ModelOutput):
+ return ModelOutput(
+ {name: self._ensure_tensor_on_device(tensor, device) for name, tensor in inputs.items()}
+ )
+ elif isinstance(inputs, dict):
+ return {name: self._ensure_tensor_on_device(tensor, device) for name, tensor in inputs.items()}
+ elif isinstance(inputs, UserDict):
+ return UserDict({name: self._ensure_tensor_on_device(tensor, device) for name, tensor in inputs.items()})
+ elif isinstance(inputs, list):
+ return [self._ensure_tensor_on_device(item, device) for item in inputs]
+ elif isinstance(inputs, tuple):
+ return tuple(self._ensure_tensor_on_device(item, device) for item in inputs)
+ elif isinstance(inputs, torch.Tensor):
+ return inputs.to(device)
+ else:
+ return inputs
+
+ def check_model_type(self, supported_models: list[str] | dict):
+ """
+ Check if the model class is in supported by the pipeline.
+
+ Args:
+ supported_models (`list[str]` or `dict`):
+ The list of models supported by the pipeline, or a dictionary with model class values.
+ """
+ if not isinstance(supported_models, list): # Create from a model mapping
+ supported_models_names = []
+ if self.task in SUPPORTED_PEFT_TASKS:
+ supported_models_names.extend(SUPPORTED_PEFT_TASKS[self.task])
+
+ model_name = None
+ for model_name in supported_models.values():
+ # Mapping can now contain tuples of models for the same configuration.
+ if isinstance(model_name, tuple):
+ supported_models_names.extend(list(model_name))
+ else:
+ supported_models_names.append(model_name)
+ if hasattr(supported_models, "_model_mapping"):
+ for model in supported_models._model_mapping._extra_content.values():
+ if isinstance(model, tuple):
+ supported_models_names.extend([m.__name__ for m in model])
+ else:
+ supported_models_names.append(model.__name__)
+ supported_models = supported_models_names
+ if self.model.__class__.__name__ not in supported_models:
+ logger.error(
+ f"The model '{self.model.__class__.__name__}' is not supported for {self.task}. Supported models are"
+ f" {supported_models}."
+ )
+
+ @abstractmethod
+ def _sanitize_parameters(self, **pipeline_parameters):
+ """
+ _sanitize_parameters will be called with any excessive named arguments from either `__init__` or `__call__`
+ methods. It should return 3 dictionaries of the resolved parameters used by the various `preprocess`,
+ `forward` and `postprocess` methods. Do not fill dictionaries if the caller didn't specify a kwargs. This
+ lets you keep defaults in function signatures, which is more "natural".
+
+ It is not meant to be called directly, it will be automatically called and the final parameters resolved by
+ `__init__` and `__call__`
+ """
+ raise NotImplementedError("_sanitize_parameters not implemented")
+
+ @abstractmethod
+ def preprocess(self, input_: Any, **preprocess_parameters: dict) -> dict[str, GenericTensor]:
+ """
+ Preprocess will take the `input_` of a specific pipeline and return a dictionary of everything necessary for
+ `_forward` to run properly. It should contain at least one tensor, but might have arbitrary other items.
+ """
+ raise NotImplementedError("preprocess not implemented")
+
+ @abstractmethod
+ def _forward(self, input_tensors: dict[str, GenericTensor], **forward_parameters: dict) -> ModelOutput:
+ """
+ _forward will receive the prepared dictionary from `preprocess` and run it on the model. This method might
+ involve the GPU or the CPU and should be agnostic to it. Isolating this function is the reason for `preprocess`
+ and `postprocess` to exist, so that the hot path, this method generally can run as fast as possible.
+
+ It is not meant to be called directly, `forward` is preferred. It is basically the same but contains additional
+ code surrounding `_forward` making sure tensors and models are on the same device, disabling the training part
+ of the code (leading to faster inference).
+ """
+ raise NotImplementedError("_forward not implemented")
+
+ @abstractmethod
+ def postprocess(self, model_outputs: ModelOutput, **postprocess_parameters: dict) -> Any:
+ """
+ Postprocess will receive the raw outputs of the `_forward` method, generally tensors, and reformat them into
+ something more friendly. Generally it will output a list or a dict or results (containing just strings and
+ numbers).
+ """
+ raise NotImplementedError("postprocess not implemented")
+
+ def get_inference_context(self):
+ return torch.no_grad
+
+ def forward(self, model_inputs, **forward_params):
+ with self.device_placement():
+ inference_context = self.get_inference_context()
+ with inference_context():
+ model_inputs = self._ensure_tensor_on_device(model_inputs, device=self.device)
+ model_outputs = self._forward(model_inputs, **forward_params)
+ model_outputs = self._ensure_tensor_on_device(model_outputs, device=torch.device("cpu"))
+ return model_outputs
+
+ def get_iterator(
+ self, inputs, num_workers: int, batch_size: int, preprocess_params, forward_params, postprocess_params
+ ):
+ if isinstance(inputs, collections.abc.Sized):
+ dataset = PipelineDataset(inputs, self.preprocess, preprocess_params)
+ else:
+ if num_workers > 1:
+ logger.warning(
+ "For iterable dataset using num_workers>1 is likely to result"
+ " in errors since everything is iterable, setting `num_workers=1`"
+ " to guarantee correctness."
+ )
+ num_workers = 1
+ dataset = PipelineIterator(inputs, self.preprocess, preprocess_params)
+ if "TOKENIZERS_PARALLELISM" not in os.environ:
+ logger.info("Disabling tokenizer parallelism, we're using DataLoader multithreading already")
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
+ # TODO hack by collating feature_extractor and image_processor
+ feature_extractor = self.feature_extractor if self.feature_extractor is not None else self.image_processor
+ collate_fn = no_collate_fn if batch_size == 1 else pad_collate_fn(self.tokenizer, feature_extractor)
+ dataloader = DataLoader(dataset, num_workers=num_workers, batch_size=batch_size, collate_fn=collate_fn)
+ model_iterator = PipelineIterator(dataloader, self.forward, forward_params, loader_batch_size=batch_size)
+ final_iterator = PipelineIterator(model_iterator, self.postprocess, postprocess_params)
+ return final_iterator
+
+ def __call__(self, inputs, *args, num_workers=None, batch_size=None, **kwargs):
+ if args:
+ logger.warning(f"Ignoring args : {args}")
+
+ # Detect if inputs are a chat-style input(s) and cast as `Chat` or list of `Chat`
+ container_types = (list, tuple, types.GeneratorType)
+ if is_torch_available():
+ container_types = (*container_types, KeyDataset)
+ if isinstance(inputs, container_types):
+ if isinstance(inputs, types.GeneratorType):
+ inputs = list(inputs)
+ if is_valid_message(inputs[0]):
+ inputs = Chat(inputs)
+ elif isinstance(inputs[0], (list, tuple)) and all(chat and is_valid_message(chat[0]) for chat in inputs):
+ inputs = [Chat(chat) for chat in inputs]
+
+ if num_workers is None:
+ if self._num_workers is None:
+ num_workers = 0
+ else:
+ num_workers = self._num_workers
+ if batch_size is None:
+ if self._batch_size is None:
+ batch_size = 1
+ else:
+ batch_size = self._batch_size
+
+ preprocess_params, forward_params, postprocess_params = self._sanitize_parameters(**kwargs)
+
+ # Fuse __init__ params and __call__ params without modifying the __init__ ones.
+ preprocess_params = {**self._preprocess_params, **preprocess_params}
+ forward_params = {**self._forward_params, **forward_params}
+ postprocess_params = {**self._postprocess_params, **postprocess_params}
+
+ self.call_count += 1
+ if self.call_count > 10 and self.device.type == "cuda":
+ logger.warning_once(
+ "You seem to be using the pipelines sequentially on GPU. In order to maximize efficiency please use a"
+ " dataset",
+ )
+
+ is_dataset = Dataset is not None and isinstance(inputs, Dataset)
+ is_generator = isinstance(inputs, types.GeneratorType)
+ is_list = isinstance(inputs, list)
+
+ is_iterable = is_dataset or is_generator or is_list
+ can_use_iterator = is_dataset or is_generator or is_list
+
+ if is_list:
+ if can_use_iterator:
+ final_iterator = self.get_iterator(
+ inputs, num_workers, batch_size, preprocess_params, forward_params, postprocess_params
+ )
+ outputs = list(final_iterator)
+ return outputs
+ else:
+ return self.run_multi(inputs, preprocess_params, forward_params, postprocess_params)
+ elif can_use_iterator:
+ return self.get_iterator(
+ inputs, num_workers, batch_size, preprocess_params, forward_params, postprocess_params
+ )
+ elif is_iterable:
+ return self.iterate(inputs, preprocess_params, forward_params, postprocess_params)
+ elif isinstance(self, ChunkPipeline):
+ return next(
+ iter(
+ self.get_iterator(
+ [inputs], num_workers, batch_size, preprocess_params, forward_params, postprocess_params
+ )
+ )
+ )
+ else:
+ return self.run_single(inputs, preprocess_params, forward_params, postprocess_params)
+
+ def run_multi(self, inputs, preprocess_params, forward_params, postprocess_params):
+ return [self.run_single(item, preprocess_params, forward_params, postprocess_params) for item in inputs]
+
+ def run_single(self, inputs, preprocess_params, forward_params, postprocess_params):
+ model_inputs = self.preprocess(inputs, **preprocess_params)
+ model_outputs = self.forward(model_inputs, **forward_params)
+ outputs = self.postprocess(model_outputs, **postprocess_params)
+ return outputs
+
+ def iterate(self, inputs, preprocess_params, forward_params, postprocess_params):
+ # This function should become `get_iterator` again, this is a temporary
+ # easy solution.
+ for input_ in inputs:
+ yield self.run_single(input_, preprocess_params, forward_params, postprocess_params)
+
+
+Pipeline.push_to_hub = copy_func(Pipeline.push_to_hub)
+if Pipeline.push_to_hub.__doc__ is not None:
+ Pipeline.push_to_hub.__doc__ = Pipeline.push_to_hub.__doc__.format(
+ object="pipe", object_class="pipeline", object_files="pipeline file"
+ ).replace(".from_pretrained", "")
+
+
+class ChunkPipeline(Pipeline):
+ def run_single(self, inputs, preprocess_params, forward_params, postprocess_params):
+ all_outputs = []
+ for model_inputs in self.preprocess(inputs, **preprocess_params):
+ model_outputs = self.forward(model_inputs, **forward_params)
+ all_outputs.append(model_outputs)
+ outputs = self.postprocess(all_outputs, **postprocess_params)
+ return outputs
+
+ def get_iterator(
+ self, inputs, num_workers: int, batch_size: int, preprocess_params, forward_params, postprocess_params
+ ):
+ if "TOKENIZERS_PARALLELISM" not in os.environ:
+ logger.info("Disabling tokenizer parallelism, we're using DataLoader multithreading already")
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
+ if num_workers > 1:
+ logger.warning(
+ "For ChunkPipeline using num_workers>0 is likely to result in errors since everything is iterable,"
+ " setting `num_workers=1` to guarantee correctness."
+ )
+ num_workers = 1
+ dataset = PipelineChunkIterator(inputs, self.preprocess, preprocess_params)
+
+ # TODO hack by collating feature_extractor and image_processor
+ feature_extractor = self.feature_extractor if self.feature_extractor is not None else self.image_processor
+ collate_fn = no_collate_fn if batch_size == 1 else pad_collate_fn(self.tokenizer, feature_extractor)
+ dataloader = DataLoader(dataset, num_workers=num_workers, batch_size=batch_size, collate_fn=collate_fn)
+ model_iterator = PipelinePackIterator(dataloader, self.forward, forward_params, loader_batch_size=batch_size)
+ final_iterator = PipelineIterator(model_iterator, self.postprocess, postprocess_params)
+ return final_iterator
+
+
+class PipelineRegistry:
+ def __init__(self, supported_tasks: dict[str, Any], task_aliases: dict[str, str]) -> None:
+ self.supported_tasks = supported_tasks
+ self.task_aliases = task_aliases
+
+ def get_supported_tasks(self) -> list[str]:
+ supported_task = list(self.supported_tasks.keys()) + list(self.task_aliases.keys())
+ supported_task.sort()
+ return supported_task
+
+ def check_task(self, task: str) -> tuple[str, dict, Any]:
+ if task in self.task_aliases:
+ task = self.task_aliases[task]
+ if task in self.supported_tasks:
+ targeted_task = self.supported_tasks[task]
+ return task, targeted_task, None
+
+ raise KeyError(f"Unknown task {task}, available tasks are {self.get_supported_tasks()}")
+
+ def register_pipeline(
+ self,
+ task: str,
+ pipeline_class: type,
+ pt_model: type | tuple[type] | None = None,
+ default: dict | None = None,
+ type: str | None = None,
+ ) -> None:
+ if task in self.supported_tasks:
+ logger.warning(f"{task} is already registered. Overwriting pipeline for task {task}...")
+
+ if pt_model is None:
+ pt_model = ()
+ elif not isinstance(pt_model, tuple):
+ pt_model = (pt_model,)
+
+ task_impl = {"impl": pipeline_class, "pt": pt_model}
+
+ if default is not None:
+ if "model" not in default:
+ default = {"model": default}
+ task_impl["default"] = default
+
+ if type is not None:
+ task_impl["type"] = type
+
+ self.supported_tasks[task] = task_impl
+ pipeline_class._registered_impl = {task: task_impl}
+
+ def to_dict(self):
+ return self.supported_tasks
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/depth_estimation.py b/.venv/lib/python3.12/site-packages/transformers/pipelines/depth_estimation.py
new file mode 100644
index 0000000000000000000000000000000000000000..03ee70673d6cecf8a0e710bf66db8d7cfc06727e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/pipelines/depth_estimation.py
@@ -0,0 +1,145 @@
+from typing import Any, Union, overload
+
+from ..utils import (
+ add_end_docstrings,
+ is_torch_available,
+ is_vision_available,
+ logging,
+ requires_backends,
+)
+from .base import Pipeline, build_pipeline_init_args
+
+
+if is_vision_available():
+ from PIL import Image
+
+ from ..image_utils import load_image
+
+if is_torch_available():
+ from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES
+
+logger = logging.get_logger(__name__)
+
+
+@add_end_docstrings(build_pipeline_init_args(has_image_processor=True))
+class DepthEstimationPipeline(Pipeline):
+ """
+ Depth estimation pipeline using any `AutoModelForDepthEstimation`. This pipeline predicts the depth of an image.
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> depth_estimator = pipeline(task="depth-estimation", model="LiheYoung/depth-anything-base-hf")
+ >>> output = depth_estimator("http://images.cocodataset.org/val2017/000000039769.jpg")
+ >>> # This is a tensor with the values being the depth expressed in meters for each pixel
+ >>> output["predicted_depth"].shape
+ torch.Size([1, 384, 384])
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+
+ This depth estimation pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"depth-estimation"`.
+
+ See the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=depth-estimation).
+ """
+
+ _load_processor = False
+ _load_image_processor = True
+ _load_feature_extractor = False
+ _load_tokenizer = False
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ requires_backends(self, "vision")
+ self.check_model_type(MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES)
+
+ @overload
+ def __call__(self, inputs: Union[str, "Image.Image"], **kwargs: Any) -> dict[str, Any]: ...
+
+ @overload
+ def __call__(self, inputs: list[Union[str, "Image.Image"]], **kwargs: Any) -> list[dict[str, Any]]: ...
+
+ def __call__(
+ self, inputs: Union[str, list[str], "Image.Image", list["Image.Image"]], **kwargs: Any
+ ) -> dict[str, Any] | list[dict[str, Any]]:
+ """
+ Predict the depth(s) of the image(s) passed as inputs.
+
+ Args:
+ inputs (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`):
+ The pipeline handles three types of images:
+
+ - A string containing a http link pointing to an image
+ - A string containing a local path to an image
+ - An image loaded in PIL directly
+
+ The pipeline accepts either a single image or a batch of images, which must then be passed as a string.
+ Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL
+ images.
+ parameters (`Dict`, *optional*):
+ A dictionary of argument names to parameter values, to control pipeline behaviour.
+ The only parameter available right now is `timeout`, which is the length of time, in seconds,
+ that the pipeline should wait before giving up on trying to download an image.
+ timeout (`float`, *optional*, defaults to None):
+ The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
+ the call may block forever.
+
+ Return:
+ A dictionary or a list of dictionaries containing result. If the input is a single image, will return a
+ dictionary, if the input is a list of several images, will return a list of dictionaries corresponding to
+ the images.
+
+ The dictionaries contain the following keys:
+
+ - **predicted_depth** (`torch.Tensor`) -- The predicted depth by the model as a `torch.Tensor`.
+ - **depth** (`PIL.Image`) -- The predicted depth by the model as a `PIL.Image`.
+ """
+ # After deprecation of this is completed, remove the default `None` value for `images`
+ if "images" in kwargs:
+ inputs = kwargs.pop("images")
+ if inputs is None:
+ raise ValueError("Cannot call the depth-estimation pipeline without an inputs argument!")
+ return super().__call__(inputs, **kwargs)
+
+ def _sanitize_parameters(self, timeout=None, parameters=None, **kwargs):
+ preprocess_params = {}
+ if timeout is not None:
+ preprocess_params["timeout"] = timeout
+ if isinstance(parameters, dict) and "timeout" in parameters:
+ preprocess_params["timeout"] = parameters["timeout"]
+ return preprocess_params, {}, {}
+
+ def preprocess(self, image, timeout=None):
+ image = load_image(image, timeout)
+ model_inputs = self.image_processor(images=image, return_tensors="pt")
+ model_inputs = model_inputs.to(self.dtype)
+ model_inputs["target_size"] = image.size[::-1]
+ return model_inputs
+
+ def _forward(self, model_inputs):
+ target_size = model_inputs.pop("target_size")
+ model_outputs = self.model(**model_inputs)
+ model_outputs["target_size"] = target_size
+ return model_outputs
+
+ def postprocess(self, model_outputs):
+ outputs = self.image_processor.post_process_depth_estimation(
+ model_outputs,
+ # this acts as `source_sizes` for ZoeDepth and as `target_sizes` for the rest of the models so do *not*
+ # replace with `target_sizes = [model_outputs["target_size"]]`
+ [model_outputs["target_size"]],
+ )
+
+ formatted_outputs = []
+ for output in outputs:
+ depth = output["predicted_depth"].detach().cpu().numpy()
+ depth = (depth - depth.min()) / (depth.max() - depth.min())
+ depth = Image.fromarray((depth * 255).astype("uint8"))
+
+ formatted_outputs.append({"predicted_depth": output["predicted_depth"], "depth": depth})
+
+ return formatted_outputs[0] if len(outputs) == 1 else formatted_outputs
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/document_question_answering.py b/.venv/lib/python3.12/site-packages/transformers/pipelines/document_question_answering.py
new file mode 100644
index 0000000000000000000000000000000000000000..de976f9d8750719397ae8be2fcedd25800da8bbf
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/pipelines/document_question_answering.py
@@ -0,0 +1,649 @@
+# Copyright 2022 The Impira Team and the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import re
+from typing import Any, Union, overload
+
+import numpy as np
+
+from ..generation import GenerationConfig
+from ..utils import (
+ ExplicitEnum,
+ add_end_docstrings,
+ is_pytesseract_available,
+ is_torch_available,
+ is_vision_available,
+ logging,
+)
+from .base import ChunkPipeline, build_pipeline_init_args
+
+
+if is_vision_available():
+ from PIL import Image
+
+ from ..image_utils import load_image
+
+if is_torch_available():
+ import torch
+
+ from ..models.auto.modeling_auto import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES
+
+TESSERACT_LOADED = False
+if is_pytesseract_available():
+ TESSERACT_LOADED = True
+ import pytesseract
+
+logger = logging.get_logger(__name__)
+
+
+# normalize_bbox() and apply_tesseract() are derived from apply_tesseract in models/layoutlmv3/feature_extraction_layoutlmv3.py.
+# However, because the pipeline may evolve from what layoutlmv3 currently does, it's copied (vs. imported) to avoid creating an
+# unnecessary dependency.
+def normalize_box(box, width, height):
+ return [
+ int(1000 * (box[0] / width)),
+ int(1000 * (box[1] / height)),
+ int(1000 * (box[2] / width)),
+ int(1000 * (box[3] / height)),
+ ]
+
+
+def decode_spans(
+ start: np.ndarray, end: np.ndarray, topk: int, max_answer_len: int, undesired_tokens: np.ndarray
+) -> tuple:
+ """
+ Take the output of any `ModelForQuestionAnswering` and will generate probabilities for each span to be the actual
+ answer.
+
+ In addition, it filters out some unwanted/impossible cases like answer len being greater than max_answer_len or
+ answer end position being before the starting position. The method supports output the k-best answer through the
+ topk argument.
+
+ Args:
+ start (`np.ndarray`): Individual start probabilities for each token.
+ end (`np.ndarray`): Individual end probabilities for each token.
+ topk (`int`): Indicates how many possible answer span(s) to extract from the model output.
+ max_answer_len (`int`): Maximum size of the answer to extract from the model's output.
+ undesired_tokens (`np.ndarray`): Mask determining tokens that can be part of the answer
+ """
+ # Ensure we have batch axis
+ if start.ndim == 1:
+ start = start[None]
+
+ if end.ndim == 1:
+ end = end[None]
+
+ # Compute the score of each tuple(start, end) to be the real answer
+ outer = np.matmul(np.expand_dims(start, -1), np.expand_dims(end, 1))
+
+ # Remove candidate with end < start and end - start > max_answer_len
+ candidates = np.tril(np.triu(outer), max_answer_len - 1)
+
+ # Inspired by Chen & al. (https://github.com/facebookresearch/DrQA)
+ scores_flat = candidates.flatten()
+ if topk == 1:
+ idx_sort = [np.argmax(scores_flat)]
+ elif len(scores_flat) <= topk:
+ idx_sort = np.argsort(-scores_flat)
+ else:
+ idx = np.argpartition(-scores_flat, topk)[0:topk]
+ idx_sort = idx[np.argsort(-scores_flat[idx])]
+
+ starts, ends = np.unravel_index(idx_sort, candidates.shape)[1:]
+ desired_spans = np.isin(starts, undesired_tokens.nonzero()) & np.isin(ends, undesired_tokens.nonzero())
+ starts = starts[desired_spans]
+ ends = ends[desired_spans]
+ scores = candidates[0, starts, ends]
+
+ return starts, ends, scores
+
+
+def select_starts_ends(
+ start: np.ndarray,
+ end: np.ndarray,
+ p_mask: np.ndarray,
+ attention_mask: np.ndarray,
+ min_null_score=1000000,
+ top_k=1,
+ handle_impossible_answer=False,
+ max_answer_len=15,
+):
+ """
+ Takes the raw output of any `ModelForQuestionAnswering` and first normalizes its outputs and then uses
+ `decode_spans()` to generate probabilities for each span to be the actual answer.
+
+ Args:
+ start (`np.ndarray`): Individual start logits for each token.
+ end (`np.ndarray`): Individual end logits for each token.
+ p_mask (`np.ndarray`): A mask with 1 for values that cannot be in the answer
+ attention_mask (`np.ndarray`): The attention mask generated by the tokenizer
+ min_null_score(`float`): The minimum null (empty) answer score seen so far.
+ topk (`int`): Indicates how many possible answer span(s) to extract from the model output.
+ handle_impossible_answer(`bool`): Whether to allow null (empty) answers
+ max_answer_len (`int`): Maximum size of the answer to extract from the model's output.
+ """
+ # Ensure padded tokens & question tokens cannot belong to the set of candidate answers.
+ undesired_tokens = np.abs(np.array(p_mask) - 1)
+
+ if attention_mask is not None:
+ undesired_tokens = undesired_tokens & attention_mask
+
+ # Generate mask
+ undesired_tokens_mask = undesired_tokens == 0.0
+
+ # Make sure non-context indexes in the tensor cannot contribute to the softmax
+ start = np.where(undesired_tokens_mask, -10000.0, start)
+ end = np.where(undesired_tokens_mask, -10000.0, end)
+
+ # Normalize logits and spans to retrieve the answer
+ start = np.exp(start - start.max(axis=-1, keepdims=True))
+ start = start / start.sum()
+
+ end = np.exp(end - end.max(axis=-1, keepdims=True))
+ end = end / end.sum()
+
+ if handle_impossible_answer:
+ min_null_score = min(min_null_score, (start[0, 0] * end[0, 0]).item())
+
+ # Mask CLS
+ start[0, 0] = end[0, 0] = 0.0
+
+ starts, ends, scores = decode_spans(start, end, top_k, max_answer_len, undesired_tokens)
+ return starts, ends, scores, min_null_score
+
+
+def apply_tesseract(image: "Image.Image", lang: str | None, tesseract_config: str | None):
+ """Applies Tesseract OCR on a document image, and returns recognized words + normalized bounding boxes."""
+ # apply OCR
+ data = pytesseract.image_to_data(image, lang=lang, output_type="dict", config=tesseract_config)
+ words, left, top, width, height = data["text"], data["left"], data["top"], data["width"], data["height"]
+
+ # filter empty words and corresponding coordinates
+ irrelevant_indices = [idx for idx, word in enumerate(words) if not word.strip()]
+ words = [word for idx, word in enumerate(words) if idx not in irrelevant_indices]
+ left = [coord for idx, coord in enumerate(left) if idx not in irrelevant_indices]
+ top = [coord for idx, coord in enumerate(top) if idx not in irrelevant_indices]
+ width = [coord for idx, coord in enumerate(width) if idx not in irrelevant_indices]
+ height = [coord for idx, coord in enumerate(height) if idx not in irrelevant_indices]
+
+ # turn coordinates into (left, top, left+width, top+height) format
+ actual_boxes = []
+ for x, y, w, h in zip(left, top, width, height):
+ actual_box = [x, y, x + w, y + h]
+ actual_boxes.append(actual_box)
+
+ image_width, image_height = image.size
+
+ # finally, normalize the bounding boxes
+ normalized_boxes = []
+ for box in actual_boxes:
+ normalized_boxes.append(normalize_box(box, image_width, image_height))
+
+ if len(words) != len(normalized_boxes):
+ raise ValueError("Not as many words as there are bounding boxes")
+
+ return words, normalized_boxes
+
+
+class ModelType(ExplicitEnum):
+ LayoutLM = "layoutlm"
+ LayoutLMv2andv3 = "layoutlmv2andv3"
+ VisionEncoderDecoder = "vision_encoder_decoder"
+
+
+@add_end_docstrings(build_pipeline_init_args(has_image_processor=True, has_tokenizer=True))
+class DocumentQuestionAnsweringPipeline(ChunkPipeline):
+ # TODO: Update task_summary docs to include an example with document QA and then update the first sentence
+ """
+ Document Question Answering pipeline using any `AutoModelForDocumentQuestionAnswering`. The inputs/outputs are
+ similar to the (extractive) question answering pipeline; however, the pipeline takes an image (and optional OCR'd
+ words/boxes) as input instead of text context.
+
+ Unless the model you're using explicitly sets these generation parameters in its configuration files
+ (`generation_config.json`), the following default values will be used:
+ - max_new_tokens: 256
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> document_qa = pipeline(model="impira/layoutlm-document-qa")
+ >>> document_qa(
+ ... image="https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png",
+ ... question="What is the invoice number?",
+ ... )
+ [{'score': 0.425, 'answer': 'us-001', 'start': 16, 'end': 16}]
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This document question answering pipeline can currently be loaded from [`pipeline`] using the following task
+ identifier: `"document-question-answering"`.
+
+ The models that this pipeline can use are models that have been fine-tuned on a document question answering task.
+ See the up-to-date list of available models on
+ [huggingface.co/models](https://huggingface.co/models?filter=document-question-answering).
+ """
+
+ _pipeline_calls_generate = True
+ _load_processor = False
+ _load_image_processor = None
+ _load_feature_extractor = None
+ _load_tokenizer = True
+ # Make sure the docstring is updated when the default generation config is changed
+ _default_generation_config = GenerationConfig(
+ max_new_tokens=256,
+ )
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ if self.tokenizer is not None and not (
+ self.tokenizer.__class__.__name__.endswith("Fast") or self.tokenizer.backend == "tokenizers"
+ ):
+ raise ValueError(
+ "`DocumentQuestionAnsweringPipeline` requires a fast tokenizer, but a slow tokenizer "
+ f"(`{self.tokenizer.__class__.__name__}`) is provided."
+ )
+
+ if self.model.config.__class__.__name__ == "VisionEncoderDecoderConfig":
+ self.model_type = ModelType.VisionEncoderDecoder
+ if self.model.config.encoder.model_type != "donut-swin":
+ raise ValueError("Currently, the only supported VisionEncoderDecoder model is Donut")
+ else:
+ self.check_model_type(MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES)
+ if self.model.config.__class__.__name__ == "LayoutLMConfig":
+ self.model_type = ModelType.LayoutLM
+ else:
+ self.model_type = ModelType.LayoutLMv2andv3
+
+ def _sanitize_parameters(
+ self,
+ padding=None,
+ doc_stride=None,
+ max_question_len=None,
+ lang: str | None = None,
+ tesseract_config: str | None = None,
+ max_answer_len=None,
+ max_seq_len=None,
+ top_k=None,
+ handle_impossible_answer=None,
+ timeout=None,
+ **kwargs,
+ ):
+ preprocess_params, postprocess_params = {}, {}
+ if padding is not None:
+ preprocess_params["padding"] = padding
+ if doc_stride is not None:
+ preprocess_params["doc_stride"] = doc_stride
+ if max_question_len is not None:
+ preprocess_params["max_question_len"] = max_question_len
+ if max_seq_len is not None:
+ preprocess_params["max_seq_len"] = max_seq_len
+ if lang is not None:
+ preprocess_params["lang"] = lang
+ if tesseract_config is not None:
+ preprocess_params["tesseract_config"] = tesseract_config
+ if timeout is not None:
+ preprocess_params["timeout"] = timeout
+
+ if top_k is not None:
+ if top_k < 1:
+ raise ValueError(f"top_k parameter should be >= 1 (got {top_k})")
+ postprocess_params["top_k"] = top_k
+ if max_answer_len is not None:
+ if max_answer_len < 1:
+ raise ValueError(f"max_answer_len parameter should be >= 1 (got {max_answer_len})")
+ postprocess_params["max_answer_len"] = max_answer_len
+ if handle_impossible_answer is not None:
+ postprocess_params["handle_impossible_answer"] = handle_impossible_answer
+
+ forward_params = {}
+ if getattr(self, "assistant_model", None) is not None:
+ forward_params["assistant_model"] = self.assistant_model
+ if getattr(self, "assistant_tokenizer", None) is not None:
+ forward_params["tokenizer"] = self.tokenizer
+ forward_params["assistant_tokenizer"] = self.assistant_tokenizer
+
+ return preprocess_params, forward_params, postprocess_params
+
+ @overload
+ def __call__(
+ self,
+ image: Union["Image.Image", str],
+ question: str,
+ word_boxes: tuple[str, list[float]] | None = None,
+ **kwargs: Any,
+ ) -> list[dict[str, Any]]: ...
+
+ @overload
+ def __call__(self, image: dict[str, Any], **kwargs: Any) -> list[dict[str, Any]]: ...
+
+ @overload
+ def __call__(self, image: list[dict[str, Any]], **kwargs: Any) -> list[list[dict[str, Any]]]: ...
+
+ def __call__(
+ self,
+ image: Union["Image.Image", str, list[dict[str, Any]]],
+ question: str | None = None,
+ word_boxes: tuple[str, list[float]] | None = None,
+ **kwargs: Any,
+ ) -> dict[str, Any] | list[dict[str, Any]]:
+ """
+ Answer the question(s) given as inputs by using the document(s). A document is defined as an image and an
+ optional list of (word, box) tuples which represent the text in the document. If the `word_boxes` are not
+ provided, it will use the Tesseract OCR engine (if available) to extract the words and boxes automatically for
+ LayoutLM-like models which require them as input. For Donut, no OCR is run.
+
+ You can invoke the pipeline several ways:
+
+ - `pipeline(image=image, question=question)`
+ - `pipeline(image=image, question=question, word_boxes=word_boxes)`
+ - `pipeline([{"image": image, "question": question}])`
+ - `pipeline([{"image": image, "question": question, "word_boxes": word_boxes}])`
+
+ Args:
+ image (`str` or `PIL.Image`):
+ The pipeline handles three types of images:
+
+ - A string containing a http link pointing to an image
+ - A string containing a local path to an image
+ - An image loaded in PIL directly
+
+ The pipeline accepts either a single image or a batch of images. If given a single image, it can be
+ broadcasted to multiple questions.
+ question (`str`):
+ A question to ask of the document.
+ word_boxes (`list[str, tuple[float, float, float, float]]`, *optional*):
+ A list of words and bounding boxes (normalized 0->1000). If you provide this optional input, then the
+ pipeline will use these words and boxes instead of running OCR on the image to derive them for models
+ that need them (e.g. LayoutLM). This allows you to reuse OCR'd results across many invocations of the
+ pipeline without having to re-run it each time.
+ top_k (`int`, *optional*, defaults to 1):
+ The number of answers to return (will be chosen by order of likelihood). Note that we return less than
+ top_k answers if there are not enough options available within the context.
+ doc_stride (`int`, *optional*, defaults to 128):
+ If the words in the document are too long to fit with the question for the model, it will be split in
+ several chunks with some overlap. This argument controls the size of that overlap.
+ max_answer_len (`int`, *optional*, defaults to 15):
+ The maximum length of predicted answers (e.g., only answers with a shorter length are considered).
+ max_seq_len (`int`, *optional*, defaults to 384):
+ The maximum length of the total sentence (context + question) in tokens of each chunk passed to the
+ model. The context will be split in several chunks (using `doc_stride` as overlap) if needed.
+ max_question_len (`int`, *optional*, defaults to 64):
+ The maximum length of the question after tokenization. It will be truncated if needed.
+ handle_impossible_answer (`bool`, *optional*, defaults to `False`):
+ Whether or not we accept impossible as an answer.
+ lang (`str`, *optional*):
+ Language to use while running OCR. Defaults to english.
+ tesseract_config (`str`, *optional*):
+ Additional flags to pass to tesseract while running OCR.
+ timeout (`float`, *optional*, defaults to None):
+ The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
+ the call may block forever.
+
+ Return:
+ A `dict` or a list of `dict`: Each result comes as a dictionary with the following keys:
+
+ - **score** (`float`) -- The probability associated to the answer.
+ - **start** (`int`) -- The start word index of the answer (in the OCR'd version of the input or provided
+ `word_boxes`).
+ - **end** (`int`) -- The end word index of the answer (in the OCR'd version of the input or provided
+ `word_boxes`).
+ - **answer** (`str`) -- The answer to the question.
+ - **words** (`list[int]`) -- The index of each word/box pair that is in the answer
+ """
+ if isinstance(question, str):
+ inputs = {"question": question, "image": image}
+ if word_boxes is not None:
+ inputs["word_boxes"] = word_boxes
+ else:
+ inputs = image
+ return super().__call__(inputs, **kwargs)
+
+ def preprocess(
+ self,
+ input,
+ padding="do_not_pad",
+ doc_stride=None,
+ max_seq_len=None,
+ word_boxes: tuple[str, list[float]] | None = None,
+ lang=None,
+ tesseract_config="",
+ timeout=None,
+ ):
+ # NOTE: This code mirrors the code in question answering and will be implemented in a follow up PR
+ # to support documents with enough tokens that overflow the model's window
+ if max_seq_len is None:
+ max_seq_len = self.tokenizer.model_max_length
+
+ if doc_stride is None:
+ doc_stride = min(max_seq_len // 2, 256)
+
+ image = None
+ image_features = {}
+ if input.get("image", None) is not None:
+ image = load_image(input["image"], timeout=timeout)
+ if self.image_processor is not None:
+ image_inputs = self.image_processor(images=image, return_tensors="pt")
+ image_inputs = image_inputs.to(self.dtype)
+ image_features.update(image_inputs)
+ elif self.feature_extractor is not None:
+ image_features.update(self.feature_extractor(images=image, return_tensors="pt"))
+ elif self.model_type == ModelType.VisionEncoderDecoder:
+ raise ValueError("If you are using a VisionEncoderDecoderModel, you must provide a feature extractor")
+
+ words, boxes = None, None
+ if self.model_type != ModelType.VisionEncoderDecoder:
+ if "word_boxes" in input:
+ words = [x[0] for x in input["word_boxes"]]
+ boxes = [x[1] for x in input["word_boxes"]]
+ elif "words" in image_features and "boxes" in image_features:
+ words = image_features.pop("words")[0]
+ boxes = image_features.pop("boxes")[0]
+ elif image is not None:
+ if not TESSERACT_LOADED:
+ raise ValueError(
+ "If you provide an image without word_boxes, then the pipeline will run OCR using Tesseract,"
+ " but pytesseract is not available"
+ )
+ if TESSERACT_LOADED:
+ words, boxes = apply_tesseract(image, lang=lang, tesseract_config=tesseract_config)
+ else:
+ raise ValueError(
+ "You must provide an image or word_boxes. If you provide an image, the pipeline will automatically"
+ " run OCR to derive words and boxes"
+ )
+
+ if self.tokenizer.padding_side != "right":
+ raise ValueError(
+ "Document question answering only supports tokenizers whose padding side is 'right', not"
+ f" {self.tokenizer.padding_side}"
+ )
+
+ if self.model_type == ModelType.VisionEncoderDecoder:
+ task_prompt = f"{input['question']}"
+ # Adapted from https://huggingface.co/spaces/nielsr/donut-docvqa/blob/main/app.py
+ encoding = {
+ "inputs": image_features["pixel_values"],
+ "decoder_input_ids": self.tokenizer(
+ task_prompt, add_special_tokens=False, return_tensors="pt"
+ ).input_ids,
+ "return_dict_in_generate": True,
+ }
+ yield {
+ **encoding,
+ "p_mask": None,
+ "word_ids": None,
+ "words": None,
+ "output_attentions": True,
+ "is_last": True,
+ }
+ else:
+ tokenizer_kwargs = {}
+ if self.model_type == ModelType.LayoutLM:
+ tokenizer_kwargs["text"] = input["question"].split()
+ tokenizer_kwargs["text_pair"] = words
+ tokenizer_kwargs["is_split_into_words"] = True
+ else:
+ tokenizer_kwargs["text"] = [input["question"]]
+ tokenizer_kwargs["text_pair"] = [words]
+ tokenizer_kwargs["boxes"] = [boxes]
+
+ encoding = self.tokenizer(
+ padding=padding,
+ max_length=max_seq_len,
+ stride=doc_stride,
+ return_token_type_ids=True,
+ truncation="only_second",
+ return_overflowing_tokens=True,
+ **tokenizer_kwargs,
+ )
+ # TODO: check why slower `LayoutLMTokenizer` and `LayoutLMv2Tokenizer` don't have this key in outputs
+ # FIXME: ydshieh and/or Narsil
+ encoding.pop("overflow_to_sample_mapping", None) # We do not use this
+
+ num_spans = len(encoding["input_ids"])
+
+ # p_mask: mask with 1 for token than cannot be in the answer (0 for token which can be in an answer)
+ # We put 0 on the tokens from the context and 1 everywhere else (question and special tokens)
+ # This logic mirrors the logic in the question_answering pipeline
+ p_mask = [[tok != 1 for tok in encoding.sequence_ids(span_id)] for span_id in range(num_spans)]
+ for span_idx in range(num_spans):
+ span_encoding = {k: torch.tensor(v[span_idx : span_idx + 1]) for (k, v) in encoding.items()}
+ if "pixel_values" in image_features:
+ span_encoding["image"] = image_features["pixel_values"]
+
+ input_ids_span_idx = encoding["input_ids"][span_idx]
+ # keep the cls_token unmasked (some models use it to indicate unanswerable questions)
+ if self.tokenizer.cls_token_id is not None:
+ cls_indices = np.nonzero(np.array(input_ids_span_idx) == self.tokenizer.cls_token_id)[0]
+ for cls_index in cls_indices:
+ p_mask[span_idx][cls_index] = 0
+
+ # For each span, place a bounding box [0,0,0,0] for question and CLS tokens, [1000,1000,1000,1000]
+ # for SEP tokens, and the word's bounding box for words in the original document.
+ if "boxes" not in tokenizer_kwargs:
+ bbox = []
+ for input_id, sequence_id, word_id in zip(
+ encoding.input_ids[span_idx],
+ encoding.sequence_ids(span_idx),
+ encoding.word_ids(span_idx),
+ ):
+ if sequence_id == 1:
+ bbox.append(boxes[word_id])
+ elif input_id == self.tokenizer.sep_token_id:
+ bbox.append([1000] * 4)
+ else:
+ bbox.append([0] * 4)
+
+ span_encoding["bbox"] = torch.tensor(bbox).unsqueeze(0)
+ yield {
+ **span_encoding,
+ "p_mask": p_mask[span_idx],
+ "word_ids": encoding.word_ids(span_idx),
+ "words": words,
+ "is_last": span_idx == num_spans - 1,
+ }
+
+ def _forward(self, model_inputs, **generate_kwargs):
+ p_mask = model_inputs.pop("p_mask", None)
+ word_ids = model_inputs.pop("word_ids", None)
+ words = model_inputs.pop("words", None)
+ is_last = model_inputs.pop("is_last", False)
+
+ if self.model_type == ModelType.VisionEncoderDecoder:
+ # User-defined `generation_config` passed to the pipeline call take precedence
+ if "generation_config" not in generate_kwargs:
+ generate_kwargs["generation_config"] = self.generation_config
+
+ model_outputs = self.model.generate(**model_inputs, **generate_kwargs)
+ else:
+ model_outputs = self.model(**model_inputs)
+
+ model_outputs = dict(model_outputs.items())
+ model_outputs["p_mask"] = p_mask
+ model_outputs["word_ids"] = word_ids
+ model_outputs["words"] = words
+ model_outputs["attention_mask"] = model_inputs.get("attention_mask", None)
+ model_outputs["is_last"] = is_last
+ return model_outputs
+
+ def postprocess(self, model_outputs, top_k=1, **kwargs):
+ if self.model_type == ModelType.VisionEncoderDecoder:
+ answers = [self.postprocess_encoder_decoder_single(o) for o in model_outputs]
+ else:
+ answers = self.postprocess_extractive_qa(model_outputs, top_k=top_k, **kwargs)
+
+ answers = sorted(answers, key=lambda x: x.get("score", 0), reverse=True)[:top_k]
+ return answers
+
+ def postprocess_encoder_decoder_single(self, model_outputs, **kwargs):
+ sequence = self.tokenizer.batch_decode(model_outputs["sequences"])[0]
+
+ # TODO: A lot of this logic is specific to Donut and should probably be handled in the tokenizer
+ # (see https://github.com/huggingface/transformers/pull/18414/files#r961747408 for more context).
+ sequence = sequence.replace(self.tokenizer.eos_token, "").replace(self.tokenizer.pad_token, "")
+ sequence = re.sub(r"<.*?>", "", sequence, count=1).strip() # remove first task start token
+ ret = {
+ "answer": None,
+ }
+
+ answer = re.search(r"(.*)", sequence)
+ if answer is not None:
+ ret["answer"] = answer.group(1).strip()
+ return ret
+
+ def postprocess_extractive_qa(
+ self, model_outputs, top_k=1, handle_impossible_answer=False, max_answer_len=15, **kwargs
+ ):
+ min_null_score = 1000000 # large and positive
+ answers = []
+ for output in model_outputs:
+ words = output["words"]
+
+ if output["start_logits"].dtype in (torch.bfloat16, torch.float16):
+ output["start_logits"] = output["start_logits"].float()
+ if output["end_logits"].dtype in (torch.bfloat16, torch.float16):
+ output["end_logits"] = output["end_logits"].float()
+
+ starts, ends, scores, min_null_score = select_starts_ends(
+ start=output["start_logits"],
+ end=output["end_logits"],
+ p_mask=output["p_mask"],
+ attention_mask=output["attention_mask"].numpy()
+ if output.get("attention_mask", None) is not None
+ else None,
+ min_null_score=min_null_score,
+ top_k=top_k,
+ handle_impossible_answer=handle_impossible_answer,
+ max_answer_len=max_answer_len,
+ )
+ word_ids = output["word_ids"]
+ for start, end, score in zip(starts, ends, scores):
+ word_start, word_end = word_ids[start], word_ids[end]
+ if word_start is not None and word_end is not None:
+ answers.append(
+ {
+ "score": float(score),
+ "answer": " ".join(words[word_start : word_end + 1]),
+ "start": word_start,
+ "end": word_end,
+ }
+ )
+
+ if handle_impossible_answer:
+ answers.append({"score": min_null_score, "answer": "", "start": 0, "end": 0})
+
+ return answers
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/feature_extraction.py b/.venv/lib/python3.12/site-packages/transformers/pipelines/feature_extraction.py
new file mode 100644
index 0000000000000000000000000000000000000000..a37f147605f04347efa34f587d7fdebe8074f3b5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/pipelines/feature_extraction.py
@@ -0,0 +1,88 @@
+from typing import Any
+
+from ..utils import add_end_docstrings
+from .base import GenericTensor, Pipeline, build_pipeline_init_args
+
+
+@add_end_docstrings(
+ build_pipeline_init_args(has_tokenizer=True, supports_binary_output=False),
+ r"""
+ tokenize_kwargs (`dict`, *optional*):
+ Additional dictionary of keyword arguments passed along to the tokenizer.
+ return_tensors (`bool`, *optional*):
+ If `True`, returns a tensor according to the specified framework, otherwise returns a list.""",
+)
+class FeatureExtractionPipeline(Pipeline):
+ """
+ Feature extraction pipeline uses no model head. This pipeline extracts the hidden states from the base
+ transformer, which can be used as features in downstream tasks.
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> extractor = pipeline(model="google-bert/bert-base-uncased", task="feature-extraction")
+ >>> result = extractor("This is a simple test.", return_tensors=True)
+ >>> result.shape # This is a tensor of shape [1, sequence_length, hidden_dimension] representing the input string.
+ torch.Size([1, 8, 768])
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This feature extraction pipeline can currently be loaded from [`pipeline`] using the task identifier:
+ `"feature-extraction"`.
+
+ All models may be used for this pipeline. See a list of all models, including community-contributed models on
+ [huggingface.co/models](https://huggingface.co/models).
+ """
+
+ _load_processor = False
+ _load_image_processor = False
+ _load_feature_extractor = False
+ _load_tokenizer = True
+
+ def _sanitize_parameters(self, truncation=None, tokenize_kwargs=None, return_tensors=None, **kwargs):
+ if tokenize_kwargs is None:
+ tokenize_kwargs = {}
+
+ if truncation is not None:
+ if "truncation" in tokenize_kwargs:
+ raise ValueError(
+ "truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)"
+ )
+ tokenize_kwargs["truncation"] = truncation
+
+ preprocess_params = tokenize_kwargs
+
+ postprocess_params = {}
+ if return_tensors is not None:
+ postprocess_params["return_tensors"] = return_tensors
+
+ return preprocess_params, {}, postprocess_params
+
+ def preprocess(self, inputs, **tokenize_kwargs) -> dict[str, GenericTensor]:
+ model_inputs = self.tokenizer(inputs, return_tensors="pt", **tokenize_kwargs)
+ return model_inputs
+
+ def _forward(self, model_inputs):
+ model_outputs = self.model(**model_inputs)
+ return model_outputs
+
+ def postprocess(self, model_outputs, return_tensors=False):
+ # [0] is the first available tensor, logits or last_hidden_state.
+ if return_tensors:
+ return model_outputs[0]
+ return model_outputs[0].tolist()
+
+ def __call__(self, *args: str | list[str], **kwargs: Any) -> Any | list[Any]:
+ """
+ Extract the features of the input(s) text.
+
+ Args:
+ args (`str` or `list[str]`): One or several texts (or one list of texts) to get the features of.
+
+ Return:
+ A nested list of `float`: The features computed by the model.
+ """
+ return super().__call__(*args, **kwargs)
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/fill_mask.py b/.venv/lib/python3.12/site-packages/transformers/pipelines/fill_mask.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ea7c487be76458ff66508a6506bc11437937cb1
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/pipelines/fill_mask.py
@@ -0,0 +1,259 @@
+from typing import Any, overload
+
+import numpy as np
+
+from ..utils import add_end_docstrings, is_torch_available, logging
+from .base import GenericTensor, Pipeline, PipelineException, build_pipeline_init_args
+
+
+if is_torch_available():
+ import torch
+
+
+logger = logging.get_logger(__name__)
+
+
+@add_end_docstrings(
+ build_pipeline_init_args(has_tokenizer=True),
+ r"""
+ top_k (`int`, *optional*, defaults to 5):
+ The number of predictions to return.
+ targets (`str` or `list[str]`, *optional*):
+ When passed, the model will limit the scores to the passed targets instead of looking up in the whole
+ vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
+ token will be used (with a warning, and that might be slower).
+ tokenizer_kwargs (`dict`, *optional*):
+ Additional dictionary of keyword arguments passed along to the tokenizer.""",
+)
+class FillMaskPipeline(Pipeline):
+ _load_processor = False
+ _load_image_processor = False
+ _load_feature_extractor = False
+ _load_tokenizer = True
+
+ """
+ Masked language modeling prediction pipeline using any `ModelWithLMHead`. See the [masked language modeling
+ examples](../task_summary#masked-language-modeling) for more information.
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> fill_masker = pipeline(model="google-bert/bert-base-uncased")
+ >>> fill_masker("This is a simple [MASK].")
+ [{'score': 0.042, 'token': 3291, 'token_str': 'problem', 'sequence': 'this is a simple problem.'}, {'score': 0.031, 'token': 3160, 'token_str': 'question', 'sequence': 'this is a simple question.'}, {'score': 0.03, 'token': 8522, 'token_str': 'equation', 'sequence': 'this is a simple equation.'}, {'score': 0.027, 'token': 2028, 'token_str': 'one', 'sequence': 'this is a simple one.'}, {'score': 0.024, 'token': 3627, 'token_str': 'rule', 'sequence': 'this is a simple rule.'}]
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This mask filling pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"fill-mask"`.
+
+ The models that this pipeline can use are models that have been trained with a masked language modeling objective,
+ which includes the bi-directional models in the library. See the up-to-date list of available models on
+ [huggingface.co/models](https://huggingface.co/models?filter=fill-mask).
+
+
+
+ This pipeline only works for inputs with exactly one token masked. Experimental: We added support for multiple
+ masks. The returned values are raw model output, and correspond to disjoint probabilities where one might expect
+ joint probabilities (See [discussion](https://github.com/huggingface/transformers/pull/10222)).
+
+
+
+
+
+ This pipeline now supports tokenizer_kwargs. For example try:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> fill_masker = pipeline(model="google-bert/bert-base-uncased")
+ >>> tokenizer_kwargs = {"truncation": True}
+ >>> fill_masker(
+ ... "This is a simple [MASK]. " + "...with a large amount of repeated text appended. " * 100,
+ ... tokenizer_kwargs=tokenizer_kwargs,
+ ... )
+ ```
+
+
+
+
+
+ """
+
+ def get_masked_index(self, input_ids: GenericTensor) -> np.ndarray:
+ masked_index = torch.nonzero(input_ids == self.tokenizer.mask_token_id, as_tuple=False)
+ return masked_index
+
+ def _ensure_exactly_one_mask_token(self, input_ids: GenericTensor) -> np.ndarray:
+ masked_index = self.get_masked_index(input_ids)
+ numel = np.prod(masked_index.shape)
+ if numel < 1:
+ raise PipelineException(
+ "fill-mask",
+ self.model.base_model_prefix,
+ f"No mask_token ({self.tokenizer.mask_token}) found on the input",
+ )
+
+ def ensure_exactly_one_mask_token(self, model_inputs: GenericTensor):
+ if isinstance(model_inputs, list):
+ for model_input in model_inputs:
+ self._ensure_exactly_one_mask_token(model_input["input_ids"][0])
+ else:
+ for input_ids in model_inputs["input_ids"]:
+ self._ensure_exactly_one_mask_token(input_ids)
+
+ def preprocess(
+ self, inputs, return_tensors=None, tokenizer_kwargs=None, **preprocess_parameters
+ ) -> dict[str, GenericTensor]:
+ if return_tensors is None:
+ return_tensors = "pt"
+ if tokenizer_kwargs is None:
+ tokenizer_kwargs = {}
+
+ model_inputs = self.tokenizer(inputs, return_tensors=return_tensors, **tokenizer_kwargs)
+ self.ensure_exactly_one_mask_token(model_inputs)
+ return model_inputs
+
+ def _forward(self, model_inputs):
+ model_outputs = self.model(**model_inputs)
+ model_outputs["input_ids"] = model_inputs["input_ids"]
+ return model_outputs
+
+ def postprocess(self, model_outputs, top_k=5, target_ids=None):
+ # Cap top_k if there are targets
+ if target_ids is not None and target_ids.shape[0] < top_k:
+ top_k = target_ids.shape[0]
+ input_ids = model_outputs["input_ids"][0]
+ outputs = model_outputs["logits"]
+
+ masked_index = torch.nonzero(input_ids == self.tokenizer.mask_token_id, as_tuple=False).squeeze(-1)
+ # Fill mask pipeline supports only one ${mask_token} per sample
+
+ logits = outputs[0, masked_index, :]
+ probs = logits.softmax(dim=-1)
+ if target_ids is not None:
+ probs = probs[..., target_ids]
+
+ values, predictions = probs.topk(top_k)
+
+ result = []
+ single_mask = values.shape[0] == 1
+ for i, (_values, _predictions) in enumerate(zip(values.tolist(), predictions.tolist())):
+ row = []
+ for v, p in zip(_values, _predictions):
+ # Copy is important since we're going to modify this array in place
+ tokens = input_ids.numpy().copy()
+ if target_ids is not None:
+ p = target_ids[p].tolist()
+
+ tokens[masked_index[i]] = p
+ # Filter padding out:
+ tokens = tokens[np.where(tokens != self.tokenizer.pad_token_id)]
+ # Originally we skip special tokens to give readable output.
+ # For multi masks though, the other [MASK] would be removed otherwise
+ # making the output look odd, so we add them back
+ sequence = self.tokenizer.decode(tokens, skip_special_tokens=single_mask)
+ proposition = {"score": v, "token": p, "token_str": self.tokenizer.decode([p]), "sequence": sequence}
+ row.append(proposition)
+ result.append(row)
+ if single_mask:
+ return result[0]
+ return result
+
+ def get_target_ids(self, targets):
+ if isinstance(targets, str):
+ targets = [targets]
+ try:
+ vocab = self.tokenizer.get_vocab()
+ except Exception:
+ vocab = {}
+ target_ids = []
+ for target in targets:
+ id_ = vocab.get(target)
+ if id_ is None:
+ input_ids = self.tokenizer(
+ target,
+ add_special_tokens=False,
+ return_attention_mask=False,
+ return_token_type_ids=False,
+ max_length=1,
+ truncation=True,
+ )["input_ids"]
+ if len(input_ids) == 0:
+ logger.warning(
+ f"The specified target token `{target}` does not exist in the model vocabulary. "
+ "We cannot replace it with anything meaningful, ignoring it"
+ )
+ continue
+ id_ = input_ids[0]
+ # XXX: If users encounter this pass
+ # it becomes pretty slow, so let's make sure
+ # The warning enables them to fix the input to
+ # get faster performance.
+ logger.warning(
+ f"The specified target token `{target}` does not exist in the model vocabulary. "
+ f"Replacing with `{self.tokenizer.convert_ids_to_tokens(id_)}`."
+ )
+ target_ids.append(id_)
+ target_ids = list(set(target_ids))
+ if len(target_ids) == 0:
+ raise ValueError("At least one target must be provided when passed.")
+ target_ids = np.array(target_ids)
+ return target_ids
+
+ def _sanitize_parameters(self, top_k=None, targets=None, tokenizer_kwargs=None):
+ preprocess_params = {}
+
+ if tokenizer_kwargs is not None:
+ preprocess_params["tokenizer_kwargs"] = tokenizer_kwargs
+
+ postprocess_params = {}
+
+ if targets is not None:
+ target_ids = self.get_target_ids(targets)
+ postprocess_params["target_ids"] = target_ids
+
+ if top_k is not None:
+ postprocess_params["top_k"] = top_k
+
+ if self.tokenizer.mask_token_id is None:
+ raise PipelineException(
+ "fill-mask", self.model.base_model_prefix, "The tokenizer does not define a `mask_token`."
+ )
+ return preprocess_params, {}, postprocess_params
+
+ @overload
+ def __call__(self, inputs: str, **kwargs: Any) -> list[dict[str, Any]]: ...
+
+ @overload
+ def __call__(self, inputs: list[str], **kwargs: Any) -> list[list[dict[str, Any]]]: ...
+
+ def __call__(self, inputs: str | list[str], **kwargs: Any) -> list[dict[str, Any]] | list[list[dict[str, Any]]]:
+ """
+ Fill the masked token in the text(s) given as inputs.
+
+ Args:
+ inputs (`str` or `list[str]`):
+ One or several texts (or one list of prompts) with masked tokens.
+ targets (`str` or `list[str]`, *optional*):
+ When passed, the model will limit the scores to the passed targets instead of looking up in the whole
+ vocab. If the provided targets are not in the model vocab, they will be tokenized and the first
+ resulting token will be used (with a warning, and that might be slower).
+ top_k (`int`, *optional*):
+ When passed, overrides the number of predictions to return.
+
+ Return:
+ A list or a list of list of `dict`: Each result comes as list of dictionaries with the following keys:
+
+ - **sequence** (`str`) -- The corresponding input with the mask token prediction.
+ - **score** (`float`) -- The corresponding probability.
+ - **token** (`int`) -- The predicted token id (to replace the masked one).
+ - **token_str** (`str`) -- The predicted token (to replace the masked one).
+ """
+ outputs = super().__call__(inputs, **kwargs)
+ if isinstance(inputs, list) and len(inputs) == 1:
+ return outputs[0]
+ return outputs
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/image_classification.py b/.venv/lib/python3.12/site-packages/transformers/pipelines/image_classification.py
new file mode 100644
index 0000000000000000000000000000000000000000..18a570df6e21f8e7ebd15d7771408cf324e306de
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/pipelines/image_classification.py
@@ -0,0 +1,229 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import Any, Union, overload
+
+import numpy as np
+
+from ..utils import (
+ ExplicitEnum,
+ add_end_docstrings,
+ is_torch_available,
+ is_vision_available,
+ logging,
+ requires_backends,
+)
+from .base import Pipeline, build_pipeline_init_args
+
+
+if is_vision_available():
+ from PIL import Image
+
+ from ..image_utils import load_image
+
+if is_torch_available():
+ import torch
+
+ from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES
+
+logger = logging.get_logger(__name__)
+
+
+# Copied from transformers.pipelines.text_classification.sigmoid
+def sigmoid(_outputs):
+ return 1.0 / (1.0 + np.exp(-_outputs))
+
+
+# Copied from transformers.pipelines.text_classification.softmax
+def softmax(_outputs):
+ maxes = np.max(_outputs, axis=-1, keepdims=True)
+ shifted_exp = np.exp(_outputs - maxes)
+ return shifted_exp / shifted_exp.sum(axis=-1, keepdims=True)
+
+
+# Copied from transformers.pipelines.text_classification.ClassificationFunction
+class ClassificationFunction(ExplicitEnum):
+ SIGMOID = "sigmoid"
+ SOFTMAX = "softmax"
+ NONE = "none"
+
+
+@add_end_docstrings(
+ build_pipeline_init_args(has_image_processor=True),
+ r"""
+ function_to_apply (`str`, *optional*, defaults to `"default"`):
+ The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:
+
+ - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model
+ has several labels, will apply the softmax function on the output.
+ - `"sigmoid"`: Applies the sigmoid function on the output.
+ - `"softmax"`: Applies the softmax function on the output.
+ - `"none"`: Does not apply any function on the output.""",
+)
+class ImageClassificationPipeline(Pipeline):
+ """
+ Image classification pipeline using any `AutoModelForImageClassification`. This pipeline predicts the class of an
+ image.
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> classifier = pipeline(model="microsoft/beit-base-patch16-224-pt22k-ft22k")
+ >>> classifier("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
+ [{'score': 0.442, 'label': 'macaw'}, {'score': 0.088, 'label': 'popinjay'}, {'score': 0.075, 'label': 'parrot'}, {'score': 0.073, 'label': 'parodist, lampooner'}, {'score': 0.046, 'label': 'poll, poll_parrot'}]
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This image classification pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"image-classification"`.
+
+ See the list of available models on
+ [huggingface.co/models](https://huggingface.co/models?filter=image-classification).
+ """
+
+ function_to_apply: ClassificationFunction = ClassificationFunction.NONE
+ _load_processor = False
+ _load_image_processor = True
+ _load_feature_extractor = False
+ _load_tokenizer = False
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ requires_backends(self, "vision")
+ self.check_model_type(MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES)
+
+ def _sanitize_parameters(self, top_k=None, function_to_apply=None, timeout=None):
+ preprocess_params = {}
+ if timeout is not None:
+ preprocess_params["timeout"] = timeout
+ postprocess_params = {}
+ if top_k is not None:
+ postprocess_params["top_k"] = top_k
+ if isinstance(function_to_apply, str):
+ function_to_apply = ClassificationFunction(function_to_apply.lower())
+ if function_to_apply is not None:
+ postprocess_params["function_to_apply"] = function_to_apply
+ return preprocess_params, {}, postprocess_params
+
+ @overload
+ def __call__(self, inputs: Union[str, "Image.Image"], **kwargs: Any) -> list[dict[str, Any]]: ...
+
+ @overload
+ def __call__(self, inputs: list[str] | list["Image.Image"], **kwargs: Any) -> list[list[dict[str, Any]]]: ...
+
+ def __call__(
+ self, inputs: Union[str, list[str], "Image.Image", list["Image.Image"]], **kwargs: Any
+ ) -> list[dict[str, Any]] | list[list[dict[str, Any]]]:
+ """
+ Assign labels to the image(s) passed as inputs.
+
+ Args:
+ inputs (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`):
+ The pipeline handles three types of images:
+
+ - A string containing a http link pointing to an image
+ - A string containing a local path to an image
+ - An image loaded in PIL directly
+
+ The pipeline accepts either a single image or a batch of images, which must then be passed as a string.
+ Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL
+ images.
+ function_to_apply (`str`, *optional*, defaults to `"default"`):
+ The function to apply to the model outputs in order to retrieve the scores. Accepts four different
+ values:
+
+ If this argument is not specified, then it will apply the following functions according to the number
+ of labels:
+
+ - If the model has a single label, will apply the sigmoid function on the output.
+ - If the model has several labels, will apply the softmax function on the output.
+
+ Possible values are:
+
+ - `"sigmoid"`: Applies the sigmoid function on the output.
+ - `"softmax"`: Applies the softmax function on the output.
+ - `"none"`: Does not apply any function on the output.
+ top_k (`int`, *optional*, defaults to 5):
+ The number of top labels that will be returned by the pipeline. If the provided number is higher than
+ the number of labels available in the model configuration, it will default to the number of labels.
+ timeout (`float`, *optional*, defaults to None):
+ The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
+ the call may block forever.
+
+ Return:
+ A dictionary or a list of dictionaries containing result. If the input is a single image, will return a
+ dictionary, if the input is a list of several images, will return a list of dictionaries corresponding to
+ the images.
+
+ The dictionaries contain the following keys:
+
+ - **label** (`str`) -- The label identified by the model.
+ - **score** (`int`) -- The score attributed by the model for that label.
+ """
+ # After deprecation of this is completed, remove the default `None` value for `images`
+ if "images" in kwargs:
+ inputs = kwargs.pop("images")
+ if inputs is None:
+ raise ValueError("Cannot call the image-classification pipeline without an inputs argument!")
+ return super().__call__(inputs, **kwargs)
+
+ def preprocess(self, image, timeout=None):
+ image = load_image(image, timeout=timeout)
+ model_inputs = self.image_processor(images=image, return_tensors="pt")
+ model_inputs = model_inputs.to(self.dtype)
+ return model_inputs
+
+ def _forward(self, model_inputs):
+ model_outputs = self.model(**model_inputs)
+ return model_outputs
+
+ def postprocess(self, model_outputs, function_to_apply=None, top_k=5):
+ if function_to_apply is None:
+ if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
+ function_to_apply = ClassificationFunction.SIGMOID
+ elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
+ function_to_apply = ClassificationFunction.SOFTMAX
+ elif hasattr(self.model.config, "function_to_apply") and function_to_apply is None:
+ function_to_apply = self.model.config.function_to_apply
+ else:
+ function_to_apply = ClassificationFunction.NONE
+
+ if top_k > self.model.config.num_labels:
+ top_k = self.model.config.num_labels
+
+ outputs = model_outputs["logits"][0]
+ if outputs.dtype in (torch.bfloat16, torch.float16):
+ outputs = outputs.to(torch.float32).numpy()
+ else:
+ outputs = outputs.numpy()
+
+ if function_to_apply == ClassificationFunction.SIGMOID:
+ scores = sigmoid(outputs)
+ elif function_to_apply == ClassificationFunction.SOFTMAX:
+ scores = softmax(outputs)
+ elif function_to_apply == ClassificationFunction.NONE:
+ scores = outputs
+ else:
+ raise ValueError(f"Unrecognized `function_to_apply` argument: {function_to_apply}")
+
+ dict_scores = [
+ {"label": self.model.config.id2label[i], "score": score.item()} for i, score in enumerate(scores)
+ ]
+ dict_scores.sort(key=lambda x: x["score"], reverse=True)
+ if top_k is not None:
+ dict_scores = dict_scores[:top_k]
+
+ return dict_scores
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/image_feature_extraction.py b/.venv/lib/python3.12/site-packages/transformers/pipelines/image_feature_extraction.py
new file mode 100644
index 0000000000000000000000000000000000000000..d049957a4138ac44a3a097832a4e754a3fddd0d7
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/pipelines/image_feature_extraction.py
@@ -0,0 +1,115 @@
+from typing import Any, Union
+
+from ..utils import add_end_docstrings, is_vision_available
+from .base import GenericTensor, Pipeline, build_pipeline_init_args
+
+
+if is_vision_available():
+ from PIL import Image
+
+ from ..image_utils import load_image
+
+
+@add_end_docstrings(
+ build_pipeline_init_args(has_image_processor=True),
+ """
+ image_processor_kwargs (`dict`, *optional*):
+ Additional dictionary of keyword arguments passed along to the image processor e.g.
+ {"size": {"height": 100, "width": 100}}
+ pool (`bool`, *optional*, defaults to `False`):
+ Whether or not to return the pooled output. If `False`, the model will return the raw hidden states.
+ """,
+)
+class ImageFeatureExtractionPipeline(Pipeline):
+ """
+ Image feature extraction pipeline uses no model head. This pipeline extracts the hidden states from the base
+ transformer, which can be used as features in downstream tasks.
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> extractor = pipeline(model="google/vit-base-patch16-224", task="image-feature-extraction")
+ >>> result = extractor("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", return_tensors=True)
+ >>> result.shape # This is a tensor of shape [1, sequence_length, hidden_dimension] representing the input image.
+ torch.Size([1, 197, 768])
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This image feature extraction pipeline can currently be loaded from [`pipeline`] using the task identifier:
+ `"image-feature-extraction"`.
+
+ All vision models may be used for this pipeline. See a list of all models, including community-contributed models on
+ [huggingface.co/models](https://huggingface.co/models).
+ """
+
+ _load_processor = False
+ _load_image_processor = True
+ _load_feature_extractor = False
+ _load_tokenizer = False
+
+ def _sanitize_parameters(self, image_processor_kwargs=None, return_tensors=None, pool=None, **kwargs):
+ preprocess_params = {} if image_processor_kwargs is None else image_processor_kwargs
+
+ postprocess_params = {}
+ if pool is not None:
+ postprocess_params["pool"] = pool
+ if return_tensors is not None:
+ postprocess_params["return_tensors"] = return_tensors
+
+ if "timeout" in kwargs:
+ preprocess_params["timeout"] = kwargs["timeout"]
+
+ return preprocess_params, {}, postprocess_params
+
+ def preprocess(self, image, timeout=None, **image_processor_kwargs) -> dict[str, GenericTensor]:
+ image = load_image(image, timeout=timeout)
+ model_inputs = self.image_processor(image, return_tensors="pt", **image_processor_kwargs)
+ model_inputs = model_inputs.to(self.dtype)
+ return model_inputs
+
+ def _forward(self, model_inputs):
+ model_outputs = self.model(**model_inputs)
+ return model_outputs
+
+ def postprocess(self, model_outputs, pool=None, return_tensors=False):
+ pool = pool if pool is not None else False
+
+ if pool:
+ if "pooler_output" not in model_outputs:
+ raise ValueError(
+ "No pooled output was returned. Make sure the model has a `pooler` layer when using the `pool` option."
+ )
+ outputs = model_outputs["pooler_output"]
+ else:
+ # [0] is the first available tensor, logits or last_hidden_state.
+ outputs = model_outputs[0]
+
+ if return_tensors:
+ return outputs
+ return outputs.tolist()
+
+ def __call__(self, *args: Union[str, "Image.Image", list["Image.Image"], list[str]], **kwargs: Any) -> list[Any]:
+ """
+ Extract the features of the input(s).
+
+ Args:
+ images (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`):
+ The pipeline handles three types of images:
+
+ - A string containing a http link pointing to an image
+ - A string containing a local path to an image
+ - An image loaded in PIL directly
+
+ The pipeline accepts either a single image or a batch of images, which must then be passed as a string.
+ Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL
+ images.
+ timeout (`float`, *optional*, defaults to None):
+ The maximum time in seconds to wait for fetching images from the web. If None, no timeout is used and
+ the call may block forever.
+ Return:
+ A nested list of `float`: The features computed by the model.
+ """
+ return super().__call__(*args, **kwargs)
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/image_segmentation.py b/.venv/lib/python3.12/site-packages/transformers/pipelines/image_segmentation.py
new file mode 100644
index 0000000000000000000000000000000000000000..49854beb5a40b1c3017febba20b72678e81b9374
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/pipelines/image_segmentation.py
@@ -0,0 +1,223 @@
+from typing import Any, Union, overload
+
+import numpy as np
+
+from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends
+from .base import Pipeline, build_pipeline_init_args
+
+
+if is_vision_available():
+ from PIL import Image
+
+ from ..image_utils import load_image
+
+if is_torch_available():
+ from ..models.auto.modeling_auto import (
+ MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES,
+ MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING_NAMES,
+ MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES,
+ MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES,
+ )
+
+
+logger = logging.get_logger(__name__)
+
+
+@add_end_docstrings(build_pipeline_init_args(has_image_processor=True))
+class ImageSegmentationPipeline(Pipeline):
+ """
+ Image segmentation pipeline using any `AutoModelForXXXSegmentation`. This pipeline predicts masks of objects and
+ their classes.
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> segmenter = pipeline(model="facebook/detr-resnet-50-panoptic")
+ >>> segments = segmenter("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
+ >>> len(segments)
+ 2
+
+ >>> segments[0]["label"]
+ 'bird'
+
+ >>> segments[1]["label"]
+ 'bird'
+
+ >>> type(segments[0]["mask"]) # This is a black and white mask showing where is the bird on the original image.
+
+
+ >>> segments[0]["mask"].size
+ (768, 512)
+ ```
+
+
+ This image segmentation pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"image-segmentation"`.
+
+ See the list of available models on
+ [huggingface.co/models](https://huggingface.co/models?filter=image-segmentation).
+ """
+
+ _load_processor = False
+ _load_image_processor = True
+ _load_feature_extractor = False
+ _load_tokenizer = None # Oneformer uses it but no-one else does
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ requires_backends(self, "vision")
+ mapping = MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES.copy()
+ mapping.update(MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES)
+ mapping.update(MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING_NAMES)
+ mapping.update(MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES)
+ self.check_model_type(mapping)
+
+ def _sanitize_parameters(self, **kwargs):
+ preprocess_kwargs = {}
+ postprocess_kwargs = {}
+ if "subtask" in kwargs:
+ postprocess_kwargs["subtask"] = kwargs["subtask"]
+ preprocess_kwargs["subtask"] = kwargs["subtask"]
+ if "threshold" in kwargs:
+ postprocess_kwargs["threshold"] = kwargs["threshold"]
+ if "mask_threshold" in kwargs:
+ postprocess_kwargs["mask_threshold"] = kwargs["mask_threshold"]
+ if "overlap_mask_area_threshold" in kwargs:
+ postprocess_kwargs["overlap_mask_area_threshold"] = kwargs["overlap_mask_area_threshold"]
+ if "timeout" in kwargs:
+ preprocess_kwargs["timeout"] = kwargs["timeout"]
+
+ return preprocess_kwargs, {}, postprocess_kwargs
+
+ @overload
+ def __call__(self, inputs: Union[str, "Image.Image"], **kwargs: Any) -> list[dict[str, Any]]: ...
+
+ @overload
+ def __call__(self, inputs: list[str] | list["Image.Image"], **kwargs: Any) -> list[list[dict[str, Any]]]: ...
+
+ def __call__(
+ self, inputs: Union[str, "Image.Image", list[str], list["Image.Image"]], **kwargs: Any
+ ) -> list[dict[str, Any]] | list[list[dict[str, Any]]]:
+ """
+ Perform segmentation (detect masks & classes) in the image(s) passed as inputs.
+
+ Args:
+ inputs (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`):
+ The pipeline handles three types of images:
+
+ - A string containing an HTTP(S) link pointing to an image
+ - A string containing a local path to an image
+ - An image loaded in PIL directly
+
+ The pipeline accepts either a single image or a batch of images. Images in a batch must all be in the
+ same format: all as HTTP(S) links, all as local paths, or all as PIL images.
+ subtask (`str`, *optional*):
+ Segmentation task to be performed, choose [`semantic`, `instance` and `panoptic`] depending on model
+ capabilities. If not set, the pipeline will attempt tp resolve in the following order:
+ `panoptic`, `instance`, `semantic`.
+ threshold (`float`, *optional*, defaults to 0.9):
+ Probability threshold to filter out predicted masks.
+ mask_threshold (`float`, *optional*, defaults to 0.5):
+ Threshold to use when turning the predicted masks into binary values.
+ overlap_mask_area_threshold (`float`, *optional*, defaults to 0.5):
+ Mask overlap threshold to eliminate small, disconnected segments.
+ timeout (`float`, *optional*, defaults to None):
+ The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
+ the call may block forever.
+
+ Return:
+ If the input is a single image, will return a list of dictionaries, if the input is a list of several images,
+ will return a list of list of dictionaries corresponding to each image.
+
+ The dictionaries contain the mask, label and score (where applicable) of each detected object and contains
+ the following keys:
+
+ - **label** (`str`) -- The class label identified by the model.
+ - **mask** (`PIL.Image`) -- A binary mask of the detected object as a Pil Image of shape (width, height) of
+ the original image. Returns a mask filled with zeros if no object is found.
+ - **score** (*optional* `float`) -- Optionally, when the model is capable of estimating a confidence of the
+ "object" described by the label and the mask.
+ """
+ # After deprecation of this is completed, remove the default `None` value for `images`
+ if "images" in kwargs:
+ inputs = kwargs.pop("images")
+ if inputs is None:
+ raise ValueError("Cannot call the image-classification pipeline without an inputs argument!")
+ return super().__call__(inputs, **kwargs)
+
+ def preprocess(self, image, subtask=None, timeout=None):
+ image = load_image(image, timeout=timeout)
+ target_size = [(image.height, image.width)]
+ if self.model.config.__class__.__name__ == "OneFormerConfig":
+ if subtask is None:
+ kwargs = {}
+ else:
+ kwargs = {"task_inputs": [subtask]}
+ inputs = self.image_processor(images=[image], return_tensors="pt", **kwargs)
+ inputs = inputs.to(self.dtype)
+ inputs["task_inputs"] = self.tokenizer(
+ inputs["task_inputs"],
+ padding="max_length",
+ max_length=self.model.config.task_seq_len,
+ return_tensors="pt",
+ )["input_ids"]
+ else:
+ inputs = self.image_processor(images=[image], return_tensors="pt")
+ inputs = inputs.to(self.dtype)
+ inputs["target_size"] = target_size
+ return inputs
+
+ def _forward(self, model_inputs):
+ target_size = model_inputs.pop("target_size")
+ model_outputs = self.model(**model_inputs)
+ model_outputs["target_size"] = target_size
+ return model_outputs
+
+ def postprocess(
+ self, model_outputs, subtask=None, threshold=0.9, mask_threshold=0.5, overlap_mask_area_threshold=0.5
+ ):
+ fn = None
+ if subtask in {"panoptic", None} and hasattr(self.image_processor, "post_process_panoptic_segmentation"):
+ fn = self.image_processor.post_process_panoptic_segmentation
+ elif subtask in {"instance", None} and hasattr(self.image_processor, "post_process_instance_segmentation"):
+ fn = self.image_processor.post_process_instance_segmentation
+
+ if fn is not None:
+ outputs = fn(
+ model_outputs,
+ threshold=threshold,
+ mask_threshold=mask_threshold,
+ overlap_mask_area_threshold=overlap_mask_area_threshold,
+ target_sizes=model_outputs["target_size"],
+ )[0]
+
+ annotation = []
+ segmentation = outputs["segmentation"]
+
+ for segment in outputs["segments_info"]:
+ mask = (segmentation == segment["id"]) * 255
+ mask = Image.fromarray(mask.numpy().astype(np.uint8), mode="L")
+ label = self.model.config.id2label[segment["label_id"]]
+ score = segment["score"]
+ annotation.append({"score": score, "label": label, "mask": mask})
+
+ elif subtask in {"semantic", None} and hasattr(self.image_processor, "post_process_semantic_segmentation"):
+ outputs = self.image_processor.post_process_semantic_segmentation(
+ model_outputs, target_sizes=model_outputs["target_size"]
+ )[0]
+
+ annotation = []
+ segmentation = outputs.numpy()
+ labels = np.unique(segmentation)
+
+ for label in labels:
+ mask = (segmentation == label) * 255
+ mask = Image.fromarray(mask.astype(np.uint8), mode="L")
+ label = self.model.config.id2label[label]
+ annotation.append({"score": None, "label": label, "mask": mask})
+ else:
+ raise ValueError(f"Subtask {subtask} is not supported for model {type(self.model)}")
+ return annotation
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/image_text_to_text.py b/.venv/lib/python3.12/site-packages/transformers/pipelines/image_text_to_text.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d28b91ab2ab9a8db3110f3aff05ded52454ec7b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/pipelines/image_text_to_text.py
@@ -0,0 +1,480 @@
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import enum
+from typing import Any, Union, overload
+
+from ..generation import GenerationConfig
+from ..processing_utils import ProcessingKwargs, Unpack
+from ..utils import (
+ add_end_docstrings,
+ is_torch_available,
+ is_vision_available,
+ logging,
+ requires_backends,
+)
+from ..utils.chat_template_utils import Chat
+from .base import Pipeline, build_pipeline_init_args
+
+
+if is_vision_available():
+ from PIL import Image
+
+ from ..image_utils import load_images, valid_images
+
+
+if is_torch_available():
+ from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES
+ from .pt_utils import KeyDataset
+
+logger = logging.get_logger(__name__)
+
+IMAGE_TOKEN = ""
+
+
+class ReturnType(enum.Enum):
+ TENSORS = 0
+ NEW_TEXT = 1
+ FULL_TEXT = 2
+
+
+@add_end_docstrings(build_pipeline_init_args(has_processor=True))
+class ImageTextToTextPipeline(Pipeline):
+ """
+ Image-text-to-text pipeline using an `AutoModelForImageTextToText`. This pipeline generates text given an image and text.
+ When the underlying model is a conversational model, it can also accept one or more chats,
+ in which case the pipeline will operate in chat mode and will continue the chat(s) by adding its response(s).
+ Each chat takes the form of a list of dicts, where each dict contains "role" and "content" keys.
+
+ Unless the model you're using explicitly sets these generation parameters in its configuration files
+ (`generation_config.json`), the following default values will be used:
+ - max_new_tokens: 256
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> pipe = pipeline(task="image-text-to-text", model="Salesforce/blip-image-captioning-base")
+ >>> pipe("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", text="A photo of")
+ [{'generated_text': 'a photo of two birds'}]
+ ```
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> pipe = pipeline("image-text-to-text", model="llava-hf/llava-interleave-qwen-0.5b-hf")
+ >>> messages = [
+ >>> {
+ >>> "role": "user",
+ >>> "content": [
+ >>> {
+ >>> "type": "image",
+ >>> "url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg",
+ >>> },
+ >>> {"type": "text", "text": "Describe this image."},
+ >>> ],
+ >>> },
+ >>> {
+ >>> "role": "assistant",
+ >>> "content": [
+ >>> {"type": "text", "text": "There is a dog and"},
+ >>> ],
+ >>> },
+ >>> ]
+ >>> pipe(text=messages, max_new_tokens=20, return_full_text=False)
+ [{'input_text': [{'role': 'user',
+ 'content': [{'type': 'image',
+ 'url': 'https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg'},
+ {'type': 'text', 'text': 'Describe this image.'}]},
+ {'role': 'assistant',
+ 'content': [{'type': 'text', 'text': 'There is a dog and'}]}],
+ 'generated_text': ' a person in the image. The dog is sitting on the sand, and the person is sitting on'}]
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This image-text to text pipeline can currently be loaded from pipeline() using the following task identifier:
+ "image-text-to-text".
+
+ See the list of available models on
+ [huggingface.co/models](https://huggingface.co/models?pipeline_tag=image-text-to-text).
+ """
+
+ _load_processor = True
+ _load_image_processor = False
+ _load_feature_extractor = False
+ _load_tokenizer = False
+
+ _pipeline_calls_generate = True
+ # Make sure the docstring is updated when the default generation config is changed
+ _default_generation_config = GenerationConfig(
+ max_new_tokens=256,
+ )
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ requires_backends(self, "vision")
+ self.check_model_type(MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES)
+
+ def _sanitize_parameters(
+ self,
+ max_new_tokens=None,
+ generate_kwargs=None,
+ timeout=None,
+ return_full_text=None,
+ return_tensors=None,
+ return_type=None,
+ clean_up_tokenization_spaces=None,
+ stop_sequence=None,
+ continue_final_message=None,
+ skip_special_tokens=None,
+ processor_kwargs=None,
+ **kwargs: Unpack[ProcessingKwargs],
+ ):
+ forward_kwargs = {}
+ preprocess_params = {}
+ postprocess_params = {}
+
+ # Preprocess params
+ preprocess_params.update(kwargs)
+ if timeout is not None:
+ preprocess_params["timeout"] = timeout
+ if continue_final_message is not None:
+ preprocess_params["continue_final_message"] = continue_final_message
+ if processor_kwargs is not None:
+ preprocess_params["processor_kwargs"] = processor_kwargs
+
+ # Forward kwargs
+ if generate_kwargs is not None:
+ forward_kwargs["generate_kwargs"] = generate_kwargs
+ if stop_sequence is not None:
+ stop_sequence_ids = self.processor.tokenizer.encode(stop_sequence, add_special_tokens=False)
+ if len(stop_sequence_ids) > 1:
+ logger.warning_once(
+ "Stopping on a multiple token sequence is not yet supported on transformers. The first token of"
+ " the stop sequence will be used as the stop sequence string in the interim."
+ )
+ generate_kwargs["eos_token_id"] = stop_sequence_ids[0]
+ if generate_kwargs is not None:
+ forward_kwargs["generate_kwargs"] = generate_kwargs
+ if max_new_tokens is not None:
+ if "generate_kwargs" not in forward_kwargs:
+ forward_kwargs["generate_kwargs"] = {}
+ if "max_new_tokens" in forward_kwargs["generate_kwargs"]:
+ raise ValueError(
+ "'max_new_tokens' is defined twice, once in 'generate_kwargs' and once as a direct parameter,"
+ " please use only one"
+ )
+ forward_kwargs["generate_kwargs"]["max_new_tokens"] = max_new_tokens
+
+ # Postprocess params
+ if return_full_text is not None and return_type is None:
+ if return_tensors is not None:
+ raise ValueError("`return_full_text` is mutually exclusive with `return_tensors`")
+ return_type = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT
+ if return_tensors is not None and return_type is None:
+ return_type = ReturnType.TENSORS
+ if return_type is not None:
+ postprocess_params["return_type"] = return_type
+ if continue_final_message is not None:
+ postprocess_params["continue_final_message"] = continue_final_message
+ if clean_up_tokenization_spaces is not None:
+ postprocess_params["clean_up_tokenization_spaces"] = clean_up_tokenization_spaces
+ if skip_special_tokens is not None:
+ postprocess_params["skip_special_tokens"] = skip_special_tokens
+
+ return preprocess_params, forward_kwargs, postprocess_params
+
+ @overload
+ def __call__(
+ self,
+ image: Union[str, "Image.Image"] | None = None,
+ text: str | None = None,
+ **kwargs: Any,
+ ) -> list[dict[str, Any]]: ...
+
+ @overload
+ def __call__(
+ self,
+ image: list[str] | list["Image.Image"] | None = None,
+ text: list[str] | None = None,
+ **kwargs: Any,
+ ) -> list[list[dict[str, Any]]]: ...
+
+ def __call__(
+ self,
+ images: Union[
+ str, list[str], list[list[str]], "Image.Image", list["Image.Image"], list[list["Image.Image"]], list[dict]
+ ]
+ | None = None,
+ text: str | list[str] | list[dict] | None = None,
+ **kwargs,
+ ) -> list[dict[str, Any]] | list[list[dict[str, Any]]]:
+ """
+ Generate a text given text and the image(s) passed as inputs.
+
+ Args:
+ images (`str`, `list[str]`, `PIL.Image, `list[PIL.Image]`, `list[dict[str, Union[str, PIL.Image]]]`):
+ The pipeline handles three types of images:
+
+ - A string containing a HTTP(s) link pointing to an image
+ - A string containing a local path to an image
+ - An image loaded in PIL directly
+
+ The pipeline accepts either a single image or a batch of images. Finally, this pipeline also supports
+ the chat format (see `text`) containing images and text in this argument.
+ text (str, list[str], `list[dict[str, Union[str, PIL.Image]]]`):
+ The text to be used for generation. If a list of strings is passed, the length of the list should be
+ the same as the number of images. Text can also follow the chat format: a list of dictionaries where
+ each dictionary represents a message in a conversation. Each dictionary should have two keys: 'role'
+ and 'content'. 'role' should be one of 'user', 'system' or 'assistant'. 'content' should be a list of
+ dictionary containing the text of the message and the type of the message. The type of the message
+ can be either 'text' or 'image'. If the type is 'image', no text is needed.
+ return_tensors (`bool`, *optional*, defaults to `False`):
+ Returns the tensors of predictions (as token indices) in the outputs. If set to
+ `True`, the decoded text is not returned.
+ return_text (`bool`, *optional*):
+ Returns the decoded texts in the outputs.
+ return_full_text (`bool`, *optional*, defaults to `True`):
+ If set to `False` only added text is returned, otherwise the full text is returned. Cannot be
+ specified at the same time as `return_text`.
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`):
+ Whether or not to clean up the potential extra spaces in the text output.
+ continue_final_message( `bool`, *optional*): This indicates that you want the model to continue the
+ last message in the input chat rather than starting a new one, allowing you to "prefill" its response.
+ By default this is `True` when the final message in the input chat has the `assistant` role and
+ `False` otherwise, but you can manually override that behaviour by setting this flag.
+
+ Return:
+ A list or a list of list of `dict`: Each result comes as a dictionary with the following key (cannot
+ return a combination of both `generated_text` and `generated_token_ids`):
+
+ - **generated_text** (`str`, present when `return_text=True`) -- The generated text.
+ - **generated_token_ids** (`torch.Tensor`, present when `return_tensors=True`) -- The token
+ ids of the generated text.
+ - **input_text** (`str`) -- The input text.
+ """
+ if images is None and text is None:
+ raise ValueError("You must at least provide either text or images.")
+
+ def _is_chat(arg):
+ return isinstance(arg, (list, tuple, KeyDataset)) and isinstance(arg[0], (list, tuple, dict))
+
+ if _is_chat(text):
+ if images is not None:
+ raise ValueError(
+ "Invalid input: you passed `chat` and `images` as separate input arguments. "
+ "Images must be placed inside the chat message's `content`. For example, "
+ "'content': ["
+ " {'type': 'image', 'url': 'image_url'}, {'type': 'text', 'text': 'Describe the image.'}}"
+ "]"
+ )
+ # We have one or more prompts in list-of-dicts format, so this is chat mode
+ if isinstance(text[0], dict):
+ return super().__call__(Chat(text), **kwargs)
+ else:
+ chats = [Chat(chat) for chat in text] # 🐈 🐈 🐈
+ return super().__call__(chats, **kwargs)
+
+ # Same as above, but the `images` argument contains the chat. This can happen e.g. is the user only passes a
+ # chat as a positional argument.
+ elif text is None and _is_chat(images):
+ # We have one or more prompts in list-of-dicts format, so this is chat mode
+ if isinstance(images[0], dict):
+ return super().__call__(Chat(images), **kwargs)
+ else:
+ chats = [Chat(image) for image in images] # 🐈 🐈 🐈
+ return super().__call__(chats, **kwargs)
+
+ elif images is not None and text is None and not valid_images(images):
+ """
+ Supports the following format
+ - {"image": image, "text": text}
+ - [{"image": image, "text": text}]
+ - Generator and datasets
+ This is a common pattern in other multimodal pipelines, so we support it here as well.
+ """
+ return super().__call__(images, **kwargs)
+
+ # encourage the user to use the chat format if supported
+ if getattr(self.processor, "chat_template", None) is not None:
+ logger.warning_once(
+ "The input data was not formatted as a chat with dicts containing 'role' and 'content' keys, even "
+ "though this model supports chat. Consider using the chat format for better results. For more "
+ "information, see https://huggingface.co/docs/transformers/en/chat_templating"
+ )
+
+ # support text only generation
+ if images is None:
+ return super().__call__(text, **kwargs)
+ if text is None:
+ raise ValueError("You must provide text for this pipeline.")
+
+ return super().__call__({"images": images, "text": text}, **kwargs)
+
+ def preprocess(self, inputs=None, timeout=None, continue_final_message=None, **processing_kwargs):
+ if isinstance(inputs, Chat):
+ # If the user passes a chat that ends in an assistant message, we treat it as a prefill by default
+ # because very few models support multiple separate, consecutive assistant messages
+ if continue_final_message is None:
+ continue_final_message = inputs.messages[-1]["role"] == "assistant"
+
+ # Processor kwargs are passed separately from jinja kwargs to chat template
+ # but it was added only in https://github.com/huggingface/transformers/pull/44881
+ processor_kwargs = processing_kwargs.pop("processor_kwargs", None) or {}
+
+ chat_template_kwargs = {
+ "continue_final_message": continue_final_message,
+ "return_tensors": "pt",
+ "tokenize": True,
+ "return_dict": True,
+ "add_generation_prompt": not continue_final_message,
+ "processor_kwargs": processor_kwargs,
+ **processing_kwargs,
+ }
+
+ # Handle Mistral tokenizer which does not accept processing kwargs
+ if self.processor.tokenizer.__class__.__name__ == "MistralCommonBackend":
+ chat_template_kwargs = {
+ k: v for k, v in chat_template_kwargs.items() if k in ["padding", "truncation", "max_length"]
+ }
+
+ model_inputs = self.processor.apply_chat_template(
+ inputs.messages,
+ **chat_template_kwargs,
+ ).to(dtype=self.dtype)
+ model_inputs["text"] = inputs
+ return model_inputs
+
+ # In case we only have text inputs
+ if isinstance(inputs, (list, tuple, str)):
+ images = None
+ text = inputs
+ inputs_text = inputs
+ else:
+ images = load_images(inputs["images"], timeout=timeout)
+ text = inputs["text"]
+ inputs_text = inputs["text"]
+
+ # if batched text inputs, we set padding to True unless specified otherwise
+ processor_kwargs = processing_kwargs.pop("processor_kwargs", None) or processing_kwargs
+ if isinstance(text, (list, tuple)) and len(text) > 1:
+ processor_kwargs.setdefault("padding", True)
+ model_inputs = self.processor(images=images, text=text, return_tensors="pt", **processor_kwargs).to(
+ dtype=self.dtype
+ )
+
+ model_inputs["text"] = inputs_text
+
+ return model_inputs
+
+ def _forward(self, model_inputs, generate_kwargs=None):
+ generate_kwargs = {} if generate_kwargs is None else generate_kwargs
+ prompt_text = model_inputs.pop("text")
+ input_ids = (
+ model_inputs["input_ids"] if "input_ids" in model_inputs else model_inputs["decoder_input_ids"]
+ ) # for decoder-only models
+
+ # User-defined `generation_config` passed to the pipeline call take precedence
+ if "generation_config" not in generate_kwargs:
+ generate_kwargs["generation_config"] = self.generation_config
+
+ generated_sequence = self.model.generate(**model_inputs, **generate_kwargs)
+
+ return {"generated_sequence": generated_sequence, "prompt_text": prompt_text, "input_ids": input_ids}
+
+ def postprocess(
+ self,
+ model_outputs,
+ return_type=ReturnType.FULL_TEXT,
+ continue_final_message=None,
+ skip_special_tokens=None,
+ **postprocess_kwargs,
+ ):
+ input_texts = model_outputs["prompt_text"]
+ input_texts = [input_texts] if isinstance(input_texts, (str, Chat)) else input_texts
+ generated_sequence = model_outputs["generated_sequence"]
+ input_ids = model_outputs["input_ids"]
+ if return_type == ReturnType.TENSORS:
+ return [
+ {"input_text": input_texts[i], "generated_token_ids": generated_sequence[i]}
+ for i in range(len(input_texts))
+ ]
+
+ # Decode inputs and outputs the same way to remove input text from generated text if present
+ skip_special_tokens = skip_special_tokens if skip_special_tokens is not None else True
+ if getattr(self.tokenizer, "response_schema", False):
+ skip_special_tokens = False
+ generated_texts = self.processor.post_process_image_text_to_text(
+ generated_sequence, skip_special_tokens=skip_special_tokens, **postprocess_kwargs
+ )
+ decoded_inputs = self.processor.post_process_image_text_to_text(
+ input_ids, skip_special_tokens=skip_special_tokens, **postprocess_kwargs
+ )
+
+ # Force consistent behavior for including the input text in the output
+ if return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
+ # Remove the input text from the generated text if the generated text starts with the input text
+ # (accounting for the possibility of a space between the input and generated text)
+ new_generated_texts = []
+ for text_generated, decoded_input in zip(generated_texts, decoded_inputs):
+ # There can be added characters before the input text, so we need to find the beginning of the input text in the generated text
+ index_input_text = text_generated.find(decoded_input)
+ # Limit the search to 2 residual characters, like spaces or new lines, to avoid removing a large part of the answer
+ if 0 <= index_input_text <= 2:
+ # If the input text is found, we remove it
+ new_generated_texts.append(text_generated[index_input_text + len(decoded_input) :])
+ else:
+ new_generated_texts.append(text_generated)
+ generated_texts = new_generated_texts
+ if return_type == ReturnType.FULL_TEXT:
+ full_texts = []
+ for prompt_text, generated_text in zip(input_texts, generated_texts):
+ if isinstance(prompt_text, str):
+ generated_text = prompt_text + generated_text
+ elif isinstance(prompt_text, Chat):
+ if continue_final_message is None:
+ # If the user passes a chat ending in an assistant message, we treat it as a prefill by
+ # default because very few models support multiple separate, consecutive assistant messages
+ continue_final_message = prompt_text.messages[-1]["role"] == "assistant"
+ if continue_final_message:
+ # With assistant prefill, concat onto the end of the last message
+ new_text = dict(prompt_text.messages[-1]["content"][-1].items())
+ new_text["text"] += generated_text
+ generated_text = list(prompt_text.messages)[:-1] + [
+ {
+ "role": prompt_text.messages[-1]["role"],
+ "content": prompt_text.messages[-1]["content"][:-1] + [new_text],
+ }
+ ]
+ else:
+ # When we're not starting from a prefill, the output is a new assistant message
+ if getattr(self.tokenizer, "response_schema", False):
+ assistant_message = self.tokenizer.parse_response(generated_text)
+ else:
+ assistant_message = {"role": "assistant", "content": generated_text}
+ generated_text = list(prompt_text.messages) + [assistant_message]
+ full_texts.append(generated_text)
+ generated_texts = full_texts
+
+ records = [
+ {
+ "input_text": input_text.messages if isinstance(input_text, Chat) else input_text,
+ "generated_text": generated_text,
+ }
+ for input_text, generated_text in zip(input_texts, generated_texts)
+ ]
+
+ return records
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/keypoint_matching.py b/.venv/lib/python3.12/site-packages/transformers/pipelines/keypoint_matching.py
new file mode 100644
index 0000000000000000000000000000000000000000..d75656a7db3b301476faf02401c0a5df5d2c5691
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/pipelines/keypoint_matching.py
@@ -0,0 +1,176 @@
+# Copyright 2025 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from collections.abc import Sequence
+from typing import Any, TypeAlias, TypedDict, Union
+
+from typing_extensions import overload
+
+from ..image_utils import is_pil_image
+from ..utils import is_vision_available, requires_backends
+from .base import Pipeline
+
+
+if is_vision_available():
+ from PIL import Image
+
+ from ..image_utils import load_image
+
+
+ImagePair: TypeAlias = Sequence[Union["Image.Image", str]]
+
+
+class Keypoint(TypedDict):
+ x: float
+ y: float
+
+
+class Match(TypedDict):
+ keypoint_image_0: Keypoint
+ keypoint_image_1: Keypoint
+ score: float
+
+
+def validate_image_pairs(images: Any) -> Sequence[Sequence[ImagePair]]:
+ error_message = (
+ "Input images must be a one of the following :",
+ " - A pair of images.",
+ " - A list of pairs of images.",
+ )
+
+ def _is_valid_image(image):
+ """images is a PIL Image or a string."""
+ return is_pil_image(image) or isinstance(image, str)
+
+ if isinstance(images, Sequence):
+ if len(images) == 2 and all((_is_valid_image(image)) for image in images):
+ return [images]
+ if all(
+ isinstance(image_pair, Sequence)
+ and len(image_pair) == 2
+ and all(_is_valid_image(image) for image in image_pair)
+ for image_pair in images
+ ):
+ return images
+ raise ValueError(error_message)
+
+
+class KeypointMatchingPipeline(Pipeline):
+ """
+ Keypoint matching pipeline using any `AutoModelForKeypointMatching`. This pipeline matches keypoints between two images.
+ """
+
+ _load_processor = False
+ _load_image_processor = True
+ _load_feature_extractor = False
+ _load_tokenizer = False
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ requires_backends(self, "vision")
+
+ def _sanitize_parameters(self, threshold=None, timeout=None):
+ preprocess_params = {}
+ if timeout is not None:
+ preprocess_params["timeout"] = timeout
+ postprocess_params = {}
+ if threshold is not None:
+ postprocess_params["threshold"] = threshold
+ return preprocess_params, {}, postprocess_params
+
+ @overload
+ def __call__(self, inputs: ImagePair, threshold: float = 0.0, **kwargs: Any) -> list[Match]: ...
+
+ @overload
+ def __call__(self, inputs: list[ImagePair], threshold: float = 0.0, **kwargs: Any) -> list[list[Match]]: ...
+
+ def __call__(
+ self,
+ inputs: list[ImagePair] | ImagePair,
+ threshold: float = 0.0,
+ **kwargs: Any,
+ ) -> list[Match] | list[list[Match]]:
+ """
+ Find matches between keypoints in two images.
+
+ Args:
+ inputs (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`):
+ The pipeline handles three types of images:
+
+ - A string containing a http link pointing to an image
+ - A string containing a local path to an image
+ - An image loaded in PIL directly
+
+ The pipeline accepts either a single pair of images or a batch of image pairs, which must then be passed as a string.
+ Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL
+ images.
+
+ threshold (`float`, *optional*, defaults to 0.0):
+ The threshold to use for keypoint matching. Keypoints matched with a lower matching score will be filtered out.
+ A value of 0 means that all matched keypoints will be returned.
+
+ kwargs:
+ `timeout (`float`, *optional*, defaults to None)`
+ The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
+ the call may block forever.
+
+ Return:
+ Union[list[Match], list[list[Match]]]:
+ A list of matches or a list if a single image pair is provided, or of lists of matches if a batch
+ of image pairs is provided. Each match is a dictionary containing the following keys:
+
+ - **keypoint_image_0** (`Keypoint`): The keypoint in the first image (x, y coordinates).
+ - **keypoint_image_1** (`Keypoint`): The keypoint in the second image (x, y coordinates).
+ - **score** (`float`): The matching score between the two keypoints.
+ """
+ if inputs is None:
+ raise ValueError("Cannot call the keypoint-matching pipeline without an inputs argument!")
+ formatted_inputs = validate_image_pairs(inputs)
+ outputs = super().__call__(formatted_inputs, threshold=threshold, **kwargs)
+ if len(formatted_inputs) == 1:
+ return outputs[0]
+ return outputs
+
+ def preprocess(self, images, timeout=None):
+ images = [load_image(image, timeout=timeout) for image in images]
+ model_inputs = self.image_processor(images=images, return_tensors="pt")
+ model_inputs = model_inputs.to(self.dtype)
+ target_sizes = [image.size for image in images]
+ preprocess_outputs = {"model_inputs": model_inputs, "target_sizes": target_sizes}
+ return preprocess_outputs
+
+ def _forward(self, preprocess_outputs):
+ model_inputs = preprocess_outputs["model_inputs"]
+ model_outputs = self.model(**model_inputs)
+ forward_outputs = {"model_outputs": model_outputs, "target_sizes": [preprocess_outputs["target_sizes"]]}
+ return forward_outputs
+
+ def postprocess(self, forward_outputs, threshold=0.0) -> list[Match]:
+ model_outputs = forward_outputs["model_outputs"]
+ target_sizes = forward_outputs["target_sizes"]
+ postprocess_outputs = self.image_processor.post_process_keypoint_matching(
+ model_outputs, target_sizes=target_sizes, threshold=threshold
+ )
+ postprocess_outputs = postprocess_outputs[0]
+ pair_result = []
+ for kp_0, kp_1, score in zip(
+ postprocess_outputs["keypoints0"],
+ postprocess_outputs["keypoints1"],
+ postprocess_outputs["matching_scores"],
+ ):
+ kp_0 = Keypoint(x=kp_0[0].item(), y=kp_0[1].item())
+ kp_1 = Keypoint(x=kp_1[0].item(), y=kp_1[1].item())
+ pair_result.append(Match(keypoint_image_0=kp_0, keypoint_image_1=kp_1, score=score.item()))
+ pair_result = sorted(pair_result, key=lambda x: x["score"], reverse=True)
+ return pair_result
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/mask_generation.py b/.venv/lib/python3.12/site-packages/transformers/pipelines/mask_generation.py
new file mode 100644
index 0000000000000000000000000000000000000000..ffbe5868f7a759c78a14b9bfa37b66d983ef7365
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/pipelines/mask_generation.py
@@ -0,0 +1,335 @@
+from collections import defaultdict
+from typing import TYPE_CHECKING, Any, Union, overload
+
+from ..image_utils import load_image
+from ..utils import (
+ add_end_docstrings,
+ is_torch_available,
+ logging,
+ requires_backends,
+)
+from .base import ChunkPipeline, build_pipeline_init_args
+
+
+if is_torch_available():
+ import torch
+
+ from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING_NAMES
+
+if TYPE_CHECKING:
+ from PIL import Image
+
+logger = logging.get_logger(__name__)
+
+
+@add_end_docstrings(
+ build_pipeline_init_args(has_image_processor=True),
+ r"""
+ points_per_batch (*optional*, int, default to 64):
+ Sets the number of points run simultaneously by the model. Higher numbers may be faster but use more GPU
+ memory.
+ output_bboxes_mask (`bool`, *optional*, default to `False`):
+ Whether or not to output the bounding box predictions.
+ output_rle_masks (`bool`, *optional*, default to `False`):
+ Whether or not to output the masks in `RLE` format""",
+)
+class MaskGenerationPipeline(ChunkPipeline):
+ """
+ Automatic mask generation for images using `SamForMaskGeneration`. This pipeline predicts binary masks for an
+ image, given an image. It is a `ChunkPipeline` because you can separate the points in a mini-batch in order to
+ avoid OOM issues. Use the `points_per_batch` argument to control the number of points that will be processed at the
+ same time. Default is `64`.
+
+ The pipeline works in 3 steps:
+ 1. `preprocess`: A grid of 1024 points evenly separated is generated along with bounding boxes and point
+ labels.
+ For more details on how the points and bounding boxes are created, check the `_generate_crop_boxes`
+ function. The image is also preprocessed using the `image_processor`. This function `yields` a minibatch of
+ `points_per_batch`.
+
+ 2. `forward`: feeds the outputs of `preprocess` to the model. The image embedding is computed only once.
+ Calls both `self.model.get_image_embeddings` and makes sure that the gradients are not computed, and the
+ tensors and models are on the same device.
+
+ 3. `postprocess`: The most important part of the automatic mask generation happens here. Three steps
+ are induced:
+ - image_processor.postprocess_masks (run on each minibatch loop): takes in the raw output masks,
+ resizes them according
+ to the image size, and transforms there to binary masks.
+ - image_processor.filter_masks (on each minibatch loop): uses both `pred_iou_thresh` and
+ `stability_scores`. Also
+ applies a variety of filters based on non maximum suppression to remove bad masks.
+ - image_processor.postprocess_masks_for_amg applies the NSM on the mask to only keep relevant ones.
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> generator = pipeline(model="facebook/sam-vit-base", task="mask-generation")
+ >>> outputs = generator(
+ ... "http://images.cocodataset.org/val2017/000000039769.jpg",
+ ... )
+
+ >>> outputs = generator(
+ ... "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", points_per_batch=128
+ ... )
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This segmentation pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"mask-generation"`.
+
+ See the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=mask-generation).
+ """
+
+ _load_processor = False
+ _load_image_processor = True
+ _load_feature_extractor = False
+ _load_tokenizer = False
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+ requires_backends(self, "vision")
+ requires_backends(self, "torch")
+
+ self.check_model_type(MODEL_FOR_MASK_GENERATION_MAPPING_NAMES)
+
+ def _sanitize_parameters(self, **kwargs):
+ preprocess_kwargs = {}
+ postprocess_kwargs = {}
+ forward_params = {}
+ # preprocess args
+ if "points_per_batch" in kwargs:
+ preprocess_kwargs["points_per_batch"] = kwargs["points_per_batch"]
+ if "points_per_crop" in kwargs:
+ preprocess_kwargs["points_per_crop"] = kwargs["points_per_crop"]
+ if "crops_n_layers" in kwargs:
+ preprocess_kwargs["crops_n_layers"] = kwargs["crops_n_layers"]
+ if "crop_overlap_ratio" in kwargs:
+ preprocess_kwargs["crop_overlap_ratio"] = kwargs["crop_overlap_ratio"]
+ if "crop_n_points_downscale_factor" in kwargs:
+ preprocess_kwargs["crop_n_points_downscale_factor"] = kwargs["crop_n_points_downscale_factor"]
+ if "timeout" in kwargs:
+ preprocess_kwargs["timeout"] = kwargs["timeout"]
+ # postprocess args
+ if "pred_iou_thresh" in kwargs:
+ forward_params["pred_iou_thresh"] = kwargs["pred_iou_thresh"]
+ if "stability_score_offset" in kwargs:
+ forward_params["stability_score_offset"] = kwargs["stability_score_offset"]
+ if "mask_threshold" in kwargs:
+ forward_params["mask_threshold"] = kwargs["mask_threshold"]
+ if "stability_score_thresh" in kwargs:
+ forward_params["stability_score_thresh"] = kwargs["stability_score_thresh"]
+ if "max_hole_area" in kwargs:
+ forward_params["max_hole_area"] = kwargs["max_hole_area"]
+ if "max_sprinkle_area" in kwargs:
+ forward_params["max_sprinkle_area"] = kwargs["max_sprinkle_area"]
+ if "crops_nms_thresh" in kwargs:
+ postprocess_kwargs["crops_nms_thresh"] = kwargs["crops_nms_thresh"]
+ if "output_rle_mask" in kwargs:
+ postprocess_kwargs["output_rle_mask"] = kwargs["output_rle_mask"]
+ if "output_bboxes_mask" in kwargs:
+ postprocess_kwargs["output_bboxes_mask"] = kwargs["output_bboxes_mask"]
+ return preprocess_kwargs, forward_params, postprocess_kwargs
+
+ @overload
+ def __call__(self, image: Union[str, "Image.Image"], *args: Any, **kwargs: Any) -> dict[str, Any]: ...
+
+ @overload
+ def __call__(self, image: list[str] | list["Image.Image"], *args: Any, **kwargs: Any) -> list[dict[str, Any]]: ...
+
+ def __call__(
+ self, image: Union[str, "Image.Image", list[str], list["Image.Image"]], *args: Any, **kwargs: Any
+ ) -> dict[str, Any] | list[dict[str, Any]]:
+ """
+ Generates binary segmentation masks
+
+ Args:
+ image (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`):
+ Image or list of images.
+ mask_threshold (`float`, *optional*, defaults to 0.0):
+ Threshold to use when turning the predicted masks into binary values.
+ pred_iou_thresh (`float`, *optional*, defaults to 0.88):
+ A filtering threshold in `[0,1]` applied on the model's predicted mask quality.
+ stability_score_thresh (`float`, *optional*, defaults to 0.95):
+ A filtering threshold in `[0,1]`, using the stability of the mask under changes to the cutoff used to
+ binarize the model's mask predictions.
+ stability_score_offset (`int`, *optional*, defaults to 1):
+ The amount to shift the cutoff when calculated the stability score.
+ crops_nms_thresh (`float`, *optional*, defaults to 0.7):
+ The box IoU cutoff used by non-maximal suppression to filter duplicate masks.
+ crops_n_layers (`int`, *optional*, defaults to 0):
+ If `crops_n_layers>0`, mask prediction will be run again on crops of the image. Sets the number of
+ layers to run, where each layer has 2**i_layer number of image crops.
+ crop_overlap_ratio (`float`, *optional*, defaults to `512 / 1500`):
+ Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of
+ the image length. Later layers with more crops scale down this overlap.
+ crop_n_points_downscale_factor (`int`, *optional*, defaults to `1`):
+ The number of points-per-side sampled in layer n is scaled down by crop_n_points_downscale_factor**n.
+ timeout (`float`, *optional*, defaults to None):
+ The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
+ the call may block forever.
+
+ Return:
+ `Dict`: A dictionary with the following keys:
+ - **mask** (`PIL.Image`) -- A binary mask of the detected object as a PIL Image of shape `(width,
+ height)` of the original image. Returns a mask filled with zeros if no object is found.
+ - **score** (*optional* `float`) -- Optionally, when the model is capable of estimating a confidence of
+ the "object" described by the label and the mask.
+
+ """
+ num_workers = kwargs.pop("num_workers", None)
+ batch_size = kwargs.pop("batch_size", None)
+ return super().__call__(image, *args, num_workers=num_workers, batch_size=batch_size, **kwargs)
+
+ def preprocess(
+ self,
+ image,
+ points_per_batch=64,
+ crops_n_layers: int = 0,
+ crop_overlap_ratio: float = 512 / 1500,
+ points_per_crop: int = 32,
+ crop_n_points_downscale_factor: int = 1,
+ timeout: float | None = None,
+ ):
+ image = load_image(image, timeout=timeout)
+ target_size = self.image_processor.size.get("longest_edge", self.image_processor.size.get("height"))
+ crop_boxes, grid_points, cropped_images, input_labels = self.image_processor.generate_crop_boxes(
+ image, target_size, crops_n_layers, crop_overlap_ratio, points_per_crop, crop_n_points_downscale_factor
+ )
+ model_inputs = self.image_processor(images=cropped_images, return_tensors="pt")
+ model_inputs = model_inputs.to(self.dtype)
+
+ with self.device_placement():
+ inference_context = self.get_inference_context()
+ with inference_context():
+ model_inputs = self._ensure_tensor_on_device(model_inputs, device=self.device)
+ embeddings = self.model.get_image_embeddings(model_inputs.pop("pixel_values"))
+
+ # Handle both SAM (single tensor) and SAM-HQ (tuple) outputs
+ if isinstance(embeddings, tuple):
+ image_embeddings, intermediate_embeddings = embeddings
+ model_inputs["intermediate_embeddings"] = intermediate_embeddings
+ else:
+ image_embeddings = embeddings
+ # TODO: Identifying the model by the type of its returned embeddings is brittle.
+ # Consider using a more robust method for distinguishing model types here.
+
+ model_inputs["image_embeddings"] = image_embeddings
+
+ n_points = grid_points.shape[1]
+ points_per_batch = points_per_batch if points_per_batch is not None else n_points
+
+ if points_per_batch <= 0:
+ raise ValueError(
+ "Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. "
+ "To return all points at once, set points_per_batch to None"
+ )
+
+ for i in range(0, n_points, points_per_batch):
+ batched_points = grid_points[:, i : i + points_per_batch, :, :]
+ labels = input_labels[:, i : i + points_per_batch]
+ is_last = i + points_per_batch >= n_points
+ yield {
+ "input_points": batched_points,
+ "input_labels": labels,
+ "input_boxes": crop_boxes,
+ "is_last": is_last,
+ **model_inputs,
+ }
+
+ def _forward(
+ self,
+ model_inputs,
+ pred_iou_thresh=0.88,
+ stability_score_thresh=0.95,
+ mask_threshold=0,
+ stability_score_offset=1,
+ max_hole_area=None,
+ max_sprinkle_area=None,
+ ):
+ input_boxes = model_inputs.pop("input_boxes")
+ is_last = model_inputs.pop("is_last")
+ original_sizes = model_inputs.pop("original_sizes").tolist()
+ reshaped_input_sizes = model_inputs.pop("reshaped_input_sizes", None)
+ reshaped_input_sizes = reshaped_input_sizes.tolist() if reshaped_input_sizes is not None else None
+
+ model_outputs = self.model(**model_inputs)
+
+ # post processing happens here in order to avoid CPU GPU copies of ALL the masks
+ low_resolution_masks = model_outputs["pred_masks"]
+ postprocess_kwargs = {}
+ if max_hole_area is not None:
+ postprocess_kwargs["max_hole_area"] = max_hole_area
+ if max_sprinkle_area is not None and max_sprinkle_area > 0:
+ postprocess_kwargs["max_sprinkle_area"] = max_sprinkle_area
+ if postprocess_kwargs:
+ low_resolution_masks = self.image_processor.post_process_masks(
+ low_resolution_masks,
+ original_sizes,
+ mask_threshold=mask_threshold,
+ reshaped_input_sizes=reshaped_input_sizes,
+ binarize=False,
+ **postprocess_kwargs,
+ )
+ masks = self.image_processor.post_process_masks(
+ low_resolution_masks,
+ original_sizes,
+ mask_threshold=mask_threshold,
+ reshaped_input_sizes=reshaped_input_sizes,
+ binarize=False,
+ )
+ iou_scores = model_outputs["iou_scores"]
+ masks, iou_scores, boxes = self.image_processor.filter_masks(
+ masks[0],
+ iou_scores[0],
+ original_sizes[0],
+ input_boxes[0],
+ pred_iou_thresh,
+ stability_score_thresh,
+ mask_threshold,
+ stability_score_offset,
+ )
+ return {
+ "masks": masks,
+ "is_last": is_last,
+ "boxes": boxes,
+ "iou_scores": iou_scores,
+ }
+
+ def postprocess(
+ self,
+ model_outputs,
+ output_rle_mask=False,
+ output_bboxes_mask=False,
+ crops_nms_thresh=0.7,
+ ):
+ all_scores = []
+ all_masks = []
+ all_boxes = []
+ for model_output in model_outputs:
+ all_scores.append(model_output.pop("iou_scores"))
+ all_masks.extend(model_output.pop("masks"))
+ all_boxes.append(model_output.pop("boxes"))
+
+ all_scores = torch.cat(all_scores)
+ all_boxes = torch.cat(all_boxes)
+ output_masks, iou_scores, rle_mask, bounding_boxes = self.image_processor.post_process_for_mask_generation(
+ all_masks, all_scores, all_boxes, crops_nms_thresh
+ )
+
+ extra = defaultdict(list)
+ for output in model_outputs:
+ for k, v in output.items():
+ extra[k].append(v)
+
+ optional = {}
+ if output_rle_mask:
+ optional["rle_mask"] = rle_mask
+
+ if output_bboxes_mask:
+ optional["bounding_boxes"] = bounding_boxes
+
+ return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/object_detection.py b/.venv/lib/python3.12/site-packages/transformers/pipelines/object_detection.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a4fba996d7d364283371c17e9cf6adbc43d0c23
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/pipelines/object_detection.py
@@ -0,0 +1,197 @@
+from typing import TYPE_CHECKING, Any, Union, overload
+
+from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends
+from .base import Pipeline, build_pipeline_init_args
+
+
+if is_vision_available():
+ from ..image_utils import load_image
+
+
+if is_torch_available():
+ import torch
+
+ from ..models.auto.modeling_auto import (
+ MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES,
+ MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES,
+ )
+
+if TYPE_CHECKING:
+ from PIL import Image
+
+logger = logging.get_logger(__name__)
+
+
+@add_end_docstrings(build_pipeline_init_args(has_image_processor=True))
+class ObjectDetectionPipeline(Pipeline):
+ """
+ Object detection pipeline using any `AutoModelForObjectDetection`. This pipeline predicts bounding boxes of objects
+ and their classes.
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> detector = pipeline(model="facebook/detr-resnet-50")
+ >>> detector("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
+ [{'score': 0.997, 'label': 'bird', 'box': {'xmin': 69, 'ymin': 171, 'xmax': 396, 'ymax': 507}}, {'score': 0.999, 'label': 'bird', 'box': {'xmin': 398, 'ymin': 105, 'xmax': 767, 'ymax': 507}}]
+
+ >>> # x, y are expressed relative to the top left hand corner.
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This object detection pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"object-detection"`.
+
+ See the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=object-detection).
+ """
+
+ _load_processor = False
+ _load_image_processor = True
+ _load_feature_extractor = False
+ _load_tokenizer = None
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ requires_backends(self, "vision")
+ mapping = MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES.copy()
+ mapping.update(MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES)
+ self.check_model_type(mapping)
+
+ def _sanitize_parameters(self, **kwargs):
+ preprocess_params = {}
+ if "timeout" in kwargs:
+ preprocess_params["timeout"] = kwargs["timeout"]
+ postprocess_kwargs = {}
+ if "threshold" in kwargs:
+ postprocess_kwargs["threshold"] = kwargs["threshold"]
+ return preprocess_params, {}, postprocess_kwargs
+
+ @overload
+ def __call__(self, image: Union[str, "Image.Image"], *args: Any, **kwargs: Any) -> list[dict[str, Any]]: ...
+
+ @overload
+ def __call__(
+ self, image: list[str] | list["Image.Image"], *args: Any, **kwargs: Any
+ ) -> list[list[dict[str, Any]]]: ...
+
+ def __call__(self, *args, **kwargs) -> list[dict[str, Any]] | list[list[dict[str, Any]]]:
+ """
+ Detect objects (bounding boxes & classes) in the image(s) passed as inputs.
+
+ Args:
+ inputs (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`):
+ The pipeline handles three types of images:
+
+ - A string containing an HTTP(S) link pointing to an image
+ - A string containing a local path to an image
+ - An image loaded in PIL directly
+
+ The pipeline accepts either a single image or a batch of images. Images in a batch must all be in the
+ same format: all as HTTP(S) links, all as local paths, or all as PIL images.
+ threshold (`float`, *optional*, defaults to 0.5):
+ The probability necessary to make a prediction.
+ timeout (`float`, *optional*, defaults to None):
+ The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
+ the call may block forever.
+
+ Return:
+ A list of dictionaries or a list of list of dictionaries containing the result. If the input is a single
+ image, will return a list of dictionaries, if the input is a list of several images, will return a list of
+ list of dictionaries corresponding to each image.
+
+ The dictionaries contain the following keys:
+
+ - **label** (`str`) -- The class label identified by the model.
+ - **score** (`float`) -- The score attributed by the model for that label.
+ - **box** (`list[dict[str, int]]`) -- The bounding box of detected object in image's original size.
+ """
+ # After deprecation of this is completed, remove the default `None` value for `images`
+ if "images" in kwargs and "inputs" not in kwargs:
+ kwargs["inputs"] = kwargs.pop("images")
+ return super().__call__(*args, **kwargs)
+
+ def preprocess(self, image, timeout=None):
+ image = load_image(image, timeout=timeout)
+ target_size = torch.IntTensor([[image.height, image.width]])
+ inputs = self.image_processor(images=[image], return_tensors="pt")
+ inputs = inputs.to(self.dtype)
+ if self.tokenizer is not None:
+ inputs = self.tokenizer(text=inputs["words"], boxes=inputs["boxes"], return_tensors="pt")
+ inputs["target_size"] = target_size
+ return inputs
+
+ def _forward(self, model_inputs):
+ target_size = model_inputs.pop("target_size")
+ outputs = self.model(**model_inputs)
+ model_outputs = outputs.__class__({"target_size": target_size, **outputs})
+ if self.tokenizer is not None:
+ model_outputs["bbox"] = model_inputs["bbox"]
+ return model_outputs
+
+ def postprocess(self, model_outputs, threshold=0.5):
+ target_size = model_outputs["target_size"]
+ if self.tokenizer is not None:
+ # This is a LayoutLMForTokenClassification variant.
+ # The OCR got the boxes and the model classified the words.
+ height, width = target_size[0].tolist()
+
+ def unnormalize(bbox):
+ return self._get_bounding_box(
+ torch.Tensor(
+ [
+ (width * bbox[0] / 1000),
+ (height * bbox[1] / 1000),
+ (width * bbox[2] / 1000),
+ (height * bbox[3] / 1000),
+ ]
+ )
+ )
+
+ scores, classes = model_outputs["logits"].squeeze(0).softmax(dim=-1).max(dim=-1)
+ labels = [self.model.config.id2label[prediction] for prediction in classes.tolist()]
+ boxes = [unnormalize(bbox) for bbox in model_outputs["bbox"].squeeze(0)]
+ keys = ["score", "label", "box"]
+ annotation = [dict(zip(keys, vals)) for vals in zip(scores.tolist(), labels, boxes) if vals[0] > threshold]
+ else:
+ # This is a regular ForObjectDetectionModel
+ raw_annotations = self.image_processor.post_process_object_detection(model_outputs, threshold, target_size)
+ raw_annotation = raw_annotations[0]
+ scores = raw_annotation["scores"]
+ labels = raw_annotation["labels"]
+ boxes = raw_annotation["boxes"]
+
+ raw_annotation["scores"] = scores.tolist()
+ raw_annotation["labels"] = [self.model.config.id2label[label.item()] for label in labels]
+ raw_annotation["boxes"] = [self._get_bounding_box(box) for box in boxes]
+
+ # {"scores": [...], ...} --> [{"score":x, ...}, ...]
+ keys = ["score", "label", "box"]
+ annotation = [
+ dict(zip(keys, vals))
+ for vals in zip(raw_annotation["scores"], raw_annotation["labels"], raw_annotation["boxes"])
+ ]
+
+ return annotation
+
+ def _get_bounding_box(self, box: "torch.Tensor") -> dict[str, int]:
+ """
+ Turns list [xmin, xmax, ymin, ymax] into dict { "xmin": xmin, ... }
+
+ Args:
+ box (`torch.Tensor`): Tensor containing the coordinates in corners format.
+
+ Returns:
+ bbox (`dict[str, int]`): Dict containing the coordinates in corners format.
+ """
+ xmin, ymin, xmax, ymax = box.int().tolist()
+ bbox = {
+ "xmin": xmin,
+ "ymin": ymin,
+ "xmax": xmax,
+ "ymax": ymax,
+ }
+ return bbox
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/pt_utils.py b/.venv/lib/python3.12/site-packages/transformers/pipelines/pt_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..3857805962a93f796e407ed88c89495b46fd0bd0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/pipelines/pt_utils.py
@@ -0,0 +1,323 @@
+import numpy as np
+import torch
+from torch.utils.data import Dataset, IterableDataset
+
+from ..utils.generic import ModelOutput
+
+
+class PipelineDataset(Dataset):
+ def __init__(self, dataset, process, params):
+ self.dataset = dataset
+ self.process = process
+ self.params = params
+
+ def __len__(self):
+ return len(self.dataset)
+
+ def __getitem__(self, i):
+ item = self.dataset[i]
+ processed = self.process(item, **self.params)
+ return processed
+
+
+class PipelineIterator(IterableDataset):
+ def __init__(self, loader, infer, params, loader_batch_size=None):
+ """
+ Roughly equivalent to
+
+ ```
+ for item in loader:
+ yield infer(item, **params)
+ ```
+
+ Arguments:
+ loader (`torch.utils.data.DataLoader` or `Iterable`):
+ The iterator that will be used to apply `infer` on.
+ infer (any function):
+ The function to apply of each element of `loader`.
+ params (`dict`):
+ The parameters passed to `infer` along with every item
+ loader_batch_size (`int`, *optional*):
+ If specified, the items of `loader` are supposed to come as batch, and are loader_batched here
+ making it roughly behave as
+
+
+ ```
+ for items in loader:
+ for i in loader_batch_size:
+ item = items[i]
+ yield infer(item, **params)
+ ```"""
+ self.loader = loader
+ self.infer = infer
+ self.params = params
+ if loader_batch_size == 1:
+ # Let's spare some time by deactivating altogether
+ loader_batch_size = None
+ self.loader_batch_size = loader_batch_size
+
+ # Internal bookkeeping
+ self._loader_batch_index = None
+ self._loader_batch_data = None
+
+ def __len__(self):
+ return len(self.loader)
+
+ def __iter__(self):
+ self.iterator = iter(self.loader)
+ return self
+
+ def loader_batch_item(self):
+ """
+ Return item located at `loader_batch_index` within the current `loader_batch_data`.
+ """
+ if isinstance(self._loader_batch_data, torch.Tensor):
+ # Batch data is simple tensor, just fetch the slice
+ result = self._loader_batch_data[self._loader_batch_index].unsqueeze(0)
+ else:
+ # Batch data is assumed to be BaseModelOutput (or dict)
+ loader_batched = {}
+ for k, element in self._loader_batch_data.items():
+ if isinstance(element, ModelOutput):
+ # Convert ModelOutput to tuple first
+ element = element.to_tuple()
+ if isinstance(element[0], torch.Tensor):
+ loader_batched[k] = tuple(el[self._loader_batch_index].unsqueeze(0) for el in element)
+ elif isinstance(element[0], np.ndarray):
+ loader_batched[k] = tuple(np.expand_dims(el[self._loader_batch_index], 0) for el in element)
+ continue
+ if k in {"hidden_states", "attentions"} and isinstance(element, tuple):
+ # Those are stored as lists of tensors so need specific unbatching.
+ if isinstance(element[0], torch.Tensor):
+ loader_batched[k] = tuple(el[self._loader_batch_index].unsqueeze(0) for el in element)
+ elif isinstance(element[0], np.ndarray):
+ loader_batched[k] = tuple(np.expand_dims(el[self._loader_batch_index], 0) for el in element)
+ continue
+ if k == "past_key_values":
+ continue
+ if element is None:
+ # This can happen for optional data that get passed around
+ loader_batched[k] = None
+ elif isinstance(element[self._loader_batch_index], torch.Tensor):
+ # Take correct batch data, but make it looked like batch_size=1
+ # For compatibility with other methods within transformers
+
+ loader_batched[k] = element[self._loader_batch_index].unsqueeze(0)
+ elif isinstance(element[self._loader_batch_index], np.ndarray):
+ # Take correct batch data, but make it looked like batch_size=1
+ # For compatibility with other methods within transformers
+ loader_batched[k] = np.expand_dims(element[self._loader_batch_index], 0)
+ else:
+ # This is typically a list, so no need to `unsqueeze`.
+ loader_batched[k] = element[self._loader_batch_index]
+ # Recreate the element by reusing the original class to make it look
+ # batch_size=1
+ result = self._loader_batch_data.__class__(loader_batched)
+ self._loader_batch_index += 1
+ return result
+
+ def __next__(self):
+ if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size:
+ # We are currently unrolling a batch so we just need to return
+ # the current item within a batch
+ return self.loader_batch_item()
+
+ # We're out of items within a batch
+ item = next(self.iterator)
+ processed = self.infer(item, **self.params)
+ # We now have a batch of "inferred things".
+ if self.loader_batch_size is not None:
+ # Try to infer the size of the batch
+ if isinstance(processed, torch.Tensor):
+ first_tensor = processed
+ elif isinstance(processed, tuple):
+ first_tensor = processed[0]
+ else:
+ key = list(processed.keys())[0]
+ first_tensor = processed[key]
+
+ if isinstance(first_tensor, list):
+ observed_batch_size = len(first_tensor)
+ else:
+ observed_batch_size = first_tensor.shape[0]
+ if 0 < observed_batch_size < self.loader_batch_size:
+ # could be last batch so we can't unroll as many
+ # elements.
+ self.loader_batch_size = observed_batch_size
+ # Setting internal index to unwrap the batch
+ self._loader_batch_data = processed[0] if isinstance(processed, tuple) else processed
+ self._loader_batch_index = 0
+ return self.loader_batch_item()
+ else:
+ # We're not unrolling batches
+ return processed
+
+
+class PipelineChunkIterator(PipelineIterator):
+ def __init__(self, loader, infer, params, loader_batch_size=None):
+ """
+ Roughly equivalent to
+
+ ```
+ for iterator in loader:
+ for item in iterator:
+ yield infer(item, **params)
+ ```
+
+ Arguments:
+ loader (`torch.utils.data.DataLoader` or `Iterable`):
+ The iterator that will be used to apply `infer` on.
+ infer (any function):
+ The function to apply of each element of `loader`.
+ params (`dict`):
+ The parameters passed to `infer` along with every item
+ """
+ super().__init__(loader, infer, params)
+
+ def __iter__(self):
+ self.iterator = iter(self.loader)
+ self.subiterator = None
+ return self
+
+ def __next__(self):
+ if self.subiterator is None:
+ "Subiterator None means we haven't started a `preprocess` iterator. so start it"
+ self.subiterator = self.infer(next(self.iterator), **self.params)
+ try:
+ # Try to return next item
+ processed = next(self.subiterator)
+ except StopIteration:
+ # When a preprocess iterator ends, we can start looking at the next item
+ # ChunkIterator will keep feeding until ALL elements of iterator
+ # all have created their subiterator and have been iterating against.
+ #
+ # Another way to look at it, is we're basically flattening lists of lists
+ # into a single list, but with generators
+ self.subiterator = self.infer(next(self.iterator), **self.params)
+ processed = next(self.subiterator)
+ return processed
+
+
+class PipelinePackIterator(PipelineIterator):
+ """
+ Roughly equivalent to
+
+ ```
+ packed = []
+ for item in loader:
+ packed.append(item)
+ if item["is_last"]:
+ yield packed
+ packed = []
+ ```
+
+ but it also handles cases where `item` are batched (meaning it's a dict of Tensor with first dimension > 1. In
+ that case it does
+
+ ```
+ packed = []
+ for batch in loader:
+ # item is batched
+ for item in batch:
+ packed.append(item)
+ if item["is_last"]:
+ yield packed
+ packed = []
+ ```
+
+ Arguments:
+ loader (`torch.utils.data.DataLoader` or `Iterable`):
+ The iterator that will be used to apply `infer` on.
+ infer (any function):
+ The function to apply of each element of `loader`.
+ params (`dict`):
+ The parameters passed to `infer` along with every item
+ loader_batch_size (`int`, *optional*):
+ If specified, the items of `loader` are supposed to come as batch, and are loader_batched here making
+ it roughly behave as
+
+
+ ```
+ for items in loader:
+ for i in loader_batch_size:
+ item = items[i]
+ yield infer(item, **params)
+ ```"""
+
+ def __iter__(self):
+ self.iterator = iter(self.loader)
+ return self
+
+ def __next__(self):
+ # Extremely similar to PipelineIterator in its unpacking mechanism
+ # BUT, we have an extra required item which is the presence of `is_last`
+ # That is because everything is flattened by `PipelineChunkIterator` we
+ # need to keep track of how to regroup here in the original `process`
+ # boundaries so that `process` and `postprocess` see the same data.
+
+ # This iterator accumulates items (possibly while unbatching) until it
+ # its a `is_last` and then just passes it on to the caller.
+ is_last = False
+ accumulator = []
+ if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size:
+ while self._loader_batch_index < self.loader_batch_size:
+ item = self.loader_batch_item()
+ is_last = item.pop("is_last")
+ accumulator.append(item)
+ if is_last:
+ return accumulator
+
+ while not is_last:
+ processed = self.infer(next(self.iterator), **self.params)
+ if self.loader_batch_size is not None:
+ if isinstance(processed, torch.Tensor):
+ first_tensor = processed
+ else:
+ key = list(processed.keys())[0]
+ first_tensor = processed[key]
+ if isinstance(first_tensor, list):
+ observed_batch_size = len(first_tensor)
+ else:
+ observed_batch_size = first_tensor.shape[0]
+ if 0 < observed_batch_size < self.loader_batch_size:
+ # could be last batch so we can't unroll as many
+ # elements.
+ self.loader_batch_size = observed_batch_size
+ self._loader_batch_data = processed
+ self._loader_batch_index = 0
+ while self._loader_batch_index < self.loader_batch_size:
+ item = self.loader_batch_item()
+ is_last = item.pop("is_last")
+ accumulator.append(item)
+ if is_last:
+ return accumulator
+ else:
+ item = processed
+ is_last = item.pop("is_last")
+ accumulator.append(item)
+ return accumulator
+
+
+class KeyDataset(Dataset):
+ def __init__(self, dataset: Dataset, key: str):
+ self.dataset = dataset
+ self.key = key
+
+ def __len__(self):
+ return len(self.dataset)
+
+ def __getitem__(self, i):
+ return self.dataset[i][self.key]
+
+
+class KeyPairDataset(Dataset):
+ def __init__(self, dataset: Dataset, key1: str, key2: str):
+ self.dataset = dataset
+ self.key1 = key1
+ self.key2 = key2
+
+ def __len__(self):
+ return len(self.dataset)
+
+ def __getitem__(self, i):
+ return {"text": self.dataset[i][self.key1], "text_pair": self.dataset[i][self.key2]}
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/table_question_answering.py b/.venv/lib/python3.12/site-packages/transformers/pipelines/table_question_answering.py
new file mode 100644
index 0000000000000000000000000000000000000000..96bcc863cbe791dde19497d876df754d4fdaf683
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/pipelines/table_question_answering.py
@@ -0,0 +1,382 @@
+import collections
+import types
+
+import numpy as np
+
+from ..generation import GenerationConfig
+from ..utils import (
+ add_end_docstrings,
+ is_torch_available,
+ requires_backends,
+)
+from .base import ArgumentHandler, Dataset, Pipeline, PipelineException, build_pipeline_init_args
+
+
+if is_torch_available():
+ import torch
+
+ from ..models.auto.modeling_auto import (
+ MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,
+ MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES,
+ )
+
+
+class TableQuestionAnsweringArgumentHandler(ArgumentHandler):
+ """
+ Handles arguments for the TableQuestionAnsweringPipeline
+ """
+
+ def __call__(self, table=None, query=None, **kwargs):
+ # Returns tqa_pipeline_inputs of shape:
+ # [
+ # {"table": pd.DataFrame, "query": list[str]},
+ # ...,
+ # {"table": pd.DataFrame, "query" : list[str]}
+ # ]
+ requires_backends(self, "pandas")
+ import pandas as pd
+
+ if table is None:
+ raise ValueError("Keyword argument `table` cannot be None.")
+ elif query is None:
+ if isinstance(table, dict) and table.get("query") is not None and table.get("table") is not None:
+ tqa_pipeline_inputs = [table]
+ elif isinstance(table, list) and len(table) > 0:
+ if not all(isinstance(d, dict) for d in table):
+ raise ValueError(
+ f"Keyword argument `table` should be a list of dict, but is {(type(d) for d in table)}"
+ )
+
+ if table[0].get("query") is not None and table[0].get("table") is not None:
+ tqa_pipeline_inputs = table
+ else:
+ raise ValueError(
+ "If keyword argument `table` is a list of dictionaries, each dictionary should have a `table`"
+ f" and `query` key, but only dictionary has keys {table[0].keys()} `table` and `query` keys."
+ )
+ elif Dataset is not None and isinstance(table, Dataset) or isinstance(table, types.GeneratorType):
+ return table
+ else:
+ raise ValueError(
+ "Invalid input. Keyword argument `table` should be either of type `dict` or `list`, but "
+ f"is {type(table)})"
+ )
+ else:
+ tqa_pipeline_inputs = [{"table": table, "query": query}]
+
+ for tqa_pipeline_input in tqa_pipeline_inputs:
+ if not isinstance(tqa_pipeline_input["table"], pd.DataFrame):
+ if tqa_pipeline_input["table"] is None:
+ raise ValueError("Table cannot be None.")
+
+ tqa_pipeline_input["table"] = pd.DataFrame(tqa_pipeline_input["table"])
+
+ return tqa_pipeline_inputs
+
+
+@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True))
+class TableQuestionAnsweringPipeline(Pipeline):
+ """
+ Table Question Answering pipeline using a `ModelForTableQuestionAnswering`. This pipeline is only available in
+ PyTorch.
+
+ Unless the model you're using explicitly sets these generation parameters in its configuration files
+ (`generation_config.json`), the following default values will be used:
+ - max_new_tokens: 256
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> oracle = pipeline(model="google/tapas-base-finetuned-wtq")
+ >>> table = {
+ ... "Repository": ["Transformers", "Datasets", "Tokenizers"],
+ ... "Stars": ["36542", "4512", "3934"],
+ ... "Contributors": ["651", "77", "34"],
+ ... "Programming language": ["Python", "Python", "Rust, Python and NodeJS"],
+ ... }
+ >>> oracle(query="How many stars does the transformers repository have?", table=table)
+ {'answer': 'AVERAGE > 36542', 'coordinates': [(0, 1)], 'cells': ['36542'], 'aggregator': 'AVERAGE'}
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This tabular question answering pipeline can currently be loaded from [`pipeline`] using the following task
+ identifier: `"table-question-answering"`.
+
+ The models that this pipeline can use are models that have been fine-tuned on a tabular question answering task.
+ See the up-to-date list of available models on
+ [huggingface.co/models](https://huggingface.co/models?filter=table-question-answering).
+ """
+
+ default_input_names = "table,query"
+
+ _pipeline_calls_generate = True
+ _load_processor = False
+ _load_image_processor = False
+ _load_feature_extractor = False
+ _load_tokenizer = True
+ # Make sure the docstring is updated when the default generation config is changed
+ _default_generation_config = GenerationConfig(
+ max_new_tokens=256,
+ )
+
+ def __init__(self, args_parser=TableQuestionAnsweringArgumentHandler(), **kwargs):
+ super().__init__(**kwargs)
+ self._args_parser = args_parser
+
+ mapping = MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES.copy()
+ mapping.update(MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES)
+ self.check_model_type(mapping)
+
+ self.aggregate = getattr(self.model.config, "aggregation_labels", None) and getattr(
+ self.model.config, "num_aggregation_labels", None
+ )
+ self.type = "tapas" if hasattr(self.model.config, "aggregation_labels") else None
+
+ def batch_inference(self, **inputs):
+ return self.model(**inputs)
+
+ def sequential_inference(self, **inputs):
+ """
+ Inference used for models that need to process sequences in a sequential fashion, like the SQA models which
+ handle conversational query related to a table.
+ """
+ all_logits = []
+ all_aggregations = []
+ prev_answers = None
+ batch_size = inputs["input_ids"].shape[0]
+
+ input_ids = inputs["input_ids"].to(self.device)
+ attention_mask = inputs["attention_mask"].to(self.device)
+ token_type_ids = inputs["token_type_ids"].to(self.device)
+ token_type_ids_example = None
+
+ for index in range(batch_size):
+ # If sequences have already been processed, the token type IDs will be created according to the previous
+ # answer.
+ if prev_answers is not None:
+ prev_labels_example = token_type_ids_example[:, 3] # shape (seq_len,)
+ model_labels = np.zeros_like(prev_labels_example.cpu().numpy()) # shape (seq_len,)
+
+ token_type_ids_example = token_type_ids[index] # shape (seq_len, 7)
+ for i in range(model_labels.shape[0]):
+ segment_id = token_type_ids_example[:, 0].tolist()[i]
+ col_id = token_type_ids_example[:, 1].tolist()[i] - 1
+ row_id = token_type_ids_example[:, 2].tolist()[i] - 1
+
+ if row_id >= 0 and col_id >= 0 and segment_id == 1:
+ model_labels[i] = int(prev_answers[(col_id, row_id)])
+
+ token_type_ids_example[:, 3] = torch.from_numpy(model_labels).type(torch.long).to(self.device)
+
+ input_ids_example = input_ids[index]
+ attention_mask_example = attention_mask[index] # shape (seq_len,)
+ token_type_ids_example = token_type_ids[index] # shape (seq_len, 7)
+ outputs = self.model(
+ input_ids=input_ids_example.unsqueeze(0),
+ attention_mask=attention_mask_example.unsqueeze(0),
+ token_type_ids=token_type_ids_example.unsqueeze(0),
+ )
+ logits = outputs.logits
+
+ if self.aggregate:
+ all_aggregations.append(outputs.logits_aggregation)
+
+ all_logits.append(logits)
+
+ dist_per_token = torch.distributions.Bernoulli(logits=logits)
+ probabilities = dist_per_token.probs * attention_mask_example.type(torch.float32).to(
+ dist_per_token.probs.device
+ )
+
+ coords_to_probs = collections.defaultdict(list)
+ for i, p in enumerate(probabilities.squeeze().tolist()):
+ segment_id = token_type_ids_example[:, 0].tolist()[i]
+ col = token_type_ids_example[:, 1].tolist()[i] - 1
+ row = token_type_ids_example[:, 2].tolist()[i] - 1
+ if col >= 0 and row >= 0 and segment_id == 1:
+ coords_to_probs[(col, row)].append(p)
+
+ prev_answers = {key: np.array(coords_to_probs[key]).mean() > 0.5 for key in coords_to_probs}
+
+ logits_batch = torch.cat(tuple(all_logits), 0)
+
+ return (logits_batch,) if not self.aggregate else (logits_batch, torch.cat(tuple(all_aggregations), 0))
+
+ def __call__(self, *args, **kwargs):
+ r"""
+ Answers queries according to a table. The pipeline accepts several types of inputs which are detailed below:
+
+ - `pipeline(table, query)`
+ - `pipeline(table, [query])`
+ - `pipeline(table=table, query=query)`
+ - `pipeline(table=table, query=[query])`
+ - `pipeline({"table": table, "query": query})`
+ - `pipeline({"table": table, "query": [query]})`
+ - `pipeline([{"table": table, "query": query}, {"table": table, "query": query}])`
+
+ The `table` argument should be a dict or a DataFrame built from that dict, containing the whole table:
+
+ Example:
+
+ ```python
+ data = {
+ "actors": ["brad pitt", "leonardo di caprio", "george clooney"],
+ "age": ["56", "45", "59"],
+ "number of movies": ["87", "53", "69"],
+ "date of birth": ["7 february 1967", "10 june 1996", "28 november 1967"],
+ }
+ ```
+
+ This dictionary can be passed in as such, or can be converted to a pandas DataFrame:
+
+ Example:
+
+ ```python
+ import pandas as pd
+
+ table = pd.DataFrame.from_dict(data)
+ ```
+
+ Args:
+ table (`pd.DataFrame` or `Dict`):
+ Pandas DataFrame or dictionary that will be converted to a DataFrame containing all the table values.
+ See above for an example of dictionary.
+ query (`str` or `list[str]`):
+ Query or list of queries that will be sent to the model alongside the table.
+ sequential (`bool`, *optional*, defaults to `False`):
+ Whether to do inference sequentially or as a batch. Batching is faster, but models like SQA require the
+ inference to be done sequentially to extract relations within sequences, given their conversational
+ nature.
+ padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
+ Activates and controls padding. Accepts the following values:
+
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
+ sequence if provided).
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
+ acceptable input length for the model if that argument is not provided.
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
+ lengths).
+
+ truncation (`bool`, `str` or [`TapasTruncationStrategy`], *optional*, defaults to `False`):
+ Activates and controls truncation. Accepts the following values:
+
+ - `True` or `'drop_rows_to_fit'`: Truncate to a maximum length specified with the argument `max_length`
+ or to the maximum acceptable input length for the model if that argument is not provided. This will
+ truncate row by row, removing rows from the table.
+ - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
+ greater than the model maximum admissible input size).
+
+
+ Return:
+ A dictionary or a list of dictionaries containing results: Each result is a dictionary with the following
+ keys:
+
+ - **answer** (`str`) -- The answer of the query given the table. If there is an aggregator, the answer will
+ be preceded by `AGGREGATOR >`.
+ - **coordinates** (`list[tuple[int, int]]`) -- Coordinates of the cells of the answers.
+ - **cells** (`list[str]`) -- List of strings made up of the answer cell values.
+ - **aggregator** (`str`) -- If the model has an aggregator, this returns the aggregator.
+ """
+ pipeline_inputs = self._args_parser(*args, **kwargs)
+
+ results = super().__call__(pipeline_inputs, **kwargs)
+ if len(results) == 1:
+ return results[0]
+ return results
+
+ def _sanitize_parameters(self, sequential=None, padding=None, truncation=None, **kwargs):
+ preprocess_params = {}
+ if padding is not None:
+ preprocess_params["padding"] = padding
+ if truncation is not None:
+ preprocess_params["truncation"] = truncation
+
+ forward_params = {}
+ if sequential is not None:
+ forward_params["sequential"] = sequential
+
+ if getattr(self, "assistant_model", None) is not None:
+ forward_params["assistant_model"] = self.assistant_model
+ if getattr(self, "assistant_tokenizer", None) is not None:
+ forward_params["tokenizer"] = self.tokenizer
+ forward_params["assistant_tokenizer"] = self.assistant_tokenizer
+
+ return preprocess_params, forward_params, {}
+
+ def preprocess(self, pipeline_input, padding=True, truncation=None):
+ if truncation is None:
+ if self.type == "tapas":
+ truncation = "drop_rows_to_fit"
+ else:
+ truncation = "do_not_truncate"
+
+ table, query = pipeline_input["table"], pipeline_input["query"]
+ if table.empty:
+ raise ValueError("table is empty")
+ if query is None or query == "":
+ raise ValueError("query is empty")
+ inputs = self.tokenizer(table, query, return_tensors="pt", truncation=truncation, padding=padding)
+ inputs["table"] = table
+ return inputs
+
+ def _forward(self, model_inputs, sequential=False, **generate_kwargs):
+ table = model_inputs.pop("table")
+
+ if self.type == "tapas":
+ if sequential:
+ outputs = self.sequential_inference(**model_inputs)
+ else:
+ outputs = self.batch_inference(**model_inputs)
+ else:
+ # User-defined `generation_config` passed to the pipeline call take precedence
+ if "generation_config" not in generate_kwargs:
+ generate_kwargs["generation_config"] = self.generation_config
+
+ outputs = self.model.generate(**model_inputs, **generate_kwargs)
+ model_outputs = {"model_inputs": model_inputs, "table": table, "outputs": outputs}
+ return model_outputs
+
+ def postprocess(self, model_outputs):
+ inputs = model_outputs["model_inputs"]
+ table = model_outputs["table"]
+ outputs = model_outputs["outputs"]
+ if self.type == "tapas":
+ if self.aggregate:
+ logits, logits_agg = outputs[:2]
+ predictions = self.tokenizer.convert_logits_to_predictions(inputs, logits, logits_agg)
+ answer_coordinates_batch, agg_predictions = predictions
+ aggregators = {i: self.model.config.aggregation_labels[pred] for i, pred in enumerate(agg_predictions)}
+
+ no_agg_label_index = self.model.config.no_aggregation_label_index
+ aggregators_prefix = {
+ i: aggregators[i] + " > " for i, pred in enumerate(agg_predictions) if pred != no_agg_label_index
+ }
+ else:
+ logits = outputs[0]
+ predictions = self.tokenizer.convert_logits_to_predictions(inputs, logits)
+ answer_coordinates_batch = predictions[0]
+ aggregators = {}
+ aggregators_prefix = {}
+ answers = []
+ for index, coordinates in enumerate(answer_coordinates_batch):
+ cells = [table.iat[coordinate] for coordinate in coordinates]
+ aggregator = aggregators.get(index, "")
+ aggregator_prefix = aggregators_prefix.get(index, "")
+ answer = {
+ "answer": aggregator_prefix + ", ".join(cells),
+ "coordinates": coordinates,
+ "cells": [table.iat[coordinate] for coordinate in coordinates],
+ }
+ if aggregator:
+ answer["aggregator"] = aggregator
+
+ answers.append(answer)
+ if len(answer) == 0:
+ raise PipelineException("Table question answering", self.model.name_or_path, "Empty answer")
+ else:
+ answers = [{"answer": answer} for answer in self.tokenizer.batch_decode(outputs, skip_special_tokens=True)]
+
+ return answers if len(answers) > 1 else answers[0]
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/text_classification.py b/.venv/lib/python3.12/site-packages/transformers/pipelines/text_classification.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab9a5d8efbc4ae9f60e0d39782f418863d773b7a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/pipelines/text_classification.py
@@ -0,0 +1,219 @@
+import inspect
+from typing import Any
+
+import numpy as np
+
+from ..utils import ExplicitEnum, add_end_docstrings, is_torch_available
+from .base import GenericTensor, Pipeline, build_pipeline_init_args
+
+
+if is_torch_available():
+ from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES
+
+
+def sigmoid(_outputs):
+ return 1.0 / (1.0 + np.exp(-_outputs))
+
+
+def softmax(_outputs):
+ maxes = np.max(_outputs, axis=-1, keepdims=True)
+ shifted_exp = np.exp(_outputs - maxes)
+ return shifted_exp / shifted_exp.sum(axis=-1, keepdims=True)
+
+
+class ClassificationFunction(ExplicitEnum):
+ SIGMOID = "sigmoid"
+ SOFTMAX = "softmax"
+ NONE = "none"
+
+
+@add_end_docstrings(
+ build_pipeline_init_args(has_tokenizer=True),
+ r"""
+ function_to_apply (`str`, *optional*, defaults to `"default"`):
+ The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:
+
+ - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model
+ has several labels, will apply the softmax function on the output. In case of regression tasks, will not
+ apply any function on the output.
+ - `"sigmoid"`: Applies the sigmoid function on the output.
+ - `"softmax"`: Applies the softmax function on the output.
+ - `"none"`: Does not apply any function on the output.""",
+)
+class TextClassificationPipeline(Pipeline):
+ """
+ Text classification pipeline using any `ModelForSequenceClassification`. See the [sequence classification
+ examples](../task_summary#sequence-classification) for more information.
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> classifier = pipeline(model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
+ >>> classifier("This movie is disgustingly good !")
+ [{'label': 'POSITIVE', 'score': 1.0}]
+
+ >>> classifier("Director tried too much.")
+ [{'label': 'NEGATIVE', 'score': 0.996}]
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This text classification pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"sentiment-analysis"` (for classifying sequences according to positive or negative sentiments).
+
+ If multiple classification labels are available (`model.config.num_labels >= 2`), the pipeline will run a softmax
+ over the results. If there is a single label, the pipeline will run a sigmoid over the result. In case of regression
+ tasks (`model.config.problem_type == "regression"`), will not apply any function on the output.
+
+ The models that this pipeline can use are models that have been fine-tuned on a sequence classification task. See
+ the up-to-date list of available models on
+ [huggingface.co/models](https://huggingface.co/models?filter=text-classification).
+ """
+
+ _load_processor = False
+ _load_image_processor = False
+ _load_feature_extractor = False
+ _load_tokenizer = True
+
+ function_to_apply = ClassificationFunction.NONE
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+
+ self.check_model_type(MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES)
+
+ def _sanitize_parameters(self, function_to_apply=None, top_k="", **tokenizer_kwargs):
+ # Using "" as default argument because we're going to use `top_k=None` in user code to declare
+ # "No top_k"
+ preprocess_params = tokenizer_kwargs
+
+ postprocess_params = {}
+
+ if isinstance(top_k, int) or top_k is None:
+ postprocess_params["top_k"] = top_k
+ postprocess_params["_legacy"] = False
+
+ if isinstance(function_to_apply, str):
+ function_to_apply = ClassificationFunction[function_to_apply.upper()]
+
+ if function_to_apply is not None:
+ postprocess_params["function_to_apply"] = function_to_apply
+ return preprocess_params, {}, postprocess_params
+
+ def __call__(
+ self,
+ inputs: str | list[str] | dict[str, str] | list[dict[str, str]],
+ **kwargs: Any,
+ ) -> list[dict[str, Any]]:
+ """
+ Classify the text(s) given as inputs.
+
+ Args:
+ inputs (`str` or `list[str]` or `dict[str]`, or `list[dict[str]]`):
+ One or several texts to classify. In order to use text pairs for your classification, you can send a
+ dictionary containing `{"text", "text_pair"}` keys, or a list of those.
+ top_k (`int`, *optional*, defaults to `1`):
+ How many results to return.
+ function_to_apply (`str`, *optional*, defaults to `"default"`):
+ The function to apply to the model outputs in order to retrieve the scores. Accepts four different
+ values:
+
+ If this argument is not specified, then it will apply the following functions according to the number
+ of labels:
+
+ - If problem type is regression, will not apply any function on the output.
+ - If the model has a single label, will apply the sigmoid function on the output.
+ - If the model has several labels, will apply the softmax function on the output.
+
+ Possible values are:
+
+ - `"sigmoid"`: Applies the sigmoid function on the output.
+ - `"softmax"`: Applies the softmax function on the output.
+ - `"none"`: Does not apply any function on the output.
+
+ Return:
+ A list of `dict`: Each result comes as list of dictionaries with the following keys:
+
+ - **label** (`str`) -- The label predicted.
+ - **score** (`float`) -- The corresponding probability.
+
+ If `top_k` is used, one such dictionary is returned per label.
+ """
+ inputs = (inputs,)
+ result = super().__call__(*inputs, **kwargs)
+ # TODO try and retrieve it in a nicer way from _sanitize_parameters.
+ _legacy = "top_k" not in kwargs
+ if isinstance(inputs[0], str) and _legacy:
+ # This pipeline is odd, and return a list when single item is run
+ return [result]
+ else:
+ return result
+
+ def preprocess(self, inputs, **tokenizer_kwargs) -> dict[str, GenericTensor]:
+ return_tensors = "pt"
+ if isinstance(inputs, dict):
+ return self.tokenizer(**inputs, return_tensors=return_tensors, **tokenizer_kwargs)
+ elif isinstance(inputs, list) and len(inputs) == 1 and isinstance(inputs[0], list) and len(inputs[0]) == 2:
+ # It used to be valid to use a list of list of list for text pairs, keeping this path for BC
+ return self.tokenizer(
+ text=inputs[0][0], text_pair=inputs[0][1], return_tensors=return_tensors, **tokenizer_kwargs
+ )
+ elif isinstance(inputs, list):
+ # This is likely an invalid usage of the pipeline attempting to pass text pairs.
+ raise ValueError(
+ "The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a"
+ ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.'
+ )
+ return self.tokenizer(inputs, return_tensors=return_tensors, **tokenizer_kwargs)
+
+ def _forward(self, model_inputs):
+ # `XXXForSequenceClassification` models should not use `use_cache=True` even if it's supported
+ model_forward = self.model.forward
+ if "use_cache" in inspect.signature(model_forward).parameters:
+ model_inputs["use_cache"] = False
+ return self.model(**model_inputs)
+
+ def postprocess(self, model_outputs, function_to_apply=None, top_k=1, _legacy=True):
+ # `_legacy` is used to determine if we're running the naked pipeline and in backward
+ # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running
+ # the more natural result containing the list.
+ # Default value before `set_parameters`
+ if function_to_apply is None:
+ if self.model.config.problem_type == "regression":
+ function_to_apply = ClassificationFunction.NONE
+ elif self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
+ function_to_apply = ClassificationFunction.SIGMOID
+ elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
+ function_to_apply = ClassificationFunction.SOFTMAX
+ elif hasattr(self.model.config, "function_to_apply") and function_to_apply is None:
+ function_to_apply = self.model.config.function_to_apply
+ else:
+ function_to_apply = ClassificationFunction.NONE
+
+ outputs = model_outputs["logits"][0]
+
+ # To enable using fp16 and bf16
+ outputs = outputs.float().numpy()
+
+ if function_to_apply == ClassificationFunction.SIGMOID:
+ scores = sigmoid(outputs)
+ elif function_to_apply == ClassificationFunction.SOFTMAX:
+ scores = softmax(outputs)
+ elif function_to_apply == ClassificationFunction.NONE:
+ scores = outputs
+ else:
+ raise ValueError(f"Unrecognized `function_to_apply` argument: {function_to_apply}")
+
+ if top_k == 1 and _legacy:
+ return {"label": self.model.config.id2label[scores.argmax().item()], "score": scores.max().item()}
+
+ dict_scores = [
+ {"label": self.model.config.id2label[i], "score": score.item()} for i, score in enumerate(scores)
+ ]
+ if not _legacy:
+ dict_scores.sort(key=lambda x: x["score"], reverse=True)
+ if top_k is not None:
+ dict_scores = dict_scores[:top_k]
+ return dict_scores
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/text_generation.py b/.venv/lib/python3.12/site-packages/transformers/pipelines/text_generation.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9ae9d077dd3beb7a2b9e216282504266fa37267
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/pipelines/text_generation.py
@@ -0,0 +1,499 @@
+import enum
+from typing import Any, overload
+
+from ..generation import GenerationConfig
+from ..utils import ModelOutput, add_end_docstrings, is_torch_available
+from ..utils.chat_template_utils import Chat, ChatType
+from .base import Pipeline, build_pipeline_init_args
+
+
+if is_torch_available():
+ import torch
+
+ from ..models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
+
+
+class ReturnType(enum.Enum):
+ TENSORS = 0
+ NEW_TEXT = 1
+ FULL_TEXT = 2
+
+
+@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True))
+class TextGenerationPipeline(Pipeline):
+ """
+ Language generation pipeline using any `ModelWithLMHead` or `ModelForCausalLM`. This pipeline predicts the words
+ that will follow a specified text prompt. When the underlying model is a conversational model, it can also accept
+ one or more chats, in which case the pipeline will operate in chat mode and will continue the chat(s) by adding
+ its response(s). Each chat takes the form of a list of dicts, where each dict contains "role" and "content" keys.
+
+ Unless the model you're using explicitly sets these generation parameters in its configuration files
+ (`generation_config.json`), the following default values will be used:
+ - max_new_tokens: 256
+ - do_sample: True
+ - temperature: 0.7
+
+ Examples:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> generator = pipeline(model="openai-community/gpt2")
+ >>> generator("I can't believe you did such a ", do_sample=False)
+ [{'generated_text': "I can't believe you did such a icky thing to me. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I"}]
+
+ >>> # These parameters will return suggestions, and only the newly created text making it easier for prompting suggestions.
+ >>> outputs = generator("My tart needs some", num_return_sequences=4, return_full_text=False)
+ ```
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> generator = pipeline(model="HuggingFaceH4/zephyr-7b-beta")
+ >>> # Zephyr-beta is a conversational model, so let's pass it a chat instead of a single string
+ >>> generator([{"role": "user", "content": "What is the capital of France? Answer in one word."}], do_sample=False, max_new_tokens=2)
+ [{'generated_text': [{'role': 'user', 'content': 'What is the capital of France? Answer in one word.'}, {'role': 'assistant', 'content': 'Paris'}]}]
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial). You can pass text
+ generation parameters to this pipeline to control stopping criteria, decoding strategy, and more. Learn more about
+ text generation parameters in [Text generation strategies](../generation_strategies) and [Text
+ generation](text_generation).
+
+ This language generation pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"text-generation"`.
+
+ The models that this pipeline can use are models that have been trained with an autoregressive language modeling
+ objective. See the list of available [text completion models](https://huggingface.co/models?filter=text-generation)
+ and the list of [conversational models](https://huggingface.co/models?other=conversational)
+ on [huggingface.co/models].
+ """
+
+ # Prefix text to help Transformer-XL and XLNet with short prompts as proposed by Aman Rusia
+ # in https://github.com/rusiaaman/XLNet-gen#methodology
+ # and https://medium.com/@amanrusia/xlnet-speaks-comparison-to-gpt-2-ea1a4e9ba39e
+
+ XL_PREFIX = """
+ In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The
+ voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western
+ Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision
+ and denounces one of the men as a horse thief. Although his father initially slaps him for making such an
+ accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of
+ the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,
+ begging for his blessing.
+ """
+
+ _pipeline_calls_generate = True
+ _load_processor = False
+ _load_image_processor = False
+ _load_feature_extractor = False
+ _load_tokenizer = True
+
+ # Make sure the docstring is updated when the default generation config is changed
+ _default_generation_config = GenerationConfig(
+ max_new_tokens=256,
+ do_sample=True, # free-form text generation often uses sampling
+ temperature=0.7,
+ )
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.check_model_type(MODEL_FOR_CAUSAL_LM_MAPPING_NAMES)
+ # Decoder-only models require left-padding for correct batched generation.
+ # Only override when there is no feature_extractor, to avoid padding_side conflicts
+ # (e.g., WhisperForCausalLM has a feature_extractor that pads on the right).
+ if self.tokenizer is not None and self.tokenizer.padding_side == "right":
+ self.tokenizer.padding_side = "left"
+
+ if "prefix" not in self._preprocess_params:
+ # This is very specific. The logic is quite complex and needs to be done
+ # as a "default".
+ # It also defines both some preprocess_kwargs and generate_kwargs
+ # which is why we cannot put them in their respective methods.
+ prefix = None
+ if self.prefix is not None:
+ prefix = self.prefix
+ if prefix is None and self.model.__class__.__name__ in [
+ "XLNetLMHeadModel",
+ "TransfoXLLMHeadModel",
+ ]:
+ # For XLNet and TransformerXL we add an article to the prompt to give more state to the model.
+ prefix = self.XL_PREFIX
+ if prefix is not None:
+ # Recalculate some generate_kwargs linked to prefix.
+ preprocess_params, forward_params, _ = self._sanitize_parameters(prefix=prefix, **self._forward_params)
+ self._preprocess_params = {**self._preprocess_params, **preprocess_params}
+ self._forward_params = {**self._forward_params, **forward_params}
+
+ def _sanitize_parameters(
+ self,
+ return_full_text=None,
+ return_tensors=None,
+ return_text=None,
+ return_type=None,
+ clean_up_tokenization_spaces=None,
+ prefix=None,
+ handle_long_generation=None,
+ stop_sequence=None,
+ truncation=None,
+ max_length=None,
+ continue_final_message=None,
+ skip_special_tokens=None,
+ tokenizer_encode_kwargs=None,
+ tools=None,
+ documents=None,
+ **generate_kwargs,
+ ):
+ # preprocess kwargs
+ preprocess_params = {}
+ add_special_tokens = False
+ if "add_special_tokens" in generate_kwargs:
+ add_special_tokens = preprocess_params["add_special_tokens"] = generate_kwargs.pop("add_special_tokens")
+
+ if "padding" in generate_kwargs:
+ preprocess_params["padding"] = generate_kwargs.pop("padding")
+
+ if truncation is not None:
+ preprocess_params["truncation"] = truncation
+
+ if max_length is not None:
+ preprocess_params["max_length"] = max_length
+ generate_kwargs["max_length"] = max_length
+
+ if tools is not None:
+ preprocess_params["tools"] = tools
+ if documents is not None:
+ preprocess_params["documents"] = documents
+
+ if prefix is not None:
+ preprocess_params["prefix"] = prefix
+ if prefix:
+ prefix_inputs = self.tokenizer(
+ prefix, padding=False, add_special_tokens=add_special_tokens, return_tensors="pt"
+ )
+ generate_kwargs["prefix_length"] = prefix_inputs["input_ids"].shape[-1]
+
+ if handle_long_generation is not None:
+ if handle_long_generation != "hole":
+ raise ValueError(
+ f"{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected"
+ " [None, 'hole']"
+ )
+ preprocess_params["handle_long_generation"] = handle_long_generation
+
+ if continue_final_message is not None:
+ preprocess_params["continue_final_message"] = continue_final_message
+
+ if tokenizer_encode_kwargs is not None:
+ preprocess_params["tokenizer_encode_kwargs"] = tokenizer_encode_kwargs
+
+ preprocess_params.update(generate_kwargs)
+
+ # forward kwargs
+ if stop_sequence is not None:
+ stop_sequence_ids = self.tokenizer.encode(stop_sequence, add_special_tokens=False)
+ generate_kwargs["eos_token_id"] = stop_sequence_ids
+ forward_params = generate_kwargs
+ if self.assistant_model is not None:
+ forward_params["assistant_model"] = self.assistant_model
+ if self.assistant_tokenizer is not None:
+ forward_params["tokenizer"] = self.tokenizer
+ forward_params["assistant_tokenizer"] = self.assistant_tokenizer
+
+ # postprocess kwargs
+ postprocess_params = {}
+ if return_full_text is not None and return_type is None:
+ if return_text is not None:
+ raise ValueError("`return_text` is mutually exclusive with `return_full_text`")
+ if return_tensors is not None:
+ raise ValueError("`return_full_text` is mutually exclusive with `return_tensors`")
+ return_type = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT
+ if return_tensors is not None and return_type is None:
+ if return_text is not None:
+ raise ValueError("`return_text` is mutually exclusive with `return_tensors`")
+ return_type = ReturnType.TENSORS
+ if return_type is not None:
+ postprocess_params["return_type"] = return_type
+ if clean_up_tokenization_spaces is not None:
+ postprocess_params["clean_up_tokenization_spaces"] = clean_up_tokenization_spaces
+ if continue_final_message is not None:
+ postprocess_params["continue_final_message"] = continue_final_message
+ if skip_special_tokens is not None:
+ postprocess_params["skip_special_tokens"] = skip_special_tokens
+
+ return preprocess_params, forward_params, postprocess_params
+
+ # overriding _parse_and_tokenize to allow for unusual language-modeling tokenizer arguments
+ def _parse_and_tokenize(self, *args, **kwargs):
+ """
+ Parse arguments and tokenize
+ """
+ # Parse arguments
+ if self.model.__class__.__name__ == "TransfoXLLMHeadModel":
+ kwargs.update({"add_space_before_punct_symbol": True})
+
+ return super()._parse_and_tokenize(*args, **kwargs)
+
+ @overload
+ def __call__(self, text_inputs: str, **kwargs: Any) -> list[dict[str, str]]: ...
+
+ @overload
+ def __call__(self, text_inputs: list[str], **kwargs: Any) -> list[list[dict[str, str]]]: ...
+
+ @overload
+ def __call__(self, text_inputs: ChatType, **kwargs: Any) -> list[dict[str, ChatType]]: ...
+
+ @overload
+ def __call__(self, text_inputs: list[ChatType], **kwargs: Any) -> list[list[dict[str, ChatType]]]: ...
+
+ def __call__(self, text_inputs, **kwargs):
+ """
+ Complete the prompt(s) given as inputs.
+
+ Args:
+ text_inputs (`str`, `list[str]`, `ChatType`, or `list[ChatType]`):
+ One or several prompts (or one list of prompts) to complete. If strings or a list of string are
+ passed, this pipeline will continue each prompt. Alternatively, a "chat", in the form of a list
+ of dicts with "role" and "content" keys, can be passed, or a list of such chats. When chats are passed,
+ the model's chat template will be used to format them before passing them to the model.
+ return_tensors (`bool`, *optional*, defaults to `False`):
+ Returns the tensors of predictions (as token indices) in the outputs. If set to
+ `True`, the decoded text is not returned.
+ return_text (`bool`, *optional*):
+ Returns the decoded texts in the outputs.
+ return_full_text (`bool`, *optional*, defaults to `True`):
+ If set to `False` only added text is returned, otherwise the full text is returned. Cannot be
+ specified at the same time as `return_text`.
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`):
+ Whether or not to clean up the potential extra spaces in the text output.
+ continue_final_message( `bool`, *optional*): This indicates that you want the model to continue the
+ last message in the input chat rather than starting a new one, allowing you to "prefill" its response.
+ By default this is `True` when the final message in the input chat has the `assistant` role and
+ `False` otherwise, but you can manually override that behaviour by setting this flag.
+ prefix (`str`, *optional*):
+ Prefix added to prompt.
+ handle_long_generation (`str`, *optional*):
+ By default, this pipelines does not handle long generation (ones that exceed in one form or the other
+ the model maximum length). There is no perfect way to address this (more info
+ :https://github.com/huggingface/transformers/issues/14033#issuecomment-948385227). This provides common
+ strategies to work around that problem depending on your use case.
+
+ - `None` : default strategy where nothing in particular happens
+ - `"hole"`: Truncates left of input, and leaves a gap wide enough to let generation happen (might
+ truncate a lot of the prompt and not suitable when generation exceed the model capacity)
+ tokenizer_encode_kwargs (`dict`, *optional*):
+ Additional keyword arguments to pass along to the encoding step of the tokenizer. If the text input is
+ a chat, it is passed to `apply_chat_template`. Otherwise, it is passed to `__call__`.
+ generate_kwargs (`dict`, *optional*):
+ Additional keyword arguments to pass along to the generate method of the model (see the generate method
+ [here](./text_generation)).
+
+ Return:
+ A list or a list of lists of `dict`: Returns one of the following dictionaries (cannot return a combination
+ of both `generated_text` and `generated_token_ids`):
+
+ - **generated_text** (`str`, present when `return_text=True`) -- The generated text.
+ - **generated_token_ids** (`torch.Tensor`, present when `return_tensors=True`) -- The token
+ ids of the generated text.
+ """
+ return super().__call__(text_inputs, **kwargs)
+
+ def preprocess(
+ self,
+ prompt_text,
+ prefix="",
+ handle_long_generation=None,
+ add_special_tokens=None,
+ truncation=None,
+ padding=None,
+ max_length=None,
+ continue_final_message=None,
+ tokenizer_encode_kwargs=None,
+ tools=None,
+ documents=None,
+ **generate_kwargs,
+ ):
+ # Only set non-None tokenizer kwargs, so as to rely on the tokenizer's defaults
+ tokenizer_kwargs = {
+ "add_special_tokens": add_special_tokens,
+ "truncation": truncation,
+ "padding": padding,
+ "max_length": max_length, # NOTE: `max_length` is also a `generate` arg. Use `tokenizer_encode_kwargs` to avoid a name clash
+ }
+ tokenizer_kwargs = {key: value for key, value in tokenizer_kwargs.items() if value is not None}
+ tokenizer_kwargs.update(tokenizer_encode_kwargs or {})
+
+ if isinstance(prompt_text, Chat):
+ tokenizer_kwargs.pop("add_special_tokens", None) # ignore add_special_tokens on chats
+ # If the user passes a chat that ends in an assistant message, we treat it as a prefill by default
+ # because very few models support multiple separate, consecutive assistant messages
+ if continue_final_message is None:
+ continue_final_message = prompt_text.messages[-1]["role"] == "assistant"
+ inputs = self.tokenizer.apply_chat_template(
+ prompt_text.messages,
+ add_generation_prompt=not continue_final_message,
+ continue_final_message=continue_final_message,
+ return_dict=True,
+ return_tensors="pt",
+ tools=tools,
+ documents=documents,
+ **tokenizer_kwargs,
+ )
+ else:
+ inputs = self.tokenizer(prefix + prompt_text, return_tensors="pt", **tokenizer_kwargs)
+
+ inputs["prompt_text"] = prompt_text
+
+ if handle_long_generation == "hole":
+ cur_len = inputs["input_ids"].shape[-1]
+ if "max_new_tokens" in generate_kwargs:
+ new_tokens = generate_kwargs["max_new_tokens"]
+ else:
+ new_tokens = generate_kwargs.get("max_length", self.generation_config.max_length) - cur_len
+ if new_tokens < 0:
+ raise ValueError("We cannot infer how many new tokens are expected")
+ if cur_len + new_tokens > self.tokenizer.model_max_length:
+ keep_length = self.tokenizer.model_max_length - new_tokens
+ if keep_length <= 0:
+ raise ValueError(
+ "We cannot use `hole` to handle this generation the number of desired tokens exceeds the"
+ " models max length"
+ )
+
+ inputs["input_ids"] = inputs["input_ids"][:, -keep_length:]
+ if "attention_mask" in inputs:
+ inputs["attention_mask"] = inputs["attention_mask"][:, -keep_length:]
+
+ return inputs
+
+ def _forward(self, model_inputs, **generate_kwargs):
+ input_ids = model_inputs["input_ids"]
+ attention_mask = model_inputs.get("attention_mask", None)
+ # Allow empty prompts
+ if input_ids.shape[1] == 0:
+ input_ids = None
+ attention_mask = None
+ in_b = 1
+ else:
+ in_b = input_ids.shape[0]
+ prompt_text = model_inputs.pop("prompt_text")
+
+ # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying
+ # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline.
+ prefix_length = generate_kwargs.pop("prefix_length", 0)
+ if prefix_length > 0:
+ has_max_new_tokens = "max_new_tokens" in generate_kwargs or (
+ "generation_config" in generate_kwargs
+ and generate_kwargs["generation_config"].max_new_tokens is not None
+ )
+ if not has_max_new_tokens:
+ generate_kwargs["max_length"] = generate_kwargs.get("max_length") or self.generation_config.max_length
+ generate_kwargs["max_length"] += prefix_length
+ has_min_new_tokens = "min_new_tokens" in generate_kwargs or (
+ "generation_config" in generate_kwargs
+ and generate_kwargs["generation_config"].min_new_tokens is not None
+ )
+ if not has_min_new_tokens and "min_length" in generate_kwargs:
+ generate_kwargs["min_length"] += prefix_length
+
+ # User-defined `generation_config` passed to the pipeline call take precedence
+ if "generation_config" not in generate_kwargs:
+ generate_kwargs["generation_config"] = self.generation_config
+
+ output = self.model.generate(input_ids=input_ids, attention_mask=attention_mask, **generate_kwargs)
+
+ if isinstance(output, ModelOutput):
+ generated_sequence = output.sequences
+ other_outputs = {k: v for k, v in output.items() if k not in {"sequences", "past_key_values"}}
+ out_b = generated_sequence.shape[0]
+
+ for key, value in other_outputs.items():
+ if isinstance(value, torch.Tensor) and value.shape[0] == out_b:
+ other_outputs[key] = value.reshape(in_b, out_b // in_b, *value.shape[1:])
+ if isinstance(value, tuple) and len(value[0]) == out_b:
+ value = torch.stack(value).swapaxes(0, 1)
+ other_outputs[key] = value
+ else:
+ generated_sequence = output
+ other_outputs = {}
+
+ out_b = generated_sequence.shape[0]
+ generated_sequence = generated_sequence.reshape(in_b, out_b // in_b, *generated_sequence.shape[1:])
+
+ model_outputs = {
+ "generated_sequence": generated_sequence,
+ "input_ids": input_ids,
+ "prompt_text": prompt_text,
+ }
+ if other_outputs:
+ model_outputs.update({"additional_outputs": other_outputs})
+ return model_outputs
+
+ def postprocess(
+ self,
+ model_outputs,
+ return_type=ReturnType.FULL_TEXT,
+ clean_up_tokenization_spaces=True,
+ continue_final_message=None,
+ skip_special_tokens=None,
+ ):
+ generated_sequence = model_outputs["generated_sequence"][0]
+ input_ids = model_outputs["input_ids"]
+ prompt_text = model_outputs["prompt_text"]
+ generated_sequence = generated_sequence.numpy().tolist()
+ records = []
+ other_outputs = model_outputs.get("additional_outputs", {})
+ split_keys = {}
+ if other_outputs:
+ for k, v in other_outputs.items():
+ if isinstance(v, torch.Tensor) and v.shape[0] == len(generated_sequence):
+ split_keys[k] = v.numpy().tolist()
+
+ skip_special_tokens = skip_special_tokens if skip_special_tokens is not None else True
+ if getattr(self.tokenizer, "response_schema", False):
+ skip_special_tokens = False
+ for idx, sequence in enumerate(generated_sequence):
+ if return_type == ReturnType.TENSORS:
+ record = {"generated_token_ids": sequence}
+ elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
+ if input_ids is None:
+ prompt_token_length = 0
+ else:
+ prompt_token_length = input_ids.shape[-1]
+
+ all_text = self.tokenizer.decode(
+ sequence[prompt_token_length:],
+ skip_special_tokens=skip_special_tokens,
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
+ )
+
+ if return_type == ReturnType.FULL_TEXT:
+ if isinstance(prompt_text, str):
+ all_text = prompt_text + all_text
+ elif isinstance(prompt_text, Chat):
+ if continue_final_message is None:
+ # If the user passes a chat ending in an assistant message, we treat it as a prefill by
+ # default because very few models support multiple separate, consecutive assistant messages
+ continue_final_message = prompt_text.messages[-1]["role"] == "assistant"
+ if continue_final_message:
+ # With assistant prefill, concat onto the end of the last message
+ all_text = list(prompt_text.messages)[:-1] + [
+ {
+ "role": prompt_text.messages[-1]["role"],
+ "content": prompt_text.messages[-1]["content"] + all_text,
+ }
+ ]
+ else:
+ # When we're not starting from a prefill, the output is a new assistant message
+ if getattr(self.tokenizer, "response_schema", False):
+ assistant_message = self.tokenizer.parse_response(all_text)
+ else:
+ # If there's no schema, then we have to assume it's all content
+ assistant_message = {"role": "assistant", "content": all_text}
+ all_text = list(prompt_text.messages) + [assistant_message]
+ record = {"generated_text": all_text}
+ for key, values in split_keys.items():
+ record[key] = values[idx]
+ records.append(record)
+
+ return records
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/text_to_audio.py b/.venv/lib/python3.12/site-packages/transformers/pipelines/text_to_audio.py
new file mode 100644
index 0000000000000000000000000000000000000000..a4d70912dd634802fe6e8816e7cbb5acc36f5ed0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/pipelines/text_to_audio.py
@@ -0,0 +1,316 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.from typing import List, Union
+
+from typing import Any, TypedDict, overload
+
+from ..audio_utils import AudioInput
+from ..generation import GenerationConfig
+from ..utils import is_torch_available
+from ..utils.chat_template_utils import Chat, ChatType
+from .base import Pipeline
+
+
+if is_torch_available():
+ import torch
+
+ from ..models.auto.modeling_auto import MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING
+ from ..models.speecht5.modeling_speecht5 import SpeechT5HifiGan
+
+DEFAULT_VOCODER_ID = "microsoft/speecht5_hifigan"
+
+
+class AudioOutput(TypedDict, total=False):
+ """
+ audio (`AudioInput`):
+ The generated audio waveform.
+ sampling_rate (`int`):
+ The sampling rate of the generated audio waveform.
+ """
+
+ audio: AudioInput
+ sampling_rate: int
+
+
+class TextToAudioPipeline(Pipeline):
+ """
+ Text-to-audio generation pipeline using any `AutoModelForTextToWaveform` or `AutoModelForTextToSpectrogram`. This
+ pipeline generates an audio file from an input text and optional other conditional inputs.
+
+ Unless the model you're using explicitly sets these generation parameters in its configuration files
+ (`generation_config.json`), the following default values will be used:
+ - max_new_tokens: 256
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> pipe = pipeline(model="suno/bark-small")
+ >>> output = pipe("Hey it's HuggingFace on the phone!")
+
+ >>> audio = output["audio"]
+ >>> sampling_rate = output["sampling_rate"]
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+
+
+ You can specify parameters passed to the model by using [`TextToAudioPipeline.__call__.forward_params`] or
+ [`TextToAudioPipeline.__call__.generate_kwargs`].
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> music_generator = pipeline(task="text-to-audio", model="facebook/musicgen-small")
+
+ >>> # diversify the music generation by adding randomness with a high temperature and set a maximum music length
+ >>> generate_kwargs = {
+ ... "do_sample": True,
+ ... "temperature": 0.7,
+ ... "max_new_tokens": 35,
+ ... }
+
+ >>> outputs = music_generator("Techno music with high melodic riffs", generate_kwargs=generate_kwargs)
+ ```
+
+
+
+ This pipeline can currently be loaded from [`pipeline`] using the following task identifiers: `"text-to-speech"` or
+ `"text-to-audio"`.
+
+ See the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=text-to-speech).
+ """
+
+ _pipeline_calls_generate = True
+ _load_processor = None # prioritize processors as some models require it
+ _load_image_processor = False
+ _load_feature_extractor = False
+ _load_tokenizer = True
+
+ # Make sure the docstring is updated when the default generation config is changed
+ _default_generation_config = GenerationConfig(
+ max_new_tokens=256,
+ )
+
+ def __init__(self, *args, vocoder=None, sampling_rate=None, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ self.vocoder = None
+ if self.model.__class__ in MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING.values():
+ self.vocoder = (
+ SpeechT5HifiGan.from_pretrained(DEFAULT_VOCODER_ID).to(self.model.device)
+ if vocoder is None
+ else vocoder
+ )
+
+ if self.model.config.model_type in ["musicgen", "speecht5"]:
+ # MusicGen and SpeechT5 expect to use their tokenizer instead
+ self.processor = None
+
+ self.sampling_rate = sampling_rate
+ if self.vocoder is not None:
+ self.sampling_rate = self.vocoder.config.sampling_rate
+
+ if self.sampling_rate is None:
+ # get sampling_rate from config and generation config
+
+ config = self.model.config
+ gen_config = self.model.__dict__.get("generation_config", None)
+ if gen_config is not None:
+ config.update({k: v for k, v in gen_config.to_dict().items() if v is not None})
+
+ for sampling_rate_name in ["sample_rate", "sampling_rate"]:
+ sampling_rate = getattr(config, sampling_rate_name, None)
+ if sampling_rate is not None:
+ self.sampling_rate = sampling_rate
+ elif getattr(config, "codec_config", None) is not None:
+ sampling_rate = getattr(config.codec_config, sampling_rate_name, None)
+ if sampling_rate is not None:
+ self.sampling_rate = sampling_rate
+
+ # last fallback to get the sampling rate based on processor
+ if self.sampling_rate is None and self.processor is not None and hasattr(self.processor, "feature_extractor"):
+ self.sampling_rate = self.processor.feature_extractor.sampling_rate
+
+ def preprocess(self, text, **kwargs):
+ if isinstance(text, str):
+ text = [text]
+
+ if self.model.config.model_type == "bark":
+ # bark Tokenizer is called with BarkProcessor which uses those kwargs
+ # Check if generation_config has semantic_config (BarkGenerationConfig) or use default
+ max_length = 256
+ if hasattr(self.generation_config, "semantic_config"):
+ max_length = getattr(self.generation_config.semantic_config, "max_input_semantic_length", 256)
+ new_kwargs = {
+ "max_length": max_length,
+ "add_special_tokens": False,
+ "return_attention_mask": True,
+ "return_token_type_ids": False,
+ }
+
+ # priority is given to kwargs
+ new_kwargs.update(kwargs)
+ kwargs = new_kwargs
+
+ preprocessor = self.processor if self.processor is not None else self.tokenizer
+ if isinstance(text, Chat):
+ output = preprocessor.apply_chat_template(
+ text.messages,
+ tokenize=True,
+ return_dict=True,
+ **kwargs,
+ )
+ else:
+ # Add speaker ID if needed and user didn't insert at start of text
+ if self.model.config.model_type == "csm":
+ text = [f"[0]{t}" if not t.startswith("[") else t for t in text]
+ kwargs.setdefault("add_special_tokens", True)
+ if self.model.config.model_type == "dia":
+ text = [f"[S1] {t}" if not t.startswith("[") else t for t in text]
+ output = preprocessor(text, **kwargs, return_tensors="pt")
+
+ return output
+
+ def _forward(self, model_inputs, **kwargs):
+ # we expect some kwargs to be additional tensors which need to be on the right device
+ kwargs = self._ensure_tensor_on_device(kwargs, device=self.device)
+ forward_params = kwargs["forward_params"]
+ generate_kwargs = kwargs["generate_kwargs"]
+
+ if self.model.can_generate():
+ # we expect some kwargs to be additional tensors which need to be on the right device
+ generate_kwargs = self._ensure_tensor_on_device(generate_kwargs, device=self.device)
+
+ # User-defined `generation_config` passed to the pipeline call take precedence
+ if "generation_config" not in generate_kwargs:
+ generate_kwargs["generation_config"] = self.generation_config
+
+ # generate_kwargs get priority over forward_params
+ forward_params.update(generate_kwargs)
+
+ # ensure dict output to facilitate postprocessing
+ forward_params.update({"return_dict_in_generate": True})
+
+ if self.model.config.model_type in ["csm"]:
+ # NOTE (ebezzam): CSM does not have the audio tokenizer in the processor therefore `output_audio=True`
+ # needed for decoding to audio
+ if "output_audio" not in forward_params:
+ forward_params["output_audio"] = True
+
+ output = self.model.generate(**model_inputs, **forward_params)
+ else:
+ if len(generate_kwargs):
+ raise ValueError(
+ "You're using the `TextToAudioPipeline` with a forward-only model, but `generate_kwargs` is non "
+ "empty. For forward-only TTA models, please use `forward_params` instead of `generate_kwargs`. "
+ f"For reference, the `generate_kwargs` used here are: {generate_kwargs.keys()}"
+ )
+ output = self.model(**model_inputs, **forward_params)[0]
+
+ if self.vocoder is not None:
+ # in that case, the output is a spectrogram that needs to be converted into a waveform
+ output = self.vocoder(output)
+
+ return output
+
+ @overload
+ def __call__(self, text_inputs: str, **forward_params: Any) -> AudioOutput: ...
+
+ @overload
+ def __call__(self, text_inputs: list[str], **forward_params: Any) -> list[AudioOutput]: ...
+
+ @overload
+ def __call__(self, text_inputs: ChatType, **forward_params: Any) -> AudioOutput: ...
+
+ @overload
+ def __call__(self, text_inputs: list[ChatType], **forward_params: Any) -> list[AudioOutput]: ...
+
+ def __call__(self, text_inputs, **forward_params):
+ """
+ Generates speech/audio from the inputs. See the [`TextToAudioPipeline`] documentation for more information.
+
+ Args:
+ text_inputs (`str`, `list[str]`, `ChatType`, or `list[ChatType]`):
+ One or several texts to generate. If strings or a list of string are passed, this pipeline will
+ generate the corresponding text. Alternatively, a "chat", in the form of a list of dicts with "role"
+ and "content" keys, can be passed, or a list of such chats. When chats are passed, the model's chat
+ template will be used to format them before passing them to the model.
+ forward_params (`dict`, *optional*):
+ Parameters passed to the model generation/forward method. `forward_params` are always passed to the
+ underlying model.
+ generate_kwargs (`dict`, *optional*):
+ The dictionary of ad-hoc parametrization of `generate_config` to be used for the generation call. For a
+ complete overview of generate, check the [following
+ guide](https://huggingface.co/docs/transformers/en/main_classes/text_generation). `generate_kwargs` are
+ only passed to the underlying model if the latter is a generative model.
+
+ Return:
+ `AudioOutput` or a list of `AudioOutput`, which is a `TypedDict` with two keys:
+
+ - **audio** (`np.ndarray` of shape `(nb_channels, audio_length)`) -- The generated audio waveform.
+ - **sampling_rate** (`int`) -- The sampling rate of the generated audio waveform.
+ """
+ return super().__call__(text_inputs, **forward_params)
+
+ def _sanitize_parameters(
+ self,
+ preprocess_params=None,
+ forward_params=None,
+ generate_kwargs=None,
+ ):
+ if getattr(self, "assistant_model", None) is not None:
+ generate_kwargs["assistant_model"] = self.assistant_model
+ if getattr(self, "assistant_tokenizer", None) is not None:
+ generate_kwargs["tokenizer"] = self.tokenizer
+ generate_kwargs["assistant_tokenizer"] = self.assistant_tokenizer
+
+ params = {
+ "forward_params": forward_params if forward_params else {},
+ "generate_kwargs": generate_kwargs if generate_kwargs else {},
+ }
+
+ if preprocess_params is None:
+ preprocess_params = {}
+ postprocess_params = {}
+
+ return preprocess_params, params, postprocess_params
+
+ def postprocess(self, audio):
+ needs_decoding = False
+ if isinstance(audio, dict):
+ if "audio" in audio:
+ audio = audio["audio"]
+ else:
+ needs_decoding = True
+ audio = audio["sequences"]
+ elif isinstance(audio, tuple):
+ audio = audio[0]
+
+ if needs_decoding and self.processor is not None:
+ audio = self.processor.decode(audio)
+
+ if isinstance(audio, list):
+ audio = [el.to(device="cpu", dtype=torch.float).numpy().squeeze() for el in audio]
+ audio = audio if len(audio) > 1 else audio[0]
+ else:
+ audio = audio.to(device="cpu", dtype=torch.float).numpy().squeeze()
+
+ return AudioOutput(
+ audio=audio,
+ sampling_rate=self.sampling_rate,
+ )
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/token_classification.py b/.venv/lib/python3.12/site-packages/transformers/pipelines/token_classification.py
new file mode 100644
index 0000000000000000000000000000000000000000..7deca9dc900ac006932996acee4ba2bf3e1f2ab1
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/pipelines/token_classification.py
@@ -0,0 +1,622 @@
+import types
+import warnings
+from typing import Any, overload
+
+import numpy as np
+
+from ..models.bert.tokenization_bert_legacy import BasicTokenizer
+from ..utils import (
+ ExplicitEnum,
+ add_end_docstrings,
+ is_torch_available,
+)
+from .base import ArgumentHandler, ChunkPipeline, Dataset, build_pipeline_init_args
+
+
+if is_torch_available():
+ import torch
+
+ from ..models.auto.modeling_auto import MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES
+
+
+class TokenClassificationArgumentHandler(ArgumentHandler):
+ """
+ Handles arguments for token classification.
+ """
+
+ def __call__(self, inputs: str | list[str], **kwargs):
+ is_split_into_words = kwargs.get("is_split_into_words", False)
+ delimiter = kwargs.get("delimiter")
+
+ if inputs is not None and isinstance(inputs, (list, tuple)) and len(inputs) > 0:
+ inputs = list(inputs)
+ batch_size = len(inputs)
+ elif isinstance(inputs, str):
+ inputs = [inputs]
+ batch_size = 1
+ elif Dataset is not None and isinstance(inputs, Dataset) or isinstance(inputs, types.GeneratorType):
+ return inputs, is_split_into_words, None, delimiter
+ else:
+ raise ValueError("At least one input is required.")
+
+ offset_mapping = kwargs.get("offset_mapping")
+ if offset_mapping:
+ if isinstance(offset_mapping, list) and isinstance(offset_mapping[0], tuple):
+ offset_mapping = [offset_mapping]
+ if len(offset_mapping) != batch_size:
+ raise ValueError("offset_mapping should have the same batch size as the input")
+ return inputs, is_split_into_words, offset_mapping, delimiter
+
+
+class AggregationStrategy(ExplicitEnum):
+ """All the valid aggregation strategies for TokenClassificationPipeline"""
+
+ NONE = "none"
+ SIMPLE = "simple"
+ FIRST = "first"
+ AVERAGE = "average"
+ MAX = "max"
+
+
+@add_end_docstrings(
+ build_pipeline_init_args(has_tokenizer=True),
+ r"""
+ ignore_labels (`list[str]`, defaults to `["O"]`):
+ A list of labels to ignore.
+ stride (`int`, *optional*):
+ If stride is provided, the pipeline is applied on all the text. The text is split into chunks of size
+ model_max_length. Works only with fast tokenizers and `aggregation_strategy` different from `NONE`. The
+ value of this argument defines the number of overlapping tokens between chunks. In other words, the model
+ will shift forward by `tokenizer.model_max_length - stride` tokens each step.
+ aggregation_strategy (`str`, *optional*, defaults to `"none"`):
+ The strategy to fuse (or not) tokens based on the model prediction.
+
+ - "none" : Will simply not do any aggregation and simply return raw results from the model
+ - "simple" : Will attempt to group entities following the default schema. (A, B-TAG), (B, I-TAG), (C,
+ I-TAG), (D, B-TAG2) (E, B-TAG2) will end up being [{"word": ABC, "entity": "TAG"}, {"word": "D",
+ "entity": "TAG2"}, {"word": "E", "entity": "TAG2"}] Notice that two consecutive B tags will end up as
+ different entities. On word based languages, we might end up splitting words undesirably : Imagine
+ Microsoft being tagged as [{"word": "Micro", "entity": "ENTERPRISE"}, {"word": "soft", "entity":
+ "NAME"}]. Look for FIRST, MAX, AVERAGE for ways to mitigate that and disambiguate words (on languages
+ that support that meaning, which is basically tokens separated by a space). These mitigations will
+ only work on real words, "New york" might still be tagged with two different entities.
+ - "first" : (works only on word based models) Will use the `SIMPLE` strategy except that words, cannot
+ end up with different tags. Words will simply use the tag of the first token of the word when there
+ is ambiguity.
+ - "average" : (works only on word based models) Will use the `SIMPLE` strategy except that words,
+ cannot end up with different tags. scores will be averaged first across tokens, and then the maximum
+ label is applied.
+ - "max" : (works only on word based models) Will use the `SIMPLE` strategy except that words, cannot
+ end up with different tags. Word entity will simply be the token with the maximum score.""",
+)
+class TokenClassificationPipeline(ChunkPipeline):
+ """
+ Named Entity Recognition pipeline using any `ModelForTokenClassification`. See the [named entity recognition
+ examples](../task_summary#named-entity-recognition) for more information.
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> token_classifier = pipeline(model="Jean-Baptiste/camembert-ner", aggregation_strategy="simple")
+ >>> sentence = "Je m'appelle jean-baptiste et je vis à montréal"
+ >>> tokens = token_classifier(sentence)
+ >>> tokens
+ [{'entity_group': 'PER', 'score': 0.9931, 'word': 'jean-baptiste', 'start': 12, 'end': 26}, {'entity_group': 'LOC', 'score': 0.998, 'word': 'montréal', 'start': 38, 'end': 47}]
+
+ >>> token = tokens[0]
+ >>> # Start and end provide an easy way to highlight words in the original text.
+ >>> sentence[token["start"] : token["end"]]
+ ' jean-baptiste'
+
+ >>> # Some models use the same idea to do part of speech.
+ >>> syntaxer = pipeline(model="vblagoje/bert-english-uncased-finetuned-pos", aggregation_strategy="simple")
+ >>> syntaxer("My name is Sarah and I live in London")
+ [{'entity_group': 'PRON', 'score': 0.999, 'word': 'my', 'start': 0, 'end': 2}, {'entity_group': 'NOUN', 'score': 0.997, 'word': 'name', 'start': 3, 'end': 7}, {'entity_group': 'AUX', 'score': 0.994, 'word': 'is', 'start': 8, 'end': 10}, {'entity_group': 'PROPN', 'score': 0.999, 'word': 'sarah', 'start': 11, 'end': 16}, {'entity_group': 'CCONJ', 'score': 0.999, 'word': 'and', 'start': 17, 'end': 20}, {'entity_group': 'PRON', 'score': 0.999, 'word': 'i', 'start': 21, 'end': 22}, {'entity_group': 'VERB', 'score': 0.998, 'word': 'live', 'start': 23, 'end': 27}, {'entity_group': 'ADP', 'score': 0.999, 'word': 'in', 'start': 28, 'end': 30}, {'entity_group': 'PROPN', 'score': 0.999, 'word': 'london', 'start': 31, 'end': 37}]
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This token recognition pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"ner"` (for predicting the classes of tokens in a sequence: person, organisation, location or miscellaneous).
+
+ The models that this pipeline can use are models that have been fine-tuned on a token classification task. See the
+ up-to-date list of available models on
+ [huggingface.co/models](https://huggingface.co/models?filter=token-classification).
+ """
+
+ default_input_names = "sequences"
+
+ _load_processor = False
+ _load_image_processor = False
+ _load_feature_extractor = False
+ _load_tokenizer = True
+
+ def __init__(self, args_parser=TokenClassificationArgumentHandler(), **kwargs):
+ super().__init__(**kwargs)
+
+ self.check_model_type(MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES)
+
+ self._basic_tokenizer = BasicTokenizer(do_lower_case=False)
+ self._args_parser = args_parser
+
+ def _sanitize_parameters(
+ self,
+ ignore_labels=None,
+ aggregation_strategy: AggregationStrategy | None = None,
+ offset_mapping: list[tuple[int, int]] | None = None,
+ is_split_into_words: bool = False,
+ stride: int | None = None,
+ delimiter: str | None = None,
+ ):
+ preprocess_params = {}
+ preprocess_params["is_split_into_words"] = is_split_into_words
+
+ if is_split_into_words:
+ preprocess_params["delimiter"] = " " if delimiter is None else delimiter
+
+ if offset_mapping is not None:
+ preprocess_params["offset_mapping"] = offset_mapping
+
+ postprocess_params = {}
+ if aggregation_strategy is not None:
+ if isinstance(aggregation_strategy, str):
+ aggregation_strategy = AggregationStrategy[aggregation_strategy.upper()]
+ if (
+ aggregation_strategy
+ in {AggregationStrategy.FIRST, AggregationStrategy.MAX, AggregationStrategy.AVERAGE}
+ and not self.tokenizer.is_fast
+ ):
+ raise ValueError(
+ "Slow tokenizers cannot handle subwords. Please set the `aggregation_strategy` option"
+ ' to `"simple"` or use a fast tokenizer.'
+ )
+ postprocess_params["aggregation_strategy"] = aggregation_strategy
+ if ignore_labels is not None:
+ postprocess_params["ignore_labels"] = ignore_labels
+ if stride is not None:
+ if stride >= self.tokenizer.model_max_length:
+ raise ValueError(
+ "`stride` must be less than `tokenizer.model_max_length` (or even lower if the tokenizer adds special tokens)"
+ )
+ if aggregation_strategy == AggregationStrategy.NONE:
+ raise ValueError(
+ "`stride` was provided to process all the text but `aggregation_strategy="
+ f'"{aggregation_strategy}"`, please select another one instead.'
+ )
+ else:
+ if self.tokenizer.is_fast:
+ tokenizer_params = {
+ "return_overflowing_tokens": True,
+ "padding": True,
+ "stride": stride,
+ }
+ preprocess_params["tokenizer_params"] = tokenizer_params
+ else:
+ raise ValueError(
+ "`stride` was provided to process all the text but you're using a slow tokenizer."
+ " Please use a fast tokenizer."
+ )
+ return preprocess_params, {}, postprocess_params
+
+ @overload
+ def __call__(self, inputs: str, **kwargs: Any) -> list[dict[str, str]]: ...
+
+ @overload
+ def __call__(self, inputs: list[str], **kwargs: Any) -> list[list[dict[str, str]]]: ...
+
+ def __call__(self, inputs: str | list[str], **kwargs: Any) -> list[dict[str, str]] | list[list[dict[str, str]]]:
+ """
+ Classify each token of the text(s) given as inputs.
+
+ Args:
+ inputs (`str` or `List[str]`):
+ One or several texts (or one list of texts) for token classification. Can be pre-tokenized when
+ `is_split_into_words=True`.
+
+ Return:
+ A list or a list of list of `dict`: Each result comes as a list of dictionaries (one for each token in the
+ corresponding input, or each entity if this pipeline was instantiated with an aggregation_strategy) with
+ the following keys:
+
+ - **word** (`str`) -- The token/word classified. This is obtained by decoding the selected tokens. If you
+ want to have the exact string in the original sentence, use `start` and `end`.
+ - **score** (`float`) -- The corresponding probability for `entity`.
+ - **entity** (`str`) -- The entity predicted for that token/word (it is named *entity_group* when
+ *aggregation_strategy* is not `"none"`.
+ - **index** (`int`, only present when `aggregation_strategy="none"`) -- The index of the corresponding
+ token in the sentence.
+ - **start** (`int`, *optional*) -- The index of the start of the corresponding entity in the sentence. Only
+ exists if the offsets are available within the tokenizer
+ - **end** (`int`, *optional*) -- The index of the end of the corresponding entity in the sentence. Only
+ exists if the offsets are available within the tokenizer
+ """
+
+ _inputs, is_split_into_words, offset_mapping, delimiter = self._args_parser(inputs, **kwargs)
+ kwargs["is_split_into_words"] = is_split_into_words
+ kwargs["delimiter"] = delimiter
+ if is_split_into_words and not all(isinstance(input, list) for input in inputs):
+ return super().__call__([inputs], **kwargs)
+ if offset_mapping:
+ kwargs["offset_mapping"] = offset_mapping
+
+ return super().__call__(inputs, **kwargs)
+
+ def preprocess(self, sentence, offset_mapping=None, **preprocess_params):
+ tokenizer_params = preprocess_params.pop("tokenizer_params", {})
+ truncation = self.tokenizer.model_max_length and self.tokenizer.model_max_length > 0
+
+ word_to_chars_map = None
+ is_split_into_words = preprocess_params["is_split_into_words"]
+ if is_split_into_words:
+ delimiter = preprocess_params["delimiter"]
+ if not isinstance(sentence, list):
+ raise ValueError("When `is_split_into_words=True`, `sentence` must be a list of tokens.")
+ words = sentence
+ sentence = delimiter.join(words) # Recreate the sentence string for later display and slicing
+ # This map will allow to convert back word => char indices
+ word_to_chars_map = []
+ delimiter_len = len(delimiter)
+ char_offset = 0
+ for word in words:
+ word_to_chars_map.append((char_offset, char_offset + len(word)))
+ char_offset += len(word) + delimiter_len
+
+ # We use `words` as the actual input for the tokenizer
+ text_to_tokenize = words
+ tokenizer_params["is_split_into_words"] = True
+ else:
+ if not isinstance(sentence, str):
+ raise ValueError("When `is_split_into_words=False`, `sentence` must be an untokenized string.")
+ text_to_tokenize = sentence
+
+ inputs = self.tokenizer(
+ text_to_tokenize,
+ return_tensors="pt",
+ truncation=truncation,
+ return_special_tokens_mask=True,
+ return_offsets_mapping=self.tokenizer.is_fast,
+ **tokenizer_params,
+ )
+
+ if is_split_into_words and not self.tokenizer.is_fast:
+ raise ValueError("is_split_into_words=True is only supported with fast tokenizers.")
+
+ inputs.pop("overflow_to_sample_mapping", None)
+ num_chunks = len(inputs["input_ids"])
+
+ for i in range(num_chunks):
+ model_inputs = {k: v[i].unsqueeze(0) for k, v in inputs.items()}
+ if offset_mapping is not None:
+ model_inputs["offset_mapping"] = offset_mapping
+
+ model_inputs["sentence"] = sentence if i == 0 else None
+ model_inputs["is_last"] = i == num_chunks - 1
+ if word_to_chars_map is not None:
+ model_inputs["word_ids"] = inputs.word_ids(i)
+ model_inputs["word_to_chars_map"] = word_to_chars_map
+
+ yield model_inputs
+
+ def _forward(self, model_inputs):
+ # Forward
+ special_tokens_mask = model_inputs.pop("special_tokens_mask")
+ offset_mapping = model_inputs.pop("offset_mapping", None)
+ sentence = model_inputs.pop("sentence")
+ is_last = model_inputs.pop("is_last")
+ word_ids = model_inputs.pop("word_ids", None)
+ word_to_chars_map = model_inputs.pop("word_to_chars_map", None)
+
+ output = self.model(**model_inputs)
+ logits = output["logits"] if isinstance(output, dict) else output[0]
+
+ return {
+ "logits": logits,
+ "special_tokens_mask": special_tokens_mask,
+ "offset_mapping": offset_mapping,
+ "sentence": sentence,
+ "is_last": is_last,
+ "word_ids": word_ids,
+ "word_to_chars_map": word_to_chars_map,
+ **model_inputs,
+ }
+
+ def postprocess(self, all_outputs, aggregation_strategy=AggregationStrategy.NONE, ignore_labels=None):
+ if ignore_labels is None:
+ ignore_labels = ["O"]
+ all_entities = []
+
+ # Get map from the first output, it's the same for all chunks
+ word_to_chars_map = all_outputs[0].get("word_to_chars_map")
+
+ for model_outputs in all_outputs:
+ if model_outputs["logits"][0].dtype in (torch.bfloat16, torch.float16):
+ logits = model_outputs["logits"][0].to(torch.float32).numpy()
+ else:
+ logits = model_outputs["logits"][0].numpy()
+
+ sentence = all_outputs[0]["sentence"]
+ input_ids = model_outputs["input_ids"][0]
+ offset_mapping = (
+ model_outputs["offset_mapping"][0] if model_outputs["offset_mapping"] is not None else None
+ )
+ special_tokens_mask = model_outputs["special_tokens_mask"][0].numpy()
+ word_ids = model_outputs.get("word_ids")
+
+ maxes = np.max(logits, axis=-1, keepdims=True)
+ shifted_exp = np.exp(logits - maxes)
+ scores = shifted_exp / shifted_exp.sum(axis=-1, keepdims=True)
+
+ pre_entities = self.gather_pre_entities(
+ sentence,
+ input_ids,
+ scores,
+ offset_mapping,
+ special_tokens_mask,
+ aggregation_strategy,
+ word_ids=word_ids,
+ word_to_chars_map=word_to_chars_map,
+ )
+ grouped_entities = self.aggregate(pre_entities, aggregation_strategy)
+ # Filter anything that is in self.ignore_labels
+ entities = [
+ entity
+ for entity in grouped_entities
+ if entity.get("entity", None) not in ignore_labels
+ and entity.get("entity_group", None) not in ignore_labels
+ ]
+ all_entities.extend(entities)
+ num_chunks = len(all_outputs)
+ if num_chunks > 1:
+ all_entities = self.aggregate_overlapping_entities(all_entities)
+ return all_entities
+
+ def aggregate_overlapping_entities(self, entities):
+ if len(entities) == 0:
+ return entities
+ entities = sorted(entities, key=lambda x: x["start"])
+ aggregated_entities = []
+ previous_entity = entities[0]
+ for entity in entities:
+ if previous_entity["start"] <= entity["start"] < previous_entity["end"]:
+ current_length = entity["end"] - entity["start"]
+ previous_length = previous_entity["end"] - previous_entity["start"]
+ if (
+ current_length > previous_length
+ or current_length == previous_length
+ and entity["score"] > previous_entity["score"]
+ ):
+ previous_entity = entity
+ else:
+ aggregated_entities.append(previous_entity)
+ previous_entity = entity
+ aggregated_entities.append(previous_entity)
+ return aggregated_entities
+
+ def gather_pre_entities(
+ self,
+ sentence: str,
+ input_ids: np.ndarray,
+ scores: np.ndarray,
+ offset_mapping: list[tuple[int, int]] | None,
+ special_tokens_mask: np.ndarray,
+ aggregation_strategy: AggregationStrategy,
+ word_ids: list[int | None] | None = None,
+ word_to_chars_map: list[tuple[int, int]] | None = None,
+ ) -> list[dict]:
+ """Fuse various numpy arrays into dicts with all the information needed for aggregation"""
+ pre_entities = []
+ for idx, token_scores in enumerate(scores):
+ # Filter special_tokens
+ if special_tokens_mask[idx]:
+ continue
+
+ word = self.tokenizer.convert_ids_to_tokens(int(input_ids[idx]))
+ if offset_mapping is not None:
+ start_ind, end_ind = offset_mapping[idx]
+
+ # If the input is pre-tokenized, we need to rescale the offsets to the absolute sentence.
+ if word_ids is not None and word_to_chars_map is not None:
+ word_index = word_ids[idx]
+ if word_index is not None:
+ start_char, _ = word_to_chars_map[word_index]
+ start_ind += start_char
+ end_ind += start_char
+
+ if not isinstance(start_ind, int):
+ start_ind = start_ind.item()
+ end_ind = end_ind.item()
+ word_ref = sentence[start_ind:end_ind]
+ if getattr(self.tokenizer, "_tokenizer", None) and getattr(
+ self.tokenizer._tokenizer.model, "continuing_subword_prefix", None
+ ):
+ # This is a BPE, word aware tokenizer, there is a correct way
+ # to fuse tokens
+ is_subword = len(word) != len(word_ref)
+ else:
+ # This is a fallback heuristic. This will fail most likely on any kind of text + punctuation mixtures that will be considered "words". Non word aware models cannot do better than this unfortunately.
+ if aggregation_strategy in {
+ AggregationStrategy.FIRST,
+ AggregationStrategy.AVERAGE,
+ AggregationStrategy.MAX,
+ }:
+ warnings.warn(
+ "Tokenizer does not support real words, using fallback heuristic",
+ UserWarning,
+ )
+ is_subword = start_ind > 0 and " " not in sentence[start_ind - 1 : start_ind + 1]
+
+ if int(input_ids[idx]) == self.tokenizer.unk_token_id:
+ word = word_ref
+ is_subword = False
+ else:
+ start_ind = None
+ end_ind = None
+ is_subword = False
+
+ pre_entity = {
+ "word": word,
+ "scores": token_scores,
+ "start": start_ind,
+ "end": end_ind,
+ "index": idx,
+ "is_subword": is_subword,
+ }
+ pre_entities.append(pre_entity)
+ return pre_entities
+
+ def aggregate(self, pre_entities: list[dict], aggregation_strategy: AggregationStrategy) -> list[dict]:
+ if aggregation_strategy in {AggregationStrategy.NONE, AggregationStrategy.SIMPLE}:
+ entities = []
+ for pre_entity in pre_entities:
+ entity_idx = pre_entity["scores"].argmax()
+ score = pre_entity["scores"][entity_idx]
+ entity = {
+ "entity": self.model.config.id2label[entity_idx],
+ "score": score,
+ "index": pre_entity["index"],
+ "word": pre_entity["word"],
+ "start": pre_entity["start"],
+ "end": pre_entity["end"],
+ }
+ entities.append(entity)
+ else:
+ entities = self.aggregate_words(pre_entities, aggregation_strategy)
+
+ if aggregation_strategy == AggregationStrategy.NONE:
+ return entities
+ return self.group_entities(entities)
+
+ def aggregate_word(self, entities: list[dict], aggregation_strategy: AggregationStrategy) -> dict:
+ word = self.tokenizer.convert_tokens_to_string([entity["word"] for entity in entities])
+ if aggregation_strategy == AggregationStrategy.FIRST:
+ scores = entities[0]["scores"]
+ idx = scores.argmax()
+ score = scores[idx]
+ entity = self.model.config.id2label[idx]
+ elif aggregation_strategy == AggregationStrategy.MAX:
+ max_entity = max(entities, key=lambda entity: entity["scores"].max())
+ scores = max_entity["scores"]
+ idx = scores.argmax()
+ score = scores[idx]
+ entity = self.model.config.id2label[idx]
+ elif aggregation_strategy == AggregationStrategy.AVERAGE:
+ scores = np.stack([entity["scores"] for entity in entities])
+ average_scores = np.nanmean(scores, axis=0)
+ entity_idx = average_scores.argmax()
+ entity = self.model.config.id2label[entity_idx]
+ score = average_scores[entity_idx]
+ else:
+ raise ValueError("Invalid aggregation_strategy")
+ new_entity = {
+ "entity": entity,
+ "score": score,
+ "word": word,
+ "start": entities[0]["start"],
+ "end": entities[-1]["end"],
+ }
+ return new_entity
+
+ def aggregate_words(self, entities: list[dict], aggregation_strategy: AggregationStrategy) -> list[dict]:
+ """
+ Override tokens from a given word that disagree to force agreement on word boundaries.
+
+ Example: micro|soft| com|pany| B-ENT I-NAME I-ENT I-ENT will be rewritten with first strategy as microsoft|
+ company| B-ENT I-ENT
+ """
+ if aggregation_strategy in {
+ AggregationStrategy.NONE,
+ AggregationStrategy.SIMPLE,
+ }:
+ raise ValueError("NONE and SIMPLE strategies are invalid for word aggregation")
+
+ word_entities = []
+ word_group = None
+ for entity in entities:
+ if word_group is None:
+ word_group = [entity]
+ elif entity["is_subword"]:
+ word_group.append(entity)
+ else:
+ word_entities.append(self.aggregate_word(word_group, aggregation_strategy))
+ word_group = [entity]
+ # Last item
+ if word_group is not None:
+ word_entities.append(self.aggregate_word(word_group, aggregation_strategy))
+ return word_entities
+
+ def group_sub_entities(self, entities: list[dict]) -> dict:
+ """
+ Group together the adjacent tokens with the same entity predicted.
+
+ Args:
+ entities (`dict`): The entities predicted by the pipeline.
+ """
+ # Get the first entity in the entity group
+ entity = entities[0]["entity"].split("-", 1)[-1]
+ scores = np.nanmean([entity["score"] for entity in entities])
+ tokens = [entity["word"] for entity in entities]
+
+ entity_group = {
+ "entity_group": entity,
+ "score": np.mean(scores),
+ "word": self.tokenizer.convert_tokens_to_string(tokens),
+ "start": entities[0]["start"],
+ "end": entities[-1]["end"],
+ }
+ return entity_group
+
+ def get_tag(self, entity_name: str) -> tuple[str, str]:
+ if entity_name.startswith("B-"):
+ bi = "B"
+ tag = entity_name[2:]
+ elif entity_name.startswith("I-"):
+ bi = "I"
+ tag = entity_name[2:]
+ else:
+ # It's not in B-, I- format
+ # Default to I- for continuation.
+ bi = "I"
+ tag = entity_name
+ return bi, tag
+
+ def group_entities(self, entities: list[dict]) -> list[dict]:
+ """
+ Find and group together the adjacent tokens with the same entity predicted.
+
+ Args:
+ entities (`dict`): The entities predicted by the pipeline.
+ """
+
+ entity_groups = []
+ entity_group_disagg = []
+
+ for entity in entities:
+ if not entity_group_disagg:
+ entity_group_disagg.append(entity)
+ continue
+
+ # If the current entity is similar and adjacent to the previous entity,
+ # append it to the disaggregated entity group
+ # The split is meant to account for the "B" and "I" prefixes
+ # Shouldn't merge if both entities are B-type
+ bi, tag = self.get_tag(entity["entity"])
+ last_bi, last_tag = self.get_tag(entity_group_disagg[-1]["entity"])
+
+ if tag == last_tag and bi != "B":
+ # Modify subword type to be previous_type
+ entity_group_disagg.append(entity)
+ else:
+ # If the current entity is different from the previous entity
+ # aggregate the disaggregated entity group
+ entity_groups.append(self.group_sub_entities(entity_group_disagg))
+ entity_group_disagg = [entity]
+ if entity_group_disagg:
+ # it's the last entity, add it to the entity groups
+ entity_groups.append(self.group_sub_entities(entity_group_disagg))
+
+ return entity_groups
+
+
+NerPipeline = TokenClassificationPipeline
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/video_classification.py b/.venv/lib/python3.12/site-packages/transformers/pipelines/video_classification.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad16b2500a78e458319e37fc0e4eb632798f5e30
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/pipelines/video_classification.py
@@ -0,0 +1,200 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from io import BytesIO
+from typing import Any, overload
+
+import httpx
+
+from ..utils import (
+ add_end_docstrings,
+ is_av_available,
+ is_torch_available,
+ logging,
+ requires_backends,
+)
+from .base import Pipeline, build_pipeline_init_args
+
+
+if is_av_available():
+ import av
+ import numpy as np
+
+
+if is_torch_available():
+ from ..models.auto.modeling_auto import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES
+
+logger = logging.get_logger(__name__)
+
+
+@add_end_docstrings(build_pipeline_init_args(has_image_processor=True, has_video_processor=True))
+class VideoClassificationPipeline(Pipeline):
+ """
+ Video classification pipeline using any `AutoModelForVideoClassification`. This pipeline predicts the class of a
+ video.
+
+ This video classification pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"video-classification"`.
+
+ See the list of available models on
+ [huggingface.co/models](https://huggingface.co/models?filter=video-classification).
+
+ The pipeline supports models that use either an image processor (legacy video models such as VideoMAE, ViViT, and
+ TimeSformer) or a video processor (newer models such as VJEPA2). When both are present the video processor takes
+ precedence; when neither is found the pipeline will raise an error.
+ """
+
+ _load_processor = False
+ _load_image_processor = None
+ _load_video_processor = None
+ _load_feature_extractor = False
+ _load_tokenizer = False
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ requires_backends(self, "av")
+ self.check_model_type(MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES)
+ if self.video_processor is None and self.image_processor is None:
+ raise ValueError(
+ "The video-classification pipeline requires either a video processor or an image processor. "
+ "Neither could be found for the given model."
+ )
+ if self.video_processor is None and self.image_processor is not None:
+ logger.warning_once(
+ "Using `image_processor` for video classification is deprecated and will be removed in a future "
+ "version. Please add a `video_processor` to this model (open a PR if you don't own it)."
+ )
+
+ def _sanitize_parameters(self, top_k=None, num_frames=None, frame_sampling_rate=None, function_to_apply=None):
+ preprocess_params = {}
+ if frame_sampling_rate is not None:
+ preprocess_params["frame_sampling_rate"] = frame_sampling_rate
+ if num_frames is not None:
+ preprocess_params["num_frames"] = num_frames
+
+ postprocess_params = {}
+ if top_k is not None:
+ postprocess_params["top_k"] = top_k
+ if function_to_apply is not None:
+ if function_to_apply not in ["softmax", "sigmoid", "none"]:
+ raise ValueError(
+ f"Invalid value for `function_to_apply`: {function_to_apply}. "
+ "Valid options are ['softmax', 'sigmoid', 'none']"
+ )
+ postprocess_params["function_to_apply"] = function_to_apply
+ else:
+ postprocess_params["function_to_apply"] = "softmax"
+ return preprocess_params, {}, postprocess_params
+
+ @overload
+ def __call__(self, inputs: str, **kwargs: Any) -> list[dict[str, Any]]: ...
+
+ @overload
+ def __call__(self, inputs: list[str], **kwargs: Any) -> list[list[dict[str, Any]]]: ...
+
+ def __call__(self, inputs: str | list[str] | None, **kwargs):
+ """
+ Assign labels to the video(s) passed as inputs.
+
+ Args:
+ inputs (`str`, `list[str]`):
+ The pipeline handles three types of videos:
+
+ - A string containing a http link pointing to a video
+ - A string containing a local path to a video
+
+ The pipeline accepts either a single video or a batch of videos, which must then be passed as a string.
+ Videos in a batch must all be in the same format: all as http links or all as local paths.
+ top_k (`int`, *optional*, defaults to 5):
+ The number of top labels that will be returned by the pipeline. If the provided number is higher than
+ the number of labels available in the model configuration, it will default to the number of labels.
+ num_frames (`int`, *optional*, defaults to `self.model.config.num_frames`):
+ The number of frames sampled from the video to run the classification on. If not provided, will default
+ to the number of frames specified in the model configuration.
+ frame_sampling_rate (`int`, *optional*, defaults to 1):
+ The sampling rate used to select frames from the video. If not provided, will default to 1, i.e. every
+ frame will be used.
+ function_to_apply(`str`, *optional*, defaults to "softmax"):
+ The function to apply to the model output. By default, the pipeline will apply the softmax function to
+ the output of the model. Valid options: ["softmax", "sigmoid", "none"]. Note that passing Python's
+ built-in `None` will default to "softmax", so you need to pass the string "none" to disable any
+ post-processing.
+
+ Return:
+ A list of dictionaries or a list of list of dictionaries containing result. If the input is a single video,
+ will return a list of `top_k` dictionaries, if the input is a list of several videos, will return a list of list of
+ `top_k` dictionaries corresponding to the videos.
+
+ The dictionaries contain the following keys:
+
+ - **label** (`str`) -- The label identified by the model.
+ - **score** (`int`) -- The score attributed by the model for that label.
+ """
+ if inputs is None:
+ raise ValueError("Cannot call the video-classification pipeline without an inputs argument!")
+ return super().__call__(inputs, **kwargs)
+
+ def preprocess(self, video, num_frames=None, frame_sampling_rate=1):
+ if num_frames is None:
+ num_frames = self.model.config.num_frames
+
+ # Decode the video manually because image processors can't decode or sample frames
+ if self.video_processor is None:
+ if video.startswith("http://") or video.startswith("https://"):
+ video = BytesIO(httpx.get(video, follow_redirects=True).content)
+
+ container = av.open(video)
+ start_idx = 0
+ end_idx = num_frames * frame_sampling_rate - 1
+ indices = np.linspace(start_idx, end_idx, num=num_frames, dtype=np.int64)
+
+ video = read_video_pyav(container, indices)
+ video = list(video)
+ model_inputs = self.image_processor(video, return_tensors="pt").to(self.dtype)
+ else:
+ processing_kwargs = {"num_frames": num_frames, "do_sample_frames": True}
+ model_inputs = self.video_processor(video, **processing_kwargs, return_tensors="pt").to(self.dtype)
+ return model_inputs
+
+ def _forward(self, model_inputs):
+ model_outputs = self.model(**model_inputs)
+ return model_outputs
+
+ def postprocess(self, model_outputs, top_k=5, function_to_apply="softmax"):
+ if top_k > self.model.config.num_labels:
+ top_k = self.model.config.num_labels
+
+ if function_to_apply == "softmax":
+ probs = model_outputs.logits[0].softmax(-1)
+ elif function_to_apply == "sigmoid":
+ probs = model_outputs.logits[0].sigmoid()
+ else:
+ probs = model_outputs.logits[0]
+ scores, ids = probs.topk(top_k)
+
+ scores = scores.tolist()
+ ids = ids.tolist()
+ return [{"score": score, "label": self.model.config.id2label[_id]} for score, _id in zip(scores, ids)]
+
+
+def read_video_pyav(container, indices):
+ frames = []
+ container.seek(0)
+ start_index = indices[0]
+ end_index = indices[-1]
+ for i, frame in enumerate(container.decode(video=0)):
+ if i > end_index:
+ break
+ if i >= start_index and i in indices:
+ frames.append(frame)
+ return np.stack([x.to_ndarray(format="rgb24") for x in frames])
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/zero_shot_audio_classification.py b/.venv/lib/python3.12/site-packages/transformers/pipelines/zero_shot_audio_classification.py
new file mode 100644
index 0000000000000000000000000000000000000000..03c1a8d1c1337bce8897451d72337ae9cfac2dc2
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/pipelines/zero_shot_audio_classification.py
@@ -0,0 +1,160 @@
+# Copyright 2023 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from collections import UserDict
+from typing import Any
+
+import httpx
+import numpy as np
+
+from ..utils import (
+ add_end_docstrings,
+ logging,
+)
+from .audio_classification import ffmpeg_read
+from .base import Pipeline, build_pipeline_init_args
+
+
+logger = logging.get_logger(__name__)
+
+
+@add_end_docstrings(build_pipeline_init_args(has_feature_extractor=True, has_tokenizer=True))
+class ZeroShotAudioClassificationPipeline(Pipeline):
+ """
+ Zero shot audio classification pipeline using `ClapModel`. This pipeline predicts the class of an audio when you
+ provide an audio and a set of `candidate_labels`.
+
+
+
+ The default `hypothesis_template` is : `"This is a sound of {}."`. Make sure you update it for your usage.
+
+
+
+ Example:
+ ```python
+ >>> from transformers import pipeline
+ >>> from datasets import load_dataset
+
+ >>> dataset = load_dataset("ashraq/esc50")
+ >>> audio = next(iter(dataset["train"]["audio"]))["array"]
+ >>> classifier = pipeline(task="zero-shot-audio-classification", model="laion/clap-htsat-unfused")
+ >>> classifier(audio, candidate_labels=["Sound of a dog", "Sound of vacuum cleaner"])
+ [{'score': 0.9996, 'label': 'Sound of a dog'}, {'score': 0.0004, 'label': 'Sound of vacuum cleaner'}]
+ ```
+
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) This audio
+ classification pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"zero-shot-audio-classification"`. See the list of available models on
+ [huggingface.co/models](https://huggingface.co/models?filter=zero-shot-audio-classification).
+ """
+
+ _load_processor = False
+ _load_image_processor = False
+ _load_feature_extractor = True
+ _load_tokenizer = True
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+
+ def __call__(self, audios: np.ndarray | bytes | str | dict, **kwargs: Any) -> list[dict[str, Any]]:
+ """
+ Assign labels to the audio(s) passed as inputs.
+
+ Args:
+ audios (`str`, `list[str]`, `np.array` or `list[np.array]`):
+ The pipeline handles three types of inputs:
+ - A string containing a http link pointing to an audio
+ - A string containing a local path to an audio
+ - An audio loaded in numpy
+ candidate_labels (`list[str]`):
+ The candidate labels for this audio. They will be formatted using *hypothesis_template*.
+ hypothesis_template (`str`, *optional*, defaults to `"This is a sound of {}"`):
+ The format used in conjunction with *candidate_labels* to attempt the audio classification by
+ replacing the placeholder with the candidate_labels. Pass "{}" if *candidate_labels* are
+ already formatted.
+ Return:
+ A list of dictionaries containing one entry per proposed label. Each dictionary contains the
+ following keys:
+ - **label** (`str`) -- One of the suggested *candidate_labels*.
+ - **score** (`float`) -- The score attributed by the model to that label. It is a value between
+ 0 and 1, computed as the `softmax` of `logits_per_audio`.
+ """
+ return super().__call__(audios, **kwargs)
+
+ def _sanitize_parameters(self, **kwargs):
+ preprocess_params = {}
+ if "candidate_labels" in kwargs:
+ preprocess_params["candidate_labels"] = kwargs["candidate_labels"]
+ if "hypothesis_template" in kwargs:
+ preprocess_params["hypothesis_template"] = kwargs["hypothesis_template"]
+
+ return preprocess_params, {}, {}
+
+ def preprocess(self, audio, candidate_labels=None, hypothesis_template="This is a sound of {}."):
+ if isinstance(audio, str):
+ if audio.startswith("http://") or audio.startswith("https://"):
+ # We need to actually check for a real protocol, otherwise it's impossible to use a local file
+ # like http_huggingface_co.png
+ audio = httpx.get(audio, follow_redirects=True).content
+ else:
+ with open(audio, "rb") as f:
+ audio = f.read()
+
+ if isinstance(audio, bytes):
+ audio = ffmpeg_read(audio, self.feature_extractor.sampling_rate)
+
+ if not isinstance(audio, np.ndarray):
+ raise TypeError("We expect a numpy ndarray as input")
+ if len(audio.shape) != 1:
+ raise ValueError("We expect a single channel audio input for ZeroShotAudioClassificationPipeline")
+
+ inputs = self.feature_extractor(
+ [audio], sampling_rate=self.feature_extractor.sampling_rate, return_tensors="pt"
+ )
+ inputs = inputs.to(self.dtype)
+ inputs["candidate_labels"] = candidate_labels
+ sequences = [hypothesis_template.format(x) for x in candidate_labels]
+ text_inputs = self.tokenizer(sequences, return_tensors="pt", padding=True)
+ inputs["text_inputs"] = [text_inputs]
+ return inputs
+
+ def _forward(self, model_inputs):
+ candidate_labels = model_inputs.pop("candidate_labels")
+ text_inputs = model_inputs.pop("text_inputs")
+ if isinstance(text_inputs[0], UserDict):
+ text_inputs = text_inputs[0]
+ else:
+ # Batching case.
+ text_inputs = text_inputs[0][0]
+
+ outputs = self.model(**text_inputs, **model_inputs)
+
+ model_outputs = {
+ "candidate_labels": candidate_labels,
+ "logits": outputs.logits_per_audio,
+ }
+ return model_outputs
+
+ def postprocess(self, model_outputs):
+ candidate_labels = model_outputs.pop("candidate_labels")
+ logits = model_outputs["logits"][0]
+
+ probs = logits.softmax(dim=0)
+ scores = probs.tolist()
+
+ result = [
+ {"score": score, "label": candidate_label}
+ for score, candidate_label in sorted(zip(scores, candidate_labels), key=lambda x: -x[0])
+ ]
+ return result
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/zero_shot_classification.py b/.venv/lib/python3.12/site-packages/transformers/pipelines/zero_shot_classification.py
new file mode 100644
index 0000000000000000000000000000000000000000..d88772310de8606235e3e7384476b12723b2c7cd
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/pipelines/zero_shot_classification.py
@@ -0,0 +1,261 @@
+import inspect
+
+import numpy as np
+
+from ..tokenization_python import TruncationStrategy
+from ..utils import add_end_docstrings, logging
+from .base import ArgumentHandler, ChunkPipeline, build_pipeline_init_args
+
+
+logger = logging.get_logger(__name__)
+
+
+class ZeroShotClassificationArgumentHandler(ArgumentHandler):
+ """
+ Handles arguments for zero-shot for text classification by turning each possible label into an NLI
+ premise/hypothesis pair.
+ """
+
+ def _parse_labels(self, labels):
+ if isinstance(labels, str):
+ labels = [label.strip() for label in labels.split(",") if label.strip()]
+ return labels
+
+ def __call__(self, sequences, labels, hypothesis_template):
+ if len(labels) == 0 or len(sequences) == 0:
+ raise ValueError("You must include at least one label and at least one sequence.")
+ if hypothesis_template.format(labels[0]) == hypothesis_template:
+ raise ValueError(
+ f'The provided hypothesis_template "{hypothesis_template}" was not able to be formatted with the target labels. '
+ "Make sure the passed template includes formatting syntax such as {} where the label should go."
+ )
+
+ if isinstance(sequences, str):
+ sequences = [sequences]
+
+ sequence_pairs = []
+ for sequence in sequences:
+ sequence_pairs.extend([[sequence, hypothesis_template.format(label)] for label in labels])
+
+ return sequence_pairs, sequences
+
+
+@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True))
+class ZeroShotClassificationPipeline(ChunkPipeline):
+ """
+ NLI-based zero-shot classification pipeline using a `ModelForSequenceClassification` trained on NLI (natural
+ language inference) tasks. Equivalent of `text-classification` pipelines, but these models don't require a
+ hardcoded number of potential classes, they can be chosen at runtime. It usually means it's slower but it is
+ **much** more flexible.
+
+ Any combination of sequences and labels can be passed and each combination will be posed as a premise/hypothesis
+ pair and passed to the pretrained model. Then, the logit for *entailment* is taken as the logit for the candidate
+ label being valid. Any NLI model can be used, but the id of the *entailment* label must be included in the model
+ config's :attr:*~transformers.PreTrainedConfig.label2id*.
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> oracle = pipeline(model="facebook/bart-large-mnli")
+ >>> oracle(
+ ... "I have a problem with my iphone that needs to be resolved asap!!",
+ ... candidate_labels=["urgent", "not urgent", "phone", "tablet", "computer"],
+ ... )
+ {'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['urgent', 'phone', 'computer', 'not urgent', 'tablet'], 'scores': [0.504, 0.479, 0.013, 0.003, 0.002]}
+
+ >>> oracle(
+ ... "I have a problem with my iphone that needs to be resolved asap!!",
+ ... candidate_labels=["english", "german"],
+ ... )
+ {'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['english', 'german'], 'scores': [0.814, 0.186]}
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This NLI pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"zero-shot-classification"`.
+
+ The models that this pipeline can use are models that have been fine-tuned on an NLI task. See the up-to-date list
+ of available models on [huggingface.co/models](https://huggingface.co/models?search=nli).
+ """
+
+ _load_processor = False
+ _load_image_processor = False
+ _load_feature_extractor = False
+ _load_tokenizer = True
+
+ def __init__(self, args_parser=ZeroShotClassificationArgumentHandler(), **kwargs):
+ self._args_parser = args_parser
+ super().__init__(**kwargs)
+ if self.entailment_id == -1:
+ logger.warning(
+ "Failed to determine 'entailment' label id from the label2id mapping in the model config. Setting to "
+ "-1. Define a descriptive label2id mapping in the model config to ensure correct outputs."
+ )
+
+ @property
+ def entailment_id(self):
+ for label, ind in self.model.config.label2id.items():
+ if label.lower().startswith("entail"):
+ return ind
+ return -1
+
+ def _parse_and_tokenize(
+ self, sequence_pairs, padding=True, add_special_tokens=True, truncation=TruncationStrategy.ONLY_FIRST, **kwargs
+ ):
+ """
+ Parse arguments and tokenize only_first so that hypothesis (label) is not truncated
+ """
+ return_tensors = "pt"
+ if self.tokenizer.pad_token is None:
+ # Override for tokenizers not supporting padding
+ logger.error(
+ "Tokenizer was not supporting padding necessary for zero-shot, attempting to use "
+ " `pad_token=eos_token`"
+ )
+ self.tokenizer.pad_token = self.tokenizer.eos_token
+ try:
+ inputs = self.tokenizer(
+ sequence_pairs,
+ add_special_tokens=add_special_tokens,
+ return_tensors=return_tensors,
+ padding=padding,
+ truncation=truncation,
+ )
+ except Exception as e:
+ if "too short" in str(e):
+ # tokenizers might yell that we want to truncate
+ # to a value that is not even reached by the input.
+ # In that case we don't want to truncate.
+ # It seems there's not a really better way to catch that
+ # exception.
+
+ inputs = self.tokenizer(
+ sequence_pairs,
+ add_special_tokens=add_special_tokens,
+ return_tensors=return_tensors,
+ padding=padding,
+ truncation=TruncationStrategy.DO_NOT_TRUNCATE,
+ )
+ else:
+ raise e
+
+ return inputs
+
+ def _sanitize_parameters(self, **kwargs):
+ preprocess_params = {}
+ if "candidate_labels" in kwargs:
+ preprocess_params["candidate_labels"] = self._args_parser._parse_labels(kwargs["candidate_labels"])
+ if "hypothesis_template" in kwargs:
+ preprocess_params["hypothesis_template"] = kwargs["hypothesis_template"]
+
+ postprocess_params = {}
+ if "multi_label" in kwargs:
+ postprocess_params["multi_label"] = kwargs["multi_label"]
+ return preprocess_params, {}, postprocess_params
+
+ def __call__(
+ self,
+ sequences: str | list[str],
+ *args,
+ **kwargs,
+ ):
+ """
+ Classify the sequence(s) given as inputs. See the [`ZeroShotClassificationPipeline`] documentation for more
+ information.
+
+ Args:
+ sequences (`str` or `list[str]`):
+ The sequence(s) to classify, will be truncated if the model input is too large.
+ candidate_labels (`str` or `list[str]`):
+ The set of possible class labels to classify each sequence into. Can be a single label, a string of
+ comma-separated labels, or a list of labels.
+ hypothesis_template (`str`, *optional*, defaults to `"This example is {}."`):
+ The template used to turn each label into an NLI-style hypothesis. This template must include a {} or
+ similar syntax for the candidate label to be inserted into the template. For example, the default
+ template is `"This example is {}."` With the candidate label `"sports"`, this would be fed into the
+ model like `" sequence to classify This example is sports . "`. The default template
+ works well in many cases, but it may be worthwhile to experiment with different templates depending on
+ the task setting.
+ multi_label (`bool`, *optional*, defaults to `False`):
+ Whether or not multiple candidate labels can be true. If `False`, the scores are normalized such that
+ the sum of the label likelihoods for each sequence is 1. If `True`, the labels are considered
+ independent and probabilities are normalized for each candidate by doing a softmax of the entailment
+ score vs. the contradiction score.
+
+ Return:
+ A `dict` or a list of `dict`: Each result comes as a dictionary with the following keys:
+
+ - **sequence** (`str`) -- The sequence for which this is the output.
+ - **labels** (`list[str]`) -- The labels sorted by order of likelihood.
+ - **scores** (`list[float]`) -- The probabilities for each of the labels.
+ """
+ if len(args) == 0:
+ pass
+ elif len(args) == 1 and "candidate_labels" not in kwargs:
+ kwargs["candidate_labels"] = args[0]
+ else:
+ raise ValueError(f"Unable to understand extra arguments {args}")
+
+ return super().__call__(sequences, **kwargs)
+
+ def preprocess(self, inputs, candidate_labels=None, hypothesis_template="This example is {}."):
+ sequence_pairs, sequences = self._args_parser(inputs, candidate_labels, hypothesis_template)
+
+ for i, (candidate_label, sequence_pair) in enumerate(zip(candidate_labels, sequence_pairs)):
+ model_input = self._parse_and_tokenize([sequence_pair])
+
+ yield {
+ "candidate_label": candidate_label,
+ "sequence": sequences[0],
+ "is_last": i == len(candidate_labels) - 1,
+ **model_input,
+ }
+
+ def _forward(self, inputs):
+ candidate_label = inputs["candidate_label"]
+ sequence = inputs["sequence"]
+ model_inputs = {k: inputs[k] for k in self.tokenizer.model_input_names}
+ # `XXXForSequenceClassification` models should not use `use_cache=True` even if it's supported
+ model_forward = self.model.forward
+ if "use_cache" in inspect.signature(model_forward).parameters:
+ model_inputs["use_cache"] = False
+ outputs = self.model(**model_inputs)
+
+ model_outputs = {
+ "candidate_label": candidate_label,
+ "sequence": sequence,
+ "is_last": inputs["is_last"],
+ **outputs,
+ }
+ return model_outputs
+
+ def postprocess(self, model_outputs, multi_label=False):
+ candidate_labels = [outputs["candidate_label"] for outputs in model_outputs]
+ sequences = [outputs["sequence"] for outputs in model_outputs]
+ logits = np.concatenate([output["logits"].float().numpy() for output in model_outputs])
+ N = logits.shape[0]
+ n = len(candidate_labels)
+ num_sequences = N // n
+ reshaped_outputs = logits.reshape((num_sequences, n, -1))
+
+ if multi_label or len(candidate_labels) == 1:
+ # softmax over the entailment vs. contradiction dim for each label independently
+ entailment_id = self.entailment_id
+ contradiction_id = -1 if entailment_id == 0 else 0
+ entail_contr_logits = reshaped_outputs[..., [contradiction_id, entailment_id]]
+ scores = np.exp(entail_contr_logits) / np.exp(entail_contr_logits).sum(-1, keepdims=True)
+ scores = scores[..., 1]
+ else:
+ # softmax the "entailment" logits over all candidate labels
+ entail_logits = reshaped_outputs[..., self.entailment_id]
+ scores = np.exp(entail_logits) / np.exp(entail_logits).sum(-1, keepdims=True)
+
+ top_inds = list(reversed(scores[0].argsort()))
+ return {
+ "sequence": sequences[0],
+ "labels": [candidate_labels[i] for i in top_inds],
+ "scores": scores[0, top_inds].tolist(),
+ }
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/zero_shot_image_classification.py b/.venv/lib/python3.12/site-packages/transformers/pipelines/zero_shot_image_classification.py
new file mode 100644
index 0000000000000000000000000000000000000000..d129c5836538904b2259e14e23e25267f529165c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/pipelines/zero_shot_image_classification.py
@@ -0,0 +1,195 @@
+from collections import UserDict
+from typing import Any, Union, overload
+
+from ..utils import (
+ add_end_docstrings,
+ is_torch_available,
+ is_vision_available,
+ logging,
+ requires_backends,
+)
+from .base import Pipeline, build_pipeline_init_args
+
+
+if is_vision_available():
+ from PIL import Image
+
+ from ..image_utils import load_image
+
+if is_torch_available():
+ import torch
+
+ from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES
+
+
+logger = logging.get_logger(__name__)
+
+
+@add_end_docstrings(build_pipeline_init_args(has_image_processor=True))
+class ZeroShotImageClassificationPipeline(Pipeline):
+ """
+ Zero shot image classification pipeline using `CLIPModel`. This pipeline predicts the class of an image when you
+ provide an image and a set of `candidate_labels`.
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> classifier = pipeline(model="google/siglip-so400m-patch14-384")
+ >>> classifier(
+ ... "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png",
+ ... candidate_labels=["animals", "humans", "landscape"],
+ ... )
+ [{'score': 0.965, 'label': 'animals'}, {'score': 0.03, 'label': 'humans'}, {'score': 0.005, 'label': 'landscape'}]
+
+ >>> classifier(
+ ... "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png",
+ ... candidate_labels=["black and white", "photorealist", "painting"],
+ ... )
+ [{'score': 0.996, 'label': 'black and white'}, {'score': 0.003, 'label': 'photorealist'}, {'score': 0.0, 'label': 'painting'}]
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This image classification pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"zero-shot-image-classification"`.
+
+ See the list of available models on
+ [huggingface.co/models](https://huggingface.co/models?filter=zero-shot-image-classification).
+ """
+
+ _load_processor = False
+ _load_image_processor = True
+ _load_feature_extractor = False
+ _load_tokenizer = True
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+
+ requires_backends(self, "vision")
+ self.check_model_type(MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES)
+
+ @overload
+ def __call__(
+ self, image: Union[str, "Image.Image"], candidate_labels: list[str], **kwargs: Any
+ ) -> list[dict[str, Any]]: ...
+
+ @overload
+ def __call__(
+ self, image: list[str] | list["Image.Image"], candidate_labels: list[str], **kwargs: Any
+ ) -> list[list[dict[str, Any]]]: ...
+
+ def __call__(
+ self,
+ image: Union[str, list[str], "Image.Image", list["Image.Image"]],
+ candidate_labels: list[str],
+ **kwargs: Any,
+ ) -> list[dict[str, Any]] | list[list[dict[str, Any]]]:
+ """
+ Assign labels to the image(s) passed as inputs.
+
+ Args:
+ image (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`):
+ The pipeline handles three types of images:
+
+ - A string containing a http link pointing to an image
+ - A string containing a local path to an image
+ - An image loaded in PIL directly
+
+ candidate_labels (`list[str]`):
+ The candidate labels for this image. They will be formatted using *hypothesis_template*.
+
+ hypothesis_template (`str`, *optional*, defaults to `"This is a photo of {}"`):
+ The format used in conjunction with *candidate_labels* to attempt the image classification by
+ replacing the placeholder with the candidate_labels. Pass "{}" if *candidate_labels* are
+ already formatted.
+
+ timeout (`float`, *optional*, defaults to None):
+ The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
+ the call may block forever.
+
+ Return:
+ A list of dictionaries containing one entry per proposed label. Each dictionary contains the
+ following keys:
+ - **label** (`str`) -- One of the suggested *candidate_labels*.
+ - **score** (`float`) -- The score attributed by the model to that label. It is a value between
+ 0 and 1, computed as the `softmax` of `logits_per_image`.
+ """
+ # After deprecation of this is completed, remove the default `None` value for `image`
+ if "images" in kwargs:
+ image = kwargs.pop("images")
+ if image is None:
+ raise ValueError("Cannot call the zero-shot-image-classification pipeline without an images argument!")
+ return super().__call__(image, candidate_labels=candidate_labels, **kwargs)
+
+ def _sanitize_parameters(self, tokenizer_kwargs=None, **kwargs):
+ preprocess_params = {}
+ if "candidate_labels" in kwargs:
+ preprocess_params["candidate_labels"] = kwargs["candidate_labels"]
+ if "timeout" in kwargs:
+ preprocess_params["timeout"] = kwargs["timeout"]
+ if "hypothesis_template" in kwargs:
+ preprocess_params["hypothesis_template"] = kwargs["hypothesis_template"]
+
+ return preprocess_params, {}, {}
+
+ def preprocess(
+ self,
+ image,
+ candidate_labels=None,
+ hypothesis_template="This is a photo of {}.",
+ timeout=None,
+ tokenizer_kwargs=None,
+ ):
+ if tokenizer_kwargs is None:
+ tokenizer_kwargs = {}
+ image = load_image(image, timeout=timeout)
+ inputs = self.image_processor(images=[image], return_tensors="pt")
+ inputs = inputs.to(self.dtype)
+ inputs["candidate_labels"] = candidate_labels
+ sequences = [hypothesis_template.format(x) for x in candidate_labels]
+ tokenizer_default_kwargs = {"padding": True}
+ if "siglip" in self.model.config.model_type:
+ tokenizer_default_kwargs.update(padding="max_length", max_length=64, truncation=True)
+ tokenizer_default_kwargs.update(tokenizer_kwargs)
+ text_inputs = self.tokenizer(sequences, return_tensors="pt", **tokenizer_default_kwargs)
+ inputs["text_inputs"] = [text_inputs]
+ return inputs
+
+ def _forward(self, model_inputs):
+ candidate_labels = model_inputs.pop("candidate_labels")
+ text_inputs = model_inputs.pop("text_inputs")
+ if isinstance(text_inputs[0], UserDict):
+ text_inputs = text_inputs[0]
+ else:
+ # Batching case.
+ text_inputs = text_inputs[0][0]
+
+ outputs = self.model(**text_inputs, **model_inputs)
+
+ model_outputs = {
+ "candidate_labels": candidate_labels,
+ "logits": outputs.logits_per_image,
+ }
+ return model_outputs
+
+ def postprocess(self, model_outputs):
+ candidate_labels = model_outputs.pop("candidate_labels")
+ logits = model_outputs["logits"][0]
+ if "siglip" in self.model.config.model_type:
+ probs = torch.sigmoid(logits).squeeze(-1)
+ scores = probs.tolist()
+ if not isinstance(scores, list):
+ scores = [scores]
+ else:
+ probs = logits.softmax(dim=-1).squeeze(-1)
+ scores = probs.tolist()
+ if not isinstance(scores, list):
+ scores = [scores]
+
+ result = [
+ {"score": score, "label": candidate_label}
+ for score, candidate_label in sorted(zip(scores, candidate_labels), key=lambda x: -x[0])
+ ]
+ return result
diff --git a/.venv/lib/python3.12/site-packages/transformers/pipelines/zero_shot_object_detection.py b/.venv/lib/python3.12/site-packages/transformers/pipelines/zero_shot_object_detection.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f353afd7499e100353bd450293fd174183a0e13
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/pipelines/zero_shot_object_detection.py
@@ -0,0 +1,242 @@
+from typing import Any, Union, overload
+
+from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends
+from .base import ChunkPipeline, build_pipeline_init_args
+
+
+if is_vision_available():
+ from PIL import Image
+
+ from ..image_utils import load_image, valid_images
+
+if is_torch_available():
+ import torch
+
+ from transformers.modeling_outputs import BaseModelOutput
+
+ from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES
+
+logger = logging.get_logger(__name__)
+
+
+@add_end_docstrings(build_pipeline_init_args(has_image_processor=True))
+class ZeroShotObjectDetectionPipeline(ChunkPipeline):
+ """
+ Zero shot object detection pipeline using `OwlViTForObjectDetection`. This pipeline predicts bounding boxes of
+ objects when you provide an image and a set of `candidate_labels`.
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> detector = pipeline(model="google/owlvit-base-patch32", task="zero-shot-object-detection")
+ >>> detector(
+ ... "http://images.cocodataset.org/val2017/000000039769.jpg",
+ ... candidate_labels=["cat", "couch"],
+ ... )
+ [{'score': 0.287, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.254, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.121, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}]
+
+ >>> detector(
+ ... "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png",
+ ... candidate_labels=["head", "bird"],
+ ... )
+ [{'score': 0.119, 'label': 'bird', 'box': {'xmin': 71, 'ymin': 170, 'xmax': 410, 'ymax': 508}}]
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This object detection pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"zero-shot-object-detection"`.
+
+ See the list of available models on
+ [huggingface.co/models](https://huggingface.co/models?filter=zero-shot-object-detection).
+ """
+
+ _load_processor = False
+ _load_image_processor = True
+ _load_feature_extractor = False
+ _load_tokenizer = True
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+
+ requires_backends(self, "vision")
+ self.check_model_type(MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES)
+
+ @overload
+ def __call__(
+ self, image: Union[str, "Image.Image"], candidate_labels: str | list[str], **kwargs: Any
+ ) -> list[dict[str, Any]]: ...
+
+ @overload
+ def __call__(self, image: list[dict[str, Any]], **kwargs: Any) -> list[list[dict[str, Any]]]: ...
+
+ def __call__(
+ self,
+ image: Union[str, "Image.Image", list[dict[str, Any]]],
+ candidate_labels: str | list[str] | None = None,
+ **kwargs: Any,
+ ) -> list[dict[str, Any]] | list[list[dict[str, Any]]]:
+ """
+ Detect objects (bounding boxes & classes) in the image(s) passed as inputs.
+
+ Args:
+ image (`str`, `PIL.Image` or `list[dict[str, Any]]`):
+ The pipeline handles three types of images:
+
+ - A string containing an http url pointing to an image
+ - A string containing a local path to an image
+ - An image loaded in PIL directly
+
+ You can use this parameter to send directly a list of images, or a dataset or a generator like so:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> detector = pipeline(model="google/owlvit-base-patch32", task="zero-shot-object-detection")
+ >>> detector(
+ ... [
+ ... {
+ ... "image": "http://images.cocodataset.org/val2017/000000039769.jpg",
+ ... "candidate_labels": ["cat", "couch"],
+ ... },
+ ... {
+ ... "image": "http://images.cocodataset.org/val2017/000000039769.jpg",
+ ... "candidate_labels": ["cat", "couch"],
+ ... },
+ ... ]
+ ... )
+ [[{'score': 0.287, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.25, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.121, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}], [{'score': 0.287, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.254, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.121, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}]]
+ ```
+
+
+ candidate_labels (`str` or `list[str]` or `list[list[str]]`):
+ What the model should recognize in the image.
+
+ threshold (`float`, *optional*, defaults to 0.1):
+ The probability necessary to make a prediction.
+
+ top_k (`int`, *optional*, defaults to None):
+ The number of top predictions that will be returned by the pipeline. If the provided number is `None`
+ or higher than the number of predictions available, it will default to the number of predictions.
+
+ timeout (`float`, *optional*, defaults to None):
+ The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
+ the call may block forever.
+
+
+ Return:
+ A list of lists containing prediction results, one list per input image. Each list contains dictionaries
+ with the following keys:
+
+ - **label** (`str`) -- Text query corresponding to the found object.
+ - **score** (`float`) -- Score corresponding to the object (between 0 and 1).
+ - **box** (`dict[str,int]`) -- Bounding box of the detected object in image's original size. It is a
+ dictionary with `x_min`, `x_max`, `y_min`, `y_max` keys.
+ """
+ if "text_queries" in kwargs:
+ candidate_labels = kwargs.pop("text_queries")
+
+ if isinstance(image, (str, Image.Image)):
+ inputs = {"image": image, "candidate_labels": candidate_labels}
+ elif isinstance(image, (list, tuple)) and valid_images(image):
+ return list(
+ super().__call__(
+ ({"image": img, "candidate_labels": labels} for img, labels in zip(image, candidate_labels)),
+ **kwargs,
+ )
+ )
+ else:
+ """
+ Supports the following format
+ - {"image": image, "candidate_labels": candidate_labels}
+ - [{"image": image, "candidate_labels": candidate_labels}]
+ - Generator and datasets
+ This is a common pattern in other multimodal pipelines, so we support it here as well.
+ """
+ inputs = image
+
+ results = super().__call__(inputs, **kwargs)
+ return results
+
+ def _sanitize_parameters(self, **kwargs):
+ preprocess_params = {}
+ if "timeout" in kwargs:
+ preprocess_params["timeout"] = kwargs["timeout"]
+ postprocess_params = {}
+ if "threshold" in kwargs:
+ postprocess_params["threshold"] = kwargs["threshold"]
+ if "top_k" in kwargs:
+ postprocess_params["top_k"] = kwargs["top_k"]
+ return preprocess_params, {}, postprocess_params
+
+ def preprocess(self, inputs, timeout=None):
+ image = load_image(inputs["image"], timeout=timeout)
+ candidate_labels = inputs["candidate_labels"]
+ if isinstance(candidate_labels, str):
+ candidate_labels = candidate_labels.split(",")
+
+ target_size = torch.tensor([[image.height, image.width]], dtype=torch.int32)
+ for i, candidate_label in enumerate(candidate_labels):
+ text_inputs = self.tokenizer(candidate_label, return_tensors="pt")
+ image_features = self.image_processor(image, return_tensors="pt")
+ image_features = image_features.to(self.dtype)
+ yield {
+ "is_last": i == len(candidate_labels) - 1,
+ "target_size": target_size,
+ "candidate_label": candidate_label,
+ **text_inputs,
+ **image_features,
+ }
+
+ def _forward(self, model_inputs):
+ target_size = model_inputs.pop("target_size")
+ candidate_label = model_inputs.pop("candidate_label")
+ is_last = model_inputs.pop("is_last")
+
+ outputs = self.model(**model_inputs)
+
+ model_outputs = {"target_size": target_size, "candidate_label": candidate_label, "is_last": is_last, **outputs}
+ return model_outputs
+
+ def postprocess(self, model_outputs, threshold=0.1, top_k=None):
+ results = []
+ for model_output in model_outputs:
+ label = model_output["candidate_label"]
+ model_output = BaseModelOutput(model_output)
+ outputs = self.image_processor.post_process_object_detection(
+ outputs=model_output, threshold=threshold, target_sizes=model_output["target_size"]
+ )[0]
+
+ for index in outputs["scores"].nonzero():
+ score = outputs["scores"][index].item()
+ box = self._get_bounding_box(outputs["boxes"][index][0])
+
+ result = {"score": score, "label": label, "box": box}
+ results.append(result)
+
+ results = sorted(results, key=lambda x: x["score"], reverse=True)
+ if top_k:
+ results = results[:top_k]
+
+ return results
+
+ def _get_bounding_box(self, box: "torch.Tensor") -> dict[str, int]:
+ """
+ Turns list [xmin, xmax, ymin, ymax] into dict { "xmin": xmin, ... }
+
+ Args:
+ box (`torch.Tensor`): Tensor containing the coordinates in corners format.
+
+ Returns:
+ bbox (`dict[str, int]`): Dict containing the coordinates in corners format.
+ """
+ xmin, ymin, xmax, ymax = box.int().tolist()
+ bbox = {
+ "xmin": xmin,
+ "ymin": ymin,
+ "xmax": xmax,
+ "ymax": ymax,
+ }
+ return bbox
diff --git a/.venv/lib/python3.12/site-packages/transformers/processing_utils.py b/.venv/lib/python3.12/site-packages/transformers/processing_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..e4dbc1c8462c80b057d6608e88d0ba510a41b16a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/transformers/processing_utils.py
@@ -0,0 +1,2309 @@
+# Copyright 2022 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Processing saving/loading class for common processors.
+"""
+
+import bisect
+import copy
+import functools
+import inspect
+import json
+import os
+import re
+import sys
+import typing
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Annotated, Any, Literal, TypedDict, TypeVar, Union
+
+import numpy as np
+import typing_extensions
+from huggingface_hub import is_offline_mode
+from huggingface_hub.dataclasses import validate_typed_dict
+from huggingface_hub.errors import EntryNotFoundError
+
+from .audio_utils import AudioInput, load_audio, make_list_of_audio
+from .dynamic_module_utils import custom_object_save
+from .feature_extraction_utils import BatchFeature
+from .image_utils import ChannelDimension, ImageInput, is_vision_available, make_flat_list_of_images
+from .tokenization_utils_base import (
+ PaddingStrategy,
+ PreTokenizedInput,
+ PreTrainedTokenizerBase,
+ TextInput,
+ TruncationStrategy,
+)
+from .utils import (
+ AUDIO_TOKENIZER_NAME,
+ CHAT_TEMPLATE_DIR,
+ CHAT_TEMPLATE_FILE,
+ LEGACY_PROCESSOR_CHAT_TEMPLATE_FILE,
+ PROCESSOR_NAME,
+ PushToHubMixin,
+ TensorType,
+ auto_docstring,
+ cached_file,
+ copy_func,
+ direct_transformers_import,
+ hf_api,
+ is_torch_available,
+ list_repo_templates,
+ logging,
+)
+from .utils.chat_template_utils import _get_template_variables, render_jinja_template
+from .utils.type_validators import (
+ device_validator,
+ image_size_validator,
+ padding_validator,
+ positive_any_number,
+ positive_int,
+ resampling_validator,
+ tensor_type_validator,
+ truncation_validator,
+ video_metadata_validator,
+)
+from .video_utils import VideoInput, VideoMetadataType, make_batched_videos
+
+
+if is_torch_available():
+ import torch
+
+ from .modeling_utils import PreTrainedAudioTokenizerBase
+
+if is_vision_available():
+ from .image_utils import PILImageResampling
+
+logger = logging.get_logger(__name__)
+
+# type hinting: specifying the type of processor class that inherits from ProcessorMixin
+SpecificProcessorType = TypeVar("SpecificProcessorType", bound="ProcessorMixin")
+
+# Dynamically import the Transformers module to grab the attribute classes of the processor from their names.
+transformers_module = direct_transformers_import(Path(__file__).parent)
+
+
+class _LazyAutoProcessorMapping(dict):
+ """
+ Lazy dictionary to avoid circular imports.
+ The mapping names are only imported when accessed.
+ """
+
+ _MAPPING_NAMES = {
+ "image_processor": ("transformers.models.auto.image_processing_auto", "AutoImageProcessor"),
+ "video_processor": ("transformers.models.auto.video_processing_auto", "AutoVideoProcessor"),
+ "feature_extractor": ("transformers.models.auto.feature_extraction_auto", "AutoFeatureExtractor"),
+ "audio_processor": ("transformers.models.auto.feature_extraction_auto", "AutoFeatureExtractor"),
+ "tokenizer": ("transformers.models.auto.tokenization_auto", "AutoTokenizer"),
+ }
+
+ def __getitem__(self, key):
+ if key not in self._MAPPING_NAMES:
+ raise KeyError(key)
+ module_name, attr_name = self._MAPPING_NAMES[key]
+ module = __import__(module_name, fromlist=[attr_name])
+ return getattr(module, attr_name)
+
+ def __contains__(self, key):
+ return key in self._MAPPING_NAMES
+
+ def keys(self):
+ return self._MAPPING_NAMES.keys()
+
+
+MODALITY_TO_AUTOPROCESSOR_MAPPING = _LazyAutoProcessorMapping()
+
+MODALITY_TO_BASE_CLASS_MAPPING = {
+ "audio_tokenizer": (
+ "HiggsAudioV2TokenizerModel",
+ "DacModel",
+ ), # TODO: @eustlb, to be replaced with PreTrainedAudioTokenizerBase
+ "audio_processor": "FeatureExtractionMixin",
+ "tokenizer": ("PreTrainedTokenizerBase", "MistralCommonBackend"),
+ "feature_extractor": "FeatureExtractionMixin",
+ "image_processor": "ImageProcessingMixin",
+ "video_processor": "BaseVideoProcessor",
+}
+
+
+def _get_modality_for_attribute(attribute_name: str) -> str:
+ """
+ Get the canonical modality type for a given attribute name.
+
+ For example:
+ - "image_processor" -> "image_processor"
+ - "encoder_image_processor" -> "image_processor"
+ - "text_tokenizer" -> "tokenizer"
+ - "my_feature_extractor" -> "feature_extractor"
+ """
+ for modality in MODALITY_TO_AUTOPROCESSOR_MAPPING.keys():
+ if modality in attribute_name:
+ return modality
+ raise ValueError(
+ f"Cannot determine modality for attribute '{attribute_name}'. "
+ f"Attribute name must contain one of: {list(MODALITY_TO_AUTOPROCESSOR_MAPPING.keys())}"
+ )
+
+
+if sys.version_info >= (3, 11):
+ Unpack = typing.Unpack
+else:
+ Unpack = typing_extensions.Unpack
+
+
+class TextKwargs(TypedDict, total=False):
+ """
+ Keyword arguments for text processing. For extended documentation, check out tokenization_utils_base methods and
+ docstrings associated.
+
+ Attributes:
+ add_special_tokens (`bool`, *optional*)
+ Whether or not to add special tokens when encoding the sequences.
+ padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*)
+ Activates and controls padding.
+ truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*):
+ Activates and controls truncation.
+ max_length (`int`, *optional*):
+ Controls the maximum length to use by one of the truncation/padding parameters.
+ stride (`int`, *optional*):
+ If set, the overflowing tokens will contain some tokens from the end of the truncated sequence.
+ is_split_into_words (`bool`, *optional*):
+ Whether or not the input is already pre-tokenized.
+ pad_to_multiple_of (`int`, *optional*):
+ If set, will pad the sequence to a multiple of the provided value.
+ return_token_type_ids (`bool`, *optional*):
+ Whether to return token type IDs.
+ return_attention_mask (`bool`, *optional*):
+ Whether to return the attention mask.
+ return_overflowing_tokens (`bool`, *optional*):
+ Whether or not to return overflowing token sequences.
+ return_special_tokens_mask (`bool`, *optional*):
+ Whether or not to return special tokens mask information.
+ return_offsets_mapping (`bool`, *optional*):
+ Whether or not to return `(char_start, char_end)` for each token.
+ return_length (`bool`, *optional*):
+ Whether or not to return the lengths of the encoded inputs.
+ verbose (`bool`, *optional*):
+ Whether or not to print more information and warnings.
+ padding_side (`str`, *optional*):
+ The side on which padding will be applied.
+ return_mm_token_type_ids (`bool`, *optional*):
+ Whether to return multimodal token type ids indicating mm placeholder token positions.
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
+ If set, will return tensors of a particular framework. Acceptable values are:
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
+ - `'np'`: Return NumPy `np.ndarray` objects.
+ """
+
+ text_pair: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None
+ text_target: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None
+ text_pair_target: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None
+ add_special_tokens: bool | None
+ padding: Annotated[bool | str | PaddingStrategy | None, padding_validator()]
+ truncation: Annotated[bool | str | TruncationStrategy | None, truncation_validator()]
+ max_length: Annotated[int | None, positive_int()]
+ stride: Annotated[int | None, positive_int()]
+ is_split_into_words: bool | None
+ pad_to_multiple_of: Annotated[int | None, positive_int()]
+ return_token_type_ids: bool | None
+ return_attention_mask: bool | None
+ return_overflowing_tokens: bool | None
+ return_special_tokens_mask: bool | None
+ return_offsets_mapping: bool | None
+ return_length: bool | None
+ verbose: bool | None
+ padding_side: Literal["left", "right"] | None
+ return_mm_token_type_ids: bool | None
+ return_tensors: Annotated[str | TensorType | None, tensor_type_validator()]
+
+
+class ImagesKwargs(TypedDict, total=False):
+ """
+ Keyword arguments for image processing. For extended documentation, check the appropriate ImageProcessor
+ class methods and docstrings.
+
+ Attributes:
+ do_convert_rgb (`bool`):
+ Whether to convert the image to RGB format.
+ do_resize (`bool`, *optional*):
+ Whether to resize the image.
+ size (`dict[str, int]`, *optional*):
+ Resize the shorter side of the input to `size["shortest_edge"]`.
+ default_to_square (`bool`, *optional*, defaults to `self.default_to_square`):
+ Whether to default to a square when resizing, if size is an int.
+ crop_size (`dict[str, int]`, *optional*):
+ Desired output size when applying center-cropping.
+ resample (`PILImageResampling`, *optional*):
+ Resampling filter to use if resizing the image.
+ do_rescale (`bool`, *optional*):
+ Whether to rescale the image by the specified scale `rescale_factor`.
+ rescale_factor (`int` or `float`, *optional*):
+ Scale factor to use if rescaling the image.
+ do_normalize (`bool`, *optional*):
+ Whether to normalize the image.
+ image_mean (`float` or `list[float] or tuple[float, float, float]`, *optional*):
+ Mean to use if normalizing the image.
+ image_std (`float` or `list[float] or tuple[float, float, float]`, *optional*):
+ Standard deviation to use if normalizing the image.
+ do_pad (`bool`, *optional*):
+ Whether to pad the images in the batch.
+ pad_size (`dict[str, int]`, *optional*):
+ The size `{"height": int, "width" int}` to pad the images to.
+ do_center_crop (`bool`, *optional*):
+ Whether to center crop the image.
+ data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format for the output image.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format for the input image.
+ device (`Union[str, torch.Tensor]`, *optional*):
+ The device to use for processing (e.g. "cpu", "cuda"), only relevant for torchvision backend.
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
+ If set, will return tensors of a particular framework. Acceptable values are:
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
+ - `'np'`: Return NumPy `np.ndarray` objects.
+ disable_grouping (`bool`, *optional*):
+ Whether to group images by shapes when processing or not, only relevant for torchvision backend.
+ image_seq_length (`int`, *optional*):
+ The number of image tokens to be used for each image in the input.
+ Added for backward compatibility but this should be set as a processor attribute in future models.
+ """
+
+ do_convert_rgb: bool | None
+ do_resize: bool | None
+ size: Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, image_size_validator()]
+ default_to_square: bool | None
+ crop_size: Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, image_size_validator()]
+ resample: Annotated[Union["PILImageResampling", int] | None, resampling_validator()]
+ do_rescale: bool | None
+ rescale_factor: float | None
+ do_normalize: bool | None
+ image_mean: float | list[float] | tuple[float, ...] | None
+ image_std: float | list[float] | tuple[float, ...] | None
+ do_pad: bool | None
+ pad_size: Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, image_size_validator()]
+ do_center_crop: bool | None
+ data_format: str | ChannelDimension | None
+ input_data_format: str | ChannelDimension | None
+ device: Annotated[Union[str, "torch.device"] | None, device_validator()]
+ return_tensors: Annotated[str | TensorType | None, tensor_type_validator()]
+ disable_grouping: bool | None
+ image_seq_length: int | None
+
+
+class VideosKwargs(TypedDict, total=False):
+ """
+ Keyword arguments for video processing.
+
+ Attributes:
+ do_convert_rgb (`bool`):
+ Whether to convert the video to RGB format.
+ do_resize (`bool`):
+ Whether to resize the video.
+ size (`dict[str, int]`, *optional*):
+ Resize the shorter side of the input to `size["shortest_edge"]`.
+ default_to_square (`bool`, *optional*, defaults to `self.default_to_square`):
+ Whether to default to a square when resizing, if size is an int.
+ resample (`PILImageResampling`, *optional*):
+ Resampling filter to use if resizing the video.
+ do_rescale (`bool`, *optional*):
+ Whether to rescale the video by the specified scale `rescale_factor`.
+ rescale_factor (`int` or `float`, *optional*):
+ Scale factor to use if rescaling the video.
+ do_normalize (`bool`, *optional*):
+ Whether to normalize the video.
+ image_mean (`float` or `list[float] or tuple[float, float, float]`, *optional*):
+ Mean to use if normalizing the video.
+ image_std (`float` or `list[float] or tuple[float, float, float]`, *optional*):
+ Standard deviation to use if normalizing the video.
+ do_center_crop (`bool`, *optional*):
+ Whether to center crop the video.
+ do_pad (`bool`, *optional*):
+ Whether to pad the images in the batch.
+ do_sample_frames (`bool`, *optional*):
+ Whether to sample frames from the video before processing or to process the whole video.
+ video_metadata (`Union[VideoMetadata, dict]`, *optional*):
+ Metadata of the video containing information about total duration, fps and total number of frames.
+ num_frames (`int`, *optional*):
+ Maximum number of frames to sample when `do_sample_frames=True`.
+ fps (`int` or `float`, *optional*):
+ Target frames to sample per second when `do_sample_frames=True`.
+ crop_size (`dict[str, int]`, *optional*):
+ Desired output size when applying center-cropping.
+ data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format for the output video.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format for the input video.
+ device (`Union[str, torch.Tensor]`, *optional*):
+ The device to use for processing (e.g. "cpu", "cuda"), only relevant for fast image processing.
+ return_metadata (`bool`, *optional*):
+ Whether to return video metadata or not.
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
+ If set, will return tensors of a particular framework. Acceptable values are:
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
+ - `'np'`: Return NumPy `np.ndarray` objects.
+ """
+
+ do_convert_rgb: bool | None
+ do_resize: bool | None
+ size: Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, image_size_validator()]
+ default_to_square: bool | None
+ resample: Annotated[Union["PILImageResampling", int] | None, resampling_validator()]
+ do_rescale: bool | None
+ rescale_factor: float | None
+ do_normalize: bool | None
+ image_mean: float | list[float] | tuple[float, ...] | None
+ image_std: float | list[float] | tuple[float, ...] | None
+ do_center_crop: bool | None
+ do_pad: bool | None
+ crop_size: Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, image_size_validator()]
+ data_format: str | ChannelDimension | None
+ input_data_format: str | ChannelDimension | None
+ device: Annotated[Union[str, "torch.device"] | None, device_validator()]
+ do_sample_frames: bool | None
+ video_metadata: Annotated[VideoMetadataType | None, video_metadata_validator()]
+ fps: Annotated[int | float | None, positive_any_number()]
+ num_frames: Annotated[int | None, positive_int()]
+ return_metadata: bool | None
+ return_tensors: Annotated[str | TensorType | None, tensor_type_validator()]
+
+
+class AudioKwargs(TypedDict, total=False):
+ """
+ Keyword arguments for audio processing.
+
+ Attributes:
+ sampling_rate (`int`, *optional*):
+ The sampling rate at which the `raw_speech` input was sampled.
+ raw_speech (`np.ndarray`, `list[float]`, `list[np.ndarray]`, `list[list[float]]`):
+ The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float
+ values, a list of numpy arrays or a list of list of float values. Must be mono channel audio, not
+ stereo, i.e. single float per timestep.
+ padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*):
+ Select a strategy to pad the returned sequences (according to the model's padding side and padding
+ index) among:
+
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
+ sequence if provided).
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
+ acceptable input length for the model if that argument is not provided.
+ - `False` or `'do_not_pad'`
+ max_length (`int`, *optional*):
+ Maximum length of the returned list and optionally padding length (see above).
+ truncation (`bool`, *optional*):
+ Activates truncation to cut input sequences longer than *max_length* to *max_length*.
+ pad_to_multiple_of (`int`, *optional*):
+ If set, will pad the sequence to a multiple of the provided value.
+ return_attention_mask (`bool`, *optional*):
+ Whether or not [`~ASTFeatureExtractor.__call__`] should return `attention_mask`.
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
+ If set, will return tensors of a particular framework. Acceptable values are:
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
+ - `'np'`: Return NumPy `np.ndarray` objects.
+ """
+
+ sampling_rate: Annotated[int | None, positive_int()]
+ raw_speech: Union["np.ndarray", list[float], list["np.ndarray"], list[list[float]]] | None
+ padding: Annotated[bool | str | PaddingStrategy | None, padding_validator()]
+ max_length: Annotated[int | None, positive_int()]
+ truncation: Annotated[bool | str | TruncationStrategy | None, truncation_validator()]
+ pad_to_multiple_of: Annotated[int | None, positive_int()]
+ return_attention_mask: bool | None
+ return_tensors: Annotated[str | TensorType | None, tensor_type_validator()]
+
+
+class ProcessingKwargs(TypedDict, total=False):
+ """
+ Base class for kwargs passing to processors.
+ In case a model has specific kwargs that are not present in the base class or default values for existing keys,
+ it should have its own `ModelProcessorKwargs` class that inherits from `ProcessingKwargs` to provide:
+ 1) Additional typed keys and that this model requires to process inputs.
+ 2) Default values for existing keys under a `_defaults` attribute.
+ New keys have to be defined as follows to ensure type hinting is done correctly.
+
+ ```python
+ # adding a new image kwarg for this model
+ class ModelImagesKwargs(ImagesKwargs, total=False):
+ new_image_kwarg: Optional[bool]
+
+ class ModelProcessorKwargs(ProcessingKwargs, total=False):
+ images_kwargs: ModelImagesKwargs
+ _defaults = {
+ "images_kwargs: {
+ "new_image_kwarg": False,
+ }
+ "text_kwargs": {
+ "padding": "max_length",
+ },
+ }
+
+ ```
+
+ For Python 3.8 compatibility, when inheriting from this class and overriding one of the kwargs,
+ you need to manually update the __annotations__ dictionary. This can be done as follows:
+
+ ```python
+ class CustomProcessorKwargs(ProcessingKwargs, total=False):
+ images_kwargs: CustomImagesKwargs
+
+ CustomProcessorKwargs.__annotations__["images_kwargs"] = CustomImagesKwargs # python 3.8 compatibility
+ ```
+
+ """
+
+ _defaults = {}
+
+ text_kwargs: TextKwargs = {
+ **TextKwargs.__annotations__,
+ }
+ images_kwargs: ImagesKwargs = {
+ **ImagesKwargs.__annotations__,
+ }
+ videos_kwargs: VideosKwargs = {
+ **VideosKwargs.__annotations__,
+ }
+ audio_kwargs: AudioKwargs = {
+ **AudioKwargs.__annotations__,
+ }
+
+
+class TokenizerChatTemplateKwargs(TypedDict, total=False):
+ """
+ NOTE: `TokenizerChatTemplateKwargs` is deprecated and will be removed in future versions
+ Keyword arguments for tokenizer's `apply_chat_template`, when it is called from within a processor.
+
+ tools (`list[Dict]`, *optional*):
+ A list of tools (callable functions) that will be accessible to the model. If the template does not
+ support function calling, this argument will have no effect. Each tool should be passed as a JSON Schema,
+ giving the name, description and argument types for the tool. See our
+ [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#automated-function-conversion-for-tool-use)
+ for more information.
+ documents (`list[dict[str, str]]`, *optional*):
+ A list of dicts representing documents that will be accessible to the model if it is performing RAG
+ (retrieval-augmented generation). If the template does not support RAG, this argument will have no
+ effect. We recommend that each document should be a dict containing "title" and "text" keys. Please
+ see the RAG section of the [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#arguments-for-RAG)
+ for examples of passing documents with chat templates.
+ add_generation_prompt (bool, *optional*):
+ If this is set, a prompt with the token(s) that indicate
+ the start of an assistant message will be appended to the formatted output. This is useful when you want to generate a response from the model.
+ Note that this argument will be passed to the chat template, and so it must be supported in the
+ template for this argument to have any effect.
+ continue_final_message (bool or str, *optional*):
+ If this is set, the chat will be formatted so that the final
+ message in the chat is open-ended, without any EOS tokens. The model will continue this message
+ rather than starting a new one. This allows you to "prefill" part of
+ the model's response for it. If a string is passed, it will be used as the key for the field to continue
+ (e.g. "reasoning_content"). Cannot be used at the same time as `add_generation_prompt`.
+
+ return_assistant_tokens_mask (`bool`, defaults to `False`):
+ Whether to return a mask of the assistant generated tokens. For tokens generated by the assistant,
+ the mask will contain 1. For user and system tokens, the mask will contain 0.
+ This functionality is only available for chat templates that support it via the `{% generation %}` keyword.
+ reasoning_effort (`str`, *optional*):
+ The reasoning effort level to use for the model's response. Supported values depend on the model
+ (e.g. `"none"`, "low"`, `"medium"`, `"high"`). If the template does not support reasoning effort,
+ this argument will have no effect.
+ """
+
+ tools: list[dict] | None = None
+ documents: list[dict[str, str]] | None = None
+ add_generation_prompt: bool | None = False
+ continue_final_message: bool | str | None = False
+ return_assistant_tokens_mask: bool | None = False
+ reasoning_effort: str | None = None
+
+
+class ProcessorChatTemplateKwargs(TokenizerChatTemplateKwargs, total=False):
+ """
+ NOTE: `ProcessorChatTemplateKwargs` is deprecated and will be removed in future versions
+
+ Keyword arguments for processor's `apply_chat_template`.
+
+ tokenize (`bool`, *optional*, defaults to `False`):
+ Whether to tokenize the output or not.
+ return_dict (`bool`, defaults to `False`):
+ Whether to return a dictionary with named outputs. Has no effect if tokenize is `False`.
+ load_audio_from_video (`bool`, *optional*, defaults to `False`):
+ Whether to use the audio track of input video. If `True` the audio track will be loaded and passed to the
+ processor. This flag has no effect if the model doesn't support audio modality.
+ """
+
+ tokenize: bool | None = False
+ return_dict: bool | None = False
+ load_audio_from_video: bool | None = False
+
+
+class AllKwargsForChatTemplate(TypedDict, total=False):
+ "NOTE: `AllKwargsForChatTemplate` is deprecated and will be removed in future versions"
+
+ processor_kwargs: ProcessingKwargs
+ template_kwargs: ProcessorChatTemplateKwargs
+
+
+@dataclass
+class MultiModalData:
+ """
+ Dataclass that holds extra useful data for processing
+ multimodal data. Processors currently cannot return keys,
+ unless it is used in model's forward. Thus we have helper
+ methods that calculate and return useful data from processing
+ input multimodals (images/videos).
+ Note that this dataclass is aimed to be used only in vLLM
+ and we might change its API in the future.
+ """
+
+ num_image_tokens: list[int] | None = None
+ num_video_tokens: list[int] | None = None
+ num_audio_tokens: list[int] | None = None
+ num_image_patches: list[int] | None = None
+
+ def __contains__(self, key):
+ return hasattr(self, key) and getattr(self, key) is not None
+
+ def __getitem__(self, key):
+ if hasattr(self, key):
+ return getattr(self, key)
+ raise AttributeError(f"{self.__class__.__name__} has no attribute {key}")
+
+
+@functools.lru_cache(maxsize=8)
+def _merge_typed_dict(preprocessor_typed_dict: type, modality_typed_dict: type) -> type:
+ return TypedDict(
+ "merged_typed_dict",
+ {**preprocessor_typed_dict.__annotations__, **modality_typed_dict.__annotations__},
+ total=False,
+ )
+
+
+class ProcessorMixin(PushToHubMixin):
+ """
+ This is a mixin used to provide saving/loading functionality for all processor classes.
+ """
+
+ # Dynamically set sub-processor attributes. Not every processor has all of these;
+ # they are populated via setattr in __init__ based on each subclass's `attributes`.
+ tokenizer: Any
+ feature_extractor: Any
+ image_processor: Any
+ video_processor: Any
+ chat_template: str | dict[str, str] | None
+
+ # Names need to be attr_class for attr in attributes
+ _auto_class = None
+ valid_processor_kwargs = ProcessingKwargs
+ skip_tensor_conversion = ["video_metadata", "text_replacement_offsets"]
+
+ # args have to match the attributes class attribute
+ def __init__(self, *args, **kwargs):
+ # First, extract chat template from kwargs. It can never be a positional arg
+ setattr(self, "chat_template", kwargs.pop("chat_template", None))
+
+ # Check audio tokenizer for its class but do not treat it as attr to avoid saving weights
+ if (audio_tokenizer := kwargs.pop("audio_tokenizer", None)) is not None:
+ proper_class = self.check_argument_for_proper_class("audio_tokenizer", audio_tokenizer)
+ if not (is_torch_available() and isinstance(audio_tokenizer, PreTrainedAudioTokenizerBase)):
+ raise ValueError(
+ f"Tried to use `{proper_class}` for audio tokenization. However, this class is not"
+ " registered for audio tokenization."
+ )
+ setattr(self, "audio_tokenizer", audio_tokenizer)
+
+ # Sanitize args and kwargs
+ for key in kwargs:
+ if key not in self.get_attributes():
+ raise TypeError(f"Unexpected keyword argument {key}.")
+ for arg, attribute_name in zip(args, self.get_attributes()):
+ if attribute_name in kwargs:
+ raise TypeError(f"Got multiple values for argument {attribute_name}.")
+ else:
+ kwargs[attribute_name] = arg
+
+ if len(kwargs) != len(self.get_attributes()):
+ raise ValueError(
+ f"This processor requires {len(self.get_attributes())} arguments: {', '.join(self.get_attributes())}. Got "
+ f"{len(args)} arguments instead."
+ )
+
+ # Check each arg is of the proper class (this will also catch a user initializing in the wrong order)
+ for attribute_name, arg in kwargs.items():
+ self.check_argument_for_proper_class(attribute_name, arg)
+ setattr(self, attribute_name, arg)
+
+ @auto_docstring
+ def __call__(
+ self,
+ images: ImageInput | None = None,
+ text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None,
+ videos: VideoInput | None = None,
+ audio: AudioInput | None = None,
+ **kwargs: Unpack[ProcessingKwargs],
+ ):
+ images, text, videos, audio = self.prepare_inputs_layout(
+ images=images, text=text, videos=videos, audio=audio, **kwargs
+ )
+ self.validate_inputs(images=images, text=text, videos=videos, audio=audio, **kwargs)
+
+ merged_kwargs = self._merge_kwargs(
+ self.valid_processor_kwargs,
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs if hasattr(self, "tokenizer") else {},
+ **kwargs,
+ )
+
+ processed_images = processed_videos = processed_audio = {}
+ images_replacements = videos_replacements = audio_replacements = []
+ if images is not None and hasattr(self, "image_processor"):
+ processed_images, images_replacements = self._process_images(images, **merged_kwargs["images_kwargs"])
+ if videos is not None and hasattr(self, "video_processor"):
+ processed_videos, videos_replacements = self._process_videos(videos, **merged_kwargs["videos_kwargs"])
+ if audio is not None and hasattr(self, "feature_extractor"):
+ processed_audio, audio_replacements = self._process_audio(audio, **merged_kwargs["audio_kwargs"])
+
+ text_inputs = {}
+ return_tensors = merged_kwargs["text_kwargs"].get("return_tensors", None)
+ if getattr(self, "tokenizer", None) is not None and text is not None:
+ return_mm_token_type_ids = merged_kwargs["text_kwargs"].pop("return_mm_token_type_ids", False)
+ return_text_replacement_offsets = merged_kwargs["text_kwargs"].pop(
+ "return_text_replacement_offsets", False
+ )
+
+ text, text_replacement_offsets = self.get_text_with_replacements(
+ text,
+ images_replacements,
+ videos_replacements,
+ audio_replacements,
+ )
+ text_inputs = self.tokenizer(text, **merged_kwargs["text_kwargs"])
+ self._check_special_mm_tokens(text, text_inputs, modalities=["image", "video", "audio"])
+
+ if return_text_replacement_offsets:
+ text_inputs["text_replacement_offsets"] = text_replacement_offsets
+
+ if return_mm_token_type_ids:
+ text_inputs["mm_token_type_ids"] = self.create_mm_token_type_ids(text_inputs["input_ids"])
+
+ # Pop unused keys from the inputs, e.g. inputs used only to compute number of image tokens
+ data = {**text_inputs, **processed_images, **processed_videos, **processed_audio}
+ data = {k: v for k, v in data.items() if k not in self.unused_input_names}
+
+ if not kwargs.get("return_metadata"):
+ data.pop("video_metadata", None)
+
+ return BatchFeature(data, tensor_type=return_tensors, skip_tensor_conversion=self.skip_tensor_conversion)
+
+ def prepare_inputs_layout(
+ self,
+ images: ImageInput | None = None,
+ text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None,
+ videos: VideoInput | None = None,
+ audio: AudioInput | None = None,
+ **kwargs: Unpack[ProcessingKwargs],
+ ):
+ """
+ Normalize and prefetch inputs before processing. Wraps text in a list for multimodal
+ processors, fetches remote images and audio if URLs are provided, and ensures audio
+ is properly batched. Returns the normalized `(images, text, videos, audio)` tuple.
+ """
+ # To support BC with models in pre-MLLM era, don't wrap text in list
+ if self.all_special_multimodal_tokens and text is not None:
+ if isinstance(text, str):
+ text = [text]
+ # avoid in-place updates on text
+ text = text.copy()
+
+ if audio is not None and hasattr(self, "feature_extractor"):
+ sampling_rate = kwargs.get("sampling_rate", self.feature_extractor.sampling_rate)
+ audio = self.feature_extractor.fetch_audio(audio, sampling_rate=sampling_rate)
+ audio = make_list_of_audio(audio)
+
+ if images is not None and hasattr(self, "image_processor"):
+ images = self.image_processor.fetch_images(images)
+
+ return images, text, videos, audio
+
+ def validate_inputs(
+ self,
+ images: ImageInput | None = None,
+ text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None,
+ videos: VideoInput | None = None,
+ audio: AudioInput | None = None,
+ **kwargs: Unpack[ProcessingKwargs],
+ ):
+ """
+ Validate that at least one input is provided and that no deprecated keyword arguments
+ are used. Raises ``ValueError`` otherwise.
+
+ Override when the processor needs additional validation on the input args.
+ """
+ if "audios" in kwargs and audio is None:
+ raise ValueError("You passed keyword argument `audios` which is deprecated. Please use `audio` instead.")
+
+ if images is None and text is None and videos is None and audio is None:
+ raise ValueError(f"You need to provide at least one input to call {self.__class__.__name__}")
+
+ # Simple preprocessing includes calling the `subprocessor` and optionally
+ # building placeholder strings. Each processor can override and add their
+ # own special pre/post processing on top, e.g. see `audioflamingo`
+ def _process_images(self, images: ImageInput, **kwargs):
+ processed_images = self.image_processor(images, **kwargs)
+
+ image_replacements = []
+ if getattr(self, "image_token", None) is not None:
+ # Some processors use nested struct, we need to flatten back if needed
+ images = make_flat_list_of_images(images)
+ for idx in range(len(images)):
+ replacement_text = self.replace_image_token(processed_images, image_idx=idx)
+ image_replacements.append(replacement_text)
+ return processed_images, image_replacements
+
+ def _process_videos(self, videos: VideoInput, **kwargs):
+ processed_videos = self.video_processor(videos, **kwargs)
+
+ video_replacements = []
+ if getattr(self, "video_token", None) is not None:
+ videos = make_batched_videos(videos)
+ for idx in range(len(videos)):
+ replacement_text = self.replace_video_token(processed_videos, video_idx=idx)
+ video_replacements.append(replacement_text)
+
+ return processed_videos, video_replacements
+
+ def _process_audio(self, audio: AudioInput, **kwargs):
+ processed_audio = self.feature_extractor(audio, **kwargs)
+
+ audio_replacements = []
+ if getattr(self, "audio_token", None) is not None:
+ for idx in range(len(audio)):
+ replacement_text = self.replace_audio_token(processed_audio, audio_idx=idx)
+ audio_replacements.append(replacement_text)
+
+ return processed_audio, audio_replacements
+
+ # To be overriden by each model's processor if they need to add placeholder tokens
+ def replace_image_token(self, image_inputs: dict, image_idx: int) -> str:
+ raise NotImplementedError
+
+ def replace_video_token(self, video_inputs: dict, video_idx: int) -> str:
+ raise NotImplementedError
+
+ def replace_audio_token(self, audio_inputs: dict, audio_idx: int) -> str:
+ raise NotImplementedError
+
+ def get_text_with_replacements(
+ self,
+ text: list[str],
+ images_replacements: list[str] = [],
+ videos_replacements: list[str] = [],
+ audio_replacements: list[str] = [],
+ ) -> tuple[list[str], list[dict[str, Any]]]:
+ """
+ Replace multimodal placeholder tokens in a batch of text strings with their
+ expanded representations, and return the modified texts alongside offset metadata.
+
+ This method is the core text-side preprocessing step for multimodal inputs. It
+ scans each text in the batch for special tokens (image, video, audio) and replaces
+ them in-order with the pre-computed replacement strings produced by
+ `self.replace_image_token` / `self.replace_video_token` / `self.replace_audio_token`.
+ Replacements are consumed from each modality's list sequentially, so the i-th
+ occurrence of e.g. ``self.image_token`` is replaced by ``images_replacements[i]``.
+
+ To add a new multimodal processor with placeholder tokens, you need to define a correct
+ `self.image_token` which is the same token that is embedded in input text and also used as
+ placeholder and repeated many times. Then you need to override `self.replace_image_token`
+ to return the correct replacement string for a given image at index `i`. Same goes for all
+ other supported modalities.
+
+ Args:
+ text (`list[str]`):
+ Batch of raw text strings, each potentially containing multimodal
+ placeholder tokens. Note that it will be modified in-place and returned.
+ images_replacements (`list[str]`, *optional*, defaults to `[]`):
+ Expanded replacement strings for each image, in the order they appear
+ across the batch. Produced by `self._process_images`.
+ videos_replacements (`list[str]`, *optional*, defaults to `[]`):
+ Expanded replacement strings for each video. Produced by
+ `self._process_videos`.
+ audio_replacements (`list[str]`, *optional*, defaults to `[]`):
+ Expanded replacement strings for each audio input. Produced by
+ `self._process_audio`.
+
+ Returns:
+ `tuple[list[str], list[dict[str, Any]]]`: A tuple of:
+ - The modified `text` batch with all placeholder tokens expanded.
+ - `batch_replacement_offsets`: one entry per batch item, each being a
+ list of dicts with keys:
+ - `"type"` (`str`): modality name — `"image"`, `"video"`, or `"audio"`
+ - `"span"` (`tuple[int, int]`): original `(start, end)` char offsets of the placeholder token
+ - `"new_span"` (`tuple[int, int]`): `(start, end)` offsets of placeholder in the expanded string
+ - `"text"` (`str`): the original placeholder token string that was matched
+ - `"replacement"` (`str`): the string it was replaced with
+ """
+ # Early exit if no special tokens found, nothing to replace
+ if not self.all_special_multimodal_tokens:
+ return text, []
+
+ # Use named regex so we can extract groups later and replace
+ # TODO @raushan: vllm encodes text and mm-data separately causing errors when a placeholder
+ # has no associated mm-data. Thus we can check if there are any `replacements` and skip otherwise
+ # Plan: update all models and contrib to vllm, they might benefit largely from `replacement_offsets`
+ token_groups = []
+ if len(images_replacements) > 0 and (image_token := getattr(self, "image_token", None)) is not None:
+ token_groups.append(f"(?P{re.escape(image_token)})")
+ if len(videos_replacements) > 0 and (video_token := getattr(self, "video_token", None)) is not None:
+ token_groups.append(f"(?P