Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers-5.3.0.dist-info/INSTALLER +1 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers-5.3.0.dist-info/METADATA +648 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers-5.3.0.dist-info/RECORD +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers-5.3.0.dist-info/REQUESTED +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers-5.3.0.dist-info/WHEEL +5 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers-5.3.0.dist-info/entry_points.txt +2 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers-5.3.0.dist-info/licenses/LICENSE +203 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers-5.3.0.dist-info/top_level.txt +1 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/parakeet/modeling_parakeet.py +814 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/parakeet/modular_parakeet.py +653 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/parakeet/processing_parakeet.py +94 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/parakeet/tokenization_parakeet.py +52 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/patchtsmixer/__init__.py +27 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/patchtsmixer/configuration_patchtsmixer.py +227 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/patchtsmixer/modeling_patchtsmixer.py +2122 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/patchtst/__init__.py +27 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/patchtst/configuration_patchtst.py +253 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/patchtst/modeling_patchtst.py +1974 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_audio/__init__.py +29 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_audio/configuration_pe_audio.py +204 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_audio/feature_extraction_pe_audio.py +160 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_audio/modeling_pe_audio.py +826 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_audio/modular_pe_audio.py +306 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_audio/processing_pe_audio.py +23 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_audio_video/__init__.py +28 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_audio_video/configuration_pe_audio_video.py +223 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_audio_video/modeling_pe_audio_video.py +978 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_audio_video/modular_pe_audio_video.py +771 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_audio_video/processing_pe_audio_video.py +24 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_video/__init__.py +29 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_video/configuration_pe_video.py +209 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_video/modeling_pe_video.py +652 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_video/modular_pe_video.py +237 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_video/processing_pe_video.py +10 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_video/video_processing_pe_video.py +64 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pegasus/__init__.py +28 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pegasus/configuration_pegasus.py +159 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pegasus/modeling_pegasus.py +1361 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pegasus/tokenization_pegasus.py +133 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pegasus_x/__init__.py +27 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pegasus_x/configuration_pegasus_x.py +170 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pegasus_x/modeling_pegasus_x.py +1484 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/perceiver/__init__.py +31 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/perceiver/configuration_perceiver.py +176 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/perceiver/image_processing_perceiver.py +345 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/perceiver/image_processing_perceiver_fast.py +119 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/perceiver/modeling_perceiver.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/perceiver/tokenization_perceiver.py +197 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/perception_lm/__init__.py +29 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/perception_lm/configuration_perception_lm.py +87 -0
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers-5.3.0.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers-5.3.0.dist-info/METADATA
ADDED
|
@@ -0,0 +1,648 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: transformers
|
| 3 |
+
Version: 5.3.0
|
| 4 |
+
Summary: Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.
|
| 5 |
+
Home-page: https://github.com/huggingface/transformers
|
| 6 |
+
Author: The Hugging Face team (past and future) with the help of all our contributors (https://github.com/huggingface/transformers/graphs/contributors)
|
| 7 |
+
Author-email: transformers@huggingface.co
|
| 8 |
+
License: Apache 2.0 License
|
| 9 |
+
Keywords: machine-learning nlp python pytorch transformer llm vlm deep-learning inference training model-hub pretrained-models llama gemma qwen
|
| 10 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 11 |
+
Classifier: Intended Audience :: Developers
|
| 12 |
+
Classifier: Intended Audience :: Education
|
| 13 |
+
Classifier: Intended Audience :: Science/Research
|
| 14 |
+
Classifier: Operating System :: OS Independent
|
| 15 |
+
Classifier: Programming Language :: Python :: 3
|
| 16 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 17 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 18 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.14
|
| 21 |
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
| 22 |
+
Requires-Python: >=3.10.0
|
| 23 |
+
Description-Content-Type: text/markdown
|
| 24 |
+
License-File: LICENSE
|
| 25 |
+
Requires-Dist: huggingface-hub<2.0,>=1.3.0
|
| 26 |
+
Requires-Dist: numpy>=1.17
|
| 27 |
+
Requires-Dist: packaging>=20.0
|
| 28 |
+
Requires-Dist: pyyaml>=5.1
|
| 29 |
+
Requires-Dist: regex!=2019.12.17
|
| 30 |
+
Requires-Dist: tokenizers<=0.23.0,>=0.22.0
|
| 31 |
+
Requires-Dist: typer
|
| 32 |
+
Requires-Dist: safetensors>=0.4.3
|
| 33 |
+
Requires-Dist: tqdm>=4.27
|
| 34 |
+
Provides-Extra: torch
|
| 35 |
+
Requires-Dist: torch>=2.4; extra == "torch"
|
| 36 |
+
Requires-Dist: accelerate>=1.1.0; extra == "torch"
|
| 37 |
+
Provides-Extra: vision
|
| 38 |
+
Requires-Dist: torchvision; extra == "vision"
|
| 39 |
+
Requires-Dist: Pillow<=15.0,>=10.0.1; extra == "vision"
|
| 40 |
+
Provides-Extra: audio
|
| 41 |
+
Requires-Dist: torchaudio; extra == "audio"
|
| 42 |
+
Requires-Dist: librosa; extra == "audio"
|
| 43 |
+
Requires-Dist: pyctcdecode>=0.4.0; extra == "audio"
|
| 44 |
+
Requires-Dist: phonemizer; extra == "audio"
|
| 45 |
+
Provides-Extra: video
|
| 46 |
+
Requires-Dist: av; extra == "video"
|
| 47 |
+
Provides-Extra: timm
|
| 48 |
+
Requires-Dist: timm>=1.0.23; extra == "timm"
|
| 49 |
+
Provides-Extra: quality
|
| 50 |
+
Requires-Dist: datasets>=2.15.0; extra == "quality"
|
| 51 |
+
Requires-Dist: ruff==0.14.10; extra == "quality"
|
| 52 |
+
Requires-Dist: GitPython<3.1.19; extra == "quality"
|
| 53 |
+
Requires-Dist: urllib3<2.0.0; extra == "quality"
|
| 54 |
+
Requires-Dist: libcst; extra == "quality"
|
| 55 |
+
Requires-Dist: rich; extra == "quality"
|
| 56 |
+
Requires-Dist: ty==0.0.12; extra == "quality"
|
| 57 |
+
Provides-Extra: kernels
|
| 58 |
+
Requires-Dist: kernels<0.11,>=0.10.2; extra == "kernels"
|
| 59 |
+
Provides-Extra: sentencepiece
|
| 60 |
+
Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "sentencepiece"
|
| 61 |
+
Requires-Dist: protobuf; extra == "sentencepiece"
|
| 62 |
+
Provides-Extra: tiktoken
|
| 63 |
+
Requires-Dist: tiktoken; extra == "tiktoken"
|
| 64 |
+
Requires-Dist: blobfile; extra == "tiktoken"
|
| 65 |
+
Provides-Extra: mistral-common
|
| 66 |
+
Requires-Dist: mistral-common[image]>=1.8.8; extra == "mistral-common"
|
| 67 |
+
Provides-Extra: chat-template
|
| 68 |
+
Requires-Dist: jinja2>=3.1.0; extra == "chat-template"
|
| 69 |
+
Requires-Dist: jmespath>=1.0.1; extra == "chat-template"
|
| 70 |
+
Provides-Extra: sklearn
|
| 71 |
+
Requires-Dist: scikit-learn; extra == "sklearn"
|
| 72 |
+
Provides-Extra: accelerate
|
| 73 |
+
Requires-Dist: accelerate>=1.1.0; extra == "accelerate"
|
| 74 |
+
Provides-Extra: retrieval
|
| 75 |
+
Requires-Dist: faiss-cpu; extra == "retrieval"
|
| 76 |
+
Requires-Dist: datasets>=2.15.0; extra == "retrieval"
|
| 77 |
+
Provides-Extra: sagemaker
|
| 78 |
+
Requires-Dist: sagemaker>=2.31.0; extra == "sagemaker"
|
| 79 |
+
Provides-Extra: deepspeed
|
| 80 |
+
Requires-Dist: deepspeed>=0.9.3; extra == "deepspeed"
|
| 81 |
+
Requires-Dist: accelerate>=1.1.0; extra == "deepspeed"
|
| 82 |
+
Provides-Extra: optuna
|
| 83 |
+
Requires-Dist: optuna; extra == "optuna"
|
| 84 |
+
Provides-Extra: integrations
|
| 85 |
+
Requires-Dist: kernels<0.11,>=0.10.2; extra == "integrations"
|
| 86 |
+
Requires-Dist: optuna; extra == "integrations"
|
| 87 |
+
Requires-Dist: codecarbon>=2.8.1; extra == "integrations"
|
| 88 |
+
Requires-Dist: ray[tune]>=2.7.0; extra == "integrations"
|
| 89 |
+
Provides-Extra: ray
|
| 90 |
+
Requires-Dist: ray[tune]>=2.7.0; extra == "ray"
|
| 91 |
+
Provides-Extra: codecarbon
|
| 92 |
+
Requires-Dist: codecarbon>=2.8.1; extra == "codecarbon"
|
| 93 |
+
Provides-Extra: serving
|
| 94 |
+
Requires-Dist: openai>=1.98.0; extra == "serving"
|
| 95 |
+
Requires-Dist: pydantic>=2; extra == "serving"
|
| 96 |
+
Requires-Dist: uvicorn; extra == "serving"
|
| 97 |
+
Requires-Dist: fastapi; extra == "serving"
|
| 98 |
+
Requires-Dist: starlette; extra == "serving"
|
| 99 |
+
Requires-Dist: rich; extra == "serving"
|
| 100 |
+
Requires-Dist: torch>=2.4; extra == "serving"
|
| 101 |
+
Requires-Dist: accelerate>=1.1.0; extra == "serving"
|
| 102 |
+
Provides-Extra: num2words
|
| 103 |
+
Requires-Dist: num2words; extra == "num2words"
|
| 104 |
+
Provides-Extra: benchmark
|
| 105 |
+
Requires-Dist: optimum-benchmark>=0.3.0; extra == "benchmark"
|
| 106 |
+
Provides-Extra: ja
|
| 107 |
+
Requires-Dist: fugashi>=1.0; extra == "ja"
|
| 108 |
+
Requires-Dist: ipadic<2.0,>=1.0.0; extra == "ja"
|
| 109 |
+
Requires-Dist: unidic_lite>=1.0.7; extra == "ja"
|
| 110 |
+
Requires-Dist: unidic>=1.0.2; extra == "ja"
|
| 111 |
+
Requires-Dist: rhoknp<1.3.1,>=1.1.0; extra == "ja"
|
| 112 |
+
Requires-Dist: sudachipy>=0.6.6; extra == "ja"
|
| 113 |
+
Requires-Dist: sudachidict_core>=20220729; extra == "ja"
|
| 114 |
+
Provides-Extra: open-telemetry
|
| 115 |
+
Requires-Dist: opentelemetry-api; extra == "open-telemetry"
|
| 116 |
+
Requires-Dist: opentelemetry-exporter-otlp; extra == "open-telemetry"
|
| 117 |
+
Requires-Dist: opentelemetry-sdk; extra == "open-telemetry"
|
| 118 |
+
Provides-Extra: testing
|
| 119 |
+
Requires-Dist: pytest<9.0.0,>=7.2.0; extra == "testing"
|
| 120 |
+
Requires-Dist: pytest-asyncio>=1.2.0; extra == "testing"
|
| 121 |
+
Requires-Dist: pytest-random-order; extra == "testing"
|
| 122 |
+
Requires-Dist: pytest-rich; extra == "testing"
|
| 123 |
+
Requires-Dist: pytest-xdist; extra == "testing"
|
| 124 |
+
Requires-Dist: pytest-order; extra == "testing"
|
| 125 |
+
Requires-Dist: pytest-rerunfailures<16.0; extra == "testing"
|
| 126 |
+
Requires-Dist: pytest-timeout; extra == "testing"
|
| 127 |
+
Requires-Dist: pytest-env; extra == "testing"
|
| 128 |
+
Requires-Dist: timeout-decorator; extra == "testing"
|
| 129 |
+
Requires-Dist: parameterized>=0.9; extra == "testing"
|
| 130 |
+
Requires-Dist: psutil; extra == "testing"
|
| 131 |
+
Requires-Dist: dill<0.3.5; extra == "testing"
|
| 132 |
+
Requires-Dist: evaluate>=0.4.6; extra == "testing"
|
| 133 |
+
Requires-Dist: rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1; extra == "testing"
|
| 134 |
+
Requires-Dist: nltk<=3.8.1; extra == "testing"
|
| 135 |
+
Requires-Dist: sacremoses; extra == "testing"
|
| 136 |
+
Requires-Dist: rjieba; extra == "testing"
|
| 137 |
+
Requires-Dist: beautifulsoup4; extra == "testing"
|
| 138 |
+
Requires-Dist: tensorboard; extra == "testing"
|
| 139 |
+
Requires-Dist: sacrebleu<2.0.0,>=1.4.12; extra == "testing"
|
| 140 |
+
Requires-Dist: filelock; extra == "testing"
|
| 141 |
+
Requires-Dist: datasets>=2.15.0; extra == "testing"
|
| 142 |
+
Requires-Dist: ruff==0.14.10; extra == "testing"
|
| 143 |
+
Requires-Dist: GitPython<3.1.19; extra == "testing"
|
| 144 |
+
Requires-Dist: urllib3<2.0.0; extra == "testing"
|
| 145 |
+
Requires-Dist: libcst; extra == "testing"
|
| 146 |
+
Requires-Dist: rich; extra == "testing"
|
| 147 |
+
Requires-Dist: ty==0.0.12; extra == "testing"
|
| 148 |
+
Requires-Dist: faiss-cpu; extra == "testing"
|
| 149 |
+
Requires-Dist: datasets>=2.15.0; extra == "testing"
|
| 150 |
+
Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "testing"
|
| 151 |
+
Requires-Dist: protobuf; extra == "testing"
|
| 152 |
+
Requires-Dist: openai>=1.98.0; extra == "testing"
|
| 153 |
+
Requires-Dist: pydantic>=2; extra == "testing"
|
| 154 |
+
Requires-Dist: uvicorn; extra == "testing"
|
| 155 |
+
Requires-Dist: fastapi; extra == "testing"
|
| 156 |
+
Requires-Dist: starlette; extra == "testing"
|
| 157 |
+
Requires-Dist: rich; extra == "testing"
|
| 158 |
+
Requires-Dist: torch>=2.4; extra == "testing"
|
| 159 |
+
Requires-Dist: accelerate>=1.1.0; extra == "testing"
|
| 160 |
+
Requires-Dist: mistral-common[image]>=1.8.8; extra == "testing"
|
| 161 |
+
Provides-Extra: deepspeed-testing
|
| 162 |
+
Requires-Dist: deepspeed>=0.9.3; extra == "deepspeed-testing"
|
| 163 |
+
Requires-Dist: accelerate>=1.1.0; extra == "deepspeed-testing"
|
| 164 |
+
Requires-Dist: pytest<9.0.0,>=7.2.0; extra == "deepspeed-testing"
|
| 165 |
+
Requires-Dist: pytest-asyncio>=1.2.0; extra == "deepspeed-testing"
|
| 166 |
+
Requires-Dist: pytest-random-order; extra == "deepspeed-testing"
|
| 167 |
+
Requires-Dist: pytest-rich; extra == "deepspeed-testing"
|
| 168 |
+
Requires-Dist: pytest-xdist; extra == "deepspeed-testing"
|
| 169 |
+
Requires-Dist: pytest-order; extra == "deepspeed-testing"
|
| 170 |
+
Requires-Dist: pytest-rerunfailures<16.0; extra == "deepspeed-testing"
|
| 171 |
+
Requires-Dist: pytest-timeout; extra == "deepspeed-testing"
|
| 172 |
+
Requires-Dist: pytest-env; extra == "deepspeed-testing"
|
| 173 |
+
Requires-Dist: timeout-decorator; extra == "deepspeed-testing"
|
| 174 |
+
Requires-Dist: parameterized>=0.9; extra == "deepspeed-testing"
|
| 175 |
+
Requires-Dist: psutil; extra == "deepspeed-testing"
|
| 176 |
+
Requires-Dist: dill<0.3.5; extra == "deepspeed-testing"
|
| 177 |
+
Requires-Dist: evaluate>=0.4.6; extra == "deepspeed-testing"
|
| 178 |
+
Requires-Dist: rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1; extra == "deepspeed-testing"
|
| 179 |
+
Requires-Dist: nltk<=3.8.1; extra == "deepspeed-testing"
|
| 180 |
+
Requires-Dist: sacremoses; extra == "deepspeed-testing"
|
| 181 |
+
Requires-Dist: rjieba; extra == "deepspeed-testing"
|
| 182 |
+
Requires-Dist: beautifulsoup4; extra == "deepspeed-testing"
|
| 183 |
+
Requires-Dist: tensorboard; extra == "deepspeed-testing"
|
| 184 |
+
Requires-Dist: sacrebleu<2.0.0,>=1.4.12; extra == "deepspeed-testing"
|
| 185 |
+
Requires-Dist: filelock; extra == "deepspeed-testing"
|
| 186 |
+
Requires-Dist: datasets>=2.15.0; extra == "deepspeed-testing"
|
| 187 |
+
Requires-Dist: ruff==0.14.10; extra == "deepspeed-testing"
|
| 188 |
+
Requires-Dist: GitPython<3.1.19; extra == "deepspeed-testing"
|
| 189 |
+
Requires-Dist: urllib3<2.0.0; extra == "deepspeed-testing"
|
| 190 |
+
Requires-Dist: libcst; extra == "deepspeed-testing"
|
| 191 |
+
Requires-Dist: rich; extra == "deepspeed-testing"
|
| 192 |
+
Requires-Dist: ty==0.0.12; extra == "deepspeed-testing"
|
| 193 |
+
Requires-Dist: faiss-cpu; extra == "deepspeed-testing"
|
| 194 |
+
Requires-Dist: datasets>=2.15.0; extra == "deepspeed-testing"
|
| 195 |
+
Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "deepspeed-testing"
|
| 196 |
+
Requires-Dist: protobuf; extra == "deepspeed-testing"
|
| 197 |
+
Requires-Dist: openai>=1.98.0; extra == "deepspeed-testing"
|
| 198 |
+
Requires-Dist: pydantic>=2; extra == "deepspeed-testing"
|
| 199 |
+
Requires-Dist: uvicorn; extra == "deepspeed-testing"
|
| 200 |
+
Requires-Dist: fastapi; extra == "deepspeed-testing"
|
| 201 |
+
Requires-Dist: starlette; extra == "deepspeed-testing"
|
| 202 |
+
Requires-Dist: rich; extra == "deepspeed-testing"
|
| 203 |
+
Requires-Dist: torch>=2.4; extra == "deepspeed-testing"
|
| 204 |
+
Requires-Dist: accelerate>=1.1.0; extra == "deepspeed-testing"
|
| 205 |
+
Requires-Dist: mistral-common[image]>=1.8.8; extra == "deepspeed-testing"
|
| 206 |
+
Requires-Dist: optuna; extra == "deepspeed-testing"
|
| 207 |
+
Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "deepspeed-testing"
|
| 208 |
+
Requires-Dist: protobuf; extra == "deepspeed-testing"
|
| 209 |
+
Provides-Extra: all
|
| 210 |
+
Requires-Dist: torch>=2.4; extra == "all"
|
| 211 |
+
Requires-Dist: accelerate>=1.1.0; extra == "all"
|
| 212 |
+
Requires-Dist: torchvision; extra == "all"
|
| 213 |
+
Requires-Dist: Pillow<=15.0,>=10.0.1; extra == "all"
|
| 214 |
+
Requires-Dist: torchaudio; extra == "all"
|
| 215 |
+
Requires-Dist: librosa; extra == "all"
|
| 216 |
+
Requires-Dist: pyctcdecode>=0.4.0; extra == "all"
|
| 217 |
+
Requires-Dist: phonemizer; extra == "all"
|
| 218 |
+
Requires-Dist: av; extra == "all"
|
| 219 |
+
Requires-Dist: kernels<0.11,>=0.10.2; extra == "all"
|
| 220 |
+
Requires-Dist: timm>=1.0.23; extra == "all"
|
| 221 |
+
Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "all"
|
| 222 |
+
Requires-Dist: protobuf; extra == "all"
|
| 223 |
+
Requires-Dist: tiktoken; extra == "all"
|
| 224 |
+
Requires-Dist: blobfile; extra == "all"
|
| 225 |
+
Requires-Dist: jinja2>=3.1.0; extra == "all"
|
| 226 |
+
Requires-Dist: jmespath>=1.0.1; extra == "all"
|
| 227 |
+
Requires-Dist: num2words; extra == "all"
|
| 228 |
+
Requires-Dist: mistral-common[image]>=1.8.8; extra == "all"
|
| 229 |
+
Provides-Extra: dev
|
| 230 |
+
Requires-Dist: torch>=2.4; extra == "dev"
|
| 231 |
+
Requires-Dist: accelerate>=1.1.0; extra == "dev"
|
| 232 |
+
Requires-Dist: torchvision; extra == "dev"
|
| 233 |
+
Requires-Dist: Pillow<=15.0,>=10.0.1; extra == "dev"
|
| 234 |
+
Requires-Dist: torchaudio; extra == "dev"
|
| 235 |
+
Requires-Dist: librosa; extra == "dev"
|
| 236 |
+
Requires-Dist: pyctcdecode>=0.4.0; extra == "dev"
|
| 237 |
+
Requires-Dist: phonemizer; extra == "dev"
|
| 238 |
+
Requires-Dist: av; extra == "dev"
|
| 239 |
+
Requires-Dist: kernels<0.11,>=0.10.2; extra == "dev"
|
| 240 |
+
Requires-Dist: timm>=1.0.23; extra == "dev"
|
| 241 |
+
Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "dev"
|
| 242 |
+
Requires-Dist: protobuf; extra == "dev"
|
| 243 |
+
Requires-Dist: tiktoken; extra == "dev"
|
| 244 |
+
Requires-Dist: blobfile; extra == "dev"
|
| 245 |
+
Requires-Dist: jinja2>=3.1.0; extra == "dev"
|
| 246 |
+
Requires-Dist: jmespath>=1.0.1; extra == "dev"
|
| 247 |
+
Requires-Dist: num2words; extra == "dev"
|
| 248 |
+
Requires-Dist: mistral-common[image]>=1.8.8; extra == "dev"
|
| 249 |
+
Requires-Dist: pytest<9.0.0,>=7.2.0; extra == "dev"
|
| 250 |
+
Requires-Dist: pytest-asyncio>=1.2.0; extra == "dev"
|
| 251 |
+
Requires-Dist: pytest-random-order; extra == "dev"
|
| 252 |
+
Requires-Dist: pytest-rich; extra == "dev"
|
| 253 |
+
Requires-Dist: pytest-xdist; extra == "dev"
|
| 254 |
+
Requires-Dist: pytest-order; extra == "dev"
|
| 255 |
+
Requires-Dist: pytest-rerunfailures<16.0; extra == "dev"
|
| 256 |
+
Requires-Dist: pytest-timeout; extra == "dev"
|
| 257 |
+
Requires-Dist: pytest-env; extra == "dev"
|
| 258 |
+
Requires-Dist: timeout-decorator; extra == "dev"
|
| 259 |
+
Requires-Dist: parameterized>=0.9; extra == "dev"
|
| 260 |
+
Requires-Dist: psutil; extra == "dev"
|
| 261 |
+
Requires-Dist: dill<0.3.5; extra == "dev"
|
| 262 |
+
Requires-Dist: evaluate>=0.4.6; extra == "dev"
|
| 263 |
+
Requires-Dist: rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1; extra == "dev"
|
| 264 |
+
Requires-Dist: nltk<=3.8.1; extra == "dev"
|
| 265 |
+
Requires-Dist: sacremoses; extra == "dev"
|
| 266 |
+
Requires-Dist: rjieba; extra == "dev"
|
| 267 |
+
Requires-Dist: beautifulsoup4; extra == "dev"
|
| 268 |
+
Requires-Dist: tensorboard; extra == "dev"
|
| 269 |
+
Requires-Dist: sacrebleu<2.0.0,>=1.4.12; extra == "dev"
|
| 270 |
+
Requires-Dist: filelock; extra == "dev"
|
| 271 |
+
Requires-Dist: datasets>=2.15.0; extra == "dev"
|
| 272 |
+
Requires-Dist: ruff==0.14.10; extra == "dev"
|
| 273 |
+
Requires-Dist: GitPython<3.1.19; extra == "dev"
|
| 274 |
+
Requires-Dist: urllib3<2.0.0; extra == "dev"
|
| 275 |
+
Requires-Dist: libcst; extra == "dev"
|
| 276 |
+
Requires-Dist: rich; extra == "dev"
|
| 277 |
+
Requires-Dist: ty==0.0.12; extra == "dev"
|
| 278 |
+
Requires-Dist: faiss-cpu; extra == "dev"
|
| 279 |
+
Requires-Dist: datasets>=2.15.0; extra == "dev"
|
| 280 |
+
Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "dev"
|
| 281 |
+
Requires-Dist: protobuf; extra == "dev"
|
| 282 |
+
Requires-Dist: openai>=1.98.0; extra == "dev"
|
| 283 |
+
Requires-Dist: pydantic>=2; extra == "dev"
|
| 284 |
+
Requires-Dist: uvicorn; extra == "dev"
|
| 285 |
+
Requires-Dist: fastapi; extra == "dev"
|
| 286 |
+
Requires-Dist: starlette; extra == "dev"
|
| 287 |
+
Requires-Dist: rich; extra == "dev"
|
| 288 |
+
Requires-Dist: torch>=2.4; extra == "dev"
|
| 289 |
+
Requires-Dist: accelerate>=1.1.0; extra == "dev"
|
| 290 |
+
Requires-Dist: mistral-common[image]>=1.8.8; extra == "dev"
|
| 291 |
+
Requires-Dist: fugashi>=1.0; extra == "dev"
|
| 292 |
+
Requires-Dist: ipadic<2.0,>=1.0.0; extra == "dev"
|
| 293 |
+
Requires-Dist: unidic_lite>=1.0.7; extra == "dev"
|
| 294 |
+
Requires-Dist: unidic>=1.0.2; extra == "dev"
|
| 295 |
+
Requires-Dist: rhoknp<1.3.1,>=1.1.0; extra == "dev"
|
| 296 |
+
Requires-Dist: sudachipy>=0.6.6; extra == "dev"
|
| 297 |
+
Requires-Dist: sudachidict_core>=20220729; extra == "dev"
|
| 298 |
+
Requires-Dist: scikit-learn; extra == "dev"
|
| 299 |
+
Dynamic: author
|
| 300 |
+
Dynamic: author-email
|
| 301 |
+
Dynamic: classifier
|
| 302 |
+
Dynamic: description
|
| 303 |
+
Dynamic: description-content-type
|
| 304 |
+
Dynamic: home-page
|
| 305 |
+
Dynamic: keywords
|
| 306 |
+
Dynamic: license
|
| 307 |
+
Dynamic: license-file
|
| 308 |
+
Dynamic: provides-extra
|
| 309 |
+
Dynamic: requires-dist
|
| 310 |
+
Dynamic: requires-python
|
| 311 |
+
Dynamic: summary
|
| 312 |
+
|
| 313 |
+
<!---
|
| 314 |
+
Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 315 |
+
|
| 316 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 317 |
+
you may not use this file except in compliance with the License.
|
| 318 |
+
You may obtain a copy of the License at
|
| 319 |
+
|
| 320 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 321 |
+
|
| 322 |
+
Unless required by applicable law or agreed to in writing, software
|
| 323 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 324 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 325 |
+
See the License for the specific language governing permissions and
|
| 326 |
+
limitations under the License.
|
| 327 |
+
-->
|
| 328 |
+
|
| 329 |
+
<p align="center">
|
| 330 |
+
<picture>
|
| 331 |
+
<source media="(prefers-color-scheme: dark)" srcset="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/transformers-logo-dark.svg">
|
| 332 |
+
<source media="(prefers-color-scheme: light)" srcset="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/transformers-logo-light.svg">
|
| 333 |
+
<img alt="Hugging Face Transformers Library" src="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/transformers-logo-light.svg" width="352" height="59" style="max-width: 100%;">
|
| 334 |
+
</picture>
|
| 335 |
+
<br/>
|
| 336 |
+
<br/>
|
| 337 |
+
</p>
|
| 338 |
+
|
| 339 |
+
<p align="center">
|
| 340 |
+
<a href="https://huggingface.com/models"><img alt="Checkpoints on Hub" src="https://img.shields.io/endpoint?url=https://huggingface.co/api/shields/models&color=brightgreen"></a>
|
| 341 |
+
<a href="https://circleci.com/gh/huggingface/transformers"><img alt="Build" src="https://img.shields.io/circleci/build/github/huggingface/transformers/main"></a>
|
| 342 |
+
<a href="https://github.com/huggingface/transformers/blob/main/LICENSE"><img alt="GitHub" src="https://img.shields.io/github/license/huggingface/transformers.svg?color=blue"></a>
|
| 343 |
+
<a href="https://huggingface.co/docs/transformers/index"><img alt="Documentation" src="https://img.shields.io/website/http/huggingface.co/docs/transformers/index.svg?down_color=red&down_message=offline&up_message=online"></a>
|
| 344 |
+
<a href="https://github.com/huggingface/transformers/releases"><img alt="GitHub release" src="https://img.shields.io/github/release/huggingface/transformers.svg"></a>
|
| 345 |
+
<a href="https://github.com/huggingface/transformers/blob/main/CODE_OF_CONDUCT.md"><img alt="Contributor Covenant" src="https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg"></a>
|
| 346 |
+
<a href="https://zenodo.org/badge/latestdoi/155220641"><img src="https://zenodo.org/badge/155220641.svg" alt="DOI"></a>
|
| 347 |
+
</p>
|
| 348 |
+
|
| 349 |
+
<h4 align="center">
|
| 350 |
+
<p>
|
| 351 |
+
<b>English</b> |
|
| 352 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_zh-hans.md">简体中文</a> |
|
| 353 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_zh-hant.md">繁體中文</a> |
|
| 354 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_ko.md">한국어</a> |
|
| 355 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_es.md">Español</a> |
|
| 356 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_ja.md">日本語</a> |
|
| 357 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_hd.md">हिन्दी</a> |
|
| 358 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_ru.md">Русский</a> |
|
| 359 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_pt-br.md">Português</a> |
|
| 360 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_te.md">తెలుగు</a> |
|
| 361 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_fr.md">Français</a> |
|
| 362 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_de.md">Deutsch</a> |
|
| 363 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_it.md">Italiano</a> |
|
| 364 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_vi.md">Tiếng Việt</a> |
|
| 365 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_ar.md">العربية</a> |
|
| 366 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_ur.md">اردو</a> |
|
| 367 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_bn.md">বাংলা</a> |
|
| 368 |
+
</p>
|
| 369 |
+
</h4>
|
| 370 |
+
|
| 371 |
+
<h3 align="center">
|
| 372 |
+
<p>State-of-the-art pretrained models for inference and training</p>
|
| 373 |
+
</h3>
|
| 374 |
+
|
| 375 |
+
<h3 align="center">
|
| 376 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/transformers_as_a_model_definition.png"/>
|
| 377 |
+
</h3>
|
| 378 |
+
|
| 379 |
+
Transformers acts as the model-definition framework for state-of-the-art machine learning with text, computer
|
| 380 |
+
vision, audio, video, and multimodal models, for both inference and training.
|
| 381 |
+
|
| 382 |
+
It centralizes the model definition so that this definition is agreed upon across the ecosystem. `transformers` is the
|
| 383 |
+
pivot across frameworks: if a model definition is supported, it will be compatible with the majority of training
|
| 384 |
+
frameworks (Axolotl, Unsloth, DeepSpeed, FSDP, PyTorch-Lightning, ...), inference engines (vLLM, SGLang, TGI, ...),
|
| 385 |
+
and adjacent modeling libraries (llama.cpp, mlx, ...) which leverage the model definition from `transformers`.
|
| 386 |
+
|
| 387 |
+
We pledge to help support new state-of-the-art models and democratize their usage by having their model definition be
|
| 388 |
+
simple, customizable, and efficient.
|
| 389 |
+
|
| 390 |
+
There are over 1M+ Transformers [model checkpoints](https://huggingface.co/models?library=transformers&sort=trending) on the [Hugging Face Hub](https://huggingface.com/models) you can use.
|
| 391 |
+
|
| 392 |
+
Explore the [Hub](https://huggingface.com/) today to find a model and use Transformers to help you get started right away.
|
| 393 |
+
|
| 394 |
+
## Installation
|
| 395 |
+
|
| 396 |
+
Transformers works with Python 3.10+, and [PyTorch](https://pytorch.org/get-started/locally/) 2.4+.
|
| 397 |
+
|
| 398 |
+
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.
|
| 399 |
+
|
| 400 |
+
```py
|
| 401 |
+
# venv
|
| 402 |
+
python -m venv .my-env
|
| 403 |
+
source .my-env/bin/activate
|
| 404 |
+
# uv
|
| 405 |
+
uv venv .my-env
|
| 406 |
+
source .my-env/bin/activate
|
| 407 |
+
```
|
| 408 |
+
|
| 409 |
+
Install Transformers in your virtual environment.
|
| 410 |
+
|
| 411 |
+
```py
|
| 412 |
+
# pip
|
| 413 |
+
pip install "transformers[torch]"
|
| 414 |
+
|
| 415 |
+
# uv
|
| 416 |
+
uv pip install "transformers[torch]"
|
| 417 |
+
```
|
| 418 |
+
|
| 419 |
+
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.
|
| 420 |
+
|
| 421 |
+
```shell
|
| 422 |
+
git clone https://github.com/huggingface/transformers.git
|
| 423 |
+
cd transformers
|
| 424 |
+
|
| 425 |
+
# pip
|
| 426 |
+
pip install '.[torch]'
|
| 427 |
+
|
| 428 |
+
# uv
|
| 429 |
+
uv pip install '.[torch]'
|
| 430 |
+
```
|
| 431 |
+
|
| 432 |
+
## Quickstart
|
| 433 |
+
|
| 434 |
+
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.
|
| 435 |
+
|
| 436 |
+
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.
|
| 437 |
+
|
| 438 |
+
```py
|
| 439 |
+
from transformers import pipeline
|
| 440 |
+
|
| 441 |
+
pipeline = pipeline(task="text-generation", model="Qwen/Qwen2.5-1.5B")
|
| 442 |
+
pipeline("the secret to baking a really good cake is ")
|
| 443 |
+
[{'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.'}]
|
| 444 |
+
```
|
| 445 |
+
|
| 446 |
+
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.
|
| 447 |
+
|
| 448 |
+
> [!TIP]
|
| 449 |
+
> 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).
|
| 450 |
+
> ```shell
|
| 451 |
+
> transformers chat Qwen/Qwen2.5-0.5B-Instruct
|
| 452 |
+
> ```
|
| 453 |
+
|
| 454 |
+
```py
|
| 455 |
+
import torch
|
| 456 |
+
from transformers import pipeline
|
| 457 |
+
|
| 458 |
+
chat = [
|
| 459 |
+
{"role": "system", "content": "You are a sassy, wise-cracking robot as imagined by Hollywood circa 1986."},
|
| 460 |
+
{"role": "user", "content": "Hey, can you tell me any fun things to do in New York?"}
|
| 461 |
+
]
|
| 462 |
+
|
| 463 |
+
pipeline = pipeline(task="text-generation", model="meta-llama/Meta-Llama-3-8B-Instruct", dtype=torch.bfloat16, device_map="auto")
|
| 464 |
+
response = pipeline(chat, max_new_tokens=512)
|
| 465 |
+
print(response[0]["generated_text"][-1]["content"])
|
| 466 |
+
```
|
| 467 |
+
|
| 468 |
+
Expand the examples below to see how `Pipeline` works for different modalities and tasks.
|
| 469 |
+
|
| 470 |
+
<details>
|
| 471 |
+
<summary>Automatic speech recognition</summary>
|
| 472 |
+
|
| 473 |
+
```py
|
| 474 |
+
from transformers import pipeline
|
| 475 |
+
|
| 476 |
+
pipeline = pipeline(task="automatic-speech-recognition", model="openai/whisper-large-v3")
|
| 477 |
+
pipeline("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
|
| 478 |
+
{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.'}
|
| 479 |
+
```
|
| 480 |
+
|
| 481 |
+
</details>
|
| 482 |
+
|
| 483 |
+
<details>
|
| 484 |
+
<summary>Image classification</summary>
|
| 485 |
+
|
| 486 |
+
<h3 align="center">
|
| 487 |
+
<a><img src="https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png"></a>
|
| 488 |
+
</h3>
|
| 489 |
+
|
| 490 |
+
```py
|
| 491 |
+
from transformers import pipeline
|
| 492 |
+
|
| 493 |
+
pipeline = pipeline(task="image-classification", model="facebook/dinov2-small-imagenet1k-1-layer")
|
| 494 |
+
pipeline("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
|
| 495 |
+
[{'label': 'macaw', 'score': 0.997848391532898},
|
| 496 |
+
{'label': 'sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita',
|
| 497 |
+
'score': 0.0016551691805943847},
|
| 498 |
+
{'label': 'lorikeet', 'score': 0.00018523589824326336},
|
| 499 |
+
{'label': 'African grey, African gray, Psittacus erithacus',
|
| 500 |
+
'score': 7.85409429227002e-05},
|
| 501 |
+
{'label': 'quail', 'score': 5.502637941390276e-05}]
|
| 502 |
+
```
|
| 503 |
+
|
| 504 |
+
</details>
|
| 505 |
+
|
| 506 |
+
<details>
|
| 507 |
+
<summary>Visual question answering</summary>
|
| 508 |
+
|
| 509 |
+
<h3 align="center">
|
| 510 |
+
<a><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/idefics-few-shot.jpg"></a>
|
| 511 |
+
</h3>
|
| 512 |
+
|
| 513 |
+
```py
|
| 514 |
+
from transformers import pipeline
|
| 515 |
+
|
| 516 |
+
pipeline = pipeline(task="visual-question-answering", model="Salesforce/blip-vqa-base")
|
| 517 |
+
pipeline(
|
| 518 |
+
image="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/idefics-few-shot.jpg",
|
| 519 |
+
question="What is in the image?",
|
| 520 |
+
)
|
| 521 |
+
[{'answer': 'statue of liberty'}]
|
| 522 |
+
```
|
| 523 |
+
|
| 524 |
+
</details>
|
| 525 |
+
|
| 526 |
+
## Why should I use Transformers?
|
| 527 |
+
|
| 528 |
+
1. Easy-to-use state-of-the-art models:
|
| 529 |
+
- High performance on natural language understanding & generation, computer vision, audio, video, and multimodal tasks.
|
| 530 |
+
- Low barrier to entry for researchers, engineers, and developers.
|
| 531 |
+
- Few user-facing abstractions with just three classes to learn.
|
| 532 |
+
- A unified API for using all our pretrained models.
|
| 533 |
+
|
| 534 |
+
1. Lower compute costs, smaller carbon footprint:
|
| 535 |
+
- Share trained models instead of training from scratch.
|
| 536 |
+
- Reduce compute time and production costs.
|
| 537 |
+
- Dozens of model architectures with 1M+ pretrained checkpoints across all modalities.
|
| 538 |
+
|
| 539 |
+
1. Choose the right framework for every part of a model's lifetime:
|
| 540 |
+
- Train state-of-the-art models in 3 lines of code.
|
| 541 |
+
- Move a single model between PyTorch/JAX/TF2.0 frameworks at will.
|
| 542 |
+
- Pick the right framework for training, evaluation, and production.
|
| 543 |
+
|
| 544 |
+
1. Easily customize a model or an example to your needs:
|
| 545 |
+
- We provide examples for each architecture to reproduce the results published by its original authors.
|
| 546 |
+
- Model internals are exposed as consistently as possible.
|
| 547 |
+
- Model files can be used independently of the library for quick experiments.
|
| 548 |
+
|
| 549 |
+
<a target="_blank" href="https://huggingface.co/enterprise">
|
| 550 |
+
<img alt="Hugging Face Enterprise Hub" src="https://github.com/user-attachments/assets/247fb16d-d251-4583-96c4-d3d76dda4925">
|
| 551 |
+
</a><br>
|
| 552 |
+
|
| 553 |
+
## Why shouldn't I use Transformers?
|
| 554 |
+
|
| 555 |
+
- 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.
|
| 556 |
+
- 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).
|
| 557 |
+
- 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.
|
| 558 |
+
|
| 559 |
+
## 100 projects using Transformers
|
| 560 |
+
|
| 561 |
+
Transformers is more than a toolkit to use pretrained models, it's a community of projects built around it and the
|
| 562 |
+
Hugging Face Hub. We want Transformers to enable developers, researchers, students, professors, engineers, and anyone
|
| 563 |
+
else to build their dream projects.
|
| 564 |
+
|
| 565 |
+
In order to celebrate Transformers 100,000 stars, we wanted to put the spotlight on the
|
| 566 |
+
community with the [awesome-transformers](./awesome-transformers.md) page which lists 100
|
| 567 |
+
incredible projects built with Transformers.
|
| 568 |
+
|
| 569 |
+
If you own or use a project that you believe should be part of the list, please open a PR to add it!
|
| 570 |
+
|
| 571 |
+
## Example models
|
| 572 |
+
|
| 573 |
+
You can test most of our models directly on their [Hub model pages](https://huggingface.co/models).
|
| 574 |
+
|
| 575 |
+
Expand each modality below to see a few example models for various use cases.
|
| 576 |
+
|
| 577 |
+
<details>
|
| 578 |
+
<summary>Audio</summary>
|
| 579 |
+
|
| 580 |
+
- Audio classification with [CLAP](https://huggingface.co/laion/clap-htsat-fused)
|
| 581 |
+
- 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)
|
| 582 |
+
- Keyword spotting with [Wav2Vec2](https://huggingface.co/superb/wav2vec2-base-superb-ks)
|
| 583 |
+
- Speech to speech generation with [Moshi](https://huggingface.co/kyutai/moshiko-pytorch-bf16)
|
| 584 |
+
- Text to audio with [MusicGen](https://huggingface.co/facebook/musicgen-large)
|
| 585 |
+
- Text to speech with [CSM](https://huggingface.co/sesame/csm-1b)
|
| 586 |
+
|
| 587 |
+
</details>
|
| 588 |
+
|
| 589 |
+
<details>
|
| 590 |
+
<summary>Computer vision</summary>
|
| 591 |
+
|
| 592 |
+
- Automatic mask generation with [SAM](https://huggingface.co/facebook/sam-vit-base)
|
| 593 |
+
- Depth estimation with [DepthPro](https://huggingface.co/apple/DepthPro-hf)
|
| 594 |
+
- Image classification with [DINO v2](https://huggingface.co/facebook/dinov2-base)
|
| 595 |
+
- Keypoint detection with [SuperPoint](https://huggingface.co/magic-leap-community/superpoint)
|
| 596 |
+
- Keypoint matching with [SuperGlue](https://huggingface.co/magic-leap-community/superglue_outdoor)
|
| 597 |
+
- Object detection with [RT-DETRv2](https://huggingface.co/PekingU/rtdetr_v2_r50vd)
|
| 598 |
+
- Pose Estimation with [VitPose](https://huggingface.co/usyd-community/vitpose-base-simple)
|
| 599 |
+
- Universal segmentation with [OneFormer](https://huggingface.co/shi-labs/oneformer_ade20k_swin_large)
|
| 600 |
+
- Video classification with [VideoMAE](https://huggingface.co/MCG-NJU/videomae-large)
|
| 601 |
+
|
| 602 |
+
</details>
|
| 603 |
+
|
| 604 |
+
<details>
|
| 605 |
+
<summary>Multimodal</summary>
|
| 606 |
+
|
| 607 |
+
- 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)
|
| 608 |
+
- Document question answering with [LayoutLMv3](https://huggingface.co/microsoft/layoutlmv3-base)
|
| 609 |
+
- Image or text to text with [Qwen-VL](https://huggingface.co/Qwen/Qwen2.5-VL-3B-Instruct)
|
| 610 |
+
- Image captioning [BLIP-2](https://huggingface.co/Salesforce/blip2-opt-2.7b)
|
| 611 |
+
- OCR-based document understanding with [GOT-OCR2](https://huggingface.co/stepfun-ai/GOT-OCR-2.0-hf)
|
| 612 |
+
- Table question answering with [TAPAS](https://huggingface.co/google/tapas-base)
|
| 613 |
+
- Unified multimodal understanding and generation with [Emu3](https://huggingface.co/BAAI/Emu3-Gen)
|
| 614 |
+
- Vision to text with [Llava-OneVision](https://huggingface.co/llava-hf/llava-onevision-qwen2-0.5b-ov-hf)
|
| 615 |
+
- Visual question answering with [Llava](https://huggingface.co/llava-hf/llava-1.5-7b-hf)
|
| 616 |
+
- Visual referring expression segmentation with [Kosmos-2](https://huggingface.co/microsoft/kosmos-2-patch14-224)
|
| 617 |
+
|
| 618 |
+
</details>
|
| 619 |
+
|
| 620 |
+
<details>
|
| 621 |
+
<summary>NLP</summary>
|
| 622 |
+
|
| 623 |
+
- Masked word completion with [ModernBERT](https://huggingface.co/answerdotai/ModernBERT-base)
|
| 624 |
+
- Named entity recognition with [Gemma](https://huggingface.co/google/gemma-2-2b)
|
| 625 |
+
- Question answering with [Mixtral](https://huggingface.co/mistralai/Mixtral-8x7B-v0.1)
|
| 626 |
+
- Summarization with [BART](https://huggingface.co/facebook/bart-large-cnn)
|
| 627 |
+
- Translation with [T5](https://huggingface.co/google-t5/t5-base)
|
| 628 |
+
- Text generation with [Llama](https://huggingface.co/meta-llama/Llama-3.2-1B)
|
| 629 |
+
- Text classification with [Qwen](https://huggingface.co/Qwen/Qwen2.5-0.5B)
|
| 630 |
+
|
| 631 |
+
</details>
|
| 632 |
+
|
| 633 |
+
## Citation
|
| 634 |
+
|
| 635 |
+
We now have a [paper](https://www.aclweb.org/anthology/2020.emnlp-demos.6/) you can cite for the 🤗 Transformers library:
|
| 636 |
+
```bibtex
|
| 637 |
+
@inproceedings{wolf-etal-2020-transformers,
|
| 638 |
+
title = "Transformers: State-of-the-Art Natural Language Processing",
|
| 639 |
+
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",
|
| 640 |
+
booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: System Demonstrations",
|
| 641 |
+
month = oct,
|
| 642 |
+
year = "2020",
|
| 643 |
+
address = "Online",
|
| 644 |
+
publisher = "Association for Computational Linguistics",
|
| 645 |
+
url = "https://www.aclweb.org/anthology/2020.emnlp-demos.6",
|
| 646 |
+
pages = "38--45"
|
| 647 |
+
}
|
| 648 |
+
```
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers-5.3.0.dist-info/RECORD
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers-5.3.0.dist-info/REQUESTED
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers-5.3.0.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: setuptools (82.0.0)
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
| 5 |
+
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers-5.3.0.dist-info/entry_points.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[console_scripts]
|
| 2 |
+
transformers = transformers.cli.transformers:main
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers-5.3.0.dist-info/licenses/LICENSE
ADDED
|
@@ -0,0 +1,203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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright 2018- The Hugging Face team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Apache License
|
| 4 |
+
Version 2.0, January 2004
|
| 5 |
+
http://www.apache.org/licenses/
|
| 6 |
+
|
| 7 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 8 |
+
|
| 9 |
+
1. Definitions.
|
| 10 |
+
|
| 11 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 12 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 13 |
+
|
| 14 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 15 |
+
the copyright owner that is granting the License.
|
| 16 |
+
|
| 17 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 18 |
+
other entities that control, are controlled by, or are under common
|
| 19 |
+
control with that entity. For the purposes of this definition,
|
| 20 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 21 |
+
direction or management of such entity, whether by contract or
|
| 22 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 23 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 24 |
+
|
| 25 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 26 |
+
exercising permissions granted by this License.
|
| 27 |
+
|
| 28 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 29 |
+
including but not limited to software source code, documentation
|
| 30 |
+
source, and configuration files.
|
| 31 |
+
|
| 32 |
+
"Object" form shall mean any form resulting from mechanical
|
| 33 |
+
transformation or translation of a Source form, including but
|
| 34 |
+
not limited to compiled object code, generated documentation,
|
| 35 |
+
and conversions to other media types.
|
| 36 |
+
|
| 37 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 38 |
+
Object form, made available under the License, as indicated by a
|
| 39 |
+
copyright notice that is included in or attached to the work
|
| 40 |
+
(an example is provided in the Appendix below).
|
| 41 |
+
|
| 42 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 43 |
+
form, that is based on (or derived from) the Work and for which the
|
| 44 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 45 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 46 |
+
of this License, Derivative Works shall not include works that remain
|
| 47 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 48 |
+
the Work and Derivative Works thereof.
|
| 49 |
+
|
| 50 |
+
"Contribution" shall mean any work of authorship, including
|
| 51 |
+
the original version of the Work and any modifications or additions
|
| 52 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 53 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 54 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 55 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 56 |
+
means any form of electronic, verbal, or written communication sent
|
| 57 |
+
to the Licensor or its representatives, including but not limited to
|
| 58 |
+
communication on electronic mailing lists, source code control systems,
|
| 59 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 60 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 61 |
+
excluding communication that is conspicuously marked or otherwise
|
| 62 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 63 |
+
|
| 64 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 65 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 66 |
+
subsequently incorporated within the Work.
|
| 67 |
+
|
| 68 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 69 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 70 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 71 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 72 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 73 |
+
Work and such Derivative Works in Source or Object form.
|
| 74 |
+
|
| 75 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 76 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 77 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 78 |
+
(except as stated in this section) patent license to make, have made,
|
| 79 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 80 |
+
where such license applies only to those patent claims licensable
|
| 81 |
+
by such Contributor that are necessarily infringed by their
|
| 82 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 83 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 84 |
+
institute patent litigation against any entity (including a
|
| 85 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 86 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 87 |
+
or contributory patent infringement, then any patent licenses
|
| 88 |
+
granted to You under this License for that Work shall terminate
|
| 89 |
+
as of the date such litigation is filed.
|
| 90 |
+
|
| 91 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 92 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 93 |
+
modifications, and in Source or Object form, provided that You
|
| 94 |
+
meet the following conditions:
|
| 95 |
+
|
| 96 |
+
(a) You must give any other recipients of the Work or
|
| 97 |
+
Derivative Works a copy of this License; and
|
| 98 |
+
|
| 99 |
+
(b) You must cause any modified files to carry prominent notices
|
| 100 |
+
stating that You changed the files; and
|
| 101 |
+
|
| 102 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 103 |
+
that You distribute, all copyright, patent, trademark, and
|
| 104 |
+
attribution notices from the Source form of the Work,
|
| 105 |
+
excluding those notices that do not pertain to any part of
|
| 106 |
+
the Derivative Works; and
|
| 107 |
+
|
| 108 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 109 |
+
distribution, then any Derivative Works that You distribute must
|
| 110 |
+
include a readable copy of the attribution notices contained
|
| 111 |
+
within such NOTICE file, excluding those notices that do not
|
| 112 |
+
pertain to any part of the Derivative Works, in at least one
|
| 113 |
+
of the following places: within a NOTICE text file distributed
|
| 114 |
+
as part of the Derivative Works; within the Source form or
|
| 115 |
+
documentation, if provided along with the Derivative Works; or,
|
| 116 |
+
within a display generated by the Derivative Works, if and
|
| 117 |
+
wherever such third-party notices normally appear. The contents
|
| 118 |
+
of the NOTICE file are for informational purposes only and
|
| 119 |
+
do not modify the License. You may add Your own attribution
|
| 120 |
+
notices within Derivative Works that You distribute, alongside
|
| 121 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 122 |
+
that such additional attribution notices cannot be construed
|
| 123 |
+
as modifying the License.
|
| 124 |
+
|
| 125 |
+
You may add Your own copyright statement to Your modifications and
|
| 126 |
+
may provide additional or different license terms and conditions
|
| 127 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 128 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 129 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 130 |
+
the conditions stated in this License.
|
| 131 |
+
|
| 132 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 133 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 134 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 135 |
+
this License, without any additional terms or conditions.
|
| 136 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 137 |
+
the terms of any separate license agreement you may have executed
|
| 138 |
+
with Licensor regarding such Contributions.
|
| 139 |
+
|
| 140 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 141 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 142 |
+
except as required for reasonable and customary use in describing the
|
| 143 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 144 |
+
|
| 145 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 146 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 147 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 148 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 149 |
+
implied, including, without limitation, any warranties or conditions
|
| 150 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 151 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 152 |
+
appropriateness of using or redistributing the Work and assume any
|
| 153 |
+
risks associated with Your exercise of permissions under this License.
|
| 154 |
+
|
| 155 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 156 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 157 |
+
unless required by applicable law (such as deliberate and grossly
|
| 158 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 159 |
+
liable to You for damages, including any direct, indirect, special,
|
| 160 |
+
incidental, or consequential damages of any character arising as a
|
| 161 |
+
result of this License or out of the use or inability to use the
|
| 162 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 163 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 164 |
+
other commercial damages or losses), even if such Contributor
|
| 165 |
+
has been advised of the possibility of such damages.
|
| 166 |
+
|
| 167 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 168 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 169 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 170 |
+
or other liability obligations and/or rights consistent with this
|
| 171 |
+
License. However, in accepting such obligations, You may act only
|
| 172 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 173 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 174 |
+
defend, and hold each Contributor harmless for any liability
|
| 175 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 176 |
+
of your accepting any such warranty or additional liability.
|
| 177 |
+
|
| 178 |
+
END OF TERMS AND CONDITIONS
|
| 179 |
+
|
| 180 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 181 |
+
|
| 182 |
+
To apply the Apache License to your work, attach the following
|
| 183 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 184 |
+
replaced with your own identifying information. (Don't include
|
| 185 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 186 |
+
comment syntax for the file format. We also recommend that a
|
| 187 |
+
file or class name and description of purpose be included on the
|
| 188 |
+
same "printed page" as the copyright notice for easier
|
| 189 |
+
identification within third-party archives.
|
| 190 |
+
|
| 191 |
+
Copyright [yyyy] [name of copyright owner]
|
| 192 |
+
|
| 193 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 194 |
+
you may not use this file except in compliance with the License.
|
| 195 |
+
You may obtain a copy of the License at
|
| 196 |
+
|
| 197 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 198 |
+
|
| 199 |
+
Unless required by applicable law or agreed to in writing, software
|
| 200 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 201 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 202 |
+
See the License for the specific language governing permissions and
|
| 203 |
+
limitations under the License.
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers-5.3.0.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
transformers
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/parakeet/modeling_parakeet.py
ADDED
|
@@ -0,0 +1,814 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/parakeet/modular_parakeet.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_parakeet.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
|
| 21 |
+
import math
|
| 22 |
+
from collections.abc import Callable
|
| 23 |
+
from dataclasses import dataclass
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
from torch import nn
|
| 27 |
+
|
| 28 |
+
from ... import initialization as init
|
| 29 |
+
from ...activations import ACT2FN
|
| 30 |
+
from ...integrations import use_kernel_func_from_hub, use_kernelized_func
|
| 31 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 32 |
+
from ...modeling_outputs import BaseModelOutput, CausalLMOutput
|
| 33 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 34 |
+
from ...processing_utils import Unpack
|
| 35 |
+
from ...utils import ModelOutput, TransformersKwargs, auto_docstring, can_return_tuple
|
| 36 |
+
from ...utils.generic import maybe_autocast, merge_with_config_defaults
|
| 37 |
+
from ...utils.output_capturing import capture_outputs
|
| 38 |
+
from .configuration_parakeet import ParakeetCTCConfig, ParakeetEncoderConfig
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@dataclass
|
| 42 |
+
@auto_docstring(
|
| 43 |
+
custom_intro="""
|
| 44 |
+
Extends [~modeling_outputs.BaseModelOutput] to include the output attention mask since sequence length is not preserved in the model's forward.
|
| 45 |
+
"""
|
| 46 |
+
)
|
| 47 |
+
class ParakeetEncoderModelOutput(BaseModelOutput):
|
| 48 |
+
attention_mask: torch.Tensor | None = None
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class ParakeetEncoderRelPositionalEncoding(nn.Module):
|
| 52 |
+
"""Relative positional encoding for Parakeet."""
|
| 53 |
+
|
| 54 |
+
inv_freq: torch.Tensor # fix linting for `register_buffer`
|
| 55 |
+
|
| 56 |
+
def __init__(self, config: ParakeetEncoderConfig, device=None):
|
| 57 |
+
super().__init__()
|
| 58 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 59 |
+
base = 10000.0
|
| 60 |
+
inv_freq = 1.0 / (
|
| 61 |
+
base
|
| 62 |
+
** (
|
| 63 |
+
torch.arange(0, config.hidden_size, 2, dtype=torch.int64).to(device=device, dtype=torch.float)
|
| 64 |
+
/ config.hidden_size
|
| 65 |
+
)
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 69 |
+
|
| 70 |
+
@torch.no_grad()
|
| 71 |
+
def forward(self, hidden_states: torch.Tensor):
|
| 72 |
+
seq_length = hidden_states.shape[1]
|
| 73 |
+
if seq_length > self.max_position_embeddings:
|
| 74 |
+
raise ValueError(
|
| 75 |
+
f"Sequence Length: {seq_length} has to be less or equal than "
|
| 76 |
+
f"config.max_position_embeddings {self.max_position_embeddings}."
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
position_ids = torch.arange(seq_length - 1, -seq_length, -1, device=hidden_states.device)
|
| 80 |
+
inv_freq_expanded = (
|
| 81 |
+
self.inv_freq[None, :, None].float().expand(hidden_states.shape[0], -1, 1).to(hidden_states.device)
|
| 82 |
+
)
|
| 83 |
+
position_ids_expanded = position_ids[None, None, :].float()
|
| 84 |
+
|
| 85 |
+
device_type = (
|
| 86 |
+
hidden_states.device.type
|
| 87 |
+
if isinstance(hidden_states.device.type, str) and hidden_states.device.type != "mps"
|
| 88 |
+
else "cpu"
|
| 89 |
+
)
|
| 90 |
+
with maybe_autocast(device_type=device_type, enabled=False): # Force float32
|
| 91 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 92 |
+
sin = freqs.sin()
|
| 93 |
+
cos = freqs.cos()
|
| 94 |
+
# interleave sin and cos
|
| 95 |
+
pos_embed = torch.stack([sin, cos], dim=-1)
|
| 96 |
+
pos_embed = pos_embed.reshape(*pos_embed.shape[:-2], -1)
|
| 97 |
+
|
| 98 |
+
return pos_embed.to(dtype=hidden_states.dtype)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class ParakeetEncoderFeedForward(nn.Module):
|
| 102 |
+
def __init__(self, config: ParakeetEncoderConfig):
|
| 103 |
+
super().__init__()
|
| 104 |
+
self.linear1 = nn.Linear(config.hidden_size, config.intermediate_size, bias=config.attention_bias)
|
| 105 |
+
self.activation = ACT2FN[config.hidden_act]
|
| 106 |
+
self.linear2 = nn.Linear(config.intermediate_size, config.hidden_size, bias=config.attention_bias)
|
| 107 |
+
self.activation_dropout = config.activation_dropout
|
| 108 |
+
|
| 109 |
+
def forward(self, hidden_states):
|
| 110 |
+
hidden_states = self.activation(self.linear1(hidden_states))
|
| 111 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
|
| 112 |
+
hidden_states = self.linear2(hidden_states)
|
| 113 |
+
return hidden_states
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class ParakeetEncoderConvolutionModule(nn.Module):
|
| 117 |
+
def __init__(self, config: ParakeetEncoderConfig, module_config=None):
|
| 118 |
+
"""
|
| 119 |
+
Args:
|
| 120 |
+
config (ParakeetEncoderConfig): Configuration for the model.
|
| 121 |
+
module_config (dict): Configuration for the module (e.g., encoder or decoder).
|
| 122 |
+
"""
|
| 123 |
+
super().__init__()
|
| 124 |
+
channels = config.hidden_size
|
| 125 |
+
# kernel_size should be an odd number for 'SAME' padding
|
| 126 |
+
if module_config is None:
|
| 127 |
+
# e.g. using `ParakeetEncoderEncoderConfig` in src/transformers/models/parakeet_encoder/configuration_parakeet_encoder.py
|
| 128 |
+
kernel_size = config.conv_kernel_size
|
| 129 |
+
self.activation = ACT2FN[getattr(config, "hidden_act", "silu")]
|
| 130 |
+
else:
|
| 131 |
+
kernel_size = module_config["kernel_size"]
|
| 132 |
+
self.activation = ACT2FN[module_config.get("activation", "silu")]
|
| 133 |
+
self.padding = (kernel_size - 1) // 2
|
| 134 |
+
self.pointwise_conv1 = nn.Conv1d(
|
| 135 |
+
channels, 2 * channels, kernel_size=1, stride=1, padding=0, bias=config.convolution_bias
|
| 136 |
+
)
|
| 137 |
+
self.depthwise_conv = nn.Conv1d(
|
| 138 |
+
channels,
|
| 139 |
+
channels,
|
| 140 |
+
kernel_size,
|
| 141 |
+
stride=1,
|
| 142 |
+
padding=self.padding,
|
| 143 |
+
groups=channels,
|
| 144 |
+
bias=config.convolution_bias,
|
| 145 |
+
)
|
| 146 |
+
self.norm = nn.BatchNorm1d(channels)
|
| 147 |
+
self.pointwise_conv2 = nn.Conv1d(
|
| 148 |
+
channels, channels, kernel_size=1, stride=1, padding=0, bias=config.convolution_bias
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
def forward(self, hidden_states, attention_mask=None):
|
| 152 |
+
"""
|
| 153 |
+
Compute convolution module.
|
| 154 |
+
|
| 155 |
+
Args:
|
| 156 |
+
hidden_states (`torch.Tensor` of shape `(batch, time, channels)`): Input tensor.
|
| 157 |
+
attention_mask (`torch.Tensor` of shape `(batch, 1, time, time)`): Attention mask.
|
| 158 |
+
|
| 159 |
+
Returns:
|
| 160 |
+
`torch.Tensor`: Output tensor of shape `(batch, time, channels)`.
|
| 161 |
+
|
| 162 |
+
"""
|
| 163 |
+
# exchange the temporal dimension and the feature dimension
|
| 164 |
+
hidden_states = hidden_states.transpose(1, 2)
|
| 165 |
+
|
| 166 |
+
# GLU mechanism, (batch_size, 2*channel, dim)
|
| 167 |
+
hidden_states = self.pointwise_conv1(hidden_states)
|
| 168 |
+
# (batch_size, channel, dim)
|
| 169 |
+
hidden_states = nn.functional.glu(hidden_states, dim=1)
|
| 170 |
+
|
| 171 |
+
# Apply padding mask before convolution
|
| 172 |
+
if attention_mask is not None:
|
| 173 |
+
if attention_mask.dtype == torch.bool:
|
| 174 |
+
all_masked_rows = torch.all(~attention_mask, dim=2)
|
| 175 |
+
else:
|
| 176 |
+
all_masked_rows = torch.all(~(attention_mask == 0.0), dim=2)
|
| 177 |
+
hidden_states = hidden_states.masked_fill(all_masked_rows, 0.0)
|
| 178 |
+
|
| 179 |
+
# 1D Depthwise Conv
|
| 180 |
+
hidden_states = self.depthwise_conv(hidden_states)
|
| 181 |
+
hidden_states = self.norm(hidden_states)
|
| 182 |
+
hidden_states = self.activation(hidden_states)
|
| 183 |
+
hidden_states = self.pointwise_conv2(hidden_states)
|
| 184 |
+
|
| 185 |
+
return hidden_states.transpose(1, 2)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def rotate_half(x):
|
| 189 |
+
"""Rotates half the hidden dims of the input."""
|
| 190 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 191 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 192 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
@use_kernel_func_from_hub("rotary_pos_emb")
|
| 196 |
+
def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
|
| 197 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 198 |
+
|
| 199 |
+
Args:
|
| 200 |
+
q (`torch.Tensor`): The query tensor.
|
| 201 |
+
k (`torch.Tensor`): The key tensor.
|
| 202 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 203 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 204 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 205 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 206 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 207 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 208 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 209 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 210 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 211 |
+
Returns:
|
| 212 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 213 |
+
"""
|
| 214 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 215 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 216 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 217 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 218 |
+
return q_embed, k_embed
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 222 |
+
"""
|
| 223 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 224 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 225 |
+
"""
|
| 226 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 227 |
+
if n_rep == 1:
|
| 228 |
+
return hidden_states
|
| 229 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 230 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def eager_attention_forward(
|
| 234 |
+
module: nn.Module,
|
| 235 |
+
query: torch.Tensor,
|
| 236 |
+
key: torch.Tensor,
|
| 237 |
+
value: torch.Tensor,
|
| 238 |
+
attention_mask: torch.Tensor | None,
|
| 239 |
+
scaling: float,
|
| 240 |
+
dropout: float = 0.0,
|
| 241 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 242 |
+
):
|
| 243 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 244 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 245 |
+
|
| 246 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 247 |
+
if attention_mask is not None:
|
| 248 |
+
attn_weights = attn_weights + attention_mask
|
| 249 |
+
|
| 250 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 251 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 252 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 253 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 254 |
+
|
| 255 |
+
return attn_output, attn_weights
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
@use_kernelized_func(apply_rotary_pos_emb)
|
| 259 |
+
class ParakeetEncoderAttention(nn.Module):
|
| 260 |
+
"""Multi-head attention with relative positional encoding. See section 3.3 of https://huggingface.co/papers/1901.02860."""
|
| 261 |
+
|
| 262 |
+
def __init__(self, config: ParakeetEncoderConfig, layer_idx: int):
|
| 263 |
+
super().__init__()
|
| 264 |
+
self.config = config
|
| 265 |
+
self.layer_idx = layer_idx
|
| 266 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 267 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 268 |
+
self.scaling = self.head_dim**-0.5
|
| 269 |
+
self.attention_dropout = config.attention_dropout
|
| 270 |
+
self.is_causal = False
|
| 271 |
+
|
| 272 |
+
self.q_proj = nn.Linear(
|
| 273 |
+
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
| 274 |
+
)
|
| 275 |
+
self.k_proj = nn.Linear(
|
| 276 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 277 |
+
)
|
| 278 |
+
self.v_proj = nn.Linear(
|
| 279 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 280 |
+
)
|
| 281 |
+
self.o_proj = nn.Linear(
|
| 282 |
+
config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
|
| 283 |
+
)
|
| 284 |
+
# W_{k,R} projection
|
| 285 |
+
self.relative_k_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
|
| 286 |
+
# global content bias
|
| 287 |
+
self.bias_u = nn.Parameter(torch.zeros(config.num_attention_heads, self.head_dim))
|
| 288 |
+
# global positional bias
|
| 289 |
+
self.bias_v = nn.Parameter(torch.zeros(config.num_attention_heads, self.head_dim))
|
| 290 |
+
|
| 291 |
+
def forward(
|
| 292 |
+
self,
|
| 293 |
+
hidden_states: torch.Tensor,
|
| 294 |
+
position_embeddings: torch.Tensor | None,
|
| 295 |
+
attention_mask: torch.Tensor | None = None,
|
| 296 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 297 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 298 |
+
input_shape = hidden_states.shape[:-1]
|
| 299 |
+
batch_size, seq_length = input_shape
|
| 300 |
+
hidden_shape = (batch_size, seq_length, -1, self.head_dim)
|
| 301 |
+
|
| 302 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 303 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 304 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 305 |
+
|
| 306 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 307 |
+
self.config._attn_implementation, eager_attention_forward
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
query_states_with_bias_u = query_states + self.bias_u.view(
|
| 311 |
+
1, self.config.num_attention_heads, 1, self.head_dim
|
| 312 |
+
)
|
| 313 |
+
query_states_with_bias_v = query_states + self.bias_v.view(
|
| 314 |
+
1, self.config.num_attention_heads, 1, self.head_dim
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
relative_key_states = self.relative_k_proj(position_embeddings)
|
| 318 |
+
relative_key_states = relative_key_states.view(batch_size, -1, self.config.num_attention_heads, self.head_dim)
|
| 319 |
+
|
| 320 |
+
# terms (b) and (d)
|
| 321 |
+
matrix_bd = query_states_with_bias_v @ relative_key_states.permute(0, 2, 3, 1)
|
| 322 |
+
matrix_bd = self._rel_shift(matrix_bd)
|
| 323 |
+
matrix_bd = matrix_bd[..., :seq_length]
|
| 324 |
+
matrix_bd = matrix_bd * self.scaling
|
| 325 |
+
|
| 326 |
+
if attention_mask is not None:
|
| 327 |
+
# here the original codebase uses -10000.0 rather than float("-inf") and then manual masked fill with 0.0s
|
| 328 |
+
# see: https://github.com/NVIDIA-NeMo/NeMo/blob/8cfedd7203462cb251a914e700e5605444277561/nemo/collections/asr/parts/submodules/multi_head_attention.py#L320-L340
|
| 329 |
+
# we rather went for a straight-forward approach with float("-inf")
|
| 330 |
+
matrix_bd = matrix_bd.masked_fill_(attention_mask.logical_not(), float("-inf"))
|
| 331 |
+
|
| 332 |
+
# will compute matrix_ac - terms (a) and (c) - and add matrix_bd
|
| 333 |
+
attn_output, attn_weights = attention_interface(
|
| 334 |
+
self,
|
| 335 |
+
query=query_states_with_bias_u,
|
| 336 |
+
key=key_states,
|
| 337 |
+
value=value_states,
|
| 338 |
+
attention_mask=matrix_bd,
|
| 339 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 340 |
+
scaling=self.scaling,
|
| 341 |
+
**kwargs,
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 345 |
+
attn_output = self.o_proj(attn_output)
|
| 346 |
+
return attn_output, attn_weights
|
| 347 |
+
|
| 348 |
+
def _rel_shift(self, attention_scores):
|
| 349 |
+
"""Relative position shift for Shaw et al. style attention. See appendix B of https://huggingface.co/papers/1901.02860."""
|
| 350 |
+
batch_size, num_heads, query_length, position_length = attention_scores.shape
|
| 351 |
+
attention_scores = nn.functional.pad(attention_scores, pad=(1, 0))
|
| 352 |
+
attention_scores = attention_scores.view(batch_size, num_heads, -1, query_length)
|
| 353 |
+
attention_scores = attention_scores[:, :, 1:].view(batch_size, num_heads, query_length, position_length)
|
| 354 |
+
return attention_scores
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
class ParakeetEncoderSubsamplingConv2D(nn.Module):
|
| 358 |
+
def __init__(self, config: ParakeetEncoderConfig):
|
| 359 |
+
super().__init__()
|
| 360 |
+
|
| 361 |
+
self.kernel_size = config.subsampling_conv_kernel_size
|
| 362 |
+
self.stride = config.subsampling_conv_stride
|
| 363 |
+
self.channels = config.subsampling_conv_channels
|
| 364 |
+
self.padding = (self.kernel_size - 1) // 2
|
| 365 |
+
self.num_layers = int(math.log2(config.subsampling_factor))
|
| 366 |
+
|
| 367 |
+
# define layers
|
| 368 |
+
self.layers = nn.ModuleList()
|
| 369 |
+
self.layers.append(
|
| 370 |
+
nn.Conv2d(1, self.channels, kernel_size=self.kernel_size, stride=self.stride, padding=self.padding)
|
| 371 |
+
)
|
| 372 |
+
self.layers.append(nn.ReLU())
|
| 373 |
+
for i in range(self.num_layers - 1):
|
| 374 |
+
# depthwise conv
|
| 375 |
+
self.layers.append(
|
| 376 |
+
nn.Conv2d(
|
| 377 |
+
self.channels,
|
| 378 |
+
self.channels,
|
| 379 |
+
kernel_size=self.kernel_size,
|
| 380 |
+
stride=self.stride,
|
| 381 |
+
padding=self.padding,
|
| 382 |
+
groups=self.channels,
|
| 383 |
+
)
|
| 384 |
+
)
|
| 385 |
+
# pointwise conv
|
| 386 |
+
self.layers.append(nn.Conv2d(self.channels, self.channels, kernel_size=1))
|
| 387 |
+
# activation
|
| 388 |
+
self.layers.append(nn.ReLU())
|
| 389 |
+
|
| 390 |
+
out_length = config.num_mel_bins // (self.stride**self.num_layers)
|
| 391 |
+
self.linear = nn.Linear(config.subsampling_conv_channels * out_length, config.hidden_size, bias=True)
|
| 392 |
+
|
| 393 |
+
def _get_output_length(self, input_lengths: torch.Tensor, conv_layer: nn.Conv2d):
|
| 394 |
+
if hasattr(conv_layer, "stride") and conv_layer.stride != (1, 1):
|
| 395 |
+
padding = conv_layer.padding
|
| 396 |
+
kernel_size = conv_layer.kernel_size[0]
|
| 397 |
+
stride = conv_layer.stride[0]
|
| 398 |
+
|
| 399 |
+
output_lengths = (input_lengths + padding[0] + padding[1] - kernel_size) // stride + 1
|
| 400 |
+
return output_lengths
|
| 401 |
+
|
| 402 |
+
return input_lengths
|
| 403 |
+
|
| 404 |
+
def forward(self, input_features: torch.Tensor, attention_mask: torch.Tensor = None):
|
| 405 |
+
hidden_states = input_features.unsqueeze(1)
|
| 406 |
+
current_lengths = attention_mask.sum(-1) if attention_mask is not None else None
|
| 407 |
+
|
| 408 |
+
for layer in self.layers:
|
| 409 |
+
hidden_states = layer(hidden_states)
|
| 410 |
+
|
| 411 |
+
# mask the hidden states
|
| 412 |
+
if isinstance(layer, nn.Conv2d) and attention_mask is not None:
|
| 413 |
+
current_lengths = self._get_output_length(current_lengths, layer)
|
| 414 |
+
current_seq_length = hidden_states.shape[2]
|
| 415 |
+
channel_mask = (
|
| 416 |
+
torch.arange(current_seq_length, device=attention_mask.device) < current_lengths[:, None]
|
| 417 |
+
)
|
| 418 |
+
hidden_states *= channel_mask[:, None, :, None]
|
| 419 |
+
|
| 420 |
+
hidden_states = hidden_states.transpose(1, 2).reshape(hidden_states.shape[0], hidden_states.shape[2], -1)
|
| 421 |
+
hidden_states = self.linear(hidden_states)
|
| 422 |
+
|
| 423 |
+
return hidden_states
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
class ParakeetEncoderBlock(GradientCheckpointingLayer):
|
| 427 |
+
def __init__(self, config: ParakeetEncoderConfig, layer_idx: int | None = None):
|
| 428 |
+
super().__init__()
|
| 429 |
+
self.gradient_checkpointing = False
|
| 430 |
+
|
| 431 |
+
self.feed_forward1 = ParakeetEncoderFeedForward(config)
|
| 432 |
+
self.self_attn = ParakeetEncoderAttention(config, layer_idx)
|
| 433 |
+
self.conv = ParakeetEncoderConvolutionModule(config)
|
| 434 |
+
self.feed_forward2 = ParakeetEncoderFeedForward(config)
|
| 435 |
+
|
| 436 |
+
self.norm_feed_forward1 = nn.LayerNorm(config.hidden_size)
|
| 437 |
+
self.norm_self_att = nn.LayerNorm(config.hidden_size)
|
| 438 |
+
self.norm_conv = nn.LayerNorm(config.hidden_size)
|
| 439 |
+
self.norm_feed_forward2 = nn.LayerNorm(config.hidden_size)
|
| 440 |
+
self.norm_out = nn.LayerNorm(config.hidden_size)
|
| 441 |
+
|
| 442 |
+
def forward(
|
| 443 |
+
self,
|
| 444 |
+
hidden_states: torch.Tensor,
|
| 445 |
+
attention_mask: torch.Tensor | None = None,
|
| 446 |
+
position_embeddings: torch.Tensor | None = None,
|
| 447 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 448 |
+
) -> torch.Tensor:
|
| 449 |
+
residual = hidden_states
|
| 450 |
+
hidden_states = self.feed_forward1(self.norm_feed_forward1(hidden_states))
|
| 451 |
+
hidden_states = residual + 0.5 * hidden_states # the conformer architecture uses a factor of 0.5
|
| 452 |
+
|
| 453 |
+
normalized_hidden_states = self.norm_self_att(hidden_states)
|
| 454 |
+
attn_output, _ = self.self_attn(
|
| 455 |
+
hidden_states=normalized_hidden_states,
|
| 456 |
+
attention_mask=attention_mask,
|
| 457 |
+
position_embeddings=position_embeddings,
|
| 458 |
+
**kwargs,
|
| 459 |
+
)
|
| 460 |
+
hidden_states = hidden_states + attn_output
|
| 461 |
+
|
| 462 |
+
conv_output = self.conv(self.norm_conv(hidden_states), attention_mask=attention_mask)
|
| 463 |
+
hidden_states = hidden_states + conv_output
|
| 464 |
+
|
| 465 |
+
ff2_output = self.feed_forward2(self.norm_feed_forward2(hidden_states))
|
| 466 |
+
hidden_states = hidden_states + 0.5 * ff2_output # the conformer architecture uses a factor of 0.5
|
| 467 |
+
|
| 468 |
+
hidden_states = self.norm_out(hidden_states)
|
| 469 |
+
|
| 470 |
+
return hidden_states
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
@auto_docstring
|
| 474 |
+
class ParakeetPreTrainedModel(PreTrainedModel):
|
| 475 |
+
config: ParakeetCTCConfig
|
| 476 |
+
base_model_prefix = "model"
|
| 477 |
+
main_input_name = "input_features"
|
| 478 |
+
input_modalities = "audio"
|
| 479 |
+
supports_gradient_checkpointing = True
|
| 480 |
+
_no_split_modules = ["ParakeetEncoderBlock"]
|
| 481 |
+
_supports_flat_attention_mask = True
|
| 482 |
+
_supports_sdpa = True
|
| 483 |
+
_supports_flex_attn = True
|
| 484 |
+
|
| 485 |
+
# TODO: @eustlb, add support when flash attention supports custom attention bias
|
| 486 |
+
_supports_flash_attn = False
|
| 487 |
+
|
| 488 |
+
_can_compile_fullgraph = True
|
| 489 |
+
_supports_attention_backend = True
|
| 490 |
+
_can_record_outputs = {
|
| 491 |
+
"hidden_states": ParakeetEncoderBlock,
|
| 492 |
+
"attentions": ParakeetEncoderAttention,
|
| 493 |
+
}
|
| 494 |
+
|
| 495 |
+
@torch.no_grad()
|
| 496 |
+
def _init_weights(self, module):
|
| 497 |
+
super()._init_weights(module)
|
| 498 |
+
|
| 499 |
+
if hasattr(self.config, "initializer_range"):
|
| 500 |
+
std = self.config.initializer_range
|
| 501 |
+
else:
|
| 502 |
+
# 0.02 is the standard default value across the library
|
| 503 |
+
std = getattr(self.config.get_text_config(), "initializer_range", 0.02)
|
| 504 |
+
|
| 505 |
+
if isinstance(module, ParakeetEncoderAttention):
|
| 506 |
+
# Initialize positional bias parameters
|
| 507 |
+
init.normal_(module.bias_u, mean=0.0, std=std)
|
| 508 |
+
init.normal_(module.bias_v, mean=0.0, std=std)
|
| 509 |
+
elif isinstance(module, ParakeetEncoderRelPositionalEncoding):
|
| 510 |
+
inv_freq = 1.0 / (
|
| 511 |
+
10000.0 ** (torch.arange(0, self.config.hidden_size, 2, dtype=torch.int64) / self.config.hidden_size)
|
| 512 |
+
)
|
| 513 |
+
init.copy_(module.inv_freq, inv_freq)
|
| 514 |
+
|
| 515 |
+
def _get_subsampling_output_length(self, input_lengths: torch.Tensor):
|
| 516 |
+
encoder_config = self.config.encoder_config if isinstance(self.config, ParakeetCTCConfig) else self.config
|
| 517 |
+
|
| 518 |
+
kernel_size = encoder_config.subsampling_conv_kernel_size
|
| 519 |
+
stride = encoder_config.subsampling_conv_stride
|
| 520 |
+
num_layers = int(math.log2(encoder_config.subsampling_factor))
|
| 521 |
+
|
| 522 |
+
all_paddings = (kernel_size - 1) // 2 * 2
|
| 523 |
+
add_pad = all_paddings - kernel_size
|
| 524 |
+
lengths = input_lengths
|
| 525 |
+
|
| 526 |
+
for _ in range(num_layers):
|
| 527 |
+
lengths = torch.div(lengths.to(dtype=torch.float) + add_pad, stride) + 1.0
|
| 528 |
+
lengths = torch.floor(lengths)
|
| 529 |
+
|
| 530 |
+
return lengths.to(dtype=torch.int)
|
| 531 |
+
|
| 532 |
+
def _get_output_attention_mask(self, attention_mask: torch.Tensor, target_length: int | None = None):
|
| 533 |
+
"""
|
| 534 |
+
Convert the input attention mask to its subsampled form. `target_length` sets the desired output length, useful
|
| 535 |
+
when the attention mask length differs from `sum(-1).max()` (i.e., when the longest sequence in the batch is padded)
|
| 536 |
+
"""
|
| 537 |
+
output_lengths = self._get_subsampling_output_length(attention_mask.sum(-1))
|
| 538 |
+
# Use target_length if provided, otherwise use max length in batch
|
| 539 |
+
max_length = target_length if target_length is not None else output_lengths.max()
|
| 540 |
+
attention_mask = torch.arange(max_length, device=attention_mask.device) < output_lengths[:, None]
|
| 541 |
+
return attention_mask
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
@auto_docstring(
|
| 545 |
+
custom_intro="""
|
| 546 |
+
The Parakeet Encoder model, based on the [Fast Conformer architecture](https://huggingface.co/papers/2305.05084).
|
| 547 |
+
"""
|
| 548 |
+
)
|
| 549 |
+
class ParakeetEncoder(ParakeetPreTrainedModel):
|
| 550 |
+
config: ParakeetEncoderConfig
|
| 551 |
+
base_model_prefix = "encoder"
|
| 552 |
+
|
| 553 |
+
def __init__(self, config: ParakeetEncoderConfig):
|
| 554 |
+
super().__init__(config)
|
| 555 |
+
self.config = config
|
| 556 |
+
self.gradient_checkpointing = False
|
| 557 |
+
|
| 558 |
+
self.dropout = config.dropout
|
| 559 |
+
self.dropout_positions = config.dropout_positions
|
| 560 |
+
self.layerdrop = config.layerdrop
|
| 561 |
+
|
| 562 |
+
self.input_scale = math.sqrt(config.hidden_size) if config.scale_input else 1.0
|
| 563 |
+
self.subsampling = ParakeetEncoderSubsamplingConv2D(config)
|
| 564 |
+
self.encode_positions = ParakeetEncoderRelPositionalEncoding(config)
|
| 565 |
+
|
| 566 |
+
self.layers = nn.ModuleList(
|
| 567 |
+
[ParakeetEncoderBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 568 |
+
)
|
| 569 |
+
|
| 570 |
+
self.post_init()
|
| 571 |
+
|
| 572 |
+
@auto_docstring
|
| 573 |
+
@merge_with_config_defaults
|
| 574 |
+
@capture_outputs
|
| 575 |
+
@can_return_tuple
|
| 576 |
+
def forward(
|
| 577 |
+
self,
|
| 578 |
+
input_features: torch.Tensor,
|
| 579 |
+
attention_mask: torch.Tensor | None = None,
|
| 580 |
+
output_attention_mask: bool | None = None,
|
| 581 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 582 |
+
) -> BaseModelOutput:
|
| 583 |
+
r"""
|
| 584 |
+
output_attention_mask (`bool`, *optional*):
|
| 585 |
+
Whether to return the output attention mask.
|
| 586 |
+
|
| 587 |
+
Example:
|
| 588 |
+
|
| 589 |
+
```python
|
| 590 |
+
>>> from transformers import AutoProcessor, ParakeetEncoder
|
| 591 |
+
>>> from datasets import load_dataset, Audio
|
| 592 |
+
|
| 593 |
+
>>> model_id = "nvidia/parakeet-ctc-1.1b"
|
| 594 |
+
>>> processor = AutoProcessor.from_pretrained(model_id)
|
| 595 |
+
>>> encoder = ParakeetEncoder.from_pretrained(model_id)
|
| 596 |
+
|
| 597 |
+
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
| 598 |
+
>>> ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
|
| 599 |
+
|
| 600 |
+
>>> inputs = processor(ds[0]["audio"]["array"])
|
| 601 |
+
>>> encoder_outputs = encoder(**inputs)
|
| 602 |
+
|
| 603 |
+
>>> print(encoder_outputs.last_hidden_state.shape)
|
| 604 |
+
```
|
| 605 |
+
"""
|
| 606 |
+
|
| 607 |
+
hidden_states = self.subsampling(input_features, attention_mask)
|
| 608 |
+
hidden_states = hidden_states * self.input_scale
|
| 609 |
+
position_embeddings = self.encode_positions(hidden_states)
|
| 610 |
+
|
| 611 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 612 |
+
position_embeddings = nn.functional.dropout(
|
| 613 |
+
position_embeddings, p=self.dropout_positions, training=self.training
|
| 614 |
+
)
|
| 615 |
+
|
| 616 |
+
if attention_mask is not None:
|
| 617 |
+
output_mask = self._get_output_attention_mask(attention_mask, target_length=hidden_states.shape[1])
|
| 618 |
+
attention_mask = output_mask.unsqueeze(1).expand(-1, hidden_states.shape[1], -1)
|
| 619 |
+
attention_mask = attention_mask & attention_mask.transpose(1, 2)
|
| 620 |
+
attention_mask = attention_mask.unsqueeze(1)
|
| 621 |
+
|
| 622 |
+
for encoder_layer in self.layers:
|
| 623 |
+
# add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
|
| 624 |
+
to_drop = False
|
| 625 |
+
if self.training:
|
| 626 |
+
dropout_probability = torch.rand([])
|
| 627 |
+
if dropout_probability < self.layerdrop: # skip the layer
|
| 628 |
+
to_drop = True
|
| 629 |
+
|
| 630 |
+
if not to_drop:
|
| 631 |
+
hidden_states = encoder_layer(
|
| 632 |
+
hidden_states,
|
| 633 |
+
attention_mask=attention_mask,
|
| 634 |
+
position_embeddings=position_embeddings,
|
| 635 |
+
**kwargs,
|
| 636 |
+
)
|
| 637 |
+
|
| 638 |
+
return ParakeetEncoderModelOutput(
|
| 639 |
+
last_hidden_state=hidden_states, attention_mask=output_mask.int() if output_attention_mask else None
|
| 640 |
+
)
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
@dataclass
|
| 644 |
+
class ParakeetGenerateOutput(ModelOutput):
|
| 645 |
+
"""
|
| 646 |
+
Outputs of Parakeet models.
|
| 647 |
+
|
| 648 |
+
Args:
|
| 649 |
+
sequences (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 650 |
+
The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
|
| 651 |
+
if all batches finished early due to the `eos_token_id`.
|
| 652 |
+
logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):
|
| 653 |
+
Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
|
| 654 |
+
at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
|
| 655 |
+
each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
|
| 656 |
+
attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
|
| 657 |
+
Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
|
| 658 |
+
`torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
|
| 659 |
+
hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):
|
| 660 |
+
Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
|
| 661 |
+
`torch.FloatTensor` of shape `(batch_size, generated_length, hidden_size)`.
|
| 662 |
+
"""
|
| 663 |
+
|
| 664 |
+
sequences: torch.LongTensor
|
| 665 |
+
logits: tuple[torch.FloatTensor] | None = None
|
| 666 |
+
attentions: tuple[tuple[torch.FloatTensor]] | None = None
|
| 667 |
+
hidden_states: tuple[tuple[torch.FloatTensor]] | None = None
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
@auto_docstring(
|
| 671 |
+
custom_intro="""
|
| 672 |
+
Parakeet Encoder with a Connectionist Temporal Classification (CTC) head.
|
| 673 |
+
"""
|
| 674 |
+
)
|
| 675 |
+
class ParakeetForCTC(ParakeetPreTrainedModel):
|
| 676 |
+
config: ParakeetCTCConfig
|
| 677 |
+
|
| 678 |
+
def __init__(self, config: ParakeetCTCConfig):
|
| 679 |
+
super().__init__(config)
|
| 680 |
+
self.encoder = ParakeetEncoder(config.encoder_config)
|
| 681 |
+
# Conv rather than linear to be consistent with NeMO decoding layer
|
| 682 |
+
self.ctc_head = nn.Conv1d(config.encoder_config.hidden_size, config.vocab_size, kernel_size=1)
|
| 683 |
+
|
| 684 |
+
self.post_init()
|
| 685 |
+
|
| 686 |
+
@auto_docstring
|
| 687 |
+
@can_return_tuple
|
| 688 |
+
def forward(
|
| 689 |
+
self,
|
| 690 |
+
input_features: torch.Tensor,
|
| 691 |
+
attention_mask: torch.Tensor | None = None,
|
| 692 |
+
labels: torch.Tensor | None = None,
|
| 693 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 694 |
+
) -> CausalLMOutput:
|
| 695 |
+
r"""
|
| 696 |
+
Example:
|
| 697 |
+
|
| 698 |
+
```python
|
| 699 |
+
>>> from transformers import AutoProcessor, ParakeetForCTC
|
| 700 |
+
>>> from datasets import load_dataset, Audio
|
| 701 |
+
|
| 702 |
+
>>> model_id = "nvidia/parakeet-ctc-1.1b"
|
| 703 |
+
>>> processor = AutoProcessor.from_pretrained(model_id)
|
| 704 |
+
>>> model = ParakeetForCTC.from_pretrained(model_id)
|
| 705 |
+
|
| 706 |
+
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
| 707 |
+
>>> ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
|
| 708 |
+
|
| 709 |
+
>>> inputs = processor(ds[0]["audio"]["array"], text=ds[0]["text"])
|
| 710 |
+
>>> outputs = model(**inputs)
|
| 711 |
+
|
| 712 |
+
>>> print(outputs.loss)
|
| 713 |
+
```"""
|
| 714 |
+
|
| 715 |
+
encoder_outputs = self.encoder(
|
| 716 |
+
input_features=input_features,
|
| 717 |
+
attention_mask=attention_mask,
|
| 718 |
+
**kwargs,
|
| 719 |
+
)
|
| 720 |
+
|
| 721 |
+
hidden_states = encoder_outputs.last_hidden_state
|
| 722 |
+
logits = self.ctc_head(hidden_states.transpose(1, 2)).transpose(1, 2)
|
| 723 |
+
|
| 724 |
+
loss = None
|
| 725 |
+
if labels is not None:
|
| 726 |
+
# retrieve loss input_lengths from attention_mask
|
| 727 |
+
attention_mask = (
|
| 728 |
+
attention_mask if attention_mask is not None else torch.ones_like(input_features, dtype=torch.long)
|
| 729 |
+
)
|
| 730 |
+
input_lengths = self._get_subsampling_output_length(attention_mask.sum(-1))
|
| 731 |
+
|
| 732 |
+
# assuming that padded tokens are filled with -100
|
| 733 |
+
# when not being attended to
|
| 734 |
+
labels_mask = labels != self.config.pad_token_id
|
| 735 |
+
target_lengths = labels_mask.sum(-1)
|
| 736 |
+
flattened_targets = labels.masked_select(labels_mask)
|
| 737 |
+
|
| 738 |
+
# ctc_loss doesn't support fp16
|
| 739 |
+
log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)
|
| 740 |
+
|
| 741 |
+
with torch.backends.cudnn.flags(enabled=False):
|
| 742 |
+
loss = nn.functional.ctc_loss(
|
| 743 |
+
log_probs,
|
| 744 |
+
flattened_targets,
|
| 745 |
+
input_lengths,
|
| 746 |
+
target_lengths,
|
| 747 |
+
blank=self.config.pad_token_id,
|
| 748 |
+
reduction=self.config.ctc_loss_reduction,
|
| 749 |
+
zero_infinity=self.config.ctc_zero_infinity,
|
| 750 |
+
)
|
| 751 |
+
|
| 752 |
+
return CausalLMOutput(
|
| 753 |
+
loss=loss,
|
| 754 |
+
logits=logits,
|
| 755 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 756 |
+
attentions=encoder_outputs.attentions,
|
| 757 |
+
)
|
| 758 |
+
|
| 759 |
+
@torch.no_grad()
|
| 760 |
+
def generate(
|
| 761 |
+
self,
|
| 762 |
+
input_features: torch.Tensor,
|
| 763 |
+
attention_mask: torch.Tensor | None = None,
|
| 764 |
+
return_dict_in_generate: bool = False,
|
| 765 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 766 |
+
) -> ParakeetGenerateOutput | torch.LongTensor:
|
| 767 |
+
r"""
|
| 768 |
+
Example:
|
| 769 |
+
|
| 770 |
+
```python
|
| 771 |
+
>>> from transformers import AutoProcessor, ParakeetForCTC
|
| 772 |
+
>>> from datasets import load_dataset, Audio
|
| 773 |
+
|
| 774 |
+
>>> model_id = "nvidia/parakeet-ctc-1.1b"
|
| 775 |
+
>>> processor = AutoProcessor.from_pretrained(model_id)
|
| 776 |
+
>>> model = ParakeetForCTC.from_pretrained(model_id)
|
| 777 |
+
|
| 778 |
+
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
| 779 |
+
>>> ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
|
| 780 |
+
|
| 781 |
+
>>> inputs = processor(ds[0]["audio"]["array"], text=ds[0]["text"])
|
| 782 |
+
>>> predicted_ids = model.generate(**inputs)
|
| 783 |
+
>>> transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)
|
| 784 |
+
|
| 785 |
+
>>> print(transcription)
|
| 786 |
+
```
|
| 787 |
+
"""
|
| 788 |
+
kwargs["return_dict"] = True
|
| 789 |
+
outputs: CausalLMOutput = self.forward(
|
| 790 |
+
input_features=input_features,
|
| 791 |
+
attention_mask=attention_mask,
|
| 792 |
+
**kwargs,
|
| 793 |
+
)
|
| 794 |
+
|
| 795 |
+
# greedy decoding
|
| 796 |
+
sequences = outputs.logits.argmax(dim=-1)
|
| 797 |
+
|
| 798 |
+
# mask out padded tokens
|
| 799 |
+
if attention_mask is not None:
|
| 800 |
+
attention_mask = self._get_output_attention_mask(attention_mask, target_length=sequences.shape[1])
|
| 801 |
+
sequences[~attention_mask] = self.config.pad_token_id
|
| 802 |
+
|
| 803 |
+
if return_dict_in_generate:
|
| 804 |
+
return ParakeetGenerateOutput(
|
| 805 |
+
sequences=sequences,
|
| 806 |
+
logits=outputs.logits,
|
| 807 |
+
attentions=outputs.attentions,
|
| 808 |
+
hidden_states=outputs.hidden_states,
|
| 809 |
+
)
|
| 810 |
+
|
| 811 |
+
return sequences
|
| 812 |
+
|
| 813 |
+
|
| 814 |
+
__all__ = ["ParakeetForCTC", "ParakeetEncoder", "ParakeetPreTrainedModel"]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/parakeet/modular_parakeet.py
ADDED
|
@@ -0,0 +1,653 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""PyTorch Parakeet model."""
|
| 15 |
+
|
| 16 |
+
import math
|
| 17 |
+
from collections.abc import Callable
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
from torch import nn
|
| 22 |
+
|
| 23 |
+
from ... import initialization as init
|
| 24 |
+
from ...activations import ACT2FN
|
| 25 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 26 |
+
from ...modeling_outputs import BaseModelOutput, CausalLMOutput
|
| 27 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 28 |
+
from ...processing_utils import Unpack
|
| 29 |
+
from ...utils import ModelOutput, TransformersKwargs, auto_docstring, can_return_tuple
|
| 30 |
+
from ...utils.generic import maybe_autocast, merge_with_config_defaults
|
| 31 |
+
from ...utils.output_capturing import capture_outputs
|
| 32 |
+
from ..fastspeech2_conformer.modeling_fastspeech2_conformer import FastSpeech2ConformerConvolutionModule
|
| 33 |
+
from ..llama.modeling_llama import LlamaAttention, eager_attention_forward
|
| 34 |
+
from .configuration_parakeet import ParakeetCTCConfig, ParakeetEncoderConfig
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@dataclass
|
| 38 |
+
@auto_docstring(
|
| 39 |
+
custom_intro="""
|
| 40 |
+
Extends [~modeling_outputs.BaseModelOutput] to include the output attention mask since sequence length is not preserved in the model's forward.
|
| 41 |
+
"""
|
| 42 |
+
)
|
| 43 |
+
class ParakeetEncoderModelOutput(BaseModelOutput):
|
| 44 |
+
attention_mask: torch.Tensor | None = None
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class ParakeetEncoderRelPositionalEncoding(nn.Module):
|
| 48 |
+
"""Relative positional encoding for Parakeet."""
|
| 49 |
+
|
| 50 |
+
inv_freq: torch.Tensor # fix linting for `register_buffer`
|
| 51 |
+
|
| 52 |
+
def __init__(self, config: ParakeetEncoderConfig, device=None):
|
| 53 |
+
super().__init__()
|
| 54 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 55 |
+
base = 10000.0
|
| 56 |
+
inv_freq = 1.0 / (
|
| 57 |
+
base
|
| 58 |
+
** (
|
| 59 |
+
torch.arange(0, config.hidden_size, 2, dtype=torch.int64).to(device=device, dtype=torch.float)
|
| 60 |
+
/ config.hidden_size
|
| 61 |
+
)
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 65 |
+
|
| 66 |
+
@torch.no_grad()
|
| 67 |
+
def forward(self, hidden_states: torch.Tensor):
|
| 68 |
+
seq_length = hidden_states.shape[1]
|
| 69 |
+
if seq_length > self.max_position_embeddings:
|
| 70 |
+
raise ValueError(
|
| 71 |
+
f"Sequence Length: {seq_length} has to be less or equal than "
|
| 72 |
+
f"config.max_position_embeddings {self.max_position_embeddings}."
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
position_ids = torch.arange(seq_length - 1, -seq_length, -1, device=hidden_states.device)
|
| 76 |
+
inv_freq_expanded = (
|
| 77 |
+
self.inv_freq[None, :, None].float().expand(hidden_states.shape[0], -1, 1).to(hidden_states.device)
|
| 78 |
+
)
|
| 79 |
+
position_ids_expanded = position_ids[None, None, :].float()
|
| 80 |
+
|
| 81 |
+
device_type = (
|
| 82 |
+
hidden_states.device.type
|
| 83 |
+
if isinstance(hidden_states.device.type, str) and hidden_states.device.type != "mps"
|
| 84 |
+
else "cpu"
|
| 85 |
+
)
|
| 86 |
+
with maybe_autocast(device_type=device_type, enabled=False): # Force float32
|
| 87 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 88 |
+
sin = freqs.sin()
|
| 89 |
+
cos = freqs.cos()
|
| 90 |
+
# interleave sin and cos
|
| 91 |
+
pos_embed = torch.stack([sin, cos], dim=-1)
|
| 92 |
+
pos_embed = pos_embed.reshape(*pos_embed.shape[:-2], -1)
|
| 93 |
+
|
| 94 |
+
return pos_embed.to(dtype=hidden_states.dtype)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class ParakeetEncoderFeedForward(nn.Module):
|
| 98 |
+
def __init__(self, config: ParakeetEncoderConfig):
|
| 99 |
+
super().__init__()
|
| 100 |
+
self.linear1 = nn.Linear(config.hidden_size, config.intermediate_size, bias=config.attention_bias)
|
| 101 |
+
self.activation = ACT2FN[config.hidden_act]
|
| 102 |
+
self.linear2 = nn.Linear(config.intermediate_size, config.hidden_size, bias=config.attention_bias)
|
| 103 |
+
self.activation_dropout = config.activation_dropout
|
| 104 |
+
|
| 105 |
+
def forward(self, hidden_states):
|
| 106 |
+
hidden_states = self.activation(self.linear1(hidden_states))
|
| 107 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
|
| 108 |
+
hidden_states = self.linear2(hidden_states)
|
| 109 |
+
return hidden_states
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class ParakeetEncoderConvolutionModule(FastSpeech2ConformerConvolutionModule):
|
| 113 |
+
def __init__(self, config: ParakeetEncoderConfig, module_config=None):
|
| 114 |
+
super().__init__(config, module_config)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class ParakeetEncoderAttention(LlamaAttention):
|
| 118 |
+
"""Multi-head attention with relative positional encoding. See section 3.3 of https://huggingface.co/papers/1901.02860."""
|
| 119 |
+
|
| 120 |
+
def __init__(self, config: ParakeetEncoderConfig, layer_idx: int):
|
| 121 |
+
super().__init__(config, layer_idx=layer_idx)
|
| 122 |
+
self.is_causal = False
|
| 123 |
+
# W_{k,R} projection
|
| 124 |
+
self.relative_k_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
|
| 125 |
+
# global content bias
|
| 126 |
+
self.bias_u = nn.Parameter(torch.zeros(config.num_attention_heads, self.head_dim))
|
| 127 |
+
# global positional bias
|
| 128 |
+
self.bias_v = nn.Parameter(torch.zeros(config.num_attention_heads, self.head_dim))
|
| 129 |
+
|
| 130 |
+
def forward(
|
| 131 |
+
self,
|
| 132 |
+
hidden_states: torch.Tensor,
|
| 133 |
+
position_embeddings: torch.Tensor | None,
|
| 134 |
+
attention_mask: torch.Tensor | None = None,
|
| 135 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 136 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 137 |
+
input_shape = hidden_states.shape[:-1]
|
| 138 |
+
batch_size, seq_length = input_shape
|
| 139 |
+
hidden_shape = (batch_size, seq_length, -1, self.head_dim)
|
| 140 |
+
|
| 141 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 142 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 143 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 144 |
+
|
| 145 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 146 |
+
self.config._attn_implementation, eager_attention_forward
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
query_states_with_bias_u = query_states + self.bias_u.view(
|
| 150 |
+
1, self.config.num_attention_heads, 1, self.head_dim
|
| 151 |
+
)
|
| 152 |
+
query_states_with_bias_v = query_states + self.bias_v.view(
|
| 153 |
+
1, self.config.num_attention_heads, 1, self.head_dim
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
relative_key_states = self.relative_k_proj(position_embeddings)
|
| 157 |
+
relative_key_states = relative_key_states.view(batch_size, -1, self.config.num_attention_heads, self.head_dim)
|
| 158 |
+
|
| 159 |
+
# terms (b) and (d)
|
| 160 |
+
matrix_bd = query_states_with_bias_v @ relative_key_states.permute(0, 2, 3, 1)
|
| 161 |
+
matrix_bd = self._rel_shift(matrix_bd)
|
| 162 |
+
matrix_bd = matrix_bd[..., :seq_length]
|
| 163 |
+
matrix_bd = matrix_bd * self.scaling
|
| 164 |
+
|
| 165 |
+
if attention_mask is not None:
|
| 166 |
+
# here the original codebase uses -10000.0 rather than float("-inf") and then manual masked fill with 0.0s
|
| 167 |
+
# see: https://github.com/NVIDIA-NeMo/NeMo/blob/8cfedd7203462cb251a914e700e5605444277561/nemo/collections/asr/parts/submodules/multi_head_attention.py#L320-L340
|
| 168 |
+
# we rather went for a straight-forward approach with float("-inf")
|
| 169 |
+
matrix_bd = matrix_bd.masked_fill_(attention_mask.logical_not(), float("-inf"))
|
| 170 |
+
|
| 171 |
+
# will compute matrix_ac - terms (a) and (c) - and add matrix_bd
|
| 172 |
+
attn_output, attn_weights = attention_interface(
|
| 173 |
+
self,
|
| 174 |
+
query=query_states_with_bias_u,
|
| 175 |
+
key=key_states,
|
| 176 |
+
value=value_states,
|
| 177 |
+
attention_mask=matrix_bd,
|
| 178 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 179 |
+
scaling=self.scaling,
|
| 180 |
+
**kwargs,
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 184 |
+
attn_output = self.o_proj(attn_output)
|
| 185 |
+
return attn_output, attn_weights
|
| 186 |
+
|
| 187 |
+
def _rel_shift(self, attention_scores):
|
| 188 |
+
"""Relative position shift for Shaw et al. style attention. See appendix B of https://huggingface.co/papers/1901.02860."""
|
| 189 |
+
batch_size, num_heads, query_length, position_length = attention_scores.shape
|
| 190 |
+
attention_scores = nn.functional.pad(attention_scores, pad=(1, 0))
|
| 191 |
+
attention_scores = attention_scores.view(batch_size, num_heads, -1, query_length)
|
| 192 |
+
attention_scores = attention_scores[:, :, 1:].view(batch_size, num_heads, query_length, position_length)
|
| 193 |
+
return attention_scores
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
class ParakeetEncoderSubsamplingConv2D(nn.Module):
|
| 197 |
+
def __init__(self, config: ParakeetEncoderConfig):
|
| 198 |
+
super().__init__()
|
| 199 |
+
|
| 200 |
+
self.kernel_size = config.subsampling_conv_kernel_size
|
| 201 |
+
self.stride = config.subsampling_conv_stride
|
| 202 |
+
self.channels = config.subsampling_conv_channels
|
| 203 |
+
self.padding = (self.kernel_size - 1) // 2
|
| 204 |
+
self.num_layers = int(math.log2(config.subsampling_factor))
|
| 205 |
+
|
| 206 |
+
# define layers
|
| 207 |
+
self.layers = nn.ModuleList()
|
| 208 |
+
self.layers.append(
|
| 209 |
+
nn.Conv2d(1, self.channels, kernel_size=self.kernel_size, stride=self.stride, padding=self.padding)
|
| 210 |
+
)
|
| 211 |
+
self.layers.append(nn.ReLU())
|
| 212 |
+
for i in range(self.num_layers - 1):
|
| 213 |
+
# depthwise conv
|
| 214 |
+
self.layers.append(
|
| 215 |
+
nn.Conv2d(
|
| 216 |
+
self.channels,
|
| 217 |
+
self.channels,
|
| 218 |
+
kernel_size=self.kernel_size,
|
| 219 |
+
stride=self.stride,
|
| 220 |
+
padding=self.padding,
|
| 221 |
+
groups=self.channels,
|
| 222 |
+
)
|
| 223 |
+
)
|
| 224 |
+
# pointwise conv
|
| 225 |
+
self.layers.append(nn.Conv2d(self.channels, self.channels, kernel_size=1))
|
| 226 |
+
# activation
|
| 227 |
+
self.layers.append(nn.ReLU())
|
| 228 |
+
|
| 229 |
+
out_length = config.num_mel_bins // (self.stride**self.num_layers)
|
| 230 |
+
self.linear = nn.Linear(config.subsampling_conv_channels * out_length, config.hidden_size, bias=True)
|
| 231 |
+
|
| 232 |
+
def _get_output_length(self, input_lengths: torch.Tensor, conv_layer: nn.Conv2d):
|
| 233 |
+
if hasattr(conv_layer, "stride") and conv_layer.stride != (1, 1):
|
| 234 |
+
padding = conv_layer.padding
|
| 235 |
+
kernel_size = conv_layer.kernel_size[0]
|
| 236 |
+
stride = conv_layer.stride[0]
|
| 237 |
+
|
| 238 |
+
output_lengths = (input_lengths + padding[0] + padding[1] - kernel_size) // stride + 1
|
| 239 |
+
return output_lengths
|
| 240 |
+
|
| 241 |
+
return input_lengths
|
| 242 |
+
|
| 243 |
+
def forward(self, input_features: torch.Tensor, attention_mask: torch.Tensor = None):
|
| 244 |
+
hidden_states = input_features.unsqueeze(1)
|
| 245 |
+
current_lengths = attention_mask.sum(-1) if attention_mask is not None else None
|
| 246 |
+
|
| 247 |
+
for layer in self.layers:
|
| 248 |
+
hidden_states = layer(hidden_states)
|
| 249 |
+
|
| 250 |
+
# mask the hidden states
|
| 251 |
+
if isinstance(layer, nn.Conv2d) and attention_mask is not None:
|
| 252 |
+
current_lengths = self._get_output_length(current_lengths, layer)
|
| 253 |
+
current_seq_length = hidden_states.shape[2]
|
| 254 |
+
channel_mask = (
|
| 255 |
+
torch.arange(current_seq_length, device=attention_mask.device) < current_lengths[:, None]
|
| 256 |
+
)
|
| 257 |
+
hidden_states *= channel_mask[:, None, :, None]
|
| 258 |
+
|
| 259 |
+
hidden_states = hidden_states.transpose(1, 2).reshape(hidden_states.shape[0], hidden_states.shape[2], -1)
|
| 260 |
+
hidden_states = self.linear(hidden_states)
|
| 261 |
+
|
| 262 |
+
return hidden_states
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
class ParakeetEncoderBlock(GradientCheckpointingLayer):
|
| 266 |
+
def __init__(self, config: ParakeetEncoderConfig, layer_idx: int | None = None):
|
| 267 |
+
super().__init__()
|
| 268 |
+
self.gradient_checkpointing = False
|
| 269 |
+
|
| 270 |
+
self.feed_forward1 = ParakeetEncoderFeedForward(config)
|
| 271 |
+
self.self_attn = ParakeetEncoderAttention(config, layer_idx)
|
| 272 |
+
self.conv = ParakeetEncoderConvolutionModule(config)
|
| 273 |
+
self.feed_forward2 = ParakeetEncoderFeedForward(config)
|
| 274 |
+
|
| 275 |
+
self.norm_feed_forward1 = nn.LayerNorm(config.hidden_size)
|
| 276 |
+
self.norm_self_att = nn.LayerNorm(config.hidden_size)
|
| 277 |
+
self.norm_conv = nn.LayerNorm(config.hidden_size)
|
| 278 |
+
self.norm_feed_forward2 = nn.LayerNorm(config.hidden_size)
|
| 279 |
+
self.norm_out = nn.LayerNorm(config.hidden_size)
|
| 280 |
+
|
| 281 |
+
def forward(
|
| 282 |
+
self,
|
| 283 |
+
hidden_states: torch.Tensor,
|
| 284 |
+
attention_mask: torch.Tensor | None = None,
|
| 285 |
+
position_embeddings: torch.Tensor | None = None,
|
| 286 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 287 |
+
) -> torch.Tensor:
|
| 288 |
+
residual = hidden_states
|
| 289 |
+
hidden_states = self.feed_forward1(self.norm_feed_forward1(hidden_states))
|
| 290 |
+
hidden_states = residual + 0.5 * hidden_states # the conformer architecture uses a factor of 0.5
|
| 291 |
+
|
| 292 |
+
normalized_hidden_states = self.norm_self_att(hidden_states)
|
| 293 |
+
attn_output, _ = self.self_attn(
|
| 294 |
+
hidden_states=normalized_hidden_states,
|
| 295 |
+
attention_mask=attention_mask,
|
| 296 |
+
position_embeddings=position_embeddings,
|
| 297 |
+
**kwargs,
|
| 298 |
+
)
|
| 299 |
+
hidden_states = hidden_states + attn_output
|
| 300 |
+
|
| 301 |
+
conv_output = self.conv(self.norm_conv(hidden_states), attention_mask=attention_mask)
|
| 302 |
+
hidden_states = hidden_states + conv_output
|
| 303 |
+
|
| 304 |
+
ff2_output = self.feed_forward2(self.norm_feed_forward2(hidden_states))
|
| 305 |
+
hidden_states = hidden_states + 0.5 * ff2_output # the conformer architecture uses a factor of 0.5
|
| 306 |
+
|
| 307 |
+
hidden_states = self.norm_out(hidden_states)
|
| 308 |
+
|
| 309 |
+
return hidden_states
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
@auto_docstring
|
| 313 |
+
class ParakeetPreTrainedModel(PreTrainedModel):
|
| 314 |
+
config: ParakeetCTCConfig
|
| 315 |
+
base_model_prefix = "model"
|
| 316 |
+
main_input_name = "input_features"
|
| 317 |
+
input_modalities = "audio"
|
| 318 |
+
supports_gradient_checkpointing = True
|
| 319 |
+
_no_split_modules = ["ParakeetEncoderBlock"]
|
| 320 |
+
_supports_flat_attention_mask = True
|
| 321 |
+
_supports_sdpa = True
|
| 322 |
+
_supports_flex_attn = True
|
| 323 |
+
|
| 324 |
+
# TODO: @eustlb, add support when flash attention supports custom attention bias
|
| 325 |
+
_supports_flash_attn = False
|
| 326 |
+
|
| 327 |
+
_can_compile_fullgraph = True
|
| 328 |
+
_supports_attention_backend = True
|
| 329 |
+
_can_record_outputs = {
|
| 330 |
+
"hidden_states": ParakeetEncoderBlock,
|
| 331 |
+
"attentions": ParakeetEncoderAttention,
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
@torch.no_grad()
|
| 335 |
+
def _init_weights(self, module):
|
| 336 |
+
super()._init_weights(module)
|
| 337 |
+
|
| 338 |
+
if hasattr(self.config, "initializer_range"):
|
| 339 |
+
std = self.config.initializer_range
|
| 340 |
+
else:
|
| 341 |
+
# 0.02 is the standard default value across the library
|
| 342 |
+
std = getattr(self.config.get_text_config(), "initializer_range", 0.02)
|
| 343 |
+
|
| 344 |
+
if isinstance(module, ParakeetEncoderAttention):
|
| 345 |
+
# Initialize positional bias parameters
|
| 346 |
+
init.normal_(module.bias_u, mean=0.0, std=std)
|
| 347 |
+
init.normal_(module.bias_v, mean=0.0, std=std)
|
| 348 |
+
elif isinstance(module, ParakeetEncoderRelPositionalEncoding):
|
| 349 |
+
inv_freq = 1.0 / (
|
| 350 |
+
10000.0 ** (torch.arange(0, self.config.hidden_size, 2, dtype=torch.int64) / self.config.hidden_size)
|
| 351 |
+
)
|
| 352 |
+
init.copy_(module.inv_freq, inv_freq)
|
| 353 |
+
|
| 354 |
+
def _get_subsampling_output_length(self, input_lengths: torch.Tensor):
|
| 355 |
+
encoder_config = self.config.encoder_config if isinstance(self.config, ParakeetCTCConfig) else self.config
|
| 356 |
+
|
| 357 |
+
kernel_size = encoder_config.subsampling_conv_kernel_size
|
| 358 |
+
stride = encoder_config.subsampling_conv_stride
|
| 359 |
+
num_layers = int(math.log2(encoder_config.subsampling_factor))
|
| 360 |
+
|
| 361 |
+
all_paddings = (kernel_size - 1) // 2 * 2
|
| 362 |
+
add_pad = all_paddings - kernel_size
|
| 363 |
+
lengths = input_lengths
|
| 364 |
+
|
| 365 |
+
for _ in range(num_layers):
|
| 366 |
+
lengths = torch.div(lengths.to(dtype=torch.float) + add_pad, stride) + 1.0
|
| 367 |
+
lengths = torch.floor(lengths)
|
| 368 |
+
|
| 369 |
+
return lengths.to(dtype=torch.int)
|
| 370 |
+
|
| 371 |
+
def _get_output_attention_mask(self, attention_mask: torch.Tensor, target_length: int | None = None):
|
| 372 |
+
"""
|
| 373 |
+
Convert the input attention mask to its subsampled form. `target_length` sets the desired output length, useful
|
| 374 |
+
when the attention mask length differs from `sum(-1).max()` (i.e., when the longest sequence in the batch is padded)
|
| 375 |
+
"""
|
| 376 |
+
output_lengths = self._get_subsampling_output_length(attention_mask.sum(-1))
|
| 377 |
+
# Use target_length if provided, otherwise use max length in batch
|
| 378 |
+
max_length = target_length if target_length is not None else output_lengths.max()
|
| 379 |
+
attention_mask = torch.arange(max_length, device=attention_mask.device) < output_lengths[:, None]
|
| 380 |
+
return attention_mask
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
@auto_docstring(
|
| 384 |
+
custom_intro="""
|
| 385 |
+
The Parakeet Encoder model, based on the [Fast Conformer architecture](https://huggingface.co/papers/2305.05084).
|
| 386 |
+
"""
|
| 387 |
+
)
|
| 388 |
+
class ParakeetEncoder(ParakeetPreTrainedModel):
|
| 389 |
+
config: ParakeetEncoderConfig
|
| 390 |
+
base_model_prefix = "encoder"
|
| 391 |
+
|
| 392 |
+
def __init__(self, config: ParakeetEncoderConfig):
|
| 393 |
+
super().__init__(config)
|
| 394 |
+
self.config = config
|
| 395 |
+
self.gradient_checkpointing = False
|
| 396 |
+
|
| 397 |
+
self.dropout = config.dropout
|
| 398 |
+
self.dropout_positions = config.dropout_positions
|
| 399 |
+
self.layerdrop = config.layerdrop
|
| 400 |
+
|
| 401 |
+
self.input_scale = math.sqrt(config.hidden_size) if config.scale_input else 1.0
|
| 402 |
+
self.subsampling = ParakeetEncoderSubsamplingConv2D(config)
|
| 403 |
+
self.encode_positions = ParakeetEncoderRelPositionalEncoding(config)
|
| 404 |
+
|
| 405 |
+
self.layers = nn.ModuleList(
|
| 406 |
+
[ParakeetEncoderBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 407 |
+
)
|
| 408 |
+
|
| 409 |
+
self.post_init()
|
| 410 |
+
|
| 411 |
+
@auto_docstring
|
| 412 |
+
@merge_with_config_defaults
|
| 413 |
+
@capture_outputs
|
| 414 |
+
@can_return_tuple
|
| 415 |
+
def forward(
|
| 416 |
+
self,
|
| 417 |
+
input_features: torch.Tensor,
|
| 418 |
+
attention_mask: torch.Tensor | None = None,
|
| 419 |
+
output_attention_mask: bool | None = None,
|
| 420 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 421 |
+
) -> BaseModelOutput:
|
| 422 |
+
r"""
|
| 423 |
+
output_attention_mask (`bool`, *optional*):
|
| 424 |
+
Whether to return the output attention mask.
|
| 425 |
+
|
| 426 |
+
Example:
|
| 427 |
+
|
| 428 |
+
```python
|
| 429 |
+
>>> from transformers import AutoProcessor, ParakeetEncoder
|
| 430 |
+
>>> from datasets import load_dataset, Audio
|
| 431 |
+
|
| 432 |
+
>>> model_id = "nvidia/parakeet-ctc-1.1b"
|
| 433 |
+
>>> processor = AutoProcessor.from_pretrained(model_id)
|
| 434 |
+
>>> encoder = ParakeetEncoder.from_pretrained(model_id)
|
| 435 |
+
|
| 436 |
+
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
| 437 |
+
>>> ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
|
| 438 |
+
|
| 439 |
+
>>> inputs = processor(ds[0]["audio"]["array"])
|
| 440 |
+
>>> encoder_outputs = encoder(**inputs)
|
| 441 |
+
|
| 442 |
+
>>> print(encoder_outputs.last_hidden_state.shape)
|
| 443 |
+
```
|
| 444 |
+
"""
|
| 445 |
+
|
| 446 |
+
hidden_states = self.subsampling(input_features, attention_mask)
|
| 447 |
+
hidden_states = hidden_states * self.input_scale
|
| 448 |
+
position_embeddings = self.encode_positions(hidden_states)
|
| 449 |
+
|
| 450 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 451 |
+
position_embeddings = nn.functional.dropout(
|
| 452 |
+
position_embeddings, p=self.dropout_positions, training=self.training
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
if attention_mask is not None:
|
| 456 |
+
output_mask = self._get_output_attention_mask(attention_mask, target_length=hidden_states.shape[1])
|
| 457 |
+
attention_mask = output_mask.unsqueeze(1).expand(-1, hidden_states.shape[1], -1)
|
| 458 |
+
attention_mask = attention_mask & attention_mask.transpose(1, 2)
|
| 459 |
+
attention_mask = attention_mask.unsqueeze(1)
|
| 460 |
+
|
| 461 |
+
for encoder_layer in self.layers:
|
| 462 |
+
# add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
|
| 463 |
+
to_drop = False
|
| 464 |
+
if self.training:
|
| 465 |
+
dropout_probability = torch.rand([])
|
| 466 |
+
if dropout_probability < self.layerdrop: # skip the layer
|
| 467 |
+
to_drop = True
|
| 468 |
+
|
| 469 |
+
if not to_drop:
|
| 470 |
+
hidden_states = encoder_layer(
|
| 471 |
+
hidden_states,
|
| 472 |
+
attention_mask=attention_mask,
|
| 473 |
+
position_embeddings=position_embeddings,
|
| 474 |
+
**kwargs,
|
| 475 |
+
)
|
| 476 |
+
|
| 477 |
+
return ParakeetEncoderModelOutput(
|
| 478 |
+
last_hidden_state=hidden_states, attention_mask=output_mask.int() if output_attention_mask else None
|
| 479 |
+
)
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
@dataclass
|
| 483 |
+
class ParakeetGenerateOutput(ModelOutput):
|
| 484 |
+
"""
|
| 485 |
+
Outputs of Parakeet models.
|
| 486 |
+
|
| 487 |
+
Args:
|
| 488 |
+
sequences (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 489 |
+
The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
|
| 490 |
+
if all batches finished early due to the `eos_token_id`.
|
| 491 |
+
logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):
|
| 492 |
+
Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
|
| 493 |
+
at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
|
| 494 |
+
each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
|
| 495 |
+
attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
|
| 496 |
+
Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
|
| 497 |
+
`torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
|
| 498 |
+
hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):
|
| 499 |
+
Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
|
| 500 |
+
`torch.FloatTensor` of shape `(batch_size, generated_length, hidden_size)`.
|
| 501 |
+
"""
|
| 502 |
+
|
| 503 |
+
sequences: torch.LongTensor
|
| 504 |
+
logits: tuple[torch.FloatTensor] | None = None
|
| 505 |
+
attentions: tuple[tuple[torch.FloatTensor]] | None = None
|
| 506 |
+
hidden_states: tuple[tuple[torch.FloatTensor]] | None = None
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
@auto_docstring(
|
| 510 |
+
custom_intro="""
|
| 511 |
+
Parakeet Encoder with a Connectionist Temporal Classification (CTC) head.
|
| 512 |
+
"""
|
| 513 |
+
)
|
| 514 |
+
class ParakeetForCTC(ParakeetPreTrainedModel):
|
| 515 |
+
config: ParakeetCTCConfig
|
| 516 |
+
|
| 517 |
+
def __init__(self, config: ParakeetCTCConfig):
|
| 518 |
+
super().__init__(config)
|
| 519 |
+
self.encoder = ParakeetEncoder(config.encoder_config)
|
| 520 |
+
# Conv rather than linear to be consistent with NeMO decoding layer
|
| 521 |
+
self.ctc_head = nn.Conv1d(config.encoder_config.hidden_size, config.vocab_size, kernel_size=1)
|
| 522 |
+
|
| 523 |
+
self.post_init()
|
| 524 |
+
|
| 525 |
+
@auto_docstring
|
| 526 |
+
@can_return_tuple
|
| 527 |
+
def forward(
|
| 528 |
+
self,
|
| 529 |
+
input_features: torch.Tensor,
|
| 530 |
+
attention_mask: torch.Tensor | None = None,
|
| 531 |
+
labels: torch.Tensor | None = None,
|
| 532 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 533 |
+
) -> CausalLMOutput:
|
| 534 |
+
r"""
|
| 535 |
+
Example:
|
| 536 |
+
|
| 537 |
+
```python
|
| 538 |
+
>>> from transformers import AutoProcessor, ParakeetForCTC
|
| 539 |
+
>>> from datasets import load_dataset, Audio
|
| 540 |
+
|
| 541 |
+
>>> model_id = "nvidia/parakeet-ctc-1.1b"
|
| 542 |
+
>>> processor = AutoProcessor.from_pretrained(model_id)
|
| 543 |
+
>>> model = ParakeetForCTC.from_pretrained(model_id)
|
| 544 |
+
|
| 545 |
+
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
| 546 |
+
>>> ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
|
| 547 |
+
|
| 548 |
+
>>> inputs = processor(ds[0]["audio"]["array"], text=ds[0]["text"])
|
| 549 |
+
>>> outputs = model(**inputs)
|
| 550 |
+
|
| 551 |
+
>>> print(outputs.loss)
|
| 552 |
+
```"""
|
| 553 |
+
|
| 554 |
+
encoder_outputs = self.encoder(
|
| 555 |
+
input_features=input_features,
|
| 556 |
+
attention_mask=attention_mask,
|
| 557 |
+
**kwargs,
|
| 558 |
+
)
|
| 559 |
+
|
| 560 |
+
hidden_states = encoder_outputs.last_hidden_state
|
| 561 |
+
logits = self.ctc_head(hidden_states.transpose(1, 2)).transpose(1, 2)
|
| 562 |
+
|
| 563 |
+
loss = None
|
| 564 |
+
if labels is not None:
|
| 565 |
+
# retrieve loss input_lengths from attention_mask
|
| 566 |
+
attention_mask = (
|
| 567 |
+
attention_mask if attention_mask is not None else torch.ones_like(input_features, dtype=torch.long)
|
| 568 |
+
)
|
| 569 |
+
input_lengths = self._get_subsampling_output_length(attention_mask.sum(-1))
|
| 570 |
+
|
| 571 |
+
# assuming that padded tokens are filled with -100
|
| 572 |
+
# when not being attended to
|
| 573 |
+
labels_mask = labels != self.config.pad_token_id
|
| 574 |
+
target_lengths = labels_mask.sum(-1)
|
| 575 |
+
flattened_targets = labels.masked_select(labels_mask)
|
| 576 |
+
|
| 577 |
+
# ctc_loss doesn't support fp16
|
| 578 |
+
log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)
|
| 579 |
+
|
| 580 |
+
with torch.backends.cudnn.flags(enabled=False):
|
| 581 |
+
loss = nn.functional.ctc_loss(
|
| 582 |
+
log_probs,
|
| 583 |
+
flattened_targets,
|
| 584 |
+
input_lengths,
|
| 585 |
+
target_lengths,
|
| 586 |
+
blank=self.config.pad_token_id,
|
| 587 |
+
reduction=self.config.ctc_loss_reduction,
|
| 588 |
+
zero_infinity=self.config.ctc_zero_infinity,
|
| 589 |
+
)
|
| 590 |
+
|
| 591 |
+
return CausalLMOutput(
|
| 592 |
+
loss=loss,
|
| 593 |
+
logits=logits,
|
| 594 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 595 |
+
attentions=encoder_outputs.attentions,
|
| 596 |
+
)
|
| 597 |
+
|
| 598 |
+
@torch.no_grad()
|
| 599 |
+
def generate(
|
| 600 |
+
self,
|
| 601 |
+
input_features: torch.Tensor,
|
| 602 |
+
attention_mask: torch.Tensor | None = None,
|
| 603 |
+
return_dict_in_generate: bool = False,
|
| 604 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 605 |
+
) -> ParakeetGenerateOutput | torch.LongTensor:
|
| 606 |
+
r"""
|
| 607 |
+
Example:
|
| 608 |
+
|
| 609 |
+
```python
|
| 610 |
+
>>> from transformers import AutoProcessor, ParakeetForCTC
|
| 611 |
+
>>> from datasets import load_dataset, Audio
|
| 612 |
+
|
| 613 |
+
>>> model_id = "nvidia/parakeet-ctc-1.1b"
|
| 614 |
+
>>> processor = AutoProcessor.from_pretrained(model_id)
|
| 615 |
+
>>> model = ParakeetForCTC.from_pretrained(model_id)
|
| 616 |
+
|
| 617 |
+
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
| 618 |
+
>>> ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
|
| 619 |
+
|
| 620 |
+
>>> inputs = processor(ds[0]["audio"]["array"], text=ds[0]["text"])
|
| 621 |
+
>>> predicted_ids = model.generate(**inputs)
|
| 622 |
+
>>> transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)
|
| 623 |
+
|
| 624 |
+
>>> print(transcription)
|
| 625 |
+
```
|
| 626 |
+
"""
|
| 627 |
+
kwargs["return_dict"] = True
|
| 628 |
+
outputs: CausalLMOutput = self.forward(
|
| 629 |
+
input_features=input_features,
|
| 630 |
+
attention_mask=attention_mask,
|
| 631 |
+
**kwargs,
|
| 632 |
+
)
|
| 633 |
+
|
| 634 |
+
# greedy decoding
|
| 635 |
+
sequences = outputs.logits.argmax(dim=-1)
|
| 636 |
+
|
| 637 |
+
# mask out padded tokens
|
| 638 |
+
if attention_mask is not None:
|
| 639 |
+
attention_mask = self._get_output_attention_mask(attention_mask, target_length=sequences.shape[1])
|
| 640 |
+
sequences[~attention_mask] = self.config.pad_token_id
|
| 641 |
+
|
| 642 |
+
if return_dict_in_generate:
|
| 643 |
+
return ParakeetGenerateOutput(
|
| 644 |
+
sequences=sequences,
|
| 645 |
+
logits=outputs.logits,
|
| 646 |
+
attentions=outputs.attentions,
|
| 647 |
+
hidden_states=outputs.hidden_states,
|
| 648 |
+
)
|
| 649 |
+
|
| 650 |
+
return sequences
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
__all__ = ["ParakeetForCTC", "ParakeetEncoder", "ParakeetPreTrainedModel"]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/parakeet/processing_parakeet.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from ...audio_utils import AudioInput, make_list_of_audio
|
| 16 |
+
from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
|
| 17 |
+
from ...tokenization_utils_base import PreTokenizedInput, TextInput
|
| 18 |
+
from ...utils import auto_docstring, logging
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
logger = logging.get_logger(__name__)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class ParakeetProcessorKwargs(ProcessingKwargs, total=False):
|
| 25 |
+
_defaults = {
|
| 26 |
+
"audio_kwargs": {
|
| 27 |
+
"sampling_rate": 16000,
|
| 28 |
+
"padding": "longest",
|
| 29 |
+
"return_attention_mask": True,
|
| 30 |
+
},
|
| 31 |
+
"text_kwargs": {
|
| 32 |
+
"padding": True,
|
| 33 |
+
"padding_side": "right",
|
| 34 |
+
"add_special_tokens": False,
|
| 35 |
+
},
|
| 36 |
+
"common_kwargs": {"return_tensors": "pt"},
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@auto_docstring
|
| 41 |
+
class ParakeetProcessor(ProcessorMixin):
|
| 42 |
+
def __init__(self, feature_extractor, tokenizer):
|
| 43 |
+
super().__init__(feature_extractor, tokenizer)
|
| 44 |
+
|
| 45 |
+
@auto_docstring
|
| 46 |
+
def __call__(
|
| 47 |
+
self,
|
| 48 |
+
audio: AudioInput,
|
| 49 |
+
text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None,
|
| 50 |
+
sampling_rate: int | None = None,
|
| 51 |
+
**kwargs: Unpack[ParakeetProcessorKwargs],
|
| 52 |
+
):
|
| 53 |
+
r"""
|
| 54 |
+
sampling_rate (`int`, *optional*):
|
| 55 |
+
The sampling rate of the input audio in Hz. This should match the sampling rate expected by the feature
|
| 56 |
+
extractor (defaults to 16000 Hz). If provided, it will be validated against the processor's expected
|
| 57 |
+
sampling rate, and an error will be raised if they don't match. If not provided, a warning will be
|
| 58 |
+
issued and the default sampling rate will be assumed.
|
| 59 |
+
"""
|
| 60 |
+
audio = make_list_of_audio(audio)
|
| 61 |
+
|
| 62 |
+
output_kwargs = self._merge_kwargs(
|
| 63 |
+
ParakeetProcessorKwargs,
|
| 64 |
+
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
|
| 65 |
+
**kwargs,
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
if sampling_rate is None:
|
| 69 |
+
logger.warning_once(
|
| 70 |
+
f"You've provided audio without specifying the sampling rate. It will be assumed to be {output_kwargs['audio_kwargs']['sampling_rate']}, which can result in silent errors."
|
| 71 |
+
)
|
| 72 |
+
elif sampling_rate != output_kwargs["audio_kwargs"]["sampling_rate"]:
|
| 73 |
+
raise ValueError(
|
| 74 |
+
f"The sampling rate of the audio ({sampling_rate}) does not match the sampling rate of the processor ({output_kwargs['audio_kwargs']['sampling_rate']}). Please provide resampled the audio to the expected sampling rate."
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
if audio is not None:
|
| 78 |
+
inputs = self.feature_extractor(audio, **output_kwargs["audio_kwargs"])
|
| 79 |
+
if text is not None:
|
| 80 |
+
encodings = self.tokenizer(text, **output_kwargs["text_kwargs"])
|
| 81 |
+
|
| 82 |
+
if text is None:
|
| 83 |
+
return inputs
|
| 84 |
+
else:
|
| 85 |
+
inputs["labels"] = encodings["input_ids"]
|
| 86 |
+
return inputs
|
| 87 |
+
|
| 88 |
+
@property
|
| 89 |
+
def model_input_names(self):
|
| 90 |
+
feature_extractor_input_names = self.feature_extractor.model_input_names
|
| 91 |
+
return feature_extractor_input_names + ["labels"]
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
__all__ = ["ParakeetProcessor"]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/parakeet/tokenization_parakeet.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import itertools
|
| 16 |
+
|
| 17 |
+
from ...tokenization_utils_tokenizers import TokenizersBackend
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class ParakeetTokenizer(TokenizersBackend):
|
| 21 |
+
"""
|
| 22 |
+
Inherits all methods from [`PreTrainedTokenizerFast`]. Users should refer to this superclass for more information regarding those methods,
|
| 23 |
+
except for `_decode` which is overridden to adapt it to CTC decoding:
|
| 24 |
+
1. Group consecutive tokens
|
| 25 |
+
2. Filter out the blank token
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
def _decode(
|
| 29 |
+
self,
|
| 30 |
+
token_ids: int | list[int],
|
| 31 |
+
skip_special_tokens: bool = False,
|
| 32 |
+
clean_up_tokenization_spaces: bool | None = None,
|
| 33 |
+
group_tokens: bool = True,
|
| 34 |
+
**kwargs,
|
| 35 |
+
) -> str:
|
| 36 |
+
if isinstance(token_ids, int):
|
| 37 |
+
token_ids = [token_ids]
|
| 38 |
+
if group_tokens:
|
| 39 |
+
token_ids = [token_group[0] for token_group in itertools.groupby(token_ids)]
|
| 40 |
+
|
| 41 |
+
# for CTC we filter out the blank token, which is the pad token
|
| 42 |
+
token_ids = [token for token in token_ids if token != self.pad_token_id]
|
| 43 |
+
|
| 44 |
+
return super()._decode(
|
| 45 |
+
token_ids=token_ids,
|
| 46 |
+
skip_special_tokens=skip_special_tokens,
|
| 47 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
| 48 |
+
**kwargs,
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
__all__ = ["ParakeetTokenizer"]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/patchtsmixer/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_patchtsmixer import *
|
| 22 |
+
from .modeling_patchtsmixer import *
|
| 23 |
+
else:
|
| 24 |
+
import sys
|
| 25 |
+
|
| 26 |
+
_file = globals()["__file__"]
|
| 27 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/patchtsmixer/configuration_patchtsmixer.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 IBM and HuggingFace Inc. team. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""PatchTSMixer model configuration"""
|
| 15 |
+
|
| 16 |
+
from ...configuration_utils import PreTrainedConfig
|
| 17 |
+
from ...utils import logging
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
logger = logging.get_logger(__name__)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class PatchTSMixerConfig(PreTrainedConfig):
|
| 24 |
+
r"""
|
| 25 |
+
This is the configuration class to store the configuration of a [`PatchTSMixerModel`]. It is used to instantiate a
|
| 26 |
+
PatchTSMixer model according to the specified arguments, defining the model architecture. Instantiating a
|
| 27 |
+
configuration with the defaults will yield a similar configuration to that of the PatchTSMixer
|
| 28 |
+
[ibm/patchtsmixer-etth1-pretrain](https://huggingface.co/ibm/patchtsmixer-etth1-pretrain) architecture.
|
| 29 |
+
|
| 30 |
+
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
|
| 31 |
+
documentation from [`PreTrainedConfig`] for more information.
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
context_length (`int`, *optional*, defaults to 32):
|
| 35 |
+
The context/history length for the input sequence.
|
| 36 |
+
patch_length (`int`, *optional*, defaults to 8):
|
| 37 |
+
The patch length for the input sequence.
|
| 38 |
+
num_input_channels (`int`, *optional*, defaults to 1):
|
| 39 |
+
Number of input variates. For Univariate, set it to 1.
|
| 40 |
+
patch_stride (`int`, *optional*, defaults to 8):
|
| 41 |
+
Determines the overlap between two consecutive patches. Set it to patch_length (or greater), if we want
|
| 42 |
+
non-overlapping patches.
|
| 43 |
+
num_parallel_samples (`int`, *optional*, defaults to 100):
|
| 44 |
+
The number of samples to generate in parallel for probabilistic forecast.
|
| 45 |
+
d_model (`int`, *optional*, defaults to 8):
|
| 46 |
+
Hidden dimension of the model. Recommended to set it as a multiple of patch_length (i.e. 2-5X of
|
| 47 |
+
patch_length). Larger value indicates more complex model.
|
| 48 |
+
expansion_factor (`int`, *optional*, defaults to 2):
|
| 49 |
+
Expansion factor to use inside MLP. Recommended range is 2-5. Larger value indicates more complex model.
|
| 50 |
+
num_layers (`int`, *optional*, defaults to 3):
|
| 51 |
+
Number of layers to use. Recommended range is 3-15. Larger value indicates more complex model.
|
| 52 |
+
dropout (`float`, *optional*, defaults to 0.2):
|
| 53 |
+
The dropout probability the `PatchTSMixer` backbone. Recommended range is 0.2-0.7
|
| 54 |
+
mode (`str`, *optional*, defaults to `"common_channel"`):
|
| 55 |
+
Mixer Mode. Determines how to process the channels. Allowed values: "common_channel", "mix_channel". In
|
| 56 |
+
"common_channel" mode, we follow Channel-independent modelling with no explicit channel-mixing. Channel
|
| 57 |
+
mixing happens in an implicit manner via shared weights across channels. (preferred first approach) In
|
| 58 |
+
"mix_channel" mode, we follow explicit channel-mixing in addition to patch and feature mixer. (preferred
|
| 59 |
+
approach when channel correlations are very important to model)
|
| 60 |
+
gated_attn (`bool`, *optional*, defaults to `True`):
|
| 61 |
+
Enable Gated Attention.
|
| 62 |
+
norm_mlp (`str`, *optional*, defaults to `"LayerNorm"`):
|
| 63 |
+
Normalization layer (BatchNorm or LayerNorm).
|
| 64 |
+
self_attn (`bool`, *optional*, defaults to `False`):
|
| 65 |
+
Enable Tiny self attention across patches. This can be enabled when the output of Vanilla PatchTSMixer with
|
| 66 |
+
gated attention is not satisfactory. Enabling this leads to explicit pair-wise attention and modelling
|
| 67 |
+
across patches.
|
| 68 |
+
self_attn_heads (`int`, *optional*, defaults to 1):
|
| 69 |
+
Number of self-attention heads. Works only when `self_attn` is set to `True`.
|
| 70 |
+
use_positional_encoding (`bool`, *optional*, defaults to `False`):
|
| 71 |
+
Enable the use of positional embedding for the tiny self-attention layers. Works only when `self_attn` is
|
| 72 |
+
set to `True`.
|
| 73 |
+
positional_encoding_type (`str`, *optional*, defaults to `"sincos"`):
|
| 74 |
+
Positional encodings. Options `"random"` and `"sincos"` are supported. Works only when
|
| 75 |
+
`use_positional_encoding` is set to `True`
|
| 76 |
+
scaling (`string` or `bool`, *optional*, defaults to `"std"`):
|
| 77 |
+
Whether to scale the input targets via "mean" scaler, "std" scaler or no scaler if `None`. If `True`, the
|
| 78 |
+
scaler is set to "mean".
|
| 79 |
+
loss (`string`, *optional*, defaults to `"mse"`):
|
| 80 |
+
The loss function for the model corresponding to the `distribution_output` head. For parametric
|
| 81 |
+
distributions it is the negative log likelihood ("nll") and for point estimates it is the mean squared
|
| 82 |
+
error "mse".
|
| 83 |
+
init_std (`float`, *optional*, defaults to 0.02):
|
| 84 |
+
The standard deviation of the truncated normal weight initialization distribution.
|
| 85 |
+
norm_eps (`float`, *optional*, defaults to 1e-05):
|
| 86 |
+
A value added to the denominator for numerical stability of normalization.
|
| 87 |
+
mask_type (`str`, *optional*, defaults to `"random"`):
|
| 88 |
+
Type of masking to use for Masked Pretraining mode. Allowed values are "random", "forecast". In Random
|
| 89 |
+
masking, points are masked randomly. In Forecast masking, points are masked towards the end.
|
| 90 |
+
random_mask_ratio (`float`, *optional*, defaults to 0.5):
|
| 91 |
+
Masking ratio to use when `mask_type` is `random`. Higher value indicates more masking.
|
| 92 |
+
num_forecast_mask_patches (`int` or `list`, *optional*, defaults to `[2]`):
|
| 93 |
+
Number of patches to be masked at the end of each batch sample. If it is an integer, all the samples in the
|
| 94 |
+
batch will have the same number of masked patches. If it is a list, samples in the batch will be randomly
|
| 95 |
+
masked by numbers defined in the list. This argument is only used for forecast pretraining.
|
| 96 |
+
mask_value (`float`, *optional*, defaults to `0.0`):
|
| 97 |
+
Mask value to use.
|
| 98 |
+
masked_loss (`bool`, *optional*, defaults to `True`):
|
| 99 |
+
Whether to compute pretraining loss only at the masked portions, or on the entire output.
|
| 100 |
+
channel_consistent_masking (`bool`, *optional*, defaults to `True`):
|
| 101 |
+
When true, masking will be same across all channels of a timeseries. Otherwise, masking positions will vary
|
| 102 |
+
across channels.
|
| 103 |
+
unmasked_channel_indices (`list`, *optional*):
|
| 104 |
+
Channels that are not masked during pretraining.
|
| 105 |
+
head_dropout (`float`, *optional*, defaults to 0.2):
|
| 106 |
+
The dropout probability the `PatchTSMixer` head.
|
| 107 |
+
distribution_output (`string`, *optional*, defaults to `"student_t"`):
|
| 108 |
+
The distribution emission head for the model when loss is "nll". Could be either "student_t", "normal" or
|
| 109 |
+
"negative_binomial".
|
| 110 |
+
prediction_length (`int`, *optional*, defaults to 16):
|
| 111 |
+
Number of time steps to forecast for a forecasting task. Also known as the Forecast Horizon.
|
| 112 |
+
prediction_channel_indices (`list`, *optional*):
|
| 113 |
+
List of channel indices to forecast. If None, forecast all channels. Target data is expected to have all
|
| 114 |
+
channels and we explicitly filter the channels in prediction and target before loss computation.
|
| 115 |
+
num_targets (`int`, *optional*, defaults to 3):
|
| 116 |
+
Number of targets (dimensionality of the regressed variable) for a regression task.
|
| 117 |
+
output_range (`list`, *optional*):
|
| 118 |
+
Output range to restrict for the regression task. Defaults to None.
|
| 119 |
+
head_aggregation (`str`, *optional*, defaults to `"max_pool"`):
|
| 120 |
+
Aggregation mode to enable for classification or regression task. Allowed values are `None`, "use_last",
|
| 121 |
+
"max_pool", "avg_pool".
|
| 122 |
+
|
| 123 |
+
Example:
|
| 124 |
+
|
| 125 |
+
```python
|
| 126 |
+
>>> from transformers import PatchTSMixerConfig, PatchTSMixerModel
|
| 127 |
+
|
| 128 |
+
>>> # Initializing a default PatchTSMixer configuration
|
| 129 |
+
>>> configuration = PatchTSMixerConfig()
|
| 130 |
+
|
| 131 |
+
>>> # Randomly initializing a model (with random weights) from the configuration
|
| 132 |
+
>>> model = PatchTSMixerModel(configuration)
|
| 133 |
+
|
| 134 |
+
>>> # Accessing the model configuration
|
| 135 |
+
>>> configuration = model.config
|
| 136 |
+
```"""
|
| 137 |
+
|
| 138 |
+
model_type = "patchtsmixer"
|
| 139 |
+
attribute_map = {
|
| 140 |
+
"hidden_size": "d_model",
|
| 141 |
+
"num_hidden_layers": "num_layers",
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
def __init__(
|
| 145 |
+
self,
|
| 146 |
+
# Time series specific configuration
|
| 147 |
+
context_length: int = 32,
|
| 148 |
+
patch_length: int = 8,
|
| 149 |
+
num_input_channels: int = 1,
|
| 150 |
+
patch_stride: int = 8,
|
| 151 |
+
num_parallel_samples: int = 100,
|
| 152 |
+
# General model configuration
|
| 153 |
+
d_model: int = 8,
|
| 154 |
+
expansion_factor: int = 2,
|
| 155 |
+
num_layers: int = 3,
|
| 156 |
+
dropout: float = 0.2,
|
| 157 |
+
mode: str = "common_channel",
|
| 158 |
+
gated_attn: bool = True,
|
| 159 |
+
norm_mlp: str = "LayerNorm",
|
| 160 |
+
self_attn: bool = False,
|
| 161 |
+
self_attn_heads: int = 1,
|
| 162 |
+
use_positional_encoding: bool = False,
|
| 163 |
+
positional_encoding_type: str = "sincos",
|
| 164 |
+
scaling: str | bool | None = "std",
|
| 165 |
+
loss: str = "mse",
|
| 166 |
+
init_std: float = 0.02,
|
| 167 |
+
norm_eps: float = 1e-5,
|
| 168 |
+
# Pretrain model configuration
|
| 169 |
+
mask_type: str = "random",
|
| 170 |
+
random_mask_ratio: float = 0.5,
|
| 171 |
+
num_forecast_mask_patches: list[int] | int | None = [2],
|
| 172 |
+
mask_value: int = 0,
|
| 173 |
+
masked_loss: bool = True,
|
| 174 |
+
channel_consistent_masking: bool = True,
|
| 175 |
+
unmasked_channel_indices: list[int] | None = None,
|
| 176 |
+
# General head configuration
|
| 177 |
+
head_dropout: float = 0.2,
|
| 178 |
+
distribution_output: str = "student_t",
|
| 179 |
+
# Prediction head configuration
|
| 180 |
+
prediction_length: int = 16,
|
| 181 |
+
prediction_channel_indices: list | None = None,
|
| 182 |
+
# Classification/Regression configuration
|
| 183 |
+
num_targets: int = 3,
|
| 184 |
+
output_range: list | None = None,
|
| 185 |
+
head_aggregation: str = "max_pool",
|
| 186 |
+
**kwargs,
|
| 187 |
+
):
|
| 188 |
+
self.num_input_channels = num_input_channels
|
| 189 |
+
self.context_length = context_length
|
| 190 |
+
self.patch_length = patch_length
|
| 191 |
+
self.patch_stride = patch_stride
|
| 192 |
+
self.d_model = d_model
|
| 193 |
+
self.expansion_factor = expansion_factor
|
| 194 |
+
self.num_layers = num_layers
|
| 195 |
+
self.dropout = dropout
|
| 196 |
+
self.mode = mode
|
| 197 |
+
self.gated_attn = gated_attn
|
| 198 |
+
self.norm_mlp = norm_mlp
|
| 199 |
+
self.scaling = scaling
|
| 200 |
+
self.head_dropout = head_dropout
|
| 201 |
+
self.num_patches = (max(context_length, patch_length) - patch_length) // patch_stride + 1
|
| 202 |
+
self.mask_type = mask_type
|
| 203 |
+
self.random_mask_ratio = random_mask_ratio
|
| 204 |
+
self.num_forecast_mask_patches = num_forecast_mask_patches
|
| 205 |
+
self.mask_value = mask_value
|
| 206 |
+
self.channel_consistent_masking = channel_consistent_masking
|
| 207 |
+
self.masked_loss = masked_loss
|
| 208 |
+
self.patch_last = True
|
| 209 |
+
self.use_positional_encoding = use_positional_encoding
|
| 210 |
+
self.positional_encoding_type = positional_encoding_type
|
| 211 |
+
self.prediction_length = prediction_length
|
| 212 |
+
self.prediction_channel_indices = prediction_channel_indices
|
| 213 |
+
self.num_targets = num_targets
|
| 214 |
+
self.output_range = output_range
|
| 215 |
+
self.head_aggregation = head_aggregation
|
| 216 |
+
self.self_attn = self_attn
|
| 217 |
+
self.self_attn_heads = self_attn_heads
|
| 218 |
+
self.init_std = init_std
|
| 219 |
+
self.distribution_output = distribution_output
|
| 220 |
+
self.loss = loss
|
| 221 |
+
self.num_parallel_samples = num_parallel_samples
|
| 222 |
+
self.unmasked_channel_indices = unmasked_channel_indices
|
| 223 |
+
self.norm_eps = norm_eps
|
| 224 |
+
super().__init__(**kwargs)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
__all__ = ["PatchTSMixerConfig"]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/patchtsmixer/modeling_patchtsmixer.py
ADDED
|
@@ -0,0 +1,2122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 IBM and HuggingFace Inc. team. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""PyTorch PatchTSMixer model."""
|
| 15 |
+
|
| 16 |
+
import math
|
| 17 |
+
from collections.abc import Callable
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
import torch.nn as nn
|
| 22 |
+
|
| 23 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 24 |
+
from transformers.utils import ModelOutput
|
| 25 |
+
|
| 26 |
+
from ... import initialization as init
|
| 27 |
+
from ...modeling_flash_attention_utils import FlashAttentionKwargs
|
| 28 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
|
| 29 |
+
from ...processing_utils import Unpack
|
| 30 |
+
from ...time_series_utils import NegativeBinomialOutput, NormalOutput, StudentTOutput
|
| 31 |
+
from ...utils import TransformersKwargs, auto_docstring, logging
|
| 32 |
+
from .configuration_patchtsmixer import PatchTSMixerConfig
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
logger = logging.get_logger(__name__)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class PatchTSMixerGatedAttention(nn.Module):
|
| 39 |
+
"""
|
| 40 |
+
Module that applies gated attention to input data.
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
in_size (`int`): The input size.
|
| 44 |
+
out_size (`int`): The output size.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
def __init__(self, in_size: int, out_size: int):
|
| 48 |
+
super().__init__()
|
| 49 |
+
self.attn_layer = nn.Linear(in_size, out_size)
|
| 50 |
+
self.attn_softmax = nn.Softmax(dim=-1)
|
| 51 |
+
|
| 52 |
+
def forward(self, inputs):
|
| 53 |
+
attn_weight = self.attn_softmax(self.attn_layer(inputs))
|
| 54 |
+
inputs = inputs * attn_weight
|
| 55 |
+
return inputs
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# Copied from transformers.models.patchtst.modeling_patchtst.PatchTSTBatchNorm with PatchTST->PatchTSMixer
|
| 59 |
+
class PatchTSMixerBatchNorm(nn.Module):
|
| 60 |
+
"""
|
| 61 |
+
Compute batch normalization over the sequence length (time) dimension.
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
def __init__(self, config: PatchTSMixerConfig):
|
| 65 |
+
super().__init__()
|
| 66 |
+
self.batchnorm = nn.BatchNorm1d(config.d_model, eps=config.norm_eps)
|
| 67 |
+
|
| 68 |
+
def forward(self, inputs: torch.Tensor):
|
| 69 |
+
"""
|
| 70 |
+
Parameters:
|
| 71 |
+
inputs (`torch.Tensor` of shape `(batch_size, sequence_length, d_model)`):
|
| 72 |
+
input for Batch norm calculation
|
| 73 |
+
Returns:
|
| 74 |
+
`torch.Tensor` of shape `(batch_size, sequence_length, d_model)`
|
| 75 |
+
"""
|
| 76 |
+
output = inputs.transpose(1, 2) # output: (batch_size, d_model, sequence_length)
|
| 77 |
+
output = self.batchnorm(output)
|
| 78 |
+
return output.transpose(1, 2)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class PatchTSMixerPositionalEncoding(nn.Module):
|
| 82 |
+
"""
|
| 83 |
+
Class for positional encoding
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
def __init__(self, config: PatchTSMixerConfig):
|
| 87 |
+
super().__init__()
|
| 88 |
+
# positional encoding: [num_patches x d_model]
|
| 89 |
+
if config.use_positional_encoding:
|
| 90 |
+
self.position_enc = self._init_pe(config)
|
| 91 |
+
else:
|
| 92 |
+
self.position_enc = nn.Parameter(torch.zeros(config.num_patches, config.d_model))
|
| 93 |
+
|
| 94 |
+
@staticmethod
|
| 95 |
+
def _init_pe(config: PatchTSMixerConfig) -> nn.Parameter:
|
| 96 |
+
# Positional encoding
|
| 97 |
+
if config.positional_encoding_type == "random":
|
| 98 |
+
position_enc = nn.Parameter(torch.randn(config.num_patches, config.d_model), requires_grad=True)
|
| 99 |
+
elif config.positional_encoding_type == "sincos":
|
| 100 |
+
position_enc = torch.zeros(config.num_patches, config.d_model)
|
| 101 |
+
position = torch.arange(0, config.num_patches).unsqueeze(1)
|
| 102 |
+
div_term = torch.exp(torch.arange(0, config.d_model, 2) * -(math.log(10000.0) / config.d_model))
|
| 103 |
+
position_enc[:, 0::2] = torch.sin(position * div_term)
|
| 104 |
+
position_enc[:, 1::2] = torch.cos(position * div_term)
|
| 105 |
+
position_enc = position_enc - position_enc.mean()
|
| 106 |
+
position_enc = position_enc / (position_enc.std() * 10)
|
| 107 |
+
position_enc = nn.Parameter(position_enc, requires_grad=False)
|
| 108 |
+
else:
|
| 109 |
+
raise ValueError(
|
| 110 |
+
f"{config.positional_encoding_type} is not a valid positional encoder. Available types are 'random' and 'sincos'."
|
| 111 |
+
)
|
| 112 |
+
return position_enc
|
| 113 |
+
|
| 114 |
+
def forward(self, patch_input: torch.Tensor):
|
| 115 |
+
# hidden_state: [bs x num_channels x num_patches x d_model]
|
| 116 |
+
hidden_state = patch_input + self.position_enc
|
| 117 |
+
return hidden_state
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class PatchTSMixerNormLayer(nn.Module):
|
| 121 |
+
"""Normalization block
|
| 122 |
+
|
| 123 |
+
Args:
|
| 124 |
+
config (`PatchTSMixerConfig`):
|
| 125 |
+
Configuration.
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
def __init__(self, config: PatchTSMixerConfig):
|
| 129 |
+
super().__init__()
|
| 130 |
+
|
| 131 |
+
self.norm_mlp = config.norm_mlp
|
| 132 |
+
|
| 133 |
+
if "batch" in config.norm_mlp.lower():
|
| 134 |
+
self.norm = PatchTSMixerBatchNorm(config)
|
| 135 |
+
else:
|
| 136 |
+
self.norm = nn.LayerNorm(config.d_model, eps=config.norm_eps)
|
| 137 |
+
|
| 138 |
+
def forward(self, inputs: torch.Tensor):
|
| 139 |
+
"""
|
| 140 |
+
Args:
|
| 141 |
+
inputs (`torch.Tensor` of shape `((batch_size, num_channels, num_patches, d_model))`):
|
| 142 |
+
Input to the normalization layer.
|
| 143 |
+
Returns:
|
| 144 |
+
`torch.Tensor` of shape `((batch_size, num_channels, num_patches, d_model))`
|
| 145 |
+
"""
|
| 146 |
+
if "batch" in self.norm_mlp.lower():
|
| 147 |
+
# reshape the data
|
| 148 |
+
inputs_reshaped = torch.reshape(
|
| 149 |
+
inputs,
|
| 150 |
+
(
|
| 151 |
+
inputs.shape[0] * inputs.shape[1],
|
| 152 |
+
inputs.shape[2],
|
| 153 |
+
inputs.shape[3],
|
| 154 |
+
),
|
| 155 |
+
) # inputs_reshaped: [batch_size*num_channels, num_patches, d_model]
|
| 156 |
+
|
| 157 |
+
# inputs_reshaped: [batch_size*num_channels, num_patches, d_model]
|
| 158 |
+
inputs_reshaped = self.norm(inputs_reshaped)
|
| 159 |
+
|
| 160 |
+
# put back data to the original shape
|
| 161 |
+
inputs = torch.reshape(inputs_reshaped, inputs.shape)
|
| 162 |
+
|
| 163 |
+
else:
|
| 164 |
+
inputs = self.norm(inputs)
|
| 165 |
+
|
| 166 |
+
return inputs
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class PatchTSMixerMLP(nn.Module):
|
| 170 |
+
def __init__(self, in_features, out_features, config):
|
| 171 |
+
super().__init__()
|
| 172 |
+
num_hidden = in_features * config.expansion_factor
|
| 173 |
+
self.fc1 = nn.Linear(in_features, num_hidden)
|
| 174 |
+
self.dropout1 = nn.Dropout(config.dropout)
|
| 175 |
+
self.fc2 = nn.Linear(num_hidden, out_features)
|
| 176 |
+
self.dropout2 = nn.Dropout(config.dropout)
|
| 177 |
+
|
| 178 |
+
def forward(self, inputs: torch.Tensor):
|
| 179 |
+
"""
|
| 180 |
+
Args:
|
| 181 |
+
inputs (`torch.Tensor` of shape `((batch_size, num_channels, num_patches, d_model))`):
|
| 182 |
+
Input to the MLP layer.
|
| 183 |
+
Returns:
|
| 184 |
+
`torch.Tensor` of the same shape as `inputs`
|
| 185 |
+
"""
|
| 186 |
+
inputs = self.dropout1(nn.functional.gelu(self.fc1(inputs)))
|
| 187 |
+
inputs = self.fc2(inputs)
|
| 188 |
+
inputs = self.dropout2(inputs)
|
| 189 |
+
return inputs
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
class PatchTSMixerChannelFeatureMixerBlock(nn.Module):
|
| 193 |
+
"""This module mixes the features in the channel dimension.
|
| 194 |
+
|
| 195 |
+
Args:
|
| 196 |
+
config (`PatchTSMixerConfig`):
|
| 197 |
+
Configuration.
|
| 198 |
+
"""
|
| 199 |
+
|
| 200 |
+
def __init__(self, config: PatchTSMixerConfig):
|
| 201 |
+
super().__init__()
|
| 202 |
+
|
| 203 |
+
self.norm = PatchTSMixerNormLayer(config)
|
| 204 |
+
self.gated_attn = config.gated_attn
|
| 205 |
+
self.mlp = PatchTSMixerMLP(
|
| 206 |
+
in_features=config.num_input_channels,
|
| 207 |
+
out_features=config.num_input_channels,
|
| 208 |
+
config=config,
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
if config.gated_attn:
|
| 212 |
+
self.gating_block = PatchTSMixerGatedAttention(
|
| 213 |
+
in_size=config.num_input_channels, out_size=config.num_input_channels
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
def forward(self, inputs: torch.Tensor):
|
| 217 |
+
"""
|
| 218 |
+
Args:
|
| 219 |
+
inputs (`torch.Tensor` of shape `((batch_size, num_channels, num_patches, d_model))`):
|
| 220 |
+
input to the MLP layer
|
| 221 |
+
Returns:
|
| 222 |
+
`torch.Tensor` of the same shape as `inputs`
|
| 223 |
+
"""
|
| 224 |
+
residual = inputs
|
| 225 |
+
inputs = self.norm(inputs)
|
| 226 |
+
|
| 227 |
+
inputs = inputs.permute(0, 3, 2, 1)
|
| 228 |
+
|
| 229 |
+
if self.gated_attn:
|
| 230 |
+
inputs = self.gating_block(inputs)
|
| 231 |
+
|
| 232 |
+
inputs = self.mlp(inputs)
|
| 233 |
+
|
| 234 |
+
inputs = inputs.permute(0, 3, 2, 1)
|
| 235 |
+
|
| 236 |
+
out = inputs + residual
|
| 237 |
+
return out
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
# Copied from transformers.models.bert.modeling_bert.eager_attention_forward
|
| 241 |
+
def eager_attention_forward(
|
| 242 |
+
module: nn.Module,
|
| 243 |
+
query: torch.Tensor,
|
| 244 |
+
key: torch.Tensor,
|
| 245 |
+
value: torch.Tensor,
|
| 246 |
+
attention_mask: torch.Tensor | None,
|
| 247 |
+
scaling: float | None = None,
|
| 248 |
+
dropout: float = 0.0,
|
| 249 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 250 |
+
):
|
| 251 |
+
if scaling is None:
|
| 252 |
+
scaling = query.size(-1) ** -0.5
|
| 253 |
+
|
| 254 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 255 |
+
attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
|
| 256 |
+
|
| 257 |
+
if attention_mask is not None:
|
| 258 |
+
attn_weights = attn_weights + attention_mask
|
| 259 |
+
|
| 260 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 261 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 262 |
+
|
| 263 |
+
attn_output = torch.matmul(attn_weights, value)
|
| 264 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 265 |
+
|
| 266 |
+
return attn_output, attn_weights
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2Attention with Wav2Vec2->PatchTSMixer
|
| 270 |
+
class PatchTSMixerAttention(nn.Module):
|
| 271 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 272 |
+
|
| 273 |
+
def __init__(
|
| 274 |
+
self,
|
| 275 |
+
embed_dim: int,
|
| 276 |
+
num_heads: int,
|
| 277 |
+
dropout: float = 0.0,
|
| 278 |
+
is_decoder: bool = False,
|
| 279 |
+
bias: bool = True,
|
| 280 |
+
is_causal: bool = False,
|
| 281 |
+
config: PatchTSMixerConfig | None = None,
|
| 282 |
+
):
|
| 283 |
+
super().__init__()
|
| 284 |
+
self.embed_dim = embed_dim
|
| 285 |
+
self.num_heads = num_heads
|
| 286 |
+
self.dropout = dropout
|
| 287 |
+
self.head_dim = embed_dim // num_heads
|
| 288 |
+
self.config = config
|
| 289 |
+
|
| 290 |
+
if (self.head_dim * num_heads) != self.embed_dim:
|
| 291 |
+
raise ValueError(
|
| 292 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
|
| 293 |
+
f" and `num_heads`: {num_heads})."
|
| 294 |
+
)
|
| 295 |
+
self.scaling = self.head_dim**-0.5
|
| 296 |
+
self.is_decoder = is_decoder
|
| 297 |
+
self.is_causal = is_causal
|
| 298 |
+
|
| 299 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 300 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 301 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 302 |
+
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 303 |
+
|
| 304 |
+
def forward(
|
| 305 |
+
self,
|
| 306 |
+
hidden_states: torch.Tensor,
|
| 307 |
+
key_value_states: torch.Tensor | None = None,
|
| 308 |
+
attention_mask: torch.Tensor | None = None,
|
| 309 |
+
output_attentions: bool | None = False,
|
| 310 |
+
# TODO: we need a refactor so that the different attention modules can get their specific kwargs
|
| 311 |
+
# ATM, we have mixed things encoder, decoder, and encoder-decoder attn
|
| 312 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 313 |
+
) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
|
| 314 |
+
"""Input shape: Batch x Time x Channel"""
|
| 315 |
+
|
| 316 |
+
# if key_value_states are provided this layer is used as a cross-attention layer
|
| 317 |
+
# for the decoder
|
| 318 |
+
is_cross_attention = key_value_states is not None
|
| 319 |
+
|
| 320 |
+
# determine input shapes
|
| 321 |
+
bsz, tgt_len = hidden_states.shape[:-1]
|
| 322 |
+
src_len = key_value_states.shape[1] if is_cross_attention else tgt_len
|
| 323 |
+
|
| 324 |
+
q_input_shape = (bsz, tgt_len, -1, self.head_dim)
|
| 325 |
+
kv_input_shape = (bsz, src_len, -1, self.head_dim)
|
| 326 |
+
|
| 327 |
+
# get query proj
|
| 328 |
+
query_states = self.q_proj(hidden_states).view(*q_input_shape).transpose(1, 2)
|
| 329 |
+
|
| 330 |
+
current_states = key_value_states if is_cross_attention else hidden_states
|
| 331 |
+
key_states = self.k_proj(current_states).view(*kv_input_shape).transpose(1, 2)
|
| 332 |
+
value_states = self.v_proj(current_states).view(*kv_input_shape).transpose(1, 2)
|
| 333 |
+
|
| 334 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 335 |
+
self.config._attn_implementation, eager_attention_forward
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
attn_output, attn_weights = attention_interface(
|
| 339 |
+
self,
|
| 340 |
+
query_states,
|
| 341 |
+
key_states,
|
| 342 |
+
value_states,
|
| 343 |
+
attention_mask,
|
| 344 |
+
dropout=0.0 if not self.training else self.dropout,
|
| 345 |
+
scaling=self.scaling,
|
| 346 |
+
output_attentions=output_attentions,
|
| 347 |
+
**kwargs,
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
attn_output = attn_output.reshape(bsz, tgt_len, -1).contiguous()
|
| 351 |
+
attn_output = self.out_proj(attn_output)
|
| 352 |
+
|
| 353 |
+
return attn_output, attn_weights, None
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
class PatchMixerBlock(nn.Module):
|
| 357 |
+
"""This module mixes the patch dimension.
|
| 358 |
+
|
| 359 |
+
Args:
|
| 360 |
+
config (`PatchTSMixerConfig`):
|
| 361 |
+
Configuration.
|
| 362 |
+
"""
|
| 363 |
+
|
| 364 |
+
def __init__(self, config: PatchTSMixerConfig):
|
| 365 |
+
super().__init__()
|
| 366 |
+
|
| 367 |
+
self.norm = PatchTSMixerNormLayer(config)
|
| 368 |
+
|
| 369 |
+
self.self_attn = config.self_attn
|
| 370 |
+
self.gated_attn = config.gated_attn
|
| 371 |
+
|
| 372 |
+
self.mlp = PatchTSMixerMLP(
|
| 373 |
+
in_features=config.num_patches,
|
| 374 |
+
out_features=config.num_patches,
|
| 375 |
+
config=config,
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
if config.gated_attn:
|
| 379 |
+
self.gating_block = PatchTSMixerGatedAttention(in_size=config.num_patches, out_size=config.num_patches)
|
| 380 |
+
|
| 381 |
+
if config.self_attn:
|
| 382 |
+
self.self_attn_layer = PatchTSMixerAttention(
|
| 383 |
+
embed_dim=config.d_model,
|
| 384 |
+
num_heads=config.self_attn_heads,
|
| 385 |
+
dropout=config.dropout,
|
| 386 |
+
config=config,
|
| 387 |
+
)
|
| 388 |
+
self.norm_attn = PatchTSMixerNormLayer(config)
|
| 389 |
+
|
| 390 |
+
def forward(self, hidden_state):
|
| 391 |
+
"""
|
| 392 |
+
Args:
|
| 393 |
+
hidden_state (`torch.Tensor`): Input tensor.
|
| 394 |
+
|
| 395 |
+
Returns:
|
| 396 |
+
`torch.Tensor`: Transformed tensor.
|
| 397 |
+
"""
|
| 398 |
+
residual = hidden_state
|
| 399 |
+
|
| 400 |
+
hidden_state = self.norm(hidden_state)
|
| 401 |
+
|
| 402 |
+
if self.self_attn:
|
| 403 |
+
batch_size, n_vars, num_patches, d_model = hidden_state.shape
|
| 404 |
+
hidden_state_reshaped = hidden_state.reshape(batch_size * n_vars, num_patches, d_model)
|
| 405 |
+
|
| 406 |
+
x_attn, _, _ = self.self_attn_layer(hidden_state_reshaped, output_attentions=False)
|
| 407 |
+
x_attn = x_attn.reshape(batch_size, n_vars, num_patches, d_model)
|
| 408 |
+
|
| 409 |
+
# Transpose so that num_patches is the last dimension
|
| 410 |
+
hidden_state = hidden_state.transpose(2, 3)
|
| 411 |
+
hidden_state = self.mlp(hidden_state)
|
| 412 |
+
|
| 413 |
+
if self.gated_attn:
|
| 414 |
+
hidden_state = self.gating_block(hidden_state)
|
| 415 |
+
|
| 416 |
+
# Transpose back
|
| 417 |
+
hidden_state = hidden_state.transpose(2, 3)
|
| 418 |
+
|
| 419 |
+
if self.self_attn:
|
| 420 |
+
hidden_state = self.norm_attn(hidden_state + x_attn)
|
| 421 |
+
|
| 422 |
+
out = hidden_state + residual
|
| 423 |
+
return out
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
class FeatureMixerBlock(nn.Module):
|
| 427 |
+
"""This module mixes the hidden feature dimension.
|
| 428 |
+
|
| 429 |
+
Args:
|
| 430 |
+
config (`PatchTSMixerConfig`):
|
| 431 |
+
Configuration.
|
| 432 |
+
|
| 433 |
+
"""
|
| 434 |
+
|
| 435 |
+
def __init__(self, config: PatchTSMixerConfig):
|
| 436 |
+
super().__init__()
|
| 437 |
+
|
| 438 |
+
self.norm = PatchTSMixerNormLayer(config)
|
| 439 |
+
|
| 440 |
+
self.gated_attn = config.gated_attn
|
| 441 |
+
|
| 442 |
+
self.mlp = PatchTSMixerMLP(
|
| 443 |
+
in_features=config.d_model,
|
| 444 |
+
out_features=config.d_model,
|
| 445 |
+
config=config,
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
if config.gated_attn:
|
| 449 |
+
self.gating_block = PatchTSMixerGatedAttention(in_size=config.d_model, out_size=config.d_model)
|
| 450 |
+
|
| 451 |
+
def forward(self, hidden: torch.Tensor):
|
| 452 |
+
"""
|
| 453 |
+
Args:
|
| 454 |
+
hidden (`torch.Tensor` of shape `(batch_size, num_patches, d_model)`):
|
| 455 |
+
Input tensor to the layer.
|
| 456 |
+
|
| 457 |
+
Returns:
|
| 458 |
+
`torch.Tensor`: Transformed tensor.
|
| 459 |
+
"""
|
| 460 |
+
residual = hidden
|
| 461 |
+
hidden = self.norm(hidden)
|
| 462 |
+
hidden = self.mlp(hidden)
|
| 463 |
+
|
| 464 |
+
if self.gated_attn:
|
| 465 |
+
hidden = self.gating_block(hidden)
|
| 466 |
+
|
| 467 |
+
out = hidden + residual
|
| 468 |
+
return out
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
class PatchTSMixerLayer(nn.Module):
|
| 472 |
+
"""
|
| 473 |
+
The `PatchTSMixer` layer that does all three kinds of mixing.
|
| 474 |
+
|
| 475 |
+
Args:
|
| 476 |
+
config (`PatchTSMixerConfig`):
|
| 477 |
+
Configuration.
|
| 478 |
+
|
| 479 |
+
"""
|
| 480 |
+
|
| 481 |
+
def __init__(self, config: PatchTSMixerConfig):
|
| 482 |
+
super().__init__()
|
| 483 |
+
|
| 484 |
+
self.patch_mixer = PatchMixerBlock(config=config)
|
| 485 |
+
self.feature_mixer = FeatureMixerBlock(config=config)
|
| 486 |
+
|
| 487 |
+
self.mode = config.mode
|
| 488 |
+
|
| 489 |
+
if config.mode == "mix_channel":
|
| 490 |
+
self.channel_feature_mixer = PatchTSMixerChannelFeatureMixerBlock(config=config)
|
| 491 |
+
|
| 492 |
+
def forward(self, hidden: torch.Tensor):
|
| 493 |
+
"""
|
| 494 |
+
Args:
|
| 495 |
+
hidden (`torch.Tensor` of shape `(batch_size, num_patches, d_model)`):
|
| 496 |
+
Input tensor to the layer.
|
| 497 |
+
|
| 498 |
+
Returns:
|
| 499 |
+
`torch.Tensor`: Transformed tensor.
|
| 500 |
+
"""
|
| 501 |
+
if self.mode == "mix_channel":
|
| 502 |
+
hidden = self.channel_feature_mixer(hidden)
|
| 503 |
+
|
| 504 |
+
hidden = self.patch_mixer(hidden)
|
| 505 |
+
hidden = self.feature_mixer(hidden) # hidden: (batch_size x num_patches x d_model)
|
| 506 |
+
return hidden
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
class PatchTSMixerBlock(nn.Module):
|
| 510 |
+
"""The main computing framework of the `PatchTSMixer` model.
|
| 511 |
+
|
| 512 |
+
Args:
|
| 513 |
+
config (`PatchTSMixerConfig`):
|
| 514 |
+
Configuration.
|
| 515 |
+
"""
|
| 516 |
+
|
| 517 |
+
def __init__(self, config: PatchTSMixerConfig):
|
| 518 |
+
super().__init__()
|
| 519 |
+
|
| 520 |
+
num_layers = config.num_layers
|
| 521 |
+
|
| 522 |
+
self.mixers = nn.ModuleList([PatchTSMixerLayer(config=config) for _ in range(num_layers)])
|
| 523 |
+
|
| 524 |
+
def forward(self, hidden_state, output_hidden_states: bool = False):
|
| 525 |
+
"""
|
| 526 |
+
Args:
|
| 527 |
+
hidden_state (`torch.Tensor`): The input tensor.
|
| 528 |
+
output_hidden_states (`bool`, *optional*, defaults to False.):
|
| 529 |
+
Whether to output the hidden states as well.
|
| 530 |
+
|
| 531 |
+
Returns:
|
| 532 |
+
`torch.Tensor`: The embedding. `list`: List of all hidden states if `output_hidden_states` is set to
|
| 533 |
+
`True`.
|
| 534 |
+
"""
|
| 535 |
+
all_hidden_states = []
|
| 536 |
+
|
| 537 |
+
embedding = hidden_state
|
| 538 |
+
|
| 539 |
+
for mod in self.mixers:
|
| 540 |
+
embedding = mod(embedding)
|
| 541 |
+
if output_hidden_states:
|
| 542 |
+
all_hidden_states.append(embedding)
|
| 543 |
+
|
| 544 |
+
if output_hidden_states:
|
| 545 |
+
return embedding, all_hidden_states
|
| 546 |
+
else:
|
| 547 |
+
return embedding, None
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
class PatchTSMixerForPredictionHead(nn.Module):
|
| 551 |
+
"""Prediction Head for Forecasting
|
| 552 |
+
|
| 553 |
+
Args:
|
| 554 |
+
config (`PatchTSMixerConfig`):
|
| 555 |
+
Configuration.
|
| 556 |
+
"""
|
| 557 |
+
|
| 558 |
+
def __init__(self, config: PatchTSMixerConfig, distribution_output=None):
|
| 559 |
+
super().__init__()
|
| 560 |
+
|
| 561 |
+
self.prediction_channel_indices = config.prediction_channel_indices
|
| 562 |
+
|
| 563 |
+
if self.prediction_channel_indices is not None:
|
| 564 |
+
self.prediction_channel_indices.sort()
|
| 565 |
+
|
| 566 |
+
self.dropout_layer = nn.Dropout(config.head_dropout)
|
| 567 |
+
if distribution_output is None:
|
| 568 |
+
self.base_forecast_block = nn.Linear((config.num_patches * config.d_model), config.prediction_length)
|
| 569 |
+
else:
|
| 570 |
+
self.base_forecast_block = distribution_output.get_parameter_projection(
|
| 571 |
+
config.num_patches * config.d_model
|
| 572 |
+
)
|
| 573 |
+
|
| 574 |
+
self.flatten = nn.Flatten(start_dim=-2)
|
| 575 |
+
|
| 576 |
+
def forward(self, hidden_features):
|
| 577 |
+
"""
|
| 578 |
+
|
| 579 |
+
Args:
|
| 580 |
+
hidden_features (`torch.Tensor` of shape `(batch_size, num_patch, d_model)` in `flatten` mode
|
| 581 |
+
or `(batch_size, n_vars, num_patch, d_model)` in `common_channel`/`mix_channel` mode.): Input hidden
|
| 582 |
+
features.
|
| 583 |
+
|
| 584 |
+
Returns:
|
| 585 |
+
`torch.Tensor` of shape `(batch_size, prediction_length, nvars)`.
|
| 586 |
+
|
| 587 |
+
"""
|
| 588 |
+
|
| 589 |
+
hidden_features = self.flatten(hidden_features) # [batch_size x n_vars x num_patch * d_model]
|
| 590 |
+
hidden_features = self.dropout_layer(hidden_features) # [batch_size x n_vars x num_patch * d_model]
|
| 591 |
+
forecast = self.base_forecast_block(hidden_features) # [batch_size x n_vars x prediction_length]
|
| 592 |
+
if isinstance(forecast, tuple):
|
| 593 |
+
forecast = tuple(z.transpose(-1, -2) for z in forecast)
|
| 594 |
+
else:
|
| 595 |
+
forecast = forecast.transpose(-1, -2) # [batch_size x prediction_length x n_vars]
|
| 596 |
+
|
| 597 |
+
if self.prediction_channel_indices is not None:
|
| 598 |
+
if isinstance(forecast, tuple):
|
| 599 |
+
forecast = tuple(z[..., self.prediction_channel_indices] for z in forecast)
|
| 600 |
+
else:
|
| 601 |
+
forecast = forecast[..., self.prediction_channel_indices] # [batch_size x prediction_length x n_vars]
|
| 602 |
+
|
| 603 |
+
return forecast
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
class PatchTSMixerLinearHead(nn.Module):
|
| 607 |
+
"""Linear head for Classification and Regression.
|
| 608 |
+
|
| 609 |
+
Args:
|
| 610 |
+
config (`PatchTSMixerConfig`):
|
| 611 |
+
Configuration.
|
| 612 |
+
"""
|
| 613 |
+
|
| 614 |
+
def __init__(self, config: PatchTSMixerConfig, distribution_output=None):
|
| 615 |
+
super().__init__()
|
| 616 |
+
|
| 617 |
+
self.head_aggregation = config.head_aggregation
|
| 618 |
+
self.output_range = config.output_range
|
| 619 |
+
|
| 620 |
+
if config.head_aggregation is None:
|
| 621 |
+
mul_factor = config.num_patches
|
| 622 |
+
else:
|
| 623 |
+
mul_factor = 1
|
| 624 |
+
self.distribution_output = distribution_output
|
| 625 |
+
if distribution_output is None:
|
| 626 |
+
self.projection = nn.Linear(
|
| 627 |
+
config.d_model * config.num_input_channels * mul_factor,
|
| 628 |
+
config.num_targets,
|
| 629 |
+
)
|
| 630 |
+
else:
|
| 631 |
+
self.projection = distribution_output.get_parameter_projection(
|
| 632 |
+
config.d_model * config.num_input_channels * mul_factor
|
| 633 |
+
)
|
| 634 |
+
|
| 635 |
+
if config.head_aggregation is None:
|
| 636 |
+
self.flatten = nn.Flatten(start_dim=-3)
|
| 637 |
+
else:
|
| 638 |
+
self.flatten = nn.Flatten(start_dim=-2)
|
| 639 |
+
|
| 640 |
+
self.dropout = nn.Dropout(config.head_dropout)
|
| 641 |
+
|
| 642 |
+
def forward(self, hidden_features):
|
| 643 |
+
"""
|
| 644 |
+
Args:
|
| 645 |
+
hidden_features (`torch.Tensor` of shape `(batch_size x num_patch x d_model)` in `flatten` mode
|
| 646 |
+
or `(batch_size x n_vars x num_patch x d_model)` in `common_channel`/`mix_channel` mode.): Input hidden
|
| 647 |
+
features.
|
| 648 |
+
|
| 649 |
+
Returns:
|
| 650 |
+
`torch.Tensor` of shape `(batch_size x num_targets)`.
|
| 651 |
+
"""
|
| 652 |
+
|
| 653 |
+
# batch_size x d_model x num_patch or batch_size x n_vars x d_model x num_patch
|
| 654 |
+
hidden_features = hidden_features.transpose(-1, -2)
|
| 655 |
+
if self.head_aggregation == "use_last":
|
| 656 |
+
# batch_size x d_model (flatten) or # batch_size x n_vars x d_model (common_channel)
|
| 657 |
+
hidden_features = hidden_features[..., -1]
|
| 658 |
+
elif self.head_aggregation == "max_pool":
|
| 659 |
+
# batch_size x n_vars x d_model or batch_size x d_model
|
| 660 |
+
hidden_features = hidden_features.max(dim=-1).values
|
| 661 |
+
elif self.head_aggregation == "avg_pool":
|
| 662 |
+
# batch_size x n_vars x d_model or batch_size x d_model
|
| 663 |
+
hidden_features = hidden_features.mean(dim=-1)
|
| 664 |
+
|
| 665 |
+
if self.flatten:
|
| 666 |
+
hidden_features = self.flatten(hidden_features)
|
| 667 |
+
hidden_features = self.dropout(hidden_features)
|
| 668 |
+
hidden_features = self.projection(hidden_features) # batch_size x num_targets
|
| 669 |
+
|
| 670 |
+
if (self.distribution_output is None) and (self.output_range is not None):
|
| 671 |
+
hidden_features = (
|
| 672 |
+
torch.sigmoid(hidden_features) * (self.output_range[1] - self.output_range[0]) + self.output_range[0]
|
| 673 |
+
)
|
| 674 |
+
return hidden_features
|
| 675 |
+
|
| 676 |
+
|
| 677 |
+
@auto_docstring
|
| 678 |
+
class PatchTSMixerPreTrainedModel(PreTrainedModel):
|
| 679 |
+
# Weight initialization
|
| 680 |
+
config: PatchTSMixerConfig
|
| 681 |
+
base_model_prefix = "model"
|
| 682 |
+
main_input_name = "past_values"
|
| 683 |
+
input_modalities = ("time",)
|
| 684 |
+
supports_gradient_checkpointing = False
|
| 685 |
+
|
| 686 |
+
@torch.no_grad()
|
| 687 |
+
def _init_weights(self, module):
|
| 688 |
+
"""Initialize weights"""
|
| 689 |
+
if isinstance(module, PatchTSMixerPositionalEncoding):
|
| 690 |
+
# initialize positional encoding
|
| 691 |
+
if self.config.positional_encoding_type == "random":
|
| 692 |
+
init.normal_(module.position_enc, mean=0.0, std=0.1)
|
| 693 |
+
elif isinstance(module, (nn.LayerNorm, nn.BatchNorm1d)):
|
| 694 |
+
init.zeros_(module.bias)
|
| 695 |
+
init.ones_(module.weight)
|
| 696 |
+
if getattr(module, "running_mean", None) is not None:
|
| 697 |
+
init.zeros_(module.running_mean)
|
| 698 |
+
init.ones_(module.running_var)
|
| 699 |
+
init.zeros_(module.num_batches_tracked)
|
| 700 |
+
elif isinstance(module, PatchTSMixerBatchNorm):
|
| 701 |
+
init.zeros_(module.batchnorm.bias)
|
| 702 |
+
init.ones_(module.batchnorm.weight)
|
| 703 |
+
elif isinstance(module, nn.Linear):
|
| 704 |
+
init.normal_(module.weight, mean=0.0, std=self.config.init_std)
|
| 705 |
+
if module.bias is not None:
|
| 706 |
+
init.zeros_(module.bias)
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
class PatchTSMixerPretrainHead(nn.Module):
|
| 710 |
+
"""Pretraining head.
|
| 711 |
+
|
| 712 |
+
Args:
|
| 713 |
+
config (`PatchTSMixerConfig`):
|
| 714 |
+
Configuration.
|
| 715 |
+
"""
|
| 716 |
+
|
| 717 |
+
def __init__(self, config: PatchTSMixerConfig):
|
| 718 |
+
super().__init__()
|
| 719 |
+
|
| 720 |
+
self.dropout_layer = nn.Dropout(config.head_dropout)
|
| 721 |
+
self.base_pt_block = nn.Linear(config.d_model, config.patch_length)
|
| 722 |
+
|
| 723 |
+
def forward(self, hidden_features):
|
| 724 |
+
"""
|
| 725 |
+
Args:
|
| 726 |
+
hidden_features (`torch.Tensor` of shape `(batch_size x num_patch x d_model)` in `flatten` mode
|
| 727 |
+
or `(batch_size x n_vars x num_patch x d_model)` in `common_channel`/`mix_channel` mode.): Input hidden
|
| 728 |
+
features.
|
| 729 |
+
|
| 730 |
+
Returns:
|
| 731 |
+
`torch.Tensor` of shape `(batch_size x n_vars x num_patch x patch_length)`.
|
| 732 |
+
"""
|
| 733 |
+
|
| 734 |
+
hidden_features = self.dropout_layer(hidden_features)
|
| 735 |
+
forecast = self.base_pt_block(hidden_features) # [batch_size x n_vars x num_patch x patch_length]
|
| 736 |
+
return forecast
|
| 737 |
+
|
| 738 |
+
|
| 739 |
+
# Copied from transformers.models.patchtst.modeling_patchtst.random_masking
|
| 740 |
+
def random_masking(
|
| 741 |
+
inputs: torch.Tensor,
|
| 742 |
+
mask_ratio: float,
|
| 743 |
+
unmasked_channel_indices: list | None = None,
|
| 744 |
+
channel_consistent_masking: bool = False,
|
| 745 |
+
mask_value: int = 0,
|
| 746 |
+
):
|
| 747 |
+
"""random_masking: Mask the input considering the control variables.
|
| 748 |
+
|
| 749 |
+
Args:
|
| 750 |
+
inputs (`torch.Tensor` of shape `(batch_size, num_channels, sequence_length, num_features)`):
|
| 751 |
+
The input tensor to mask.
|
| 752 |
+
mask_ratio (`float`):
|
| 753 |
+
Masking ratio applied to mask the input data during random pretraining. It is the number between 0 and 1.
|
| 754 |
+
unmasked_channel_indices (list, *optional*):
|
| 755 |
+
Indices of channels that will not be masked.
|
| 756 |
+
channel_consistent_masking (bool, *optional*, defaults to `False`):
|
| 757 |
+
When true, masking will be same across all channels of a timeseries. Otherwise, masking positions will vary
|
| 758 |
+
across channels.
|
| 759 |
+
mask_value (int, *optional*, defaults to 0):
|
| 760 |
+
Define the value of masked patches for pretraining.
|
| 761 |
+
|
| 762 |
+
Returns:
|
| 763 |
+
`tuple(torch.Tensor)`: inputs_mask, masked input, same shape as input Tensor and mask tensor of shape [bs x c x
|
| 764 |
+
n]
|
| 765 |
+
"""
|
| 766 |
+
if mask_ratio < 0 or mask_ratio >= 1:
|
| 767 |
+
raise ValueError(f"Mask ratio {mask_ratio} has to be between 0 and 1.")
|
| 768 |
+
|
| 769 |
+
batch_size, num_channels, sequence_length, num_features = inputs.shape
|
| 770 |
+
device = inputs.device
|
| 771 |
+
|
| 772 |
+
len_keep = int(sequence_length * (1 - mask_ratio))
|
| 773 |
+
|
| 774 |
+
if channel_consistent_masking:
|
| 775 |
+
noise = torch.rand(batch_size, 1, sequence_length, device=device) # noise in [0, 1], bs x 1 x L
|
| 776 |
+
noise = noise.repeat(1, num_channels, 1) # bs x num_channels x time
|
| 777 |
+
else:
|
| 778 |
+
# noise in [0, 1], bs x num_channels x L
|
| 779 |
+
noise = torch.rand(batch_size, num_channels, sequence_length, device=device)
|
| 780 |
+
|
| 781 |
+
# mask: [bs x num_channels x num_patch]
|
| 782 |
+
mask = torch.ones(batch_size, num_channels, sequence_length, device=device)
|
| 783 |
+
mask[:, :, :len_keep] = 0
|
| 784 |
+
|
| 785 |
+
# sort noise for each sample
|
| 786 |
+
ids_shuffle = torch.argsort(noise, dim=-1) # ascend: small is keep, large is remove
|
| 787 |
+
ids_restore = torch.argsort(ids_shuffle, dim=-1) # ids_restore: [bs x num_channels x L]
|
| 788 |
+
|
| 789 |
+
mask = torch.gather(mask, dim=-1, index=ids_restore)
|
| 790 |
+
mask = mask.unsqueeze(-1).repeat(1, 1, 1, num_features) # mask: [bs x num_channels x num_patches x patch_length]
|
| 791 |
+
if unmasked_channel_indices is not None:
|
| 792 |
+
mask[:, unmasked_channel_indices, :, :] = 0
|
| 793 |
+
|
| 794 |
+
inputs_mask = inputs.masked_fill(mask.bool(), mask_value)
|
| 795 |
+
return inputs_mask, mask[..., 0]
|
| 796 |
+
|
| 797 |
+
|
| 798 |
+
# Copied from transformers.models.patchtst.modeling_patchtst.forecast_masking
|
| 799 |
+
def forecast_masking(
|
| 800 |
+
inputs: torch.Tensor,
|
| 801 |
+
num_forecast_mask_patches: list | int,
|
| 802 |
+
unmasked_channel_indices: list | None = None,
|
| 803 |
+
mask_value: int = 0,
|
| 804 |
+
):
|
| 805 |
+
"""Forecast masking that masks the last K patches where K is from the num_forecast_mask_patches.
|
| 806 |
+
If num_forecast_mask_patches is a list, samples in the batch will be randomly masked by numbers defined in the list.
|
| 807 |
+
|
| 808 |
+
Parameters:
|
| 809 |
+
inputs (`torch.Tensor`):
|
| 810 |
+
Input of shape `(bs, num_channels, num_patch, patch_length)`
|
| 811 |
+
num_forecast_mask_patches (`list`):
|
| 812 |
+
Number of patches to be masked at the end of each batch sample. e.g. 4 or [3, 5].
|
| 813 |
+
unmasked_channel_indices (`list`, *optional*):
|
| 814 |
+
Indices of channels that are not masked.
|
| 815 |
+
mask_value (`int`, *optional*, defaults to 0):
|
| 816 |
+
Values in the masked patches will be filled by `mask_value`.
|
| 817 |
+
|
| 818 |
+
Returns:
|
| 819 |
+
`tuple(torch.Tensor)`: inputs_mask, masked input, same shape as inputs Tensor and Mask tensor of shape `(bs,
|
| 820 |
+
num_channels , num_patch)` or `(bs, tsg1, tsg2, num_channels, num_patch)`
|
| 821 |
+
"""
|
| 822 |
+
|
| 823 |
+
if isinstance(num_forecast_mask_patches, int):
|
| 824 |
+
num_forecast_mask_patches = [num_forecast_mask_patches]
|
| 825 |
+
forecast_mask_ratios = [1 for _ in num_forecast_mask_patches]
|
| 826 |
+
|
| 827 |
+
batch_size, num_channels, sequence_length, num_features = inputs.shape
|
| 828 |
+
mask = torch.zeros(batch_size, num_channels, sequence_length, device=inputs.device)
|
| 829 |
+
|
| 830 |
+
t_list = []
|
| 831 |
+
total_length = 0
|
| 832 |
+
total_ratio = sum(forecast_mask_ratios)
|
| 833 |
+
|
| 834 |
+
for patch_length, ratio in zip(num_forecast_mask_patches, forecast_mask_ratios):
|
| 835 |
+
if patch_length <= 0 or patch_length >= sequence_length:
|
| 836 |
+
raise ValueError(
|
| 837 |
+
f"num_forecast_mask_patches {patch_length} should be greater than 0 and less than total patches."
|
| 838 |
+
)
|
| 839 |
+
temp_len = int(batch_size * ratio / total_ratio)
|
| 840 |
+
t_list.append([patch_length, ratio, temp_len])
|
| 841 |
+
total_length += temp_len
|
| 842 |
+
|
| 843 |
+
t_list = sorted(t_list, key=lambda x: x[2])
|
| 844 |
+
|
| 845 |
+
if total_length < batch_size:
|
| 846 |
+
t_list[0][2] = t_list[0][2] + (batch_size - total_length)
|
| 847 |
+
elif total_length > batch_size:
|
| 848 |
+
t_list[-1][2] = t_list[-1][2] + (total_length - batch_size)
|
| 849 |
+
|
| 850 |
+
batch1 = 0
|
| 851 |
+
for patch_len, _, temp_len in t_list:
|
| 852 |
+
batch2 = batch1 + temp_len
|
| 853 |
+
mask[batch1:batch2, :, -patch_len:] = 1
|
| 854 |
+
batch1 = batch2
|
| 855 |
+
|
| 856 |
+
perm = torch.randperm(mask.shape[0])
|
| 857 |
+
mask = mask[perm]
|
| 858 |
+
|
| 859 |
+
mask = mask.unsqueeze(-1).repeat(1, 1, 1, num_features) # mask: [bs x num_channels x num_patch x patch_len]
|
| 860 |
+
if unmasked_channel_indices is not None:
|
| 861 |
+
mask[:, unmasked_channel_indices, :, :] = 0
|
| 862 |
+
|
| 863 |
+
inputs_mask = inputs.masked_fill(mask.bool(), mask_value)
|
| 864 |
+
return inputs_mask, mask[..., 0]
|
| 865 |
+
|
| 866 |
+
|
| 867 |
+
# Copied from transformers.models.patchtst.modeling_patchtst.PatchTSTPatchify with PatchTST->PatchTSMixer
|
| 868 |
+
class PatchTSMixerPatchify(nn.Module):
|
| 869 |
+
"""
|
| 870 |
+
A class to patchify the time series sequence into different patches
|
| 871 |
+
|
| 872 |
+
Returns:
|
| 873 |
+
`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`
|
| 874 |
+
"""
|
| 875 |
+
|
| 876 |
+
def __init__(self, config: PatchTSMixerConfig):
|
| 877 |
+
super().__init__()
|
| 878 |
+
|
| 879 |
+
self.sequence_length = config.context_length
|
| 880 |
+
self.patch_length = config.patch_length
|
| 881 |
+
self.patch_stride = config.patch_stride
|
| 882 |
+
|
| 883 |
+
if self.sequence_length <= self.patch_length:
|
| 884 |
+
raise ValueError(
|
| 885 |
+
f"Sequence length ({self.sequence_length}) has to be greater than the patch length ({self.patch_length})"
|
| 886 |
+
)
|
| 887 |
+
|
| 888 |
+
# get the number of patches
|
| 889 |
+
self.num_patches = (max(self.sequence_length, self.patch_length) - self.patch_length) // self.patch_stride + 1
|
| 890 |
+
new_sequence_length = self.patch_length + self.patch_stride * (self.num_patches - 1)
|
| 891 |
+
self.sequence_start = self.sequence_length - new_sequence_length
|
| 892 |
+
|
| 893 |
+
def forward(self, past_values: torch.Tensor):
|
| 894 |
+
"""
|
| 895 |
+
Parameters:
|
| 896 |
+
past_values (`torch.Tensor` of shape `(batch_size, sequence_length, num_channels)`, *required*):
|
| 897 |
+
Input for patchification
|
| 898 |
+
|
| 899 |
+
Returns:
|
| 900 |
+
`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`
|
| 901 |
+
"""
|
| 902 |
+
sequence_length = past_values.shape[-2]
|
| 903 |
+
if sequence_length != self.sequence_length:
|
| 904 |
+
raise ValueError(
|
| 905 |
+
f"Input sequence length ({sequence_length}) doesn't match model configuration ({self.sequence_length})."
|
| 906 |
+
)
|
| 907 |
+
# output: [bs x new_sequence_length x num_channels]
|
| 908 |
+
output = past_values[:, self.sequence_start :, :]
|
| 909 |
+
# output: [bs x num_patches x num_input_channels x patch_length]
|
| 910 |
+
output = output.unfold(dimension=-2, size=self.patch_length, step=self.patch_stride)
|
| 911 |
+
# output: [bs x num_input_channels x num_patches x patch_length]
|
| 912 |
+
output = output.transpose(-2, -3).contiguous()
|
| 913 |
+
return output
|
| 914 |
+
|
| 915 |
+
|
| 916 |
+
# Copied from transformers.models.patchtst.modeling_patchtst.PatchTSTMasking with PatchTST->PatchTSMixer
|
| 917 |
+
class PatchTSMixerMasking(nn.Module):
|
| 918 |
+
"""
|
| 919 |
+
Class to perform random or forecast masking.
|
| 920 |
+
|
| 921 |
+
Parameters:
|
| 922 |
+
config (`PatchTSMixerConfig`): model config
|
| 923 |
+
Returns:
|
| 924 |
+
x_mask (`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`)
|
| 925 |
+
Masked patched input
|
| 926 |
+
mask (`torch.Tensor` of shape `(batch_size, num_channels, num_patches)`)
|
| 927 |
+
Bool tensor indicating True on masked points
|
| 928 |
+
"""
|
| 929 |
+
|
| 930 |
+
def __init__(self, config: PatchTSMixerConfig):
|
| 931 |
+
super().__init__()
|
| 932 |
+
self.random_mask_ratio = config.random_mask_ratio
|
| 933 |
+
self.channel_consistent_masking = config.channel_consistent_masking
|
| 934 |
+
self.mask_type = config.mask_type
|
| 935 |
+
self.num_forecast_mask_patches = config.num_forecast_mask_patches
|
| 936 |
+
self.unmasked_channel_indices = config.unmasked_channel_indices
|
| 937 |
+
self.mask_value = config.mask_value
|
| 938 |
+
if self.unmasked_channel_indices is not None:
|
| 939 |
+
self.unmasked_channel_indices = sorted(self.unmasked_channel_indices)
|
| 940 |
+
|
| 941 |
+
def forward(self, patch_input: torch.Tensor):
|
| 942 |
+
"""
|
| 943 |
+
Parameters:
|
| 944 |
+
patch_input (`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`, *required*):
|
| 945 |
+
Patch input
|
| 946 |
+
|
| 947 |
+
Return:
|
| 948 |
+
masked_input (`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`)
|
| 949 |
+
Masked patched input
|
| 950 |
+
mask (`torch.Tensor` of shape `(batch_size, num_channels, num_patches)`)
|
| 951 |
+
Bool tensor indicating True on masked points
|
| 952 |
+
|
| 953 |
+
"""
|
| 954 |
+
if self.mask_type == "random":
|
| 955 |
+
masked_input, mask = random_masking(
|
| 956 |
+
inputs=patch_input,
|
| 957 |
+
mask_ratio=self.random_mask_ratio,
|
| 958 |
+
unmasked_channel_indices=self.unmasked_channel_indices,
|
| 959 |
+
channel_consistent_masking=self.channel_consistent_masking,
|
| 960 |
+
mask_value=self.mask_value,
|
| 961 |
+
)
|
| 962 |
+
elif self.mask_type == "forecast":
|
| 963 |
+
masked_input, mask = forecast_masking(
|
| 964 |
+
inputs=patch_input,
|
| 965 |
+
num_forecast_mask_patches=self.num_forecast_mask_patches,
|
| 966 |
+
unmasked_channel_indices=self.unmasked_channel_indices,
|
| 967 |
+
mask_value=self.mask_value,
|
| 968 |
+
)
|
| 969 |
+
else:
|
| 970 |
+
raise ValueError(f"Invalid mask type {self.mask_type}.")
|
| 971 |
+
|
| 972 |
+
# mask: [bs x num_input_channels x num_patch]
|
| 973 |
+
mask = mask.bool()
|
| 974 |
+
return masked_input, mask
|
| 975 |
+
|
| 976 |
+
|
| 977 |
+
# Copied from transformers.models.patchtst.modeling_patchtst.PatchTSTStdScaler with PatchTST->PatchTSMixer
|
| 978 |
+
class PatchTSMixerStdScaler(nn.Module):
|
| 979 |
+
"""
|
| 980 |
+
Standardize features by calculating the mean and scaling along the first dimension, and then normalizes it by
|
| 981 |
+
subtracting from the mean and dividing by the standard deviation.
|
| 982 |
+
"""
|
| 983 |
+
|
| 984 |
+
def __init__(self, config: PatchTSMixerConfig):
|
| 985 |
+
super().__init__()
|
| 986 |
+
self.dim = config.scaling_dim if hasattr(config, "scaling_dim") else 1
|
| 987 |
+
self.keepdim = config.keepdim if hasattr(config, "keepdim") else True
|
| 988 |
+
self.minimum_scale = config.minimum_scale if hasattr(config, "minimum_scale") else 1e-5
|
| 989 |
+
|
| 990 |
+
def forward(
|
| 991 |
+
self, data: torch.Tensor, observed_indicator: torch.Tensor
|
| 992 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 993 |
+
"""
|
| 994 |
+
Parameters:
|
| 995 |
+
data (`torch.Tensor` of shape `(batch_size, sequence_length, num_input_channels)`):
|
| 996 |
+
input for Batch norm calculation
|
| 997 |
+
observed_indicator (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`):
|
| 998 |
+
Calculating the scale on the observed indicator.
|
| 999 |
+
Returns:
|
| 1000 |
+
tuple of `torch.Tensor` of shapes
|
| 1001 |
+
(`(batch_size, sequence_length, num_input_channels)`,`(batch_size, 1, num_input_channels)`,
|
| 1002 |
+
`(batch_size, 1, num_input_channels)`)
|
| 1003 |
+
"""
|
| 1004 |
+
denominator = observed_indicator.sum(self.dim, keepdim=self.keepdim)
|
| 1005 |
+
denominator = denominator.clamp_min(1.0)
|
| 1006 |
+
loc = (data * observed_indicator).sum(self.dim, keepdim=self.keepdim) / denominator
|
| 1007 |
+
|
| 1008 |
+
variance = (((data - loc) * observed_indicator) ** 2).sum(self.dim, keepdim=self.keepdim) / denominator
|
| 1009 |
+
scale = torch.sqrt(variance + self.minimum_scale)
|
| 1010 |
+
return (data - loc) / scale, loc, scale
|
| 1011 |
+
|
| 1012 |
+
|
| 1013 |
+
# Copied from transformers.models.patchtst.modeling_patchtst.PatchTSTMeanScaler with PatchTST->PatchTSMixer
|
| 1014 |
+
class PatchTSMixerMeanScaler(nn.Module):
|
| 1015 |
+
"""
|
| 1016 |
+
Computes a scaling factor as the weighted average absolute value along the first dimension, and scales the data
|
| 1017 |
+
accordingly.
|
| 1018 |
+
"""
|
| 1019 |
+
|
| 1020 |
+
def __init__(self, config: PatchTSMixerConfig):
|
| 1021 |
+
super().__init__()
|
| 1022 |
+
self.dim = config.scaling_dim if hasattr(config, "scaling_dim") else 1
|
| 1023 |
+
self.keepdim = config.keepdim if hasattr(config, "keepdim") else True
|
| 1024 |
+
self.minimum_scale = config.minimum_scale if hasattr(config, "minimum_scale") else 1e-10
|
| 1025 |
+
self.default_scale = config.default_scale if hasattr(config, "default_scale") else None
|
| 1026 |
+
|
| 1027 |
+
def forward(
|
| 1028 |
+
self, data: torch.Tensor, observed_indicator: torch.Tensor
|
| 1029 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 1030 |
+
"""
|
| 1031 |
+
Parameters:
|
| 1032 |
+
data (`torch.Tensor` of shape `(batch_size, sequence_length, num_input_channels)`):
|
| 1033 |
+
input for Batch norm calculation
|
| 1034 |
+
observed_indicator (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`):
|
| 1035 |
+
Calculating the scale on the observed indicator.
|
| 1036 |
+
Returns:
|
| 1037 |
+
tuple of `torch.Tensor` of shapes
|
| 1038 |
+
(`(batch_size, sequence_length, num_input_channels)`,`(batch_size, 1, num_input_channels)`,
|
| 1039 |
+
`(batch_size, 1, num_input_channels)`)
|
| 1040 |
+
"""
|
| 1041 |
+
ts_sum = (data * observed_indicator).abs().sum(self.dim, keepdim=True)
|
| 1042 |
+
num_observed = observed_indicator.sum(self.dim, keepdim=True)
|
| 1043 |
+
|
| 1044 |
+
scale = ts_sum / torch.clamp(num_observed, min=1)
|
| 1045 |
+
|
| 1046 |
+
# If `default_scale` is provided, we use it, otherwise we use the scale
|
| 1047 |
+
# of the batch.
|
| 1048 |
+
if self.default_scale is None:
|
| 1049 |
+
batch_sum = ts_sum.sum(dim=0)
|
| 1050 |
+
batch_observations = torch.clamp(num_observed.sum(0), min=1)
|
| 1051 |
+
default_scale = torch.squeeze(batch_sum / batch_observations)
|
| 1052 |
+
else:
|
| 1053 |
+
default_scale = self.default_scale * torch.ones_like(scale)
|
| 1054 |
+
|
| 1055 |
+
# apply default scale where there are no observations
|
| 1056 |
+
scale = torch.where(num_observed > 0, scale, default_scale)
|
| 1057 |
+
|
| 1058 |
+
# ensure the scale is at least `self.minimum_scale`
|
| 1059 |
+
scale = torch.clamp(scale, min=self.minimum_scale)
|
| 1060 |
+
scaled_data = data / scale
|
| 1061 |
+
|
| 1062 |
+
if not self.keepdim:
|
| 1063 |
+
scale = scale.squeeze(dim=self.dim)
|
| 1064 |
+
|
| 1065 |
+
return scaled_data, torch.zeros_like(scale), scale
|
| 1066 |
+
|
| 1067 |
+
|
| 1068 |
+
# Copied from transformers.models.patchtst.modeling_patchtst.PatchTSTNOPScaler with PatchTST->PatchTSMixer
|
| 1069 |
+
class PatchTSMixerNOPScaler(nn.Module):
|
| 1070 |
+
"""
|
| 1071 |
+
Assigns a scaling factor equal to 1 along the first dimension, and therefore applies no scaling to the input data.
|
| 1072 |
+
"""
|
| 1073 |
+
|
| 1074 |
+
def __init__(self, config: PatchTSMixerConfig):
|
| 1075 |
+
super().__init__()
|
| 1076 |
+
self.dim = config.scaling_dim if hasattr(config, "scaling_dim") else 1
|
| 1077 |
+
self.keepdim = config.keepdim if hasattr(config, "keepdim") else True
|
| 1078 |
+
|
| 1079 |
+
def forward(
|
| 1080 |
+
self, data: torch.Tensor, observed_indicator: torch.Tensor | None = None
|
| 1081 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 1082 |
+
"""
|
| 1083 |
+
Parameters:
|
| 1084 |
+
data (`torch.Tensor` of shape `(batch_size, sequence_length, num_input_channels)`):
|
| 1085 |
+
input for Batch norm calculation
|
| 1086 |
+
Returns:
|
| 1087 |
+
tuple of `torch.Tensor` of shapes
|
| 1088 |
+
(`(batch_size, sequence_length, num_input_channels)`,`(batch_size, 1, num_input_channels)`,
|
| 1089 |
+
`(batch_size, 1, num_input_channels)`)
|
| 1090 |
+
"""
|
| 1091 |
+
scale = torch.ones_like(data, requires_grad=False).mean(dim=self.dim, keepdim=self.keepdim)
|
| 1092 |
+
loc = torch.zeros_like(data, requires_grad=False).mean(dim=self.dim, keepdim=self.keepdim)
|
| 1093 |
+
return data, loc, scale
|
| 1094 |
+
|
| 1095 |
+
|
| 1096 |
+
@dataclass
|
| 1097 |
+
@auto_docstring(
|
| 1098 |
+
custom_intro="""
|
| 1099 |
+
Base class for `PatchTSMixerEncoderOutput`, with potential hidden states.
|
| 1100 |
+
"""
|
| 1101 |
+
)
|
| 1102 |
+
class PatchTSMixerEncoderOutput(ModelOutput):
|
| 1103 |
+
r"""
|
| 1104 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_channels, num_patches, d_model)`):
|
| 1105 |
+
Hidden-state at the output of the last layer of the model.
|
| 1106 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*):
|
| 1107 |
+
Hidden-states of the model at the output of each layer.
|
| 1108 |
+
"""
|
| 1109 |
+
|
| 1110 |
+
last_hidden_state: torch.FloatTensor | None = None
|
| 1111 |
+
hidden_states: tuple[torch.FloatTensor] | None = None
|
| 1112 |
+
|
| 1113 |
+
|
| 1114 |
+
class PatchTSMixerEncoder(PatchTSMixerPreTrainedModel):
|
| 1115 |
+
"""
|
| 1116 |
+
Encoder for PatchTSMixer which inputs patched time-series and outputs patched embeddings.
|
| 1117 |
+
|
| 1118 |
+
Args:
|
| 1119 |
+
config (`PatchTSMixerConfig`):
|
| 1120 |
+
Configuration.
|
| 1121 |
+
"""
|
| 1122 |
+
|
| 1123 |
+
def __init__(self, config: PatchTSMixerConfig):
|
| 1124 |
+
super().__init__(config)
|
| 1125 |
+
|
| 1126 |
+
self.use_return_dict = config.use_return_dict
|
| 1127 |
+
|
| 1128 |
+
self.patcher = nn.Linear(config.patch_length, config.d_model)
|
| 1129 |
+
if config.use_positional_encoding:
|
| 1130 |
+
self.positional_encoder = PatchTSMixerPositionalEncoding(config=config)
|
| 1131 |
+
else:
|
| 1132 |
+
self.positional_encoder = None
|
| 1133 |
+
self.mlp_mixer_encoder = PatchTSMixerBlock(config=config)
|
| 1134 |
+
|
| 1135 |
+
# Initialize weights and apply final processing
|
| 1136 |
+
self.post_init()
|
| 1137 |
+
|
| 1138 |
+
@auto_docstring
|
| 1139 |
+
def forward(
|
| 1140 |
+
self,
|
| 1141 |
+
past_values: torch.Tensor,
|
| 1142 |
+
output_hidden_states: bool | None = False,
|
| 1143 |
+
return_dict: bool | None = None,
|
| 1144 |
+
**kwargs,
|
| 1145 |
+
) -> tuple | PatchTSMixerEncoderOutput:
|
| 1146 |
+
r"""
|
| 1147 |
+
past_values (`torch.FloatTensor` of shape `(batch_size, seq_length, num_input_channels)`):
|
| 1148 |
+
Context values of the time series. For a pretraining task, this denotes the input time series to
|
| 1149 |
+
predict the masked portion. For a forecasting task, this denotes the history/past time series values.
|
| 1150 |
+
Similarly, for classification or regression tasks, it denotes the appropriate context values of the
|
| 1151 |
+
time series.
|
| 1152 |
+
|
| 1153 |
+
For univariate time series, `num_input_channels` dimension should be 1. For multivariate time series,
|
| 1154 |
+
it is greater than 1.
|
| 1155 |
+
|
| 1156 |
+
Returns:
|
| 1157 |
+
`torch.FloatTensor` of shape `(batch_size, n_vars, num_patches, d_model)`
|
| 1158 |
+
"""
|
| 1159 |
+
|
| 1160 |
+
return_dict = return_dict if return_dict is not None else self.use_return_dict
|
| 1161 |
+
|
| 1162 |
+
# flatten [bs x num_patch x d_model]. common_channel/mix_channel: [bs x n_vars x num_patch x d_model]
|
| 1163 |
+
patches = self.patcher(past_values)
|
| 1164 |
+
|
| 1165 |
+
# add positional encoder
|
| 1166 |
+
if self.positional_encoder is not None:
|
| 1167 |
+
patches = self.positional_encoder(patches)
|
| 1168 |
+
|
| 1169 |
+
last_hidden_state, hidden_states = self.mlp_mixer_encoder(patches, output_hidden_states=output_hidden_states)
|
| 1170 |
+
|
| 1171 |
+
if not return_dict:
|
| 1172 |
+
return tuple(
|
| 1173 |
+
v
|
| 1174 |
+
for v in [
|
| 1175 |
+
last_hidden_state,
|
| 1176 |
+
hidden_states,
|
| 1177 |
+
]
|
| 1178 |
+
)
|
| 1179 |
+
|
| 1180 |
+
return PatchTSMixerEncoderOutput(last_hidden_state=last_hidden_state, hidden_states=hidden_states)
|
| 1181 |
+
|
| 1182 |
+
|
| 1183 |
+
@dataclass
|
| 1184 |
+
@auto_docstring(
|
| 1185 |
+
custom_intro="""
|
| 1186 |
+
Base class for model's outputs, with potential hidden states.
|
| 1187 |
+
"""
|
| 1188 |
+
)
|
| 1189 |
+
class PatchTSMixerModelOutput(ModelOutput):
|
| 1190 |
+
r"""
|
| 1191 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_channels, num_patches, d_model)`):
|
| 1192 |
+
Hidden-state at the output of the last layer of the model.
|
| 1193 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*):
|
| 1194 |
+
Hidden-states of the model at the output of each layer.
|
| 1195 |
+
patch_input (`torch.FloatTensor` of shape `(batch_size, num_channels, num_patches, patch_length)`):
|
| 1196 |
+
Patched input data to the model.
|
| 1197 |
+
mask (`torch.FloatTensor` of shape `(batch_size, num_channels, num_patches)`, *optional*):
|
| 1198 |
+
Bool Tensor indicating True in masked patches and False otherwise.
|
| 1199 |
+
loc (`torch.FloatTensor` of shape `(batch_size, 1, num_channels)`, *optional*):
|
| 1200 |
+
Gives the mean of the context window per channel. Used for revin denorm outside the model, if revin
|
| 1201 |
+
enabled.
|
| 1202 |
+
scale (`torch.FloatTensor` of shape `(batch_size, 1, num_channels)`, *optional*):
|
| 1203 |
+
Gives the std dev of the context window per channel. Used for revin denorm outside the model, if revin
|
| 1204 |
+
enabled.
|
| 1205 |
+
"""
|
| 1206 |
+
|
| 1207 |
+
last_hidden_state: torch.FloatTensor | None = None
|
| 1208 |
+
hidden_states: tuple[torch.FloatTensor] | None = None
|
| 1209 |
+
patch_input: torch.FloatTensor | None = None
|
| 1210 |
+
mask: torch.FloatTensor | None = None
|
| 1211 |
+
loc: torch.FloatTensor | None = None
|
| 1212 |
+
scale: torch.FloatTensor | None = None
|
| 1213 |
+
|
| 1214 |
+
|
| 1215 |
+
@auto_docstring(
|
| 1216 |
+
custom_intro="""
|
| 1217 |
+
The PatchTSMixer Model for time-series forecasting.
|
| 1218 |
+
"""
|
| 1219 |
+
)
|
| 1220 |
+
class PatchTSMixerModel(PatchTSMixerPreTrainedModel):
|
| 1221 |
+
def __init__(self, config: PatchTSMixerConfig, mask_input: bool = False):
|
| 1222 |
+
r"""
|
| 1223 |
+
mask_input (bool, *optional*, defaults to `False`):
|
| 1224 |
+
Whether to mask the input using the [`PatchTSMixerMasking`] module.
|
| 1225 |
+
"""
|
| 1226 |
+
super().__init__(config)
|
| 1227 |
+
|
| 1228 |
+
self.use_return_dict = config.use_return_dict
|
| 1229 |
+
self.encoder = PatchTSMixerEncoder(config)
|
| 1230 |
+
self.patching = PatchTSMixerPatchify(config)
|
| 1231 |
+
|
| 1232 |
+
if mask_input is True:
|
| 1233 |
+
self.masking = PatchTSMixerMasking(config)
|
| 1234 |
+
else:
|
| 1235 |
+
self.masking = None
|
| 1236 |
+
|
| 1237 |
+
if config.scaling == "mean":
|
| 1238 |
+
self.scaler = PatchTSMixerMeanScaler(config)
|
| 1239 |
+
elif config.scaling == "std" or config.scaling is True:
|
| 1240 |
+
self.scaler = PatchTSMixerStdScaler(config)
|
| 1241 |
+
else:
|
| 1242 |
+
self.scaler = PatchTSMixerNOPScaler(config)
|
| 1243 |
+
|
| 1244 |
+
# Initialize weights and apply final processing
|
| 1245 |
+
self.post_init()
|
| 1246 |
+
|
| 1247 |
+
@auto_docstring
|
| 1248 |
+
def forward(
|
| 1249 |
+
self,
|
| 1250 |
+
past_values: torch.Tensor,
|
| 1251 |
+
observed_mask: torch.Tensor | None = None,
|
| 1252 |
+
output_hidden_states: bool | None = False,
|
| 1253 |
+
return_dict: bool | None = None,
|
| 1254 |
+
**kwargs,
|
| 1255 |
+
) -> PatchTSMixerModelOutput:
|
| 1256 |
+
r"""
|
| 1257 |
+
past_values (`torch.FloatTensor` of shape `(batch_size, seq_length, num_input_channels)`):
|
| 1258 |
+
Context values of the time series. For a pretraining task, this denotes the input time series to predict
|
| 1259 |
+
the masked portion. For a forecasting task, this denotes the history/past time series values. Similarly,
|
| 1260 |
+
for classification or regression tasks, it denotes the appropriate context values of the time series.
|
| 1261 |
+
|
| 1262 |
+
For univariate time series, `num_input_channels` dimension should be 1. For multivariate time series, it is
|
| 1263 |
+
greater than 1.
|
| 1264 |
+
observed_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
|
| 1265 |
+
Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
|
| 1266 |
+
in `[0, 1]`:
|
| 1267 |
+
- 1 for values that are **observed**,
|
| 1268 |
+
- 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
|
| 1269 |
+
"""
|
| 1270 |
+
return_dict = return_dict if return_dict is not None else self.use_return_dict
|
| 1271 |
+
|
| 1272 |
+
mask = None
|
| 1273 |
+
if observed_mask is None:
|
| 1274 |
+
observed_mask = torch.ones_like(past_values)
|
| 1275 |
+
scaled_past_values, loc, scale = self.scaler(past_values, observed_mask)
|
| 1276 |
+
|
| 1277 |
+
patched_x = self.patching(scaled_past_values) # [batch_size x num_input_channels x num_patch x patch_length
|
| 1278 |
+
|
| 1279 |
+
enc_input = patched_x
|
| 1280 |
+
if self.masking is not None:
|
| 1281 |
+
enc_input, mask = self.masking(patched_x)
|
| 1282 |
+
# enc_input: [batch_size x num_input_channels x num_patch x patch_length]
|
| 1283 |
+
# mask: [batch_size x num_input_channels x num_patch]
|
| 1284 |
+
|
| 1285 |
+
encoder_output = self.encoder(
|
| 1286 |
+
enc_input,
|
| 1287 |
+
output_hidden_states=output_hidden_states,
|
| 1288 |
+
return_dict=return_dict,
|
| 1289 |
+
)
|
| 1290 |
+
|
| 1291 |
+
if isinstance(encoder_output, tuple):
|
| 1292 |
+
encoder_output = PatchTSMixerEncoderOutput(*encoder_output)
|
| 1293 |
+
|
| 1294 |
+
if not return_dict:
|
| 1295 |
+
return tuple(
|
| 1296 |
+
v
|
| 1297 |
+
for v in [
|
| 1298 |
+
encoder_output.last_hidden_state,
|
| 1299 |
+
encoder_output.hidden_states,
|
| 1300 |
+
patched_x,
|
| 1301 |
+
mask,
|
| 1302 |
+
loc,
|
| 1303 |
+
scale,
|
| 1304 |
+
]
|
| 1305 |
+
)
|
| 1306 |
+
|
| 1307 |
+
return PatchTSMixerModelOutput(
|
| 1308 |
+
last_hidden_state=encoder_output.last_hidden_state,
|
| 1309 |
+
hidden_states=encoder_output.hidden_states,
|
| 1310 |
+
patch_input=patched_x,
|
| 1311 |
+
mask=mask,
|
| 1312 |
+
loc=loc,
|
| 1313 |
+
scale=scale,
|
| 1314 |
+
)
|
| 1315 |
+
|
| 1316 |
+
|
| 1317 |
+
@dataclass
|
| 1318 |
+
@auto_docstring(
|
| 1319 |
+
custom_intro="""
|
| 1320 |
+
Output type of [`PatchTSMixerForPreTrainingOutput`].
|
| 1321 |
+
"""
|
| 1322 |
+
)
|
| 1323 |
+
class PatchTSMixerForPreTrainingOutput(ModelOutput):
|
| 1324 |
+
r"""
|
| 1325 |
+
loss (*optional*, returned when `y` is provided, `torch.FloatTensor` of shape `()`):
|
| 1326 |
+
Total loss
|
| 1327 |
+
prediction_outputs (`torch.FloatTensor` of shape `(batch_size, num_input_channels, num_patches, patch_length)`):
|
| 1328 |
+
Prediction output from the pretrain head.
|
| 1329 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_input_channels, num_patches, d_model)`):
|
| 1330 |
+
Backbone embeddings before passing through the head.
|
| 1331 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*):
|
| 1332 |
+
Hidden-states of the model at the output of each layer.
|
| 1333 |
+
"""
|
| 1334 |
+
|
| 1335 |
+
loss: torch.FloatTensor | None = None
|
| 1336 |
+
prediction_outputs: torch.FloatTensor | None = None
|
| 1337 |
+
last_hidden_state: torch.FloatTensor | None = None
|
| 1338 |
+
hidden_states: tuple[torch.FloatTensor] | None = None
|
| 1339 |
+
|
| 1340 |
+
|
| 1341 |
+
@auto_docstring(
|
| 1342 |
+
custom_intro="""
|
| 1343 |
+
`PatchTSMixer` for mask pretraining.
|
| 1344 |
+
"""
|
| 1345 |
+
)
|
| 1346 |
+
class PatchTSMixerForPretraining(PatchTSMixerPreTrainedModel):
|
| 1347 |
+
def __init__(self, config: PatchTSMixerConfig):
|
| 1348 |
+
super().__init__(config)
|
| 1349 |
+
self.model = PatchTSMixerModel(config, mask_input=True)
|
| 1350 |
+
self.head = PatchTSMixerPretrainHead(config=config)
|
| 1351 |
+
self.masked_loss = config.masked_loss
|
| 1352 |
+
self.use_return_dict = config.use_return_dict
|
| 1353 |
+
|
| 1354 |
+
# Initialize weights and apply final processing
|
| 1355 |
+
self.post_init()
|
| 1356 |
+
|
| 1357 |
+
@auto_docstring
|
| 1358 |
+
def forward(
|
| 1359 |
+
self,
|
| 1360 |
+
past_values: torch.Tensor,
|
| 1361 |
+
observed_mask: torch.Tensor | None = None,
|
| 1362 |
+
output_hidden_states: bool | None = False,
|
| 1363 |
+
return_loss: bool = True,
|
| 1364 |
+
return_dict: bool | None = None,
|
| 1365 |
+
**kwargs,
|
| 1366 |
+
) -> PatchTSMixerForPreTrainingOutput:
|
| 1367 |
+
r"""
|
| 1368 |
+
past_values (`torch.FloatTensor` of shape `(batch_size, seq_length, num_input_channels)`):
|
| 1369 |
+
Context values of the time series. For a pretraining task, this denotes the input time series to predict
|
| 1370 |
+
the masked portion. For a forecasting task, this denotes the history/past time series values. Similarly,
|
| 1371 |
+
for classification or regression tasks, it denotes the appropriate context values of the time series.
|
| 1372 |
+
|
| 1373 |
+
For univariate time series, `num_input_channels` dimension should be 1. For multivariate time series, it is
|
| 1374 |
+
greater than 1.
|
| 1375 |
+
observed_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
|
| 1376 |
+
Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
|
| 1377 |
+
in `[0, 1]`:
|
| 1378 |
+
- 1 for values that are **observed**,
|
| 1379 |
+
- 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
|
| 1380 |
+
return_loss (`bool`, *optional*):
|
| 1381 |
+
Whether to return the loss in the `forward` call.
|
| 1382 |
+
"""
|
| 1383 |
+
return_dict = return_dict if return_dict is not None else self.use_return_dict
|
| 1384 |
+
|
| 1385 |
+
if self.masked_loss is True:
|
| 1386 |
+
loss = torch.nn.MSELoss(reduction="none")
|
| 1387 |
+
else:
|
| 1388 |
+
loss = torch.nn.MSELoss(reduction="mean")
|
| 1389 |
+
|
| 1390 |
+
# past_values: tensor [batch_size x context_length x num_input_channels]
|
| 1391 |
+
model_output = self.model(
|
| 1392 |
+
past_values,
|
| 1393 |
+
observed_mask=observed_mask,
|
| 1394 |
+
output_hidden_states=output_hidden_states,
|
| 1395 |
+
return_dict=return_dict,
|
| 1396 |
+
) # x.last_hidden_state: [batch_size x nvars x num_patch x d_model]
|
| 1397 |
+
if isinstance(model_output, tuple):
|
| 1398 |
+
model_output = PatchTSMixerModelOutput(*model_output)
|
| 1399 |
+
|
| 1400 |
+
x_hat = self.head(model_output.last_hidden_state) # tensor [batch_size x nvars x num_patch x patch_length]
|
| 1401 |
+
|
| 1402 |
+
if return_loss is True:
|
| 1403 |
+
loss_val = loss(x_hat, model_output.patch_input)
|
| 1404 |
+
else:
|
| 1405 |
+
loss_val = None
|
| 1406 |
+
|
| 1407 |
+
# calculate masked_loss
|
| 1408 |
+
if self.masked_loss is True and loss_val is not None:
|
| 1409 |
+
loss_val = (loss_val.mean(dim=-1) * model_output.mask).sum() / (model_output.mask.sum() + 1e-10)
|
| 1410 |
+
|
| 1411 |
+
if not return_dict:
|
| 1412 |
+
return tuple(
|
| 1413 |
+
v
|
| 1414 |
+
for v in [
|
| 1415 |
+
loss_val,
|
| 1416 |
+
x_hat,
|
| 1417 |
+
model_output.last_hidden_state,
|
| 1418 |
+
model_output.hidden_states,
|
| 1419 |
+
]
|
| 1420 |
+
)
|
| 1421 |
+
|
| 1422 |
+
return PatchTSMixerForPreTrainingOutput(
|
| 1423 |
+
loss=loss_val,
|
| 1424 |
+
prediction_outputs=x_hat, # tensor [batch_size x nvars x num_patch x patch_length]
|
| 1425 |
+
last_hidden_state=model_output.last_hidden_state, # x: [batch_size x nvars x num_patch x d_model]
|
| 1426 |
+
hidden_states=model_output.hidden_states,
|
| 1427 |
+
)
|
| 1428 |
+
|
| 1429 |
+
|
| 1430 |
+
@dataclass
|
| 1431 |
+
@auto_docstring(
|
| 1432 |
+
custom_intro="""
|
| 1433 |
+
Output type of [`PatchTSMixerForPredictionOutput`].
|
| 1434 |
+
"""
|
| 1435 |
+
)
|
| 1436 |
+
class PatchTSMixerForPredictionOutput(ModelOutput):
|
| 1437 |
+
r"""
|
| 1438 |
+
loss (*optional*, returned when `y` is provided, `torch.FloatTensor` of shape `()`):
|
| 1439 |
+
Total loss.
|
| 1440 |
+
prediction_outputs (`torch.FloatTensor` of shape `(batch_size, prediction_length, num_input_channels)`):
|
| 1441 |
+
Prediction output from the forecast head.
|
| 1442 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_input_channels, num_patches, d_model)`):
|
| 1443 |
+
Backbone embeddings before passing through the head.
|
| 1444 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*):
|
| 1445 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 1446 |
+
loc (`torch.FloatTensor`, *optional* of shape `(batch_size, 1, num_input_channels)`):
|
| 1447 |
+
Input mean
|
| 1448 |
+
scale (`torch.FloatTensor`, *optional* of shape `(batch_size, 1, num_input_channels)`):
|
| 1449 |
+
Input std dev
|
| 1450 |
+
"""
|
| 1451 |
+
|
| 1452 |
+
loss: torch.FloatTensor | None = None
|
| 1453 |
+
prediction_outputs: torch.FloatTensor | None = None
|
| 1454 |
+
last_hidden_state: torch.FloatTensor | None = None
|
| 1455 |
+
hidden_states: tuple[torch.FloatTensor] | None = None
|
| 1456 |
+
loc: torch.FloatTensor | None = None
|
| 1457 |
+
scale: torch.FloatTensor | None = None
|
| 1458 |
+
|
| 1459 |
+
|
| 1460 |
+
@dataclass
|
| 1461 |
+
@auto_docstring(
|
| 1462 |
+
custom_intro="""
|
| 1463 |
+
Base class for time series model's predictions outputs that contains the sampled values from the chosen
|
| 1464 |
+
distribution.
|
| 1465 |
+
"""
|
| 1466 |
+
)
|
| 1467 |
+
class SamplePatchTSMixerPredictionOutput(ModelOutput):
|
| 1468 |
+
r"""
|
| 1469 |
+
sequences (`torch.FloatTensor` of shape `(batch_size, num_samples, prediction_length, number_channels)`):
|
| 1470 |
+
Sampled values from the chosen distribution.
|
| 1471 |
+
"""
|
| 1472 |
+
|
| 1473 |
+
sequences: torch.FloatTensor | None = None
|
| 1474 |
+
|
| 1475 |
+
|
| 1476 |
+
@dataclass
|
| 1477 |
+
@auto_docstring(
|
| 1478 |
+
custom_intro="""
|
| 1479 |
+
Base class for time series model's predictions outputs that contains the sampled values from the chosen
|
| 1480 |
+
distribution.
|
| 1481 |
+
"""
|
| 1482 |
+
)
|
| 1483 |
+
class SamplePatchTSMixerRegressionOutput(ModelOutput):
|
| 1484 |
+
r"""
|
| 1485 |
+
sequences (`torch.FloatTensor` of shape `(batch_size, num_samples, prediction_length, number_channels)`):
|
| 1486 |
+
Sampled values from the chosen distribution.
|
| 1487 |
+
"""
|
| 1488 |
+
|
| 1489 |
+
sequences: torch.FloatTensor | None = None
|
| 1490 |
+
|
| 1491 |
+
|
| 1492 |
+
# Copied from transformers.models.time_series_transformer.modeling_time_series_transformer.nll
|
| 1493 |
+
def nll(input: torch.distributions.Distribution, target: torch.Tensor) -> torch.Tensor:
|
| 1494 |
+
"""
|
| 1495 |
+
Computes the negative log likelihood loss from input distribution with respect to target.
|
| 1496 |
+
"""
|
| 1497 |
+
return -input.log_prob(target)
|
| 1498 |
+
|
| 1499 |
+
|
| 1500 |
+
# Copied from transformers.models.time_series_transformer.modeling_time_series_transformer.weighted_average
|
| 1501 |
+
def weighted_average(input_tensor: torch.Tensor, weights: torch.Tensor | None = None, dim=None) -> torch.Tensor:
|
| 1502 |
+
"""
|
| 1503 |
+
Computes the weighted average of a given tensor across a given `dim`, masking values associated with weight zero,
|
| 1504 |
+
meaning instead of `nan * 0 = nan` you will get `0 * 0 = 0`.
|
| 1505 |
+
|
| 1506 |
+
Args:
|
| 1507 |
+
input_tensor (`torch.FloatTensor`):
|
| 1508 |
+
Input tensor, of which the average must be computed.
|
| 1509 |
+
weights (`torch.FloatTensor`, *optional*):
|
| 1510 |
+
Weights tensor, of the same shape as `input_tensor`.
|
| 1511 |
+
dim (`int`, *optional*):
|
| 1512 |
+
The dim along which to average `input_tensor`.
|
| 1513 |
+
|
| 1514 |
+
Returns:
|
| 1515 |
+
`torch.FloatTensor`: The tensor with values averaged along the specified `dim`.
|
| 1516 |
+
"""
|
| 1517 |
+
if weights is not None:
|
| 1518 |
+
weighted_tensor = torch.where(weights != 0, input_tensor * weights, torch.zeros_like(input_tensor))
|
| 1519 |
+
sum_weights = torch.clamp(weights.sum(dim=dim) if dim else weights.sum(), min=1.0)
|
| 1520 |
+
return (weighted_tensor.sum(dim=dim) if dim else weighted_tensor.sum()) / sum_weights
|
| 1521 |
+
else:
|
| 1522 |
+
return input_tensor.mean(dim=dim)
|
| 1523 |
+
|
| 1524 |
+
|
| 1525 |
+
class PatchTSMixerForPrediction(PatchTSMixerPreTrainedModel):
|
| 1526 |
+
r"""
|
| 1527 |
+
`PatchTSMixer` for forecasting application.
|
| 1528 |
+
|
| 1529 |
+
Args:
|
| 1530 |
+
config (`PatchTSMixerConfig`):
|
| 1531 |
+
Configuration.
|
| 1532 |
+
|
| 1533 |
+
Returns:
|
| 1534 |
+
`None`.
|
| 1535 |
+
"""
|
| 1536 |
+
|
| 1537 |
+
def __init__(self, config: PatchTSMixerConfig):
|
| 1538 |
+
super().__init__(config)
|
| 1539 |
+
self.loss = config.loss
|
| 1540 |
+
self.use_return_dict = config.use_return_dict
|
| 1541 |
+
self.prediction_channel_indices = config.prediction_channel_indices
|
| 1542 |
+
self.num_parallel_samples = config.num_parallel_samples
|
| 1543 |
+
|
| 1544 |
+
if config.loss == "mse":
|
| 1545 |
+
self.distribution_output = None
|
| 1546 |
+
else:
|
| 1547 |
+
dim = config.prediction_length
|
| 1548 |
+
distribution_output_map = {
|
| 1549 |
+
"student_t": StudentTOutput,
|
| 1550 |
+
"normal": NormalOutput,
|
| 1551 |
+
"negative_binomial": NegativeBinomialOutput,
|
| 1552 |
+
}
|
| 1553 |
+
output_class = distribution_output_map.get(config.distribution_output)
|
| 1554 |
+
if output_class is not None:
|
| 1555 |
+
self.distribution_output = output_class(dim=dim)
|
| 1556 |
+
else:
|
| 1557 |
+
raise ValueError(f"Unknown distribution output {config.distribution_output}")
|
| 1558 |
+
|
| 1559 |
+
self.model = PatchTSMixerModel(config)
|
| 1560 |
+
self.head = PatchTSMixerForPredictionHead(
|
| 1561 |
+
config=config,
|
| 1562 |
+
distribution_output=self.distribution_output,
|
| 1563 |
+
)
|
| 1564 |
+
|
| 1565 |
+
# Initialize weights and apply final processing
|
| 1566 |
+
self.post_init()
|
| 1567 |
+
|
| 1568 |
+
@auto_docstring
|
| 1569 |
+
def forward(
|
| 1570 |
+
self,
|
| 1571 |
+
past_values: torch.Tensor,
|
| 1572 |
+
observed_mask: torch.Tensor | None = None,
|
| 1573 |
+
future_values: torch.Tensor | None = None,
|
| 1574 |
+
output_hidden_states: bool | None = False,
|
| 1575 |
+
return_loss: bool = True,
|
| 1576 |
+
return_dict: bool | None = None,
|
| 1577 |
+
**kwargs,
|
| 1578 |
+
) -> PatchTSMixerForPredictionOutput:
|
| 1579 |
+
r"""
|
| 1580 |
+
past_values (`torch.FloatTensor` of shape `(batch_size, seq_length, num_input_channels)`):
|
| 1581 |
+
Context values of the time series. For a pretraining task, this denotes the input time series to predict
|
| 1582 |
+
the masked portion. For a forecasting task, this denotes the history/past time series values. Similarly,
|
| 1583 |
+
for classification or regression tasks, it denotes the appropriate context values of the time series.
|
| 1584 |
+
|
| 1585 |
+
For univariate time series, `num_input_channels` dimension should be 1. For multivariate time series, it is
|
| 1586 |
+
greater than 1.
|
| 1587 |
+
observed_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
|
| 1588 |
+
Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
|
| 1589 |
+
in `[0, 1]`:
|
| 1590 |
+
- 1 for values that are **observed**,
|
| 1591 |
+
- 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
|
| 1592 |
+
future_values (`torch.FloatTensor` of shape `(batch_size, target_len, num_input_channels)` for forecasting,:
|
| 1593 |
+
`(batch_size, num_targets)` for regression, or `(batch_size,)` for classification, *optional*):
|
| 1594 |
+
Target values of the time series, that serve as labels for the model. The `future_values` is what the
|
| 1595 |
+
Transformer needs during training to learn to output, given the `past_values`. Note that, this is NOT
|
| 1596 |
+
required for a pretraining task.
|
| 1597 |
+
|
| 1598 |
+
For a forecasting task, the shape is be `(batch_size, target_len, num_input_channels)`. Even if we want
|
| 1599 |
+
to forecast only specific channels by setting the indices in `prediction_channel_indices` parameter,
|
| 1600 |
+
pass the target data with all channels, as channel Filtering for both prediction and target will be
|
| 1601 |
+
manually applied before the loss computation.
|
| 1602 |
+
return_loss (`bool`, *optional*):
|
| 1603 |
+
Whether to return the loss in the `forward` call.
|
| 1604 |
+
"""
|
| 1605 |
+
if self.loss == "mse":
|
| 1606 |
+
loss = nn.MSELoss(reduction="mean")
|
| 1607 |
+
elif self.loss == "nll":
|
| 1608 |
+
loss = nll
|
| 1609 |
+
else:
|
| 1610 |
+
raise ValueError("Invalid loss function: Allowed values: mse and nll")
|
| 1611 |
+
|
| 1612 |
+
return_dict = return_dict if return_dict is not None else self.use_return_dict
|
| 1613 |
+
|
| 1614 |
+
# past_values: tensor [batch_size x context_length x num_input_channels]
|
| 1615 |
+
model_output = self.model(
|
| 1616 |
+
past_values,
|
| 1617 |
+
observed_mask=observed_mask,
|
| 1618 |
+
output_hidden_states=output_hidden_states,
|
| 1619 |
+
return_dict=return_dict,
|
| 1620 |
+
) # model_output: [batch_size x nvars x num_patch x d_model]
|
| 1621 |
+
if isinstance(model_output, tuple):
|
| 1622 |
+
model_output = PatchTSMixerModelOutput(*model_output)
|
| 1623 |
+
|
| 1624 |
+
# tensor [batch_size x prediction_length x num_input_channels]
|
| 1625 |
+
y_hat = self.head(model_output.last_hidden_state)
|
| 1626 |
+
|
| 1627 |
+
loss_val = None
|
| 1628 |
+
if self.prediction_channel_indices is not None:
|
| 1629 |
+
if self.distribution_output:
|
| 1630 |
+
distribution = self.distribution_output.distribution(
|
| 1631 |
+
y_hat,
|
| 1632 |
+
loc=model_output.loc[..., self.prediction_channel_indices],
|
| 1633 |
+
scale=model_output.scale[..., self.prediction_channel_indices],
|
| 1634 |
+
)
|
| 1635 |
+
if future_values is not None and return_loss is True:
|
| 1636 |
+
loss_val = loss(
|
| 1637 |
+
distribution,
|
| 1638 |
+
future_values[..., self.prediction_channel_indices],
|
| 1639 |
+
)
|
| 1640 |
+
# take average of the loss
|
| 1641 |
+
loss_val = weighted_average(loss_val)
|
| 1642 |
+
else:
|
| 1643 |
+
y_hat = (
|
| 1644 |
+
y_hat * model_output.scale[..., self.prediction_channel_indices]
|
| 1645 |
+
+ model_output.loc[..., self.prediction_channel_indices]
|
| 1646 |
+
)
|
| 1647 |
+
if future_values is not None and return_loss is True:
|
| 1648 |
+
loss_val = loss(y_hat, future_values[..., self.prediction_channel_indices])
|
| 1649 |
+
else:
|
| 1650 |
+
if self.distribution_output:
|
| 1651 |
+
distribution = self.distribution_output.distribution(
|
| 1652 |
+
y_hat, loc=model_output.loc, scale=model_output.scale
|
| 1653 |
+
)
|
| 1654 |
+
if future_values is not None and return_loss is True:
|
| 1655 |
+
loss_val = loss(distribution, future_values)
|
| 1656 |
+
loss_val = weighted_average(loss_val)
|
| 1657 |
+
else:
|
| 1658 |
+
y_hat = y_hat * model_output.scale + model_output.loc
|
| 1659 |
+
if future_values is not None and return_loss is True:
|
| 1660 |
+
loss_val = loss(y_hat, future_values)
|
| 1661 |
+
|
| 1662 |
+
if self.prediction_channel_indices is not None:
|
| 1663 |
+
loc = model_output.loc[..., self.prediction_channel_indices]
|
| 1664 |
+
scale = model_output.scale[..., self.prediction_channel_indices]
|
| 1665 |
+
else:
|
| 1666 |
+
loc = model_output.loc
|
| 1667 |
+
scale = model_output.scale
|
| 1668 |
+
|
| 1669 |
+
if not return_dict:
|
| 1670 |
+
return tuple(
|
| 1671 |
+
v
|
| 1672 |
+
for v in [
|
| 1673 |
+
loss_val,
|
| 1674 |
+
y_hat,
|
| 1675 |
+
model_output.last_hidden_state,
|
| 1676 |
+
model_output.hidden_states,
|
| 1677 |
+
loc,
|
| 1678 |
+
scale,
|
| 1679 |
+
]
|
| 1680 |
+
)
|
| 1681 |
+
|
| 1682 |
+
return PatchTSMixerForPredictionOutput(
|
| 1683 |
+
loss=loss_val,
|
| 1684 |
+
prediction_outputs=y_hat, # tensor [batch_size x prediction_length x num_input_channels]
|
| 1685 |
+
last_hidden_state=model_output.last_hidden_state, # x: [batch_size x nvars x num_patch x d_model]
|
| 1686 |
+
hidden_states=model_output.hidden_states,
|
| 1687 |
+
loc=loc,
|
| 1688 |
+
scale=scale,
|
| 1689 |
+
)
|
| 1690 |
+
|
| 1691 |
+
@torch.no_grad()
|
| 1692 |
+
def generate(
|
| 1693 |
+
self,
|
| 1694 |
+
past_values: torch.Tensor,
|
| 1695 |
+
observed_mask: torch.Tensor | None = None,
|
| 1696 |
+
) -> SamplePatchTSMixerPredictionOutput:
|
| 1697 |
+
"""
|
| 1698 |
+
Generate sequences of sample predictions from a model with a probability distribution head.
|
| 1699 |
+
|
| 1700 |
+
Args:
|
| 1701 |
+
past_values (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_input_channels)`):
|
| 1702 |
+
Past values of the time series that serves as context in order to predict the future.
|
| 1703 |
+
|
| 1704 |
+
observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
|
| 1705 |
+
Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
|
| 1706 |
+
in `[0, 1]`:
|
| 1707 |
+
|
| 1708 |
+
- 1 for values that are **observed**,
|
| 1709 |
+
- 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
|
| 1710 |
+
|
| 1711 |
+
Return:
|
| 1712 |
+
[`SamplePatchTSMixerPredictionOutput`] where the outputs `sequences` tensor will have shape `(batch_size,
|
| 1713 |
+
number of samples, prediction_length, num_input_channels)`.
|
| 1714 |
+
"""
|
| 1715 |
+
# get number of samples
|
| 1716 |
+
num_parallel_samples = self.num_parallel_samples
|
| 1717 |
+
|
| 1718 |
+
# get model output
|
| 1719 |
+
outputs = self(
|
| 1720 |
+
past_values=past_values,
|
| 1721 |
+
future_values=None,
|
| 1722 |
+
observed_mask=observed_mask,
|
| 1723 |
+
output_hidden_states=False,
|
| 1724 |
+
)
|
| 1725 |
+
|
| 1726 |
+
# get distribution
|
| 1727 |
+
|
| 1728 |
+
distribution = self.distribution_output.distribution(
|
| 1729 |
+
outputs.prediction_outputs, loc=outputs.loc, scale=outputs.scale
|
| 1730 |
+
)
|
| 1731 |
+
|
| 1732 |
+
# get samples: list of [batch_size x prediction_length x num_channels]
|
| 1733 |
+
samples = [distribution.sample() for _ in range(num_parallel_samples)]
|
| 1734 |
+
|
| 1735 |
+
# stack tensors
|
| 1736 |
+
samples = torch.stack(samples, dim=1) # [batch_size x num_samples x prediction_length x num_channels]
|
| 1737 |
+
return SamplePatchTSMixerPredictionOutput(sequences=samples)
|
| 1738 |
+
|
| 1739 |
+
|
| 1740 |
+
@dataclass
|
| 1741 |
+
@auto_docstring(
|
| 1742 |
+
custom_intro="""
|
| 1743 |
+
Output type of [`PatchTSMixerForTimeSeriesClassificationOutput`].
|
| 1744 |
+
"""
|
| 1745 |
+
)
|
| 1746 |
+
class PatchTSMixerForTimeSeriesClassificationOutput(ModelOutput):
|
| 1747 |
+
r"""
|
| 1748 |
+
loss (*optional*, returned when `y` is provided, `torch.FloatTensor` of shape `()`):
|
| 1749 |
+
Total loss.
|
| 1750 |
+
prediction_outputs (`torch.FloatTensor` of shape `(batch_size, num_labels)`):
|
| 1751 |
+
Prediction output from the classification head.
|
| 1752 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_input_channels, num_patches, d_model)`):
|
| 1753 |
+
Backbone embeddings before passing through the head.
|
| 1754 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*):
|
| 1755 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 1756 |
+
"""
|
| 1757 |
+
|
| 1758 |
+
loss: torch.FloatTensor | None = None
|
| 1759 |
+
prediction_outputs: torch.FloatTensor | None = None
|
| 1760 |
+
last_hidden_state: torch.FloatTensor | None = None
|
| 1761 |
+
hidden_states: tuple[torch.FloatTensor] | None = None
|
| 1762 |
+
|
| 1763 |
+
|
| 1764 |
+
class PatchTSMixerForTimeSeriesClassification(PatchTSMixerPreTrainedModel):
|
| 1765 |
+
r"""
|
| 1766 |
+
`PatchTSMixer` for classification application.
|
| 1767 |
+
|
| 1768 |
+
Args:
|
| 1769 |
+
config (`PatchTSMixerConfig`):
|
| 1770 |
+
Configuration.
|
| 1771 |
+
|
| 1772 |
+
Returns:
|
| 1773 |
+
`None`.
|
| 1774 |
+
"""
|
| 1775 |
+
|
| 1776 |
+
def __init__(self, config: PatchTSMixerConfig):
|
| 1777 |
+
super().__init__(config)
|
| 1778 |
+
|
| 1779 |
+
self.model = PatchTSMixerModel(config)
|
| 1780 |
+
self.head = PatchTSMixerLinearHead(
|
| 1781 |
+
config=config,
|
| 1782 |
+
)
|
| 1783 |
+
self.use_return_dict = config.use_return_dict
|
| 1784 |
+
if config.scaling in ["std", "mean", True]:
|
| 1785 |
+
self.inject_scale = InjectScalerStatistics4D(d_model=config.d_model, num_patches=config.num_patches)
|
| 1786 |
+
else:
|
| 1787 |
+
self.inject_scale = None
|
| 1788 |
+
|
| 1789 |
+
# Initialize weights and apply final processing
|
| 1790 |
+
self.post_init()
|
| 1791 |
+
|
| 1792 |
+
@auto_docstring
|
| 1793 |
+
def forward(
|
| 1794 |
+
self,
|
| 1795 |
+
past_values: torch.Tensor,
|
| 1796 |
+
target_values: torch.Tensor | None = None,
|
| 1797 |
+
output_hidden_states: bool | None = False,
|
| 1798 |
+
return_loss: bool = True,
|
| 1799 |
+
return_dict: bool | None = None,
|
| 1800 |
+
**kwargs,
|
| 1801 |
+
) -> PatchTSMixerForTimeSeriesClassificationOutput:
|
| 1802 |
+
r"""
|
| 1803 |
+
past_values (`torch.FloatTensor` of shape `(batch_size, seq_length, num_input_channels)`):
|
| 1804 |
+
Context values of the time series. For a pretraining task, this denotes the input time series to predict
|
| 1805 |
+
the masked portion. For a forecasting task, this denotes the history/past time series values. Similarly,
|
| 1806 |
+
for classification or regression tasks, it denotes the appropriate context values of the time series.
|
| 1807 |
+
|
| 1808 |
+
For univariate time series, `num_input_channels` dimension should be 1. For multivariate time series, it is
|
| 1809 |
+
greater than 1.
|
| 1810 |
+
target_values (`torch.FloatTensor` of shape `(batch_size, target_len, num_input_channels)` for forecasting,
|
| 1811 |
+
`(batch_size, num_targets)` for regression, or `(batch_size,)` for classification, *optional*):
|
| 1812 |
+
Target
|
| 1813 |
+
values of the time series, that serve as labels for the model. The `target_values` is what the
|
| 1814 |
+
Transformer needs during training to learn to output, given the `past_values`. Note that, this is NOT
|
| 1815 |
+
required for a pretraining task.
|
| 1816 |
+
|
| 1817 |
+
For a forecasting task, the shape is be `(batch_size, target_len, num_input_channels)`. Even if we want
|
| 1818 |
+
to forecast only specific channels by setting the indices in `prediction_channel_indices` parameter,
|
| 1819 |
+
pass the target data with all channels, as channel Filtering for both prediction and target will be
|
| 1820 |
+
manually applied before the loss computation.
|
| 1821 |
+
|
| 1822 |
+
For a classification task, it has a shape of `(batch_size,)`.
|
| 1823 |
+
|
| 1824 |
+
For a regression task, it has a shape of `(batch_size, num_targets)`.
|
| 1825 |
+
return_loss (`bool`, *optional*):
|
| 1826 |
+
Whether to return the loss in the `forward` call.
|
| 1827 |
+
"""
|
| 1828 |
+
|
| 1829 |
+
loss = torch.nn.CrossEntropyLoss()
|
| 1830 |
+
|
| 1831 |
+
return_dict = return_dict if return_dict is not None else self.use_return_dict
|
| 1832 |
+
|
| 1833 |
+
model_output = self.model(
|
| 1834 |
+
past_values,
|
| 1835 |
+
output_hidden_states=output_hidden_states,
|
| 1836 |
+
return_dict=return_dict,
|
| 1837 |
+
) # x: [batch_size x nvars x num_patch x d_model]
|
| 1838 |
+
if isinstance(model_output, tuple):
|
| 1839 |
+
model_output = PatchTSMixerModelOutput(*model_output)
|
| 1840 |
+
|
| 1841 |
+
if self.inject_scale is not None:
|
| 1842 |
+
model_output.last_hidden_state = self.inject_scale(
|
| 1843 |
+
model_output.last_hidden_state,
|
| 1844 |
+
loc=model_output.loc,
|
| 1845 |
+
scale=model_output.scale,
|
| 1846 |
+
) # x: [batch_size x nvars x num_patch x d_model]
|
| 1847 |
+
|
| 1848 |
+
y_hat = self.head(model_output.last_hidden_state) # tensor [batch_size x n_labels]
|
| 1849 |
+
|
| 1850 |
+
if target_values is not None and return_loss is True:
|
| 1851 |
+
loss_val = loss(y_hat, target_values)
|
| 1852 |
+
else:
|
| 1853 |
+
loss_val = None
|
| 1854 |
+
|
| 1855 |
+
if not return_dict:
|
| 1856 |
+
return tuple(
|
| 1857 |
+
v
|
| 1858 |
+
for v in [
|
| 1859 |
+
loss_val,
|
| 1860 |
+
y_hat,
|
| 1861 |
+
model_output.last_hidden_state,
|
| 1862 |
+
model_output.hidden_states,
|
| 1863 |
+
]
|
| 1864 |
+
)
|
| 1865 |
+
|
| 1866 |
+
return PatchTSMixerForTimeSeriesClassificationOutput(
|
| 1867 |
+
loss=loss_val,
|
| 1868 |
+
prediction_outputs=y_hat, # tensor [batch_size x n_labels]
|
| 1869 |
+
last_hidden_state=model_output.last_hidden_state, # x: [batch_size x nvars x num_patch x d_model]
|
| 1870 |
+
hidden_states=model_output.hidden_states,
|
| 1871 |
+
)
|
| 1872 |
+
|
| 1873 |
+
|
| 1874 |
+
@dataclass
|
| 1875 |
+
@auto_docstring(
|
| 1876 |
+
custom_intro="""
|
| 1877 |
+
Output type of [`PatchTSMixerForRegressionOutput`].
|
| 1878 |
+
"""
|
| 1879 |
+
)
|
| 1880 |
+
class PatchTSMixerForRegressionOutput(ModelOutput):
|
| 1881 |
+
r"""
|
| 1882 |
+
loss (*optional*, returned when `y` is provided, `torch.FloatTensor` of shape `()`):
|
| 1883 |
+
Total loss.
|
| 1884 |
+
regression_outputs (`torch.FloatTensor` of shape `(batch_size, num_targets)`):
|
| 1885 |
+
Prediction output from the regression head.
|
| 1886 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_input_channels, num_patches, d_model)`):
|
| 1887 |
+
Backbone embeddings before passing through the head.
|
| 1888 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*):
|
| 1889 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 1890 |
+
"""
|
| 1891 |
+
|
| 1892 |
+
loss: torch.FloatTensor | None = None
|
| 1893 |
+
regression_outputs: torch.FloatTensor | None = None
|
| 1894 |
+
last_hidden_state: torch.FloatTensor | None = None
|
| 1895 |
+
hidden_states: tuple[torch.FloatTensor] | None = None
|
| 1896 |
+
|
| 1897 |
+
|
| 1898 |
+
class InjectScalerStatistics4D(nn.Module):
|
| 1899 |
+
def __init__(self, d_model: int, num_patches: int, expansion: int = 2):
|
| 1900 |
+
super().__init__()
|
| 1901 |
+
|
| 1902 |
+
self.inverse_trans_expansion = nn.Linear(d_model + 2, expansion * d_model)
|
| 1903 |
+
self.inverse_trans_compression = nn.Linear(expansion * d_model, d_model)
|
| 1904 |
+
self.map_scale_expansion = nn.Linear(2, 2 * expansion)
|
| 1905 |
+
self.map_scale_compression = nn.Linear(2 * expansion, 2)
|
| 1906 |
+
self.num_patches = num_patches
|
| 1907 |
+
|
| 1908 |
+
def forward(self, inputs: torch.Tensor, loc: torch.Tensor, scale: torch.Tensor):
|
| 1909 |
+
"""
|
| 1910 |
+
Args:
|
| 1911 |
+
inputs (`torch.Tensor` of shape `(batch_size, num_input_channels, num_patch, d_model)`)
|
| 1912 |
+
loc (`torch.Tensor` of shape `(batch_size, 1, num_input_channels)`)
|
| 1913 |
+
scale (`torch.Tensor` of shape `(batch_size, 1, num_input_channels)`)
|
| 1914 |
+
Returns:
|
| 1915 |
+
`torch.Tensor` of shape `(batch_size, num_input_channels, num_patch, d_model)`
|
| 1916 |
+
"""
|
| 1917 |
+
|
| 1918 |
+
mean = loc.transpose(-1, -2) # [batch_size x n_channels x 1 ]
|
| 1919 |
+
mean = mean.unsqueeze(-2) # [batch_size x n_channels x 1 x 1]
|
| 1920 |
+
mean = mean.repeat(1, 1, self.num_patches, 1) # [batch_size x n_channels x num_patch x 1]
|
| 1921 |
+
|
| 1922 |
+
stdev = scale.transpose(-1, -2) # [batch_size x n_channels x 1 ]
|
| 1923 |
+
stdev = stdev.unsqueeze(-2) # [batch_size x n_channels x 1 x 1]
|
| 1924 |
+
stdev = stdev.repeat(1, 1, self.num_patches, 1) # [batch_size x n_channels x num_patch x 1]
|
| 1925 |
+
|
| 1926 |
+
concat_stats = torch.cat([mean, stdev], dim=-1) # [batch_size x n_channels x num_patch x 2]
|
| 1927 |
+
|
| 1928 |
+
concat_stats = self.map_scale_expansion(concat_stats) # [batch_size x n_channels x num_patch x (2*expansion)]
|
| 1929 |
+
concat_stats = self.map_scale_compression(concat_stats) # [batch_size x n_channels x num_patch x 2]
|
| 1930 |
+
|
| 1931 |
+
inputs = torch.cat([inputs, concat_stats], dim=-1) # [batch_size x channels x num_patch x d_model+2]
|
| 1932 |
+
inputs = self.inverse_trans_expansion(inputs) # [batch_size x channels x num_patch x (expansion*d_model)]
|
| 1933 |
+
inputs = self.inverse_trans_compression(inputs) # [batch_size x channels x num_patch x d_model]
|
| 1934 |
+
|
| 1935 |
+
return inputs
|
| 1936 |
+
|
| 1937 |
+
|
| 1938 |
+
@auto_docstring(
|
| 1939 |
+
custom_intro="""
|
| 1940 |
+
`PatchTSMixer` for regression application.
|
| 1941 |
+
"""
|
| 1942 |
+
)
|
| 1943 |
+
class PatchTSMixerForRegression(PatchTSMixerPreTrainedModel):
|
| 1944 |
+
def __init__(self, config: PatchTSMixerConfig):
|
| 1945 |
+
super().__init__(config)
|
| 1946 |
+
|
| 1947 |
+
self.model = PatchTSMixerModel(config)
|
| 1948 |
+
|
| 1949 |
+
self.loss = config.loss
|
| 1950 |
+
self.distribution_output = config.distribution_output
|
| 1951 |
+
|
| 1952 |
+
self.use_return_dict = config.use_return_dict
|
| 1953 |
+
self.num_parallel_samples = config.num_parallel_samples
|
| 1954 |
+
|
| 1955 |
+
if config.loss == "mse":
|
| 1956 |
+
self.distribution_output = None
|
| 1957 |
+
else:
|
| 1958 |
+
distribution_output_map = {
|
| 1959 |
+
"student_t": StudentTOutput,
|
| 1960 |
+
"normal": NormalOutput,
|
| 1961 |
+
"negative_binomial": NegativeBinomialOutput,
|
| 1962 |
+
}
|
| 1963 |
+
output_class = distribution_output_map.get(config.distribution_output)
|
| 1964 |
+
if output_class is not None:
|
| 1965 |
+
self.distribution_output = output_class(dim=config.num_targets)
|
| 1966 |
+
else:
|
| 1967 |
+
raise ValueError(f"Unknown distribution output {config.distribution_output}")
|
| 1968 |
+
|
| 1969 |
+
if config.scaling in ["std", "mean", True]:
|
| 1970 |
+
self.inject_scale = InjectScalerStatistics4D(d_model=config.d_model, num_patches=config.num_patches)
|
| 1971 |
+
else:
|
| 1972 |
+
self.inject_scale = None
|
| 1973 |
+
|
| 1974 |
+
self.head = PatchTSMixerLinearHead(
|
| 1975 |
+
config=config,
|
| 1976 |
+
distribution_output=self.distribution_output,
|
| 1977 |
+
)
|
| 1978 |
+
|
| 1979 |
+
# Initialize weights and apply final processing
|
| 1980 |
+
self.post_init()
|
| 1981 |
+
|
| 1982 |
+
@auto_docstring
|
| 1983 |
+
def forward(
|
| 1984 |
+
self,
|
| 1985 |
+
past_values: torch.Tensor,
|
| 1986 |
+
target_values: torch.Tensor | None = None,
|
| 1987 |
+
output_hidden_states: bool | None = False,
|
| 1988 |
+
return_loss: bool = True,
|
| 1989 |
+
return_dict: bool | None = None,
|
| 1990 |
+
**kwargs,
|
| 1991 |
+
) -> PatchTSMixerForRegressionOutput:
|
| 1992 |
+
r"""
|
| 1993 |
+
past_values (`torch.FloatTensor` of shape `(batch_size, seq_length, num_input_channels)`):
|
| 1994 |
+
Context values of the time series. For a pretraining task, this denotes the input time series to predict
|
| 1995 |
+
the masked portion. For a forecasting task, this denotes the history/past time series values. Similarly,
|
| 1996 |
+
for classification or regression tasks, it denotes the appropriate context values of the time series.
|
| 1997 |
+
|
| 1998 |
+
For univariate time series, `num_input_channels` dimension should be 1. For multivariate time series, it is
|
| 1999 |
+
greater than 1.
|
| 2000 |
+
target_values (`torch.FloatTensor` of shape `(batch_size, target_len, num_input_channels)` for forecasting,
|
| 2001 |
+
`(batch_size, num_targets)` for regression, or `(batch_size,)` for classification, *optional*):
|
| 2002 |
+
Target values of the time series, that serve as labels for the model. The `target_values` is what the
|
| 2003 |
+
Transformer needs during training to learn to output, given the `past_values`. Note that, this is NOT
|
| 2004 |
+
required for a pretraining task.
|
| 2005 |
+
|
| 2006 |
+
For a forecasting task, the shape is be `(batch_size, target_len, num_input_channels)`. Even if we want
|
| 2007 |
+
to forecast only specific channels by setting the indices in `prediction_channel_indices` parameter,
|
| 2008 |
+
pass the target data with all channels, as channel Filtering for both prediction and target will be
|
| 2009 |
+
manually applied before the loss computation.
|
| 2010 |
+
|
| 2011 |
+
For a classification task, it has a shape of `(batch_size,)`.
|
| 2012 |
+
|
| 2013 |
+
For a regression task, it has a shape of `(batch_size, num_targets)`.
|
| 2014 |
+
return_loss (`bool`, *optional*):
|
| 2015 |
+
Whether to return the loss in the `forward` call.
|
| 2016 |
+
"""
|
| 2017 |
+
|
| 2018 |
+
if self.loss == "mse":
|
| 2019 |
+
loss = nn.MSELoss(reduction="mean")
|
| 2020 |
+
elif self.loss == "nll":
|
| 2021 |
+
loss = nll
|
| 2022 |
+
else:
|
| 2023 |
+
raise ValueError("Invalid loss function: Allowed values: mse and nll")
|
| 2024 |
+
|
| 2025 |
+
return_dict = return_dict if return_dict is not None else self.use_return_dict
|
| 2026 |
+
model_output = self.model(
|
| 2027 |
+
past_values,
|
| 2028 |
+
output_hidden_states=output_hidden_states,
|
| 2029 |
+
return_dict=return_dict,
|
| 2030 |
+
) # model_output: [batch_size x nvars x num_patch x d_model]
|
| 2031 |
+
if isinstance(model_output, tuple):
|
| 2032 |
+
model_output = PatchTSMixerModelOutput(*model_output)
|
| 2033 |
+
|
| 2034 |
+
if self.inject_scale is not None:
|
| 2035 |
+
model_output.last_hidden_state = self.inject_scale(
|
| 2036 |
+
model_output.last_hidden_state,
|
| 2037 |
+
loc=model_output.loc,
|
| 2038 |
+
scale=model_output.scale,
|
| 2039 |
+
) # x: [batch_size x nvars x num_patch x d_model]
|
| 2040 |
+
|
| 2041 |
+
y_hat = self.head(model_output.last_hidden_state) # [batch_size x num_targets]
|
| 2042 |
+
|
| 2043 |
+
if target_values is not None and return_loss is True:
|
| 2044 |
+
if self.distribution_output:
|
| 2045 |
+
if self.distribution_output == "negative_binomial" and torch.any(target_values < 0):
|
| 2046 |
+
raise Exception("target_values cannot be negative for negative_binomial distribution.")
|
| 2047 |
+
distribution = self.distribution_output.distribution(y_hat)
|
| 2048 |
+
# y_hat should be a 2-tuple, each with dimension [bs, num_targets]
|
| 2049 |
+
y_hat = tuple(item.view(-1, self.config.num_targets) for item in y_hat)
|
| 2050 |
+
loss_val = loss(distribution, target_values)
|
| 2051 |
+
# take average of the loss
|
| 2052 |
+
loss_val = weighted_average(loss_val)
|
| 2053 |
+
else:
|
| 2054 |
+
loss_val = loss(y_hat, target_values)
|
| 2055 |
+
else:
|
| 2056 |
+
loss_val = None
|
| 2057 |
+
|
| 2058 |
+
if not return_dict:
|
| 2059 |
+
return tuple(
|
| 2060 |
+
v
|
| 2061 |
+
for v in [
|
| 2062 |
+
loss_val,
|
| 2063 |
+
y_hat,
|
| 2064 |
+
model_output.last_hidden_state,
|
| 2065 |
+
model_output.hidden_states,
|
| 2066 |
+
]
|
| 2067 |
+
)
|
| 2068 |
+
|
| 2069 |
+
return PatchTSMixerForRegressionOutput(
|
| 2070 |
+
loss=loss_val,
|
| 2071 |
+
regression_outputs=y_hat, # tensor [batch_size x num_targets]
|
| 2072 |
+
last_hidden_state=model_output.last_hidden_state, # [batch_size x nvars x num_patch x d_model]
|
| 2073 |
+
hidden_states=model_output.hidden_states,
|
| 2074 |
+
)
|
| 2075 |
+
|
| 2076 |
+
@torch.no_grad()
|
| 2077 |
+
def generate(
|
| 2078 |
+
self,
|
| 2079 |
+
past_values: torch.Tensor,
|
| 2080 |
+
) -> SamplePatchTSMixerRegressionOutput:
|
| 2081 |
+
"""
|
| 2082 |
+
Generate sequences of sample predictions from a model with a probability distribution head.
|
| 2083 |
+
|
| 2084 |
+
Args:
|
| 2085 |
+
past_values (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_input_channels)`):
|
| 2086 |
+
Past values of the time series that serves as context in order to predict the target values.
|
| 2087 |
+
|
| 2088 |
+
Return:
|
| 2089 |
+
[`SamplePatchTSMixerRegressionOutput`] where the outputs `sequences` tensor will have shape `(batch_size,
|
| 2090 |
+
number of samples, num_targets)`.
|
| 2091 |
+
"""
|
| 2092 |
+
# get number of samples
|
| 2093 |
+
num_parallel_samples = self.num_parallel_samples
|
| 2094 |
+
|
| 2095 |
+
# get model output
|
| 2096 |
+
outputs = self(
|
| 2097 |
+
past_values=past_values,
|
| 2098 |
+
target_values=None,
|
| 2099 |
+
output_hidden_states=False,
|
| 2100 |
+
)
|
| 2101 |
+
|
| 2102 |
+
# get distribution
|
| 2103 |
+
distribution = self.distribution_output.distribution(outputs.regression_outputs)
|
| 2104 |
+
|
| 2105 |
+
# get samples
|
| 2106 |
+
samples = [
|
| 2107 |
+
distribution.sample() for _ in range(num_parallel_samples)
|
| 2108 |
+
] # samples: list of [batch_size x num_targets]
|
| 2109 |
+
# stack tensors
|
| 2110 |
+
# [batch_size x num_samples x num_targets]
|
| 2111 |
+
samples = torch.stack(samples, dim=1).view(-1, num_parallel_samples, self.config.num_targets)
|
| 2112 |
+
return SamplePatchTSMixerRegressionOutput(sequences=samples)
|
| 2113 |
+
|
| 2114 |
+
|
| 2115 |
+
__all__ = [
|
| 2116 |
+
"PatchTSMixerPreTrainedModel",
|
| 2117 |
+
"PatchTSMixerModel",
|
| 2118 |
+
"PatchTSMixerForPretraining",
|
| 2119 |
+
"PatchTSMixerForPrediction",
|
| 2120 |
+
"PatchTSMixerForTimeSeriesClassification",
|
| 2121 |
+
"PatchTSMixerForRegression",
|
| 2122 |
+
]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/patchtst/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_patchtst import *
|
| 22 |
+
from .modeling_patchtst import *
|
| 23 |
+
else:
|
| 24 |
+
import sys
|
| 25 |
+
|
| 26 |
+
_file = globals()["__file__"]
|
| 27 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/patchtst/configuration_patchtst.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""PatchTST model configuration"""
|
| 15 |
+
|
| 16 |
+
from transformers.configuration_utils import PreTrainedConfig
|
| 17 |
+
from transformers.utils import logging
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
logger = logging.get_logger(__name__)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class PatchTSTConfig(PreTrainedConfig):
|
| 24 |
+
r"""
|
| 25 |
+
This is the configuration class to store the configuration of an [`PatchTSTModel`]. It is used to instantiate an
|
| 26 |
+
PatchTST model according to the specified arguments, defining the model architecture.
|
| 27 |
+
[ibm/patchtst](https://huggingface.co/ibm/patchtst) architecture.
|
| 28 |
+
|
| 29 |
+
Configuration objects inherit from [`PreTrainedConfig`] can be used to control the model outputs. Read the
|
| 30 |
+
documentation from [`PreTrainedConfig`] for more information.
|
| 31 |
+
|
| 32 |
+
Args:
|
| 33 |
+
num_input_channels (`int`, *optional*, defaults to 1):
|
| 34 |
+
The size of the target variable which by default is 1 for univariate targets. Would be > 1 in case of
|
| 35 |
+
multivariate targets.
|
| 36 |
+
context_length (`int`, *optional*, defaults to 32):
|
| 37 |
+
The context length of the input sequence.
|
| 38 |
+
distribution_output (`str`, *optional*, defaults to `"student_t"`):
|
| 39 |
+
The distribution emission head for the model when loss is "nll". Could be either "student_t", "normal" or
|
| 40 |
+
"negative_binomial".
|
| 41 |
+
loss (`str`, *optional*, defaults to `"mse"`):
|
| 42 |
+
The loss function for the model corresponding to the `distribution_output` head. For parametric
|
| 43 |
+
distributions it is the negative log likelihood ("nll") and for point estimates it is the mean squared
|
| 44 |
+
error "mse".
|
| 45 |
+
patch_length (`int`, *optional*, defaults to 1):
|
| 46 |
+
Define the patch length of the patchification process.
|
| 47 |
+
patch_stride (`int`, *optional*, defaults to 1):
|
| 48 |
+
Define the stride of the patchification process.
|
| 49 |
+
num_hidden_layers (`int`, *optional*, defaults to 3):
|
| 50 |
+
Number of hidden layers.
|
| 51 |
+
d_model (`int`, *optional*, defaults to 128):
|
| 52 |
+
Dimensionality of the transformer layers.
|
| 53 |
+
num_attention_heads (`int`, *optional*, defaults to 4):
|
| 54 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 55 |
+
share_embedding (`bool`, *optional*, defaults to `True`):
|
| 56 |
+
Sharing the input embedding across all channels.
|
| 57 |
+
channel_attention (`bool`, *optional*, defaults to `False`):
|
| 58 |
+
Activate channel attention block in the Transformer to allow channels to attend each other.
|
| 59 |
+
ffn_dim (`int`, *optional*, defaults to 512):
|
| 60 |
+
Dimension of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
|
| 61 |
+
norm_type (`str` , *optional*, defaults to `"batchnorm"`):
|
| 62 |
+
Normalization at each Transformer layer. Can be `"batchnorm"` or `"layernorm"`.
|
| 63 |
+
norm_eps (`float`, *optional*, defaults to 1e-05):
|
| 64 |
+
A value added to the denominator for numerical stability of normalization.
|
| 65 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 66 |
+
The dropout probability for the attention probabilities.
|
| 67 |
+
positional_dropout (`float`, *optional*, defaults to 0.0):
|
| 68 |
+
The dropout probability in the positional embedding layer.
|
| 69 |
+
path_dropout (`float`, *optional*, defaults to 0.0):
|
| 70 |
+
The dropout path in the residual block.
|
| 71 |
+
ff_dropout (`float`, *optional*, defaults to 0.0):
|
| 72 |
+
The dropout probability used between the two layers of the feed-forward networks.
|
| 73 |
+
bias (`bool`, *optional*, defaults to `True`):
|
| 74 |
+
Whether to add bias in the feed-forward networks.
|
| 75 |
+
activation_function (`str`, *optional*, defaults to `"gelu"`):
|
| 76 |
+
The non-linear activation function (string) in the Transformer.`"gelu"` and `"relu"` are supported.
|
| 77 |
+
pre_norm (`bool`, *optional*, defaults to `True`):
|
| 78 |
+
Normalization is applied before self-attention if pre_norm is set to `True`. Otherwise, normalization is
|
| 79 |
+
applied after residual block.
|
| 80 |
+
positional_encoding_type (`str`, *optional*, defaults to `"sincos"`):
|
| 81 |
+
Positional encodings. Options `"random"` and `"sincos"` are supported.
|
| 82 |
+
use_cls_token (`bool`, *optional*, defaults to `False`):
|
| 83 |
+
Whether cls token is used.
|
| 84 |
+
init_std (`float`, *optional*, defaults to 0.02):
|
| 85 |
+
The standard deviation of the truncated normal weight initialization distribution.
|
| 86 |
+
share_projection (`bool`, *optional*, defaults to `True`):
|
| 87 |
+
Sharing the projection layer across different channels in the forecast head.
|
| 88 |
+
scaling (`Union`, *optional*, defaults to `"std"`):
|
| 89 |
+
Whether to scale the input targets via "mean" scaler, "std" scaler or no scaler if `None`. If `True`, the
|
| 90 |
+
scaler is set to "mean".
|
| 91 |
+
do_mask_input (`bool`, *optional*):
|
| 92 |
+
Apply masking during the pretraining.
|
| 93 |
+
mask_type (`str`, *optional*, defaults to `"random"`):
|
| 94 |
+
Masking type. Only `"random"` and `"forecast"` are currently supported.
|
| 95 |
+
random_mask_ratio (`float`, *optional*, defaults to 0.5):
|
| 96 |
+
Masking ratio applied to mask the input data during random pretraining.
|
| 97 |
+
num_forecast_mask_patches (`int` or `list`, *optional*, defaults to `[2]`):
|
| 98 |
+
Number of patches to be masked at the end of each batch sample. If it is an integer,
|
| 99 |
+
all the samples in the batch will have the same number of masked patches. If it is a list,
|
| 100 |
+
samples in the batch will be randomly masked by numbers defined in the list. This argument is only used
|
| 101 |
+
for forecast pretraining.
|
| 102 |
+
channel_consistent_masking (`bool`, *optional*, defaults to `False`):
|
| 103 |
+
If channel consistent masking is True, all the channels will have the same masking pattern.
|
| 104 |
+
unmasked_channel_indices (`list`, *optional*):
|
| 105 |
+
Indices of channels that are not masked during pretraining. Values in the list are number between 1 and
|
| 106 |
+
`num_input_channels`
|
| 107 |
+
mask_value (`int`, *optional*, defaults to 0):
|
| 108 |
+
Values in the masked patches will be filled by `mask_value`.
|
| 109 |
+
pooling_type (`str`, *optional*, defaults to `"mean"`):
|
| 110 |
+
Pooling of the embedding. `"mean"`, `"max"` and `None` are supported.
|
| 111 |
+
head_dropout (`float`, *optional*, defaults to 0.0):
|
| 112 |
+
The dropout probability for head.
|
| 113 |
+
prediction_length (`int`, *optional*, defaults to 24):
|
| 114 |
+
The prediction horizon that the model will output.
|
| 115 |
+
num_targets (`int`, *optional*, defaults to 1):
|
| 116 |
+
Number of targets for regression and classification tasks. For classification, it is the number of
|
| 117 |
+
classes.
|
| 118 |
+
output_range (`list`, *optional*):
|
| 119 |
+
Output range for regression task. The range of output values can be set to enforce the model to produce
|
| 120 |
+
values within a range.
|
| 121 |
+
num_parallel_samples (`int`, *optional*, defaults to 100):
|
| 122 |
+
The number of samples is generated in parallel for probabilistic prediction.
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
```python
|
| 126 |
+
>>> from transformers import PatchTSTConfig, PatchTSTModel
|
| 127 |
+
|
| 128 |
+
>>> # Initializing an PatchTST configuration with 12 time steps for prediction
|
| 129 |
+
>>> configuration = PatchTSTConfig(prediction_length=12)
|
| 130 |
+
|
| 131 |
+
>>> # Randomly initializing a model (with random weights) from the configuration
|
| 132 |
+
>>> model = PatchTSTModel(configuration)
|
| 133 |
+
|
| 134 |
+
>>> # Accessing the model configuration
|
| 135 |
+
>>> configuration = model.config
|
| 136 |
+
```"""
|
| 137 |
+
|
| 138 |
+
model_type = "patchtst"
|
| 139 |
+
attribute_map = {
|
| 140 |
+
"hidden_size": "d_model",
|
| 141 |
+
"num_attention_heads": "num_attention_heads",
|
| 142 |
+
"num_hidden_layers": "num_hidden_layers",
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
def __init__(
|
| 146 |
+
self,
|
| 147 |
+
# time series specific configuration
|
| 148 |
+
num_input_channels: int = 1,
|
| 149 |
+
context_length: int = 32,
|
| 150 |
+
distribution_output: str = "student_t",
|
| 151 |
+
loss: str = "mse",
|
| 152 |
+
# PatchTST arguments
|
| 153 |
+
patch_length: int = 1,
|
| 154 |
+
patch_stride: int = 1,
|
| 155 |
+
# Transformer architecture configuration
|
| 156 |
+
num_hidden_layers: int = 3,
|
| 157 |
+
d_model: int = 128,
|
| 158 |
+
num_attention_heads: int = 4,
|
| 159 |
+
share_embedding: bool = True,
|
| 160 |
+
channel_attention: bool = False,
|
| 161 |
+
ffn_dim: int = 512,
|
| 162 |
+
norm_type: str = "batchnorm",
|
| 163 |
+
norm_eps: float = 1e-05,
|
| 164 |
+
attention_dropout: float = 0.0,
|
| 165 |
+
positional_dropout: float = 0.0,
|
| 166 |
+
path_dropout: float = 0.0,
|
| 167 |
+
ff_dropout: float = 0.0,
|
| 168 |
+
bias: bool = True,
|
| 169 |
+
activation_function: str = "gelu",
|
| 170 |
+
pre_norm: bool = True,
|
| 171 |
+
positional_encoding_type: str = "sincos",
|
| 172 |
+
use_cls_token: bool = False,
|
| 173 |
+
init_std: float = 0.02,
|
| 174 |
+
share_projection: bool = True,
|
| 175 |
+
scaling: str | bool | None = "std",
|
| 176 |
+
# mask pretraining
|
| 177 |
+
do_mask_input: bool | None = None,
|
| 178 |
+
mask_type: str = "random",
|
| 179 |
+
random_mask_ratio: float = 0.5,
|
| 180 |
+
num_forecast_mask_patches: list[int] | int | None = [2],
|
| 181 |
+
channel_consistent_masking: bool | None = False,
|
| 182 |
+
unmasked_channel_indices: list[int] | None = None,
|
| 183 |
+
mask_value: int = 0,
|
| 184 |
+
# head
|
| 185 |
+
pooling_type: str = "mean",
|
| 186 |
+
head_dropout: float = 0.0,
|
| 187 |
+
prediction_length: int = 24,
|
| 188 |
+
num_targets: int = 1,
|
| 189 |
+
output_range: list | None = None,
|
| 190 |
+
# distribution head
|
| 191 |
+
num_parallel_samples: int = 100,
|
| 192 |
+
**kwargs,
|
| 193 |
+
):
|
| 194 |
+
# time series specific configuration
|
| 195 |
+
self.context_length = context_length
|
| 196 |
+
self.num_input_channels = num_input_channels # n_vars
|
| 197 |
+
self.loss = loss
|
| 198 |
+
self.distribution_output = distribution_output
|
| 199 |
+
self.num_parallel_samples = num_parallel_samples
|
| 200 |
+
|
| 201 |
+
# Transformer architecture configuration
|
| 202 |
+
self.d_model = d_model
|
| 203 |
+
self.num_attention_heads = num_attention_heads
|
| 204 |
+
self.ffn_dim = ffn_dim
|
| 205 |
+
self.num_hidden_layers = num_hidden_layers
|
| 206 |
+
self.attention_dropout = attention_dropout
|
| 207 |
+
self.share_embedding = share_embedding
|
| 208 |
+
self.channel_attention = channel_attention
|
| 209 |
+
self.norm_type = norm_type
|
| 210 |
+
self.norm_eps = norm_eps
|
| 211 |
+
self.positional_dropout = positional_dropout
|
| 212 |
+
self.path_dropout = path_dropout
|
| 213 |
+
self.ff_dropout = ff_dropout
|
| 214 |
+
self.bias = bias
|
| 215 |
+
self.activation_function = activation_function
|
| 216 |
+
self.pre_norm = pre_norm
|
| 217 |
+
self.positional_encoding_type = positional_encoding_type
|
| 218 |
+
self.use_cls_token = use_cls_token
|
| 219 |
+
self.init_std = init_std
|
| 220 |
+
self.scaling = scaling
|
| 221 |
+
|
| 222 |
+
# PatchTST parameters
|
| 223 |
+
self.patch_length = patch_length
|
| 224 |
+
self.patch_stride = patch_stride
|
| 225 |
+
|
| 226 |
+
# Mask pretraining
|
| 227 |
+
self.do_mask_input = do_mask_input
|
| 228 |
+
self.mask_type = mask_type
|
| 229 |
+
self.random_mask_ratio = random_mask_ratio # for random masking
|
| 230 |
+
self.num_forecast_mask_patches = num_forecast_mask_patches # for forecast masking
|
| 231 |
+
self.channel_consistent_masking = channel_consistent_masking
|
| 232 |
+
self.unmasked_channel_indices = unmasked_channel_indices
|
| 233 |
+
self.mask_value = mask_value
|
| 234 |
+
|
| 235 |
+
# general head params
|
| 236 |
+
self.pooling_type = pooling_type
|
| 237 |
+
self.head_dropout = head_dropout
|
| 238 |
+
|
| 239 |
+
# For prediction head
|
| 240 |
+
self.share_projection = share_projection
|
| 241 |
+
self.prediction_length = prediction_length
|
| 242 |
+
|
| 243 |
+
# For prediction and regression head
|
| 244 |
+
self.num_parallel_samples = num_parallel_samples
|
| 245 |
+
|
| 246 |
+
# Regression
|
| 247 |
+
self.num_targets = num_targets
|
| 248 |
+
self.output_range = output_range
|
| 249 |
+
|
| 250 |
+
super().__init__(**kwargs)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
__all__ = ["PatchTSTConfig"]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/patchtst/modeling_patchtst.py
ADDED
|
@@ -0,0 +1,1974 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 IBM & Hugging Face. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""PyTorch PatchTST model."""
|
| 15 |
+
|
| 16 |
+
import math
|
| 17 |
+
from collections.abc import Callable
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
from torch import nn
|
| 22 |
+
|
| 23 |
+
from ... import initialization as init
|
| 24 |
+
from ...activations import ACT2CLS
|
| 25 |
+
from ...integrations.deepspeed import is_deepspeed_zero3_enabled
|
| 26 |
+
from ...modeling_flash_attention_utils import FlashAttentionKwargs
|
| 27 |
+
from ...modeling_outputs import BaseModelOutput
|
| 28 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 29 |
+
from ...processing_utils import Unpack
|
| 30 |
+
from ...time_series_utils import NegativeBinomialOutput, NormalOutput, StudentTOutput
|
| 31 |
+
from ...utils import ModelOutput, TransformersKwargs, auto_docstring, logging
|
| 32 |
+
from .configuration_patchtst import PatchTSTConfig
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
logger = logging.get_logger(__name__)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# Copied from transformers.models.bert.modeling_bert.eager_attention_forward
|
| 39 |
+
def eager_attention_forward(
|
| 40 |
+
module: nn.Module,
|
| 41 |
+
query: torch.Tensor,
|
| 42 |
+
key: torch.Tensor,
|
| 43 |
+
value: torch.Tensor,
|
| 44 |
+
attention_mask: torch.Tensor | None,
|
| 45 |
+
scaling: float | None = None,
|
| 46 |
+
dropout: float = 0.0,
|
| 47 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 48 |
+
):
|
| 49 |
+
if scaling is None:
|
| 50 |
+
scaling = query.size(-1) ** -0.5
|
| 51 |
+
|
| 52 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 53 |
+
attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
|
| 54 |
+
|
| 55 |
+
if attention_mask is not None:
|
| 56 |
+
attn_weights = attn_weights + attention_mask
|
| 57 |
+
|
| 58 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 59 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 60 |
+
|
| 61 |
+
attn_output = torch.matmul(attn_weights, value)
|
| 62 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 63 |
+
|
| 64 |
+
return attn_output, attn_weights
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2Attention with Wav2Vec2->PatchTST
|
| 68 |
+
class PatchTSTAttention(nn.Module):
|
| 69 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 70 |
+
|
| 71 |
+
def __init__(
|
| 72 |
+
self,
|
| 73 |
+
embed_dim: int,
|
| 74 |
+
num_heads: int,
|
| 75 |
+
dropout: float = 0.0,
|
| 76 |
+
is_decoder: bool = False,
|
| 77 |
+
bias: bool = True,
|
| 78 |
+
is_causal: bool = False,
|
| 79 |
+
config: PatchTSTConfig | None = None,
|
| 80 |
+
):
|
| 81 |
+
super().__init__()
|
| 82 |
+
self.embed_dim = embed_dim
|
| 83 |
+
self.num_heads = num_heads
|
| 84 |
+
self.dropout = dropout
|
| 85 |
+
self.head_dim = embed_dim // num_heads
|
| 86 |
+
self.config = config
|
| 87 |
+
|
| 88 |
+
if (self.head_dim * num_heads) != self.embed_dim:
|
| 89 |
+
raise ValueError(
|
| 90 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
|
| 91 |
+
f" and `num_heads`: {num_heads})."
|
| 92 |
+
)
|
| 93 |
+
self.scaling = self.head_dim**-0.5
|
| 94 |
+
self.is_decoder = is_decoder
|
| 95 |
+
self.is_causal = is_causal
|
| 96 |
+
|
| 97 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 98 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 99 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 100 |
+
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 101 |
+
|
| 102 |
+
def forward(
|
| 103 |
+
self,
|
| 104 |
+
hidden_states: torch.Tensor,
|
| 105 |
+
key_value_states: torch.Tensor | None = None,
|
| 106 |
+
attention_mask: torch.Tensor | None = None,
|
| 107 |
+
output_attentions: bool | None = False,
|
| 108 |
+
# TODO: we need a refactor so that the different attention modules can get their specific kwargs
|
| 109 |
+
# ATM, we have mixed things encoder, decoder, and encoder-decoder attn
|
| 110 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 111 |
+
) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
|
| 112 |
+
"""Input shape: Batch x Time x Channel"""
|
| 113 |
+
|
| 114 |
+
# if key_value_states are provided this layer is used as a cross-attention layer
|
| 115 |
+
# for the decoder
|
| 116 |
+
is_cross_attention = key_value_states is not None
|
| 117 |
+
|
| 118 |
+
# determine input shapes
|
| 119 |
+
bsz, tgt_len = hidden_states.shape[:-1]
|
| 120 |
+
src_len = key_value_states.shape[1] if is_cross_attention else tgt_len
|
| 121 |
+
|
| 122 |
+
q_input_shape = (bsz, tgt_len, -1, self.head_dim)
|
| 123 |
+
kv_input_shape = (bsz, src_len, -1, self.head_dim)
|
| 124 |
+
|
| 125 |
+
# get query proj
|
| 126 |
+
query_states = self.q_proj(hidden_states).view(*q_input_shape).transpose(1, 2)
|
| 127 |
+
|
| 128 |
+
current_states = key_value_states if is_cross_attention else hidden_states
|
| 129 |
+
key_states = self.k_proj(current_states).view(*kv_input_shape).transpose(1, 2)
|
| 130 |
+
value_states = self.v_proj(current_states).view(*kv_input_shape).transpose(1, 2)
|
| 131 |
+
|
| 132 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 133 |
+
self.config._attn_implementation, eager_attention_forward
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
attn_output, attn_weights = attention_interface(
|
| 137 |
+
self,
|
| 138 |
+
query_states,
|
| 139 |
+
key_states,
|
| 140 |
+
value_states,
|
| 141 |
+
attention_mask,
|
| 142 |
+
dropout=0.0 if not self.training else self.dropout,
|
| 143 |
+
scaling=self.scaling,
|
| 144 |
+
output_attentions=output_attentions,
|
| 145 |
+
**kwargs,
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
attn_output = attn_output.reshape(bsz, tgt_len, -1).contiguous()
|
| 149 |
+
attn_output = self.out_proj(attn_output)
|
| 150 |
+
|
| 151 |
+
return attn_output, attn_weights, None
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
class PatchTSTBatchNorm(nn.Module):
|
| 155 |
+
"""
|
| 156 |
+
Compute batch normalization over the sequence length (time) dimension.
|
| 157 |
+
"""
|
| 158 |
+
|
| 159 |
+
def __init__(self, config: PatchTSTConfig):
|
| 160 |
+
super().__init__()
|
| 161 |
+
self.batchnorm = nn.BatchNorm1d(config.d_model, eps=config.norm_eps)
|
| 162 |
+
|
| 163 |
+
def forward(self, inputs: torch.Tensor):
|
| 164 |
+
"""
|
| 165 |
+
Parameters:
|
| 166 |
+
inputs (`torch.Tensor` of shape `(batch_size, sequence_length, d_model)`):
|
| 167 |
+
input for Batch norm calculation
|
| 168 |
+
Returns:
|
| 169 |
+
`torch.Tensor` of shape `(batch_size, sequence_length, d_model)`
|
| 170 |
+
"""
|
| 171 |
+
output = inputs.transpose(1, 2) # output: (batch_size, d_model, sequence_length)
|
| 172 |
+
output = self.batchnorm(output)
|
| 173 |
+
return output.transpose(1, 2)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def random_masking(
|
| 177 |
+
inputs: torch.Tensor,
|
| 178 |
+
mask_ratio: float,
|
| 179 |
+
unmasked_channel_indices: list | None = None,
|
| 180 |
+
channel_consistent_masking: bool = False,
|
| 181 |
+
mask_value: int = 0,
|
| 182 |
+
):
|
| 183 |
+
"""random_masking: Mask the input considering the control variables.
|
| 184 |
+
|
| 185 |
+
Args:
|
| 186 |
+
inputs (`torch.Tensor` of shape `(batch_size, num_channels, sequence_length, num_features)`):
|
| 187 |
+
The input tensor to mask.
|
| 188 |
+
mask_ratio (`float`):
|
| 189 |
+
Masking ratio applied to mask the input data during random pretraining. It is the number between 0 and 1.
|
| 190 |
+
unmasked_channel_indices (list, *optional*):
|
| 191 |
+
Indices of channels that will not be masked.
|
| 192 |
+
channel_consistent_masking (bool, *optional*, defaults to `False`):
|
| 193 |
+
When true, masking will be same across all channels of a timeseries. Otherwise, masking positions will vary
|
| 194 |
+
across channels.
|
| 195 |
+
mask_value (int, *optional*, defaults to 0):
|
| 196 |
+
Define the value of masked patches for pretraining.
|
| 197 |
+
|
| 198 |
+
Returns:
|
| 199 |
+
`tuple(torch.Tensor)`: inputs_mask, masked input, same shape as input Tensor and mask tensor of shape [bs x c x
|
| 200 |
+
n]
|
| 201 |
+
"""
|
| 202 |
+
if mask_ratio < 0 or mask_ratio >= 1:
|
| 203 |
+
raise ValueError(f"Mask ratio {mask_ratio} has to be between 0 and 1.")
|
| 204 |
+
|
| 205 |
+
batch_size, num_channels, sequence_length, num_features = inputs.shape
|
| 206 |
+
device = inputs.device
|
| 207 |
+
|
| 208 |
+
len_keep = int(sequence_length * (1 - mask_ratio))
|
| 209 |
+
|
| 210 |
+
if channel_consistent_masking:
|
| 211 |
+
noise = torch.rand(batch_size, 1, sequence_length, device=device) # noise in [0, 1], bs x 1 x L
|
| 212 |
+
noise = noise.repeat(1, num_channels, 1) # bs x num_channels x time
|
| 213 |
+
else:
|
| 214 |
+
# noise in [0, 1], bs x num_channels x L
|
| 215 |
+
noise = torch.rand(batch_size, num_channels, sequence_length, device=device)
|
| 216 |
+
|
| 217 |
+
# mask: [bs x num_channels x num_patch]
|
| 218 |
+
mask = torch.ones(batch_size, num_channels, sequence_length, device=device)
|
| 219 |
+
mask[:, :, :len_keep] = 0
|
| 220 |
+
|
| 221 |
+
# sort noise for each sample
|
| 222 |
+
ids_shuffle = torch.argsort(noise, dim=-1) # ascend: small is keep, large is remove
|
| 223 |
+
ids_restore = torch.argsort(ids_shuffle, dim=-1) # ids_restore: [bs x num_channels x L]
|
| 224 |
+
|
| 225 |
+
mask = torch.gather(mask, dim=-1, index=ids_restore)
|
| 226 |
+
mask = mask.unsqueeze(-1).repeat(1, 1, 1, num_features) # mask: [bs x num_channels x num_patches x patch_length]
|
| 227 |
+
if unmasked_channel_indices is not None:
|
| 228 |
+
mask[:, unmasked_channel_indices, :, :] = 0
|
| 229 |
+
|
| 230 |
+
inputs_mask = inputs.masked_fill(mask.bool(), mask_value)
|
| 231 |
+
return inputs_mask, mask[..., 0]
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def forecast_masking(
|
| 235 |
+
inputs: torch.Tensor,
|
| 236 |
+
num_forecast_mask_patches: list | int,
|
| 237 |
+
unmasked_channel_indices: list | None = None,
|
| 238 |
+
mask_value: int = 0,
|
| 239 |
+
):
|
| 240 |
+
"""Forecast masking that masks the last K patches where K is from the num_forecast_mask_patches.
|
| 241 |
+
If num_forecast_mask_patches is a list, samples in the batch will be randomly masked by numbers defined in the list.
|
| 242 |
+
|
| 243 |
+
Parameters:
|
| 244 |
+
inputs (`torch.Tensor`):
|
| 245 |
+
Input of shape `(bs, num_channels, num_patch, patch_length)`
|
| 246 |
+
num_forecast_mask_patches (`list`):
|
| 247 |
+
Number of patches to be masked at the end of each batch sample. e.g. 4 or [3, 5].
|
| 248 |
+
unmasked_channel_indices (`list`, *optional*):
|
| 249 |
+
Indices of channels that are not masked.
|
| 250 |
+
mask_value (`int`, *optional*, defaults to 0):
|
| 251 |
+
Values in the masked patches will be filled by `mask_value`.
|
| 252 |
+
|
| 253 |
+
Returns:
|
| 254 |
+
`tuple(torch.Tensor)`: inputs_mask, masked input, same shape as inputs Tensor and Mask tensor of shape `(bs,
|
| 255 |
+
num_channels , num_patch)` or `(bs, tsg1, tsg2, num_channels, num_patch)`
|
| 256 |
+
"""
|
| 257 |
+
|
| 258 |
+
if isinstance(num_forecast_mask_patches, int):
|
| 259 |
+
num_forecast_mask_patches = [num_forecast_mask_patches]
|
| 260 |
+
forecast_mask_ratios = [1 for _ in num_forecast_mask_patches]
|
| 261 |
+
|
| 262 |
+
batch_size, num_channels, sequence_length, num_features = inputs.shape
|
| 263 |
+
mask = torch.zeros(batch_size, num_channels, sequence_length, device=inputs.device)
|
| 264 |
+
|
| 265 |
+
t_list = []
|
| 266 |
+
total_length = 0
|
| 267 |
+
total_ratio = sum(forecast_mask_ratios)
|
| 268 |
+
|
| 269 |
+
for patch_length, ratio in zip(num_forecast_mask_patches, forecast_mask_ratios):
|
| 270 |
+
if patch_length <= 0 or patch_length >= sequence_length:
|
| 271 |
+
raise ValueError(
|
| 272 |
+
f"num_forecast_mask_patches {patch_length} should be greater than 0 and less than total patches."
|
| 273 |
+
)
|
| 274 |
+
temp_len = int(batch_size * ratio / total_ratio)
|
| 275 |
+
t_list.append([patch_length, ratio, temp_len])
|
| 276 |
+
total_length += temp_len
|
| 277 |
+
|
| 278 |
+
t_list = sorted(t_list, key=lambda x: x[2])
|
| 279 |
+
|
| 280 |
+
if total_length < batch_size:
|
| 281 |
+
t_list[0][2] = t_list[0][2] + (batch_size - total_length)
|
| 282 |
+
elif total_length > batch_size:
|
| 283 |
+
t_list[-1][2] = t_list[-1][2] + (total_length - batch_size)
|
| 284 |
+
|
| 285 |
+
batch1 = 0
|
| 286 |
+
for patch_len, _, temp_len in t_list:
|
| 287 |
+
batch2 = batch1 + temp_len
|
| 288 |
+
mask[batch1:batch2, :, -patch_len:] = 1
|
| 289 |
+
batch1 = batch2
|
| 290 |
+
|
| 291 |
+
perm = torch.randperm(mask.shape[0])
|
| 292 |
+
mask = mask[perm]
|
| 293 |
+
|
| 294 |
+
mask = mask.unsqueeze(-1).repeat(1, 1, 1, num_features) # mask: [bs x num_channels x num_patch x patch_len]
|
| 295 |
+
if unmasked_channel_indices is not None:
|
| 296 |
+
mask[:, unmasked_channel_indices, :, :] = 0
|
| 297 |
+
|
| 298 |
+
inputs_mask = inputs.masked_fill(mask.bool(), mask_value)
|
| 299 |
+
return inputs_mask, mask[..., 0]
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
class PatchTSTPatchify(nn.Module):
|
| 303 |
+
"""
|
| 304 |
+
A class to patchify the time series sequence into different patches
|
| 305 |
+
|
| 306 |
+
Returns:
|
| 307 |
+
`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`
|
| 308 |
+
"""
|
| 309 |
+
|
| 310 |
+
def __init__(self, config: PatchTSTConfig):
|
| 311 |
+
super().__init__()
|
| 312 |
+
|
| 313 |
+
self.sequence_length = config.context_length
|
| 314 |
+
self.patch_length = config.patch_length
|
| 315 |
+
self.patch_stride = config.patch_stride
|
| 316 |
+
|
| 317 |
+
if self.sequence_length <= self.patch_length:
|
| 318 |
+
raise ValueError(
|
| 319 |
+
f"Sequence length ({self.sequence_length}) has to be greater than the patch length ({self.patch_length})"
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
# get the number of patches
|
| 323 |
+
self.num_patches = (max(self.sequence_length, self.patch_length) - self.patch_length) // self.patch_stride + 1
|
| 324 |
+
new_sequence_length = self.patch_length + self.patch_stride * (self.num_patches - 1)
|
| 325 |
+
self.sequence_start = self.sequence_length - new_sequence_length
|
| 326 |
+
|
| 327 |
+
def forward(self, past_values: torch.Tensor):
|
| 328 |
+
"""
|
| 329 |
+
Parameters:
|
| 330 |
+
past_values (`torch.Tensor` of shape `(batch_size, sequence_length, num_channels)`, *required*):
|
| 331 |
+
Input for patchification
|
| 332 |
+
|
| 333 |
+
Returns:
|
| 334 |
+
`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`
|
| 335 |
+
"""
|
| 336 |
+
sequence_length = past_values.shape[-2]
|
| 337 |
+
if sequence_length != self.sequence_length:
|
| 338 |
+
raise ValueError(
|
| 339 |
+
f"Input sequence length ({sequence_length}) doesn't match model configuration ({self.sequence_length})."
|
| 340 |
+
)
|
| 341 |
+
# output: [bs x new_sequence_length x num_channels]
|
| 342 |
+
output = past_values[:, self.sequence_start :, :]
|
| 343 |
+
# output: [bs x num_patches x num_input_channels x patch_length]
|
| 344 |
+
output = output.unfold(dimension=-2, size=self.patch_length, step=self.patch_stride)
|
| 345 |
+
# output: [bs x num_input_channels x num_patches x patch_length]
|
| 346 |
+
output = output.transpose(-2, -3).contiguous()
|
| 347 |
+
return output
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
class PatchTSTMasking(nn.Module):
|
| 351 |
+
"""
|
| 352 |
+
Class to perform random or forecast masking.
|
| 353 |
+
|
| 354 |
+
Parameters:
|
| 355 |
+
config (`PatchTSTConfig`): model config
|
| 356 |
+
Returns:
|
| 357 |
+
x_mask (`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`)
|
| 358 |
+
Masked patched input
|
| 359 |
+
mask (`torch.Tensor` of shape `(batch_size, num_channels, num_patches)`)
|
| 360 |
+
Bool tensor indicating True on masked points
|
| 361 |
+
"""
|
| 362 |
+
|
| 363 |
+
def __init__(self, config: PatchTSTConfig):
|
| 364 |
+
super().__init__()
|
| 365 |
+
self.random_mask_ratio = config.random_mask_ratio
|
| 366 |
+
self.channel_consistent_masking = config.channel_consistent_masking
|
| 367 |
+
self.mask_type = config.mask_type
|
| 368 |
+
self.num_forecast_mask_patches = config.num_forecast_mask_patches
|
| 369 |
+
self.unmasked_channel_indices = config.unmasked_channel_indices
|
| 370 |
+
self.mask_value = config.mask_value
|
| 371 |
+
if self.unmasked_channel_indices is not None:
|
| 372 |
+
self.unmasked_channel_indices = sorted(self.unmasked_channel_indices)
|
| 373 |
+
|
| 374 |
+
def forward(self, patch_input: torch.Tensor):
|
| 375 |
+
"""
|
| 376 |
+
Parameters:
|
| 377 |
+
patch_input (`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`, *required*):
|
| 378 |
+
Patch input
|
| 379 |
+
|
| 380 |
+
Return:
|
| 381 |
+
masked_input (`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`)
|
| 382 |
+
Masked patched input
|
| 383 |
+
mask (`torch.Tensor` of shape `(batch_size, num_channels, num_patches)`)
|
| 384 |
+
Bool tensor indicating True on masked points
|
| 385 |
+
|
| 386 |
+
"""
|
| 387 |
+
if self.mask_type == "random":
|
| 388 |
+
masked_input, mask = random_masking(
|
| 389 |
+
inputs=patch_input,
|
| 390 |
+
mask_ratio=self.random_mask_ratio,
|
| 391 |
+
unmasked_channel_indices=self.unmasked_channel_indices,
|
| 392 |
+
channel_consistent_masking=self.channel_consistent_masking,
|
| 393 |
+
mask_value=self.mask_value,
|
| 394 |
+
)
|
| 395 |
+
elif self.mask_type == "forecast":
|
| 396 |
+
masked_input, mask = forecast_masking(
|
| 397 |
+
inputs=patch_input,
|
| 398 |
+
num_forecast_mask_patches=self.num_forecast_mask_patches,
|
| 399 |
+
unmasked_channel_indices=self.unmasked_channel_indices,
|
| 400 |
+
mask_value=self.mask_value,
|
| 401 |
+
)
|
| 402 |
+
else:
|
| 403 |
+
raise ValueError(f"Invalid mask type {self.mask_type}.")
|
| 404 |
+
|
| 405 |
+
# mask: [bs x num_input_channels x num_patch]
|
| 406 |
+
mask = mask.bool()
|
| 407 |
+
return masked_input, mask
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
class PatchTSTEncoderLayer(nn.Module):
|
| 411 |
+
"""
|
| 412 |
+
PatchTST encoder layer
|
| 413 |
+
"""
|
| 414 |
+
|
| 415 |
+
def __init__(self, config: PatchTSTConfig):
|
| 416 |
+
super().__init__()
|
| 417 |
+
|
| 418 |
+
self.channel_attention = config.channel_attention
|
| 419 |
+
|
| 420 |
+
self.self_attn = PatchTSTAttention(
|
| 421 |
+
embed_dim=config.d_model,
|
| 422 |
+
num_heads=config.num_attention_heads,
|
| 423 |
+
dropout=config.attention_dropout,
|
| 424 |
+
config=config,
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
# Add & Norm of the sublayer 1
|
| 428 |
+
self.dropout_path1 = nn.Dropout(config.path_dropout) if config.path_dropout > 0 else nn.Identity()
|
| 429 |
+
if config.norm_type == "batchnorm":
|
| 430 |
+
self.norm_sublayer1 = PatchTSTBatchNorm(config)
|
| 431 |
+
elif config.norm_type == "layernorm":
|
| 432 |
+
self.norm_sublayer1 = nn.LayerNorm(config.d_model, eps=config.norm_eps)
|
| 433 |
+
else:
|
| 434 |
+
raise ValueError(f"{config.norm_type} is not a supported norm layer type.")
|
| 435 |
+
|
| 436 |
+
# Add & Norm of the sublayer 2
|
| 437 |
+
if self.channel_attention:
|
| 438 |
+
self.dropout_path2 = nn.Dropout(config.path_dropout) if config.path_dropout > 0 else nn.Identity()
|
| 439 |
+
if config.norm_type == "batchnorm":
|
| 440 |
+
self.norm_sublayer2 = PatchTSTBatchNorm(config)
|
| 441 |
+
elif config.norm_type == "layernorm":
|
| 442 |
+
self.norm_sublayer2 = nn.LayerNorm(config.d_model, eps=config.norm_eps)
|
| 443 |
+
else:
|
| 444 |
+
raise ValueError(f"{config.norm_type} is not a supported norm layer type.")
|
| 445 |
+
|
| 446 |
+
# Position-wise Feed-Forward
|
| 447 |
+
self.ff = nn.Sequential(
|
| 448 |
+
nn.Linear(config.d_model, config.ffn_dim, bias=config.bias),
|
| 449 |
+
ACT2CLS[config.activation_function](),
|
| 450 |
+
nn.Dropout(config.ff_dropout) if config.ff_dropout > 0 else nn.Identity(),
|
| 451 |
+
nn.Linear(config.ffn_dim, config.d_model, bias=config.bias),
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
# Add & Norm of sublayer 3
|
| 455 |
+
self.dropout_path3 = nn.Dropout(config.path_dropout) if config.path_dropout > 0 else nn.Identity()
|
| 456 |
+
if config.norm_type == "batchnorm":
|
| 457 |
+
self.norm_sublayer3 = PatchTSTBatchNorm(config)
|
| 458 |
+
elif config.norm_type == "layernorm":
|
| 459 |
+
self.norm_sublayer3 = nn.LayerNorm(config.d_model, eps=config.norm_eps)
|
| 460 |
+
else:
|
| 461 |
+
raise ValueError(f"{config.norm_type} is not a supported norm layer type.")
|
| 462 |
+
|
| 463 |
+
self.pre_norm = config.pre_norm
|
| 464 |
+
|
| 465 |
+
def forward(self, hidden_state: torch.Tensor, output_attentions: bool | None = None):
|
| 466 |
+
"""
|
| 467 |
+
Parameters:
|
| 468 |
+
hidden_state (`torch.Tensor` of shape `(batch_size, num_channels, sequence_length, d_model)`, *required*):
|
| 469 |
+
Past values of the time series
|
| 470 |
+
output_attentions (`bool`, *optional*):
|
| 471 |
+
Whether or not to return the output attention of all layers
|
| 472 |
+
Return:
|
| 473 |
+
`torch.Tensor` of shape `(batch_size, num_channels, sequence_length, d_model)`
|
| 474 |
+
|
| 475 |
+
"""
|
| 476 |
+
batch_size, num_input_channels, sequence_length, d_model = hidden_state.shape
|
| 477 |
+
|
| 478 |
+
# First sublayer: attention across time
|
| 479 |
+
# hidden_states: [(bs*num_channels) x sequence_length x d_model]
|
| 480 |
+
hidden_state = hidden_state.view(batch_size * num_input_channels, sequence_length, d_model)
|
| 481 |
+
|
| 482 |
+
if self.pre_norm:
|
| 483 |
+
## Norm and Multi-Head attention and Add residual connection
|
| 484 |
+
attn_output, attn_weights, _ = self.self_attn(
|
| 485 |
+
hidden_states=self.norm_sublayer1(hidden_state), output_attentions=output_attentions
|
| 486 |
+
)
|
| 487 |
+
# Add: residual connection with residual dropout
|
| 488 |
+
hidden_state = hidden_state + self.dropout_path1(attn_output)
|
| 489 |
+
else:
|
| 490 |
+
## Multi-Head attention and Add residual connection and Norm - Standard Transformer from BERT
|
| 491 |
+
attn_output, attn_weights, _ = self.self_attn(
|
| 492 |
+
hidden_states=hidden_state, output_attentions=output_attentions
|
| 493 |
+
)
|
| 494 |
+
# hidden_states: [(bs*num_channels) x sequence_length x d_model]
|
| 495 |
+
hidden_state = self.norm_sublayer1(hidden_state + self.dropout_path1(attn_output))
|
| 496 |
+
|
| 497 |
+
# hidden_state: [bs x num_channels x sequence_length x d_model]
|
| 498 |
+
hidden_state = hidden_state.reshape(batch_size, num_input_channels, sequence_length, d_model)
|
| 499 |
+
|
| 500 |
+
# second sublayer: attention across variable at any given time
|
| 501 |
+
if self.channel_attention:
|
| 502 |
+
# hidden_state: [bs x sequence_length x num_channels x d_model]
|
| 503 |
+
hidden_state = hidden_state.transpose(2, 1).contiguous()
|
| 504 |
+
# hidden_state: [(bs*sequence_length) x num_channels x d_model]
|
| 505 |
+
hidden_state = hidden_state.view(batch_size * sequence_length, num_input_channels, d_model)
|
| 506 |
+
if self.pre_norm:
|
| 507 |
+
## Norm and Multi-Head attention and Add residual connection
|
| 508 |
+
attn_output, channel_attn_weights, _ = self.self_attn(
|
| 509 |
+
hidden_states=self.norm_sublayer2(hidden_state), output_attentions=output_attentions
|
| 510 |
+
)
|
| 511 |
+
# Add: residual connection with residual dropout
|
| 512 |
+
hidden_state = hidden_state + self.dropout_path2(attn_output)
|
| 513 |
+
else:
|
| 514 |
+
## Multi-Head attention and Add residual connection and Norm
|
| 515 |
+
attn_output, channel_attn_weights, _ = self.self_attn(
|
| 516 |
+
hidden_states=hidden_state, output_attentions=output_attentions
|
| 517 |
+
)
|
| 518 |
+
# hidden_states: [(bs*sequence_length) x num_channels x d_model]
|
| 519 |
+
hidden_state = self.norm_sublayer2(hidden_state + self.dropout_path2(attn_output))
|
| 520 |
+
|
| 521 |
+
# Reshape hidden state
|
| 522 |
+
# hidden_state: [bs x sequence_length x num_channels x d_model]
|
| 523 |
+
hidden_state = hidden_state.reshape(batch_size, sequence_length, num_input_channels, d_model)
|
| 524 |
+
# hidden_state: [bs x num_channels x sequence_length x d_model]
|
| 525 |
+
hidden_state = hidden_state.transpose(1, 2).contiguous()
|
| 526 |
+
|
| 527 |
+
# Third sublayer: mixing across hidden
|
| 528 |
+
# hidden_state: [(batch_size*num_channels) x sequence_length x d_model]
|
| 529 |
+
hidden_state = hidden_state.view(batch_size * num_input_channels, sequence_length, d_model)
|
| 530 |
+
if self.pre_norm:
|
| 531 |
+
## Norm and Position-wise Feed-Forward and Add residual connection
|
| 532 |
+
# Add: residual connection with residual dropout
|
| 533 |
+
hidden_state = hidden_state + self.dropout_path3(self.ff(self.norm_sublayer3(hidden_state)))
|
| 534 |
+
else:
|
| 535 |
+
## Position-wise Feed-Forward and Add residual connection and Norm
|
| 536 |
+
# Add: residual connection with residual dropout
|
| 537 |
+
hidden_state = self.norm_sublayer3(hidden_state + self.dropout_path3(self.ff(hidden_state)))
|
| 538 |
+
|
| 539 |
+
# [bs x num_channels x sequence_length x d_model]
|
| 540 |
+
hidden_state = hidden_state.reshape(batch_size, num_input_channels, sequence_length, d_model)
|
| 541 |
+
|
| 542 |
+
outputs = (hidden_state,)
|
| 543 |
+
if output_attentions:
|
| 544 |
+
outputs += (attn_weights, channel_attn_weights) if self.channel_attention else (attn_weights,)
|
| 545 |
+
|
| 546 |
+
return outputs
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
@auto_docstring
|
| 550 |
+
class PatchTSTPreTrainedModel(PreTrainedModel):
|
| 551 |
+
config: PatchTSTConfig
|
| 552 |
+
base_model_prefix = "model"
|
| 553 |
+
main_input_name = "past_values"
|
| 554 |
+
input_modalities = ("time",)
|
| 555 |
+
supports_gradient_checkpointing = False
|
| 556 |
+
_supports_flash_attn = True
|
| 557 |
+
_supports_sdpa = True
|
| 558 |
+
_supports_flex_attn = True
|
| 559 |
+
|
| 560 |
+
@torch.no_grad()
|
| 561 |
+
def _init_weights(self, module: nn.Module):
|
| 562 |
+
"""
|
| 563 |
+
Initialize weights
|
| 564 |
+
"""
|
| 565 |
+
if isinstance(module, PatchTSTPositionalEncoding):
|
| 566 |
+
# get the number of patches
|
| 567 |
+
num_patches = (
|
| 568 |
+
max(self.config.context_length, self.config.patch_length) - self.config.patch_length
|
| 569 |
+
) // self.config.patch_stride + 1
|
| 570 |
+
# initialize cls_token
|
| 571 |
+
if self.config.use_cls_token:
|
| 572 |
+
init.normal_(module.cls_token, std=0.02)
|
| 573 |
+
num_patches += 1
|
| 574 |
+
# initialize positional encoding
|
| 575 |
+
position_enc = module._init_pe(self.config, num_patches)
|
| 576 |
+
if is_deepspeed_zero3_enabled():
|
| 577 |
+
import deepspeed
|
| 578 |
+
|
| 579 |
+
with deepspeed.zero.GatheredParameters(module.position_enc, modifier_rank=None):
|
| 580 |
+
if module.position_enc.numel() > 0:
|
| 581 |
+
init.copy_(module.position_enc, position_enc)
|
| 582 |
+
else:
|
| 583 |
+
init.copy_(module.position_enc, position_enc)
|
| 584 |
+
elif isinstance(module, (nn.LayerNorm, nn.BatchNorm1d)):
|
| 585 |
+
init.zeros_(module.bias)
|
| 586 |
+
init.ones_(module.weight)
|
| 587 |
+
if getattr(module, "running_mean", None) is not None:
|
| 588 |
+
init.zeros_(module.running_mean)
|
| 589 |
+
init.ones_(module.running_var)
|
| 590 |
+
init.zeros_(module.num_batches_tracked)
|
| 591 |
+
elif isinstance(module, nn.Linear):
|
| 592 |
+
init.normal_(module.weight, mean=0.0, std=self.config.init_std)
|
| 593 |
+
if module.bias is not None:
|
| 594 |
+
init.zeros_(module.bias)
|
| 595 |
+
|
| 596 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
| 597 |
+
if isinstance(module, (PatchTSTEncoder)):
|
| 598 |
+
module.gradient_checkpointing = value
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
class PatchTSTEmbedding(nn.Module):
|
| 602 |
+
def __init__(self, config: PatchTSTConfig):
|
| 603 |
+
super().__init__()
|
| 604 |
+
self.num_input_channels = config.num_input_channels
|
| 605 |
+
self.share_embedding = config.share_embedding
|
| 606 |
+
# Input encoding: projection of feature vectors onto a d-dim vector space
|
| 607 |
+
if self.share_embedding:
|
| 608 |
+
self.input_embedding = nn.Linear(config.patch_length, config.d_model)
|
| 609 |
+
else:
|
| 610 |
+
self.input_embedding = nn.ModuleList()
|
| 611 |
+
for _ in range(config.num_input_channels):
|
| 612 |
+
self.input_embedding.append(nn.Linear(config.patch_length, config.d_model))
|
| 613 |
+
|
| 614 |
+
def forward(self, patch_input: torch.Tensor):
|
| 615 |
+
"""
|
| 616 |
+
Parameters:
|
| 617 |
+
patch_input (`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`, *required*):
|
| 618 |
+
Patch input for embedding
|
| 619 |
+
return:
|
| 620 |
+
`torch.Tensor` of shape `(batch_size, num_channels, num_patches, d_model)`
|
| 621 |
+
"""
|
| 622 |
+
# Input encoding
|
| 623 |
+
num_input_channels = patch_input.shape[1]
|
| 624 |
+
if num_input_channels != self.num_input_channels:
|
| 625 |
+
raise ValueError(
|
| 626 |
+
f"The defined number of input channels ({self.num_input_channels}) in the config "
|
| 627 |
+
f"has to be the same as the number of channels in the batch input ({num_input_channels})"
|
| 628 |
+
)
|
| 629 |
+
if self.share_embedding:
|
| 630 |
+
embeddings = self.input_embedding(patch_input) # x: [bs x num_channels x num_patches x d_model]
|
| 631 |
+
else:
|
| 632 |
+
embeddings = [self.input_embedding[i](patch_input[:, i, :, :]) for i in range(num_input_channels)]
|
| 633 |
+
embeddings = torch.stack(embeddings, dim=1)
|
| 634 |
+
return embeddings
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
class PatchTSTPositionalEncoding(nn.Module):
|
| 638 |
+
"""
|
| 639 |
+
Class for positional encoding
|
| 640 |
+
"""
|
| 641 |
+
|
| 642 |
+
def __init__(self, config: PatchTSTConfig, num_patches: int):
|
| 643 |
+
super().__init__()
|
| 644 |
+
self.use_cls_token = config.use_cls_token
|
| 645 |
+
self.num_input_channels = config.num_input_channels
|
| 646 |
+
if config.use_cls_token:
|
| 647 |
+
# cls_token: [1 x num_input_channels x 1 x d_model]
|
| 648 |
+
self.cls_token = nn.Parameter(torch.zeros(1, 1, 1, config.d_model))
|
| 649 |
+
num_patches += 1
|
| 650 |
+
# positional encoding: [num_patches x d_model]
|
| 651 |
+
self.position_enc = self._init_pe(config, num_patches)
|
| 652 |
+
# Positional dropout
|
| 653 |
+
self.positional_dropout = (
|
| 654 |
+
nn.Dropout(config.positional_dropout) if config.positional_dropout > 0 else nn.Identity()
|
| 655 |
+
)
|
| 656 |
+
|
| 657 |
+
@staticmethod
|
| 658 |
+
def _init_pe(config: PatchTSTConfig, num_patches: int) -> nn.Parameter:
|
| 659 |
+
# Positional encoding
|
| 660 |
+
if config.positional_encoding_type == "random":
|
| 661 |
+
position_enc = nn.Parameter(torch.randn(num_patches, config.d_model), requires_grad=True)
|
| 662 |
+
elif config.positional_encoding_type == "sincos":
|
| 663 |
+
position_enc = torch.zeros(num_patches, config.d_model)
|
| 664 |
+
position = torch.arange(0, num_patches).unsqueeze(1)
|
| 665 |
+
div_term = torch.exp(torch.arange(0, config.d_model, 2) * -(math.log(10000.0) / config.d_model))
|
| 666 |
+
position_enc[:, 0::2] = torch.sin(position * div_term)
|
| 667 |
+
position_enc[:, 1::2] = torch.cos(position * div_term)
|
| 668 |
+
position_enc = position_enc - position_enc.mean()
|
| 669 |
+
position_enc = position_enc / (position_enc.std() * 10)
|
| 670 |
+
position_enc = nn.Parameter(position_enc, requires_grad=False)
|
| 671 |
+
else:
|
| 672 |
+
raise ValueError(
|
| 673 |
+
f"{config.positional_encoding_type} is not a valid positional encoder. Available types are 'random' and 'sincos'."
|
| 674 |
+
)
|
| 675 |
+
return position_enc
|
| 676 |
+
|
| 677 |
+
def forward(self, patch_input: torch.Tensor):
|
| 678 |
+
if self.use_cls_token:
|
| 679 |
+
# patch_input: [bs x num_channels x num_patches x d_model]
|
| 680 |
+
patch_input = self.positional_dropout(patch_input + self.position_enc[1:, :])
|
| 681 |
+
# append cls token where cls_token: [1 x num_channels x 1 x d_model]
|
| 682 |
+
cls_token = self.cls_token + self.position_enc[:1, :]
|
| 683 |
+
# get the same copy of cls_token for all the samples in batch: [bs x num_channels x 1 x d_model]
|
| 684 |
+
cls_tokens = cls_token.expand(patch_input.shape[0], self.num_input_channels, -1, -1)
|
| 685 |
+
# hidden_state: [bs x num_channels x (num_patches+1) x d_model]
|
| 686 |
+
hidden_state = torch.cat((cls_tokens, patch_input), dim=2)
|
| 687 |
+
else:
|
| 688 |
+
# hidden_state: [bs x num_channels x num_patches x d_model]
|
| 689 |
+
hidden_state = self.positional_dropout(patch_input + self.position_enc)
|
| 690 |
+
return hidden_state
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
class PatchTSTEncoder(PatchTSTPreTrainedModel):
|
| 694 |
+
"""
|
| 695 |
+
PatchTST Encoder
|
| 696 |
+
"""
|
| 697 |
+
|
| 698 |
+
def __init__(self, config: PatchTSTConfig, num_patches: int):
|
| 699 |
+
super().__init__(config)
|
| 700 |
+
self.gradient_checkpointing = False
|
| 701 |
+
|
| 702 |
+
# Input embedding: projection of feature vectors onto a d-dim vector space
|
| 703 |
+
self.embedder = PatchTSTEmbedding(config)
|
| 704 |
+
# Positional encoding
|
| 705 |
+
self.positional_encoder = PatchTSTPositionalEncoding(config, num_patches)
|
| 706 |
+
# Encoder
|
| 707 |
+
self.layers = nn.ModuleList([PatchTSTEncoderLayer(config) for i in range(config.num_hidden_layers)])
|
| 708 |
+
|
| 709 |
+
# Initialize weights and apply final processing
|
| 710 |
+
self.post_init()
|
| 711 |
+
|
| 712 |
+
def forward(
|
| 713 |
+
self,
|
| 714 |
+
patch_input: torch.Tensor,
|
| 715 |
+
output_hidden_states: bool | None = None,
|
| 716 |
+
output_attentions: bool | None = None,
|
| 717 |
+
**kwargs,
|
| 718 |
+
) -> BaseModelOutput:
|
| 719 |
+
"""
|
| 720 |
+
Parameters:
|
| 721 |
+
patch_input (`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`, *required*):
|
| 722 |
+
Past values of the time series
|
| 723 |
+
output_hidden_states (bool, optional): Indicates if hidden states should be outputted.
|
| 724 |
+
output_attentions (bool, optional): Indicates if attentions should be outputted.
|
| 725 |
+
|
| 726 |
+
return:
|
| 727 |
+
`BaseModelOutput`
|
| 728 |
+
"""
|
| 729 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 730 |
+
output_hidden_states = (
|
| 731 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 732 |
+
)
|
| 733 |
+
|
| 734 |
+
# Input embedding
|
| 735 |
+
patch_input = self.embedder(patch_input)
|
| 736 |
+
# Positional encoding
|
| 737 |
+
hidden_state = self.positional_encoder(patch_input)
|
| 738 |
+
|
| 739 |
+
encoder_states = () if output_hidden_states else None
|
| 740 |
+
all_attentions = () if output_attentions else None
|
| 741 |
+
for encoder_layer in self.layers:
|
| 742 |
+
if output_hidden_states:
|
| 743 |
+
encoder_states = encoder_states + (hidden_state,)
|
| 744 |
+
|
| 745 |
+
layer_outputs = encoder_layer(hidden_state=hidden_state, output_attentions=output_attentions)
|
| 746 |
+
# get hidden state. hidden_state shape is [bs x num_channels x num_patches x d_model]
|
| 747 |
+
# or [bs x num_channels x (num_patches+1) x d_model] if use cls_token
|
| 748 |
+
hidden_state = layer_outputs[0]
|
| 749 |
+
# append attention matrix at each layer
|
| 750 |
+
if output_attentions:
|
| 751 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 752 |
+
# return past_values, hidden_states
|
| 753 |
+
return BaseModelOutput(last_hidden_state=hidden_state, hidden_states=encoder_states, attentions=all_attentions)
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
@dataclass
|
| 757 |
+
@auto_docstring(
|
| 758 |
+
custom_intro="""
|
| 759 |
+
Base class for model's outputs, with potential hidden states.
|
| 760 |
+
"""
|
| 761 |
+
)
|
| 762 |
+
class PatchTSTModelOutput(ModelOutput):
|
| 763 |
+
r"""
|
| 764 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_channels, num_patches, patch_length)`):
|
| 765 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 766 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 767 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 768 |
+
one for the output of each layer) of shape `(batch_size, num_channels, height, width)`. Hidden-states of
|
| 769 |
+
the model at the output of each layer plus the optional initial embedding outputs.
|
| 770 |
+
mask (`torch.FloatTensor` of shape `(batch_size, num_channels, num_patches)`, *optional*):
|
| 771 |
+
Bool masked tensor indicating which patches are masked
|
| 772 |
+
loc (`torch.FloatTensor` of shape `(batch_size, 1, num_channels)`, *optional*):
|
| 773 |
+
Mean of the input data (batch_size, sequence_length, num_channels) over the sequence_length
|
| 774 |
+
scale (`torch.FloatTensor` of shape `(batch_size, 1, num_channels)`, *optional*):
|
| 775 |
+
Std of the input data (batch_size, sequence_length, num_channels) over the sequence_length
|
| 776 |
+
patch_input (`torch.FloatTensor` of shape `(batch_size, num_channels, num_patches, patch_length)`):
|
| 777 |
+
Patched input to the Transformer
|
| 778 |
+
"""
|
| 779 |
+
|
| 780 |
+
last_hidden_state: torch.FloatTensor | None = None
|
| 781 |
+
hidden_states: tuple[torch.FloatTensor] | None = None
|
| 782 |
+
attentions: tuple[torch.FloatTensor] | None = None
|
| 783 |
+
mask: torch.FloatTensor | None = None
|
| 784 |
+
loc: torch.FloatTensor | None = None
|
| 785 |
+
scale: torch.FloatTensor | None = None
|
| 786 |
+
patch_input: torch.FloatTensor | None = None
|
| 787 |
+
|
| 788 |
+
|
| 789 |
+
@dataclass
|
| 790 |
+
@auto_docstring(
|
| 791 |
+
custom_intro="""
|
| 792 |
+
Output type of [`PatchTSTForPretraining`].
|
| 793 |
+
"""
|
| 794 |
+
)
|
| 795 |
+
class PatchTSTForPretrainingOutput(ModelOutput):
|
| 796 |
+
r"""
|
| 797 |
+
loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
|
| 798 |
+
MSE loss.
|
| 799 |
+
prediction_output (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
| 800 |
+
Prediction outputs of the time series modeling heads.
|
| 801 |
+
"""
|
| 802 |
+
|
| 803 |
+
loss: torch.FloatTensor | None = None
|
| 804 |
+
prediction_output: torch.FloatTensor | None = None
|
| 805 |
+
hidden_states: tuple[torch.FloatTensor] | None = None
|
| 806 |
+
attentions: tuple[torch.FloatTensor] | None = None
|
| 807 |
+
|
| 808 |
+
|
| 809 |
+
@dataclass
|
| 810 |
+
@auto_docstring(
|
| 811 |
+
custom_intro="""
|
| 812 |
+
Output type of [`PatchTSTForRegression`].
|
| 813 |
+
"""
|
| 814 |
+
)
|
| 815 |
+
class PatchTSTForRegressionOutput(ModelOutput):
|
| 816 |
+
r"""
|
| 817 |
+
loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
|
| 818 |
+
MSE loss.
|
| 819 |
+
regression_outputs (`torch.FloatTensor` of shape `(batch_size, num_targets)`):
|
| 820 |
+
Regression outputs of the time series modeling heads.
|
| 821 |
+
"""
|
| 822 |
+
|
| 823 |
+
loss: torch.FloatTensor | None = None
|
| 824 |
+
regression_outputs: torch.FloatTensor | None = None
|
| 825 |
+
hidden_states: tuple[torch.FloatTensor] | None = None
|
| 826 |
+
attentions: tuple[torch.FloatTensor] | None = None
|
| 827 |
+
|
| 828 |
+
|
| 829 |
+
@dataclass
|
| 830 |
+
@auto_docstring(
|
| 831 |
+
custom_intro="""
|
| 832 |
+
Output type of [`PatchTSTForPrediction`].
|
| 833 |
+
"""
|
| 834 |
+
)
|
| 835 |
+
class PatchTSTForPredictionOutput(ModelOutput):
|
| 836 |
+
r"""
|
| 837 |
+
loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
|
| 838 |
+
MSE loss.
|
| 839 |
+
prediction_outputs (`torch.FloatTensor` of shape `(batch_size, prediction_length, -1)`):
|
| 840 |
+
Prediction outputs of the time series modeling heads.
|
| 841 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 842 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 843 |
+
sequence_length)`.
|
| 844 |
+
|
| 845 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 846 |
+
heads.
|
| 847 |
+
loc: (`torch.FloatTensor` of shape `(batch_size, 1, num_channels)`, *optional*)
|
| 848 |
+
Mean of the input data (batch_size, sequence_length, num_channels) over the sequence_length
|
| 849 |
+
scale: (`torch.FloatTensor` of shape `(batch_size, 1, num_channels)`, *optional*)
|
| 850 |
+
Std of the input data (batch_size, sequence_length, num_channels) over the sequence_length
|
| 851 |
+
"""
|
| 852 |
+
|
| 853 |
+
loss: torch.FloatTensor | None = None
|
| 854 |
+
prediction_outputs: torch.FloatTensor | None = None
|
| 855 |
+
hidden_states: tuple[torch.FloatTensor] | None = None
|
| 856 |
+
attentions: tuple[torch.FloatTensor] | None = None
|
| 857 |
+
loc: torch.FloatTensor | None = None
|
| 858 |
+
scale: torch.FloatTensor | None = None
|
| 859 |
+
|
| 860 |
+
|
| 861 |
+
@dataclass
|
| 862 |
+
@auto_docstring(
|
| 863 |
+
custom_intro="""
|
| 864 |
+
Output type of [`PatchTSTForClassification`].
|
| 865 |
+
"""
|
| 866 |
+
)
|
| 867 |
+
class PatchTSTForClassificationOutput(ModelOutput):
|
| 868 |
+
r"""
|
| 869 |
+
loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
|
| 870 |
+
Total loss as the sum of the masked language modeling loss and the next sequence prediction
|
| 871 |
+
(classification) loss.
|
| 872 |
+
prediction_logits (`torch.FloatTensor` of shape `(batch_size, num_targets)`):
|
| 873 |
+
Prediction scores of the PatchTST modeling head (scores before SoftMax).
|
| 874 |
+
"""
|
| 875 |
+
|
| 876 |
+
loss: torch.FloatTensor | None = None
|
| 877 |
+
prediction_logits: torch.FloatTensor | None = None
|
| 878 |
+
hidden_states: tuple[torch.FloatTensor] | None = None
|
| 879 |
+
attentions: tuple[torch.FloatTensor] | None = None
|
| 880 |
+
|
| 881 |
+
|
| 882 |
+
@dataclass
|
| 883 |
+
@auto_docstring(
|
| 884 |
+
custom_intro="""
|
| 885 |
+
Base class for time series model's predictions outputs that contains the sampled values from the chosen
|
| 886 |
+
distribution.
|
| 887 |
+
"""
|
| 888 |
+
)
|
| 889 |
+
class SamplePatchTSTOutput(ModelOutput):
|
| 890 |
+
r"""
|
| 891 |
+
sequences (`torch.FloatTensor` of shape `(batch_size, num_samples, prediction_length, num_targets)`):
|
| 892 |
+
Sampled values from the chosen distribution.
|
| 893 |
+
"""
|
| 894 |
+
|
| 895 |
+
sequences: torch.FloatTensor | None = None
|
| 896 |
+
|
| 897 |
+
|
| 898 |
+
# Copied from transformers.models.time_series_transformer.modeling_time_series_transformer.nll
|
| 899 |
+
def nll(input: torch.distributions.Distribution, target: torch.Tensor) -> torch.Tensor:
|
| 900 |
+
"""
|
| 901 |
+
Computes the negative log likelihood loss from input distribution with respect to target.
|
| 902 |
+
"""
|
| 903 |
+
return -input.log_prob(target)
|
| 904 |
+
|
| 905 |
+
|
| 906 |
+
# Copied from transformers.models.time_series_transformer.modeling_time_series_transformer.weighted_average
|
| 907 |
+
def weighted_average(input_tensor: torch.Tensor, weights: torch.Tensor | None = None, dim=None) -> torch.Tensor:
|
| 908 |
+
"""
|
| 909 |
+
Computes the weighted average of a given tensor across a given `dim`, masking values associated with weight zero,
|
| 910 |
+
meaning instead of `nan * 0 = nan` you will get `0 * 0 = 0`.
|
| 911 |
+
|
| 912 |
+
Args:
|
| 913 |
+
input_tensor (`torch.FloatTensor`):
|
| 914 |
+
Input tensor, of which the average must be computed.
|
| 915 |
+
weights (`torch.FloatTensor`, *optional*):
|
| 916 |
+
Weights tensor, of the same shape as `input_tensor`.
|
| 917 |
+
dim (`int`, *optional*):
|
| 918 |
+
The dim along which to average `input_tensor`.
|
| 919 |
+
|
| 920 |
+
Returns:
|
| 921 |
+
`torch.FloatTensor`: The tensor with values averaged along the specified `dim`.
|
| 922 |
+
"""
|
| 923 |
+
if weights is not None:
|
| 924 |
+
weighted_tensor = torch.where(weights != 0, input_tensor * weights, torch.zeros_like(input_tensor))
|
| 925 |
+
sum_weights = torch.clamp(weights.sum(dim=dim) if dim else weights.sum(), min=1.0)
|
| 926 |
+
return (weighted_tensor.sum(dim=dim) if dim else weighted_tensor.sum()) / sum_weights
|
| 927 |
+
else:
|
| 928 |
+
return input_tensor.mean(dim=dim)
|
| 929 |
+
|
| 930 |
+
|
| 931 |
+
# Copied from transformers.models.time_series_transformer.modeling_time_series_transformer.TimeSeriesStdScaler with TimeSeriesTransformer->PatchTST,TimeSeries->PatchTST
|
| 932 |
+
class PatchTSTStdScaler(nn.Module):
|
| 933 |
+
"""
|
| 934 |
+
Standardize features by calculating the mean and scaling along the first dimension, and then normalizes it by
|
| 935 |
+
subtracting from the mean and dividing by the standard deviation.
|
| 936 |
+
"""
|
| 937 |
+
|
| 938 |
+
def __init__(self, config: PatchTSTConfig):
|
| 939 |
+
super().__init__()
|
| 940 |
+
self.dim = config.scaling_dim if hasattr(config, "scaling_dim") else 1
|
| 941 |
+
self.keepdim = config.keepdim if hasattr(config, "keepdim") else True
|
| 942 |
+
self.minimum_scale = config.minimum_scale if hasattr(config, "minimum_scale") else 1e-5
|
| 943 |
+
|
| 944 |
+
def forward(
|
| 945 |
+
self, data: torch.Tensor, observed_indicator: torch.Tensor
|
| 946 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 947 |
+
"""
|
| 948 |
+
Parameters:
|
| 949 |
+
data (`torch.Tensor` of shape `(batch_size, sequence_length, num_input_channels)`):
|
| 950 |
+
input for Batch norm calculation
|
| 951 |
+
observed_indicator (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`):
|
| 952 |
+
Calculating the scale on the observed indicator.
|
| 953 |
+
Returns:
|
| 954 |
+
tuple of `torch.Tensor` of shapes
|
| 955 |
+
(`(batch_size, sequence_length, num_input_channels)`,`(batch_size, 1, num_input_channels)`,
|
| 956 |
+
`(batch_size, 1, num_input_channels)`)
|
| 957 |
+
"""
|
| 958 |
+
denominator = observed_indicator.sum(self.dim, keepdim=self.keepdim)
|
| 959 |
+
denominator = denominator.clamp_min(1.0)
|
| 960 |
+
loc = (data * observed_indicator).sum(self.dim, keepdim=self.keepdim) / denominator
|
| 961 |
+
|
| 962 |
+
variance = (((data - loc) * observed_indicator) ** 2).sum(self.dim, keepdim=self.keepdim) / denominator
|
| 963 |
+
scale = torch.sqrt(variance + self.minimum_scale)
|
| 964 |
+
return (data - loc) / scale, loc, scale
|
| 965 |
+
|
| 966 |
+
|
| 967 |
+
# Copied from transformers.models.time_series_transformer.modeling_time_series_transformer.TimeSeriesMeanScaler with TimeSeriesTransformer->PatchTST,TimeSeries->PatchTST
|
| 968 |
+
class PatchTSTMeanScaler(nn.Module):
|
| 969 |
+
"""
|
| 970 |
+
Computes a scaling factor as the weighted average absolute value along the first dimension, and scales the data
|
| 971 |
+
accordingly.
|
| 972 |
+
"""
|
| 973 |
+
|
| 974 |
+
def __init__(self, config: PatchTSTConfig):
|
| 975 |
+
super().__init__()
|
| 976 |
+
self.dim = config.scaling_dim if hasattr(config, "scaling_dim") else 1
|
| 977 |
+
self.keepdim = config.keepdim if hasattr(config, "keepdim") else True
|
| 978 |
+
self.minimum_scale = config.minimum_scale if hasattr(config, "minimum_scale") else 1e-10
|
| 979 |
+
self.default_scale = config.default_scale if hasattr(config, "default_scale") else None
|
| 980 |
+
|
| 981 |
+
def forward(
|
| 982 |
+
self, data: torch.Tensor, observed_indicator: torch.Tensor
|
| 983 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 984 |
+
"""
|
| 985 |
+
Parameters:
|
| 986 |
+
data (`torch.Tensor` of shape `(batch_size, sequence_length, num_input_channels)`):
|
| 987 |
+
input for Batch norm calculation
|
| 988 |
+
observed_indicator (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`):
|
| 989 |
+
Calculating the scale on the observed indicator.
|
| 990 |
+
Returns:
|
| 991 |
+
tuple of `torch.Tensor` of shapes
|
| 992 |
+
(`(batch_size, sequence_length, num_input_channels)`,`(batch_size, 1, num_input_channels)`,
|
| 993 |
+
`(batch_size, 1, num_input_channels)`)
|
| 994 |
+
"""
|
| 995 |
+
ts_sum = (data * observed_indicator).abs().sum(self.dim, keepdim=True)
|
| 996 |
+
num_observed = observed_indicator.sum(self.dim, keepdim=True)
|
| 997 |
+
|
| 998 |
+
scale = ts_sum / torch.clamp(num_observed, min=1)
|
| 999 |
+
|
| 1000 |
+
# If `default_scale` is provided, we use it, otherwise we use the scale
|
| 1001 |
+
# of the batch.
|
| 1002 |
+
if self.default_scale is None:
|
| 1003 |
+
batch_sum = ts_sum.sum(dim=0)
|
| 1004 |
+
batch_observations = torch.clamp(num_observed.sum(0), min=1)
|
| 1005 |
+
default_scale = torch.squeeze(batch_sum / batch_observations)
|
| 1006 |
+
else:
|
| 1007 |
+
default_scale = self.default_scale * torch.ones_like(scale)
|
| 1008 |
+
|
| 1009 |
+
# apply default scale where there are no observations
|
| 1010 |
+
scale = torch.where(num_observed > 0, scale, default_scale)
|
| 1011 |
+
|
| 1012 |
+
# ensure the scale is at least `self.minimum_scale`
|
| 1013 |
+
scale = torch.clamp(scale, min=self.minimum_scale)
|
| 1014 |
+
scaled_data = data / scale
|
| 1015 |
+
|
| 1016 |
+
if not self.keepdim:
|
| 1017 |
+
scale = scale.squeeze(dim=self.dim)
|
| 1018 |
+
|
| 1019 |
+
return scaled_data, torch.zeros_like(scale), scale
|
| 1020 |
+
|
| 1021 |
+
|
| 1022 |
+
# Copied from transformers.models.time_series_transformer.modeling_time_series_transformer.TimeSeriesNOPScaler with TimeSeriesTransformer->PatchTST,TimeSeries->PatchTST
|
| 1023 |
+
class PatchTSTNOPScaler(nn.Module):
|
| 1024 |
+
"""
|
| 1025 |
+
Assigns a scaling factor equal to 1 along the first dimension, and therefore applies no scaling to the input data.
|
| 1026 |
+
"""
|
| 1027 |
+
|
| 1028 |
+
def __init__(self, config: PatchTSTConfig):
|
| 1029 |
+
super().__init__()
|
| 1030 |
+
self.dim = config.scaling_dim if hasattr(config, "scaling_dim") else 1
|
| 1031 |
+
self.keepdim = config.keepdim if hasattr(config, "keepdim") else True
|
| 1032 |
+
|
| 1033 |
+
def forward(
|
| 1034 |
+
self, data: torch.Tensor, observed_indicator: torch.Tensor | None = None
|
| 1035 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 1036 |
+
"""
|
| 1037 |
+
Parameters:
|
| 1038 |
+
data (`torch.Tensor` of shape `(batch_size, sequence_length, num_input_channels)`):
|
| 1039 |
+
input for Batch norm calculation
|
| 1040 |
+
Returns:
|
| 1041 |
+
tuple of `torch.Tensor` of shapes
|
| 1042 |
+
(`(batch_size, sequence_length, num_input_channels)`,`(batch_size, 1, num_input_channels)`,
|
| 1043 |
+
`(batch_size, 1, num_input_channels)`)
|
| 1044 |
+
"""
|
| 1045 |
+
scale = torch.ones_like(data, requires_grad=False).mean(dim=self.dim, keepdim=self.keepdim)
|
| 1046 |
+
loc = torch.zeros_like(data, requires_grad=False).mean(dim=self.dim, keepdim=self.keepdim)
|
| 1047 |
+
return data, loc, scale
|
| 1048 |
+
|
| 1049 |
+
|
| 1050 |
+
class PatchTSTScaler(nn.Module):
|
| 1051 |
+
def __init__(self, config: PatchTSTConfig):
|
| 1052 |
+
super().__init__()
|
| 1053 |
+
if config.scaling == "mean" or config.scaling is True:
|
| 1054 |
+
self.scaler = PatchTSTMeanScaler(config)
|
| 1055 |
+
elif config.scaling == "std":
|
| 1056 |
+
self.scaler = PatchTSTStdScaler(config)
|
| 1057 |
+
else:
|
| 1058 |
+
self.scaler = PatchTSTNOPScaler(config)
|
| 1059 |
+
|
| 1060 |
+
def forward(
|
| 1061 |
+
self, data: torch.Tensor, observed_indicator: torch.Tensor
|
| 1062 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 1063 |
+
"""
|
| 1064 |
+
Parameters:
|
| 1065 |
+
data (`torch.Tensor` of shape `(batch_size, sequence_length, num_input_channels)`):
|
| 1066 |
+
Input for scaler calculation
|
| 1067 |
+
observed_indicator (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`):
|
| 1068 |
+
Calculating the scale on the observed indicator.
|
| 1069 |
+
Returns:
|
| 1070 |
+
tuple of `torch.Tensor` of shapes
|
| 1071 |
+
(`(batch_size, sequence_length, num_input_channels)`,`(batch_size, 1, num_input_channels)`,
|
| 1072 |
+
`(batch_size, 1, um_input_channels)`)
|
| 1073 |
+
"""
|
| 1074 |
+
data, loc, scale = self.scaler(data, observed_indicator)
|
| 1075 |
+
return data, loc, scale
|
| 1076 |
+
|
| 1077 |
+
|
| 1078 |
+
@auto_docstring
|
| 1079 |
+
class PatchTSTModel(PatchTSTPreTrainedModel):
|
| 1080 |
+
def __init__(self, config: PatchTSTConfig):
|
| 1081 |
+
super().__init__(config)
|
| 1082 |
+
|
| 1083 |
+
self.scaler = PatchTSTScaler(config)
|
| 1084 |
+
self.patchifier = PatchTSTPatchify(config)
|
| 1085 |
+
self.do_mask_input = config.do_mask_input
|
| 1086 |
+
# get num_patches information from PatchTSTPatchify
|
| 1087 |
+
num_patches = self.patchifier.num_patches
|
| 1088 |
+
|
| 1089 |
+
if self.do_mask_input:
|
| 1090 |
+
self.masking = PatchTSTMasking(config)
|
| 1091 |
+
else:
|
| 1092 |
+
self.masking = nn.Identity()
|
| 1093 |
+
self.encoder = PatchTSTEncoder(config, num_patches=num_patches)
|
| 1094 |
+
|
| 1095 |
+
# Initialize weights and apply final processing
|
| 1096 |
+
self.post_init()
|
| 1097 |
+
|
| 1098 |
+
def forward(
|
| 1099 |
+
self,
|
| 1100 |
+
past_values: torch.Tensor,
|
| 1101 |
+
past_observed_mask: torch.Tensor | None = None,
|
| 1102 |
+
future_values: torch.Tensor | None = None,
|
| 1103 |
+
output_hidden_states: bool | None = None,
|
| 1104 |
+
output_attentions: bool | None = None,
|
| 1105 |
+
return_dict: bool | None = None,
|
| 1106 |
+
**kwargs,
|
| 1107 |
+
) -> tuple | PatchTSTModelOutput:
|
| 1108 |
+
r"""
|
| 1109 |
+
Parameters:
|
| 1110 |
+
past_values (`torch.Tensor` of shape `(bs, sequence_length, num_input_channels)`, *required*):
|
| 1111 |
+
Input sequence to the model
|
| 1112 |
+
past_observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
|
| 1113 |
+
Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
|
| 1114 |
+
in `[0, 1]`:
|
| 1115 |
+
|
| 1116 |
+
- 1 for values that are **observed**,
|
| 1117 |
+
- 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
|
| 1118 |
+
future_values (`torch.BoolTensor` of shape `(batch_size, prediction_length, num_input_channels)`, *optional*):
|
| 1119 |
+
Future target values associated with the `past_values`
|
| 1120 |
+
output_hidden_states (`bool`, *optional*):
|
| 1121 |
+
Whether or not to return the hidden states of all layers
|
| 1122 |
+
output_attentions (`bool`, *optional*):
|
| 1123 |
+
Whether or not to return the output attention of all layers
|
| 1124 |
+
return_dict (`bool`, *optional*):
|
| 1125 |
+
Whether or not to return a `ModelOutput` instead of a plain tuple.
|
| 1126 |
+
|
| 1127 |
+
Returns:
|
| 1128 |
+
`PatchTSTModelOutput` or tuple of `torch.Tensor` (if `return_dict`=False or `config.return_dict`=False)
|
| 1129 |
+
|
| 1130 |
+
Examples:
|
| 1131 |
+
|
| 1132 |
+
```python
|
| 1133 |
+
>>> from huggingface_hub import hf_hub_download
|
| 1134 |
+
>>> import torch
|
| 1135 |
+
>>> from transformers import PatchTSTModel
|
| 1136 |
+
|
| 1137 |
+
>>> file = hf_hub_download(
|
| 1138 |
+
... repo_id="hf-internal-testing/etth1-hourly-batch", filename="train-batch.pt", repo_type="dataset"
|
| 1139 |
+
... )
|
| 1140 |
+
>>> batch = torch.load(file)
|
| 1141 |
+
|
| 1142 |
+
>>> model = PatchTSTModel.from_pretrained("namctin/patchtst_etth1_pretrain")
|
| 1143 |
+
|
| 1144 |
+
>>> # during training, one provides both past and future values
|
| 1145 |
+
>>> outputs = model(
|
| 1146 |
+
... past_values=batch["past_values"],
|
| 1147 |
+
... future_values=batch["future_values"],
|
| 1148 |
+
... )
|
| 1149 |
+
|
| 1150 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
| 1151 |
+
```"""
|
| 1152 |
+
|
| 1153 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1154 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1155 |
+
output_hidden_states = (
|
| 1156 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1157 |
+
)
|
| 1158 |
+
|
| 1159 |
+
if past_observed_mask is None:
|
| 1160 |
+
past_observed_mask = torch.ones_like(past_values)
|
| 1161 |
+
|
| 1162 |
+
# x: tensor [bs x sequence_length x num_input_channels]
|
| 1163 |
+
scaled_past_values, loc, scale = self.scaler(past_values, past_observed_mask)
|
| 1164 |
+
|
| 1165 |
+
# patched_values: [bs x num_input_channels x num_patches x patch_length] for pretrain
|
| 1166 |
+
patched_values = self.patchifier(scaled_past_values)
|
| 1167 |
+
if self.do_mask_input:
|
| 1168 |
+
masked_values, mask = self.masking(patched_values)
|
| 1169 |
+
else:
|
| 1170 |
+
masked_values, mask = self.masking(patched_values), None
|
| 1171 |
+
|
| 1172 |
+
encoder_output = self.encoder(
|
| 1173 |
+
patch_input=masked_values, output_hidden_states=output_hidden_states, output_attentions=output_attentions
|
| 1174 |
+
)
|
| 1175 |
+
|
| 1176 |
+
if not return_dict:
|
| 1177 |
+
outputs = (encoder_output.last_hidden_state, encoder_output.hidden_states, encoder_output.attentions)
|
| 1178 |
+
outputs = outputs + (mask, loc, scale, patched_values)
|
| 1179 |
+
return tuple(v for v in outputs if v is not None)
|
| 1180 |
+
|
| 1181 |
+
return PatchTSTModelOutput(
|
| 1182 |
+
last_hidden_state=encoder_output.last_hidden_state,
|
| 1183 |
+
hidden_states=encoder_output.hidden_states,
|
| 1184 |
+
attentions=encoder_output.attentions,
|
| 1185 |
+
mask=mask,
|
| 1186 |
+
loc=loc,
|
| 1187 |
+
scale=scale,
|
| 1188 |
+
patch_input=patched_values,
|
| 1189 |
+
)
|
| 1190 |
+
|
| 1191 |
+
|
| 1192 |
+
class PatchTSTMaskPretrainHead(nn.Module):
|
| 1193 |
+
"""
|
| 1194 |
+
Pretraining head for mask modelling
|
| 1195 |
+
"""
|
| 1196 |
+
|
| 1197 |
+
def __init__(self, config: PatchTSTConfig):
|
| 1198 |
+
super().__init__()
|
| 1199 |
+
self.dropout = nn.Dropout(config.head_dropout) if config.head_dropout > 0 else nn.Identity()
|
| 1200 |
+
self.linear = nn.Linear(config.d_model, config.patch_length)
|
| 1201 |
+
self.use_cls_token = config.use_cls_token
|
| 1202 |
+
|
| 1203 |
+
def forward(self, embedding: torch.Tensor) -> torch.Tensor:
|
| 1204 |
+
"""
|
| 1205 |
+
Parameters:
|
| 1206 |
+
embedding (`torch.Tensor` of shape `(bs, num_channels, num_patches, d_model)` or
|
| 1207 |
+
`(bs, num_channels, num_patches+1, d_model)` if `cls_token` is set to True, *required*):
|
| 1208 |
+
Embedding from the model
|
| 1209 |
+
Returns:
|
| 1210 |
+
`torch.Tensor` of shape `(bs, num_channels, num_patches, d_model)` or
|
| 1211 |
+
`(bs, num_channels, num_patches+1, d_model)` if `cls_token` is set to True
|
| 1212 |
+
|
| 1213 |
+
"""
|
| 1214 |
+
embedding = self.linear(self.dropout(embedding)) # [bs x num_channels x num_patches x patch_length]
|
| 1215 |
+
if self.use_cls_token:
|
| 1216 |
+
embedding = embedding[:, :, 1:, :] # remove the first cls token
|
| 1217 |
+
return embedding
|
| 1218 |
+
|
| 1219 |
+
|
| 1220 |
+
@auto_docstring(
|
| 1221 |
+
custom_intro="""
|
| 1222 |
+
The PatchTST for pretrain model.
|
| 1223 |
+
"""
|
| 1224 |
+
)
|
| 1225 |
+
class PatchTSTForPretraining(PatchTSTPreTrainedModel):
|
| 1226 |
+
def __init__(self, config: PatchTSTConfig):
|
| 1227 |
+
super().__init__(config)
|
| 1228 |
+
|
| 1229 |
+
config.do_mask_input = True
|
| 1230 |
+
self.model = PatchTSTModel(config=config)
|
| 1231 |
+
self.head = PatchTSTMaskPretrainHead(config)
|
| 1232 |
+
|
| 1233 |
+
# Initialize weights and apply final processing
|
| 1234 |
+
self.post_init()
|
| 1235 |
+
|
| 1236 |
+
def forward(
|
| 1237 |
+
self,
|
| 1238 |
+
past_values: torch.Tensor,
|
| 1239 |
+
past_observed_mask: torch.Tensor | None = None,
|
| 1240 |
+
output_hidden_states: bool | None = None,
|
| 1241 |
+
output_attentions: bool | None = None,
|
| 1242 |
+
return_dict: bool | None = None,
|
| 1243 |
+
**kwargs,
|
| 1244 |
+
) -> tuple | PatchTSTForPretrainingOutput:
|
| 1245 |
+
r"""
|
| 1246 |
+
Parameters:
|
| 1247 |
+
past_values (`torch.Tensor` of shape `(bs, sequence_length, num_input_channels)`, *required*):
|
| 1248 |
+
Input sequence to the model
|
| 1249 |
+
past_observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
|
| 1250 |
+
Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
|
| 1251 |
+
in `[0, 1]`:
|
| 1252 |
+
|
| 1253 |
+
- 1 for values that are **observed**,
|
| 1254 |
+
- 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
|
| 1255 |
+
output_hidden_states (`bool`, *optional*):
|
| 1256 |
+
Whether or not to return the hidden states of all layers
|
| 1257 |
+
output_attentions (`bool`, *optional*):
|
| 1258 |
+
Whether or not to return the output attention of all layers
|
| 1259 |
+
return_dict (`bool`, *optional*): Whether or not to return a `ModelOutput` instead of a plain tuple.
|
| 1260 |
+
|
| 1261 |
+
Returns:
|
| 1262 |
+
`PatchTSTForPretrainingOutput` or tuple of `torch.Tensor` (if `return_dict`=False or
|
| 1263 |
+
`config.return_dict`=False)
|
| 1264 |
+
|
| 1265 |
+
Examples:
|
| 1266 |
+
|
| 1267 |
+
```python
|
| 1268 |
+
>>> from huggingface_hub import hf_hub_download
|
| 1269 |
+
>>> import torch
|
| 1270 |
+
>>> from transformers import PatchTSTConfig, PatchTSTForPretraining
|
| 1271 |
+
|
| 1272 |
+
>>> file = hf_hub_download(
|
| 1273 |
+
... repo_id="hf-internal-testing/etth1-hourly-batch", filename="train-batch.pt", repo_type="dataset"
|
| 1274 |
+
... )
|
| 1275 |
+
>>> batch = torch.load(file)
|
| 1276 |
+
|
| 1277 |
+
>>> # Config for random mask pretraining
|
| 1278 |
+
>>> config = PatchTSTConfig(
|
| 1279 |
+
... num_input_channels=7,
|
| 1280 |
+
... context_length=512,
|
| 1281 |
+
... patch_length=12,
|
| 1282 |
+
... stride=12,
|
| 1283 |
+
... mask_type='random',
|
| 1284 |
+
... random_mask_ratio=0.4,
|
| 1285 |
+
... use_cls_token=True,
|
| 1286 |
+
... )
|
| 1287 |
+
>>> # Config for forecast mask pretraining
|
| 1288 |
+
>>> config = PatchTSTConfig(
|
| 1289 |
+
... num_input_channels=7,
|
| 1290 |
+
... context_length=512,
|
| 1291 |
+
... patch_length=12,
|
| 1292 |
+
... stride=12,
|
| 1293 |
+
... mask_type='forecast',
|
| 1294 |
+
... num_forecast_mask_patches=5,
|
| 1295 |
+
... use_cls_token=True,
|
| 1296 |
+
... )
|
| 1297 |
+
>>> model = PatchTSTForPretraining(config)
|
| 1298 |
+
|
| 1299 |
+
>>> # during training, one provides both past and future values
|
| 1300 |
+
>>> outputs = model(past_values=batch["past_values"])
|
| 1301 |
+
|
| 1302 |
+
>>> loss = outputs.loss
|
| 1303 |
+
>>> loss.backward()
|
| 1304 |
+
```"""
|
| 1305 |
+
|
| 1306 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1307 |
+
|
| 1308 |
+
# past_values: [bs x num_channels x num_patches x d_model] or
|
| 1309 |
+
# [bs x num_channels x (num_patches+1) x d_model] if use cls_token
|
| 1310 |
+
model_output = self.model(
|
| 1311 |
+
past_values=past_values,
|
| 1312 |
+
past_observed_mask=past_observed_mask,
|
| 1313 |
+
output_hidden_states=output_hidden_states,
|
| 1314 |
+
output_attentions=output_attentions,
|
| 1315 |
+
return_dict=True,
|
| 1316 |
+
)
|
| 1317 |
+
|
| 1318 |
+
# last_hidden_state: [bs x num_channels x num_patches x patch_length] or
|
| 1319 |
+
# [bs x num_channels x (num_patches+1) x patch_length] if use cls_token
|
| 1320 |
+
x_hat = self.head(model_output.last_hidden_state)
|
| 1321 |
+
|
| 1322 |
+
# calculate masked_loss
|
| 1323 |
+
loss = nn.MSELoss(reduction="none")
|
| 1324 |
+
loss_val = loss(x_hat, model_output.patch_input)
|
| 1325 |
+
masked_loss = (loss_val.mean(dim=-1) * model_output.mask).sum() / (model_output.mask.sum() + 1e-10)
|
| 1326 |
+
|
| 1327 |
+
encoder_states = model_output.hidden_states
|
| 1328 |
+
if not return_dict:
|
| 1329 |
+
outputs = (x_hat,) + model_output[1:-4]
|
| 1330 |
+
outputs = (masked_loss,) + outputs if masked_loss is not None else outputs
|
| 1331 |
+
return outputs
|
| 1332 |
+
return PatchTSTForPretrainingOutput(
|
| 1333 |
+
loss=masked_loss, prediction_output=x_hat, hidden_states=encoder_states, attentions=model_output.attentions
|
| 1334 |
+
)
|
| 1335 |
+
|
| 1336 |
+
|
| 1337 |
+
class PatchTSTClassificationHead(nn.Module):
|
| 1338 |
+
def __init__(self, config: PatchTSTConfig):
|
| 1339 |
+
super().__init__()
|
| 1340 |
+
self.use_cls_token = config.use_cls_token
|
| 1341 |
+
self.pooling_type = config.pooling_type
|
| 1342 |
+
self.flatten = nn.Flatten(start_dim=1)
|
| 1343 |
+
self.dropout = nn.Dropout(config.head_dropout) if config.head_dropout > 0 else nn.Identity()
|
| 1344 |
+
self.linear = nn.Linear(config.num_input_channels * config.d_model, config.num_targets)
|
| 1345 |
+
|
| 1346 |
+
def forward(self, embedding: torch.Tensor):
|
| 1347 |
+
"""
|
| 1348 |
+
Parameters:
|
| 1349 |
+
embedding (`torch.Tensor` of shape `(bs, num_channels, num_patches, d_model)` or
|
| 1350 |
+
`(bs, num_channels, num_patches+1, d_model)` if `cls_token` is set to True, *required*):
|
| 1351 |
+
Embedding from the model
|
| 1352 |
+
Returns:
|
| 1353 |
+
`torch.Tensor` of shape `(bs, num_targets)`
|
| 1354 |
+
|
| 1355 |
+
"""
|
| 1356 |
+
if self.use_cls_token:
|
| 1357 |
+
# use the first output token, pooled_embedding: bs x num_channels x d_model
|
| 1358 |
+
pooled_embedding = embedding[:, :, 0, :]
|
| 1359 |
+
elif self.pooling_type == "mean":
|
| 1360 |
+
# pooled_embedding: [bs x num_channels x d_model]
|
| 1361 |
+
pooled_embedding = embedding.mean(dim=2)
|
| 1362 |
+
elif self.pooling_type == "max":
|
| 1363 |
+
# pooled_embedding: [bs x num_channels x d_model]
|
| 1364 |
+
pooled_embedding = embedding.max(dim=2).values
|
| 1365 |
+
else:
|
| 1366 |
+
raise ValueError(f"pooling operator {self.pooling_type} is not implemented yet")
|
| 1367 |
+
# pooled_embedding: bs x num_channels * d_model
|
| 1368 |
+
pooled_embedding = self.flatten(pooled_embedding)
|
| 1369 |
+
# output: bs x n_classes
|
| 1370 |
+
output = self.linear(self.dropout(pooled_embedding))
|
| 1371 |
+
return output
|
| 1372 |
+
|
| 1373 |
+
|
| 1374 |
+
@auto_docstring(
|
| 1375 |
+
custom_intro="""
|
| 1376 |
+
The PatchTST for classification model.
|
| 1377 |
+
"""
|
| 1378 |
+
)
|
| 1379 |
+
class PatchTSTForClassification(PatchTSTPreTrainedModel):
|
| 1380 |
+
def __init__(self, config: PatchTSTConfig):
|
| 1381 |
+
super().__init__(config)
|
| 1382 |
+
|
| 1383 |
+
# Turn off masking
|
| 1384 |
+
if config.do_mask_input:
|
| 1385 |
+
logger.warning("Setting `do_mask_input` parameter to False.")
|
| 1386 |
+
config.do_mask_input = False
|
| 1387 |
+
|
| 1388 |
+
self.model = PatchTSTModel(config)
|
| 1389 |
+
self.head = PatchTSTClassificationHead(config)
|
| 1390 |
+
|
| 1391 |
+
# Initialize weights and apply final processing
|
| 1392 |
+
self.post_init()
|
| 1393 |
+
|
| 1394 |
+
@auto_docstring
|
| 1395 |
+
def forward(
|
| 1396 |
+
self,
|
| 1397 |
+
past_values: torch.Tensor,
|
| 1398 |
+
target_values: torch.Tensor | None = None,
|
| 1399 |
+
past_observed_mask: bool | None = None,
|
| 1400 |
+
output_hidden_states: bool | None = None,
|
| 1401 |
+
output_attentions: bool | None = None,
|
| 1402 |
+
return_dict: bool | None = None,
|
| 1403 |
+
**kwargs,
|
| 1404 |
+
) -> tuple | PatchTSTForClassificationOutput:
|
| 1405 |
+
r"""
|
| 1406 |
+
past_values (`torch.Tensor` of shape `(bs, sequence_length, num_input_channels)`, *required*):
|
| 1407 |
+
Input sequence to the model
|
| 1408 |
+
target_values (`torch.Tensor`, *optional*):
|
| 1409 |
+
Labels associates with the `past_values`
|
| 1410 |
+
past_observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
|
| 1411 |
+
Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
|
| 1412 |
+
in `[0, 1]`:
|
| 1413 |
+
|
| 1414 |
+
- 1 for values that are **observed**,
|
| 1415 |
+
- 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
|
| 1416 |
+
|
| 1417 |
+
Examples:
|
| 1418 |
+
|
| 1419 |
+
```python
|
| 1420 |
+
>>> from transformers import PatchTSTConfig, PatchTSTForClassification
|
| 1421 |
+
|
| 1422 |
+
>>> # classification task with two input channel2 and 3 classes
|
| 1423 |
+
>>> config = PatchTSTConfig(
|
| 1424 |
+
... num_input_channels=2,
|
| 1425 |
+
... num_targets=3,
|
| 1426 |
+
... context_length=512,
|
| 1427 |
+
... patch_length=12,
|
| 1428 |
+
... stride=12,
|
| 1429 |
+
... use_cls_token=True,
|
| 1430 |
+
... )
|
| 1431 |
+
>>> model = PatchTSTForClassification(config=config)
|
| 1432 |
+
|
| 1433 |
+
>>> # during inference, one only provides past values
|
| 1434 |
+
>>> past_values = torch.randn(20, 512, 2)
|
| 1435 |
+
>>> outputs = model(past_values=past_values)
|
| 1436 |
+
>>> labels = outputs.prediction_logits
|
| 1437 |
+
```"""
|
| 1438 |
+
|
| 1439 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1440 |
+
|
| 1441 |
+
model_output = self.model(
|
| 1442 |
+
past_values=past_values,
|
| 1443 |
+
past_observed_mask=past_observed_mask,
|
| 1444 |
+
output_hidden_states=output_hidden_states,
|
| 1445 |
+
output_attentions=output_attentions,
|
| 1446 |
+
return_dict=True,
|
| 1447 |
+
)
|
| 1448 |
+
y_hat = self.head(model_output.last_hidden_state)
|
| 1449 |
+
|
| 1450 |
+
loss_val = None
|
| 1451 |
+
if target_values is not None:
|
| 1452 |
+
loss = nn.CrossEntropyLoss()
|
| 1453 |
+
loss_val = loss(y_hat, target_values)
|
| 1454 |
+
|
| 1455 |
+
if not return_dict:
|
| 1456 |
+
outputs = (y_hat,) + model_output[1:-3]
|
| 1457 |
+
outputs = (loss_val,) + outputs if loss_val is not None else outputs
|
| 1458 |
+
return outputs
|
| 1459 |
+
return PatchTSTForClassificationOutput(
|
| 1460 |
+
loss=loss_val,
|
| 1461 |
+
prediction_logits=y_hat,
|
| 1462 |
+
hidden_states=model_output.hidden_states,
|
| 1463 |
+
attentions=model_output.attentions,
|
| 1464 |
+
)
|
| 1465 |
+
|
| 1466 |
+
|
| 1467 |
+
@auto_docstring(
|
| 1468 |
+
custom_intro="""
|
| 1469 |
+
The PatchTST for regression Model.
|
| 1470 |
+
"""
|
| 1471 |
+
)
|
| 1472 |
+
class PatchTSTPredictionHead(nn.Module):
|
| 1473 |
+
def __init__(self, config: PatchTSTConfig, num_patches: int, distribution_output=None):
|
| 1474 |
+
r"""
|
| 1475 |
+
num_patches (`int`):
|
| 1476 |
+
The number of patches in the input sequence.
|
| 1477 |
+
distribution_output (`DistributionOutput`, *optional*):
|
| 1478 |
+
The distribution output layer for probabilistic forecasting. If None, a linear output layer is used.
|
| 1479 |
+
"""
|
| 1480 |
+
super().__init__()
|
| 1481 |
+
|
| 1482 |
+
self.share_projection = config.share_projection
|
| 1483 |
+
self.num_input_channels = config.num_input_channels
|
| 1484 |
+
self.use_cls_token = config.use_cls_token
|
| 1485 |
+
self.pooling_type = config.pooling_type
|
| 1486 |
+
if self.pooling_type or self.use_cls_token:
|
| 1487 |
+
head_dim = config.d_model
|
| 1488 |
+
else:
|
| 1489 |
+
head_dim = config.d_model * num_patches
|
| 1490 |
+
|
| 1491 |
+
if not self.share_projection:
|
| 1492 |
+
# if each channel has its own head
|
| 1493 |
+
self.projections = nn.ModuleList()
|
| 1494 |
+
self.dropouts = nn.ModuleList()
|
| 1495 |
+
self.flattens = nn.ModuleList()
|
| 1496 |
+
for i in range(self.num_input_channels):
|
| 1497 |
+
self.flattens.append(nn.Flatten(start_dim=2))
|
| 1498 |
+
if distribution_output is None:
|
| 1499 |
+
# use linear head
|
| 1500 |
+
self.projections.append(nn.Linear(head_dim, config.prediction_length))
|
| 1501 |
+
else:
|
| 1502 |
+
# use distribution head
|
| 1503 |
+
self.projections.append(distribution_output.get_parameter_projection(head_dim))
|
| 1504 |
+
self.dropouts.append(nn.Dropout(config.head_dropout) if config.head_dropout > 0 else nn.Identity())
|
| 1505 |
+
else:
|
| 1506 |
+
# all the channels share the same head
|
| 1507 |
+
self.flatten = nn.Flatten(start_dim=2)
|
| 1508 |
+
if distribution_output is None:
|
| 1509 |
+
# use linear head
|
| 1510 |
+
self.projection = nn.Linear(head_dim, config.prediction_length)
|
| 1511 |
+
else:
|
| 1512 |
+
# use distribution head
|
| 1513 |
+
self.projection = distribution_output.get_parameter_projection(head_dim)
|
| 1514 |
+
self.dropout = nn.Dropout(config.head_dropout) if config.head_dropout > 0 else nn.Identity()
|
| 1515 |
+
|
| 1516 |
+
def forward(self, embedding: torch.Tensor):
|
| 1517 |
+
"""
|
| 1518 |
+
Parameters:
|
| 1519 |
+
embedding (`torch.Tensor` of shape `(bs, num_channels, num_patches, d_model)` or
|
| 1520 |
+
`(bs, num_channels, num_patches+1, d_model)` if `cls_token` is set to True, *required*):
|
| 1521 |
+
Embedding from the model
|
| 1522 |
+
Returns:
|
| 1523 |
+
`torch.Tensor` of shape `(bs, forecast_len, num_channels)`
|
| 1524 |
+
|
| 1525 |
+
"""
|
| 1526 |
+
if self.use_cls_token:
|
| 1527 |
+
# pooled_embedding: [bs x num_channels x d_model]
|
| 1528 |
+
pooled_embedding = embedding[:, :, 0, :]
|
| 1529 |
+
else:
|
| 1530 |
+
if self.pooling_type == "mean":
|
| 1531 |
+
# pooled_embedding: [bs x num_channels x d_model]
|
| 1532 |
+
pooled_embedding = embedding.mean(dim=2)
|
| 1533 |
+
elif self.pooling_type == "max":
|
| 1534 |
+
# pooled_embedding: [bs x num_channels x d_model]
|
| 1535 |
+
pooled_embedding = embedding.max(dim=2).values
|
| 1536 |
+
else:
|
| 1537 |
+
# pooled_embedding: [bs x num_channels x num_patches x d_model]
|
| 1538 |
+
pooled_embedding = embedding
|
| 1539 |
+
|
| 1540 |
+
if not self.share_projection:
|
| 1541 |
+
output = []
|
| 1542 |
+
for i in range(self.num_input_channels):
|
| 1543 |
+
# pooled_embedding: [bs x (d_model * num_patches)] or [bs x d_model)]
|
| 1544 |
+
pooled_embedding = self.flattens[i](pooled_embedding[:, i, :])
|
| 1545 |
+
pooled_embedding = self.dropouts[i](pooled_embedding)
|
| 1546 |
+
# pooled_embedding: [bs x forecast_len]
|
| 1547 |
+
# or tuple ([bs x forecast_len], [bs x forecast_len]) if using distribution head
|
| 1548 |
+
pooled_embedding = self.projections[i](pooled_embedding)
|
| 1549 |
+
output.append(pooled_embedding)
|
| 1550 |
+
# output: [bs x num_channels x forecast_len]
|
| 1551 |
+
output = torch.stack(output, dim=1)
|
| 1552 |
+
else:
|
| 1553 |
+
# pooled_embedding: [bs x num_channels x (d_model * num_patches)] or [bs x num_channels x d_model)]
|
| 1554 |
+
pooled_embedding = self.flatten(pooled_embedding)
|
| 1555 |
+
pooled_embedding = self.dropout(pooled_embedding)
|
| 1556 |
+
# output: [bs x num_channels x forecast_len] or
|
| 1557 |
+
# tuple ([bs x num_channels x forecast_len], [bs x num_channels x forecast_len]) if using distribution head
|
| 1558 |
+
output = self.projection(pooled_embedding)
|
| 1559 |
+
|
| 1560 |
+
if isinstance(output, tuple):
|
| 1561 |
+
# output: ([bs x forecast_len x num_channels], [bs x forecast_len x num_channels])
|
| 1562 |
+
output = tuple(z.transpose(2, 1) for z in output)
|
| 1563 |
+
else:
|
| 1564 |
+
output = output.transpose(2, 1) # [bs x forecast_len x num_channels]
|
| 1565 |
+
return output
|
| 1566 |
+
|
| 1567 |
+
|
| 1568 |
+
@auto_docstring(
|
| 1569 |
+
custom_intro="""
|
| 1570 |
+
The PatchTST for prediction model.
|
| 1571 |
+
"""
|
| 1572 |
+
)
|
| 1573 |
+
class PatchTSTForPrediction(PatchTSTPreTrainedModel):
|
| 1574 |
+
def __init__(self, config: PatchTSTConfig):
|
| 1575 |
+
super().__init__(config)
|
| 1576 |
+
|
| 1577 |
+
# Turn off masking
|
| 1578 |
+
if config.do_mask_input:
|
| 1579 |
+
logger.warning("Setting `do_mask_input` parameter to False.")
|
| 1580 |
+
config.do_mask_input = False
|
| 1581 |
+
|
| 1582 |
+
self.model = PatchTSTModel(config)
|
| 1583 |
+
|
| 1584 |
+
if config.loss == "mse":
|
| 1585 |
+
self.distribution_output = None
|
| 1586 |
+
else:
|
| 1587 |
+
if config.distribution_output == "student_t":
|
| 1588 |
+
self.distribution_output = StudentTOutput(dim=config.prediction_length)
|
| 1589 |
+
elif config.distribution_output == "normal":
|
| 1590 |
+
self.distribution_output = NormalOutput(dim=config.prediction_length)
|
| 1591 |
+
elif config.distribution_output == "negative_binomial":
|
| 1592 |
+
self.distribution_output = NegativeBinomialOutput(dim=config.prediction_length)
|
| 1593 |
+
else:
|
| 1594 |
+
raise ValueError(f"Unknown distribution output {config.distribution_output}")
|
| 1595 |
+
|
| 1596 |
+
self.head = PatchTSTPredictionHead(
|
| 1597 |
+
config, self.model.patchifier.num_patches, distribution_output=self.distribution_output
|
| 1598 |
+
)
|
| 1599 |
+
|
| 1600 |
+
# Initialize weights and apply final processing
|
| 1601 |
+
self.post_init()
|
| 1602 |
+
|
| 1603 |
+
def forward(
|
| 1604 |
+
self,
|
| 1605 |
+
past_values: torch.Tensor,
|
| 1606 |
+
past_observed_mask: torch.Tensor | None = None,
|
| 1607 |
+
future_values: torch.Tensor | None = None,
|
| 1608 |
+
output_hidden_states: bool | None = None,
|
| 1609 |
+
output_attentions: bool | None = None,
|
| 1610 |
+
return_dict: bool | None = None,
|
| 1611 |
+
**kwargs,
|
| 1612 |
+
) -> tuple | PatchTSTForPredictionOutput:
|
| 1613 |
+
r"""
|
| 1614 |
+
Parameters:
|
| 1615 |
+
past_values (`torch.Tensor` of shape `(bs, sequence_length, num_input_channels)`, *required*):
|
| 1616 |
+
Input sequence to the model
|
| 1617 |
+
past_observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
|
| 1618 |
+
Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
|
| 1619 |
+
in `[0, 1]`:
|
| 1620 |
+
|
| 1621 |
+
- 1 for values that are **observed**,
|
| 1622 |
+
- 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
|
| 1623 |
+
future_values (`torch.Tensor` of shape `(bs, forecast_len, num_input_channels)`, *optional*):
|
| 1624 |
+
Future target values associated with the `past_values`
|
| 1625 |
+
output_hidden_states (`bool`, *optional*):
|
| 1626 |
+
Whether or not to return the hidden states of all layers
|
| 1627 |
+
output_attentions (`bool`, *optional*):
|
| 1628 |
+
Whether or not to return the output attention of all layers
|
| 1629 |
+
return_dict (`bool`, *optional*):
|
| 1630 |
+
Whether or not to return a `ModelOutput` instead of a plain tuple.
|
| 1631 |
+
|
| 1632 |
+
Returns:
|
| 1633 |
+
`PatchTSTForPredictionOutput` or tuple of `torch.Tensor` (if `return_dict`=False or
|
| 1634 |
+
`config.return_dict`=False)
|
| 1635 |
+
|
| 1636 |
+
Examples:
|
| 1637 |
+
|
| 1638 |
+
```python
|
| 1639 |
+
>>> from huggingface_hub import hf_hub_download
|
| 1640 |
+
>>> import torch
|
| 1641 |
+
>>> from transformers import PatchTSTConfig, PatchTSTForPrediction
|
| 1642 |
+
|
| 1643 |
+
>>> file = hf_hub_download(
|
| 1644 |
+
... repo_id="hf-internal-testing/etth1-hourly-batch", filename="train-batch.pt", repo_type="dataset"
|
| 1645 |
+
... )
|
| 1646 |
+
>>> batch = torch.load(file)
|
| 1647 |
+
|
| 1648 |
+
>>> # Prediction task with 7 input channels and prediction length is 96
|
| 1649 |
+
>>> model = PatchTSTForPrediction.from_pretrained("namctin/patchtst_etth1_forecast")
|
| 1650 |
+
|
| 1651 |
+
>>> # during training, one provides both past and future values
|
| 1652 |
+
>>> outputs = model(
|
| 1653 |
+
... past_values=batch["past_values"],
|
| 1654 |
+
... future_values=batch["future_values"],
|
| 1655 |
+
... )
|
| 1656 |
+
|
| 1657 |
+
>>> loss = outputs.loss
|
| 1658 |
+
>>> loss.backward()
|
| 1659 |
+
|
| 1660 |
+
>>> # during inference, one only provides past values, the model outputs future values
|
| 1661 |
+
>>> outputs = model(past_values=batch["past_values"])
|
| 1662 |
+
>>> prediction_outputs = outputs.prediction_outputs
|
| 1663 |
+
```"""
|
| 1664 |
+
|
| 1665 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1666 |
+
|
| 1667 |
+
# get model output
|
| 1668 |
+
model_output = self.model(
|
| 1669 |
+
past_values=past_values,
|
| 1670 |
+
past_observed_mask=past_observed_mask,
|
| 1671 |
+
output_hidden_states=output_hidden_states,
|
| 1672 |
+
output_attentions=output_attentions,
|
| 1673 |
+
return_dict=True,
|
| 1674 |
+
)
|
| 1675 |
+
# get output head
|
| 1676 |
+
y_hat = self.head(model_output.last_hidden_state)
|
| 1677 |
+
|
| 1678 |
+
loss_val = None
|
| 1679 |
+
|
| 1680 |
+
if self.distribution_output:
|
| 1681 |
+
y_hat_out = y_hat
|
| 1682 |
+
else:
|
| 1683 |
+
y_hat_out = y_hat * model_output.scale + model_output.loc
|
| 1684 |
+
|
| 1685 |
+
if future_values is not None:
|
| 1686 |
+
if self.distribution_output:
|
| 1687 |
+
distribution = self.distribution_output.distribution(
|
| 1688 |
+
y_hat, loc=model_output.loc, scale=model_output.scale
|
| 1689 |
+
)
|
| 1690 |
+
loss_val = nll(distribution, future_values)
|
| 1691 |
+
# take average of the loss
|
| 1692 |
+
loss_val = weighted_average(loss_val)
|
| 1693 |
+
else:
|
| 1694 |
+
loss = nn.MSELoss(reduction="mean")
|
| 1695 |
+
loss_val = loss(y_hat_out, future_values)
|
| 1696 |
+
|
| 1697 |
+
loc = model_output.loc
|
| 1698 |
+
scale = model_output.scale
|
| 1699 |
+
|
| 1700 |
+
if not return_dict:
|
| 1701 |
+
outputs = (y_hat_out,) + model_output[1:-1]
|
| 1702 |
+
outputs = (loss_val,) + outputs if loss_val is not None else outputs
|
| 1703 |
+
return outputs
|
| 1704 |
+
return PatchTSTForPredictionOutput(
|
| 1705 |
+
loss=loss_val,
|
| 1706 |
+
prediction_outputs=y_hat_out,
|
| 1707 |
+
hidden_states=model_output.hidden_states,
|
| 1708 |
+
attentions=model_output.attentions,
|
| 1709 |
+
loc=loc,
|
| 1710 |
+
scale=scale,
|
| 1711 |
+
)
|
| 1712 |
+
|
| 1713 |
+
@torch.no_grad()
|
| 1714 |
+
def generate(
|
| 1715 |
+
self,
|
| 1716 |
+
past_values: torch.Tensor,
|
| 1717 |
+
past_observed_mask: torch.Tensor | None = None,
|
| 1718 |
+
) -> SamplePatchTSTOutput:
|
| 1719 |
+
"""
|
| 1720 |
+
Generate sequences of sample predictions from a model with a probability distribution head.
|
| 1721 |
+
|
| 1722 |
+
Parameters:
|
| 1723 |
+
past_values (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_input_channels)`):
|
| 1724 |
+
Past values of the time series that serves as context in order to predict the future.
|
| 1725 |
+
past_observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
|
| 1726 |
+
Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
|
| 1727 |
+
in `[0, 1]`:
|
| 1728 |
+
|
| 1729 |
+
- 1 for values that are **observed**,
|
| 1730 |
+
- 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
|
| 1731 |
+
|
| 1732 |
+
Return:
|
| 1733 |
+
[`SamplePatchTSTOutput`] where the outputs `sequences` tensor will have shape `(batch_size, number of
|
| 1734 |
+
samples, prediction_length, 1)` or `(batch_size, number of samples, prediction_length, num_input_channels)`
|
| 1735 |
+
for multivariate predictions.
|
| 1736 |
+
"""
|
| 1737 |
+
# get number of samples
|
| 1738 |
+
num_parallel_samples = self.config.num_parallel_samples
|
| 1739 |
+
|
| 1740 |
+
# get model output
|
| 1741 |
+
outputs = self(
|
| 1742 |
+
past_values=past_values,
|
| 1743 |
+
future_values=None,
|
| 1744 |
+
past_observed_mask=past_observed_mask,
|
| 1745 |
+
output_hidden_states=False,
|
| 1746 |
+
)
|
| 1747 |
+
if self.distribution_output:
|
| 1748 |
+
# get distribution
|
| 1749 |
+
distribution = self.distribution_output.distribution(
|
| 1750 |
+
outputs.prediction_outputs, loc=outputs.loc, scale=outputs.scale
|
| 1751 |
+
)
|
| 1752 |
+
# get samples: list of [bs x forecast_len x num_channels]
|
| 1753 |
+
samples = [distribution.sample() for _ in range(num_parallel_samples)]
|
| 1754 |
+
# samples: [bs x num_samples x forecast_len x num_channels]
|
| 1755 |
+
samples = torch.stack(samples, dim=1)
|
| 1756 |
+
else:
|
| 1757 |
+
samples = outputs.prediction_outputs.unsqueeze(1)
|
| 1758 |
+
|
| 1759 |
+
return SamplePatchTSTOutput(sequences=samples)
|
| 1760 |
+
|
| 1761 |
+
|
| 1762 |
+
class PatchTSTRegressionHead(nn.Module):
|
| 1763 |
+
"""
|
| 1764 |
+
Regression head
|
| 1765 |
+
"""
|
| 1766 |
+
|
| 1767 |
+
def __init__(self, config: PatchTSTConfig, distribution_output=None):
|
| 1768 |
+
super().__init__()
|
| 1769 |
+
self.y_range = config.output_range
|
| 1770 |
+
self.use_cls_token = config.use_cls_token
|
| 1771 |
+
self.pooling_type = config.pooling_type
|
| 1772 |
+
self.distribution_output = distribution_output
|
| 1773 |
+
|
| 1774 |
+
head_dim = config.num_input_channels * config.d_model
|
| 1775 |
+
|
| 1776 |
+
self.flatten = nn.Flatten(start_dim=1)
|
| 1777 |
+
self.dropout = nn.Dropout(config.head_dropout) if config.head_dropout > 0 else nn.Identity()
|
| 1778 |
+
|
| 1779 |
+
if distribution_output is None:
|
| 1780 |
+
self.projection = nn.Linear(head_dim, config.num_targets)
|
| 1781 |
+
else:
|
| 1782 |
+
self.projection = distribution_output.get_parameter_projection(head_dim)
|
| 1783 |
+
|
| 1784 |
+
def forward(self, embedding: torch.Tensor):
|
| 1785 |
+
"""
|
| 1786 |
+
Parameters:
|
| 1787 |
+
embedding (`torch.Tensor` of shape `(bs, num_channels, num_patches, d_model)` or
|
| 1788 |
+
`(bs, num_channels, num_patches+1, d_model)` if `cls_token` is set to True, *required*):
|
| 1789 |
+
Embedding from the model
|
| 1790 |
+
Returns:
|
| 1791 |
+
`torch.Tensor` of shape `(bs, output_dim)`
|
| 1792 |
+
|
| 1793 |
+
"""
|
| 1794 |
+
if self.use_cls_token:
|
| 1795 |
+
# use the first output token, pooled_embedding: [bs x num_channels x d_model]
|
| 1796 |
+
pooled_embedding = embedding[:, :, 0, :]
|
| 1797 |
+
elif self.pooling_type == "mean":
|
| 1798 |
+
# pooled_embedding: [bs x num_channels x d_model]
|
| 1799 |
+
pooled_embedding = embedding.mean(dim=2)
|
| 1800 |
+
elif self.pooling_type == "max":
|
| 1801 |
+
# pooled_embedding: [bs x num_channels x d_model]
|
| 1802 |
+
pooled_embedding = embedding.max(dim=2).values
|
| 1803 |
+
else:
|
| 1804 |
+
raise ValueError(f"pooling operator {self.pooling_type} is not implemented yet")
|
| 1805 |
+
# flatten the input
|
| 1806 |
+
# pooled_embedding: bs x (num_channels * d_model)
|
| 1807 |
+
pooled_embedding = self.dropout(self.flatten(pooled_embedding))
|
| 1808 |
+
# projection
|
| 1809 |
+
# output: bs x output_dim or a tuple of this shape for distribution head
|
| 1810 |
+
output = self.projection(pooled_embedding)
|
| 1811 |
+
# apply sigmoid to bound the output if required
|
| 1812 |
+
if (self.distribution_output is None) & (self.y_range is not None): # linear head
|
| 1813 |
+
output = torch.sigmoid(output) * (self.y_range[1] - self.y_range[0]) + self.y_range[0]
|
| 1814 |
+
return output
|
| 1815 |
+
|
| 1816 |
+
|
| 1817 |
+
@auto_docstring(
|
| 1818 |
+
custom_intro="""
|
| 1819 |
+
The PatchTST for regression model.
|
| 1820 |
+
"""
|
| 1821 |
+
)
|
| 1822 |
+
class PatchTSTForRegression(PatchTSTPreTrainedModel):
|
| 1823 |
+
def __init__(self, config: PatchTSTConfig):
|
| 1824 |
+
super().__init__(config)
|
| 1825 |
+
|
| 1826 |
+
# Turn off masking
|
| 1827 |
+
if config.do_mask_input:
|
| 1828 |
+
logger.warning("Setting `do_mask_input` parameter to False.")
|
| 1829 |
+
config.do_mask_input = False
|
| 1830 |
+
|
| 1831 |
+
self.model = PatchTSTModel(config)
|
| 1832 |
+
if config.loss == "mse":
|
| 1833 |
+
self.distribution_output = None
|
| 1834 |
+
else:
|
| 1835 |
+
if config.distribution_output == "student_t":
|
| 1836 |
+
self.distribution_output = StudentTOutput(dim=config.num_targets)
|
| 1837 |
+
elif config.distribution_output == "normal":
|
| 1838 |
+
self.distribution_output = NormalOutput(dim=config.num_targets)
|
| 1839 |
+
elif config.distribution_output == "negative_binomial":
|
| 1840 |
+
self.distribution_output = NegativeBinomialOutput(dim=config.num_targets)
|
| 1841 |
+
else:
|
| 1842 |
+
raise ValueError(f"Unknown distribution output {config.distribution_output}")
|
| 1843 |
+
|
| 1844 |
+
self.head = PatchTSTRegressionHead(config, self.distribution_output)
|
| 1845 |
+
|
| 1846 |
+
# Initialize weights and apply final processing
|
| 1847 |
+
self.post_init()
|
| 1848 |
+
|
| 1849 |
+
@auto_docstring
|
| 1850 |
+
def forward(
|
| 1851 |
+
self,
|
| 1852 |
+
past_values: torch.Tensor,
|
| 1853 |
+
target_values: torch.Tensor | None = None,
|
| 1854 |
+
past_observed_mask: torch.Tensor | None = None,
|
| 1855 |
+
output_hidden_states: bool | None = None,
|
| 1856 |
+
output_attentions: bool | None = None,
|
| 1857 |
+
return_dict: bool | None = None,
|
| 1858 |
+
**kwargs,
|
| 1859 |
+
) -> tuple | PatchTSTForRegressionOutput:
|
| 1860 |
+
r"""
|
| 1861 |
+
past_values (`torch.Tensor` of shape `(bs, sequence_length, num_input_channels)`, *required*):
|
| 1862 |
+
Input sequence to the model
|
| 1863 |
+
target_values (`torch.Tensor` of shape `(bs, num_input_channels)`):
|
| 1864 |
+
Target values associates with the `past_values`
|
| 1865 |
+
past_observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
|
| 1866 |
+
Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
|
| 1867 |
+
in `[0, 1]`:
|
| 1868 |
+
|
| 1869 |
+
- 1 for values that are **observed**,
|
| 1870 |
+
- 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
|
| 1871 |
+
Whether or not to return a `ModelOutput` instead of a plain tuple.
|
| 1872 |
+
|
| 1873 |
+
Examples:
|
| 1874 |
+
|
| 1875 |
+
```python
|
| 1876 |
+
>>> from transformers import PatchTSTConfig, PatchTSTForRegression
|
| 1877 |
+
|
| 1878 |
+
>>> # Regression task with 6 input channels and regress 2 targets
|
| 1879 |
+
>>> model = PatchTSTForRegression.from_pretrained("namctin/patchtst_etth1_regression")
|
| 1880 |
+
|
| 1881 |
+
>>> # during inference, one only provides past values, the model outputs future values
|
| 1882 |
+
>>> past_values = torch.randn(20, 512, 6)
|
| 1883 |
+
>>> outputs = model(past_values=past_values)
|
| 1884 |
+
>>> regression_outputs = outputs.regression_outputs
|
| 1885 |
+
```"""
|
| 1886 |
+
|
| 1887 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1888 |
+
|
| 1889 |
+
model_output = self.model(
|
| 1890 |
+
past_values=past_values,
|
| 1891 |
+
past_observed_mask=past_observed_mask,
|
| 1892 |
+
output_hidden_states=output_hidden_states,
|
| 1893 |
+
output_attentions=output_attentions,
|
| 1894 |
+
return_dict=True,
|
| 1895 |
+
)
|
| 1896 |
+
# get output head. y_hat is of shape [bs x num_targets] or tuple of this shape
|
| 1897 |
+
y_hat = self.head(model_output.last_hidden_state)
|
| 1898 |
+
|
| 1899 |
+
loss = None
|
| 1900 |
+
if target_values is not None:
|
| 1901 |
+
if self.distribution_output:
|
| 1902 |
+
distribution = self.distribution_output.distribution(y_hat)
|
| 1903 |
+
# y_hat should be a 2-tuple, each with dimension [bs, num_targets]
|
| 1904 |
+
y_hat = tuple(item.view(-1, self.config.num_targets) for item in y_hat)
|
| 1905 |
+
loss = nll(distribution, target_values)
|
| 1906 |
+
# take average of the loss
|
| 1907 |
+
loss = weighted_average(loss)
|
| 1908 |
+
else:
|
| 1909 |
+
loss = nn.MSELoss(reduction="mean")
|
| 1910 |
+
loss = loss(y_hat, target_values)
|
| 1911 |
+
|
| 1912 |
+
if not return_dict:
|
| 1913 |
+
# hidden_states, attentions, mask
|
| 1914 |
+
outputs = (y_hat,) + model_output[1:-3]
|
| 1915 |
+
outputs = (loss,) + outputs if loss is not None else outputs
|
| 1916 |
+
return outputs
|
| 1917 |
+
return PatchTSTForRegressionOutput(
|
| 1918 |
+
loss=loss,
|
| 1919 |
+
regression_outputs=y_hat,
|
| 1920 |
+
hidden_states=model_output.hidden_states,
|
| 1921 |
+
attentions=model_output.attentions,
|
| 1922 |
+
)
|
| 1923 |
+
|
| 1924 |
+
@torch.no_grad()
|
| 1925 |
+
def generate(
|
| 1926 |
+
self,
|
| 1927 |
+
past_values: torch.Tensor,
|
| 1928 |
+
past_observed_mask: torch.Tensor | None = None,
|
| 1929 |
+
) -> SamplePatchTSTOutput:
|
| 1930 |
+
"""
|
| 1931 |
+
Generate sequences of sample predictions from a model with a probability distribution head.
|
| 1932 |
+
|
| 1933 |
+
Parameters:
|
| 1934 |
+
past_values (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_input_channels)`):
|
| 1935 |
+
Past values of the time series that serves as context in order to predict the future.
|
| 1936 |
+
past_observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
|
| 1937 |
+
Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
|
| 1938 |
+
in `[0, 1]`:
|
| 1939 |
+
|
| 1940 |
+
- 1 for values that are **observed**,
|
| 1941 |
+
- 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
|
| 1942 |
+
|
| 1943 |
+
Return:
|
| 1944 |
+
[`SamplePatchTSTOutput`] where the outputs `sequences` tensor will have shape `(batch_size, number of
|
| 1945 |
+
samples, num_targets)`.
|
| 1946 |
+
"""
|
| 1947 |
+
# get number of samples
|
| 1948 |
+
num_parallel_samples = self.config.num_parallel_samples
|
| 1949 |
+
|
| 1950 |
+
# get model output
|
| 1951 |
+
outputs = self(
|
| 1952 |
+
past_values=past_values,
|
| 1953 |
+
target_values=None,
|
| 1954 |
+
past_observed_mask=past_observed_mask,
|
| 1955 |
+
output_hidden_states=False,
|
| 1956 |
+
)
|
| 1957 |
+
|
| 1958 |
+
# get distribution
|
| 1959 |
+
distribution = self.distribution_output.distribution(outputs.regression_outputs)
|
| 1960 |
+
# get samples: list of [bs x num_targets]
|
| 1961 |
+
samples = [distribution.sample() for _ in range(num_parallel_samples)]
|
| 1962 |
+
# samples: [bs x num_samples x num_targets]
|
| 1963 |
+
samples = torch.stack(samples, dim=1).view(-1, num_parallel_samples, self.config.num_targets)
|
| 1964 |
+
return SamplePatchTSTOutput(sequences=samples)
|
| 1965 |
+
|
| 1966 |
+
|
| 1967 |
+
__all__ = [
|
| 1968 |
+
"PatchTSTModel",
|
| 1969 |
+
"PatchTSTPreTrainedModel",
|
| 1970 |
+
"PatchTSTForPrediction",
|
| 1971 |
+
"PatchTSTForPretraining",
|
| 1972 |
+
"PatchTSTForRegression",
|
| 1973 |
+
"PatchTSTForClassification",
|
| 1974 |
+
]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_audio/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 the HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_pe_audio import *
|
| 22 |
+
from .feature_extraction_pe_audio import *
|
| 23 |
+
from .modeling_pe_audio import *
|
| 24 |
+
from .processing_pe_audio import *
|
| 25 |
+
else:
|
| 26 |
+
import sys
|
| 27 |
+
|
| 28 |
+
_file = globals()["__file__"]
|
| 29 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_audio/configuration_pe_audio.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 the HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from ...configuration_utils import PreTrainedConfig, PretrainedConfig
|
| 16 |
+
from ...modeling_rope_utils import RopeParameters
|
| 17 |
+
from ...utils import logging
|
| 18 |
+
from ..auto import CONFIG_MAPPING, AutoConfig
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
logger = logging.get_logger(__name__)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class PeAudioEncoderConfig(PreTrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
This is the configuration class to store the configuration of a [`PeAudioEncoder`]. It is used to instantiate a
|
| 27 |
+
PeAudioEncoder model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 28 |
+
with the defaults will yield a similar configuration to that of pe-av-large.
|
| 29 |
+
e.g. [facebook/pe-av-large](https://huggingface.co/facebook/pe-av-large)
|
| 30 |
+
|
| 31 |
+
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
|
| 32 |
+
documentation from [`PreTrainedConfig`] for more information.
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
dac_config (`Union[PreTrainedConfig, dict]`, *optional*):
|
| 37 |
+
Configuration for the DAC audio encoder used to tokenize the raw audio inputs. If a dictionary is passed, it
|
| 38 |
+
will be used to instantiate a [`~transformers.DacConfig`] with default DAC hyperparameters.
|
| 39 |
+
hidden_size (`int`, *optional*, defaults to 1792):
|
| 40 |
+
Dimension of the hidden representations.
|
| 41 |
+
intermediate_size (`int`, *optional*, defaults to 4800):
|
| 42 |
+
Dimension of the feedforward layers in the Transformer blocks.
|
| 43 |
+
num_hidden_layers (`int`, *optional*, defaults to 6):
|
| 44 |
+
Number of Transformer encoder blocks.
|
| 45 |
+
num_attention_heads (`int`, *optional*, defaults to 14):
|
| 46 |
+
Number of attention heads used in each attention layer.
|
| 47 |
+
num_key_value_heads (`int`, *optional*):
|
| 48 |
+
Number of key and value heads for grouped-query attention. If unset, this defaults to `num_attention_heads`.
|
| 49 |
+
head_dim (`int`, *optional*, defaults to 128):
|
| 50 |
+
Dimension of each attention head for query, key, and value projections.
|
| 51 |
+
hidden_act (`str`, *optional*, defaults to `"silu"`):
|
| 52 |
+
The non-linear activation function (function or string) in the Transformer blocks.
|
| 53 |
+
max_position_embeddings (`int`, *optional*, defaults to 10000):
|
| 54 |
+
Maximum sequence length supported by the rotary position embeddings.
|
| 55 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 56 |
+
Standard deviation of the truncated normal initializer for weight matrices.
|
| 57 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-05):
|
| 58 |
+
Epsilon used by the RMS normalization layers.
|
| 59 |
+
rope_parameters (`Union[RopeParameters, dict]`, *optional*, defaults to `{'rope_theta': 20000}`):
|
| 60 |
+
Parameters for the rotary position embeddings, such as the base `rope_theta`.
|
| 61 |
+
attention_bias (`bool`, *optional*, defaults to `False`):
|
| 62 |
+
Whether to use bias terms in the query, key, value, and output projections.
|
| 63 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 64 |
+
Dropout ratio applied to attention probabilities.
|
| 65 |
+
|
| 66 |
+
```python
|
| 67 |
+
>>> from transformers import PeAudioEncoder, PeAudioEncoderConfig
|
| 68 |
+
|
| 69 |
+
>>> # Initializing a PeAudioEncoder style configuration
|
| 70 |
+
>>> configuration = PeAudioEncoderConfig()
|
| 71 |
+
|
| 72 |
+
>>> # Initializing a model from the pe-av-large style configuration
|
| 73 |
+
>>> model = PeAudioEncoder(configuration)
|
| 74 |
+
|
| 75 |
+
>>> # Accessing the model configuration
|
| 76 |
+
>>> configuration = model.config
|
| 77 |
+
```"""
|
| 78 |
+
|
| 79 |
+
model_type = "pe_audio_encoder"
|
| 80 |
+
sub_configs = {"dac_config": AutoConfig}
|
| 81 |
+
base_config_key = "audio_video_config"
|
| 82 |
+
|
| 83 |
+
_default_dac_config_kwargs = {
|
| 84 |
+
"downsampling_ratios": [2, 8, 10, 12],
|
| 85 |
+
"encoder_hidden_size": 64,
|
| 86 |
+
"codebook_dim": 128,
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
def __init__(
|
| 90 |
+
self,
|
| 91 |
+
dac_config: dict | PreTrainedConfig | None = None,
|
| 92 |
+
hidden_size: int | None = 1792,
|
| 93 |
+
intermediate_size: int | None = 4800,
|
| 94 |
+
num_hidden_layers: int | None = 6,
|
| 95 |
+
num_attention_heads: int | None = 14,
|
| 96 |
+
num_key_value_heads: int | None = None,
|
| 97 |
+
head_dim: int | None = 128,
|
| 98 |
+
hidden_act: str | None = "silu",
|
| 99 |
+
max_position_embeddings: int | None = 10000,
|
| 100 |
+
initializer_range: float | None = 0.02,
|
| 101 |
+
rms_norm_eps: float | None = 1e-5,
|
| 102 |
+
rope_parameters: RopeParameters | dict | None = {"rope_theta": 20000},
|
| 103 |
+
attention_bias: bool | None = False,
|
| 104 |
+
attention_dropout: float | None = 0.0,
|
| 105 |
+
**kwargs,
|
| 106 |
+
):
|
| 107 |
+
self.hidden_size = hidden_size
|
| 108 |
+
self.intermediate_size = intermediate_size
|
| 109 |
+
self.num_hidden_layers = num_hidden_layers
|
| 110 |
+
self.num_attention_heads = num_attention_heads
|
| 111 |
+
|
| 112 |
+
# for backward compatibility
|
| 113 |
+
if num_key_value_heads is None:
|
| 114 |
+
num_key_value_heads = num_attention_heads
|
| 115 |
+
|
| 116 |
+
self.num_key_value_heads = num_key_value_heads
|
| 117 |
+
self.head_dim = head_dim
|
| 118 |
+
self.hidden_act = hidden_act
|
| 119 |
+
self.max_position_embeddings = max_position_embeddings
|
| 120 |
+
self.initializer_range = initializer_range
|
| 121 |
+
self.rms_norm_eps = rms_norm_eps
|
| 122 |
+
self.rope_parameters = rope_parameters
|
| 123 |
+
self.attention_bias = attention_bias
|
| 124 |
+
self.attention_dropout = attention_dropout
|
| 125 |
+
|
| 126 |
+
if isinstance(dac_config, dict):
|
| 127 |
+
dac_config["model_type"] = dac_config.get("model_type", "dac")
|
| 128 |
+
dac_config = CONFIG_MAPPING[dac_config["model_type"]](**{**self._default_dac_config_kwargs, **dac_config})
|
| 129 |
+
elif dac_config is None:
|
| 130 |
+
dac_config = CONFIG_MAPPING["dac"](**self._default_dac_config_kwargs)
|
| 131 |
+
|
| 132 |
+
self.dac_config = dac_config
|
| 133 |
+
|
| 134 |
+
super().__init__(**kwargs)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class PeAudioConfig(PretrainedConfig):
|
| 138 |
+
r"""
|
| 139 |
+
This is the configuration class to store the configuration of a [`PeAudioModel`]. It is used to instantiate a
|
| 140 |
+
PeAudioModel model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 141 |
+
with the defaults will yield a similar configuration to that of pe-av-large.
|
| 142 |
+
e.g. [facebook/pe-av-large](https://huggingface.co/facebook/pe-av-large)
|
| 143 |
+
|
| 144 |
+
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
|
| 145 |
+
documentation from [`PreTrainedConfig`] for more information.
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
Args:
|
| 149 |
+
text_config (`dict` or `PreTrainedConfig`, *optional*):
|
| 150 |
+
Configuration for the text model component.
|
| 151 |
+
audio_config (`dict` or `PreTrainedConfig`, *optional*):
|
| 152 |
+
Configuration for the audio encoder component.
|
| 153 |
+
|
| 154 |
+
```python
|
| 155 |
+
>>> from transformers import PeAudioModel, PeAudioConfig
|
| 156 |
+
|
| 157 |
+
>>> # Initializing a PeAudioModel style configuration
|
| 158 |
+
>>> configuration = PeAudioConfig()
|
| 159 |
+
|
| 160 |
+
>>> # Initializing a model from the pe-av-large style configuration
|
| 161 |
+
>>> model = PeAudioModel(configuration)
|
| 162 |
+
|
| 163 |
+
>>> # Accessing the model configuration
|
| 164 |
+
>>> configuration = model.config
|
| 165 |
+
```"""
|
| 166 |
+
|
| 167 |
+
model_type = "pe_audio"
|
| 168 |
+
sub_configs = {"text_config": AutoConfig, "audio_config": PeAudioEncoderConfig}
|
| 169 |
+
base_config_key = "audio_video_config"
|
| 170 |
+
|
| 171 |
+
_default_text_config_kwargs = {
|
| 172 |
+
"model_type": "modernbert",
|
| 173 |
+
"hidden_size": 1024,
|
| 174 |
+
"intermediate_size": 2624,
|
| 175 |
+
"num_hidden_layers": 22,
|
| 176 |
+
"num_attention_heads": 16,
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
def __init__(
|
| 180 |
+
self,
|
| 181 |
+
text_config=None,
|
| 182 |
+
audio_config=None,
|
| 183 |
+
**kwargs,
|
| 184 |
+
):
|
| 185 |
+
if isinstance(text_config, dict):
|
| 186 |
+
text_config["model_type"] = text_config.get("model_type", "modernbert")
|
| 187 |
+
text_config = CONFIG_MAPPING[text_config["model_type"]](
|
| 188 |
+
**{**self._default_text_config_kwargs, **text_config}
|
| 189 |
+
)
|
| 190 |
+
elif text_config is None:
|
| 191 |
+
text_config = CONFIG_MAPPING["modernbert"](**self._default_text_config_kwargs)
|
| 192 |
+
|
| 193 |
+
if isinstance(audio_config, dict):
|
| 194 |
+
audio_config = PeAudioEncoderConfig(**audio_config)
|
| 195 |
+
elif audio_config is None:
|
| 196 |
+
audio_config = PeAudioEncoderConfig()
|
| 197 |
+
|
| 198 |
+
self.text_config = text_config
|
| 199 |
+
self.audio_config = audio_config
|
| 200 |
+
|
| 201 |
+
super().__init__(**kwargs)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
__all__ = ["PeAudioEncoderConfig", "PeAudioConfig"]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_audio/feature_extraction_pe_audio.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
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 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
|
| 17 |
+
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
|
| 18 |
+
from ...feature_extraction_utils import BatchFeature
|
| 19 |
+
from ...processing_utils import load_audio
|
| 20 |
+
from ...utils import PaddingStrategy, TensorType, logging
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class PeAudioFeatureExtractor(SequenceFeatureExtractor):
|
| 27 |
+
r"""
|
| 28 |
+
Constructs a PeAudioFeatureExtractor feature extractor.
|
| 29 |
+
|
| 30 |
+
This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExtractor`] which contains
|
| 31 |
+
most of the main methods. Users should refer to this superclass for more information regarding those methods.
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
feature_size (`int`, *optional*, defaults to 1):
|
| 35 |
+
The feature dimension of the extracted features. Use 1 for mono, 2 for stereo.
|
| 36 |
+
sampling_rate (`int`, *optional*, defaults to 48000):
|
| 37 |
+
The sampling rate at which the audio waveform should be digitalized, expressed in hertz (Hz).
|
| 38 |
+
padding_value (`float`, *optional*, defaults to 0.0):
|
| 39 |
+
The value that is used for padding.
|
| 40 |
+
hop_length (`int`, *optional*, defaults to 1920):
|
| 41 |
+
Overlap length between successive windows.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
model_input_names = ["input_values"]
|
| 45 |
+
|
| 46 |
+
def __init__(
|
| 47 |
+
self,
|
| 48 |
+
feature_size: int = 1,
|
| 49 |
+
sampling_rate: int = 48_000,
|
| 50 |
+
padding_value: float = 0.0,
|
| 51 |
+
hop_length: int = 1920,
|
| 52 |
+
**kwargs,
|
| 53 |
+
):
|
| 54 |
+
super().__init__(feature_size=feature_size, sampling_rate=sampling_rate, padding_value=padding_value, **kwargs)
|
| 55 |
+
self.hop_length = hop_length
|
| 56 |
+
|
| 57 |
+
def _reflect_pad(self, wav):
|
| 58 |
+
if len(wav) % self.hop_length == 0:
|
| 59 |
+
return wav
|
| 60 |
+
p1d = (0, self.hop_length - (len(wav) % self.hop_length))
|
| 61 |
+
return np.pad(wav, p1d, "reflect")
|
| 62 |
+
|
| 63 |
+
def __call__(
|
| 64 |
+
self,
|
| 65 |
+
raw_audio: np.ndarray | list[float] | list[np.ndarray] | list[list[float]] | str | list[str],
|
| 66 |
+
padding: bool | str | PaddingStrategy | None = None,
|
| 67 |
+
truncation: bool | None = False,
|
| 68 |
+
max_length: int | None = None,
|
| 69 |
+
return_tensors: str | TensorType | None = None,
|
| 70 |
+
sampling_rate: int | None = None,
|
| 71 |
+
) -> BatchFeature:
|
| 72 |
+
from_file = False
|
| 73 |
+
if isinstance(raw_audio, str):
|
| 74 |
+
raw_audio = [raw_audio]
|
| 75 |
+
|
| 76 |
+
if isinstance(raw_audio, (list, tuple)) and isinstance(raw_audio[0], str):
|
| 77 |
+
loaded = []
|
| 78 |
+
for audio_file in raw_audio:
|
| 79 |
+
loaded.append(load_audio(audio_file, self.sampling_rate))
|
| 80 |
+
raw_audio = loaded
|
| 81 |
+
from_file = True
|
| 82 |
+
|
| 83 |
+
if sampling_rate is not None:
|
| 84 |
+
if sampling_rate != self.sampling_rate:
|
| 85 |
+
raise ValueError(
|
| 86 |
+
f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of"
|
| 87 |
+
f" {self.sampling_rate}. Please make sure that the provided audio input was sampled with"
|
| 88 |
+
f" {self.sampling_rate} and not {sampling_rate}."
|
| 89 |
+
)
|
| 90 |
+
elif not from_file:
|
| 91 |
+
logger.warning(
|
| 92 |
+
f"It is strongly recommended to pass the `sampling_rate` argument to `{self.__class__.__name__}()`. "
|
| 93 |
+
"Failing to do so can result in silent errors that might be hard to debug."
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
if padding and truncation:
|
| 97 |
+
raise ValueError("Both padding and truncation were set. Make sure you only set one.")
|
| 98 |
+
elif padding is None:
|
| 99 |
+
# by default let's pad the inputs
|
| 100 |
+
padding = True
|
| 101 |
+
|
| 102 |
+
is_batched = bool(
|
| 103 |
+
isinstance(raw_audio, (list, tuple)) and (isinstance(raw_audio[0], (np.ndarray, tuple, list)))
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
if is_batched:
|
| 107 |
+
raw_audio = [np.asarray(audio, dtype=np.float32).T for audio in raw_audio]
|
| 108 |
+
elif not is_batched and not isinstance(raw_audio, np.ndarray):
|
| 109 |
+
raw_audio = np.asarray(raw_audio, dtype=np.float32)
|
| 110 |
+
elif isinstance(raw_audio, np.ndarray) and raw_audio.dtype is np.dtype(np.float64):
|
| 111 |
+
raw_audio = raw_audio.astype(np.float32)
|
| 112 |
+
|
| 113 |
+
# always return batch
|
| 114 |
+
if not is_batched:
|
| 115 |
+
raw_audio = [np.asarray(raw_audio).T]
|
| 116 |
+
|
| 117 |
+
if isinstance(raw_audio, list):
|
| 118 |
+
raw_audio = [self._reflect_pad(x) for x in raw_audio]
|
| 119 |
+
else:
|
| 120 |
+
raw_audio = self._reflect_pad(raw_audio)
|
| 121 |
+
|
| 122 |
+
# verify inputs are valid
|
| 123 |
+
for example in raw_audio:
|
| 124 |
+
if example.ndim > 2:
|
| 125 |
+
raise ValueError(f"Expected input shape (channels, length) but got shape {example.shape}")
|
| 126 |
+
if self.feature_size == 1 and example.ndim != 1:
|
| 127 |
+
raise ValueError(f"Expected mono audio but example has {example.shape[-1]} channels")
|
| 128 |
+
if self.feature_size == 2:
|
| 129 |
+
raise ValueError("Stereo audio isn't supported for now")
|
| 130 |
+
|
| 131 |
+
input_values = BatchFeature({"input_values": raw_audio})
|
| 132 |
+
|
| 133 |
+
# normal padding on batch
|
| 134 |
+
padded_inputs = self.pad(
|
| 135 |
+
input_values,
|
| 136 |
+
max_length=max_length,
|
| 137 |
+
truncation=truncation,
|
| 138 |
+
padding=padding,
|
| 139 |
+
return_attention_mask=padding,
|
| 140 |
+
pad_to_multiple_of=self.hop_length,
|
| 141 |
+
)
|
| 142 |
+
if padding:
|
| 143 |
+
padded_inputs["padding_mask"] = padded_inputs.pop("attention_mask")
|
| 144 |
+
if padding:
|
| 145 |
+
padded_inputs.input_values = padded_inputs.input_values[:, np.newaxis, :]
|
| 146 |
+
|
| 147 |
+
input_values = []
|
| 148 |
+
for example in padded_inputs.pop("input_values"):
|
| 149 |
+
if self.feature_size == 1:
|
| 150 |
+
example = example[..., None]
|
| 151 |
+
input_values.append(example.T)
|
| 152 |
+
|
| 153 |
+
padded_inputs["input_values"] = input_values
|
| 154 |
+
if return_tensors is not None:
|
| 155 |
+
padded_inputs = padded_inputs.convert_to_tensors(return_tensors)
|
| 156 |
+
|
| 157 |
+
return padded_inputs
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
__all__ = ["PeAudioFeatureExtractor"]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_audio/modeling_pe_audio.py
ADDED
|
@@ -0,0 +1,826 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/pe_audio/modular_pe_audio.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_pe_audio.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2025 the HuggingFace Inc. team. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
import math
|
| 21 |
+
from collections.abc import Callable
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
from typing import Any, Optional
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
import torch.nn.functional as F
|
| 28 |
+
|
| 29 |
+
from ... import initialization as init
|
| 30 |
+
from ...activations import ACT2FN
|
| 31 |
+
from ...cache_utils import Cache
|
| 32 |
+
from ...configuration_utils import PreTrainedConfig
|
| 33 |
+
from ...integrations import use_kernel_forward_from_hub, use_kernelized_func
|
| 34 |
+
from ...masking_utils import create_bidirectional_mask
|
| 35 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 36 |
+
from ...modeling_outputs import BaseModelOutputWithPooling, MaskedLMOutput
|
| 37 |
+
from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
| 38 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 39 |
+
from ...processing_utils import Unpack
|
| 40 |
+
from ...utils import ModelOutput, TransformersKwargs, auto_docstring, can_return_tuple
|
| 41 |
+
from ...utils.generic import maybe_autocast, merge_with_config_defaults
|
| 42 |
+
from ...utils.output_capturing import capture_outputs
|
| 43 |
+
from ..auto import AutoModel
|
| 44 |
+
from .configuration_pe_audio import PeAudioConfig, PeAudioEncoderConfig
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class Snake1d(nn.Module):
|
| 48 |
+
"""
|
| 49 |
+
A 1-dimensional Snake activation function module.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
def __init__(self, hidden_dim):
|
| 53 |
+
super().__init__()
|
| 54 |
+
self.alpha = nn.Parameter(torch.ones(1, hidden_dim, 1))
|
| 55 |
+
|
| 56 |
+
def forward(self, hidden_states):
|
| 57 |
+
shape = hidden_states.shape
|
| 58 |
+
hidden_states = hidden_states.reshape(shape[0], shape[1], -1)
|
| 59 |
+
hidden_states = hidden_states + (self.alpha + 1e-9).reciprocal() * torch.sin(self.alpha * hidden_states).pow(2)
|
| 60 |
+
hidden_states = hidden_states.reshape(shape)
|
| 61 |
+
return hidden_states
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class PeAudioDacResidualUnit(nn.Module):
|
| 65 |
+
"""
|
| 66 |
+
A residual unit composed of Snake1d and weight-normalized Conv1d layers with dilations.
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
def __init__(self, dimension: int = 16, dilation: int = 1):
|
| 70 |
+
super().__init__()
|
| 71 |
+
pad = ((7 - 1) * dilation) // 2
|
| 72 |
+
|
| 73 |
+
self.snake1 = Snake1d(dimension)
|
| 74 |
+
self.conv1 = nn.Conv1d(dimension, dimension, kernel_size=7, dilation=dilation, padding=pad)
|
| 75 |
+
self.snake2 = Snake1d(dimension)
|
| 76 |
+
self.conv2 = nn.Conv1d(dimension, dimension, kernel_size=1)
|
| 77 |
+
|
| 78 |
+
def forward(self, hidden_state):
|
| 79 |
+
"""
|
| 80 |
+
Forward pass through the residual unit.
|
| 81 |
+
|
| 82 |
+
Args:
|
| 83 |
+
hidden_state (`torch.Tensor` of shape `(batch_size, channels, time_steps)`):
|
| 84 |
+
Input tensor .
|
| 85 |
+
|
| 86 |
+
Returns:
|
| 87 |
+
output_tensor (`torch.Tensor` of shape `(batch_size, channels, time_steps)`):
|
| 88 |
+
Input tensor after passing through the residual unit.
|
| 89 |
+
"""
|
| 90 |
+
output_tensor = hidden_state
|
| 91 |
+
output_tensor = self.conv1(self.snake1(output_tensor))
|
| 92 |
+
output_tensor = self.conv2(self.snake2(output_tensor))
|
| 93 |
+
|
| 94 |
+
padding = (hidden_state.shape[-1] - output_tensor.shape[-1]) // 2
|
| 95 |
+
if padding > 0:
|
| 96 |
+
hidden_state = hidden_state[..., padding:-padding]
|
| 97 |
+
output_tensor = hidden_state + output_tensor
|
| 98 |
+
return output_tensor
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class PeAudioDacEncoderBlock(nn.Module):
|
| 102 |
+
"""Encoder block used in PE_AUDIO_DAC encoder."""
|
| 103 |
+
|
| 104 |
+
def __init__(self, config: PreTrainedConfig, stride: int = 1, stride_index: int = 1):
|
| 105 |
+
super().__init__()
|
| 106 |
+
|
| 107 |
+
dimension = config.encoder_hidden_size * 2**stride_index
|
| 108 |
+
self.res_unit1 = PeAudioDacResidualUnit(dimension // 2, dilation=1)
|
| 109 |
+
self.res_unit2 = PeAudioDacResidualUnit(dimension // 2, dilation=3)
|
| 110 |
+
self.res_unit3 = PeAudioDacResidualUnit(dimension // 2, dilation=9)
|
| 111 |
+
self.snake1 = Snake1d(dimension // 2)
|
| 112 |
+
self.conv1 = nn.Conv1d(
|
| 113 |
+
dimension // 2, dimension, kernel_size=2 * stride, stride=stride, padding=math.ceil(stride / 2)
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
def forward(self, hidden_state):
|
| 117 |
+
hidden_state = self.res_unit1(hidden_state)
|
| 118 |
+
hidden_state = self.res_unit2(hidden_state)
|
| 119 |
+
hidden_state = self.snake1(self.res_unit3(hidden_state))
|
| 120 |
+
hidden_state = self.conv1(hidden_state)
|
| 121 |
+
|
| 122 |
+
return hidden_state
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class PeAudioDacEncoder(nn.Module):
|
| 126 |
+
"""PE_AUDIO_DAC Encoder"""
|
| 127 |
+
|
| 128 |
+
def __init__(self, config: PreTrainedConfig):
|
| 129 |
+
super().__init__()
|
| 130 |
+
|
| 131 |
+
strides = config.downsampling_ratios
|
| 132 |
+
# Create first convolution
|
| 133 |
+
self.conv1 = nn.Conv1d(1, config.encoder_hidden_size, kernel_size=7, padding=3)
|
| 134 |
+
|
| 135 |
+
self.block = []
|
| 136 |
+
# Create EncoderBlocks that double channels as they downsample by `stride`
|
| 137 |
+
for stride_index, stride in enumerate(strides):
|
| 138 |
+
stride_index = stride_index + 1
|
| 139 |
+
self.block += [PeAudioDacEncoderBlock(config, stride=stride, stride_index=stride_index)]
|
| 140 |
+
|
| 141 |
+
self.block = nn.ModuleList(self.block)
|
| 142 |
+
d_model = config.encoder_hidden_size * 2**stride_index
|
| 143 |
+
self.snake1 = Snake1d(d_model)
|
| 144 |
+
self.conv2 = nn.Conv1d(d_model, config.hidden_size, kernel_size=3, padding=1)
|
| 145 |
+
|
| 146 |
+
def forward(self, hidden_state):
|
| 147 |
+
hidden_state = self.conv1(hidden_state)
|
| 148 |
+
|
| 149 |
+
for module in self.block:
|
| 150 |
+
hidden_state = module(hidden_state)
|
| 151 |
+
|
| 152 |
+
hidden_state = self.snake1(hidden_state)
|
| 153 |
+
hidden_state = self.conv2(hidden_state)
|
| 154 |
+
|
| 155 |
+
return hidden_state
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class PeAudioEncoderEmbedder(nn.Module):
|
| 159 |
+
def __init__(self, config: PeAudioEncoderConfig):
|
| 160 |
+
super().__init__()
|
| 161 |
+
self.dac_encoder = PeAudioDacEncoder(config.dac_config)
|
| 162 |
+
self.bottleneck = nn.Conv1d(config.dac_config.hidden_size, config.dac_config.codebook_dim, 1)
|
| 163 |
+
self.data_proj = nn.Linear(config.dac_config.codebook_dim, config.hidden_size)
|
| 164 |
+
self.config = config
|
| 165 |
+
|
| 166 |
+
def forward(
|
| 167 |
+
self,
|
| 168 |
+
input_values: torch.Tensor,
|
| 169 |
+
padding_mask: torch.Tensor | None = None,
|
| 170 |
+
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
| 171 |
+
with torch.no_grad(), torch.backends.cudnn.flags(enabled=False):
|
| 172 |
+
hidden_states = self.dac_encoder(input_values)
|
| 173 |
+
hidden_states = self.bottleneck(hidden_states)
|
| 174 |
+
|
| 175 |
+
codec_features = hidden_states.transpose(1, 2)
|
| 176 |
+
inputs_embeds = self.data_proj(codec_features)
|
| 177 |
+
|
| 178 |
+
if padding_mask is not None:
|
| 179 |
+
padding_mask = padding_mask[:, :: self.config.dac_config.hop_length]
|
| 180 |
+
|
| 181 |
+
return inputs_embeds, padding_mask
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
class PeAudioContrastiveHead(nn.Module):
|
| 185 |
+
def __init__(
|
| 186 |
+
self,
|
| 187 |
+
in_dim: int,
|
| 188 |
+
out_dim: int,
|
| 189 |
+
) -> None:
|
| 190 |
+
super().__init__()
|
| 191 |
+
self.layer_norm = nn.LayerNorm(normalized_shape=in_dim, eps=1e-6)
|
| 192 |
+
self.proj = nn.Linear(in_dim, out_dim, bias=False)
|
| 193 |
+
|
| 194 |
+
def forward(self, x: torch.Tensor) -> torch.FloatTensor:
|
| 195 |
+
return self.proj(self.layer_norm(x))
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
class PeAudioMaskedGroupNorm(nn.GroupNorm):
|
| 199 |
+
def forward(self, x, padding_mask=None):
|
| 200 |
+
if padding_mask is None:
|
| 201 |
+
return super().forward(x)
|
| 202 |
+
|
| 203 |
+
batch_size, hidden_size, seq_len = x.shape
|
| 204 |
+
group_size = hidden_size // self.num_groups
|
| 205 |
+
grouped_shape = (batch_size, -1, group_size, seq_len)
|
| 206 |
+
|
| 207 |
+
x_grouped = x.view(grouped_shape)
|
| 208 |
+
padding_mask_grouped = padding_mask.reshape(grouped_shape).bool()
|
| 209 |
+
|
| 210 |
+
mean = torch.masked.mean(x_grouped, mask=padding_mask_grouped, dim=(2, 3), keepdim=True)
|
| 211 |
+
var = torch.masked.var(x_grouped, mask=padding_mask_grouped, dim=(2, 3), keepdim=True, unbiased=False)
|
| 212 |
+
|
| 213 |
+
x_norm = (x_grouped - mean) / torch.sqrt(var + self.eps)
|
| 214 |
+
x_norm = x_norm.view(x.shape)
|
| 215 |
+
|
| 216 |
+
if self.affine:
|
| 217 |
+
x_norm = x_norm * self.weight.view(1, -1, 1) + self.bias.view(1, -1, 1)
|
| 218 |
+
|
| 219 |
+
return x_norm * padding_mask
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
class PeAudioConvBlock1d(nn.Module):
|
| 223 |
+
def __init__(self, config):
|
| 224 |
+
super().__init__()
|
| 225 |
+
self.groupnorm = PeAudioMaskedGroupNorm(num_groups=1, num_channels=config.hidden_size)
|
| 226 |
+
self.activation = nn.SiLU()
|
| 227 |
+
self.project = nn.Conv1d(
|
| 228 |
+
in_channels=config.hidden_size,
|
| 229 |
+
out_channels=config.hidden_size,
|
| 230 |
+
kernel_size=3,
|
| 231 |
+
padding="same",
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
def forward(self, x, padding_mask=None):
|
| 235 |
+
x = self.groupnorm(x, padding_mask=padding_mask)
|
| 236 |
+
x = self.activation(x)
|
| 237 |
+
return self.project(x)
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
class PeAudioResnetBlock1d(nn.Module):
|
| 241 |
+
def __init__(self, config):
|
| 242 |
+
super().__init__()
|
| 243 |
+
self.block1 = PeAudioConvBlock1d(config)
|
| 244 |
+
self.block2 = PeAudioConvBlock1d(config)
|
| 245 |
+
|
| 246 |
+
def forward(self, hidden_states, padding_mask=None):
|
| 247 |
+
"""
|
| 248 |
+
Args:
|
| 249 |
+
hidden_states: (batch_size, seq_len, hidden_size)
|
| 250 |
+
padding_mask: (batch_size, seq_len)
|
| 251 |
+
Returns:
|
| 252 |
+
hidden_states: (batch_size, seq_len, hidden_size)
|
| 253 |
+
"""
|
| 254 |
+
# transpose for convolutions
|
| 255 |
+
# (batch_size, seq_len, hidden_size) -> (batch_size, hidden_size, seq_len)
|
| 256 |
+
hidden_states = hidden_states.transpose(1, 2)
|
| 257 |
+
|
| 258 |
+
if padding_mask is not None:
|
| 259 |
+
padding_mask = padding_mask.unsqueeze(1).expand_as(hidden_states)
|
| 260 |
+
|
| 261 |
+
residual = hidden_states
|
| 262 |
+
hidden_states = self.block1(hidden_states, padding_mask=padding_mask)
|
| 263 |
+
hidden_states = self.block2(hidden_states, padding_mask=padding_mask)
|
| 264 |
+
hidden_states = residual + hidden_states
|
| 265 |
+
|
| 266 |
+
return hidden_states.transpose(1, 2)
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
class PeAudioEncoderPatchEmbedder(nn.Module):
|
| 270 |
+
def __init__(self, config):
|
| 271 |
+
super().__init__()
|
| 272 |
+
self.resnet_block = PeAudioResnetBlock1d(config)
|
| 273 |
+
self.class_embedding = nn.Parameter(torch.randn(1, 1, config.hidden_size))
|
| 274 |
+
|
| 275 |
+
def forward(self, inputs_embeds, padding_mask=None):
|
| 276 |
+
# Embedding step: prepend class token and run the ResNet block.
|
| 277 |
+
hidden_states = torch.cat(
|
| 278 |
+
[self.class_embedding.expand(inputs_embeds.size(0), -1, -1), inputs_embeds],
|
| 279 |
+
dim=1,
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
if padding_mask is not None:
|
| 283 |
+
# TODO: any reason why we take padding_mask[0] and not just 1?
|
| 284 |
+
padding_mask = torch.cat([padding_mask[:, [0]], padding_mask], dim=1)
|
| 285 |
+
|
| 286 |
+
hidden_states = self.resnet_block(hidden_states, padding_mask=padding_mask)
|
| 287 |
+
return hidden_states, padding_mask
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 291 |
+
"""
|
| 292 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 293 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 294 |
+
"""
|
| 295 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 296 |
+
if n_rep == 1:
|
| 297 |
+
return hidden_states
|
| 298 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 299 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def eager_attention_forward(
|
| 303 |
+
module: nn.Module,
|
| 304 |
+
query: torch.Tensor,
|
| 305 |
+
key: torch.Tensor,
|
| 306 |
+
value: torch.Tensor,
|
| 307 |
+
attention_mask: torch.Tensor | None,
|
| 308 |
+
scaling: float,
|
| 309 |
+
dropout: float = 0.0,
|
| 310 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 311 |
+
):
|
| 312 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 313 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 314 |
+
|
| 315 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 316 |
+
if attention_mask is not None:
|
| 317 |
+
attn_weights = attn_weights + attention_mask
|
| 318 |
+
|
| 319 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 320 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 321 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 322 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 323 |
+
|
| 324 |
+
return attn_output, attn_weights
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def stack_freqs(cos: torch.Tensor, sin: torch.Tensor):
|
| 328 |
+
dim = cos.size(-1)
|
| 329 |
+
cos = cos.narrow(-1, 0, dim // 2)
|
| 330 |
+
sin = sin.narrow(-1, 0, dim // 2)
|
| 331 |
+
freqs_cis = torch.stack((cos, -sin, sin, cos), dim=-1).view(*cos.size(), 2, 2)
|
| 332 |
+
return freqs_cis
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
|
| 336 |
+
freqs_cis = stack_freqs(cos, sin)
|
| 337 |
+
freqs_cis = freqs_cis.unsqueeze(unsqueeze_dim)
|
| 338 |
+
q_ = q.reshape(*q.shape[:-1], -1, 1, 2)
|
| 339 |
+
k_ = k.reshape(*k.shape[:-1], -1, 1, 2)
|
| 340 |
+
return (q_ * freqs_cis).sum(5).flatten(3), (k_ * freqs_cis).sum(5).flatten(3)
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
@use_kernel_forward_from_hub("RMSNorm")
|
| 344 |
+
class PeAudioEncoderRMSNorm(nn.Module):
|
| 345 |
+
def __init__(self, hidden_size, eps: float = 1e-6) -> None:
|
| 346 |
+
"""
|
| 347 |
+
PeAudioEncoderRMSNorm is equivalent to T5LayerNorm
|
| 348 |
+
"""
|
| 349 |
+
super().__init__()
|
| 350 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 351 |
+
self.variance_epsilon = eps
|
| 352 |
+
|
| 353 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 354 |
+
input_dtype = hidden_states.dtype
|
| 355 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 356 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 357 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 358 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 359 |
+
|
| 360 |
+
def extra_repr(self):
|
| 361 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
@use_kernelized_func(apply_rotary_pos_emb)
|
| 365 |
+
class PeAudioEncoderAttention(nn.Module):
|
| 366 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 367 |
+
|
| 368 |
+
def __init__(self, config, layer_idx):
|
| 369 |
+
super().__init__()
|
| 370 |
+
self.layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None
|
| 371 |
+
self.config = config
|
| 372 |
+
self.layer_idx = layer_idx
|
| 373 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 374 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 375 |
+
self.scaling = self.head_dim**-0.5
|
| 376 |
+
self.attention_dropout = config.attention_dropout
|
| 377 |
+
self.is_causal = False
|
| 378 |
+
|
| 379 |
+
self.q_proj = nn.Linear(
|
| 380 |
+
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
| 381 |
+
)
|
| 382 |
+
self.k_proj = nn.Linear(
|
| 383 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 384 |
+
)
|
| 385 |
+
self.v_proj = nn.Linear(
|
| 386 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 387 |
+
)
|
| 388 |
+
self.o_proj = nn.Linear(
|
| 389 |
+
config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
|
| 390 |
+
)
|
| 391 |
+
self.q_norm = PeAudioEncoderRMSNorm(
|
| 392 |
+
self.head_dim, eps=config.rms_norm_eps
|
| 393 |
+
) # unlike olmo, only on the head dim!
|
| 394 |
+
self.k_norm = PeAudioEncoderRMSNorm(
|
| 395 |
+
self.head_dim, eps=config.rms_norm_eps
|
| 396 |
+
) # thus post q_norm does not need reshape
|
| 397 |
+
|
| 398 |
+
def forward(
|
| 399 |
+
self,
|
| 400 |
+
hidden_states: torch.Tensor,
|
| 401 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 402 |
+
attention_mask: torch.Tensor | None = None,
|
| 403 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 404 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 405 |
+
input_shape = hidden_states.shape[:-1]
|
| 406 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 407 |
+
|
| 408 |
+
query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
|
| 409 |
+
key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
|
| 410 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 411 |
+
|
| 412 |
+
cos, sin = position_embeddings
|
| 413 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 414 |
+
|
| 415 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 416 |
+
self.config._attn_implementation, eager_attention_forward
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
attn_output, attn_weights = attention_interface(
|
| 420 |
+
self,
|
| 421 |
+
query_states,
|
| 422 |
+
key_states,
|
| 423 |
+
value_states,
|
| 424 |
+
attention_mask,
|
| 425 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 426 |
+
scaling=self.scaling,
|
| 427 |
+
**kwargs,
|
| 428 |
+
)
|
| 429 |
+
|
| 430 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 431 |
+
attn_output = self.o_proj(attn_output)
|
| 432 |
+
return attn_output, attn_weights
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
class PeAudioEncoderMLP(nn.Module):
|
| 436 |
+
def __init__(self, config):
|
| 437 |
+
super().__init__()
|
| 438 |
+
self.config = config
|
| 439 |
+
self.hidden_size = config.hidden_size
|
| 440 |
+
self.intermediate_size = config.intermediate_size
|
| 441 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 442 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 443 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
| 444 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 445 |
+
|
| 446 |
+
def forward(self, x):
|
| 447 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 448 |
+
return down_proj
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
class PeAudioEncoderLayer(GradientCheckpointingLayer):
|
| 452 |
+
def __init__(self, config, layer_idx):
|
| 453 |
+
super().__init__()
|
| 454 |
+
self.hidden_size = config.hidden_size
|
| 455 |
+
|
| 456 |
+
self.self_attn = PeAudioEncoderAttention(config=config, layer_idx=layer_idx)
|
| 457 |
+
|
| 458 |
+
self.mlp = PeAudioEncoderMLP(config)
|
| 459 |
+
self.input_layernorm = PeAudioEncoderRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 460 |
+
self.post_attention_layernorm = PeAudioEncoderRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 461 |
+
|
| 462 |
+
def forward(
|
| 463 |
+
self,
|
| 464 |
+
hidden_states: torch.Tensor,
|
| 465 |
+
attention_mask: torch.Tensor | None = None,
|
| 466 |
+
position_ids: torch.LongTensor | None = None,
|
| 467 |
+
past_key_values: Cache | None = None,
|
| 468 |
+
use_cache: bool | None = False,
|
| 469 |
+
cache_position: torch.LongTensor | None = None,
|
| 470 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 471 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 472 |
+
) -> torch.Tensor:
|
| 473 |
+
residual = hidden_states
|
| 474 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 475 |
+
# Self Attention
|
| 476 |
+
hidden_states, _ = self.self_attn(
|
| 477 |
+
hidden_states=hidden_states,
|
| 478 |
+
attention_mask=attention_mask,
|
| 479 |
+
position_ids=position_ids,
|
| 480 |
+
past_key_values=past_key_values,
|
| 481 |
+
use_cache=use_cache,
|
| 482 |
+
cache_position=cache_position,
|
| 483 |
+
position_embeddings=position_embeddings,
|
| 484 |
+
**kwargs,
|
| 485 |
+
)
|
| 486 |
+
hidden_states = residual + hidden_states
|
| 487 |
+
|
| 488 |
+
# Fully Connected
|
| 489 |
+
residual = hidden_states
|
| 490 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 491 |
+
hidden_states = self.mlp(hidden_states)
|
| 492 |
+
hidden_states = residual + hidden_states
|
| 493 |
+
return hidden_states
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
@auto_docstring
|
| 497 |
+
class PeAudioPreTrainedModel(PreTrainedModel):
|
| 498 |
+
config: PeAudioConfig
|
| 499 |
+
base_model_prefix = "audio_model"
|
| 500 |
+
supports_gradient_checkpointing = True
|
| 501 |
+
_no_split_modules = ["PeAudioEncoderLayer"]
|
| 502 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 503 |
+
_supports_flash_attn = True
|
| 504 |
+
_supports_sdpa = True
|
| 505 |
+
_supports_flex_attn = True
|
| 506 |
+
|
| 507 |
+
_can_compile_fullgraph = True
|
| 508 |
+
_supports_attention_backend = True
|
| 509 |
+
_can_record_outputs = {
|
| 510 |
+
"hidden_states": PeAudioEncoderLayer,
|
| 511 |
+
"attentions": PeAudioEncoderAttention,
|
| 512 |
+
}
|
| 513 |
+
|
| 514 |
+
@torch.no_grad()
|
| 515 |
+
def _init_weights(self, module):
|
| 516 |
+
super()._init_weights(module)
|
| 517 |
+
|
| 518 |
+
if hasattr(self.config, "initializer_range"):
|
| 519 |
+
std = self.config.initializer_range
|
| 520 |
+
else:
|
| 521 |
+
# 0.02 is the standard default value across the library
|
| 522 |
+
std = getattr(self.config.get_text_config(), "initializer_range", 0.02)
|
| 523 |
+
|
| 524 |
+
if isinstance(module, PeAudioEncoderPatchEmbedder):
|
| 525 |
+
embed_dim = module.class_embedding.shape[-1]
|
| 526 |
+
init.normal_(module.class_embedding, mean=0.0, std=embed_dim**-0.5 * std)
|
| 527 |
+
if isinstance(module, nn.Conv1d):
|
| 528 |
+
init.trunc_normal_(module.weight, std=0.02)
|
| 529 |
+
init.constant_(module.bias, 0)
|
| 530 |
+
elif isinstance(module, Snake1d):
|
| 531 |
+
init.ones_(module.alpha)
|
| 532 |
+
elif isinstance(module, nn.ConvTranspose1d):
|
| 533 |
+
module.reset_parameters()
|
| 534 |
+
elif isinstance(module, nn.Embedding):
|
| 535 |
+
init.normal_(module.weight, mean=0.0, std=0.02)
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
@dataclass
|
| 539 |
+
@auto_docstring(
|
| 540 |
+
custom_intro="""
|
| 541 |
+
Class for outputs of [`PeAudioEncoder`].
|
| 542 |
+
"""
|
| 543 |
+
)
|
| 544 |
+
class PeAudioEncoderOutput(BaseModelOutputWithPooling):
|
| 545 |
+
codec_features: torch.FloatTensor | None = None
|
| 546 |
+
output_mask: tuple[torch.FloatTensor] | None = None
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
class PeAudioEncoderRotaryEmbedding(nn.Module):
|
| 550 |
+
inv_freq: torch.Tensor # fix linting for `register_buffer`
|
| 551 |
+
|
| 552 |
+
def __init__(self, config: PeAudioEncoderConfig, device=None):
|
| 553 |
+
super().__init__()
|
| 554 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 555 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 556 |
+
|
| 557 |
+
self.config = config
|
| 558 |
+
|
| 559 |
+
self.rope_type = self.config.rope_parameters["rope_type"]
|
| 560 |
+
rope_init_fn: Callable = self.compute_default_rope_parameters
|
| 561 |
+
if self.rope_type != "default":
|
| 562 |
+
rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 563 |
+
inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
|
| 564 |
+
|
| 565 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 566 |
+
self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
|
| 567 |
+
|
| 568 |
+
@staticmethod
|
| 569 |
+
def compute_default_rope_parameters(
|
| 570 |
+
config: PeAudioEncoderConfig | None = None,
|
| 571 |
+
device: Optional["torch.device"] = None,
|
| 572 |
+
seq_len: int | None = None,
|
| 573 |
+
) -> tuple["torch.Tensor", float]:
|
| 574 |
+
"""
|
| 575 |
+
Computes the inverse frequencies according to the original RoPE implementation
|
| 576 |
+
Args:
|
| 577 |
+
config ([`~transformers.PreTrainedConfig`]):
|
| 578 |
+
The model configuration.
|
| 579 |
+
device (`torch.device`):
|
| 580 |
+
The device to use for initialization of the inverse frequencies.
|
| 581 |
+
seq_len (`int`, *optional*):
|
| 582 |
+
The current sequence length. Unused for this type of RoPE.
|
| 583 |
+
Returns:
|
| 584 |
+
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
|
| 585 |
+
post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
|
| 586 |
+
"""
|
| 587 |
+
base = config.rope_parameters["rope_theta"]
|
| 588 |
+
dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
|
| 589 |
+
|
| 590 |
+
attention_factor = 1.0 # Unused in this type of RoPE
|
| 591 |
+
|
| 592 |
+
# Compute the inverse frequencies
|
| 593 |
+
inv_freq = 1.0 / (
|
| 594 |
+
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
|
| 595 |
+
)
|
| 596 |
+
return inv_freq, attention_factor
|
| 597 |
+
|
| 598 |
+
@torch.no_grad()
|
| 599 |
+
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
|
| 600 |
+
def forward(self, x, position_ids):
|
| 601 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
|
| 602 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 603 |
+
|
| 604 |
+
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
| 605 |
+
with maybe_autocast(device_type=device_type, enabled=False): # Force float32
|
| 606 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 607 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 608 |
+
cos = emb.cos() * self.attention_scaling
|
| 609 |
+
sin = emb.sin() * self.attention_scaling
|
| 610 |
+
|
| 611 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 612 |
+
|
| 613 |
+
|
| 614 |
+
@auto_docstring(
|
| 615 |
+
custom_intro="""
|
| 616 |
+
The PeAudio Encoder model.
|
| 617 |
+
"""
|
| 618 |
+
)
|
| 619 |
+
class PeAudioEncoder(PeAudioPreTrainedModel):
|
| 620 |
+
config: PeAudioEncoderConfig
|
| 621 |
+
main_input_name = "input_values"
|
| 622 |
+
base_model_prefix = "audio_model.audio_encoder"
|
| 623 |
+
|
| 624 |
+
def __init__(self, config: PeAudioEncoderConfig):
|
| 625 |
+
super().__init__(config)
|
| 626 |
+
self.embedder = PeAudioEncoderEmbedder(config)
|
| 627 |
+
self.patch_embedder = PeAudioEncoderPatchEmbedder(config)
|
| 628 |
+
self.layers = nn.ModuleList(
|
| 629 |
+
[PeAudioEncoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 630 |
+
)
|
| 631 |
+
self.norm = PeAudioEncoderRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 632 |
+
self.rotary_emb = PeAudioEncoderRotaryEmbedding(config=config)
|
| 633 |
+
self.output = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
|
| 634 |
+
self.gradient_checkpointing = False
|
| 635 |
+
|
| 636 |
+
self.post_init()
|
| 637 |
+
|
| 638 |
+
@can_return_tuple
|
| 639 |
+
@merge_with_config_defaults
|
| 640 |
+
@capture_outputs
|
| 641 |
+
def forward(
|
| 642 |
+
self,
|
| 643 |
+
input_values: torch.Tensor,
|
| 644 |
+
padding_mask: torch.Tensor | None = None,
|
| 645 |
+
**kwargs,
|
| 646 |
+
) -> tuple | BaseModelOutputWithPooling:
|
| 647 |
+
inputs_embeds, padding_mask = self.embedder(input_values, padding_mask=padding_mask)
|
| 648 |
+
inputs_embeds, attention_mask = self.patch_embedder(inputs_embeds, padding_mask=padding_mask)
|
| 649 |
+
|
| 650 |
+
if attention_mask is not None:
|
| 651 |
+
attention_mask = create_bidirectional_mask(
|
| 652 |
+
config=self.config,
|
| 653 |
+
inputs_embeds=inputs_embeds,
|
| 654 |
+
attention_mask=attention_mask,
|
| 655 |
+
)
|
| 656 |
+
|
| 657 |
+
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
| 658 |
+
position_embeddings = self.rotary_emb(inputs_embeds, position_ids)
|
| 659 |
+
|
| 660 |
+
hidden_states = inputs_embeds
|
| 661 |
+
for encoder_layer in self.layers[: self.config.num_hidden_layers]:
|
| 662 |
+
hidden_states = encoder_layer(
|
| 663 |
+
hidden_states,
|
| 664 |
+
attention_mask=attention_mask,
|
| 665 |
+
position_embeddings=position_embeddings,
|
| 666 |
+
**kwargs,
|
| 667 |
+
)
|
| 668 |
+
|
| 669 |
+
hidden_states = self.norm(hidden_states)
|
| 670 |
+
hidden_states = self.output(hidden_states)
|
| 671 |
+
|
| 672 |
+
return PeAudioEncoderOutput(
|
| 673 |
+
last_hidden_state=hidden_states[:, 1:],
|
| 674 |
+
pooler_output=hidden_states[:, 0],
|
| 675 |
+
output_mask=padding_mask,
|
| 676 |
+
)
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
# TODO: not sure about the typing for text_model_output
|
| 680 |
+
@dataclass
|
| 681 |
+
# @auto_docstring
|
| 682 |
+
class PeAudioOutput(ModelOutput):
|
| 683 |
+
loss: torch.FloatTensor | None = None
|
| 684 |
+
logits_audio_text: torch.FloatTensor | None = None
|
| 685 |
+
text_audio_embeds: torch.FloatTensor | None = None
|
| 686 |
+
audio_embeds: torch.FloatTensor | None = None
|
| 687 |
+
text_outputs: BaseModelOutputWithPooling = None
|
| 688 |
+
audio_outputs: BaseModelOutputWithPooling = None
|
| 689 |
+
|
| 690 |
+
def to_tuple(self) -> tuple[Any]:
|
| 691 |
+
return tuple(
|
| 692 |
+
self[k] if k not in ["text_outputs", "audio_outputs"] else getattr(self, k).to_tuple() for k in self.keys()
|
| 693 |
+
)
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
class PeAudioModel(PeAudioPreTrainedModel):
|
| 697 |
+
def __init__(self, config: PeAudioConfig):
|
| 698 |
+
super().__init__(config)
|
| 699 |
+
self.text_model = AutoModel.from_config(config.text_config)
|
| 700 |
+
self.audio_encoder = PeAudioEncoder(config.audio_config)
|
| 701 |
+
|
| 702 |
+
self.text_audio_head = PeAudioContrastiveHead(config.text_config.hidden_size, config.text_config.hidden_size)
|
| 703 |
+
self.audio_head = PeAudioContrastiveHead(config.audio_config.hidden_size, config.text_config.hidden_size)
|
| 704 |
+
|
| 705 |
+
self.text_audio_logit_scale = nn.Parameter(torch.zeros(1))
|
| 706 |
+
self.text_audio_logit_bias = nn.Parameter(torch.zeros(1))
|
| 707 |
+
|
| 708 |
+
self.post_init()
|
| 709 |
+
|
| 710 |
+
def get_text_audio_embeds(self, input_ids, attention_mask=None):
|
| 711 |
+
# TODO: naming can be improved here...
|
| 712 |
+
text_outputs: MaskedLMOutput = self.text_model(
|
| 713 |
+
input_ids=input_ids,
|
| 714 |
+
attention_mask=attention_mask,
|
| 715 |
+
return_dict=True,
|
| 716 |
+
)
|
| 717 |
+
text_audio_embeds = text_outputs.hidden_states[-1][:, 0]
|
| 718 |
+
return self.text_audio_head(text_audio_embeds)
|
| 719 |
+
|
| 720 |
+
def get_audio_embeds(self, input_values, padding_mask=None):
|
| 721 |
+
audio_outputs: BaseModelOutputWithPooling = self.audio_encoder(
|
| 722 |
+
input_values=input_values,
|
| 723 |
+
padding_mask=padding_mask,
|
| 724 |
+
return_dict=True,
|
| 725 |
+
)
|
| 726 |
+
audio_embeds = audio_outputs.pooler_output
|
| 727 |
+
return self.audio_head(audio_embeds)
|
| 728 |
+
|
| 729 |
+
@can_return_tuple
|
| 730 |
+
def forward(
|
| 731 |
+
self,
|
| 732 |
+
input_ids: torch.Tensor,
|
| 733 |
+
input_values: torch.Tensor,
|
| 734 |
+
attention_mask: torch.Tensor | None = None,
|
| 735 |
+
padding_mask: torch.Tensor | None = None,
|
| 736 |
+
return_loss: bool | None = None,
|
| 737 |
+
**kwargs,
|
| 738 |
+
) -> PeAudioOutput:
|
| 739 |
+
audio_outputs: BaseModelOutputWithPooling = self.audio_encoder(
|
| 740 |
+
input_values=input_values, padding_mask=padding_mask, **kwargs
|
| 741 |
+
)
|
| 742 |
+
|
| 743 |
+
kwargs["output_hidden_states"] = True
|
| 744 |
+
text_outputs: MaskedLMOutput = self.text_model(input_ids=input_ids, attention_mask=attention_mask, **kwargs)
|
| 745 |
+
|
| 746 |
+
audio_embeds = audio_outputs.pooler_output
|
| 747 |
+
audio_embeds = self.audio_head(audio_embeds)
|
| 748 |
+
|
| 749 |
+
text_audio_embeds = text_outputs.hidden_states[-1][:, 0]
|
| 750 |
+
text_audio_embeds = self.text_audio_head(text_audio_embeds)
|
| 751 |
+
|
| 752 |
+
logits_audio_text = audio_embeds @ text_audio_embeds.T
|
| 753 |
+
logits_audio_text = logits_audio_text * self.text_audio_logit_scale.to(
|
| 754 |
+
logits_audio_text.device
|
| 755 |
+
) + self.text_audio_logit_bias.to(logits_audio_text.device)
|
| 756 |
+
|
| 757 |
+
loss = None
|
| 758 |
+
if return_loss:
|
| 759 |
+
labels = torch.eye(logits_audio_text.shape[0], device=logits_audio_text.device)
|
| 760 |
+
loss = -F.logsigmoid(labels * logits_audio_text).sum() / logits_audio_text.shape[0]
|
| 761 |
+
|
| 762 |
+
return PeAudioOutput(
|
| 763 |
+
logits_audio_text=logits_audio_text,
|
| 764 |
+
text_audio_embeds=text_audio_embeds,
|
| 765 |
+
audio_embeds=audio_embeds,
|
| 766 |
+
text_outputs=text_outputs,
|
| 767 |
+
audio_outputs=audio_outputs,
|
| 768 |
+
loss=loss,
|
| 769 |
+
)
|
| 770 |
+
|
| 771 |
+
|
| 772 |
+
# TODO: underline in documentation that logits output shape is
|
| 773 |
+
# 1. Model: (n_audio, n_text)
|
| 774 |
+
# 2. Frame-level: (n_audio, n_text, n_frames)
|
| 775 |
+
class PeAudioFrameLevelModel(PeAudioModel):
|
| 776 |
+
def get_audio_embeds(self, input_values, padding_mask=None):
|
| 777 |
+
audio_outputs: BaseModelOutputWithPooling = self.audio_encoder(
|
| 778 |
+
input_values=input_values,
|
| 779 |
+
padding_mask=padding_mask,
|
| 780 |
+
return_dict=True,
|
| 781 |
+
)
|
| 782 |
+
audio_embeds = audio_outputs.last_hidden_state
|
| 783 |
+
audio_embeds = self.audio_head(audio_embeds)
|
| 784 |
+
return audio_embeds
|
| 785 |
+
|
| 786 |
+
@can_return_tuple
|
| 787 |
+
def forward(
|
| 788 |
+
self,
|
| 789 |
+
input_ids: torch.Tensor,
|
| 790 |
+
input_values: torch.Tensor,
|
| 791 |
+
attention_mask: torch.Tensor | None = None,
|
| 792 |
+
padding_mask: torch.Tensor | None = None,
|
| 793 |
+
return_loss: bool | None = None,
|
| 794 |
+
**kwargs,
|
| 795 |
+
) -> PeAudioOutput:
|
| 796 |
+
audio_outputs: BaseModelOutputWithPooling = self.audio_encoder(
|
| 797 |
+
input_values=input_values, padding_mask=padding_mask, **kwargs
|
| 798 |
+
)
|
| 799 |
+
kwargs["output_hidden_states"] = True
|
| 800 |
+
text_outputs: MaskedLMOutput = self.text_model(input_ids=input_ids, attention_mask=attention_mask, **kwargs)
|
| 801 |
+
|
| 802 |
+
audio_embeds = audio_outputs.last_hidden_state
|
| 803 |
+
audio_embeds = self.audio_head(audio_embeds)
|
| 804 |
+
|
| 805 |
+
text_audio_embeds = text_outputs.hidden_states[-1][:, 0]
|
| 806 |
+
text_audio_embeds = self.text_audio_head(text_audio_embeds)
|
| 807 |
+
|
| 808 |
+
logits_audio_text = (audio_embeds @ text_audio_embeds.T).transpose(1, 2)
|
| 809 |
+
logits_audio_text = logits_audio_text * self.text_audio_logit_scale + self.text_audio_logit_bias
|
| 810 |
+
|
| 811 |
+
loss = None
|
| 812 |
+
if return_loss:
|
| 813 |
+
labels = torch.eye(logits_audio_text.shape[0], device=logits_audio_text.device)
|
| 814 |
+
loss = -F.logsigmoid(labels * logits_audio_text).sum() / logits_audio_text.shape[0]
|
| 815 |
+
|
| 816 |
+
return PeAudioOutput(
|
| 817 |
+
logits_audio_text=logits_audio_text,
|
| 818 |
+
text_audio_embeds=text_audio_embeds,
|
| 819 |
+
audio_embeds=audio_embeds,
|
| 820 |
+
text_outputs=text_outputs,
|
| 821 |
+
audio_outputs=audio_outputs,
|
| 822 |
+
loss=loss,
|
| 823 |
+
)
|
| 824 |
+
|
| 825 |
+
|
| 826 |
+
__all__ = ["PeAudioFrameLevelModel", "PeAudioModel", "PeAudioEncoder"]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_audio/modular_pe_audio.py
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 the HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from dataclasses import dataclass
|
| 15 |
+
from typing import Any
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
import torch.nn as nn
|
| 19 |
+
import torch.nn.functional as F
|
| 20 |
+
|
| 21 |
+
from ... import initialization as init
|
| 22 |
+
from ...configuration_utils import PreTrainedConfig
|
| 23 |
+
from ...masking_utils import create_bidirectional_mask
|
| 24 |
+
from ...modeling_outputs import BaseModelOutputWithPooling, MaskedLMOutput
|
| 25 |
+
from ...utils import ModelOutput, auto_docstring, can_return_tuple
|
| 26 |
+
from ...utils.generic import merge_with_config_defaults
|
| 27 |
+
from ...utils.output_capturing import capture_outputs
|
| 28 |
+
from ..auto import AutoModel
|
| 29 |
+
from ..dac.modeling_dac import DacEncoder, DacEncoderBlock, Snake1d
|
| 30 |
+
from ..pe_audio_video.modeling_pe_audio_video import (
|
| 31 |
+
PeAudioVideoContrastiveHead,
|
| 32 |
+
PeAudioVideoEncoder,
|
| 33 |
+
PeAudioVideoPreTrainedModel,
|
| 34 |
+
)
|
| 35 |
+
from .configuration_pe_audio import PeAudioConfig, PeAudioEncoderConfig
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class PeAudioDacEncoderBlock(DacEncoderBlock):
|
| 39 |
+
def __init__(self, config: PreTrainedConfig, stride: int = 1, stride_index: int = 1):
|
| 40 |
+
super().__init__(config, stride=stride, stride_index=stride_index)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class PeAudioDacEncoder(DacEncoder):
|
| 44 |
+
def __init__(self, config: PreTrainedConfig):
|
| 45 |
+
super().__init__(config)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class PeAudioEncoderEmbedder(nn.Module):
|
| 49 |
+
def __init__(self, config: PeAudioEncoderConfig):
|
| 50 |
+
super().__init__()
|
| 51 |
+
self.dac_encoder = PeAudioDacEncoder(config.dac_config)
|
| 52 |
+
self.bottleneck = nn.Conv1d(config.dac_config.hidden_size, config.dac_config.codebook_dim, 1)
|
| 53 |
+
self.data_proj = nn.Linear(config.dac_config.codebook_dim, config.hidden_size)
|
| 54 |
+
self.config = config
|
| 55 |
+
|
| 56 |
+
def forward(
|
| 57 |
+
self,
|
| 58 |
+
input_values: torch.Tensor,
|
| 59 |
+
padding_mask: torch.Tensor | None = None,
|
| 60 |
+
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
| 61 |
+
with torch.no_grad(), torch.backends.cudnn.flags(enabled=False):
|
| 62 |
+
hidden_states = self.dac_encoder(input_values)
|
| 63 |
+
hidden_states = self.bottleneck(hidden_states)
|
| 64 |
+
|
| 65 |
+
codec_features = hidden_states.transpose(1, 2)
|
| 66 |
+
inputs_embeds = self.data_proj(codec_features)
|
| 67 |
+
|
| 68 |
+
if padding_mask is not None:
|
| 69 |
+
padding_mask = padding_mask[:, :: self.config.dac_config.hop_length]
|
| 70 |
+
|
| 71 |
+
return inputs_embeds, padding_mask
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class PeAudioContrastiveHead(PeAudioVideoContrastiveHead): ...
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class PeAudioPreTrainedModel(PeAudioVideoPreTrainedModel):
|
| 78 |
+
base_model_prefix = "audio_model"
|
| 79 |
+
|
| 80 |
+
@torch.no_grad()
|
| 81 |
+
def _init_weights(self, module):
|
| 82 |
+
super()._init_weights(module)
|
| 83 |
+
if isinstance(module, nn.Conv1d):
|
| 84 |
+
init.trunc_normal_(module.weight, std=0.02)
|
| 85 |
+
init.constant_(module.bias, 0)
|
| 86 |
+
elif isinstance(module, Snake1d):
|
| 87 |
+
init.ones_(module.alpha)
|
| 88 |
+
elif isinstance(module, nn.ConvTranspose1d):
|
| 89 |
+
module.reset_parameters()
|
| 90 |
+
elif isinstance(module, nn.Embedding):
|
| 91 |
+
init.normal_(module.weight, mean=0.0, std=0.02)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
@dataclass
|
| 95 |
+
@auto_docstring(
|
| 96 |
+
custom_intro="""
|
| 97 |
+
Class for outputs of [`PeAudioEncoder`].
|
| 98 |
+
"""
|
| 99 |
+
)
|
| 100 |
+
class PeAudioEncoderOutput(BaseModelOutputWithPooling):
|
| 101 |
+
codec_features: torch.FloatTensor | None = None
|
| 102 |
+
output_mask: tuple[torch.FloatTensor] | None = None
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
# TODO: add the capture of codec features?
|
| 106 |
+
@auto_docstring(
|
| 107 |
+
custom_intro="""
|
| 108 |
+
The PeAudio Encoder model.
|
| 109 |
+
"""
|
| 110 |
+
)
|
| 111 |
+
class PeAudioEncoder(PeAudioVideoEncoder):
|
| 112 |
+
base_model_prefix = "audio_model.audio_encoder"
|
| 113 |
+
|
| 114 |
+
@can_return_tuple
|
| 115 |
+
@merge_with_config_defaults
|
| 116 |
+
@capture_outputs
|
| 117 |
+
def forward(
|
| 118 |
+
self,
|
| 119 |
+
input_values: torch.Tensor,
|
| 120 |
+
padding_mask: torch.Tensor | None = None,
|
| 121 |
+
**kwargs,
|
| 122 |
+
) -> tuple | BaseModelOutputWithPooling:
|
| 123 |
+
inputs_embeds, padding_mask = self.embedder(input_values, padding_mask=padding_mask)
|
| 124 |
+
inputs_embeds, attention_mask = self.patch_embedder(inputs_embeds, padding_mask=padding_mask)
|
| 125 |
+
|
| 126 |
+
if attention_mask is not None:
|
| 127 |
+
attention_mask = create_bidirectional_mask(
|
| 128 |
+
config=self.config,
|
| 129 |
+
inputs_embeds=inputs_embeds,
|
| 130 |
+
attention_mask=attention_mask,
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
| 134 |
+
position_embeddings = self.rotary_emb(inputs_embeds, position_ids)
|
| 135 |
+
|
| 136 |
+
hidden_states = inputs_embeds
|
| 137 |
+
for encoder_layer in self.layers[: self.config.num_hidden_layers]:
|
| 138 |
+
hidden_states = encoder_layer(
|
| 139 |
+
hidden_states,
|
| 140 |
+
attention_mask=attention_mask,
|
| 141 |
+
position_embeddings=position_embeddings,
|
| 142 |
+
**kwargs,
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
hidden_states = self.norm(hidden_states)
|
| 146 |
+
hidden_states = self.output(hidden_states)
|
| 147 |
+
|
| 148 |
+
return PeAudioEncoderOutput(
|
| 149 |
+
last_hidden_state=hidden_states[:, 1:],
|
| 150 |
+
pooler_output=hidden_states[:, 0],
|
| 151 |
+
output_mask=padding_mask,
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
# TODO: not sure about the typing for text_model_output
|
| 156 |
+
@dataclass
|
| 157 |
+
# @auto_docstring
|
| 158 |
+
class PeAudioOutput(ModelOutput):
|
| 159 |
+
loss: torch.FloatTensor | None = None
|
| 160 |
+
logits_audio_text: torch.FloatTensor | None = None
|
| 161 |
+
text_audio_embeds: torch.FloatTensor | None = None
|
| 162 |
+
audio_embeds: torch.FloatTensor | None = None
|
| 163 |
+
text_outputs: BaseModelOutputWithPooling = None
|
| 164 |
+
audio_outputs: BaseModelOutputWithPooling = None
|
| 165 |
+
|
| 166 |
+
def to_tuple(self) -> tuple[Any]:
|
| 167 |
+
return tuple(
|
| 168 |
+
self[k] if k not in ["text_outputs", "audio_outputs"] else getattr(self, k).to_tuple() for k in self.keys()
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
class PeAudioModel(PeAudioPreTrainedModel):
|
| 173 |
+
def __init__(self, config: PeAudioConfig):
|
| 174 |
+
super().__init__(config)
|
| 175 |
+
self.text_model = AutoModel.from_config(config.text_config)
|
| 176 |
+
self.audio_encoder = PeAudioEncoder(config.audio_config)
|
| 177 |
+
|
| 178 |
+
self.text_audio_head = PeAudioContrastiveHead(config.text_config.hidden_size, config.text_config.hidden_size)
|
| 179 |
+
self.audio_head = PeAudioContrastiveHead(config.audio_config.hidden_size, config.text_config.hidden_size)
|
| 180 |
+
|
| 181 |
+
self.text_audio_logit_scale = nn.Parameter(torch.zeros(1))
|
| 182 |
+
self.text_audio_logit_bias = nn.Parameter(torch.zeros(1))
|
| 183 |
+
|
| 184 |
+
self.post_init()
|
| 185 |
+
|
| 186 |
+
def get_text_audio_embeds(self, input_ids, attention_mask=None):
|
| 187 |
+
# TODO: naming can be improved here...
|
| 188 |
+
text_outputs: MaskedLMOutput = self.text_model(
|
| 189 |
+
input_ids=input_ids,
|
| 190 |
+
attention_mask=attention_mask,
|
| 191 |
+
return_dict=True,
|
| 192 |
+
)
|
| 193 |
+
text_audio_embeds = text_outputs.hidden_states[-1][:, 0]
|
| 194 |
+
return self.text_audio_head(text_audio_embeds)
|
| 195 |
+
|
| 196 |
+
def get_audio_embeds(self, input_values, padding_mask=None):
|
| 197 |
+
audio_outputs: BaseModelOutputWithPooling = self.audio_encoder(
|
| 198 |
+
input_values=input_values,
|
| 199 |
+
padding_mask=padding_mask,
|
| 200 |
+
return_dict=True,
|
| 201 |
+
)
|
| 202 |
+
audio_embeds = audio_outputs.pooler_output
|
| 203 |
+
return self.audio_head(audio_embeds)
|
| 204 |
+
|
| 205 |
+
@can_return_tuple
|
| 206 |
+
def forward(
|
| 207 |
+
self,
|
| 208 |
+
input_ids: torch.Tensor,
|
| 209 |
+
input_values: torch.Tensor,
|
| 210 |
+
attention_mask: torch.Tensor | None = None,
|
| 211 |
+
padding_mask: torch.Tensor | None = None,
|
| 212 |
+
return_loss: bool | None = None,
|
| 213 |
+
**kwargs,
|
| 214 |
+
) -> PeAudioOutput:
|
| 215 |
+
audio_outputs: BaseModelOutputWithPooling = self.audio_encoder(
|
| 216 |
+
input_values=input_values, padding_mask=padding_mask, **kwargs
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
kwargs["output_hidden_states"] = True
|
| 220 |
+
text_outputs: MaskedLMOutput = self.text_model(input_ids=input_ids, attention_mask=attention_mask, **kwargs)
|
| 221 |
+
|
| 222 |
+
audio_embeds = audio_outputs.pooler_output
|
| 223 |
+
audio_embeds = self.audio_head(audio_embeds)
|
| 224 |
+
|
| 225 |
+
text_audio_embeds = text_outputs.hidden_states[-1][:, 0]
|
| 226 |
+
text_audio_embeds = self.text_audio_head(text_audio_embeds)
|
| 227 |
+
|
| 228 |
+
logits_audio_text = audio_embeds @ text_audio_embeds.T
|
| 229 |
+
logits_audio_text = logits_audio_text * self.text_audio_logit_scale.to(
|
| 230 |
+
logits_audio_text.device
|
| 231 |
+
) + self.text_audio_logit_bias.to(logits_audio_text.device)
|
| 232 |
+
|
| 233 |
+
loss = None
|
| 234 |
+
if return_loss:
|
| 235 |
+
labels = torch.eye(logits_audio_text.shape[0], device=logits_audio_text.device)
|
| 236 |
+
loss = -F.logsigmoid(labels * logits_audio_text).sum() / logits_audio_text.shape[0]
|
| 237 |
+
|
| 238 |
+
return PeAudioOutput(
|
| 239 |
+
logits_audio_text=logits_audio_text,
|
| 240 |
+
text_audio_embeds=text_audio_embeds,
|
| 241 |
+
audio_embeds=audio_embeds,
|
| 242 |
+
text_outputs=text_outputs,
|
| 243 |
+
audio_outputs=audio_outputs,
|
| 244 |
+
loss=loss,
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
# TODO: underline in documentation that logits output shape is
|
| 249 |
+
# 1. Model: (n_audio, n_text)
|
| 250 |
+
# 2. Frame-level: (n_audio, n_text, n_frames)
|
| 251 |
+
class PeAudioFrameLevelModel(PeAudioModel):
|
| 252 |
+
def get_audio_embeds(self, input_values, padding_mask=None):
|
| 253 |
+
audio_outputs: BaseModelOutputWithPooling = self.audio_encoder(
|
| 254 |
+
input_values=input_values,
|
| 255 |
+
padding_mask=padding_mask,
|
| 256 |
+
return_dict=True,
|
| 257 |
+
)
|
| 258 |
+
audio_embeds = audio_outputs.last_hidden_state
|
| 259 |
+
audio_embeds = self.audio_head(audio_embeds)
|
| 260 |
+
return audio_embeds
|
| 261 |
+
|
| 262 |
+
@can_return_tuple
|
| 263 |
+
def forward(
|
| 264 |
+
self,
|
| 265 |
+
input_ids: torch.Tensor,
|
| 266 |
+
input_values: torch.Tensor,
|
| 267 |
+
attention_mask: torch.Tensor | None = None,
|
| 268 |
+
padding_mask: torch.Tensor | None = None,
|
| 269 |
+
return_loss: bool | None = None,
|
| 270 |
+
**kwargs,
|
| 271 |
+
) -> PeAudioOutput:
|
| 272 |
+
audio_outputs: BaseModelOutputWithPooling = self.audio_encoder(
|
| 273 |
+
input_values=input_values, padding_mask=padding_mask, **kwargs
|
| 274 |
+
)
|
| 275 |
+
kwargs["output_hidden_states"] = True
|
| 276 |
+
text_outputs: MaskedLMOutput = self.text_model(input_ids=input_ids, attention_mask=attention_mask, **kwargs)
|
| 277 |
+
|
| 278 |
+
audio_embeds = audio_outputs.last_hidden_state
|
| 279 |
+
audio_embeds = self.audio_head(audio_embeds)
|
| 280 |
+
|
| 281 |
+
text_audio_embeds = text_outputs.hidden_states[-1][:, 0]
|
| 282 |
+
text_audio_embeds = self.text_audio_head(text_audio_embeds)
|
| 283 |
+
|
| 284 |
+
logits_audio_text = (audio_embeds @ text_audio_embeds.T).transpose(1, 2)
|
| 285 |
+
logits_audio_text = logits_audio_text * self.text_audio_logit_scale + self.text_audio_logit_bias
|
| 286 |
+
|
| 287 |
+
loss = None
|
| 288 |
+
if return_loss:
|
| 289 |
+
labels = torch.eye(logits_audio_text.shape[0], device=logits_audio_text.device)
|
| 290 |
+
loss = -F.logsigmoid(labels * logits_audio_text).sum() / logits_audio_text.shape[0]
|
| 291 |
+
|
| 292 |
+
return PeAudioOutput(
|
| 293 |
+
logits_audio_text=logits_audio_text,
|
| 294 |
+
text_audio_embeds=text_audio_embeds,
|
| 295 |
+
audio_embeds=audio_embeds,
|
| 296 |
+
text_outputs=text_outputs,
|
| 297 |
+
audio_outputs=audio_outputs,
|
| 298 |
+
loss=loss,
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
__all__ = [
|
| 303 |
+
"PeAudioFrameLevelModel",
|
| 304 |
+
"PeAudioModel",
|
| 305 |
+
"PeAudioEncoder",
|
| 306 |
+
]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_audio/processing_pe_audio.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 the HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from ...processing_utils import ProcessorMixin
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class PeAudioProcessor(ProcessorMixin):
|
| 18 |
+
attributes = ["feature_extractor", "tokenizer"]
|
| 19 |
+
feature_extractor_class = "PeAudioFeatureExtractor"
|
| 20 |
+
tokenizer_class = "AutoTokenizer"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
__all__ = ["PeAudioProcessor"]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_audio_video/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 the HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_pe_audio_video import *
|
| 22 |
+
from .modeling_pe_audio_video import *
|
| 23 |
+
from .processing_pe_audio_video import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_audio_video/configuration_pe_audio_video.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 the HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
from ...configuration_utils import PreTrainedConfig, PretrainedConfig
|
| 17 |
+
from ...modeling_rope_utils import RopeParameters
|
| 18 |
+
from ...utils import logging
|
| 19 |
+
from ..auto import CONFIG_MAPPING, AutoConfig
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
logger = logging.get_logger(__name__)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class PeAudioVideoEncoderConfig(PreTrainedConfig):
|
| 26 |
+
r"""
|
| 27 |
+
This is the configuration class to store the configuration of a [`PeAudioVideoEncoderModel`]. It is used to instantiate a
|
| 28 |
+
PeAudioVideoEncoder model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 29 |
+
with the defaults will yield a similar configuration to that of pe-av-large.
|
| 30 |
+
e.g. [facebook/pe-av-large](https://huggingface.co/facebook/pe-av-large)
|
| 31 |
+
|
| 32 |
+
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
|
| 33 |
+
documentation from [`PreTrainedConfig`] for more information.
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
audio_config (`Union[PreTrainedConfig, dict]`, *optional*):
|
| 38 |
+
Configuration for the audio encoder. If a dictionary is provided, it is used to instantiate
|
| 39 |
+
[`~transformers.PeAudioEncoderConfig`].
|
| 40 |
+
video_config (`Union[PreTrainedConfig, dict]`, *optional*):
|
| 41 |
+
Configuration for the video encoder. If a dictionary is provided, it is used to instantiate
|
| 42 |
+
[`~transformers.PeVideoEncoderConfig`].
|
| 43 |
+
hidden_size (`int`, *optional*, defaults to 1792):
|
| 44 |
+
Dimension of the hidden representations.
|
| 45 |
+
intermediate_size (`int`, *optional*, defaults to 4800):
|
| 46 |
+
Dimension of the feedforward layers in the Transformer blocks.
|
| 47 |
+
num_hidden_layers (`int`, *optional*, defaults to 6):
|
| 48 |
+
Number of Transformer encoder blocks.
|
| 49 |
+
num_attention_heads (`int`, *optional*, defaults to 14):
|
| 50 |
+
Number of attention heads used in each attention layer.
|
| 51 |
+
num_key_value_heads (`int`, *optional*):
|
| 52 |
+
Number of key and value heads for grouped-query attention. If unset, this defaults to `num_attention_heads`.
|
| 53 |
+
head_dim (`int`, *optional*, defaults to 128):
|
| 54 |
+
Dimension of each attention head for query, key, and value projections.
|
| 55 |
+
hidden_act (`str`, *optional*, defaults to `"silu"`):
|
| 56 |
+
The non-linear activation function (function or string) in the Transformer blocks.
|
| 57 |
+
max_position_embeddings (`int`, *optional*, defaults to 10000):
|
| 58 |
+
Maximum sequence length supported by the rotary position embeddings.
|
| 59 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 60 |
+
Standard deviation of the truncated normal initializer for weight matrices.
|
| 61 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-05):
|
| 62 |
+
Epsilon used by the RMS normalization layers.
|
| 63 |
+
rope_parameters (`Union[RopeParameters, dict]`, *optional*, defaults to `{'rope_theta': 20000}`):
|
| 64 |
+
Parameters for the rotary position embeddings, such as the base `rope_theta`.
|
| 65 |
+
attention_bias (`bool`, *optional*, defaults to `False`):
|
| 66 |
+
Whether to use bias terms in the query, key, value, and output projections.
|
| 67 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 68 |
+
Dropout ratio applied to attention probabilities.
|
| 69 |
+
|
| 70 |
+
```python
|
| 71 |
+
>>> from transformers import PeAudioVideoEncoder, PeAudioVideoEncoderConfig
|
| 72 |
+
|
| 73 |
+
>>> # Initializing a PeAudioVideoEncoder style configuration
|
| 74 |
+
>>> configuration = PeAudioVideoEncoderConfig()
|
| 75 |
+
|
| 76 |
+
>>> # Initializing a model from the pe-av-large style configuration
|
| 77 |
+
>>> model = PeAudioVideoEncoder(configuration)
|
| 78 |
+
|
| 79 |
+
>>> # Accessing the model configuration
|
| 80 |
+
>>> configuration = model.config
|
| 81 |
+
```"""
|
| 82 |
+
|
| 83 |
+
model_type = "pe_audio_video_encoder"
|
| 84 |
+
base_config_key = "audio_video_config"
|
| 85 |
+
sub_configs = {"audio_config": AutoConfig, "video_config": AutoConfig}
|
| 86 |
+
|
| 87 |
+
def __init__(
|
| 88 |
+
self,
|
| 89 |
+
audio_config: dict | PreTrainedConfig | None = None,
|
| 90 |
+
video_config: dict | PreTrainedConfig | None = None,
|
| 91 |
+
hidden_size: int | None = 1792,
|
| 92 |
+
intermediate_size: int | None = 4800,
|
| 93 |
+
num_hidden_layers: int | None = 6,
|
| 94 |
+
num_attention_heads: int | None = 14,
|
| 95 |
+
num_key_value_heads: int | None = None,
|
| 96 |
+
head_dim: int | None = 128,
|
| 97 |
+
hidden_act: str | None = "silu",
|
| 98 |
+
max_position_embeddings: int | None = 10000,
|
| 99 |
+
initializer_range: float | None = 0.02,
|
| 100 |
+
rms_norm_eps: float | None = 1e-5,
|
| 101 |
+
rope_parameters: RopeParameters | dict | None = {"rope_theta": 20000},
|
| 102 |
+
attention_bias: bool | None = False,
|
| 103 |
+
attention_dropout: float | None = 0.0,
|
| 104 |
+
**kwargs,
|
| 105 |
+
):
|
| 106 |
+
self.hidden_size = hidden_size
|
| 107 |
+
self.intermediate_size = intermediate_size
|
| 108 |
+
self.num_hidden_layers = num_hidden_layers
|
| 109 |
+
self.num_attention_heads = num_attention_heads
|
| 110 |
+
|
| 111 |
+
# for backward compatibility
|
| 112 |
+
if num_key_value_heads is None:
|
| 113 |
+
num_key_value_heads = num_attention_heads
|
| 114 |
+
|
| 115 |
+
self.num_key_value_heads = num_key_value_heads
|
| 116 |
+
self.head_dim = head_dim
|
| 117 |
+
self.hidden_act = hidden_act
|
| 118 |
+
self.max_position_embeddings = max_position_embeddings
|
| 119 |
+
self.initializer_range = initializer_range
|
| 120 |
+
self.rms_norm_eps = rms_norm_eps
|
| 121 |
+
self.rope_parameters = rope_parameters
|
| 122 |
+
self.attention_bias = attention_bias
|
| 123 |
+
self.attention_dropout = attention_dropout
|
| 124 |
+
|
| 125 |
+
if isinstance(audio_config, dict):
|
| 126 |
+
audio_config["model_type"] = audio_config.get("model_type", "pe_audio_encoder")
|
| 127 |
+
audio_config = CONFIG_MAPPING[audio_config["model_type"]](**audio_config)
|
| 128 |
+
elif audio_config is None:
|
| 129 |
+
audio_config = CONFIG_MAPPING["pe_audio_encoder"]()
|
| 130 |
+
|
| 131 |
+
if isinstance(video_config, dict):
|
| 132 |
+
video_config["model_type"] = video_config.get("model_type", "pe_video_encoder")
|
| 133 |
+
video_config = CONFIG_MAPPING[video_config["model_type"]](**video_config)
|
| 134 |
+
elif video_config is None:
|
| 135 |
+
video_config = CONFIG_MAPPING["pe_video_encoder"]()
|
| 136 |
+
|
| 137 |
+
self.audio_config = audio_config
|
| 138 |
+
self.video_config = video_config
|
| 139 |
+
|
| 140 |
+
super().__init__(**kwargs)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class PeAudioVideoConfig(PretrainedConfig):
|
| 144 |
+
r"""
|
| 145 |
+
This is the configuration class to store the configuration of a [`PeAudioVideoModel`]. It is used to instantiate a
|
| 146 |
+
PeAudioVideoModel model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 147 |
+
with the defaults will yield a similar configuration to that of pe-av-large.
|
| 148 |
+
e.g. [facebook/pe-av-large](https://huggingface.co/facebook/pe-av-large)
|
| 149 |
+
|
| 150 |
+
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
|
| 151 |
+
documentation from [`PreTrainedConfig`] for more information.
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
Args:
|
| 155 |
+
text_config (`dict` or `PreTrainedConfig`, *optional*):
|
| 156 |
+
Configuration for the text model component.
|
| 157 |
+
audio_video_config (`dict` or `PreTrainedConfig`, *optional*):
|
| 158 |
+
Configuration for the audio-video encoder component.
|
| 159 |
+
|
| 160 |
+
```python
|
| 161 |
+
>>> from transformers import PeAudioVideoModel, PeAudioVideoConfig
|
| 162 |
+
|
| 163 |
+
>>> # Initializing a PeAudioVideoModel style configuration
|
| 164 |
+
>>> configuration = PeAudioVideoConfig()
|
| 165 |
+
|
| 166 |
+
>>> # Initializing a model from the pe-av-large style configuration
|
| 167 |
+
>>> model = PeAudioModel(configuration)
|
| 168 |
+
|
| 169 |
+
>>> # Accessing the model configuration
|
| 170 |
+
>>> configuration = model.config
|
| 171 |
+
```"""
|
| 172 |
+
|
| 173 |
+
model_type = "pe_audio_video"
|
| 174 |
+
sub_configs = {"text_config": AutoConfig, "audio_video_config": PeAudioVideoEncoderConfig}
|
| 175 |
+
|
| 176 |
+
_default_text_config_kwargs = {
|
| 177 |
+
"model_type": "modernbert",
|
| 178 |
+
"hidden_size": 1024,
|
| 179 |
+
"intermediate_size": 2624,
|
| 180 |
+
"num_hidden_layers": 22,
|
| 181 |
+
"num_attention_heads": 16,
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
def __init__(
|
| 185 |
+
self,
|
| 186 |
+
text_config=None,
|
| 187 |
+
audio_video_config=None,
|
| 188 |
+
**kwargs,
|
| 189 |
+
):
|
| 190 |
+
if isinstance(text_config, dict):
|
| 191 |
+
text_config["model_type"] = text_config.get("model_type", "modernbert")
|
| 192 |
+
text_config = CONFIG_MAPPING[text_config["model_type"]](
|
| 193 |
+
**{**self._default_text_config_kwargs, **text_config}
|
| 194 |
+
)
|
| 195 |
+
elif text_config is None:
|
| 196 |
+
text_config = CONFIG_MAPPING["modernbert"](**self._default_text_config_kwargs)
|
| 197 |
+
|
| 198 |
+
if isinstance(audio_video_config, dict):
|
| 199 |
+
audio_video_config = PeAudioVideoEncoderConfig(**audio_video_config)
|
| 200 |
+
elif audio_video_config is None:
|
| 201 |
+
audio_video_config = PeAudioVideoEncoderConfig()
|
| 202 |
+
|
| 203 |
+
self.text_config = text_config
|
| 204 |
+
self.audio_video_config = audio_video_config
|
| 205 |
+
|
| 206 |
+
super().__init__(**kwargs)
|
| 207 |
+
|
| 208 |
+
@property
|
| 209 |
+
def audio_config(self):
|
| 210 |
+
return CONFIG_MAPPING["pe_audio"](
|
| 211 |
+
text_config=self.text_config,
|
| 212 |
+
audio_config=self.audio_video_config.audio_config,
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
@property
|
| 216 |
+
def video_config(self):
|
| 217 |
+
return CONFIG_MAPPING["pe_video"](
|
| 218 |
+
text_config=self.text_config,
|
| 219 |
+
video_config=self.audio_video_config.video_config,
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
__all__ = ["PeAudioVideoEncoderConfig", "PeAudioVideoConfig"]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_audio_video/modeling_pe_audio_video.py
ADDED
|
@@ -0,0 +1,978 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/pe_audio_video/modular_pe_audio_video.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_pe_audio_video.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2025 the HuggingFace Inc. team. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
from collections.abc import Callable
|
| 21 |
+
from dataclasses import dataclass
|
| 22 |
+
from typing import Any, Optional
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
import torch.nn as nn
|
| 26 |
+
|
| 27 |
+
from ... import initialization as init
|
| 28 |
+
from ...activations import ACT2FN
|
| 29 |
+
from ...cache_utils import Cache
|
| 30 |
+
from ...integrations import use_kernel_forward_from_hub, use_kernelized_func
|
| 31 |
+
from ...masking_utils import create_bidirectional_mask
|
| 32 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 33 |
+
from ...modeling_outputs import BaseModelOutputWithPooling, MaskedLMOutput
|
| 34 |
+
from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
| 35 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 36 |
+
from ...processing_utils import Unpack
|
| 37 |
+
from ...utils import ModelOutput, TransformersKwargs, auto_docstring, can_return_tuple
|
| 38 |
+
from ...utils.generic import maybe_autocast, merge_with_config_defaults
|
| 39 |
+
from ...utils.output_capturing import capture_outputs
|
| 40 |
+
from ..auto import AutoModel
|
| 41 |
+
from .configuration_pe_audio_video import PeAudioVideoConfig, PeAudioVideoEncoderConfig
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class PeAudioVideoMaskedGroupNorm(nn.GroupNorm):
|
| 45 |
+
def forward(self, x, padding_mask=None):
|
| 46 |
+
if padding_mask is None:
|
| 47 |
+
return super().forward(x)
|
| 48 |
+
|
| 49 |
+
batch_size, hidden_size, seq_len = x.shape
|
| 50 |
+
group_size = hidden_size // self.num_groups
|
| 51 |
+
grouped_shape = (batch_size, -1, group_size, seq_len)
|
| 52 |
+
|
| 53 |
+
x_grouped = x.view(grouped_shape)
|
| 54 |
+
padding_mask_grouped = padding_mask.reshape(grouped_shape).bool()
|
| 55 |
+
|
| 56 |
+
mean = torch.masked.mean(x_grouped, mask=padding_mask_grouped, dim=(2, 3), keepdim=True)
|
| 57 |
+
var = torch.masked.var(x_grouped, mask=padding_mask_grouped, dim=(2, 3), keepdim=True, unbiased=False)
|
| 58 |
+
|
| 59 |
+
x_norm = (x_grouped - mean) / torch.sqrt(var + self.eps)
|
| 60 |
+
x_norm = x_norm.view(x.shape)
|
| 61 |
+
|
| 62 |
+
if self.affine:
|
| 63 |
+
x_norm = x_norm * self.weight.view(1, -1, 1) + self.bias.view(1, -1, 1)
|
| 64 |
+
|
| 65 |
+
return x_norm * padding_mask
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class PeAudioVideoConvBlock1d(nn.Module):
|
| 69 |
+
def __init__(self, config):
|
| 70 |
+
super().__init__()
|
| 71 |
+
self.groupnorm = PeAudioVideoMaskedGroupNorm(num_groups=1, num_channels=config.hidden_size)
|
| 72 |
+
self.activation = nn.SiLU()
|
| 73 |
+
self.project = nn.Conv1d(
|
| 74 |
+
in_channels=config.hidden_size,
|
| 75 |
+
out_channels=config.hidden_size,
|
| 76 |
+
kernel_size=3,
|
| 77 |
+
padding="same",
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
def forward(self, x, padding_mask=None):
|
| 81 |
+
x = self.groupnorm(x, padding_mask=padding_mask)
|
| 82 |
+
x = self.activation(x)
|
| 83 |
+
return self.project(x)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class PeAudioVideoResnetBlock1d(nn.Module):
|
| 87 |
+
def __init__(self, config):
|
| 88 |
+
super().__init__()
|
| 89 |
+
self.block1 = PeAudioVideoConvBlock1d(config)
|
| 90 |
+
self.block2 = PeAudioVideoConvBlock1d(config)
|
| 91 |
+
|
| 92 |
+
def forward(self, hidden_states, padding_mask=None):
|
| 93 |
+
"""
|
| 94 |
+
Args:
|
| 95 |
+
hidden_states: (batch_size, seq_len, hidden_size)
|
| 96 |
+
padding_mask: (batch_size, seq_len)
|
| 97 |
+
Returns:
|
| 98 |
+
hidden_states: (batch_size, seq_len, hidden_size)
|
| 99 |
+
"""
|
| 100 |
+
# transpose for convolutions
|
| 101 |
+
# (batch_size, seq_len, hidden_size) -> (batch_size, hidden_size, seq_len)
|
| 102 |
+
hidden_states = hidden_states.transpose(1, 2)
|
| 103 |
+
|
| 104 |
+
if padding_mask is not None:
|
| 105 |
+
padding_mask = padding_mask.unsqueeze(1).expand_as(hidden_states)
|
| 106 |
+
|
| 107 |
+
residual = hidden_states
|
| 108 |
+
hidden_states = self.block1(hidden_states, padding_mask=padding_mask)
|
| 109 |
+
hidden_states = self.block2(hidden_states, padding_mask=padding_mask)
|
| 110 |
+
hidden_states = residual + hidden_states
|
| 111 |
+
|
| 112 |
+
return hidden_states.transpose(1, 2)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class PeAudioVideoEncoderPatchEmbedder(nn.Module):
|
| 116 |
+
def __init__(self, config):
|
| 117 |
+
super().__init__()
|
| 118 |
+
self.resnet_block = PeAudioVideoResnetBlock1d(config)
|
| 119 |
+
self.class_embedding = nn.Parameter(torch.randn(1, 1, config.hidden_size))
|
| 120 |
+
|
| 121 |
+
def forward(self, inputs_embeds, padding_mask=None):
|
| 122 |
+
# Embedding step: prepend class token and run the ResNet block.
|
| 123 |
+
hidden_states = torch.cat(
|
| 124 |
+
[self.class_embedding.expand(inputs_embeds.size(0), -1, -1), inputs_embeds],
|
| 125 |
+
dim=1,
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
if padding_mask is not None:
|
| 129 |
+
# TODO: any reason why we take padding_mask[0] and not just 1?
|
| 130 |
+
padding_mask = torch.cat([padding_mask[:, [0]], padding_mask], dim=1)
|
| 131 |
+
|
| 132 |
+
hidden_states = self.resnet_block(hidden_states, padding_mask=padding_mask)
|
| 133 |
+
return hidden_states, padding_mask
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class PeAudioVideoContrastiveHead(nn.Module):
|
| 137 |
+
def __init__(
|
| 138 |
+
self,
|
| 139 |
+
in_dim: int,
|
| 140 |
+
out_dim: int,
|
| 141 |
+
) -> None:
|
| 142 |
+
super().__init__()
|
| 143 |
+
self.layer_norm = nn.LayerNorm(normalized_shape=in_dim, eps=1e-6)
|
| 144 |
+
self.proj = nn.Linear(in_dim, out_dim, bias=False)
|
| 145 |
+
|
| 146 |
+
def forward(self, x: torch.Tensor) -> torch.FloatTensor:
|
| 147 |
+
return self.proj(self.layer_norm(x))
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class PeAudioVideoEncoderEmbedder(nn.Module):
|
| 151 |
+
def __init__(self, config: PeAudioVideoEncoderConfig):
|
| 152 |
+
super().__init__()
|
| 153 |
+
self.audio_encoder = AutoModel.from_config(config.audio_config)
|
| 154 |
+
self.video_encoder = AutoModel.from_config(config.video_config)
|
| 155 |
+
|
| 156 |
+
self.video_proj = nn.Conv1d(config.video_config.hidden_size, config.audio_config.hidden_size, 1)
|
| 157 |
+
self.video_norm = nn.LayerNorm(config.audio_config.hidden_size)
|
| 158 |
+
|
| 159 |
+
self.concat_modality_proj = nn.Linear(
|
| 160 |
+
config.audio_config.hidden_size + config.video_config.hidden_size,
|
| 161 |
+
config.hidden_size,
|
| 162 |
+
)
|
| 163 |
+
self.data_proj = nn.Linear(config.hidden_size, config.hidden_size)
|
| 164 |
+
|
| 165 |
+
def _align_video_hidden_state(
|
| 166 |
+
self,
|
| 167 |
+
video_hidden_state: torch.Tensor,
|
| 168 |
+
audio_hidden_state: torch.Tensor,
|
| 169 |
+
padding_mask_videos: torch.Tensor | None = None,
|
| 170 |
+
padding_mask: torch.Tensor | None = None,
|
| 171 |
+
) -> torch.Tensor:
|
| 172 |
+
"""
|
| 173 |
+
Align video_hidden_state to audio_hidden_state by nearest neighbor interpolation.
|
| 174 |
+
"""
|
| 175 |
+
if video_hidden_state.shape[1] == audio_hidden_state.shape[1]:
|
| 176 |
+
return video_hidden_state
|
| 177 |
+
|
| 178 |
+
if padding_mask_videos is not None:
|
| 179 |
+
video_lengths = padding_mask_videos.sum(dim=-1)
|
| 180 |
+
else:
|
| 181 |
+
video_lengths = video_hidden_state.shape[1] * video_hidden_state.new_ones(
|
| 182 |
+
video_hidden_state.shape[0], dtype=torch.long
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
if padding_mask is not None:
|
| 186 |
+
audio_lengths = padding_mask.sum(dim=-1)
|
| 187 |
+
else:
|
| 188 |
+
audio_lengths = audio_hidden_state.shape[1] * audio_hidden_state.new_ones(
|
| 189 |
+
audio_hidden_state.shape[0], dtype=torch.long
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
if (audio_lengths == video_hidden_state.shape[1]).all() or (
|
| 193 |
+
video_lengths == audio_hidden_state.shape[1]
|
| 194 |
+
).all():
|
| 195 |
+
# no need to align taking into account the padding masks
|
| 196 |
+
# note: when one of the above is true, we can expect the other to be true as there is no reason
|
| 197 |
+
# to have masked audio without masked video and vice versa
|
| 198 |
+
|
| 199 |
+
return nn.functional.interpolate(
|
| 200 |
+
video_hidden_state.transpose(1, 2), size=audio_hidden_state.shape[1], mode="nearest"
|
| 201 |
+
).transpose(1, 2)
|
| 202 |
+
|
| 203 |
+
aligned_shape = (*audio_hidden_state.shape[:2], video_hidden_state.shape[-1])
|
| 204 |
+
aligned_hidden_state = audio_hidden_state.new_zeros(aligned_shape)
|
| 205 |
+
|
| 206 |
+
for i, (hidden_state, video_length, audio_length) in enumerate(
|
| 207 |
+
zip(video_hidden_state, video_lengths, audio_lengths)
|
| 208 |
+
):
|
| 209 |
+
hidden_state = hidden_state[:video_length]
|
| 210 |
+
if hidden_state.numel() > 0 and audio_length > 0:
|
| 211 |
+
interpolated_hidden_state = nn.functional.interpolate(
|
| 212 |
+
hidden_state[None].transpose(1, 2), size=audio_length, mode="nearest"
|
| 213 |
+
).transpose(1, 2)[0]
|
| 214 |
+
aligned_hidden_state[i, :audio_length, :] = interpolated_hidden_state
|
| 215 |
+
|
| 216 |
+
return aligned_hidden_state
|
| 217 |
+
|
| 218 |
+
def forward(
|
| 219 |
+
self,
|
| 220 |
+
input_values: torch.Tensor,
|
| 221 |
+
pixel_values_videos: torch.Tensor,
|
| 222 |
+
padding_mask: torch.Tensor | None = None,
|
| 223 |
+
padding_mask_videos: torch.Tensor | None = None,
|
| 224 |
+
):
|
| 225 |
+
audio_output = self.audio_encoder(input_values, padding_mask=padding_mask)
|
| 226 |
+
video_output = self.video_encoder(pixel_values_videos, padding_mask_videos=padding_mask_videos)
|
| 227 |
+
|
| 228 |
+
audio_hidden_state = audio_output.last_hidden_state
|
| 229 |
+
video_hidden_state = video_output.last_hidden_state
|
| 230 |
+
padding_mask = audio_output.output_mask
|
| 231 |
+
|
| 232 |
+
video_hidden_state = self.video_proj(video_hidden_state.transpose(1, 2)).transpose(1, 2)
|
| 233 |
+
video_hidden_state = self._align_video_hidden_state(
|
| 234 |
+
video_hidden_state=video_hidden_state,
|
| 235 |
+
audio_hidden_state=audio_hidden_state,
|
| 236 |
+
padding_mask_videos=padding_mask_videos,
|
| 237 |
+
padding_mask=padding_mask,
|
| 238 |
+
)
|
| 239 |
+
video_hidden_state = self.video_norm(video_hidden_state)
|
| 240 |
+
inputs_embeds = torch.cat([audio_hidden_state, video_hidden_state], dim=-1)
|
| 241 |
+
inputs_embeds = self.concat_modality_proj(inputs_embeds)
|
| 242 |
+
inputs_embeds = self.data_proj(inputs_embeds)
|
| 243 |
+
|
| 244 |
+
return inputs_embeds, padding_mask, audio_output, video_output
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 248 |
+
"""
|
| 249 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 250 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 251 |
+
"""
|
| 252 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 253 |
+
if n_rep == 1:
|
| 254 |
+
return hidden_states
|
| 255 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 256 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def eager_attention_forward(
|
| 260 |
+
module: nn.Module,
|
| 261 |
+
query: torch.Tensor,
|
| 262 |
+
key: torch.Tensor,
|
| 263 |
+
value: torch.Tensor,
|
| 264 |
+
attention_mask: torch.Tensor | None,
|
| 265 |
+
scaling: float,
|
| 266 |
+
dropout: float = 0.0,
|
| 267 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 268 |
+
):
|
| 269 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 270 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 271 |
+
|
| 272 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 273 |
+
if attention_mask is not None:
|
| 274 |
+
attn_weights = attn_weights + attention_mask
|
| 275 |
+
|
| 276 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 277 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 278 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 279 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 280 |
+
|
| 281 |
+
return attn_output, attn_weights
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def stack_freqs(cos: torch.Tensor, sin: torch.Tensor):
|
| 285 |
+
dim = cos.size(-1)
|
| 286 |
+
cos = cos.narrow(-1, 0, dim // 2)
|
| 287 |
+
sin = sin.narrow(-1, 0, dim // 2)
|
| 288 |
+
freqs_cis = torch.stack((cos, -sin, sin, cos), dim=-1).view(*cos.size(), 2, 2)
|
| 289 |
+
return freqs_cis
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
|
| 293 |
+
freqs_cis = stack_freqs(cos, sin)
|
| 294 |
+
freqs_cis = freqs_cis.unsqueeze(unsqueeze_dim)
|
| 295 |
+
q_ = q.reshape(*q.shape[:-1], -1, 1, 2)
|
| 296 |
+
k_ = k.reshape(*k.shape[:-1], -1, 1, 2)
|
| 297 |
+
return (q_ * freqs_cis).sum(5).flatten(3), (k_ * freqs_cis).sum(5).flatten(3)
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
@use_kernelized_func(apply_rotary_pos_emb)
|
| 301 |
+
class PeAudioVideoEncoderAttention(nn.Module):
|
| 302 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 303 |
+
|
| 304 |
+
def __init__(self, config, layer_idx):
|
| 305 |
+
super().__init__()
|
| 306 |
+
self.layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None
|
| 307 |
+
self.config = config
|
| 308 |
+
self.layer_idx = layer_idx
|
| 309 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 310 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 311 |
+
self.scaling = self.head_dim**-0.5
|
| 312 |
+
self.attention_dropout = config.attention_dropout
|
| 313 |
+
self.is_causal = False
|
| 314 |
+
|
| 315 |
+
self.q_proj = nn.Linear(
|
| 316 |
+
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
| 317 |
+
)
|
| 318 |
+
self.k_proj = nn.Linear(
|
| 319 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 320 |
+
)
|
| 321 |
+
self.v_proj = nn.Linear(
|
| 322 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 323 |
+
)
|
| 324 |
+
self.o_proj = nn.Linear(
|
| 325 |
+
config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
|
| 326 |
+
)
|
| 327 |
+
self.q_norm = PeAudioVideoEncoderRMSNorm(
|
| 328 |
+
self.head_dim, eps=config.rms_norm_eps
|
| 329 |
+
) # unlike olmo, only on the head dim!
|
| 330 |
+
self.k_norm = PeAudioVideoEncoderRMSNorm(
|
| 331 |
+
self.head_dim, eps=config.rms_norm_eps
|
| 332 |
+
) # thus post q_norm does not need reshape
|
| 333 |
+
|
| 334 |
+
def forward(
|
| 335 |
+
self,
|
| 336 |
+
hidden_states: torch.Tensor,
|
| 337 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 338 |
+
attention_mask: torch.Tensor | None = None,
|
| 339 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 340 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 341 |
+
input_shape = hidden_states.shape[:-1]
|
| 342 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 343 |
+
|
| 344 |
+
query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
|
| 345 |
+
key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
|
| 346 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 347 |
+
|
| 348 |
+
cos, sin = position_embeddings
|
| 349 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 350 |
+
|
| 351 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 352 |
+
self.config._attn_implementation, eager_attention_forward
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
attn_output, attn_weights = attention_interface(
|
| 356 |
+
self,
|
| 357 |
+
query_states,
|
| 358 |
+
key_states,
|
| 359 |
+
value_states,
|
| 360 |
+
attention_mask,
|
| 361 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 362 |
+
scaling=self.scaling,
|
| 363 |
+
**kwargs,
|
| 364 |
+
)
|
| 365 |
+
|
| 366 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 367 |
+
attn_output = self.o_proj(attn_output)
|
| 368 |
+
return attn_output, attn_weights
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
class PeAudioVideoEncoderMLP(nn.Module):
|
| 372 |
+
def __init__(self, config):
|
| 373 |
+
super().__init__()
|
| 374 |
+
self.config = config
|
| 375 |
+
self.hidden_size = config.hidden_size
|
| 376 |
+
self.intermediate_size = config.intermediate_size
|
| 377 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 378 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 379 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
| 380 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 381 |
+
|
| 382 |
+
def forward(self, x):
|
| 383 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 384 |
+
return down_proj
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
class PeAudioVideoEncoderLayer(GradientCheckpointingLayer):
|
| 388 |
+
def __init__(self, config, layer_idx):
|
| 389 |
+
super().__init__()
|
| 390 |
+
self.hidden_size = config.hidden_size
|
| 391 |
+
|
| 392 |
+
self.self_attn = PeAudioVideoEncoderAttention(config=config, layer_idx=layer_idx)
|
| 393 |
+
|
| 394 |
+
self.mlp = PeAudioVideoEncoderMLP(config)
|
| 395 |
+
self.input_layernorm = PeAudioVideoEncoderRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 396 |
+
self.post_attention_layernorm = PeAudioVideoEncoderRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 397 |
+
|
| 398 |
+
def forward(
|
| 399 |
+
self,
|
| 400 |
+
hidden_states: torch.Tensor,
|
| 401 |
+
attention_mask: torch.Tensor | None = None,
|
| 402 |
+
position_ids: torch.LongTensor | None = None,
|
| 403 |
+
past_key_values: Cache | None = None,
|
| 404 |
+
use_cache: bool | None = False,
|
| 405 |
+
cache_position: torch.LongTensor | None = None,
|
| 406 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 407 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 408 |
+
) -> torch.Tensor:
|
| 409 |
+
residual = hidden_states
|
| 410 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 411 |
+
# Self Attention
|
| 412 |
+
hidden_states, _ = self.self_attn(
|
| 413 |
+
hidden_states=hidden_states,
|
| 414 |
+
attention_mask=attention_mask,
|
| 415 |
+
position_ids=position_ids,
|
| 416 |
+
past_key_values=past_key_values,
|
| 417 |
+
use_cache=use_cache,
|
| 418 |
+
cache_position=cache_position,
|
| 419 |
+
position_embeddings=position_embeddings,
|
| 420 |
+
**kwargs,
|
| 421 |
+
)
|
| 422 |
+
hidden_states = residual + hidden_states
|
| 423 |
+
|
| 424 |
+
# Fully Connected
|
| 425 |
+
residual = hidden_states
|
| 426 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 427 |
+
hidden_states = self.mlp(hidden_states)
|
| 428 |
+
hidden_states = residual + hidden_states
|
| 429 |
+
return hidden_states
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
@use_kernel_forward_from_hub("RMSNorm")
|
| 433 |
+
class PeAudioVideoEncoderRMSNorm(nn.Module):
|
| 434 |
+
def __init__(self, hidden_size, eps: float = 1e-6) -> None:
|
| 435 |
+
"""
|
| 436 |
+
PeAudioVideoEncoderRMSNorm is equivalent to T5LayerNorm
|
| 437 |
+
"""
|
| 438 |
+
super().__init__()
|
| 439 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 440 |
+
self.variance_epsilon = eps
|
| 441 |
+
|
| 442 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 443 |
+
input_dtype = hidden_states.dtype
|
| 444 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 445 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 446 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 447 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 448 |
+
|
| 449 |
+
def extra_repr(self):
|
| 450 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
class PeAudioVideoEncoderRotaryEmbedding(nn.Module):
|
| 454 |
+
inv_freq: torch.Tensor # fix linting for `register_buffer`
|
| 455 |
+
|
| 456 |
+
def __init__(self, config: PeAudioVideoEncoderConfig, device=None):
|
| 457 |
+
super().__init__()
|
| 458 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 459 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 460 |
+
|
| 461 |
+
self.config = config
|
| 462 |
+
|
| 463 |
+
self.rope_type = self.config.rope_parameters["rope_type"]
|
| 464 |
+
rope_init_fn: Callable = self.compute_default_rope_parameters
|
| 465 |
+
if self.rope_type != "default":
|
| 466 |
+
rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 467 |
+
inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
|
| 468 |
+
|
| 469 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 470 |
+
self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
|
| 471 |
+
|
| 472 |
+
@staticmethod
|
| 473 |
+
def compute_default_rope_parameters(
|
| 474 |
+
config: PeAudioVideoEncoderConfig | None = None,
|
| 475 |
+
device: Optional["torch.device"] = None,
|
| 476 |
+
seq_len: int | None = None,
|
| 477 |
+
) -> tuple["torch.Tensor", float]:
|
| 478 |
+
"""
|
| 479 |
+
Computes the inverse frequencies according to the original RoPE implementation
|
| 480 |
+
Args:
|
| 481 |
+
config ([`~transformers.PreTrainedConfig`]):
|
| 482 |
+
The model configuration.
|
| 483 |
+
device (`torch.device`):
|
| 484 |
+
The device to use for initialization of the inverse frequencies.
|
| 485 |
+
seq_len (`int`, *optional*):
|
| 486 |
+
The current sequence length. Unused for this type of RoPE.
|
| 487 |
+
Returns:
|
| 488 |
+
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
|
| 489 |
+
post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
|
| 490 |
+
"""
|
| 491 |
+
base = config.rope_parameters["rope_theta"]
|
| 492 |
+
dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
|
| 493 |
+
|
| 494 |
+
attention_factor = 1.0 # Unused in this type of RoPE
|
| 495 |
+
|
| 496 |
+
# Compute the inverse frequencies
|
| 497 |
+
inv_freq = 1.0 / (
|
| 498 |
+
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
|
| 499 |
+
)
|
| 500 |
+
return inv_freq, attention_factor
|
| 501 |
+
|
| 502 |
+
@torch.no_grad()
|
| 503 |
+
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
|
| 504 |
+
def forward(self, x, position_ids):
|
| 505 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
|
| 506 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 507 |
+
|
| 508 |
+
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
| 509 |
+
with maybe_autocast(device_type=device_type, enabled=False): # Force float32
|
| 510 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 511 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 512 |
+
cos = emb.cos() * self.attention_scaling
|
| 513 |
+
sin = emb.sin() * self.attention_scaling
|
| 514 |
+
|
| 515 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
@auto_docstring
|
| 519 |
+
class PeAudioVideoPreTrainedModel(PreTrainedModel):
|
| 520 |
+
config: PeAudioVideoConfig
|
| 521 |
+
base_model_prefix = "model"
|
| 522 |
+
supports_gradient_checkpointing = True
|
| 523 |
+
_no_split_modules = ["PeAudioVideoEncoderLayer"]
|
| 524 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 525 |
+
_supports_flash_attn = True
|
| 526 |
+
_supports_sdpa = True
|
| 527 |
+
_supports_flex_attn = True
|
| 528 |
+
|
| 529 |
+
_can_compile_fullgraph = True
|
| 530 |
+
_supports_attention_backend = True
|
| 531 |
+
_can_record_outputs = {
|
| 532 |
+
"hidden_states": PeAudioVideoEncoderLayer,
|
| 533 |
+
"attentions": PeAudioVideoEncoderAttention,
|
| 534 |
+
}
|
| 535 |
+
|
| 536 |
+
def _init_weights(self, module):
|
| 537 |
+
super()._init_weights(module)
|
| 538 |
+
|
| 539 |
+
if hasattr(self.config, "initializer_range"):
|
| 540 |
+
std = self.config.initializer_range
|
| 541 |
+
else:
|
| 542 |
+
# 0.02 is the standard default value across the library
|
| 543 |
+
std = getattr(self.config.get_text_config(), "initializer_range", 0.02)
|
| 544 |
+
|
| 545 |
+
if isinstance(module, PeAudioVideoEncoderPatchEmbedder):
|
| 546 |
+
embed_dim = module.class_embedding.shape[-1]
|
| 547 |
+
init.normal_(module.class_embedding, mean=0.0, std=embed_dim**-0.5 * std)
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
@dataclass
|
| 551 |
+
@auto_docstring(
|
| 552 |
+
custom_intro="""
|
| 553 |
+
Class for outputs of [`PeAudioVideoEncoder`].
|
| 554 |
+
"""
|
| 555 |
+
)
|
| 556 |
+
class PeAudioVideoEncoderOutput(BaseModelOutputWithPooling):
|
| 557 |
+
audio_model_output: BaseModelOutputWithPooling | None = None
|
| 558 |
+
video_model_output: BaseModelOutputWithPooling | None = None
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
@auto_docstring(
|
| 562 |
+
custom_intro="""
|
| 563 |
+
The PeAudioVideo Encoder model.
|
| 564 |
+
"""
|
| 565 |
+
)
|
| 566 |
+
class PeAudioVideoEncoder(PeAudioVideoPreTrainedModel):
|
| 567 |
+
config: PeAudioVideoEncoderConfig
|
| 568 |
+
main_input_name = "input_values"
|
| 569 |
+
base_model_prefix = "audio_video_encoder"
|
| 570 |
+
|
| 571 |
+
def __init__(self, config: PeAudioVideoEncoderConfig):
|
| 572 |
+
super().__init__(config)
|
| 573 |
+
self.embedder = PeAudioVideoEncoderEmbedder(config)
|
| 574 |
+
self.patch_embedder = PeAudioVideoEncoderPatchEmbedder(config)
|
| 575 |
+
self.layers = nn.ModuleList(
|
| 576 |
+
[PeAudioVideoEncoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 577 |
+
)
|
| 578 |
+
self.norm = PeAudioVideoEncoderRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 579 |
+
self.rotary_emb = PeAudioVideoEncoderRotaryEmbedding(config=config)
|
| 580 |
+
self.output = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
|
| 581 |
+
self.gradient_checkpointing = False
|
| 582 |
+
|
| 583 |
+
self.post_init()
|
| 584 |
+
|
| 585 |
+
@can_return_tuple
|
| 586 |
+
@merge_with_config_defaults
|
| 587 |
+
@capture_outputs
|
| 588 |
+
def forward(
|
| 589 |
+
self,
|
| 590 |
+
input_values: torch.Tensor | None = None,
|
| 591 |
+
pixel_values_videos: torch.Tensor | None = None,
|
| 592 |
+
padding_mask: torch.Tensor | None = None,
|
| 593 |
+
padding_mask_videos: torch.Tensor | None = None,
|
| 594 |
+
**kwargs,
|
| 595 |
+
) -> tuple | PeAudioVideoEncoderOutput:
|
| 596 |
+
inputs_embeds, padding_mask, audio_output, video_output = self.embedder(
|
| 597 |
+
input_values,
|
| 598 |
+
pixel_values_videos,
|
| 599 |
+
padding_mask=padding_mask,
|
| 600 |
+
padding_mask_videos=padding_mask_videos,
|
| 601 |
+
)
|
| 602 |
+
inputs_embeds, attention_mask = self.patch_embedder(inputs_embeds, padding_mask=padding_mask)
|
| 603 |
+
|
| 604 |
+
if attention_mask is not None:
|
| 605 |
+
attention_mask = create_bidirectional_mask(
|
| 606 |
+
config=self.config,
|
| 607 |
+
inputs_embeds=inputs_embeds,
|
| 608 |
+
attention_mask=attention_mask,
|
| 609 |
+
)
|
| 610 |
+
|
| 611 |
+
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
| 612 |
+
position_embeddings = self.rotary_emb(inputs_embeds, position_ids)
|
| 613 |
+
|
| 614 |
+
hidden_states = inputs_embeds
|
| 615 |
+
for encoder_layer in self.layers[: self.config.num_hidden_layers]:
|
| 616 |
+
hidden_states = encoder_layer(
|
| 617 |
+
hidden_states,
|
| 618 |
+
attention_mask=attention_mask,
|
| 619 |
+
position_embeddings=position_embeddings,
|
| 620 |
+
**kwargs,
|
| 621 |
+
)
|
| 622 |
+
|
| 623 |
+
hidden_states = self.norm(hidden_states)
|
| 624 |
+
hidden_states = self.output(hidden_states)
|
| 625 |
+
|
| 626 |
+
return PeAudioVideoEncoderOutput(
|
| 627 |
+
last_hidden_state=hidden_states[:, 1:],
|
| 628 |
+
pooler_output=hidden_states[:, 0],
|
| 629 |
+
audio_model_output=audio_output,
|
| 630 |
+
video_model_output=video_output,
|
| 631 |
+
)
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
@dataclass
|
| 635 |
+
@auto_docstring(
|
| 636 |
+
custom_intro="""
|
| 637 |
+
Class for outputs of [`PeAudioVideoModel`] when using text, audio, and/or video.
|
| 638 |
+
"""
|
| 639 |
+
)
|
| 640 |
+
class PeAudioVideoOutput(ModelOutput):
|
| 641 |
+
# embeddings
|
| 642 |
+
audio_embeds: torch.FloatTensor | None = None
|
| 643 |
+
video_embeds: torch.FloatTensor | None = None
|
| 644 |
+
audio_video_embeds: torch.FloatTensor | None = None
|
| 645 |
+
text_audio_embeds: torch.FloatTensor | None = None
|
| 646 |
+
text_video_embeds: torch.FloatTensor | None = None
|
| 647 |
+
text_audio_video_embeds: torch.FloatTensor | None = None
|
| 648 |
+
audio_plus_text_embeds: torch.FloatTensor | None = None
|
| 649 |
+
video_plus_text_embeds: torch.FloatTensor | None = None
|
| 650 |
+
|
| 651 |
+
# model outputs
|
| 652 |
+
# TODO: update types to the correct ones
|
| 653 |
+
text_outputs: MaskedLMOutput | None = None
|
| 654 |
+
audio_outputs: BaseModelOutputWithPooling | None = None
|
| 655 |
+
video_outputs: BaseModelOutputWithPooling | None = None
|
| 656 |
+
audio_video_outputs: BaseModelOutputWithPooling | None = None
|
| 657 |
+
|
| 658 |
+
# logits
|
| 659 |
+
logits_audio_text: torch.FloatTensor | None = None
|
| 660 |
+
logits_video_text: torch.FloatTensor | None = None
|
| 661 |
+
logits_audio_video: torch.FloatTensor | None = None
|
| 662 |
+
logits_audio_video_text: torch.FloatTensor | None = None
|
| 663 |
+
logits_audio_plus_text_video: torch.FloatTensor | None = None
|
| 664 |
+
logits_video_plus_text_audio: torch.FloatTensor | None = None
|
| 665 |
+
|
| 666 |
+
audio_text_loss: torch.FloatTensor | None = None
|
| 667 |
+
video_text_loss: torch.FloatTensor | None = None
|
| 668 |
+
audio_video_loss: torch.FloatTensor | None = None
|
| 669 |
+
audio_video_text_loss: torch.FloatTensor | None = None
|
| 670 |
+
audio_plus_text_video_loss: torch.FloatTensor | None = None
|
| 671 |
+
video_plus_text_audio_loss: torch.FloatTensor | None = None
|
| 672 |
+
loss: torch.FloatTensor | None = None
|
| 673 |
+
|
| 674 |
+
def to_tuple(self) -> tuple[Any]:
|
| 675 |
+
return tuple(self[k] if not k.endswith("model_output") else getattr(self, k).to_tuple() for k in self.keys())
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
@dataclass
|
| 679 |
+
class AudioVideoEmbeddings(ModelOutput):
|
| 680 |
+
audio_embeds: torch.FloatTensor | None = None
|
| 681 |
+
video_embeds: torch.FloatTensor | None = None
|
| 682 |
+
audio_video_embeds: torch.FloatTensor | None = None
|
| 683 |
+
|
| 684 |
+
|
| 685 |
+
class PeAudioVideoModel(PeAudioVideoPreTrainedModel):
|
| 686 |
+
_tied_weights_keys = {
|
| 687 |
+
r"audio_model\.text_model\.(?!rotary_emb)": r"^text_model\.(?!rotary_emb)",
|
| 688 |
+
r"video_model\.text_model\.(?!rotary_emb)": r"^text_model\.(?!rotary_emb)",
|
| 689 |
+
r"audio_video_encoder\.embedder\.audio_encoder\.(?!rotary_emb)": r"audio_model\.audio_encoder\.(?!rotary_emb)",
|
| 690 |
+
r"audio_video_encoder\.embedder\.video_encoder\.(?!rotary_emb|.*\.rope\.pos_embed)": r"video_model\.video_encoder\.(?!rotary_emb|.*\.rope\.pos_embed)",
|
| 691 |
+
}
|
| 692 |
+
|
| 693 |
+
def __init__(self, config: PeAudioVideoConfig):
|
| 694 |
+
super().__init__(config)
|
| 695 |
+
self.text_model = AutoModel.from_config(config.text_config)
|
| 696 |
+
self.audio_model = AutoModel.from_config(config.audio_config)
|
| 697 |
+
self.video_model = AutoModel.from_config(config.video_config)
|
| 698 |
+
self.audio_video_encoder = PeAudioVideoEncoder(config.audio_video_config)
|
| 699 |
+
|
| 700 |
+
text_hidden_size = config.text_config.hidden_size
|
| 701 |
+
audio_hidden_size = config.audio_video_config.audio_config.hidden_size
|
| 702 |
+
video_hidden_size = config.audio_video_config.video_config.hidden_size
|
| 703 |
+
|
| 704 |
+
# audio-video
|
| 705 |
+
self.audio_video_head = PeAudioVideoContrastiveHead(config.audio_video_config.hidden_size, text_hidden_size)
|
| 706 |
+
self.text_audio_video_head = PeAudioVideoContrastiveHead(text_hidden_size, text_hidden_size)
|
| 707 |
+
self.audio_video_logit_scale = nn.Parameter(torch.zeros(1))
|
| 708 |
+
self.audio_video_logit_bias = nn.Parameter(torch.zeros(1))
|
| 709 |
+
self.text_audio_video_logit_scale = nn.Parameter(torch.zeros(1))
|
| 710 |
+
self.text_audio_video_logit_bias = nn.Parameter(torch.zeros(1))
|
| 711 |
+
|
| 712 |
+
# text-audio
|
| 713 |
+
self.audio_plus_text_head = PeAudioVideoContrastiveHead(text_hidden_size + audio_hidden_size, text_hidden_size)
|
| 714 |
+
self.audio_plus_text_logit_scale = nn.Parameter(torch.zeros(1))
|
| 715 |
+
self.audio_plus_text_logit_bias = nn.Parameter(torch.zeros(1))
|
| 716 |
+
|
| 717 |
+
# text-video
|
| 718 |
+
self.video_plus_text_head = PeAudioVideoContrastiveHead(text_hidden_size + video_hidden_size, text_hidden_size)
|
| 719 |
+
self.video_plus_text_logit_scale = nn.Parameter(torch.zeros(1))
|
| 720 |
+
self.video_plus_text_logit_bias = nn.Parameter(torch.zeros(1))
|
| 721 |
+
|
| 722 |
+
self.post_init()
|
| 723 |
+
|
| 724 |
+
def _contrastive_loss(self, logits: torch.Tensor) -> torch.Tensor:
|
| 725 |
+
labels = torch.eye(logits.shape[0], device=logits.device)
|
| 726 |
+
loss = -nn.functional.logsigmoid(labels * logits).sum() / logits.shape[0]
|
| 727 |
+
return loss
|
| 728 |
+
|
| 729 |
+
def get_text_audio_embeds(self, input_ids, attention_mask=None):
|
| 730 |
+
return self.audio_model.get_text_embeds(input_ids, attention_mask)
|
| 731 |
+
|
| 732 |
+
def get_text_video_embeds(self, input_ids, attention_mask=None):
|
| 733 |
+
return self.video_model.get_text_embeds(input_ids, attention_mask)
|
| 734 |
+
|
| 735 |
+
def get_text_audio_video_embeds(self, input_ids, attention_mask=None):
|
| 736 |
+
text_outputs: MaskedLMOutput = self.text_model(
|
| 737 |
+
input_ids=input_ids,
|
| 738 |
+
attention_mask=attention_mask,
|
| 739 |
+
return_dict=True,
|
| 740 |
+
)
|
| 741 |
+
text_embeds = text_outputs.hidden_states[-1][:, 0]
|
| 742 |
+
return self.text_audio_video_head(text_embeds)
|
| 743 |
+
|
| 744 |
+
def get_audio_embeds(self, input_values, padding_mask=None):
|
| 745 |
+
return self.audio_model.get_audio_embeds(input_values, padding_mask)
|
| 746 |
+
|
| 747 |
+
def get_video_embeds(self, pixel_values_videos, padding_mask_videos=None):
|
| 748 |
+
return self.video_model.get_video_embeds(pixel_values_videos, padding_mask_videos)
|
| 749 |
+
|
| 750 |
+
def get_audio_video_embeds(
|
| 751 |
+
self,
|
| 752 |
+
input_values: torch.Tensor,
|
| 753 |
+
pixel_values_videos: torch.Tensor,
|
| 754 |
+
padding_mask: torch.Tensor | None = None,
|
| 755 |
+
padding_mask_videos: torch.Tensor | None = None,
|
| 756 |
+
return_audio_embeds: bool = False,
|
| 757 |
+
return_video_embeds: bool = False,
|
| 758 |
+
**kwargs,
|
| 759 |
+
) -> AudioVideoEmbeddings:
|
| 760 |
+
audio_video_outputs = self.audio_video_encoder(
|
| 761 |
+
input_values=input_values,
|
| 762 |
+
pixel_values_videos=pixel_values_videos,
|
| 763 |
+
padding_mask=padding_mask,
|
| 764 |
+
padding_mask_videos=padding_mask_videos,
|
| 765 |
+
**kwargs,
|
| 766 |
+
)
|
| 767 |
+
if return_audio_embeds:
|
| 768 |
+
audio_embeds = self.audio_model.audio_head(audio_video_outputs.audio_model_output.pooler_output)
|
| 769 |
+
if return_video_embeds:
|
| 770 |
+
video_embeds = self.video_model.video_head(audio_video_outputs.video_model_output.pooler_output)
|
| 771 |
+
|
| 772 |
+
audio_video_embeds = self.audio_video_head(audio_video_outputs.pooler_output)
|
| 773 |
+
return AudioVideoEmbeddings(
|
| 774 |
+
audio_embeds=audio_embeds if return_audio_embeds else None,
|
| 775 |
+
video_embeds=video_embeds if return_video_embeds else None,
|
| 776 |
+
audio_video_embeds=audio_video_embeds,
|
| 777 |
+
)
|
| 778 |
+
|
| 779 |
+
def get_audio_plus_text_embeds(
|
| 780 |
+
self,
|
| 781 |
+
input_ids: torch.Tensor,
|
| 782 |
+
input_values: torch.Tensor,
|
| 783 |
+
attention_mask: torch.Tensor | None = None,
|
| 784 |
+
padding_mask: torch.Tensor | None = None,
|
| 785 |
+
) -> torch.Tensor:
|
| 786 |
+
audio_embeds = self.audio_model.audio_encoder(
|
| 787 |
+
input_values=input_values,
|
| 788 |
+
padding_mask=padding_mask,
|
| 789 |
+
return_dict=True,
|
| 790 |
+
)
|
| 791 |
+
text_outputs: MaskedLMOutput = self.text_model(
|
| 792 |
+
input_ids=input_ids,
|
| 793 |
+
attention_mask=attention_mask,
|
| 794 |
+
return_dict=True,
|
| 795 |
+
)
|
| 796 |
+
text_embeds = text_outputs.hidden_states[-1][:, 0]
|
| 797 |
+
|
| 798 |
+
audio_plus_text_embeds = torch.cat([text_embeds, audio_embeds], dim=-1)
|
| 799 |
+
return self.audio_plus_text_head(audio_plus_text_embeds)
|
| 800 |
+
|
| 801 |
+
def get_video_plus_text_embeds(
|
| 802 |
+
self,
|
| 803 |
+
input_ids: torch.Tensor,
|
| 804 |
+
pixel_values_videos: torch.Tensor,
|
| 805 |
+
attention_mask: torch.Tensor | None = None,
|
| 806 |
+
padding_mask_videos: torch.Tensor | None = None,
|
| 807 |
+
) -> torch.Tensor:
|
| 808 |
+
video_embeds = self.video_model.video_encoder(
|
| 809 |
+
pixel_values_videos=pixel_values_videos,
|
| 810 |
+
padding_mask_videos=padding_mask_videos,
|
| 811 |
+
return_dict=True,
|
| 812 |
+
)
|
| 813 |
+
text_outputs: MaskedLMOutput = self.text_model(
|
| 814 |
+
input_ids=input_ids,
|
| 815 |
+
attention_mask=attention_mask,
|
| 816 |
+
return_dict=True,
|
| 817 |
+
)
|
| 818 |
+
text_embeds = text_outputs.hidden_states[-1][:, 0]
|
| 819 |
+
|
| 820 |
+
video_plus_text_embeds = torch.cat([text_embeds, video_embeds], dim=-1)
|
| 821 |
+
return self.video_plus_text_head(video_plus_text_embeds)
|
| 822 |
+
|
| 823 |
+
@can_return_tuple
|
| 824 |
+
def forward(
|
| 825 |
+
self,
|
| 826 |
+
input_ids: torch.Tensor | None = None,
|
| 827 |
+
pixel_values_videos: torch.Tensor | None = None,
|
| 828 |
+
input_values: torch.Tensor | None = None,
|
| 829 |
+
attention_mask: torch.Tensor | None = None,
|
| 830 |
+
padding_mask_videos: torch.Tensor | None = None,
|
| 831 |
+
padding_mask: torch.Tensor | None = None,
|
| 832 |
+
return_loss=False,
|
| 833 |
+
**kwargs,
|
| 834 |
+
) -> PeAudioVideoOutput:
|
| 835 |
+
if sum([input_ids is not None, pixel_values_videos is not None, input_values is not None]) < 2:
|
| 836 |
+
raise ValueError("At least two of input_ids, pixel_values_videos, or input_values must be provided")
|
| 837 |
+
|
| 838 |
+
if pixel_values_videos is None:
|
| 839 |
+
outputs = self.audio_model(
|
| 840 |
+
input_ids=input_ids,
|
| 841 |
+
input_values=input_values,
|
| 842 |
+
attention_mask=attention_mask,
|
| 843 |
+
padding_mask=padding_mask,
|
| 844 |
+
return_dict=True,
|
| 845 |
+
)
|
| 846 |
+
audio_plus_text_embeds = torch.cat(
|
| 847 |
+
[outputs.audio_outputs.pooler_output, outputs.text_outputs.hidden_states[-1][:, 0]], dim=-1
|
| 848 |
+
)
|
| 849 |
+
audio_plus_text_embeds = self.audio_plus_text_head(audio_plus_text_embeds)
|
| 850 |
+
return PeAudioVideoOutput(audio_plus_text_embeds=audio_plus_text_embeds, **outputs)
|
| 851 |
+
|
| 852 |
+
if input_values is None:
|
| 853 |
+
outputs = self.video_model(
|
| 854 |
+
input_ids=input_ids,
|
| 855 |
+
pixel_values_videos=pixel_values_videos,
|
| 856 |
+
attention_mask=attention_mask,
|
| 857 |
+
padding_mask_videos=padding_mask_videos,
|
| 858 |
+
return_dict=True,
|
| 859 |
+
)
|
| 860 |
+
video_plus_text_embeds = torch.cat(
|
| 861 |
+
[outputs.video_outputs.pooler_output, outputs.text_outputs.hidden_states[-1][:, 0]], dim=-1
|
| 862 |
+
)
|
| 863 |
+
video_plus_text_embeds = self.video_plus_text_head(video_plus_text_embeds)
|
| 864 |
+
return PeAudioVideoOutput(video_plus_text_embeds=video_plus_text_embeds, **outputs)
|
| 865 |
+
|
| 866 |
+
audio_video_outputs = self.audio_video_encoder(
|
| 867 |
+
input_values=input_values,
|
| 868 |
+
pixel_values_videos=pixel_values_videos,
|
| 869 |
+
padding_mask=padding_mask,
|
| 870 |
+
padding_mask_videos=padding_mask_videos,
|
| 871 |
+
**kwargs,
|
| 872 |
+
)
|
| 873 |
+
audio_embeds = audio_video_outputs.audio_model_output.pooler_output
|
| 874 |
+
video_embeds = audio_video_outputs.video_model_output.pooler_output
|
| 875 |
+
audio_video_embeds = audio_video_outputs.pooler_output
|
| 876 |
+
|
| 877 |
+
audio_embeds = self.audio_model.audio_head(audio_embeds)
|
| 878 |
+
video_embeds = self.video_model.video_head(video_embeds)
|
| 879 |
+
audio_video_embeds = self.audio_video_head(audio_video_embeds)
|
| 880 |
+
logits_audio_video = audio_embeds @ video_embeds.T
|
| 881 |
+
logits_audio_video = logits_audio_video * self.audio_video_logit_scale + self.audio_video_logit_bias
|
| 882 |
+
audio_video_loss = self._contrastive_loss(logits_audio_video) if return_loss else None
|
| 883 |
+
|
| 884 |
+
if input_ids is None:
|
| 885 |
+
return PeAudioVideoOutput(
|
| 886 |
+
logits_audio_video=logits_audio_video,
|
| 887 |
+
audio_embeds=audio_embeds,
|
| 888 |
+
video_embeds=video_embeds,
|
| 889 |
+
audio_video_embeds=audio_video_embeds,
|
| 890 |
+
loss=audio_video_loss,
|
| 891 |
+
audio_video_loss=audio_video_loss,
|
| 892 |
+
)
|
| 893 |
+
|
| 894 |
+
kwargs["output_hidden_states"] = True
|
| 895 |
+
text_outputs = self.text_model(input_ids=input_ids, attention_mask=attention_mask, **kwargs)
|
| 896 |
+
text_embeds = text_outputs.hidden_states[-1][:, 0]
|
| 897 |
+
audio_plus_text_embeds = torch.cat([audio_video_outputs.audio_model_output.pooler_output, text_embeds], dim=-1)
|
| 898 |
+
video_plus_text_embeds = torch.cat([audio_video_outputs.video_model_output.pooler_output, text_embeds], dim=-1)
|
| 899 |
+
|
| 900 |
+
text_audio_embeds = self.audio_model.text_audio_head(text_embeds)
|
| 901 |
+
text_video_embeds = self.video_model.text_video_head(text_embeds)
|
| 902 |
+
text_audio_video_embeds = self.text_audio_video_head(text_embeds)
|
| 903 |
+
audio_plus_text_embeds = self.audio_plus_text_head(audio_plus_text_embeds)
|
| 904 |
+
video_plus_text_embeds = self.video_plus_text_head(video_plus_text_embeds)
|
| 905 |
+
|
| 906 |
+
logits_audio_text = audio_embeds @ text_audio_embeds.T
|
| 907 |
+
logits_video_text = video_embeds @ text_video_embeds.T
|
| 908 |
+
logits_audio_video_text = audio_video_embeds @ text_audio_video_embeds.T
|
| 909 |
+
|
| 910 |
+
logits_audio_plus_text_video = audio_plus_text_embeds @ video_embeds.T
|
| 911 |
+
logits_video_plus_text_audio = video_plus_text_embeds @ audio_embeds.T
|
| 912 |
+
|
| 913 |
+
logits_audio_text = (
|
| 914 |
+
logits_audio_text * self.audio_model.text_audio_logit_scale + self.audio_model.text_audio_logit_bias
|
| 915 |
+
)
|
| 916 |
+
logits_video_text = (
|
| 917 |
+
logits_video_text * self.video_model.text_video_logit_scale + self.video_model.text_video_logit_bias
|
| 918 |
+
)
|
| 919 |
+
logits_audio_video_text = (
|
| 920 |
+
logits_audio_video_text * self.text_audio_video_logit_scale + self.text_audio_video_logit_bias
|
| 921 |
+
)
|
| 922 |
+
|
| 923 |
+
logits_audio_plus_text_video = (
|
| 924 |
+
logits_audio_plus_text_video * self.audio_plus_text_logit_scale + self.audio_plus_text_logit_bias
|
| 925 |
+
)
|
| 926 |
+
logits_video_plus_text_audio = (
|
| 927 |
+
logits_video_plus_text_audio * self.video_plus_text_logit_scale + self.video_plus_text_logit_bias
|
| 928 |
+
)
|
| 929 |
+
|
| 930 |
+
if return_loss:
|
| 931 |
+
audio_text_loss = self._contrastive_loss(logits_audio_text)
|
| 932 |
+
video_text_loss = self._contrastive_loss(logits_video_text)
|
| 933 |
+
audio_video_text_loss = self._contrastive_loss(logits_audio_video_text)
|
| 934 |
+
audio_plus_text_video_loss = self._contrastive_loss(logits_audio_plus_text_video)
|
| 935 |
+
video_plus_text_audio_loss = self._contrastive_loss(logits_video_plus_text_audio)
|
| 936 |
+
loss = (
|
| 937 |
+
audio_video_text_loss
|
| 938 |
+
+ audio_text_loss
|
| 939 |
+
+ video_text_loss
|
| 940 |
+
+ audio_video_loss
|
| 941 |
+
+ audio_plus_text_video_loss
|
| 942 |
+
+ video_plus_text_audio_loss
|
| 943 |
+
)
|
| 944 |
+
|
| 945 |
+
return PeAudioVideoOutput(
|
| 946 |
+
# embeddings
|
| 947 |
+
audio_embeds=audio_embeds,
|
| 948 |
+
video_embeds=video_embeds,
|
| 949 |
+
audio_video_embeds=audio_video_embeds,
|
| 950 |
+
text_audio_embeds=text_audio_embeds,
|
| 951 |
+
text_video_embeds=text_video_embeds,
|
| 952 |
+
text_audio_video_embeds=text_audio_video_embeds,
|
| 953 |
+
audio_plus_text_embeds=audio_plus_text_embeds,
|
| 954 |
+
video_plus_text_embeds=video_plus_text_embeds,
|
| 955 |
+
# model outputs
|
| 956 |
+
text_outputs=text_outputs,
|
| 957 |
+
audio_outputs=audio_video_outputs.audio_model_output,
|
| 958 |
+
video_outputs=audio_video_outputs.video_model_output,
|
| 959 |
+
audio_video_outputs=audio_video_outputs,
|
| 960 |
+
# logits
|
| 961 |
+
logits_audio_text=logits_audio_text,
|
| 962 |
+
logits_video_text=logits_video_text,
|
| 963 |
+
logits_audio_video=logits_audio_video,
|
| 964 |
+
logits_audio_video_text=logits_audio_video_text,
|
| 965 |
+
logits_audio_plus_text_video=logits_audio_plus_text_video,
|
| 966 |
+
logits_video_plus_text_audio=logits_video_plus_text_audio,
|
| 967 |
+
# losses
|
| 968 |
+
audio_text_loss=audio_text_loss if return_loss else None,
|
| 969 |
+
video_text_loss=video_text_loss if return_loss else None,
|
| 970 |
+
audio_video_loss=audio_video_loss if return_loss else None,
|
| 971 |
+
audio_video_text_loss=audio_video_text_loss if return_loss else None,
|
| 972 |
+
audio_plus_text_video_loss=audio_plus_text_video_loss if return_loss else None,
|
| 973 |
+
video_plus_text_audio_loss=video_plus_text_audio_loss if return_loss else None,
|
| 974 |
+
loss=loss if return_loss else None,
|
| 975 |
+
)
|
| 976 |
+
|
| 977 |
+
|
| 978 |
+
__all__ = ["PeAudioVideoModel", "PeAudioVideoEncoder"]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_audio_video/modular_pe_audio_video.py
ADDED
|
@@ -0,0 +1,771 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 the HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from collections.abc import Callable
|
| 15 |
+
from dataclasses import dataclass
|
| 16 |
+
from typing import Any
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
import torch.nn as nn
|
| 20 |
+
|
| 21 |
+
from ... import initialization as init
|
| 22 |
+
from ...masking_utils import create_bidirectional_mask
|
| 23 |
+
from ...modeling_outputs import BaseModelOutputWithPooling, MaskedLMOutput
|
| 24 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel, eager_attention_forward
|
| 25 |
+
from ...processing_utils import Unpack
|
| 26 |
+
from ...utils import ModelOutput, TransformersKwargs, auto_docstring, can_return_tuple
|
| 27 |
+
from ...utils.generic import merge_with_config_defaults
|
| 28 |
+
from ...utils.output_capturing import capture_outputs
|
| 29 |
+
from ..auto import AutoModel
|
| 30 |
+
from ..qwen3.modeling_qwen3 import Qwen3Attention, Qwen3DecoderLayer, Qwen3RMSNorm, Qwen3RotaryEmbedding
|
| 31 |
+
from .configuration_pe_audio_video import PeAudioVideoConfig, PeAudioVideoEncoderConfig
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class PeAudioVideoMaskedGroupNorm(nn.GroupNorm):
|
| 35 |
+
def forward(self, x, padding_mask=None):
|
| 36 |
+
if padding_mask is None:
|
| 37 |
+
return super().forward(x)
|
| 38 |
+
|
| 39 |
+
batch_size, hidden_size, seq_len = x.shape
|
| 40 |
+
group_size = hidden_size // self.num_groups
|
| 41 |
+
grouped_shape = (batch_size, -1, group_size, seq_len)
|
| 42 |
+
|
| 43 |
+
x_grouped = x.view(grouped_shape)
|
| 44 |
+
padding_mask_grouped = padding_mask.reshape(grouped_shape).bool()
|
| 45 |
+
|
| 46 |
+
mean = torch.masked.mean(x_grouped, mask=padding_mask_grouped, dim=(2, 3), keepdim=True)
|
| 47 |
+
var = torch.masked.var(x_grouped, mask=padding_mask_grouped, dim=(2, 3), keepdim=True, unbiased=False)
|
| 48 |
+
|
| 49 |
+
x_norm = (x_grouped - mean) / torch.sqrt(var + self.eps)
|
| 50 |
+
x_norm = x_norm.view(x.shape)
|
| 51 |
+
|
| 52 |
+
if self.affine:
|
| 53 |
+
x_norm = x_norm * self.weight.view(1, -1, 1) + self.bias.view(1, -1, 1)
|
| 54 |
+
|
| 55 |
+
return x_norm * padding_mask
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class PeAudioVideoConvBlock1d(nn.Module):
|
| 59 |
+
def __init__(self, config):
|
| 60 |
+
super().__init__()
|
| 61 |
+
self.groupnorm = PeAudioVideoMaskedGroupNorm(num_groups=1, num_channels=config.hidden_size)
|
| 62 |
+
self.activation = nn.SiLU()
|
| 63 |
+
self.project = nn.Conv1d(
|
| 64 |
+
in_channels=config.hidden_size,
|
| 65 |
+
out_channels=config.hidden_size,
|
| 66 |
+
kernel_size=3,
|
| 67 |
+
padding="same",
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
def forward(self, x, padding_mask=None):
|
| 71 |
+
x = self.groupnorm(x, padding_mask=padding_mask)
|
| 72 |
+
x = self.activation(x)
|
| 73 |
+
return self.project(x)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class PeAudioVideoResnetBlock1d(nn.Module):
|
| 77 |
+
def __init__(self, config):
|
| 78 |
+
super().__init__()
|
| 79 |
+
self.block1 = PeAudioVideoConvBlock1d(config)
|
| 80 |
+
self.block2 = PeAudioVideoConvBlock1d(config)
|
| 81 |
+
|
| 82 |
+
def forward(self, hidden_states, padding_mask=None):
|
| 83 |
+
"""
|
| 84 |
+
Args:
|
| 85 |
+
hidden_states: (batch_size, seq_len, hidden_size)
|
| 86 |
+
padding_mask: (batch_size, seq_len)
|
| 87 |
+
Returns:
|
| 88 |
+
hidden_states: (batch_size, seq_len, hidden_size)
|
| 89 |
+
"""
|
| 90 |
+
# transpose for convolutions
|
| 91 |
+
# (batch_size, seq_len, hidden_size) -> (batch_size, hidden_size, seq_len)
|
| 92 |
+
hidden_states = hidden_states.transpose(1, 2)
|
| 93 |
+
|
| 94 |
+
if padding_mask is not None:
|
| 95 |
+
padding_mask = padding_mask.unsqueeze(1).expand_as(hidden_states)
|
| 96 |
+
|
| 97 |
+
residual = hidden_states
|
| 98 |
+
hidden_states = self.block1(hidden_states, padding_mask=padding_mask)
|
| 99 |
+
hidden_states = self.block2(hidden_states, padding_mask=padding_mask)
|
| 100 |
+
hidden_states = residual + hidden_states
|
| 101 |
+
|
| 102 |
+
return hidden_states.transpose(1, 2)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class PeAudioVideoEncoderPatchEmbedder(nn.Module):
|
| 106 |
+
def __init__(self, config):
|
| 107 |
+
super().__init__()
|
| 108 |
+
self.resnet_block = PeAudioVideoResnetBlock1d(config)
|
| 109 |
+
self.class_embedding = nn.Parameter(torch.randn(1, 1, config.hidden_size))
|
| 110 |
+
|
| 111 |
+
def forward(self, inputs_embeds, padding_mask=None):
|
| 112 |
+
# Embedding step: prepend class token and run the ResNet block.
|
| 113 |
+
hidden_states = torch.cat(
|
| 114 |
+
[self.class_embedding.expand(inputs_embeds.size(0), -1, -1), inputs_embeds],
|
| 115 |
+
dim=1,
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
if padding_mask is not None:
|
| 119 |
+
# TODO: any reason why we take padding_mask[0] and not just 1?
|
| 120 |
+
padding_mask = torch.cat([padding_mask[:, [0]], padding_mask], dim=1)
|
| 121 |
+
|
| 122 |
+
hidden_states = self.resnet_block(hidden_states, padding_mask=padding_mask)
|
| 123 |
+
return hidden_states, padding_mask
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class PeAudioVideoContrastiveHead(nn.Module):
|
| 127 |
+
def __init__(
|
| 128 |
+
self,
|
| 129 |
+
in_dim: int,
|
| 130 |
+
out_dim: int,
|
| 131 |
+
) -> None:
|
| 132 |
+
super().__init__()
|
| 133 |
+
self.layer_norm = nn.LayerNorm(normalized_shape=in_dim, eps=1e-6)
|
| 134 |
+
self.proj = nn.Linear(in_dim, out_dim, bias=False)
|
| 135 |
+
|
| 136 |
+
def forward(self, x: torch.Tensor) -> torch.FloatTensor:
|
| 137 |
+
return self.proj(self.layer_norm(x))
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class PeAudioVideoEncoderEmbedder(nn.Module):
|
| 141 |
+
def __init__(self, config: PeAudioVideoEncoderConfig):
|
| 142 |
+
super().__init__()
|
| 143 |
+
self.audio_encoder = AutoModel.from_config(config.audio_config)
|
| 144 |
+
self.video_encoder = AutoModel.from_config(config.video_config)
|
| 145 |
+
|
| 146 |
+
self.video_proj = nn.Conv1d(config.video_config.hidden_size, config.audio_config.hidden_size, 1)
|
| 147 |
+
self.video_norm = nn.LayerNorm(config.audio_config.hidden_size)
|
| 148 |
+
|
| 149 |
+
self.concat_modality_proj = nn.Linear(
|
| 150 |
+
config.audio_config.hidden_size + config.video_config.hidden_size,
|
| 151 |
+
config.hidden_size,
|
| 152 |
+
)
|
| 153 |
+
self.data_proj = nn.Linear(config.hidden_size, config.hidden_size)
|
| 154 |
+
|
| 155 |
+
def _align_video_hidden_state(
|
| 156 |
+
self,
|
| 157 |
+
video_hidden_state: torch.Tensor,
|
| 158 |
+
audio_hidden_state: torch.Tensor,
|
| 159 |
+
padding_mask_videos: torch.Tensor | None = None,
|
| 160 |
+
padding_mask: torch.Tensor | None = None,
|
| 161 |
+
) -> torch.Tensor:
|
| 162 |
+
"""
|
| 163 |
+
Align video_hidden_state to audio_hidden_state by nearest neighbor interpolation.
|
| 164 |
+
"""
|
| 165 |
+
if video_hidden_state.shape[1] == audio_hidden_state.shape[1]:
|
| 166 |
+
return video_hidden_state
|
| 167 |
+
|
| 168 |
+
if padding_mask_videos is not None:
|
| 169 |
+
video_lengths = padding_mask_videos.sum(dim=-1)
|
| 170 |
+
else:
|
| 171 |
+
video_lengths = video_hidden_state.shape[1] * video_hidden_state.new_ones(
|
| 172 |
+
video_hidden_state.shape[0], dtype=torch.long
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
if padding_mask is not None:
|
| 176 |
+
audio_lengths = padding_mask.sum(dim=-1)
|
| 177 |
+
else:
|
| 178 |
+
audio_lengths = audio_hidden_state.shape[1] * audio_hidden_state.new_ones(
|
| 179 |
+
audio_hidden_state.shape[0], dtype=torch.long
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
if (audio_lengths == video_hidden_state.shape[1]).all() or (
|
| 183 |
+
video_lengths == audio_hidden_state.shape[1]
|
| 184 |
+
).all():
|
| 185 |
+
# no need to align taking into account the padding masks
|
| 186 |
+
# note: when one of the above is true, we can expect the other to be true as there is no reason
|
| 187 |
+
# to have masked audio without masked video and vice versa
|
| 188 |
+
|
| 189 |
+
return nn.functional.interpolate(
|
| 190 |
+
video_hidden_state.transpose(1, 2), size=audio_hidden_state.shape[1], mode="nearest"
|
| 191 |
+
).transpose(1, 2)
|
| 192 |
+
|
| 193 |
+
aligned_shape = (*audio_hidden_state.shape[:2], video_hidden_state.shape[-1])
|
| 194 |
+
aligned_hidden_state = audio_hidden_state.new_zeros(aligned_shape)
|
| 195 |
+
|
| 196 |
+
for i, (hidden_state, video_length, audio_length) in enumerate(
|
| 197 |
+
zip(video_hidden_state, video_lengths, audio_lengths)
|
| 198 |
+
):
|
| 199 |
+
hidden_state = hidden_state[:video_length]
|
| 200 |
+
if hidden_state.numel() > 0 and audio_length > 0:
|
| 201 |
+
interpolated_hidden_state = nn.functional.interpolate(
|
| 202 |
+
hidden_state[None].transpose(1, 2), size=audio_length, mode="nearest"
|
| 203 |
+
).transpose(1, 2)[0]
|
| 204 |
+
aligned_hidden_state[i, :audio_length, :] = interpolated_hidden_state
|
| 205 |
+
|
| 206 |
+
return aligned_hidden_state
|
| 207 |
+
|
| 208 |
+
def forward(
|
| 209 |
+
self,
|
| 210 |
+
input_values: torch.Tensor,
|
| 211 |
+
pixel_values_videos: torch.Tensor,
|
| 212 |
+
padding_mask: torch.Tensor | None = None,
|
| 213 |
+
padding_mask_videos: torch.Tensor | None = None,
|
| 214 |
+
):
|
| 215 |
+
audio_output = self.audio_encoder(input_values, padding_mask=padding_mask)
|
| 216 |
+
video_output = self.video_encoder(pixel_values_videos, padding_mask_videos=padding_mask_videos)
|
| 217 |
+
|
| 218 |
+
audio_hidden_state = audio_output.last_hidden_state
|
| 219 |
+
video_hidden_state = video_output.last_hidden_state
|
| 220 |
+
padding_mask = audio_output.output_mask
|
| 221 |
+
|
| 222 |
+
video_hidden_state = self.video_proj(video_hidden_state.transpose(1, 2)).transpose(1, 2)
|
| 223 |
+
video_hidden_state = self._align_video_hidden_state(
|
| 224 |
+
video_hidden_state=video_hidden_state,
|
| 225 |
+
audio_hidden_state=audio_hidden_state,
|
| 226 |
+
padding_mask_videos=padding_mask_videos,
|
| 227 |
+
padding_mask=padding_mask,
|
| 228 |
+
)
|
| 229 |
+
video_hidden_state = self.video_norm(video_hidden_state)
|
| 230 |
+
inputs_embeds = torch.cat([audio_hidden_state, video_hidden_state], dim=-1)
|
| 231 |
+
inputs_embeds = self.concat_modality_proj(inputs_embeds)
|
| 232 |
+
inputs_embeds = self.data_proj(inputs_embeds)
|
| 233 |
+
|
| 234 |
+
return inputs_embeds, padding_mask, audio_output, video_output
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
class PeAudioVideoEncoderAttention(Qwen3Attention):
|
| 238 |
+
def __init__(self, config, layer_idx):
|
| 239 |
+
super().__init__(config, layer_idx)
|
| 240 |
+
self.is_causal = False
|
| 241 |
+
del self.sliding_window
|
| 242 |
+
|
| 243 |
+
def forward(
|
| 244 |
+
self,
|
| 245 |
+
hidden_states: torch.Tensor,
|
| 246 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 247 |
+
attention_mask: torch.Tensor | None = None,
|
| 248 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 249 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 250 |
+
input_shape = hidden_states.shape[:-1]
|
| 251 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 252 |
+
|
| 253 |
+
query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
|
| 254 |
+
key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
|
| 255 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 256 |
+
|
| 257 |
+
cos, sin = position_embeddings
|
| 258 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 259 |
+
|
| 260 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 261 |
+
self.config._attn_implementation, eager_attention_forward
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
attn_output, attn_weights = attention_interface(
|
| 265 |
+
self,
|
| 266 |
+
query_states,
|
| 267 |
+
key_states,
|
| 268 |
+
value_states,
|
| 269 |
+
attention_mask,
|
| 270 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 271 |
+
scaling=self.scaling,
|
| 272 |
+
**kwargs,
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 276 |
+
attn_output = self.o_proj(attn_output)
|
| 277 |
+
return attn_output, attn_weights
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
class PeAudioVideoEncoderLayer(Qwen3DecoderLayer):
|
| 281 |
+
def __init__(self, config, layer_idx):
|
| 282 |
+
super().__init__(config, layer_idx)
|
| 283 |
+
del self.attention_type
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
class PeAudioVideoEncoderRMSNorm(Qwen3RMSNorm): ...
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def stack_freqs(cos: torch.Tensor, sin: torch.Tensor):
|
| 290 |
+
dim = cos.size(-1)
|
| 291 |
+
cos = cos.narrow(-1, 0, dim // 2)
|
| 292 |
+
sin = sin.narrow(-1, 0, dim // 2)
|
| 293 |
+
freqs_cis = torch.stack((cos, -sin, sin, cos), dim=-1).view(*cos.size(), 2, 2)
|
| 294 |
+
return freqs_cis
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
|
| 298 |
+
freqs_cis = stack_freqs(cos, sin)
|
| 299 |
+
freqs_cis = freqs_cis.unsqueeze(unsqueeze_dim)
|
| 300 |
+
q_ = q.reshape(*q.shape[:-1], -1, 1, 2)
|
| 301 |
+
k_ = k.reshape(*k.shape[:-1], -1, 1, 2)
|
| 302 |
+
return (q_ * freqs_cis).sum(5).flatten(3), (k_ * freqs_cis).sum(5).flatten(3)
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
class PeAudioVideoEncoderRotaryEmbedding(Qwen3RotaryEmbedding): ...
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
@auto_docstring
|
| 309 |
+
class PeAudioVideoPreTrainedModel(PreTrainedModel):
|
| 310 |
+
config: PeAudioVideoConfig
|
| 311 |
+
base_model_prefix = "model"
|
| 312 |
+
supports_gradient_checkpointing = True
|
| 313 |
+
_no_split_modules = ["PeAudioVideoEncoderLayer"]
|
| 314 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 315 |
+
_supports_flash_attn = True
|
| 316 |
+
_supports_sdpa = True
|
| 317 |
+
_supports_flex_attn = True
|
| 318 |
+
|
| 319 |
+
_can_compile_fullgraph = True
|
| 320 |
+
_supports_attention_backend = True
|
| 321 |
+
_can_record_outputs = {
|
| 322 |
+
"hidden_states": PeAudioVideoEncoderLayer,
|
| 323 |
+
"attentions": PeAudioVideoEncoderAttention,
|
| 324 |
+
}
|
| 325 |
+
|
| 326 |
+
def _init_weights(self, module):
|
| 327 |
+
super()._init_weights(module)
|
| 328 |
+
|
| 329 |
+
if hasattr(self.config, "initializer_range"):
|
| 330 |
+
std = self.config.initializer_range
|
| 331 |
+
else:
|
| 332 |
+
# 0.02 is the standard default value across the library
|
| 333 |
+
std = getattr(self.config.get_text_config(), "initializer_range", 0.02)
|
| 334 |
+
|
| 335 |
+
if isinstance(module, PeAudioVideoEncoderPatchEmbedder):
|
| 336 |
+
embed_dim = module.class_embedding.shape[-1]
|
| 337 |
+
init.normal_(module.class_embedding, mean=0.0, std=embed_dim**-0.5 * std)
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
@dataclass
|
| 341 |
+
@auto_docstring(
|
| 342 |
+
custom_intro="""
|
| 343 |
+
Class for outputs of [`PeAudioVideoEncoder`].
|
| 344 |
+
"""
|
| 345 |
+
)
|
| 346 |
+
class PeAudioVideoEncoderOutput(BaseModelOutputWithPooling):
|
| 347 |
+
audio_model_output: BaseModelOutputWithPooling | None = None
|
| 348 |
+
video_model_output: BaseModelOutputWithPooling | None = None
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
@auto_docstring(
|
| 352 |
+
custom_intro="""
|
| 353 |
+
The PeAudioVideo Encoder model.
|
| 354 |
+
"""
|
| 355 |
+
)
|
| 356 |
+
class PeAudioVideoEncoder(PeAudioVideoPreTrainedModel):
|
| 357 |
+
config: PeAudioVideoEncoderConfig
|
| 358 |
+
main_input_name = "input_values"
|
| 359 |
+
base_model_prefix = "audio_video_encoder"
|
| 360 |
+
|
| 361 |
+
def __init__(self, config: PeAudioVideoEncoderConfig):
|
| 362 |
+
super().__init__(config)
|
| 363 |
+
self.embedder = PeAudioVideoEncoderEmbedder(config)
|
| 364 |
+
self.patch_embedder = PeAudioVideoEncoderPatchEmbedder(config)
|
| 365 |
+
self.layers = nn.ModuleList(
|
| 366 |
+
[PeAudioVideoEncoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 367 |
+
)
|
| 368 |
+
self.norm = PeAudioVideoEncoderRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 369 |
+
self.rotary_emb = PeAudioVideoEncoderRotaryEmbedding(config=config)
|
| 370 |
+
self.output = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
|
| 371 |
+
self.gradient_checkpointing = False
|
| 372 |
+
|
| 373 |
+
self.post_init()
|
| 374 |
+
|
| 375 |
+
@can_return_tuple
|
| 376 |
+
@merge_with_config_defaults
|
| 377 |
+
@capture_outputs
|
| 378 |
+
def forward(
|
| 379 |
+
self,
|
| 380 |
+
input_values: torch.Tensor | None = None,
|
| 381 |
+
pixel_values_videos: torch.Tensor | None = None,
|
| 382 |
+
padding_mask: torch.Tensor | None = None,
|
| 383 |
+
padding_mask_videos: torch.Tensor | None = None,
|
| 384 |
+
**kwargs,
|
| 385 |
+
) -> tuple | PeAudioVideoEncoderOutput:
|
| 386 |
+
inputs_embeds, padding_mask, audio_output, video_output = self.embedder(
|
| 387 |
+
input_values,
|
| 388 |
+
pixel_values_videos,
|
| 389 |
+
padding_mask=padding_mask,
|
| 390 |
+
padding_mask_videos=padding_mask_videos,
|
| 391 |
+
)
|
| 392 |
+
inputs_embeds, attention_mask = self.patch_embedder(inputs_embeds, padding_mask=padding_mask)
|
| 393 |
+
|
| 394 |
+
if attention_mask is not None:
|
| 395 |
+
attention_mask = create_bidirectional_mask(
|
| 396 |
+
config=self.config,
|
| 397 |
+
inputs_embeds=inputs_embeds,
|
| 398 |
+
attention_mask=attention_mask,
|
| 399 |
+
)
|
| 400 |
+
|
| 401 |
+
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
| 402 |
+
position_embeddings = self.rotary_emb(inputs_embeds, position_ids)
|
| 403 |
+
|
| 404 |
+
hidden_states = inputs_embeds
|
| 405 |
+
for encoder_layer in self.layers[: self.config.num_hidden_layers]:
|
| 406 |
+
hidden_states = encoder_layer(
|
| 407 |
+
hidden_states,
|
| 408 |
+
attention_mask=attention_mask,
|
| 409 |
+
position_embeddings=position_embeddings,
|
| 410 |
+
**kwargs,
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
+
hidden_states = self.norm(hidden_states)
|
| 414 |
+
hidden_states = self.output(hidden_states)
|
| 415 |
+
|
| 416 |
+
return PeAudioVideoEncoderOutput(
|
| 417 |
+
last_hidden_state=hidden_states[:, 1:],
|
| 418 |
+
pooler_output=hidden_states[:, 0],
|
| 419 |
+
audio_model_output=audio_output,
|
| 420 |
+
video_model_output=video_output,
|
| 421 |
+
)
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
@dataclass
|
| 425 |
+
@auto_docstring(
|
| 426 |
+
custom_intro="""
|
| 427 |
+
Class for outputs of [`PeAudioVideoModel`] when using text, audio, and/or video.
|
| 428 |
+
"""
|
| 429 |
+
)
|
| 430 |
+
class PeAudioVideoOutput(ModelOutput):
|
| 431 |
+
# embeddings
|
| 432 |
+
audio_embeds: torch.FloatTensor | None = None
|
| 433 |
+
video_embeds: torch.FloatTensor | None = None
|
| 434 |
+
audio_video_embeds: torch.FloatTensor | None = None
|
| 435 |
+
text_audio_embeds: torch.FloatTensor | None = None
|
| 436 |
+
text_video_embeds: torch.FloatTensor | None = None
|
| 437 |
+
text_audio_video_embeds: torch.FloatTensor | None = None
|
| 438 |
+
audio_plus_text_embeds: torch.FloatTensor | None = None
|
| 439 |
+
video_plus_text_embeds: torch.FloatTensor | None = None
|
| 440 |
+
|
| 441 |
+
# model outputs
|
| 442 |
+
# TODO: update types to the correct ones
|
| 443 |
+
text_outputs: MaskedLMOutput | None = None
|
| 444 |
+
audio_outputs: BaseModelOutputWithPooling | None = None
|
| 445 |
+
video_outputs: BaseModelOutputWithPooling | None = None
|
| 446 |
+
audio_video_outputs: BaseModelOutputWithPooling | None = None
|
| 447 |
+
|
| 448 |
+
# logits
|
| 449 |
+
logits_audio_text: torch.FloatTensor | None = None
|
| 450 |
+
logits_video_text: torch.FloatTensor | None = None
|
| 451 |
+
logits_audio_video: torch.FloatTensor | None = None
|
| 452 |
+
logits_audio_video_text: torch.FloatTensor | None = None
|
| 453 |
+
logits_audio_plus_text_video: torch.FloatTensor | None = None
|
| 454 |
+
logits_video_plus_text_audio: torch.FloatTensor | None = None
|
| 455 |
+
|
| 456 |
+
audio_text_loss: torch.FloatTensor | None = None
|
| 457 |
+
video_text_loss: torch.FloatTensor | None = None
|
| 458 |
+
audio_video_loss: torch.FloatTensor | None = None
|
| 459 |
+
audio_video_text_loss: torch.FloatTensor | None = None
|
| 460 |
+
audio_plus_text_video_loss: torch.FloatTensor | None = None
|
| 461 |
+
video_plus_text_audio_loss: torch.FloatTensor | None = None
|
| 462 |
+
loss: torch.FloatTensor | None = None
|
| 463 |
+
|
| 464 |
+
def to_tuple(self) -> tuple[Any]:
|
| 465 |
+
return tuple(self[k] if not k.endswith("model_output") else getattr(self, k).to_tuple() for k in self.keys())
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
@dataclass
|
| 469 |
+
class AudioVideoEmbeddings(ModelOutput):
|
| 470 |
+
audio_embeds: torch.FloatTensor | None = None
|
| 471 |
+
video_embeds: torch.FloatTensor | None = None
|
| 472 |
+
audio_video_embeds: torch.FloatTensor | None = None
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
class PeAudioVideoModel(PeAudioVideoPreTrainedModel):
|
| 476 |
+
_tied_weights_keys = {
|
| 477 |
+
r"audio_model\.text_model\.(?!rotary_emb)": r"^text_model\.(?!rotary_emb)",
|
| 478 |
+
r"video_model\.text_model\.(?!rotary_emb)": r"^text_model\.(?!rotary_emb)",
|
| 479 |
+
r"audio_video_encoder\.embedder\.audio_encoder\.(?!rotary_emb)": r"audio_model\.audio_encoder\.(?!rotary_emb)",
|
| 480 |
+
r"audio_video_encoder\.embedder\.video_encoder\.(?!rotary_emb|.*\.rope\.pos_embed)": r"video_model\.video_encoder\.(?!rotary_emb|.*\.rope\.pos_embed)",
|
| 481 |
+
}
|
| 482 |
+
|
| 483 |
+
def __init__(self, config: PeAudioVideoConfig):
|
| 484 |
+
super().__init__(config)
|
| 485 |
+
self.text_model = AutoModel.from_config(config.text_config)
|
| 486 |
+
self.audio_model = AutoModel.from_config(config.audio_config)
|
| 487 |
+
self.video_model = AutoModel.from_config(config.video_config)
|
| 488 |
+
self.audio_video_encoder = PeAudioVideoEncoder(config.audio_video_config)
|
| 489 |
+
|
| 490 |
+
text_hidden_size = config.text_config.hidden_size
|
| 491 |
+
audio_hidden_size = config.audio_video_config.audio_config.hidden_size
|
| 492 |
+
video_hidden_size = config.audio_video_config.video_config.hidden_size
|
| 493 |
+
|
| 494 |
+
# audio-video
|
| 495 |
+
self.audio_video_head = PeAudioVideoContrastiveHead(config.audio_video_config.hidden_size, text_hidden_size)
|
| 496 |
+
self.text_audio_video_head = PeAudioVideoContrastiveHead(text_hidden_size, text_hidden_size)
|
| 497 |
+
self.audio_video_logit_scale = nn.Parameter(torch.zeros(1))
|
| 498 |
+
self.audio_video_logit_bias = nn.Parameter(torch.zeros(1))
|
| 499 |
+
self.text_audio_video_logit_scale = nn.Parameter(torch.zeros(1))
|
| 500 |
+
self.text_audio_video_logit_bias = nn.Parameter(torch.zeros(1))
|
| 501 |
+
|
| 502 |
+
# text-audio
|
| 503 |
+
self.audio_plus_text_head = PeAudioVideoContrastiveHead(text_hidden_size + audio_hidden_size, text_hidden_size)
|
| 504 |
+
self.audio_plus_text_logit_scale = nn.Parameter(torch.zeros(1))
|
| 505 |
+
self.audio_plus_text_logit_bias = nn.Parameter(torch.zeros(1))
|
| 506 |
+
|
| 507 |
+
# text-video
|
| 508 |
+
self.video_plus_text_head = PeAudioVideoContrastiveHead(text_hidden_size + video_hidden_size, text_hidden_size)
|
| 509 |
+
self.video_plus_text_logit_scale = nn.Parameter(torch.zeros(1))
|
| 510 |
+
self.video_plus_text_logit_bias = nn.Parameter(torch.zeros(1))
|
| 511 |
+
|
| 512 |
+
self.post_init()
|
| 513 |
+
|
| 514 |
+
def _contrastive_loss(self, logits: torch.Tensor) -> torch.Tensor:
|
| 515 |
+
labels = torch.eye(logits.shape[0], device=logits.device)
|
| 516 |
+
loss = -nn.functional.logsigmoid(labels * logits).sum() / logits.shape[0]
|
| 517 |
+
return loss
|
| 518 |
+
|
| 519 |
+
def get_text_audio_embeds(self, input_ids, attention_mask=None):
|
| 520 |
+
return self.audio_model.get_text_embeds(input_ids, attention_mask)
|
| 521 |
+
|
| 522 |
+
def get_text_video_embeds(self, input_ids, attention_mask=None):
|
| 523 |
+
return self.video_model.get_text_embeds(input_ids, attention_mask)
|
| 524 |
+
|
| 525 |
+
def get_text_audio_video_embeds(self, input_ids, attention_mask=None):
|
| 526 |
+
text_outputs: MaskedLMOutput = self.text_model(
|
| 527 |
+
input_ids=input_ids,
|
| 528 |
+
attention_mask=attention_mask,
|
| 529 |
+
return_dict=True,
|
| 530 |
+
)
|
| 531 |
+
text_embeds = text_outputs.hidden_states[-1][:, 0]
|
| 532 |
+
return self.text_audio_video_head(text_embeds)
|
| 533 |
+
|
| 534 |
+
def get_audio_embeds(self, input_values, padding_mask=None):
|
| 535 |
+
return self.audio_model.get_audio_embeds(input_values, padding_mask)
|
| 536 |
+
|
| 537 |
+
def get_video_embeds(self, pixel_values_videos, padding_mask_videos=None):
|
| 538 |
+
return self.video_model.get_video_embeds(pixel_values_videos, padding_mask_videos)
|
| 539 |
+
|
| 540 |
+
def get_audio_video_embeds(
|
| 541 |
+
self,
|
| 542 |
+
input_values: torch.Tensor,
|
| 543 |
+
pixel_values_videos: torch.Tensor,
|
| 544 |
+
padding_mask: torch.Tensor | None = None,
|
| 545 |
+
padding_mask_videos: torch.Tensor | None = None,
|
| 546 |
+
return_audio_embeds: bool = False,
|
| 547 |
+
return_video_embeds: bool = False,
|
| 548 |
+
**kwargs,
|
| 549 |
+
) -> AudioVideoEmbeddings:
|
| 550 |
+
audio_video_outputs = self.audio_video_encoder(
|
| 551 |
+
input_values=input_values,
|
| 552 |
+
pixel_values_videos=pixel_values_videos,
|
| 553 |
+
padding_mask=padding_mask,
|
| 554 |
+
padding_mask_videos=padding_mask_videos,
|
| 555 |
+
**kwargs,
|
| 556 |
+
)
|
| 557 |
+
if return_audio_embeds:
|
| 558 |
+
audio_embeds = self.audio_model.audio_head(audio_video_outputs.audio_model_output.pooler_output)
|
| 559 |
+
if return_video_embeds:
|
| 560 |
+
video_embeds = self.video_model.video_head(audio_video_outputs.video_model_output.pooler_output)
|
| 561 |
+
|
| 562 |
+
audio_video_embeds = self.audio_video_head(audio_video_outputs.pooler_output)
|
| 563 |
+
return AudioVideoEmbeddings(
|
| 564 |
+
audio_embeds=audio_embeds if return_audio_embeds else None,
|
| 565 |
+
video_embeds=video_embeds if return_video_embeds else None,
|
| 566 |
+
audio_video_embeds=audio_video_embeds,
|
| 567 |
+
)
|
| 568 |
+
|
| 569 |
+
def get_audio_plus_text_embeds(
|
| 570 |
+
self,
|
| 571 |
+
input_ids: torch.Tensor,
|
| 572 |
+
input_values: torch.Tensor,
|
| 573 |
+
attention_mask: torch.Tensor | None = None,
|
| 574 |
+
padding_mask: torch.Tensor | None = None,
|
| 575 |
+
) -> torch.Tensor:
|
| 576 |
+
audio_embeds = self.audio_model.audio_encoder(
|
| 577 |
+
input_values=input_values,
|
| 578 |
+
padding_mask=padding_mask,
|
| 579 |
+
return_dict=True,
|
| 580 |
+
)
|
| 581 |
+
text_outputs: MaskedLMOutput = self.text_model(
|
| 582 |
+
input_ids=input_ids,
|
| 583 |
+
attention_mask=attention_mask,
|
| 584 |
+
return_dict=True,
|
| 585 |
+
)
|
| 586 |
+
text_embeds = text_outputs.hidden_states[-1][:, 0]
|
| 587 |
+
|
| 588 |
+
audio_plus_text_embeds = torch.cat([text_embeds, audio_embeds], dim=-1)
|
| 589 |
+
return self.audio_plus_text_head(audio_plus_text_embeds)
|
| 590 |
+
|
| 591 |
+
def get_video_plus_text_embeds(
|
| 592 |
+
self,
|
| 593 |
+
input_ids: torch.Tensor,
|
| 594 |
+
pixel_values_videos: torch.Tensor,
|
| 595 |
+
attention_mask: torch.Tensor | None = None,
|
| 596 |
+
padding_mask_videos: torch.Tensor | None = None,
|
| 597 |
+
) -> torch.Tensor:
|
| 598 |
+
video_embeds = self.video_model.video_encoder(
|
| 599 |
+
pixel_values_videos=pixel_values_videos,
|
| 600 |
+
padding_mask_videos=padding_mask_videos,
|
| 601 |
+
return_dict=True,
|
| 602 |
+
)
|
| 603 |
+
text_outputs: MaskedLMOutput = self.text_model(
|
| 604 |
+
input_ids=input_ids,
|
| 605 |
+
attention_mask=attention_mask,
|
| 606 |
+
return_dict=True,
|
| 607 |
+
)
|
| 608 |
+
text_embeds = text_outputs.hidden_states[-1][:, 0]
|
| 609 |
+
|
| 610 |
+
video_plus_text_embeds = torch.cat([text_embeds, video_embeds], dim=-1)
|
| 611 |
+
return self.video_plus_text_head(video_plus_text_embeds)
|
| 612 |
+
|
| 613 |
+
@can_return_tuple
|
| 614 |
+
def forward(
|
| 615 |
+
self,
|
| 616 |
+
input_ids: torch.Tensor | None = None,
|
| 617 |
+
pixel_values_videos: torch.Tensor | None = None,
|
| 618 |
+
input_values: torch.Tensor | None = None,
|
| 619 |
+
attention_mask: torch.Tensor | None = None,
|
| 620 |
+
padding_mask_videos: torch.Tensor | None = None,
|
| 621 |
+
padding_mask: torch.Tensor | None = None,
|
| 622 |
+
return_loss=False,
|
| 623 |
+
**kwargs,
|
| 624 |
+
) -> PeAudioVideoOutput:
|
| 625 |
+
if sum([input_ids is not None, pixel_values_videos is not None, input_values is not None]) < 2:
|
| 626 |
+
raise ValueError("At least two of input_ids, pixel_values_videos, or input_values must be provided")
|
| 627 |
+
|
| 628 |
+
if pixel_values_videos is None:
|
| 629 |
+
outputs = self.audio_model(
|
| 630 |
+
input_ids=input_ids,
|
| 631 |
+
input_values=input_values,
|
| 632 |
+
attention_mask=attention_mask,
|
| 633 |
+
padding_mask=padding_mask,
|
| 634 |
+
return_dict=True,
|
| 635 |
+
)
|
| 636 |
+
audio_plus_text_embeds = torch.cat(
|
| 637 |
+
[outputs.audio_outputs.pooler_output, outputs.text_outputs.hidden_states[-1][:, 0]], dim=-1
|
| 638 |
+
)
|
| 639 |
+
audio_plus_text_embeds = self.audio_plus_text_head(audio_plus_text_embeds)
|
| 640 |
+
return PeAudioVideoOutput(audio_plus_text_embeds=audio_plus_text_embeds, **outputs)
|
| 641 |
+
|
| 642 |
+
if input_values is None:
|
| 643 |
+
outputs = self.video_model(
|
| 644 |
+
input_ids=input_ids,
|
| 645 |
+
pixel_values_videos=pixel_values_videos,
|
| 646 |
+
attention_mask=attention_mask,
|
| 647 |
+
padding_mask_videos=padding_mask_videos,
|
| 648 |
+
return_dict=True,
|
| 649 |
+
)
|
| 650 |
+
video_plus_text_embeds = torch.cat(
|
| 651 |
+
[outputs.video_outputs.pooler_output, outputs.text_outputs.hidden_states[-1][:, 0]], dim=-1
|
| 652 |
+
)
|
| 653 |
+
video_plus_text_embeds = self.video_plus_text_head(video_plus_text_embeds)
|
| 654 |
+
return PeAudioVideoOutput(video_plus_text_embeds=video_plus_text_embeds, **outputs)
|
| 655 |
+
|
| 656 |
+
audio_video_outputs = self.audio_video_encoder(
|
| 657 |
+
input_values=input_values,
|
| 658 |
+
pixel_values_videos=pixel_values_videos,
|
| 659 |
+
padding_mask=padding_mask,
|
| 660 |
+
padding_mask_videos=padding_mask_videos,
|
| 661 |
+
**kwargs,
|
| 662 |
+
)
|
| 663 |
+
audio_embeds = audio_video_outputs.audio_model_output.pooler_output
|
| 664 |
+
video_embeds = audio_video_outputs.video_model_output.pooler_output
|
| 665 |
+
audio_video_embeds = audio_video_outputs.pooler_output
|
| 666 |
+
|
| 667 |
+
audio_embeds = self.audio_model.audio_head(audio_embeds)
|
| 668 |
+
video_embeds = self.video_model.video_head(video_embeds)
|
| 669 |
+
audio_video_embeds = self.audio_video_head(audio_video_embeds)
|
| 670 |
+
logits_audio_video = audio_embeds @ video_embeds.T
|
| 671 |
+
logits_audio_video = logits_audio_video * self.audio_video_logit_scale + self.audio_video_logit_bias
|
| 672 |
+
audio_video_loss = self._contrastive_loss(logits_audio_video) if return_loss else None
|
| 673 |
+
|
| 674 |
+
if input_ids is None:
|
| 675 |
+
return PeAudioVideoOutput(
|
| 676 |
+
logits_audio_video=logits_audio_video,
|
| 677 |
+
audio_embeds=audio_embeds,
|
| 678 |
+
video_embeds=video_embeds,
|
| 679 |
+
audio_video_embeds=audio_video_embeds,
|
| 680 |
+
loss=audio_video_loss,
|
| 681 |
+
audio_video_loss=audio_video_loss,
|
| 682 |
+
)
|
| 683 |
+
|
| 684 |
+
kwargs["output_hidden_states"] = True
|
| 685 |
+
text_outputs = self.text_model(input_ids=input_ids, attention_mask=attention_mask, **kwargs)
|
| 686 |
+
text_embeds = text_outputs.hidden_states[-1][:, 0]
|
| 687 |
+
audio_plus_text_embeds = torch.cat([audio_video_outputs.audio_model_output.pooler_output, text_embeds], dim=-1)
|
| 688 |
+
video_plus_text_embeds = torch.cat([audio_video_outputs.video_model_output.pooler_output, text_embeds], dim=-1)
|
| 689 |
+
|
| 690 |
+
text_audio_embeds = self.audio_model.text_audio_head(text_embeds)
|
| 691 |
+
text_video_embeds = self.video_model.text_video_head(text_embeds)
|
| 692 |
+
text_audio_video_embeds = self.text_audio_video_head(text_embeds)
|
| 693 |
+
audio_plus_text_embeds = self.audio_plus_text_head(audio_plus_text_embeds)
|
| 694 |
+
video_plus_text_embeds = self.video_plus_text_head(video_plus_text_embeds)
|
| 695 |
+
|
| 696 |
+
logits_audio_text = audio_embeds @ text_audio_embeds.T
|
| 697 |
+
logits_video_text = video_embeds @ text_video_embeds.T
|
| 698 |
+
logits_audio_video_text = audio_video_embeds @ text_audio_video_embeds.T
|
| 699 |
+
|
| 700 |
+
logits_audio_plus_text_video = audio_plus_text_embeds @ video_embeds.T
|
| 701 |
+
logits_video_plus_text_audio = video_plus_text_embeds @ audio_embeds.T
|
| 702 |
+
|
| 703 |
+
logits_audio_text = (
|
| 704 |
+
logits_audio_text * self.audio_model.text_audio_logit_scale + self.audio_model.text_audio_logit_bias
|
| 705 |
+
)
|
| 706 |
+
logits_video_text = (
|
| 707 |
+
logits_video_text * self.video_model.text_video_logit_scale + self.video_model.text_video_logit_bias
|
| 708 |
+
)
|
| 709 |
+
logits_audio_video_text = (
|
| 710 |
+
logits_audio_video_text * self.text_audio_video_logit_scale + self.text_audio_video_logit_bias
|
| 711 |
+
)
|
| 712 |
+
|
| 713 |
+
logits_audio_plus_text_video = (
|
| 714 |
+
logits_audio_plus_text_video * self.audio_plus_text_logit_scale + self.audio_plus_text_logit_bias
|
| 715 |
+
)
|
| 716 |
+
logits_video_plus_text_audio = (
|
| 717 |
+
logits_video_plus_text_audio * self.video_plus_text_logit_scale + self.video_plus_text_logit_bias
|
| 718 |
+
)
|
| 719 |
+
|
| 720 |
+
if return_loss:
|
| 721 |
+
audio_text_loss = self._contrastive_loss(logits_audio_text)
|
| 722 |
+
video_text_loss = self._contrastive_loss(logits_video_text)
|
| 723 |
+
audio_video_text_loss = self._contrastive_loss(logits_audio_video_text)
|
| 724 |
+
audio_plus_text_video_loss = self._contrastive_loss(logits_audio_plus_text_video)
|
| 725 |
+
video_plus_text_audio_loss = self._contrastive_loss(logits_video_plus_text_audio)
|
| 726 |
+
loss = (
|
| 727 |
+
audio_video_text_loss
|
| 728 |
+
+ audio_text_loss
|
| 729 |
+
+ video_text_loss
|
| 730 |
+
+ audio_video_loss
|
| 731 |
+
+ audio_plus_text_video_loss
|
| 732 |
+
+ video_plus_text_audio_loss
|
| 733 |
+
)
|
| 734 |
+
|
| 735 |
+
return PeAudioVideoOutput(
|
| 736 |
+
# embeddings
|
| 737 |
+
audio_embeds=audio_embeds,
|
| 738 |
+
video_embeds=video_embeds,
|
| 739 |
+
audio_video_embeds=audio_video_embeds,
|
| 740 |
+
text_audio_embeds=text_audio_embeds,
|
| 741 |
+
text_video_embeds=text_video_embeds,
|
| 742 |
+
text_audio_video_embeds=text_audio_video_embeds,
|
| 743 |
+
audio_plus_text_embeds=audio_plus_text_embeds,
|
| 744 |
+
video_plus_text_embeds=video_plus_text_embeds,
|
| 745 |
+
# model outputs
|
| 746 |
+
text_outputs=text_outputs,
|
| 747 |
+
audio_outputs=audio_video_outputs.audio_model_output,
|
| 748 |
+
video_outputs=audio_video_outputs.video_model_output,
|
| 749 |
+
audio_video_outputs=audio_video_outputs,
|
| 750 |
+
# logits
|
| 751 |
+
logits_audio_text=logits_audio_text,
|
| 752 |
+
logits_video_text=logits_video_text,
|
| 753 |
+
logits_audio_video=logits_audio_video,
|
| 754 |
+
logits_audio_video_text=logits_audio_video_text,
|
| 755 |
+
logits_audio_plus_text_video=logits_audio_plus_text_video,
|
| 756 |
+
logits_video_plus_text_audio=logits_video_plus_text_audio,
|
| 757 |
+
# losses
|
| 758 |
+
audio_text_loss=audio_text_loss if return_loss else None,
|
| 759 |
+
video_text_loss=video_text_loss if return_loss else None,
|
| 760 |
+
audio_video_loss=audio_video_loss if return_loss else None,
|
| 761 |
+
audio_video_text_loss=audio_video_text_loss if return_loss else None,
|
| 762 |
+
audio_plus_text_video_loss=audio_plus_text_video_loss if return_loss else None,
|
| 763 |
+
video_plus_text_audio_loss=video_plus_text_audio_loss if return_loss else None,
|
| 764 |
+
loss=loss if return_loss else None,
|
| 765 |
+
)
|
| 766 |
+
|
| 767 |
+
|
| 768 |
+
__all__ = [
|
| 769 |
+
"PeAudioVideoModel",
|
| 770 |
+
"PeAudioVideoEncoder",
|
| 771 |
+
]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_audio_video/processing_pe_audio_video.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 the HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from ...processing_utils import ProcessorMixin
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class PeAudioVideoProcessor(ProcessorMixin):
|
| 18 |
+
attributes = ["feature_extractor", "video_processor", "tokenizer"]
|
| 19 |
+
feature_extractor_class = "PeAudioFeatureExtractor"
|
| 20 |
+
tokenizer_class = "AutoTokenizer"
|
| 21 |
+
video_processor_class = "PeVideoVideoProcessor"
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
__all__ = ["PeAudioVideoProcessor"]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_video/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 the HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_pe_video import *
|
| 22 |
+
from .modeling_pe_video import *
|
| 23 |
+
from .processing_pe_video import *
|
| 24 |
+
from .video_processing_pe_video import *
|
| 25 |
+
else:
|
| 26 |
+
import sys
|
| 27 |
+
|
| 28 |
+
_file = globals()["__file__"]
|
| 29 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
miniconda3/envs/ladir/lib/python3.10/site-pack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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 the HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from ...configuration_utils import PreTrainedConfig, PretrainedConfig
|
| 16 |
+
from ...modeling_rope_utils import RopeParameters
|
| 17 |
+
from ...utils import logging
|
| 18 |
+
from ..auto import CONFIG_MAPPING, AutoConfig
|
| 19 |
+
from ..timm_wrapper import TimmWrapperConfig
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
logger = logging.get_logger(__name__)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class PeVideoEncoderConfig(PreTrainedConfig):
|
| 26 |
+
r"""
|
| 27 |
+
This is the configuration class to store the configuration of a [`PeVideoEncoder`]. It is used to instantiate a
|
| 28 |
+
PeVideoEncoder model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 29 |
+
with the defaults will yield a similar configuration to that of pe-av-large.
|
| 30 |
+
e.g. [facebook/pe-av-large](https://huggingface.co/facebook/pe-av-large)
|
| 31 |
+
|
| 32 |
+
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
|
| 33 |
+
documentation from [`PreTrainedConfig`] for more information.
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
vision_config (`Union[PreTrainedConfig, dict]`, *optional*):
|
| 38 |
+
Configuration for the vision backbone used to extract frame embeddings. If a dictionary is provided, it is
|
| 39 |
+
used to instantiate a [`~transformers.TimmWrapperConfig`] with the PE default arguments.
|
| 40 |
+
hidden_size (`int`, *optional*, defaults to 1792):
|
| 41 |
+
Dimension of the hidden representations.
|
| 42 |
+
intermediate_size (`int`, *optional*, defaults to 4800):
|
| 43 |
+
Dimension of the feedforward layers in the Transformer blocks.
|
| 44 |
+
num_hidden_layers (`int`, *optional*, defaults to 6):
|
| 45 |
+
Number of Transformer encoder blocks.
|
| 46 |
+
num_attention_heads (`int`, *optional*, defaults to 14):
|
| 47 |
+
Number of attention heads used in each attention layer.
|
| 48 |
+
num_key_value_heads (`int`, *optional*):
|
| 49 |
+
Number of key and value heads for grouped-query attention. If unset, this defaults to `num_attention_heads`.
|
| 50 |
+
head_dim (`int`, *optional*, defaults to 128):
|
| 51 |
+
Dimension of each attention head for query, key, and value projections.
|
| 52 |
+
hidden_act (`str`, *optional*, defaults to `"silu"`):
|
| 53 |
+
The non-linear activation function (function or string) in the Transformer blocks.
|
| 54 |
+
max_position_embeddings (`int`, *optional*, defaults to 10000):
|
| 55 |
+
Maximum sequence length supported by the rotary position embeddings.
|
| 56 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 57 |
+
Standard deviation of the truncated normal initializer for weight matrices.
|
| 58 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-05):
|
| 59 |
+
Epsilon used by the RMS normalization layers.
|
| 60 |
+
rope_parameters (`Union[RopeParameters, dict]`, *optional*, defaults to `{'rope_theta': 20000}`):
|
| 61 |
+
Parameters for the rotary position embeddings, such as the base `rope_theta`.
|
| 62 |
+
attention_bias (`bool`, *optional*, defaults to `False`):
|
| 63 |
+
Whether to use bias terms in the query, key, value, and output projections.
|
| 64 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 65 |
+
Dropout ratio applied to attention probabilities.
|
| 66 |
+
|
| 67 |
+
```python
|
| 68 |
+
>>> from transformers import PeAudioEncoder, PeAudioEncoderConfig
|
| 69 |
+
|
| 70 |
+
>>> # Initializing a PeAudioEncoder style configuration
|
| 71 |
+
>>> configuration = PeAudioEncoderConfig()
|
| 72 |
+
|
| 73 |
+
>>> # Initializing a model from the pe-av-large style configuration
|
| 74 |
+
>>> model = PeAudioEncoder(configuration)
|
| 75 |
+
|
| 76 |
+
>>> # Accessing the model configuration
|
| 77 |
+
>>> configuration = model.config
|
| 78 |
+
```"""
|
| 79 |
+
|
| 80 |
+
model_type = "pe_video_encoder"
|
| 81 |
+
sub_configs = {"vision_config": TimmWrapperConfig}
|
| 82 |
+
base_config_key = "audio_video_config"
|
| 83 |
+
|
| 84 |
+
_default_vision_config_kwargs = {
|
| 85 |
+
"architecture": "vit_pe_core_large_patch14_336",
|
| 86 |
+
"do_pooling": True,
|
| 87 |
+
"num_classes": 1024,
|
| 88 |
+
"global_pool": "map",
|
| 89 |
+
"initializer_range": 0.02,
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
def __init__(
|
| 93 |
+
self,
|
| 94 |
+
vision_config: dict | PreTrainedConfig | None = None,
|
| 95 |
+
hidden_size: int | None = 1792,
|
| 96 |
+
intermediate_size: int | None = 4800,
|
| 97 |
+
num_hidden_layers: int | None = 6,
|
| 98 |
+
num_attention_heads: int | None = 14,
|
| 99 |
+
num_key_value_heads: int | None = None,
|
| 100 |
+
head_dim: int | None = 128,
|
| 101 |
+
hidden_act: str | None = "silu",
|
| 102 |
+
max_position_embeddings: int | None = 10000,
|
| 103 |
+
initializer_range: float | None = 0.02,
|
| 104 |
+
rms_norm_eps: float | None = 1e-5,
|
| 105 |
+
rope_parameters: RopeParameters | dict | None = {"rope_theta": 20000},
|
| 106 |
+
attention_bias: bool | None = False,
|
| 107 |
+
attention_dropout: float | None = 0.0,
|
| 108 |
+
**kwargs,
|
| 109 |
+
):
|
| 110 |
+
self.hidden_size = hidden_size
|
| 111 |
+
self.intermediate_size = intermediate_size
|
| 112 |
+
self.num_hidden_layers = num_hidden_layers
|
| 113 |
+
self.num_attention_heads = num_attention_heads
|
| 114 |
+
|
| 115 |
+
# for backward compatibility
|
| 116 |
+
if num_key_value_heads is None:
|
| 117 |
+
num_key_value_heads = num_attention_heads
|
| 118 |
+
|
| 119 |
+
self.num_key_value_heads = num_key_value_heads
|
| 120 |
+
self.head_dim = head_dim
|
| 121 |
+
self.hidden_act = hidden_act
|
| 122 |
+
self.max_position_embeddings = max_position_embeddings
|
| 123 |
+
self.initializer_range = initializer_range
|
| 124 |
+
self.rms_norm_eps = rms_norm_eps
|
| 125 |
+
self.rope_parameters = rope_parameters
|
| 126 |
+
self.attention_bias = attention_bias
|
| 127 |
+
self.attention_dropout = attention_dropout
|
| 128 |
+
|
| 129 |
+
if isinstance(vision_config, dict):
|
| 130 |
+
vision_config["model_type"] = vision_config.get("model_type", "timm_wrapper")
|
| 131 |
+
vision_config = CONFIG_MAPPING[vision_config["model_type"]].from_dict(
|
| 132 |
+
{**self._default_vision_config_kwargs, **vision_config}
|
| 133 |
+
)
|
| 134 |
+
elif vision_config is None:
|
| 135 |
+
vision_config = CONFIG_MAPPING["timm_wrapper"].from_dict(self._default_vision_config_kwargs)
|
| 136 |
+
|
| 137 |
+
self.vision_config = vision_config
|
| 138 |
+
|
| 139 |
+
super().__init__(**kwargs)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class PeVideoConfig(PretrainedConfig):
|
| 143 |
+
r"""
|
| 144 |
+
This is the configuration class to store the configuration of a [`PeVideoModel`]. It is used to instantiate a
|
| 145 |
+
PeVideoModel model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 146 |
+
with the defaults will yield a similar configuration to that of pe-av-large.
|
| 147 |
+
e.g. [facebook/pe-av-large](https://huggingface.co/facebook/pe-av-large)
|
| 148 |
+
|
| 149 |
+
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
|
| 150 |
+
documentation from [`PreTrainedConfig`] for more information.
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
Args:
|
| 154 |
+
text_config (`dict` or `PreTrainedConfig`, *optional*):
|
| 155 |
+
Configuration for the text model component.
|
| 156 |
+
video_config (`dict` or `PreTrainedConfig`, *optional*):
|
| 157 |
+
Configuration for the video encoder component.
|
| 158 |
+
|
| 159 |
+
```python
|
| 160 |
+
>>> from transformers import PeVideoModel, PeVideoConfig
|
| 161 |
+
|
| 162 |
+
>>> # Initializing a PeVideoModel style configuration
|
| 163 |
+
>>> configuration = PeVideoConfig()
|
| 164 |
+
|
| 165 |
+
>>> # Initializing a model from the pe-av-large style configuration
|
| 166 |
+
>>> model = PeVideoModel(configuration)
|
| 167 |
+
|
| 168 |
+
>>> # Accessing the model configuration
|
| 169 |
+
>>> configuration = model.config
|
| 170 |
+
```"""
|
| 171 |
+
|
| 172 |
+
model_type = "pe_video"
|
| 173 |
+
sub_configs = {"text_config": AutoConfig, "video_config": PeVideoEncoderConfig}
|
| 174 |
+
base_config_key = "audio_video_config"
|
| 175 |
+
|
| 176 |
+
_default_text_config_kwargs = {
|
| 177 |
+
"model_type": "modernbert",
|
| 178 |
+
"hidden_size": 1024,
|
| 179 |
+
"intermediate_size": 2624,
|
| 180 |
+
"num_hidden_layers": 22,
|
| 181 |
+
"num_attention_heads": 16,
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
def __init__(
|
| 185 |
+
self,
|
| 186 |
+
text_config=None,
|
| 187 |
+
video_config=None,
|
| 188 |
+
**kwargs,
|
| 189 |
+
):
|
| 190 |
+
if isinstance(text_config, dict):
|
| 191 |
+
text_config["model_type"] = text_config.get("model_type", "modernbert")
|
| 192 |
+
text_config = CONFIG_MAPPING[text_config["model_type"]](
|
| 193 |
+
**{**self._default_text_config_kwargs, **text_config}
|
| 194 |
+
)
|
| 195 |
+
elif text_config is None:
|
| 196 |
+
text_config = CONFIG_MAPPING["modernbert"](**self._default_text_config_kwargs)
|
| 197 |
+
|
| 198 |
+
if isinstance(video_config, dict):
|
| 199 |
+
video_config = PeVideoEncoderConfig(**video_config)
|
| 200 |
+
elif video_config is None:
|
| 201 |
+
video_config = PeVideoEncoderConfig()
|
| 202 |
+
|
| 203 |
+
self.text_config = text_config
|
| 204 |
+
self.video_config = video_config
|
| 205 |
+
|
| 206 |
+
super().__init__(**kwargs)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
__all__ = ["PeVideoEncoderConfig", "PeVideoConfig"]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_video/modeling_pe_video.py
ADDED
|
@@ -0,0 +1,652 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/pe_video/modular_pe_video.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_pe_video.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2025 the HuggingFace Inc. team. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
from collections.abc import Callable
|
| 21 |
+
from dataclasses import dataclass
|
| 22 |
+
from typing import Any, Optional
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
import torch.nn as nn
|
| 26 |
+
import torch.nn.functional as F
|
| 27 |
+
|
| 28 |
+
from ... import initialization as init
|
| 29 |
+
from ...activations import ACT2FN
|
| 30 |
+
from ...cache_utils import Cache
|
| 31 |
+
from ...integrations import use_kernel_forward_from_hub, use_kernelized_func
|
| 32 |
+
from ...masking_utils import create_bidirectional_mask
|
| 33 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 34 |
+
from ...modeling_outputs import BaseModelOutputWithPooling, MaskedLMOutput
|
| 35 |
+
from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
| 36 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 37 |
+
from ...processing_utils import Unpack
|
| 38 |
+
from ...utils import ModelOutput, TransformersKwargs, auto_docstring, can_return_tuple
|
| 39 |
+
from ...utils.generic import maybe_autocast, merge_with_config_defaults
|
| 40 |
+
from ...utils.output_capturing import capture_outputs
|
| 41 |
+
from ..auto import AutoModel, AutoModelForImageClassification
|
| 42 |
+
from .configuration_pe_video import PeVideoConfig, PeVideoEncoderConfig
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# TODO: not sure about the typing for text_model_output
|
| 46 |
+
@dataclass
|
| 47 |
+
# @auto_docstring
|
| 48 |
+
class PeVideoOutput(ModelOutput):
|
| 49 |
+
loss: torch.FloatTensor | None = None
|
| 50 |
+
logits_video_text: torch.FloatTensor | None = None
|
| 51 |
+
text_video_embeds: torch.FloatTensor | None = None
|
| 52 |
+
video_embeds: torch.FloatTensor | None = None
|
| 53 |
+
text_outputs: BaseModelOutputWithPooling = None
|
| 54 |
+
video_outputs: BaseModelOutputWithPooling = None
|
| 55 |
+
|
| 56 |
+
def to_tuple(self) -> tuple[Any]:
|
| 57 |
+
return tuple(
|
| 58 |
+
self[k] if k not in ["text_outputs", "video_outputs"] else getattr(self, k).to_tuple() for k in self.keys()
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class PeVideoContrastiveHead(nn.Module):
|
| 63 |
+
def __init__(
|
| 64 |
+
self,
|
| 65 |
+
in_dim: int,
|
| 66 |
+
out_dim: int,
|
| 67 |
+
) -> None:
|
| 68 |
+
super().__init__()
|
| 69 |
+
self.layer_norm = nn.LayerNorm(normalized_shape=in_dim, eps=1e-6)
|
| 70 |
+
self.proj = nn.Linear(in_dim, out_dim, bias=False)
|
| 71 |
+
|
| 72 |
+
def forward(self, x: torch.Tensor) -> torch.FloatTensor:
|
| 73 |
+
return self.proj(self.layer_norm(x))
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class PeVideoMaskedGroupNorm(nn.GroupNorm):
|
| 77 |
+
def forward(self, x, padding_mask=None):
|
| 78 |
+
if padding_mask is None:
|
| 79 |
+
return super().forward(x)
|
| 80 |
+
|
| 81 |
+
batch_size, hidden_size, seq_len = x.shape
|
| 82 |
+
group_size = hidden_size // self.num_groups
|
| 83 |
+
grouped_shape = (batch_size, -1, group_size, seq_len)
|
| 84 |
+
|
| 85 |
+
x_grouped = x.view(grouped_shape)
|
| 86 |
+
padding_mask_grouped = padding_mask.reshape(grouped_shape).bool()
|
| 87 |
+
|
| 88 |
+
mean = torch.masked.mean(x_grouped, mask=padding_mask_grouped, dim=(2, 3), keepdim=True)
|
| 89 |
+
var = torch.masked.var(x_grouped, mask=padding_mask_grouped, dim=(2, 3), keepdim=True, unbiased=False)
|
| 90 |
+
|
| 91 |
+
x_norm = (x_grouped - mean) / torch.sqrt(var + self.eps)
|
| 92 |
+
x_norm = x_norm.view(x.shape)
|
| 93 |
+
|
| 94 |
+
if self.affine:
|
| 95 |
+
x_norm = x_norm * self.weight.view(1, -1, 1) + self.bias.view(1, -1, 1)
|
| 96 |
+
|
| 97 |
+
return x_norm * padding_mask
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class PeVideoConvBlock1d(nn.Module):
|
| 101 |
+
def __init__(self, config):
|
| 102 |
+
super().__init__()
|
| 103 |
+
self.groupnorm = PeVideoMaskedGroupNorm(num_groups=1, num_channels=config.hidden_size)
|
| 104 |
+
self.activation = nn.SiLU()
|
| 105 |
+
self.project = nn.Conv1d(
|
| 106 |
+
in_channels=config.hidden_size,
|
| 107 |
+
out_channels=config.hidden_size,
|
| 108 |
+
kernel_size=3,
|
| 109 |
+
padding="same",
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
def forward(self, x, padding_mask=None):
|
| 113 |
+
x = self.groupnorm(x, padding_mask=padding_mask)
|
| 114 |
+
x = self.activation(x)
|
| 115 |
+
return self.project(x)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class PeVideoResnetBlock1d(nn.Module):
|
| 119 |
+
def __init__(self, config):
|
| 120 |
+
super().__init__()
|
| 121 |
+
self.block1 = PeVideoConvBlock1d(config)
|
| 122 |
+
self.block2 = PeVideoConvBlock1d(config)
|
| 123 |
+
|
| 124 |
+
def forward(self, hidden_states, padding_mask=None):
|
| 125 |
+
"""
|
| 126 |
+
Args:
|
| 127 |
+
hidden_states: (batch_size, seq_len, hidden_size)
|
| 128 |
+
padding_mask: (batch_size, seq_len)
|
| 129 |
+
Returns:
|
| 130 |
+
hidden_states: (batch_size, seq_len, hidden_size)
|
| 131 |
+
"""
|
| 132 |
+
# transpose for convolutions
|
| 133 |
+
# (batch_size, seq_len, hidden_size) -> (batch_size, hidden_size, seq_len)
|
| 134 |
+
hidden_states = hidden_states.transpose(1, 2)
|
| 135 |
+
|
| 136 |
+
if padding_mask is not None:
|
| 137 |
+
padding_mask = padding_mask.unsqueeze(1).expand_as(hidden_states)
|
| 138 |
+
|
| 139 |
+
residual = hidden_states
|
| 140 |
+
hidden_states = self.block1(hidden_states, padding_mask=padding_mask)
|
| 141 |
+
hidden_states = self.block2(hidden_states, padding_mask=padding_mask)
|
| 142 |
+
hidden_states = residual + hidden_states
|
| 143 |
+
|
| 144 |
+
return hidden_states.transpose(1, 2)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class PeVideoEncoderPatchEmbedder(nn.Module):
|
| 148 |
+
def __init__(self, config):
|
| 149 |
+
super().__init__()
|
| 150 |
+
self.resnet_block = PeVideoResnetBlock1d(config)
|
| 151 |
+
self.class_embedding = nn.Parameter(torch.randn(1, 1, config.hidden_size))
|
| 152 |
+
|
| 153 |
+
def forward(self, inputs_embeds, padding_mask=None):
|
| 154 |
+
# Embedding step: prepend class token and run the ResNet block.
|
| 155 |
+
hidden_states = torch.cat(
|
| 156 |
+
[self.class_embedding.expand(inputs_embeds.size(0), -1, -1), inputs_embeds],
|
| 157 |
+
dim=1,
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
if padding_mask is not None:
|
| 161 |
+
# TODO: any reason why we take padding_mask[0] and not just 1?
|
| 162 |
+
padding_mask = torch.cat([padding_mask[:, [0]], padding_mask], dim=1)
|
| 163 |
+
|
| 164 |
+
hidden_states = self.resnet_block(hidden_states, padding_mask=padding_mask)
|
| 165 |
+
return hidden_states, padding_mask
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class PeVideoEncoderEmbedder(nn.Module):
|
| 169 |
+
def __init__(self, config: PeVideoEncoderConfig):
|
| 170 |
+
super().__init__()
|
| 171 |
+
self.vision_model = AutoModelForImageClassification.from_config(config.vision_config)
|
| 172 |
+
self.proj = nn.Linear(config.vision_config.num_labels, config.hidden_size, bias=False)
|
| 173 |
+
self.data_proj = nn.Linear(config.hidden_size, config.hidden_size)
|
| 174 |
+
|
| 175 |
+
def forward(
|
| 176 |
+
self,
|
| 177 |
+
pixel_values_videos: torch.Tensor,
|
| 178 |
+
padding_mask: torch.Tensor | None = None,
|
| 179 |
+
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
| 180 |
+
input_shape = pixel_values_videos.shape
|
| 181 |
+
|
| 182 |
+
pixel_values_videos = pixel_values_videos.view(-1, *input_shape[2:])
|
| 183 |
+
vision_encoder_outputs = self.vision_model(pixel_values_videos)
|
| 184 |
+
|
| 185 |
+
logits = vision_encoder_outputs.logits.view(*input_shape[:2], -1)
|
| 186 |
+
logits = F.normalize(logits, dim=-1)
|
| 187 |
+
|
| 188 |
+
vision_features = self.proj(logits)
|
| 189 |
+
inputs_embeds = self.data_proj(vision_features)
|
| 190 |
+
|
| 191 |
+
return inputs_embeds, padding_mask
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 195 |
+
"""
|
| 196 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 197 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 198 |
+
"""
|
| 199 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 200 |
+
if n_rep == 1:
|
| 201 |
+
return hidden_states
|
| 202 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 203 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def eager_attention_forward(
|
| 207 |
+
module: nn.Module,
|
| 208 |
+
query: torch.Tensor,
|
| 209 |
+
key: torch.Tensor,
|
| 210 |
+
value: torch.Tensor,
|
| 211 |
+
attention_mask: torch.Tensor | None,
|
| 212 |
+
scaling: float,
|
| 213 |
+
dropout: float = 0.0,
|
| 214 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 215 |
+
):
|
| 216 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 217 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 218 |
+
|
| 219 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 220 |
+
if attention_mask is not None:
|
| 221 |
+
attn_weights = attn_weights + attention_mask
|
| 222 |
+
|
| 223 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 224 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 225 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 226 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 227 |
+
|
| 228 |
+
return attn_output, attn_weights
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def stack_freqs(cos: torch.Tensor, sin: torch.Tensor):
|
| 232 |
+
dim = cos.size(-1)
|
| 233 |
+
cos = cos.narrow(-1, 0, dim // 2)
|
| 234 |
+
sin = sin.narrow(-1, 0, dim // 2)
|
| 235 |
+
freqs_cis = torch.stack((cos, -sin, sin, cos), dim=-1).view(*cos.size(), 2, 2)
|
| 236 |
+
return freqs_cis
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
|
| 240 |
+
freqs_cis = stack_freqs(cos, sin)
|
| 241 |
+
freqs_cis = freqs_cis.unsqueeze(unsqueeze_dim)
|
| 242 |
+
q_ = q.reshape(*q.shape[:-1], -1, 1, 2)
|
| 243 |
+
k_ = k.reshape(*k.shape[:-1], -1, 1, 2)
|
| 244 |
+
return (q_ * freqs_cis).sum(5).flatten(3), (k_ * freqs_cis).sum(5).flatten(3)
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
@use_kernel_forward_from_hub("RMSNorm")
|
| 248 |
+
class PeVideoEncoderRMSNorm(nn.Module):
|
| 249 |
+
def __init__(self, hidden_size, eps: float = 1e-6) -> None:
|
| 250 |
+
"""
|
| 251 |
+
PeVideoEncoderRMSNorm is equivalent to T5LayerNorm
|
| 252 |
+
"""
|
| 253 |
+
super().__init__()
|
| 254 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 255 |
+
self.variance_epsilon = eps
|
| 256 |
+
|
| 257 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 258 |
+
input_dtype = hidden_states.dtype
|
| 259 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 260 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 261 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 262 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 263 |
+
|
| 264 |
+
def extra_repr(self):
|
| 265 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
@use_kernelized_func(apply_rotary_pos_emb)
|
| 269 |
+
class PeVideoEncoderAttention(nn.Module):
|
| 270 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 271 |
+
|
| 272 |
+
def __init__(self, config, layer_idx):
|
| 273 |
+
super().__init__()
|
| 274 |
+
self.layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None
|
| 275 |
+
self.config = config
|
| 276 |
+
self.layer_idx = layer_idx
|
| 277 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 278 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 279 |
+
self.scaling = self.head_dim**-0.5
|
| 280 |
+
self.attention_dropout = config.attention_dropout
|
| 281 |
+
self.is_causal = False
|
| 282 |
+
|
| 283 |
+
self.q_proj = nn.Linear(
|
| 284 |
+
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
| 285 |
+
)
|
| 286 |
+
self.k_proj = nn.Linear(
|
| 287 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 288 |
+
)
|
| 289 |
+
self.v_proj = nn.Linear(
|
| 290 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 291 |
+
)
|
| 292 |
+
self.o_proj = nn.Linear(
|
| 293 |
+
config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
|
| 294 |
+
)
|
| 295 |
+
self.q_norm = PeVideoEncoderRMSNorm(
|
| 296 |
+
self.head_dim, eps=config.rms_norm_eps
|
| 297 |
+
) # unlike olmo, only on the head dim!
|
| 298 |
+
self.k_norm = PeVideoEncoderRMSNorm(
|
| 299 |
+
self.head_dim, eps=config.rms_norm_eps
|
| 300 |
+
) # thus post q_norm does not need reshape
|
| 301 |
+
|
| 302 |
+
def forward(
|
| 303 |
+
self,
|
| 304 |
+
hidden_states: torch.Tensor,
|
| 305 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 306 |
+
attention_mask: torch.Tensor | None = None,
|
| 307 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 308 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 309 |
+
input_shape = hidden_states.shape[:-1]
|
| 310 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 311 |
+
|
| 312 |
+
query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
|
| 313 |
+
key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
|
| 314 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 315 |
+
|
| 316 |
+
cos, sin = position_embeddings
|
| 317 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 318 |
+
|
| 319 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 320 |
+
self.config._attn_implementation, eager_attention_forward
|
| 321 |
+
)
|
| 322 |
+
|
| 323 |
+
attn_output, attn_weights = attention_interface(
|
| 324 |
+
self,
|
| 325 |
+
query_states,
|
| 326 |
+
key_states,
|
| 327 |
+
value_states,
|
| 328 |
+
attention_mask,
|
| 329 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 330 |
+
scaling=self.scaling,
|
| 331 |
+
**kwargs,
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 335 |
+
attn_output = self.o_proj(attn_output)
|
| 336 |
+
return attn_output, attn_weights
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
class PeVideoEncoderMLP(nn.Module):
|
| 340 |
+
def __init__(self, config):
|
| 341 |
+
super().__init__()
|
| 342 |
+
self.config = config
|
| 343 |
+
self.hidden_size = config.hidden_size
|
| 344 |
+
self.intermediate_size = config.intermediate_size
|
| 345 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 346 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 347 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
| 348 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 349 |
+
|
| 350 |
+
def forward(self, x):
|
| 351 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 352 |
+
return down_proj
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
class PeVideoEncoderLayer(GradientCheckpointingLayer):
|
| 356 |
+
def __init__(self, config, layer_idx):
|
| 357 |
+
super().__init__()
|
| 358 |
+
self.hidden_size = config.hidden_size
|
| 359 |
+
|
| 360 |
+
self.self_attn = PeVideoEncoderAttention(config=config, layer_idx=layer_idx)
|
| 361 |
+
|
| 362 |
+
self.mlp = PeVideoEncoderMLP(config)
|
| 363 |
+
self.input_layernorm = PeVideoEncoderRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 364 |
+
self.post_attention_layernorm = PeVideoEncoderRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 365 |
+
|
| 366 |
+
def forward(
|
| 367 |
+
self,
|
| 368 |
+
hidden_states: torch.Tensor,
|
| 369 |
+
attention_mask: torch.Tensor | None = None,
|
| 370 |
+
position_ids: torch.LongTensor | None = None,
|
| 371 |
+
past_key_values: Cache | None = None,
|
| 372 |
+
use_cache: bool | None = False,
|
| 373 |
+
cache_position: torch.LongTensor | None = None,
|
| 374 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 375 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 376 |
+
) -> torch.Tensor:
|
| 377 |
+
residual = hidden_states
|
| 378 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 379 |
+
# Self Attention
|
| 380 |
+
hidden_states, _ = self.self_attn(
|
| 381 |
+
hidden_states=hidden_states,
|
| 382 |
+
attention_mask=attention_mask,
|
| 383 |
+
position_ids=position_ids,
|
| 384 |
+
past_key_values=past_key_values,
|
| 385 |
+
use_cache=use_cache,
|
| 386 |
+
cache_position=cache_position,
|
| 387 |
+
position_embeddings=position_embeddings,
|
| 388 |
+
**kwargs,
|
| 389 |
+
)
|
| 390 |
+
hidden_states = residual + hidden_states
|
| 391 |
+
|
| 392 |
+
# Fully Connected
|
| 393 |
+
residual = hidden_states
|
| 394 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 395 |
+
hidden_states = self.mlp(hidden_states)
|
| 396 |
+
hidden_states = residual + hidden_states
|
| 397 |
+
return hidden_states
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
@auto_docstring
|
| 401 |
+
class PeVideoPreTrainedModel(PreTrainedModel):
|
| 402 |
+
config: PeVideoConfig
|
| 403 |
+
base_model_prefix = "video_model"
|
| 404 |
+
supports_gradient_checkpointing = True
|
| 405 |
+
_no_split_modules = ["PeVideoEncoderLayer"]
|
| 406 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 407 |
+
_supports_flash_attn = True
|
| 408 |
+
_supports_sdpa = True
|
| 409 |
+
_supports_flex_attn = True
|
| 410 |
+
|
| 411 |
+
_can_compile_fullgraph = True
|
| 412 |
+
_supports_attention_backend = True
|
| 413 |
+
_can_record_outputs = {
|
| 414 |
+
"hidden_states": PeVideoEncoderLayer,
|
| 415 |
+
"attentions": PeVideoEncoderAttention,
|
| 416 |
+
}
|
| 417 |
+
main_input_name = "pixel_values_videos"
|
| 418 |
+
|
| 419 |
+
def _init_weights(self, module):
|
| 420 |
+
super()._init_weights(module)
|
| 421 |
+
|
| 422 |
+
if hasattr(self.config, "initializer_range"):
|
| 423 |
+
std = self.config.initializer_range
|
| 424 |
+
else:
|
| 425 |
+
# 0.02 is the standard default value across the library
|
| 426 |
+
std = getattr(self.config.get_text_config(), "initializer_range", 0.02)
|
| 427 |
+
|
| 428 |
+
if isinstance(module, PeVideoEncoderPatchEmbedder):
|
| 429 |
+
embed_dim = module.class_embedding.shape[-1]
|
| 430 |
+
init.normal_(module.class_embedding, mean=0.0, std=embed_dim**-0.5 * std)
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
class PeVideoEncoderRotaryEmbedding(nn.Module):
|
| 434 |
+
inv_freq: torch.Tensor # fix linting for `register_buffer`
|
| 435 |
+
|
| 436 |
+
def __init__(self, config: PeVideoEncoderConfig, device=None):
|
| 437 |
+
super().__init__()
|
| 438 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 439 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 440 |
+
|
| 441 |
+
self.config = config
|
| 442 |
+
|
| 443 |
+
self.rope_type = self.config.rope_parameters["rope_type"]
|
| 444 |
+
rope_init_fn: Callable = self.compute_default_rope_parameters
|
| 445 |
+
if self.rope_type != "default":
|
| 446 |
+
rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 447 |
+
inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
|
| 448 |
+
|
| 449 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 450 |
+
self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
|
| 451 |
+
|
| 452 |
+
@staticmethod
|
| 453 |
+
def compute_default_rope_parameters(
|
| 454 |
+
config: PeVideoEncoderConfig | None = None,
|
| 455 |
+
device: Optional["torch.device"] = None,
|
| 456 |
+
seq_len: int | None = None,
|
| 457 |
+
) -> tuple["torch.Tensor", float]:
|
| 458 |
+
"""
|
| 459 |
+
Computes the inverse frequencies according to the original RoPE implementation
|
| 460 |
+
Args:
|
| 461 |
+
config ([`~transformers.PreTrainedConfig`]):
|
| 462 |
+
The model configuration.
|
| 463 |
+
device (`torch.device`):
|
| 464 |
+
The device to use for initialization of the inverse frequencies.
|
| 465 |
+
seq_len (`int`, *optional*):
|
| 466 |
+
The current sequence length. Unused for this type of RoPE.
|
| 467 |
+
Returns:
|
| 468 |
+
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
|
| 469 |
+
post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
|
| 470 |
+
"""
|
| 471 |
+
base = config.rope_parameters["rope_theta"]
|
| 472 |
+
dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
|
| 473 |
+
|
| 474 |
+
attention_factor = 1.0 # Unused in this type of RoPE
|
| 475 |
+
|
| 476 |
+
# Compute the inverse frequencies
|
| 477 |
+
inv_freq = 1.0 / (
|
| 478 |
+
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
|
| 479 |
+
)
|
| 480 |
+
return inv_freq, attention_factor
|
| 481 |
+
|
| 482 |
+
@torch.no_grad()
|
| 483 |
+
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
|
| 484 |
+
def forward(self, x, position_ids):
|
| 485 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
|
| 486 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 487 |
+
|
| 488 |
+
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
| 489 |
+
with maybe_autocast(device_type=device_type, enabled=False): # Force float32
|
| 490 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 491 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 492 |
+
cos = emb.cos() * self.attention_scaling
|
| 493 |
+
sin = emb.sin() * self.attention_scaling
|
| 494 |
+
|
| 495 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
@auto_docstring(
|
| 499 |
+
custom_intro="""
|
| 500 |
+
The PeVideo Encoder model.
|
| 501 |
+
"""
|
| 502 |
+
)
|
| 503 |
+
class PeVideoEncoder(PeVideoPreTrainedModel):
|
| 504 |
+
config: PeVideoEncoderConfig
|
| 505 |
+
main_input_name = "pixel_values_videos"
|
| 506 |
+
base_model_prefix = "video_model.video_encoder"
|
| 507 |
+
|
| 508 |
+
def __init__(self, config: PeVideoEncoderConfig):
|
| 509 |
+
super().__init__(config)
|
| 510 |
+
self.embedder = PeVideoEncoderEmbedder(config)
|
| 511 |
+
self.patch_embedder = PeVideoEncoderPatchEmbedder(config)
|
| 512 |
+
self.layers = nn.ModuleList(
|
| 513 |
+
[PeVideoEncoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 514 |
+
)
|
| 515 |
+
self.norm = PeVideoEncoderRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 516 |
+
self.rotary_emb = PeVideoEncoderRotaryEmbedding(config=config)
|
| 517 |
+
self.output = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
|
| 518 |
+
self.gradient_checkpointing = False
|
| 519 |
+
|
| 520 |
+
self.post_init()
|
| 521 |
+
|
| 522 |
+
@can_return_tuple
|
| 523 |
+
@merge_with_config_defaults
|
| 524 |
+
@capture_outputs
|
| 525 |
+
def forward(
|
| 526 |
+
self,
|
| 527 |
+
pixel_values_videos: torch.Tensor,
|
| 528 |
+
padding_mask_videos: torch.Tensor | None = None,
|
| 529 |
+
**kwargs,
|
| 530 |
+
) -> tuple | BaseModelOutputWithPooling:
|
| 531 |
+
inputs_embeds, padding_mask = self.embedder(pixel_values_videos, padding_mask=padding_mask_videos)
|
| 532 |
+
inputs_embeds, attention_mask = self.patch_embedder(inputs_embeds, padding_mask=padding_mask)
|
| 533 |
+
|
| 534 |
+
if attention_mask is not None:
|
| 535 |
+
attention_mask = create_bidirectional_mask(
|
| 536 |
+
config=self.config,
|
| 537 |
+
inputs_embeds=inputs_embeds,
|
| 538 |
+
attention_mask=attention_mask,
|
| 539 |
+
)
|
| 540 |
+
|
| 541 |
+
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
| 542 |
+
position_embeddings = self.rotary_emb(inputs_embeds, position_ids)
|
| 543 |
+
|
| 544 |
+
hidden_states = inputs_embeds
|
| 545 |
+
for encoder_layer in self.layers[: self.config.num_hidden_layers]:
|
| 546 |
+
hidden_states = encoder_layer(
|
| 547 |
+
hidden_states,
|
| 548 |
+
attention_mask=attention_mask,
|
| 549 |
+
position_embeddings=position_embeddings,
|
| 550 |
+
**kwargs,
|
| 551 |
+
)
|
| 552 |
+
|
| 553 |
+
hidden_states = self.norm(hidden_states)
|
| 554 |
+
hidden_states = self.output(hidden_states)
|
| 555 |
+
|
| 556 |
+
return BaseModelOutputWithPooling(
|
| 557 |
+
last_hidden_state=hidden_states[:, 1:],
|
| 558 |
+
pooler_output=hidden_states[:, 0],
|
| 559 |
+
)
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
class PeVideoModel(PeVideoPreTrainedModel):
|
| 563 |
+
main_input_name = "input_ids"
|
| 564 |
+
|
| 565 |
+
def __init__(self, config: PeVideoConfig):
|
| 566 |
+
super().__init__(config)
|
| 567 |
+
self.text_model = AutoModel.from_config(config.text_config)
|
| 568 |
+
self.video_encoder = PeVideoEncoder(config.video_config)
|
| 569 |
+
|
| 570 |
+
self.text_video_head = PeVideoContrastiveHead(config.text_config.hidden_size, config.text_config.hidden_size)
|
| 571 |
+
self.video_head = PeVideoContrastiveHead(config.video_config.hidden_size, config.text_config.hidden_size)
|
| 572 |
+
|
| 573 |
+
self.text_video_logit_scale = nn.Parameter(torch.zeros(1))
|
| 574 |
+
self.text_video_logit_bias = nn.Parameter(torch.zeros(1))
|
| 575 |
+
|
| 576 |
+
self.post_init()
|
| 577 |
+
|
| 578 |
+
@can_return_tuple
|
| 579 |
+
@auto_docstring
|
| 580 |
+
def get_text_features(
|
| 581 |
+
self,
|
| 582 |
+
input_ids: torch.Tensor,
|
| 583 |
+
attention_mask: torch.Tensor | None = None,
|
| 584 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 585 |
+
) -> tuple | BaseModelOutputWithPooling:
|
| 586 |
+
text_outputs: BaseModelOutputWithPooling = self.text_model(
|
| 587 |
+
input_ids=input_ids,
|
| 588 |
+
attention_mask=attention_mask,
|
| 589 |
+
return_dict=True,
|
| 590 |
+
**kwargs,
|
| 591 |
+
)
|
| 592 |
+
text_outputs.pooler_output = self.text_video_head(text_outputs.last_hidden_state)
|
| 593 |
+
return text_outputs
|
| 594 |
+
|
| 595 |
+
@can_return_tuple
|
| 596 |
+
@auto_docstring
|
| 597 |
+
def get_video_features(
|
| 598 |
+
self,
|
| 599 |
+
pixel_values_videos: torch.Tensor,
|
| 600 |
+
padding_mask_videos: torch.Tensor | None = None,
|
| 601 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 602 |
+
) -> tuple | BaseModelOutputWithPooling:
|
| 603 |
+
video_outputs: BaseModelOutputWithPooling = self.video_encoder(
|
| 604 |
+
pixel_values_videos=pixel_values_videos,
|
| 605 |
+
padding_mask_videos=padding_mask_videos,
|
| 606 |
+
return_dict=True,
|
| 607 |
+
**kwargs,
|
| 608 |
+
)
|
| 609 |
+
video_outputs.pooler_output = self.video_head(video_outputs.pooler_output)
|
| 610 |
+
return video_outputs
|
| 611 |
+
|
| 612 |
+
@can_return_tuple
|
| 613 |
+
def forward(
|
| 614 |
+
self,
|
| 615 |
+
input_ids: torch.Tensor,
|
| 616 |
+
pixel_values_videos: torch.Tensor,
|
| 617 |
+
attention_mask: torch.Tensor | None = None,
|
| 618 |
+
padding_mask_videos: torch.Tensor | None = None,
|
| 619 |
+
return_loss: bool | None = None,
|
| 620 |
+
**kwargs,
|
| 621 |
+
) -> PeVideoOutput:
|
| 622 |
+
video_outputs: BaseModelOutputWithPooling = self.video_encoder(
|
| 623 |
+
pixel_values_videos=pixel_values_videos, padding_mask_videos=padding_mask_videos, **kwargs
|
| 624 |
+
)
|
| 625 |
+
kwargs["output_hidden_states"] = True
|
| 626 |
+
text_outputs: MaskedLMOutput = self.text_model(input_ids=input_ids, attention_mask=attention_mask, **kwargs)
|
| 627 |
+
|
| 628 |
+
video_embeds = video_outputs.pooler_output
|
| 629 |
+
video_embeds = self.video_head(video_embeds)
|
| 630 |
+
|
| 631 |
+
text_video_embeds = text_outputs.hidden_states[-1][:, 0]
|
| 632 |
+
text_video_embeds = self.text_video_head(text_video_embeds)
|
| 633 |
+
|
| 634 |
+
logits_video_text = video_embeds @ text_video_embeds.T
|
| 635 |
+
logits_video_text = logits_video_text * self.text_video_logit_scale + self.text_video_logit_bias
|
| 636 |
+
|
| 637 |
+
loss = None
|
| 638 |
+
if return_loss:
|
| 639 |
+
labels = torch.eye(logits_video_text.shape[0], device=logits_video_text.device)
|
| 640 |
+
loss = -F.logsigmoid(labels * logits_video_text).sum() / logits_video_text.shape[0]
|
| 641 |
+
|
| 642 |
+
return PeVideoOutput(
|
| 643 |
+
logits_video_text=logits_video_text,
|
| 644 |
+
text_video_embeds=text_video_embeds,
|
| 645 |
+
video_embeds=video_embeds,
|
| 646 |
+
text_outputs=text_outputs,
|
| 647 |
+
video_outputs=video_outputs,
|
| 648 |
+
loss=loss,
|
| 649 |
+
)
|
| 650 |
+
|
| 651 |
+
|
| 652 |
+
__all__ = ["PeVideoEncoder", "PeVideoModel"]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_video/modular_pe_video.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 the HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from dataclasses import dataclass
|
| 15 |
+
from typing import Any
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
import torch.nn as nn
|
| 19 |
+
import torch.nn.functional as F
|
| 20 |
+
|
| 21 |
+
from ...masking_utils import create_bidirectional_mask
|
| 22 |
+
from ...modeling_outputs import BaseModelOutputWithPooling, MaskedLMOutput
|
| 23 |
+
from ...processing_utils import Unpack
|
| 24 |
+
from ...utils import ModelOutput, TransformersKwargs, auto_docstring, can_return_tuple
|
| 25 |
+
from ...utils.generic import merge_with_config_defaults
|
| 26 |
+
from ...utils.output_capturing import capture_outputs
|
| 27 |
+
from ..auto import AutoModel, AutoModelForImageClassification
|
| 28 |
+
from ..pe_audio_video.modeling_pe_audio_video import (
|
| 29 |
+
PeAudioVideoContrastiveHead,
|
| 30 |
+
PeAudioVideoEncoder,
|
| 31 |
+
PeAudioVideoEncoderPatchEmbedder,
|
| 32 |
+
PeAudioVideoPreTrainedModel,
|
| 33 |
+
)
|
| 34 |
+
from .configuration_pe_video import PeVideoConfig, PeVideoEncoderConfig
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# TODO: not sure about the typing for text_model_output
|
| 38 |
+
@dataclass
|
| 39 |
+
# @auto_docstring
|
| 40 |
+
class PeVideoOutput(ModelOutput):
|
| 41 |
+
loss: torch.FloatTensor | None = None
|
| 42 |
+
logits_video_text: torch.FloatTensor | None = None
|
| 43 |
+
text_video_embeds: torch.FloatTensor | None = None
|
| 44 |
+
video_embeds: torch.FloatTensor | None = None
|
| 45 |
+
text_outputs: BaseModelOutputWithPooling = None
|
| 46 |
+
video_outputs: BaseModelOutputWithPooling = None
|
| 47 |
+
|
| 48 |
+
def to_tuple(self) -> tuple[Any]:
|
| 49 |
+
return tuple(
|
| 50 |
+
self[k] if k not in ["text_outputs", "video_outputs"] else getattr(self, k).to_tuple() for k in self.keys()
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class PeVideoContrastiveHead(PeAudioVideoContrastiveHead): ...
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class PeVideoEncoderPatchEmbedder(PeAudioVideoEncoderPatchEmbedder): ...
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class PeVideoEncoderEmbedder(nn.Module):
|
| 61 |
+
def __init__(self, config: PeVideoEncoderConfig):
|
| 62 |
+
super().__init__()
|
| 63 |
+
self.vision_model = AutoModelForImageClassification.from_config(config.vision_config)
|
| 64 |
+
self.proj = nn.Linear(config.vision_config.num_labels, config.hidden_size, bias=False)
|
| 65 |
+
self.data_proj = nn.Linear(config.hidden_size, config.hidden_size)
|
| 66 |
+
|
| 67 |
+
def forward(
|
| 68 |
+
self,
|
| 69 |
+
pixel_values_videos: torch.Tensor,
|
| 70 |
+
padding_mask: torch.Tensor | None = None,
|
| 71 |
+
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
| 72 |
+
input_shape = pixel_values_videos.shape
|
| 73 |
+
|
| 74 |
+
pixel_values_videos = pixel_values_videos.view(-1, *input_shape[2:])
|
| 75 |
+
vision_encoder_outputs = self.vision_model(pixel_values_videos)
|
| 76 |
+
|
| 77 |
+
logits = vision_encoder_outputs.logits.view(*input_shape[:2], -1)
|
| 78 |
+
logits = F.normalize(logits, dim=-1)
|
| 79 |
+
|
| 80 |
+
vision_features = self.proj(logits)
|
| 81 |
+
inputs_embeds = self.data_proj(vision_features)
|
| 82 |
+
|
| 83 |
+
return inputs_embeds, padding_mask
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class PeVideoPreTrainedModel(PeAudioVideoPreTrainedModel):
|
| 87 |
+
base_model_prefix = "video_model"
|
| 88 |
+
main_input_name = "pixel_values_videos"
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@auto_docstring(
|
| 92 |
+
custom_intro="""
|
| 93 |
+
The PeVideo Encoder model.
|
| 94 |
+
"""
|
| 95 |
+
)
|
| 96 |
+
class PeVideoEncoder(PeAudioVideoEncoder):
|
| 97 |
+
base_model_prefix = "video_model.video_encoder"
|
| 98 |
+
main_input_name = "pixel_values_videos"
|
| 99 |
+
|
| 100 |
+
def __init__(self, config: PeVideoEncoderConfig):
|
| 101 |
+
super().__init__(config)
|
| 102 |
+
self.embedder = PeVideoEncoderEmbedder(config)
|
| 103 |
+
|
| 104 |
+
@can_return_tuple
|
| 105 |
+
@merge_with_config_defaults
|
| 106 |
+
@capture_outputs
|
| 107 |
+
def forward(
|
| 108 |
+
self,
|
| 109 |
+
pixel_values_videos: torch.Tensor,
|
| 110 |
+
padding_mask_videos: torch.Tensor | None = None,
|
| 111 |
+
**kwargs,
|
| 112 |
+
) -> tuple | BaseModelOutputWithPooling:
|
| 113 |
+
inputs_embeds, padding_mask = self.embedder(pixel_values_videos, padding_mask=padding_mask_videos)
|
| 114 |
+
inputs_embeds, attention_mask = self.patch_embedder(inputs_embeds, padding_mask=padding_mask)
|
| 115 |
+
|
| 116 |
+
if attention_mask is not None:
|
| 117 |
+
attention_mask = create_bidirectional_mask(
|
| 118 |
+
config=self.config,
|
| 119 |
+
inputs_embeds=inputs_embeds,
|
| 120 |
+
attention_mask=attention_mask,
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
| 124 |
+
position_embeddings = self.rotary_emb(inputs_embeds, position_ids)
|
| 125 |
+
|
| 126 |
+
hidden_states = inputs_embeds
|
| 127 |
+
for encoder_layer in self.layers[: self.config.num_hidden_layers]:
|
| 128 |
+
hidden_states = encoder_layer(
|
| 129 |
+
hidden_states,
|
| 130 |
+
attention_mask=attention_mask,
|
| 131 |
+
position_embeddings=position_embeddings,
|
| 132 |
+
**kwargs,
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
hidden_states = self.norm(hidden_states)
|
| 136 |
+
hidden_states = self.output(hidden_states)
|
| 137 |
+
|
| 138 |
+
return BaseModelOutputWithPooling(
|
| 139 |
+
last_hidden_state=hidden_states[:, 1:],
|
| 140 |
+
pooler_output=hidden_states[:, 0],
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
class PeVideoModel(PeVideoPreTrainedModel):
|
| 145 |
+
main_input_name = "input_ids"
|
| 146 |
+
|
| 147 |
+
def __init__(self, config: PeVideoConfig):
|
| 148 |
+
super().__init__(config)
|
| 149 |
+
self.text_model = AutoModel.from_config(config.text_config)
|
| 150 |
+
self.video_encoder = PeVideoEncoder(config.video_config)
|
| 151 |
+
|
| 152 |
+
self.text_video_head = PeVideoContrastiveHead(config.text_config.hidden_size, config.text_config.hidden_size)
|
| 153 |
+
self.video_head = PeVideoContrastiveHead(config.video_config.hidden_size, config.text_config.hidden_size)
|
| 154 |
+
|
| 155 |
+
self.text_video_logit_scale = nn.Parameter(torch.zeros(1))
|
| 156 |
+
self.text_video_logit_bias = nn.Parameter(torch.zeros(1))
|
| 157 |
+
|
| 158 |
+
self.post_init()
|
| 159 |
+
|
| 160 |
+
@can_return_tuple
|
| 161 |
+
@auto_docstring
|
| 162 |
+
def get_text_features(
|
| 163 |
+
self,
|
| 164 |
+
input_ids: torch.Tensor,
|
| 165 |
+
attention_mask: torch.Tensor | None = None,
|
| 166 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 167 |
+
) -> tuple | BaseModelOutputWithPooling:
|
| 168 |
+
text_outputs: BaseModelOutputWithPooling = self.text_model(
|
| 169 |
+
input_ids=input_ids,
|
| 170 |
+
attention_mask=attention_mask,
|
| 171 |
+
return_dict=True,
|
| 172 |
+
**kwargs,
|
| 173 |
+
)
|
| 174 |
+
text_outputs.pooler_output = self.text_video_head(text_outputs.last_hidden_state)
|
| 175 |
+
return text_outputs
|
| 176 |
+
|
| 177 |
+
@can_return_tuple
|
| 178 |
+
@auto_docstring
|
| 179 |
+
def get_video_features(
|
| 180 |
+
self,
|
| 181 |
+
pixel_values_videos: torch.Tensor,
|
| 182 |
+
padding_mask_videos: torch.Tensor | None = None,
|
| 183 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 184 |
+
) -> tuple | BaseModelOutputWithPooling:
|
| 185 |
+
video_outputs: BaseModelOutputWithPooling = self.video_encoder(
|
| 186 |
+
pixel_values_videos=pixel_values_videos,
|
| 187 |
+
padding_mask_videos=padding_mask_videos,
|
| 188 |
+
return_dict=True,
|
| 189 |
+
**kwargs,
|
| 190 |
+
)
|
| 191 |
+
video_outputs.pooler_output = self.video_head(video_outputs.pooler_output)
|
| 192 |
+
return video_outputs
|
| 193 |
+
|
| 194 |
+
@can_return_tuple
|
| 195 |
+
def forward(
|
| 196 |
+
self,
|
| 197 |
+
input_ids: torch.Tensor,
|
| 198 |
+
pixel_values_videos: torch.Tensor,
|
| 199 |
+
attention_mask: torch.Tensor | None = None,
|
| 200 |
+
padding_mask_videos: torch.Tensor | None = None,
|
| 201 |
+
return_loss: bool | None = None,
|
| 202 |
+
**kwargs,
|
| 203 |
+
) -> PeVideoOutput:
|
| 204 |
+
video_outputs: BaseModelOutputWithPooling = self.video_encoder(
|
| 205 |
+
pixel_values_videos=pixel_values_videos, padding_mask_videos=padding_mask_videos, **kwargs
|
| 206 |
+
)
|
| 207 |
+
kwargs["output_hidden_states"] = True
|
| 208 |
+
text_outputs: MaskedLMOutput = self.text_model(input_ids=input_ids, attention_mask=attention_mask, **kwargs)
|
| 209 |
+
|
| 210 |
+
video_embeds = video_outputs.pooler_output
|
| 211 |
+
video_embeds = self.video_head(video_embeds)
|
| 212 |
+
|
| 213 |
+
text_video_embeds = text_outputs.hidden_states[-1][:, 0]
|
| 214 |
+
text_video_embeds = self.text_video_head(text_video_embeds)
|
| 215 |
+
|
| 216 |
+
logits_video_text = video_embeds @ text_video_embeds.T
|
| 217 |
+
logits_video_text = logits_video_text * self.text_video_logit_scale + self.text_video_logit_bias
|
| 218 |
+
|
| 219 |
+
loss = None
|
| 220 |
+
if return_loss:
|
| 221 |
+
labels = torch.eye(logits_video_text.shape[0], device=logits_video_text.device)
|
| 222 |
+
loss = -F.logsigmoid(labels * logits_video_text).sum() / logits_video_text.shape[0]
|
| 223 |
+
|
| 224 |
+
return PeVideoOutput(
|
| 225 |
+
logits_video_text=logits_video_text,
|
| 226 |
+
text_video_embeds=text_video_embeds,
|
| 227 |
+
video_embeds=video_embeds,
|
| 228 |
+
text_outputs=text_outputs,
|
| 229 |
+
video_outputs=video_outputs,
|
| 230 |
+
loss=loss,
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
__all__ = [
|
| 235 |
+
"PeVideoEncoder",
|
| 236 |
+
"PeVideoModel",
|
| 237 |
+
]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_video/processing_pe_video.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ...processing_utils import ProcessorMixin
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class PeVideoProcessor(ProcessorMixin):
|
| 5 |
+
attributes = ["video_processor", "tokenizer"]
|
| 6 |
+
video_processor_class = "PeVideoVideoProcessor"
|
| 7 |
+
tokenizer_class = "AutoTokenizer"
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
__all__ = ["PeVideoProcessor"]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pe_video/video_processing_pe_video.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 the HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
|
| 17 |
+
from ...image_processing_utils import BatchFeature
|
| 18 |
+
from ...image_utils import PILImageResampling
|
| 19 |
+
from ...processing_utils import Unpack, VideosKwargs
|
| 20 |
+
from ...video_processing_utils import BaseVideoProcessor, VideoMetadata
|
| 21 |
+
from ...video_utils import VideoInput
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class PeVideoVideoProcessor(BaseVideoProcessor):
|
| 25 |
+
resample = PILImageResampling.BILINEAR
|
| 26 |
+
|
| 27 |
+
def sample_frames(
|
| 28 |
+
self,
|
| 29 |
+
metadata: VideoMetadata,
|
| 30 |
+
num_frames: int | None = None,
|
| 31 |
+
fps: int | float | None = None,
|
| 32 |
+
**kwargs,
|
| 33 |
+
):
|
| 34 |
+
if num_frames:
|
| 35 |
+
total_frames = metadata.total_num_frames
|
| 36 |
+
num_frames = num_frames if num_frames is not None else self.num_frames
|
| 37 |
+
assert num_frames is not None, "`num_frames` must be specified if `fixed_len_video == True`"
|
| 38 |
+
frame_idxs = [int(i * (total_frames - 1) / (num_frames - 1)) for i in range(num_frames)]
|
| 39 |
+
return torch.tensor(frame_idxs)
|
| 40 |
+
else:
|
| 41 |
+
return super().sample_frames(metadata, num_frames, fps, **kwargs)
|
| 42 |
+
|
| 43 |
+
def _preprocess(
|
| 44 |
+
self,
|
| 45 |
+
videos: VideoInput,
|
| 46 |
+
**kwargs: Unpack[VideosKwargs],
|
| 47 |
+
) -> BatchFeature:
|
| 48 |
+
# Always set `return_tensors` to `None` since it won't pad variable length videos
|
| 49 |
+
# We'll handle this after we call the parent' method
|
| 50 |
+
return_tensors = kwargs.pop("return_tensors", None)
|
| 51 |
+
result = super()._preprocess(videos, **kwargs)
|
| 52 |
+
pixels = result.pixel_values_videos
|
| 53 |
+
data = {"pixel_values_videos": pixels}
|
| 54 |
+
if return_tensors:
|
| 55 |
+
lengths = torch.tensor([video.size(0) for video in pixels])
|
| 56 |
+
pixels = torch.nn.utils.rnn.pad_sequence(pixels, batch_first=True, padding_value=0.0)
|
| 57 |
+
data["pixel_values_videos"] = pixels
|
| 58 |
+
if lengths.unique().size(0) > 1:
|
| 59 |
+
mask = torch.arange(lengths.max())[None] < lengths[:, None]
|
| 60 |
+
data["padding_mask_videos"] = mask
|
| 61 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
__all__ = ["PeVideoVideoProcessor"]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pegasus/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_pegasus import *
|
| 22 |
+
from .modeling_pegasus import *
|
| 23 |
+
from .tokenization_pegasus import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pegasus/configuration_pegasus.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021, Google and The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""PEGASUS model configuration"""
|
| 15 |
+
|
| 16 |
+
from ...configuration_utils import PreTrainedConfig
|
| 17 |
+
from ...utils import logging
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
logger = logging.get_logger(__name__)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class PegasusConfig(PreTrainedConfig):
|
| 24 |
+
r"""
|
| 25 |
+
This is the configuration class to store the configuration of a [`PegasusModel`]. It is used to instantiate an
|
| 26 |
+
PEGASUS model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 27 |
+
with the defaults will yield a similar configuration to that of the PEGASUS
|
| 28 |
+
[google/pegasus-large](https://huggingface.co/google/pegasus-large) architecture.
|
| 29 |
+
|
| 30 |
+
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
|
| 31 |
+
documentation from [`PreTrainedConfig`] for more information.
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
vocab_size (`int`, *optional*, defaults to 50265):
|
| 36 |
+
Vocabulary size of the PEGASUS model. Defines the number of different tokens that can be represented by the
|
| 37 |
+
`inputs_ids` passed when calling [`PegasusModel`].
|
| 38 |
+
d_model (`int`, *optional*, defaults to 1024):
|
| 39 |
+
Dimensionality of the layers and the pooler layer.
|
| 40 |
+
encoder_layers (`int`, *optional*, defaults to 12):
|
| 41 |
+
Number of encoder layers.
|
| 42 |
+
decoder_layers (`int`, *optional*, defaults to 12):
|
| 43 |
+
Number of decoder layers.
|
| 44 |
+
encoder_attention_heads (`int`, *optional*, defaults to 16):
|
| 45 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 46 |
+
decoder_attention_heads (`int`, *optional*, defaults to 16):
|
| 47 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
| 48 |
+
decoder_ffn_dim (`int`, *optional*, defaults to 4096):
|
| 49 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
|
| 50 |
+
encoder_ffn_dim (`int`, *optional*, defaults to 4096):
|
| 51 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
|
| 52 |
+
activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 53 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 54 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 55 |
+
dropout (`float`, *optional*, defaults to 0.1):
|
| 56 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 57 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 58 |
+
The dropout ratio for the attention probabilities.
|
| 59 |
+
activation_dropout (`float`, *optional*, defaults to 0.0):
|
| 60 |
+
The dropout ratio for activations inside the fully connected layer.
|
| 61 |
+
max_position_embeddings (`int`, *optional*, defaults to 1024):
|
| 62 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 63 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 64 |
+
init_std (`float`, *optional*, defaults to 0.02):
|
| 65 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 66 |
+
encoder_layerdrop (`float`, *optional*, defaults to 0.0):
|
| 67 |
+
The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556)
|
| 68 |
+
for more details.
|
| 69 |
+
decoder_layerdrop (`float`, *optional*, defaults to 0.0):
|
| 70 |
+
The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556)
|
| 71 |
+
for more details.
|
| 72 |
+
scale_embedding (`bool`, *optional*, defaults to `False`):
|
| 73 |
+
Scale embeddings by diving by sqrt(d_model).
|
| 74 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 75 |
+
Whether or not the model should return the last key/values attentions (not used by all models)
|
| 76 |
+
forced_eos_token_id (`int`, *optional*, defaults to 1):
|
| 77 |
+
The id of the token to force as the last generated token when `max_length` is reached. Usually set to
|
| 78 |
+
`eos_token_id`.
|
| 79 |
+
|
| 80 |
+
Example:
|
| 81 |
+
|
| 82 |
+
```python
|
| 83 |
+
>>> from transformers import PegasusConfig, PegasusModel
|
| 84 |
+
|
| 85 |
+
>>> # Initializing a PEGASUS google/pegasus-large style configuration
|
| 86 |
+
>>> configuration = PegasusConfig()
|
| 87 |
+
|
| 88 |
+
>>> # Initializing a model (with random weights) from the google/pegasus-large style configuration
|
| 89 |
+
>>> model = PegasusModel(configuration)
|
| 90 |
+
|
| 91 |
+
>>> # Accessing the model configuration
|
| 92 |
+
>>> configuration = model.config
|
| 93 |
+
```"""
|
| 94 |
+
|
| 95 |
+
model_type = "pegasus"
|
| 96 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 97 |
+
attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
|
| 98 |
+
|
| 99 |
+
def __init__(
|
| 100 |
+
self,
|
| 101 |
+
vocab_size=50265,
|
| 102 |
+
max_position_embeddings=1024,
|
| 103 |
+
encoder_layers=12,
|
| 104 |
+
encoder_ffn_dim=4096,
|
| 105 |
+
encoder_attention_heads=16,
|
| 106 |
+
decoder_layers=12,
|
| 107 |
+
decoder_ffn_dim=4096,
|
| 108 |
+
decoder_attention_heads=16,
|
| 109 |
+
encoder_layerdrop=0.0,
|
| 110 |
+
decoder_layerdrop=0.0,
|
| 111 |
+
use_cache=True,
|
| 112 |
+
is_encoder_decoder=True,
|
| 113 |
+
activation_function="gelu",
|
| 114 |
+
d_model=1024,
|
| 115 |
+
dropout=0.1,
|
| 116 |
+
attention_dropout=0.0,
|
| 117 |
+
activation_dropout=0.0,
|
| 118 |
+
init_std=0.02,
|
| 119 |
+
decoder_start_token_id=0,
|
| 120 |
+
scale_embedding=False,
|
| 121 |
+
pad_token_id=0,
|
| 122 |
+
eos_token_id=1,
|
| 123 |
+
forced_eos_token_id=1,
|
| 124 |
+
is_decoder=False,
|
| 125 |
+
tie_word_embeddings=True,
|
| 126 |
+
**kwargs,
|
| 127 |
+
):
|
| 128 |
+
self.is_decoder = is_decoder
|
| 129 |
+
self.tie_word_embeddings = tie_word_embeddings
|
| 130 |
+
self.vocab_size = vocab_size
|
| 131 |
+
self.max_position_embeddings = max_position_embeddings
|
| 132 |
+
self.d_model = d_model
|
| 133 |
+
self.encoder_ffn_dim = encoder_ffn_dim
|
| 134 |
+
self.encoder_layers = encoder_layers
|
| 135 |
+
self.encoder_attention_heads = encoder_attention_heads
|
| 136 |
+
self.decoder_ffn_dim = decoder_ffn_dim
|
| 137 |
+
self.decoder_layers = decoder_layers
|
| 138 |
+
self.decoder_attention_heads = decoder_attention_heads
|
| 139 |
+
self.dropout = dropout
|
| 140 |
+
self.attention_dropout = attention_dropout
|
| 141 |
+
self.activation_dropout = activation_dropout
|
| 142 |
+
self.activation_function = activation_function
|
| 143 |
+
self.init_std = init_std
|
| 144 |
+
self.encoder_layerdrop = encoder_layerdrop
|
| 145 |
+
self.decoder_layerdrop = decoder_layerdrop
|
| 146 |
+
self.use_cache = use_cache
|
| 147 |
+
self.num_hidden_layers = encoder_layers
|
| 148 |
+
self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
|
| 149 |
+
self.pad_token_id = pad_token_id
|
| 150 |
+
self.eos_token_id = eos_token_id
|
| 151 |
+
self.decoder_start_token_id = decoder_start_token_id
|
| 152 |
+
self.forced_eos_token_id = forced_eos_token_id
|
| 153 |
+
super().__init__(
|
| 154 |
+
is_encoder_decoder=is_encoder_decoder,
|
| 155 |
+
**kwargs,
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
__all__ = ["PegasusConfig"]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pegasus/modeling_pegasus.py
ADDED
|
@@ -0,0 +1,1361 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021, Google and The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""PyTorch PEGASUS model."""
|
| 15 |
+
|
| 16 |
+
import copy
|
| 17 |
+
import math
|
| 18 |
+
from collections.abc import Callable
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
import torch
|
| 22 |
+
from torch import nn
|
| 23 |
+
from torch.nn import CrossEntropyLoss
|
| 24 |
+
|
| 25 |
+
from ... import initialization as init
|
| 26 |
+
from ...activations import ACT2FN
|
| 27 |
+
from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
|
| 28 |
+
from ...generation import GenerationMixin
|
| 29 |
+
from ...masking_utils import create_bidirectional_mask, create_causal_mask
|
| 30 |
+
from ...modeling_flash_attention_utils import FlashAttentionKwargs
|
| 31 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 32 |
+
from ...modeling_outputs import (
|
| 33 |
+
BaseModelOutput,
|
| 34 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 35 |
+
CausalLMOutputWithCrossAttentions,
|
| 36 |
+
Seq2SeqLMOutput,
|
| 37 |
+
Seq2SeqModelOutput,
|
| 38 |
+
)
|
| 39 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 40 |
+
from ...processing_utils import Unpack
|
| 41 |
+
from ...utils import (
|
| 42 |
+
TransformersKwargs,
|
| 43 |
+
auto_docstring,
|
| 44 |
+
is_torchdynamo_compiling,
|
| 45 |
+
logging,
|
| 46 |
+
)
|
| 47 |
+
from .configuration_pegasus import PegasusConfig
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
logger = logging.get_logger(__name__)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
# Copied from transformers.models.bart.modeling_bart.shift_tokens_right
|
| 54 |
+
def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
|
| 55 |
+
"""
|
| 56 |
+
Shift input ids one token to the right.
|
| 57 |
+
"""
|
| 58 |
+
shifted_input_ids = input_ids.new_zeros(input_ids.shape)
|
| 59 |
+
shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
|
| 60 |
+
shifted_input_ids[:, 0] = decoder_start_token_id
|
| 61 |
+
|
| 62 |
+
if pad_token_id is None:
|
| 63 |
+
raise ValueError("self.model.config.pad_token_id has to be defined.")
|
| 64 |
+
# replace possible -100 values in labels by `pad_token_id`
|
| 65 |
+
shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
|
| 66 |
+
|
| 67 |
+
return shifted_input_ids
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# Copied from transformers.models.marian.modeling_marian.MarianSinusoidalPositionalEmbedding with Marian->Pegasus
|
| 71 |
+
class PegasusSinusoidalPositionalEmbedding(nn.Embedding):
|
| 72 |
+
"""This module produces sinusoidal positional embeddings of any length."""
|
| 73 |
+
|
| 74 |
+
def __init__(self, num_positions: int, embedding_dim: int, padding_idx: int | None = None) -> None:
|
| 75 |
+
super().__init__(num_positions, embedding_dim, _freeze=True)
|
| 76 |
+
|
| 77 |
+
def create_weight(self):
|
| 78 |
+
"""
|
| 79 |
+
Identical to the XLM create_sinusoidal_embeddings except features are not interleaved. The cos features are in
|
| 80 |
+
the 2nd half of the vector. [dim // 2:]
|
| 81 |
+
"""
|
| 82 |
+
n_pos, dim = self.weight.shape
|
| 83 |
+
position_enc = np.array(
|
| 84 |
+
[[pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)] for pos in range(n_pos)]
|
| 85 |
+
)
|
| 86 |
+
out = torch.empty(n_pos, dim, dtype=self.weight.dtype, requires_grad=False)
|
| 87 |
+
sentinel = dim // 2 if dim % 2 == 0 else (dim // 2) + 1
|
| 88 |
+
out[:, 0:sentinel] = torch.FloatTensor(np.sin(position_enc[:, 0::2]))
|
| 89 |
+
out[:, sentinel:] = torch.FloatTensor(np.cos(position_enc[:, 1::2]))
|
| 90 |
+
return out
|
| 91 |
+
|
| 92 |
+
@torch.no_grad()
|
| 93 |
+
def forward(
|
| 94 |
+
self, input_ids_shape: torch.Size, past_key_values_length: int = 0, position_ids: torch.Tensor | None = None
|
| 95 |
+
) -> torch.Tensor:
|
| 96 |
+
"""`input_ids_shape` is expected to be [bsz x seqlen]."""
|
| 97 |
+
if position_ids is None:
|
| 98 |
+
bsz, seq_len = input_ids_shape[:2]
|
| 99 |
+
position_ids = torch.arange(
|
| 100 |
+
past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device
|
| 101 |
+
)
|
| 102 |
+
return super().forward(position_ids)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
# Copied from transformers.models.bert.modeling_bert.eager_attention_forward
|
| 106 |
+
def eager_attention_forward(
|
| 107 |
+
module: nn.Module,
|
| 108 |
+
query: torch.Tensor,
|
| 109 |
+
key: torch.Tensor,
|
| 110 |
+
value: torch.Tensor,
|
| 111 |
+
attention_mask: torch.Tensor | None,
|
| 112 |
+
scaling: float | None = None,
|
| 113 |
+
dropout: float = 0.0,
|
| 114 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 115 |
+
):
|
| 116 |
+
if scaling is None:
|
| 117 |
+
scaling = query.size(-1) ** -0.5
|
| 118 |
+
|
| 119 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 120 |
+
attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
|
| 121 |
+
|
| 122 |
+
if attention_mask is not None:
|
| 123 |
+
attn_weights = attn_weights + attention_mask
|
| 124 |
+
|
| 125 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 126 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 127 |
+
|
| 128 |
+
attn_output = torch.matmul(attn_weights, value)
|
| 129 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 130 |
+
|
| 131 |
+
return attn_output, attn_weights
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
# Copied from transformers.models.bart.modeling_bart.BartAttention with Bart->Pegasus
|
| 135 |
+
class PegasusAttention(nn.Module):
|
| 136 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 137 |
+
|
| 138 |
+
def __init__(
|
| 139 |
+
self,
|
| 140 |
+
embed_dim: int,
|
| 141 |
+
num_heads: int,
|
| 142 |
+
dropout: float = 0.0,
|
| 143 |
+
is_decoder: bool = False,
|
| 144 |
+
bias: bool = True,
|
| 145 |
+
is_causal: bool = False,
|
| 146 |
+
config: PegasusConfig | None = None,
|
| 147 |
+
layer_idx: int | None = None,
|
| 148 |
+
):
|
| 149 |
+
super().__init__()
|
| 150 |
+
self.embed_dim = embed_dim
|
| 151 |
+
self.num_heads = num_heads
|
| 152 |
+
self.dropout = dropout
|
| 153 |
+
self.head_dim = embed_dim // num_heads
|
| 154 |
+
self.config = config
|
| 155 |
+
|
| 156 |
+
if (self.head_dim * num_heads) != self.embed_dim:
|
| 157 |
+
raise ValueError(
|
| 158 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
|
| 159 |
+
f" and `num_heads`: {num_heads})."
|
| 160 |
+
)
|
| 161 |
+
self.scaling = self.head_dim**-0.5
|
| 162 |
+
self.is_decoder = is_decoder
|
| 163 |
+
self.is_causal = is_causal
|
| 164 |
+
self.layer_idx = layer_idx
|
| 165 |
+
if layer_idx is None and self.is_decoder:
|
| 166 |
+
logger.warning_once(
|
| 167 |
+
f"Instantiating a decoder {self.__class__.__name__} without passing `layer_idx` is not recommended and "
|
| 168 |
+
"will lead to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
| 169 |
+
"when creating this class."
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 173 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 174 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 175 |
+
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 176 |
+
|
| 177 |
+
def forward(
|
| 178 |
+
self,
|
| 179 |
+
hidden_states: torch.Tensor,
|
| 180 |
+
key_value_states: torch.Tensor | None = None,
|
| 181 |
+
past_key_values: Cache | None = None,
|
| 182 |
+
attention_mask: torch.Tensor | None = None,
|
| 183 |
+
output_attentions: bool = False,
|
| 184 |
+
cache_position: torch.Tensor | None = None,
|
| 185 |
+
# TODO: we need a refactor so that the different attention modules can get their specific kwargs
|
| 186 |
+
# ATM, we have mixed things encoder, decoder, and encoder-decoder attn
|
| 187 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 188 |
+
) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
|
| 189 |
+
"""Input shape: Batch x Time x Channel"""
|
| 190 |
+
|
| 191 |
+
# if key_value_states are provided this layer is used as a cross-attention layer
|
| 192 |
+
# for the decoder
|
| 193 |
+
is_cross_attention = key_value_states is not None
|
| 194 |
+
|
| 195 |
+
# determine input shapes
|
| 196 |
+
bsz, tgt_len = hidden_states.shape[:-1]
|
| 197 |
+
src_len = key_value_states.shape[1] if is_cross_attention else tgt_len
|
| 198 |
+
|
| 199 |
+
q_input_shape = (bsz, tgt_len, -1, self.head_dim)
|
| 200 |
+
kv_input_shape = (bsz, src_len, -1, self.head_dim)
|
| 201 |
+
|
| 202 |
+
# get query proj
|
| 203 |
+
query_states = self.q_proj(hidden_states).view(*q_input_shape).transpose(1, 2)
|
| 204 |
+
|
| 205 |
+
is_updated = False
|
| 206 |
+
if past_key_values is not None:
|
| 207 |
+
if isinstance(past_key_values, EncoderDecoderCache):
|
| 208 |
+
is_updated = past_key_values.is_updated.get(self.layer_idx)
|
| 209 |
+
if is_cross_attention:
|
| 210 |
+
# after the first generated id, we can subsequently re-use all key/value_states from cache
|
| 211 |
+
curr_past_key_values = past_key_values.cross_attention_cache
|
| 212 |
+
else:
|
| 213 |
+
curr_past_key_values = past_key_values.self_attention_cache
|
| 214 |
+
else:
|
| 215 |
+
curr_past_key_values = past_key_values
|
| 216 |
+
|
| 217 |
+
current_states = key_value_states if is_cross_attention else hidden_states
|
| 218 |
+
if is_cross_attention and past_key_values is not None and is_updated:
|
| 219 |
+
# reuse k,v, cross_attentions
|
| 220 |
+
key_states = curr_past_key_values.layers[self.layer_idx].keys
|
| 221 |
+
value_states = curr_past_key_values.layers[self.layer_idx].values
|
| 222 |
+
else:
|
| 223 |
+
key_states = self.k_proj(current_states)
|
| 224 |
+
value_states = self.v_proj(current_states)
|
| 225 |
+
key_states = key_states.view(*kv_input_shape).transpose(1, 2)
|
| 226 |
+
value_states = value_states.view(*kv_input_shape).transpose(1, 2)
|
| 227 |
+
|
| 228 |
+
if past_key_values is not None:
|
| 229 |
+
# save all key/value_states to cache to be re-used for fast auto-regressive generation
|
| 230 |
+
cache_position = cache_position if not is_cross_attention else None
|
| 231 |
+
key_states, value_states = curr_past_key_values.update(
|
| 232 |
+
key_states, value_states, self.layer_idx, {"cache_position": cache_position}
|
| 233 |
+
)
|
| 234 |
+
# set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
|
| 235 |
+
if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
|
| 236 |
+
past_key_values.is_updated[self.layer_idx] = True
|
| 237 |
+
|
| 238 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 239 |
+
self.config._attn_implementation, eager_attention_forward
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
attn_output, attn_weights = attention_interface(
|
| 243 |
+
self,
|
| 244 |
+
query_states,
|
| 245 |
+
key_states,
|
| 246 |
+
value_states,
|
| 247 |
+
attention_mask,
|
| 248 |
+
dropout=0.0 if not self.training else self.dropout,
|
| 249 |
+
scaling=self.scaling,
|
| 250 |
+
output_attentions=output_attentions,
|
| 251 |
+
**kwargs,
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
attn_output = attn_output.reshape(bsz, tgt_len, -1).contiguous()
|
| 255 |
+
attn_output = self.out_proj(attn_output)
|
| 256 |
+
|
| 257 |
+
return attn_output, attn_weights
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
# Copied from transformers.models.mbart.modeling_mbart.MBartEncoderLayer with MBart->Pegasus, MBART->PEGASUS
|
| 261 |
+
class PegasusEncoderLayer(GradientCheckpointingLayer):
|
| 262 |
+
def __init__(self, config: PegasusConfig):
|
| 263 |
+
super().__init__()
|
| 264 |
+
self.embed_dim = config.d_model
|
| 265 |
+
|
| 266 |
+
self.self_attn = PegasusAttention(
|
| 267 |
+
embed_dim=self.embed_dim,
|
| 268 |
+
num_heads=config.encoder_attention_heads,
|
| 269 |
+
dropout=config.attention_dropout,
|
| 270 |
+
config=config,
|
| 271 |
+
)
|
| 272 |
+
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 273 |
+
self.dropout = config.dropout
|
| 274 |
+
self.activation_fn = ACT2FN[config.activation_function]
|
| 275 |
+
self.activation_dropout = config.activation_dropout
|
| 276 |
+
self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
|
| 277 |
+
self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
|
| 278 |
+
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 279 |
+
|
| 280 |
+
def forward(
|
| 281 |
+
self,
|
| 282 |
+
hidden_states: torch.Tensor,
|
| 283 |
+
attention_mask: torch.Tensor,
|
| 284 |
+
output_attentions: bool = False,
|
| 285 |
+
) -> torch.Tensor:
|
| 286 |
+
"""
|
| 287 |
+
Args:
|
| 288 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 289 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
| 290 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 291 |
+
output_attentions (`bool`, *optional*):
|
| 292 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 293 |
+
returned tensors for more detail.
|
| 294 |
+
"""
|
| 295 |
+
residual = hidden_states
|
| 296 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 297 |
+
hidden_states, attn_weights = self.self_attn(
|
| 298 |
+
hidden_states=hidden_states,
|
| 299 |
+
attention_mask=attention_mask,
|
| 300 |
+
output_attentions=output_attentions,
|
| 301 |
+
)
|
| 302 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 303 |
+
hidden_states = residual + hidden_states
|
| 304 |
+
|
| 305 |
+
residual = hidden_states
|
| 306 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 307 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 308 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
|
| 309 |
+
hidden_states = self.fc2(hidden_states)
|
| 310 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 311 |
+
hidden_states = residual + hidden_states
|
| 312 |
+
|
| 313 |
+
if hidden_states.dtype == torch.float16:
|
| 314 |
+
clamp_value = torch.finfo(hidden_states.dtype).max - 1000
|
| 315 |
+
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
|
| 316 |
+
|
| 317 |
+
return hidden_states, attn_weights
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
# Copied from transformers.models.mbart.modeling_mbart.MBartDecoderLayer with MBart->Pegasus, MBART->PEGASUS
|
| 321 |
+
class PegasusDecoderLayer(GradientCheckpointingLayer):
|
| 322 |
+
def __init__(self, config: PegasusConfig, layer_idx: int | None = None):
|
| 323 |
+
super().__init__()
|
| 324 |
+
self.embed_dim = config.d_model
|
| 325 |
+
|
| 326 |
+
self.self_attn = PegasusAttention(
|
| 327 |
+
embed_dim=self.embed_dim,
|
| 328 |
+
num_heads=config.decoder_attention_heads,
|
| 329 |
+
dropout=config.attention_dropout,
|
| 330 |
+
is_decoder=True,
|
| 331 |
+
is_causal=True,
|
| 332 |
+
config=config,
|
| 333 |
+
layer_idx=layer_idx,
|
| 334 |
+
)
|
| 335 |
+
self.dropout = config.dropout
|
| 336 |
+
self.activation_fn = ACT2FN[config.activation_function]
|
| 337 |
+
self.activation_dropout = config.activation_dropout
|
| 338 |
+
|
| 339 |
+
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 340 |
+
self.encoder_attn = PegasusAttention(
|
| 341 |
+
self.embed_dim,
|
| 342 |
+
config.decoder_attention_heads,
|
| 343 |
+
dropout=config.attention_dropout,
|
| 344 |
+
is_decoder=True,
|
| 345 |
+
config=config,
|
| 346 |
+
layer_idx=layer_idx,
|
| 347 |
+
)
|
| 348 |
+
self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 349 |
+
self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
|
| 350 |
+
self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
|
| 351 |
+
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 352 |
+
|
| 353 |
+
def forward(
|
| 354 |
+
self,
|
| 355 |
+
hidden_states: torch.Tensor,
|
| 356 |
+
attention_mask: torch.Tensor | None = None,
|
| 357 |
+
encoder_hidden_states: torch.Tensor | None = None,
|
| 358 |
+
encoder_attention_mask: torch.Tensor | None = None,
|
| 359 |
+
past_key_values: Cache | None = None,
|
| 360 |
+
output_attentions: bool | None = False,
|
| 361 |
+
use_cache: bool | None = True,
|
| 362 |
+
cache_position: torch.Tensor | None = None,
|
| 363 |
+
) -> torch.Tensor:
|
| 364 |
+
"""
|
| 365 |
+
Args:
|
| 366 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 367 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
| 368 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 369 |
+
encoder_hidden_states (`torch.FloatTensor`):
|
| 370 |
+
cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 371 |
+
encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
|
| 372 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 373 |
+
past_key_values (`Cache`): cached past key and value projection states
|
| 374 |
+
output_attentions (`bool`, *optional*):
|
| 375 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 376 |
+
returned tensors for more detail.
|
| 377 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
| 378 |
+
Indices depicting the position of the input sequence tokens in the sequence. It is used to update the
|
| 379 |
+
cache in the correct position and to infer the complete sequence length.
|
| 380 |
+
"""
|
| 381 |
+
residual = hidden_states
|
| 382 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 383 |
+
|
| 384 |
+
# Self Attention
|
| 385 |
+
hidden_states, self_attn_weights = self.self_attn(
|
| 386 |
+
hidden_states=hidden_states,
|
| 387 |
+
past_key_values=past_key_values,
|
| 388 |
+
attention_mask=attention_mask,
|
| 389 |
+
output_attentions=output_attentions,
|
| 390 |
+
cache_position=cache_position,
|
| 391 |
+
)
|
| 392 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 393 |
+
hidden_states = residual + hidden_states
|
| 394 |
+
|
| 395 |
+
# Cross-Attention Block
|
| 396 |
+
cross_attn_weights = None
|
| 397 |
+
if encoder_hidden_states is not None:
|
| 398 |
+
residual = hidden_states
|
| 399 |
+
hidden_states = self.encoder_attn_layer_norm(hidden_states)
|
| 400 |
+
|
| 401 |
+
hidden_states, cross_attn_weights = self.encoder_attn(
|
| 402 |
+
hidden_states=hidden_states,
|
| 403 |
+
key_value_states=encoder_hidden_states,
|
| 404 |
+
attention_mask=encoder_attention_mask,
|
| 405 |
+
past_key_values=past_key_values,
|
| 406 |
+
output_attentions=output_attentions,
|
| 407 |
+
)
|
| 408 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 409 |
+
hidden_states = residual + hidden_states
|
| 410 |
+
|
| 411 |
+
# Fully Connected
|
| 412 |
+
residual = hidden_states
|
| 413 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 414 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 415 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
|
| 416 |
+
hidden_states = self.fc2(hidden_states)
|
| 417 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 418 |
+
hidden_states = residual + hidden_states
|
| 419 |
+
|
| 420 |
+
outputs = (hidden_states,)
|
| 421 |
+
|
| 422 |
+
if output_attentions:
|
| 423 |
+
outputs += (self_attn_weights, cross_attn_weights)
|
| 424 |
+
|
| 425 |
+
return outputs
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
@auto_docstring
|
| 429 |
+
class PegasusPreTrainedModel(PreTrainedModel):
|
| 430 |
+
config: PegasusConfig
|
| 431 |
+
base_model_prefix = "model"
|
| 432 |
+
supports_gradient_checkpointing = True
|
| 433 |
+
_supports_flash_attn = True
|
| 434 |
+
_supports_sdpa = True
|
| 435 |
+
_supports_flex_attn = True
|
| 436 |
+
_can_compile_fullgraph = True
|
| 437 |
+
|
| 438 |
+
@torch.no_grad()
|
| 439 |
+
def _init_weights(self, module):
|
| 440 |
+
super()._init_weights(module)
|
| 441 |
+
if isinstance(module, PegasusSinusoidalPositionalEmbedding):
|
| 442 |
+
init.copy_(module.weight, module.create_weight())
|
| 443 |
+
elif isinstance(module, PegasusForConditionalGeneration):
|
| 444 |
+
init.zeros_(module.final_logits_bias)
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
class PegasusEncoder(PegasusPreTrainedModel):
|
| 448 |
+
"""
|
| 449 |
+
Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
|
| 450 |
+
[`PegasusEncoderLayer`].
|
| 451 |
+
|
| 452 |
+
Args:
|
| 453 |
+
config: PegasusConfig
|
| 454 |
+
embed_tokens (nn.Embedding): output embedding
|
| 455 |
+
"""
|
| 456 |
+
|
| 457 |
+
def __init__(self, config: PegasusConfig):
|
| 458 |
+
super().__init__(config)
|
| 459 |
+
|
| 460 |
+
self.dropout = config.dropout
|
| 461 |
+
self.layerdrop = config.encoder_layerdrop
|
| 462 |
+
|
| 463 |
+
embed_dim = config.d_model
|
| 464 |
+
self.padding_idx = config.pad_token_id
|
| 465 |
+
self.max_source_positions = config.max_position_embeddings
|
| 466 |
+
self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
|
| 467 |
+
|
| 468 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, embed_dim, self.padding_idx)
|
| 469 |
+
|
| 470 |
+
self.embed_positions = PegasusSinusoidalPositionalEmbedding(
|
| 471 |
+
config.max_position_embeddings,
|
| 472 |
+
embed_dim,
|
| 473 |
+
self.padding_idx,
|
| 474 |
+
)
|
| 475 |
+
self.layers = nn.ModuleList([PegasusEncoderLayer(config) for _ in range(config.encoder_layers)])
|
| 476 |
+
self.layer_norm = nn.LayerNorm(config.d_model)
|
| 477 |
+
|
| 478 |
+
self.gradient_checkpointing = False
|
| 479 |
+
# Initialize weights and apply final processing
|
| 480 |
+
self.post_init()
|
| 481 |
+
|
| 482 |
+
def resize_position_embeddings(self, new_num_position_embeddings: int):
|
| 483 |
+
"""
|
| 484 |
+
Resizes position embeddings matrix of the model if `new_num_position_embeddings !=
|
| 485 |
+
config.max_position_embeddings`.
|
| 486 |
+
|
| 487 |
+
Arguments:
|
| 488 |
+
new_num_position_embeddings (`int`):
|
| 489 |
+
The number of new position embeddings. If position embeddings are learned, increasing the size will add
|
| 490 |
+
newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If
|
| 491 |
+
position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will
|
| 492 |
+
add correct vectors at the end following the position encoding algorithm, whereas reducing the size
|
| 493 |
+
will remove vectors from the end.
|
| 494 |
+
"""
|
| 495 |
+
logger.info(f"Setting `config.max_position_embeddings={new_num_position_embeddings}`...")
|
| 496 |
+
self.config.max_position_embeddings = new_num_position_embeddings
|
| 497 |
+
|
| 498 |
+
self.embed_positions = PegasusSinusoidalPositionalEmbedding(
|
| 499 |
+
self.config.max_position_embeddings,
|
| 500 |
+
self.config.d_model,
|
| 501 |
+
self.padding_idx,
|
| 502 |
+
)
|
| 503 |
+
init.copy_(self.embed_positions.weight, self.embed_positions.create_weight())
|
| 504 |
+
self.embed_positions.to(self.device)
|
| 505 |
+
|
| 506 |
+
def get_position_embeddings(self) -> nn.Embedding:
|
| 507 |
+
"""
|
| 508 |
+
Returns the position embeddings matrix
|
| 509 |
+
"""
|
| 510 |
+
return self.embed_positions
|
| 511 |
+
|
| 512 |
+
def forward(
|
| 513 |
+
self,
|
| 514 |
+
input_ids=None,
|
| 515 |
+
attention_mask=None,
|
| 516 |
+
inputs_embeds=None,
|
| 517 |
+
output_attentions=None,
|
| 518 |
+
output_hidden_states=None,
|
| 519 |
+
return_dict=None,
|
| 520 |
+
**kwargs,
|
| 521 |
+
):
|
| 522 |
+
r"""
|
| 523 |
+
Args:
|
| 524 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 525 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
|
| 526 |
+
provide it.
|
| 527 |
+
|
| 528 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 529 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 530 |
+
|
| 531 |
+
[What are input IDs?](../glossary#input-ids)
|
| 532 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 533 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 534 |
+
|
| 535 |
+
- 1 for tokens that are **not masked**,
|
| 536 |
+
- 0 for tokens that are **masked**.
|
| 537 |
+
|
| 538 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 539 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 540 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 541 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 542 |
+
than the model's internal embedding lookup matrix.
|
| 543 |
+
output_attentions (`bool`, *optional*):
|
| 544 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 545 |
+
returned tensors for more detail.
|
| 546 |
+
output_hidden_states (`bool`, *optional*):
|
| 547 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 548 |
+
for more detail.
|
| 549 |
+
return_dict (`bool`, *optional*):
|
| 550 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 551 |
+
"""
|
| 552 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 553 |
+
output_hidden_states = (
|
| 554 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 555 |
+
)
|
| 556 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 557 |
+
|
| 558 |
+
# retrieve input_ids and inputs_embeds
|
| 559 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 560 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 561 |
+
elif input_ids is not None:
|
| 562 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 563 |
+
input_shape = input_ids.size()
|
| 564 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
| 565 |
+
elif inputs_embeds is not None:
|
| 566 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 567 |
+
else:
|
| 568 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 569 |
+
|
| 570 |
+
if inputs_embeds is None:
|
| 571 |
+
inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
|
| 572 |
+
|
| 573 |
+
embed_pos = self.embed_positions(input_shape)
|
| 574 |
+
|
| 575 |
+
hidden_states = inputs_embeds + embed_pos
|
| 576 |
+
|
| 577 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 578 |
+
|
| 579 |
+
attention_mask = create_bidirectional_mask(
|
| 580 |
+
config=self.config,
|
| 581 |
+
inputs_embeds=inputs_embeds,
|
| 582 |
+
attention_mask=attention_mask,
|
| 583 |
+
)
|
| 584 |
+
|
| 585 |
+
encoder_states = () if output_hidden_states else None
|
| 586 |
+
all_attentions = () if output_attentions else None
|
| 587 |
+
|
| 588 |
+
for idx, encoder_layer in enumerate(self.layers):
|
| 589 |
+
if output_hidden_states:
|
| 590 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 591 |
+
# add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
|
| 592 |
+
to_drop = False
|
| 593 |
+
if self.training:
|
| 594 |
+
dropout_probability = torch.rand([])
|
| 595 |
+
if dropout_probability < self.layerdrop: # skip the layer
|
| 596 |
+
to_drop = True
|
| 597 |
+
|
| 598 |
+
if to_drop:
|
| 599 |
+
layer_outputs = (None, None)
|
| 600 |
+
else:
|
| 601 |
+
layer_outputs = encoder_layer(
|
| 602 |
+
hidden_states,
|
| 603 |
+
attention_mask,
|
| 604 |
+
output_attentions=output_attentions,
|
| 605 |
+
)
|
| 606 |
+
|
| 607 |
+
hidden_states = layer_outputs[0]
|
| 608 |
+
|
| 609 |
+
if output_attentions:
|
| 610 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 611 |
+
|
| 612 |
+
hidden_states = self.layer_norm(hidden_states)
|
| 613 |
+
|
| 614 |
+
if output_hidden_states:
|
| 615 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 616 |
+
|
| 617 |
+
if not return_dict:
|
| 618 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
| 619 |
+
return BaseModelOutput(
|
| 620 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
|
| 621 |
+
)
|
| 622 |
+
|
| 623 |
+
|
| 624 |
+
class PegasusDecoder(PegasusPreTrainedModel):
|
| 625 |
+
"""
|
| 626 |
+
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`PegasusDecoderLayer`]
|
| 627 |
+
|
| 628 |
+
Args:
|
| 629 |
+
config: PegasusConfig
|
| 630 |
+
embed_tokens (nn.Embedding): output embedding
|
| 631 |
+
"""
|
| 632 |
+
|
| 633 |
+
def __init__(self, config: PegasusConfig):
|
| 634 |
+
super().__init__(config)
|
| 635 |
+
self.dropout = config.dropout
|
| 636 |
+
self.layerdrop = config.decoder_layerdrop
|
| 637 |
+
self.padding_idx = config.pad_token_id
|
| 638 |
+
self.max_target_positions = config.max_position_embeddings
|
| 639 |
+
self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
|
| 640 |
+
|
| 641 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model, self.padding_idx)
|
| 642 |
+
|
| 643 |
+
self.embed_positions = PegasusSinusoidalPositionalEmbedding(
|
| 644 |
+
config.max_position_embeddings,
|
| 645 |
+
config.d_model,
|
| 646 |
+
self.padding_idx,
|
| 647 |
+
)
|
| 648 |
+
self.layers = nn.ModuleList([PegasusDecoderLayer(config, layer_idx=i) for i in range(config.decoder_layers)])
|
| 649 |
+
self.layer_norm = nn.LayerNorm(config.d_model)
|
| 650 |
+
|
| 651 |
+
self.gradient_checkpointing = False
|
| 652 |
+
# Initialize weights and apply final processing
|
| 653 |
+
self.post_init()
|
| 654 |
+
|
| 655 |
+
def resize_position_embeddings(self, new_num_position_embeddings: int):
|
| 656 |
+
"""
|
| 657 |
+
Resizes position embeddings matrix of the model if `new_num_position_embeddings !=
|
| 658 |
+
config.max_position_embeddings`.
|
| 659 |
+
|
| 660 |
+
Arguments:
|
| 661 |
+
new_num_position_embeddings (`int`):
|
| 662 |
+
The number of new position embeddings. If position embeddings are learned, increasing the size will add
|
| 663 |
+
newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If
|
| 664 |
+
position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will
|
| 665 |
+
add correct vectors at the end following the position encoding algorithm, whereas reducing the size
|
| 666 |
+
will remove vectors from the end.
|
| 667 |
+
"""
|
| 668 |
+
logger.info(f"Setting `config.max_position_embeddings={new_num_position_embeddings}`...")
|
| 669 |
+
self.config.max_position_embeddings = new_num_position_embeddings
|
| 670 |
+
|
| 671 |
+
self.embed_positions = PegasusSinusoidalPositionalEmbedding(
|
| 672 |
+
self.config.max_position_embeddings,
|
| 673 |
+
self.config.d_model,
|
| 674 |
+
self.padding_idx,
|
| 675 |
+
)
|
| 676 |
+
init.copy_(self.embed_positions.weight, self.embed_positions.create_weight())
|
| 677 |
+
self.embed_positions.to(self.device)
|
| 678 |
+
|
| 679 |
+
def get_position_embeddings(self) -> nn.Embedding:
|
| 680 |
+
"""
|
| 681 |
+
Returns the position embeddings matrix
|
| 682 |
+
"""
|
| 683 |
+
return self.embed_positions
|
| 684 |
+
|
| 685 |
+
def forward(
|
| 686 |
+
self,
|
| 687 |
+
input_ids=None,
|
| 688 |
+
attention_mask=None,
|
| 689 |
+
encoder_hidden_states=None,
|
| 690 |
+
encoder_attention_mask=None,
|
| 691 |
+
past_key_values=None,
|
| 692 |
+
inputs_embeds=None,
|
| 693 |
+
use_cache=None,
|
| 694 |
+
output_attentions=None,
|
| 695 |
+
output_hidden_states=None,
|
| 696 |
+
return_dict=None,
|
| 697 |
+
cache_position=None,
|
| 698 |
+
**kwargs,
|
| 699 |
+
):
|
| 700 |
+
r"""
|
| 701 |
+
Args:
|
| 702 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 703 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
|
| 704 |
+
provide it.
|
| 705 |
+
|
| 706 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 707 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 708 |
+
|
| 709 |
+
[What are input IDs?](../glossary#input-ids)
|
| 710 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 711 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 712 |
+
|
| 713 |
+
- 1 for tokens that are **not masked**,
|
| 714 |
+
- 0 for tokens that are **masked**.
|
| 715 |
+
|
| 716 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 717 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
|
| 718 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
|
| 719 |
+
of the decoder.
|
| 720 |
+
encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
|
| 721 |
+
Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
|
| 722 |
+
selected in `[0, 1]`:
|
| 723 |
+
|
| 724 |
+
- 1 for tokens that are **not masked**,
|
| 725 |
+
- 0 for tokens that are **masked**.
|
| 726 |
+
|
| 727 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 728 |
+
past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 729 |
+
It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
|
| 730 |
+
|
| 731 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
|
| 732 |
+
cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
| 733 |
+
|
| 734 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
|
| 735 |
+
that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
|
| 736 |
+
all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 737 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 738 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 739 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 740 |
+
than the model's internal embedding lookup matrix.
|
| 741 |
+
output_attentions (`bool`, *optional*):
|
| 742 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 743 |
+
returned tensors for more detail.
|
| 744 |
+
output_hidden_states (`bool`, *optional*):
|
| 745 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 746 |
+
for more detail.
|
| 747 |
+
return_dict (`bool`, *optional*):
|
| 748 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 749 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
| 750 |
+
Indices depicting the position of the input sequence tokens in the sequence. It is used to update the
|
| 751 |
+
cache in the correct position and to infer the complete sequence length.
|
| 752 |
+
"""
|
| 753 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 754 |
+
output_hidden_states = (
|
| 755 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 756 |
+
)
|
| 757 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 758 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 759 |
+
|
| 760 |
+
# retrieve input_ids and inputs_embeds
|
| 761 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 762 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
| 763 |
+
elif input_ids is not None:
|
| 764 |
+
input = input_ids
|
| 765 |
+
input_shape = input.shape
|
| 766 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
| 767 |
+
elif inputs_embeds is not None:
|
| 768 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 769 |
+
input = inputs_embeds[:, :, -1]
|
| 770 |
+
else:
|
| 771 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
| 772 |
+
|
| 773 |
+
if inputs_embeds is None:
|
| 774 |
+
inputs_embeds = self.embed_tokens(input)
|
| 775 |
+
|
| 776 |
+
# important to apply scale outside of `if` in case users pass `embeds`
|
| 777 |
+
inputs_embeds = inputs_embeds * self.embed_scale
|
| 778 |
+
|
| 779 |
+
if self.gradient_checkpointing and self.training:
|
| 780 |
+
if use_cache:
|
| 781 |
+
logger.warning_once(
|
| 782 |
+
"`use_cache=True` is incompatible with gradient checkpointing`. Setting `use_cache=False`..."
|
| 783 |
+
)
|
| 784 |
+
use_cache = False
|
| 785 |
+
|
| 786 |
+
# initialize `past_key_values`
|
| 787 |
+
if use_cache and past_key_values is None:
|
| 788 |
+
past_key_values = (
|
| 789 |
+
EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
|
| 790 |
+
if encoder_hidden_states is not None or self.config.is_encoder_decoder
|
| 791 |
+
else DynamicCache(config=self.config)
|
| 792 |
+
)
|
| 793 |
+
|
| 794 |
+
batch_size, seq_length = inputs_embeds.size()[:-1]
|
| 795 |
+
past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 796 |
+
if cache_position is None:
|
| 797 |
+
cache_position = torch.arange(
|
| 798 |
+
past_key_values_length, past_key_values_length + seq_length, device=inputs_embeds.device
|
| 799 |
+
)
|
| 800 |
+
|
| 801 |
+
if attention_mask is None and not is_torchdynamo_compiling():
|
| 802 |
+
# required mask seq length can be calculated via length of past cache
|
| 803 |
+
mask_seq_length = past_key_values_length + seq_length
|
| 804 |
+
attention_mask = torch.ones(batch_size, mask_seq_length, device=inputs_embeds.device)
|
| 805 |
+
|
| 806 |
+
self_attn_cache = (
|
| 807 |
+
past_key_values.self_attention_cache
|
| 808 |
+
if isinstance(past_key_values, EncoderDecoderCache)
|
| 809 |
+
else past_key_values
|
| 810 |
+
)
|
| 811 |
+
|
| 812 |
+
causal_mask = create_causal_mask(
|
| 813 |
+
config=self.config,
|
| 814 |
+
inputs_embeds=inputs_embeds,
|
| 815 |
+
attention_mask=attention_mask,
|
| 816 |
+
cache_position=cache_position,
|
| 817 |
+
past_key_values=self_attn_cache,
|
| 818 |
+
)
|
| 819 |
+
encoder_attention_mask = create_bidirectional_mask(
|
| 820 |
+
config=self.config,
|
| 821 |
+
inputs_embeds=inputs_embeds,
|
| 822 |
+
attention_mask=encoder_attention_mask,
|
| 823 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 824 |
+
)
|
| 825 |
+
|
| 826 |
+
# embed positions
|
| 827 |
+
positions = self.embed_positions((batch_size, seq_length), past_key_values_length, position_ids=cache_position)
|
| 828 |
+
hidden_states = inputs_embeds + positions
|
| 829 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 830 |
+
|
| 831 |
+
# decoder layers
|
| 832 |
+
all_hidden_states = () if output_hidden_states else None
|
| 833 |
+
all_self_attns = () if output_attentions else None
|
| 834 |
+
all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
|
| 835 |
+
|
| 836 |
+
for idx, decoder_layer in enumerate(self.layers):
|
| 837 |
+
# add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
|
| 838 |
+
if output_hidden_states:
|
| 839 |
+
all_hidden_states += (hidden_states,)
|
| 840 |
+
if self.training:
|
| 841 |
+
dropout_probability = torch.rand([])
|
| 842 |
+
if dropout_probability < self.layerdrop:
|
| 843 |
+
continue
|
| 844 |
+
|
| 845 |
+
layer_outputs = decoder_layer(
|
| 846 |
+
hidden_states,
|
| 847 |
+
causal_mask,
|
| 848 |
+
encoder_hidden_states, # as a positional argument for gradient checkpointing
|
| 849 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 850 |
+
past_key_values=past_key_values,
|
| 851 |
+
output_attentions=output_attentions,
|
| 852 |
+
use_cache=use_cache,
|
| 853 |
+
cache_position=cache_position,
|
| 854 |
+
)
|
| 855 |
+
hidden_states = layer_outputs[0]
|
| 856 |
+
|
| 857 |
+
if output_attentions:
|
| 858 |
+
all_self_attns += (layer_outputs[1],)
|
| 859 |
+
|
| 860 |
+
if encoder_hidden_states is not None:
|
| 861 |
+
all_cross_attentions += (layer_outputs[2],)
|
| 862 |
+
|
| 863 |
+
hidden_states = self.layer_norm(hidden_states)
|
| 864 |
+
|
| 865 |
+
# add hidden states from the last decoder layer
|
| 866 |
+
if output_hidden_states:
|
| 867 |
+
all_hidden_states += (hidden_states,)
|
| 868 |
+
|
| 869 |
+
if not return_dict:
|
| 870 |
+
return tuple(
|
| 871 |
+
v
|
| 872 |
+
for v in [hidden_states, past_key_values, all_hidden_states, all_self_attns, all_cross_attentions]
|
| 873 |
+
if v is not None
|
| 874 |
+
)
|
| 875 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 876 |
+
last_hidden_state=hidden_states,
|
| 877 |
+
past_key_values=past_key_values,
|
| 878 |
+
hidden_states=all_hidden_states,
|
| 879 |
+
attentions=all_self_attns,
|
| 880 |
+
cross_attentions=all_cross_attentions,
|
| 881 |
+
)
|
| 882 |
+
|
| 883 |
+
|
| 884 |
+
@auto_docstring
|
| 885 |
+
class PegasusModel(PegasusPreTrainedModel):
|
| 886 |
+
_tied_weights_keys = {
|
| 887 |
+
"decoder.embed_tokens.weight": "shared.weight",
|
| 888 |
+
"encoder.embed_tokens.weight": "shared.weight",
|
| 889 |
+
}
|
| 890 |
+
|
| 891 |
+
def __init__(self, config: PegasusConfig):
|
| 892 |
+
super().__init__(config)
|
| 893 |
+
|
| 894 |
+
padding_idx, vocab_size = config.pad_token_id, config.vocab_size
|
| 895 |
+
self.shared = nn.Embedding(vocab_size, config.d_model, padding_idx)
|
| 896 |
+
|
| 897 |
+
self.encoder = PegasusEncoder(config)
|
| 898 |
+
self.decoder = PegasusDecoder(config)
|
| 899 |
+
|
| 900 |
+
# Initialize weights and apply final processing
|
| 901 |
+
self.post_init()
|
| 902 |
+
|
| 903 |
+
def get_input_embeddings(self):
|
| 904 |
+
return self.shared
|
| 905 |
+
|
| 906 |
+
def set_input_embeddings(self, value):
|
| 907 |
+
self.shared = value
|
| 908 |
+
self.encoder.embed_tokens = self.shared
|
| 909 |
+
self.decoder.embed_tokens = self.shared
|
| 910 |
+
|
| 911 |
+
def resize_position_embeddings(self, new_num_position_embeddings: int):
|
| 912 |
+
"""
|
| 913 |
+
Resizes position embeddings matrix of the model if `new_num_position_embeddings !=
|
| 914 |
+
config.max_position_embeddings`.
|
| 915 |
+
|
| 916 |
+
Arguments:
|
| 917 |
+
new_num_position_embeddings (`int`):
|
| 918 |
+
The number of new position embeddings. If position embeddings are learned, increasing the size will add
|
| 919 |
+
newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If
|
| 920 |
+
position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will
|
| 921 |
+
add correct vectors at the end following the position encoding algorithm, whereas reducing the size
|
| 922 |
+
will remove vectors from the end.
|
| 923 |
+
"""
|
| 924 |
+
self.config.max_position_embeddings = new_num_position_embeddings
|
| 925 |
+
self.encoder.resize_position_embeddings(new_num_position_embeddings)
|
| 926 |
+
self.decoder.resize_position_embeddings(new_num_position_embeddings)
|
| 927 |
+
|
| 928 |
+
def get_position_embeddings(self) -> tuple[nn.Embedding]:
|
| 929 |
+
"""
|
| 930 |
+
Returns the position embeddings matrix
|
| 931 |
+
"""
|
| 932 |
+
return (self.encoder.get_position_embeddings(), self.decoder.get_position_embeddings())
|
| 933 |
+
|
| 934 |
+
@auto_docstring
|
| 935 |
+
def forward(
|
| 936 |
+
self,
|
| 937 |
+
input_ids: torch.Tensor | None = None,
|
| 938 |
+
attention_mask: torch.Tensor | None = None,
|
| 939 |
+
decoder_input_ids: torch.Tensor | None = None,
|
| 940 |
+
decoder_attention_mask: torch.Tensor | None = None,
|
| 941 |
+
encoder_outputs: tuple[torch.FloatTensor] | None = None,
|
| 942 |
+
past_key_values: Cache | None = None,
|
| 943 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 944 |
+
decoder_inputs_embeds: torch.Tensor | None = None,
|
| 945 |
+
use_cache: bool | None = None,
|
| 946 |
+
output_attentions: bool | None = None,
|
| 947 |
+
output_hidden_states: bool | None = None,
|
| 948 |
+
return_dict: bool | None = None,
|
| 949 |
+
cache_position: torch.Tensor | None = None,
|
| 950 |
+
**kwargs,
|
| 951 |
+
) -> tuple | Seq2SeqModelOutput:
|
| 952 |
+
r"""
|
| 953 |
+
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 954 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 955 |
+
|
| 956 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 957 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 958 |
+
|
| 959 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 960 |
+
|
| 961 |
+
Pegasus uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If
|
| 962 |
+
`past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
| 963 |
+
`past_key_values`).
|
| 964 |
+
decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 965 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 966 |
+
be used by default.
|
| 967 |
+
|
| 968 |
+
Example:
|
| 969 |
+
|
| 970 |
+
```python
|
| 971 |
+
>>> from transformers import AutoTokenizer, PegasusModel
|
| 972 |
+
|
| 973 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/pegasus-large")
|
| 974 |
+
>>> model = PegasusModel.from_pretrained("google/pegasus-large")
|
| 975 |
+
|
| 976 |
+
>>> inputs = tokenizer("Studies have been shown that owning a dog is good for you", return_tensors="pt")
|
| 977 |
+
>>> decoder_inputs = tokenizer("Studies show that", return_tensors="pt")
|
| 978 |
+
>>> outputs = model(input_ids=inputs.input_ids, decoder_input_ids=decoder_inputs.input_ids)
|
| 979 |
+
|
| 980 |
+
>>> last_hidden_states = outputs.last_hidden_state
|
| 981 |
+
>>> list(last_hidden_states.shape)
|
| 982 |
+
[1, 4, 1024]
|
| 983 |
+
```"""
|
| 984 |
+
|
| 985 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 986 |
+
output_hidden_states = (
|
| 987 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 988 |
+
)
|
| 989 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 990 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 991 |
+
|
| 992 |
+
if encoder_outputs is None:
|
| 993 |
+
encoder_outputs = self.encoder(
|
| 994 |
+
input_ids=input_ids,
|
| 995 |
+
attention_mask=attention_mask,
|
| 996 |
+
inputs_embeds=inputs_embeds,
|
| 997 |
+
output_attentions=output_attentions,
|
| 998 |
+
output_hidden_states=output_hidden_states,
|
| 999 |
+
return_dict=return_dict,
|
| 1000 |
+
)
|
| 1001 |
+
# If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
|
| 1002 |
+
elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
|
| 1003 |
+
encoder_outputs = BaseModelOutput(
|
| 1004 |
+
last_hidden_state=encoder_outputs[0],
|
| 1005 |
+
hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
|
| 1006 |
+
attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
|
| 1007 |
+
)
|
| 1008 |
+
|
| 1009 |
+
# decoder outputs consists of (dec_features, past_key_values, dec_hidden, dec_attn)
|
| 1010 |
+
decoder_outputs = self.decoder(
|
| 1011 |
+
input_ids=decoder_input_ids,
|
| 1012 |
+
attention_mask=decoder_attention_mask,
|
| 1013 |
+
encoder_hidden_states=encoder_outputs[0],
|
| 1014 |
+
encoder_attention_mask=attention_mask,
|
| 1015 |
+
past_key_values=past_key_values,
|
| 1016 |
+
inputs_embeds=decoder_inputs_embeds,
|
| 1017 |
+
use_cache=use_cache,
|
| 1018 |
+
output_attentions=output_attentions,
|
| 1019 |
+
output_hidden_states=output_hidden_states,
|
| 1020 |
+
return_dict=return_dict,
|
| 1021 |
+
cache_position=cache_position,
|
| 1022 |
+
)
|
| 1023 |
+
|
| 1024 |
+
if not return_dict:
|
| 1025 |
+
return decoder_outputs + encoder_outputs
|
| 1026 |
+
|
| 1027 |
+
return Seq2SeqModelOutput(
|
| 1028 |
+
last_hidden_state=decoder_outputs.last_hidden_state,
|
| 1029 |
+
past_key_values=decoder_outputs.past_key_values,
|
| 1030 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 1031 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 1032 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 1033 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
| 1034 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 1035 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 1036 |
+
)
|
| 1037 |
+
|
| 1038 |
+
|
| 1039 |
+
@auto_docstring(
|
| 1040 |
+
custom_intro="""
|
| 1041 |
+
The PEGASUS Model with a language modeling head. Can be used for summarization.
|
| 1042 |
+
"""
|
| 1043 |
+
)
|
| 1044 |
+
class PegasusForConditionalGeneration(PegasusPreTrainedModel, GenerationMixin):
|
| 1045 |
+
base_model_prefix = "model"
|
| 1046 |
+
_keys_to_ignore_on_load_missing = ["final_logits_bias"]
|
| 1047 |
+
_tied_weights_keys = {
|
| 1048 |
+
"lm_head.weight": "model.shared.weight",
|
| 1049 |
+
}
|
| 1050 |
+
|
| 1051 |
+
def __init__(self, config: PegasusConfig):
|
| 1052 |
+
super().__init__(config)
|
| 1053 |
+
self.model = PegasusModel(config)
|
| 1054 |
+
self.register_buffer("final_logits_bias", torch.zeros((1, self.model.shared.num_embeddings)))
|
| 1055 |
+
self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)
|
| 1056 |
+
|
| 1057 |
+
# Initialize weights and apply final processing
|
| 1058 |
+
self.post_init()
|
| 1059 |
+
|
| 1060 |
+
def resize_token_embeddings(
|
| 1061 |
+
self, new_num_tokens: int, pad_to_multiple_of: int | None = None, mean_resizing: bool = True
|
| 1062 |
+
) -> nn.Embedding:
|
| 1063 |
+
new_embeddings = super().resize_token_embeddings(new_num_tokens, pad_to_multiple_of, mean_resizing)
|
| 1064 |
+
self._resize_final_logits_bias(new_embeddings.weight.shape[0])
|
| 1065 |
+
return new_embeddings
|
| 1066 |
+
|
| 1067 |
+
def _resize_final_logits_bias(self, new_num_tokens: int) -> None:
|
| 1068 |
+
old_num_tokens = self.final_logits_bias.shape[-1]
|
| 1069 |
+
if new_num_tokens <= old_num_tokens:
|
| 1070 |
+
new_bias = self.final_logits_bias[:, :new_num_tokens]
|
| 1071 |
+
else:
|
| 1072 |
+
extra_bias = torch.zeros((1, new_num_tokens - old_num_tokens), device=self.final_logits_bias.device)
|
| 1073 |
+
new_bias = torch.cat([self.final_logits_bias, extra_bias], dim=1)
|
| 1074 |
+
self.register_buffer("final_logits_bias", new_bias)
|
| 1075 |
+
|
| 1076 |
+
def resize_position_embeddings(self, new_num_position_embeddings: int):
|
| 1077 |
+
"""
|
| 1078 |
+
Resizes position embeddings matrix of the model if `new_num_position_embeddings !=
|
| 1079 |
+
config.max_position_embeddings`.
|
| 1080 |
+
|
| 1081 |
+
Arguments:
|
| 1082 |
+
new_num_position_embeddings (`int`):
|
| 1083 |
+
The number of new position embeddings. If position embeddings are learned, increasing the size will add
|
| 1084 |
+
newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If
|
| 1085 |
+
position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will
|
| 1086 |
+
add correct vectors at the end following the position encoding algorithm, whereas reducing the size
|
| 1087 |
+
will remove vectors from the end.
|
| 1088 |
+
"""
|
| 1089 |
+
self.config.max_position_embeddings = new_num_position_embeddings
|
| 1090 |
+
self.model.encoder.resize_position_embeddings(new_num_position_embeddings)
|
| 1091 |
+
self.model.decoder.resize_position_embeddings(new_num_position_embeddings)
|
| 1092 |
+
|
| 1093 |
+
def get_position_embeddings(self) -> tuple[nn.Embedding]:
|
| 1094 |
+
"""
|
| 1095 |
+
Returns the position embeddings matrix
|
| 1096 |
+
"""
|
| 1097 |
+
return (self.model.encoder.get_position_embeddings(), self.model.decoder.get_position_embeddings())
|
| 1098 |
+
|
| 1099 |
+
@auto_docstring
|
| 1100 |
+
def forward(
|
| 1101 |
+
self,
|
| 1102 |
+
input_ids: torch.Tensor | None = None,
|
| 1103 |
+
attention_mask: torch.Tensor | None = None,
|
| 1104 |
+
decoder_input_ids: torch.Tensor | None = None,
|
| 1105 |
+
decoder_attention_mask: torch.Tensor | None = None,
|
| 1106 |
+
encoder_outputs: tuple[torch.FloatTensor] | None = None,
|
| 1107 |
+
past_key_values: Cache | None = None,
|
| 1108 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 1109 |
+
decoder_inputs_embeds: torch.Tensor | None = None,
|
| 1110 |
+
labels: torch.Tensor | None = None,
|
| 1111 |
+
use_cache: bool | None = None,
|
| 1112 |
+
output_attentions: bool | None = None,
|
| 1113 |
+
output_hidden_states: bool | None = None,
|
| 1114 |
+
return_dict: bool | None = None,
|
| 1115 |
+
cache_position: torch.Tensor | None = None,
|
| 1116 |
+
**kwargs,
|
| 1117 |
+
) -> tuple | Seq2SeqLMOutput:
|
| 1118 |
+
r"""
|
| 1119 |
+
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 1120 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 1121 |
+
|
| 1122 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1123 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 1124 |
+
|
| 1125 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 1126 |
+
|
| 1127 |
+
Pegasus uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If
|
| 1128 |
+
`past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
| 1129 |
+
`past_key_values`).
|
| 1130 |
+
decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 1131 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 1132 |
+
be used by default.
|
| 1133 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1134 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 1135 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 1136 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 1137 |
+
|
| 1138 |
+
Example Summarization:
|
| 1139 |
+
|
| 1140 |
+
```python
|
| 1141 |
+
>>> from transformers import AutoTokenizer, PegasusForConditionalGeneration
|
| 1142 |
+
|
| 1143 |
+
>>> model = PegasusForConditionalGeneration.from_pretrained("google/pegasus-xsum")
|
| 1144 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/pegasus-xsum")
|
| 1145 |
+
|
| 1146 |
+
>>> ARTICLE_TO_SUMMARIZE = (
|
| 1147 |
+
... "PG&E stated it scheduled the blackouts in response to forecasts for high winds "
|
| 1148 |
+
... "amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were "
|
| 1149 |
+
... "scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow."
|
| 1150 |
+
... )
|
| 1151 |
+
>>> inputs = tokenizer(ARTICLE_TO_SUMMARIZE, max_length=1024, return_tensors="pt")
|
| 1152 |
+
|
| 1153 |
+
>>> # Generate Summary
|
| 1154 |
+
>>> summary_ids = model.generate(inputs["input_ids"])
|
| 1155 |
+
>>> tokenizer.batch_decode(summary_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 1156 |
+
"California's largest electricity provider has turned off power to hundreds of thousands of customers."
|
| 1157 |
+
```
|
| 1158 |
+
"""
|
| 1159 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1160 |
+
|
| 1161 |
+
if labels is not None:
|
| 1162 |
+
if use_cache:
|
| 1163 |
+
logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
|
| 1164 |
+
use_cache = False
|
| 1165 |
+
if decoder_input_ids is None and decoder_inputs_embeds is None:
|
| 1166 |
+
decoder_input_ids = shift_tokens_right(
|
| 1167 |
+
labels, self.config.pad_token_id, self.config.decoder_start_token_id
|
| 1168 |
+
)
|
| 1169 |
+
|
| 1170 |
+
outputs = self.model(
|
| 1171 |
+
input_ids,
|
| 1172 |
+
attention_mask=attention_mask,
|
| 1173 |
+
decoder_input_ids=decoder_input_ids,
|
| 1174 |
+
encoder_outputs=encoder_outputs,
|
| 1175 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1176 |
+
past_key_values=past_key_values,
|
| 1177 |
+
inputs_embeds=inputs_embeds,
|
| 1178 |
+
decoder_inputs_embeds=decoder_inputs_embeds,
|
| 1179 |
+
use_cache=use_cache,
|
| 1180 |
+
output_attentions=output_attentions,
|
| 1181 |
+
output_hidden_states=output_hidden_states,
|
| 1182 |
+
return_dict=return_dict,
|
| 1183 |
+
cache_position=cache_position,
|
| 1184 |
+
)
|
| 1185 |
+
lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias
|
| 1186 |
+
|
| 1187 |
+
masked_lm_loss = None
|
| 1188 |
+
if labels is not None:
|
| 1189 |
+
loss_fct = CrossEntropyLoss()
|
| 1190 |
+
masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))
|
| 1191 |
+
|
| 1192 |
+
if not return_dict:
|
| 1193 |
+
output = (lm_logits,) + outputs[1:]
|
| 1194 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
| 1195 |
+
|
| 1196 |
+
return Seq2SeqLMOutput(
|
| 1197 |
+
loss=masked_lm_loss,
|
| 1198 |
+
logits=lm_logits,
|
| 1199 |
+
past_key_values=outputs.past_key_values,
|
| 1200 |
+
decoder_hidden_states=outputs.decoder_hidden_states,
|
| 1201 |
+
decoder_attentions=outputs.decoder_attentions,
|
| 1202 |
+
cross_attentions=outputs.cross_attentions,
|
| 1203 |
+
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
|
| 1204 |
+
encoder_hidden_states=outputs.encoder_hidden_states,
|
| 1205 |
+
encoder_attentions=outputs.encoder_attentions,
|
| 1206 |
+
)
|
| 1207 |
+
|
| 1208 |
+
def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
|
| 1209 |
+
return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id)
|
| 1210 |
+
|
| 1211 |
+
|
| 1212 |
+
# Copied from transformers.models.bart.modeling_bart.BartDecoderWrapper with Bart->Pegasus
|
| 1213 |
+
class PegasusDecoderWrapper(PegasusPreTrainedModel):
|
| 1214 |
+
"""
|
| 1215 |
+
This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
|
| 1216 |
+
used in combination with the [`EncoderDecoderModel`] framework.
|
| 1217 |
+
"""
|
| 1218 |
+
|
| 1219 |
+
def __init__(self, config):
|
| 1220 |
+
super().__init__(config)
|
| 1221 |
+
self.decoder = PegasusDecoder(config)
|
| 1222 |
+
self.post_init()
|
| 1223 |
+
|
| 1224 |
+
def forward(self, *args, **kwargs):
|
| 1225 |
+
return self.decoder(*args, **kwargs)
|
| 1226 |
+
|
| 1227 |
+
|
| 1228 |
+
class PegasusForCausalLM(PegasusPreTrainedModel, GenerationMixin):
|
| 1229 |
+
_tied_weights_keys = {
|
| 1230 |
+
"lm_head.weight": "model.decoder.embed_tokens.weight",
|
| 1231 |
+
}
|
| 1232 |
+
|
| 1233 |
+
def __init__(self, config):
|
| 1234 |
+
config = copy.deepcopy(config)
|
| 1235 |
+
config.is_decoder = True
|
| 1236 |
+
config.is_encoder_decoder = False
|
| 1237 |
+
super().__init__(config)
|
| 1238 |
+
self.model = PegasusDecoderWrapper(config)
|
| 1239 |
+
|
| 1240 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 1241 |
+
|
| 1242 |
+
# Initialize weights and apply final processing
|
| 1243 |
+
self.post_init()
|
| 1244 |
+
|
| 1245 |
+
def get_input_embeddings(self):
|
| 1246 |
+
return self.model.decoder.embed_tokens
|
| 1247 |
+
|
| 1248 |
+
def set_input_embeddings(self, value):
|
| 1249 |
+
self.model.decoder.embed_tokens = value
|
| 1250 |
+
|
| 1251 |
+
def get_position_embeddings(self) -> nn.Embedding:
|
| 1252 |
+
"""
|
| 1253 |
+
Returns the position embeddings matrix
|
| 1254 |
+
"""
|
| 1255 |
+
return self.model.decoder.get_position_embeddings()
|
| 1256 |
+
|
| 1257 |
+
def resize_position_embeddings(self, new_num_position_embeddings: int):
|
| 1258 |
+
"""
|
| 1259 |
+
Resizes position embeddings matrix of the model if `new_num_position_embeddings !=
|
| 1260 |
+
config.max_position_embeddings`.
|
| 1261 |
+
|
| 1262 |
+
Arguments:
|
| 1263 |
+
new_num_position_embeddings (`int`):
|
| 1264 |
+
The number of new position embeddings. If position embeddings are learned, increasing the size will add
|
| 1265 |
+
newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If
|
| 1266 |
+
position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will
|
| 1267 |
+
add correct vectors at the end following the position encoding algorithm, whereas reducing the size
|
| 1268 |
+
will remove vectors from the end.
|
| 1269 |
+
"""
|
| 1270 |
+
self.config.max_position_embeddings = new_num_position_embeddings
|
| 1271 |
+
self.model.decoder.resize_position_embeddings(new_num_position_embeddings)
|
| 1272 |
+
|
| 1273 |
+
@auto_docstring
|
| 1274 |
+
# Copied from transformers.models.bart.modeling_bart.BartForCausalLM.forward with Bart->Pegasus, facebook/bart-base->google/pegasus-large
|
| 1275 |
+
def forward(
|
| 1276 |
+
self,
|
| 1277 |
+
input_ids: torch.LongTensor | None = None,
|
| 1278 |
+
attention_mask: torch.Tensor | None = None,
|
| 1279 |
+
encoder_hidden_states: torch.FloatTensor | None = None,
|
| 1280 |
+
encoder_attention_mask: torch.FloatTensor | None = None,
|
| 1281 |
+
past_key_values: Cache | None = None,
|
| 1282 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 1283 |
+
labels: torch.LongTensor | None = None,
|
| 1284 |
+
use_cache: bool | None = None,
|
| 1285 |
+
output_attentions: bool | None = None,
|
| 1286 |
+
output_hidden_states: bool | None = None,
|
| 1287 |
+
return_dict: bool | None = None,
|
| 1288 |
+
cache_position: torch.LongTensor | None = None,
|
| 1289 |
+
logits_to_keep: int | torch.Tensor = 0,
|
| 1290 |
+
**kwargs,
|
| 1291 |
+
) -> tuple | CausalLMOutputWithCrossAttentions:
|
| 1292 |
+
r"""
|
| 1293 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1294 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 1295 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 1296 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 1297 |
+
|
| 1298 |
+
Example:
|
| 1299 |
+
|
| 1300 |
+
```python
|
| 1301 |
+
>>> from transformers import AutoTokenizer, PegasusForCausalLM
|
| 1302 |
+
|
| 1303 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/pegasus-large")
|
| 1304 |
+
>>> model = PegasusForCausalLM.from_pretrained("google/pegasus-large")
|
| 1305 |
+
>>> assert model.config.is_decoder, f"{model.__class__} has to be configured as a decoder."
|
| 1306 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
|
| 1307 |
+
>>> outputs = model(**inputs)
|
| 1308 |
+
|
| 1309 |
+
>>> logits = outputs.logits
|
| 1310 |
+
>>> expected_shape = [1, inputs.input_ids.shape[-1], model.config.vocab_size]
|
| 1311 |
+
>>> list(logits.shape) == expected_shape
|
| 1312 |
+
True
|
| 1313 |
+
```"""
|
| 1314 |
+
|
| 1315 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1316 |
+
output_hidden_states = (
|
| 1317 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1318 |
+
)
|
| 1319 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1320 |
+
|
| 1321 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 1322 |
+
outputs = self.model.decoder(
|
| 1323 |
+
input_ids=input_ids,
|
| 1324 |
+
attention_mask=attention_mask,
|
| 1325 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1326 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1327 |
+
past_key_values=past_key_values,
|
| 1328 |
+
inputs_embeds=inputs_embeds,
|
| 1329 |
+
use_cache=use_cache,
|
| 1330 |
+
output_attentions=output_attentions,
|
| 1331 |
+
output_hidden_states=output_hidden_states,
|
| 1332 |
+
return_dict=return_dict,
|
| 1333 |
+
cache_position=cache_position,
|
| 1334 |
+
)
|
| 1335 |
+
|
| 1336 |
+
hidden_states = outputs[0]
|
| 1337 |
+
# Only compute necessary logits
|
| 1338 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 1339 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
| 1340 |
+
|
| 1341 |
+
loss = None
|
| 1342 |
+
if labels is not None:
|
| 1343 |
+
labels = labels.to(logits.device)
|
| 1344 |
+
loss_fct = CrossEntropyLoss()
|
| 1345 |
+
loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
|
| 1346 |
+
|
| 1347 |
+
if not return_dict:
|
| 1348 |
+
output = (logits,) + outputs[1:]
|
| 1349 |
+
return (loss,) + output if loss is not None else output
|
| 1350 |
+
|
| 1351 |
+
return CausalLMOutputWithCrossAttentions(
|
| 1352 |
+
loss=loss,
|
| 1353 |
+
logits=logits,
|
| 1354 |
+
past_key_values=outputs.past_key_values,
|
| 1355 |
+
hidden_states=outputs.hidden_states,
|
| 1356 |
+
attentions=outputs.attentions,
|
| 1357 |
+
cross_attentions=outputs.cross_attentions,
|
| 1358 |
+
)
|
| 1359 |
+
|
| 1360 |
+
|
| 1361 |
+
__all__ = ["PegasusForCausalLM", "PegasusForConditionalGeneration", "PegasusModel", "PegasusPreTrainedModel"]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pegasus/tokenization_pegasus.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 Google and The HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Tokenization class for model PEGASUS."""
|
| 15 |
+
|
| 16 |
+
from tokenizers import Regex, Tokenizer, decoders, normalizers, pre_tokenizers, processors
|
| 17 |
+
from tokenizers.models import Unigram
|
| 18 |
+
|
| 19 |
+
from ...tokenization_utils_tokenizers import TokenizersBackend
|
| 20 |
+
from ...utils import logging
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
VOCAB_FILES_NAMES = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class PegasusTokenizer(TokenizersBackend):
|
| 29 |
+
r"""
|
| 30 |
+
Construct a PEGASUS tokenizer (backed by HuggingFace's *tokenizers* library). Based on
|
| 31 |
+
[Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models).
|
| 32 |
+
|
| 33 |
+
This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should
|
| 34 |
+
refer to this superclass for more information regarding those methods.
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
vocab_file (`str`, *optional*):
|
| 38 |
+
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
|
| 39 |
+
contains the vocabulary necessary to instantiate a tokenizer.
|
| 40 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 41 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 42 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 43 |
+
The end of sequence token.
|
| 44 |
+
|
| 45 |
+
<Tip>
|
| 46 |
+
|
| 47 |
+
When building a sequence using special tokens, this is not the token that is used for the end of sequence.
|
| 48 |
+
The token used is the `sep_token`.
|
| 49 |
+
|
| 50 |
+
</Tip>
|
| 51 |
+
|
| 52 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 53 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 54 |
+
token instead.
|
| 55 |
+
mask_token (`str`, *optional*, defaults to `"<mask_2>"`):
|
| 56 |
+
The token used for masking single token values. This is the token used when training this model with masked
|
| 57 |
+
language modeling (MLM). This is the token that the PEGASUS encoder will try to predict during pretraining.
|
| 58 |
+
It corresponds to *[MASK2]* in [PEGASUS: Pre-training with Extracted Gap-sentences for Abstractive
|
| 59 |
+
Summarization](https://huggingface.co/papers/1912.08777).
|
| 60 |
+
mask_token_sent (`str`, *optional*, defaults to `"<mask_1>"`):
|
| 61 |
+
The token used for masking whole target sentences. This is the token used when training this model with gap
|
| 62 |
+
sentences generation (GSG). This is the sentence that the PEGASUS decoder will try to predict during
|
| 63 |
+
pretraining. It corresponds to *[MASK1]* in [PEGASUS: Pre-training with Extracted Gap-sentences for
|
| 64 |
+
Abstractive Summarization](https://huggingface.co/papers/1912.08777).
|
| 65 |
+
additional_special_tokens (`List[str]`, *optional*):
|
| 66 |
+
Additional special tokens used by the tokenizer. If no additional_special_tokens are provided <mask_2> and
|
| 67 |
+
<unk_2, ..., unk_102> are used as additional special tokens corresponding to the [original PEGASUS
|
| 68 |
+
tokenizer](https://github.com/google-research/pegasus/blob/939830367bcf411193d2b5eca2f2f90f3f9260ca/pegasus/ops/pretrain_parsing_ops.cc#L66)
|
| 69 |
+
that uses the tokens 2 - 104 only for pretraining
|
| 70 |
+
offset (`int`, *optional*, defaults to 103):
|
| 71 |
+
Offset for additional special tokens.
|
| 72 |
+
vocab (`str` or `list[tuple[str, float]]`, *optional*):
|
| 73 |
+
Custom vocabulary with `(token, score)` tuples. If not provided, a blank vocabulary is initialized.
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 77 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 78 |
+
model = Unigram
|
| 79 |
+
|
| 80 |
+
def __init__(
|
| 81 |
+
self,
|
| 82 |
+
vocab: str | list[tuple[str, float]] | None = None,
|
| 83 |
+
pad_token="<pad>",
|
| 84 |
+
eos_token="</s>",
|
| 85 |
+
unk_token="<unk>",
|
| 86 |
+
mask_token="<mask_2>",
|
| 87 |
+
mask_token_sent="<mask_1>",
|
| 88 |
+
_spm_precompiled_charsmap=None,
|
| 89 |
+
additional_special_tokens=None,
|
| 90 |
+
offset=103,
|
| 91 |
+
**kwargs,
|
| 92 |
+
):
|
| 93 |
+
self.offset = offset
|
| 94 |
+
|
| 95 |
+
if additional_special_tokens is None:
|
| 96 |
+
additional_special_tokens = [mask_token_sent] if mask_token_sent is not None else []
|
| 97 |
+
additional_special_tokens += [f"<unk_{i}>" for i in range(2, self.offset)]
|
| 98 |
+
|
| 99 |
+
if vocab is None:
|
| 100 |
+
vocab = [(str(unk_token), 0.0), (str(pad_token), 0.0), (str(eos_token), 0.0), (str(mask_token), 0.0)]
|
| 101 |
+
|
| 102 |
+
self._vocab = vocab
|
| 103 |
+
self._tokenizer = Tokenizer(Unigram(vocab=vocab, unk_id=self._vocab.index((str(unk_token), 0.0), 1)))
|
| 104 |
+
if _spm_precompiled_charsmap is not None:
|
| 105 |
+
self._tokenizer.normalizer = normalizers.Sequence(
|
| 106 |
+
[normalizers.Precompiled(_spm_precompiled_charsmap), normalizers.Replace(Regex(r" {2,}"), " ")]
|
| 107 |
+
)
|
| 108 |
+
else:
|
| 109 |
+
self._tokenizer.normalizer = normalizers.Sequence(
|
| 110 |
+
[normalizers.Replace(Regex(r"\n"), " "), normalizers.Replace(Regex(r" {2,}"), " ")]
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
self._tokenizer.pre_tokenizer = pre_tokenizers.Metaspace(replacement="▁", prepend_scheme="always", split=True)
|
| 114 |
+
self._tokenizer.decoder = decoders.Metaspace(replacement="▁", prepend_scheme="always", split=True)
|
| 115 |
+
|
| 116 |
+
super().__init__(
|
| 117 |
+
pad_token=pad_token,
|
| 118 |
+
eos_token=eos_token,
|
| 119 |
+
unk_token=unk_token,
|
| 120 |
+
mask_token=mask_token,
|
| 121 |
+
mask_token_sent=mask_token_sent,
|
| 122 |
+
offset=offset,
|
| 123 |
+
additional_special_tokens=additional_special_tokens,
|
| 124 |
+
**kwargs,
|
| 125 |
+
)
|
| 126 |
+
self._tokenizer.post_processor = processors.TemplateProcessing(
|
| 127 |
+
single=f"$A {eos_token}",
|
| 128 |
+
pair=f"$A $B {eos_token}",
|
| 129 |
+
special_tokens=[(str(eos_token), self.convert_tokens_to_ids(str(eos_token)))],
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
__all__ = ["PegasusTokenizer"]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pegasus_x/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_pegasus_x import *
|
| 22 |
+
from .modeling_pegasus_x import *
|
| 23 |
+
else:
|
| 24 |
+
import sys
|
| 25 |
+
|
| 26 |
+
_file = globals()["__file__"]
|
| 27 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pegasus_x/configuration_pegasus_x.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022, Google and The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""PEGASUS-X model configuration"""
|
| 15 |
+
|
| 16 |
+
from ...configuration_utils import PreTrainedConfig
|
| 17 |
+
from ...utils import logging
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
logger = logging.get_logger(__name__)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class PegasusXConfig(PreTrainedConfig):
|
| 24 |
+
r"""
|
| 25 |
+
This is the configuration class to store the configuration of a [`PegasusXModel`]. It is used to instantiate a
|
| 26 |
+
PEGASUS-X model according to the specified arguments, defining the model architecture. Instantiating a
|
| 27 |
+
configuration with the defaults will yield a similar configuration to that of the PEGASUS-X
|
| 28 |
+
[google/pegasus-x-large](https://huggingface.co/google/pegasus-x-large) architecture.
|
| 29 |
+
|
| 30 |
+
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
|
| 31 |
+
documentation from [`PreTrainedConfig`] for more information.
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
vocab_size (`int`, *optional*, defaults to 96103):
|
| 36 |
+
Vocabulary size of the PEGASUS-X model. Defines the number of different tokens that can be represented by
|
| 37 |
+
the `inputs_ids` passed when calling [`PegasusXModel`].
|
| 38 |
+
d_model (`int`, *optional*, defaults to 1024):
|
| 39 |
+
Dimension of the layers and the pooler layer.
|
| 40 |
+
encoder_layers (`int`, *optional*, defaults to 16):
|
| 41 |
+
Number of encoder layers.
|
| 42 |
+
decoder_layers (`int`, *optional*, defaults to 16):
|
| 43 |
+
Number of decoder layers.
|
| 44 |
+
encoder_attention_heads (`int`, *optional*, defaults to 16):
|
| 45 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 46 |
+
decoder_attention_heads (`int`, *optional*, defaults to 16):
|
| 47 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
| 48 |
+
decoder_ffn_dim (`int`, *optional*, defaults to 4096):
|
| 49 |
+
Dimension of the "intermediate" (often named feed-forward) layer in decoder.
|
| 50 |
+
encoder_ffn_dim (`int`, *optional*, defaults to 4096):
|
| 51 |
+
Dimension of the "intermediate" (often named feed-forward) layer in decoder.
|
| 52 |
+
activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 53 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 54 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 55 |
+
dropout (`float`, *optional*, defaults to 0.1):
|
| 56 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 57 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 58 |
+
The dropout ratio for the attention probabilities.
|
| 59 |
+
activation_dropout (`float`, *optional*, defaults to 0.0):
|
| 60 |
+
The dropout ratio for activations inside the fully connected layer.
|
| 61 |
+
max_position_embeddings (`int`, *optional*, defaults to 16384):
|
| 62 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 63 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 64 |
+
init_std (`float`, *optional*, defaults to 0.02):
|
| 65 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 66 |
+
encoder_layerdrop (`float`, *optional*, defaults to 0.0):
|
| 67 |
+
The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556)
|
| 68 |
+
for more details.
|
| 69 |
+
decoder_layerdrop (`float`, *optional*, defaults to 0.0):
|
| 70 |
+
The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556)
|
| 71 |
+
for more details.
|
| 72 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 73 |
+
Whether or not the model should return the last key/values attentions (not used by all models)
|
| 74 |
+
forced_eos_token_id (`int`, *optional*, defaults to 1):
|
| 75 |
+
The id of the token to force as the last generated token when `max_length` is reached. Usually set to
|
| 76 |
+
`eos_token_id`.
|
| 77 |
+
num_global_tokens (`int`, *optional*, defaults to 128):
|
| 78 |
+
Number of global tokens to use for the encoder
|
| 79 |
+
block_size (`int`, *optional*, defaults to 512):
|
| 80 |
+
Block size for encoder local attention. Sequence length should be an exact multiple of block size.
|
| 81 |
+
block_size must be a multiple of 2 if stagger_local_block is True
|
| 82 |
+
stagger_local_block (`bool`, *optional*, defaults to `True`):
|
| 83 |
+
Whether to stagger every other local attention by half a block
|
| 84 |
+
|
| 85 |
+
Example:
|
| 86 |
+
|
| 87 |
+
```python
|
| 88 |
+
>>> from transformers import PegasusXConfig, PegasusXModel
|
| 89 |
+
|
| 90 |
+
>>> # Initializing a PEGASUS google/pegasus-x-large style configuration
|
| 91 |
+
>>> configuration = PegasusXConfig()
|
| 92 |
+
|
| 93 |
+
>>> # Initializing a model (with random weights) from the google/pegasus-x-large style configuration
|
| 94 |
+
>>> model = PegasusXModel(configuration)
|
| 95 |
+
|
| 96 |
+
>>> # Accessing the model configuration
|
| 97 |
+
>>> configuration = model.config
|
| 98 |
+
```"""
|
| 99 |
+
|
| 100 |
+
model_type = "pegasus_x"
|
| 101 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 102 |
+
attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
|
| 103 |
+
|
| 104 |
+
def __init__(
|
| 105 |
+
self,
|
| 106 |
+
vocab_size=96103,
|
| 107 |
+
max_position_embeddings=16384,
|
| 108 |
+
encoder_layers=16,
|
| 109 |
+
encoder_ffn_dim=4096,
|
| 110 |
+
encoder_attention_heads=16,
|
| 111 |
+
decoder_layers=16,
|
| 112 |
+
decoder_ffn_dim=4096,
|
| 113 |
+
decoder_attention_heads=16,
|
| 114 |
+
encoder_layerdrop=0.0,
|
| 115 |
+
decoder_layerdrop=0.0,
|
| 116 |
+
use_cache=True,
|
| 117 |
+
is_encoder_decoder=True,
|
| 118 |
+
activation_function="gelu",
|
| 119 |
+
d_model=1024,
|
| 120 |
+
dropout=0.1,
|
| 121 |
+
attention_dropout=0.0,
|
| 122 |
+
activation_dropout=0.0,
|
| 123 |
+
init_std=0.02,
|
| 124 |
+
decoder_start_token_id=0,
|
| 125 |
+
scale_embedding=True,
|
| 126 |
+
pad_token_id=0,
|
| 127 |
+
eos_token_id=1,
|
| 128 |
+
forced_eos_token_id=1,
|
| 129 |
+
num_global_tokens=32,
|
| 130 |
+
block_size=512,
|
| 131 |
+
stagger_local_blocks=True,
|
| 132 |
+
tie_word_embeddings=True,
|
| 133 |
+
**kwargs,
|
| 134 |
+
):
|
| 135 |
+
self.vocab_size = vocab_size
|
| 136 |
+
self.max_position_embeddings = max_position_embeddings
|
| 137 |
+
self.d_model = d_model
|
| 138 |
+
self.encoder_ffn_dim = encoder_ffn_dim
|
| 139 |
+
self.encoder_layers = encoder_layers
|
| 140 |
+
self.encoder_attention_heads = encoder_attention_heads
|
| 141 |
+
self.decoder_ffn_dim = decoder_ffn_dim
|
| 142 |
+
self.decoder_layers = decoder_layers
|
| 143 |
+
self.decoder_attention_heads = decoder_attention_heads
|
| 144 |
+
self.dropout = dropout
|
| 145 |
+
self.attention_dropout = attention_dropout
|
| 146 |
+
self.activation_dropout = activation_dropout
|
| 147 |
+
self.activation_function = activation_function
|
| 148 |
+
self.init_std = init_std
|
| 149 |
+
self.encoder_layerdrop = encoder_layerdrop
|
| 150 |
+
self.decoder_layerdrop = decoder_layerdrop
|
| 151 |
+
self.use_cache = use_cache
|
| 152 |
+
self.num_hidden_layers = encoder_layers
|
| 153 |
+
self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
|
| 154 |
+
|
| 155 |
+
self.num_global_tokens = num_global_tokens
|
| 156 |
+
self.block_size = block_size
|
| 157 |
+
self.stagger_local_blocks = stagger_local_blocks
|
| 158 |
+
self.pad_token_id = pad_token_id
|
| 159 |
+
self.eos_token_id = eos_token_id
|
| 160 |
+
self.decoder_start_token_id = decoder_start_token_id
|
| 161 |
+
self.tie_word_embeddings = tie_word_embeddings
|
| 162 |
+
|
| 163 |
+
super().__init__(
|
| 164 |
+
is_encoder_decoder=is_encoder_decoder,
|
| 165 |
+
forced_eos_token_id=forced_eos_token_id,
|
| 166 |
+
**kwargs,
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
__all__ = ["PegasusXConfig"]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/pegasus_x/modeling_pegasus_x.py
ADDED
|
@@ -0,0 +1,1484 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022, Google and The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""PyTorch PEGASUS-X model."""
|
| 15 |
+
|
| 16 |
+
import math
|
| 17 |
+
from collections.abc import Callable
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
import torch
|
| 22 |
+
from torch import nn
|
| 23 |
+
from torch.nn import CrossEntropyLoss
|
| 24 |
+
|
| 25 |
+
from ...activations import ACT2FN
|
| 26 |
+
from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
|
| 27 |
+
from ...generation import GenerationMixin
|
| 28 |
+
from ...masking_utils import create_bidirectional_mask, create_causal_mask
|
| 29 |
+
from ...modeling_flash_attention_utils import FlashAttentionKwargs
|
| 30 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 31 |
+
from ...modeling_outputs import (
|
| 32 |
+
BaseModelOutput,
|
| 33 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 34 |
+
Seq2SeqLMOutput,
|
| 35 |
+
Seq2SeqModelOutput,
|
| 36 |
+
)
|
| 37 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 38 |
+
from ...processing_utils import Unpack
|
| 39 |
+
from ...utils import TransformersKwargs, auto_docstring, is_torchdynamo_compiling, logging
|
| 40 |
+
from ...utils.deprecation import deprecate_kwarg
|
| 41 |
+
from .configuration_pegasus_x import PegasusXConfig
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
logger = logging.get_logger(__name__)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@dataclass
|
| 48 |
+
class DimensionInfo:
|
| 49 |
+
"""Wrapper for dimension info."""
|
| 50 |
+
|
| 51 |
+
batch_size: int # batch size
|
| 52 |
+
seq_len: int # token length
|
| 53 |
+
block_size: int # block size
|
| 54 |
+
num_heads: int # num heads
|
| 55 |
+
hidden_dim: int # hidden dim
|
| 56 |
+
dim_per_head: int # dim per head
|
| 57 |
+
num_blocks: int # num blocks
|
| 58 |
+
global_len: int # global length
|
| 59 |
+
padded_seq_len: int # padded token seq length
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# Copied from transformers.models.bart.modeling_bart.shift_tokens_right
|
| 63 |
+
def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
|
| 64 |
+
"""
|
| 65 |
+
Shift input ids one token to the right.
|
| 66 |
+
"""
|
| 67 |
+
shifted_input_ids = input_ids.new_zeros(input_ids.shape)
|
| 68 |
+
shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
|
| 69 |
+
shifted_input_ids[:, 0] = decoder_start_token_id
|
| 70 |
+
|
| 71 |
+
if pad_token_id is None:
|
| 72 |
+
raise ValueError("self.model.config.pad_token_id has to be defined.")
|
| 73 |
+
# replace possible -100 values in labels by `pad_token_id`
|
| 74 |
+
shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
|
| 75 |
+
|
| 76 |
+
return shifted_input_ids
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
# Copied from transformers.models.bart.modeling_bart.BartScaledWordEmbedding with Bart->PegasusX
|
| 80 |
+
class PegasusXScaledWordEmbedding(nn.Embedding):
|
| 81 |
+
"""
|
| 82 |
+
This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: float | None = 1.0):
|
| 86 |
+
super().__init__(num_embeddings, embedding_dim, padding_idx)
|
| 87 |
+
self.embed_scale = embed_scale
|
| 88 |
+
|
| 89 |
+
def forward(self, input_ids: torch.Tensor):
|
| 90 |
+
return super().forward(input_ids) * self.embed_scale
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class PegasusXSinusoidalPositionalEmbedding(nn.Module):
|
| 94 |
+
"""This module produces sinusoidal positional embeddings of any length."""
|
| 95 |
+
|
| 96 |
+
def __init__(self, embed_dim, max_scale: int = 10000.0):
|
| 97 |
+
super().__init__()
|
| 98 |
+
self.embed_dim = embed_dim
|
| 99 |
+
self.max_scale = max_scale
|
| 100 |
+
|
| 101 |
+
@deprecate_kwarg("input_embeds", version="5.6.0", new_name="inputs_embeds")
|
| 102 |
+
@torch.no_grad()
|
| 103 |
+
def forward(
|
| 104 |
+
self, inputs_embeds: torch.Tensor, past_key_values_length: int = 0, position_ids: torch.Tensor | None = None
|
| 105 |
+
) -> torch.Tensor:
|
| 106 |
+
"""`input_ids_shape` is expected to be [bsz x seqlen]."""
|
| 107 |
+
batch_size, seq_len = inputs_embeds.shape[:2]
|
| 108 |
+
if position_ids is None:
|
| 109 |
+
position_ids = torch.arange(
|
| 110 |
+
past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=inputs_embeds.device
|
| 111 |
+
)[:, None]
|
| 112 |
+
|
| 113 |
+
pe = torch.zeros((seq_len, self.embed_dim), device=inputs_embeds.device, dtype=inputs_embeds.dtype)
|
| 114 |
+
half_d_feature = self.embed_dim // 2
|
| 115 |
+
div_term = torch.exp(
|
| 116 |
+
torch.arange(half_d_feature, device=inputs_embeds.device, dtype=torch.int64).type_as(inputs_embeds)
|
| 117 |
+
* -(np.log(float(self.max_scale)) / (half_d_feature - 1))
|
| 118 |
+
)
|
| 119 |
+
pe[:, :half_d_feature] = torch.sin(position_ids * div_term)
|
| 120 |
+
pe[:, half_d_feature:] = torch.cos(position_ids * div_term)
|
| 121 |
+
return pe[None].expand(batch_size, -1, -1)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
# Copied from transformers.models.bert.modeling_bert.eager_attention_forward
|
| 125 |
+
def eager_attention_forward(
|
| 126 |
+
module: nn.Module,
|
| 127 |
+
query: torch.Tensor,
|
| 128 |
+
key: torch.Tensor,
|
| 129 |
+
value: torch.Tensor,
|
| 130 |
+
attention_mask: torch.Tensor | None,
|
| 131 |
+
scaling: float | None = None,
|
| 132 |
+
dropout: float = 0.0,
|
| 133 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 134 |
+
):
|
| 135 |
+
if scaling is None:
|
| 136 |
+
scaling = query.size(-1) ** -0.5
|
| 137 |
+
|
| 138 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 139 |
+
attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
|
| 140 |
+
|
| 141 |
+
if attention_mask is not None:
|
| 142 |
+
attn_weights = attn_weights + attention_mask
|
| 143 |
+
|
| 144 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 145 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 146 |
+
|
| 147 |
+
attn_output = torch.matmul(attn_weights, value)
|
| 148 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 149 |
+
|
| 150 |
+
return attn_output, attn_weights
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
# Copied from transformers.models.bart.modeling_bart.BartAttention with Bart->PegasusX
|
| 154 |
+
class PegasusXAttention(nn.Module):
|
| 155 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 156 |
+
|
| 157 |
+
def __init__(
|
| 158 |
+
self,
|
| 159 |
+
embed_dim: int,
|
| 160 |
+
num_heads: int,
|
| 161 |
+
dropout: float = 0.0,
|
| 162 |
+
is_decoder: bool = False,
|
| 163 |
+
bias: bool = True,
|
| 164 |
+
is_causal: bool = False,
|
| 165 |
+
config: PegasusXConfig | None = None,
|
| 166 |
+
layer_idx: int | None = None,
|
| 167 |
+
):
|
| 168 |
+
super().__init__()
|
| 169 |
+
self.embed_dim = embed_dim
|
| 170 |
+
self.num_heads = num_heads
|
| 171 |
+
self.dropout = dropout
|
| 172 |
+
self.head_dim = embed_dim // num_heads
|
| 173 |
+
self.config = config
|
| 174 |
+
|
| 175 |
+
if (self.head_dim * num_heads) != self.embed_dim:
|
| 176 |
+
raise ValueError(
|
| 177 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
|
| 178 |
+
f" and `num_heads`: {num_heads})."
|
| 179 |
+
)
|
| 180 |
+
self.scaling = self.head_dim**-0.5
|
| 181 |
+
self.is_decoder = is_decoder
|
| 182 |
+
self.is_causal = is_causal
|
| 183 |
+
self.layer_idx = layer_idx
|
| 184 |
+
if layer_idx is None and self.is_decoder:
|
| 185 |
+
logger.warning_once(
|
| 186 |
+
f"Instantiating a decoder {self.__class__.__name__} without passing `layer_idx` is not recommended and "
|
| 187 |
+
"will lead to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
| 188 |
+
"when creating this class."
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 192 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 193 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 194 |
+
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 195 |
+
|
| 196 |
+
def forward(
|
| 197 |
+
self,
|
| 198 |
+
hidden_states: torch.Tensor,
|
| 199 |
+
key_value_states: torch.Tensor | None = None,
|
| 200 |
+
past_key_values: Cache | None = None,
|
| 201 |
+
attention_mask: torch.Tensor | None = None,
|
| 202 |
+
output_attentions: bool = False,
|
| 203 |
+
cache_position: torch.Tensor | None = None,
|
| 204 |
+
# TODO: we need a refactor so that the different attention modules can get their specific kwargs
|
| 205 |
+
# ATM, we have mixed things encoder, decoder, and encoder-decoder attn
|
| 206 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 207 |
+
) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
|
| 208 |
+
"""Input shape: Batch x Time x Channel"""
|
| 209 |
+
|
| 210 |
+
# if key_value_states are provided this layer is used as a cross-attention layer
|
| 211 |
+
# for the decoder
|
| 212 |
+
is_cross_attention = key_value_states is not None
|
| 213 |
+
|
| 214 |
+
# determine input shapes
|
| 215 |
+
bsz, tgt_len = hidden_states.shape[:-1]
|
| 216 |
+
src_len = key_value_states.shape[1] if is_cross_attention else tgt_len
|
| 217 |
+
|
| 218 |
+
q_input_shape = (bsz, tgt_len, -1, self.head_dim)
|
| 219 |
+
kv_input_shape = (bsz, src_len, -1, self.head_dim)
|
| 220 |
+
|
| 221 |
+
# get query proj
|
| 222 |
+
query_states = self.q_proj(hidden_states).view(*q_input_shape).transpose(1, 2)
|
| 223 |
+
|
| 224 |
+
is_updated = False
|
| 225 |
+
if past_key_values is not None:
|
| 226 |
+
if isinstance(past_key_values, EncoderDecoderCache):
|
| 227 |
+
is_updated = past_key_values.is_updated.get(self.layer_idx)
|
| 228 |
+
if is_cross_attention:
|
| 229 |
+
# after the first generated id, we can subsequently re-use all key/value_states from cache
|
| 230 |
+
curr_past_key_values = past_key_values.cross_attention_cache
|
| 231 |
+
else:
|
| 232 |
+
curr_past_key_values = past_key_values.self_attention_cache
|
| 233 |
+
else:
|
| 234 |
+
curr_past_key_values = past_key_values
|
| 235 |
+
|
| 236 |
+
current_states = key_value_states if is_cross_attention else hidden_states
|
| 237 |
+
if is_cross_attention and past_key_values is not None and is_updated:
|
| 238 |
+
# reuse k,v, cross_attentions
|
| 239 |
+
key_states = curr_past_key_values.layers[self.layer_idx].keys
|
| 240 |
+
value_states = curr_past_key_values.layers[self.layer_idx].values
|
| 241 |
+
else:
|
| 242 |
+
key_states = self.k_proj(current_states)
|
| 243 |
+
value_states = self.v_proj(current_states)
|
| 244 |
+
key_states = key_states.view(*kv_input_shape).transpose(1, 2)
|
| 245 |
+
value_states = value_states.view(*kv_input_shape).transpose(1, 2)
|
| 246 |
+
|
| 247 |
+
if past_key_values is not None:
|
| 248 |
+
# save all key/value_states to cache to be re-used for fast auto-regressive generation
|
| 249 |
+
cache_position = cache_position if not is_cross_attention else None
|
| 250 |
+
key_states, value_states = curr_past_key_values.update(
|
| 251 |
+
key_states, value_states, self.layer_idx, {"cache_position": cache_position}
|
| 252 |
+
)
|
| 253 |
+
# set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
|
| 254 |
+
if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
|
| 255 |
+
past_key_values.is_updated[self.layer_idx] = True
|
| 256 |
+
|
| 257 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 258 |
+
self.config._attn_implementation, eager_attention_forward
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
attn_output, attn_weights = attention_interface(
|
| 262 |
+
self,
|
| 263 |
+
query_states,
|
| 264 |
+
key_states,
|
| 265 |
+
value_states,
|
| 266 |
+
attention_mask,
|
| 267 |
+
dropout=0.0 if not self.training else self.dropout,
|
| 268 |
+
scaling=self.scaling,
|
| 269 |
+
output_attentions=output_attentions,
|
| 270 |
+
**kwargs,
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
attn_output = attn_output.reshape(bsz, tgt_len, -1).contiguous()
|
| 274 |
+
attn_output = self.out_proj(attn_output)
|
| 275 |
+
|
| 276 |
+
return attn_output, attn_weights
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
class PegasusXGlobalLocalAttention(nn.Module):
|
| 280 |
+
"""Global + Local attention. For use with Encoder only."""
|
| 281 |
+
|
| 282 |
+
def __init__(
|
| 283 |
+
self,
|
| 284 |
+
embed_dim: int,
|
| 285 |
+
num_heads: int,
|
| 286 |
+
block_size: int,
|
| 287 |
+
dropout: float = 0.0,
|
| 288 |
+
is_decoder: bool = False,
|
| 289 |
+
):
|
| 290 |
+
super().__init__()
|
| 291 |
+
self.embed_dim = embed_dim
|
| 292 |
+
self.num_heads = num_heads
|
| 293 |
+
self.block_size = block_size
|
| 294 |
+
self.dropout = dropout
|
| 295 |
+
self.head_dim = embed_dim // num_heads
|
| 296 |
+
|
| 297 |
+
if (self.head_dim * num_heads) != self.embed_dim:
|
| 298 |
+
raise ValueError(
|
| 299 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
|
| 300 |
+
f" and `num_heads`: {num_heads})."
|
| 301 |
+
)
|
| 302 |
+
self.scaling = self.head_dim**-0.5
|
| 303 |
+
self.is_decoder = is_decoder
|
| 304 |
+
|
| 305 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=False)
|
| 306 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=False)
|
| 307 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=False)
|
| 308 |
+
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=False)
|
| 309 |
+
|
| 310 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
| 311 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
| 312 |
+
|
| 313 |
+
def forward(
|
| 314 |
+
self,
|
| 315 |
+
token_hidden_states: torch.Tensor,
|
| 316 |
+
global_hidden_states: torch.Tensor,
|
| 317 |
+
attention_mask: torch.Tensor | None = None,
|
| 318 |
+
output_attentions: bool = False,
|
| 319 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
|
| 320 |
+
"""Input shape: Batch x Time x Channel"""
|
| 321 |
+
dim = DimensionInfo(
|
| 322 |
+
batch_size=token_hidden_states.shape[0],
|
| 323 |
+
seq_len=token_hidden_states.shape[1],
|
| 324 |
+
block_size=self.block_size,
|
| 325 |
+
num_heads=self.num_heads,
|
| 326 |
+
hidden_dim=token_hidden_states.shape[2],
|
| 327 |
+
dim_per_head=self.head_dim,
|
| 328 |
+
num_blocks=token_hidden_states.shape[1] // self.block_size,
|
| 329 |
+
global_len=global_hidden_states.shape[1],
|
| 330 |
+
padded_seq_len=token_hidden_states.shape[1],
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
# [batch_size, num_heads, padded_seq_len, dim_per_head]
|
| 334 |
+
local_q = self._shape(
|
| 335 |
+
self.q_proj(token_hidden_states) * self.scaling,
|
| 336 |
+
seq_len=dim.padded_seq_len,
|
| 337 |
+
bsz=dim.batch_size,
|
| 338 |
+
)
|
| 339 |
+
local_k = self._shape(
|
| 340 |
+
self.k_proj(token_hidden_states),
|
| 341 |
+
seq_len=dim.padded_seq_len,
|
| 342 |
+
bsz=dim.batch_size,
|
| 343 |
+
)
|
| 344 |
+
local_v = self._shape(
|
| 345 |
+
self.v_proj(token_hidden_states),
|
| 346 |
+
seq_len=dim.padded_seq_len,
|
| 347 |
+
bsz=dim.batch_size,
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
# [batch_size, num_heads, global_len, dim_per_head]
|
| 351 |
+
global_q = self._shape(
|
| 352 |
+
self.q_proj(global_hidden_states) * self.scaling,
|
| 353 |
+
seq_len=dim.global_len,
|
| 354 |
+
bsz=dim.batch_size,
|
| 355 |
+
)
|
| 356 |
+
global_k = self._shape(
|
| 357 |
+
self.k_proj(global_hidden_states),
|
| 358 |
+
seq_len=dim.global_len,
|
| 359 |
+
bsz=dim.batch_size,
|
| 360 |
+
)
|
| 361 |
+
global_v = self._shape(
|
| 362 |
+
self.v_proj(global_hidden_states),
|
| 363 |
+
seq_len=dim.global_len,
|
| 364 |
+
bsz=dim.batch_size,
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
global_attn_output, global_attn_probs = self.compute_global_attention_representations(
|
| 368 |
+
global_q=global_q,
|
| 369 |
+
global_k=global_k,
|
| 370 |
+
global_v=global_v,
|
| 371 |
+
local_k=local_k,
|
| 372 |
+
local_v=local_v,
|
| 373 |
+
mask=attention_mask,
|
| 374 |
+
dim=dim,
|
| 375 |
+
)
|
| 376 |
+
local_attn_output, local_attn_probs = self.compute_local_attention_representations(
|
| 377 |
+
global_k=global_k,
|
| 378 |
+
global_v=global_v,
|
| 379 |
+
local_q=local_q,
|
| 380 |
+
local_k=local_k,
|
| 381 |
+
local_v=local_v,
|
| 382 |
+
mask=attention_mask,
|
| 383 |
+
dim=dim,
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
# [batch_size, global_len, hidden_dim]
|
| 387 |
+
global_attn_output = (
|
| 388 |
+
global_attn_output.transpose(1, 2).contiguous().view(dim.batch_size, dim.global_len, dim.hidden_dim)
|
| 389 |
+
)
|
| 390 |
+
# [batch_size, global_len, hidden_dim]
|
| 391 |
+
global_attn_output = self.out_proj(global_attn_output)
|
| 392 |
+
# [batch_size, num_heads, block_size, num_heads, dim_per_head]
|
| 393 |
+
local_attn_output = local_attn_output.permute(0, 2, 3, 1, 4).contiguous()
|
| 394 |
+
# [batch_size, padded_seq_len, hidden_dim]
|
| 395 |
+
local_attn_output = local_attn_output.view(dim.batch_size, dim.padded_seq_len, dim.hidden_dim)
|
| 396 |
+
# [batch_size, padded_seq_len, hidden_dim]
|
| 397 |
+
local_attn_output = self.out_proj(local_attn_output)
|
| 398 |
+
|
| 399 |
+
if output_attentions:
|
| 400 |
+
attn_probs = {"global": global_attn_probs, "local": local_attn_probs}
|
| 401 |
+
else:
|
| 402 |
+
attn_probs = None
|
| 403 |
+
|
| 404 |
+
return local_attn_output, global_attn_output, attn_probs
|
| 405 |
+
|
| 406 |
+
def compute_global_attention_representations(
|
| 407 |
+
self, global_q, global_k, global_v, local_k, local_v, mask, dim: DimensionInfo
|
| 408 |
+
):
|
| 409 |
+
"""Compute attention representations for global tokens.
|
| 410 |
+
|
| 411 |
+
Global tokens will attend to both global tokens as well as all input sequence tokens. Because the input
|
| 412 |
+
sequence tokens are arranged in blocks for local attention, we unblock them and compute attention.
|
| 413 |
+
|
| 414 |
+
Args:
|
| 415 |
+
global_q (`torch.FloatTensor`) of shape [batch_size, num_heads, global_len, dim_per_head]:
|
| 416 |
+
query vectors from global tokens
|
| 417 |
+
global_k (`torch.FloatTensor`) of shape [batch_size, num_heads, global_len, dim_per_head]:
|
| 418 |
+
key vectors from global tokens
|
| 419 |
+
global_v (`torch.FloatTensor`) of shape [batch_size, num_heads, global_len, dim_per_head]:
|
| 420 |
+
value vectors from global tokens
|
| 421 |
+
local_k (`torch.FloatTensor`) of shape [batch_size, num_heads, padded_seq_len, dim_per_head]:
|
| 422 |
+
key vectors from local tokens
|
| 423 |
+
local_v (`torch.FloatTensor`) of shape [batch_size, num_heads, padded_seq_len, dim_per_head]:
|
| 424 |
+
value vectors from local tokens
|
| 425 |
+
mask (`torch.FloatTensor`) of shape [batch_size, padded_seq_len]: attention mask
|
| 426 |
+
dim (DimensionInfo): DimensionInfo wrapper for dimensions
|
| 427 |
+
|
| 428 |
+
Returns:
|
| 429 |
+
output of shape `[batch_sizes, length, features]`. where length will be padded to a multiple of block_size
|
| 430 |
+
"""
|
| 431 |
+
# [batch_size, num_heads, global_len+padded_seq_len, dim_per_head]
|
| 432 |
+
global_and_local_k = torch.cat([global_k, local_k], dim=2)
|
| 433 |
+
# [batch_size, num_heads, global_len+padded_seq_len, dim_per_head]
|
| 434 |
+
global_and_local_v = torch.cat([global_v, local_v], dim=2)
|
| 435 |
+
|
| 436 |
+
# [batch_size, global_len+padded_seq_len]
|
| 437 |
+
extended_mask = nn.functional.pad(mask, pad=(dim.global_len, 0), value=0)
|
| 438 |
+
|
| 439 |
+
# [batch_size, num_heads, global_len, global_len+padded_seq_len]
|
| 440 |
+
attn_weights = torch.einsum("BHGF,BHXF->BHGX", global_q, global_and_local_k)
|
| 441 |
+
attn_weights = attn_weights + extended_mask[:, None, None, :]
|
| 442 |
+
attn_probs = nn.functional.softmax(attn_weights, dim=-1)
|
| 443 |
+
attn_probs = nn.functional.dropout(attn_probs, p=self.dropout, training=self.training)
|
| 444 |
+
|
| 445 |
+
# [batch_size, num_heads, global_len, F]
|
| 446 |
+
attn_output = torch.einsum("BHGX,BHXF->BHGF", attn_probs, global_and_local_v)
|
| 447 |
+
return attn_output, attn_probs
|
| 448 |
+
|
| 449 |
+
def compute_local_attention_representations(
|
| 450 |
+
self, global_k, global_v, local_q, local_k, local_v, mask, dim: DimensionInfo
|
| 451 |
+
):
|
| 452 |
+
"""Compute attention representations for local tokens.
|
| 453 |
+
|
| 454 |
+
Local tokens will attend to both global tokens as well as all other tokens within the same local block. Hence,
|
| 455 |
+
we need to tile and concatenate the global tokens to every local block
|
| 456 |
+
|
| 457 |
+
Args:
|
| 458 |
+
global_k (`torch.FloatTensor`) of shape [batch_size, num_heads, global_len, dim_per_head]:
|
| 459 |
+
key vectors from global tokens
|
| 460 |
+
global_v (`torch.FloatTensor`) of shape [batch_size, num_heads, global_len, dim_per_head]:
|
| 461 |
+
value vectors from global tokens
|
| 462 |
+
local_q (`torch.FloatTensor`) of shape [batch_size, num_heads, padded_seq_len, dim_per_head]:
|
| 463 |
+
query vectors from local tokens
|
| 464 |
+
local_k (`torch.FloatTensor`) of shape [batch_size, num_heads, padded_seq_len, dim_per_head]:
|
| 465 |
+
key vectors from local tokens
|
| 466 |
+
local_v (`torch.FloatTensor`) of shape [batch_size, num_heads, padded_seq_len, dim_per_head]:
|
| 467 |
+
value vectors from local tokens
|
| 468 |
+
mask (`torch.FloatTensor`) of shape [batch_size, padded_seq_len]: attention mask
|
| 469 |
+
dim (DimensionInfo): DimensionInfo wrapper for dimensions
|
| 470 |
+
|
| 471 |
+
Returns:
|
| 472 |
+
output of shape `[batch_sizes, length, features]`. where length will be padded to a multiple of block_size
|
| 473 |
+
"""
|
| 474 |
+
# [batch_size, num_heads, num_blocks, block_size, dim_per_head]
|
| 475 |
+
blocked_local_q = local_q.view(dim.batch_size, dim.num_heads, dim.num_blocks, dim.block_size, dim.dim_per_head)
|
| 476 |
+
# [batch_size, num_heads, num_blocks, block_size, dim_per_head]
|
| 477 |
+
blocked_local_k = local_k.view(dim.batch_size, dim.num_heads, dim.num_blocks, dim.block_size, dim.dim_per_head)
|
| 478 |
+
# [batch_size, num_heads, num_blocks, block_size, dim_per_head]
|
| 479 |
+
blocked_local_v = local_v.view(dim.batch_size, dim.num_heads, dim.num_blocks, dim.block_size, dim.dim_per_head)
|
| 480 |
+
|
| 481 |
+
# [batch_size, num_blocks, global_len+block_size]
|
| 482 |
+
extended_mask = nn.functional.pad(
|
| 483 |
+
mask.view(dim.batch_size, dim.num_blocks, dim.block_size),
|
| 484 |
+
pad=(dim.global_len, 0),
|
| 485 |
+
value=0,
|
| 486 |
+
)
|
| 487 |
+
|
| 488 |
+
# [batch_size, num_heads, num_blocks, block_size, global_len]
|
| 489 |
+
blocked_local2global = torch.einsum("BHNKF,BHGF->BHNKG", blocked_local_q, global_k)
|
| 490 |
+
# [batch_size, num_heads, num_blocks, block_size, block_size]
|
| 491 |
+
blocked_local2local = torch.einsum("BHNKF,BHNXF->BHNKX", blocked_local_q, blocked_local_k)
|
| 492 |
+
|
| 493 |
+
# [batch_size, num_heads, num_blocks, block_size, global_len+block_size]
|
| 494 |
+
attn_weights = torch.cat([blocked_local2global, blocked_local2local], dim=-1)
|
| 495 |
+
attn_weights = attn_weights + extended_mask[:, None, :, None, :]
|
| 496 |
+
attn_probs = nn.functional.softmax(attn_weights, dim=-1)
|
| 497 |
+
attn_probs = nn.functional.dropout(attn_probs, p=self.dropout, training=self.training)
|
| 498 |
+
|
| 499 |
+
# [batch_size, num_heads, num_blocks, block_size, global_len]
|
| 500 |
+
local2global_attn_probs = attn_probs[:, :, :, :, : dim.global_len]
|
| 501 |
+
# [batch_size, num_heads, num_blocks, block_size, block_size]
|
| 502 |
+
local2local_attn_probs = attn_probs[:, :, :, :, dim.global_len :]
|
| 503 |
+
|
| 504 |
+
# [batch_size, num_heads, num_blocks, block_size, dim_per_head]
|
| 505 |
+
local2global_attn_output = torch.einsum("BHNKG,BHGF->BHNKF", local2global_attn_probs, global_v)
|
| 506 |
+
# [batch_size, num_heads, num_blocks, block_size, dim_per_head]
|
| 507 |
+
local2local_attn_output = torch.einsum("BHNKX,BHNXF->BHNKF", local2local_attn_probs, blocked_local_v)
|
| 508 |
+
# [batch_size, num_heads, num_blocks, block_size, dim_per_head]
|
| 509 |
+
attn_output = local2global_attn_output + local2local_attn_output
|
| 510 |
+
return attn_output, attn_probs
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
class PegasusXEncoderLayer(GradientCheckpointingLayer):
|
| 514 |
+
def __init__(self, stagger_blocks_this_layer: bool, config: PegasusXConfig):
|
| 515 |
+
super().__init__()
|
| 516 |
+
self.embed_dim = config.d_model
|
| 517 |
+
self.self_attn = PegasusXGlobalLocalAttention(
|
| 518 |
+
embed_dim=self.embed_dim,
|
| 519 |
+
num_heads=config.encoder_attention_heads,
|
| 520 |
+
block_size=config.block_size,
|
| 521 |
+
dropout=config.attention_dropout,
|
| 522 |
+
)
|
| 523 |
+
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 524 |
+
self.global_self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 525 |
+
self.dropout = config.dropout
|
| 526 |
+
self.activation_fn = ACT2FN[config.activation_function]
|
| 527 |
+
self.activation_dropout = config.activation_dropout
|
| 528 |
+
self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
|
| 529 |
+
self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
|
| 530 |
+
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 531 |
+
self.stagger_blocks_this_layer = stagger_blocks_this_layer
|
| 532 |
+
self.block_size = config.block_size
|
| 533 |
+
|
| 534 |
+
def forward(
|
| 535 |
+
self,
|
| 536 |
+
hidden_states: torch.Tensor,
|
| 537 |
+
global_hidden_states: torch.Tensor,
|
| 538 |
+
attention_mask: torch.Tensor,
|
| 539 |
+
output_attentions: bool = False,
|
| 540 |
+
) -> torch.Tensor:
|
| 541 |
+
"""
|
| 542 |
+
Args:
|
| 543 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape *(seq_len, batch, embed_dim)*
|
| 544 |
+
global_hidden_states (`torch.FloatTensor`): global token hidden states
|
| 545 |
+
*(seq_len, num_global_tokens, embed_dim)*
|
| 546 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
| 547 |
+
*(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
|
| 548 |
+
output_attentions (`bool`, *optional*):
|
| 549 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 550 |
+
returned tensors for more detail.
|
| 551 |
+
"""
|
| 552 |
+
residual = hidden_states
|
| 553 |
+
global_residual = global_hidden_states
|
| 554 |
+
|
| 555 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 556 |
+
global_hidden_states = self.global_self_attn_layer_norm(global_hidden_states)
|
| 557 |
+
|
| 558 |
+
if self.stagger_blocks_this_layer:
|
| 559 |
+
# Pad the blocks to simulate staggering
|
| 560 |
+
hidden_states, attention_mask = self.pad_local_tokens(
|
| 561 |
+
hidden_states=hidden_states, attention_mask=attention_mask, block_size=self.block_size
|
| 562 |
+
)
|
| 563 |
+
|
| 564 |
+
hidden_states, global_hidden_states, attn_weights = self.self_attn(
|
| 565 |
+
token_hidden_states=hidden_states,
|
| 566 |
+
global_hidden_states=global_hidden_states,
|
| 567 |
+
attention_mask=attention_mask,
|
| 568 |
+
output_attentions=output_attentions,
|
| 569 |
+
)
|
| 570 |
+
|
| 571 |
+
if self.stagger_blocks_this_layer:
|
| 572 |
+
# Undo the padding
|
| 573 |
+
hidden_states = self.unpad_local_tokens(padded_hidden_states=hidden_states, block_size=self.block_size)
|
| 574 |
+
|
| 575 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 576 |
+
hidden_states = residual + hidden_states
|
| 577 |
+
|
| 578 |
+
global_hidden_states = nn.functional.dropout(global_hidden_states, p=self.dropout, training=self.training)
|
| 579 |
+
global_hidden_states = global_residual + global_hidden_states
|
| 580 |
+
|
| 581 |
+
residual = hidden_states
|
| 582 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 583 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 584 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
|
| 585 |
+
hidden_states = self.fc2(hidden_states)
|
| 586 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 587 |
+
hidden_states = residual + hidden_states
|
| 588 |
+
|
| 589 |
+
global_residual = global_hidden_states
|
| 590 |
+
global_hidden_states = self.final_layer_norm(global_hidden_states)
|
| 591 |
+
global_hidden_states = self.activation_fn(self.fc1(global_hidden_states))
|
| 592 |
+
global_hidden_states = nn.functional.dropout(
|
| 593 |
+
global_hidden_states, p=self.activation_dropout, training=self.training
|
| 594 |
+
)
|
| 595 |
+
global_hidden_states = self.fc2(global_hidden_states)
|
| 596 |
+
global_hidden_states = nn.functional.dropout(global_hidden_states, p=self.dropout, training=self.training)
|
| 597 |
+
global_hidden_states = global_residual + global_hidden_states
|
| 598 |
+
outputs = (hidden_states, global_hidden_states)
|
| 599 |
+
|
| 600 |
+
if output_attentions:
|
| 601 |
+
outputs += (attn_weights,)
|
| 602 |
+
|
| 603 |
+
return outputs
|
| 604 |
+
|
| 605 |
+
@classmethod
|
| 606 |
+
def pad_local_tokens(cls, hidden_states, attention_mask, block_size):
|
| 607 |
+
# hidden_states: [batch_size, seq_len, hidden_dim]
|
| 608 |
+
pad_size = block_size // 2
|
| 609 |
+
mask_min_value = torch.finfo(hidden_states.dtype).min
|
| 610 |
+
padded_hidden_states = torch.nn.functional.pad(
|
| 611 |
+
hidden_states,
|
| 612 |
+
pad=(0, 0, pad_size, pad_size),
|
| 613 |
+
)
|
| 614 |
+
padded_mask = torch.nn.functional.pad(
|
| 615 |
+
attention_mask,
|
| 616 |
+
pad=(pad_size, pad_size),
|
| 617 |
+
value=mask_min_value,
|
| 618 |
+
)
|
| 619 |
+
return padded_hidden_states, padded_mask
|
| 620 |
+
|
| 621 |
+
@classmethod
|
| 622 |
+
def unpad_local_tokens(cls, padded_hidden_states, block_size):
|
| 623 |
+
# padded_hidden_states: [batch_size, padded seq_len, hidden_dim]
|
| 624 |
+
pad_size = block_size // 2
|
| 625 |
+
return padded_hidden_states[:, pad_size:-pad_size, :]
|
| 626 |
+
|
| 627 |
+
|
| 628 |
+
class PegasusXDecoderLayer(GradientCheckpointingLayer):
|
| 629 |
+
def __init__(self, config: PegasusXConfig, layer_idx: int | None = None):
|
| 630 |
+
super().__init__()
|
| 631 |
+
self.embed_dim = config.d_model
|
| 632 |
+
|
| 633 |
+
self.self_attn = PegasusXAttention(
|
| 634 |
+
embed_dim=self.embed_dim,
|
| 635 |
+
num_heads=config.decoder_attention_heads,
|
| 636 |
+
dropout=config.attention_dropout,
|
| 637 |
+
is_decoder=True,
|
| 638 |
+
bias=False,
|
| 639 |
+
config=config,
|
| 640 |
+
layer_idx=layer_idx,
|
| 641 |
+
)
|
| 642 |
+
self.dropout = config.dropout
|
| 643 |
+
self.activation_fn = ACT2FN[config.activation_function]
|
| 644 |
+
self.activation_dropout = config.activation_dropout
|
| 645 |
+
|
| 646 |
+
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 647 |
+
self.encoder_attn = PegasusXAttention(
|
| 648 |
+
self.embed_dim,
|
| 649 |
+
config.decoder_attention_heads,
|
| 650 |
+
dropout=config.attention_dropout,
|
| 651 |
+
is_decoder=True,
|
| 652 |
+
bias=False,
|
| 653 |
+
config=config,
|
| 654 |
+
layer_idx=layer_idx,
|
| 655 |
+
)
|
| 656 |
+
self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 657 |
+
self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
|
| 658 |
+
self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
|
| 659 |
+
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 660 |
+
|
| 661 |
+
def forward(
|
| 662 |
+
self,
|
| 663 |
+
hidden_states: torch.Tensor,
|
| 664 |
+
attention_mask: torch.Tensor | None = None,
|
| 665 |
+
encoder_hidden_states: torch.Tensor | None = None,
|
| 666 |
+
encoder_attention_mask: torch.Tensor | None = None,
|
| 667 |
+
past_key_values: Cache | None = None,
|
| 668 |
+
output_attentions: bool | None = False,
|
| 669 |
+
use_cache: bool | None = True,
|
| 670 |
+
cache_position: torch.Tensor | None = None,
|
| 671 |
+
) -> torch.Tensor:
|
| 672 |
+
"""
|
| 673 |
+
Args:
|
| 674 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape *(seq_len, batch, embed_dim)*
|
| 675 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
| 676 |
+
*(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
|
| 677 |
+
encoder_hidden_states (`torch.FloatTensor`):
|
| 678 |
+
cross attention input to the layer of shape *(seq_len, batch, embed_dim)*
|
| 679 |
+
encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
|
| 680 |
+
*(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
|
| 681 |
+
past_key_values (`Cache`): cached past key and value projection states
|
| 682 |
+
output_attentions (`bool`, *optional*):
|
| 683 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 684 |
+
returned tensors for more detail.
|
| 685 |
+
use_cache: Whether to us KV cache for decoding
|
| 686 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
| 687 |
+
Indices depicting the position of the input sequence tokens in the sequence. It is used to update the
|
| 688 |
+
cache in the correct position and to infer the complete sequence length.
|
| 689 |
+
"""
|
| 690 |
+
residual = hidden_states
|
| 691 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 692 |
+
|
| 693 |
+
# Self Attention
|
| 694 |
+
hidden_states, self_attn_weights = self.self_attn(
|
| 695 |
+
hidden_states=hidden_states,
|
| 696 |
+
past_key_values=past_key_values,
|
| 697 |
+
attention_mask=attention_mask,
|
| 698 |
+
output_attentions=output_attentions,
|
| 699 |
+
cache_position=cache_position,
|
| 700 |
+
)
|
| 701 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 702 |
+
hidden_states = residual + hidden_states
|
| 703 |
+
|
| 704 |
+
# Cross-Attention Block
|
| 705 |
+
cross_attn_weights = None
|
| 706 |
+
if encoder_hidden_states is not None:
|
| 707 |
+
residual = hidden_states
|
| 708 |
+
hidden_states = self.encoder_attn_layer_norm(hidden_states)
|
| 709 |
+
|
| 710 |
+
hidden_states, cross_attn_weights = self.encoder_attn(
|
| 711 |
+
hidden_states=hidden_states,
|
| 712 |
+
key_value_states=encoder_hidden_states,
|
| 713 |
+
attention_mask=encoder_attention_mask,
|
| 714 |
+
past_key_values=past_key_values,
|
| 715 |
+
output_attentions=output_attentions,
|
| 716 |
+
)
|
| 717 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 718 |
+
hidden_states = residual + hidden_states
|
| 719 |
+
|
| 720 |
+
# Fully Connected
|
| 721 |
+
residual = hidden_states
|
| 722 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 723 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 724 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
|
| 725 |
+
hidden_states = self.fc2(hidden_states)
|
| 726 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 727 |
+
hidden_states = residual + hidden_states
|
| 728 |
+
|
| 729 |
+
outputs = (hidden_states,)
|
| 730 |
+
|
| 731 |
+
if output_attentions:
|
| 732 |
+
outputs += (self_attn_weights, cross_attn_weights)
|
| 733 |
+
return outputs
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
@auto_docstring
|
| 737 |
+
class PegasusXPreTrainedModel(PreTrainedModel):
|
| 738 |
+
config: PegasusXConfig
|
| 739 |
+
base_model_prefix = "model"
|
| 740 |
+
supports_gradient_checkpointing = True
|
| 741 |
+
_no_split_modules = [r"PegasusXEncoderLayer", r"PegasusXDecoderLayer"]
|
| 742 |
+
_supports_flash_attn = True
|
| 743 |
+
# Flaky logits
|
| 744 |
+
_supports_sdpa = False
|
| 745 |
+
_supports_flex_attn = True
|
| 746 |
+
_can_compile_fullgraph = True
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
class PegasusXEncoder(PegasusXPreTrainedModel):
|
| 750 |
+
"""
|
| 751 |
+
Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
|
| 752 |
+
[`PegasusXEncoderLayer`].
|
| 753 |
+
|
| 754 |
+
Args:
|
| 755 |
+
config: PegasusXConfig
|
| 756 |
+
embed_tokens (nn.Embedding): output embedding
|
| 757 |
+
"""
|
| 758 |
+
|
| 759 |
+
def __init__(self, config: PegasusXConfig):
|
| 760 |
+
super().__init__(config)
|
| 761 |
+
|
| 762 |
+
self.dropout = config.dropout
|
| 763 |
+
self.layerdrop = config.encoder_layerdrop
|
| 764 |
+
|
| 765 |
+
embed_dim = config.d_model
|
| 766 |
+
padding_idx = config.pad_token_id
|
| 767 |
+
self.max_source_positions = config.max_position_embeddings
|
| 768 |
+
embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
|
| 769 |
+
|
| 770 |
+
self.embed_tokens = PegasusXScaledWordEmbedding(
|
| 771 |
+
config.vocab_size, embed_dim, padding_idx, embed_scale=embed_scale
|
| 772 |
+
)
|
| 773 |
+
|
| 774 |
+
self.embed_global = nn.Embedding(config.num_global_tokens, embed_dim)
|
| 775 |
+
self.embed_positions = PegasusXSinusoidalPositionalEmbedding(embed_dim)
|
| 776 |
+
self.layers = nn.ModuleList(
|
| 777 |
+
[
|
| 778 |
+
PegasusXEncoderLayer(
|
| 779 |
+
stagger_blocks_this_layer=i % 2 == 1 and config.stagger_local_blocks, config=config
|
| 780 |
+
)
|
| 781 |
+
for i in range(config.encoder_layers)
|
| 782 |
+
]
|
| 783 |
+
)
|
| 784 |
+
self.layer_norm = nn.LayerNorm(config.d_model)
|
| 785 |
+
|
| 786 |
+
self.gradient_checkpointing = False
|
| 787 |
+
# Initialize weights and apply final processing
|
| 788 |
+
self.post_init()
|
| 789 |
+
|
| 790 |
+
def resize_position_embeddings(self, new_num_position_embeddings: int):
|
| 791 |
+
"""
|
| 792 |
+
Resizes position embeddings matrix of the model if `new_num_position_embeddings !=
|
| 793 |
+
config.max_position_embeddings`.
|
| 794 |
+
|
| 795 |
+
Arguments:
|
| 796 |
+
new_num_position_embeddings (`int`):
|
| 797 |
+
The number of new position embeddings. If position embeddings are learned, increasing the size will add
|
| 798 |
+
newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If
|
| 799 |
+
position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will
|
| 800 |
+
add correct vectors at the end following the position encoding algorithm, whereas reducing the size
|
| 801 |
+
will remove vectors from the end.
|
| 802 |
+
"""
|
| 803 |
+
logger.info(f"Setting `config.max_position_embeddings={new_num_position_embeddings}`...")
|
| 804 |
+
self.config.max_position_embeddings = new_num_position_embeddings
|
| 805 |
+
|
| 806 |
+
self.embed_positions = PegasusXSinusoidalPositionalEmbedding(self.config.d_model)
|
| 807 |
+
self.embed_positions.to(self.device)
|
| 808 |
+
|
| 809 |
+
def get_position_embeddings(self) -> nn.Embedding:
|
| 810 |
+
"""
|
| 811 |
+
Returns the position embeddings matrix
|
| 812 |
+
"""
|
| 813 |
+
return self.embed_positions
|
| 814 |
+
|
| 815 |
+
def forward(
|
| 816 |
+
self,
|
| 817 |
+
input_ids=None,
|
| 818 |
+
attention_mask=None,
|
| 819 |
+
inputs_embeds=None,
|
| 820 |
+
output_attentions=None,
|
| 821 |
+
output_hidden_states=None,
|
| 822 |
+
return_dict=None,
|
| 823 |
+
**kwargs,
|
| 824 |
+
):
|
| 825 |
+
r"""
|
| 826 |
+
Args:
|
| 827 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 828 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
|
| 829 |
+
provide it.
|
| 830 |
+
|
| 831 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 832 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 833 |
+
|
| 834 |
+
[What are input IDs?](../glossary#input-ids)
|
| 835 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 836 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 837 |
+
|
| 838 |
+
- 1 for tokens that are **not masked**,
|
| 839 |
+
- 0 for tokens that are **masked**.
|
| 840 |
+
|
| 841 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 842 |
+
|
| 843 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 844 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 845 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 846 |
+
than the model's internal embedding lookup matrix.
|
| 847 |
+
output_attentions (`bool`, *optional*):
|
| 848 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 849 |
+
returned tensors for more detail.
|
| 850 |
+
output_hidden_states (`bool`, *optional*):
|
| 851 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 852 |
+
for more detail.
|
| 853 |
+
return_dict (`bool`, *optional*):
|
| 854 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 855 |
+
"""
|
| 856 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 857 |
+
output_hidden_states = (
|
| 858 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 859 |
+
)
|
| 860 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 861 |
+
|
| 862 |
+
# retrieve input_ids and inputs_embeds
|
| 863 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 864 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 865 |
+
elif input_ids is not None:
|
| 866 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 867 |
+
input_shape = input_ids.size()
|
| 868 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
| 869 |
+
elif inputs_embeds is not None:
|
| 870 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 871 |
+
else:
|
| 872 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 873 |
+
|
| 874 |
+
if inputs_embeds is None:
|
| 875 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 876 |
+
|
| 877 |
+
embed_pos = self.embed_positions(inputs_embeds)
|
| 878 |
+
|
| 879 |
+
hidden_states = inputs_embeds + embed_pos
|
| 880 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 881 |
+
|
| 882 |
+
batch_size, seq_len, _ = hidden_states.shape
|
| 883 |
+
|
| 884 |
+
# Setup mask
|
| 885 |
+
if attention_mask is None:
|
| 886 |
+
attention_mask = torch.ones(*input_shape, dtype=inputs_embeds.dtype, device=inputs_embeds.device)
|
| 887 |
+
attention_mask = attention_mask.to(dtype=hidden_states.dtype)
|
| 888 |
+
mask_min_value = torch.finfo(hidden_states.dtype).min
|
| 889 |
+
inverted_mask = 1.0 - attention_mask
|
| 890 |
+
attention_mask = inverted_mask.masked_fill(
|
| 891 |
+
inverted_mask.to(torch.bool),
|
| 892 |
+
mask_min_value,
|
| 893 |
+
)
|
| 894 |
+
|
| 895 |
+
# padding to block_size
|
| 896 |
+
if seq_len % self.config.block_size != 0:
|
| 897 |
+
pad_len = self.config.block_size - seq_len % self.config.block_size
|
| 898 |
+
hidden_states = nn.functional.pad(hidden_states, pad=(0, 0, 0, pad_len), value=0)
|
| 899 |
+
attention_mask = nn.functional.pad(attention_mask, pad=(0, pad_len), value=mask_min_value)
|
| 900 |
+
|
| 901 |
+
# Global tokens
|
| 902 |
+
global_hidden_states = self.embed_global(
|
| 903 |
+
torch.arange(self.config.num_global_tokens, device=hidden_states.device)[None].expand(batch_size, -1)
|
| 904 |
+
)
|
| 905 |
+
|
| 906 |
+
encoder_states = () if output_hidden_states else None
|
| 907 |
+
all_attentions = () if output_attentions else None
|
| 908 |
+
|
| 909 |
+
for idx, encoder_layer in enumerate(self.layers):
|
| 910 |
+
if output_hidden_states:
|
| 911 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 912 |
+
# add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
|
| 913 |
+
to_drop = False
|
| 914 |
+
if self.training:
|
| 915 |
+
dropout_probability = torch.rand([])
|
| 916 |
+
if dropout_probability < self.layerdrop: # skip the layer
|
| 917 |
+
to_drop = True
|
| 918 |
+
|
| 919 |
+
if to_drop:
|
| 920 |
+
layer_outputs = (None, None)
|
| 921 |
+
else:
|
| 922 |
+
layer_outputs = encoder_layer(
|
| 923 |
+
hidden_states,
|
| 924 |
+
global_hidden_states,
|
| 925 |
+
attention_mask,
|
| 926 |
+
output_attentions=output_attentions,
|
| 927 |
+
)
|
| 928 |
+
|
| 929 |
+
hidden_states = layer_outputs[0]
|
| 930 |
+
global_hidden_states = layer_outputs[1]
|
| 931 |
+
|
| 932 |
+
if output_attentions:
|
| 933 |
+
all_attentions = all_attentions + (layer_outputs[2],)
|
| 934 |
+
|
| 935 |
+
# Undo padding-to-block-size
|
| 936 |
+
hidden_states = hidden_states[:, :seq_len]
|
| 937 |
+
|
| 938 |
+
hidden_states = self.layer_norm(hidden_states)
|
| 939 |
+
|
| 940 |
+
if output_hidden_states:
|
| 941 |
+
encoder_states = encoder_states + ((hidden_states, global_hidden_states),)
|
| 942 |
+
|
| 943 |
+
if not return_dict:
|
| 944 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
| 945 |
+
return BaseModelOutput(
|
| 946 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
|
| 947 |
+
)
|
| 948 |
+
|
| 949 |
+
|
| 950 |
+
class PegasusXDecoder(PegasusXPreTrainedModel):
|
| 951 |
+
"""
|
| 952 |
+
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`PegasusDecoderLayer`]
|
| 953 |
+
|
| 954 |
+
Args:
|
| 955 |
+
config: PegasusXConfig
|
| 956 |
+
embed_tokens (nn.Embedding): output embedding
|
| 957 |
+
"""
|
| 958 |
+
|
| 959 |
+
def __init__(self, config: PegasusXConfig):
|
| 960 |
+
super().__init__(config)
|
| 961 |
+
self.dropout = config.dropout
|
| 962 |
+
self.layerdrop = config.decoder_layerdrop
|
| 963 |
+
self.max_target_positions = config.max_position_embeddings
|
| 964 |
+
embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
|
| 965 |
+
padding_idx = config.pad_token_id
|
| 966 |
+
|
| 967 |
+
self.embed_tokens = PegasusXScaledWordEmbedding(
|
| 968 |
+
config.vocab_size, config.d_model, padding_idx=padding_idx, embed_scale=embed_scale
|
| 969 |
+
)
|
| 970 |
+
|
| 971 |
+
self.embed_positions = PegasusXSinusoidalPositionalEmbedding(config.d_model)
|
| 972 |
+
self.layers = nn.ModuleList([PegasusXDecoderLayer(config, layer_idx=i) for i in range(config.decoder_layers)])
|
| 973 |
+
self.layer_norm = nn.LayerNorm(config.d_model)
|
| 974 |
+
|
| 975 |
+
self.gradient_checkpointing = False
|
| 976 |
+
# Initialize weights and apply final processing
|
| 977 |
+
self.post_init()
|
| 978 |
+
|
| 979 |
+
def forward(
|
| 980 |
+
self,
|
| 981 |
+
input_ids=None,
|
| 982 |
+
attention_mask=None,
|
| 983 |
+
encoder_hidden_states=None,
|
| 984 |
+
encoder_attention_mask=None,
|
| 985 |
+
past_key_values=None,
|
| 986 |
+
inputs_embeds=None,
|
| 987 |
+
use_cache=None,
|
| 988 |
+
output_attentions=None,
|
| 989 |
+
output_hidden_states=None,
|
| 990 |
+
return_dict=None,
|
| 991 |
+
cache_position=None,
|
| 992 |
+
**kwargs,
|
| 993 |
+
):
|
| 994 |
+
r"""
|
| 995 |
+
Args:
|
| 996 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 997 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
|
| 998 |
+
provide it.
|
| 999 |
+
|
| 1000 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1001 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 1002 |
+
|
| 1003 |
+
[What are input IDs?](../glossary#input-ids)
|
| 1004 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1005 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 1006 |
+
|
| 1007 |
+
- 1 for tokens that are **not masked**,
|
| 1008 |
+
- 0 for tokens that are **masked**.
|
| 1009 |
+
|
| 1010 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 1011 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
|
| 1012 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
|
| 1013 |
+
of the decoder.
|
| 1014 |
+
encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
|
| 1015 |
+
Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
|
| 1016 |
+
selected in `[0, 1]`:
|
| 1017 |
+
|
| 1018 |
+
- 1 for tokens that are **not masked**,
|
| 1019 |
+
- 0 for tokens that are **masked**.
|
| 1020 |
+
|
| 1021 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 1022 |
+
|
| 1023 |
+
past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 1024 |
+
It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
|
| 1025 |
+
|
| 1026 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
|
| 1027 |
+
cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
| 1028 |
+
|
| 1029 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
|
| 1030 |
+
that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
|
| 1031 |
+
all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 1032 |
+
inputs_embeds (`torch.FloatTensor` of
|
| 1033 |
+
shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing
|
| 1034 |
+
`input_ids` you can choose to directly pass an embedded representation. This is useful if you want more
|
| 1035 |
+
control over how to convert `input_ids` indices into associated vectors than the model's internal
|
| 1036 |
+
embedding lookup matrix.
|
| 1037 |
+
output_attentions (`bool`, *optional*):
|
| 1038 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 1039 |
+
returned tensors for more detail.
|
| 1040 |
+
output_hidden_states (`bool`, *optional*):
|
| 1041 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 1042 |
+
for more detail.
|
| 1043 |
+
return_dict (`bool`, *optional*):
|
| 1044 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 1045 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
| 1046 |
+
Indices depicting the position of the input sequence tokens in the sequence. It is used to update the
|
| 1047 |
+
cache in the correct position and to infer the complete sequence length.
|
| 1048 |
+
"""
|
| 1049 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1050 |
+
output_hidden_states = (
|
| 1051 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1052 |
+
)
|
| 1053 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 1054 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1055 |
+
|
| 1056 |
+
# retrieve input_ids and inputs_embeds
|
| 1057 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 1058 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
| 1059 |
+
elif input_ids is not None:
|
| 1060 |
+
input = input_ids
|
| 1061 |
+
input_shape = input.shape
|
| 1062 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
| 1063 |
+
elif inputs_embeds is not None:
|
| 1064 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 1065 |
+
input = inputs_embeds[:, :, -1]
|
| 1066 |
+
else:
|
| 1067 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
| 1068 |
+
|
| 1069 |
+
if inputs_embeds is None:
|
| 1070 |
+
inputs_embeds = self.embed_tokens(input)
|
| 1071 |
+
|
| 1072 |
+
if self.gradient_checkpointing and self.training:
|
| 1073 |
+
if use_cache:
|
| 1074 |
+
logger.warning_once(
|
| 1075 |
+
"`use_cache=True` is incompatible with gradient checkpointing`. Setting `use_cache=False`..."
|
| 1076 |
+
)
|
| 1077 |
+
use_cache = False
|
| 1078 |
+
|
| 1079 |
+
# initialize `past_key_values`
|
| 1080 |
+
if use_cache and past_key_values is None:
|
| 1081 |
+
past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
|
| 1082 |
+
|
| 1083 |
+
batch_size, seq_length = inputs_embeds.size()[:-1]
|
| 1084 |
+
past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 1085 |
+
if cache_position is None:
|
| 1086 |
+
cache_position = torch.arange(
|
| 1087 |
+
past_key_values_length, past_key_values_length + seq_length, device=inputs_embeds.device
|
| 1088 |
+
)
|
| 1089 |
+
|
| 1090 |
+
if attention_mask is None and not is_torchdynamo_compiling():
|
| 1091 |
+
# required mask seq length can be calculated via length of past cache
|
| 1092 |
+
mask_seq_length = past_key_values_length + seq_length
|
| 1093 |
+
attention_mask = torch.ones(batch_size, mask_seq_length, device=inputs_embeds.device)
|
| 1094 |
+
|
| 1095 |
+
self_attn_cache = (
|
| 1096 |
+
past_key_values.self_attention_cache
|
| 1097 |
+
if isinstance(past_key_values, EncoderDecoderCache)
|
| 1098 |
+
else past_key_values
|
| 1099 |
+
)
|
| 1100 |
+
|
| 1101 |
+
causal_mask = create_causal_mask(
|
| 1102 |
+
config=self.config,
|
| 1103 |
+
inputs_embeds=inputs_embeds,
|
| 1104 |
+
attention_mask=attention_mask,
|
| 1105 |
+
cache_position=cache_position,
|
| 1106 |
+
past_key_values=self_attn_cache,
|
| 1107 |
+
)
|
| 1108 |
+
encoder_attention_mask = create_bidirectional_mask(
|
| 1109 |
+
config=self.config,
|
| 1110 |
+
inputs_embeds=inputs_embeds,
|
| 1111 |
+
attention_mask=encoder_attention_mask,
|
| 1112 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1113 |
+
)
|
| 1114 |
+
|
| 1115 |
+
# embed positions
|
| 1116 |
+
position_ids = cache_position.unsqueeze(1)
|
| 1117 |
+
position_ids = self.embed_positions(inputs_embeds, past_key_values_length, position_ids)
|
| 1118 |
+
position_ids = position_ids.to(inputs_embeds.device)
|
| 1119 |
+
hidden_states = inputs_embeds + position_ids
|
| 1120 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 1121 |
+
|
| 1122 |
+
# decoder layers
|
| 1123 |
+
all_hidden_states = () if output_hidden_states else None
|
| 1124 |
+
all_self_attns = () if output_attentions else None
|
| 1125 |
+
all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
|
| 1126 |
+
|
| 1127 |
+
for idx, decoder_layer in enumerate(self.layers):
|
| 1128 |
+
# add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
|
| 1129 |
+
if output_hidden_states:
|
| 1130 |
+
all_hidden_states += (hidden_states,)
|
| 1131 |
+
if self.training:
|
| 1132 |
+
dropout_probability = torch.rand([])
|
| 1133 |
+
if dropout_probability < self.layerdrop:
|
| 1134 |
+
continue
|
| 1135 |
+
|
| 1136 |
+
layer_outputs = decoder_layer(
|
| 1137 |
+
hidden_states,
|
| 1138 |
+
causal_mask,
|
| 1139 |
+
encoder_hidden_states, # as a positional argument for gradient checkpointing
|
| 1140 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1141 |
+
past_key_values=past_key_values,
|
| 1142 |
+
output_attentions=output_attentions,
|
| 1143 |
+
use_cache=use_cache,
|
| 1144 |
+
cache_position=cache_position,
|
| 1145 |
+
)
|
| 1146 |
+
hidden_states = layer_outputs[0]
|
| 1147 |
+
|
| 1148 |
+
if output_attentions:
|
| 1149 |
+
all_self_attns += (layer_outputs[1],)
|
| 1150 |
+
|
| 1151 |
+
if encoder_hidden_states is not None:
|
| 1152 |
+
all_cross_attentions += (layer_outputs[2],)
|
| 1153 |
+
|
| 1154 |
+
hidden_states = self.layer_norm(hidden_states)
|
| 1155 |
+
|
| 1156 |
+
# add hidden states from the last decoder layer
|
| 1157 |
+
if output_hidden_states:
|
| 1158 |
+
all_hidden_states += (hidden_states,)
|
| 1159 |
+
|
| 1160 |
+
if not return_dict:
|
| 1161 |
+
return tuple(
|
| 1162 |
+
v
|
| 1163 |
+
for v in [hidden_states, past_key_values, all_hidden_states, all_self_attns, all_cross_attentions]
|
| 1164 |
+
if v is not None
|
| 1165 |
+
)
|
| 1166 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 1167 |
+
last_hidden_state=hidden_states,
|
| 1168 |
+
past_key_values=past_key_values,
|
| 1169 |
+
hidden_states=all_hidden_states,
|
| 1170 |
+
attentions=all_self_attns,
|
| 1171 |
+
cross_attentions=all_cross_attentions,
|
| 1172 |
+
)
|
| 1173 |
+
|
| 1174 |
+
|
| 1175 |
+
@auto_docstring
|
| 1176 |
+
class PegasusXModel(PegasusXPreTrainedModel):
|
| 1177 |
+
_tied_weights_keys = {
|
| 1178 |
+
"encoder.embed_tokens.weight": "shared.weight",
|
| 1179 |
+
"decoder.embed_tokens.weight": "shared.weight",
|
| 1180 |
+
}
|
| 1181 |
+
|
| 1182 |
+
def __init__(self, config: PegasusXConfig):
|
| 1183 |
+
super().__init__(config)
|
| 1184 |
+
|
| 1185 |
+
vocab_size = config.vocab_size
|
| 1186 |
+
embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
|
| 1187 |
+
padding_idx = config.pad_token_id
|
| 1188 |
+
self.shared = PegasusXScaledWordEmbedding(
|
| 1189 |
+
vocab_size, config.d_model, padding_idx=padding_idx, embed_scale=embed_scale
|
| 1190 |
+
)
|
| 1191 |
+
|
| 1192 |
+
self.encoder = PegasusXEncoder(config)
|
| 1193 |
+
self.decoder = PegasusXDecoder(config)
|
| 1194 |
+
|
| 1195 |
+
# Initialize weights and apply final processing
|
| 1196 |
+
self.post_init()
|
| 1197 |
+
|
| 1198 |
+
def get_input_embeddings(self):
|
| 1199 |
+
return self.shared
|
| 1200 |
+
|
| 1201 |
+
def set_input_embeddings(self, value):
|
| 1202 |
+
self.shared = value
|
| 1203 |
+
self.encoder.embed_tokens = self.shared
|
| 1204 |
+
self.decoder.embed_tokens = self.shared
|
| 1205 |
+
|
| 1206 |
+
def resize_position_embeddings(self, new_num_position_embeddings: int):
|
| 1207 |
+
"""
|
| 1208 |
+
Resizes position embeddings matrix of the model if `new_num_position_embeddings !=
|
| 1209 |
+
config.max_position_embeddings`.
|
| 1210 |
+
|
| 1211 |
+
Arguments:
|
| 1212 |
+
new_num_position_embeddings (`int`):
|
| 1213 |
+
The number of new position embeddings. If position embeddings are learned, increasing the size will add
|
| 1214 |
+
newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If
|
| 1215 |
+
position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will
|
| 1216 |
+
add correct vectors at the end following the position encoding algorithm, whereas reducing the size
|
| 1217 |
+
will remove vectors from the end.
|
| 1218 |
+
"""
|
| 1219 |
+
self.config.max_position_embeddings = new_num_position_embeddings
|
| 1220 |
+
self.encoder.resize_position_embeddings(new_num_position_embeddings)
|
| 1221 |
+
self.decoder.resize_position_embeddings(new_num_position_embeddings)
|
| 1222 |
+
|
| 1223 |
+
def get_position_embeddings(self) -> tuple[nn.Embedding]:
|
| 1224 |
+
"""
|
| 1225 |
+
Returns the position embeddings matrix
|
| 1226 |
+
"""
|
| 1227 |
+
return (self.encoder.get_position_embeddings(), self.decoder.get_position_embeddings())
|
| 1228 |
+
|
| 1229 |
+
@auto_docstring
|
| 1230 |
+
def forward(
|
| 1231 |
+
self,
|
| 1232 |
+
input_ids: torch.Tensor | None = None,
|
| 1233 |
+
attention_mask: torch.Tensor | None = None,
|
| 1234 |
+
decoder_input_ids: torch.Tensor | None = None,
|
| 1235 |
+
decoder_attention_mask: torch.Tensor | None = None,
|
| 1236 |
+
encoder_outputs: tuple[torch.FloatTensor] | None = None,
|
| 1237 |
+
past_key_values: Cache | None = None,
|
| 1238 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 1239 |
+
decoder_inputs_embeds: torch.Tensor | None = None,
|
| 1240 |
+
use_cache: bool | None = None,
|
| 1241 |
+
output_attentions: bool | None = None,
|
| 1242 |
+
output_hidden_states: bool | None = None,
|
| 1243 |
+
return_dict: bool | None = None,
|
| 1244 |
+
cache_position: torch.Tensor | None = None,
|
| 1245 |
+
**kwargs,
|
| 1246 |
+
) -> tuple | Seq2SeqModelOutput:
|
| 1247 |
+
r"""
|
| 1248 |
+
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 1249 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 1250 |
+
|
| 1251 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1252 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 1253 |
+
|
| 1254 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 1255 |
+
|
| 1256 |
+
PEGASUS-X uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If
|
| 1257 |
+
`past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
| 1258 |
+
`past_key_values`).
|
| 1259 |
+
decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 1260 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 1261 |
+
be used by default.
|
| 1262 |
+
|
| 1263 |
+
Example:
|
| 1264 |
+
|
| 1265 |
+
```python
|
| 1266 |
+
>>> from transformers import AutoTokenizer, PegasusModel
|
| 1267 |
+
|
| 1268 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/pegasus-x-large")
|
| 1269 |
+
>>> model = PegasusModel.from_pretrained("google/pegasus-x-large")
|
| 1270 |
+
|
| 1271 |
+
>>> inputs = tokenizer("Studies have been shown that owning a dog is good for you", return_tensors="pt")
|
| 1272 |
+
>>> decoder_inputs = tokenizer("Studies show that", return_tensors="pt")
|
| 1273 |
+
>>> outputs = model(input_ids=inputs.input_ids, decoder_input_ids=decoder_inputs.input_ids)
|
| 1274 |
+
|
| 1275 |
+
>>> last_hidden_states = outputs.last_hidden_state
|
| 1276 |
+
>>> list(last_hidden_states.shape)
|
| 1277 |
+
[1, 4, 1024]
|
| 1278 |
+
```"""
|
| 1279 |
+
|
| 1280 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1281 |
+
output_hidden_states = (
|
| 1282 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1283 |
+
)
|
| 1284 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 1285 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1286 |
+
|
| 1287 |
+
if encoder_outputs is None:
|
| 1288 |
+
encoder_outputs = self.encoder(
|
| 1289 |
+
input_ids=input_ids,
|
| 1290 |
+
attention_mask=attention_mask,
|
| 1291 |
+
inputs_embeds=inputs_embeds,
|
| 1292 |
+
output_attentions=output_attentions,
|
| 1293 |
+
output_hidden_states=output_hidden_states,
|
| 1294 |
+
return_dict=return_dict,
|
| 1295 |
+
)
|
| 1296 |
+
# If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
|
| 1297 |
+
elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
|
| 1298 |
+
encoder_outputs = BaseModelOutput(
|
| 1299 |
+
last_hidden_state=encoder_outputs[0],
|
| 1300 |
+
hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
|
| 1301 |
+
attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
|
| 1302 |
+
)
|
| 1303 |
+
|
| 1304 |
+
# decoder outputs consists of (dec_features, past_key_values, dec_hidden, dec_attn)
|
| 1305 |
+
decoder_outputs = self.decoder(
|
| 1306 |
+
input_ids=decoder_input_ids,
|
| 1307 |
+
attention_mask=decoder_attention_mask,
|
| 1308 |
+
encoder_hidden_states=encoder_outputs[0],
|
| 1309 |
+
encoder_attention_mask=attention_mask,
|
| 1310 |
+
past_key_values=past_key_values,
|
| 1311 |
+
inputs_embeds=decoder_inputs_embeds,
|
| 1312 |
+
use_cache=use_cache,
|
| 1313 |
+
output_attentions=output_attentions,
|
| 1314 |
+
output_hidden_states=output_hidden_states,
|
| 1315 |
+
return_dict=return_dict,
|
| 1316 |
+
cache_position=cache_position,
|
| 1317 |
+
)
|
| 1318 |
+
|
| 1319 |
+
if not return_dict:
|
| 1320 |
+
return decoder_outputs + encoder_outputs
|
| 1321 |
+
|
| 1322 |
+
return Seq2SeqModelOutput(
|
| 1323 |
+
last_hidden_state=decoder_outputs.last_hidden_state,
|
| 1324 |
+
past_key_values=decoder_outputs.past_key_values,
|
| 1325 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 1326 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 1327 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 1328 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
| 1329 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 1330 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 1331 |
+
)
|
| 1332 |
+
|
| 1333 |
+
|
| 1334 |
+
@auto_docstring(
|
| 1335 |
+
custom_intro="""
|
| 1336 |
+
The PEGASUS-X for conditional generation (e.g. summarization).
|
| 1337 |
+
"""
|
| 1338 |
+
)
|
| 1339 |
+
class PegasusXForConditionalGeneration(PegasusXPreTrainedModel, GenerationMixin):
|
| 1340 |
+
base_model_prefix = "model"
|
| 1341 |
+
_tied_weights_keys = {
|
| 1342 |
+
"lm_head.weight": "model.shared.weight",
|
| 1343 |
+
}
|
| 1344 |
+
|
| 1345 |
+
def __init__(self, config: PegasusXConfig):
|
| 1346 |
+
super().__init__(config)
|
| 1347 |
+
self.model = PegasusXModel(config)
|
| 1348 |
+
self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)
|
| 1349 |
+
|
| 1350 |
+
# Initialize weights and apply final processing
|
| 1351 |
+
self.post_init()
|
| 1352 |
+
|
| 1353 |
+
def resize_position_embeddings(self, new_num_position_embeddings: int):
|
| 1354 |
+
"""
|
| 1355 |
+
Resizes position embeddings matrix of the model if `new_num_position_embeddings !=
|
| 1356 |
+
config.max_position_embeddings`.
|
| 1357 |
+
|
| 1358 |
+
Arguments:
|
| 1359 |
+
new_num_position_embeddings (`int`):
|
| 1360 |
+
The number of new position embeddings. If position embeddings are learned, increasing the size will add
|
| 1361 |
+
newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If
|
| 1362 |
+
position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will
|
| 1363 |
+
add correct vectors at the end following the position encoding algorithm, whereas reducing the size
|
| 1364 |
+
will remove vectors from the end.
|
| 1365 |
+
"""
|
| 1366 |
+
self.config.max_position_embeddings = new_num_position_embeddings
|
| 1367 |
+
self.model.encoder.resize_position_embeddings(new_num_position_embeddings)
|
| 1368 |
+
self.model.decoder.resize_position_embeddings(new_num_position_embeddings)
|
| 1369 |
+
|
| 1370 |
+
def get_position_embeddings(self) -> tuple[nn.Embedding]:
|
| 1371 |
+
"""
|
| 1372 |
+
Returns the position embeddings matrix
|
| 1373 |
+
"""
|
| 1374 |
+
return (self.model.encoder.get_position_embeddings(), self.model.decoder.get_position_embeddings())
|
| 1375 |
+
|
| 1376 |
+
@auto_docstring
|
| 1377 |
+
def forward(
|
| 1378 |
+
self,
|
| 1379 |
+
input_ids: torch.Tensor | None = None,
|
| 1380 |
+
attention_mask: torch.Tensor | None = None,
|
| 1381 |
+
decoder_input_ids: torch.Tensor | None = None,
|
| 1382 |
+
decoder_attention_mask: torch.Tensor | None = None,
|
| 1383 |
+
encoder_outputs: tuple[torch.FloatTensor] | None = None,
|
| 1384 |
+
past_key_values: Cache | None = None,
|
| 1385 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 1386 |
+
decoder_inputs_embeds: torch.Tensor | None = None,
|
| 1387 |
+
labels: torch.Tensor | None = None,
|
| 1388 |
+
use_cache: bool | None = None,
|
| 1389 |
+
output_attentions: bool | None = None,
|
| 1390 |
+
output_hidden_states: bool | None = None,
|
| 1391 |
+
return_dict: bool | None = None,
|
| 1392 |
+
cache_position: torch.Tensor | None = None,
|
| 1393 |
+
**kwargs,
|
| 1394 |
+
) -> tuple | Seq2SeqLMOutput:
|
| 1395 |
+
r"""
|
| 1396 |
+
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 1397 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 1398 |
+
|
| 1399 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1400 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 1401 |
+
|
| 1402 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 1403 |
+
|
| 1404 |
+
PEGASUS-X uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If
|
| 1405 |
+
`past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
| 1406 |
+
`past_key_values`).
|
| 1407 |
+
decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 1408 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 1409 |
+
be used by default.
|
| 1410 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1411 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 1412 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 1413 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 1414 |
+
"""
|
| 1415 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1416 |
+
|
| 1417 |
+
if labels is not None:
|
| 1418 |
+
if use_cache:
|
| 1419 |
+
logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
|
| 1420 |
+
use_cache = False
|
| 1421 |
+
if decoder_input_ids is None and decoder_inputs_embeds is None:
|
| 1422 |
+
decoder_input_ids = shift_tokens_right(
|
| 1423 |
+
labels, self.config.pad_token_id, self.config.decoder_start_token_id
|
| 1424 |
+
)
|
| 1425 |
+
|
| 1426 |
+
outputs = self.model(
|
| 1427 |
+
input_ids,
|
| 1428 |
+
attention_mask=attention_mask,
|
| 1429 |
+
decoder_input_ids=decoder_input_ids,
|
| 1430 |
+
encoder_outputs=encoder_outputs,
|
| 1431 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1432 |
+
past_key_values=past_key_values,
|
| 1433 |
+
inputs_embeds=inputs_embeds,
|
| 1434 |
+
decoder_inputs_embeds=decoder_inputs_embeds,
|
| 1435 |
+
use_cache=use_cache,
|
| 1436 |
+
output_attentions=output_attentions,
|
| 1437 |
+
output_hidden_states=output_hidden_states,
|
| 1438 |
+
return_dict=return_dict,
|
| 1439 |
+
cache_position=cache_position,
|
| 1440 |
+
)
|
| 1441 |
+
lm_logits = self.lm_head(outputs[0])
|
| 1442 |
+
|
| 1443 |
+
masked_lm_loss = None
|
| 1444 |
+
if labels is not None:
|
| 1445 |
+
loss_fct = CrossEntropyLoss()
|
| 1446 |
+
masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))
|
| 1447 |
+
|
| 1448 |
+
if not return_dict:
|
| 1449 |
+
output = (lm_logits,) + outputs[1:]
|
| 1450 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
| 1451 |
+
|
| 1452 |
+
return Seq2SeqLMOutput(
|
| 1453 |
+
loss=masked_lm_loss,
|
| 1454 |
+
logits=lm_logits,
|
| 1455 |
+
past_key_values=outputs.past_key_values,
|
| 1456 |
+
decoder_hidden_states=outputs.decoder_hidden_states,
|
| 1457 |
+
decoder_attentions=outputs.decoder_attentions,
|
| 1458 |
+
cross_attentions=outputs.cross_attentions,
|
| 1459 |
+
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
|
| 1460 |
+
encoder_hidden_states=outputs.encoder_hidden_states,
|
| 1461 |
+
encoder_attentions=outputs.encoder_attentions,
|
| 1462 |
+
)
|
| 1463 |
+
|
| 1464 |
+
def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
|
| 1465 |
+
return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id)
|
| 1466 |
+
|
| 1467 |
+
|
| 1468 |
+
# Copied from transformers.models.bart.modeling_bart.BartDecoderWrapper with Bart->PegasusX
|
| 1469 |
+
class PegasusXDecoderWrapper(PegasusXPreTrainedModel):
|
| 1470 |
+
"""
|
| 1471 |
+
This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
|
| 1472 |
+
used in combination with the [`EncoderDecoderModel`] framework.
|
| 1473 |
+
"""
|
| 1474 |
+
|
| 1475 |
+
def __init__(self, config):
|
| 1476 |
+
super().__init__(config)
|
| 1477 |
+
self.decoder = PegasusXDecoder(config)
|
| 1478 |
+
self.post_init()
|
| 1479 |
+
|
| 1480 |
+
def forward(self, *args, **kwargs):
|
| 1481 |
+
return self.decoder(*args, **kwargs)
|
| 1482 |
+
|
| 1483 |
+
|
| 1484 |
+
__all__ = ["PegasusXForConditionalGeneration", "PegasusXModel", "PegasusXPreTrainedModel"]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/perceiver/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_perceiver import *
|
| 22 |
+
from .feature_extraction_perceiver import *
|
| 23 |
+
from .image_processing_perceiver import *
|
| 24 |
+
from .image_processing_perceiver_fast import *
|
| 25 |
+
from .modeling_perceiver import *
|
| 26 |
+
from .tokenization_perceiver import *
|
| 27 |
+
else:
|
| 28 |
+
import sys
|
| 29 |
+
|
| 30 |
+
_file = globals()["__file__"]
|
| 31 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/perceiver/configuration_perceiver.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright Deepmind and The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Perceiver model configuration"""
|
| 15 |
+
|
| 16 |
+
from ...configuration_utils import PreTrainedConfig
|
| 17 |
+
from ...utils import logging
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
logger = logging.get_logger(__name__)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class PerceiverConfig(PreTrainedConfig):
|
| 24 |
+
r"""
|
| 25 |
+
This is the configuration class to store the configuration of a [`PerceiverModel`]. It is used to instantiate an
|
| 26 |
+
Perceiver model according to the specified arguments, defining the model architecture. Instantiating a
|
| 27 |
+
configuration with the defaults will yield a similar configuration to that of the Perceiver
|
| 28 |
+
[deepmind/language-perceiver](https://huggingface.co/deepmind/language-perceiver) architecture.
|
| 29 |
+
|
| 30 |
+
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
|
| 31 |
+
documentation from [`PreTrainedConfig`] for more information.
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
num_latents (`int`, *optional*, defaults to 256):
|
| 35 |
+
The number of latents.
|
| 36 |
+
d_latents (`int`, *optional*, defaults to 1280):
|
| 37 |
+
Dimension of the latent embeddings.
|
| 38 |
+
d_model (`int`, *optional*, defaults to 768):
|
| 39 |
+
Dimension of the inputs. Should only be provided in case [*PerceiverTextPreprocessor*] is used or no
|
| 40 |
+
preprocessor is provided.
|
| 41 |
+
num_blocks (`int`, *optional*, defaults to 1):
|
| 42 |
+
Number of blocks in the Transformer encoder.
|
| 43 |
+
num_self_attends_per_block (`int`, *optional*, defaults to 26):
|
| 44 |
+
The number of self-attention layers per block.
|
| 45 |
+
num_self_attention_heads (`int`, *optional*, defaults to 8):
|
| 46 |
+
Number of attention heads for each self-attention layer in the Transformer encoder.
|
| 47 |
+
num_cross_attention_heads (`int`, *optional*, defaults to 8):
|
| 48 |
+
Number of attention heads for each cross-attention layer in the Transformer encoder.
|
| 49 |
+
qk_channels (`int`, *optional*):
|
| 50 |
+
Dimension to project the queries + keys before applying attention in the cross-attention and self-attention
|
| 51 |
+
layers of the encoder. Will default to preserving the dimension of the queries if not specified.
|
| 52 |
+
v_channels (`int`, *optional*):
|
| 53 |
+
Dimension to project the values before applying attention in the cross-attention and self-attention layers
|
| 54 |
+
of the encoder. Will default to preserving the dimension of the queries if not specified.
|
| 55 |
+
cross_attention_shape_for_attention (`str`, *optional*, defaults to `"kv"`):
|
| 56 |
+
Dimension to use when downsampling the queries and keys in the cross-attention layer of the encoder.
|
| 57 |
+
self_attention_widening_factor (`int`, *optional*, defaults to 1):
|
| 58 |
+
Dimension of the feed-forward layer in the cross-attention layer of the Transformer encoder.
|
| 59 |
+
cross_attention_widening_factor (`int`, *optional*, defaults to 1):
|
| 60 |
+
Dimension of the feed-forward layer in the self-attention layers of the Transformer encoder.
|
| 61 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 62 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 63 |
+
`"relu"`, `"selu"` and `"gelu_new"` are supported.
|
| 64 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 65 |
+
The dropout ratio for the attention probabilities.
|
| 66 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 67 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 68 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 69 |
+
The epsilon used by the layer normalization layers.
|
| 70 |
+
use_query_residual (`float`, *optional*, defaults to `True`):
|
| 71 |
+
Whether to add a query residual in the cross-attention layer of the encoder.
|
| 72 |
+
vocab_size (`int`, *optional*, defaults to 262):
|
| 73 |
+
Vocabulary size for the masked language modeling model.
|
| 74 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
| 75 |
+
The maximum sequence length that the masked language modeling model might ever be used with. Typically set
|
| 76 |
+
this to something large just in case (e.g., 512 or 1024 or 2048).
|
| 77 |
+
image_size (`int`, *optional*, defaults to 56):
|
| 78 |
+
Size of the images after preprocessing, for [`PerceiverForImageClassificationLearned`].
|
| 79 |
+
train_size (`list[int]`, *optional*, defaults to `[368, 496]`):
|
| 80 |
+
Training size of the images for the optical flow model.
|
| 81 |
+
num_frames (`int`, *optional*, defaults to 16):
|
| 82 |
+
Number of video frames used for the multimodal autoencoding model.
|
| 83 |
+
audio_samples_per_frame (`int`, *optional*, defaults to 1920):
|
| 84 |
+
Number of audio samples per frame for the multimodal autoencoding model.
|
| 85 |
+
samples_per_patch (`int`, *optional*, defaults to 16):
|
| 86 |
+
Number of audio samples per patch when preprocessing the audio for the multimodal autoencoding model.
|
| 87 |
+
output_shape (`list[int]`, *optional*, defaults to `[1, 16, 224, 224]`):
|
| 88 |
+
Shape of the output (batch_size, num_frames, height, width) for the video decoder queries of the multimodal
|
| 89 |
+
autoencoding model. This excludes the channel dimension.
|
| 90 |
+
output_num_channels (`int`, *optional*, defaults to 512):
|
| 91 |
+
Number of output channels for each modalitiy decoder.
|
| 92 |
+
|
| 93 |
+
Example:
|
| 94 |
+
|
| 95 |
+
```python
|
| 96 |
+
>>> from transformers import PerceiverModel, PerceiverConfig
|
| 97 |
+
|
| 98 |
+
>>> # Initializing a Perceiver deepmind/language-perceiver style configuration
|
| 99 |
+
>>> configuration = PerceiverConfig()
|
| 100 |
+
|
| 101 |
+
>>> # Initializing a model from the deepmind/language-perceiver style configuration
|
| 102 |
+
>>> model = PerceiverModel(configuration)
|
| 103 |
+
|
| 104 |
+
>>> # Accessing the model configuration
|
| 105 |
+
>>> configuration = model.config
|
| 106 |
+
```"""
|
| 107 |
+
|
| 108 |
+
model_type = "perceiver"
|
| 109 |
+
|
| 110 |
+
def __init__(
|
| 111 |
+
self,
|
| 112 |
+
num_latents=256,
|
| 113 |
+
d_latents=1280,
|
| 114 |
+
d_model=768,
|
| 115 |
+
num_blocks=1,
|
| 116 |
+
num_self_attends_per_block=26,
|
| 117 |
+
num_self_attention_heads=8,
|
| 118 |
+
num_cross_attention_heads=8,
|
| 119 |
+
qk_channels=None,
|
| 120 |
+
v_channels=None,
|
| 121 |
+
cross_attention_shape_for_attention="kv",
|
| 122 |
+
self_attention_widening_factor=1,
|
| 123 |
+
cross_attention_widening_factor=1,
|
| 124 |
+
hidden_act="gelu",
|
| 125 |
+
attention_probs_dropout_prob=0.1,
|
| 126 |
+
initializer_range=0.02,
|
| 127 |
+
layer_norm_eps=1e-12,
|
| 128 |
+
use_query_residual=True,
|
| 129 |
+
vocab_size=262,
|
| 130 |
+
max_position_embeddings=2048,
|
| 131 |
+
image_size=56,
|
| 132 |
+
train_size=[368, 496],
|
| 133 |
+
num_frames=16,
|
| 134 |
+
audio_samples_per_frame=1920,
|
| 135 |
+
samples_per_patch=16,
|
| 136 |
+
output_shape=[1, 16, 224, 224],
|
| 137 |
+
output_num_channels=512,
|
| 138 |
+
_label_trainable_num_channels=1024,
|
| 139 |
+
**kwargs,
|
| 140 |
+
):
|
| 141 |
+
super().__init__(**kwargs)
|
| 142 |
+
|
| 143 |
+
self.num_latents = num_latents
|
| 144 |
+
self.d_latents = d_latents
|
| 145 |
+
self.d_model = d_model
|
| 146 |
+
self.num_blocks = num_blocks
|
| 147 |
+
self.num_self_attends_per_block = num_self_attends_per_block
|
| 148 |
+
self.num_self_attention_heads = num_self_attention_heads
|
| 149 |
+
self.num_cross_attention_heads = num_cross_attention_heads
|
| 150 |
+
self.qk_channels = qk_channels
|
| 151 |
+
self.v_channels = v_channels
|
| 152 |
+
self.cross_attention_shape_for_attention = cross_attention_shape_for_attention
|
| 153 |
+
self.self_attention_widening_factor = self_attention_widening_factor
|
| 154 |
+
self.cross_attention_widening_factor = cross_attention_widening_factor
|
| 155 |
+
self.hidden_act = hidden_act
|
| 156 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 157 |
+
self.initializer_range = initializer_range
|
| 158 |
+
self.layer_norm_eps = layer_norm_eps
|
| 159 |
+
self.use_query_residual = use_query_residual
|
| 160 |
+
# masked language modeling attributes
|
| 161 |
+
self.vocab_size = vocab_size
|
| 162 |
+
self.max_position_embeddings = max_position_embeddings
|
| 163 |
+
# image classification attributes
|
| 164 |
+
self.image_size = image_size
|
| 165 |
+
# flow attributes
|
| 166 |
+
self.train_size = train_size
|
| 167 |
+
# multimodal autoencoding attributes
|
| 168 |
+
self.num_frames = num_frames
|
| 169 |
+
self.audio_samples_per_frame = audio_samples_per_frame
|
| 170 |
+
self.samples_per_patch = samples_per_patch
|
| 171 |
+
self.output_shape = output_shape
|
| 172 |
+
self.output_num_channels = output_num_channels
|
| 173 |
+
self._label_trainable_num_channels = _label_trainable_num_channels
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
__all__ = ["PerceiverConfig"]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/perceiver/image_processing_perceiver.py
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Image processor class for Perceiver."""
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
|
| 18 |
+
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
|
| 19 |
+
from ...image_transforms import center_crop, resize, to_channel_dimension_format
|
| 20 |
+
from ...image_utils import (
|
| 21 |
+
IMAGENET_DEFAULT_MEAN,
|
| 22 |
+
IMAGENET_DEFAULT_STD,
|
| 23 |
+
ChannelDimension,
|
| 24 |
+
ImageInput,
|
| 25 |
+
PILImageResampling,
|
| 26 |
+
get_image_size,
|
| 27 |
+
infer_channel_dimension_format,
|
| 28 |
+
is_scaled_image,
|
| 29 |
+
make_flat_list_of_images,
|
| 30 |
+
to_numpy_array,
|
| 31 |
+
valid_images,
|
| 32 |
+
validate_preprocess_arguments,
|
| 33 |
+
)
|
| 34 |
+
from ...utils import TensorType, filter_out_non_signature_kwargs, is_vision_available, logging
|
| 35 |
+
from ...utils.import_utils import requires
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
if is_vision_available():
|
| 39 |
+
import PIL
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
logger = logging.get_logger(__name__)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@requires(backends=("vision",))
|
| 46 |
+
class PerceiverImageProcessor(BaseImageProcessor):
|
| 47 |
+
r"""
|
| 48 |
+
Constructs a Perceiver image processor.
|
| 49 |
+
|
| 50 |
+
Args:
|
| 51 |
+
do_center_crop (`bool`, `optional`, defaults to `True`):
|
| 52 |
+
Whether or not to center crop the image. If the input size if smaller than `crop_size` along any edge, the
|
| 53 |
+
image will be padded with zeros and then center cropped. Can be overridden by the `do_center_crop`
|
| 54 |
+
parameter in the `preprocess` method.
|
| 55 |
+
crop_size (`dict[str, int]`, *optional*, defaults to `{"height": 256, "width": 256}`):
|
| 56 |
+
Desired output size when applying center-cropping. Can be overridden by the `crop_size` parameter in the
|
| 57 |
+
`preprocess` method.
|
| 58 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
| 59 |
+
Whether to resize the image to `(size["height"], size["width"])`. Can be overridden by the `do_resize`
|
| 60 |
+
parameter in the `preprocess` method.
|
| 61 |
+
size (`dict[str, int]` *optional*, defaults to `{"height": 224, "width": 224}`):
|
| 62 |
+
Size of the image after resizing. Can be overridden by the `size` parameter in the `preprocess` method.
|
| 63 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
|
| 64 |
+
Defines the resampling filter to use if resizing the image. Can be overridden by the `resample` parameter
|
| 65 |
+
in the `preprocess` method.
|
| 66 |
+
do_rescale (`bool`, *optional*, defaults to `True`):
|
| 67 |
+
Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
|
| 68 |
+
parameter in the `preprocess` method.
|
| 69 |
+
rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
|
| 70 |
+
Defines the scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter
|
| 71 |
+
in the `preprocess` method.
|
| 72 |
+
do_normalize:
|
| 73 |
+
Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
|
| 74 |
+
method.
|
| 75 |
+
image_mean (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
|
| 76 |
+
Mean to use if normalizing the image. This is a float or list of floats the length of the number of
|
| 77 |
+
channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
|
| 78 |
+
image_std (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
|
| 79 |
+
Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
|
| 80 |
+
number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
model_input_names = ["pixel_values"]
|
| 84 |
+
|
| 85 |
+
def __init__(
|
| 86 |
+
self,
|
| 87 |
+
do_center_crop: bool = True,
|
| 88 |
+
crop_size: dict[str, int] | None = None,
|
| 89 |
+
do_resize: bool = True,
|
| 90 |
+
size: dict[str, int] | None = None,
|
| 91 |
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
| 92 |
+
do_rescale: bool = True,
|
| 93 |
+
rescale_factor: int | float = 1 / 255,
|
| 94 |
+
do_normalize: bool = True,
|
| 95 |
+
image_mean: float | list[float] | None = None,
|
| 96 |
+
image_std: float | list[float] | None = None,
|
| 97 |
+
**kwargs,
|
| 98 |
+
) -> None:
|
| 99 |
+
super().__init__(**kwargs)
|
| 100 |
+
crop_size = crop_size if crop_size is not None else {"height": 256, "width": 256}
|
| 101 |
+
crop_size = get_size_dict(crop_size, param_name="crop_size")
|
| 102 |
+
size = size if size is not None else {"height": 224, "width": 224}
|
| 103 |
+
size = get_size_dict(size)
|
| 104 |
+
|
| 105 |
+
self.do_center_crop = do_center_crop
|
| 106 |
+
self.crop_size = crop_size
|
| 107 |
+
self.do_resize = do_resize
|
| 108 |
+
self.size = size
|
| 109 |
+
self.resample = resample
|
| 110 |
+
self.do_rescale = do_rescale
|
| 111 |
+
self.rescale_factor = rescale_factor
|
| 112 |
+
self.do_normalize = do_normalize
|
| 113 |
+
self.image_mean = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
|
| 114 |
+
self.image_std = image_std if image_std is not None else IMAGENET_DEFAULT_STD
|
| 115 |
+
|
| 116 |
+
def center_crop(
|
| 117 |
+
self,
|
| 118 |
+
image: np.ndarray,
|
| 119 |
+
crop_size: dict[str, int],
|
| 120 |
+
size: int | None = None,
|
| 121 |
+
data_format: str | ChannelDimension | None = None,
|
| 122 |
+
input_data_format: str | ChannelDimension | None = None,
|
| 123 |
+
**kwargs,
|
| 124 |
+
) -> np.ndarray:
|
| 125 |
+
"""
|
| 126 |
+
Center crop an image to `(size["height"] / crop_size["height"] * min_dim, size["width"] / crop_size["width"] *
|
| 127 |
+
min_dim)`. Where `min_dim = min(size["height"], size["width"])`.
|
| 128 |
+
|
| 129 |
+
If the input size is smaller than `crop_size` along any edge, the image will be padded with zeros and then
|
| 130 |
+
center cropped.
|
| 131 |
+
|
| 132 |
+
Args:
|
| 133 |
+
image (`np.ndarray`):
|
| 134 |
+
Image to center crop.
|
| 135 |
+
crop_size (`dict[str, int]`):
|
| 136 |
+
Desired output size after applying the center crop.
|
| 137 |
+
size (`dict[str, int]`, *optional*):
|
| 138 |
+
Size of the image after resizing. If not provided, the self.size attribute will be used.
|
| 139 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
| 140 |
+
The channel dimension format of the image. If not provided, it will be the same as the input image.
|
| 141 |
+
input_data_format (`str` or `ChannelDimension`, *optional*):
|
| 142 |
+
The channel dimension format of the input image. If not provided, it will be inferred.
|
| 143 |
+
"""
|
| 144 |
+
size = self.size if size is None else size
|
| 145 |
+
size = get_size_dict(size)
|
| 146 |
+
crop_size = get_size_dict(crop_size, param_name="crop_size")
|
| 147 |
+
|
| 148 |
+
height, width = get_image_size(image, channel_dim=input_data_format)
|
| 149 |
+
min_dim = min(height, width)
|
| 150 |
+
cropped_height = (size["height"] / crop_size["height"]) * min_dim
|
| 151 |
+
cropped_width = (size["width"] / crop_size["width"]) * min_dim
|
| 152 |
+
return center_crop(
|
| 153 |
+
image,
|
| 154 |
+
size=(cropped_height, cropped_width),
|
| 155 |
+
data_format=data_format,
|
| 156 |
+
input_data_format=input_data_format,
|
| 157 |
+
**kwargs,
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
# Copied from transformers.models.vit.image_processing_vit.ViTImageProcessor.resize with PILImageResampling.BILINEAR->PILImageResampling.BICUBIC
|
| 161 |
+
def resize(
|
| 162 |
+
self,
|
| 163 |
+
image: np.ndarray,
|
| 164 |
+
size: dict[str, int],
|
| 165 |
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
| 166 |
+
data_format: str | ChannelDimension | None = None,
|
| 167 |
+
input_data_format: str | ChannelDimension | None = None,
|
| 168 |
+
**kwargs,
|
| 169 |
+
) -> np.ndarray:
|
| 170 |
+
"""
|
| 171 |
+
Resize an image to `(size["height"], size["width"])`.
|
| 172 |
+
|
| 173 |
+
Args:
|
| 174 |
+
image (`np.ndarray`):
|
| 175 |
+
Image to resize.
|
| 176 |
+
size (`dict[str, int]`):
|
| 177 |
+
Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
|
| 178 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
|
| 179 |
+
`PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BICUBIC`.
|
| 180 |
+
data_format (`ChannelDimension` or `str`, *optional*):
|
| 181 |
+
The channel dimension format for the output image. If unset, the channel dimension format of the input
|
| 182 |
+
image is used. Can be one of:
|
| 183 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 184 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 185 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 186 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 187 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
| 188 |
+
from the input image. Can be one of:
|
| 189 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 190 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 191 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 192 |
+
|
| 193 |
+
Returns:
|
| 194 |
+
`np.ndarray`: The resized image.
|
| 195 |
+
"""
|
| 196 |
+
size = get_size_dict(size)
|
| 197 |
+
if "height" not in size or "width" not in size:
|
| 198 |
+
raise ValueError(f"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}")
|
| 199 |
+
output_size = (size["height"], size["width"])
|
| 200 |
+
return resize(
|
| 201 |
+
image,
|
| 202 |
+
size=output_size,
|
| 203 |
+
resample=resample,
|
| 204 |
+
data_format=data_format,
|
| 205 |
+
input_data_format=input_data_format,
|
| 206 |
+
**kwargs,
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
@filter_out_non_signature_kwargs()
|
| 210 |
+
def preprocess(
|
| 211 |
+
self,
|
| 212 |
+
images: ImageInput,
|
| 213 |
+
do_center_crop: bool | None = None,
|
| 214 |
+
crop_size: dict[str, int] | None = None,
|
| 215 |
+
do_resize: bool | None = None,
|
| 216 |
+
size: dict[str, int] | None = None,
|
| 217 |
+
resample: PILImageResampling | None = None,
|
| 218 |
+
do_rescale: bool | None = None,
|
| 219 |
+
rescale_factor: float | None = None,
|
| 220 |
+
do_normalize: bool | None = None,
|
| 221 |
+
image_mean: float | list[float] | None = None,
|
| 222 |
+
image_std: float | list[float] | None = None,
|
| 223 |
+
return_tensors: str | TensorType | None = None,
|
| 224 |
+
data_format: ChannelDimension = ChannelDimension.FIRST,
|
| 225 |
+
input_data_format: str | ChannelDimension | None = None,
|
| 226 |
+
) -> PIL.Image.Image:
|
| 227 |
+
"""
|
| 228 |
+
Preprocess an image or batch of images.
|
| 229 |
+
|
| 230 |
+
Args:
|
| 231 |
+
images (`ImageInput`):
|
| 232 |
+
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
|
| 233 |
+
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
| 234 |
+
do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
|
| 235 |
+
Whether to center crop the image to `crop_size`.
|
| 236 |
+
crop_size (`dict[str, int]`, *optional*, defaults to `self.crop_size`):
|
| 237 |
+
Desired output size after applying the center crop.
|
| 238 |
+
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
|
| 239 |
+
Whether to resize the image.
|
| 240 |
+
size (`dict[str, int]`, *optional*, defaults to `self.size`):
|
| 241 |
+
Size of the image after resizing.
|
| 242 |
+
resample (`int`, *optional*, defaults to `self.resample`):
|
| 243 |
+
Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`, Only
|
| 244 |
+
has an effect if `do_resize` is set to `True`.
|
| 245 |
+
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
|
| 246 |
+
Whether to rescale the image.
|
| 247 |
+
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
|
| 248 |
+
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
|
| 249 |
+
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
|
| 250 |
+
Whether to normalize the image.
|
| 251 |
+
image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
|
| 252 |
+
Image mean.
|
| 253 |
+
image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
|
| 254 |
+
Image standard deviation.
|
| 255 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
| 256 |
+
The type of tensors to return. Can be one of:
|
| 257 |
+
- Unset: Return a list of `np.ndarray`.
|
| 258 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
| 259 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
| 260 |
+
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
|
| 261 |
+
The channel dimension format for the output image. Can be one of:
|
| 262 |
+
- `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 263 |
+
- `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 264 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 265 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
| 266 |
+
from the input image. Can be one of:
|
| 267 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 268 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 269 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 270 |
+
"""
|
| 271 |
+
do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
|
| 272 |
+
crop_size = crop_size if crop_size is not None else self.crop_size
|
| 273 |
+
crop_size = get_size_dict(crop_size, param_name="crop_size")
|
| 274 |
+
do_resize = do_resize if do_resize is not None else self.do_resize
|
| 275 |
+
size = size if size is not None else self.size
|
| 276 |
+
size = get_size_dict(size)
|
| 277 |
+
resample = resample if resample is not None else self.resample
|
| 278 |
+
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
|
| 279 |
+
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
|
| 280 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
| 281 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
| 282 |
+
image_std = image_std if image_std is not None else self.image_std
|
| 283 |
+
|
| 284 |
+
images = make_flat_list_of_images(images)
|
| 285 |
+
|
| 286 |
+
if not valid_images(images):
|
| 287 |
+
raise ValueError("Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, or torch.Tensor")
|
| 288 |
+
validate_preprocess_arguments(
|
| 289 |
+
do_rescale=do_rescale,
|
| 290 |
+
rescale_factor=rescale_factor,
|
| 291 |
+
do_normalize=do_normalize,
|
| 292 |
+
image_mean=image_mean,
|
| 293 |
+
image_std=image_std,
|
| 294 |
+
do_center_crop=do_center_crop,
|
| 295 |
+
crop_size=crop_size,
|
| 296 |
+
do_resize=do_resize,
|
| 297 |
+
size=size,
|
| 298 |
+
resample=resample,
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
# All transformations expect numpy arrays.
|
| 302 |
+
images = [to_numpy_array(image) for image in images]
|
| 303 |
+
|
| 304 |
+
if do_rescale and is_scaled_image(images[0]):
|
| 305 |
+
logger.warning_once(
|
| 306 |
+
"It looks like you are trying to rescale already rescaled images. If the input"
|
| 307 |
+
" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
if input_data_format is None:
|
| 311 |
+
# We assume that all images have the same channel dimension format.
|
| 312 |
+
input_data_format = infer_channel_dimension_format(images[0])
|
| 313 |
+
|
| 314 |
+
if do_center_crop:
|
| 315 |
+
images = [
|
| 316 |
+
self.center_crop(image, crop_size, size=size, input_data_format=input_data_format) for image in images
|
| 317 |
+
]
|
| 318 |
+
|
| 319 |
+
if do_resize:
|
| 320 |
+
images = [
|
| 321 |
+
self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
|
| 322 |
+
for image in images
|
| 323 |
+
]
|
| 324 |
+
|
| 325 |
+
if do_rescale:
|
| 326 |
+
images = [
|
| 327 |
+
self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
|
| 328 |
+
for image in images
|
| 329 |
+
]
|
| 330 |
+
|
| 331 |
+
if do_normalize:
|
| 332 |
+
images = [
|
| 333 |
+
self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
|
| 334 |
+
for image in images
|
| 335 |
+
]
|
| 336 |
+
|
| 337 |
+
images = [
|
| 338 |
+
to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
|
| 339 |
+
]
|
| 340 |
+
|
| 341 |
+
data = {"pixel_values": images}
|
| 342 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
__all__ = ["PerceiverImageProcessor"]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/perceiver/image_processing_perceiver_fast.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Fast Image processor class for Perceiver."""
|
| 15 |
+
|
| 16 |
+
from typing import Optional
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
import torchvision.transforms.v2.functional as tvF
|
| 20 |
+
|
| 21 |
+
from ...image_processing_utils_fast import BaseImageProcessorFast, BatchFeature
|
| 22 |
+
from ...image_transforms import group_images_by_shape, reorder_images
|
| 23 |
+
from ...image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling, SizeDict
|
| 24 |
+
from ...utils import (
|
| 25 |
+
TensorType,
|
| 26 |
+
auto_docstring,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@auto_docstring
|
| 31 |
+
class PerceiverImageProcessorFast(BaseImageProcessorFast):
|
| 32 |
+
resample = PILImageResampling.BICUBIC
|
| 33 |
+
image_mean = IMAGENET_DEFAULT_MEAN
|
| 34 |
+
image_std = IMAGENET_DEFAULT_STD
|
| 35 |
+
size = {"height": 224, "width": 224}
|
| 36 |
+
crop_size = {"height": 256, "width": 256}
|
| 37 |
+
do_resize = True
|
| 38 |
+
do_center_crop = True
|
| 39 |
+
do_rescale = True
|
| 40 |
+
do_normalize = True
|
| 41 |
+
|
| 42 |
+
def center_crop(
|
| 43 |
+
self,
|
| 44 |
+
image: "torch.Tensor",
|
| 45 |
+
crop_size: dict[str, int],
|
| 46 |
+
size: dict[str, int],
|
| 47 |
+
**kwargs,
|
| 48 |
+
) -> "torch.Tensor":
|
| 49 |
+
"""
|
| 50 |
+
Center crop an image to `(size["height"] / crop_size["height"] * min_dim, size["width"] / crop_size["width"] *
|
| 51 |
+
min_dim)`. Where `min_dim = min(size["height"], size["width"])`.
|
| 52 |
+
|
| 53 |
+
If the input size is smaller than `crop_size` along any edge, the image will be padded with zeros and then
|
| 54 |
+
center cropped.
|
| 55 |
+
|
| 56 |
+
Args:
|
| 57 |
+
image (`"torch.Tensor"`):
|
| 58 |
+
Image to center crop.
|
| 59 |
+
crop_size (`dict[str, int]`):
|
| 60 |
+
Desired output size after applying the center crop.
|
| 61 |
+
size (`dict[str, int]`):
|
| 62 |
+
Size of the output image.
|
| 63 |
+
|
| 64 |
+
Returns:
|
| 65 |
+
`torch.Tensor`: The center cropped image.
|
| 66 |
+
"""
|
| 67 |
+
if size.height is None or size.width is None:
|
| 68 |
+
raise ValueError(f"The size dictionary must have keys 'height' and 'width'. Got {size.keys()}")
|
| 69 |
+
height, width = image.shape[-2:]
|
| 70 |
+
min_dim = min(height, width)
|
| 71 |
+
cropped_height = int((size.height / crop_size.height) * min_dim)
|
| 72 |
+
cropped_width = int((size.width / crop_size.width) * min_dim)
|
| 73 |
+
return super().center_crop(image, SizeDict(height=cropped_height, width=cropped_width))
|
| 74 |
+
|
| 75 |
+
def _preprocess(
|
| 76 |
+
self,
|
| 77 |
+
images: list["torch.Tensor"],
|
| 78 |
+
do_resize: bool,
|
| 79 |
+
size: SizeDict,
|
| 80 |
+
interpolation: Optional["tvF.InterpolationMode"],
|
| 81 |
+
do_center_crop: bool,
|
| 82 |
+
crop_size: SizeDict,
|
| 83 |
+
do_rescale: bool,
|
| 84 |
+
rescale_factor: float,
|
| 85 |
+
do_normalize: bool,
|
| 86 |
+
image_mean: float | list[float] | None,
|
| 87 |
+
image_std: float | list[float] | None,
|
| 88 |
+
disable_grouping: bool | None,
|
| 89 |
+
return_tensors: str | TensorType | None,
|
| 90 |
+
**kwargs,
|
| 91 |
+
) -> BatchFeature:
|
| 92 |
+
# Group images by size for batched resizing
|
| 93 |
+
grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
|
| 94 |
+
resized_images_grouped = {}
|
| 95 |
+
for shape, stacked_images in grouped_images.items():
|
| 96 |
+
if do_center_crop:
|
| 97 |
+
stacked_images = self.center_crop(stacked_images, size=size, crop_size=crop_size)
|
| 98 |
+
if do_resize:
|
| 99 |
+
stacked_images = self.resize(image=stacked_images, size=size, interpolation=interpolation)
|
| 100 |
+
resized_images_grouped[shape] = stacked_images
|
| 101 |
+
resized_images = reorder_images(resized_images_grouped, grouped_images_index)
|
| 102 |
+
|
| 103 |
+
# Group images by size for further processing
|
| 104 |
+
# Needed in case do_resize is False, or resize returns images with different sizes
|
| 105 |
+
grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
|
| 106 |
+
processed_images_grouped = {}
|
| 107 |
+
for shape, stacked_images in grouped_images.items():
|
| 108 |
+
# Fused rescale and normalize
|
| 109 |
+
stacked_images = self.rescale_and_normalize(
|
| 110 |
+
stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
|
| 111 |
+
)
|
| 112 |
+
processed_images_grouped[shape] = stacked_images
|
| 113 |
+
|
| 114 |
+
processed_images = reorder_images(processed_images_grouped, grouped_images_index)
|
| 115 |
+
|
| 116 |
+
return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
__all__ = ["PerceiverImageProcessorFast"]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/perceiver/modeling_perceiver.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/perceiver/tokenization_perceiver.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 The HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Tokenization class for Perceiver."""
|
| 15 |
+
|
| 16 |
+
from ...tokenization_python import AddedToken, PreTrainedTokenizer
|
| 17 |
+
from ...utils import logging
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
logger = logging.get_logger(__name__)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class PerceiverTokenizer(PreTrainedTokenizer):
|
| 24 |
+
"""
|
| 25 |
+
Construct a Perceiver tokenizer. The Perceiver simply uses raw bytes utf-8 encoding.
|
| 26 |
+
|
| 27 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 28 |
+
this superclass for more information regarding those methods.
|
| 29 |
+
|
| 30 |
+
Args:
|
| 31 |
+
pad_token (`str`, *optional*, defaults to `"[PAD]"`):
|
| 32 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 33 |
+
bos_token (`str`, *optional*, defaults to `"[BOS]"`):
|
| 34 |
+
The BOS token (reserved in the vocab, but not actually used).
|
| 35 |
+
eos_token (`str`, *optional*, defaults to `"[EOS]"`):
|
| 36 |
+
The end of sequence token (reserved in the vocab, but not actually used).
|
| 37 |
+
|
| 38 |
+
<Tip>
|
| 39 |
+
|
| 40 |
+
When building a sequence using special tokens, this is not the token that is used for the end of sequence.
|
| 41 |
+
The token used is the `sep_token`.
|
| 42 |
+
|
| 43 |
+
</Tip>
|
| 44 |
+
|
| 45 |
+
mask_token (`str`, *optional*, defaults to `"[MASK]"`):
|
| 46 |
+
The MASK token, useful for masked language modeling.
|
| 47 |
+
cls_token (`str`, *optional*, defaults to `"[CLS]"`):
|
| 48 |
+
The CLS token (reserved in the vocab, but not actually used).
|
| 49 |
+
sep_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 50 |
+
The separator token, which is used when building a sequence from two sequences.
|
| 51 |
+
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 55 |
+
|
| 56 |
+
def __init__(
|
| 57 |
+
self,
|
| 58 |
+
pad_token="[PAD]",
|
| 59 |
+
bos_token="[BOS]",
|
| 60 |
+
eos_token="[EOS]",
|
| 61 |
+
mask_token="[MASK]",
|
| 62 |
+
cls_token="[CLS]",
|
| 63 |
+
sep_token="[SEP]",
|
| 64 |
+
model_max_length=2048,
|
| 65 |
+
**kwargs,
|
| 66 |
+
) -> None:
|
| 67 |
+
pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
|
| 68 |
+
bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
|
| 69 |
+
eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
|
| 70 |
+
mask_token = AddedToken(mask_token, lstrip=False, rstrip=False) if isinstance(mask_token, str) else mask_token
|
| 71 |
+
cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
|
| 72 |
+
sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
|
| 73 |
+
|
| 74 |
+
self._utf_vocab_size = 2**8 # utf is 8 bits
|
| 75 |
+
|
| 76 |
+
# Since these tokens are not part of the vocabulary, we manually add them
|
| 77 |
+
self._added_tokens_decoder: dict[str, int] = {
|
| 78 |
+
0: pad_token,
|
| 79 |
+
1: bos_token,
|
| 80 |
+
2: eos_token,
|
| 81 |
+
3: mask_token,
|
| 82 |
+
4: cls_token,
|
| 83 |
+
5: sep_token,
|
| 84 |
+
}
|
| 85 |
+
self._num_special_tokens = len(self._added_tokens_decoder)
|
| 86 |
+
super().__init__(
|
| 87 |
+
pad_token=pad_token,
|
| 88 |
+
bos_token=bos_token,
|
| 89 |
+
eos_token=eos_token,
|
| 90 |
+
mask_token=mask_token,
|
| 91 |
+
cls_token=cls_token,
|
| 92 |
+
sep_token=sep_token,
|
| 93 |
+
model_max_length=model_max_length,
|
| 94 |
+
**kwargs,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
def get_vocab(self) -> dict[str, int]:
|
| 98 |
+
vocab = {}
|
| 99 |
+
for i in range(self._utf_vocab_size):
|
| 100 |
+
token = chr(i)
|
| 101 |
+
vocab[token] = i + self._num_special_tokens
|
| 102 |
+
vocab.update(self.added_tokens_encoder)
|
| 103 |
+
return vocab
|
| 104 |
+
|
| 105 |
+
@property
|
| 106 |
+
def vocab_size(self):
|
| 107 |
+
return self._utf_vocab_size
|
| 108 |
+
|
| 109 |
+
def get_special_tokens_mask(
|
| 110 |
+
self, token_ids_0: list[int], token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False
|
| 111 |
+
) -> list[int]:
|
| 112 |
+
"""
|
| 113 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 114 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
| 115 |
+
|
| 116 |
+
Args:
|
| 117 |
+
token_ids_0 (`list[int]`):
|
| 118 |
+
List of IDs.
|
| 119 |
+
token_ids_1 (`list[int]`, *optional*):
|
| 120 |
+
Optional second list of IDs for sequence pairs.
|
| 121 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 122 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 123 |
+
|
| 124 |
+
Returns:
|
| 125 |
+
`list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 126 |
+
"""
|
| 127 |
+
if already_has_special_tokens:
|
| 128 |
+
return super().get_special_tokens_mask(
|
| 129 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
# normal case: some special tokens
|
| 133 |
+
if token_ids_1 is None:
|
| 134 |
+
return [1] + [0] * len(token_ids_0) + [1]
|
| 135 |
+
return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
|
| 136 |
+
|
| 137 |
+
def build_inputs_with_special_tokens(
|
| 138 |
+
self, token_ids_0: list[int], token_ids_1: list[int] | None = None
|
| 139 |
+
) -> list[int]:
|
| 140 |
+
"""
|
| 141 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks. A sequence has the
|
| 142 |
+
following format:
|
| 143 |
+
|
| 144 |
+
- single sequence: `[CLS] X [SEP]`
|
| 145 |
+
- pair of sequences: `[CLS] A [SEP] B [SEP]`
|
| 146 |
+
|
| 147 |
+
Args:
|
| 148 |
+
token_ids_0 (`list[int]`):
|
| 149 |
+
List of IDs to which the special tokens will be added.
|
| 150 |
+
token_ids_1 (`list[int]`, *optional*):
|
| 151 |
+
Optional second list of IDs for sequence pairs.
|
| 152 |
+
|
| 153 |
+
Returns:
|
| 154 |
+
`list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 155 |
+
"""
|
| 156 |
+
if token_ids_1 is None:
|
| 157 |
+
return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
|
| 158 |
+
else:
|
| 159 |
+
return [self.cls_token_id] + token_ids_0 + [self.sep_token_id] + token_ids_1 + [self.sep_token_id]
|
| 160 |
+
|
| 161 |
+
def _tokenize(self, text: str) -> list[str]:
|
| 162 |
+
"""Take as input a string and return a list of strings (tokens) for words/sub-words"""
|
| 163 |
+
tokens = [chr(i) for i in text.encode("utf-8")]
|
| 164 |
+
return tokens
|
| 165 |
+
|
| 166 |
+
def _convert_token_to_id(self, token):
|
| 167 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 168 |
+
if len(token) != 1:
|
| 169 |
+
token_id = self.unk_token_id
|
| 170 |
+
else:
|
| 171 |
+
token_id = ord(token) + self._num_special_tokens
|
| 172 |
+
return token_id
|
| 173 |
+
|
| 174 |
+
def _convert_id_to_token(self, index):
|
| 175 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 176 |
+
token = chr(index - self._num_special_tokens)
|
| 177 |
+
return token
|
| 178 |
+
|
| 179 |
+
# TODO @ArthurZ refactor this as well....
|
| 180 |
+
def convert_tokens_to_string(self, tokens):
|
| 181 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 182 |
+
bstring = b""
|
| 183 |
+
for token in tokens:
|
| 184 |
+
if token in self.added_tokens_encoder:
|
| 185 |
+
tok_string = str(token).encode("utf-8")
|
| 186 |
+
else:
|
| 187 |
+
tok_string = bytes([ord(token)])
|
| 188 |
+
bstring += tok_string
|
| 189 |
+
string = bstring.decode("utf-8", errors="replace")
|
| 190 |
+
return string
|
| 191 |
+
|
| 192 |
+
# PerceiverTokenizer has no vocab file
|
| 193 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
|
| 194 |
+
return ()
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
__all__ = ["PerceiverTokenizer"]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/perception_lm/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_perception_lm import *
|
| 22 |
+
from .image_processing_perception_lm_fast import *
|
| 23 |
+
from .modeling_perception_lm import *
|
| 24 |
+
from .processing_perception_lm import *
|
| 25 |
+
else:
|
| 26 |
+
import sys
|
| 27 |
+
|
| 28 |
+
_file = globals()["__file__"]
|
| 29 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/perception_lm/configuration_perception_lm.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 Meta Platforms, Inc. and the HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 3 |
+
# you may not use this file except in compliance with the License.
|
| 4 |
+
# You may obtain a copy of the License at
|
| 5 |
+
#
|
| 6 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
#
|
| 8 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 9 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 10 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 11 |
+
# See the License for the specific language governing permissions and
|
| 12 |
+
# limitations under the License.
|
| 13 |
+
"""PerceptionLM model configuration"""
|
| 14 |
+
|
| 15 |
+
from ...configuration_utils import PreTrainedConfig
|
| 16 |
+
from ...utils import logging
|
| 17 |
+
from ..auto import CONFIG_MAPPING, AutoConfig
|
| 18 |
+
from ..timm_wrapper.configuration_timm_wrapper import TimmWrapperConfig
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
logger = logging.get_logger(__name__)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class PerceptionLMConfig(PreTrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
This is the configuration class to store the configuration of a [`PerceptionLMForConditionalGeneration`]. It is used to instantiate an
|
| 27 |
+
PerceptionLM model according to the specified arguments, defining the model architecture.
|
| 28 |
+
|
| 29 |
+
Example models:
|
| 30 |
+
- [facebook/Perception-LM-1B](https://huggingface.co/facebook/Perception-LM-1B).
|
| 31 |
+
- [facebook/Perception-LM-3B](https://huggingface.co/facebook/Perception-LM-3B).
|
| 32 |
+
- [facebook/Perception-LM-8B](https://huggingface.co/facebook/Perception-LM-8B).
|
| 33 |
+
|
| 34 |
+
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
|
| 35 |
+
documentation from [`PreTrainedConfig`] for more information.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
vision_config (`Union[TimmWrapperConfig, dict]`, *optional*, defaults to `TimmWrapperConfig()`):
|
| 39 |
+
The config object or dictionary of the vision backbone.
|
| 40 |
+
text_config (`Union[PreTrainedConfig, dict]`, *optional*, defaults to `LlamaConfig()`):
|
| 41 |
+
The config object or dictionary of the text backbone.
|
| 42 |
+
vision_use_cls_token (`bool`, *optional*, defaults to `True`):
|
| 43 |
+
Whether CLS token is used in the vision backbone. If used, we remove CLS token embedding from vision output.
|
| 44 |
+
projector_pooling_ratio (`int`, *optional*, defaults to 1):
|
| 45 |
+
The pooling ratio used in the multimodal projector.
|
| 46 |
+
image_token_id (`int`, *optional*, defaults to 128002):
|
| 47 |
+
The image token index to encode the image prompt.
|
| 48 |
+
video_token_id (`int`, *optional*, defaults to 128003):
|
| 49 |
+
The video token index to encode the video prompt.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
model_type = "perception_lm"
|
| 53 |
+
sub_configs = {"text_config": AutoConfig, "vision_config": TimmWrapperConfig}
|
| 54 |
+
|
| 55 |
+
def __init__(
|
| 56 |
+
self,
|
| 57 |
+
vision_config=None,
|
| 58 |
+
text_config=None,
|
| 59 |
+
vision_use_cls_token=True,
|
| 60 |
+
projector_pooling_ratio=1,
|
| 61 |
+
image_token_id=128002,
|
| 62 |
+
video_token_id=128003,
|
| 63 |
+
**kwargs,
|
| 64 |
+
):
|
| 65 |
+
self.image_token_id = image_token_id
|
| 66 |
+
self.video_token_id = video_token_id
|
| 67 |
+
if isinstance(vision_config, dict):
|
| 68 |
+
vision_config = TimmWrapperConfig(**vision_config)
|
| 69 |
+
elif isinstance(vision_config, TimmWrapperConfig):
|
| 70 |
+
pass
|
| 71 |
+
elif vision_config is None:
|
| 72 |
+
vision_config = TimmWrapperConfig()
|
| 73 |
+
self.vision_config = vision_config
|
| 74 |
+
self.vision_use_cls_token = vision_use_cls_token
|
| 75 |
+
|
| 76 |
+
if isinstance(text_config, dict):
|
| 77 |
+
text_config["model_type"] = text_config.get("model_type", "llama")
|
| 78 |
+
text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config)
|
| 79 |
+
elif text_config is None:
|
| 80 |
+
text_config = CONFIG_MAPPING["llama"]()
|
| 81 |
+
|
| 82 |
+
self.text_config = text_config
|
| 83 |
+
self.projector_pooling_ratio = projector_pooling_ratio
|
| 84 |
+
super().__init__(**kwargs)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
__all__ = ["PerceptionLMConfig"]
|