Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers-4.56.2.dist-info/INSTALLER +1 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers-4.56.2.dist-info/LICENSE +203 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers-4.56.2.dist-info/METADATA +805 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers-4.56.2.dist-info/RECORD +0 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers-4.56.2.dist-info/REQUESTED +0 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers-4.56.2.dist-info/WHEEL +5 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers-4.56.2.dist-info/entry_points.txt +3 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers-4.56.2.dist-info/top_level.txt +1 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/siglip/image_processing_siglip.py +245 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/siglip/image_processing_siglip_fast.py +38 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/siglip/modeling_siglip.py +1222 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/siglip/processing_siglip.py +124 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/siglip/tokenization_siglip.py +380 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/siglip2/__init__.py +30 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/siglip2/configuration_siglip2.py +265 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/siglip2/image_processing_siglip2.py +344 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/siglip2/image_processing_siglip2_fast.py +182 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/siglip2/modeling_siglip2.py +1303 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/siglip2/modular_siglip2.py +637 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/siglip2/processing_siglip2.py +151 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/smollm3/__init__.py +27 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/smollm3/configuration_smollm3.py +247 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/smollm3/modeling_smollm3.py +527 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/smollm3/modular_smollm3.py +361 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/smolvlm/__init__.py +30 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/smolvlm/configuration_smolvlm.py +196 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/smolvlm/image_processing_smolvlm.py +896 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/smolvlm/image_processing_smolvlm_fast.py +536 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/smolvlm/modeling_smolvlm.py +1028 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/smolvlm/modular_smolvlm.py +410 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/smolvlm/processing_smolvlm.py +423 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/smolvlm/video_processing_smolvlm.py +377 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speech_encoder_decoder/__init__.py +28 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speech_encoder_decoder/configuration_speech_encoder_decoder.py +112 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speech_encoder_decoder/modeling_flax_speech_encoder_decoder.py +930 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speech_encoder_decoder/modeling_speech_encoder_decoder.py +504 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speech_to_text/__init__.py +31 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speech_to_text/configuration_speech_to_text.py +199 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speech_to_text/feature_extraction_speech_to_text.py +315 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speech_to_text/modeling_speech_to_text.py +1336 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speech_to_text/modeling_tf_speech_to_text.py +1600 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speech_to_text/processing_speech_to_text.py +106 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speech_to_text/tokenization_speech_to_text.py +295 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speecht5/__init__.py +30 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speecht5/configuration_speecht5.py +422 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speecht5/feature_extraction_speecht5.py +396 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speecht5/modeling_speecht5.py +0 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speecht5/number_normalizer.py +192 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speecht5/processing_speecht5.py +172 -0
- code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speecht5/tokenization_speecht5.py +223 -0
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers-4.56.2.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers-4.56.2.dist-info/LICENSE
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers-4.56.2.dist-info/METADATA
ADDED
|
@@ -0,0 +1,805 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: transformers
|
| 3 |
+
Version: 4.56.2
|
| 4 |
+
Summary: State-of-the-art Machine Learning for JAX, PyTorch and TensorFlow
|
| 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: NLP vision speech deep learning transformer pytorch tensorflow jax BERT GPT-2 Wav2Vec2 ViT
|
| 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: License :: OSI Approved :: Apache Software License
|
| 15 |
+
Classifier: Operating System :: OS Independent
|
| 16 |
+
Classifier: Programming Language :: Python :: 3
|
| 17 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 18 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 21 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 22 |
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
| 23 |
+
Requires-Python: >=3.9.0
|
| 24 |
+
Description-Content-Type: text/markdown
|
| 25 |
+
License-File: LICENSE
|
| 26 |
+
Requires-Dist: filelock
|
| 27 |
+
Requires-Dist: huggingface-hub<1.0,>=0.34.0
|
| 28 |
+
Requires-Dist: numpy>=1.17
|
| 29 |
+
Requires-Dist: packaging>=20.0
|
| 30 |
+
Requires-Dist: pyyaml>=5.1
|
| 31 |
+
Requires-Dist: regex!=2019.12.17
|
| 32 |
+
Requires-Dist: requests
|
| 33 |
+
Requires-Dist: tokenizers<=0.23.0,>=0.22.0
|
| 34 |
+
Requires-Dist: safetensors>=0.4.3
|
| 35 |
+
Requires-Dist: tqdm>=4.27
|
| 36 |
+
Provides-Extra: accelerate
|
| 37 |
+
Requires-Dist: accelerate>=0.26.0; extra == "accelerate"
|
| 38 |
+
Provides-Extra: all
|
| 39 |
+
Requires-Dist: tensorflow<2.16,>2.9; extra == "all"
|
| 40 |
+
Requires-Dist: onnxconverter-common; extra == "all"
|
| 41 |
+
Requires-Dist: tf2onnx; extra == "all"
|
| 42 |
+
Requires-Dist: tensorflow-text<2.16; extra == "all"
|
| 43 |
+
Requires-Dist: keras-nlp<0.14.0,>=0.3.1; extra == "all"
|
| 44 |
+
Requires-Dist: torch>=2.2; extra == "all"
|
| 45 |
+
Requires-Dist: accelerate>=0.26.0; extra == "all"
|
| 46 |
+
Requires-Dist: jax<=0.4.13,>=0.4.1; extra == "all"
|
| 47 |
+
Requires-Dist: jaxlib<=0.4.13,>=0.4.1; extra == "all"
|
| 48 |
+
Requires-Dist: flax<=0.7.0,>=0.4.1; extra == "all"
|
| 49 |
+
Requires-Dist: optax<=0.1.4,>=0.0.8; extra == "all"
|
| 50 |
+
Requires-Dist: scipy<1.13.0; extra == "all"
|
| 51 |
+
Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "all"
|
| 52 |
+
Requires-Dist: protobuf; extra == "all"
|
| 53 |
+
Requires-Dist: tokenizers<=0.23.0,>=0.22.0; extra == "all"
|
| 54 |
+
Requires-Dist: torchaudio; extra == "all"
|
| 55 |
+
Requires-Dist: librosa; extra == "all"
|
| 56 |
+
Requires-Dist: pyctcdecode>=0.4.0; extra == "all"
|
| 57 |
+
Requires-Dist: phonemizer; extra == "all"
|
| 58 |
+
Requires-Dist: kenlm; extra == "all"
|
| 59 |
+
Requires-Dist: Pillow<=15.0,>=10.0.1; extra == "all"
|
| 60 |
+
Requires-Dist: kernels<=0.9,>=0.6.1; extra == "all"
|
| 61 |
+
Requires-Dist: optuna; extra == "all"
|
| 62 |
+
Requires-Dist: ray[tune]>=2.7.0; extra == "all"
|
| 63 |
+
Requires-Dist: sigopt; extra == "all"
|
| 64 |
+
Requires-Dist: timm!=1.0.18,<=1.0.19; extra == "all"
|
| 65 |
+
Requires-Dist: torchvision; extra == "all"
|
| 66 |
+
Requires-Dist: codecarbon>=2.8.1; extra == "all"
|
| 67 |
+
Requires-Dist: av; extra == "all"
|
| 68 |
+
Requires-Dist: num2words; extra == "all"
|
| 69 |
+
Requires-Dist: mistral-common[opencv]>=1.6.3; extra == "all"
|
| 70 |
+
Requires-Dist: jinja2>=3.1.0; extra == "all"
|
| 71 |
+
Provides-Extra: audio
|
| 72 |
+
Requires-Dist: librosa; extra == "audio"
|
| 73 |
+
Requires-Dist: pyctcdecode>=0.4.0; extra == "audio"
|
| 74 |
+
Requires-Dist: phonemizer; extra == "audio"
|
| 75 |
+
Requires-Dist: kenlm; extra == "audio"
|
| 76 |
+
Provides-Extra: benchmark
|
| 77 |
+
Requires-Dist: optimum-benchmark>=0.3.0; extra == "benchmark"
|
| 78 |
+
Provides-Extra: chat_template
|
| 79 |
+
Requires-Dist: jinja2>=3.1.0; extra == "chat-template"
|
| 80 |
+
Provides-Extra: codecarbon
|
| 81 |
+
Requires-Dist: codecarbon>=2.8.1; extra == "codecarbon"
|
| 82 |
+
Provides-Extra: deepspeed
|
| 83 |
+
Requires-Dist: deepspeed>=0.9.3; extra == "deepspeed"
|
| 84 |
+
Requires-Dist: accelerate>=0.26.0; extra == "deepspeed"
|
| 85 |
+
Provides-Extra: deepspeed-testing
|
| 86 |
+
Requires-Dist: deepspeed>=0.9.3; extra == "deepspeed-testing"
|
| 87 |
+
Requires-Dist: accelerate>=0.26.0; extra == "deepspeed-testing"
|
| 88 |
+
Requires-Dist: pytest>=7.2.0; extra == "deepspeed-testing"
|
| 89 |
+
Requires-Dist: pytest-asyncio; extra == "deepspeed-testing"
|
| 90 |
+
Requires-Dist: pytest-rich; extra == "deepspeed-testing"
|
| 91 |
+
Requires-Dist: pytest-xdist; extra == "deepspeed-testing"
|
| 92 |
+
Requires-Dist: pytest-order; extra == "deepspeed-testing"
|
| 93 |
+
Requires-Dist: pytest-rerunfailures; extra == "deepspeed-testing"
|
| 94 |
+
Requires-Dist: timeout-decorator; extra == "deepspeed-testing"
|
| 95 |
+
Requires-Dist: parameterized>=0.9; extra == "deepspeed-testing"
|
| 96 |
+
Requires-Dist: psutil; extra == "deepspeed-testing"
|
| 97 |
+
Requires-Dist: datasets>=2.15.0; extra == "deepspeed-testing"
|
| 98 |
+
Requires-Dist: dill<0.3.5; extra == "deepspeed-testing"
|
| 99 |
+
Requires-Dist: evaluate>=0.2.0; extra == "deepspeed-testing"
|
| 100 |
+
Requires-Dist: pytest-timeout; extra == "deepspeed-testing"
|
| 101 |
+
Requires-Dist: ruff==0.11.2; extra == "deepspeed-testing"
|
| 102 |
+
Requires-Dist: rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1; extra == "deepspeed-testing"
|
| 103 |
+
Requires-Dist: nltk<=3.8.1; extra == "deepspeed-testing"
|
| 104 |
+
Requires-Dist: GitPython<3.1.19; extra == "deepspeed-testing"
|
| 105 |
+
Requires-Dist: sacremoses; extra == "deepspeed-testing"
|
| 106 |
+
Requires-Dist: rjieba; extra == "deepspeed-testing"
|
| 107 |
+
Requires-Dist: beautifulsoup4; extra == "deepspeed-testing"
|
| 108 |
+
Requires-Dist: tensorboard; extra == "deepspeed-testing"
|
| 109 |
+
Requires-Dist: pydantic>=2; extra == "deepspeed-testing"
|
| 110 |
+
Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "deepspeed-testing"
|
| 111 |
+
Requires-Dist: sacrebleu<2.0.0,>=1.4.12; extra == "deepspeed-testing"
|
| 112 |
+
Requires-Dist: libcst; extra == "deepspeed-testing"
|
| 113 |
+
Requires-Dist: faiss-cpu; extra == "deepspeed-testing"
|
| 114 |
+
Requires-Dist: cookiecutter==1.7.3; extra == "deepspeed-testing"
|
| 115 |
+
Requires-Dist: mistral-common[opencv]>=1.6.3; extra == "deepspeed-testing"
|
| 116 |
+
Requires-Dist: optuna; extra == "deepspeed-testing"
|
| 117 |
+
Requires-Dist: protobuf; extra == "deepspeed-testing"
|
| 118 |
+
Provides-Extra: dev
|
| 119 |
+
Requires-Dist: tensorflow<2.16,>2.9; extra == "dev"
|
| 120 |
+
Requires-Dist: onnxconverter-common; extra == "dev"
|
| 121 |
+
Requires-Dist: tf2onnx; extra == "dev"
|
| 122 |
+
Requires-Dist: tensorflow-text<2.16; extra == "dev"
|
| 123 |
+
Requires-Dist: keras-nlp<0.14.0,>=0.3.1; extra == "dev"
|
| 124 |
+
Requires-Dist: torch>=2.2; extra == "dev"
|
| 125 |
+
Requires-Dist: accelerate>=0.26.0; extra == "dev"
|
| 126 |
+
Requires-Dist: jax<=0.4.13,>=0.4.1; extra == "dev"
|
| 127 |
+
Requires-Dist: jaxlib<=0.4.13,>=0.4.1; extra == "dev"
|
| 128 |
+
Requires-Dist: flax<=0.7.0,>=0.4.1; extra == "dev"
|
| 129 |
+
Requires-Dist: optax<=0.1.4,>=0.0.8; extra == "dev"
|
| 130 |
+
Requires-Dist: scipy<1.13.0; extra == "dev"
|
| 131 |
+
Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "dev"
|
| 132 |
+
Requires-Dist: protobuf; extra == "dev"
|
| 133 |
+
Requires-Dist: tokenizers<=0.23.0,>=0.22.0; extra == "dev"
|
| 134 |
+
Requires-Dist: torchaudio; extra == "dev"
|
| 135 |
+
Requires-Dist: librosa; extra == "dev"
|
| 136 |
+
Requires-Dist: pyctcdecode>=0.4.0; extra == "dev"
|
| 137 |
+
Requires-Dist: phonemizer; extra == "dev"
|
| 138 |
+
Requires-Dist: kenlm; extra == "dev"
|
| 139 |
+
Requires-Dist: Pillow<=15.0,>=10.0.1; extra == "dev"
|
| 140 |
+
Requires-Dist: kernels<=0.9,>=0.6.1; extra == "dev"
|
| 141 |
+
Requires-Dist: optuna; extra == "dev"
|
| 142 |
+
Requires-Dist: ray[tune]>=2.7.0; extra == "dev"
|
| 143 |
+
Requires-Dist: sigopt; extra == "dev"
|
| 144 |
+
Requires-Dist: timm!=1.0.18,<=1.0.19; extra == "dev"
|
| 145 |
+
Requires-Dist: torchvision; extra == "dev"
|
| 146 |
+
Requires-Dist: codecarbon>=2.8.1; extra == "dev"
|
| 147 |
+
Requires-Dist: av; extra == "dev"
|
| 148 |
+
Requires-Dist: num2words; extra == "dev"
|
| 149 |
+
Requires-Dist: mistral-common[opencv]>=1.6.3; extra == "dev"
|
| 150 |
+
Requires-Dist: jinja2>=3.1.0; extra == "dev"
|
| 151 |
+
Requires-Dist: pytest>=7.2.0; extra == "dev"
|
| 152 |
+
Requires-Dist: pytest-asyncio; extra == "dev"
|
| 153 |
+
Requires-Dist: pytest-rich; extra == "dev"
|
| 154 |
+
Requires-Dist: pytest-xdist; extra == "dev"
|
| 155 |
+
Requires-Dist: pytest-order; extra == "dev"
|
| 156 |
+
Requires-Dist: pytest-rerunfailures; extra == "dev"
|
| 157 |
+
Requires-Dist: timeout-decorator; extra == "dev"
|
| 158 |
+
Requires-Dist: parameterized>=0.9; extra == "dev"
|
| 159 |
+
Requires-Dist: psutil; extra == "dev"
|
| 160 |
+
Requires-Dist: datasets>=2.15.0; extra == "dev"
|
| 161 |
+
Requires-Dist: dill<0.3.5; extra == "dev"
|
| 162 |
+
Requires-Dist: evaluate>=0.2.0; extra == "dev"
|
| 163 |
+
Requires-Dist: pytest-timeout; extra == "dev"
|
| 164 |
+
Requires-Dist: ruff==0.11.2; extra == "dev"
|
| 165 |
+
Requires-Dist: rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1; extra == "dev"
|
| 166 |
+
Requires-Dist: nltk<=3.8.1; extra == "dev"
|
| 167 |
+
Requires-Dist: GitPython<3.1.19; extra == "dev"
|
| 168 |
+
Requires-Dist: sacremoses; extra == "dev"
|
| 169 |
+
Requires-Dist: rjieba; extra == "dev"
|
| 170 |
+
Requires-Dist: beautifulsoup4; extra == "dev"
|
| 171 |
+
Requires-Dist: tensorboard; extra == "dev"
|
| 172 |
+
Requires-Dist: pydantic>=2; extra == "dev"
|
| 173 |
+
Requires-Dist: sacrebleu<2.0.0,>=1.4.12; extra == "dev"
|
| 174 |
+
Requires-Dist: libcst; extra == "dev"
|
| 175 |
+
Requires-Dist: faiss-cpu; extra == "dev"
|
| 176 |
+
Requires-Dist: cookiecutter==1.7.3; extra == "dev"
|
| 177 |
+
Requires-Dist: urllib3<2.0.0; extra == "dev"
|
| 178 |
+
Requires-Dist: rich; extra == "dev"
|
| 179 |
+
Requires-Dist: pandas<2.3.0; extra == "dev"
|
| 180 |
+
Requires-Dist: fugashi>=1.0; extra == "dev"
|
| 181 |
+
Requires-Dist: ipadic<2.0,>=1.0.0; extra == "dev"
|
| 182 |
+
Requires-Dist: unidic-lite>=1.0.7; extra == "dev"
|
| 183 |
+
Requires-Dist: unidic>=1.0.2; extra == "dev"
|
| 184 |
+
Requires-Dist: sudachipy>=0.6.6; extra == "dev"
|
| 185 |
+
Requires-Dist: sudachidict-core>=20220729; extra == "dev"
|
| 186 |
+
Requires-Dist: rhoknp<1.3.1,>=1.1.0; extra == "dev"
|
| 187 |
+
Requires-Dist: scikit-learn; extra == "dev"
|
| 188 |
+
Provides-Extra: dev-tensorflow
|
| 189 |
+
Requires-Dist: pytest>=7.2.0; extra == "dev-tensorflow"
|
| 190 |
+
Requires-Dist: pytest-asyncio; extra == "dev-tensorflow"
|
| 191 |
+
Requires-Dist: pytest-rich; extra == "dev-tensorflow"
|
| 192 |
+
Requires-Dist: pytest-xdist; extra == "dev-tensorflow"
|
| 193 |
+
Requires-Dist: pytest-order; extra == "dev-tensorflow"
|
| 194 |
+
Requires-Dist: pytest-rerunfailures; extra == "dev-tensorflow"
|
| 195 |
+
Requires-Dist: timeout-decorator; extra == "dev-tensorflow"
|
| 196 |
+
Requires-Dist: parameterized>=0.9; extra == "dev-tensorflow"
|
| 197 |
+
Requires-Dist: psutil; extra == "dev-tensorflow"
|
| 198 |
+
Requires-Dist: datasets>=2.15.0; extra == "dev-tensorflow"
|
| 199 |
+
Requires-Dist: dill<0.3.5; extra == "dev-tensorflow"
|
| 200 |
+
Requires-Dist: evaluate>=0.2.0; extra == "dev-tensorflow"
|
| 201 |
+
Requires-Dist: pytest-timeout; extra == "dev-tensorflow"
|
| 202 |
+
Requires-Dist: ruff==0.11.2; extra == "dev-tensorflow"
|
| 203 |
+
Requires-Dist: rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1; extra == "dev-tensorflow"
|
| 204 |
+
Requires-Dist: nltk<=3.8.1; extra == "dev-tensorflow"
|
| 205 |
+
Requires-Dist: GitPython<3.1.19; extra == "dev-tensorflow"
|
| 206 |
+
Requires-Dist: sacremoses; extra == "dev-tensorflow"
|
| 207 |
+
Requires-Dist: rjieba; extra == "dev-tensorflow"
|
| 208 |
+
Requires-Dist: beautifulsoup4; extra == "dev-tensorflow"
|
| 209 |
+
Requires-Dist: tensorboard; extra == "dev-tensorflow"
|
| 210 |
+
Requires-Dist: pydantic>=2; extra == "dev-tensorflow"
|
| 211 |
+
Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "dev-tensorflow"
|
| 212 |
+
Requires-Dist: sacrebleu<2.0.0,>=1.4.12; extra == "dev-tensorflow"
|
| 213 |
+
Requires-Dist: libcst; extra == "dev-tensorflow"
|
| 214 |
+
Requires-Dist: faiss-cpu; extra == "dev-tensorflow"
|
| 215 |
+
Requires-Dist: cookiecutter==1.7.3; extra == "dev-tensorflow"
|
| 216 |
+
Requires-Dist: mistral-common[opencv]>=1.6.3; extra == "dev-tensorflow"
|
| 217 |
+
Requires-Dist: tensorflow<2.16,>2.9; extra == "dev-tensorflow"
|
| 218 |
+
Requires-Dist: onnxconverter-common; extra == "dev-tensorflow"
|
| 219 |
+
Requires-Dist: tf2onnx; extra == "dev-tensorflow"
|
| 220 |
+
Requires-Dist: tensorflow-text<2.16; extra == "dev-tensorflow"
|
| 221 |
+
Requires-Dist: keras-nlp<0.14.0,>=0.3.1; extra == "dev-tensorflow"
|
| 222 |
+
Requires-Dist: protobuf; extra == "dev-tensorflow"
|
| 223 |
+
Requires-Dist: tokenizers<=0.23.0,>=0.22.0; extra == "dev-tensorflow"
|
| 224 |
+
Requires-Dist: Pillow<=15.0,>=10.0.1; extra == "dev-tensorflow"
|
| 225 |
+
Requires-Dist: urllib3<2.0.0; extra == "dev-tensorflow"
|
| 226 |
+
Requires-Dist: rich; extra == "dev-tensorflow"
|
| 227 |
+
Requires-Dist: pandas<2.3.0; extra == "dev-tensorflow"
|
| 228 |
+
Requires-Dist: scikit-learn; extra == "dev-tensorflow"
|
| 229 |
+
Requires-Dist: onnxruntime>=1.4.0; extra == "dev-tensorflow"
|
| 230 |
+
Requires-Dist: onnxruntime-tools>=1.4.2; extra == "dev-tensorflow"
|
| 231 |
+
Requires-Dist: librosa; extra == "dev-tensorflow"
|
| 232 |
+
Requires-Dist: pyctcdecode>=0.4.0; extra == "dev-tensorflow"
|
| 233 |
+
Requires-Dist: phonemizer; extra == "dev-tensorflow"
|
| 234 |
+
Requires-Dist: kenlm; extra == "dev-tensorflow"
|
| 235 |
+
Provides-Extra: dev-torch
|
| 236 |
+
Requires-Dist: pytest>=7.2.0; extra == "dev-torch"
|
| 237 |
+
Requires-Dist: pytest-asyncio; extra == "dev-torch"
|
| 238 |
+
Requires-Dist: pytest-rich; extra == "dev-torch"
|
| 239 |
+
Requires-Dist: pytest-xdist; extra == "dev-torch"
|
| 240 |
+
Requires-Dist: pytest-order; extra == "dev-torch"
|
| 241 |
+
Requires-Dist: pytest-rerunfailures; extra == "dev-torch"
|
| 242 |
+
Requires-Dist: timeout-decorator; extra == "dev-torch"
|
| 243 |
+
Requires-Dist: parameterized>=0.9; extra == "dev-torch"
|
| 244 |
+
Requires-Dist: psutil; extra == "dev-torch"
|
| 245 |
+
Requires-Dist: datasets>=2.15.0; extra == "dev-torch"
|
| 246 |
+
Requires-Dist: dill<0.3.5; extra == "dev-torch"
|
| 247 |
+
Requires-Dist: evaluate>=0.2.0; extra == "dev-torch"
|
| 248 |
+
Requires-Dist: pytest-timeout; extra == "dev-torch"
|
| 249 |
+
Requires-Dist: ruff==0.11.2; extra == "dev-torch"
|
| 250 |
+
Requires-Dist: rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1; extra == "dev-torch"
|
| 251 |
+
Requires-Dist: nltk<=3.8.1; extra == "dev-torch"
|
| 252 |
+
Requires-Dist: GitPython<3.1.19; extra == "dev-torch"
|
| 253 |
+
Requires-Dist: sacremoses; extra == "dev-torch"
|
| 254 |
+
Requires-Dist: rjieba; extra == "dev-torch"
|
| 255 |
+
Requires-Dist: beautifulsoup4; extra == "dev-torch"
|
| 256 |
+
Requires-Dist: tensorboard; extra == "dev-torch"
|
| 257 |
+
Requires-Dist: pydantic>=2; extra == "dev-torch"
|
| 258 |
+
Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "dev-torch"
|
| 259 |
+
Requires-Dist: sacrebleu<2.0.0,>=1.4.12; extra == "dev-torch"
|
| 260 |
+
Requires-Dist: libcst; extra == "dev-torch"
|
| 261 |
+
Requires-Dist: faiss-cpu; extra == "dev-torch"
|
| 262 |
+
Requires-Dist: cookiecutter==1.7.3; extra == "dev-torch"
|
| 263 |
+
Requires-Dist: mistral-common[opencv]>=1.6.3; extra == "dev-torch"
|
| 264 |
+
Requires-Dist: torch>=2.2; extra == "dev-torch"
|
| 265 |
+
Requires-Dist: accelerate>=0.26.0; extra == "dev-torch"
|
| 266 |
+
Requires-Dist: protobuf; extra == "dev-torch"
|
| 267 |
+
Requires-Dist: tokenizers<=0.23.0,>=0.22.0; extra == "dev-torch"
|
| 268 |
+
Requires-Dist: torchaudio; extra == "dev-torch"
|
| 269 |
+
Requires-Dist: librosa; extra == "dev-torch"
|
| 270 |
+
Requires-Dist: pyctcdecode>=0.4.0; extra == "dev-torch"
|
| 271 |
+
Requires-Dist: phonemizer; extra == "dev-torch"
|
| 272 |
+
Requires-Dist: kenlm; extra == "dev-torch"
|
| 273 |
+
Requires-Dist: Pillow<=15.0,>=10.0.1; extra == "dev-torch"
|
| 274 |
+
Requires-Dist: kernels<=0.9,>=0.6.1; extra == "dev-torch"
|
| 275 |
+
Requires-Dist: optuna; extra == "dev-torch"
|
| 276 |
+
Requires-Dist: ray[tune]>=2.7.0; extra == "dev-torch"
|
| 277 |
+
Requires-Dist: sigopt; extra == "dev-torch"
|
| 278 |
+
Requires-Dist: timm!=1.0.18,<=1.0.19; extra == "dev-torch"
|
| 279 |
+
Requires-Dist: torchvision; extra == "dev-torch"
|
| 280 |
+
Requires-Dist: codecarbon>=2.8.1; extra == "dev-torch"
|
| 281 |
+
Requires-Dist: urllib3<2.0.0; extra == "dev-torch"
|
| 282 |
+
Requires-Dist: rich; extra == "dev-torch"
|
| 283 |
+
Requires-Dist: pandas<2.3.0; extra == "dev-torch"
|
| 284 |
+
Requires-Dist: fugashi>=1.0; extra == "dev-torch"
|
| 285 |
+
Requires-Dist: ipadic<2.0,>=1.0.0; extra == "dev-torch"
|
| 286 |
+
Requires-Dist: unidic-lite>=1.0.7; extra == "dev-torch"
|
| 287 |
+
Requires-Dist: unidic>=1.0.2; extra == "dev-torch"
|
| 288 |
+
Requires-Dist: sudachipy>=0.6.6; extra == "dev-torch"
|
| 289 |
+
Requires-Dist: sudachidict-core>=20220729; extra == "dev-torch"
|
| 290 |
+
Requires-Dist: rhoknp<1.3.1,>=1.1.0; extra == "dev-torch"
|
| 291 |
+
Requires-Dist: scikit-learn; extra == "dev-torch"
|
| 292 |
+
Requires-Dist: onnxruntime>=1.4.0; extra == "dev-torch"
|
| 293 |
+
Requires-Dist: onnxruntime-tools>=1.4.2; extra == "dev-torch"
|
| 294 |
+
Requires-Dist: num2words; extra == "dev-torch"
|
| 295 |
+
Provides-Extra: flax
|
| 296 |
+
Requires-Dist: jax<=0.4.13,>=0.4.1; extra == "flax"
|
| 297 |
+
Requires-Dist: jaxlib<=0.4.13,>=0.4.1; extra == "flax"
|
| 298 |
+
Requires-Dist: flax<=0.7.0,>=0.4.1; extra == "flax"
|
| 299 |
+
Requires-Dist: optax<=0.1.4,>=0.0.8; extra == "flax"
|
| 300 |
+
Requires-Dist: scipy<1.13.0; extra == "flax"
|
| 301 |
+
Provides-Extra: flax-speech
|
| 302 |
+
Requires-Dist: librosa; extra == "flax-speech"
|
| 303 |
+
Requires-Dist: pyctcdecode>=0.4.0; extra == "flax-speech"
|
| 304 |
+
Requires-Dist: phonemizer; extra == "flax-speech"
|
| 305 |
+
Requires-Dist: kenlm; extra == "flax-speech"
|
| 306 |
+
Provides-Extra: ftfy
|
| 307 |
+
Requires-Dist: ftfy; extra == "ftfy"
|
| 308 |
+
Provides-Extra: hf_xet
|
| 309 |
+
Requires-Dist: hf-xet; extra == "hf-xet"
|
| 310 |
+
Provides-Extra: hub-kernels
|
| 311 |
+
Requires-Dist: kernels<=0.9,>=0.6.1; extra == "hub-kernels"
|
| 312 |
+
Provides-Extra: integrations
|
| 313 |
+
Requires-Dist: kernels<=0.9,>=0.6.1; extra == "integrations"
|
| 314 |
+
Requires-Dist: optuna; extra == "integrations"
|
| 315 |
+
Requires-Dist: ray[tune]>=2.7.0; extra == "integrations"
|
| 316 |
+
Requires-Dist: sigopt; extra == "integrations"
|
| 317 |
+
Provides-Extra: ja
|
| 318 |
+
Requires-Dist: fugashi>=1.0; extra == "ja"
|
| 319 |
+
Requires-Dist: ipadic<2.0,>=1.0.0; extra == "ja"
|
| 320 |
+
Requires-Dist: unidic-lite>=1.0.7; extra == "ja"
|
| 321 |
+
Requires-Dist: unidic>=1.0.2; extra == "ja"
|
| 322 |
+
Requires-Dist: sudachipy>=0.6.6; extra == "ja"
|
| 323 |
+
Requires-Dist: sudachidict-core>=20220729; extra == "ja"
|
| 324 |
+
Requires-Dist: rhoknp<1.3.1,>=1.1.0; extra == "ja"
|
| 325 |
+
Provides-Extra: mistral-common
|
| 326 |
+
Requires-Dist: mistral-common[opencv]>=1.6.3; extra == "mistral-common"
|
| 327 |
+
Provides-Extra: modelcreation
|
| 328 |
+
Requires-Dist: cookiecutter==1.7.3; extra == "modelcreation"
|
| 329 |
+
Provides-Extra: natten
|
| 330 |
+
Requires-Dist: natten<0.15.0,>=0.14.6; extra == "natten"
|
| 331 |
+
Provides-Extra: num2words
|
| 332 |
+
Requires-Dist: num2words; extra == "num2words"
|
| 333 |
+
Provides-Extra: onnx
|
| 334 |
+
Requires-Dist: onnxconverter-common; extra == "onnx"
|
| 335 |
+
Requires-Dist: tf2onnx; extra == "onnx"
|
| 336 |
+
Requires-Dist: onnxruntime>=1.4.0; extra == "onnx"
|
| 337 |
+
Requires-Dist: onnxruntime-tools>=1.4.2; extra == "onnx"
|
| 338 |
+
Provides-Extra: onnxruntime
|
| 339 |
+
Requires-Dist: onnxruntime>=1.4.0; extra == "onnxruntime"
|
| 340 |
+
Requires-Dist: onnxruntime-tools>=1.4.2; extra == "onnxruntime"
|
| 341 |
+
Provides-Extra: open-telemetry
|
| 342 |
+
Requires-Dist: opentelemetry-api; extra == "open-telemetry"
|
| 343 |
+
Requires-Dist: opentelemetry-exporter-otlp; extra == "open-telemetry"
|
| 344 |
+
Requires-Dist: opentelemetry-sdk; extra == "open-telemetry"
|
| 345 |
+
Provides-Extra: optuna
|
| 346 |
+
Requires-Dist: optuna; extra == "optuna"
|
| 347 |
+
Provides-Extra: quality
|
| 348 |
+
Requires-Dist: datasets>=2.15.0; extra == "quality"
|
| 349 |
+
Requires-Dist: ruff==0.11.2; extra == "quality"
|
| 350 |
+
Requires-Dist: GitPython<3.1.19; extra == "quality"
|
| 351 |
+
Requires-Dist: urllib3<2.0.0; extra == "quality"
|
| 352 |
+
Requires-Dist: libcst; extra == "quality"
|
| 353 |
+
Requires-Dist: rich; extra == "quality"
|
| 354 |
+
Requires-Dist: pandas<2.3.0; extra == "quality"
|
| 355 |
+
Provides-Extra: ray
|
| 356 |
+
Requires-Dist: ray[tune]>=2.7.0; extra == "ray"
|
| 357 |
+
Provides-Extra: retrieval
|
| 358 |
+
Requires-Dist: faiss-cpu; extra == "retrieval"
|
| 359 |
+
Requires-Dist: datasets>=2.15.0; extra == "retrieval"
|
| 360 |
+
Provides-Extra: ruff
|
| 361 |
+
Requires-Dist: ruff==0.11.2; extra == "ruff"
|
| 362 |
+
Provides-Extra: sagemaker
|
| 363 |
+
Requires-Dist: sagemaker>=2.31.0; extra == "sagemaker"
|
| 364 |
+
Provides-Extra: sentencepiece
|
| 365 |
+
Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "sentencepiece"
|
| 366 |
+
Requires-Dist: protobuf; extra == "sentencepiece"
|
| 367 |
+
Provides-Extra: serving
|
| 368 |
+
Requires-Dist: openai>=1.98.0; extra == "serving"
|
| 369 |
+
Requires-Dist: pydantic>=2; extra == "serving"
|
| 370 |
+
Requires-Dist: uvicorn; extra == "serving"
|
| 371 |
+
Requires-Dist: fastapi; extra == "serving"
|
| 372 |
+
Requires-Dist: starlette; extra == "serving"
|
| 373 |
+
Requires-Dist: torch>=2.2; extra == "serving"
|
| 374 |
+
Requires-Dist: accelerate>=0.26.0; extra == "serving"
|
| 375 |
+
Provides-Extra: sigopt
|
| 376 |
+
Requires-Dist: sigopt; extra == "sigopt"
|
| 377 |
+
Provides-Extra: sklearn
|
| 378 |
+
Requires-Dist: scikit-learn; extra == "sklearn"
|
| 379 |
+
Provides-Extra: speech
|
| 380 |
+
Requires-Dist: torchaudio; extra == "speech"
|
| 381 |
+
Requires-Dist: librosa; extra == "speech"
|
| 382 |
+
Requires-Dist: pyctcdecode>=0.4.0; extra == "speech"
|
| 383 |
+
Requires-Dist: phonemizer; extra == "speech"
|
| 384 |
+
Requires-Dist: kenlm; extra == "speech"
|
| 385 |
+
Provides-Extra: testing
|
| 386 |
+
Requires-Dist: pytest>=7.2.0; extra == "testing"
|
| 387 |
+
Requires-Dist: pytest-asyncio; extra == "testing"
|
| 388 |
+
Requires-Dist: pytest-rich; extra == "testing"
|
| 389 |
+
Requires-Dist: pytest-xdist; extra == "testing"
|
| 390 |
+
Requires-Dist: pytest-order; extra == "testing"
|
| 391 |
+
Requires-Dist: pytest-rerunfailures; extra == "testing"
|
| 392 |
+
Requires-Dist: timeout-decorator; extra == "testing"
|
| 393 |
+
Requires-Dist: parameterized>=0.9; extra == "testing"
|
| 394 |
+
Requires-Dist: psutil; extra == "testing"
|
| 395 |
+
Requires-Dist: datasets>=2.15.0; extra == "testing"
|
| 396 |
+
Requires-Dist: dill<0.3.5; extra == "testing"
|
| 397 |
+
Requires-Dist: evaluate>=0.2.0; extra == "testing"
|
| 398 |
+
Requires-Dist: pytest-timeout; extra == "testing"
|
| 399 |
+
Requires-Dist: ruff==0.11.2; extra == "testing"
|
| 400 |
+
Requires-Dist: rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1; extra == "testing"
|
| 401 |
+
Requires-Dist: nltk<=3.8.1; extra == "testing"
|
| 402 |
+
Requires-Dist: GitPython<3.1.19; extra == "testing"
|
| 403 |
+
Requires-Dist: sacremoses; extra == "testing"
|
| 404 |
+
Requires-Dist: rjieba; extra == "testing"
|
| 405 |
+
Requires-Dist: beautifulsoup4; extra == "testing"
|
| 406 |
+
Requires-Dist: tensorboard; extra == "testing"
|
| 407 |
+
Requires-Dist: pydantic>=2; extra == "testing"
|
| 408 |
+
Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "testing"
|
| 409 |
+
Requires-Dist: sacrebleu<2.0.0,>=1.4.12; extra == "testing"
|
| 410 |
+
Requires-Dist: libcst; extra == "testing"
|
| 411 |
+
Requires-Dist: faiss-cpu; extra == "testing"
|
| 412 |
+
Requires-Dist: cookiecutter==1.7.3; extra == "testing"
|
| 413 |
+
Requires-Dist: mistral-common[opencv]>=1.6.3; extra == "testing"
|
| 414 |
+
Provides-Extra: tf
|
| 415 |
+
Requires-Dist: tensorflow<2.16,>2.9; extra == "tf"
|
| 416 |
+
Requires-Dist: onnxconverter-common; extra == "tf"
|
| 417 |
+
Requires-Dist: tf2onnx; extra == "tf"
|
| 418 |
+
Requires-Dist: tensorflow-text<2.16; extra == "tf"
|
| 419 |
+
Requires-Dist: keras-nlp<0.14.0,>=0.3.1; extra == "tf"
|
| 420 |
+
Provides-Extra: tf-cpu
|
| 421 |
+
Requires-Dist: keras<2.16,>2.9; extra == "tf-cpu"
|
| 422 |
+
Requires-Dist: tensorflow-cpu<2.16,>2.9; extra == "tf-cpu"
|
| 423 |
+
Requires-Dist: onnxconverter-common; extra == "tf-cpu"
|
| 424 |
+
Requires-Dist: tf2onnx; extra == "tf-cpu"
|
| 425 |
+
Requires-Dist: tensorflow-text<2.16; extra == "tf-cpu"
|
| 426 |
+
Requires-Dist: keras-nlp<0.14.0,>=0.3.1; extra == "tf-cpu"
|
| 427 |
+
Requires-Dist: tensorflow-probability<0.24; extra == "tf-cpu"
|
| 428 |
+
Provides-Extra: tf-speech
|
| 429 |
+
Requires-Dist: librosa; extra == "tf-speech"
|
| 430 |
+
Requires-Dist: pyctcdecode>=0.4.0; extra == "tf-speech"
|
| 431 |
+
Requires-Dist: phonemizer; extra == "tf-speech"
|
| 432 |
+
Requires-Dist: kenlm; extra == "tf-speech"
|
| 433 |
+
Provides-Extra: tiktoken
|
| 434 |
+
Requires-Dist: tiktoken; extra == "tiktoken"
|
| 435 |
+
Requires-Dist: blobfile; extra == "tiktoken"
|
| 436 |
+
Provides-Extra: timm
|
| 437 |
+
Requires-Dist: timm!=1.0.18,<=1.0.19; extra == "timm"
|
| 438 |
+
Provides-Extra: tokenizers
|
| 439 |
+
Requires-Dist: tokenizers<=0.23.0,>=0.22.0; extra == "tokenizers"
|
| 440 |
+
Provides-Extra: torch
|
| 441 |
+
Requires-Dist: torch>=2.2; extra == "torch"
|
| 442 |
+
Requires-Dist: accelerate>=0.26.0; extra == "torch"
|
| 443 |
+
Provides-Extra: torch-speech
|
| 444 |
+
Requires-Dist: torchaudio; extra == "torch-speech"
|
| 445 |
+
Requires-Dist: librosa; extra == "torch-speech"
|
| 446 |
+
Requires-Dist: pyctcdecode>=0.4.0; extra == "torch-speech"
|
| 447 |
+
Requires-Dist: phonemizer; extra == "torch-speech"
|
| 448 |
+
Requires-Dist: kenlm; extra == "torch-speech"
|
| 449 |
+
Provides-Extra: torch-vision
|
| 450 |
+
Requires-Dist: torchvision; extra == "torch-vision"
|
| 451 |
+
Requires-Dist: Pillow<=15.0,>=10.0.1; extra == "torch-vision"
|
| 452 |
+
Provides-Extra: torchhub
|
| 453 |
+
Requires-Dist: filelock; extra == "torchhub"
|
| 454 |
+
Requires-Dist: huggingface-hub<1.0,>=0.34.0; extra == "torchhub"
|
| 455 |
+
Requires-Dist: importlib-metadata; extra == "torchhub"
|
| 456 |
+
Requires-Dist: numpy>=1.17; extra == "torchhub"
|
| 457 |
+
Requires-Dist: packaging>=20.0; extra == "torchhub"
|
| 458 |
+
Requires-Dist: protobuf; extra == "torchhub"
|
| 459 |
+
Requires-Dist: regex!=2019.12.17; extra == "torchhub"
|
| 460 |
+
Requires-Dist: requests; extra == "torchhub"
|
| 461 |
+
Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "torchhub"
|
| 462 |
+
Requires-Dist: torch>=2.2; extra == "torchhub"
|
| 463 |
+
Requires-Dist: tokenizers<=0.23.0,>=0.22.0; extra == "torchhub"
|
| 464 |
+
Requires-Dist: tqdm>=4.27; extra == "torchhub"
|
| 465 |
+
Provides-Extra: video
|
| 466 |
+
Requires-Dist: av; extra == "video"
|
| 467 |
+
Provides-Extra: vision
|
| 468 |
+
Requires-Dist: Pillow<=15.0,>=10.0.1; extra == "vision"
|
| 469 |
+
|
| 470 |
+
<!---
|
| 471 |
+
Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 472 |
+
|
| 473 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 474 |
+
you may not use this file except in compliance with the License.
|
| 475 |
+
You may obtain a copy of the License at
|
| 476 |
+
|
| 477 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 478 |
+
|
| 479 |
+
Unless required by applicable law or agreed to in writing, software
|
| 480 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 481 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 482 |
+
See the License for the specific language governing permissions and
|
| 483 |
+
limitations under the License.
|
| 484 |
+
-->
|
| 485 |
+
|
| 486 |
+
<p align="center">
|
| 487 |
+
<picture>
|
| 488 |
+
<source media="(prefers-color-scheme: dark)" srcset="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/transformers-logo-dark.svg">
|
| 489 |
+
<source media="(prefers-color-scheme: light)" srcset="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/transformers-logo-light.svg">
|
| 490 |
+
<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%;">
|
| 491 |
+
</picture>
|
| 492 |
+
<br/>
|
| 493 |
+
<br/>
|
| 494 |
+
</p>
|
| 495 |
+
|
| 496 |
+
<p align="center">
|
| 497 |
+
<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>
|
| 498 |
+
<a href="https://circleci.com/gh/huggingface/transformers"><img alt="Build" src="https://img.shields.io/circleci/build/github/huggingface/transformers/main"></a>
|
| 499 |
+
<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>
|
| 500 |
+
<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>
|
| 501 |
+
<a href="https://github.com/huggingface/transformers/releases"><img alt="GitHub release" src="https://img.shields.io/github/release/huggingface/transformers.svg"></a>
|
| 502 |
+
<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>
|
| 503 |
+
<a href="https://zenodo.org/badge/latestdoi/155220641"><img src="https://zenodo.org/badge/155220641.svg" alt="DOI"></a>
|
| 504 |
+
</p>
|
| 505 |
+
|
| 506 |
+
<h4 align="center">
|
| 507 |
+
<p>
|
| 508 |
+
<b>English</b> |
|
| 509 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_zh-hans.md">简体中文</a> |
|
| 510 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_zh-hant.md">繁體中文</a> |
|
| 511 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_ko.md">한국어</a> |
|
| 512 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_es.md">Español</a> |
|
| 513 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_ja.md">日本語</a> |
|
| 514 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_hd.md">हिन्दी</a> |
|
| 515 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_ru.md">Русский</a> |
|
| 516 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_pt-br.md">Português</a> |
|
| 517 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_te.md">తెలుగు</a> |
|
| 518 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_fr.md">Français</a> |
|
| 519 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_de.md">Deutsch</a> |
|
| 520 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_vi.md">Tiếng Việt</a> |
|
| 521 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_ar.md">العربية</a> |
|
| 522 |
+
<a href="https://github.com/huggingface/transformers/blob/main/i18n/README_ur.md">اردو</a> |
|
| 523 |
+
</p>
|
| 524 |
+
</h4>
|
| 525 |
+
|
| 526 |
+
<h3 align="center">
|
| 527 |
+
<p>State-of-the-art pretrained models for inference and training</p>
|
| 528 |
+
</h3>
|
| 529 |
+
|
| 530 |
+
<h3 align="center">
|
| 531 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/transformers_as_a_model_definition.png"/>
|
| 532 |
+
</h3>
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
Transformers acts as the model-definition framework for state-of-the-art machine learning models in text, computer
|
| 536 |
+
vision, audio, video, and multimodal model, for both inference and training.
|
| 537 |
+
|
| 538 |
+
It centralizes the model definition so that this definition is agreed upon across the ecosystem. `transformers` is the
|
| 539 |
+
pivot across frameworks: if a model definition is supported, it will be compatible with the majority of training
|
| 540 |
+
frameworks (Axolotl, Unsloth, DeepSpeed, FSDP, PyTorch-Lightning, ...), inference engines (vLLM, SGLang, TGI, ...),
|
| 541 |
+
and adjacent modeling libraries (llama.cpp, mlx, ...) which leverage the model definition from `transformers`.
|
| 542 |
+
|
| 543 |
+
We pledge to help support new state-of-the-art models and democratize their usage by having their model definition be
|
| 544 |
+
simple, customizable, and efficient.
|
| 545 |
+
|
| 546 |
+
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.
|
| 547 |
+
|
| 548 |
+
Explore the [Hub](https://huggingface.com/) today to find a model and use Transformers to help you get started right away.
|
| 549 |
+
|
| 550 |
+
## Installation
|
| 551 |
+
|
| 552 |
+
Transformers works with Python 3.9+ [PyTorch](https://pytorch.org/get-started/locally/) 2.1+, [TensorFlow](https://www.tensorflow.org/install/pip) 2.6+, and [Flax](https://flax.readthedocs.io/en/latest/) 0.4.1+.
|
| 553 |
+
|
| 554 |
+
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.
|
| 555 |
+
|
| 556 |
+
```py
|
| 557 |
+
# venv
|
| 558 |
+
python -m venv .my-env
|
| 559 |
+
source .my-env/bin/activate
|
| 560 |
+
# uv
|
| 561 |
+
uv venv .my-env
|
| 562 |
+
source .my-env/bin/activate
|
| 563 |
+
```
|
| 564 |
+
|
| 565 |
+
Install Transformers in your virtual environment.
|
| 566 |
+
|
| 567 |
+
```py
|
| 568 |
+
# pip
|
| 569 |
+
pip install "transformers[torch]"
|
| 570 |
+
|
| 571 |
+
# uv
|
| 572 |
+
uv pip install "transformers[torch]"
|
| 573 |
+
```
|
| 574 |
+
|
| 575 |
+
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.
|
| 576 |
+
|
| 577 |
+
```shell
|
| 578 |
+
git clone https://github.com/huggingface/transformers.git
|
| 579 |
+
cd transformers
|
| 580 |
+
|
| 581 |
+
# pip
|
| 582 |
+
pip install .[torch]
|
| 583 |
+
|
| 584 |
+
# uv
|
| 585 |
+
uv pip install .[torch]
|
| 586 |
+
```
|
| 587 |
+
|
| 588 |
+
## Quickstart
|
| 589 |
+
|
| 590 |
+
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.
|
| 591 |
+
|
| 592 |
+
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.
|
| 593 |
+
|
| 594 |
+
```py
|
| 595 |
+
from transformers import pipeline
|
| 596 |
+
|
| 597 |
+
pipeline = pipeline(task="text-generation", model="Qwen/Qwen2.5-1.5B")
|
| 598 |
+
pipeline("the secret to baking a really good cake is ")
|
| 599 |
+
[{'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.'}]
|
| 600 |
+
```
|
| 601 |
+
|
| 602 |
+
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.
|
| 603 |
+
|
| 604 |
+
> [!TIP]
|
| 605 |
+
> You can also chat with a model directly from the command line.
|
| 606 |
+
> ```shell
|
| 607 |
+
> transformers chat Qwen/Qwen2.5-0.5B-Instruct
|
| 608 |
+
> ```
|
| 609 |
+
|
| 610 |
+
```py
|
| 611 |
+
import torch
|
| 612 |
+
from transformers import pipeline
|
| 613 |
+
|
| 614 |
+
chat = [
|
| 615 |
+
{"role": "system", "content": "You are a sassy, wise-cracking robot as imagined by Hollywood circa 1986."},
|
| 616 |
+
{"role": "user", "content": "Hey, can you tell me any fun things to do in New York?"}
|
| 617 |
+
]
|
| 618 |
+
|
| 619 |
+
pipeline = pipeline(task="text-generation", model="meta-llama/Meta-Llama-3-8B-Instruct", dtype=torch.bfloat16, device_map="auto")
|
| 620 |
+
response = pipeline(chat, max_new_tokens=512)
|
| 621 |
+
print(response[0]["generated_text"][-1]["content"])
|
| 622 |
+
```
|
| 623 |
+
|
| 624 |
+
Expand the examples below to see how `Pipeline` works for different modalities and tasks.
|
| 625 |
+
|
| 626 |
+
<details>
|
| 627 |
+
<summary>Automatic speech recognition</summary>
|
| 628 |
+
|
| 629 |
+
```py
|
| 630 |
+
from transformers import pipeline
|
| 631 |
+
|
| 632 |
+
pipeline = pipeline(task="automatic-speech-recognition", model="openai/whisper-large-v3")
|
| 633 |
+
pipeline("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
|
| 634 |
+
{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.'}
|
| 635 |
+
```
|
| 636 |
+
|
| 637 |
+
</details>
|
| 638 |
+
|
| 639 |
+
<details>
|
| 640 |
+
<summary>Image classification</summary>
|
| 641 |
+
|
| 642 |
+
<h3 align="center">
|
| 643 |
+
<a><img src="https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png"></a>
|
| 644 |
+
</h3>
|
| 645 |
+
|
| 646 |
+
```py
|
| 647 |
+
from transformers import pipeline
|
| 648 |
+
|
| 649 |
+
pipeline = pipeline(task="image-classification", model="facebook/dinov2-small-imagenet1k-1-layer")
|
| 650 |
+
pipeline("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
|
| 651 |
+
[{'label': 'macaw', 'score': 0.997848391532898},
|
| 652 |
+
{'label': 'sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita',
|
| 653 |
+
'score': 0.0016551691805943847},
|
| 654 |
+
{'label': 'lorikeet', 'score': 0.00018523589824326336},
|
| 655 |
+
{'label': 'African grey, African gray, Psittacus erithacus',
|
| 656 |
+
'score': 7.85409429227002e-05},
|
| 657 |
+
{'label': 'quail', 'score': 5.502637941390276e-05}]
|
| 658 |
+
```
|
| 659 |
+
|
| 660 |
+
</details>
|
| 661 |
+
|
| 662 |
+
<details>
|
| 663 |
+
<summary>Visual question answering</summary>
|
| 664 |
+
|
| 665 |
+
|
| 666 |
+
<h3 align="center">
|
| 667 |
+
<a><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/idefics-few-shot.jpg"></a>
|
| 668 |
+
</h3>
|
| 669 |
+
|
| 670 |
+
```py
|
| 671 |
+
from transformers import pipeline
|
| 672 |
+
|
| 673 |
+
pipeline = pipeline(task="visual-question-answering", model="Salesforce/blip-vqa-base")
|
| 674 |
+
pipeline(
|
| 675 |
+
image="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/idefics-few-shot.jpg",
|
| 676 |
+
question="What is in the image?",
|
| 677 |
+
)
|
| 678 |
+
[{'answer': 'statue of liberty'}]
|
| 679 |
+
```
|
| 680 |
+
|
| 681 |
+
</details>
|
| 682 |
+
|
| 683 |
+
## Why should I use Transformers?
|
| 684 |
+
|
| 685 |
+
1. Easy-to-use state-of-the-art models:
|
| 686 |
+
- High performance on natural language understanding & generation, computer vision, audio, video, and multimodal tasks.
|
| 687 |
+
- Low barrier to entry for researchers, engineers, and developers.
|
| 688 |
+
- Few user-facing abstractions with just three classes to learn.
|
| 689 |
+
- A unified API for using all our pretrained models.
|
| 690 |
+
|
| 691 |
+
1. Lower compute costs, smaller carbon footprint:
|
| 692 |
+
- Share trained models instead of training from scratch.
|
| 693 |
+
- Reduce compute time and production costs.
|
| 694 |
+
- Dozens of model architectures with 1M+ pretrained checkpoints across all modalities.
|
| 695 |
+
|
| 696 |
+
1. Choose the right framework for every part of a models lifetime:
|
| 697 |
+
- Train state-of-the-art models in 3 lines of code.
|
| 698 |
+
- Move a single model between PyTorch/JAX/TF2.0 frameworks at will.
|
| 699 |
+
- Pick the right framework for training, evaluation, and production.
|
| 700 |
+
|
| 701 |
+
1. Easily customize a model or an example to your needs:
|
| 702 |
+
- We provide examples for each architecture to reproduce the results published by its original authors.
|
| 703 |
+
- Model internals are exposed as consistently as possible.
|
| 704 |
+
- Model files can be used independently of the library for quick experiments.
|
| 705 |
+
|
| 706 |
+
<a target="_blank" href="https://huggingface.co/enterprise">
|
| 707 |
+
<img alt="Hugging Face Enterprise Hub" src="https://github.com/user-attachments/assets/247fb16d-d251-4583-96c4-d3d76dda4925">
|
| 708 |
+
</a><br>
|
| 709 |
+
|
| 710 |
+
## Why shouldn't I use Transformers?
|
| 711 |
+
|
| 712 |
+
- 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.
|
| 713 |
+
- 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).
|
| 714 |
+
- 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.
|
| 715 |
+
|
| 716 |
+
## 100 projects using Transformers
|
| 717 |
+
|
| 718 |
+
Transformers is more than a toolkit to use pretrained models, it's a community of projects built around it and the
|
| 719 |
+
Hugging Face Hub. We want Transformers to enable developers, researchers, students, professors, engineers, and anyone
|
| 720 |
+
else to build their dream projects.
|
| 721 |
+
|
| 722 |
+
In order to celebrate Transformers 100,000 stars, we wanted to put the spotlight on the
|
| 723 |
+
community with the [awesome-transformers](./awesome-transformers.md) page which lists 100
|
| 724 |
+
incredible projects built with Transformers.
|
| 725 |
+
|
| 726 |
+
If you own or use a project that you believe should be part of the list, please open a PR to add it!
|
| 727 |
+
|
| 728 |
+
## Example models
|
| 729 |
+
|
| 730 |
+
You can test most of our models directly on their [Hub model pages](https://huggingface.co/models).
|
| 731 |
+
|
| 732 |
+
Expand each modality below to see a few example models for various use cases.
|
| 733 |
+
|
| 734 |
+
<details>
|
| 735 |
+
<summary>Audio</summary>
|
| 736 |
+
|
| 737 |
+
- Audio classification with [Whisper](https://huggingface.co/openai/whisper-large-v3-turbo)
|
| 738 |
+
- Automatic speech recognition with [Moonshine](https://huggingface.co/UsefulSensors/moonshine)
|
| 739 |
+
- Keyword spotting with [Wav2Vec2](https://huggingface.co/superb/wav2vec2-base-superb-ks)
|
| 740 |
+
- Speech to speech generation with [Moshi](https://huggingface.co/kyutai/moshiko-pytorch-bf16)
|
| 741 |
+
- Text to audio with [MusicGen](https://huggingface.co/facebook/musicgen-large)
|
| 742 |
+
- Text to speech with [Bark](https://huggingface.co/suno/bark)
|
| 743 |
+
|
| 744 |
+
</details>
|
| 745 |
+
|
| 746 |
+
<details>
|
| 747 |
+
<summary>Computer vision</summary>
|
| 748 |
+
|
| 749 |
+
- Automatic mask generation with [SAM](https://huggingface.co/facebook/sam-vit-base)
|
| 750 |
+
- Depth estimation with [DepthPro](https://huggingface.co/apple/DepthPro-hf)
|
| 751 |
+
- Image classification with [DINO v2](https://huggingface.co/facebook/dinov2-base)
|
| 752 |
+
- Keypoint detection with [SuperPoint](https://huggingface.co/magic-leap-community/superpoint)
|
| 753 |
+
- Keypoint matching with [SuperGlue](https://huggingface.co/magic-leap-community/superglue_outdoor)
|
| 754 |
+
- Object detection with [RT-DETRv2](https://huggingface.co/PekingU/rtdetr_v2_r50vd)
|
| 755 |
+
- Pose Estimation with [VitPose](https://huggingface.co/usyd-community/vitpose-base-simple)
|
| 756 |
+
- Universal segmentation with [OneFormer](https://huggingface.co/shi-labs/oneformer_ade20k_swin_large)
|
| 757 |
+
- Video classification with [VideoMAE](https://huggingface.co/MCG-NJU/videomae-large)
|
| 758 |
+
|
| 759 |
+
</details>
|
| 760 |
+
|
| 761 |
+
<details>
|
| 762 |
+
<summary>Multimodal</summary>
|
| 763 |
+
|
| 764 |
+
- Audio or text to text with [Qwen2-Audio](https://huggingface.co/Qwen/Qwen2-Audio-7B)
|
| 765 |
+
- Document question answering with [LayoutLMv3](https://huggingface.co/microsoft/layoutlmv3-base)
|
| 766 |
+
- Image or text to text with [Qwen-VL](https://huggingface.co/Qwen/Qwen2.5-VL-3B-Instruct)
|
| 767 |
+
- Image captioning [BLIP-2](https://huggingface.co/Salesforce/blip2-opt-2.7b)
|
| 768 |
+
- OCR-based document understanding with [GOT-OCR2](https://huggingface.co/stepfun-ai/GOT-OCR-2.0-hf)
|
| 769 |
+
- Table question answering with [TAPAS](https://huggingface.co/google/tapas-base)
|
| 770 |
+
- Unified multimodal understanding and generation with [Emu3](https://huggingface.co/BAAI/Emu3-Gen)
|
| 771 |
+
- Vision to text with [Llava-OneVision](https://huggingface.co/llava-hf/llava-onevision-qwen2-0.5b-ov-hf)
|
| 772 |
+
- Visual question answering with [Llava](https://huggingface.co/llava-hf/llava-1.5-7b-hf)
|
| 773 |
+
- Visual referring expression segmentation with [Kosmos-2](https://huggingface.co/microsoft/kosmos-2-patch14-224)
|
| 774 |
+
|
| 775 |
+
</details>
|
| 776 |
+
|
| 777 |
+
<details>
|
| 778 |
+
<summary>NLP</summary>
|
| 779 |
+
|
| 780 |
+
- Masked word completion with [ModernBERT](https://huggingface.co/answerdotai/ModernBERT-base)
|
| 781 |
+
- Named entity recognition with [Gemma](https://huggingface.co/google/gemma-2-2b)
|
| 782 |
+
- Question answering with [Mixtral](https://huggingface.co/mistralai/Mixtral-8x7B-v0.1)
|
| 783 |
+
- Summarization with [BART](https://huggingface.co/facebook/bart-large-cnn)
|
| 784 |
+
- Translation with [T5](https://huggingface.co/google-t5/t5-base)
|
| 785 |
+
- Text generation with [Llama](https://huggingface.co/meta-llama/Llama-3.2-1B)
|
| 786 |
+
- Text classification with [Qwen](https://huggingface.co/Qwen/Qwen2.5-0.5B)
|
| 787 |
+
|
| 788 |
+
</details>
|
| 789 |
+
|
| 790 |
+
## Citation
|
| 791 |
+
|
| 792 |
+
We now have a [paper](https://www.aclweb.org/anthology/2020.emnlp-demos.6/) you can cite for the 🤗 Transformers library:
|
| 793 |
+
```bibtex
|
| 794 |
+
@inproceedings{wolf-etal-2020-transformers,
|
| 795 |
+
title = "Transformers: State-of-the-Art Natural Language Processing",
|
| 796 |
+
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",
|
| 797 |
+
booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: System Demonstrations",
|
| 798 |
+
month = oct,
|
| 799 |
+
year = "2020",
|
| 800 |
+
address = "Online",
|
| 801 |
+
publisher = "Association for Computational Linguistics",
|
| 802 |
+
url = "https://www.aclweb.org/anthology/2020.emnlp-demos.6",
|
| 803 |
+
pages = "38--45"
|
| 804 |
+
}
|
| 805 |
+
```
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers-4.56.2.dist-info/RECORD
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers-4.56.2.dist-info/REQUESTED
ADDED
|
File without changes
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers-4.56.2.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: bdist_wheel (0.45.1)
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
| 5 |
+
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers-4.56.2.dist-info/entry_points.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[console_scripts]
|
| 2 |
+
transformers = transformers.commands.transformers_cli:main
|
| 3 |
+
transformers-cli = transformers.commands.transformers_cli:main_cli
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers-4.56.2.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
transformers
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/siglip/image_processing_siglip.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Image processor class for SigLIP."""
|
| 16 |
+
|
| 17 |
+
from typing import Optional, Union
|
| 18 |
+
|
| 19 |
+
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
|
| 20 |
+
from ...image_transforms import (
|
| 21 |
+
convert_to_rgb,
|
| 22 |
+
resize,
|
| 23 |
+
to_channel_dimension_format,
|
| 24 |
+
)
|
| 25 |
+
from ...image_utils import (
|
| 26 |
+
IMAGENET_STANDARD_MEAN,
|
| 27 |
+
IMAGENET_STANDARD_STD,
|
| 28 |
+
ChannelDimension,
|
| 29 |
+
ImageInput,
|
| 30 |
+
PILImageResampling,
|
| 31 |
+
infer_channel_dimension_format,
|
| 32 |
+
is_scaled_image,
|
| 33 |
+
make_flat_list_of_images,
|
| 34 |
+
to_numpy_array,
|
| 35 |
+
valid_images,
|
| 36 |
+
validate_preprocess_arguments,
|
| 37 |
+
)
|
| 38 |
+
from ...utils import TensorType, filter_out_non_signature_kwargs, is_vision_available, logging
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
logger = logging.get_logger(__name__)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
if is_vision_available():
|
| 45 |
+
import PIL
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class SiglipImageProcessor(BaseImageProcessor):
|
| 49 |
+
r"""
|
| 50 |
+
Constructs a SigLIP image processor.
|
| 51 |
+
|
| 52 |
+
Args:
|
| 53 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
| 54 |
+
Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by
|
| 55 |
+
`do_resize` in the `preprocess` method.
|
| 56 |
+
size (`dict[str, int]` *optional*, defaults to `{"height": 224, "width": 224}`):
|
| 57 |
+
Size of the image after resizing. Can be overridden by `size` in the `preprocess` method.
|
| 58 |
+
resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
|
| 59 |
+
Resampling filter to use if resizing the image. Can be overridden by `resample` in the `preprocess` method.
|
| 60 |
+
do_rescale (`bool`, *optional*, defaults to `True`):
|
| 61 |
+
Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in
|
| 62 |
+
the `preprocess` method.
|
| 63 |
+
rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
|
| 64 |
+
Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in the `preprocess`
|
| 65 |
+
method.
|
| 66 |
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
| 67 |
+
Whether to normalize the image by the specified mean and standard deviation. Can be overridden by
|
| 68 |
+
`do_normalize` in the `preprocess` method.
|
| 69 |
+
image_mean (`float` or `list[float]`, *optional*, defaults to `[0.5, 0.5, 0.5]`):
|
| 70 |
+
Mean to use if normalizing the image. This is a float or list of floats the length of the number of
|
| 71 |
+
channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
|
| 72 |
+
image_std (`float` or `list[float]`, *optional*, defaults to `[0.5, 0.5, 0.5]`):
|
| 73 |
+
Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
|
| 74 |
+
number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
|
| 75 |
+
Can be overridden by the `image_std` parameter in the `preprocess` method.
|
| 76 |
+
do_convert_rgb (`bool`, *optional*, defaults to `True`):
|
| 77 |
+
Whether to convert the image to RGB.
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
model_input_names = ["pixel_values"]
|
| 81 |
+
|
| 82 |
+
def __init__(
|
| 83 |
+
self,
|
| 84 |
+
do_resize: bool = True,
|
| 85 |
+
size: Optional[dict[str, int]] = None,
|
| 86 |
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
| 87 |
+
do_rescale: bool = True,
|
| 88 |
+
rescale_factor: Union[int, float] = 1 / 255,
|
| 89 |
+
do_normalize: bool = True,
|
| 90 |
+
image_mean: Optional[Union[float, list[float]]] = None,
|
| 91 |
+
image_std: Optional[Union[float, list[float]]] = None,
|
| 92 |
+
do_convert_rgb: Optional[bool] = None,
|
| 93 |
+
**kwargs,
|
| 94 |
+
) -> None:
|
| 95 |
+
super().__init__(**kwargs)
|
| 96 |
+
size = size if size is not None else {"height": 224, "width": 224}
|
| 97 |
+
image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
|
| 98 |
+
image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
|
| 99 |
+
|
| 100 |
+
self.do_resize = do_resize
|
| 101 |
+
self.size = size
|
| 102 |
+
self.resample = resample
|
| 103 |
+
self.do_rescale = do_rescale
|
| 104 |
+
self.rescale_factor = rescale_factor
|
| 105 |
+
self.do_normalize = do_normalize
|
| 106 |
+
self.image_mean = image_mean
|
| 107 |
+
self.image_std = image_std
|
| 108 |
+
self.do_convert_rgb = do_convert_rgb
|
| 109 |
+
|
| 110 |
+
@filter_out_non_signature_kwargs()
|
| 111 |
+
def preprocess(
|
| 112 |
+
self,
|
| 113 |
+
images: ImageInput,
|
| 114 |
+
do_resize: Optional[bool] = None,
|
| 115 |
+
size: Optional[dict[str, int]] = None,
|
| 116 |
+
resample: PILImageResampling = None,
|
| 117 |
+
do_rescale: Optional[bool] = None,
|
| 118 |
+
rescale_factor: Optional[float] = None,
|
| 119 |
+
do_normalize: Optional[bool] = None,
|
| 120 |
+
image_mean: Optional[Union[float, list[float]]] = None,
|
| 121 |
+
image_std: Optional[Union[float, list[float]]] = None,
|
| 122 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 123 |
+
data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
|
| 124 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 125 |
+
do_convert_rgb: Optional[bool] = None,
|
| 126 |
+
) -> PIL.Image.Image:
|
| 127 |
+
"""
|
| 128 |
+
Preprocess an image or batch of images.
|
| 129 |
+
|
| 130 |
+
Args:
|
| 131 |
+
images (`ImageInput`):
|
| 132 |
+
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
|
| 133 |
+
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
| 134 |
+
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
|
| 135 |
+
Whether to resize the image.
|
| 136 |
+
size (`dict[str, int]`, *optional*, defaults to `self.size`):
|
| 137 |
+
Size of the image after resizing.
|
| 138 |
+
resample (`int`, *optional*, defaults to `self.resample`):
|
| 139 |
+
Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
|
| 140 |
+
has an effect if `do_resize` is set to `True`.
|
| 141 |
+
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
|
| 142 |
+
Whether to rescale the image.
|
| 143 |
+
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
|
| 144 |
+
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
|
| 145 |
+
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
|
| 146 |
+
Whether to normalize the image.
|
| 147 |
+
image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
|
| 148 |
+
Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
|
| 149 |
+
image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
|
| 150 |
+
Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
|
| 151 |
+
`True`.
|
| 152 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
| 153 |
+
The type of tensors to return. Can be one of:
|
| 154 |
+
- Unset: Return a list of `np.ndarray`.
|
| 155 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
| 156 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
| 157 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
| 158 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
| 159 |
+
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
|
| 160 |
+
The channel dimension format for the output image. Can be one of:
|
| 161 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 162 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 163 |
+
- Unset: Use the channel dimension format of the input image.
|
| 164 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 165 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
| 166 |
+
from the input image. Can be one of:
|
| 167 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 168 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 169 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 170 |
+
do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
|
| 171 |
+
Whether to convert the image to RGB.
|
| 172 |
+
"""
|
| 173 |
+
do_resize = do_resize if do_resize is not None else self.do_resize
|
| 174 |
+
size = size if size is not None else self.size
|
| 175 |
+
size = get_size_dict(size, param_name="size", default_to_square=False)
|
| 176 |
+
resample = resample if resample is not None else self.resample
|
| 177 |
+
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
|
| 178 |
+
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
|
| 179 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
| 180 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
| 181 |
+
image_std = image_std if image_std is not None else self.image_std
|
| 182 |
+
do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
|
| 183 |
+
|
| 184 |
+
images = self.fetch_images(images)
|
| 185 |
+
images = make_flat_list_of_images(images)
|
| 186 |
+
|
| 187 |
+
if not valid_images(images):
|
| 188 |
+
raise ValueError(
|
| 189 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
| 190 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
| 191 |
+
)
|
| 192 |
+
validate_preprocess_arguments(
|
| 193 |
+
do_rescale=do_rescale,
|
| 194 |
+
rescale_factor=rescale_factor,
|
| 195 |
+
do_normalize=do_normalize,
|
| 196 |
+
image_mean=image_mean,
|
| 197 |
+
image_std=image_std,
|
| 198 |
+
do_resize=do_resize,
|
| 199 |
+
size=size,
|
| 200 |
+
resample=resample,
|
| 201 |
+
)
|
| 202 |
+
if do_convert_rgb:
|
| 203 |
+
images = [convert_to_rgb(image) for image in images]
|
| 204 |
+
|
| 205 |
+
# All transformations expect numpy arrays.
|
| 206 |
+
images = [to_numpy_array(image) for image in images]
|
| 207 |
+
|
| 208 |
+
if do_rescale and is_scaled_image(images[0]):
|
| 209 |
+
logger.warning_once(
|
| 210 |
+
"It looks like you are trying to rescale already rescaled images. If the input"
|
| 211 |
+
" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
if input_data_format is None:
|
| 215 |
+
# We assume that all images have the same channel dimension format.
|
| 216 |
+
input_data_format = infer_channel_dimension_format(images[0])
|
| 217 |
+
|
| 218 |
+
if do_resize:
|
| 219 |
+
height, width = size["height"], size["width"]
|
| 220 |
+
images = [
|
| 221 |
+
resize(image=image, size=(height, width), resample=resample, input_data_format=input_data_format)
|
| 222 |
+
for image in images
|
| 223 |
+
]
|
| 224 |
+
|
| 225 |
+
if do_rescale:
|
| 226 |
+
images = [
|
| 227 |
+
self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
|
| 228 |
+
for image in images
|
| 229 |
+
]
|
| 230 |
+
|
| 231 |
+
if do_normalize:
|
| 232 |
+
images = [
|
| 233 |
+
self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
|
| 234 |
+
for image in images
|
| 235 |
+
]
|
| 236 |
+
|
| 237 |
+
images = [
|
| 238 |
+
to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
|
| 239 |
+
]
|
| 240 |
+
|
| 241 |
+
data = {"pixel_values": images}
|
| 242 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
__all__ = ["SiglipImageProcessor"]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/siglip/image_processing_siglip_fast.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Fast Image processor class for SigLIP."""
|
| 16 |
+
|
| 17 |
+
from ...image_processing_utils_fast import BaseImageProcessorFast
|
| 18 |
+
from ...image_utils import (
|
| 19 |
+
IMAGENET_STANDARD_MEAN,
|
| 20 |
+
IMAGENET_STANDARD_STD,
|
| 21 |
+
PILImageResampling,
|
| 22 |
+
)
|
| 23 |
+
from ...utils import auto_docstring
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@auto_docstring
|
| 27 |
+
class SiglipImageProcessorFast(BaseImageProcessorFast):
|
| 28 |
+
resample = PILImageResampling.BICUBIC
|
| 29 |
+
image_mean = IMAGENET_STANDARD_MEAN
|
| 30 |
+
image_std = IMAGENET_STANDARD_STD
|
| 31 |
+
size = {"height": 224, "width": 224}
|
| 32 |
+
default_to_square = False
|
| 33 |
+
do_resize = True
|
| 34 |
+
do_rescale = True
|
| 35 |
+
do_normalize = True
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
__all__ = ["SiglipImageProcessorFast"]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/siglip/modeling_siglip.py
ADDED
|
@@ -0,0 +1,1222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 Google AI and The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch Siglip model."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
import warnings
|
| 19 |
+
from dataclasses import dataclass
|
| 20 |
+
from typing import Any, Callable, Optional, Union
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
import torch
|
| 24 |
+
from torch import nn
|
| 25 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 26 |
+
from torch.nn.init import _calculate_fan_in_and_fan_out
|
| 27 |
+
|
| 28 |
+
from ...activations import ACT2FN
|
| 29 |
+
from ...modeling_attn_mask_utils import _prepare_4d_attention_mask
|
| 30 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 31 |
+
from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, ImageClassifierOutput
|
| 32 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 33 |
+
from ...utils import ModelOutput, auto_docstring, can_return_tuple, torch_int
|
| 34 |
+
from .configuration_siglip import SiglipConfig, SiglipTextConfig, SiglipVisionConfig
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _trunc_normal_(tensor, mean, std, a, b):
|
| 38 |
+
# Cut & paste from PyTorch official master until it's in a few official releases - RW
|
| 39 |
+
# Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
|
| 40 |
+
def norm_cdf(x):
|
| 41 |
+
# Computes standard normal cumulative distribution function
|
| 42 |
+
return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0
|
| 43 |
+
|
| 44 |
+
if (mean < a - 2 * std) or (mean > b + 2 * std):
|
| 45 |
+
warnings.warn(
|
| 46 |
+
"mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
|
| 47 |
+
"The distribution of values may be incorrect.",
|
| 48 |
+
stacklevel=2,
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
# Values are generated by using a truncated uniform distribution and
|
| 52 |
+
# then using the inverse CDF for the normal distribution.
|
| 53 |
+
# Get upper and lower cdf values
|
| 54 |
+
l = norm_cdf((a - mean) / std)
|
| 55 |
+
u = norm_cdf((b - mean) / std)
|
| 56 |
+
|
| 57 |
+
# Uniformly fill tensor with values from [l, u], then translate to
|
| 58 |
+
# [2l-1, 2u-1].
|
| 59 |
+
tensor.uniform_(2 * l - 1, 2 * u - 1)
|
| 60 |
+
|
| 61 |
+
# Use inverse cdf transform for normal distribution to get truncated
|
| 62 |
+
# standard normal
|
| 63 |
+
tensor.erfinv_()
|
| 64 |
+
|
| 65 |
+
# Transform to proper mean, std
|
| 66 |
+
tensor.mul_(std * math.sqrt(2.0))
|
| 67 |
+
tensor.add_(mean)
|
| 68 |
+
|
| 69 |
+
# Clamp to ensure it's in the proper range
|
| 70 |
+
tensor.clamp_(min=a, max=b)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def trunc_normal_tf_(
|
| 74 |
+
tensor: torch.Tensor, mean: float = 0.0, std: float = 1.0, a: float = -2.0, b: float = 2.0
|
| 75 |
+
) -> torch.Tensor:
|
| 76 |
+
"""Fills the input Tensor with values drawn from a truncated
|
| 77 |
+
normal distribution. The values are effectively drawn from the
|
| 78 |
+
normal distribution :math:`\\mathcal{N}(\text{mean}, \text{std}^2)`
|
| 79 |
+
with values outside :math:`[a, b]` redrawn until they are within
|
| 80 |
+
the bounds. The method used for generating the random values works
|
| 81 |
+
best when :math:`a \\leq \text{mean} \\leq b`.
|
| 82 |
+
|
| 83 |
+
NOTE: this 'tf' variant behaves closer to Tensorflow / JAX impl where the
|
| 84 |
+
bounds [a, b] are applied when sampling the normal distribution with mean=0, std=1.0
|
| 85 |
+
and the result is subsequently scaled and shifted by the mean and std args.
|
| 86 |
+
|
| 87 |
+
Args:
|
| 88 |
+
tensor: an n-dimensional `torch.Tensor`
|
| 89 |
+
mean: the mean of the normal distribution
|
| 90 |
+
std: the standard deviation of the normal distribution
|
| 91 |
+
a: the minimum cutoff value
|
| 92 |
+
b: the maximum cutoff value
|
| 93 |
+
"""
|
| 94 |
+
with torch.no_grad():
|
| 95 |
+
_trunc_normal_(tensor, 0, 1.0, a, b)
|
| 96 |
+
tensor.mul_(std).add_(mean)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def variance_scaling_(tensor, scale=1.0, mode="fan_in", distribution="normal"):
|
| 100 |
+
fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor)
|
| 101 |
+
if mode == "fan_in":
|
| 102 |
+
denom = fan_in
|
| 103 |
+
elif mode == "fan_out":
|
| 104 |
+
denom = fan_out
|
| 105 |
+
elif mode == "fan_avg":
|
| 106 |
+
denom = (fan_in + fan_out) / 2
|
| 107 |
+
|
| 108 |
+
variance = scale / denom
|
| 109 |
+
|
| 110 |
+
if distribution == "truncated_normal":
|
| 111 |
+
# constant is stddev of standard normal truncated to (-2, 2)
|
| 112 |
+
trunc_normal_tf_(tensor, std=math.sqrt(variance) / 0.87962566103423978)
|
| 113 |
+
elif distribution == "normal":
|
| 114 |
+
with torch.no_grad():
|
| 115 |
+
tensor.normal_(std=math.sqrt(variance))
|
| 116 |
+
elif distribution == "uniform":
|
| 117 |
+
bound = math.sqrt(3 * variance)
|
| 118 |
+
with torch.no_grad():
|
| 119 |
+
tensor.uniform_(-bound, bound)
|
| 120 |
+
else:
|
| 121 |
+
raise ValueError(f"invalid distribution {distribution}")
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def lecun_normal_(tensor):
|
| 125 |
+
variance_scaling_(tensor, mode="fan_in", distribution="truncated_normal")
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def default_flax_embed_init(tensor):
|
| 129 |
+
variance_scaling_(tensor, mode="fan_in", distribution="normal")
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
@dataclass
|
| 133 |
+
@auto_docstring(
|
| 134 |
+
custom_intro="""
|
| 135 |
+
Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
|
| 136 |
+
"""
|
| 137 |
+
)
|
| 138 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPVisionModelOutput with CLIP->Siglip
|
| 139 |
+
class SiglipVisionModelOutput(ModelOutput):
|
| 140 |
+
r"""
|
| 141 |
+
image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
|
| 142 |
+
The image embeddings obtained by applying the projection layer to the pooler_output.
|
| 143 |
+
"""
|
| 144 |
+
|
| 145 |
+
image_embeds: Optional[torch.FloatTensor] = None
|
| 146 |
+
last_hidden_state: Optional[torch.FloatTensor] = None
|
| 147 |
+
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 148 |
+
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
@dataclass
|
| 152 |
+
@auto_docstring(
|
| 153 |
+
custom_intro="""
|
| 154 |
+
Base class for text model's outputs that also contains a pooling of the last hidden states.
|
| 155 |
+
"""
|
| 156 |
+
)
|
| 157 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPTextModelOutput with CLIP->Siglip
|
| 158 |
+
class SiglipTextModelOutput(ModelOutput):
|
| 159 |
+
r"""
|
| 160 |
+
text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
|
| 161 |
+
The text embeddings obtained by applying the projection layer to the pooler_output.
|
| 162 |
+
"""
|
| 163 |
+
|
| 164 |
+
text_embeds: Optional[torch.FloatTensor] = None
|
| 165 |
+
last_hidden_state: Optional[torch.FloatTensor] = None
|
| 166 |
+
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 167 |
+
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
@dataclass
|
| 171 |
+
@auto_docstring
|
| 172 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPOutput with CLIP->Siglip
|
| 173 |
+
class SiglipOutput(ModelOutput):
|
| 174 |
+
r"""
|
| 175 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
|
| 176 |
+
Contrastive loss for image-text similarity.
|
| 177 |
+
logits_per_image (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
|
| 178 |
+
The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
|
| 179 |
+
similarity scores.
|
| 180 |
+
logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
|
| 181 |
+
The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
|
| 182 |
+
similarity scores.
|
| 183 |
+
text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
| 184 |
+
The text embeddings obtained by applying the projection layer to the pooled output of [`SiglipTextModel`].
|
| 185 |
+
image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
| 186 |
+
The image embeddings obtained by applying the projection layer to the pooled output of [`SiglipVisionModel`].
|
| 187 |
+
text_model_output (`BaseModelOutputWithPooling`):
|
| 188 |
+
The output of the [`SiglipTextModel`].
|
| 189 |
+
vision_model_output (`BaseModelOutputWithPooling`):
|
| 190 |
+
The output of the [`SiglipVisionModel`].
|
| 191 |
+
"""
|
| 192 |
+
|
| 193 |
+
loss: Optional[torch.FloatTensor] = None
|
| 194 |
+
logits_per_image: Optional[torch.FloatTensor] = None
|
| 195 |
+
logits_per_text: Optional[torch.FloatTensor] = None
|
| 196 |
+
text_embeds: Optional[torch.FloatTensor] = None
|
| 197 |
+
image_embeds: Optional[torch.FloatTensor] = None
|
| 198 |
+
text_model_output: BaseModelOutputWithPooling = None
|
| 199 |
+
vision_model_output: BaseModelOutputWithPooling = None
|
| 200 |
+
|
| 201 |
+
def to_tuple(self) -> tuple[Any]:
|
| 202 |
+
return tuple(
|
| 203 |
+
self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
|
| 204 |
+
for k in self.keys()
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
class SiglipVisionEmbeddings(nn.Module):
|
| 209 |
+
def __init__(self, config: SiglipVisionConfig):
|
| 210 |
+
super().__init__()
|
| 211 |
+
self.config = config
|
| 212 |
+
self.embed_dim = config.hidden_size
|
| 213 |
+
self.image_size = config.image_size
|
| 214 |
+
self.patch_size = config.patch_size
|
| 215 |
+
|
| 216 |
+
self.patch_embedding = nn.Conv2d(
|
| 217 |
+
in_channels=config.num_channels,
|
| 218 |
+
out_channels=self.embed_dim,
|
| 219 |
+
kernel_size=self.patch_size,
|
| 220 |
+
stride=self.patch_size,
|
| 221 |
+
padding="valid",
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
self.num_patches = (self.image_size // self.patch_size) ** 2
|
| 225 |
+
self.num_positions = self.num_patches
|
| 226 |
+
self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
|
| 227 |
+
self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
|
| 228 |
+
|
| 229 |
+
def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
|
| 230 |
+
"""
|
| 231 |
+
This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
|
| 232 |
+
images. This method is also adapted to support torch.jit tracing and no class embeddings.
|
| 233 |
+
|
| 234 |
+
Adapted from:
|
| 235 |
+
- https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
|
| 236 |
+
- https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
|
| 237 |
+
"""
|
| 238 |
+
|
| 239 |
+
num_patches = embeddings.shape[1]
|
| 240 |
+
num_positions = self.position_embedding.weight.shape[0]
|
| 241 |
+
|
| 242 |
+
# always interpolate when tracing to ensure the exported model works for dynamic input shapes
|
| 243 |
+
if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
|
| 244 |
+
return self.position_embedding(self.position_ids)
|
| 245 |
+
|
| 246 |
+
patch_pos_embed = self.position_embedding.weight.unsqueeze(0)
|
| 247 |
+
|
| 248 |
+
dim = embeddings.shape[-1]
|
| 249 |
+
|
| 250 |
+
new_height = height // self.patch_size
|
| 251 |
+
new_width = width // self.patch_size
|
| 252 |
+
|
| 253 |
+
sqrt_num_positions = torch_int(num_positions**0.5)
|
| 254 |
+
patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
|
| 255 |
+
patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
|
| 256 |
+
|
| 257 |
+
patch_pos_embed = nn.functional.interpolate(
|
| 258 |
+
patch_pos_embed,
|
| 259 |
+
size=(new_height, new_width),
|
| 260 |
+
mode="bicubic",
|
| 261 |
+
align_corners=False,
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
| 265 |
+
return patch_pos_embed
|
| 266 |
+
|
| 267 |
+
def forward(self, pixel_values: torch.FloatTensor, interpolate_pos_encoding=False) -> torch.Tensor:
|
| 268 |
+
_, _, height, width = pixel_values.shape
|
| 269 |
+
target_dtype = self.patch_embedding.weight.dtype
|
| 270 |
+
patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
|
| 271 |
+
embeddings = patch_embeds.flatten(2).transpose(1, 2)
|
| 272 |
+
|
| 273 |
+
if interpolate_pos_encoding:
|
| 274 |
+
embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
|
| 275 |
+
else:
|
| 276 |
+
embeddings = embeddings + self.position_embedding(self.position_ids)
|
| 277 |
+
return embeddings
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPTextEmbeddings with CLIP->Siglip
|
| 281 |
+
class SiglipTextEmbeddings(nn.Module):
|
| 282 |
+
def __init__(self, config: SiglipTextConfig):
|
| 283 |
+
super().__init__()
|
| 284 |
+
embed_dim = config.hidden_size
|
| 285 |
+
|
| 286 |
+
self.token_embedding = nn.Embedding(config.vocab_size, embed_dim)
|
| 287 |
+
self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim)
|
| 288 |
+
|
| 289 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 290 |
+
self.register_buffer(
|
| 291 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
def forward(
|
| 295 |
+
self,
|
| 296 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 297 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 298 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 299 |
+
) -> torch.Tensor:
|
| 300 |
+
seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2]
|
| 301 |
+
max_position_embedding = self.position_embedding.weight.shape[0]
|
| 302 |
+
|
| 303 |
+
if seq_length > max_position_embedding:
|
| 304 |
+
raise ValueError(
|
| 305 |
+
f"Sequence length must be less than max_position_embeddings (got `sequence length`: "
|
| 306 |
+
f"{seq_length} and max_position_embeddings: {max_position_embedding}"
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
if position_ids is None:
|
| 310 |
+
position_ids = self.position_ids[:, :seq_length]
|
| 311 |
+
|
| 312 |
+
if inputs_embeds is None:
|
| 313 |
+
inputs_embeds = self.token_embedding(input_ids)
|
| 314 |
+
|
| 315 |
+
position_embeddings = self.position_embedding(position_ids)
|
| 316 |
+
embeddings = inputs_embeds + position_embeddings
|
| 317 |
+
|
| 318 |
+
return embeddings
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def eager_attention_forward(
|
| 322 |
+
module: nn.Module,
|
| 323 |
+
query: torch.Tensor,
|
| 324 |
+
key: torch.Tensor,
|
| 325 |
+
value: torch.Tensor,
|
| 326 |
+
attention_mask: Optional[torch.Tensor],
|
| 327 |
+
scaling: float,
|
| 328 |
+
dropout: float = 0.0,
|
| 329 |
+
**kwargs,
|
| 330 |
+
):
|
| 331 |
+
attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling
|
| 332 |
+
if attention_mask is not None:
|
| 333 |
+
attn_weights = attn_weights + attention_mask
|
| 334 |
+
|
| 335 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 336 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 337 |
+
|
| 338 |
+
attn_output = torch.matmul(attn_weights, value)
|
| 339 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 340 |
+
|
| 341 |
+
return attn_output, attn_weights
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
class SiglipAttention(nn.Module):
|
| 345 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 346 |
+
|
| 347 |
+
def __init__(self, config):
|
| 348 |
+
super().__init__()
|
| 349 |
+
self.config = config
|
| 350 |
+
self.embed_dim = config.hidden_size
|
| 351 |
+
self.num_heads = config.num_attention_heads
|
| 352 |
+
self.head_dim = self.embed_dim // self.num_heads
|
| 353 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
| 354 |
+
raise ValueError(
|
| 355 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
|
| 356 |
+
f" {self.num_heads})."
|
| 357 |
+
)
|
| 358 |
+
self.scale = self.head_dim**-0.5
|
| 359 |
+
self.dropout = config.attention_dropout
|
| 360 |
+
self.is_causal = False
|
| 361 |
+
|
| 362 |
+
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 363 |
+
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 364 |
+
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 365 |
+
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 366 |
+
|
| 367 |
+
def forward(
|
| 368 |
+
self,
|
| 369 |
+
hidden_states: torch.Tensor,
|
| 370 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 371 |
+
**kwargs,
|
| 372 |
+
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 373 |
+
"""Input shape: Batch x Time x Channel"""
|
| 374 |
+
|
| 375 |
+
batch_size, seq_length, embed_dim = hidden_states.shape
|
| 376 |
+
|
| 377 |
+
queries = self.q_proj(hidden_states)
|
| 378 |
+
keys = self.k_proj(hidden_states)
|
| 379 |
+
values = self.v_proj(hidden_states)
|
| 380 |
+
|
| 381 |
+
queries = queries.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
|
| 382 |
+
keys = keys.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
|
| 383 |
+
values = values.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
|
| 384 |
+
|
| 385 |
+
attention_interface: Callable = eager_attention_forward
|
| 386 |
+
if self.config._attn_implementation != "eager":
|
| 387 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 388 |
+
|
| 389 |
+
attn_output, attn_weights = attention_interface(
|
| 390 |
+
self,
|
| 391 |
+
queries,
|
| 392 |
+
keys,
|
| 393 |
+
values,
|
| 394 |
+
attention_mask,
|
| 395 |
+
is_causal=self.is_causal,
|
| 396 |
+
scaling=self.scale,
|
| 397 |
+
dropout=0.0 if not self.training else self.dropout,
|
| 398 |
+
)
|
| 399 |
+
|
| 400 |
+
attn_output = attn_output.reshape(batch_size, seq_length, embed_dim).contiguous()
|
| 401 |
+
attn_output = self.out_proj(attn_output)
|
| 402 |
+
|
| 403 |
+
return attn_output, attn_weights
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Siglip
|
| 407 |
+
class SiglipMLP(nn.Module):
|
| 408 |
+
def __init__(self, config):
|
| 409 |
+
super().__init__()
|
| 410 |
+
self.config = config
|
| 411 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
| 412 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 413 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 414 |
+
|
| 415 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 416 |
+
hidden_states = self.fc1(hidden_states)
|
| 417 |
+
hidden_states = self.activation_fn(hidden_states)
|
| 418 |
+
hidden_states = self.fc2(hidden_states)
|
| 419 |
+
return hidden_states
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
class SiglipEncoderLayer(GradientCheckpointingLayer):
|
| 423 |
+
def __init__(self, config: Union[SiglipVisionConfig, SiglipTextConfig]):
|
| 424 |
+
super().__init__()
|
| 425 |
+
self.embed_dim = config.hidden_size
|
| 426 |
+
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 427 |
+
self.self_attn = SiglipAttention(config)
|
| 428 |
+
self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 429 |
+
self.mlp = SiglipMLP(config)
|
| 430 |
+
|
| 431 |
+
def forward(
|
| 432 |
+
self,
|
| 433 |
+
hidden_states: torch.Tensor,
|
| 434 |
+
attention_mask: torch.Tensor,
|
| 435 |
+
output_attentions: Optional[bool] = False,
|
| 436 |
+
) -> tuple[torch.FloatTensor]:
|
| 437 |
+
"""
|
| 438 |
+
Args:
|
| 439 |
+
hidden_states (`torch.FloatTensor`):
|
| 440 |
+
Input to the layer of shape `(batch, seq_len, embed_dim)`.
|
| 441 |
+
attention_mask (`torch.FloatTensor`):
|
| 442 |
+
Attention mask of shape `(batch, 1, q_len, k_v_seq_len)` where padding elements are indicated by very large negative values.
|
| 443 |
+
output_attentions (`bool`, *optional*, defaults to `False`):
|
| 444 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 445 |
+
returned tensors for more detail.
|
| 446 |
+
"""
|
| 447 |
+
residual = hidden_states
|
| 448 |
+
|
| 449 |
+
hidden_states = self.layer_norm1(hidden_states)
|
| 450 |
+
hidden_states, attn_weights = self.self_attn(
|
| 451 |
+
hidden_states=hidden_states,
|
| 452 |
+
attention_mask=attention_mask,
|
| 453 |
+
output_attentions=output_attentions,
|
| 454 |
+
)
|
| 455 |
+
hidden_states = residual + hidden_states
|
| 456 |
+
|
| 457 |
+
residual = hidden_states
|
| 458 |
+
hidden_states = self.layer_norm2(hidden_states)
|
| 459 |
+
hidden_states = self.mlp(hidden_states)
|
| 460 |
+
hidden_states = residual + hidden_states
|
| 461 |
+
|
| 462 |
+
outputs = (hidden_states,)
|
| 463 |
+
|
| 464 |
+
if output_attentions:
|
| 465 |
+
outputs += (attn_weights,)
|
| 466 |
+
|
| 467 |
+
return outputs
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
@auto_docstring
|
| 471 |
+
class SiglipPreTrainedModel(PreTrainedModel):
|
| 472 |
+
config: SiglipConfig
|
| 473 |
+
base_model_prefix = "siglip"
|
| 474 |
+
supports_gradient_checkpointing = True
|
| 475 |
+
|
| 476 |
+
_no_split_modules = [
|
| 477 |
+
"SiglipTextEmbeddings",
|
| 478 |
+
"SiglipVisionEmbeddings",
|
| 479 |
+
"SiglipEncoderLayer",
|
| 480 |
+
"SiglipMultiheadAttentionPoolingHead",
|
| 481 |
+
]
|
| 482 |
+
_supports_flash_attn = True
|
| 483 |
+
_supports_sdpa = True
|
| 484 |
+
_supports_flex_attn = True
|
| 485 |
+
_supports_attention_backend = True
|
| 486 |
+
|
| 487 |
+
def _init_weights(self, module):
|
| 488 |
+
"""Initialize the weights"""
|
| 489 |
+
if isinstance(module, SiglipVisionEmbeddings):
|
| 490 |
+
width = (
|
| 491 |
+
self.config.vision_config.hidden_size
|
| 492 |
+
if isinstance(self.config, SiglipConfig)
|
| 493 |
+
else self.config.hidden_size
|
| 494 |
+
)
|
| 495 |
+
nn.init.normal_(module.position_embedding.weight, std=1 / np.sqrt(width))
|
| 496 |
+
elif isinstance(module, nn.Embedding):
|
| 497 |
+
default_flax_embed_init(module.weight)
|
| 498 |
+
elif isinstance(module, SiglipAttention):
|
| 499 |
+
nn.init.xavier_uniform_(module.q_proj.weight)
|
| 500 |
+
nn.init.xavier_uniform_(module.k_proj.weight)
|
| 501 |
+
nn.init.xavier_uniform_(module.v_proj.weight)
|
| 502 |
+
nn.init.xavier_uniform_(module.out_proj.weight)
|
| 503 |
+
nn.init.zeros_(module.q_proj.bias)
|
| 504 |
+
nn.init.zeros_(module.k_proj.bias)
|
| 505 |
+
nn.init.zeros_(module.v_proj.bias)
|
| 506 |
+
nn.init.zeros_(module.out_proj.bias)
|
| 507 |
+
elif isinstance(module, SiglipMLP):
|
| 508 |
+
nn.init.xavier_uniform_(module.fc1.weight)
|
| 509 |
+
nn.init.xavier_uniform_(module.fc2.weight)
|
| 510 |
+
nn.init.normal_(module.fc1.bias, std=1e-6)
|
| 511 |
+
nn.init.normal_(module.fc2.bias, std=1e-6)
|
| 512 |
+
elif isinstance(module, SiglipMultiheadAttentionPoolingHead):
|
| 513 |
+
nn.init.xavier_uniform_(module.probe.data)
|
| 514 |
+
nn.init.xavier_uniform_(module.attention.in_proj_weight.data)
|
| 515 |
+
nn.init.zeros_(module.attention.in_proj_bias.data)
|
| 516 |
+
elif isinstance(module, SiglipModel):
|
| 517 |
+
logit_scale_init = torch.log(torch.tensor(1.0))
|
| 518 |
+
module.logit_scale.data.fill_(logit_scale_init)
|
| 519 |
+
module.logit_bias.data.zero_()
|
| 520 |
+
elif isinstance(module, SiglipForImageClassification):
|
| 521 |
+
nn.init.normal_(
|
| 522 |
+
module.classifier.weight,
|
| 523 |
+
std=self.config.vision_config.hidden_size**-0.5 * self.config.initializer_factor,
|
| 524 |
+
)
|
| 525 |
+
elif isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 526 |
+
lecun_normal_(module.weight)
|
| 527 |
+
if module.bias is not None:
|
| 528 |
+
nn.init.zeros_(module.bias)
|
| 529 |
+
elif isinstance(module, nn.LayerNorm):
|
| 530 |
+
module.bias.data.zero_()
|
| 531 |
+
module.weight.data.fill_(1.0)
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
# Copied from transformers.models.altclip.modeling_altclip.AltCLIPEncoder with AltCLIP->Siglip
|
| 535 |
+
class SiglipEncoder(nn.Module):
|
| 536 |
+
"""
|
| 537 |
+
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
|
| 538 |
+
[`SiglipEncoderLayer`].
|
| 539 |
+
|
| 540 |
+
Args:
|
| 541 |
+
config: SiglipConfig
|
| 542 |
+
"""
|
| 543 |
+
|
| 544 |
+
def __init__(self, config: SiglipConfig):
|
| 545 |
+
super().__init__()
|
| 546 |
+
self.config = config
|
| 547 |
+
self.layers = nn.ModuleList([SiglipEncoderLayer(config) for _ in range(config.num_hidden_layers)])
|
| 548 |
+
self.gradient_checkpointing = False
|
| 549 |
+
|
| 550 |
+
# Ignore copy
|
| 551 |
+
@can_return_tuple
|
| 552 |
+
def forward(
|
| 553 |
+
self,
|
| 554 |
+
inputs_embeds,
|
| 555 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 556 |
+
output_attentions: Optional[bool] = None,
|
| 557 |
+
output_hidden_states: Optional[bool] = None,
|
| 558 |
+
) -> BaseModelOutput:
|
| 559 |
+
r"""
|
| 560 |
+
Args:
|
| 561 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 562 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 563 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 564 |
+
than the model's internal embedding lookup matrix.
|
| 565 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 566 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 567 |
+
|
| 568 |
+
- 1 for tokens that are **not masked**,
|
| 569 |
+
- 0 for tokens that are **masked**.
|
| 570 |
+
|
| 571 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 572 |
+
output_attentions (`bool`, *optional*):
|
| 573 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 574 |
+
returned tensors for more detail.
|
| 575 |
+
output_hidden_states (`bool`, *optional*):
|
| 576 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 577 |
+
for more detail.
|
| 578 |
+
return_dict (`bool`, *optional*):
|
| 579 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 580 |
+
"""
|
| 581 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 582 |
+
output_hidden_states = (
|
| 583 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 584 |
+
)
|
| 585 |
+
|
| 586 |
+
encoder_states = () if output_hidden_states else None
|
| 587 |
+
all_attentions = () if output_attentions else None
|
| 588 |
+
|
| 589 |
+
hidden_states = inputs_embeds
|
| 590 |
+
for encoder_layer in self.layers:
|
| 591 |
+
if output_hidden_states:
|
| 592 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 593 |
+
|
| 594 |
+
layer_outputs = encoder_layer(
|
| 595 |
+
hidden_states,
|
| 596 |
+
attention_mask,
|
| 597 |
+
output_attentions=output_attentions,
|
| 598 |
+
)
|
| 599 |
+
|
| 600 |
+
hidden_states = layer_outputs[0]
|
| 601 |
+
|
| 602 |
+
if output_attentions:
|
| 603 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 604 |
+
|
| 605 |
+
if output_hidden_states:
|
| 606 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 607 |
+
|
| 608 |
+
return BaseModelOutput(
|
| 609 |
+
last_hidden_state=hidden_states,
|
| 610 |
+
hidden_states=encoder_states,
|
| 611 |
+
attentions=all_attentions,
|
| 612 |
+
)
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
class SiglipTextTransformer(nn.Module):
|
| 616 |
+
def __init__(self, config: SiglipTextConfig):
|
| 617 |
+
super().__init__()
|
| 618 |
+
self.config = config
|
| 619 |
+
embed_dim = config.hidden_size
|
| 620 |
+
self.embeddings = SiglipTextEmbeddings(config)
|
| 621 |
+
self.encoder = SiglipEncoder(config)
|
| 622 |
+
self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
| 623 |
+
|
| 624 |
+
self.head = nn.Linear(embed_dim, config.projection_size)
|
| 625 |
+
|
| 626 |
+
@can_return_tuple
|
| 627 |
+
@auto_docstring
|
| 628 |
+
def forward(
|
| 629 |
+
self,
|
| 630 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 631 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 632 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 633 |
+
output_attentions: Optional[bool] = None,
|
| 634 |
+
output_hidden_states: Optional[bool] = None,
|
| 635 |
+
) -> BaseModelOutputWithPooling:
|
| 636 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 637 |
+
output_hidden_states = (
|
| 638 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 639 |
+
)
|
| 640 |
+
|
| 641 |
+
if input_ids is None:
|
| 642 |
+
raise ValueError("You have to specify input_ids")
|
| 643 |
+
|
| 644 |
+
input_shape = input_ids.size()
|
| 645 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
| 646 |
+
|
| 647 |
+
hidden_states = self.embeddings(input_ids=input_ids, position_ids=position_ids)
|
| 648 |
+
|
| 649 |
+
# note: SigLIP's text model does not use a causal mask, unlike the original CLIP model.
|
| 650 |
+
# expand attention_mask
|
| 651 |
+
uses_flash_attention = "flash" in self.config._attn_implementation
|
| 652 |
+
if uses_flash_attention:
|
| 653 |
+
attention_mask = None
|
| 654 |
+
elif attention_mask is not None and not uses_flash_attention:
|
| 655 |
+
# [batch_size, seq_len] -> [batch_size, 1, tgt_seq_len, src_seq_len]
|
| 656 |
+
attention_mask = _prepare_4d_attention_mask(attention_mask, hidden_states.dtype)
|
| 657 |
+
|
| 658 |
+
encoder_outputs: BaseModelOutput = self.encoder(
|
| 659 |
+
inputs_embeds=hidden_states,
|
| 660 |
+
attention_mask=attention_mask,
|
| 661 |
+
output_attentions=output_attentions,
|
| 662 |
+
output_hidden_states=output_hidden_states,
|
| 663 |
+
)
|
| 664 |
+
|
| 665 |
+
last_hidden_state = encoder_outputs.last_hidden_state
|
| 666 |
+
last_hidden_state = self.final_layer_norm(last_hidden_state)
|
| 667 |
+
|
| 668 |
+
# The model uses the last token's hidden state, which may be padding.
|
| 669 |
+
pooled_output = last_hidden_state[:, -1, :]
|
| 670 |
+
pooled_output = self.head(pooled_output)
|
| 671 |
+
|
| 672 |
+
return BaseModelOutputWithPooling(
|
| 673 |
+
last_hidden_state=last_hidden_state,
|
| 674 |
+
pooler_output=pooled_output,
|
| 675 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 676 |
+
attentions=encoder_outputs.attentions,
|
| 677 |
+
)
|
| 678 |
+
|
| 679 |
+
|
| 680 |
+
@auto_docstring(
|
| 681 |
+
custom_intro="""
|
| 682 |
+
The text model from SigLIP without any head or projection on top.
|
| 683 |
+
"""
|
| 684 |
+
)
|
| 685 |
+
class SiglipTextModel(SiglipPreTrainedModel):
|
| 686 |
+
config: SiglipTextConfig
|
| 687 |
+
|
| 688 |
+
def __init__(self, config: SiglipTextConfig):
|
| 689 |
+
super().__init__(config)
|
| 690 |
+
self.text_model = SiglipTextTransformer(config)
|
| 691 |
+
# Initialize weights and apply final processing
|
| 692 |
+
self.post_init()
|
| 693 |
+
|
| 694 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 695 |
+
return self.text_model.embeddings.token_embedding
|
| 696 |
+
|
| 697 |
+
def set_input_embeddings(self, value):
|
| 698 |
+
self.text_model.embeddings.token_embedding = value
|
| 699 |
+
|
| 700 |
+
@can_return_tuple
|
| 701 |
+
@auto_docstring
|
| 702 |
+
def forward(
|
| 703 |
+
self,
|
| 704 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 705 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 706 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 707 |
+
output_attentions: Optional[bool] = None,
|
| 708 |
+
output_hidden_states: Optional[bool] = None,
|
| 709 |
+
) -> BaseModelOutputWithPooling:
|
| 710 |
+
r"""
|
| 711 |
+
Examples:
|
| 712 |
+
|
| 713 |
+
```python
|
| 714 |
+
>>> from transformers import AutoTokenizer, SiglipTextModel
|
| 715 |
+
|
| 716 |
+
>>> model = SiglipTextModel.from_pretrained("google/siglip-base-patch16-224")
|
| 717 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/siglip-base-patch16-224")
|
| 718 |
+
|
| 719 |
+
>>> # important: make sure to set padding="max_length" as that's how the model was trained
|
| 720 |
+
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding="max_length", return_tensors="pt")
|
| 721 |
+
|
| 722 |
+
>>> outputs = model(**inputs)
|
| 723 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
| 724 |
+
>>> pooled_output = outputs.pooler_output # pooled (EOS token) states
|
| 725 |
+
```"""
|
| 726 |
+
|
| 727 |
+
return self.text_model(
|
| 728 |
+
input_ids=input_ids,
|
| 729 |
+
attention_mask=attention_mask,
|
| 730 |
+
position_ids=position_ids,
|
| 731 |
+
output_attentions=output_attentions,
|
| 732 |
+
output_hidden_states=output_hidden_states,
|
| 733 |
+
)
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
class SiglipVisionTransformer(nn.Module):
|
| 737 |
+
def __init__(self, config: SiglipVisionConfig):
|
| 738 |
+
super().__init__()
|
| 739 |
+
self.config = config
|
| 740 |
+
embed_dim = config.hidden_size
|
| 741 |
+
|
| 742 |
+
self.embeddings = SiglipVisionEmbeddings(config)
|
| 743 |
+
self.encoder = SiglipEncoder(config)
|
| 744 |
+
self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
| 745 |
+
self.use_head = True if not hasattr(config, "vision_use_head") else config.vision_use_head
|
| 746 |
+
if self.use_head:
|
| 747 |
+
self.head = SiglipMultiheadAttentionPoolingHead(config)
|
| 748 |
+
|
| 749 |
+
@can_return_tuple
|
| 750 |
+
@auto_docstring
|
| 751 |
+
def forward(
|
| 752 |
+
self,
|
| 753 |
+
pixel_values,
|
| 754 |
+
output_attentions: Optional[bool] = None,
|
| 755 |
+
output_hidden_states: Optional[bool] = None,
|
| 756 |
+
interpolate_pos_encoding: Optional[bool] = False,
|
| 757 |
+
) -> BaseModelOutputWithPooling:
|
| 758 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 759 |
+
output_hidden_states = (
|
| 760 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 761 |
+
)
|
| 762 |
+
|
| 763 |
+
hidden_states = self.embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
|
| 764 |
+
|
| 765 |
+
encoder_outputs: BaseModelOutput = self.encoder(
|
| 766 |
+
inputs_embeds=hidden_states,
|
| 767 |
+
output_attentions=output_attentions,
|
| 768 |
+
output_hidden_states=output_hidden_states,
|
| 769 |
+
)
|
| 770 |
+
|
| 771 |
+
last_hidden_state = encoder_outputs.last_hidden_state
|
| 772 |
+
last_hidden_state = self.post_layernorm(last_hidden_state)
|
| 773 |
+
|
| 774 |
+
pooler_output = self.head(last_hidden_state) if self.use_head else None
|
| 775 |
+
|
| 776 |
+
return BaseModelOutputWithPooling(
|
| 777 |
+
last_hidden_state=last_hidden_state,
|
| 778 |
+
pooler_output=pooler_output,
|
| 779 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 780 |
+
attentions=encoder_outputs.attentions,
|
| 781 |
+
)
|
| 782 |
+
|
| 783 |
+
|
| 784 |
+
class SiglipMultiheadAttentionPoolingHead(nn.Module):
|
| 785 |
+
"""Multihead Attention Pooling."""
|
| 786 |
+
|
| 787 |
+
def __init__(self, config: SiglipVisionConfig):
|
| 788 |
+
super().__init__()
|
| 789 |
+
|
| 790 |
+
self.probe = nn.Parameter(torch.randn(1, 1, config.hidden_size))
|
| 791 |
+
self.attention = torch.nn.MultiheadAttention(config.hidden_size, config.num_attention_heads, batch_first=True)
|
| 792 |
+
self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 793 |
+
self.mlp = SiglipMLP(config)
|
| 794 |
+
|
| 795 |
+
def forward(self, hidden_state):
|
| 796 |
+
batch_size = hidden_state.shape[0]
|
| 797 |
+
probe = self.probe.repeat(batch_size, 1, 1)
|
| 798 |
+
|
| 799 |
+
hidden_state = self.attention(probe, hidden_state, hidden_state)[0]
|
| 800 |
+
|
| 801 |
+
residual = hidden_state
|
| 802 |
+
hidden_state = self.layernorm(hidden_state)
|
| 803 |
+
hidden_state = residual + self.mlp(hidden_state)
|
| 804 |
+
|
| 805 |
+
return hidden_state[:, 0]
|
| 806 |
+
|
| 807 |
+
|
| 808 |
+
@auto_docstring(
|
| 809 |
+
custom_intro="""
|
| 810 |
+
The vision model from SigLIP without any head or projection on top.
|
| 811 |
+
"""
|
| 812 |
+
)
|
| 813 |
+
class SiglipVisionModel(SiglipPreTrainedModel):
|
| 814 |
+
config: SiglipVisionConfig
|
| 815 |
+
main_input_name = "pixel_values"
|
| 816 |
+
|
| 817 |
+
def __init__(self, config: SiglipVisionConfig):
|
| 818 |
+
super().__init__(config)
|
| 819 |
+
|
| 820 |
+
self.vision_model = SiglipVisionTransformer(config)
|
| 821 |
+
|
| 822 |
+
# Initialize weights and apply final processing
|
| 823 |
+
self.post_init()
|
| 824 |
+
|
| 825 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 826 |
+
return self.vision_model.embeddings.patch_embedding
|
| 827 |
+
|
| 828 |
+
@can_return_tuple
|
| 829 |
+
@auto_docstring
|
| 830 |
+
def forward(
|
| 831 |
+
self,
|
| 832 |
+
pixel_values,
|
| 833 |
+
output_attentions: Optional[bool] = None,
|
| 834 |
+
output_hidden_states: Optional[bool] = None,
|
| 835 |
+
interpolate_pos_encoding: bool = False,
|
| 836 |
+
) -> BaseModelOutputWithPooling:
|
| 837 |
+
r"""
|
| 838 |
+
Examples:
|
| 839 |
+
|
| 840 |
+
```python
|
| 841 |
+
>>> from PIL import Image
|
| 842 |
+
>>> import requests
|
| 843 |
+
>>> from transformers import AutoProcessor, SiglipVisionModel
|
| 844 |
+
|
| 845 |
+
>>> model = SiglipVisionModel.from_pretrained("google/siglip-base-patch16-224")
|
| 846 |
+
>>> processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224")
|
| 847 |
+
|
| 848 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 849 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 850 |
+
|
| 851 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 852 |
+
|
| 853 |
+
>>> outputs = model(**inputs)
|
| 854 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
| 855 |
+
>>> pooled_output = outputs.pooler_output # pooled features
|
| 856 |
+
```"""
|
| 857 |
+
|
| 858 |
+
return self.vision_model(
|
| 859 |
+
pixel_values=pixel_values,
|
| 860 |
+
output_attentions=output_attentions,
|
| 861 |
+
output_hidden_states=output_hidden_states,
|
| 862 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 863 |
+
)
|
| 864 |
+
|
| 865 |
+
|
| 866 |
+
@auto_docstring
|
| 867 |
+
class SiglipModel(SiglipPreTrainedModel):
|
| 868 |
+
config: SiglipConfig
|
| 869 |
+
|
| 870 |
+
def __init__(self, config: SiglipConfig):
|
| 871 |
+
super().__init__(config)
|
| 872 |
+
|
| 873 |
+
if not isinstance(config.text_config, SiglipTextConfig):
|
| 874 |
+
raise TypeError(
|
| 875 |
+
"config.text_config is expected to be of type SiglipTextConfig but is of type"
|
| 876 |
+
f" {type(config.text_config)}."
|
| 877 |
+
)
|
| 878 |
+
|
| 879 |
+
if not isinstance(config.vision_config, SiglipVisionConfig):
|
| 880 |
+
raise TypeError(
|
| 881 |
+
"config.vision_config is expected to be of type SiglipVisionConfig but is of type"
|
| 882 |
+
f" {type(config.vision_config)}."
|
| 883 |
+
)
|
| 884 |
+
|
| 885 |
+
text_config = config.text_config
|
| 886 |
+
vision_config = config.vision_config
|
| 887 |
+
|
| 888 |
+
# First, initialize the text and vision models with proper attention implementation
|
| 889 |
+
text_model = SiglipTextModel._from_config(text_config)
|
| 890 |
+
vision_model = SiglipVisionModel._from_config(vision_config)
|
| 891 |
+
|
| 892 |
+
# Second, get the text and vision submodules (for backward compatibility)
|
| 893 |
+
self.text_model = text_model.text_model
|
| 894 |
+
self.vision_model = vision_model.vision_model
|
| 895 |
+
|
| 896 |
+
self.logit_scale = nn.Parameter(torch.randn(1))
|
| 897 |
+
self.logit_bias = nn.Parameter(torch.randn(1))
|
| 898 |
+
|
| 899 |
+
# Initialize weights and apply final processing
|
| 900 |
+
self.post_init()
|
| 901 |
+
|
| 902 |
+
@auto_docstring
|
| 903 |
+
def get_text_features(
|
| 904 |
+
self,
|
| 905 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 906 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 907 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 908 |
+
output_attentions: Optional[bool] = None,
|
| 909 |
+
output_hidden_states: Optional[bool] = None,
|
| 910 |
+
) -> torch.FloatTensor:
|
| 911 |
+
r"""
|
| 912 |
+
Returns:
|
| 913 |
+
text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
|
| 914 |
+
applying the projection layer to the pooled output of [`SiglipTextModel`].
|
| 915 |
+
|
| 916 |
+
Examples:
|
| 917 |
+
|
| 918 |
+
```python
|
| 919 |
+
>>> from transformers import AutoTokenizer, AutoModel
|
| 920 |
+
>>> import torch
|
| 921 |
+
|
| 922 |
+
>>> model = AutoModel.from_pretrained("google/siglip-base-patch16-224")
|
| 923 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/siglip-base-patch16-224")
|
| 924 |
+
|
| 925 |
+
>>> # important: make sure to set padding="max_length" as that's how the model was trained
|
| 926 |
+
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding="max_length", return_tensors="pt")
|
| 927 |
+
>>> with torch.no_grad():
|
| 928 |
+
... text_features = model.get_text_features(**inputs)
|
| 929 |
+
```"""
|
| 930 |
+
# Use SigLIP model's config for some fields (if specified) instead of those of vision & text components.
|
| 931 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 932 |
+
output_hidden_states = (
|
| 933 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 934 |
+
)
|
| 935 |
+
|
| 936 |
+
text_outputs: BaseModelOutputWithPooling = self.text_model(
|
| 937 |
+
input_ids=input_ids,
|
| 938 |
+
attention_mask=attention_mask,
|
| 939 |
+
position_ids=position_ids,
|
| 940 |
+
output_attentions=output_attentions,
|
| 941 |
+
output_hidden_states=output_hidden_states,
|
| 942 |
+
)
|
| 943 |
+
|
| 944 |
+
pooled_output = text_outputs.pooler_output
|
| 945 |
+
|
| 946 |
+
return pooled_output
|
| 947 |
+
|
| 948 |
+
@auto_docstring
|
| 949 |
+
def get_image_features(
|
| 950 |
+
self,
|
| 951 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 952 |
+
output_attentions: Optional[bool] = None,
|
| 953 |
+
output_hidden_states: Optional[bool] = None,
|
| 954 |
+
interpolate_pos_encoding: bool = False,
|
| 955 |
+
) -> torch.FloatTensor:
|
| 956 |
+
r"""
|
| 957 |
+
Returns:
|
| 958 |
+
image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
|
| 959 |
+
applying the projection layer to the pooled output of [`SiglipVisionModel`].
|
| 960 |
+
|
| 961 |
+
Examples:
|
| 962 |
+
|
| 963 |
+
```python
|
| 964 |
+
>>> from PIL import Image
|
| 965 |
+
>>> import requests
|
| 966 |
+
>>> from transformers import AutoProcessor, AutoModel
|
| 967 |
+
>>> import torch
|
| 968 |
+
|
| 969 |
+
>>> model = AutoModel.from_pretrained("google/siglip-base-patch16-224")
|
| 970 |
+
>>> processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224")
|
| 971 |
+
|
| 972 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 973 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 974 |
+
|
| 975 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 976 |
+
|
| 977 |
+
>>> with torch.no_grad():
|
| 978 |
+
... image_features = model.get_image_features(**inputs)
|
| 979 |
+
```"""
|
| 980 |
+
# Use SiglipModel's config for some fields (if specified) instead of those of vision & text components.
|
| 981 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 982 |
+
output_hidden_states = (
|
| 983 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 984 |
+
)
|
| 985 |
+
|
| 986 |
+
vision_outputs: BaseModelOutputWithPooling = self.vision_model(
|
| 987 |
+
pixel_values=pixel_values,
|
| 988 |
+
output_attentions=output_attentions,
|
| 989 |
+
output_hidden_states=output_hidden_states,
|
| 990 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 991 |
+
)
|
| 992 |
+
|
| 993 |
+
pooled_output = vision_outputs.pooler_output
|
| 994 |
+
|
| 995 |
+
return pooled_output
|
| 996 |
+
|
| 997 |
+
@can_return_tuple
|
| 998 |
+
@auto_docstring
|
| 999 |
+
def forward(
|
| 1000 |
+
self,
|
| 1001 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1002 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1003 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1004 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1005 |
+
return_loss: Optional[bool] = None,
|
| 1006 |
+
output_attentions: Optional[bool] = None,
|
| 1007 |
+
output_hidden_states: Optional[bool] = None,
|
| 1008 |
+
interpolate_pos_encoding: bool = False,
|
| 1009 |
+
) -> SiglipOutput:
|
| 1010 |
+
r"""
|
| 1011 |
+
return_loss (`bool`, *optional*):
|
| 1012 |
+
Whether or not to return the contrastive loss.
|
| 1013 |
+
|
| 1014 |
+
Examples:
|
| 1015 |
+
|
| 1016 |
+
```python
|
| 1017 |
+
>>> from PIL import Image
|
| 1018 |
+
>>> import requests
|
| 1019 |
+
>>> from transformers import AutoProcessor, AutoModel
|
| 1020 |
+
>>> import torch
|
| 1021 |
+
|
| 1022 |
+
>>> model = AutoModel.from_pretrained("google/siglip-base-patch16-224")
|
| 1023 |
+
>>> processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224")
|
| 1024 |
+
|
| 1025 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1026 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1027 |
+
|
| 1028 |
+
>>> texts = ["a photo of 2 cats", "a photo of 2 dogs"]
|
| 1029 |
+
>>> # important: we pass `padding=max_length` since the model was trained with this
|
| 1030 |
+
>>> inputs = processor(text=texts, images=image, padding="max_length", return_tensors="pt")
|
| 1031 |
+
|
| 1032 |
+
>>> with torch.no_grad():
|
| 1033 |
+
... outputs = model(**inputs)
|
| 1034 |
+
|
| 1035 |
+
>>> logits_per_image = outputs.logits_per_image
|
| 1036 |
+
>>> probs = torch.sigmoid(logits_per_image) # these are the probabilities
|
| 1037 |
+
>>> print(f"{probs[0][0]:.1%} that image 0 is '{texts[0]}'")
|
| 1038 |
+
31.9% that image 0 is 'a photo of 2 cats'
|
| 1039 |
+
```"""
|
| 1040 |
+
# Use SigLIP model's config for some fields (if specified) instead of those of vision & text components.
|
| 1041 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1042 |
+
output_hidden_states = (
|
| 1043 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1044 |
+
)
|
| 1045 |
+
|
| 1046 |
+
vision_outputs: BaseModelOutputWithPooling = self.vision_model(
|
| 1047 |
+
pixel_values=pixel_values,
|
| 1048 |
+
output_attentions=output_attentions,
|
| 1049 |
+
output_hidden_states=output_hidden_states,
|
| 1050 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 1051 |
+
)
|
| 1052 |
+
|
| 1053 |
+
text_outputs: BaseModelOutputWithPooling = self.text_model(
|
| 1054 |
+
input_ids=input_ids,
|
| 1055 |
+
attention_mask=attention_mask,
|
| 1056 |
+
position_ids=position_ids,
|
| 1057 |
+
output_attentions=output_attentions,
|
| 1058 |
+
output_hidden_states=output_hidden_states,
|
| 1059 |
+
)
|
| 1060 |
+
|
| 1061 |
+
image_embeds = vision_outputs.pooler_output
|
| 1062 |
+
text_embeds = text_outputs.pooler_output
|
| 1063 |
+
|
| 1064 |
+
# normalized features
|
| 1065 |
+
image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
|
| 1066 |
+
text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
|
| 1067 |
+
|
| 1068 |
+
# cosine similarity as logits
|
| 1069 |
+
logits_per_text = torch.matmul(text_embeds, image_embeds.t().to(text_embeds.device))
|
| 1070 |
+
|
| 1071 |
+
logit_scale, logit_bias = self.logit_scale.to(text_embeds.device), self.logit_bias.to(text_embeds.device)
|
| 1072 |
+
logits_per_text = logits_per_text * logit_scale.exp() + logit_bias
|
| 1073 |
+
|
| 1074 |
+
logits_per_image = logits_per_text.t()
|
| 1075 |
+
|
| 1076 |
+
loss = None
|
| 1077 |
+
if return_loss:
|
| 1078 |
+
# Adapted from https://github.com/google-research/big_vision/blob/01edb81a4716f93a48be43b3a4af14e29cdb3a7f/big_vision/trainers/proj/image_text/siglip.py#L287
|
| 1079 |
+
eye = torch.eye(logits_per_text.size(0), device=logits_per_text.device)
|
| 1080 |
+
m1_diag1 = -torch.ones_like(logits_per_text) + 2 * eye
|
| 1081 |
+
loglik = torch.nn.functional.logsigmoid(m1_diag1 * logits_per_text)
|
| 1082 |
+
nll = -torch.sum(loglik, dim=-1)
|
| 1083 |
+
loss = nll.mean()
|
| 1084 |
+
|
| 1085 |
+
return SiglipOutput(
|
| 1086 |
+
loss=loss,
|
| 1087 |
+
logits_per_image=logits_per_image,
|
| 1088 |
+
logits_per_text=logits_per_text,
|
| 1089 |
+
text_embeds=text_embeds,
|
| 1090 |
+
image_embeds=image_embeds,
|
| 1091 |
+
text_model_output=text_outputs,
|
| 1092 |
+
vision_model_output=vision_outputs,
|
| 1093 |
+
)
|
| 1094 |
+
|
| 1095 |
+
|
| 1096 |
+
@auto_docstring(
|
| 1097 |
+
custom_intro="""
|
| 1098 |
+
SigLIP vision encoder with an image classification head on top (a linear layer on top of the pooled final hidden states of
|
| 1099 |
+
the patch tokens) e.g. for ImageNet.
|
| 1100 |
+
"""
|
| 1101 |
+
)
|
| 1102 |
+
class SiglipForImageClassification(SiglipPreTrainedModel):
|
| 1103 |
+
main_input_name = "pixel_values"
|
| 1104 |
+
|
| 1105 |
+
def __init__(self, config: SiglipConfig) -> None:
|
| 1106 |
+
super().__init__(config)
|
| 1107 |
+
|
| 1108 |
+
self.num_labels = config.num_labels
|
| 1109 |
+
|
| 1110 |
+
# Create the vision model with proper attention
|
| 1111 |
+
# and take only vision_model submodule (for backward compatibility)
|
| 1112 |
+
vision_model = SiglipVisionModel._from_config(config.vision_config)
|
| 1113 |
+
self.vision_model = vision_model.vision_model
|
| 1114 |
+
|
| 1115 |
+
# Classifier head
|
| 1116 |
+
self.classifier = (
|
| 1117 |
+
nn.Linear(config.vision_config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
|
| 1118 |
+
)
|
| 1119 |
+
|
| 1120 |
+
# Initialize weights and apply final processing
|
| 1121 |
+
self.post_init()
|
| 1122 |
+
|
| 1123 |
+
@can_return_tuple
|
| 1124 |
+
@auto_docstring
|
| 1125 |
+
def forward(
|
| 1126 |
+
self,
|
| 1127 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 1128 |
+
labels: Optional[torch.Tensor] = None,
|
| 1129 |
+
output_attentions: Optional[bool] = None,
|
| 1130 |
+
output_hidden_states: Optional[bool] = None,
|
| 1131 |
+
interpolate_pos_encoding: bool = False,
|
| 1132 |
+
) -> ImageClassifierOutput:
|
| 1133 |
+
r"""
|
| 1134 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1135 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 1136 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1137 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1138 |
+
|
| 1139 |
+
Examples:
|
| 1140 |
+
|
| 1141 |
+
```python
|
| 1142 |
+
>>> from transformers import AutoImageProcessor, SiglipForImageClassification
|
| 1143 |
+
>>> import torch
|
| 1144 |
+
>>> from PIL import Image
|
| 1145 |
+
>>> import requests
|
| 1146 |
+
|
| 1147 |
+
>>> torch.manual_seed(3) # doctest: +IGNORE_RESULT
|
| 1148 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1149 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1150 |
+
|
| 1151 |
+
>>> # note: we are loading a `SiglipModel` from the hub here,
|
| 1152 |
+
>>> # so the head will be randomly initialized, hence the predictions will be random if seed is not set above.
|
| 1153 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("google/siglip-base-patch16-224")
|
| 1154 |
+
>>> model = SiglipForImageClassification.from_pretrained("google/siglip-base-patch16-224")
|
| 1155 |
+
|
| 1156 |
+
>>> inputs = image_processor(images=image, return_tensors="pt")
|
| 1157 |
+
>>> outputs = model(**inputs)
|
| 1158 |
+
>>> logits = outputs.logits
|
| 1159 |
+
>>> # model predicts one of the two classes
|
| 1160 |
+
>>> predicted_class_idx = logits.argmax(-1).item()
|
| 1161 |
+
>>> print("Predicted class:", model.config.id2label[predicted_class_idx])
|
| 1162 |
+
Predicted class: LABEL_1
|
| 1163 |
+
```"""
|
| 1164 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1165 |
+
output_hidden_states = (
|
| 1166 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1167 |
+
)
|
| 1168 |
+
|
| 1169 |
+
outputs: BaseModelOutputWithPooling = self.vision_model(
|
| 1170 |
+
pixel_values,
|
| 1171 |
+
output_attentions=output_attentions,
|
| 1172 |
+
output_hidden_states=output_hidden_states,
|
| 1173 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 1174 |
+
)
|
| 1175 |
+
|
| 1176 |
+
sequence_output = outputs.last_hidden_state
|
| 1177 |
+
|
| 1178 |
+
# average pool the patch tokens
|
| 1179 |
+
sequence_output = torch.mean(sequence_output, dim=1)
|
| 1180 |
+
# apply classifier
|
| 1181 |
+
logits = self.classifier(sequence_output)
|
| 1182 |
+
|
| 1183 |
+
loss = None
|
| 1184 |
+
if labels is not None:
|
| 1185 |
+
# move labels to correct device to enable model parallelism
|
| 1186 |
+
labels = labels.to(logits.device)
|
| 1187 |
+
if self.config.problem_type is None:
|
| 1188 |
+
if self.num_labels == 1:
|
| 1189 |
+
self.config.problem_type = "regression"
|
| 1190 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 1191 |
+
self.config.problem_type = "single_label_classification"
|
| 1192 |
+
else:
|
| 1193 |
+
self.config.problem_type = "multi_label_classification"
|
| 1194 |
+
|
| 1195 |
+
if self.config.problem_type == "regression":
|
| 1196 |
+
loss_fct = MSELoss()
|
| 1197 |
+
if self.num_labels == 1:
|
| 1198 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 1199 |
+
else:
|
| 1200 |
+
loss = loss_fct(logits, labels)
|
| 1201 |
+
elif self.config.problem_type == "single_label_classification":
|
| 1202 |
+
loss_fct = CrossEntropyLoss()
|
| 1203 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1204 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 1205 |
+
loss_fct = BCEWithLogitsLoss()
|
| 1206 |
+
loss = loss_fct(logits, labels)
|
| 1207 |
+
|
| 1208 |
+
return ImageClassifierOutput(
|
| 1209 |
+
loss=loss,
|
| 1210 |
+
logits=logits,
|
| 1211 |
+
hidden_states=outputs.hidden_states,
|
| 1212 |
+
attentions=outputs.attentions,
|
| 1213 |
+
)
|
| 1214 |
+
|
| 1215 |
+
|
| 1216 |
+
__all__ = [
|
| 1217 |
+
"SiglipModel",
|
| 1218 |
+
"SiglipPreTrainedModel",
|
| 1219 |
+
"SiglipTextModel",
|
| 1220 |
+
"SiglipVisionModel",
|
| 1221 |
+
"SiglipForImageClassification",
|
| 1222 |
+
]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/siglip/processing_siglip.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Image/Text processor class for SigLIP.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from typing import Optional, Union
|
| 20 |
+
|
| 21 |
+
from ...feature_extraction_utils import BatchFeature
|
| 22 |
+
from ...image_utils import ImageInput
|
| 23 |
+
from ...processing_utils import ProcessorMixin
|
| 24 |
+
from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
|
| 25 |
+
from ...utils import TensorType
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class SiglipProcessor(ProcessorMixin):
|
| 29 |
+
r"""
|
| 30 |
+
Constructs a Siglip processor which wraps a Siglip image processor and a Siglip tokenizer into a single processor.
|
| 31 |
+
|
| 32 |
+
[`SiglipProcessor`] offers all the functionalities of [`SiglipImageProcessor`] and [`SiglipTokenizer`]. See the
|
| 33 |
+
[`~SiglipProcessor.__call__`] and [`~SiglipProcessor.decode`] for more information.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
image_processor ([`SiglipImageProcessor`]):
|
| 37 |
+
The image processor is a required input.
|
| 38 |
+
tokenizer ([`SiglipTokenizer`]):
|
| 39 |
+
The tokenizer is a required input.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
attributes = ["image_processor", "tokenizer"]
|
| 43 |
+
image_processor_class = ("SiglipImageProcessor", "SiglipImageProcessorFast")
|
| 44 |
+
tokenizer_class = "AutoTokenizer"
|
| 45 |
+
|
| 46 |
+
def __init__(self, image_processor, tokenizer):
|
| 47 |
+
super().__init__(image_processor, tokenizer)
|
| 48 |
+
|
| 49 |
+
def __call__(
|
| 50 |
+
self,
|
| 51 |
+
text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
|
| 52 |
+
images: ImageInput = None,
|
| 53 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
| 54 |
+
truncation: Union[bool, str, TruncationStrategy] = None,
|
| 55 |
+
max_length: Optional[int] = None,
|
| 56 |
+
return_tensors: Optional[Union[str, TensorType]] = TensorType.PYTORCH,
|
| 57 |
+
) -> BatchFeature:
|
| 58 |
+
"""
|
| 59 |
+
Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
|
| 60 |
+
and `kwargs` arguments to SiglipTokenizer's [`~SiglipTokenizer.__call__`] if `text` is not `None` to encode
|
| 61 |
+
the text. To prepare the image(s), this method forwards the `images` argument to
|
| 62 |
+
SiglipImageProcessor's [`~SiglipImageProcessor.__call__`] if `images` is not `None`. Please refer to the docstring
|
| 63 |
+
of the above two methods for more information.
|
| 64 |
+
|
| 65 |
+
Args:
|
| 66 |
+
text (`str`, `list[str]`, `list[list[str]]`):
|
| 67 |
+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
|
| 68 |
+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
| 69 |
+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
| 70 |
+
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
|
| 71 |
+
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
| 72 |
+
tensor. Both channels-first and channels-last formats are supported.
|
| 73 |
+
padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
|
| 74 |
+
Select a strategy to pad the returned sequences (according to the model's padding side and padding
|
| 75 |
+
index) among:
|
| 76 |
+
- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
|
| 77 |
+
sequence if provided).
|
| 78 |
+
- `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
|
| 79 |
+
acceptable input length for the model if that argument is not provided.
|
| 80 |
+
- `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
|
| 81 |
+
lengths).
|
| 82 |
+
max_length (`int`, *optional*):
|
| 83 |
+
Maximum length of the returned list and optionally padding length (see above).
|
| 84 |
+
truncation (`bool`, *optional*):
|
| 85 |
+
Activates truncation to cut input sequences longer than `max_length` to `max_length`.
|
| 86 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 87 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
| 88 |
+
|
| 89 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 90 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 91 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
| 92 |
+
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
| 93 |
+
|
| 94 |
+
Returns:
|
| 95 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
| 96 |
+
|
| 97 |
+
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
|
| 98 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
| 99 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
| 100 |
+
`None`).
|
| 101 |
+
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
|
| 102 |
+
"""
|
| 103 |
+
|
| 104 |
+
if text is None and images is None:
|
| 105 |
+
raise ValueError("You have to specify either text or images. Both cannot be none.")
|
| 106 |
+
|
| 107 |
+
if text is not None:
|
| 108 |
+
encoding = self.tokenizer(
|
| 109 |
+
text, return_tensors=return_tensors, padding=padding, truncation=truncation, max_length=max_length
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
if images is not None:
|
| 113 |
+
image_features = self.image_processor(images, return_tensors=return_tensors)
|
| 114 |
+
|
| 115 |
+
if text is not None and images is not None:
|
| 116 |
+
encoding.update(image_features)
|
| 117 |
+
return encoding
|
| 118 |
+
elif text is not None:
|
| 119 |
+
return encoding
|
| 120 |
+
else:
|
| 121 |
+
return BatchFeature(data=dict(**image_features), tensor_type=return_tensors)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
__all__ = ["SiglipProcessor"]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/siglip/tokenization_siglip.py
ADDED
|
@@ -0,0 +1,380 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Tokenization class for SigLIP model."""
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
import re
|
| 19 |
+
import string
|
| 20 |
+
import warnings
|
| 21 |
+
from shutil import copyfile
|
| 22 |
+
from typing import TYPE_CHECKING, Any, Optional
|
| 23 |
+
|
| 24 |
+
import sentencepiece as spm
|
| 25 |
+
|
| 26 |
+
from ...convert_slow_tokenizer import import_protobuf
|
| 27 |
+
from ...tokenization_utils import PreTrainedTokenizer
|
| 28 |
+
from ...tokenization_utils_base import AddedToken
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
if TYPE_CHECKING:
|
| 32 |
+
from ...tokenization_utils_base import TextInput
|
| 33 |
+
from ...utils import logging, requires_backends
|
| 34 |
+
from ...utils.import_utils import requires
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
logger = logging.get_logger(__name__)
|
| 38 |
+
|
| 39 |
+
VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
SPIECE_UNDERLINE = "▁"
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@requires(backends=("sentencepiece",))
|
| 46 |
+
class SiglipTokenizer(PreTrainedTokenizer):
|
| 47 |
+
"""
|
| 48 |
+
Construct a Siglip tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
|
| 49 |
+
|
| 50 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 51 |
+
this superclass for more information regarding those methods.
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
vocab_file (`str`):
|
| 55 |
+
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
|
| 56 |
+
contains the vocabulary necessary to instantiate a tokenizer.
|
| 57 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 58 |
+
The end of sequence token.
|
| 59 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 60 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 61 |
+
token instead.
|
| 62 |
+
pad_token (`str`, *optional*, defaults to `"</s>"`):
|
| 63 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 64 |
+
additional_special_tokens (`list[str]`, *optional*):
|
| 65 |
+
Additional special tokens used by the tokenizer.
|
| 66 |
+
sp_model_kwargs (`dict`, *optional*):
|
| 67 |
+
Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
|
| 68 |
+
SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
|
| 69 |
+
to set:
|
| 70 |
+
|
| 71 |
+
- `enable_sampling`: Enable subword regularization.
|
| 72 |
+
- `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
|
| 73 |
+
|
| 74 |
+
- `nbest_size = {0,1}`: No sampling is performed.
|
| 75 |
+
- `nbest_size > 1`: samples from the nbest_size results.
|
| 76 |
+
- `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
|
| 77 |
+
using forward-filtering-and-backward-sampling algorithm.
|
| 78 |
+
|
| 79 |
+
- `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
|
| 80 |
+
BPE-dropout.
|
| 81 |
+
model_max_length (`int`, *optional*, defaults to 64):
|
| 82 |
+
The maximum length (in number of tokens) for model inputs.
|
| 83 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 84 |
+
Whether or not to lowercase the input when tokenizing.
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 88 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 89 |
+
|
| 90 |
+
def __init__(
|
| 91 |
+
self,
|
| 92 |
+
vocab_file,
|
| 93 |
+
eos_token="</s>",
|
| 94 |
+
unk_token="<unk>",
|
| 95 |
+
pad_token="</s>",
|
| 96 |
+
additional_special_tokens=None,
|
| 97 |
+
sp_model_kwargs: Optional[dict[str, Any]] = None,
|
| 98 |
+
model_max_length=64,
|
| 99 |
+
do_lower_case=True,
|
| 100 |
+
**kwargs,
|
| 101 |
+
) -> None:
|
| 102 |
+
requires_backends(self, "protobuf")
|
| 103 |
+
|
| 104 |
+
pad_token = (
|
| 105 |
+
AddedToken(pad_token, rstrip=True, lstrip=True, normalized=False, special=True)
|
| 106 |
+
if isinstance(pad_token, str)
|
| 107 |
+
else pad_token
|
| 108 |
+
)
|
| 109 |
+
unk_token = (
|
| 110 |
+
AddedToken(unk_token, rstrip=True, lstrip=True, normalized=False, special=True)
|
| 111 |
+
if isinstance(unk_token, str)
|
| 112 |
+
else unk_token
|
| 113 |
+
)
|
| 114 |
+
eos_token = (
|
| 115 |
+
AddedToken(eos_token, rstrip=True, lstrip=True, normalized=False, special=True)
|
| 116 |
+
if isinstance(eos_token, str)
|
| 117 |
+
else eos_token
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
| 121 |
+
|
| 122 |
+
self.do_lower_case = do_lower_case
|
| 123 |
+
self.vocab_file = vocab_file
|
| 124 |
+
|
| 125 |
+
self.sp_model = self.get_spm_processor()
|
| 126 |
+
self.vocab_file = vocab_file
|
| 127 |
+
|
| 128 |
+
super().__init__(
|
| 129 |
+
eos_token=eos_token,
|
| 130 |
+
unk_token=unk_token,
|
| 131 |
+
pad_token=pad_token,
|
| 132 |
+
additional_special_tokens=additional_special_tokens,
|
| 133 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
| 134 |
+
model_max_length=model_max_length,
|
| 135 |
+
do_lower_case=do_lower_case,
|
| 136 |
+
**kwargs,
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
def get_spm_processor(self):
|
| 140 |
+
tokenizer = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 141 |
+
with open(self.vocab_file, "rb") as f:
|
| 142 |
+
sp_model = f.read()
|
| 143 |
+
model_pb2 = import_protobuf()
|
| 144 |
+
model = model_pb2.ModelProto.FromString(sp_model)
|
| 145 |
+
normalizer_spec = model_pb2.NormalizerSpec()
|
| 146 |
+
normalizer_spec.add_dummy_prefix = False
|
| 147 |
+
model.normalizer_spec.MergeFrom(normalizer_spec)
|
| 148 |
+
sp_model = model.SerializeToString()
|
| 149 |
+
tokenizer.LoadFromSerializedProto(sp_model)
|
| 150 |
+
return tokenizer
|
| 151 |
+
|
| 152 |
+
@property
|
| 153 |
+
# Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.vocab_size
|
| 154 |
+
def vocab_size(self):
|
| 155 |
+
return self.sp_model.get_piece_size()
|
| 156 |
+
|
| 157 |
+
# Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.get_vocab
|
| 158 |
+
def get_vocab(self):
|
| 159 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
| 160 |
+
vocab.update(self.added_tokens_encoder)
|
| 161 |
+
return vocab
|
| 162 |
+
|
| 163 |
+
# Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.get_special_tokens_mask
|
| 164 |
+
def get_special_tokens_mask(
|
| 165 |
+
self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
|
| 166 |
+
) -> list[int]:
|
| 167 |
+
"""
|
| 168 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 169 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
| 170 |
+
|
| 171 |
+
Args:
|
| 172 |
+
token_ids_0 (`list[int]`):
|
| 173 |
+
List of IDs.
|
| 174 |
+
token_ids_1 (`list[int]`, *optional*):
|
| 175 |
+
Optional second list of IDs for sequence pairs.
|
| 176 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 177 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 178 |
+
|
| 179 |
+
Returns:
|
| 180 |
+
`list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 181 |
+
"""
|
| 182 |
+
if already_has_special_tokens:
|
| 183 |
+
return super().get_special_tokens_mask(
|
| 184 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
# normal case: some special tokens
|
| 188 |
+
if token_ids_1 is None:
|
| 189 |
+
return ([0] * len(token_ids_0)) + [1]
|
| 190 |
+
return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
|
| 191 |
+
|
| 192 |
+
# Copied from transformers.models.t5.tokenization_t5.T5Tokenizer._add_eos_if_not_present
|
| 193 |
+
def _add_eos_if_not_present(self, token_ids: list[int]) -> list[int]:
|
| 194 |
+
"""Do not add eos again if user already added it."""
|
| 195 |
+
if len(token_ids) > 0 and token_ids[-1] == self.eos_token_id:
|
| 196 |
+
warnings.warn(
|
| 197 |
+
f"This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated"
|
| 198 |
+
" eos tokens being added."
|
| 199 |
+
)
|
| 200 |
+
return token_ids
|
| 201 |
+
else:
|
| 202 |
+
return token_ids + [self.eos_token_id]
|
| 203 |
+
|
| 204 |
+
# Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.create_token_type_ids_from_sequences
|
| 205 |
+
def create_token_type_ids_from_sequences(
|
| 206 |
+
self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
|
| 207 |
+
) -> list[int]:
|
| 208 |
+
"""
|
| 209 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. T5 does not make
|
| 210 |
+
use of token type ids, therefore a list of zeros is returned.
|
| 211 |
+
|
| 212 |
+
Args:
|
| 213 |
+
token_ids_0 (`list[int]`):
|
| 214 |
+
List of IDs.
|
| 215 |
+
token_ids_1 (`list[int]`, *optional*):
|
| 216 |
+
Optional second list of IDs for sequence pairs.
|
| 217 |
+
|
| 218 |
+
Returns:
|
| 219 |
+
`list[int]`: List of zeros.
|
| 220 |
+
"""
|
| 221 |
+
eos = [self.eos_token_id]
|
| 222 |
+
|
| 223 |
+
if token_ids_1 is None:
|
| 224 |
+
return len(token_ids_0 + eos) * [0]
|
| 225 |
+
return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
|
| 226 |
+
|
| 227 |
+
# Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.build_inputs_with_special_tokens
|
| 228 |
+
def build_inputs_with_special_tokens(
|
| 229 |
+
self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
|
| 230 |
+
) -> list[int]:
|
| 231 |
+
"""
|
| 232 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 233 |
+
adding special tokens. A sequence has the following format:
|
| 234 |
+
|
| 235 |
+
- single sequence: `X </s>`
|
| 236 |
+
- pair of sequences: `A </s> B </s>`
|
| 237 |
+
|
| 238 |
+
Args:
|
| 239 |
+
token_ids_0 (`list[int]`):
|
| 240 |
+
List of IDs to which the special tokens will be added.
|
| 241 |
+
token_ids_1 (`list[int]`, *optional*):
|
| 242 |
+
Optional second list of IDs for sequence pairs.
|
| 243 |
+
|
| 244 |
+
Returns:
|
| 245 |
+
`list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 246 |
+
"""
|
| 247 |
+
token_ids_0 = self._add_eos_if_not_present(token_ids_0)
|
| 248 |
+
if token_ids_1 is None:
|
| 249 |
+
return token_ids_0
|
| 250 |
+
else:
|
| 251 |
+
token_ids_1 = self._add_eos_if_not_present(token_ids_1)
|
| 252 |
+
return token_ids_0 + token_ids_1
|
| 253 |
+
|
| 254 |
+
# Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.__getstate__
|
| 255 |
+
def __getstate__(self):
|
| 256 |
+
state = self.__dict__.copy()
|
| 257 |
+
state["sp_model"] = None
|
| 258 |
+
return state
|
| 259 |
+
|
| 260 |
+
# Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.__setstate__
|
| 261 |
+
def __setstate__(self, d):
|
| 262 |
+
self.__dict__ = d
|
| 263 |
+
|
| 264 |
+
# for backward compatibility
|
| 265 |
+
if not hasattr(self, "sp_model_kwargs"):
|
| 266 |
+
self.sp_model_kwargs = {}
|
| 267 |
+
|
| 268 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 269 |
+
self.sp_model.Load(self.vocab_file)
|
| 270 |
+
|
| 271 |
+
def remove_punctuation(self, text: str) -> str:
|
| 272 |
+
return text.translate(str.maketrans("", "", string.punctuation))
|
| 273 |
+
|
| 274 |
+
# source: https://github.com/google-research/big_vision/blob/3b8e5ab6ad4f96e32b32826f9e1b8fd277914f9c/big_vision/evaluators/proj/image_text/prompt_engineering.py#L94
|
| 275 |
+
def canonicalize_text(self, text, *, keep_punctuation_exact_string=None):
|
| 276 |
+
"""Returns canonicalized `text` (puncuation removed).
|
| 277 |
+
|
| 278 |
+
Args:
|
| 279 |
+
text (`str`):
|
| 280 |
+
String to be canonicalized.
|
| 281 |
+
keep_punctuation_exact_string (`str`, *optional*):
|
| 282 |
+
If provided, then this exact string is kept. For example providing '{}' will keep any occurrences of '{}'
|
| 283 |
+
(but will still remove '{' and '}' that appear separately).
|
| 284 |
+
"""
|
| 285 |
+
if keep_punctuation_exact_string:
|
| 286 |
+
text = keep_punctuation_exact_string.join(
|
| 287 |
+
self.remove_punctuation(part) for part in text.split(keep_punctuation_exact_string)
|
| 288 |
+
)
|
| 289 |
+
else:
|
| 290 |
+
text = self.remove_punctuation(text)
|
| 291 |
+
text = re.sub(r"\s+", " ", text)
|
| 292 |
+
text = text.strip()
|
| 293 |
+
|
| 294 |
+
return text
|
| 295 |
+
|
| 296 |
+
def tokenize(self, text: "TextInput", add_special_tokens=False, **kwargs) -> list[str]:
|
| 297 |
+
"""
|
| 298 |
+
Converts a string to a list of tokens.
|
| 299 |
+
"""
|
| 300 |
+
tokens = super().tokenize(SPIECE_UNDERLINE + text.replace(SPIECE_UNDERLINE, " "), **kwargs)
|
| 301 |
+
|
| 302 |
+
if len(tokens) > 1 and tokens[0] == SPIECE_UNDERLINE and tokens[1] in self.all_special_tokens:
|
| 303 |
+
tokens = tokens[1:]
|
| 304 |
+
return tokens
|
| 305 |
+
|
| 306 |
+
@property
|
| 307 |
+
# Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.unk_token_length
|
| 308 |
+
def unk_token_length(self):
|
| 309 |
+
return len(self.sp_model.encode(str(self.unk_token)))
|
| 310 |
+
|
| 311 |
+
def _tokenize(self, text, **kwargs):
|
| 312 |
+
"""
|
| 313 |
+
Returns a tokenized string.
|
| 314 |
+
|
| 315 |
+
We de-activated the `add_dummy_prefix` option, thus the sentencepiece internals will always strip any
|
| 316 |
+
SPIECE_UNDERLINE.
|
| 317 |
+
|
| 318 |
+
For example: `self.sp_model.encode(f"{SPIECE_UNDERLINE}Hey", out_type = str)` will give `['H', 'e', 'y']` instead of `['▁He', 'y']`.
|
| 319 |
+
|
| 320 |
+
Thus we always encode `f"{unk_token}text"` and strip the `unk_token`. Here is an example with `unk_token = "<unk>"` and `unk_token_length = 4`.
|
| 321 |
+
`self.tokenizer.sp_model.encode("<unk> Hey", out_type = str)[4:]`.
|
| 322 |
+
"""
|
| 323 |
+
text = self.canonicalize_text(text, keep_punctuation_exact_string=None)
|
| 324 |
+
tokens = self.sp_model.encode(text, out_type=str)
|
| 325 |
+
|
| 326 |
+
# 1. Encode string + prefix ex: "<unk> Hey"
|
| 327 |
+
tokens = self.sp_model.encode(self.unk_token + text, out_type=str)
|
| 328 |
+
# 2. Remove self.unk_token from ['<','unk','>', '▁Hey']
|
| 329 |
+
return tokens[self.unk_token_length :] if len(tokens) >= self.unk_token_length else tokens
|
| 330 |
+
|
| 331 |
+
# Copied from transformers.models.t5.tokenization_t5.T5Tokenizer._convert_token_to_id
|
| 332 |
+
def _convert_token_to_id(self, token):
|
| 333 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 334 |
+
return self.sp_model.piece_to_id(token)
|
| 335 |
+
|
| 336 |
+
# Copied from transformers.models.t5.tokenization_t5.T5Tokenizer._convert_id_to_token
|
| 337 |
+
def _convert_id_to_token(self, index):
|
| 338 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 339 |
+
token = self.sp_model.IdToPiece(index)
|
| 340 |
+
return token
|
| 341 |
+
|
| 342 |
+
def convert_tokens_to_string(self, tokens):
|
| 343 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 344 |
+
current_sub_tokens = []
|
| 345 |
+
out_string = ""
|
| 346 |
+
prev_is_special = False
|
| 347 |
+
for token in tokens:
|
| 348 |
+
# make sure that special tokens are not decoded using sentencepiece model
|
| 349 |
+
if token in self.all_special_tokens:
|
| 350 |
+
if not prev_is_special:
|
| 351 |
+
out_string += " "
|
| 352 |
+
out_string += self.sp_model.decode(current_sub_tokens) + token
|
| 353 |
+
prev_is_special = True
|
| 354 |
+
current_sub_tokens = []
|
| 355 |
+
else:
|
| 356 |
+
current_sub_tokens.append(token)
|
| 357 |
+
prev_is_special = False
|
| 358 |
+
out_string += self.sp_model.decode(current_sub_tokens)
|
| 359 |
+
return out_string.strip()
|
| 360 |
+
|
| 361 |
+
# Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.save_vocabulary
|
| 362 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
|
| 363 |
+
if not os.path.isdir(save_directory):
|
| 364 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 365 |
+
return
|
| 366 |
+
out_vocab_file = os.path.join(
|
| 367 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
| 371 |
+
copyfile(self.vocab_file, out_vocab_file)
|
| 372 |
+
elif not os.path.isfile(self.vocab_file):
|
| 373 |
+
with open(out_vocab_file, "wb") as fi:
|
| 374 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
| 375 |
+
fi.write(content_spiece_model)
|
| 376 |
+
|
| 377 |
+
return (out_vocab_file,)
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
__all__ = ["SiglipTokenizer"]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/siglip2/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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_siglip2 import *
|
| 22 |
+
from .image_processing_siglip2 import *
|
| 23 |
+
from .image_processing_siglip2_fast import *
|
| 24 |
+
from .modeling_siglip2 import *
|
| 25 |
+
from .processing_siglip2 import *
|
| 26 |
+
else:
|
| 27 |
+
import sys
|
| 28 |
+
|
| 29 |
+
_file = globals()["__file__"]
|
| 30 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/siglip2/configuration_siglip2.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/siglip2/modular_siglip2.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_siglip2.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# coding=utf-8
|
| 8 |
+
# Copyright 2025 The HuggingFace Inc. team.
|
| 9 |
+
#
|
| 10 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 11 |
+
# you may not use this file except in compliance with the License.
|
| 12 |
+
# You may obtain a copy of the License at
|
| 13 |
+
#
|
| 14 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 15 |
+
#
|
| 16 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 17 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 18 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 19 |
+
# See the License for the specific language governing permissions and
|
| 20 |
+
# limitations under the License.
|
| 21 |
+
|
| 22 |
+
from ...configuration_utils import PretrainedConfig
|
| 23 |
+
from ...utils import logging
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
logger = logging.get_logger(__name__)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class Siglip2TextConfig(PretrainedConfig):
|
| 30 |
+
r"""
|
| 31 |
+
This is the configuration class to store the configuration of a [`Siglip2TextModel`]. It is used to instantiate a
|
| 32 |
+
Siglip2 text encoder according to the specified arguments, defining the model architecture. Instantiating a
|
| 33 |
+
configuration with the defaults will yield a similar configuration to that of the text encoder of the Siglip2
|
| 34 |
+
[google/siglip2-base-patch16-224](https://huggingface.co/google/siglip2-base-patch16-224) architecture.
|
| 35 |
+
|
| 36 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 37 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 38 |
+
|
| 39 |
+
Args:
|
| 40 |
+
vocab_size (`int`, *optional*, defaults to 32000):
|
| 41 |
+
Vocabulary size of the Siglip2 text model. Defines the number of different tokens that can be represented by
|
| 42 |
+
the `inputs_ids` passed when calling [`Siglip2Model`].
|
| 43 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 44 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 45 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 46 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 47 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 48 |
+
Number of hidden layers in the Transformer encoder.
|
| 49 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 50 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 51 |
+
max_position_embeddings (`int`, *optional*, defaults to 64):
|
| 52 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 53 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 54 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
|
| 55 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 56 |
+
`"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
|
| 57 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-06):
|
| 58 |
+
The epsilon used by the layer normalization layers.
|
| 59 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 60 |
+
The dropout ratio for the attention probabilities.
|
| 61 |
+
pad_token_id (`int`, *optional*, defaults to 1):
|
| 62 |
+
The id of the padding token in the vocabulary.
|
| 63 |
+
bos_token_id (`int`, *optional*, defaults to 49406):
|
| 64 |
+
The id of the beginning-of-sequence token in the vocabulary.
|
| 65 |
+
eos_token_id (`int`, *optional*, defaults to 49407):
|
| 66 |
+
The id of the end-of-sequence token in the vocabulary.
|
| 67 |
+
projection_size (`int`, *optional*, defaults to `hidden_size`):
|
| 68 |
+
The size of the projection head.
|
| 69 |
+
|
| 70 |
+
Example:
|
| 71 |
+
|
| 72 |
+
```python
|
| 73 |
+
>>> from transformers import Siglip2TextConfig, Siglip2TextModel
|
| 74 |
+
|
| 75 |
+
>>> # Initializing a Siglip2TextConfig with google/siglip2-base-patch16-224 style configuration
|
| 76 |
+
>>> configuration = Siglip2TextConfig()
|
| 77 |
+
|
| 78 |
+
>>> # Initializing a Siglip2TextModel (with random weights) from the google/siglip2-base-patch16-224 style configuration
|
| 79 |
+
>>> model = Siglip2TextModel(configuration)
|
| 80 |
+
|
| 81 |
+
>>> # Accessing the model configuration
|
| 82 |
+
>>> configuration = model.config
|
| 83 |
+
```"""
|
| 84 |
+
|
| 85 |
+
model_type = "siglip2_text_model"
|
| 86 |
+
base_config_key = "text_config"
|
| 87 |
+
|
| 88 |
+
def __init__(
|
| 89 |
+
self,
|
| 90 |
+
vocab_size=32000,
|
| 91 |
+
hidden_size=768,
|
| 92 |
+
intermediate_size=3072,
|
| 93 |
+
num_hidden_layers=12,
|
| 94 |
+
num_attention_heads=12,
|
| 95 |
+
max_position_embeddings=64,
|
| 96 |
+
hidden_act="gelu_pytorch_tanh",
|
| 97 |
+
layer_norm_eps=1e-6,
|
| 98 |
+
attention_dropout=0.0,
|
| 99 |
+
# This differs from `CLIPTokenizer`'s default and from openai/siglip2
|
| 100 |
+
# See https://github.com/huggingface/transformers/pull/24773#issuecomment-1632287538
|
| 101 |
+
pad_token_id=1,
|
| 102 |
+
bos_token_id=49406,
|
| 103 |
+
eos_token_id=49407,
|
| 104 |
+
projection_size=None,
|
| 105 |
+
**kwargs,
|
| 106 |
+
):
|
| 107 |
+
super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
| 108 |
+
|
| 109 |
+
self.vocab_size = vocab_size
|
| 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 |
+
self.max_position_embeddings = max_position_embeddings
|
| 115 |
+
self.layer_norm_eps = layer_norm_eps
|
| 116 |
+
self.hidden_act = hidden_act
|
| 117 |
+
self.attention_dropout = attention_dropout
|
| 118 |
+
self.projection_size = projection_size if projection_size is not None else hidden_size
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class Siglip2VisionConfig(PretrainedConfig):
|
| 122 |
+
r"""
|
| 123 |
+
This is the configuration class to store the configuration of a [`Siglip2VisionModel`]. It is used to instantiate a
|
| 124 |
+
Siglip2 vision encoder according to the specified arguments, defining the model architecture. Instantiating a
|
| 125 |
+
configuration with the defaults will yield a similar configuration to that of the vision encoder of the Siglip2
|
| 126 |
+
[google/siglip2-base-patch16-naflex](https://huggingface.co/google/siglip2-base-patch16-naflex) architecture.
|
| 127 |
+
|
| 128 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 129 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 133 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 134 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 135 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 136 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 137 |
+
Number of hidden layers in the Transformer encoder.
|
| 138 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 139 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 140 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 141 |
+
Number of channels in the input images.
|
| 142 |
+
num_patches (`int`, *optional*, defaults to 256):
|
| 143 |
+
The number of patches in the image with the size of (`patch_size`, `patch_size`).
|
| 144 |
+
The image is resized to fill maximum of this number of patches, and to preserve
|
| 145 |
+
the aspect ratio. In case the resulted number of patches is lower, the image is
|
| 146 |
+
padded in "patch" dimension.
|
| 147 |
+
patch_size (`int`, *optional*, defaults to 16):
|
| 148 |
+
The size (resolution) of each patch.
|
| 149 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
|
| 150 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 151 |
+
`"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
|
| 152 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-06):
|
| 153 |
+
The epsilon used by the layer normalization layers.
|
| 154 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 155 |
+
The dropout ratio for the attention probabilities.
|
| 156 |
+
|
| 157 |
+
Example:
|
| 158 |
+
|
| 159 |
+
```python
|
| 160 |
+
>>> from transformers import Siglip2VisionConfig, Siglip2VisionModel
|
| 161 |
+
|
| 162 |
+
>>> # Initializing a Siglip2VisionConfig with google/siglip2-base-patch16-naflex style configuration
|
| 163 |
+
>>> configuration = Siglip2VisionConfig()
|
| 164 |
+
|
| 165 |
+
>>> # Initializing a Siglip2VisionModel (with random weights) from the google/siglip2-base-patch16-naflex style configuration
|
| 166 |
+
>>> model = Siglip2VisionModel(configuration)
|
| 167 |
+
|
| 168 |
+
>>> # Accessing the model configuration
|
| 169 |
+
>>> configuration = model.config
|
| 170 |
+
```"""
|
| 171 |
+
|
| 172 |
+
model_type = "siglip2_vision_model"
|
| 173 |
+
base_config_key = "vision_config"
|
| 174 |
+
|
| 175 |
+
def __init__(
|
| 176 |
+
self,
|
| 177 |
+
hidden_size=768,
|
| 178 |
+
intermediate_size=3072,
|
| 179 |
+
num_hidden_layers=12,
|
| 180 |
+
num_attention_heads=12,
|
| 181 |
+
num_channels=3,
|
| 182 |
+
num_patches=256,
|
| 183 |
+
patch_size=16,
|
| 184 |
+
hidden_act="gelu_pytorch_tanh",
|
| 185 |
+
layer_norm_eps=1e-6,
|
| 186 |
+
attention_dropout=0.0,
|
| 187 |
+
**kwargs,
|
| 188 |
+
):
|
| 189 |
+
super().__init__(**kwargs)
|
| 190 |
+
|
| 191 |
+
self.hidden_size = hidden_size
|
| 192 |
+
self.intermediate_size = intermediate_size
|
| 193 |
+
self.num_hidden_layers = num_hidden_layers
|
| 194 |
+
self.num_attention_heads = num_attention_heads
|
| 195 |
+
self.num_channels = num_channels
|
| 196 |
+
self.patch_size = patch_size
|
| 197 |
+
self.attention_dropout = attention_dropout
|
| 198 |
+
self.layer_norm_eps = layer_norm_eps
|
| 199 |
+
self.hidden_act = hidden_act
|
| 200 |
+
self.num_patches = num_patches
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
class Siglip2Config(PretrainedConfig):
|
| 204 |
+
r"""
|
| 205 |
+
[`Siglip2Config`] is the configuration class to store the configuration of a [`Siglip2Model`]. It is used to
|
| 206 |
+
instantiate a Siglip2 model according to the specified arguments, defining the text model and vision model configs.
|
| 207 |
+
Instantiating a configuration with the defaults will yield a similar configuration to that of the Siglip2
|
| 208 |
+
[google/siglip2-base-patch16-224](https://huggingface.co/google/siglip2-base-patch16-224) architecture.
|
| 209 |
+
|
| 210 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 211 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 212 |
+
|
| 213 |
+
Args:
|
| 214 |
+
text_config (`dict`, *optional*):
|
| 215 |
+
Dictionary of configuration options used to initialize [`Siglip2TextConfig`].
|
| 216 |
+
vision_config (`dict`, *optional*):
|
| 217 |
+
Dictionary of configuration options used to initialize [`Siglip2VisionConfig`].
|
| 218 |
+
kwargs (*optional*):
|
| 219 |
+
Dictionary of keyword arguments.
|
| 220 |
+
|
| 221 |
+
Example:
|
| 222 |
+
|
| 223 |
+
```python
|
| 224 |
+
>>> from transformers import Siglip2Config, Siglip2Model
|
| 225 |
+
|
| 226 |
+
>>> # Initializing a Siglip2Config with google/siglip2-base-patch16-224 style configuration
|
| 227 |
+
>>> configuration = Siglip2Config()
|
| 228 |
+
|
| 229 |
+
>>> # Initializing a Siglip2Model (with random weights) from the google/siglip2-base-patch16-224 style configuration
|
| 230 |
+
>>> model = Siglip2Model(configuration)
|
| 231 |
+
|
| 232 |
+
>>> # Accessing the model configuration
|
| 233 |
+
>>> configuration = model.config
|
| 234 |
+
|
| 235 |
+
>>> # We can also initialize a Siglip2Config from a Siglip2TextConfig and a Siglip2VisionConfig
|
| 236 |
+
>>> from transformers import Siglip2TextConfig, Siglip2VisionConfig
|
| 237 |
+
|
| 238 |
+
>>> # Initializing a Siglip2Text and Siglip2Vision configuration
|
| 239 |
+
>>> config_text = Siglip2TextConfig()
|
| 240 |
+
>>> config_vision = Siglip2VisionConfig()
|
| 241 |
+
|
| 242 |
+
>>> config = Siglip2Config.from_text_vision_configs(config_text, config_vision)
|
| 243 |
+
```"""
|
| 244 |
+
|
| 245 |
+
model_type = "siglip2"
|
| 246 |
+
sub_configs = {"text_config": Siglip2TextConfig, "vision_config": Siglip2VisionConfig}
|
| 247 |
+
|
| 248 |
+
def __init__(self, text_config=None, vision_config=None, **kwargs):
|
| 249 |
+
super().__init__(**kwargs)
|
| 250 |
+
|
| 251 |
+
if text_config is None:
|
| 252 |
+
text_config = {}
|
| 253 |
+
logger.info("`text_config` is `None`. Initializing the `Siglip2TextConfig` with default values.")
|
| 254 |
+
|
| 255 |
+
if vision_config is None:
|
| 256 |
+
vision_config = {}
|
| 257 |
+
logger.info("`vision_config` is `None`. initializing the `Siglip2VisionConfig` with default values.")
|
| 258 |
+
|
| 259 |
+
self.text_config = Siglip2TextConfig(**text_config)
|
| 260 |
+
self.vision_config = Siglip2VisionConfig(**vision_config)
|
| 261 |
+
|
| 262 |
+
self.initializer_factor = 1.0
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
__all__ = ["Siglip2Config", "Siglip2TextConfig", "Siglip2VisionConfig"]
|
code/LaDi-RL-old-qwen-cod/LaDi-R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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Image processor class for SigLIP2."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
from functools import lru_cache
|
| 19 |
+
from typing import Optional, Union
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
|
| 23 |
+
from ...image_processing_utils import BaseImageProcessor, BatchFeature
|
| 24 |
+
from ...image_transforms import (
|
| 25 |
+
convert_to_rgb,
|
| 26 |
+
resize,
|
| 27 |
+
to_channel_dimension_format,
|
| 28 |
+
)
|
| 29 |
+
from ...image_utils import (
|
| 30 |
+
ChannelDimension,
|
| 31 |
+
ImageInput,
|
| 32 |
+
PILImageResampling,
|
| 33 |
+
infer_channel_dimension_format,
|
| 34 |
+
is_scaled_image,
|
| 35 |
+
make_flat_list_of_images,
|
| 36 |
+
to_numpy_array,
|
| 37 |
+
valid_images,
|
| 38 |
+
validate_preprocess_arguments,
|
| 39 |
+
)
|
| 40 |
+
from ...utils import TensorType, filter_out_non_signature_kwargs, is_vision_available, logging
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
logger = logging.get_logger(__name__)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
if is_vision_available():
|
| 47 |
+
from PIL import Image
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@lru_cache(maxsize=256)
|
| 51 |
+
def get_image_size_for_max_num_patches(
|
| 52 |
+
image_height: int, image_width: int, patch_size: int, max_num_patches: int, eps: float = 1e-5
|
| 53 |
+
) -> tuple[int, int]:
|
| 54 |
+
"""
|
| 55 |
+
Determine image size based on max number of patches, ensure dimensions are divisible by patch size and image is at least 1 patch.
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
image_height (`int`):
|
| 59 |
+
Original image height.
|
| 60 |
+
image_width (`int`):
|
| 61 |
+
Original image width.
|
| 62 |
+
patch_size (`int`):
|
| 63 |
+
Patch size for processing.
|
| 64 |
+
max_num_patches (`int`):
|
| 65 |
+
Maximum number of patches.
|
| 66 |
+
eps (`float`):
|
| 67 |
+
Small threshold for binary search.
|
| 68 |
+
|
| 69 |
+
Returns:
|
| 70 |
+
Tuple: (target_height, target_width)
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
def get_scaled_image_size(scale: float, size: int, patch_size: int) -> int:
|
| 74 |
+
scaled_size = size * scale
|
| 75 |
+
scaled_size = math.ceil(scaled_size / patch_size) * patch_size # make divisible by patch_size
|
| 76 |
+
scaled_size = max(patch_size, scaled_size) # ensure at least 1 patch
|
| 77 |
+
return int(scaled_size)
|
| 78 |
+
|
| 79 |
+
# Binary search for optimal scale
|
| 80 |
+
scale_min, scale_max = eps / 10, 100.0
|
| 81 |
+
while (scale_max - scale_min) >= eps:
|
| 82 |
+
scale = (scale_min + scale_max) / 2
|
| 83 |
+
target_height = get_scaled_image_size(scale, image_height, patch_size)
|
| 84 |
+
target_width = get_scaled_image_size(scale, image_width, patch_size)
|
| 85 |
+
num_patches = (target_height / patch_size) * (target_width / patch_size)
|
| 86 |
+
|
| 87 |
+
if num_patches <= max_num_patches:
|
| 88 |
+
scale_min = scale
|
| 89 |
+
else:
|
| 90 |
+
scale_max = scale
|
| 91 |
+
|
| 92 |
+
scale = scale_min
|
| 93 |
+
target_height = get_scaled_image_size(scale, image_height, patch_size)
|
| 94 |
+
target_width = get_scaled_image_size(scale, image_width, patch_size)
|
| 95 |
+
return target_height, target_width
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def convert_image_to_patches(image: np.ndarray, patch_size: int) -> np.ndarray:
|
| 99 |
+
"""
|
| 100 |
+
Convert 3D array image of shape (image_height, image_width, num_channels) into 2D array of patches of shape
|
| 101 |
+
(num_patches_height * num_patches_width, patch_size * patch_size * num_channels).
|
| 102 |
+
"""
|
| 103 |
+
image_height, image_width, num_channels = image.shape
|
| 104 |
+
num_patches_height = image_height // patch_size
|
| 105 |
+
num_patches_width = image_width // patch_size
|
| 106 |
+
patched_image = image.reshape(num_patches_height, patch_size, num_patches_width, patch_size, num_channels)
|
| 107 |
+
patched_image = patched_image.transpose(0, 2, 1, 3, 4)
|
| 108 |
+
patched_image = patched_image.reshape(num_patches_height * num_patches_width, -1)
|
| 109 |
+
return patched_image
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def pad_along_first_dim(array: np.ndarray, target_length: int, pad_value: int = 0) -> tuple[np.ndarray, np.ndarray]:
|
| 113 |
+
"""
|
| 114 |
+
Pad the array along the first dimension.
|
| 115 |
+
"""
|
| 116 |
+
current_length = array.shape[0]
|
| 117 |
+
padding_length = target_length - current_length
|
| 118 |
+
mask = np.ones((target_length,), dtype=np.int32)
|
| 119 |
+
if padding_length > 0:
|
| 120 |
+
paddings = [(0, padding_length)] + [(0, 0)] * (array.ndim - 1)
|
| 121 |
+
array = np.pad(array, paddings, mode="constant", constant_values=pad_value)
|
| 122 |
+
mask[-padding_length:] = 0
|
| 123 |
+
return array, mask
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class Siglip2ImageProcessor(BaseImageProcessor):
|
| 127 |
+
r"""
|
| 128 |
+
Constructs a SigLIP2 image processor.
|
| 129 |
+
|
| 130 |
+
Args:
|
| 131 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
| 132 |
+
Whether to resize the image's dimensions to fit `max_num_patches` according to given `patch_size`.
|
| 133 |
+
Can be overridden by `do_resize` in the `preprocess` method.
|
| 134 |
+
resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
|
| 135 |
+
Resampling filter to use if resizing the image. Can be overridden by `resample` in the `preprocess` method.
|
| 136 |
+
do_rescale (`bool`, *optional*, defaults to `True`):
|
| 137 |
+
Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in
|
| 138 |
+
the `preprocess` method.
|
| 139 |
+
rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
|
| 140 |
+
Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in the `preprocess`
|
| 141 |
+
method.
|
| 142 |
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
| 143 |
+
Whether to normalize the image by the specified mean and standard deviation. Can be overridden by
|
| 144 |
+
`do_normalize` in the `preprocess` method.
|
| 145 |
+
image_mean (`float` or `list[float]`, *optional*, defaults to `[0.5, 0.5, 0.5]`):
|
| 146 |
+
Mean to use if normalizing the image. This is a float or list of floats the length of the number of
|
| 147 |
+
channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
|
| 148 |
+
image_std (`float` or `list[float]`, *optional*, defaults to `[0.5, 0.5, 0.5]`):
|
| 149 |
+
Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
|
| 150 |
+
number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
|
| 151 |
+
Can be overridden by the `image_std` parameter in the `preprocess` method.
|
| 152 |
+
do_convert_rgb (`bool`, *optional*, defaults to `True`):
|
| 153 |
+
Whether to convert the image to RGB.
|
| 154 |
+
patch_size (`int`, *optional*, defaults to 16):
|
| 155 |
+
The size (resolution) of each patch the image will be split to.
|
| 156 |
+
max_num_patches (`int`, *optional*, defaults to 256):
|
| 157 |
+
The image will be resized to have at most this number of patches,
|
| 158 |
+
and then padded in "patch" dimension to match this number exactly.
|
| 159 |
+
"""
|
| 160 |
+
|
| 161 |
+
model_input_names = ["pixel_values", "pixel_attention_mask", "spatial_shapes"]
|
| 162 |
+
|
| 163 |
+
def __init__(
|
| 164 |
+
self,
|
| 165 |
+
do_resize: bool = True,
|
| 166 |
+
resample: "PILImageResampling" = PILImageResampling.BILINEAR,
|
| 167 |
+
do_rescale: bool = True,
|
| 168 |
+
rescale_factor: float = 1 / 255,
|
| 169 |
+
do_normalize: bool = True,
|
| 170 |
+
image_mean: Optional[Union[float, list[float]]] = None,
|
| 171 |
+
image_std: Optional[Union[float, list[float]]] = None,
|
| 172 |
+
do_convert_rgb: Optional[bool] = None,
|
| 173 |
+
patch_size: int = 16,
|
| 174 |
+
max_num_patches: int = 256,
|
| 175 |
+
**kwargs,
|
| 176 |
+
):
|
| 177 |
+
super().__init__(**kwargs)
|
| 178 |
+
|
| 179 |
+
image_mean = image_mean if image_mean is not None else [0.5, 0.5, 0.5]
|
| 180 |
+
image_std = image_std if image_std is not None else [0.5, 0.5, 0.5]
|
| 181 |
+
|
| 182 |
+
self.do_resize = do_resize
|
| 183 |
+
self.resample = resample
|
| 184 |
+
self.do_rescale = do_rescale
|
| 185 |
+
self.rescale_factor = rescale_factor
|
| 186 |
+
self.do_normalize = do_normalize
|
| 187 |
+
self.image_mean = image_mean
|
| 188 |
+
self.image_std = image_std
|
| 189 |
+
self.do_convert_rgb = do_convert_rgb
|
| 190 |
+
self.patch_size = patch_size
|
| 191 |
+
self.max_num_patches = max_num_patches
|
| 192 |
+
|
| 193 |
+
@filter_out_non_signature_kwargs()
|
| 194 |
+
def preprocess(
|
| 195 |
+
self,
|
| 196 |
+
images: ImageInput,
|
| 197 |
+
do_resize: Optional[bool] = None,
|
| 198 |
+
resample: Optional["PILImageResampling"] = None,
|
| 199 |
+
do_rescale: Optional[bool] = None,
|
| 200 |
+
rescale_factor: Optional[float] = None,
|
| 201 |
+
do_normalize: Optional[bool] = None,
|
| 202 |
+
image_mean: Optional[Union[float, list[float]]] = None,
|
| 203 |
+
image_std: Optional[Union[float, list[float]]] = None,
|
| 204 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 205 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 206 |
+
do_convert_rgb: Optional[bool] = None,
|
| 207 |
+
patch_size: Optional[int] = None,
|
| 208 |
+
max_num_patches: Optional[int] = None,
|
| 209 |
+
) -> "Image.Image":
|
| 210 |
+
"""
|
| 211 |
+
Preprocess an image or batch of images.
|
| 212 |
+
|
| 213 |
+
Args:
|
| 214 |
+
images (`ImageInput`):
|
| 215 |
+
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
|
| 216 |
+
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
| 217 |
+
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
|
| 218 |
+
Whether to resize the image.
|
| 219 |
+
size (`dict[str, int]`, *optional*, defaults to `self.size`):
|
| 220 |
+
Size of the image after resizing.
|
| 221 |
+
resample (`int`, *optional*, defaults to `self.resample`):
|
| 222 |
+
Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
|
| 223 |
+
has an effect if `do_resize` is set to `True`.
|
| 224 |
+
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
|
| 225 |
+
Whether to rescale the image.
|
| 226 |
+
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
|
| 227 |
+
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
|
| 228 |
+
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
|
| 229 |
+
Whether to normalize the image.
|
| 230 |
+
image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
|
| 231 |
+
Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
|
| 232 |
+
image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
|
| 233 |
+
Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
|
| 234 |
+
`True`.
|
| 235 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
| 236 |
+
The type of tensors to return. Can be one of:
|
| 237 |
+
- Unset: Return a list of `np.ndarray`.
|
| 238 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
| 239 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
| 240 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
| 241 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
| 242 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 243 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
| 244 |
+
from the input image. Can be one of:
|
| 245 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 246 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 247 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 248 |
+
do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
|
| 249 |
+
Whether to convert the image to RGB.
|
| 250 |
+
patch_size (`int`, *optional*, defaults to `self.patch_size`):
|
| 251 |
+
Patch size for processing, same as the patch size used in the model.
|
| 252 |
+
max_num_patches (`int`, *optional*, defaults to `self.max_num_patches`):
|
| 253 |
+
Maximum number of patches per image, the image will be resized to have at most this number of patches.
|
| 254 |
+
"""
|
| 255 |
+
do_resize = do_resize if do_resize is not None else self.do_resize
|
| 256 |
+
resample = resample if resample is not None else self.resample
|
| 257 |
+
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
|
| 258 |
+
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
|
| 259 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
| 260 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
| 261 |
+
image_std = image_std if image_std is not None else self.image_std
|
| 262 |
+
do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
|
| 263 |
+
patch_size = patch_size if patch_size is not None else self.patch_size
|
| 264 |
+
max_num_patches = max_num_patches if max_num_patches is not None else self.max_num_patches
|
| 265 |
+
|
| 266 |
+
# Explicitly specify data format to be channels last for image preprocessing.
|
| 267 |
+
# Image processor does not support different output formats, because it returns patches.
|
| 268 |
+
data_format = ChannelDimension.LAST
|
| 269 |
+
|
| 270 |
+
images = self.fetch_images(images)
|
| 271 |
+
images = make_flat_list_of_images(images)
|
| 272 |
+
|
| 273 |
+
if not valid_images(images):
|
| 274 |
+
raise ValueError(
|
| 275 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
| 276 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
| 277 |
+
)
|
| 278 |
+
validate_preprocess_arguments(
|
| 279 |
+
do_rescale=do_rescale,
|
| 280 |
+
rescale_factor=rescale_factor,
|
| 281 |
+
do_normalize=do_normalize,
|
| 282 |
+
image_mean=image_mean,
|
| 283 |
+
image_std=image_std,
|
| 284 |
+
)
|
| 285 |
+
if do_convert_rgb:
|
| 286 |
+
images = [convert_to_rgb(image) for image in images]
|
| 287 |
+
|
| 288 |
+
# All transformations expect numpy arrays.
|
| 289 |
+
images = [to_numpy_array(image) for image in images]
|
| 290 |
+
|
| 291 |
+
if do_rescale and is_scaled_image(images[0]):
|
| 292 |
+
logger.warning_once(
|
| 293 |
+
"It looks like you are trying to rescale already rescaled images. If the input"
|
| 294 |
+
" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
if input_data_format is None:
|
| 298 |
+
# We assume that all images have the same channel dimension format.
|
| 299 |
+
input_data_format = infer_channel_dimension_format(images[0])
|
| 300 |
+
|
| 301 |
+
pixel_masks = []
|
| 302 |
+
pixel_values = []
|
| 303 |
+
spatial_shapes = []
|
| 304 |
+
|
| 305 |
+
for image in images:
|
| 306 |
+
image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
|
| 307 |
+
|
| 308 |
+
if do_resize:
|
| 309 |
+
height, width = get_image_size_for_max_num_patches(
|
| 310 |
+
image_height=image.shape[0],
|
| 311 |
+
image_width=image.shape[1],
|
| 312 |
+
patch_size=patch_size,
|
| 313 |
+
max_num_patches=max_num_patches,
|
| 314 |
+
)
|
| 315 |
+
image = resize(image=image, size=(height, width), resample=resample, input_data_format=data_format)
|
| 316 |
+
|
| 317 |
+
if do_rescale:
|
| 318 |
+
image = self.rescale(image=image, scale=rescale_factor, input_data_format=data_format)
|
| 319 |
+
|
| 320 |
+
if do_normalize:
|
| 321 |
+
image = self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=data_format)
|
| 322 |
+
|
| 323 |
+
patches = convert_image_to_patches(image, patch_size)
|
| 324 |
+
patches, mask = pad_along_first_dim(patches, max_num_patches)
|
| 325 |
+
num_patches_height = image.shape[0] // patch_size
|
| 326 |
+
num_patches_width = image.shape[1] // patch_size
|
| 327 |
+
|
| 328 |
+
spatial_shapes.append((num_patches_height, num_patches_width))
|
| 329 |
+
pixel_values.append(patches)
|
| 330 |
+
pixel_masks.append(mask)
|
| 331 |
+
|
| 332 |
+
batch_feature = BatchFeature(
|
| 333 |
+
data={
|
| 334 |
+
"pixel_values": pixel_values,
|
| 335 |
+
"pixel_attention_mask": pixel_masks,
|
| 336 |
+
"spatial_shapes": spatial_shapes,
|
| 337 |
+
},
|
| 338 |
+
tensor_type=return_tensors,
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
return batch_feature
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
__all__ = ["Siglip2ImageProcessor"]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/siglip2/image_processing_siglip2_fast.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Fast Image processor class for SigLIP2."""
|
| 16 |
+
|
| 17 |
+
from typing import Optional, Union
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
from ...image_processing_utils import BatchFeature
|
| 22 |
+
from ...image_processing_utils_fast import (
|
| 23 |
+
BaseImageProcessorFast,
|
| 24 |
+
DefaultFastImageProcessorKwargs,
|
| 25 |
+
SizeDict,
|
| 26 |
+
)
|
| 27 |
+
from ...image_utils import (
|
| 28 |
+
ImageInput,
|
| 29 |
+
PILImageResampling,
|
| 30 |
+
)
|
| 31 |
+
from ...processing_utils import Unpack
|
| 32 |
+
from ...utils import (
|
| 33 |
+
TensorType,
|
| 34 |
+
auto_docstring,
|
| 35 |
+
is_torch_available,
|
| 36 |
+
is_torchvision_available,
|
| 37 |
+
is_torchvision_v2_available,
|
| 38 |
+
logging,
|
| 39 |
+
)
|
| 40 |
+
from .image_processing_siglip2 import get_image_size_for_max_num_patches
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
if is_torch_available():
|
| 44 |
+
import torch
|
| 45 |
+
|
| 46 |
+
if is_torchvision_available():
|
| 47 |
+
if is_torchvision_v2_available():
|
| 48 |
+
from torchvision.transforms.v2 import functional as F
|
| 49 |
+
else:
|
| 50 |
+
from torchvision.transforms import functional as F
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
logger = logging.get_logger(__name__)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def convert_image_to_patches(image: "torch.Tensor", patch_size: int) -> "torch.Tensor":
|
| 57 |
+
"""
|
| 58 |
+
Convert 3D tensor image of shape (num_channels, image_height, image_width) into 2D tensor of patches of shape
|
| 59 |
+
(num_patches_height * num_patches_width, patch_size * patch_size * num_channels).
|
| 60 |
+
"""
|
| 61 |
+
num_channels, image_height, image_width = image.shape
|
| 62 |
+
num_patches_height = image_height // patch_size
|
| 63 |
+
num_patches_width = image_width // patch_size
|
| 64 |
+
patched_image = image.reshape(num_channels, num_patches_height, patch_size, num_patches_width, patch_size)
|
| 65 |
+
patched_image = patched_image.permute(1, 3, 2, 4, 0)
|
| 66 |
+
patched_image = patched_image.reshape(num_patches_height * num_patches_width, -1)
|
| 67 |
+
return patched_image
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def pad_along_first_dim(
|
| 71 |
+
tensor: "torch.Tensor", target_length: int, pad_value: int = 0
|
| 72 |
+
) -> tuple["torch.Tensor", "torch.Tensor"]:
|
| 73 |
+
"""
|
| 74 |
+
Pad the tensor along the first dimension.
|
| 75 |
+
"""
|
| 76 |
+
current_length = tensor.shape[0]
|
| 77 |
+
padding_length = target_length - current_length
|
| 78 |
+
mask = torch.ones((target_length,), dtype=torch.int32)
|
| 79 |
+
if padding_length > 0:
|
| 80 |
+
padding = [0, 0] * (tensor.ndim - 1) + [0, padding_length]
|
| 81 |
+
tensor = torch.nn.functional.pad(tensor, padding, mode="constant", value=pad_value)
|
| 82 |
+
mask[-padding_length:] = 0
|
| 83 |
+
return tensor, mask
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class Siglip2FastImageProcessorKwargs(DefaultFastImageProcessorKwargs):
|
| 87 |
+
"""
|
| 88 |
+
patch_size (`int`, *optional*, defaults to 16):
|
| 89 |
+
The size (resolution) of each patch the image will be split to.
|
| 90 |
+
max_num_patches (`int`, *optional*, defaults to 256):
|
| 91 |
+
The image will be resized to have at most this number of patches,
|
| 92 |
+
and then padded in "patch" dimension to match this number exactly.
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
patch_size: Optional[int]
|
| 96 |
+
max_num_patches: Optional[int]
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
@auto_docstring
|
| 100 |
+
class Siglip2ImageProcessorFast(BaseImageProcessorFast):
|
| 101 |
+
resample = PILImageResampling.BILINEAR
|
| 102 |
+
image_mean = [0.5, 0.5, 0.5]
|
| 103 |
+
image_std = [0.5, 0.5, 0.5]
|
| 104 |
+
do_resize = True
|
| 105 |
+
do_rescale = True
|
| 106 |
+
do_normalize = True
|
| 107 |
+
patch_size = 16
|
| 108 |
+
max_num_patches = 256
|
| 109 |
+
valid_kwargs = Siglip2FastImageProcessorKwargs
|
| 110 |
+
unused_kwargs = ["size", "do_center_crop", "crop_size"]
|
| 111 |
+
|
| 112 |
+
def __init__(self, **kwargs: Unpack[Siglip2FastImageProcessorKwargs]):
|
| 113 |
+
super().__init__(**kwargs)
|
| 114 |
+
|
| 115 |
+
def _validate_preprocess_kwargs(self, **kwargs) -> tuple:
|
| 116 |
+
# Remove do_resize from kwargs to not raise an error as size is None
|
| 117 |
+
kwargs.pop("do_resize", None)
|
| 118 |
+
return super()._validate_preprocess_kwargs(**kwargs)
|
| 119 |
+
|
| 120 |
+
@auto_docstring
|
| 121 |
+
def preprocess(self, images: ImageInput, **kwargs: Unpack[Siglip2FastImageProcessorKwargs]) -> BatchFeature:
|
| 122 |
+
return super().preprocess(images, **kwargs)
|
| 123 |
+
|
| 124 |
+
def _preprocess(
|
| 125 |
+
self,
|
| 126 |
+
images: list["torch.Tensor"],
|
| 127 |
+
do_resize: bool,
|
| 128 |
+
patch_size: int,
|
| 129 |
+
max_num_patches: int,
|
| 130 |
+
interpolation: Optional["F.InterpolationMode"],
|
| 131 |
+
do_rescale: bool,
|
| 132 |
+
rescale_factor: float,
|
| 133 |
+
do_normalize: bool,
|
| 134 |
+
image_mean: Optional[Union[float, list[float]]],
|
| 135 |
+
image_std: Optional[Union[float, list[float]]],
|
| 136 |
+
return_tensors: Optional[Union[str, TensorType]],
|
| 137 |
+
**kwargs,
|
| 138 |
+
) -> BatchFeature:
|
| 139 |
+
pixel_masks = []
|
| 140 |
+
pixel_values = []
|
| 141 |
+
spatial_shapes = []
|
| 142 |
+
|
| 143 |
+
for image in images:
|
| 144 |
+
if do_resize:
|
| 145 |
+
height, width = get_image_size_for_max_num_patches(
|
| 146 |
+
image_height=image.shape[1],
|
| 147 |
+
image_width=image.shape[2],
|
| 148 |
+
patch_size=patch_size,
|
| 149 |
+
max_num_patches=max_num_patches,
|
| 150 |
+
)
|
| 151 |
+
side_dict = SizeDict(height=height, width=width)
|
| 152 |
+
image = self.resize(image=image, size=side_dict, interpolation=interpolation)
|
| 153 |
+
|
| 154 |
+
image = self.rescale_and_normalize(image, do_rescale, rescale_factor, do_normalize, image_mean, image_std)
|
| 155 |
+
|
| 156 |
+
# (num_channels, height, width) -> (num_patches, patch_size * patch_size * num_channels)
|
| 157 |
+
patches = convert_image_to_patches(image, patch_size)
|
| 158 |
+
patches, mask = pad_along_first_dim(patches, max_num_patches)
|
| 159 |
+
|
| 160 |
+
num_patches_height = image.shape[1] // patch_size
|
| 161 |
+
num_patches_width = image.shape[2] // patch_size
|
| 162 |
+
|
| 163 |
+
spatial_shapes.append((num_patches_height, num_patches_width))
|
| 164 |
+
pixel_values.append(patches)
|
| 165 |
+
pixel_masks.append(mask)
|
| 166 |
+
|
| 167 |
+
pixel_values = torch.stack(pixel_values)
|
| 168 |
+
pixel_masks = torch.stack(pixel_masks)
|
| 169 |
+
spatial_shapes = torch.tensor(spatial_shapes)
|
| 170 |
+
|
| 171 |
+
batch_feature = BatchFeature(
|
| 172 |
+
data={
|
| 173 |
+
"pixel_values": pixel_values,
|
| 174 |
+
"pixel_attention_mask": pixel_masks,
|
| 175 |
+
"spatial_shapes": spatial_shapes,
|
| 176 |
+
},
|
| 177 |
+
tensor_type=return_tensors,
|
| 178 |
+
)
|
| 179 |
+
return batch_feature
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
__all__ = ["Siglip2ImageProcessorFast"]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/siglip2/modeling_siglip2.py
ADDED
|
@@ -0,0 +1,1303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/siglip2/modular_siglip2.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_siglip2.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# coding=utf-8
|
| 8 |
+
# Copyright 2025 The HuggingFace Inc. team.
|
| 9 |
+
#
|
| 10 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 11 |
+
# you may not use this file except in compliance with the License.
|
| 12 |
+
# You may obtain a copy of the License at
|
| 13 |
+
#
|
| 14 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 15 |
+
#
|
| 16 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 17 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 18 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 19 |
+
# See the License for the specific language governing permissions and
|
| 20 |
+
# limitations under the License.
|
| 21 |
+
import math
|
| 22 |
+
import warnings
|
| 23 |
+
from dataclasses import dataclass
|
| 24 |
+
from typing import Any, Callable, Optional, Union
|
| 25 |
+
|
| 26 |
+
import numpy as np
|
| 27 |
+
import torch
|
| 28 |
+
import torch.nn as nn
|
| 29 |
+
import torch.nn.functional as F
|
| 30 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 31 |
+
from torch.nn.init import _calculate_fan_in_and_fan_out
|
| 32 |
+
|
| 33 |
+
from ...activations import ACT2FN
|
| 34 |
+
from ...modeling_attn_mask_utils import _prepare_4d_attention_mask
|
| 35 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 36 |
+
from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, ImageClassifierOutput
|
| 37 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 38 |
+
from ...utils import ModelOutput, auto_docstring, can_return_tuple
|
| 39 |
+
from .configuration_siglip2 import Siglip2Config, Siglip2TextConfig, Siglip2VisionConfig
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@dataclass
|
| 43 |
+
@auto_docstring(
|
| 44 |
+
custom_intro="""
|
| 45 |
+
Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
|
| 46 |
+
"""
|
| 47 |
+
)
|
| 48 |
+
class Siglip2VisionOutput(ModelOutput):
|
| 49 |
+
r"""
|
| 50 |
+
image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
|
| 51 |
+
The image embeddings obtained by applying the projection layer to the pooler_output.
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
image_embeds: Optional[torch.FloatTensor] = None
|
| 55 |
+
last_hidden_state: Optional[torch.FloatTensor] = None
|
| 56 |
+
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 57 |
+
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@dataclass
|
| 61 |
+
@auto_docstring(
|
| 62 |
+
custom_intro="""
|
| 63 |
+
Base class for text model's outputs that also contains a pooling of the last hidden states.
|
| 64 |
+
"""
|
| 65 |
+
)
|
| 66 |
+
class Siglip2TextOutput(ModelOutput):
|
| 67 |
+
r"""
|
| 68 |
+
text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
|
| 69 |
+
The text embeddings obtained by applying the projection layer to the pooler_output.
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
text_embeds: Optional[torch.FloatTensor] = None
|
| 73 |
+
last_hidden_state: Optional[torch.FloatTensor] = None
|
| 74 |
+
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 75 |
+
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@dataclass
|
| 79 |
+
@auto_docstring
|
| 80 |
+
class Siglip2Output(ModelOutput):
|
| 81 |
+
r"""
|
| 82 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
|
| 83 |
+
Contrastive loss for image-text similarity.
|
| 84 |
+
logits_per_image (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
|
| 85 |
+
The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
|
| 86 |
+
similarity scores.
|
| 87 |
+
logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
|
| 88 |
+
The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
|
| 89 |
+
similarity scores.
|
| 90 |
+
text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
| 91 |
+
The text embeddings obtained by applying the projection layer to the pooled output of [`Siglip2TextModel`].
|
| 92 |
+
image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
| 93 |
+
The image embeddings obtained by applying the projection layer to the pooled output of [`Siglip2VisionModel`].
|
| 94 |
+
text_model_output (`BaseModelOutputWithPooling`):
|
| 95 |
+
The output of the [`Siglip2TextModel`].
|
| 96 |
+
vision_model_output (`BaseModelOutputWithPooling`):
|
| 97 |
+
The output of the [`Siglip2VisionModel`].
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
loss: Optional[torch.FloatTensor] = None
|
| 101 |
+
logits_per_image: Optional[torch.FloatTensor] = None
|
| 102 |
+
logits_per_text: Optional[torch.FloatTensor] = None
|
| 103 |
+
text_embeds: Optional[torch.FloatTensor] = None
|
| 104 |
+
image_embeds: Optional[torch.FloatTensor] = None
|
| 105 |
+
text_model_output: BaseModelOutputWithPooling = None
|
| 106 |
+
vision_model_output: BaseModelOutputWithPooling = None
|
| 107 |
+
|
| 108 |
+
def to_tuple(self) -> tuple[Any]:
|
| 109 |
+
return tuple(
|
| 110 |
+
self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
|
| 111 |
+
for k in self.keys()
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class Siglip2VisionEmbeddings(nn.Module):
|
| 116 |
+
def __init__(self, config: Siglip2VisionConfig):
|
| 117 |
+
super().__init__()
|
| 118 |
+
self.config = config
|
| 119 |
+
self.embed_dim = config.hidden_size
|
| 120 |
+
self.patch_size = config.patch_size
|
| 121 |
+
|
| 122 |
+
self.patch_embedding = nn.Linear(
|
| 123 |
+
in_features=config.num_channels * self.patch_size * self.patch_size,
|
| 124 |
+
out_features=self.embed_dim,
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
self.num_patches = config.num_patches
|
| 128 |
+
self.position_embedding_size = int(self.num_patches**0.5)
|
| 129 |
+
self.position_embedding = nn.Embedding(self.num_patches, self.embed_dim)
|
| 130 |
+
|
| 131 |
+
@staticmethod
|
| 132 |
+
def resize_positional_embeddings(
|
| 133 |
+
positional_embeddings: torch.Tensor,
|
| 134 |
+
spatial_shapes: torch.LongTensor,
|
| 135 |
+
max_length: int,
|
| 136 |
+
) -> torch.Tensor:
|
| 137 |
+
"""
|
| 138 |
+
Resize positional embeddings to image-specific size and pad to a fixed size.
|
| 139 |
+
|
| 140 |
+
Args:
|
| 141 |
+
positional_embeddings (`torch.Tensor`):
|
| 142 |
+
Position embeddings of shape (height, width, embed_dim)
|
| 143 |
+
spatial_shapes (`torch.LongTensor`):
|
| 144 |
+
Spatial shapes of shape (batch_size, 2) to resize the positional embeddings to
|
| 145 |
+
max_length (`int`):
|
| 146 |
+
Maximum length of the positional embeddings to pad resized positional embeddings to
|
| 147 |
+
|
| 148 |
+
Returns:
|
| 149 |
+
`torch.Tensor`: Embeddings of shape (batch_size, max_length, embed_dim)
|
| 150 |
+
"""
|
| 151 |
+
batch_size = spatial_shapes.shape[0]
|
| 152 |
+
embed_dim = positional_embeddings.shape[-1]
|
| 153 |
+
source_dtype = positional_embeddings.dtype
|
| 154 |
+
|
| 155 |
+
resulted_positional_embeddings = torch.empty(
|
| 156 |
+
(batch_size, max_length, embed_dim),
|
| 157 |
+
device=positional_embeddings.device,
|
| 158 |
+
dtype=source_dtype,
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
# (height, width, embed_dim) -> (1, embed_dim, height, width) for interpolation
|
| 162 |
+
positional_embeddings = positional_embeddings.permute(2, 0, 1).unsqueeze(0)
|
| 163 |
+
|
| 164 |
+
# Upcast to float32 on CPU because antialias is not supported for bfloat16/float16 on CPU
|
| 165 |
+
if positional_embeddings.device.type == "cpu":
|
| 166 |
+
positional_embeddings = positional_embeddings.to(torch.float32)
|
| 167 |
+
|
| 168 |
+
for i in range(batch_size):
|
| 169 |
+
# (1, dim, height, width) -> (1, dim, target_height, target_width)
|
| 170 |
+
height, width = spatial_shapes[i]
|
| 171 |
+
resized_embeddings = F.interpolate(
|
| 172 |
+
positional_embeddings,
|
| 173 |
+
size=(height, width),
|
| 174 |
+
mode="bilinear",
|
| 175 |
+
align_corners=False,
|
| 176 |
+
antialias=True,
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
# (1, dim, target_height, target_width) -> (target_height * target_width, dim)
|
| 180 |
+
resized_embeddings = resized_embeddings.reshape(embed_dim, height * width).transpose(0, 1)
|
| 181 |
+
|
| 182 |
+
# Cast to original dtype
|
| 183 |
+
resized_embeddings = resized_embeddings.to(source_dtype)
|
| 184 |
+
|
| 185 |
+
resulted_positional_embeddings[i, : height * width] = resized_embeddings
|
| 186 |
+
resulted_positional_embeddings[i, height * width :] = resized_embeddings[0]
|
| 187 |
+
|
| 188 |
+
return resulted_positional_embeddings
|
| 189 |
+
|
| 190 |
+
def forward(self, pixel_values: torch.FloatTensor, spatial_shapes: torch.LongTensor) -> torch.Tensor:
|
| 191 |
+
"""
|
| 192 |
+
Args:
|
| 193 |
+
pixel_values (`torch.FloatTensor`):
|
| 194 |
+
Pixel values of shape (batch_size, max_num_patches, num_channels * patch_size * patch_size)
|
| 195 |
+
spatial_shapes (`list[tuple[int, int]]`):
|
| 196 |
+
Spatial shapes of shape (batch_size, 2) to resize the positional embeddings to
|
| 197 |
+
"""
|
| 198 |
+
|
| 199 |
+
# Apply patch embeddings to already patchified pixel values
|
| 200 |
+
target_dtype = self.patch_embedding.weight.dtype
|
| 201 |
+
patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype))
|
| 202 |
+
|
| 203 |
+
# Get positional resized and padded positional embeddings
|
| 204 |
+
positional_embeddings = self.position_embedding.weight.reshape(
|
| 205 |
+
self.position_embedding_size, self.position_embedding_size, -1
|
| 206 |
+
)
|
| 207 |
+
resized_positional_embeddings = self.resize_positional_embeddings(
|
| 208 |
+
positional_embeddings, spatial_shapes, max_length=pixel_values.shape[1]
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
# Add positional embeddings to patch embeddings
|
| 212 |
+
embeddings = patch_embeds + resized_positional_embeddings
|
| 213 |
+
return embeddings
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def eager_attention_forward(
|
| 217 |
+
module: nn.Module,
|
| 218 |
+
query: torch.Tensor,
|
| 219 |
+
key: torch.Tensor,
|
| 220 |
+
value: torch.Tensor,
|
| 221 |
+
attention_mask: Optional[torch.Tensor],
|
| 222 |
+
scaling: float,
|
| 223 |
+
dropout: float = 0.0,
|
| 224 |
+
**kwargs,
|
| 225 |
+
):
|
| 226 |
+
attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling
|
| 227 |
+
if attention_mask is not None:
|
| 228 |
+
attn_weights = attn_weights + attention_mask
|
| 229 |
+
|
| 230 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 231 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 232 |
+
|
| 233 |
+
attn_output = torch.matmul(attn_weights, value)
|
| 234 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 235 |
+
|
| 236 |
+
return attn_output, attn_weights
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
class Siglip2Attention(nn.Module):
|
| 240 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 241 |
+
|
| 242 |
+
def __init__(self, config):
|
| 243 |
+
super().__init__()
|
| 244 |
+
self.config = config
|
| 245 |
+
self.embed_dim = config.hidden_size
|
| 246 |
+
self.num_heads = config.num_attention_heads
|
| 247 |
+
self.head_dim = self.embed_dim // self.num_heads
|
| 248 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
| 249 |
+
raise ValueError(
|
| 250 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
|
| 251 |
+
f" {self.num_heads})."
|
| 252 |
+
)
|
| 253 |
+
self.scale = self.head_dim**-0.5
|
| 254 |
+
self.dropout = config.attention_dropout
|
| 255 |
+
self.is_causal = False
|
| 256 |
+
|
| 257 |
+
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 258 |
+
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 259 |
+
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 260 |
+
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 261 |
+
|
| 262 |
+
def forward(
|
| 263 |
+
self,
|
| 264 |
+
hidden_states: torch.Tensor,
|
| 265 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 266 |
+
**kwargs,
|
| 267 |
+
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 268 |
+
"""Input shape: Batch x Time x Channel"""
|
| 269 |
+
|
| 270 |
+
batch_size, seq_length, embed_dim = hidden_states.shape
|
| 271 |
+
|
| 272 |
+
queries = self.q_proj(hidden_states)
|
| 273 |
+
keys = self.k_proj(hidden_states)
|
| 274 |
+
values = self.v_proj(hidden_states)
|
| 275 |
+
|
| 276 |
+
queries = queries.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
|
| 277 |
+
keys = keys.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
|
| 278 |
+
values = values.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
|
| 279 |
+
|
| 280 |
+
attention_interface: Callable = eager_attention_forward
|
| 281 |
+
if self.config._attn_implementation != "eager":
|
| 282 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 283 |
+
|
| 284 |
+
attn_output, attn_weights = attention_interface(
|
| 285 |
+
self,
|
| 286 |
+
queries,
|
| 287 |
+
keys,
|
| 288 |
+
values,
|
| 289 |
+
attention_mask,
|
| 290 |
+
is_causal=self.is_causal,
|
| 291 |
+
scaling=self.scale,
|
| 292 |
+
dropout=0.0 if not self.training else self.dropout,
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
attn_output = attn_output.reshape(batch_size, seq_length, embed_dim).contiguous()
|
| 296 |
+
attn_output = self.out_proj(attn_output)
|
| 297 |
+
|
| 298 |
+
return attn_output, attn_weights
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
class Siglip2MLP(nn.Module):
|
| 302 |
+
def __init__(self, config):
|
| 303 |
+
super().__init__()
|
| 304 |
+
self.config = config
|
| 305 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
| 306 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 307 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 308 |
+
|
| 309 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 310 |
+
hidden_states = self.fc1(hidden_states)
|
| 311 |
+
hidden_states = self.activation_fn(hidden_states)
|
| 312 |
+
hidden_states = self.fc2(hidden_states)
|
| 313 |
+
return hidden_states
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
class Siglip2EncoderLayer(GradientCheckpointingLayer):
|
| 317 |
+
def __init__(self, config: Union[Siglip2VisionConfig, Siglip2TextConfig]):
|
| 318 |
+
super().__init__()
|
| 319 |
+
self.embed_dim = config.hidden_size
|
| 320 |
+
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 321 |
+
self.self_attn = Siglip2Attention(config)
|
| 322 |
+
self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 323 |
+
self.mlp = Siglip2MLP(config)
|
| 324 |
+
|
| 325 |
+
def forward(
|
| 326 |
+
self,
|
| 327 |
+
hidden_states: torch.Tensor,
|
| 328 |
+
attention_mask: torch.Tensor,
|
| 329 |
+
output_attentions: Optional[bool] = False,
|
| 330 |
+
) -> tuple[torch.FloatTensor]:
|
| 331 |
+
"""
|
| 332 |
+
Args:
|
| 333 |
+
hidden_states (`torch.FloatTensor`):
|
| 334 |
+
Input to the layer of shape `(batch, seq_len, embed_dim)`.
|
| 335 |
+
attention_mask (`torch.FloatTensor`):
|
| 336 |
+
Attention mask of shape `(batch, 1, q_len, k_v_seq_len)` where padding elements are indicated by very large negative values.
|
| 337 |
+
output_attentions (`bool`, *optional*, defaults to `False`):
|
| 338 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 339 |
+
returned tensors for more detail.
|
| 340 |
+
"""
|
| 341 |
+
residual = hidden_states
|
| 342 |
+
|
| 343 |
+
hidden_states = self.layer_norm1(hidden_states)
|
| 344 |
+
hidden_states, attn_weights = self.self_attn(
|
| 345 |
+
hidden_states=hidden_states,
|
| 346 |
+
attention_mask=attention_mask,
|
| 347 |
+
output_attentions=output_attentions,
|
| 348 |
+
)
|
| 349 |
+
hidden_states = residual + hidden_states
|
| 350 |
+
|
| 351 |
+
residual = hidden_states
|
| 352 |
+
hidden_states = self.layer_norm2(hidden_states)
|
| 353 |
+
hidden_states = self.mlp(hidden_states)
|
| 354 |
+
hidden_states = residual + hidden_states
|
| 355 |
+
|
| 356 |
+
outputs = (hidden_states,)
|
| 357 |
+
|
| 358 |
+
if output_attentions:
|
| 359 |
+
outputs += (attn_weights,)
|
| 360 |
+
|
| 361 |
+
return outputs
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
class Siglip2Encoder(nn.Module):
|
| 365 |
+
"""
|
| 366 |
+
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
|
| 367 |
+
[`Siglip2EncoderLayer`].
|
| 368 |
+
|
| 369 |
+
Args:
|
| 370 |
+
config: Siglip2Config
|
| 371 |
+
"""
|
| 372 |
+
|
| 373 |
+
def __init__(self, config: Siglip2Config):
|
| 374 |
+
super().__init__()
|
| 375 |
+
self.config = config
|
| 376 |
+
self.layers = nn.ModuleList([Siglip2EncoderLayer(config) for _ in range(config.num_hidden_layers)])
|
| 377 |
+
self.gradient_checkpointing = False
|
| 378 |
+
|
| 379 |
+
# Ignore copy
|
| 380 |
+
@can_return_tuple
|
| 381 |
+
def forward(
|
| 382 |
+
self,
|
| 383 |
+
inputs_embeds,
|
| 384 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 385 |
+
output_attentions: Optional[bool] = None,
|
| 386 |
+
output_hidden_states: Optional[bool] = None,
|
| 387 |
+
) -> BaseModelOutput:
|
| 388 |
+
r"""
|
| 389 |
+
Args:
|
| 390 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 391 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 392 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 393 |
+
than the model's internal embedding lookup matrix.
|
| 394 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 395 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 396 |
+
|
| 397 |
+
- 1 for tokens that are **not masked**,
|
| 398 |
+
- 0 for tokens that are **masked**.
|
| 399 |
+
|
| 400 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 401 |
+
output_attentions (`bool`, *optional*):
|
| 402 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 403 |
+
returned tensors for more detail.
|
| 404 |
+
output_hidden_states (`bool`, *optional*):
|
| 405 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 406 |
+
for more detail.
|
| 407 |
+
return_dict (`bool`, *optional*):
|
| 408 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 409 |
+
"""
|
| 410 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 411 |
+
output_hidden_states = (
|
| 412 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 413 |
+
)
|
| 414 |
+
|
| 415 |
+
encoder_states = () if output_hidden_states else None
|
| 416 |
+
all_attentions = () if output_attentions else None
|
| 417 |
+
|
| 418 |
+
hidden_states = inputs_embeds
|
| 419 |
+
for encoder_layer in self.layers:
|
| 420 |
+
if output_hidden_states:
|
| 421 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 422 |
+
|
| 423 |
+
layer_outputs = encoder_layer(
|
| 424 |
+
hidden_states,
|
| 425 |
+
attention_mask,
|
| 426 |
+
output_attentions=output_attentions,
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
hidden_states = layer_outputs[0]
|
| 430 |
+
|
| 431 |
+
if output_attentions:
|
| 432 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 433 |
+
|
| 434 |
+
if output_hidden_states:
|
| 435 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 436 |
+
|
| 437 |
+
return BaseModelOutput(
|
| 438 |
+
last_hidden_state=hidden_states,
|
| 439 |
+
hidden_states=encoder_states,
|
| 440 |
+
attentions=all_attentions,
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
class Siglip2VisionTransformer(nn.Module):
|
| 445 |
+
def __init__(self, config: Siglip2VisionConfig):
|
| 446 |
+
super().__init__()
|
| 447 |
+
self.config = config
|
| 448 |
+
embed_dim = config.hidden_size
|
| 449 |
+
|
| 450 |
+
self.embeddings = Siglip2VisionEmbeddings(config)
|
| 451 |
+
self.encoder = Siglip2Encoder(config)
|
| 452 |
+
self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
| 453 |
+
self.use_head = True if not hasattr(config, "vision_use_head") else config.vision_use_head
|
| 454 |
+
if self.use_head:
|
| 455 |
+
self.head = Siglip2MultiheadAttentionPoolingHead(config)
|
| 456 |
+
self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
|
| 457 |
+
|
| 458 |
+
@can_return_tuple
|
| 459 |
+
@auto_docstring
|
| 460 |
+
def forward(
|
| 461 |
+
self,
|
| 462 |
+
pixel_values: torch.FloatTensor,
|
| 463 |
+
attention_mask: torch.Tensor,
|
| 464 |
+
spatial_shapes: torch.LongTensor,
|
| 465 |
+
output_attentions: Optional[bool] = None,
|
| 466 |
+
output_hidden_states: Optional[bool] = None,
|
| 467 |
+
) -> BaseModelOutputWithPooling:
|
| 468 |
+
r"""
|
| 469 |
+
spatial_shapes (`torch.LongTensor` of shape `(batch_size, 2)`):
|
| 470 |
+
Tensor containing the spatial dimensions (height, width) of the input images.
|
| 471 |
+
"""
|
| 472 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 473 |
+
output_hidden_states = (
|
| 474 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 475 |
+
)
|
| 476 |
+
|
| 477 |
+
hidden_states = self.embeddings(pixel_values, spatial_shapes)
|
| 478 |
+
|
| 479 |
+
if attention_mask is not None and not self._use_flash_attention_2:
|
| 480 |
+
# [batch_size, seq_len] -> [batch_size, 1, tgt_seq_len, src_seq_len]
|
| 481 |
+
encoder_attention_mask = _prepare_4d_attention_mask(attention_mask, hidden_states.dtype)
|
| 482 |
+
else:
|
| 483 |
+
encoder_attention_mask = attention_mask
|
| 484 |
+
|
| 485 |
+
encoder_outputs: BaseModelOutput = self.encoder(
|
| 486 |
+
inputs_embeds=hidden_states,
|
| 487 |
+
attention_mask=encoder_attention_mask,
|
| 488 |
+
output_attentions=output_attentions,
|
| 489 |
+
output_hidden_states=output_hidden_states,
|
| 490 |
+
)
|
| 491 |
+
|
| 492 |
+
last_hidden_state = encoder_outputs.last_hidden_state
|
| 493 |
+
last_hidden_state = self.post_layernorm(last_hidden_state)
|
| 494 |
+
|
| 495 |
+
pooler_output = self.head(last_hidden_state, attention_mask) if self.use_head else None
|
| 496 |
+
|
| 497 |
+
return BaseModelOutputWithPooling(
|
| 498 |
+
last_hidden_state=last_hidden_state,
|
| 499 |
+
pooler_output=pooler_output,
|
| 500 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 501 |
+
attentions=encoder_outputs.attentions,
|
| 502 |
+
)
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
def _trunc_normal_(tensor, mean, std, a, b):
|
| 506 |
+
# Cut & paste from PyTorch official master until it's in a few official releases - RW
|
| 507 |
+
# Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
|
| 508 |
+
def norm_cdf(x):
|
| 509 |
+
# Computes standard normal cumulative distribution function
|
| 510 |
+
return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0
|
| 511 |
+
|
| 512 |
+
if (mean < a - 2 * std) or (mean > b + 2 * std):
|
| 513 |
+
warnings.warn(
|
| 514 |
+
"mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
|
| 515 |
+
"The distribution of values may be incorrect.",
|
| 516 |
+
stacklevel=2,
|
| 517 |
+
)
|
| 518 |
+
|
| 519 |
+
# Values are generated by using a truncated uniform distribution and
|
| 520 |
+
# then using the inverse CDF for the normal distribution.
|
| 521 |
+
# Get upper and lower cdf values
|
| 522 |
+
l = norm_cdf((a - mean) / std)
|
| 523 |
+
u = norm_cdf((b - mean) / std)
|
| 524 |
+
|
| 525 |
+
# Uniformly fill tensor with values from [l, u], then translate to
|
| 526 |
+
# [2l-1, 2u-1].
|
| 527 |
+
tensor.uniform_(2 * l - 1, 2 * u - 1)
|
| 528 |
+
|
| 529 |
+
# Use inverse cdf transform for normal distribution to get truncated
|
| 530 |
+
# standard normal
|
| 531 |
+
tensor.erfinv_()
|
| 532 |
+
|
| 533 |
+
# Transform to proper mean, std
|
| 534 |
+
tensor.mul_(std * math.sqrt(2.0))
|
| 535 |
+
tensor.add_(mean)
|
| 536 |
+
|
| 537 |
+
# Clamp to ensure it's in the proper range
|
| 538 |
+
tensor.clamp_(min=a, max=b)
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
def trunc_normal_tf_(
|
| 542 |
+
tensor: torch.Tensor, mean: float = 0.0, std: float = 1.0, a: float = -2.0, b: float = 2.0
|
| 543 |
+
) -> torch.Tensor:
|
| 544 |
+
"""Fills the input Tensor with values drawn from a truncated
|
| 545 |
+
normal distribution. The values are effectively drawn from the
|
| 546 |
+
normal distribution :math:`\\mathcal{N}(\text{mean}, \text{std}^2)`
|
| 547 |
+
with values outside :math:`[a, b]` redrawn until they are within
|
| 548 |
+
the bounds. The method used for generating the random values works
|
| 549 |
+
best when :math:`a \\leq \text{mean} \\leq b`.
|
| 550 |
+
|
| 551 |
+
NOTE: this 'tf' variant behaves closer to Tensorflow / JAX impl where the
|
| 552 |
+
bounds [a, b] are applied when sampling the normal distribution with mean=0, std=1.0
|
| 553 |
+
and the result is subsequently scaled and shifted by the mean and std args.
|
| 554 |
+
|
| 555 |
+
Args:
|
| 556 |
+
tensor: an n-dimensional `torch.Tensor`
|
| 557 |
+
mean: the mean of the normal distribution
|
| 558 |
+
std: the standard deviation of the normal distribution
|
| 559 |
+
a: the minimum cutoff value
|
| 560 |
+
b: the maximum cutoff value
|
| 561 |
+
"""
|
| 562 |
+
with torch.no_grad():
|
| 563 |
+
_trunc_normal_(tensor, 0, 1.0, a, b)
|
| 564 |
+
tensor.mul_(std).add_(mean)
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
def variance_scaling_(tensor, scale=1.0, mode="fan_in", distribution="normal"):
|
| 568 |
+
fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor)
|
| 569 |
+
if mode == "fan_in":
|
| 570 |
+
denom = fan_in
|
| 571 |
+
elif mode == "fan_out":
|
| 572 |
+
denom = fan_out
|
| 573 |
+
elif mode == "fan_avg":
|
| 574 |
+
denom = (fan_in + fan_out) / 2
|
| 575 |
+
|
| 576 |
+
variance = scale / denom
|
| 577 |
+
|
| 578 |
+
if distribution == "truncated_normal":
|
| 579 |
+
# constant is stddev of standard normal truncated to (-2, 2)
|
| 580 |
+
trunc_normal_tf_(tensor, std=math.sqrt(variance) / 0.87962566103423978)
|
| 581 |
+
elif distribution == "normal":
|
| 582 |
+
with torch.no_grad():
|
| 583 |
+
tensor.normal_(std=math.sqrt(variance))
|
| 584 |
+
elif distribution == "uniform":
|
| 585 |
+
bound = math.sqrt(3 * variance)
|
| 586 |
+
with torch.no_grad():
|
| 587 |
+
tensor.uniform_(-bound, bound)
|
| 588 |
+
else:
|
| 589 |
+
raise ValueError(f"invalid distribution {distribution}")
|
| 590 |
+
|
| 591 |
+
|
| 592 |
+
def lecun_normal_(tensor):
|
| 593 |
+
variance_scaling_(tensor, mode="fan_in", distribution="truncated_normal")
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
def default_flax_embed_init(tensor):
|
| 597 |
+
variance_scaling_(tensor, mode="fan_in", distribution="normal")
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
@auto_docstring
|
| 601 |
+
class Siglip2PreTrainedModel(PreTrainedModel):
|
| 602 |
+
config: Siglip2Config
|
| 603 |
+
base_model_prefix = "siglip2"
|
| 604 |
+
supports_gradient_checkpointing = True
|
| 605 |
+
|
| 606 |
+
_no_split_modules = [
|
| 607 |
+
"Siglip2TextEmbeddings",
|
| 608 |
+
"Siglip2VisionEmbeddings",
|
| 609 |
+
"Siglip2EncoderLayer",
|
| 610 |
+
"Siglip2MultiheadAttentionPoolingHead",
|
| 611 |
+
]
|
| 612 |
+
_supports_flash_attn = True
|
| 613 |
+
_supports_sdpa = True
|
| 614 |
+
_supports_flex_attn = True
|
| 615 |
+
_supports_attention_backend = True
|
| 616 |
+
|
| 617 |
+
def _init_weights(self, module):
|
| 618 |
+
"""Initialize the weights"""
|
| 619 |
+
if isinstance(module, Siglip2VisionEmbeddings):
|
| 620 |
+
width = (
|
| 621 |
+
self.config.vision_config.hidden_size
|
| 622 |
+
if isinstance(self.config, Siglip2Config)
|
| 623 |
+
else self.config.hidden_size
|
| 624 |
+
)
|
| 625 |
+
nn.init.normal_(module.position_embedding.weight, std=1 / np.sqrt(width))
|
| 626 |
+
elif isinstance(module, nn.Embedding):
|
| 627 |
+
default_flax_embed_init(module.weight)
|
| 628 |
+
elif isinstance(module, Siglip2Attention):
|
| 629 |
+
nn.init.xavier_uniform_(module.q_proj.weight)
|
| 630 |
+
nn.init.xavier_uniform_(module.k_proj.weight)
|
| 631 |
+
nn.init.xavier_uniform_(module.v_proj.weight)
|
| 632 |
+
nn.init.xavier_uniform_(module.out_proj.weight)
|
| 633 |
+
nn.init.zeros_(module.q_proj.bias)
|
| 634 |
+
nn.init.zeros_(module.k_proj.bias)
|
| 635 |
+
nn.init.zeros_(module.v_proj.bias)
|
| 636 |
+
nn.init.zeros_(module.out_proj.bias)
|
| 637 |
+
elif isinstance(module, Siglip2MLP):
|
| 638 |
+
nn.init.xavier_uniform_(module.fc1.weight)
|
| 639 |
+
nn.init.xavier_uniform_(module.fc2.weight)
|
| 640 |
+
nn.init.normal_(module.fc1.bias, std=1e-6)
|
| 641 |
+
nn.init.normal_(module.fc2.bias, std=1e-6)
|
| 642 |
+
elif isinstance(module, Siglip2MultiheadAttentionPoolingHead):
|
| 643 |
+
nn.init.xavier_uniform_(module.probe.data)
|
| 644 |
+
nn.init.xavier_uniform_(module.attention.in_proj_weight.data)
|
| 645 |
+
nn.init.zeros_(module.attention.in_proj_bias.data)
|
| 646 |
+
elif isinstance(module, Siglip2Model):
|
| 647 |
+
logit_scale_init = torch.log(torch.tensor(1.0))
|
| 648 |
+
module.logit_scale.data.fill_(logit_scale_init)
|
| 649 |
+
module.logit_bias.data.zero_()
|
| 650 |
+
elif isinstance(module, Siglip2ForImageClassification):
|
| 651 |
+
nn.init.normal_(
|
| 652 |
+
module.classifier.weight,
|
| 653 |
+
std=self.config.vision_config.hidden_size**-0.5 * self.config.initializer_factor,
|
| 654 |
+
)
|
| 655 |
+
elif isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 656 |
+
lecun_normal_(module.weight)
|
| 657 |
+
if module.bias is not None:
|
| 658 |
+
nn.init.zeros_(module.bias)
|
| 659 |
+
elif isinstance(module, nn.LayerNorm):
|
| 660 |
+
module.bias.data.zero_()
|
| 661 |
+
module.weight.data.fill_(1.0)
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
class Siglip2TextEmbeddings(nn.Module):
|
| 665 |
+
def __init__(self, config: Siglip2TextConfig):
|
| 666 |
+
super().__init__()
|
| 667 |
+
embed_dim = config.hidden_size
|
| 668 |
+
|
| 669 |
+
self.token_embedding = nn.Embedding(config.vocab_size, embed_dim)
|
| 670 |
+
self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim)
|
| 671 |
+
|
| 672 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 673 |
+
self.register_buffer(
|
| 674 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
| 675 |
+
)
|
| 676 |
+
|
| 677 |
+
def forward(
|
| 678 |
+
self,
|
| 679 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 680 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 681 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 682 |
+
) -> torch.Tensor:
|
| 683 |
+
seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2]
|
| 684 |
+
max_position_embedding = self.position_embedding.weight.shape[0]
|
| 685 |
+
|
| 686 |
+
if seq_length > max_position_embedding:
|
| 687 |
+
raise ValueError(
|
| 688 |
+
f"Sequence length must be less than max_position_embeddings (got `sequence length`: "
|
| 689 |
+
f"{seq_length} and max_position_embeddings: {max_position_embedding}"
|
| 690 |
+
)
|
| 691 |
+
|
| 692 |
+
if position_ids is None:
|
| 693 |
+
position_ids = self.position_ids[:, :seq_length]
|
| 694 |
+
|
| 695 |
+
if inputs_embeds is None:
|
| 696 |
+
inputs_embeds = self.token_embedding(input_ids)
|
| 697 |
+
|
| 698 |
+
position_embeddings = self.position_embedding(position_ids)
|
| 699 |
+
embeddings = inputs_embeds + position_embeddings
|
| 700 |
+
|
| 701 |
+
return embeddings
|
| 702 |
+
|
| 703 |
+
|
| 704 |
+
class Siglip2TextTransformer(nn.Module):
|
| 705 |
+
def __init__(self, config: Siglip2TextConfig):
|
| 706 |
+
super().__init__()
|
| 707 |
+
self.config = config
|
| 708 |
+
embed_dim = config.hidden_size
|
| 709 |
+
self.embeddings = Siglip2TextEmbeddings(config)
|
| 710 |
+
self.encoder = Siglip2Encoder(config)
|
| 711 |
+
self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
| 712 |
+
|
| 713 |
+
self.head = nn.Linear(embed_dim, config.projection_size)
|
| 714 |
+
|
| 715 |
+
@can_return_tuple
|
| 716 |
+
@auto_docstring
|
| 717 |
+
def forward(
|
| 718 |
+
self,
|
| 719 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 720 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 721 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 722 |
+
output_attentions: Optional[bool] = None,
|
| 723 |
+
output_hidden_states: Optional[bool] = None,
|
| 724 |
+
) -> BaseModelOutputWithPooling:
|
| 725 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 726 |
+
output_hidden_states = (
|
| 727 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 728 |
+
)
|
| 729 |
+
|
| 730 |
+
if input_ids is None:
|
| 731 |
+
raise ValueError("You have to specify input_ids")
|
| 732 |
+
|
| 733 |
+
input_shape = input_ids.size()
|
| 734 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
| 735 |
+
|
| 736 |
+
hidden_states = self.embeddings(input_ids=input_ids, position_ids=position_ids)
|
| 737 |
+
|
| 738 |
+
# note: Siglip2's text model does not use a causal mask, unlike the original CLIP model.
|
| 739 |
+
# expand attention_mask
|
| 740 |
+
uses_flash_attention = "flash" in self.config._attn_implementation
|
| 741 |
+
if uses_flash_attention:
|
| 742 |
+
attention_mask = None
|
| 743 |
+
elif attention_mask is not None and not uses_flash_attention:
|
| 744 |
+
# [batch_size, seq_len] -> [batch_size, 1, tgt_seq_len, src_seq_len]
|
| 745 |
+
attention_mask = _prepare_4d_attention_mask(attention_mask, hidden_states.dtype)
|
| 746 |
+
|
| 747 |
+
encoder_outputs: BaseModelOutput = self.encoder(
|
| 748 |
+
inputs_embeds=hidden_states,
|
| 749 |
+
attention_mask=attention_mask,
|
| 750 |
+
output_attentions=output_attentions,
|
| 751 |
+
output_hidden_states=output_hidden_states,
|
| 752 |
+
)
|
| 753 |
+
|
| 754 |
+
last_hidden_state = encoder_outputs.last_hidden_state
|
| 755 |
+
last_hidden_state = self.final_layer_norm(last_hidden_state)
|
| 756 |
+
|
| 757 |
+
# The model uses the last token's hidden state, which may be padding.
|
| 758 |
+
pooled_output = last_hidden_state[:, -1, :]
|
| 759 |
+
pooled_output = self.head(pooled_output)
|
| 760 |
+
|
| 761 |
+
return BaseModelOutputWithPooling(
|
| 762 |
+
last_hidden_state=last_hidden_state,
|
| 763 |
+
pooler_output=pooled_output,
|
| 764 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 765 |
+
attentions=encoder_outputs.attentions,
|
| 766 |
+
)
|
| 767 |
+
|
| 768 |
+
|
| 769 |
+
@auto_docstring(
|
| 770 |
+
custom_intro="""
|
| 771 |
+
The text model from Siglip2 without any head or projection on top.
|
| 772 |
+
"""
|
| 773 |
+
)
|
| 774 |
+
class Siglip2TextModel(Siglip2PreTrainedModel):
|
| 775 |
+
config: Siglip2TextConfig
|
| 776 |
+
|
| 777 |
+
def __init__(self, config: Siglip2TextConfig):
|
| 778 |
+
super().__init__(config)
|
| 779 |
+
self.text_model = Siglip2TextTransformer(config)
|
| 780 |
+
# Initialize weights and apply final processing
|
| 781 |
+
self.post_init()
|
| 782 |
+
|
| 783 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 784 |
+
return self.text_model.embeddings.token_embedding
|
| 785 |
+
|
| 786 |
+
def set_input_embeddings(self, value):
|
| 787 |
+
self.text_model.embeddings.token_embedding = value
|
| 788 |
+
|
| 789 |
+
@can_return_tuple
|
| 790 |
+
@auto_docstring
|
| 791 |
+
def forward(
|
| 792 |
+
self,
|
| 793 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 794 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 795 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 796 |
+
output_attentions: Optional[bool] = None,
|
| 797 |
+
output_hidden_states: Optional[bool] = None,
|
| 798 |
+
) -> BaseModelOutputWithPooling:
|
| 799 |
+
r"""
|
| 800 |
+
Examples:
|
| 801 |
+
|
| 802 |
+
```python
|
| 803 |
+
>>> from transformers import AutoTokenizer, Siglip2TextModel
|
| 804 |
+
|
| 805 |
+
>>> model = Siglip2TextModel.from_pretrained("google/siglip2-base-patch16-224")
|
| 806 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/siglip2-base-patch16-224")
|
| 807 |
+
|
| 808 |
+
>>> # important: make sure to set padding="max_length" as that's how the model was trained
|
| 809 |
+
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding="max_length", return_tensors="pt")
|
| 810 |
+
|
| 811 |
+
>>> outputs = model(**inputs)
|
| 812 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
| 813 |
+
>>> pooled_output = outputs.pooler_output # pooled (EOS token) states
|
| 814 |
+
```"""
|
| 815 |
+
|
| 816 |
+
return self.text_model(
|
| 817 |
+
input_ids=input_ids,
|
| 818 |
+
attention_mask=attention_mask,
|
| 819 |
+
position_ids=position_ids,
|
| 820 |
+
output_attentions=output_attentions,
|
| 821 |
+
output_hidden_states=output_hidden_states,
|
| 822 |
+
)
|
| 823 |
+
|
| 824 |
+
|
| 825 |
+
class Siglip2MultiheadAttentionPoolingHead(nn.Module):
|
| 826 |
+
"""Multihead Attention Pooling."""
|
| 827 |
+
|
| 828 |
+
def __init__(self, config: Siglip2VisionConfig):
|
| 829 |
+
super().__init__()
|
| 830 |
+
|
| 831 |
+
self.probe = nn.Parameter(torch.randn(1, 1, config.hidden_size))
|
| 832 |
+
self.attention = torch.nn.MultiheadAttention(config.hidden_size, config.num_attention_heads, batch_first=True)
|
| 833 |
+
self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 834 |
+
self.mlp = Siglip2MLP(config)
|
| 835 |
+
self.num_heads = config.num_attention_heads
|
| 836 |
+
|
| 837 |
+
def forward(self, hidden_state: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
|
| 838 |
+
batch_size = hidden_state.shape[0]
|
| 839 |
+
probe = self.probe.repeat(batch_size, 1, 1)
|
| 840 |
+
|
| 841 |
+
if attention_mask is not None:
|
| 842 |
+
target_len, source_len = probe.shape[1], hidden_state.shape[1]
|
| 843 |
+
attention_mask = _prepare_4d_attention_mask(attention_mask, hidden_state.dtype, target_len)
|
| 844 |
+
attention_mask = attention_mask.repeat(1, self.num_heads, target_len, 1)
|
| 845 |
+
attention_mask = attention_mask.reshape(-1, target_len, source_len)
|
| 846 |
+
|
| 847 |
+
hidden_state = self.attention(probe, hidden_state, hidden_state, attn_mask=attention_mask)[0]
|
| 848 |
+
|
| 849 |
+
residual = hidden_state
|
| 850 |
+
hidden_state = self.layernorm(hidden_state)
|
| 851 |
+
hidden_state = residual + self.mlp(hidden_state)
|
| 852 |
+
|
| 853 |
+
return hidden_state[:, 0]
|
| 854 |
+
|
| 855 |
+
|
| 856 |
+
@auto_docstring(
|
| 857 |
+
custom_intro="""
|
| 858 |
+
The vision model from Siglip2 without any head or projection on top.
|
| 859 |
+
"""
|
| 860 |
+
)
|
| 861 |
+
class Siglip2VisionModel(Siglip2PreTrainedModel):
|
| 862 |
+
config: Siglip2VisionConfig
|
| 863 |
+
main_input_name = "pixel_values"
|
| 864 |
+
|
| 865 |
+
def __init__(self, config: Siglip2VisionConfig):
|
| 866 |
+
super().__init__(config)
|
| 867 |
+
|
| 868 |
+
self.vision_model = Siglip2VisionTransformer(config)
|
| 869 |
+
|
| 870 |
+
# Initialize weights and apply final processing
|
| 871 |
+
self.post_init()
|
| 872 |
+
|
| 873 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 874 |
+
return self.vision_model.embeddings.patch_embedding
|
| 875 |
+
|
| 876 |
+
@can_return_tuple
|
| 877 |
+
@auto_docstring
|
| 878 |
+
def forward(
|
| 879 |
+
self,
|
| 880 |
+
pixel_values: torch.FloatTensor,
|
| 881 |
+
pixel_attention_mask: torch.Tensor,
|
| 882 |
+
spatial_shapes: torch.LongTensor,
|
| 883 |
+
output_attentions: Optional[bool] = None,
|
| 884 |
+
output_hidden_states: Optional[bool] = None,
|
| 885 |
+
) -> BaseModelOutputWithPooling:
|
| 886 |
+
r"""
|
| 887 |
+
pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
|
| 888 |
+
Mask to avoid performing attention on padding pixel indices.
|
| 889 |
+
spatial_shapes (`torch.LongTensor` of shape `(batch_size, 2)`):
|
| 890 |
+
Tensor containing the spatial dimensions (height, width) of the input images.
|
| 891 |
+
|
| 892 |
+
Examples:
|
| 893 |
+
|
| 894 |
+
```python
|
| 895 |
+
>>> from PIL import Image
|
| 896 |
+
>>> import requests
|
| 897 |
+
>>> from transformers import AutoProcessor, Siglip2VisionModel
|
| 898 |
+
|
| 899 |
+
>>> model = Siglip2VisionModel.from_pretrained("google/siglip2-base-patch16-224")
|
| 900 |
+
>>> processor = AutoProcessor.from_pretrained("google/siglip2-base-patch16-224")
|
| 901 |
+
|
| 902 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 903 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 904 |
+
|
| 905 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 906 |
+
|
| 907 |
+
>>> outputs = model(**inputs)
|
| 908 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
| 909 |
+
>>> pooled_output = outputs.pooler_output # pooled features
|
| 910 |
+
```"""
|
| 911 |
+
return self.vision_model(
|
| 912 |
+
pixel_values=pixel_values,
|
| 913 |
+
attention_mask=pixel_attention_mask,
|
| 914 |
+
spatial_shapes=spatial_shapes,
|
| 915 |
+
output_attentions=output_attentions,
|
| 916 |
+
output_hidden_states=output_hidden_states,
|
| 917 |
+
)
|
| 918 |
+
|
| 919 |
+
|
| 920 |
+
@auto_docstring
|
| 921 |
+
class Siglip2Model(Siglip2PreTrainedModel):
|
| 922 |
+
config: Siglip2Config
|
| 923 |
+
|
| 924 |
+
def __init__(self, config: Siglip2Config):
|
| 925 |
+
super().__init__(config)
|
| 926 |
+
|
| 927 |
+
if not isinstance(config.text_config, Siglip2TextConfig):
|
| 928 |
+
raise TypeError(
|
| 929 |
+
"config.text_config is expected to be of type Siglip2TextConfig but is of type"
|
| 930 |
+
f" {type(config.text_config)}."
|
| 931 |
+
)
|
| 932 |
+
|
| 933 |
+
if not isinstance(config.vision_config, Siglip2VisionConfig):
|
| 934 |
+
raise TypeError(
|
| 935 |
+
"config.vision_config is expected to be of type Siglip2VisionConfig but is of type"
|
| 936 |
+
f" {type(config.vision_config)}."
|
| 937 |
+
)
|
| 938 |
+
|
| 939 |
+
text_config = config.text_config
|
| 940 |
+
vision_config = config.vision_config
|
| 941 |
+
|
| 942 |
+
# First, initialize the text and vision models with proper attention implementation
|
| 943 |
+
text_model = Siglip2TextModel._from_config(text_config)
|
| 944 |
+
vision_model = Siglip2VisionModel._from_config(vision_config)
|
| 945 |
+
|
| 946 |
+
# Second, get the text and vision submodules (for backward compatibility)
|
| 947 |
+
self.text_model = text_model.text_model
|
| 948 |
+
self.vision_model = vision_model.vision_model
|
| 949 |
+
|
| 950 |
+
self.logit_scale = nn.Parameter(torch.randn(1))
|
| 951 |
+
self.logit_bias = nn.Parameter(torch.randn(1))
|
| 952 |
+
|
| 953 |
+
# Initialize weights and apply final processing
|
| 954 |
+
self.post_init()
|
| 955 |
+
|
| 956 |
+
@auto_docstring
|
| 957 |
+
def get_text_features(
|
| 958 |
+
self,
|
| 959 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 960 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 961 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 962 |
+
output_attentions: Optional[bool] = None,
|
| 963 |
+
output_hidden_states: Optional[bool] = None,
|
| 964 |
+
) -> torch.FloatTensor:
|
| 965 |
+
r"""
|
| 966 |
+
Returns:
|
| 967 |
+
text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
|
| 968 |
+
applying the projection layer to the pooled output of [`Siglip2TextModel`].
|
| 969 |
+
|
| 970 |
+
Examples:
|
| 971 |
+
|
| 972 |
+
```python
|
| 973 |
+
>>> from transformers import AutoTokenizer, AutoModel
|
| 974 |
+
>>> import torch
|
| 975 |
+
|
| 976 |
+
>>> model = AutoModel.from_pretrained("google/siglip2-base-patch16-224")
|
| 977 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/siglip2-base-patch16-224")
|
| 978 |
+
|
| 979 |
+
>>> # important: make sure to set padding="max_length" as that's how the model was trained
|
| 980 |
+
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding="max_length", return_tensors="pt")
|
| 981 |
+
>>> with torch.no_grad():
|
| 982 |
+
... text_features = model.get_text_features(**inputs)
|
| 983 |
+
```"""
|
| 984 |
+
# Use Siglip2 model's config for some fields (if specified) instead of those of vision & text components.
|
| 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 |
+
|
| 990 |
+
text_outputs: BaseModelOutputWithPooling = self.text_model(
|
| 991 |
+
input_ids=input_ids,
|
| 992 |
+
attention_mask=attention_mask,
|
| 993 |
+
position_ids=position_ids,
|
| 994 |
+
output_attentions=output_attentions,
|
| 995 |
+
output_hidden_states=output_hidden_states,
|
| 996 |
+
)
|
| 997 |
+
|
| 998 |
+
pooled_output = text_outputs.pooler_output
|
| 999 |
+
|
| 1000 |
+
return pooled_output
|
| 1001 |
+
|
| 1002 |
+
@auto_docstring
|
| 1003 |
+
def get_image_features(
|
| 1004 |
+
self,
|
| 1005 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1006 |
+
pixel_attention_mask: Optional[torch.Tensor] = None,
|
| 1007 |
+
spatial_shapes: Optional[torch.LongTensor] = None,
|
| 1008 |
+
output_attentions: Optional[bool] = None,
|
| 1009 |
+
output_hidden_states: Optional[bool] = None,
|
| 1010 |
+
) -> torch.FloatTensor:
|
| 1011 |
+
r"""
|
| 1012 |
+
pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
|
| 1013 |
+
Mask to avoid performing attention on padding pixel indices.
|
| 1014 |
+
spatial_shapes (`torch.LongTensor` of shape `(batch_size, 2)`):
|
| 1015 |
+
Tensor containing the spatial dimensions (height, width) of the input images.
|
| 1016 |
+
|
| 1017 |
+
Returns:
|
| 1018 |
+
image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
|
| 1019 |
+
applying the projection layer to the pooled output of [`Siglip2VisionModel`].
|
| 1020 |
+
|
| 1021 |
+
Examples:
|
| 1022 |
+
|
| 1023 |
+
```python
|
| 1024 |
+
>>> from PIL import Image
|
| 1025 |
+
>>> import requests
|
| 1026 |
+
>>> from transformers import AutoProcessor, AutoModel
|
| 1027 |
+
>>> import torch
|
| 1028 |
+
|
| 1029 |
+
>>> model = AutoModel.from_pretrained("google/siglip2-base-patch16-224")
|
| 1030 |
+
>>> processor = AutoProcessor.from_pretrained("google/siglip2-base-patch16-224")
|
| 1031 |
+
|
| 1032 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1033 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1034 |
+
|
| 1035 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 1036 |
+
|
| 1037 |
+
>>> with torch.no_grad():
|
| 1038 |
+
... image_features = model.get_image_features(**inputs)
|
| 1039 |
+
```
|
| 1040 |
+
"""
|
| 1041 |
+
# Use Siglip2Model's config for some fields (if specified) instead of those of vision & text components.
|
| 1042 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1043 |
+
output_hidden_states = (
|
| 1044 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1045 |
+
)
|
| 1046 |
+
|
| 1047 |
+
vision_outputs: BaseModelOutputWithPooling = self.vision_model(
|
| 1048 |
+
pixel_values=pixel_values,
|
| 1049 |
+
attention_mask=pixel_attention_mask,
|
| 1050 |
+
spatial_shapes=spatial_shapes,
|
| 1051 |
+
output_attentions=output_attentions,
|
| 1052 |
+
output_hidden_states=output_hidden_states,
|
| 1053 |
+
)
|
| 1054 |
+
|
| 1055 |
+
pooled_output = vision_outputs.pooler_output
|
| 1056 |
+
|
| 1057 |
+
return pooled_output
|
| 1058 |
+
|
| 1059 |
+
@can_return_tuple
|
| 1060 |
+
@auto_docstring
|
| 1061 |
+
def forward(
|
| 1062 |
+
self,
|
| 1063 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1064 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1065 |
+
pixel_attention_mask: Optional[torch.Tensor] = None,
|
| 1066 |
+
spatial_shapes: Optional[torch.LongTensor] = None,
|
| 1067 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1068 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1069 |
+
return_loss: Optional[bool] = None,
|
| 1070 |
+
output_attentions: Optional[bool] = None,
|
| 1071 |
+
output_hidden_states: Optional[bool] = None,
|
| 1072 |
+
) -> Siglip2Output:
|
| 1073 |
+
r"""
|
| 1074 |
+
pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
|
| 1075 |
+
Mask to avoid performing attention on padding pixel indices.
|
| 1076 |
+
spatial_shapes (`torch.LongTensor` of shape `(batch_size, 2)`):
|
| 1077 |
+
Tensor containing the spatial dimensions (height, width) of the input images.
|
| 1078 |
+
return_loss (`bool`, *optional*):
|
| 1079 |
+
Whether or not to return the contrastive loss.
|
| 1080 |
+
|
| 1081 |
+
Examples:
|
| 1082 |
+
|
| 1083 |
+
```python
|
| 1084 |
+
>>> from PIL import Image
|
| 1085 |
+
>>> import requests
|
| 1086 |
+
>>> from transformers import AutoProcessor, AutoModel
|
| 1087 |
+
>>> import torch
|
| 1088 |
+
|
| 1089 |
+
>>> model = AutoModel.from_pretrained("google/siglip2-base-patch16-224")
|
| 1090 |
+
>>> processor = AutoProcessor.from_pretrained("google/siglip2-base-patch16-224")
|
| 1091 |
+
|
| 1092 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1093 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1094 |
+
|
| 1095 |
+
>>> texts = ["a photo of 2 cats", "a photo of 2 dogs"]
|
| 1096 |
+
>>> # important: we pass `padding=max_length` since the model was trained with this
|
| 1097 |
+
>>> inputs = processor(text=texts, images=image, padding="max_length", return_tensors="pt")
|
| 1098 |
+
|
| 1099 |
+
>>> with torch.no_grad():
|
| 1100 |
+
... outputs = model(**inputs)
|
| 1101 |
+
|
| 1102 |
+
>>> logits_per_image = outputs.logits_per_image
|
| 1103 |
+
>>> probs = torch.sigmoid(logits_per_image) # these are the probabilities
|
| 1104 |
+
>>> print(f"{probs[0][0]:.1%} that image 0 is '{texts[0]}'")
|
| 1105 |
+
31.9% that image 0 is 'a photo of 2 cats'
|
| 1106 |
+
```
|
| 1107 |
+
"""
|
| 1108 |
+
# Use Siglip2 model's config for some fields (if specified) instead of those of vision & text components.
|
| 1109 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1110 |
+
output_hidden_states = (
|
| 1111 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1112 |
+
)
|
| 1113 |
+
|
| 1114 |
+
vision_outputs: BaseModelOutputWithPooling = self.vision_model(
|
| 1115 |
+
pixel_values=pixel_values,
|
| 1116 |
+
attention_mask=pixel_attention_mask,
|
| 1117 |
+
spatial_shapes=spatial_shapes,
|
| 1118 |
+
output_attentions=output_attentions,
|
| 1119 |
+
output_hidden_states=output_hidden_states,
|
| 1120 |
+
)
|
| 1121 |
+
|
| 1122 |
+
text_outputs: BaseModelOutputWithPooling = self.text_model(
|
| 1123 |
+
input_ids=input_ids,
|
| 1124 |
+
attention_mask=attention_mask,
|
| 1125 |
+
position_ids=position_ids,
|
| 1126 |
+
output_attentions=output_attentions,
|
| 1127 |
+
output_hidden_states=output_hidden_states,
|
| 1128 |
+
)
|
| 1129 |
+
|
| 1130 |
+
image_embeds = vision_outputs.pooler_output
|
| 1131 |
+
text_embeds = text_outputs.pooler_output
|
| 1132 |
+
|
| 1133 |
+
# normalized features
|
| 1134 |
+
image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
|
| 1135 |
+
text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
|
| 1136 |
+
|
| 1137 |
+
# cosine similarity as logits
|
| 1138 |
+
logits_per_text = torch.matmul(text_embeds, image_embeds.t().to(text_embeds.device))
|
| 1139 |
+
|
| 1140 |
+
logit_scale, logit_bias = self.logit_scale.to(text_embeds.device), self.logit_bias.to(text_embeds.device)
|
| 1141 |
+
logits_per_text = logits_per_text * logit_scale.exp() + logit_bias
|
| 1142 |
+
|
| 1143 |
+
logits_per_image = logits_per_text.t()
|
| 1144 |
+
|
| 1145 |
+
loss = None
|
| 1146 |
+
if return_loss:
|
| 1147 |
+
# Adapted from https://github.com/google-research/big_vision/blob/01edb81a4716f93a48be43b3a4af14e29cdb3a7f/big_vision/trainers/proj/image_text/siglip2.py#L287
|
| 1148 |
+
eye = torch.eye(logits_per_text.size(0), device=logits_per_text.device)
|
| 1149 |
+
m1_diag1 = -torch.ones_like(logits_per_text) + 2 * eye
|
| 1150 |
+
loglik = torch.nn.functional.logsigmoid(m1_diag1 * logits_per_text)
|
| 1151 |
+
nll = -torch.sum(loglik, dim=-1)
|
| 1152 |
+
loss = nll.mean()
|
| 1153 |
+
|
| 1154 |
+
return Siglip2Output(
|
| 1155 |
+
loss=loss,
|
| 1156 |
+
logits_per_image=logits_per_image,
|
| 1157 |
+
logits_per_text=logits_per_text,
|
| 1158 |
+
text_embeds=text_embeds,
|
| 1159 |
+
image_embeds=image_embeds,
|
| 1160 |
+
text_model_output=text_outputs,
|
| 1161 |
+
vision_model_output=vision_outputs,
|
| 1162 |
+
)
|
| 1163 |
+
|
| 1164 |
+
|
| 1165 |
+
@auto_docstring(
|
| 1166 |
+
custom_intro="""
|
| 1167 |
+
Siglip2 vision encoder with an image classification head on top (a linear layer on top of the pooled final hidden states of
|
| 1168 |
+
the patch tokens) e.g. for ImageNet.
|
| 1169 |
+
"""
|
| 1170 |
+
)
|
| 1171 |
+
class Siglip2ForImageClassification(Siglip2PreTrainedModel):
|
| 1172 |
+
main_input_name = "pixel_values"
|
| 1173 |
+
|
| 1174 |
+
def __init__(self, config: Siglip2Config) -> None:
|
| 1175 |
+
super().__init__(config)
|
| 1176 |
+
|
| 1177 |
+
self.num_labels = config.num_labels
|
| 1178 |
+
|
| 1179 |
+
# Create the vision model with proper attention
|
| 1180 |
+
# and take only vision_model submodule (for backward compatibility)
|
| 1181 |
+
vision_model = Siglip2VisionModel._from_config(config.vision_config)
|
| 1182 |
+
self.vision_model = vision_model.vision_model
|
| 1183 |
+
|
| 1184 |
+
# Classifier head
|
| 1185 |
+
self.classifier = (
|
| 1186 |
+
nn.Linear(config.vision_config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
|
| 1187 |
+
)
|
| 1188 |
+
|
| 1189 |
+
# Initialize weights and apply final processing
|
| 1190 |
+
self.post_init()
|
| 1191 |
+
|
| 1192 |
+
@can_return_tuple
|
| 1193 |
+
@auto_docstring
|
| 1194 |
+
def forward(
|
| 1195 |
+
self,
|
| 1196 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 1197 |
+
pixel_attention_mask: Optional[torch.Tensor] = None,
|
| 1198 |
+
spatial_shapes: Optional[torch.LongTensor] = None,
|
| 1199 |
+
labels: Optional[torch.Tensor] = None,
|
| 1200 |
+
output_attentions: Optional[bool] = None,
|
| 1201 |
+
output_hidden_states: Optional[bool] = None,
|
| 1202 |
+
) -> ImageClassifierOutput:
|
| 1203 |
+
r"""
|
| 1204 |
+
pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
|
| 1205 |
+
Mask to avoid performing attention on padding pixel indices.
|
| 1206 |
+
spatial_shapes (`torch.LongTensor` of shape `(batch_size, 2)`):
|
| 1207 |
+
Tensor containing the spatial dimensions (height, width) of the input images.
|
| 1208 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1209 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 1210 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1211 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1212 |
+
|
| 1213 |
+
Examples:
|
| 1214 |
+
|
| 1215 |
+
```python
|
| 1216 |
+
>>> from transformers import AutoImageProcessor, Siglip2ForImageClassification
|
| 1217 |
+
>>> import torch
|
| 1218 |
+
>>> from PIL import Image
|
| 1219 |
+
>>> import requests
|
| 1220 |
+
|
| 1221 |
+
>>> torch.manual_seed(3) # doctest: +IGNORE_RESULT
|
| 1222 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1223 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1224 |
+
|
| 1225 |
+
>>> # note: we are loading a `Siglip2Model` from the hub here,
|
| 1226 |
+
>>> # so the head will be randomly initialized, hence the predictions will be random if seed is not set above.
|
| 1227 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("google/siglip2-base-patch16-224")
|
| 1228 |
+
>>> model = Siglip2ForImageClassification.from_pretrained("google/siglip2-base-patch16-224")
|
| 1229 |
+
|
| 1230 |
+
>>> inputs = image_processor(images=image, return_tensors="pt")
|
| 1231 |
+
>>> outputs = model(**inputs)
|
| 1232 |
+
>>> logits = outputs.logits
|
| 1233 |
+
>>> # model predicts one of the two classes
|
| 1234 |
+
>>> predicted_class_idx = logits.argmax(-1).item()
|
| 1235 |
+
>>> print("Predicted class:", model.config.id2label[predicted_class_idx])
|
| 1236 |
+
Predicted class: LABEL_1
|
| 1237 |
+
```
|
| 1238 |
+
"""
|
| 1239 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1240 |
+
output_hidden_states = (
|
| 1241 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1242 |
+
)
|
| 1243 |
+
|
| 1244 |
+
outputs: BaseModelOutputWithPooling = self.vision_model(
|
| 1245 |
+
pixel_values,
|
| 1246 |
+
attention_mask=pixel_attention_mask,
|
| 1247 |
+
spatial_shapes=spatial_shapes,
|
| 1248 |
+
output_attentions=output_attentions,
|
| 1249 |
+
output_hidden_states=output_hidden_states,
|
| 1250 |
+
)
|
| 1251 |
+
|
| 1252 |
+
sequence_output = outputs.last_hidden_state
|
| 1253 |
+
|
| 1254 |
+
# average pool the patch tokens
|
| 1255 |
+
if pixel_attention_mask is not None:
|
| 1256 |
+
pool_mask = pixel_attention_mask[..., None].to(sequence_output.device)
|
| 1257 |
+
sequence_output = torch.sum(sequence_output * pool_mask, dim=1) / torch.sum(pool_mask, dim=1)
|
| 1258 |
+
else:
|
| 1259 |
+
sequence_output = torch.mean(sequence_output, dim=1)
|
| 1260 |
+
|
| 1261 |
+
# apply classifier
|
| 1262 |
+
logits = self.classifier(sequence_output)
|
| 1263 |
+
|
| 1264 |
+
loss = None
|
| 1265 |
+
if labels is not None:
|
| 1266 |
+
# move labels to correct device to enable model parallelism
|
| 1267 |
+
labels = labels.to(logits.device)
|
| 1268 |
+
if self.config.problem_type is None:
|
| 1269 |
+
if self.num_labels == 1:
|
| 1270 |
+
self.config.problem_type = "regression"
|
| 1271 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 1272 |
+
self.config.problem_type = "single_label_classification"
|
| 1273 |
+
else:
|
| 1274 |
+
self.config.problem_type = "multi_label_classification"
|
| 1275 |
+
|
| 1276 |
+
if self.config.problem_type == "regression":
|
| 1277 |
+
loss_fct = MSELoss()
|
| 1278 |
+
if self.num_labels == 1:
|
| 1279 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 1280 |
+
else:
|
| 1281 |
+
loss = loss_fct(logits, labels)
|
| 1282 |
+
elif self.config.problem_type == "single_label_classification":
|
| 1283 |
+
loss_fct = CrossEntropyLoss()
|
| 1284 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1285 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 1286 |
+
loss_fct = BCEWithLogitsLoss()
|
| 1287 |
+
loss = loss_fct(logits, labels)
|
| 1288 |
+
|
| 1289 |
+
return ImageClassifierOutput(
|
| 1290 |
+
loss=loss,
|
| 1291 |
+
logits=logits,
|
| 1292 |
+
hidden_states=outputs.hidden_states,
|
| 1293 |
+
attentions=outputs.attentions,
|
| 1294 |
+
)
|
| 1295 |
+
|
| 1296 |
+
|
| 1297 |
+
__all__ = [
|
| 1298 |
+
"Siglip2Model",
|
| 1299 |
+
"Siglip2PreTrainedModel",
|
| 1300 |
+
"Siglip2TextModel",
|
| 1301 |
+
"Siglip2VisionModel",
|
| 1302 |
+
"Siglip2ForImageClassification",
|
| 1303 |
+
]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/siglip2/modular_siglip2.py
ADDED
|
@@ -0,0 +1,637 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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c. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
from typing import Optional
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
import torch.nn as nn
|
| 19 |
+
import torch.nn.functional as F
|
| 20 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 21 |
+
|
| 22 |
+
from transformers.models.siglip.configuration_siglip import SiglipConfig, SiglipTextConfig, SiglipVisionConfig
|
| 23 |
+
from transformers.models.siglip.modeling_siglip import (
|
| 24 |
+
BaseModelOutput,
|
| 25 |
+
BaseModelOutputWithPooling,
|
| 26 |
+
ImageClassifierOutput,
|
| 27 |
+
SiglipForImageClassification,
|
| 28 |
+
SiglipModel,
|
| 29 |
+
SiglipMultiheadAttentionPoolingHead,
|
| 30 |
+
SiglipOutput,
|
| 31 |
+
SiglipPreTrainedModel,
|
| 32 |
+
SiglipTextModel,
|
| 33 |
+
SiglipTextModelOutput,
|
| 34 |
+
SiglipVisionModel,
|
| 35 |
+
SiglipVisionModelOutput,
|
| 36 |
+
SiglipVisionTransformer,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
from ...modeling_attn_mask_utils import _prepare_4d_attention_mask
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class Siglip2TextConfig(SiglipTextConfig):
|
| 43 |
+
pass
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class Siglip2VisionConfig(SiglipVisionConfig):
|
| 47 |
+
r"""
|
| 48 |
+
This is the configuration class to store the configuration of a [`Siglip2VisionModel`]. It is used to instantiate a
|
| 49 |
+
Siglip2 vision encoder according to the specified arguments, defining the model architecture. Instantiating a
|
| 50 |
+
configuration with the defaults will yield a similar configuration to that of the vision encoder of the Siglip2
|
| 51 |
+
[google/siglip2-base-patch16-naflex](https://huggingface.co/google/siglip2-base-patch16-naflex) architecture.
|
| 52 |
+
|
| 53 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 54 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 55 |
+
|
| 56 |
+
Args:
|
| 57 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 58 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 59 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 60 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 61 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 62 |
+
Number of hidden layers in the Transformer encoder.
|
| 63 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 64 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 65 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 66 |
+
Number of channels in the input images.
|
| 67 |
+
num_patches (`int`, *optional*, defaults to 256):
|
| 68 |
+
The number of patches in the image with the size of (`patch_size`, `patch_size`).
|
| 69 |
+
The image is resized to fill maximum of this number of patches, and to preserve
|
| 70 |
+
the aspect ratio. In case the resulted number of patches is lower, the image is
|
| 71 |
+
padded in "patch" dimension.
|
| 72 |
+
patch_size (`int`, *optional*, defaults to 16):
|
| 73 |
+
The size (resolution) of each patch.
|
| 74 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
|
| 75 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 76 |
+
`"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
|
| 77 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-06):
|
| 78 |
+
The epsilon used by the layer normalization layers.
|
| 79 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 80 |
+
The dropout ratio for the attention probabilities.
|
| 81 |
+
|
| 82 |
+
Example:
|
| 83 |
+
|
| 84 |
+
```python
|
| 85 |
+
>>> from transformers import Siglip2VisionConfig, Siglip2VisionModel
|
| 86 |
+
|
| 87 |
+
>>> # Initializing a Siglip2VisionConfig with google/siglip2-base-patch16-naflex style configuration
|
| 88 |
+
>>> configuration = Siglip2VisionConfig()
|
| 89 |
+
|
| 90 |
+
>>> # Initializing a Siglip2VisionModel (with random weights) from the google/siglip2-base-patch16-naflex style configuration
|
| 91 |
+
>>> model = Siglip2VisionModel(configuration)
|
| 92 |
+
|
| 93 |
+
>>> # Accessing the model configuration
|
| 94 |
+
>>> configuration = model.config
|
| 95 |
+
```"""
|
| 96 |
+
|
| 97 |
+
def __init__(
|
| 98 |
+
self,
|
| 99 |
+
hidden_size=768,
|
| 100 |
+
intermediate_size=3072,
|
| 101 |
+
num_hidden_layers=12,
|
| 102 |
+
num_attention_heads=12,
|
| 103 |
+
num_channels=3,
|
| 104 |
+
num_patches=256,
|
| 105 |
+
patch_size=16,
|
| 106 |
+
hidden_act="gelu_pytorch_tanh",
|
| 107 |
+
layer_norm_eps=1e-6,
|
| 108 |
+
attention_dropout=0.0,
|
| 109 |
+
**kwargs,
|
| 110 |
+
):
|
| 111 |
+
super().__init__(**kwargs)
|
| 112 |
+
self.num_patches = num_patches
|
| 113 |
+
del self.image_size
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class Siglip2Config(SiglipConfig):
|
| 117 |
+
pass
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class Siglip2VisionOutput(SiglipVisionModelOutput):
|
| 121 |
+
pass
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class Siglip2TextOutput(SiglipTextModelOutput):
|
| 125 |
+
pass
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class Siglip2Output(SiglipOutput):
|
| 129 |
+
pass
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class Siglip2VisionEmbeddings(nn.Module):
|
| 133 |
+
def __init__(self, config: Siglip2VisionConfig):
|
| 134 |
+
super().__init__()
|
| 135 |
+
self.config = config
|
| 136 |
+
self.embed_dim = config.hidden_size
|
| 137 |
+
self.patch_size = config.patch_size
|
| 138 |
+
|
| 139 |
+
self.patch_embedding = nn.Linear(
|
| 140 |
+
in_features=config.num_channels * self.patch_size * self.patch_size,
|
| 141 |
+
out_features=self.embed_dim,
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
self.num_patches = config.num_patches
|
| 145 |
+
self.position_embedding_size = int(self.num_patches**0.5)
|
| 146 |
+
self.position_embedding = nn.Embedding(self.num_patches, self.embed_dim)
|
| 147 |
+
|
| 148 |
+
@staticmethod
|
| 149 |
+
def resize_positional_embeddings(
|
| 150 |
+
positional_embeddings: torch.Tensor,
|
| 151 |
+
spatial_shapes: torch.LongTensor,
|
| 152 |
+
max_length: int,
|
| 153 |
+
) -> torch.Tensor:
|
| 154 |
+
"""
|
| 155 |
+
Resize positional embeddings to image-specific size and pad to a fixed size.
|
| 156 |
+
|
| 157 |
+
Args:
|
| 158 |
+
positional_embeddings (`torch.Tensor`):
|
| 159 |
+
Position embeddings of shape (height, width, embed_dim)
|
| 160 |
+
spatial_shapes (`torch.LongTensor`):
|
| 161 |
+
Spatial shapes of shape (batch_size, 2) to resize the positional embeddings to
|
| 162 |
+
max_length (`int`):
|
| 163 |
+
Maximum length of the positional embeddings to pad resized positional embeddings to
|
| 164 |
+
|
| 165 |
+
Returns:
|
| 166 |
+
`torch.Tensor`: Embeddings of shape (batch_size, max_length, embed_dim)
|
| 167 |
+
"""
|
| 168 |
+
batch_size = spatial_shapes.shape[0]
|
| 169 |
+
embed_dim = positional_embeddings.shape[-1]
|
| 170 |
+
source_dtype = positional_embeddings.dtype
|
| 171 |
+
|
| 172 |
+
resulted_positional_embeddings = torch.empty(
|
| 173 |
+
(batch_size, max_length, embed_dim),
|
| 174 |
+
device=positional_embeddings.device,
|
| 175 |
+
dtype=source_dtype,
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
# (height, width, embed_dim) -> (1, embed_dim, height, width) for interpolation
|
| 179 |
+
positional_embeddings = positional_embeddings.permute(2, 0, 1).unsqueeze(0)
|
| 180 |
+
|
| 181 |
+
# Upcast to float32 on CPU because antialias is not supported for bfloat16/float16 on CPU
|
| 182 |
+
if positional_embeddings.device.type == "cpu":
|
| 183 |
+
positional_embeddings = positional_embeddings.to(torch.float32)
|
| 184 |
+
|
| 185 |
+
for i in range(batch_size):
|
| 186 |
+
# (1, dim, height, width) -> (1, dim, target_height, target_width)
|
| 187 |
+
height, width = spatial_shapes[i]
|
| 188 |
+
resized_embeddings = F.interpolate(
|
| 189 |
+
positional_embeddings,
|
| 190 |
+
size=(height, width),
|
| 191 |
+
mode="bilinear",
|
| 192 |
+
align_corners=False,
|
| 193 |
+
antialias=True,
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
# (1, dim, target_height, target_width) -> (target_height * target_width, dim)
|
| 197 |
+
resized_embeddings = resized_embeddings.reshape(embed_dim, height * width).transpose(0, 1)
|
| 198 |
+
|
| 199 |
+
# Cast to original dtype
|
| 200 |
+
resized_embeddings = resized_embeddings.to(source_dtype)
|
| 201 |
+
|
| 202 |
+
resulted_positional_embeddings[i, : height * width] = resized_embeddings
|
| 203 |
+
resulted_positional_embeddings[i, height * width :] = resized_embeddings[0]
|
| 204 |
+
|
| 205 |
+
return resulted_positional_embeddings
|
| 206 |
+
|
| 207 |
+
def forward(self, pixel_values: torch.FloatTensor, spatial_shapes: torch.LongTensor) -> torch.Tensor:
|
| 208 |
+
"""
|
| 209 |
+
Args:
|
| 210 |
+
pixel_values (`torch.FloatTensor`):
|
| 211 |
+
Pixel values of shape (batch_size, max_num_patches, num_channels * patch_size * patch_size)
|
| 212 |
+
spatial_shapes (`list[tuple[int, int]]`):
|
| 213 |
+
Spatial shapes of shape (batch_size, 2) to resize the positional embeddings to
|
| 214 |
+
"""
|
| 215 |
+
|
| 216 |
+
# Apply patch embeddings to already patchified pixel values
|
| 217 |
+
target_dtype = self.patch_embedding.weight.dtype
|
| 218 |
+
patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype))
|
| 219 |
+
|
| 220 |
+
# Get positional resized and padded positional embeddings
|
| 221 |
+
positional_embeddings = self.position_embedding.weight.reshape(
|
| 222 |
+
self.position_embedding_size, self.position_embedding_size, -1
|
| 223 |
+
)
|
| 224 |
+
resized_positional_embeddings = self.resize_positional_embeddings(
|
| 225 |
+
positional_embeddings, spatial_shapes, max_length=pixel_values.shape[1]
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
# Add positional embeddings to patch embeddings
|
| 229 |
+
embeddings = patch_embeds + resized_positional_embeddings
|
| 230 |
+
return embeddings
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
class Siglip2VisionTransformer(SiglipVisionTransformer):
|
| 234 |
+
def __init__(self, config: Siglip2VisionConfig):
|
| 235 |
+
super().__init__(config)
|
| 236 |
+
self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
|
| 237 |
+
|
| 238 |
+
# Update: add `spatial_shapes` and `attention_mask`
|
| 239 |
+
def forward(
|
| 240 |
+
self,
|
| 241 |
+
pixel_values: torch.FloatTensor,
|
| 242 |
+
attention_mask: torch.Tensor,
|
| 243 |
+
spatial_shapes: torch.LongTensor,
|
| 244 |
+
output_attentions: Optional[bool] = None,
|
| 245 |
+
output_hidden_states: Optional[bool] = None,
|
| 246 |
+
) -> BaseModelOutputWithPooling:
|
| 247 |
+
r"""
|
| 248 |
+
spatial_shapes (`torch.LongTensor` of shape `(batch_size, 2)`):
|
| 249 |
+
Tensor containing the spatial dimensions (height, width) of the input images.
|
| 250 |
+
"""
|
| 251 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 252 |
+
output_hidden_states = (
|
| 253 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
hidden_states = self.embeddings(pixel_values, spatial_shapes)
|
| 257 |
+
|
| 258 |
+
if attention_mask is not None and not self._use_flash_attention_2:
|
| 259 |
+
# [batch_size, seq_len] -> [batch_size, 1, tgt_seq_len, src_seq_len]
|
| 260 |
+
encoder_attention_mask = _prepare_4d_attention_mask(attention_mask, hidden_states.dtype)
|
| 261 |
+
else:
|
| 262 |
+
encoder_attention_mask = attention_mask
|
| 263 |
+
|
| 264 |
+
encoder_outputs: BaseModelOutput = self.encoder(
|
| 265 |
+
inputs_embeds=hidden_states,
|
| 266 |
+
attention_mask=encoder_attention_mask,
|
| 267 |
+
output_attentions=output_attentions,
|
| 268 |
+
output_hidden_states=output_hidden_states,
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
last_hidden_state = encoder_outputs.last_hidden_state
|
| 272 |
+
last_hidden_state = self.post_layernorm(last_hidden_state)
|
| 273 |
+
|
| 274 |
+
pooler_output = self.head(last_hidden_state, attention_mask) if self.use_head else None
|
| 275 |
+
|
| 276 |
+
return BaseModelOutputWithPooling(
|
| 277 |
+
last_hidden_state=last_hidden_state,
|
| 278 |
+
pooler_output=pooler_output,
|
| 279 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 280 |
+
attentions=encoder_outputs.attentions,
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
class Siglip2PreTrainedModel(SiglipPreTrainedModel):
|
| 285 |
+
pass
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
class Siglip2TextModel(SiglipTextModel):
|
| 289 |
+
pass
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
class Siglip2MultiheadAttentionPoolingHead(SiglipMultiheadAttentionPoolingHead):
|
| 293 |
+
def __init__(self, config: Siglip2VisionConfig):
|
| 294 |
+
super().__init__(config)
|
| 295 |
+
self.num_heads = config.num_attention_heads
|
| 296 |
+
|
| 297 |
+
def forward(self, hidden_state: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
|
| 298 |
+
batch_size = hidden_state.shape[0]
|
| 299 |
+
probe = self.probe.repeat(batch_size, 1, 1)
|
| 300 |
+
|
| 301 |
+
if attention_mask is not None:
|
| 302 |
+
target_len, source_len = probe.shape[1], hidden_state.shape[1]
|
| 303 |
+
attention_mask = _prepare_4d_attention_mask(attention_mask, hidden_state.dtype, target_len)
|
| 304 |
+
attention_mask = attention_mask.repeat(1, self.num_heads, target_len, 1)
|
| 305 |
+
attention_mask = attention_mask.reshape(-1, target_len, source_len)
|
| 306 |
+
|
| 307 |
+
hidden_state = self.attention(probe, hidden_state, hidden_state, attn_mask=attention_mask)[0]
|
| 308 |
+
|
| 309 |
+
residual = hidden_state
|
| 310 |
+
hidden_state = self.layernorm(hidden_state)
|
| 311 |
+
hidden_state = residual + self.mlp(hidden_state)
|
| 312 |
+
|
| 313 |
+
return hidden_state[:, 0]
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
class Siglip2VisionModel(SiglipVisionModel):
|
| 317 |
+
# Update: add `spatial_shapes` and `pixel_attention_mask`
|
| 318 |
+
def forward(
|
| 319 |
+
self,
|
| 320 |
+
pixel_values: torch.FloatTensor,
|
| 321 |
+
pixel_attention_mask: torch.Tensor,
|
| 322 |
+
spatial_shapes: torch.LongTensor,
|
| 323 |
+
output_attentions: Optional[bool] = None,
|
| 324 |
+
output_hidden_states: Optional[bool] = None,
|
| 325 |
+
) -> BaseModelOutputWithPooling:
|
| 326 |
+
r"""
|
| 327 |
+
pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
|
| 328 |
+
Mask to avoid performing attention on padding pixel indices.
|
| 329 |
+
spatial_shapes (`torch.LongTensor` of shape `(batch_size, 2)`):
|
| 330 |
+
Tensor containing the spatial dimensions (height, width) of the input images.
|
| 331 |
+
|
| 332 |
+
Examples:
|
| 333 |
+
|
| 334 |
+
```python
|
| 335 |
+
>>> from PIL import Image
|
| 336 |
+
>>> import requests
|
| 337 |
+
>>> from transformers import AutoProcessor, Siglip2VisionModel
|
| 338 |
+
|
| 339 |
+
>>> model = Siglip2VisionModel.from_pretrained("google/siglip2-base-patch16-224")
|
| 340 |
+
>>> processor = AutoProcessor.from_pretrained("google/siglip2-base-patch16-224")
|
| 341 |
+
|
| 342 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 343 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 344 |
+
|
| 345 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 346 |
+
|
| 347 |
+
>>> outputs = model(**inputs)
|
| 348 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
| 349 |
+
>>> pooled_output = outputs.pooler_output # pooled features
|
| 350 |
+
```"""
|
| 351 |
+
return self.vision_model(
|
| 352 |
+
pixel_values=pixel_values,
|
| 353 |
+
attention_mask=pixel_attention_mask,
|
| 354 |
+
spatial_shapes=spatial_shapes,
|
| 355 |
+
output_attentions=output_attentions,
|
| 356 |
+
output_hidden_states=output_hidden_states,
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
class Siglip2Model(SiglipModel):
|
| 361 |
+
# Update: add `spatial_shapes` and `pixel_attention_mask`
|
| 362 |
+
def get_image_features(
|
| 363 |
+
self,
|
| 364 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 365 |
+
pixel_attention_mask: Optional[torch.Tensor] = None,
|
| 366 |
+
spatial_shapes: Optional[torch.LongTensor] = None,
|
| 367 |
+
output_attentions: Optional[bool] = None,
|
| 368 |
+
output_hidden_states: Optional[bool] = None,
|
| 369 |
+
) -> torch.FloatTensor:
|
| 370 |
+
r"""
|
| 371 |
+
pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
|
| 372 |
+
Mask to avoid performing attention on padding pixel indices.
|
| 373 |
+
spatial_shapes (`torch.LongTensor` of shape `(batch_size, 2)`):
|
| 374 |
+
Tensor containing the spatial dimensions (height, width) of the input images.
|
| 375 |
+
|
| 376 |
+
Returns:
|
| 377 |
+
image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
|
| 378 |
+
applying the projection layer to the pooled output of [`Siglip2VisionModel`].
|
| 379 |
+
|
| 380 |
+
Examples:
|
| 381 |
+
|
| 382 |
+
```python
|
| 383 |
+
>>> from PIL import Image
|
| 384 |
+
>>> import requests
|
| 385 |
+
>>> from transformers import AutoProcessor, AutoModel
|
| 386 |
+
>>> import torch
|
| 387 |
+
|
| 388 |
+
>>> model = AutoModel.from_pretrained("google/siglip2-base-patch16-224")
|
| 389 |
+
>>> processor = AutoProcessor.from_pretrained("google/siglip2-base-patch16-224")
|
| 390 |
+
|
| 391 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 392 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 393 |
+
|
| 394 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 395 |
+
|
| 396 |
+
>>> with torch.no_grad():
|
| 397 |
+
... image_features = model.get_image_features(**inputs)
|
| 398 |
+
```
|
| 399 |
+
"""
|
| 400 |
+
# Use Siglip2Model's config for some fields (if specified) instead of those of vision & text components.
|
| 401 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 402 |
+
output_hidden_states = (
|
| 403 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 404 |
+
)
|
| 405 |
+
|
| 406 |
+
vision_outputs: BaseModelOutputWithPooling = self.vision_model(
|
| 407 |
+
pixel_values=pixel_values,
|
| 408 |
+
attention_mask=pixel_attention_mask,
|
| 409 |
+
spatial_shapes=spatial_shapes,
|
| 410 |
+
output_attentions=output_attentions,
|
| 411 |
+
output_hidden_states=output_hidden_states,
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
pooled_output = vision_outputs.pooler_output
|
| 415 |
+
|
| 416 |
+
return pooled_output
|
| 417 |
+
|
| 418 |
+
# Update: add `spatial_shapes` and `pixel_attention_mask`
|
| 419 |
+
def forward(
|
| 420 |
+
self,
|
| 421 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 422 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 423 |
+
pixel_attention_mask: Optional[torch.Tensor] = None,
|
| 424 |
+
spatial_shapes: Optional[torch.LongTensor] = None,
|
| 425 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 426 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 427 |
+
return_loss: Optional[bool] = None,
|
| 428 |
+
output_attentions: Optional[bool] = None,
|
| 429 |
+
output_hidden_states: Optional[bool] = None,
|
| 430 |
+
) -> Siglip2Output:
|
| 431 |
+
r"""
|
| 432 |
+
pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
|
| 433 |
+
Mask to avoid performing attention on padding pixel indices.
|
| 434 |
+
spatial_shapes (`torch.LongTensor` of shape `(batch_size, 2)`):
|
| 435 |
+
Tensor containing the spatial dimensions (height, width) of the input images.
|
| 436 |
+
return_loss (`bool`, *optional*):
|
| 437 |
+
Whether or not to return the contrastive loss.
|
| 438 |
+
|
| 439 |
+
Examples:
|
| 440 |
+
|
| 441 |
+
```python
|
| 442 |
+
>>> from PIL import Image
|
| 443 |
+
>>> import requests
|
| 444 |
+
>>> from transformers import AutoProcessor, AutoModel
|
| 445 |
+
>>> import torch
|
| 446 |
+
|
| 447 |
+
>>> model = AutoModel.from_pretrained("google/siglip2-base-patch16-224")
|
| 448 |
+
>>> processor = AutoProcessor.from_pretrained("google/siglip2-base-patch16-224")
|
| 449 |
+
|
| 450 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 451 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 452 |
+
|
| 453 |
+
>>> texts = ["a photo of 2 cats", "a photo of 2 dogs"]
|
| 454 |
+
>>> # important: we pass `padding=max_length` since the model was trained with this
|
| 455 |
+
>>> inputs = processor(text=texts, images=image, padding="max_length", return_tensors="pt")
|
| 456 |
+
|
| 457 |
+
>>> with torch.no_grad():
|
| 458 |
+
... outputs = model(**inputs)
|
| 459 |
+
|
| 460 |
+
>>> logits_per_image = outputs.logits_per_image
|
| 461 |
+
>>> probs = torch.sigmoid(logits_per_image) # these are the probabilities
|
| 462 |
+
>>> print(f"{probs[0][0]:.1%} that image 0 is '{texts[0]}'")
|
| 463 |
+
31.9% that image 0 is 'a photo of 2 cats'
|
| 464 |
+
```
|
| 465 |
+
"""
|
| 466 |
+
# Use Siglip2 model's config for some fields (if specified) instead of those of vision & text components.
|
| 467 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 468 |
+
output_hidden_states = (
|
| 469 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
vision_outputs: BaseModelOutputWithPooling = self.vision_model(
|
| 473 |
+
pixel_values=pixel_values,
|
| 474 |
+
attention_mask=pixel_attention_mask,
|
| 475 |
+
spatial_shapes=spatial_shapes,
|
| 476 |
+
output_attentions=output_attentions,
|
| 477 |
+
output_hidden_states=output_hidden_states,
|
| 478 |
+
)
|
| 479 |
+
|
| 480 |
+
text_outputs: BaseModelOutputWithPooling = self.text_model(
|
| 481 |
+
input_ids=input_ids,
|
| 482 |
+
attention_mask=attention_mask,
|
| 483 |
+
position_ids=position_ids,
|
| 484 |
+
output_attentions=output_attentions,
|
| 485 |
+
output_hidden_states=output_hidden_states,
|
| 486 |
+
)
|
| 487 |
+
|
| 488 |
+
image_embeds = vision_outputs.pooler_output
|
| 489 |
+
text_embeds = text_outputs.pooler_output
|
| 490 |
+
|
| 491 |
+
# normalized features
|
| 492 |
+
image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
|
| 493 |
+
text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
|
| 494 |
+
|
| 495 |
+
# cosine similarity as logits
|
| 496 |
+
logits_per_text = torch.matmul(text_embeds, image_embeds.t().to(text_embeds.device))
|
| 497 |
+
|
| 498 |
+
logit_scale, logit_bias = self.logit_scale.to(text_embeds.device), self.logit_bias.to(text_embeds.device)
|
| 499 |
+
logits_per_text = logits_per_text * logit_scale.exp() + logit_bias
|
| 500 |
+
|
| 501 |
+
logits_per_image = logits_per_text.t()
|
| 502 |
+
|
| 503 |
+
loss = None
|
| 504 |
+
if return_loss:
|
| 505 |
+
# Adapted from https://github.com/google-research/big_vision/blob/01edb81a4716f93a48be43b3a4af14e29cdb3a7f/big_vision/trainers/proj/image_text/siglip2.py#L287
|
| 506 |
+
eye = torch.eye(logits_per_text.size(0), device=logits_per_text.device)
|
| 507 |
+
m1_diag1 = -torch.ones_like(logits_per_text) + 2 * eye
|
| 508 |
+
loglik = torch.nn.functional.logsigmoid(m1_diag1 * logits_per_text)
|
| 509 |
+
nll = -torch.sum(loglik, dim=-1)
|
| 510 |
+
loss = nll.mean()
|
| 511 |
+
|
| 512 |
+
return Siglip2Output(
|
| 513 |
+
loss=loss,
|
| 514 |
+
logits_per_image=logits_per_image,
|
| 515 |
+
logits_per_text=logits_per_text,
|
| 516 |
+
text_embeds=text_embeds,
|
| 517 |
+
image_embeds=image_embeds,
|
| 518 |
+
text_model_output=text_outputs,
|
| 519 |
+
vision_model_output=vision_outputs,
|
| 520 |
+
)
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
class Siglip2ForImageClassification(SiglipForImageClassification):
|
| 524 |
+
# Update: add `spatial_shapes` and `pixel_attention_mask`
|
| 525 |
+
def forward(
|
| 526 |
+
self,
|
| 527 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 528 |
+
pixel_attention_mask: Optional[torch.Tensor] = None,
|
| 529 |
+
spatial_shapes: Optional[torch.LongTensor] = None,
|
| 530 |
+
labels: Optional[torch.Tensor] = None,
|
| 531 |
+
output_attentions: Optional[bool] = None,
|
| 532 |
+
output_hidden_states: Optional[bool] = None,
|
| 533 |
+
) -> ImageClassifierOutput:
|
| 534 |
+
r"""
|
| 535 |
+
pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
|
| 536 |
+
Mask to avoid performing attention on padding pixel indices.
|
| 537 |
+
spatial_shapes (`torch.LongTensor` of shape `(batch_size, 2)`):
|
| 538 |
+
Tensor containing the spatial dimensions (height, width) of the input images.
|
| 539 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 540 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 541 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 542 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 543 |
+
|
| 544 |
+
Examples:
|
| 545 |
+
|
| 546 |
+
```python
|
| 547 |
+
>>> from transformers import AutoImageProcessor, Siglip2ForImageClassification
|
| 548 |
+
>>> import torch
|
| 549 |
+
>>> from PIL import Image
|
| 550 |
+
>>> import requests
|
| 551 |
+
|
| 552 |
+
>>> torch.manual_seed(3) # doctest: +IGNORE_RESULT
|
| 553 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 554 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 555 |
+
|
| 556 |
+
>>> # note: we are loading a `Siglip2Model` from the hub here,
|
| 557 |
+
>>> # so the head will be randomly initialized, hence the predictions will be random if seed is not set above.
|
| 558 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("google/siglip2-base-patch16-224")
|
| 559 |
+
>>> model = Siglip2ForImageClassification.from_pretrained("google/siglip2-base-patch16-224")
|
| 560 |
+
|
| 561 |
+
>>> inputs = image_processor(images=image, return_tensors="pt")
|
| 562 |
+
>>> outputs = model(**inputs)
|
| 563 |
+
>>> logits = outputs.logits
|
| 564 |
+
>>> # model predicts one of the two classes
|
| 565 |
+
>>> predicted_class_idx = logits.argmax(-1).item()
|
| 566 |
+
>>> print("Predicted class:", model.config.id2label[predicted_class_idx])
|
| 567 |
+
Predicted class: LABEL_1
|
| 568 |
+
```
|
| 569 |
+
"""
|
| 570 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 571 |
+
output_hidden_states = (
|
| 572 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 573 |
+
)
|
| 574 |
+
|
| 575 |
+
outputs: BaseModelOutputWithPooling = self.vision_model(
|
| 576 |
+
pixel_values,
|
| 577 |
+
attention_mask=pixel_attention_mask,
|
| 578 |
+
spatial_shapes=spatial_shapes,
|
| 579 |
+
output_attentions=output_attentions,
|
| 580 |
+
output_hidden_states=output_hidden_states,
|
| 581 |
+
)
|
| 582 |
+
|
| 583 |
+
sequence_output = outputs.last_hidden_state
|
| 584 |
+
|
| 585 |
+
# average pool the patch tokens
|
| 586 |
+
if pixel_attention_mask is not None:
|
| 587 |
+
pool_mask = pixel_attention_mask[..., None].to(sequence_output.device)
|
| 588 |
+
sequence_output = torch.sum(sequence_output * pool_mask, dim=1) / torch.sum(pool_mask, dim=1)
|
| 589 |
+
else:
|
| 590 |
+
sequence_output = torch.mean(sequence_output, dim=1)
|
| 591 |
+
|
| 592 |
+
# apply classifier
|
| 593 |
+
logits = self.classifier(sequence_output)
|
| 594 |
+
|
| 595 |
+
loss = None
|
| 596 |
+
if labels is not None:
|
| 597 |
+
# move labels to correct device to enable model parallelism
|
| 598 |
+
labels = labels.to(logits.device)
|
| 599 |
+
if self.config.problem_type is None:
|
| 600 |
+
if self.num_labels == 1:
|
| 601 |
+
self.config.problem_type = "regression"
|
| 602 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 603 |
+
self.config.problem_type = "single_label_classification"
|
| 604 |
+
else:
|
| 605 |
+
self.config.problem_type = "multi_label_classification"
|
| 606 |
+
|
| 607 |
+
if self.config.problem_type == "regression":
|
| 608 |
+
loss_fct = MSELoss()
|
| 609 |
+
if self.num_labels == 1:
|
| 610 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 611 |
+
else:
|
| 612 |
+
loss = loss_fct(logits, labels)
|
| 613 |
+
elif self.config.problem_type == "single_label_classification":
|
| 614 |
+
loss_fct = CrossEntropyLoss()
|
| 615 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 616 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 617 |
+
loss_fct = BCEWithLogitsLoss()
|
| 618 |
+
loss = loss_fct(logits, labels)
|
| 619 |
+
|
| 620 |
+
return ImageClassifierOutput(
|
| 621 |
+
loss=loss,
|
| 622 |
+
logits=logits,
|
| 623 |
+
hidden_states=outputs.hidden_states,
|
| 624 |
+
attentions=outputs.attentions,
|
| 625 |
+
)
|
| 626 |
+
|
| 627 |
+
|
| 628 |
+
__all__ = [
|
| 629 |
+
"Siglip2Config",
|
| 630 |
+
"Siglip2TextConfig",
|
| 631 |
+
"Siglip2VisionConfig",
|
| 632 |
+
"Siglip2Model",
|
| 633 |
+
"Siglip2PreTrainedModel",
|
| 634 |
+
"Siglip2TextModel",
|
| 635 |
+
"Siglip2VisionModel",
|
| 636 |
+
"Siglip2ForImageClassification",
|
| 637 |
+
]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/siglip2/processing_siglip2.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Image/Text processor class for SigLIP2.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from typing import Optional, Union
|
| 20 |
+
|
| 21 |
+
from ...feature_extraction_utils import BatchFeature
|
| 22 |
+
from ...image_utils import ImageInput
|
| 23 |
+
from ...processing_utils import ImagesKwargs, ProcessingKwargs, ProcessorMixin, Unpack
|
| 24 |
+
from ...tokenization_utils_base import PreTokenizedInput, TextInput
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class Siglip2ImagesKwargs(ImagesKwargs, total=False):
|
| 28 |
+
max_num_patches: Optional[int]
|
| 29 |
+
patch_size: Optional[int]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class Siglip2ProcessorKwargs(ProcessingKwargs, total=False):
|
| 33 |
+
images_kwargs: Siglip2ImagesKwargs
|
| 34 |
+
|
| 35 |
+
_defaults = {
|
| 36 |
+
"text_kwargs": {
|
| 37 |
+
"padding": "max_length",
|
| 38 |
+
"truncation": True,
|
| 39 |
+
"max_length": 64,
|
| 40 |
+
},
|
| 41 |
+
"images_kwargs": {
|
| 42 |
+
"max_num_patches": 256,
|
| 43 |
+
"patch_size": 16,
|
| 44 |
+
},
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class Siglip2Processor(ProcessorMixin):
|
| 49 |
+
r"""
|
| 50 |
+
Constructs a Siglip2 processor which wraps a Siglip2 image processor and a Gemma tokenizer into a single processor.
|
| 51 |
+
|
| 52 |
+
[`Siglip2Processor`] offers all the functionalities of [`Siglip2ImageProcessor`] and [`GemmaTokenizerFast`]. See the
|
| 53 |
+
[`~Siglip2Processor.__call__`] and [`~Siglip2Processor.decode`] for more information.
|
| 54 |
+
|
| 55 |
+
Args:
|
| 56 |
+
image_processor ([`Siglip2ImageProcessor`]):
|
| 57 |
+
The image processor is a required input.
|
| 58 |
+
tokenizer ([`GemmaTokenizerFast`]):
|
| 59 |
+
The tokenizer is a required input.
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
attributes = ["image_processor", "tokenizer"]
|
| 63 |
+
|
| 64 |
+
image_processor_class = "AutoImageProcessor"
|
| 65 |
+
tokenizer_class = "AutoTokenizer"
|
| 66 |
+
|
| 67 |
+
def __init__(self, image_processor, tokenizer):
|
| 68 |
+
super().__init__(image_processor, tokenizer)
|
| 69 |
+
|
| 70 |
+
def __call__(
|
| 71 |
+
self,
|
| 72 |
+
images: Optional[Union[ImageInput, list[ImageInput], list[list[ImageInput]]]] = None,
|
| 73 |
+
text: Optional[Union[TextInput, "PreTokenizedInput", list[TextInput], list["PreTokenizedInput"]]] = None,
|
| 74 |
+
audio=None,
|
| 75 |
+
videos=None,
|
| 76 |
+
**kwargs: Unpack[Siglip2ProcessorKwargs],
|
| 77 |
+
) -> BatchFeature:
|
| 78 |
+
"""
|
| 79 |
+
Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
|
| 80 |
+
and `kwargs` arguments to GemmaTokenizerFast's [`~GemmaTokenizerFast.__call__`] if `text` is not `None` to encode
|
| 81 |
+
the text. To prepare the image(s), this method forwards the `images` argument to
|
| 82 |
+
Siglip2ImageProcessor's [`~Siglip2ImageProcessor.__call__`] if `images` is not `None`. Please refer to the docstring
|
| 83 |
+
of the above two methods for more information.
|
| 84 |
+
|
| 85 |
+
Args:
|
| 86 |
+
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
|
| 87 |
+
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
| 88 |
+
tensor. Both channels-first and channels-last formats are supported.
|
| 89 |
+
text (`str`, `list[str]`, `list[list[str]]`):
|
| 90 |
+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
|
| 91 |
+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
| 92 |
+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
| 93 |
+
padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `max_length`):
|
| 94 |
+
Select a strategy to pad the returned sequences (according to the model's padding side and padding
|
| 95 |
+
index) among:
|
| 96 |
+
- `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
|
| 97 |
+
acceptable input length for the model if that argument is not provided.
|
| 98 |
+
- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
|
| 99 |
+
sequence if provided).
|
| 100 |
+
- `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
|
| 101 |
+
lengths).
|
| 102 |
+
max_length (`int`, *optional*, defaults to 64):
|
| 103 |
+
Maximum length of the returned list and optionally padding length (see above).
|
| 104 |
+
truncation (`bool`, *optional*, defaults to `True`):
|
| 105 |
+
Activates truncation to cut input sequences longer than `max_length` to `max_length`.
|
| 106 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*, defaults to `'pt'`):
|
| 107 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
| 108 |
+
|
| 109 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 110 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 111 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
| 112 |
+
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
| 113 |
+
|
| 114 |
+
Returns:
|
| 115 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
| 116 |
+
|
| 117 |
+
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
|
| 118 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
| 119 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
| 120 |
+
`None`).
|
| 121 |
+
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
|
| 122 |
+
- **pixel_attention_mask** -- Attention mask for the pixel values. Returned when `images` is not `None`.
|
| 123 |
+
- **spatial_shapes** -- The number of horizontal and vertical patches per image.
|
| 124 |
+
Returned when `images` is not `None`.
|
| 125 |
+
"""
|
| 126 |
+
output_kwargs = self._merge_kwargs(
|
| 127 |
+
Siglip2ProcessorKwargs,
|
| 128 |
+
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
|
| 129 |
+
**kwargs,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
if text is None and images is None:
|
| 133 |
+
raise ValueError("You have to specify either text or images. Both cannot be none.")
|
| 134 |
+
|
| 135 |
+
if text is not None:
|
| 136 |
+
encoding = self.tokenizer(text, **output_kwargs["text_kwargs"])
|
| 137 |
+
|
| 138 |
+
if images is not None:
|
| 139 |
+
image_features = self.image_processor(images, **output_kwargs["images_kwargs"])
|
| 140 |
+
|
| 141 |
+
if text is not None and images is not None:
|
| 142 |
+
encoding.update(image_features)
|
| 143 |
+
return encoding
|
| 144 |
+
elif text is not None:
|
| 145 |
+
return encoding
|
| 146 |
+
else:
|
| 147 |
+
return_tensors = output_kwargs["common_kwargs"]["return_tensors"]
|
| 148 |
+
return BatchFeature(data=dict(**image_features), tensor_type=return_tensors)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
__all__ = ["Siglip2Processor"]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/smollm3/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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_smollm3 import *
|
| 22 |
+
from .modeling_smollm3 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__)
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/smollm3/configuration_smollm3.py
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/smollm3/modular_smollm3.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_smollm3.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# coding=utf-8
|
| 8 |
+
# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
|
| 9 |
+
#
|
| 10 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 11 |
+
# you may not use this file except in compliance with the License.
|
| 12 |
+
# You may obtain a copy of the License at
|
| 13 |
+
#
|
| 14 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 15 |
+
#
|
| 16 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 17 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 18 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 19 |
+
# See the License for the specific language governing permissions and
|
| 20 |
+
# limitations under the License.
|
| 21 |
+
|
| 22 |
+
from ...configuration_utils import PretrainedConfig, layer_type_validation
|
| 23 |
+
from ...modeling_rope_utils import rope_config_validation
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class SmolLM3Config(PretrainedConfig):
|
| 27 |
+
r"""
|
| 28 |
+
This is the configuration class to store the configuration of a [`SmolLM3Model`]. It is used to instantiate a
|
| 29 |
+
SmolLM3 model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 30 |
+
with the defaults will yield a similar configuration to that of the SmolLM3 3B.
|
| 31 |
+
e.g. [HuggingFaceTB/SmolLM3-3B](https://huggingface.co/HuggingFaceTB/SmolLM3-3B)
|
| 32 |
+
|
| 33 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 34 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
vocab_size (`int`, *optional*, defaults to 128256):
|
| 38 |
+
Vocabulary size of the SmolLM3 model. Defines the number of different tokens that can be represented by the
|
| 39 |
+
`inputs_ids` passed when calling [`SmolLM3Model`]
|
| 40 |
+
hidden_size (`int`, *optional*, defaults to 2048):
|
| 41 |
+
Dimension of the hidden representations.
|
| 42 |
+
intermediate_size (`int`, *optional*, defaults to 11008):
|
| 43 |
+
Dimension of the MLP representations.
|
| 44 |
+
num_hidden_layers (`int`, *optional*, defaults to 36):
|
| 45 |
+
Number of hidden layers in the Transformer encoder.
|
| 46 |
+
num_attention_heads (`int`, *optional*, defaults to 16):
|
| 47 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 48 |
+
num_key_value_heads (`int`, *optional*, defaults to 4):
|
| 49 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
| 50 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
| 51 |
+
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
| 52 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
| 53 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
| 54 |
+
paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `16`.
|
| 55 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
| 56 |
+
The non-linear activation function (function or string) in the decoder.
|
| 57 |
+
max_position_embeddings (`int`, *optional*, defaults to 32768):
|
| 58 |
+
The maximum sequence length that this model might ever be used with.
|
| 59 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 60 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 61 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
| 62 |
+
The epsilon used by the rms normalization layers.
|
| 63 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 64 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 65 |
+
relevant if `config.is_decoder=True`.
|
| 66 |
+
pad_token_id (`int`, *optional*, defaults to 128004):
|
| 67 |
+
The id of the padding token.
|
| 68 |
+
bos_token_id (`int`, *optional*, defaults to 128000):
|
| 69 |
+
The id of the beginning of sentence token.
|
| 70 |
+
eos_token_id (`int`, *optional*, defaults to 128001):
|
| 71 |
+
The id of the end of sentence token.
|
| 72 |
+
rope_theta (`float`, *optional*, defaults to 2000000.0):
|
| 73 |
+
The base period of the RoPE embeddings.
|
| 74 |
+
rope_scaling (`Dict`, *optional*):
|
| 75 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
|
| 76 |
+
and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
|
| 77 |
+
accordingly.
|
| 78 |
+
Expected contents:
|
| 79 |
+
`rope_type` (`str`):
|
| 80 |
+
The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
|
| 81 |
+
'llama3'], with 'default' being the original RoPE implementation.
|
| 82 |
+
`factor` (`float`, *optional*):
|
| 83 |
+
Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
|
| 84 |
+
most scaling types, a `factor` of x will enable the model to handle sequences of length x *
|
| 85 |
+
original maximum pre-trained length.
|
| 86 |
+
`original_max_position_embeddings` (`int`, *optional*):
|
| 87 |
+
Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
|
| 88 |
+
pretraining.
|
| 89 |
+
`attention_factor` (`float`, *optional*):
|
| 90 |
+
Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
|
| 91 |
+
computation. If unspecified, it defaults to value recommended by the implementation, using the
|
| 92 |
+
`factor` field to infer the suggested value.
|
| 93 |
+
`beta_fast` (`float`, *optional*):
|
| 94 |
+
Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
|
| 95 |
+
ramp function. If unspecified, it defaults to 32.
|
| 96 |
+
`beta_slow` (`float`, *optional*):
|
| 97 |
+
Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
|
| 98 |
+
ramp function. If unspecified, it defaults to 1.
|
| 99 |
+
`short_factor` (`List[float]`, *optional*):
|
| 100 |
+
Only used with 'longrope'. The scaling factor to be applied to short contexts (<
|
| 101 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
| 102 |
+
size divided by the number of attention heads divided by 2
|
| 103 |
+
`long_factor` (`List[float]`, *optional*):
|
| 104 |
+
Only used with 'longrope'. The scaling factor to be applied to long contexts (<
|
| 105 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
| 106 |
+
size divided by the number of attention heads divided by 2
|
| 107 |
+
`low_freq_factor` (`float`, *optional*):
|
| 108 |
+
Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
|
| 109 |
+
`high_freq_factor` (`float`, *optional*):
|
| 110 |
+
Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
|
| 111 |
+
use_sliding_window (`bool`, *optional*, defaults to `False`):
|
| 112 |
+
Whether to use sliding window attention.
|
| 113 |
+
sliding_window (`int`, *optional*):
|
| 114 |
+
Sliding window attention (SWA) window size. If not specified, will default to `None`.
|
| 115 |
+
no_rope_layers (`List[int]`, *optional*):
|
| 116 |
+
List with at least the same length as the number of layers in the model.
|
| 117 |
+
A `1` at an index position indicates that the corresponding layer will use RoPE,
|
| 118 |
+
while a `0` indicates that it's a NoPE layer.
|
| 119 |
+
no_rope_layer_interval (`int`, *optional*, defaults to 4):
|
| 120 |
+
If `no_rope_layers` is `None`, it will be created using a NoPE layer every
|
| 121 |
+
`no_rope_layer_interval` layers.
|
| 122 |
+
layer_types (`list`, *optional*):
|
| 123 |
+
Attention pattern for each layer. Automatically computed based on sliding window and NoPE settings.
|
| 124 |
+
attention_bias (`bool`, *optional*, defaults to `False`):
|
| 125 |
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
| 126 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 127 |
+
The dropout ratio for the attention probabilities.
|
| 128 |
+
|
| 129 |
+
```python
|
| 130 |
+
>>> from transformers import SmolLM3Model, SmolLM3Config
|
| 131 |
+
|
| 132 |
+
>>> # Initializing a SmolLM3 style configuration
|
| 133 |
+
>>> configuration = SmolLM3Config()
|
| 134 |
+
|
| 135 |
+
>>> # Initializing a model from the SmolLM3 style configuration
|
| 136 |
+
>>> model = SmolLM3Model(configuration)
|
| 137 |
+
|
| 138 |
+
>>> # Accessing the model configuration
|
| 139 |
+
>>> configuration = model.config
|
| 140 |
+
```"""
|
| 141 |
+
|
| 142 |
+
model_type = "smollm3"
|
| 143 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 144 |
+
|
| 145 |
+
base_model_tp_plan = {
|
| 146 |
+
"layers.*.self_attn.q_proj": "colwise",
|
| 147 |
+
"layers.*.self_attn.k_proj": "colwise",
|
| 148 |
+
"layers.*.self_attn.v_proj": "colwise",
|
| 149 |
+
"layers.*.self_attn.o_proj": "rowwise",
|
| 150 |
+
"layers.*.mlp.gate_proj": "colwise",
|
| 151 |
+
"layers.*.mlp.up_proj": "colwise",
|
| 152 |
+
"layers.*.mlp.down_proj": "rowwise",
|
| 153 |
+
}
|
| 154 |
+
base_model_pp_plan = {
|
| 155 |
+
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
| 156 |
+
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
|
| 157 |
+
"norm": (["hidden_states"], ["hidden_states"]),
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
def __init__(
|
| 161 |
+
self,
|
| 162 |
+
vocab_size=128256,
|
| 163 |
+
hidden_size=2048,
|
| 164 |
+
intermediate_size=11008,
|
| 165 |
+
num_hidden_layers=36,
|
| 166 |
+
num_attention_heads=16,
|
| 167 |
+
num_key_value_heads=4,
|
| 168 |
+
hidden_act="silu",
|
| 169 |
+
max_position_embeddings=32768,
|
| 170 |
+
initializer_range=0.02,
|
| 171 |
+
rms_norm_eps=1e-6,
|
| 172 |
+
use_cache=True,
|
| 173 |
+
pad_token_id=128004,
|
| 174 |
+
bos_token_id=128000,
|
| 175 |
+
eos_token_id=128001,
|
| 176 |
+
rope_theta=2000000.0,
|
| 177 |
+
rope_scaling=None,
|
| 178 |
+
use_sliding_window=False,
|
| 179 |
+
sliding_window=None,
|
| 180 |
+
no_rope_layers=None,
|
| 181 |
+
no_rope_layer_interval=4,
|
| 182 |
+
layer_types=None,
|
| 183 |
+
attention_bias=False,
|
| 184 |
+
attention_dropout=0.0,
|
| 185 |
+
mlp_bias=False,
|
| 186 |
+
**kwargs,
|
| 187 |
+
):
|
| 188 |
+
super().__init__(
|
| 189 |
+
pad_token_id=pad_token_id,
|
| 190 |
+
bos_token_id=bos_token_id,
|
| 191 |
+
eos_token_id=eos_token_id,
|
| 192 |
+
**kwargs,
|
| 193 |
+
)
|
| 194 |
+
self.vocab_size = vocab_size
|
| 195 |
+
self.max_position_embeddings = max_position_embeddings
|
| 196 |
+
self.mlp_bias = mlp_bias
|
| 197 |
+
self.hidden_size = hidden_size
|
| 198 |
+
self.intermediate_size = intermediate_size
|
| 199 |
+
self.num_hidden_layers = num_hidden_layers
|
| 200 |
+
self.num_attention_heads = num_attention_heads
|
| 201 |
+
self.use_sliding_window = use_sliding_window
|
| 202 |
+
self.sliding_window = sliding_window
|
| 203 |
+
|
| 204 |
+
# for backward compatibility
|
| 205 |
+
if num_key_value_heads is None:
|
| 206 |
+
num_key_value_heads = num_attention_heads
|
| 207 |
+
|
| 208 |
+
self.num_key_value_heads = num_key_value_heads
|
| 209 |
+
self.hidden_act = hidden_act
|
| 210 |
+
self.initializer_range = initializer_range
|
| 211 |
+
self.rms_norm_eps = rms_norm_eps
|
| 212 |
+
self.use_cache = use_cache
|
| 213 |
+
self.rope_theta = rope_theta
|
| 214 |
+
self.rope_scaling = rope_scaling
|
| 215 |
+
self.attention_bias = attention_bias
|
| 216 |
+
self.attention_dropout = attention_dropout
|
| 217 |
+
|
| 218 |
+
if no_rope_layers is None:
|
| 219 |
+
self.no_rope_layers = [
|
| 220 |
+
int((layer_idx + 1) % no_rope_layer_interval != 0) for layer_idx in range(num_hidden_layers)
|
| 221 |
+
]
|
| 222 |
+
else:
|
| 223 |
+
self.no_rope_layers = no_rope_layers
|
| 224 |
+
|
| 225 |
+
self.no_rope_layer_interval = no_rope_layer_interval
|
| 226 |
+
|
| 227 |
+
# Update layer_types based on sliding window and NoPE pattern
|
| 228 |
+
if layer_types is None:
|
| 229 |
+
layer_types = []
|
| 230 |
+
for layer_idx in range(num_hidden_layers):
|
| 231 |
+
has_rope = self.no_rope_layers[layer_idx]
|
| 232 |
+
if use_sliding_window and sliding_window is not None and not has_rope:
|
| 233 |
+
layer_types.append("sliding_attention")
|
| 234 |
+
else:
|
| 235 |
+
layer_types.append("full_attention")
|
| 236 |
+
|
| 237 |
+
self.layer_types = layer_types
|
| 238 |
+
layer_type_validation(self.layer_types)
|
| 239 |
+
|
| 240 |
+
# Validate the correctness of rotary position embeddings parameters
|
| 241 |
+
# BC: if there is a 'type' field, move it to 'rope_type'.
|
| 242 |
+
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
| 243 |
+
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
| 244 |
+
rope_config_validation(self)
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
__all__ = ["SmolLM3Config"]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/smollm3/modeling_smollm3.py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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/smollm3/modular_smollm3.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_smollm3.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# coding=utf-8
|
| 8 |
+
# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
|
| 9 |
+
#
|
| 10 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 11 |
+
# you may not use this file except in compliance with the License.
|
| 12 |
+
# You may obtain a copy of the License at
|
| 13 |
+
#
|
| 14 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 15 |
+
#
|
| 16 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 17 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 18 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 19 |
+
# See the License for the specific language governing permissions and
|
| 20 |
+
# limitations under the License.
|
| 21 |
+
|
| 22 |
+
from typing import Callable, Optional, Union
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
from torch import nn
|
| 26 |
+
|
| 27 |
+
from ...activations import ACT2FN
|
| 28 |
+
from ...cache_utils import Cache, DynamicCache
|
| 29 |
+
from ...generation import GenerationMixin
|
| 30 |
+
from ...integrations import use_kernel_forward_from_hub
|
| 31 |
+
from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask
|
| 32 |
+
from ...modeling_flash_attention_utils import FlashAttentionKwargs
|
| 33 |
+
from ...modeling_layers import (
|
| 34 |
+
GenericForQuestionAnswering,
|
| 35 |
+
GenericForSequenceClassification,
|
| 36 |
+
GenericForTokenClassification,
|
| 37 |
+
GradientCheckpointingLayer,
|
| 38 |
+
)
|
| 39 |
+
from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 40 |
+
from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
| 41 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 42 |
+
from ...processing_utils import Unpack
|
| 43 |
+
from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
|
| 44 |
+
from ...utils.deprecation import deprecate_kwarg
|
| 45 |
+
from ...utils.generic import check_model_inputs
|
| 46 |
+
from .configuration_smollm3 import SmolLM3Config
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def rotate_half(x):
|
| 50 |
+
"""Rotates half the hidden dims of the input."""
|
| 51 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 52 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 53 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
| 57 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 58 |
+
|
| 59 |
+
Args:
|
| 60 |
+
q (`torch.Tensor`): The query tensor.
|
| 61 |
+
k (`torch.Tensor`): The key tensor.
|
| 62 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 63 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 64 |
+
position_ids (`torch.Tensor`, *optional*):
|
| 65 |
+
Deprecated and unused.
|
| 66 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 67 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 68 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 69 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 70 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 71 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 72 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 73 |
+
Returns:
|
| 74 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 75 |
+
"""
|
| 76 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 77 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 78 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 79 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 80 |
+
return q_embed, k_embed
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 84 |
+
"""
|
| 85 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 86 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 87 |
+
"""
|
| 88 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 89 |
+
if n_rep == 1:
|
| 90 |
+
return hidden_states
|
| 91 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 92 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def eager_attention_forward(
|
| 96 |
+
module: nn.Module,
|
| 97 |
+
query: torch.Tensor,
|
| 98 |
+
key: torch.Tensor,
|
| 99 |
+
value: torch.Tensor,
|
| 100 |
+
attention_mask: Optional[torch.Tensor],
|
| 101 |
+
scaling: float,
|
| 102 |
+
dropout: float = 0.0,
|
| 103 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 104 |
+
):
|
| 105 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 106 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 107 |
+
|
| 108 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 109 |
+
if attention_mask is not None:
|
| 110 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
| 111 |
+
attn_weights = attn_weights + causal_mask
|
| 112 |
+
|
| 113 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 114 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 115 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 116 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 117 |
+
|
| 118 |
+
return attn_output, attn_weights
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class SmolLM3Attention(nn.Module):
|
| 122 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 123 |
+
|
| 124 |
+
def __init__(self, config: SmolLM3Config, layer_idx: int):
|
| 125 |
+
super().__init__()
|
| 126 |
+
self.config = config
|
| 127 |
+
self.layer_idx = layer_idx
|
| 128 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 129 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 130 |
+
self.scaling = self.head_dim**-0.5
|
| 131 |
+
self.attention_dropout = config.attention_dropout
|
| 132 |
+
self.is_causal = True
|
| 133 |
+
|
| 134 |
+
self.q_proj = nn.Linear(
|
| 135 |
+
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
| 136 |
+
)
|
| 137 |
+
self.k_proj = nn.Linear(
|
| 138 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 139 |
+
)
|
| 140 |
+
self.v_proj = nn.Linear(
|
| 141 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 142 |
+
)
|
| 143 |
+
self.o_proj = nn.Linear(
|
| 144 |
+
config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
self.use_rope = config.no_rope_layers[layer_idx]
|
| 148 |
+
self.sliding_window = (
|
| 149 |
+
config.sliding_window
|
| 150 |
+
if config.use_sliding_window and config.layer_types[layer_idx] == "sliding_attention"
|
| 151 |
+
else None
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 155 |
+
def forward(
|
| 156 |
+
self,
|
| 157 |
+
hidden_states: torch.Tensor,
|
| 158 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 159 |
+
attention_mask: Optional[torch.Tensor],
|
| 160 |
+
past_key_values: Optional[Cache] = None,
|
| 161 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 162 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 163 |
+
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 164 |
+
input_shape = hidden_states.shape[:-1]
|
| 165 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 166 |
+
|
| 167 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 168 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 169 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 170 |
+
|
| 171 |
+
if self.use_rope:
|
| 172 |
+
cos, sin = position_embeddings
|
| 173 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 174 |
+
|
| 175 |
+
if past_key_values is not None:
|
| 176 |
+
cache_kwargs = {"cache_position": cache_position}
|
| 177 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 178 |
+
|
| 179 |
+
attention_interface: Callable = eager_attention_forward
|
| 180 |
+
if self.config._attn_implementation != "eager":
|
| 181 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 182 |
+
|
| 183 |
+
attn_output, attn_weights = attention_interface(
|
| 184 |
+
self,
|
| 185 |
+
query_states,
|
| 186 |
+
key_states,
|
| 187 |
+
value_states,
|
| 188 |
+
attention_mask,
|
| 189 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 190 |
+
scaling=self.scaling,
|
| 191 |
+
sliding_window=self.sliding_window,
|
| 192 |
+
**kwargs,
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 196 |
+
attn_output = self.o_proj(attn_output)
|
| 197 |
+
return attn_output, attn_weights
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
@use_kernel_forward_from_hub("RMSNorm")
|
| 201 |
+
class SmolLM3RMSNorm(nn.Module):
|
| 202 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 203 |
+
"""
|
| 204 |
+
SmolLM3RMSNorm is equivalent to T5LayerNorm
|
| 205 |
+
"""
|
| 206 |
+
super().__init__()
|
| 207 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 208 |
+
self.variance_epsilon = eps
|
| 209 |
+
|
| 210 |
+
def forward(self, hidden_states):
|
| 211 |
+
input_dtype = hidden_states.dtype
|
| 212 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 213 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 214 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 215 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 216 |
+
|
| 217 |
+
def extra_repr(self):
|
| 218 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
class SmolLM3MLP(nn.Module):
|
| 222 |
+
def __init__(self, config):
|
| 223 |
+
super().__init__()
|
| 224 |
+
self.config = config
|
| 225 |
+
self.hidden_size = config.hidden_size
|
| 226 |
+
self.intermediate_size = config.intermediate_size
|
| 227 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
| 228 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
| 229 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
|
| 230 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 231 |
+
|
| 232 |
+
def forward(self, x):
|
| 233 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 234 |
+
return down_proj
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
class SmolLM3DecoderLayer(GradientCheckpointingLayer):
|
| 238 |
+
def __init__(self, config: SmolLM3Config, layer_idx: int):
|
| 239 |
+
super().__init__()
|
| 240 |
+
self.hidden_size = config.hidden_size
|
| 241 |
+
|
| 242 |
+
self.self_attn = SmolLM3Attention(config=config, layer_idx=layer_idx)
|
| 243 |
+
|
| 244 |
+
self.mlp = SmolLM3MLP(config)
|
| 245 |
+
self.input_layernorm = SmolLM3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 246 |
+
self.post_attention_layernorm = SmolLM3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 247 |
+
self.attention_type = config.layer_types[layer_idx]
|
| 248 |
+
|
| 249 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 250 |
+
def forward(
|
| 251 |
+
self,
|
| 252 |
+
hidden_states: torch.Tensor,
|
| 253 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 254 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 255 |
+
past_key_values: Optional[Cache] = None,
|
| 256 |
+
use_cache: Optional[bool] = False,
|
| 257 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 258 |
+
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
|
| 259 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 260 |
+
) -> torch.Tensor:
|
| 261 |
+
residual = hidden_states
|
| 262 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 263 |
+
# Self Attention
|
| 264 |
+
hidden_states, _ = self.self_attn(
|
| 265 |
+
hidden_states=hidden_states,
|
| 266 |
+
attention_mask=attention_mask,
|
| 267 |
+
position_ids=position_ids,
|
| 268 |
+
past_key_values=past_key_values,
|
| 269 |
+
use_cache=use_cache,
|
| 270 |
+
cache_position=cache_position,
|
| 271 |
+
position_embeddings=position_embeddings,
|
| 272 |
+
**kwargs,
|
| 273 |
+
)
|
| 274 |
+
hidden_states = residual + hidden_states
|
| 275 |
+
|
| 276 |
+
# Fully Connected
|
| 277 |
+
residual = hidden_states
|
| 278 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 279 |
+
hidden_states = self.mlp(hidden_states)
|
| 280 |
+
hidden_states = residual + hidden_states
|
| 281 |
+
return hidden_states
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
@auto_docstring
|
| 285 |
+
class SmolLM3PreTrainedModel(PreTrainedModel):
|
| 286 |
+
config: SmolLM3Config
|
| 287 |
+
base_model_prefix = "model"
|
| 288 |
+
supports_gradient_checkpointing = True
|
| 289 |
+
_no_split_modules = ["SmolLM3DecoderLayer"]
|
| 290 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 291 |
+
_supports_flash_attn = True
|
| 292 |
+
_supports_sdpa = True
|
| 293 |
+
_supports_flex_attn = True
|
| 294 |
+
|
| 295 |
+
_can_compile_fullgraph = True
|
| 296 |
+
_supports_attention_backend = True
|
| 297 |
+
_can_record_outputs = {
|
| 298 |
+
"hidden_states": SmolLM3DecoderLayer,
|
| 299 |
+
"attentions": SmolLM3Attention,
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
class SmolLM3RotaryEmbedding(nn.Module):
|
| 304 |
+
inv_freq: torch.Tensor # fix linting for `register_buffer`
|
| 305 |
+
|
| 306 |
+
def __init__(self, config: SmolLM3Config, device=None):
|
| 307 |
+
super().__init__()
|
| 308 |
+
# BC: "rope_type" was originally "type"
|
| 309 |
+
if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
|
| 310 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
| 311 |
+
else:
|
| 312 |
+
self.rope_type = "default"
|
| 313 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 314 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 315 |
+
|
| 316 |
+
self.config = config
|
| 317 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 318 |
+
|
| 319 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
| 320 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 321 |
+
self.original_inv_freq = self.inv_freq
|
| 322 |
+
|
| 323 |
+
@torch.no_grad()
|
| 324 |
+
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
|
| 325 |
+
def forward(self, x, position_ids):
|
| 326 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
|
| 327 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 328 |
+
|
| 329 |
+
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
| 330 |
+
with torch.autocast(device_type=device_type, enabled=False): # Force float32
|
| 331 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 332 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 333 |
+
cos = emb.cos() * self.attention_scaling
|
| 334 |
+
sin = emb.sin() * self.attention_scaling
|
| 335 |
+
|
| 336 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
@auto_docstring
|
| 340 |
+
class SmolLM3Model(SmolLM3PreTrainedModel):
|
| 341 |
+
def __init__(self, config: SmolLM3Config):
|
| 342 |
+
super().__init__(config)
|
| 343 |
+
self.padding_idx = config.pad_token_id
|
| 344 |
+
self.vocab_size = config.vocab_size
|
| 345 |
+
|
| 346 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 347 |
+
self.layers = nn.ModuleList(
|
| 348 |
+
[SmolLM3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 349 |
+
)
|
| 350 |
+
self.norm = SmolLM3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 351 |
+
self.rotary_emb = SmolLM3RotaryEmbedding(config=config)
|
| 352 |
+
self.gradient_checkpointing = False
|
| 353 |
+
self.has_sliding_layers = "sliding_attention" in self.config.layer_types
|
| 354 |
+
|
| 355 |
+
# Initialize weights and apply final processing
|
| 356 |
+
self.post_init()
|
| 357 |
+
|
| 358 |
+
@check_model_inputs
|
| 359 |
+
@auto_docstring
|
| 360 |
+
def forward(
|
| 361 |
+
self,
|
| 362 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 363 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 364 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 365 |
+
past_key_values: Optional[Cache] = None,
|
| 366 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 367 |
+
use_cache: Optional[bool] = None,
|
| 368 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 369 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 370 |
+
) -> BaseModelOutputWithPast:
|
| 371 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 372 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 373 |
+
|
| 374 |
+
if inputs_embeds is None:
|
| 375 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 376 |
+
|
| 377 |
+
if use_cache and past_key_values is None:
|
| 378 |
+
past_key_values = DynamicCache(config=self.config)
|
| 379 |
+
|
| 380 |
+
if cache_position is None:
|
| 381 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 382 |
+
cache_position = torch.arange(
|
| 383 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
if position_ids is None:
|
| 387 |
+
position_ids = cache_position.unsqueeze(0)
|
| 388 |
+
|
| 389 |
+
# It may already have been prepared by e.g. `generate`
|
| 390 |
+
if not isinstance(causal_mask_mapping := attention_mask, dict):
|
| 391 |
+
# Prepare mask arguments
|
| 392 |
+
mask_kwargs = {
|
| 393 |
+
"config": self.config,
|
| 394 |
+
"input_embeds": inputs_embeds,
|
| 395 |
+
"attention_mask": attention_mask,
|
| 396 |
+
"cache_position": cache_position,
|
| 397 |
+
"past_key_values": past_key_values,
|
| 398 |
+
"position_ids": position_ids,
|
| 399 |
+
}
|
| 400 |
+
# Create the masks
|
| 401 |
+
causal_mask_mapping = {
|
| 402 |
+
"full_attention": create_causal_mask(**mask_kwargs),
|
| 403 |
+
}
|
| 404 |
+
# The sliding window alternating layers are not always activated depending on the config
|
| 405 |
+
if self.has_sliding_layers:
|
| 406 |
+
causal_mask_mapping["sliding_attention"] = create_sliding_window_causal_mask(**mask_kwargs)
|
| 407 |
+
|
| 408 |
+
hidden_states = inputs_embeds
|
| 409 |
+
|
| 410 |
+
# create position embeddings to be shared across the decoder layers
|
| 411 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
| 412 |
+
|
| 413 |
+
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
|
| 414 |
+
hidden_states = decoder_layer(
|
| 415 |
+
hidden_states,
|
| 416 |
+
attention_mask=causal_mask_mapping[decoder_layer.attention_type],
|
| 417 |
+
position_ids=position_ids,
|
| 418 |
+
past_key_values=past_key_values,
|
| 419 |
+
use_cache=use_cache,
|
| 420 |
+
cache_position=cache_position,
|
| 421 |
+
position_embeddings=position_embeddings,
|
| 422 |
+
**kwargs,
|
| 423 |
+
)
|
| 424 |
+
|
| 425 |
+
hidden_states = self.norm(hidden_states)
|
| 426 |
+
return BaseModelOutputWithPast(
|
| 427 |
+
last_hidden_state=hidden_states,
|
| 428 |
+
past_key_values=past_key_values if use_cache else None,
|
| 429 |
+
)
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
@auto_docstring
|
| 433 |
+
class SmolLM3ForCausalLM(SmolLM3PreTrainedModel, GenerationMixin):
|
| 434 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 435 |
+
_tp_plan = {"lm_head": "colwise_rep"}
|
| 436 |
+
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
| 437 |
+
|
| 438 |
+
def __init__(self, config):
|
| 439 |
+
super().__init__(config)
|
| 440 |
+
self.model = SmolLM3Model(config)
|
| 441 |
+
self.vocab_size = config.vocab_size
|
| 442 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 443 |
+
|
| 444 |
+
# Initialize weights and apply final processing
|
| 445 |
+
self.post_init()
|
| 446 |
+
|
| 447 |
+
@can_return_tuple
|
| 448 |
+
@auto_docstring
|
| 449 |
+
def forward(
|
| 450 |
+
self,
|
| 451 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 452 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 453 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 454 |
+
past_key_values: Optional[Cache] = None,
|
| 455 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 456 |
+
labels: Optional[torch.LongTensor] = None,
|
| 457 |
+
use_cache: Optional[bool] = None,
|
| 458 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 459 |
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
| 460 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 461 |
+
) -> CausalLMOutputWithPast:
|
| 462 |
+
r"""
|
| 463 |
+
Example:
|
| 464 |
+
|
| 465 |
+
```python
|
| 466 |
+
>>> from transformers import AutoTokenizer, SmolLM3ForCausalLM
|
| 467 |
+
|
| 468 |
+
>>> model = SmolLM3ForCausalLM.from_pretrained("meta-smollm3/SmolLM3-2-7b-hf")
|
| 469 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("meta-smollm3/SmolLM3-2-7b-hf")
|
| 470 |
+
|
| 471 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
| 472 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
| 473 |
+
|
| 474 |
+
>>> # Generate
|
| 475 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
| 476 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 477 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
| 478 |
+
```"""
|
| 479 |
+
outputs: BaseModelOutputWithPast = self.model(
|
| 480 |
+
input_ids=input_ids,
|
| 481 |
+
attention_mask=attention_mask,
|
| 482 |
+
position_ids=position_ids,
|
| 483 |
+
past_key_values=past_key_values,
|
| 484 |
+
inputs_embeds=inputs_embeds,
|
| 485 |
+
use_cache=use_cache,
|
| 486 |
+
cache_position=cache_position,
|
| 487 |
+
**kwargs,
|
| 488 |
+
)
|
| 489 |
+
|
| 490 |
+
hidden_states = outputs.last_hidden_state
|
| 491 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 492 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 493 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
| 494 |
+
|
| 495 |
+
loss = None
|
| 496 |
+
if labels is not None:
|
| 497 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
| 498 |
+
|
| 499 |
+
return CausalLMOutputWithPast(
|
| 500 |
+
loss=loss,
|
| 501 |
+
logits=logits,
|
| 502 |
+
past_key_values=outputs.past_key_values,
|
| 503 |
+
hidden_states=outputs.hidden_states,
|
| 504 |
+
attentions=outputs.attentions,
|
| 505 |
+
)
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
class SmolLM3ForSequenceClassification(GenericForSequenceClassification, SmolLM3PreTrainedModel):
|
| 509 |
+
pass
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
class SmolLM3ForTokenClassification(GenericForTokenClassification, SmolLM3PreTrainedModel):
|
| 513 |
+
pass
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
class SmolLM3ForQuestionAnswering(GenericForQuestionAnswering, SmolLM3PreTrainedModel):
|
| 517 |
+
base_model_prefix = "transformer" # For BC, where `transformer` was used instead of `model`
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
__all__ = [
|
| 521 |
+
"SmolLM3PreTrainedModel",
|
| 522 |
+
"SmolLM3Model",
|
| 523 |
+
"SmolLM3ForCausalLM",
|
| 524 |
+
"SmolLM3ForSequenceClassification",
|
| 525 |
+
"SmolLM3ForTokenClassification",
|
| 526 |
+
"SmolLM3ForQuestionAnswering",
|
| 527 |
+
]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/smollm3/modular_smollm3.py
ADDED
|
@@ -0,0 +1,361 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
from typing import Callable, Optional
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
|
| 20 |
+
from ...cache_utils import Cache
|
| 21 |
+
from ...configuration_utils import PretrainedConfig, layer_type_validation
|
| 22 |
+
from ...modeling_flash_attention_utils import FlashAttentionKwargs
|
| 23 |
+
from ...modeling_rope_utils import rope_config_validation
|
| 24 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
|
| 25 |
+
from ...processing_utils import Unpack
|
| 26 |
+
from ...utils import logging
|
| 27 |
+
from ...utils.deprecation import deprecate_kwarg
|
| 28 |
+
from ..llama.modeling_llama import (
|
| 29 |
+
LlamaAttention,
|
| 30 |
+
LlamaDecoderLayer,
|
| 31 |
+
LlamaForCausalLM,
|
| 32 |
+
LlamaForQuestionAnswering,
|
| 33 |
+
LlamaForSequenceClassification,
|
| 34 |
+
LlamaForTokenClassification,
|
| 35 |
+
LlamaPreTrainedModel,
|
| 36 |
+
apply_rotary_pos_emb,
|
| 37 |
+
eager_attention_forward,
|
| 38 |
+
)
|
| 39 |
+
from ..qwen2.modeling_qwen2 import Qwen2Model
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
logger = logging.get_logger(__name__)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class SmolLM3Config(PretrainedConfig):
|
| 46 |
+
r"""
|
| 47 |
+
This is the configuration class to store the configuration of a [`SmolLM3Model`]. It is used to instantiate a
|
| 48 |
+
SmolLM3 model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 49 |
+
with the defaults will yield a similar configuration to that of the SmolLM3 3B.
|
| 50 |
+
e.g. [HuggingFaceTB/SmolLM3-3B](https://huggingface.co/HuggingFaceTB/SmolLM3-3B)
|
| 51 |
+
|
| 52 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 53 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 54 |
+
|
| 55 |
+
Args:
|
| 56 |
+
vocab_size (`int`, *optional*, defaults to 128256):
|
| 57 |
+
Vocabulary size of the SmolLM3 model. Defines the number of different tokens that can be represented by the
|
| 58 |
+
`inputs_ids` passed when calling [`SmolLM3Model`]
|
| 59 |
+
hidden_size (`int`, *optional*, defaults to 2048):
|
| 60 |
+
Dimension of the hidden representations.
|
| 61 |
+
intermediate_size (`int`, *optional*, defaults to 11008):
|
| 62 |
+
Dimension of the MLP representations.
|
| 63 |
+
num_hidden_layers (`int`, *optional*, defaults to 36):
|
| 64 |
+
Number of hidden layers in the Transformer encoder.
|
| 65 |
+
num_attention_heads (`int`, *optional*, defaults to 16):
|
| 66 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 67 |
+
num_key_value_heads (`int`, *optional*, defaults to 4):
|
| 68 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
| 69 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
| 70 |
+
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
| 71 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
| 72 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
| 73 |
+
paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `16`.
|
| 74 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
| 75 |
+
The non-linear activation function (function or string) in the decoder.
|
| 76 |
+
max_position_embeddings (`int`, *optional*, defaults to 32768):
|
| 77 |
+
The maximum sequence length that this model might ever be used with.
|
| 78 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 79 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 80 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
| 81 |
+
The epsilon used by the rms normalization layers.
|
| 82 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 83 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 84 |
+
relevant if `config.is_decoder=True`.
|
| 85 |
+
pad_token_id (`int`, *optional*, defaults to 128004):
|
| 86 |
+
The id of the padding token.
|
| 87 |
+
bos_token_id (`int`, *optional*, defaults to 128000):
|
| 88 |
+
The id of the beginning of sentence token.
|
| 89 |
+
eos_token_id (`int`, *optional*, defaults to 128001):
|
| 90 |
+
The id of the end of sentence token.
|
| 91 |
+
rope_theta (`float`, *optional*, defaults to 2000000.0):
|
| 92 |
+
The base period of the RoPE embeddings.
|
| 93 |
+
rope_scaling (`Dict`, *optional*):
|
| 94 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
|
| 95 |
+
and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
|
| 96 |
+
accordingly.
|
| 97 |
+
Expected contents:
|
| 98 |
+
`rope_type` (`str`):
|
| 99 |
+
The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
|
| 100 |
+
'llama3'], with 'default' being the original RoPE implementation.
|
| 101 |
+
`factor` (`float`, *optional*):
|
| 102 |
+
Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
|
| 103 |
+
most scaling types, a `factor` of x will enable the model to handle sequences of length x *
|
| 104 |
+
original maximum pre-trained length.
|
| 105 |
+
`original_max_position_embeddings` (`int`, *optional*):
|
| 106 |
+
Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
|
| 107 |
+
pretraining.
|
| 108 |
+
`attention_factor` (`float`, *optional*):
|
| 109 |
+
Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
|
| 110 |
+
computation. If unspecified, it defaults to value recommended by the implementation, using the
|
| 111 |
+
`factor` field to infer the suggested value.
|
| 112 |
+
`beta_fast` (`float`, *optional*):
|
| 113 |
+
Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
|
| 114 |
+
ramp function. If unspecified, it defaults to 32.
|
| 115 |
+
`beta_slow` (`float`, *optional*):
|
| 116 |
+
Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
|
| 117 |
+
ramp function. If unspecified, it defaults to 1.
|
| 118 |
+
`short_factor` (`List[float]`, *optional*):
|
| 119 |
+
Only used with 'longrope'. The scaling factor to be applied to short contexts (<
|
| 120 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
| 121 |
+
size divided by the number of attention heads divided by 2
|
| 122 |
+
`long_factor` (`List[float]`, *optional*):
|
| 123 |
+
Only used with 'longrope'. The scaling factor to be applied to long contexts (<
|
| 124 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
| 125 |
+
size divided by the number of attention heads divided by 2
|
| 126 |
+
`low_freq_factor` (`float`, *optional*):
|
| 127 |
+
Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
|
| 128 |
+
`high_freq_factor` (`float`, *optional*):
|
| 129 |
+
Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
|
| 130 |
+
use_sliding_window (`bool`, *optional*, defaults to `False`):
|
| 131 |
+
Whether to use sliding window attention.
|
| 132 |
+
sliding_window (`int`, *optional*):
|
| 133 |
+
Sliding window attention (SWA) window size. If not specified, will default to `None`.
|
| 134 |
+
no_rope_layers (`List[int]`, *optional*):
|
| 135 |
+
List with at least the same length as the number of layers in the model.
|
| 136 |
+
A `1` at an index position indicates that the corresponding layer will use RoPE,
|
| 137 |
+
while a `0` indicates that it's a NoPE layer.
|
| 138 |
+
no_rope_layer_interval (`int`, *optional*, defaults to 4):
|
| 139 |
+
If `no_rope_layers` is `None`, it will be created using a NoPE layer every
|
| 140 |
+
`no_rope_layer_interval` layers.
|
| 141 |
+
layer_types (`list`, *optional*):
|
| 142 |
+
Attention pattern for each layer. Automatically computed based on sliding window and NoPE settings.
|
| 143 |
+
attention_bias (`bool`, *optional*, defaults to `False`):
|
| 144 |
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
| 145 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 146 |
+
The dropout ratio for the attention probabilities.
|
| 147 |
+
|
| 148 |
+
```python
|
| 149 |
+
>>> from transformers import SmolLM3Model, SmolLM3Config
|
| 150 |
+
|
| 151 |
+
>>> # Initializing a SmolLM3 style configuration
|
| 152 |
+
>>> configuration = SmolLM3Config()
|
| 153 |
+
|
| 154 |
+
>>> # Initializing a model from the SmolLM3 style configuration
|
| 155 |
+
>>> model = SmolLM3Model(configuration)
|
| 156 |
+
|
| 157 |
+
>>> # Accessing the model configuration
|
| 158 |
+
>>> configuration = model.config
|
| 159 |
+
```"""
|
| 160 |
+
|
| 161 |
+
model_type = "smollm3"
|
| 162 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 163 |
+
|
| 164 |
+
base_model_tp_plan = {
|
| 165 |
+
"layers.*.self_attn.q_proj": "colwise",
|
| 166 |
+
"layers.*.self_attn.k_proj": "colwise",
|
| 167 |
+
"layers.*.self_attn.v_proj": "colwise",
|
| 168 |
+
"layers.*.self_attn.o_proj": "rowwise",
|
| 169 |
+
"layers.*.mlp.gate_proj": "colwise",
|
| 170 |
+
"layers.*.mlp.up_proj": "colwise",
|
| 171 |
+
"layers.*.mlp.down_proj": "rowwise",
|
| 172 |
+
}
|
| 173 |
+
base_model_pp_plan = {
|
| 174 |
+
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
| 175 |
+
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
|
| 176 |
+
"norm": (["hidden_states"], ["hidden_states"]),
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
def __init__(
|
| 180 |
+
self,
|
| 181 |
+
vocab_size=128256,
|
| 182 |
+
hidden_size=2048,
|
| 183 |
+
intermediate_size=11008,
|
| 184 |
+
num_hidden_layers=36,
|
| 185 |
+
num_attention_heads=16,
|
| 186 |
+
num_key_value_heads=4,
|
| 187 |
+
hidden_act="silu",
|
| 188 |
+
max_position_embeddings=32768,
|
| 189 |
+
initializer_range=0.02,
|
| 190 |
+
rms_norm_eps=1e-6,
|
| 191 |
+
use_cache=True,
|
| 192 |
+
pad_token_id=128004,
|
| 193 |
+
bos_token_id=128000,
|
| 194 |
+
eos_token_id=128001,
|
| 195 |
+
rope_theta=2000000.0,
|
| 196 |
+
rope_scaling=None,
|
| 197 |
+
use_sliding_window=False,
|
| 198 |
+
sliding_window=None,
|
| 199 |
+
no_rope_layers=None,
|
| 200 |
+
no_rope_layer_interval=4,
|
| 201 |
+
layer_types=None,
|
| 202 |
+
attention_bias=False,
|
| 203 |
+
attention_dropout=0.0,
|
| 204 |
+
mlp_bias=False,
|
| 205 |
+
**kwargs,
|
| 206 |
+
):
|
| 207 |
+
super().__init__(
|
| 208 |
+
pad_token_id=pad_token_id,
|
| 209 |
+
bos_token_id=bos_token_id,
|
| 210 |
+
eos_token_id=eos_token_id,
|
| 211 |
+
**kwargs,
|
| 212 |
+
)
|
| 213 |
+
self.vocab_size = vocab_size
|
| 214 |
+
self.max_position_embeddings = max_position_embeddings
|
| 215 |
+
self.mlp_bias = mlp_bias
|
| 216 |
+
self.hidden_size = hidden_size
|
| 217 |
+
self.intermediate_size = intermediate_size
|
| 218 |
+
self.num_hidden_layers = num_hidden_layers
|
| 219 |
+
self.num_attention_heads = num_attention_heads
|
| 220 |
+
self.use_sliding_window = use_sliding_window
|
| 221 |
+
self.sliding_window = sliding_window
|
| 222 |
+
|
| 223 |
+
# for backward compatibility
|
| 224 |
+
if num_key_value_heads is None:
|
| 225 |
+
num_key_value_heads = num_attention_heads
|
| 226 |
+
|
| 227 |
+
self.num_key_value_heads = num_key_value_heads
|
| 228 |
+
self.hidden_act = hidden_act
|
| 229 |
+
self.initializer_range = initializer_range
|
| 230 |
+
self.rms_norm_eps = rms_norm_eps
|
| 231 |
+
self.use_cache = use_cache
|
| 232 |
+
self.rope_theta = rope_theta
|
| 233 |
+
self.rope_scaling = rope_scaling
|
| 234 |
+
self.attention_bias = attention_bias
|
| 235 |
+
self.attention_dropout = attention_dropout
|
| 236 |
+
|
| 237 |
+
if no_rope_layers is None:
|
| 238 |
+
self.no_rope_layers = [
|
| 239 |
+
int((layer_idx + 1) % no_rope_layer_interval != 0) for layer_idx in range(num_hidden_layers)
|
| 240 |
+
]
|
| 241 |
+
else:
|
| 242 |
+
self.no_rope_layers = no_rope_layers
|
| 243 |
+
|
| 244 |
+
self.no_rope_layer_interval = no_rope_layer_interval
|
| 245 |
+
|
| 246 |
+
# Update layer_types based on sliding window and NoPE pattern
|
| 247 |
+
if layer_types is None:
|
| 248 |
+
layer_types = []
|
| 249 |
+
for layer_idx in range(num_hidden_layers):
|
| 250 |
+
has_rope = self.no_rope_layers[layer_idx]
|
| 251 |
+
if use_sliding_window and sliding_window is not None and not has_rope:
|
| 252 |
+
layer_types.append("sliding_attention")
|
| 253 |
+
else:
|
| 254 |
+
layer_types.append("full_attention")
|
| 255 |
+
|
| 256 |
+
self.layer_types = layer_types
|
| 257 |
+
layer_type_validation(self.layer_types)
|
| 258 |
+
|
| 259 |
+
# Validate the correctness of rotary position embeddings parameters
|
| 260 |
+
# BC: if there is a 'type' field, move it to 'rope_type'.
|
| 261 |
+
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
| 262 |
+
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
| 263 |
+
rope_config_validation(self)
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
class SmolLM3Attention(LlamaAttention):
|
| 267 |
+
def __init__(self, config: SmolLM3Config, layer_idx: int):
|
| 268 |
+
super().__init__(config, layer_idx)
|
| 269 |
+
|
| 270 |
+
self.use_rope = config.no_rope_layers[layer_idx]
|
| 271 |
+
self.sliding_window = (
|
| 272 |
+
config.sliding_window
|
| 273 |
+
if config.use_sliding_window and config.layer_types[layer_idx] == "sliding_attention"
|
| 274 |
+
else None
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 278 |
+
def forward(
|
| 279 |
+
self,
|
| 280 |
+
hidden_states: torch.Tensor,
|
| 281 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 282 |
+
attention_mask: Optional[torch.Tensor],
|
| 283 |
+
past_key_values: Optional[Cache] = None,
|
| 284 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 285 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 286 |
+
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 287 |
+
input_shape = hidden_states.shape[:-1]
|
| 288 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 289 |
+
|
| 290 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 291 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 292 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 293 |
+
|
| 294 |
+
if self.use_rope:
|
| 295 |
+
cos, sin = position_embeddings
|
| 296 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 297 |
+
|
| 298 |
+
if past_key_values is not None:
|
| 299 |
+
cache_kwargs = {"cache_position": cache_position}
|
| 300 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 301 |
+
|
| 302 |
+
attention_interface: Callable = eager_attention_forward
|
| 303 |
+
if self.config._attn_implementation != "eager":
|
| 304 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 305 |
+
|
| 306 |
+
attn_output, attn_weights = attention_interface(
|
| 307 |
+
self,
|
| 308 |
+
query_states,
|
| 309 |
+
key_states,
|
| 310 |
+
value_states,
|
| 311 |
+
attention_mask,
|
| 312 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 313 |
+
scaling=self.scaling,
|
| 314 |
+
sliding_window=self.sliding_window,
|
| 315 |
+
**kwargs,
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 319 |
+
attn_output = self.o_proj(attn_output)
|
| 320 |
+
return attn_output, attn_weights
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
class SmolLM3DecoderLayer(LlamaDecoderLayer):
|
| 324 |
+
def __init__(self, config: SmolLM3Config, layer_idx: int):
|
| 325 |
+
super().__init__(config, layer_idx)
|
| 326 |
+
self.attention_type = config.layer_types[layer_idx]
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
class SmolLM3PreTrainedModel(LlamaPreTrainedModel):
|
| 330 |
+
pass
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
class SmolLM3Model(Qwen2Model):
|
| 334 |
+
pass
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
class SmolLM3ForCausalLM(LlamaForCausalLM):
|
| 338 |
+
pass
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
class SmolLM3ForSequenceClassification(LlamaForSequenceClassification):
|
| 342 |
+
pass
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
class SmolLM3ForTokenClassification(LlamaForTokenClassification):
|
| 346 |
+
pass
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
class SmolLM3ForQuestionAnswering(LlamaForQuestionAnswering):
|
| 350 |
+
pass
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
__all__ = [
|
| 354 |
+
"SmolLM3Config",
|
| 355 |
+
"SmolLM3PreTrainedModel",
|
| 356 |
+
"SmolLM3Model",
|
| 357 |
+
"SmolLM3ForCausalLM",
|
| 358 |
+
"SmolLM3ForSequenceClassification",
|
| 359 |
+
"SmolLM3ForTokenClassification",
|
| 360 |
+
"SmolLM3ForQuestionAnswering",
|
| 361 |
+
]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/smolvlm/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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_smolvlm import *
|
| 22 |
+
from .image_processing_smolvlm import *
|
| 23 |
+
from .image_processing_smolvlm_fast import *
|
| 24 |
+
from .modeling_smolvlm import *
|
| 25 |
+
from .processing_smolvlm import *
|
| 26 |
+
else:
|
| 27 |
+
import sys
|
| 28 |
+
|
| 29 |
+
_file = globals()["__file__"]
|
| 30 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/smolvlm/configuration_smolvlm.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/smolvlm/modular_smolvlm.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_smolvlm.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# coding=utf-8
|
| 8 |
+
# Copyright 2025 the HuggingFace Inc. team. All rights reserved.
|
| 9 |
+
# Written by Orr Zohar
|
| 10 |
+
#
|
| 11 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 12 |
+
# you may not use this file except in compliance with the License.
|
| 13 |
+
# You may obtain a copy of the License at
|
| 14 |
+
#
|
| 15 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 16 |
+
#
|
| 17 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 18 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 19 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 20 |
+
# See the License for the specific language governing permissions and
|
| 21 |
+
# limitations under the License.
|
| 22 |
+
from ...configuration_utils import PretrainedConfig
|
| 23 |
+
from ...utils import logging
|
| 24 |
+
from ..auto import CONFIG_MAPPING, AutoConfig
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
logger = logging.get_logger(__name__)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class SmolVLMVisionConfig(PretrainedConfig):
|
| 31 |
+
r"""
|
| 32 |
+
This is the configuration class to store the configuration of a [`SmolVLMVisionModel`]. It is used to instantiate a
|
| 33 |
+
SmolVLM vision encoder according to the specified arguments, defining the model architecture. Instantiating a
|
| 34 |
+
configuration with the defaults will yield a similar configuration to that of the SigLIP checkpoint
|
| 35 |
+
[google/siglip-so400m-patch14-384](https://huggingface.co/google/siglip-so400m-patch14-384) used in SmolVLM
|
| 36 |
+
[HuggingFaceTB/SmolVLM2-2.2B-Instruct](https://huggingface.co/HuggingFaceTB/SmolVLM2-2.2B-Instruct).
|
| 37 |
+
|
| 38 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 39 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 40 |
+
|
| 41 |
+
Args:
|
| 42 |
+
hidden_size (`int`, *optional*, defaults to 1152):
|
| 43 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 44 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 45 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 46 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 47 |
+
Number of hidden layers in the Transformer encoder.
|
| 48 |
+
num_attention_heads (`int`, *optional*, defaults to 16):
|
| 49 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 50 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 51 |
+
Number of channels in the input images.
|
| 52 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 53 |
+
The size (resolution) of each image.
|
| 54 |
+
patch_size (`int`, *optional*, defaults to 32):
|
| 55 |
+
The size (resolution) of each patch.
|
| 56 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
|
| 57 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 58 |
+
`"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
|
| 59 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-06):
|
| 60 |
+
The epsilon used by the layer normalization layers.
|
| 61 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 62 |
+
The dropout ratio for the attention probabilities.
|
| 63 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 64 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 65 |
+
|
| 66 |
+
Example:
|
| 67 |
+
|
| 68 |
+
```python
|
| 69 |
+
>>> from transformers.models.smolvlm.modeling_smolvlm import SmolVLMVisionTransformer
|
| 70 |
+
>>> from transformers.models.smolvlm.configuration_smolvlm import SmolVLMVisionConfig
|
| 71 |
+
|
| 72 |
+
>>> # Initializing a SmolVLMVisionConfig with google/siglip-so400m-patch14-384 style configuration
|
| 73 |
+
>>> configuration = SmolVLMVisionConfig()
|
| 74 |
+
|
| 75 |
+
>>> # Initializing a SmolVLMVisionTransformer (with random weights) from the google/siglip-so400m-patch14-384 style configuration
|
| 76 |
+
>>> model = SmolVLMVisionTransformer(configuration)
|
| 77 |
+
|
| 78 |
+
>>> # Accessing the model configuration
|
| 79 |
+
>>> configuration = model.config
|
| 80 |
+
```"""
|
| 81 |
+
|
| 82 |
+
model_type = "smolvlm_vision"
|
| 83 |
+
base_config_key = "vision_config"
|
| 84 |
+
|
| 85 |
+
def __init__(
|
| 86 |
+
self,
|
| 87 |
+
hidden_size=1152,
|
| 88 |
+
intermediate_size=3072,
|
| 89 |
+
num_hidden_layers=12,
|
| 90 |
+
num_attention_heads=16,
|
| 91 |
+
num_channels=3,
|
| 92 |
+
image_size=224,
|
| 93 |
+
patch_size=32,
|
| 94 |
+
hidden_act="gelu_pytorch_tanh",
|
| 95 |
+
layer_norm_eps=1e-6,
|
| 96 |
+
attention_dropout=0.0,
|
| 97 |
+
initializer_range=0.02,
|
| 98 |
+
**kwargs,
|
| 99 |
+
):
|
| 100 |
+
super().__init__(**kwargs)
|
| 101 |
+
|
| 102 |
+
self.hidden_size = hidden_size
|
| 103 |
+
self.intermediate_size = intermediate_size
|
| 104 |
+
self.num_hidden_layers = num_hidden_layers
|
| 105 |
+
self.num_attention_heads = num_attention_heads
|
| 106 |
+
self.num_channels = num_channels
|
| 107 |
+
self.patch_size = patch_size
|
| 108 |
+
self.image_size = image_size
|
| 109 |
+
self.attention_dropout = attention_dropout
|
| 110 |
+
self.layer_norm_eps = layer_norm_eps
|
| 111 |
+
self.hidden_act = hidden_act
|
| 112 |
+
self.initializer_range = initializer_range
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class SmolVLMConfig(PretrainedConfig):
|
| 116 |
+
r"""
|
| 117 |
+
This is the configuration class to store the configuration of a [`SmolVLMModel`]. It is used to instantiate a
|
| 118 |
+
SmolVLM model according to the specified arguments, defining the model architecture. Instantiating a
|
| 119 |
+
configuration with the defaults will yield a similar configuration to that of the model of the SmolVLM
|
| 120 |
+
[HuggingFaceTB/SmolVLM2-2.2B-Instruct](https://huggingface.co/HuggingFaceTB/SmolVLM2-2.2B-Instruct) architecture.
|
| 121 |
+
|
| 122 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 123 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 124 |
+
|
| 125 |
+
Args:
|
| 126 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 127 |
+
Whether or not the model should cache the key/value pairs of the attention mechanism. Only
|
| 128 |
+
relevant if `config.is_decoder=True`.
|
| 129 |
+
image_token_id (`int`, *optional*, defaults to 128257):
|
| 130 |
+
The id of the "image" token.
|
| 131 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
| 132 |
+
Whether or not to tie the word embeddings with the token embeddings.
|
| 133 |
+
vision_config (`IdeficsVisionConfig` or `dict`, *optional*, defaults to `IdeficsVisionConfig`):
|
| 134 |
+
Custom vision config or dict for the vision tower
|
| 135 |
+
text_config (`PretrainedConfig` or `dict`, *optional*, defaults to `LlamaConfig`):
|
| 136 |
+
Custom text config or dict for the text model
|
| 137 |
+
scale_factor (`int`, *optional*, defaults to 2):
|
| 138 |
+
The scale factor for the image encoder.
|
| 139 |
+
pad_token_id (`int`, *optional*, defaults to 128002):
|
| 140 |
+
The id of the padding token.
|
| 141 |
+
|
| 142 |
+
Example:
|
| 143 |
+
```python
|
| 144 |
+
>>> from transformers import SmolVLMModel, SmolVLMConfig
|
| 145 |
+
>>> # Initializing configuration
|
| 146 |
+
>>> configuration = SmolVLMConfig()
|
| 147 |
+
>>> # Initializing a model from the configuration
|
| 148 |
+
>>> model = SmolVLMModel(configuration)
|
| 149 |
+
>>> # Accessing the model configuration
|
| 150 |
+
>>> configuration = model.config
|
| 151 |
+
```"""
|
| 152 |
+
|
| 153 |
+
model_type = "smolvlm"
|
| 154 |
+
sub_configs = {"text_config": AutoConfig, "vision_config": SmolVLMVisionConfig}
|
| 155 |
+
|
| 156 |
+
def __init__(
|
| 157 |
+
self,
|
| 158 |
+
use_cache=True,
|
| 159 |
+
image_token_id=128257,
|
| 160 |
+
tie_word_embeddings=False,
|
| 161 |
+
vision_config=None,
|
| 162 |
+
text_config=None,
|
| 163 |
+
scale_factor=2,
|
| 164 |
+
pad_token_id=128_002,
|
| 165 |
+
**kwargs,
|
| 166 |
+
):
|
| 167 |
+
self.image_token_id = image_token_id
|
| 168 |
+
self.use_cache = use_cache
|
| 169 |
+
self.tie_word_embeddings = tie_word_embeddings
|
| 170 |
+
|
| 171 |
+
if vision_config is None:
|
| 172 |
+
self.vision_config = SmolVLMVisionConfig()
|
| 173 |
+
logger.info("vision_config is None, using default vision config")
|
| 174 |
+
elif isinstance(vision_config, dict):
|
| 175 |
+
self.vision_config = SmolVLMVisionConfig(**vision_config)
|
| 176 |
+
elif isinstance(vision_config, SmolVLMVisionConfig):
|
| 177 |
+
self.vision_config = vision_config
|
| 178 |
+
|
| 179 |
+
if isinstance(text_config, dict):
|
| 180 |
+
text_config["model_type"] = text_config.get("model_type", "llama")
|
| 181 |
+
text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config)
|
| 182 |
+
elif text_config is None:
|
| 183 |
+
logger.info("text_config is None, using default text config")
|
| 184 |
+
text_config = CONFIG_MAPPING["llama"](
|
| 185 |
+
rms_norm_eps=1e-5,
|
| 186 |
+
pad_token_id=pad_token_id,
|
| 187 |
+
tie_word_embeddings=False,
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
self.text_config = text_config
|
| 191 |
+
self.scale_factor = scale_factor
|
| 192 |
+
|
| 193 |
+
super().__init__(**kwargs, pad_token_id=pad_token_id, tie_word_embeddings=tie_word_embeddings)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
__all__ = ["SmolVLMVisionConfig", "SmolVLMConfig"]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/smolvlm/image_processing_smolvlm.py
ADDED
|
@@ -0,0 +1,896 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/smolvlm/modular_smolvlm.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_smolvlm.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# coding=utf-8
|
| 8 |
+
# Copyright 2025 the HuggingFace Inc. team. All rights reserved.
|
| 9 |
+
# Written by Orr Zohar
|
| 10 |
+
#
|
| 11 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 12 |
+
# you may not use this file except in compliance with the License.
|
| 13 |
+
# You may obtain a copy of the License at
|
| 14 |
+
#
|
| 15 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 16 |
+
#
|
| 17 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 18 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 19 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 20 |
+
# See the License for the specific language governing permissions and
|
| 21 |
+
# limitations under the License.
|
| 22 |
+
import math
|
| 23 |
+
from collections.abc import Iterable
|
| 24 |
+
from typing import Optional, Union
|
| 25 |
+
|
| 26 |
+
import numpy as np
|
| 27 |
+
|
| 28 |
+
from ...image_processing_utils import BaseImageProcessor, BatchFeature
|
| 29 |
+
from ...image_transforms import PaddingMode, pad, to_channel_dimension_format, to_pil_image
|
| 30 |
+
from ...image_utils import (
|
| 31 |
+
IMAGENET_STANDARD_MEAN,
|
| 32 |
+
IMAGENET_STANDARD_STD,
|
| 33 |
+
ChannelDimension,
|
| 34 |
+
ImageInput,
|
| 35 |
+
PILImageResampling,
|
| 36 |
+
get_image_size,
|
| 37 |
+
infer_channel_dimension_format,
|
| 38 |
+
is_scaled_image,
|
| 39 |
+
make_nested_list_of_images,
|
| 40 |
+
to_numpy_array,
|
| 41 |
+
valid_images,
|
| 42 |
+
validate_preprocess_arguments,
|
| 43 |
+
)
|
| 44 |
+
from ...utils import TensorType, is_vision_available, logging
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
if is_vision_available():
|
| 48 |
+
import PIL
|
| 49 |
+
from PIL import Image
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
logger = logging.get_logger(__name__)
|
| 53 |
+
MAX_IMAGE_SIZE = 4096 # 4k resolution as absolute maximum
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _resize_output_size_rescale_to_max_len(
|
| 57 |
+
height: int, width: int, min_len: Optional[int] = 1, max_len: Optional[int] = None
|
| 58 |
+
) -> tuple[int, int]:
|
| 59 |
+
"""
|
| 60 |
+
Get the output size of the image after resizing given a dictionary specifying the max and min sizes.
|
| 61 |
+
Args:
|
| 62 |
+
height (`int`):
|
| 63 |
+
Height of the input image.
|
| 64 |
+
width (`int`):
|
| 65 |
+
Width of the input image.
|
| 66 |
+
min_len (`int`, *optional*, defaults to 1):
|
| 67 |
+
Minimum size of the output image.
|
| 68 |
+
max_len (`int`, *optional*, defaults to the maximum size of the image):
|
| 69 |
+
Maximum size of the output image.
|
| 70 |
+
Returns:
|
| 71 |
+
The output size of the image after resizing.
|
| 72 |
+
"""
|
| 73 |
+
max_len = max(height, width) if max_len is None else max_len
|
| 74 |
+
aspect_ratio = width / height
|
| 75 |
+
|
| 76 |
+
if width >= height:
|
| 77 |
+
width = max_len
|
| 78 |
+
height = int(width / aspect_ratio)
|
| 79 |
+
if height % 2 != 0:
|
| 80 |
+
height += 1
|
| 81 |
+
elif height > width:
|
| 82 |
+
height = max_len
|
| 83 |
+
width = int(height * aspect_ratio)
|
| 84 |
+
if width % 2 != 0:
|
| 85 |
+
width += 1
|
| 86 |
+
|
| 87 |
+
# Avoid resizing to a size smaller than min_len
|
| 88 |
+
height = max(height, min_len)
|
| 89 |
+
width = max(width, min_len)
|
| 90 |
+
return height, width
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _resize_output_size_scale_below_upper_bound(
|
| 94 |
+
height: int, width: int, max_len: Optional[dict[str, int]] = None
|
| 95 |
+
) -> tuple[int, int]:
|
| 96 |
+
"""
|
| 97 |
+
Get the output size of the image after resizing given a dictionary specifying the max and min sizes.
|
| 98 |
+
Args:
|
| 99 |
+
height (`int`):
|
| 100 |
+
Height of the input image.
|
| 101 |
+
width (`int`):
|
| 102 |
+
Width of the input image.
|
| 103 |
+
max_len (`dict[str, int]`, *optional*, defaults to the maximum size of the image):
|
| 104 |
+
Defines the maximum dimensions of the image.
|
| 105 |
+
Returns:
|
| 106 |
+
The output size of the image after resizing.
|
| 107 |
+
"""
|
| 108 |
+
max_len = max(height, width) if max_len is None else max_len
|
| 109 |
+
|
| 110 |
+
aspect_ratio = width / height
|
| 111 |
+
if width >= height and width > max_len:
|
| 112 |
+
width = max_len
|
| 113 |
+
height = int(width / aspect_ratio)
|
| 114 |
+
elif height > width and height > max_len:
|
| 115 |
+
height = max_len
|
| 116 |
+
width = int(height * aspect_ratio)
|
| 117 |
+
|
| 118 |
+
# Avoid resizing to a size smaller than 1
|
| 119 |
+
height = max(height, 1)
|
| 120 |
+
width = max(width, 1)
|
| 121 |
+
return height, width
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def get_resize_output_image_size(
|
| 125 |
+
image,
|
| 126 |
+
resolution_max_side: int,
|
| 127 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 128 |
+
) -> tuple[int, int]:
|
| 129 |
+
"""
|
| 130 |
+
Get the output size of the image after resizing given a dictionary specifying the max and min sizes.
|
| 131 |
+
Args:
|
| 132 |
+
image (`np.ndarray`):
|
| 133 |
+
Image to resize.
|
| 134 |
+
resolution_max_side (`int`):
|
| 135 |
+
The longest edge of the image will be resized to this value. The shortest edge will be resized to keep the
|
| 136 |
+
input aspect ratio.
|
| 137 |
+
input_data_format (`ChannelDimension` or `str`):
|
| 138 |
+
The channel dimension format of the input image.
|
| 139 |
+
Returns:
|
| 140 |
+
The output size of the image after resizing.
|
| 141 |
+
"""
|
| 142 |
+
height, width = get_image_size(image, channel_dim=input_data_format)
|
| 143 |
+
|
| 144 |
+
# Find the output size, when rescaling the longest edge to max_len and preserving the aspect ratio
|
| 145 |
+
height, width = _resize_output_size_rescale_to_max_len(height, width, max_len=resolution_max_side)
|
| 146 |
+
# Find the output size when scaling the image to be below the MAX_IMAGE_SIZE
|
| 147 |
+
height, width = _resize_output_size_scale_below_upper_bound(height, width, max_len=MAX_IMAGE_SIZE)
|
| 148 |
+
return height, width
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def get_max_height_width(
|
| 152 |
+
images_list: list[list[np.ndarray]], input_data_format: Optional[Union[str, ChannelDimension]] = None
|
| 153 |
+
) -> list[int]:
|
| 154 |
+
"""
|
| 155 |
+
Get the maximum height and width across all images in a batch.
|
| 156 |
+
"""
|
| 157 |
+
if input_data_format is None:
|
| 158 |
+
input_data_format = infer_channel_dimension_format(images_list[0][0], num_channels=(1, 3, 4))
|
| 159 |
+
|
| 160 |
+
max_height = max_width = float("-inf")
|
| 161 |
+
for images in images_list:
|
| 162 |
+
for image in images:
|
| 163 |
+
height, width = get_image_size(image, channel_dim=input_data_format)
|
| 164 |
+
max_height = max(height, max_height)
|
| 165 |
+
max_width = max(width, max_width)
|
| 166 |
+
return (max_height, max_width)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def make_pixel_mask(
|
| 170 |
+
image: np.ndarray, output_size: tuple[int, int], input_data_format: Optional[Union[str, ChannelDimension]] = None
|
| 171 |
+
) -> np.ndarray:
|
| 172 |
+
"""
|
| 173 |
+
Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding.
|
| 174 |
+
Args:
|
| 175 |
+
image (`np.ndarray`):
|
| 176 |
+
Image to make the pixel mask for.
|
| 177 |
+
output_size (`tuple[int, int]`):
|
| 178 |
+
Output size of the mask.
|
| 179 |
+
"""
|
| 180 |
+
input_height, input_width = get_image_size(image, channel_dim=input_data_format)
|
| 181 |
+
mask = np.zeros(output_size, dtype=np.int64)
|
| 182 |
+
mask[:input_height, :input_width] = 1
|
| 183 |
+
return mask
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def convert_to_rgb(
|
| 187 |
+
image: np.ndarray,
|
| 188 |
+
palette: Optional[PIL.ImagePalette.ImagePalette] = None,
|
| 189 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 190 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 191 |
+
) -> ImageInput:
|
| 192 |
+
"""
|
| 193 |
+
Converts an image to RGB format.
|
| 194 |
+
Args:
|
| 195 |
+
image (`np.ndarray`):
|
| 196 |
+
The image to convert.
|
| 197 |
+
palette (list[int], *optional*):
|
| 198 |
+
The palette to use if given.
|
| 199 |
+
data_format (ChannelDimension or str, *optional*):
|
| 200 |
+
The channel dimension format for the output image. If not provided, it will be the same as the input image.
|
| 201 |
+
input_data_format (ChannelDimension or str, *optional*):
|
| 202 |
+
The channel dimension format of the input image.
|
| 203 |
+
"""
|
| 204 |
+
if input_data_format is None:
|
| 205 |
+
input_data_format = infer_channel_dimension_format(image, num_channels=(1, 3, 4))
|
| 206 |
+
|
| 207 |
+
# For all transformations, we want to keep the same data format as the input image unless otherwise specified.
|
| 208 |
+
# The resized image from PIL will always have channels last, so find the input format first.
|
| 209 |
+
data_format = input_data_format if data_format is None else data_format
|
| 210 |
+
|
| 211 |
+
mode = "P" if palette is not None else None
|
| 212 |
+
image = to_pil_image(image, image_mode=mode, input_data_format=input_data_format)
|
| 213 |
+
if image.mode == "P" and palette is not None:
|
| 214 |
+
image.putpalette(palette)
|
| 215 |
+
|
| 216 |
+
image_rgba = image.convert("RGBA")
|
| 217 |
+
background = Image.new("RGBA", image_rgba.size, (255, 255, 255))
|
| 218 |
+
alpha_composite = Image.alpha_composite(background, image_rgba)
|
| 219 |
+
alpha_composite = alpha_composite.convert("RGB")
|
| 220 |
+
|
| 221 |
+
output_array = np.array(alpha_composite)
|
| 222 |
+
# The image is always in channels last format after converting from a PIL image
|
| 223 |
+
output_array = to_channel_dimension_format(output_array, data_format, input_channel_dim=ChannelDimension.LAST)
|
| 224 |
+
return output_array
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
# FIXME Amy: make a more general crop function that isn't just centre crop
|
| 228 |
+
def _crop(
|
| 229 |
+
image: np.ndarray,
|
| 230 |
+
w1: int,
|
| 231 |
+
h1: int,
|
| 232 |
+
w2: int,
|
| 233 |
+
h2: int,
|
| 234 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 235 |
+
) -> np.ndarray:
|
| 236 |
+
if data_format is None:
|
| 237 |
+
data_format = infer_channel_dimension_format(image, num_channels=(1, 3, 4))
|
| 238 |
+
|
| 239 |
+
if data_format == ChannelDimension.FIRST:
|
| 240 |
+
image = image[:, h1:h2, w1:w2]
|
| 241 |
+
elif data_format == ChannelDimension.LAST:
|
| 242 |
+
image = image[h1:h2, w1:w2, :]
|
| 243 |
+
else:
|
| 244 |
+
raise ValueError("Invalid channel dimension format.")
|
| 245 |
+
|
| 246 |
+
return image
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
class SmolVLMImageProcessor(BaseImageProcessor):
|
| 250 |
+
r"""
|
| 251 |
+
Constructs a SmolVLM image processor.
|
| 252 |
+
Args:
|
| 253 |
+
do_convert_rgb (`bool`, *optional*, defaults to `True`):
|
| 254 |
+
Whether to convert the image to RGB. This is useful if the input image is of a different format e.g. RGBA.
|
| 255 |
+
Only has an effect if the input image is in the PIL format.
|
| 256 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
| 257 |
+
Whether to resize the image. The longest edge of the image is resized to be <= `size["longest_edge"]`, with the
|
| 258 |
+
shortest edge resized to keep the input aspect ratio.
|
| 259 |
+
size (`Dict`, *optional*, defaults to `{"longest_edge": 4 * 364}`):
|
| 260 |
+
Controls the size of the output image. This is a dictionary containing the key "longest_edge".
|
| 261 |
+
The image will be resized such that the longest edge is <= `size["longest_edge"]` and the shortest edge is resized
|
| 262 |
+
to keep the input aspect ratio.
|
| 263 |
+
resample (`Resampling`, *optional*, defaults to `Resampling.LANCZOS`):
|
| 264 |
+
Resampling filter to use when resizing the image.
|
| 265 |
+
do_image_splitting (`bool`, *optional*, defaults to `True`):
|
| 266 |
+
Whether to split the image into sub-images concatenated with the original image. They are split into patches
|
| 267 |
+
such that each patch has a size of `max_image_size["height"]` x `max_image_size["width"]`.
|
| 268 |
+
max_image_size (`Dict`, *optional*, defaults to `{"longest_edge": 364}`):
|
| 269 |
+
Maximum resolution of the patches of images accepted by the model. This is a dictionary containing the key "longest_edge".
|
| 270 |
+
do_rescale (`bool`, *optional*, defaults to `True`):
|
| 271 |
+
Whether to rescale the image. If set to `True`, the image is rescaled to have pixel values between 0 and 1.
|
| 272 |
+
rescale_factor (`float`, *optional*, defaults to `1/255`):
|
| 273 |
+
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
|
| 274 |
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
| 275 |
+
Whether to normalize the image. If set to `True`, the image is normalized to have a mean of `image_mean` and
|
| 276 |
+
a standard deviation of `image_std`.
|
| 277 |
+
image_mean (`float` or `list[float]`, *optional*, defaults to `IDEFICS_STANDARD_MEAN`):
|
| 278 |
+
Mean to use if normalizing the image. This is a float or list of floats the length of the number of
|
| 279 |
+
channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method. Can be
|
| 280 |
+
overridden by the `image_mean` parameter in the `preprocess` method.
|
| 281 |
+
image_std (`float` or `list[float]`, *optional*, defaults to `IDEFICS_STANDARD_STD`):
|
| 282 |
+
Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
|
| 283 |
+
number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
|
| 284 |
+
Can be overridden by the `image_std` parameter in the `preprocess` method.
|
| 285 |
+
do_pad (`bool`, *optional*, defaults to `True`):
|
| 286 |
+
Whether or not to pad the images to the largest height and width in the batch and number of images per
|
| 287 |
+
sample in the batch, such that the returned tensor is of shape (batch_size, max_num_images, num_channels, max_height, max_width).
|
| 288 |
+
"""
|
| 289 |
+
|
| 290 |
+
model_input_names = ["pixel_values", "pixel_attention_mask"]
|
| 291 |
+
|
| 292 |
+
def __init__(
|
| 293 |
+
self,
|
| 294 |
+
do_convert_rgb: bool = True,
|
| 295 |
+
do_resize: bool = True,
|
| 296 |
+
size: Optional[dict[str, int]] = None,
|
| 297 |
+
resample: PILImageResampling = PILImageResampling.LANCZOS,
|
| 298 |
+
do_image_splitting: bool = True,
|
| 299 |
+
max_image_size: Optional[dict[str, int]] = None,
|
| 300 |
+
do_rescale: bool = True,
|
| 301 |
+
rescale_factor: float = 1 / 255,
|
| 302 |
+
do_normalize: bool = True,
|
| 303 |
+
image_mean: Optional[Union[float, list[float]]] = None,
|
| 304 |
+
image_std: Optional[Union[float, list[float]]] = None,
|
| 305 |
+
do_pad: bool = True,
|
| 306 |
+
**kwargs,
|
| 307 |
+
) -> None:
|
| 308 |
+
super().__init__(**kwargs)
|
| 309 |
+
self.do_convert_rgb = do_convert_rgb
|
| 310 |
+
self.do_resize = do_resize
|
| 311 |
+
self.size = size if size is not None else {"longest_edge": 4 * 364}
|
| 312 |
+
self.resample = resample
|
| 313 |
+
self.do_image_splitting = do_image_splitting
|
| 314 |
+
self.max_image_size = max_image_size if max_image_size is not None else {"longest_edge": 364}
|
| 315 |
+
self.do_rescale = do_rescale
|
| 316 |
+
self.rescale_factor = rescale_factor
|
| 317 |
+
self.do_normalize = do_normalize
|
| 318 |
+
self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
|
| 319 |
+
self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
|
| 320 |
+
self.do_pad = do_pad
|
| 321 |
+
|
| 322 |
+
def resize(
|
| 323 |
+
self,
|
| 324 |
+
image: np.ndarray,
|
| 325 |
+
size: dict[str, int],
|
| 326 |
+
resample: PILImageResampling = PILImageResampling.LANCZOS,
|
| 327 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 328 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 329 |
+
**kwargs,
|
| 330 |
+
) -> np.ndarray:
|
| 331 |
+
"""
|
| 332 |
+
Resize an image. The longest edge of the image is resized to size["longest_edge"], with the shortest edge
|
| 333 |
+
resized to keep the input aspect ratio. Can also be used with size["height"] and size["width"].
|
| 334 |
+
Args:
|
| 335 |
+
image (`np.ndarray`):
|
| 336 |
+
Image to resize.
|
| 337 |
+
size (`dict[str, int]`):
|
| 338 |
+
Size of the output image.
|
| 339 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.LANCZOS`):
|
| 340 |
+
Resampling filter to use when resizing the image.
|
| 341 |
+
data_format (`ChannelDimension` or `str`, *optional*):
|
| 342 |
+
The channel dimension format of the output image. If not provided, it will be the same as the input image.
|
| 343 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 344 |
+
The channel dimension format of the input image. If not provided, it will be inferred.
|
| 345 |
+
"""
|
| 346 |
+
if input_data_format is None:
|
| 347 |
+
input_data_format = infer_channel_dimension_format(image, num_channels=(1, 3, 4))
|
| 348 |
+
|
| 349 |
+
# For all transformations, we want to keep the same data format as the input image unless otherwise specified.
|
| 350 |
+
# The resized image from PIL will always have channels last, so find the input format first.
|
| 351 |
+
data_format = input_data_format if data_format is None else data_format
|
| 352 |
+
|
| 353 |
+
if "longest_edge" in size:
|
| 354 |
+
size = get_resize_output_image_size(
|
| 355 |
+
image, resolution_max_side=size["longest_edge"], input_data_format=input_data_format
|
| 356 |
+
)
|
| 357 |
+
elif "height" in size and "width" in size:
|
| 358 |
+
size = (size["height"], size["width"])
|
| 359 |
+
else:
|
| 360 |
+
raise ValueError("size must be a dictionary with key 'longest_edge' or 'height' and 'width'.")
|
| 361 |
+
|
| 362 |
+
image_mode = None
|
| 363 |
+
if image.ndim == 2 or image.shape[-1] == 1:
|
| 364 |
+
image_mode = "P"
|
| 365 |
+
image = to_pil_image(image, image_mode=image_mode, input_data_format=input_data_format)
|
| 366 |
+
|
| 367 |
+
resized_image = image.resize((size[1], size[0]), resample=resample)
|
| 368 |
+
resized_image = np.array(resized_image)
|
| 369 |
+
|
| 370 |
+
# If the input image channel dimension was of size 1, then it is dropped when converting to a PIL image
|
| 371 |
+
# so we need to add it back if necessary.
|
| 372 |
+
resized_image = np.expand_dims(resized_image, axis=-1) if resized_image.ndim == 2 else resized_image
|
| 373 |
+
# The image is always in channels last format after converting from a PIL image
|
| 374 |
+
resized_image = to_channel_dimension_format(
|
| 375 |
+
resized_image, data_format, input_channel_dim=ChannelDimension.LAST
|
| 376 |
+
)
|
| 377 |
+
return resized_image
|
| 378 |
+
|
| 379 |
+
def split_image(
|
| 380 |
+
self,
|
| 381 |
+
image,
|
| 382 |
+
max_image_size: dict[str, int],
|
| 383 |
+
resample: PILImageResampling = PILImageResampling.LANCZOS,
|
| 384 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 385 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 386 |
+
):
|
| 387 |
+
"""
|
| 388 |
+
Split an image into squares of side max_image_size and the original image resized to max_image_size.
|
| 389 |
+
That means that a single image becomes a sequence of images.
|
| 390 |
+
This is a "trick" to spend more compute on each image with no changes in the vision encoder.
|
| 391 |
+
1) If one side of the original image is larger than `max_image_size`, resize it to `max_image_size` while preserving the aspect ratio.
|
| 392 |
+
2) Divide the resulting image into `ceil(height / max_image_size)` x `ceil(width / max_image_size)`
|
| 393 |
+
sub-images of the same size each (image_size, image_size). Typically, 364x364.
|
| 394 |
+
3) Returns the list of the crops and the original image, in addition to the number of splits for the height and the width.
|
| 395 |
+
Args:
|
| 396 |
+
image (`np.ndarray`):
|
| 397 |
+
Images to split.
|
| 398 |
+
max_image_size (`dict[str, int]`):
|
| 399 |
+
Maximum size of the output image. If the image is larger than this size, it will be split into
|
| 400 |
+
patches of this size, and the original image will be concatenated with the patches, resized to max_size.
|
| 401 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.LANCZOS`):
|
| 402 |
+
Resampling filter to use when resizing the image.
|
| 403 |
+
data_format (`ChannelDimension` or `str`, *optional*):
|
| 404 |
+
The channel dimension format of the output image. If not provided, it will be the same as the input image.
|
| 405 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 406 |
+
The channel dimension format of the input image. If not provided, it will be inferred.
|
| 407 |
+
"""
|
| 408 |
+
height, width = get_image_size(image, channel_dim=input_data_format)
|
| 409 |
+
max_height = max_width = max_image_size["longest_edge"]
|
| 410 |
+
|
| 411 |
+
frames = []
|
| 412 |
+
if height > max_height or width > max_width:
|
| 413 |
+
# Calculate the number of splits
|
| 414 |
+
num_splits_h = math.ceil(height / max_height)
|
| 415 |
+
num_splits_w = math.ceil(width / max_width)
|
| 416 |
+
# Calculate the optimal width and height for the sub-images
|
| 417 |
+
optimal_height = math.ceil(height / num_splits_h)
|
| 418 |
+
optimal_width = math.ceil(width / num_splits_w)
|
| 419 |
+
|
| 420 |
+
# Iterate through each row and column
|
| 421 |
+
for r in range(num_splits_h):
|
| 422 |
+
for c in range(num_splits_w):
|
| 423 |
+
# Calculate the starting point of the crop
|
| 424 |
+
start_x = c * optimal_width
|
| 425 |
+
start_y = r * optimal_height
|
| 426 |
+
|
| 427 |
+
# Calculate the ending point of the crop
|
| 428 |
+
end_x = min(start_x + optimal_width, width)
|
| 429 |
+
end_y = min(start_y + optimal_height, height)
|
| 430 |
+
|
| 431 |
+
# Crop the image
|
| 432 |
+
cropped_image = _crop(
|
| 433 |
+
image,
|
| 434 |
+
start_x,
|
| 435 |
+
start_y,
|
| 436 |
+
end_x,
|
| 437 |
+
end_y,
|
| 438 |
+
data_format=data_format,
|
| 439 |
+
)
|
| 440 |
+
frames.append(cropped_image)
|
| 441 |
+
|
| 442 |
+
# For the global image at the end, we resize it to match the max_image_size, for cpu memory efficiency
|
| 443 |
+
global_image_height, global_image_width = max_height, max_width
|
| 444 |
+
if height != global_image_height or width != global_image_width:
|
| 445 |
+
image = self.resize(
|
| 446 |
+
image,
|
| 447 |
+
{"height": global_image_height, "width": global_image_width},
|
| 448 |
+
resample=resample,
|
| 449 |
+
input_data_format=data_format,
|
| 450 |
+
)
|
| 451 |
+
else:
|
| 452 |
+
num_splits_h, num_splits_w = 0, 0
|
| 453 |
+
|
| 454 |
+
frames.append(image)
|
| 455 |
+
|
| 456 |
+
return frames, num_splits_h, num_splits_w
|
| 457 |
+
|
| 458 |
+
def resize_for_vision_encoder(
|
| 459 |
+
self,
|
| 460 |
+
image: np.ndarray,
|
| 461 |
+
vision_encoder_max_size: int,
|
| 462 |
+
resample: PILImageResampling = PILImageResampling.LANCZOS,
|
| 463 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 464 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 465 |
+
):
|
| 466 |
+
"""
|
| 467 |
+
Resize images to be multiples of `vision_encoder_max_size` while preserving the aspect ratio.
|
| 468 |
+
Args:
|
| 469 |
+
image (`np.ndarray`):
|
| 470 |
+
Images to resize.
|
| 471 |
+
vision_encoder_max_size (`int`):
|
| 472 |
+
Maximum size of the output image. If the image is larger than this size, it will be split into
|
| 473 |
+
patches of this size, and the original image will be concatenated with the patches, resized to max_size.
|
| 474 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.LANCZOS`):
|
| 475 |
+
Resampling filter to use when resizing the image.
|
| 476 |
+
data_format (`ChannelDimension` or `str`, *optional*):
|
| 477 |
+
The channel dimension format of the output image. If not provided, it will be the same as the input image.
|
| 478 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 479 |
+
The channel dimension format of the input image. If not provided, it will be inferred
|
| 480 |
+
"""
|
| 481 |
+
height, width = get_image_size(image, channel_dim=input_data_format)
|
| 482 |
+
|
| 483 |
+
aspect_ratio = width / height
|
| 484 |
+
if width >= height:
|
| 485 |
+
width = math.ceil(width / vision_encoder_max_size) * vision_encoder_max_size
|
| 486 |
+
height = int(width / aspect_ratio)
|
| 487 |
+
height = math.ceil(height / vision_encoder_max_size) * vision_encoder_max_size
|
| 488 |
+
elif height > width:
|
| 489 |
+
height = math.ceil(height / vision_encoder_max_size) * vision_encoder_max_size
|
| 490 |
+
width = int(height * aspect_ratio)
|
| 491 |
+
width = math.ceil(width / vision_encoder_max_size) * vision_encoder_max_size
|
| 492 |
+
new_size = {"height": height, "width": width}
|
| 493 |
+
return self.resize(
|
| 494 |
+
image, size=new_size, resample=resample, input_data_format=input_data_format, data_format=data_format
|
| 495 |
+
)
|
| 496 |
+
|
| 497 |
+
def _pad_image(
|
| 498 |
+
self,
|
| 499 |
+
image: np.ndarray,
|
| 500 |
+
output_size: tuple[int, int],
|
| 501 |
+
constant_values: Union[float, Iterable[float]] = 0,
|
| 502 |
+
data_format: Optional[ChannelDimension] = None,
|
| 503 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 504 |
+
) -> np.ndarray:
|
| 505 |
+
"""
|
| 506 |
+
Pad an image with zeros to the given size.
|
| 507 |
+
"""
|
| 508 |
+
input_height, input_width = get_image_size(image, channel_dim=input_data_format)
|
| 509 |
+
output_height, output_width = output_size
|
| 510 |
+
|
| 511 |
+
pad_bottom = output_height - input_height
|
| 512 |
+
pad_right = output_width - input_width
|
| 513 |
+
padding = ((0, pad_bottom), (0, pad_right))
|
| 514 |
+
padded_image = pad(
|
| 515 |
+
image,
|
| 516 |
+
padding,
|
| 517 |
+
mode=PaddingMode.CONSTANT,
|
| 518 |
+
constant_values=constant_values,
|
| 519 |
+
data_format=data_format,
|
| 520 |
+
input_data_format=input_data_format,
|
| 521 |
+
)
|
| 522 |
+
return padded_image
|
| 523 |
+
|
| 524 |
+
def pad(
|
| 525 |
+
self,
|
| 526 |
+
images: list[np.ndarray],
|
| 527 |
+
constant_values: Union[float, Iterable[float]] = 0,
|
| 528 |
+
return_pixel_mask: bool = True,
|
| 529 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 530 |
+
data_format: Optional[ChannelDimension] = None,
|
| 531 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 532 |
+
) -> BatchFeature:
|
| 533 |
+
"""
|
| 534 |
+
For a list of images, for each images, pads a batch of images to the bottom and right of the image with zeros to the size of largest height and width.
|
| 535 |
+
For each sample in the batch, pads the sample with empty images to the max_number of images per sample in the batch. Optionally returns a pixel mask.
|
| 536 |
+
Args:
|
| 537 |
+
images (`list[np.ndarray]`):
|
| 538 |
+
List of list of images to pad. Pads to the largest height and width in the batch.
|
| 539 |
+
constant_values (`float` or `Iterable[float]`, *optional*):
|
| 540 |
+
The value to use for the padding if `mode` is `"constant"`.
|
| 541 |
+
return_pixel_mask (`bool`, *optional*, defaults to `True`):
|
| 542 |
+
Whether to return a pixel mask.
|
| 543 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
| 544 |
+
The type of tensors to return. Can be one of:
|
| 545 |
+
- Unset: Return a list of `np.ndarray`.
|
| 546 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
| 547 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
| 548 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
| 549 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
| 550 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
| 551 |
+
The channel dimension format of the image. If not provided, it will be the same as the input image.
|
| 552 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 553 |
+
The channel dimension format of the input image. If not provided, it will be inferred.
|
| 554 |
+
"""
|
| 555 |
+
pad_size = get_max_height_width(images, input_data_format=input_data_format)
|
| 556 |
+
|
| 557 |
+
batch_size = len(images)
|
| 558 |
+
max_num_images = max(len(images_) for images_ in images)
|
| 559 |
+
input_data_format = (
|
| 560 |
+
infer_channel_dimension_format(images[0][0], num_channels=(1, 3, 4))
|
| 561 |
+
if input_data_format is None
|
| 562 |
+
else input_data_format
|
| 563 |
+
)
|
| 564 |
+
data_format = input_data_format if data_format is None else data_format
|
| 565 |
+
|
| 566 |
+
if input_data_format == ChannelDimension.FIRST:
|
| 567 |
+
n_channels = images[0][0].shape[0]
|
| 568 |
+
elif input_data_format == ChannelDimension.LAST:
|
| 569 |
+
n_channels = images[0][0].shape[-1]
|
| 570 |
+
else:
|
| 571 |
+
raise ValueError("Invalid channel dimension format.")
|
| 572 |
+
|
| 573 |
+
def empty_image(size, input_data_format):
|
| 574 |
+
if input_data_format == ChannelDimension.FIRST:
|
| 575 |
+
return np.zeros((n_channels, *size), dtype=np.uint8)
|
| 576 |
+
elif input_data_format == ChannelDimension.LAST:
|
| 577 |
+
return np.zeros((*size, n_channels), dtype=np.uint8)
|
| 578 |
+
|
| 579 |
+
padded_images_list = [
|
| 580 |
+
[empty_image(pad_size, data_format) for _ in range(max_num_images)] for _ in range(batch_size)
|
| 581 |
+
]
|
| 582 |
+
padded_masks = [[np.zeros(pad_size, dtype=np.int64) for _ in range(max_num_images)] for _ in range(batch_size)]
|
| 583 |
+
|
| 584 |
+
for batch_idx in range(batch_size):
|
| 585 |
+
for sample_idx, image in enumerate(images[batch_idx]):
|
| 586 |
+
padded_images_list[batch_idx][sample_idx] = self._pad_image(
|
| 587 |
+
image,
|
| 588 |
+
pad_size,
|
| 589 |
+
constant_values=constant_values,
|
| 590 |
+
data_format=data_format,
|
| 591 |
+
input_data_format=input_data_format,
|
| 592 |
+
)
|
| 593 |
+
padded_masks[batch_idx][sample_idx] = make_pixel_mask(
|
| 594 |
+
image, output_size=pad_size, input_data_format=input_data_format
|
| 595 |
+
)
|
| 596 |
+
|
| 597 |
+
padded_masks = padded_masks if return_pixel_mask else None
|
| 598 |
+
return padded_images_list, padded_masks
|
| 599 |
+
|
| 600 |
+
def preprocess(
|
| 601 |
+
self,
|
| 602 |
+
images: ImageInput,
|
| 603 |
+
do_convert_rgb: Optional[bool] = None,
|
| 604 |
+
do_resize: Optional[bool] = None,
|
| 605 |
+
size: Optional[dict[str, int]] = None,
|
| 606 |
+
resample: PILImageResampling = None,
|
| 607 |
+
do_image_splitting: Optional[bool] = None,
|
| 608 |
+
do_rescale: Optional[bool] = None,
|
| 609 |
+
max_image_size: Optional[dict[str, int]] = None,
|
| 610 |
+
rescale_factor: Optional[float] = None,
|
| 611 |
+
do_normalize: Optional[bool] = None,
|
| 612 |
+
image_mean: Optional[Union[float, list[float]]] = None,
|
| 613 |
+
image_std: Optional[Union[float, list[float]]] = None,
|
| 614 |
+
do_pad: Optional[bool] = None,
|
| 615 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 616 |
+
return_row_col_info: bool = False,
|
| 617 |
+
data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
|
| 618 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 619 |
+
):
|
| 620 |
+
"""
|
| 621 |
+
Preprocess a batch of images.
|
| 622 |
+
Args:
|
| 623 |
+
images (`ImageInput`):
|
| 624 |
+
A list of images to preprocess.
|
| 625 |
+
do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
|
| 626 |
+
Whether to convert the image to RGB.
|
| 627 |
+
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
|
| 628 |
+
Whether to resize the image.
|
| 629 |
+
size (`dict[str, int]`, *optional*, defaults to `self.size`):
|
| 630 |
+
Size of the image after resizing. With the longest edge resized to keep the input aspect ratio.
|
| 631 |
+
resample (`int`, *optional*, defaults to `self.resample`):
|
| 632 |
+
Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
|
| 633 |
+
has an effect if `do_resize` is set to `True`.
|
| 634 |
+
do_image_splitting (`bool`, *optional*, defaults to `self.do_image_splitting`):
|
| 635 |
+
Whether to split the image into sub-images concatenated with the original image. They are split into patches
|
| 636 |
+
such that each patch has a size of `max_image_size["height"]` x `max_image_size["width"]`.
|
| 637 |
+
max_image_size (`Dict`, *optional*, defaults to `self.max_image_size`):
|
| 638 |
+
Maximum resolution of the images. If the image is larger than this size, the image is split into patches.
|
| 639 |
+
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
|
| 640 |
+
Whether to rescale the image.
|
| 641 |
+
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
|
| 642 |
+
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
|
| 643 |
+
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
|
| 644 |
+
Whether to normalize the image.
|
| 645 |
+
image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
|
| 646 |
+
Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
|
| 647 |
+
image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
|
| 648 |
+
Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
|
| 649 |
+
`True`.
|
| 650 |
+
do_pad (`bool`, *optional*, defaults to `self.do_pad`):
|
| 651 |
+
Whether or not to pad the images to the largest height and width in the batch.
|
| 652 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
| 653 |
+
The type of tensors to return. Can be one of:
|
| 654 |
+
- Unset: Return a list of `np.ndarray`.
|
| 655 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
| 656 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
| 657 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
| 658 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
| 659 |
+
return_row_col_info (`bool`, *optional*, default to `False`):
|
| 660 |
+
Whether to return the number of rows and columns of the split images. This is used for the
|
| 661 |
+
`SmolVLMProcessor` to generate prompt strings based on the number of rows and columns.
|
| 662 |
+
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
|
| 663 |
+
The channel dimension format for the output image. Can be one of:
|
| 664 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 665 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 666 |
+
- Unset: Use the channel dimension format of the input image.
|
| 667 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 668 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
| 669 |
+
from the input image. Can be one of:
|
| 670 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 671 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 672 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 673 |
+
"""
|
| 674 |
+
do_resize = do_resize if do_resize is not None else self.do_resize
|
| 675 |
+
size = size if size is not None else self.size
|
| 676 |
+
resample = resample if resample is not None else self.resample
|
| 677 |
+
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
|
| 678 |
+
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
|
| 679 |
+
do_image_splitting = do_image_splitting if do_image_splitting is not None else self.do_image_splitting
|
| 680 |
+
max_image_size = max_image_size if max_image_size is not None else self.max_image_size
|
| 681 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
| 682 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
| 683 |
+
image_std = image_std if image_std is not None else self.image_std
|
| 684 |
+
do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
|
| 685 |
+
do_pad = do_pad if do_pad is not None else self.do_pad
|
| 686 |
+
|
| 687 |
+
images = self.fetch_images(images)
|
| 688 |
+
images_list = make_nested_list_of_images(images)
|
| 689 |
+
|
| 690 |
+
if not valid_images(images_list[0]):
|
| 691 |
+
raise ValueError(
|
| 692 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
| 693 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
| 694 |
+
)
|
| 695 |
+
|
| 696 |
+
validate_preprocess_arguments(
|
| 697 |
+
do_rescale=do_rescale,
|
| 698 |
+
rescale_factor=rescale_factor,
|
| 699 |
+
do_normalize=do_normalize,
|
| 700 |
+
image_mean=image_mean,
|
| 701 |
+
image_std=image_std,
|
| 702 |
+
do_resize=do_resize,
|
| 703 |
+
size=size,
|
| 704 |
+
resample=resample,
|
| 705 |
+
)
|
| 706 |
+
|
| 707 |
+
# save the palettes for conversion to RGB
|
| 708 |
+
palettes_list = [
|
| 709 |
+
[im.getpalette() if isinstance(im, Image.Image) and im.mode == "P" else None for im in images]
|
| 710 |
+
for images in images_list
|
| 711 |
+
]
|
| 712 |
+
|
| 713 |
+
# All transformations expect numpy arrays.
|
| 714 |
+
images_list = [[to_numpy_array(image) for image in images] for images in images_list]
|
| 715 |
+
|
| 716 |
+
# Extra channel dimension for grayscale images
|
| 717 |
+
if input_data_format in [ChannelDimension.LAST, None]:
|
| 718 |
+
images_list = [
|
| 719 |
+
[np.expand_dims(img, axis=-1) if img.ndim == 2 else img for img in images] for images in images_list
|
| 720 |
+
]
|
| 721 |
+
elif input_data_format == ChannelDimension.FIRST:
|
| 722 |
+
images_list = [
|
| 723 |
+
[np.expand_dims(img, axis=0) if img.ndim == 2 else img for img in images] for images in images_list
|
| 724 |
+
]
|
| 725 |
+
|
| 726 |
+
if do_rescale and is_scaled_image(images_list[0][0]):
|
| 727 |
+
logger.warning_once(
|
| 728 |
+
"It looks like you are trying to rescale already rescaled images. If the input"
|
| 729 |
+
" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
|
| 730 |
+
)
|
| 731 |
+
|
| 732 |
+
# We assume that all images have the same channel dimension format.
|
| 733 |
+
if input_data_format is None:
|
| 734 |
+
input_data_format = infer_channel_dimension_format(images_list[0][0], num_channels=(1, 3, 4))
|
| 735 |
+
|
| 736 |
+
if do_resize:
|
| 737 |
+
images_list = [
|
| 738 |
+
[
|
| 739 |
+
self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
|
| 740 |
+
for image in images
|
| 741 |
+
]
|
| 742 |
+
for images in images_list
|
| 743 |
+
]
|
| 744 |
+
|
| 745 |
+
if do_image_splitting:
|
| 746 |
+
# We first resize both height and width of each image to the nearest max_image_size multiple, disregarding the aspect ratio
|
| 747 |
+
# for size=(10, max_image_size) -> rescaled_size=(max_image_size, max_image_size)
|
| 748 |
+
# for size=(11, max_image_size+1) -> rescaled_size=(max_image_size, max_image_size*2)
|
| 749 |
+
images_list = [
|
| 750 |
+
[
|
| 751 |
+
self.resize_for_vision_encoder(
|
| 752 |
+
image, max_image_size["longest_edge"], resample=resample, input_data_format=input_data_format
|
| 753 |
+
)
|
| 754 |
+
for image in images
|
| 755 |
+
]
|
| 756 |
+
for images in images_list
|
| 757 |
+
]
|
| 758 |
+
images_list_split_arrays = []
|
| 759 |
+
palettes_list_split_arrays = []
|
| 760 |
+
images_list_rows = []
|
| 761 |
+
images_list_cols = []
|
| 762 |
+
for images, palettes in zip(images_list, palettes_list):
|
| 763 |
+
split_image_arrays = []
|
| 764 |
+
split_palettes_arrays = []
|
| 765 |
+
image_rows = []
|
| 766 |
+
image_cols = []
|
| 767 |
+
for image, palette in zip(images, palettes):
|
| 768 |
+
split_image_array, rows, cols = self.split_image(
|
| 769 |
+
image,
|
| 770 |
+
max_image_size=max_image_size,
|
| 771 |
+
resample=resample,
|
| 772 |
+
input_data_format=input_data_format,
|
| 773 |
+
)
|
| 774 |
+
split_image_arrays.extend(split_image_array)
|
| 775 |
+
split_palettes_arrays.extend([palette] * len(split_image_array))
|
| 776 |
+
image_rows.append(rows)
|
| 777 |
+
image_cols.append(cols)
|
| 778 |
+
images_list_split_arrays.append(split_image_arrays)
|
| 779 |
+
palettes_list_split_arrays.append(split_palettes_arrays)
|
| 780 |
+
images_list_rows.append(image_rows)
|
| 781 |
+
images_list_cols.append(image_cols)
|
| 782 |
+
images_list = images_list_split_arrays
|
| 783 |
+
palettes_list = palettes_list_split_arrays
|
| 784 |
+
else:
|
| 785 |
+
# We square the images to max_image_size
|
| 786 |
+
images_list = [
|
| 787 |
+
[
|
| 788 |
+
self.resize(
|
| 789 |
+
image=image,
|
| 790 |
+
size={"height": max_image_size["longest_edge"], "width": max_image_size["longest_edge"]},
|
| 791 |
+
resample=resample,
|
| 792 |
+
input_data_format=input_data_format,
|
| 793 |
+
)
|
| 794 |
+
for image in images
|
| 795 |
+
]
|
| 796 |
+
for images in images_list
|
| 797 |
+
]
|
| 798 |
+
images_list_rows = [[0] * len(images) for images in images_list]
|
| 799 |
+
images_list_cols = [[0] * len(images) for images in images_list]
|
| 800 |
+
|
| 801 |
+
if do_convert_rgb:
|
| 802 |
+
images_list = [
|
| 803 |
+
[convert_to_rgb(img, palette) for img, palette in zip(images, palettes)]
|
| 804 |
+
for images, palettes in zip(images_list, palettes_list)
|
| 805 |
+
]
|
| 806 |
+
|
| 807 |
+
if do_rescale:
|
| 808 |
+
images_list = [
|
| 809 |
+
[self.rescale(image, rescale_factor, input_data_format=input_data_format) for image in images]
|
| 810 |
+
for images in images_list
|
| 811 |
+
]
|
| 812 |
+
|
| 813 |
+
if do_normalize:
|
| 814 |
+
images_list = [
|
| 815 |
+
[
|
| 816 |
+
self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
|
| 817 |
+
for image in images
|
| 818 |
+
]
|
| 819 |
+
for images in images_list
|
| 820 |
+
]
|
| 821 |
+
|
| 822 |
+
pixel_attention_mask = None
|
| 823 |
+
if do_pad:
|
| 824 |
+
images_list, pixel_attention_mask = self.pad(
|
| 825 |
+
images_list, return_pixel_mask=True, return_tensors=return_tensors, input_data_format=input_data_format
|
| 826 |
+
)
|
| 827 |
+
|
| 828 |
+
if data_format is not None:
|
| 829 |
+
images_list = [
|
| 830 |
+
[
|
| 831 |
+
to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
|
| 832 |
+
for image in images
|
| 833 |
+
]
|
| 834 |
+
for images in images_list
|
| 835 |
+
]
|
| 836 |
+
|
| 837 |
+
# Faster tensor conversion
|
| 838 |
+
data = {"pixel_values": np.array(images_list) if do_pad and return_tensors is not None else images_list}
|
| 839 |
+
if pixel_attention_mask is not None:
|
| 840 |
+
data["pixel_attention_mask"] = (
|
| 841 |
+
np.array(pixel_attention_mask) if do_pad and return_tensors is not None else pixel_attention_mask
|
| 842 |
+
)
|
| 843 |
+
|
| 844 |
+
encoding = BatchFeature(data=data, tensor_type=return_tensors)
|
| 845 |
+
|
| 846 |
+
# This is needed for generating correct text inputs in the processor - we don't pad to the max number of images
|
| 847 |
+
if return_row_col_info:
|
| 848 |
+
encoding["rows"] = images_list_rows
|
| 849 |
+
encoding["cols"] = images_list_cols
|
| 850 |
+
|
| 851 |
+
return encoding
|
| 852 |
+
|
| 853 |
+
def get_number_of_image_patches(self, height: int, width: int, images_kwargs=None):
|
| 854 |
+
"""
|
| 855 |
+
A utility that returns number of image patches for a given image size.
|
| 856 |
+
|
| 857 |
+
Args:
|
| 858 |
+
height (`int`):
|
| 859 |
+
Height of the input image.
|
| 860 |
+
width (`int`):
|
| 861 |
+
Width of the input image.
|
| 862 |
+
images_kwargs (`dict`, *optional*)
|
| 863 |
+
Any kwargs to override defaults of the image processor.
|
| 864 |
+
Returns:
|
| 865 |
+
`int`: Number of patches per image.
|
| 866 |
+
"""
|
| 867 |
+
do_image_splitting = images_kwargs.get("do_image_splitting", self.do_image_splitting)
|
| 868 |
+
max_image_size = images_kwargs.get("max_image_size", self.max_image_size)
|
| 869 |
+
size = images_kwargs.get("size", self.size)
|
| 870 |
+
|
| 871 |
+
num_patches = num_rows = num_cols = 1
|
| 872 |
+
if do_image_splitting:
|
| 873 |
+
height, width = _resize_output_size_rescale_to_max_len(height, width, max_len=size["longest_edge"])
|
| 874 |
+
height, width = _resize_output_size_scale_below_upper_bound(height, width, max_len=4096)
|
| 875 |
+
aspect_ratio = width / height
|
| 876 |
+
|
| 877 |
+
if width >= height:
|
| 878 |
+
resized_width = math.ceil(width / max_image_size["longest_edge"]) * max_image_size["longest_edge"]
|
| 879 |
+
resized_height = int(width / aspect_ratio)
|
| 880 |
+
resized_height = math.ceil(height / max_image_size["longest_edge"]) * max_image_size["longest_edge"]
|
| 881 |
+
elif height > width:
|
| 882 |
+
resized_height = math.ceil(height / max_image_size["longest_edge"]) * max_image_size["longest_edge"]
|
| 883 |
+
resized_width = int(height * aspect_ratio)
|
| 884 |
+
resized_width = math.ceil(width / max_image_size["longest_edge"]) * max_image_size["longest_edge"]
|
| 885 |
+
|
| 886 |
+
max_height = max_width = max_image_size["longest_edge"]
|
| 887 |
+
if resized_height > max_height or resized_width > max_width:
|
| 888 |
+
# Calculate the number of splits
|
| 889 |
+
num_rows = math.ceil(resized_height / max_height)
|
| 890 |
+
num_cols = math.ceil(resized_width / max_width)
|
| 891 |
+
num_patches = num_rows * num_cols + 1
|
| 892 |
+
|
| 893 |
+
return num_patches, num_rows, num_cols
|
| 894 |
+
|
| 895 |
+
|
| 896 |
+
__all__ = ["SmolVLMImageProcessor"]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/smolvlm/image_processing_smolvlm_fast.py
ADDED
|
@@ -0,0 +1,536 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/smolvlm/modular_smolvlm.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_smolvlm.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# coding=utf-8
|
| 8 |
+
# Copyright 2025 the HuggingFace Inc. team. All rights reserved.
|
| 9 |
+
# Written by Orr Zohar
|
| 10 |
+
#
|
| 11 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 12 |
+
# you may not use this file except in compliance with the License.
|
| 13 |
+
# You may obtain a copy of the License at
|
| 14 |
+
#
|
| 15 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 16 |
+
#
|
| 17 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 18 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 19 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 20 |
+
# See the License for the specific language governing permissions and
|
| 21 |
+
# limitations under the License.
|
| 22 |
+
import math
|
| 23 |
+
from typing import Optional, Union
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
|
| 27 |
+
from ...image_processing_utils import BatchFeature
|
| 28 |
+
from ...image_processing_utils_fast import (
|
| 29 |
+
BaseImageProcessorFast,
|
| 30 |
+
DefaultFastImageProcessorKwargs,
|
| 31 |
+
SizeDict,
|
| 32 |
+
group_images_by_shape,
|
| 33 |
+
reorder_images,
|
| 34 |
+
)
|
| 35 |
+
from ...image_utils import (
|
| 36 |
+
IMAGENET_STANDARD_MEAN,
|
| 37 |
+
IMAGENET_STANDARD_STD,
|
| 38 |
+
ImageInput,
|
| 39 |
+
PILImageResampling,
|
| 40 |
+
make_nested_list_of_images,
|
| 41 |
+
)
|
| 42 |
+
from ...processing_utils import Unpack
|
| 43 |
+
from ...utils import TensorType, auto_docstring, is_torchvision_available, logging
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
if is_torchvision_available():
|
| 47 |
+
from torchvision.transforms import functional as F
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
logger = logging.get_logger(__name__)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class SmolVLMFastImageProcessorKwargs(DefaultFastImageProcessorKwargs):
|
| 54 |
+
"""
|
| 55 |
+
do_pad (`bool`, *optional*):
|
| 56 |
+
Whether to pad the image. If `True`, will pad the patch dimension of the images in the batch to the largest
|
| 57 |
+
number of patches in the batch. Padding will be applied to the bottom and right with zeros.
|
| 58 |
+
do_image_splitting (`bool`, *optional*, defaults to `True`):
|
| 59 |
+
Whether to split the image into sub-images concatenated with the original image. They are split into patches
|
| 60 |
+
such that each patch has a size of `max_image_size["height"]` x `max_image_size["width"]`.
|
| 61 |
+
max_image_size (`Dict`, *optional*, defaults to `{"longest_edge": 364}`):
|
| 62 |
+
Maximum resolution of the patches of images accepted by the model. This is a dictionary containing the key "longest_edge".
|
| 63 |
+
return_row_col_info (`bool`, *optional*, defaults to `False`):
|
| 64 |
+
Whether to return the row and column information of the images.
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
do_pad: Optional[bool]
|
| 68 |
+
do_image_splitting: Optional[bool]
|
| 69 |
+
max_image_size: Optional[dict[str, int]]
|
| 70 |
+
return_row_col_info: Optional[bool]
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
MAX_IMAGE_SIZE = 4096 # 4k resolution as absolute maximum
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _resize_output_size_rescale_to_max_len(
|
| 77 |
+
height: int, width: int, min_len: Optional[int] = 1, max_len: Optional[int] = None
|
| 78 |
+
) -> tuple[int, int]:
|
| 79 |
+
"""
|
| 80 |
+
Get the output size of the image after resizing given a dictionary specifying the max and min sizes.
|
| 81 |
+
Args:
|
| 82 |
+
height (`int`):
|
| 83 |
+
Height of the input image.
|
| 84 |
+
width (`int`):
|
| 85 |
+
Width of the input image.
|
| 86 |
+
min_len (`int`, *optional*, defaults to 1):
|
| 87 |
+
Minimum size of the output image.
|
| 88 |
+
max_len (`int`, *optional*, defaults to the maximum size of the image):
|
| 89 |
+
Maximum size of the output image.
|
| 90 |
+
Returns:
|
| 91 |
+
The output size of the image after resizing.
|
| 92 |
+
"""
|
| 93 |
+
max_len = max(height, width) if max_len is None else max_len
|
| 94 |
+
aspect_ratio = width / height
|
| 95 |
+
|
| 96 |
+
if width >= height:
|
| 97 |
+
width = max_len
|
| 98 |
+
height = int(width / aspect_ratio)
|
| 99 |
+
if height % 2 != 0:
|
| 100 |
+
height += 1
|
| 101 |
+
elif height > width:
|
| 102 |
+
height = max_len
|
| 103 |
+
width = int(height * aspect_ratio)
|
| 104 |
+
if width % 2 != 0:
|
| 105 |
+
width += 1
|
| 106 |
+
|
| 107 |
+
# Avoid resizing to a size smaller than min_len
|
| 108 |
+
height = max(height, min_len)
|
| 109 |
+
width = max(width, min_len)
|
| 110 |
+
return height, width
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _resize_output_size_scale_below_upper_bound(
|
| 114 |
+
height: int, width: int, max_len: Optional[dict[str, int]] = None
|
| 115 |
+
) -> tuple[int, int]:
|
| 116 |
+
"""
|
| 117 |
+
Get the output size of the image after resizing given a dictionary specifying the max and min sizes.
|
| 118 |
+
Args:
|
| 119 |
+
height (`int`):
|
| 120 |
+
Height of the input image.
|
| 121 |
+
width (`int`):
|
| 122 |
+
Width of the input image.
|
| 123 |
+
max_len (`Dict[str, int]`, *optional*, defaults to the maximum size of the image):
|
| 124 |
+
Defines the maximum dimensions of the image.
|
| 125 |
+
Returns:
|
| 126 |
+
The output size of the image after resizing.
|
| 127 |
+
"""
|
| 128 |
+
max_len = max(height, width) if max_len is None else max_len
|
| 129 |
+
|
| 130 |
+
aspect_ratio = width / height
|
| 131 |
+
if width >= height and width > max_len:
|
| 132 |
+
width = max_len
|
| 133 |
+
height = int(width / aspect_ratio)
|
| 134 |
+
elif height > width and height > max_len:
|
| 135 |
+
height = max_len
|
| 136 |
+
width = int(height * aspect_ratio)
|
| 137 |
+
|
| 138 |
+
# Avoid resizing to a size smaller than 1
|
| 139 |
+
height = max(height, 1)
|
| 140 |
+
width = max(width, 1)
|
| 141 |
+
return height, width
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def get_resize_output_image_size(
|
| 145 |
+
image,
|
| 146 |
+
resolution_max_side: int,
|
| 147 |
+
) -> tuple[int, int]:
|
| 148 |
+
"""
|
| 149 |
+
Get the output size of the image after resizing given a dictionary specifying the max and min sizes.
|
| 150 |
+
Args:
|
| 151 |
+
image (`torch.Tensor`):
|
| 152 |
+
Image to resize.
|
| 153 |
+
resolution_max_side (`int`):
|
| 154 |
+
The longest edge of the image will be resized to this value. The shortest edge will be resized to keep the
|
| 155 |
+
input aspect ratio.
|
| 156 |
+
Returns:
|
| 157 |
+
The output size of the image after resizing.
|
| 158 |
+
"""
|
| 159 |
+
height, width = image.size()[-2:]
|
| 160 |
+
|
| 161 |
+
# Find the output size, when rescaling the longest edge to max_len and preserving the aspect ratio
|
| 162 |
+
height, width = _resize_output_size_rescale_to_max_len(height, width, max_len=resolution_max_side)
|
| 163 |
+
# Find the output size when scaling the image to be below the MAX_IMAGE_SIZE
|
| 164 |
+
height, width = _resize_output_size_scale_below_upper_bound(height, width, max_len=MAX_IMAGE_SIZE)
|
| 165 |
+
return height, width
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def get_max_height_width(images_list: list[list["torch.Tensor"]]) -> tuple[int, int]:
|
| 169 |
+
"""
|
| 170 |
+
Get the maximum height and width across all images in a batch.
|
| 171 |
+
"""
|
| 172 |
+
image_sizes = []
|
| 173 |
+
for images in images_list:
|
| 174 |
+
for image in images:
|
| 175 |
+
image_sizes.append(image.size()[-2:])
|
| 176 |
+
|
| 177 |
+
max_height = max(size[0] for size in image_sizes)
|
| 178 |
+
max_width = max(size[1] for size in image_sizes)
|
| 179 |
+
return (max_height, max_width)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
@auto_docstring
|
| 183 |
+
class SmolVLMImageProcessorFast(BaseImageProcessorFast):
|
| 184 |
+
resample = PILImageResampling.LANCZOS
|
| 185 |
+
image_mean = IMAGENET_STANDARD_MEAN
|
| 186 |
+
image_std = IMAGENET_STANDARD_STD
|
| 187 |
+
size = {"longest_edge": 4 * 364}
|
| 188 |
+
max_image_size = {"longest_edge": 364}
|
| 189 |
+
do_resize = True
|
| 190 |
+
do_rescale = True
|
| 191 |
+
do_normalize = True
|
| 192 |
+
do_convert_rgb = True
|
| 193 |
+
do_image_splitting = True
|
| 194 |
+
do_pad = True
|
| 195 |
+
return_row_col_info = False
|
| 196 |
+
valid_kwargs = SmolVLMFastImageProcessorKwargs
|
| 197 |
+
|
| 198 |
+
def _prepare_images_structure(self, images: ImageInput, expected_ndims: int = 3) -> ImageInput:
|
| 199 |
+
"""
|
| 200 |
+
Prepare a nested images structure for processing.
|
| 201 |
+
"""
|
| 202 |
+
return make_nested_list_of_images(images, expected_ndims=expected_ndims)
|
| 203 |
+
|
| 204 |
+
def resize(
|
| 205 |
+
self,
|
| 206 |
+
image: "torch.Tensor",
|
| 207 |
+
size: SizeDict,
|
| 208 |
+
interpolation: "F.InterpolationMode" = None,
|
| 209 |
+
antialias: bool = True,
|
| 210 |
+
**kwargs,
|
| 211 |
+
) -> "torch.Tensor":
|
| 212 |
+
"""
|
| 213 |
+
Resize an image. The longest edge of the image is resized to size.longest_edge, with the shortest edge
|
| 214 |
+
resized to keep the input aspect ratio. Can also be used with size.height and size.width.
|
| 215 |
+
Args:
|
| 216 |
+
image (`np.ndarray`):
|
| 217 |
+
Image to resize.
|
| 218 |
+
size (`Dict[str, int]`):
|
| 219 |
+
Size of the output image.
|
| 220 |
+
interpolation (`InterpolationMode`, *optional*, defaults to `InterpolationMode.BILINEAR`):
|
| 221 |
+
`InterpolationMode` filter to use when resizing the image e.g. `InterpolationMode.BICUBIC`.
|
| 222 |
+
antialias (`bool`, *optional*, defaults to `True`):
|
| 223 |
+
Whether to use antialiasing when resizing the image.
|
| 224 |
+
"""
|
| 225 |
+
interpolation = interpolation if interpolation is not None else F.InterpolationMode.BILINEAR
|
| 226 |
+
if interpolation == F.InterpolationMode.LANCZOS:
|
| 227 |
+
logger.warning_once(
|
| 228 |
+
"You have used fast image processor with LANCZOS resample which not yet supported for torch.Tensor. "
|
| 229 |
+
"BICUBIC resample will be used as an alternative. Please fall back to slow image processor if you "
|
| 230 |
+
"want full consistency with the original model."
|
| 231 |
+
)
|
| 232 |
+
interpolation = F.InterpolationMode.BICUBIC
|
| 233 |
+
|
| 234 |
+
if size.longest_edge:
|
| 235 |
+
size = get_resize_output_image_size(image, resolution_max_side=size.longest_edge)
|
| 236 |
+
elif size.height and size.width:
|
| 237 |
+
size = (size.height, size.width)
|
| 238 |
+
else:
|
| 239 |
+
raise ValueError("size must be a dictionary with key 'longest_edge' or 'height' and 'width'.")
|
| 240 |
+
|
| 241 |
+
return F.resize(image, size, interpolation=interpolation, antialias=antialias)
|
| 242 |
+
|
| 243 |
+
def split_images(
|
| 244 |
+
self,
|
| 245 |
+
images: torch.Tensor,
|
| 246 |
+
max_image_size: dict[str, int],
|
| 247 |
+
interpolation: "F.InterpolationMode" = None,
|
| 248 |
+
):
|
| 249 |
+
"""
|
| 250 |
+
Split an image into squares of side max_image_size and the original image resized to max_image_size.
|
| 251 |
+
That means that a single image becomes a sequence of images.
|
| 252 |
+
This is a "trick" to spend more compute on each image with no changes in the vision encoder.
|
| 253 |
+
1) If one side of the original image is larger than `max_image_size`, resize it to `max_image_size` while preserving the aspect ratio.
|
| 254 |
+
2) Divide the resulting image into `ceil(height / max_image_size)` x `ceil(width / max_image_size)`
|
| 255 |
+
sub-images of the same size each (image_size, image_size). Typically, 364x364.
|
| 256 |
+
3) Returns the list of the crops and the original image, in addition to the number of splits for the height and the width.
|
| 257 |
+
Args:
|
| 258 |
+
images (`torch.Tensor`):
|
| 259 |
+
Images to split.
|
| 260 |
+
max_image_size (`Dict[str, int]`):
|
| 261 |
+
Maximum size of the output image. If the image is larger than this size, it will be split into
|
| 262 |
+
patches of this size, and the original image will be concatenated with the patches, resized to max_size.
|
| 263 |
+
interpolation (`InterpolationMode`, *optional*, defaults to `InterpolationMode.BILINEAR`):
|
| 264 |
+
`InterpolationMode` filter to use when resizing the image e.g. `InterpolationMode.BICUBIC`.
|
| 265 |
+
"""
|
| 266 |
+
batch_size, num_channels, height, width = images.size()
|
| 267 |
+
height_dim, width_dim = 2, 3
|
| 268 |
+
|
| 269 |
+
max_height = max_width = max_image_size["longest_edge"]
|
| 270 |
+
|
| 271 |
+
frames = []
|
| 272 |
+
if height > max_height or width > max_width:
|
| 273 |
+
# Calculate the number of splits
|
| 274 |
+
num_splits_h = math.ceil(height / max_height)
|
| 275 |
+
num_splits_w = math.ceil(width / max_width)
|
| 276 |
+
|
| 277 |
+
# Split the images by height, then by width
|
| 278 |
+
frames = (
|
| 279 |
+
images.unfold(height_dim, size=max_height, step=max_height)
|
| 280 |
+
.unfold(width_dim, size=max_width, step=max_width)
|
| 281 |
+
.contiguous()
|
| 282 |
+
.view(batch_size, num_channels, -1, max_height, max_width)
|
| 283 |
+
.permute(0, 2, 1, 3, 4)
|
| 284 |
+
) # batch_size x n_frames x num_channels x height x width
|
| 285 |
+
|
| 286 |
+
# For the global image at the end, we resize it to match the max_image_size, for cpu memory efficiency
|
| 287 |
+
global_image_height, global_image_width = max_height, max_width
|
| 288 |
+
images = self.resize(
|
| 289 |
+
images, SizeDict(height=global_image_height, width=global_image_width), interpolation=interpolation
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
frames = torch.cat((frames, images.unsqueeze(1)), dim=1)
|
| 293 |
+
else:
|
| 294 |
+
num_splits_h, num_splits_w = 0, 0
|
| 295 |
+
frames = images.unsqueeze(1)
|
| 296 |
+
|
| 297 |
+
num_splits_h = [num_splits_h] * batch_size
|
| 298 |
+
num_splits_w = [num_splits_w] * batch_size
|
| 299 |
+
|
| 300 |
+
return frames, num_splits_h, num_splits_w
|
| 301 |
+
|
| 302 |
+
def resize_for_vision_encoder(
|
| 303 |
+
self,
|
| 304 |
+
image: torch.Tensor,
|
| 305 |
+
vision_encoder_max_size: int,
|
| 306 |
+
interpolation: "F.InterpolationMode" = None,
|
| 307 |
+
):
|
| 308 |
+
"""
|
| 309 |
+
Resize images to be multiples of `vision_encoder_max_size` while preserving the aspect ratio.
|
| 310 |
+
Args:
|
| 311 |
+
image (`torch.Tensor`):
|
| 312 |
+
Images to resize.
|
| 313 |
+
vision_encoder_max_size (`int`):
|
| 314 |
+
Maximum size of the output image. If the image is larger than this size, it will be split into
|
| 315 |
+
patches of this size, and the original image will be concatenated with the patches, resized to max_size.
|
| 316 |
+
interpolation (`InterpolationMode`, *optional*, defaults to `InterpolationMode.BILINEAR`):
|
| 317 |
+
`InterpolationMode` filter to use when resizing the image e.g. `InterpolationMode.BICUBIC`.
|
| 318 |
+
"""
|
| 319 |
+
height, width = image.size()[-2:]
|
| 320 |
+
|
| 321 |
+
aspect_ratio = width / height
|
| 322 |
+
if width >= height:
|
| 323 |
+
width = math.ceil(width / vision_encoder_max_size) * vision_encoder_max_size
|
| 324 |
+
height = int(width / aspect_ratio)
|
| 325 |
+
height = math.ceil(height / vision_encoder_max_size) * vision_encoder_max_size
|
| 326 |
+
elif height > width:
|
| 327 |
+
height = math.ceil(height / vision_encoder_max_size) * vision_encoder_max_size
|
| 328 |
+
width = int(height * aspect_ratio)
|
| 329 |
+
width = math.ceil(width / vision_encoder_max_size) * vision_encoder_max_size
|
| 330 |
+
new_size = SizeDict(height=height, width=width)
|
| 331 |
+
return self.resize(image, size=new_size, interpolation=interpolation)
|
| 332 |
+
|
| 333 |
+
def pad(
|
| 334 |
+
self,
|
| 335 |
+
image: torch.Tensor,
|
| 336 |
+
padded_size: tuple[int, int],
|
| 337 |
+
fill: int = 0,
|
| 338 |
+
return_pixel_mask: bool = True,
|
| 339 |
+
):
|
| 340 |
+
original_size = image.shape[-2:]
|
| 341 |
+
padding_bottom = padded_size[0] - original_size[0]
|
| 342 |
+
padding_right = padded_size[1] - original_size[1]
|
| 343 |
+
|
| 344 |
+
if padding_bottom < 0 or padding_right < 0:
|
| 345 |
+
raise ValueError(
|
| 346 |
+
f"Padding dimensions are negative. Please make sure that the padded size is larger than the "
|
| 347 |
+
f"original size. Got padded size: {padded_size}, original size: {original_size}."
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
# Only pad if necessary
|
| 351 |
+
if original_size != padded_size:
|
| 352 |
+
padding = (0, 0, padding_right, padding_bottom)
|
| 353 |
+
image = F.pad(image, padding, fill=fill, padding_mode="constant")
|
| 354 |
+
|
| 355 |
+
# Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding.
|
| 356 |
+
pixel_mask = None
|
| 357 |
+
if return_pixel_mask:
|
| 358 |
+
pixel_mask = torch.zeros_like(image[..., 0, :, :], dtype=torch.int64)
|
| 359 |
+
pixel_mask[: original_size[0], : original_size[1]] = 1
|
| 360 |
+
|
| 361 |
+
return image, pixel_mask
|
| 362 |
+
|
| 363 |
+
@auto_docstring
|
| 364 |
+
def preprocess(self, images: ImageInput, **kwargs: Unpack[SmolVLMFastImageProcessorKwargs]) -> BatchFeature:
|
| 365 |
+
return super().preprocess(images, **kwargs)
|
| 366 |
+
|
| 367 |
+
def _preprocess(
|
| 368 |
+
self,
|
| 369 |
+
images: list[list["torch.Tensor"]],
|
| 370 |
+
do_resize: bool,
|
| 371 |
+
size: SizeDict,
|
| 372 |
+
interpolation: Optional["F.InterpolationMode"],
|
| 373 |
+
do_rescale: bool,
|
| 374 |
+
rescale_factor: float,
|
| 375 |
+
do_normalize: bool,
|
| 376 |
+
image_mean: Optional[Union[float, list[float]]],
|
| 377 |
+
image_std: Optional[Union[float, list[float]]],
|
| 378 |
+
do_pad: Optional[bool],
|
| 379 |
+
do_image_splitting: Optional[bool],
|
| 380 |
+
max_image_size: Optional[dict[str, int]],
|
| 381 |
+
return_row_col_info: Optional[bool],
|
| 382 |
+
disable_grouping: Optional[bool],
|
| 383 |
+
return_tensors: Optional[Union[str, TensorType]],
|
| 384 |
+
**kwargs,
|
| 385 |
+
) -> BatchFeature:
|
| 386 |
+
"""
|
| 387 |
+
Process a batch of images for the model.
|
| 388 |
+
"""
|
| 389 |
+
|
| 390 |
+
grouped_images, grouped_images_index = group_images_by_shape(
|
| 391 |
+
images, is_nested=True, disable_grouping=disable_grouping
|
| 392 |
+
)
|
| 393 |
+
resized_images_grouped = {}
|
| 394 |
+
for shape, stacked_images in grouped_images.items():
|
| 395 |
+
if do_resize:
|
| 396 |
+
stacked_images = self.resize(stacked_images, size, interpolation=interpolation)
|
| 397 |
+
resized_images_grouped[shape] = stacked_images
|
| 398 |
+
resized_images = reorder_images(resized_images_grouped, grouped_images_index, is_nested=True)
|
| 399 |
+
|
| 400 |
+
grouped_images, grouped_images_index = group_images_by_shape(
|
| 401 |
+
resized_images, is_nested=True, disable_grouping=disable_grouping
|
| 402 |
+
)
|
| 403 |
+
split_images_grouped = {}
|
| 404 |
+
if do_image_splitting:
|
| 405 |
+
rows_grouped = {}
|
| 406 |
+
cols_grouped = {}
|
| 407 |
+
for shape, stacked_images in grouped_images.items():
|
| 408 |
+
stacked_images = self.resize_for_vision_encoder(
|
| 409 |
+
stacked_images, max_image_size["longest_edge"], interpolation=interpolation
|
| 410 |
+
)
|
| 411 |
+
stacked_images, rows, cols = self.split_images(
|
| 412 |
+
stacked_images, max_image_size=max_image_size, interpolation=interpolation
|
| 413 |
+
)
|
| 414 |
+
split_images_grouped[shape] = stacked_images
|
| 415 |
+
rows_grouped[shape] = rows
|
| 416 |
+
cols_grouped[shape] = cols
|
| 417 |
+
processed_images = reorder_images(split_images_grouped, grouped_images_index, is_nested=True)
|
| 418 |
+
rows = reorder_images(rows_grouped, grouped_images_index, is_nested=True)
|
| 419 |
+
cols = reorder_images(cols_grouped, grouped_images_index, is_nested=True)
|
| 420 |
+
# flattenened the doubly nested list to a nested list
|
| 421 |
+
for i, group_images in enumerate(processed_images):
|
| 422 |
+
processed_images[i] = [image for sublist in group_images for image in sublist]
|
| 423 |
+
else:
|
| 424 |
+
for shape, stacked_images in grouped_images.items():
|
| 425 |
+
# We square the images to max_image_size
|
| 426 |
+
stacked_images = self.resize(
|
| 427 |
+
image=stacked_images,
|
| 428 |
+
size=SizeDict(height=max_image_size["longest_edge"], width=max_image_size["longest_edge"]),
|
| 429 |
+
interpolation=interpolation,
|
| 430 |
+
)
|
| 431 |
+
split_images_grouped[shape] = stacked_images
|
| 432 |
+
processed_images = reorder_images(split_images_grouped, grouped_images_index, is_nested=True)
|
| 433 |
+
rows = [[0] * len(images) for images in processed_images]
|
| 434 |
+
cols = [[0] * len(images) for images in processed_images]
|
| 435 |
+
# Group images by size for further processing
|
| 436 |
+
# Needed in case do_resize is False, or resize returns images with different sizes
|
| 437 |
+
grouped_images, grouped_images_index = group_images_by_shape(
|
| 438 |
+
processed_images, is_nested=True, disable_grouping=disable_grouping
|
| 439 |
+
)
|
| 440 |
+
processed_images_grouped = {}
|
| 441 |
+
for shape, stacked_images in grouped_images.items():
|
| 442 |
+
# Fused rescale and normalize
|
| 443 |
+
stacked_images = self.rescale_and_normalize(
|
| 444 |
+
stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
|
| 445 |
+
)
|
| 446 |
+
processed_images_grouped[shape] = stacked_images
|
| 447 |
+
processed_images = reorder_images(processed_images_grouped, grouped_images_index, is_nested=True)
|
| 448 |
+
if do_pad:
|
| 449 |
+
# Get max images per batch
|
| 450 |
+
max_num_images = max(len(images_) for images_ in processed_images)
|
| 451 |
+
max_height, max_width = get_max_height_width(processed_images)
|
| 452 |
+
|
| 453 |
+
processed_images_padded = torch.zeros(
|
| 454 |
+
len(processed_images),
|
| 455 |
+
max_num_images,
|
| 456 |
+
*(processed_images[0][0].shape[0], max_height, max_width),
|
| 457 |
+
device=processed_images[0][0].device,
|
| 458 |
+
)
|
| 459 |
+
pixel_attention_masks = torch.zeros(
|
| 460 |
+
len(processed_images),
|
| 461 |
+
max_num_images,
|
| 462 |
+
*(max_height, max_width),
|
| 463 |
+
device=processed_images[0][0].device,
|
| 464 |
+
)
|
| 465 |
+
for i, images in enumerate(processed_images):
|
| 466 |
+
for j, image in enumerate(images):
|
| 467 |
+
processed_images_padded[i, j], pixel_attention_masks[i, j] = self.pad(
|
| 468 |
+
image, (max_height, max_width)
|
| 469 |
+
)
|
| 470 |
+
processed_images = processed_images_padded
|
| 471 |
+
|
| 472 |
+
if do_pad:
|
| 473 |
+
data = {"pixel_values": processed_images, "pixel_attention_mask": pixel_attention_masks}
|
| 474 |
+
elif return_tensors == "pt":
|
| 475 |
+
data = {"pixel_values": torch.stack([torch.stack(images) for images in processed_images])}
|
| 476 |
+
else:
|
| 477 |
+
data = {"pixel_values": processed_images}
|
| 478 |
+
# This is needed for generating correct text inputs in the processor - we don't pad to the max number of images
|
| 479 |
+
encoding = BatchFeature(data=data, tensor_type=return_tensors)
|
| 480 |
+
|
| 481 |
+
if return_row_col_info:
|
| 482 |
+
encoding["rows"] = rows
|
| 483 |
+
encoding["cols"] = cols
|
| 484 |
+
|
| 485 |
+
return encoding
|
| 486 |
+
|
| 487 |
+
def to_dict(self):
|
| 488 |
+
encoder_dict = super().to_dict()
|
| 489 |
+
encoder_dict.pop("_valid_processor_keys", None)
|
| 490 |
+
encoder_dict.pop("return_row_col_info", None)
|
| 491 |
+
return encoder_dict
|
| 492 |
+
|
| 493 |
+
def get_number_of_image_patches(self, height: int, width: int, images_kwargs=None):
|
| 494 |
+
"""
|
| 495 |
+
A utility that returns number of image patches for a given image size.
|
| 496 |
+
|
| 497 |
+
Args:
|
| 498 |
+
height (`int`):
|
| 499 |
+
Height of the input image.
|
| 500 |
+
width (`int`):
|
| 501 |
+
Width of the input image.
|
| 502 |
+
images_kwargs (`dict`, *optional*)
|
| 503 |
+
Any kwargs to override defaults of the image processor.
|
| 504 |
+
Returns:
|
| 505 |
+
`int`: Number of patches per image.
|
| 506 |
+
"""
|
| 507 |
+
do_image_splitting = images_kwargs.get("do_image_splitting", self.do_image_splitting)
|
| 508 |
+
max_image_size = images_kwargs.get("max_image_size", self.max_image_size)
|
| 509 |
+
size = images_kwargs.get("size", self.size)
|
| 510 |
+
|
| 511 |
+
num_patches = num_rows = num_cols = 1
|
| 512 |
+
if do_image_splitting:
|
| 513 |
+
height, width = _resize_output_size_rescale_to_max_len(height, width, max_len=size["longest_edge"])
|
| 514 |
+
height, width = _resize_output_size_scale_below_upper_bound(height, width, max_len=MAX_IMAGE_SIZE)
|
| 515 |
+
aspect_ratio = width / height
|
| 516 |
+
|
| 517 |
+
if width >= height:
|
| 518 |
+
resized_width = math.ceil(width / max_image_size["longest_edge"]) * max_image_size["longest_edge"]
|
| 519 |
+
resized_height = int(width / aspect_ratio)
|
| 520 |
+
resized_height = math.ceil(height / max_image_size["longest_edge"]) * max_image_size["longest_edge"]
|
| 521 |
+
elif height > width:
|
| 522 |
+
resized_height = math.ceil(height / max_image_size["longest_edge"]) * max_image_size["longest_edge"]
|
| 523 |
+
resized_width = int(height * aspect_ratio)
|
| 524 |
+
resized_width = math.ceil(width / max_image_size["longest_edge"]) * max_image_size["longest_edge"]
|
| 525 |
+
|
| 526 |
+
max_height = max_width = max_image_size["longest_edge"]
|
| 527 |
+
if resized_height > max_height or resized_width > max_width:
|
| 528 |
+
# Calculate the number of splits
|
| 529 |
+
num_rows = math.ceil(resized_height / max_height)
|
| 530 |
+
num_cols = math.ceil(resized_width / max_width)
|
| 531 |
+
num_patches = num_rows * num_cols + 1
|
| 532 |
+
|
| 533 |
+
return num_patches, num_rows, num_cols
|
| 534 |
+
|
| 535 |
+
|
| 536 |
+
__all__ = ["SmolVLMImageProcessorFast"]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/smolvlm/modeling_smolvlm.py
ADDED
|
@@ -0,0 +1,1028 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/smolvlm/modular_smolvlm.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_smolvlm.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# coding=utf-8
|
| 8 |
+
# Copyright 2025 the HuggingFace Inc. team. All rights reserved.
|
| 9 |
+
# Written by Orr Zohar
|
| 10 |
+
#
|
| 11 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 12 |
+
# you may not use this file except in compliance with the License.
|
| 13 |
+
# You may obtain a copy of the License at
|
| 14 |
+
#
|
| 15 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 16 |
+
#
|
| 17 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 18 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 19 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 20 |
+
# See the License for the specific language governing permissions and
|
| 21 |
+
# limitations under the License.
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
from typing import Callable, Optional, Union
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
from torch import nn
|
| 27 |
+
|
| 28 |
+
from ...activations import ACT2FN
|
| 29 |
+
from ...cache_utils import Cache, DynamicCache
|
| 30 |
+
from ...generation import GenerationConfig, GenerationMixin
|
| 31 |
+
from ...modeling_attn_mask_utils import _prepare_4d_attention_mask
|
| 32 |
+
from ...modeling_flash_attention_utils import FlashAttentionKwargs
|
| 33 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 34 |
+
from ...modeling_outputs import BaseModelOutput, ModelOutput
|
| 35 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 36 |
+
from ...processing_utils import Unpack
|
| 37 |
+
from ...utils import (
|
| 38 |
+
TransformersKwargs,
|
| 39 |
+
auto_docstring,
|
| 40 |
+
can_return_tuple,
|
| 41 |
+
logging,
|
| 42 |
+
)
|
| 43 |
+
from ..auto import AutoModel
|
| 44 |
+
from .configuration_smolvlm import SmolVLMConfig, SmolVLMVisionConfig
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
logger = logging.get_logger(__name__)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class SmolVLMRMSNorm(nn.Module):
|
| 51 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 52 |
+
"""
|
| 53 |
+
SmolVLMRMSNorm is equivalent to T5LayerNorm
|
| 54 |
+
"""
|
| 55 |
+
super().__init__()
|
| 56 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 57 |
+
self.variance_epsilon = eps
|
| 58 |
+
|
| 59 |
+
def forward(self, hidden_states):
|
| 60 |
+
input_dtype = hidden_states.dtype
|
| 61 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 62 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 63 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 64 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 65 |
+
|
| 66 |
+
def extra_repr(self):
|
| 67 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@auto_docstring
|
| 71 |
+
class SmolVLMPreTrainedModel(PreTrainedModel):
|
| 72 |
+
config: SmolVLMConfig
|
| 73 |
+
base_model_prefix = "model"
|
| 74 |
+
supports_gradient_checkpointing = True
|
| 75 |
+
_no_split_modules = ["SmolVLMVisionAttention", "SmolVLMDecoderLayer"]
|
| 76 |
+
_skip_keys_device_placement = "past_key_values"
|
| 77 |
+
_supports_flash_attn = True
|
| 78 |
+
_supports_sdpa = True
|
| 79 |
+
_supports_flex_attn = True
|
| 80 |
+
|
| 81 |
+
_supports_attention_backend = True
|
| 82 |
+
|
| 83 |
+
def _init_weights(self, module):
|
| 84 |
+
std = getattr(self.config, "initializer_range", self.config.get_text_config().initializer_range)
|
| 85 |
+
|
| 86 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 87 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 88 |
+
if module.bias is not None:
|
| 89 |
+
module.bias.data.zero_()
|
| 90 |
+
elif isinstance(module, nn.Embedding):
|
| 91 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 92 |
+
if module.padding_idx is not None:
|
| 93 |
+
module.weight.data[module.padding_idx].zero_()
|
| 94 |
+
elif isinstance(module, nn.LayerNorm):
|
| 95 |
+
module.weight.data.fill_(1.0)
|
| 96 |
+
module.bias.data.zero_()
|
| 97 |
+
elif isinstance(module, SmolVLMRMSNorm):
|
| 98 |
+
module.weight.data.fill_(1.0)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class SmolVLMVisionEmbeddings(nn.Module):
|
| 102 |
+
"""
|
| 103 |
+
This is a modified version of `siglip.modelign_siglip.SiglipVisionEmbeddings` to enable images of variable
|
| 104 |
+
resolution.
|
| 105 |
+
|
| 106 |
+
The modifications are adapted from [Patch n' Pack: NaViT, a Vision Transformer for any Aspect Ratio and Resolution](https://huggingface.co/papers/2307.06304)
|
| 107 |
+
which allows treating images in their native aspect ratio and without the need to resize them to the same
|
| 108 |
+
fixed size. In particular, we start from the original pre-trained SigLIP model
|
| 109 |
+
(which uses images of fixed-size square images) and adapt it by training on images of variable resolutions.
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
def __init__(self, config: SmolVLMVisionConfig):
|
| 113 |
+
super().__init__()
|
| 114 |
+
self.embed_dim = config.hidden_size
|
| 115 |
+
self.image_size = config.image_size
|
| 116 |
+
self.patch_size = config.patch_size
|
| 117 |
+
|
| 118 |
+
self.patch_embedding = nn.Conv2d(
|
| 119 |
+
in_channels=config.num_channels,
|
| 120 |
+
out_channels=self.embed_dim,
|
| 121 |
+
kernel_size=self.patch_size,
|
| 122 |
+
stride=self.patch_size,
|
| 123 |
+
padding="valid",
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
self.num_patches_per_side = self.image_size // self.patch_size
|
| 127 |
+
self.num_patches = self.num_patches_per_side**2
|
| 128 |
+
self.num_positions = self.num_patches
|
| 129 |
+
self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
|
| 130 |
+
|
| 131 |
+
def forward(self, pixel_values: torch.FloatTensor, patch_attention_mask: torch.BoolTensor) -> torch.Tensor:
|
| 132 |
+
batch_size, _, max_im_h, max_im_w = pixel_values.shape
|
| 133 |
+
|
| 134 |
+
patch_embeds = self.patch_embedding(pixel_values)
|
| 135 |
+
embeddings = patch_embeds.flatten(2).transpose(1, 2)
|
| 136 |
+
|
| 137 |
+
max_nb_patches_h, max_nb_patches_w = max_im_h // self.patch_size, max_im_w // self.patch_size
|
| 138 |
+
boundaries = torch.arange(
|
| 139 |
+
1 / self.num_patches_per_side, 1.0, 1 / self.num_patches_per_side, device=pixel_values.device
|
| 140 |
+
)
|
| 141 |
+
position_ids = torch.full(
|
| 142 |
+
size=(batch_size, max_nb_patches_h * max_nb_patches_w), fill_value=0, device=pixel_values.device
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
for batch_idx, p_attn_mask in enumerate(patch_attention_mask):
|
| 146 |
+
nb_patches_h = p_attn_mask[:, 0].sum()
|
| 147 |
+
nb_patches_w = p_attn_mask[0].sum()
|
| 148 |
+
|
| 149 |
+
h_indices = torch.arange(nb_patches_h, device=position_ids.device, dtype=pixel_values.dtype)
|
| 150 |
+
w_indices = torch.arange(nb_patches_w, device=position_ids.device, dtype=pixel_values.dtype)
|
| 151 |
+
|
| 152 |
+
fractional_coords_h = h_indices / nb_patches_h * (1 - 1e-6)
|
| 153 |
+
fractional_coords_w = w_indices / nb_patches_w * (1 - 1e-6)
|
| 154 |
+
|
| 155 |
+
bucket_coords_h = torch.bucketize(fractional_coords_h, boundaries, right=True)
|
| 156 |
+
bucket_coords_w = torch.bucketize(fractional_coords_w, boundaries, right=True)
|
| 157 |
+
|
| 158 |
+
pos_ids = (bucket_coords_h[:, None] * self.num_patches_per_side + bucket_coords_w).flatten()
|
| 159 |
+
position_ids[batch_idx][p_attn_mask.view(-1)] = pos_ids
|
| 160 |
+
|
| 161 |
+
embeddings = embeddings + self.position_embedding(position_ids)
|
| 162 |
+
return embeddings
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def eager_attention_forward(
|
| 166 |
+
module: nn.Module,
|
| 167 |
+
query: torch.Tensor,
|
| 168 |
+
key: torch.Tensor,
|
| 169 |
+
value: torch.Tensor,
|
| 170 |
+
attention_mask: Optional[torch.Tensor],
|
| 171 |
+
scaling: float,
|
| 172 |
+
dropout: float = 0.0,
|
| 173 |
+
**kwargs,
|
| 174 |
+
):
|
| 175 |
+
attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling
|
| 176 |
+
if attention_mask is not None:
|
| 177 |
+
attn_weights = attn_weights + attention_mask
|
| 178 |
+
|
| 179 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 180 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 181 |
+
|
| 182 |
+
attn_output = torch.matmul(attn_weights, value)
|
| 183 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 184 |
+
|
| 185 |
+
return attn_output, attn_weights
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
class SmolVLMVisionAttention(nn.Module):
|
| 189 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 190 |
+
|
| 191 |
+
def __init__(self, config):
|
| 192 |
+
super().__init__()
|
| 193 |
+
self.config = config
|
| 194 |
+
self.embed_dim = config.hidden_size
|
| 195 |
+
self.num_heads = config.num_attention_heads
|
| 196 |
+
self.head_dim = self.embed_dim // self.num_heads
|
| 197 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
| 198 |
+
raise ValueError(
|
| 199 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
|
| 200 |
+
f" {self.num_heads})."
|
| 201 |
+
)
|
| 202 |
+
self.scale = self.head_dim**-0.5
|
| 203 |
+
self.dropout = config.attention_dropout
|
| 204 |
+
|
| 205 |
+
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 206 |
+
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 207 |
+
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 208 |
+
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 209 |
+
|
| 210 |
+
# Ignore copy
|
| 211 |
+
self.is_causal = False
|
| 212 |
+
|
| 213 |
+
def forward(
|
| 214 |
+
self,
|
| 215 |
+
hidden_states: torch.Tensor,
|
| 216 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 217 |
+
**kwargs,
|
| 218 |
+
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 219 |
+
"""Input shape: Batch x Time x Channel"""
|
| 220 |
+
|
| 221 |
+
batch_size, seq_length, embed_dim = hidden_states.shape
|
| 222 |
+
|
| 223 |
+
queries = self.q_proj(hidden_states)
|
| 224 |
+
keys = self.k_proj(hidden_states)
|
| 225 |
+
values = self.v_proj(hidden_states)
|
| 226 |
+
|
| 227 |
+
queries = queries.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
|
| 228 |
+
keys = keys.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
|
| 229 |
+
values = values.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
|
| 230 |
+
|
| 231 |
+
attention_interface: Callable = eager_attention_forward
|
| 232 |
+
if self.config._attn_implementation != "eager":
|
| 233 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 234 |
+
|
| 235 |
+
attn_output, attn_weights = attention_interface(
|
| 236 |
+
self,
|
| 237 |
+
queries,
|
| 238 |
+
keys,
|
| 239 |
+
values,
|
| 240 |
+
attention_mask,
|
| 241 |
+
is_causal=self.is_causal,
|
| 242 |
+
scaling=self.scale,
|
| 243 |
+
dropout=0.0 if not self.training else self.dropout,
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
attn_output = attn_output.reshape(batch_size, seq_length, embed_dim).contiguous()
|
| 247 |
+
attn_output = self.out_proj(attn_output)
|
| 248 |
+
|
| 249 |
+
return attn_output, attn_weights
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
class SmolVLMVisionMLP(nn.Module):
|
| 253 |
+
def __init__(self, config):
|
| 254 |
+
super().__init__()
|
| 255 |
+
self.config = config
|
| 256 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
| 257 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 258 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 259 |
+
|
| 260 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 261 |
+
hidden_states = self.fc1(hidden_states)
|
| 262 |
+
hidden_states = self.activation_fn(hidden_states)
|
| 263 |
+
hidden_states = self.fc2(hidden_states)
|
| 264 |
+
return hidden_states
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
class SmolVLMEncoderLayer(GradientCheckpointingLayer):
|
| 268 |
+
def __init__(self, config: SmolVLMVisionConfig):
|
| 269 |
+
super().__init__()
|
| 270 |
+
self.embed_dim = config.hidden_size
|
| 271 |
+
self.self_attn = SmolVLMVisionAttention(config)
|
| 272 |
+
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 273 |
+
self.mlp = SmolVLMVisionMLP(config)
|
| 274 |
+
self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 275 |
+
|
| 276 |
+
def forward(
|
| 277 |
+
self,
|
| 278 |
+
hidden_states: torch.Tensor,
|
| 279 |
+
attention_mask: torch.Tensor,
|
| 280 |
+
output_attentions: Optional[bool] = False,
|
| 281 |
+
) -> tuple[torch.FloatTensor]:
|
| 282 |
+
"""
|
| 283 |
+
Args:
|
| 284 |
+
hidden_states (`torch.FloatTensor`):
|
| 285 |
+
Input to the layer of shape `(batch, seq_len, embed_dim)`.
|
| 286 |
+
attention_mask (`torch.FloatTensor`):
|
| 287 |
+
Attention mask of shape `(batch, 1, q_len, k_v_seq_len)` where padding elements are indicated by very large negative values.
|
| 288 |
+
output_attentions (`bool`, *optional*, defaults to `False`):
|
| 289 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 290 |
+
returned tensors for more detail.
|
| 291 |
+
"""
|
| 292 |
+
residual = hidden_states
|
| 293 |
+
|
| 294 |
+
hidden_states = self.layer_norm1(hidden_states)
|
| 295 |
+
hidden_states, attn_weights = self.self_attn(
|
| 296 |
+
hidden_states=hidden_states,
|
| 297 |
+
attention_mask=attention_mask,
|
| 298 |
+
output_attentions=output_attentions,
|
| 299 |
+
)
|
| 300 |
+
hidden_states = residual + hidden_states
|
| 301 |
+
|
| 302 |
+
residual = hidden_states
|
| 303 |
+
hidden_states = self.layer_norm2(hidden_states)
|
| 304 |
+
hidden_states = self.mlp(hidden_states)
|
| 305 |
+
hidden_states = residual + hidden_states
|
| 306 |
+
|
| 307 |
+
outputs = (hidden_states,)
|
| 308 |
+
|
| 309 |
+
if output_attentions:
|
| 310 |
+
outputs += (attn_weights,)
|
| 311 |
+
|
| 312 |
+
return outputs
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
class SmolVLMEncoder(nn.Module):
|
| 316 |
+
"""
|
| 317 |
+
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
|
| 318 |
+
[`SmolVLMEncoderLayer`].
|
| 319 |
+
|
| 320 |
+
Args:
|
| 321 |
+
config: SmolVLMConfig
|
| 322 |
+
"""
|
| 323 |
+
|
| 324 |
+
def __init__(self, config: SmolVLMConfig):
|
| 325 |
+
super().__init__()
|
| 326 |
+
self.config = config
|
| 327 |
+
self.layers = nn.ModuleList([SmolVLMEncoderLayer(config) for _ in range(config.num_hidden_layers)])
|
| 328 |
+
self.gradient_checkpointing = False
|
| 329 |
+
|
| 330 |
+
# Ignore copy
|
| 331 |
+
def forward(
|
| 332 |
+
self,
|
| 333 |
+
inputs_embeds,
|
| 334 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 335 |
+
output_attentions: Optional[bool] = None,
|
| 336 |
+
output_hidden_states: Optional[bool] = None,
|
| 337 |
+
return_dict: Optional[bool] = None,
|
| 338 |
+
) -> Union[tuple, BaseModelOutput]:
|
| 339 |
+
r"""
|
| 340 |
+
Args:
|
| 341 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 342 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 343 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 344 |
+
than the model's internal embedding lookup matrix.
|
| 345 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 346 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 347 |
+
|
| 348 |
+
- 1 for tokens that are **not masked**,
|
| 349 |
+
- 0 for tokens that are **masked**.
|
| 350 |
+
|
| 351 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 352 |
+
output_attentions (`bool`, *optional*):
|
| 353 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 354 |
+
returned tensors for more detail.
|
| 355 |
+
output_hidden_states (`bool`, *optional*):
|
| 356 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 357 |
+
for more detail.
|
| 358 |
+
return_dict (`bool`, *optional*):
|
| 359 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 360 |
+
"""
|
| 361 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 362 |
+
output_hidden_states = (
|
| 363 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 364 |
+
)
|
| 365 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 366 |
+
|
| 367 |
+
encoder_states = () if output_hidden_states else None
|
| 368 |
+
all_attentions = () if output_attentions else None
|
| 369 |
+
|
| 370 |
+
hidden_states = inputs_embeds
|
| 371 |
+
for encoder_layer in self.layers:
|
| 372 |
+
if output_hidden_states:
|
| 373 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 374 |
+
layer_outputs = encoder_layer(
|
| 375 |
+
hidden_states,
|
| 376 |
+
attention_mask,
|
| 377 |
+
output_attentions=output_attentions,
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
hidden_states = layer_outputs[0]
|
| 381 |
+
|
| 382 |
+
if output_attentions:
|
| 383 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 384 |
+
|
| 385 |
+
if output_hidden_states:
|
| 386 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 387 |
+
|
| 388 |
+
if not return_dict:
|
| 389 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
| 390 |
+
return BaseModelOutput(
|
| 391 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
@auto_docstring(
|
| 396 |
+
custom_intro="""
|
| 397 |
+
The SmolVLM Vision Transformer Model outputting raw image embedding.
|
| 398 |
+
"""
|
| 399 |
+
)
|
| 400 |
+
class SmolVLMVisionTransformer(SmolVLMPreTrainedModel):
|
| 401 |
+
config: SmolVLMVisionConfig
|
| 402 |
+
_supports_sdpa = True
|
| 403 |
+
_supports_flash_attn = True
|
| 404 |
+
_supports_flex_attn = True
|
| 405 |
+
|
| 406 |
+
def __init__(self, config: SmolVLMVisionConfig):
|
| 407 |
+
super().__init__(config)
|
| 408 |
+
embed_dim = config.hidden_size
|
| 409 |
+
|
| 410 |
+
self.embeddings = SmolVLMVisionEmbeddings(config)
|
| 411 |
+
self.encoder = SmolVLMEncoder(config)
|
| 412 |
+
self.patch_size = config.patch_size
|
| 413 |
+
self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
| 414 |
+
self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
|
| 415 |
+
|
| 416 |
+
def get_input_embeddings(self):
|
| 417 |
+
return self.embeddings
|
| 418 |
+
|
| 419 |
+
def set_input_embeddings(self, value):
|
| 420 |
+
self.embeddings = value
|
| 421 |
+
|
| 422 |
+
def forward(
|
| 423 |
+
self,
|
| 424 |
+
pixel_values,
|
| 425 |
+
patch_attention_mask: Optional[torch.BoolTensor] = None,
|
| 426 |
+
output_attentions: Optional[bool] = None,
|
| 427 |
+
output_hidden_states: Optional[bool] = None,
|
| 428 |
+
return_dict: Optional[bool] = None,
|
| 429 |
+
) -> Union[tuple, BaseModelOutput]:
|
| 430 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 431 |
+
output_hidden_states = (
|
| 432 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 433 |
+
)
|
| 434 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 435 |
+
|
| 436 |
+
batch_size = pixel_values.size(0)
|
| 437 |
+
if patch_attention_mask is None:
|
| 438 |
+
patch_size = self.patch_size
|
| 439 |
+
patch_attention_mask = torch.ones(
|
| 440 |
+
(
|
| 441 |
+
batch_size,
|
| 442 |
+
pixel_values.size(2) // patch_size,
|
| 443 |
+
pixel_values.size(3) // patch_size,
|
| 444 |
+
)
|
| 445 |
+
)
|
| 446 |
+
patch_attention_mask = patch_attention_mask.to(dtype=torch.bool, device=pixel_values.device)
|
| 447 |
+
|
| 448 |
+
hidden_states = self.embeddings(pixel_values=pixel_values, patch_attention_mask=patch_attention_mask)
|
| 449 |
+
|
| 450 |
+
patch_attention_mask = patch_attention_mask.view(batch_size, -1)
|
| 451 |
+
# The call to `_upad_input` in `_flash_attention_forward` is expensive
|
| 452 |
+
# So when the `patch_attention_mask` is full of 1s (i.e. attending to the whole sequence),
|
| 453 |
+
# avoiding passing the attention_mask, which is equivalent to attending to the full sequence
|
| 454 |
+
if not self._use_flash_attention_2:
|
| 455 |
+
patch_attention_mask = _prepare_4d_attention_mask(patch_attention_mask, hidden_states.dtype)
|
| 456 |
+
elif not torch.any(~patch_attention_mask):
|
| 457 |
+
patch_attention_mask = None
|
| 458 |
+
|
| 459 |
+
encoder_outputs = self.encoder(
|
| 460 |
+
inputs_embeds=hidden_states,
|
| 461 |
+
attention_mask=patch_attention_mask,
|
| 462 |
+
output_attentions=output_attentions,
|
| 463 |
+
output_hidden_states=output_hidden_states,
|
| 464 |
+
return_dict=return_dict,
|
| 465 |
+
)
|
| 466 |
+
|
| 467 |
+
last_hidden_state = encoder_outputs[0]
|
| 468 |
+
last_hidden_state = self.post_layernorm(last_hidden_state)
|
| 469 |
+
|
| 470 |
+
if not return_dict:
|
| 471 |
+
return (last_hidden_state,) + encoder_outputs[1:]
|
| 472 |
+
|
| 473 |
+
return BaseModelOutput(
|
| 474 |
+
last_hidden_state=last_hidden_state,
|
| 475 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 476 |
+
attentions=encoder_outputs.attentions,
|
| 477 |
+
)
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
@dataclass
|
| 481 |
+
@auto_docstring(
|
| 482 |
+
custom_intro="""
|
| 483 |
+
Base class for SmolVLM model's outputs that may also contain a past key/values (to speed up sequential decoding).
|
| 484 |
+
"""
|
| 485 |
+
)
|
| 486 |
+
class SmolVLMBaseModelOutputWithPast(ModelOutput):
|
| 487 |
+
r"""
|
| 488 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 489 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 490 |
+
If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1,
|
| 491 |
+
hidden_size)` is output.
|
| 492 |
+
past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 493 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
|
| 494 |
+
`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and optionally if
|
| 495 |
+
`config.is_encoder_decoder=True` 2 additional tensors of shape `(batch_size, num_heads,
|
| 496 |
+
encoder_sequence_length, embed_size_per_head)`.
|
| 497 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
|
| 498 |
+
`config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values`
|
| 499 |
+
input) to speed up sequential decoding.
|
| 500 |
+
image_hidden_states (`tuple(torch.FloatTensor)`, *optional*):
|
| 501 |
+
Tuple of `torch.FloatTensor` (one for the output of the image embeddings, `(batch_size, num_images,
|
| 502 |
+
sequence_length, hidden_size)`.
|
| 503 |
+
image_hidden_states of the model produced by the vision encoder
|
| 504 |
+
"""
|
| 505 |
+
|
| 506 |
+
last_hidden_state: Optional[torch.FloatTensor] = None
|
| 507 |
+
past_key_values: Optional[tuple[tuple[torch.FloatTensor]]] = None
|
| 508 |
+
hidden_states: Optional[tuple[torch.FloatTensor]] = None
|
| 509 |
+
attentions: Optional[tuple[torch.FloatTensor]] = None
|
| 510 |
+
image_hidden_states: Optional[tuple[torch.FloatTensor]] = None
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
class SmolVLMSimpleMLP(nn.Module):
|
| 514 |
+
def __init__(self, config):
|
| 515 |
+
super().__init__()
|
| 516 |
+
input_size = config.vision_config.hidden_size * (config.scale_factor**2)
|
| 517 |
+
output_size = config.text_config.hidden_size
|
| 518 |
+
self.proj = nn.Linear(input_size, output_size, bias=False)
|
| 519 |
+
|
| 520 |
+
def forward(self, x):
|
| 521 |
+
return self.proj(x)
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
class SmolVLMConnector(nn.Module):
|
| 525 |
+
def __init__(self, config):
|
| 526 |
+
super().__init__()
|
| 527 |
+
self.scale_factor = config.scale_factor
|
| 528 |
+
self.modality_projection = SmolVLMSimpleMLP(config)
|
| 529 |
+
|
| 530 |
+
def pixel_shuffle(self, x, scale_factor=2):
|
| 531 |
+
bsz, seq, embed_dim = x.size()
|
| 532 |
+
height = width = int(seq**0.5)
|
| 533 |
+
x = x.view(bsz, height, width, embed_dim)
|
| 534 |
+
x = x.view(bsz, height, int(width / scale_factor), embed_dim * scale_factor)
|
| 535 |
+
x = x.permute(0, 2, 1, 3)
|
| 536 |
+
x = x.reshape(bsz, int(width / scale_factor), int(height / scale_factor), embed_dim * (scale_factor**2))
|
| 537 |
+
x = x.permute(0, 2, 1, 3)
|
| 538 |
+
x = x.reshape(bsz, int(seq / (scale_factor**2)), embed_dim * (scale_factor**2))
|
| 539 |
+
return x
|
| 540 |
+
|
| 541 |
+
def forward(self, image_hidden_states):
|
| 542 |
+
image_hidden_states = self.pixel_shuffle(image_hidden_states, self.scale_factor)
|
| 543 |
+
image_hidden_states = self.modality_projection(image_hidden_states)
|
| 544 |
+
return image_hidden_states
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
@auto_docstring(
|
| 548 |
+
custom_intro="""
|
| 549 |
+
SmolVLM model consisting of a SIGLIP vision encoder and Llama3 language decoder
|
| 550 |
+
"""
|
| 551 |
+
)
|
| 552 |
+
class SmolVLMModel(SmolVLMPreTrainedModel):
|
| 553 |
+
"""
|
| 554 |
+
A subclass of Idefics3Model. We do *not* remove or block the call to inputs_merger
|
| 555 |
+
in forward. Instead, we override inputs_merger here with custom logic.
|
| 556 |
+
"""
|
| 557 |
+
|
| 558 |
+
def __init__(self, config: SmolVLMConfig):
|
| 559 |
+
super().__init__(config)
|
| 560 |
+
self.padding_idx = self.config.text_config.pad_token_id
|
| 561 |
+
self.vocab_size = self.config.text_config.vocab_size
|
| 562 |
+
|
| 563 |
+
self.vision_model = SmolVLMVisionTransformer._from_config(config.vision_config)
|
| 564 |
+
self.connector = SmolVLMConnector(config)
|
| 565 |
+
self.text_model = AutoModel.from_config(config.text_config)
|
| 566 |
+
|
| 567 |
+
self.image_seq_len = int(
|
| 568 |
+
((config.vision_config.image_size // config.vision_config.patch_size) ** 2) / (config.scale_factor**2)
|
| 569 |
+
)
|
| 570 |
+
self.image_token_id = self.config.image_token_id
|
| 571 |
+
|
| 572 |
+
self._use_flash_attention_2 = config.text_config._attn_implementation == "flash_attention_2"
|
| 573 |
+
|
| 574 |
+
self.post_init()
|
| 575 |
+
|
| 576 |
+
def enable_input_require_grads(self):
|
| 577 |
+
"""
|
| 578 |
+
Enables the gradients for the input embeddings.
|
| 579 |
+
|
| 580 |
+
This is useful for lora when using gradient checkpointing.
|
| 581 |
+
c.f. https://github.com/huggingface/peft/issues/1402#issuecomment-1913675032
|
| 582 |
+
|
| 583 |
+
Override to set output.requires_grad = True for both the decoder's and vision model's embeddings.
|
| 584 |
+
"""
|
| 585 |
+
|
| 586 |
+
def get_lowest_module(module):
|
| 587 |
+
if len(list(module.children())) == 0:
|
| 588 |
+
# If the module has no children, it is a leaf module (e.g., Linear, Conv2d, etc.)
|
| 589 |
+
return module
|
| 590 |
+
else:
|
| 591 |
+
# Recursively call the function on each child module
|
| 592 |
+
return get_lowest_module(list(module.children())[0])
|
| 593 |
+
|
| 594 |
+
def make_inputs_require_grads(module, input, output):
|
| 595 |
+
output.requires_grad_(True)
|
| 596 |
+
|
| 597 |
+
self._text_require_grads_hook = self.get_input_embeddings().register_forward_hook(make_inputs_require_grads)
|
| 598 |
+
self._vision_require_grads_hook = get_lowest_module(self.vision_model).register_forward_hook(
|
| 599 |
+
make_inputs_require_grads
|
| 600 |
+
)
|
| 601 |
+
|
| 602 |
+
def disable_input_require_grads(self):
|
| 603 |
+
self._text_require_grads_hook.remove()
|
| 604 |
+
self._vision_require_grads_hook.remove()
|
| 605 |
+
|
| 606 |
+
def get_input_embeddings(self):
|
| 607 |
+
return self.text_model.get_input_embeddings()
|
| 608 |
+
|
| 609 |
+
def set_input_embeddings(self, value):
|
| 610 |
+
self.text_model.set_input_embeddings(value)
|
| 611 |
+
|
| 612 |
+
def inputs_merger(
|
| 613 |
+
self, input_ids: torch.LongTensor, inputs_embeds: torch.Tensor, image_hidden_states: torch.Tensor
|
| 614 |
+
):
|
| 615 |
+
"""
|
| 616 |
+
This method aims at merging the token embeddings with the image hidden states into one single sequence of vectors that are fed to the transformer LM.
|
| 617 |
+
The merging happens as follows:
|
| 618 |
+
- The text token sequence is: `tok_1 tok_2 tok_3 <fake_token_around_image> <image> <image> ... <image> <fake_token_around_image> tok_4`.
|
| 619 |
+
- We get the image hidden states for the image through the vision encoder and that hidden state, after a pixel shuffle operation, is then projected into the text embedding space.
|
| 620 |
+
We thus have a sequence of image hidden states of size (1, image_seq_len, hidden_dim), where 1 is for batch_size of 1 image and hidden_dim is the hidden_dim of the LM transformer.
|
| 621 |
+
- The merging happens so that we obtain the following sequence: `vector_tok_1 vector_tok_2 vector_tok_3 vector_fake_tok_around_image {sequence of image_seq_len image hidden states} vector_fake_toke_around_image vector_tok_4`. That sequence is fed to the LM.
|
| 622 |
+
- To fit the format of that sequence, `input_ids`, `input_embeds`, `attention_mask` are all 3 adapted to insert the image hidden states.
|
| 623 |
+
"""
|
| 624 |
+
_, patch_size, _ = image_hidden_states.shape
|
| 625 |
+
|
| 626 |
+
if input_ids is None:
|
| 627 |
+
image_mask = inputs_embeds == self.get_input_embeddings()(
|
| 628 |
+
torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
|
| 629 |
+
)
|
| 630 |
+
image_mask = image_mask[..., 0] # slice off the hidden dim
|
| 631 |
+
else:
|
| 632 |
+
image_mask = input_ids == self.config.image_token_id
|
| 633 |
+
|
| 634 |
+
num_image_tokens = image_mask.sum(dim=1)
|
| 635 |
+
if not torch.all(num_image_tokens % patch_size == 0):
|
| 636 |
+
raise ValueError("At least one sample has <image> tokens not divisible by patch_size.")
|
| 637 |
+
|
| 638 |
+
blocks_per_sample = num_image_tokens // patch_size
|
| 639 |
+
|
| 640 |
+
offsets = torch.nn.functional.pad(blocks_per_sample.cumsum(dim=0), (1, 0), value=0)
|
| 641 |
+
block_offset = offsets[:-1]
|
| 642 |
+
row_cum = image_mask.cumsum(dim=-1)
|
| 643 |
+
chunk_idx = (row_cum - 1) // patch_size
|
| 644 |
+
local_idx = (row_cum - 1) % patch_size
|
| 645 |
+
block_idx = block_offset.unsqueeze(1) + chunk_idx
|
| 646 |
+
|
| 647 |
+
image_embeds = torch.zeros_like(inputs_embeds)
|
| 648 |
+
image_embeds[image_mask] = image_hidden_states[block_idx[image_mask], local_idx[image_mask], :]
|
| 649 |
+
|
| 650 |
+
merged_embeds = torch.where(image_mask.unsqueeze(-1), image_embeds, inputs_embeds)
|
| 651 |
+
return merged_embeds
|
| 652 |
+
|
| 653 |
+
def get_image_features(self, pixel_values: torch.FloatTensor, pixel_attention_mask: torch.LongTensor = None):
|
| 654 |
+
"""
|
| 655 |
+
Encodes images into continuous embeddings that can be forwarded to the language model.
|
| 656 |
+
|
| 657 |
+
Args:
|
| 658 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
|
| 659 |
+
The tensors corresponding to the input images.
|
| 660 |
+
pixel_attention_mask (`torch.LongTensor`, *optional*):
|
| 661 |
+
The attention mask indicating padded regions in the image.
|
| 662 |
+
"""
|
| 663 |
+
batch_size, num_images, num_channels, height, width = pixel_values.shape
|
| 664 |
+
pixel_values = pixel_values.to(dtype=self.dtype) # fp16 compatibility
|
| 665 |
+
pixel_values = pixel_values.view(batch_size * num_images, *pixel_values.shape[2:])
|
| 666 |
+
|
| 667 |
+
# Remove padding images - padding images are full 0.
|
| 668 |
+
nb_values_per_image = pixel_values.shape[1:].numel()
|
| 669 |
+
real_images_inds = (pixel_values == 0.0).sum(dim=(-1, -2, -3)) != nb_values_per_image
|
| 670 |
+
|
| 671 |
+
if not any(real_images_inds):
|
| 672 |
+
# no images, leave one empty image.
|
| 673 |
+
real_images_inds[0] = True
|
| 674 |
+
|
| 675 |
+
pixel_values = pixel_values[real_images_inds].contiguous()
|
| 676 |
+
# Handle the vision attention mask
|
| 677 |
+
if pixel_attention_mask is None:
|
| 678 |
+
pixel_attention_mask = torch.ones(
|
| 679 |
+
size=[pixel_values.shape[i] for i in (0, 2, 3)],
|
| 680 |
+
dtype=torch.bool,
|
| 681 |
+
device=pixel_values.device,
|
| 682 |
+
)
|
| 683 |
+
else:
|
| 684 |
+
# Remove padding images from the mask
|
| 685 |
+
pixel_attention_mask = pixel_attention_mask.view(batch_size * num_images, *pixel_attention_mask.shape[2:])
|
| 686 |
+
pixel_attention_mask = pixel_attention_mask[real_images_inds].contiguous()
|
| 687 |
+
patch_size = self.config.vision_config.patch_size
|
| 688 |
+
patches_subgrid = pixel_attention_mask.unfold(dimension=1, size=patch_size, step=patch_size)
|
| 689 |
+
patches_subgrid = patches_subgrid.unfold(dimension=2, size=patch_size, step=patch_size)
|
| 690 |
+
patch_attention_mask = (patches_subgrid.sum(dim=(-1, -2)) > 0).bool()
|
| 691 |
+
|
| 692 |
+
# Get sequence from the vision encoder
|
| 693 |
+
image_hidden_states = self.vision_model(pixel_values=pixel_values, patch_attention_mask=patch_attention_mask)
|
| 694 |
+
image_hidden_states = image_hidden_states.last_hidden_state
|
| 695 |
+
|
| 696 |
+
# Modality projection & resampling
|
| 697 |
+
image_hidden_states = self.connector(image_hidden_states)
|
| 698 |
+
return image_hidden_states
|
| 699 |
+
|
| 700 |
+
@can_return_tuple
|
| 701 |
+
@auto_docstring(
|
| 702 |
+
custom_intro="""
|
| 703 |
+
Inputs fed to the model can have an arbitrary number of images. To account for this, pixel_values fed to
|
| 704 |
+
the model have image padding -> (batch_size, max_num_images, 3, max_heights, max_widths) where
|
| 705 |
+
max_num_images is the maximum number of images among the batch_size samples in the batch.
|
| 706 |
+
Padding images are not needed beyond padding the pixel_values at the entrance of the model.
|
| 707 |
+
For efficiency, we only pass through the vision_model's forward the real images by
|
| 708 |
+
discarding the padding images i.e. pixel_values of size (image_batch_size, 3, height, width) where
|
| 709 |
+
image_batch_size would be 7 when num_images_per_sample=[1, 3, 1, 2] and max_num_images would be 3.
|
| 710 |
+
"""
|
| 711 |
+
)
|
| 712 |
+
def forward(
|
| 713 |
+
self,
|
| 714 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 715 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 716 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 717 |
+
past_key_values: Optional[Cache] = None,
|
| 718 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 719 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 720 |
+
pixel_attention_mask: Optional[torch.BoolTensor] = None,
|
| 721 |
+
image_hidden_states: Optional[torch.FloatTensor] = None,
|
| 722 |
+
use_cache: Optional[bool] = None,
|
| 723 |
+
output_attentions: Optional[bool] = None,
|
| 724 |
+
output_hidden_states: Optional[bool] = None,
|
| 725 |
+
return_dict: Optional[bool] = None,
|
| 726 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 727 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 728 |
+
) -> Union[tuple, SmolVLMBaseModelOutputWithPast]:
|
| 729 |
+
r"""
|
| 730 |
+
pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
|
| 731 |
+
Mask to avoid performing attention on padding pixel indices.
|
| 732 |
+
image_hidden_states (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
|
| 733 |
+
The hidden states of the image encoder after modality projection.
|
| 734 |
+
"""
|
| 735 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 736 |
+
output_hidden_states = (
|
| 737 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 738 |
+
)
|
| 739 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 740 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 741 |
+
|
| 742 |
+
if self.training and self.text_model.gradient_checkpointing and use_cache:
|
| 743 |
+
logger.warning_once(
|
| 744 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 745 |
+
)
|
| 746 |
+
use_cache = False
|
| 747 |
+
|
| 748 |
+
# retrieve input_ids and inputs_embeds
|
| 749 |
+
if input_ids is not None:
|
| 750 |
+
batch_size, seq_length = input_ids.shape
|
| 751 |
+
elif inputs_embeds is not None:
|
| 752 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
| 753 |
+
else:
|
| 754 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 755 |
+
|
| 756 |
+
if use_cache and past_key_values is None:
|
| 757 |
+
past_key_values = DynamicCache(config=self.config)
|
| 758 |
+
|
| 759 |
+
if inputs_embeds is None:
|
| 760 |
+
inputs_embeds = self.text_model.get_input_embeddings()(input_ids).to(input_ids.device)
|
| 761 |
+
|
| 762 |
+
# START VISUAL INPUTS INTEGRATION
|
| 763 |
+
if pixel_values is not None and image_hidden_states is not None:
|
| 764 |
+
raise ValueError("You cannot specify both pixel_values and image_hidden_states at the same time")
|
| 765 |
+
|
| 766 |
+
if pixel_values is not None:
|
| 767 |
+
image_hidden_states = self.get_image_features(pixel_values, pixel_attention_mask).to(inputs_embeds.device)
|
| 768 |
+
elif image_hidden_states is not None:
|
| 769 |
+
image_hidden_states = image_hidden_states.to(dtype=self.dtype, device=inputs_embeds.device)
|
| 770 |
+
|
| 771 |
+
if image_hidden_states is not None:
|
| 772 |
+
# When we generate, we don't want to replace the potential image_token_id that we generated by images
|
| 773 |
+
# that simply don't exist
|
| 774 |
+
inputs_embeds = self.inputs_merger(
|
| 775 |
+
input_ids=input_ids,
|
| 776 |
+
inputs_embeds=inputs_embeds,
|
| 777 |
+
image_hidden_states=image_hidden_states,
|
| 778 |
+
)
|
| 779 |
+
|
| 780 |
+
outputs = self.text_model(
|
| 781 |
+
inputs_embeds=inputs_embeds,
|
| 782 |
+
attention_mask=attention_mask,
|
| 783 |
+
position_ids=position_ids,
|
| 784 |
+
past_key_values=past_key_values,
|
| 785 |
+
use_cache=use_cache,
|
| 786 |
+
output_attentions=output_attentions,
|
| 787 |
+
output_hidden_states=output_hidden_states,
|
| 788 |
+
return_dict=True,
|
| 789 |
+
cache_position=cache_position,
|
| 790 |
+
**kwargs,
|
| 791 |
+
)
|
| 792 |
+
|
| 793 |
+
return SmolVLMBaseModelOutputWithPast(
|
| 794 |
+
last_hidden_state=outputs.last_hidden_state,
|
| 795 |
+
past_key_values=outputs.past_key_values,
|
| 796 |
+
hidden_states=outputs.hidden_states,
|
| 797 |
+
attentions=outputs.attentions,
|
| 798 |
+
image_hidden_states=image_hidden_states,
|
| 799 |
+
)
|
| 800 |
+
|
| 801 |
+
|
| 802 |
+
@dataclass
|
| 803 |
+
@auto_docstring(
|
| 804 |
+
custom_intro="""
|
| 805 |
+
Base class for Idefics causal language model (or autoregressive) outputs.
|
| 806 |
+
"""
|
| 807 |
+
)
|
| 808 |
+
class SmolVLMCausalLMOutputWithPast(ModelOutput):
|
| 809 |
+
r"""
|
| 810 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
| 811 |
+
Language modeling loss (for next-token prediction).
|
| 812 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
| 813 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
| 814 |
+
past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 815 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
|
| 816 |
+
`(batch_size, num_heads, sequence_length, embed_size_per_head)`)
|
| 817 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
|
| 818 |
+
`past_key_values` input) to speed up sequential decoding.
|
| 819 |
+
image_hidden_states (`tuple(torch.FloatTensor)`, *optional*):
|
| 820 |
+
Tuple of `torch.FloatTensor` (one for the output of the image embeddings, `(batch_size, num_images,
|
| 821 |
+
sequence_length, hidden_size)`.
|
| 822 |
+
image_hidden_states of the model produced by the vision encoder
|
| 823 |
+
"""
|
| 824 |
+
|
| 825 |
+
loss: Optional[torch.FloatTensor] = None
|
| 826 |
+
logits: Optional[torch.FloatTensor] = None
|
| 827 |
+
past_key_values: Optional[list[torch.FloatTensor]] = None
|
| 828 |
+
hidden_states: Optional[tuple[torch.FloatTensor]] = None
|
| 829 |
+
attentions: Optional[tuple[torch.FloatTensor]] = None
|
| 830 |
+
image_hidden_states: Optional[tuple[torch.FloatTensor]] = None
|
| 831 |
+
|
| 832 |
+
|
| 833 |
+
@auto_docstring(
|
| 834 |
+
custom_intro="""
|
| 835 |
+
The SmolVLM Model with a language modeling head. It is made up a SigLIP vision encoder, with a language modeling head on top.
|
| 836 |
+
"""
|
| 837 |
+
)
|
| 838 |
+
class SmolVLMForConditionalGeneration(SmolVLMPreTrainedModel, GenerationMixin):
|
| 839 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 840 |
+
|
| 841 |
+
def __init__(self, config):
|
| 842 |
+
super().__init__(config)
|
| 843 |
+
self.model = SmolVLMModel(config)
|
| 844 |
+
self.image_token_id = self.config.image_token_id
|
| 845 |
+
self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
|
| 846 |
+
self.vocab_size = config.text_config.vocab_size
|
| 847 |
+
self.model.text_model.generation_config = GenerationConfig.from_model_config(config)
|
| 848 |
+
|
| 849 |
+
# Initialize weights and apply final processing
|
| 850 |
+
self.post_init()
|
| 851 |
+
|
| 852 |
+
def enable_input_require_grads(self):
|
| 853 |
+
"""
|
| 854 |
+
Enables the gradients for the input embeddings. This is useful for fine-tuning adapter weights while keeping
|
| 855 |
+
the model weights fixed.
|
| 856 |
+
"""
|
| 857 |
+
|
| 858 |
+
def make_inputs_require_grads(module, input, output):
|
| 859 |
+
output.requires_grad_(True)
|
| 860 |
+
|
| 861 |
+
self._text_require_grads_hook = self.get_input_embeddings().register_forward_hook(make_inputs_require_grads)
|
| 862 |
+
self._vision_require_grads_hook = self.model.vision_model.get_input_embeddings().register_forward_hook(
|
| 863 |
+
make_inputs_require_grads
|
| 864 |
+
)
|
| 865 |
+
|
| 866 |
+
def disable_input_require_grads(self):
|
| 867 |
+
self._text_require_grads_hook.remove()
|
| 868 |
+
self._vision_require_grads_hook.remove()
|
| 869 |
+
|
| 870 |
+
def get_input_embeddings(self):
|
| 871 |
+
return self.model.text_model.get_input_embeddings()
|
| 872 |
+
|
| 873 |
+
def set_input_embeddings(self, value):
|
| 874 |
+
self.model.text_model.set_input_embeddings(value)
|
| 875 |
+
|
| 876 |
+
def get_image_features(self, pixel_values: torch.FloatTensor, pixel_attention_mask: torch.LongTensor = None):
|
| 877 |
+
return self.model.get_image_features(pixel_values=pixel_values, pixel_attention_mask=pixel_attention_mask)
|
| 878 |
+
|
| 879 |
+
@can_return_tuple
|
| 880 |
+
@auto_docstring
|
| 881 |
+
def forward(
|
| 882 |
+
self,
|
| 883 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 884 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 885 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 886 |
+
past_key_values: Optional[Cache] = None,
|
| 887 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 888 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 889 |
+
pixel_attention_mask: Optional[torch.BoolTensor] = None,
|
| 890 |
+
image_hidden_states: Optional[torch.FloatTensor] = None,
|
| 891 |
+
labels: Optional[torch.LongTensor] = None,
|
| 892 |
+
use_cache: Optional[bool] = None,
|
| 893 |
+
output_attentions: Optional[bool] = None,
|
| 894 |
+
output_hidden_states: Optional[bool] = None,
|
| 895 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 896 |
+
return_dict: Optional[bool] = None,
|
| 897 |
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
| 898 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 899 |
+
) -> Union[tuple, SmolVLMCausalLMOutputWithPast]:
|
| 900 |
+
r"""
|
| 901 |
+
pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
|
| 902 |
+
Mask to avoid performing attention on padding pixel indices.
|
| 903 |
+
image_hidden_states (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
|
| 904 |
+
The hidden states of the image encoder after modality projection.
|
| 905 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 906 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 907 |
+
config.vocab_size]` or `model.image_token_id`. Tokens with indices set to `model.image_token_id` are
|
| 908 |
+
ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 909 |
+
|
| 910 |
+
Example:
|
| 911 |
+
|
| 912 |
+
```python
|
| 913 |
+
>>> import requests
|
| 914 |
+
>>> import torch
|
| 915 |
+
>>> from PIL import Image
|
| 916 |
+
>>> from io import BytesIO
|
| 917 |
+
|
| 918 |
+
>>> from transformers import AutoProcessor, AutoModelForImageTextToText
|
| 919 |
+
>>> from transformers.image_utils import load_image
|
| 920 |
+
|
| 921 |
+
>>> # Note that passing the image urls (instead of the actual pil images) to the processor is also possible
|
| 922 |
+
>>> image1 = load_image("https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg")
|
| 923 |
+
>>> image2 = load_image("https://cdn.britannica.com/59/94459-050-DBA42467/Skyline-Chicago.jpg")
|
| 924 |
+
>>> image3 = load_image("https://cdn.britannica.com/68/170868-050-8DDE8263/Golden-Gate-Bridge-San-Francisco.jpg")
|
| 925 |
+
|
| 926 |
+
>>> processor = AutoProcessor.from_pretrained("HuggingFaceTB/SmolVLM2-2.2B-Instruct")
|
| 927 |
+
>>> model = AutoModelForImageTextToText.from_pretrained("HuggingFaceTB/SmolVLM2-2.2B-Instruct", dtype=torch.bfloat16, device_map="auto")
|
| 928 |
+
|
| 929 |
+
>>> # Create inputs
|
| 930 |
+
>>> messages = [
|
| 931 |
+
... {
|
| 932 |
+
... "role": "user",
|
| 933 |
+
... "content": [
|
| 934 |
+
... {"type": "video", "path": path/to/video},
|
| 935 |
+
... {"type": "text", "text": "What is happening in this video?"},
|
| 936 |
+
... ]
|
| 937 |
+
... }
|
| 938 |
+
... ]
|
| 939 |
+
|
| 940 |
+
>>> inputs = processor.apply_chat_template([messages], add_generation_prompt=True)
|
| 941 |
+
|
| 942 |
+
>>> # Generate
|
| 943 |
+
>>> generated_ids = model.generate(**inputs, max_new_tokens=256)
|
| 944 |
+
>>> generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)
|
| 945 |
+
|
| 946 |
+
>>> print(generated_texts)
|
| 947 |
+
```"""
|
| 948 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 949 |
+
output_hidden_states = (
|
| 950 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 951 |
+
)
|
| 952 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 953 |
+
|
| 954 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 955 |
+
outputs = self.model(
|
| 956 |
+
input_ids=input_ids,
|
| 957 |
+
attention_mask=attention_mask,
|
| 958 |
+
position_ids=position_ids,
|
| 959 |
+
past_key_values=past_key_values,
|
| 960 |
+
inputs_embeds=inputs_embeds,
|
| 961 |
+
pixel_values=pixel_values,
|
| 962 |
+
pixel_attention_mask=pixel_attention_mask,
|
| 963 |
+
image_hidden_states=image_hidden_states,
|
| 964 |
+
use_cache=use_cache,
|
| 965 |
+
output_attentions=output_attentions,
|
| 966 |
+
output_hidden_states=output_hidden_states,
|
| 967 |
+
cache_position=cache_position,
|
| 968 |
+
return_dict=True,
|
| 969 |
+
**kwargs,
|
| 970 |
+
)
|
| 971 |
+
|
| 972 |
+
hidden_states = outputs[0]
|
| 973 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 974 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 975 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
| 976 |
+
|
| 977 |
+
loss = None
|
| 978 |
+
if labels is not None:
|
| 979 |
+
loss = self.loss_function(
|
| 980 |
+
logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
|
| 981 |
+
)
|
| 982 |
+
|
| 983 |
+
return SmolVLMCausalLMOutputWithPast(
|
| 984 |
+
loss=loss,
|
| 985 |
+
logits=logits,
|
| 986 |
+
past_key_values=outputs.past_key_values,
|
| 987 |
+
hidden_states=outputs.hidden_states,
|
| 988 |
+
attentions=outputs.attentions,
|
| 989 |
+
image_hidden_states=outputs.image_hidden_states,
|
| 990 |
+
)
|
| 991 |
+
|
| 992 |
+
def prepare_inputs_for_generation(
|
| 993 |
+
self,
|
| 994 |
+
input_ids,
|
| 995 |
+
past_key_values=None,
|
| 996 |
+
attention_mask=None,
|
| 997 |
+
inputs_embeds=None,
|
| 998 |
+
cache_position=None,
|
| 999 |
+
pixel_values=None,
|
| 1000 |
+
pixel_attention_mask=None,
|
| 1001 |
+
image_hidden_states=None,
|
| 1002 |
+
logits_to_keep=None,
|
| 1003 |
+
**kwargs,
|
| 1004 |
+
):
|
| 1005 |
+
# Overwritten -- there are mutually exclusive inputs (if the logic to make `image_hidden_states` take
|
| 1006 |
+
# precedence is moved to the model, we can remove this fn)
|
| 1007 |
+
|
| 1008 |
+
model_inputs = super().prepare_inputs_for_generation(
|
| 1009 |
+
input_ids,
|
| 1010 |
+
past_key_values=past_key_values,
|
| 1011 |
+
attention_mask=attention_mask,
|
| 1012 |
+
inputs_embeds=inputs_embeds,
|
| 1013 |
+
cache_position=cache_position,
|
| 1014 |
+
pixel_values=pixel_values,
|
| 1015 |
+
pixel_attention_mask=pixel_attention_mask,
|
| 1016 |
+
image_hidden_states=image_hidden_states,
|
| 1017 |
+
logits_to_keep=logits_to_keep,
|
| 1018 |
+
**kwargs,
|
| 1019 |
+
)
|
| 1020 |
+
|
| 1021 |
+
if image_hidden_states is not None or cache_position[0] != 0:
|
| 1022 |
+
model_inputs["pixel_values"] = None
|
| 1023 |
+
model_inputs["pixel_attention_mask"] = None
|
| 1024 |
+
|
| 1025 |
+
return model_inputs
|
| 1026 |
+
|
| 1027 |
+
|
| 1028 |
+
__all__ = ["SmolVLMForConditionalGeneration", "SmolVLMPreTrainedModel", "SmolVLMModel", "SmolVLMVisionTransformer"]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/smolvlm/modular_smolvlm.py
ADDED
|
@@ -0,0 +1,410 @@
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
# Written by Orr Zohar
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
from typing import Optional, Union
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
import torch.utils.checkpoint
|
| 20 |
+
from torch import nn
|
| 21 |
+
|
| 22 |
+
from ...cache_utils import Cache, DynamicCache
|
| 23 |
+
from ...generation import GenerationConfig
|
| 24 |
+
from ...modeling_flash_attention_utils import FlashAttentionKwargs
|
| 25 |
+
from ...processing_utils import Unpack
|
| 26 |
+
from ...utils import auto_docstring, can_return_tuple, logging
|
| 27 |
+
from ..idefics3.configuration_idefics3 import Idefics3Config, Idefics3VisionConfig
|
| 28 |
+
from ..idefics3.image_processing_idefics3 import Idefics3ImageProcessor
|
| 29 |
+
from ..idefics3.image_processing_idefics3_fast import Idefics3ImageProcessorFast
|
| 30 |
+
from ..idefics3.modeling_idefics3 import (
|
| 31 |
+
Idefics3BaseModelOutputWithPast,
|
| 32 |
+
Idefics3ForConditionalGeneration,
|
| 33 |
+
Idefics3Model,
|
| 34 |
+
Idefics3PreTrainedModel,
|
| 35 |
+
Idefics3VisionTransformer,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
logger = logging.get_logger(__name__)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class SmolVLMVisionConfig(Idefics3VisionConfig):
|
| 43 |
+
r"""
|
| 44 |
+
This is the configuration class to store the configuration of a [`SmolVLMVisionModel`]. It is used to instantiate a
|
| 45 |
+
SmolVLM vision encoder according to the specified arguments, defining the model architecture. Instantiating a
|
| 46 |
+
configuration with the defaults will yield a similar configuration to that of the SigLIP checkpoint
|
| 47 |
+
[google/siglip-so400m-patch14-384](https://huggingface.co/google/siglip-so400m-patch14-384) used in SmolVLM
|
| 48 |
+
[HuggingFaceTB/SmolVLM2-2.2B-Instruct](https://huggingface.co/HuggingFaceTB/SmolVLM2-2.2B-Instruct).
|
| 49 |
+
|
| 50 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 51 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
hidden_size (`int`, *optional*, defaults to 1152):
|
| 55 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 56 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 57 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 58 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 59 |
+
Number of hidden layers in the Transformer encoder.
|
| 60 |
+
num_attention_heads (`int`, *optional*, defaults to 16):
|
| 61 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 62 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 63 |
+
Number of channels in the input images.
|
| 64 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 65 |
+
The size (resolution) of each image.
|
| 66 |
+
patch_size (`int`, *optional*, defaults to 32):
|
| 67 |
+
The size (resolution) of each patch.
|
| 68 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
|
| 69 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 70 |
+
`"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
|
| 71 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-06):
|
| 72 |
+
The epsilon used by the layer normalization layers.
|
| 73 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 74 |
+
The dropout ratio for the attention probabilities.
|
| 75 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 76 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 77 |
+
|
| 78 |
+
Example:
|
| 79 |
+
|
| 80 |
+
```python
|
| 81 |
+
>>> from transformers.models.smolvlm.modeling_smolvlm import SmolVLMVisionTransformer
|
| 82 |
+
>>> from transformers.models.smolvlm.configuration_smolvlm import SmolVLMVisionConfig
|
| 83 |
+
|
| 84 |
+
>>> # Initializing a SmolVLMVisionConfig with google/siglip-so400m-patch14-384 style configuration
|
| 85 |
+
>>> configuration = SmolVLMVisionConfig()
|
| 86 |
+
|
| 87 |
+
>>> # Initializing a SmolVLMVisionTransformer (with random weights) from the google/siglip-so400m-patch14-384 style configuration
|
| 88 |
+
>>> model = SmolVLMVisionTransformer(configuration)
|
| 89 |
+
|
| 90 |
+
>>> # Accessing the model configuration
|
| 91 |
+
>>> configuration = model.config
|
| 92 |
+
```"""
|
| 93 |
+
|
| 94 |
+
model_type = "smolvlm_vision"
|
| 95 |
+
pass
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class SmolVLMPreTrainedModel(Idefics3PreTrainedModel):
|
| 99 |
+
pass
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class SmolVLMVisionTransformer(Idefics3VisionTransformer):
|
| 103 |
+
pass
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class SmolVLMConfig(Idefics3Config):
|
| 107 |
+
r"""
|
| 108 |
+
This is the configuration class to store the configuration of a [`SmolVLMModel`]. It is used to instantiate a
|
| 109 |
+
SmolVLM model according to the specified arguments, defining the model architecture. Instantiating a
|
| 110 |
+
configuration with the defaults will yield a similar configuration to that of the model of the SmolVLM
|
| 111 |
+
[HuggingFaceTB/SmolVLM2-2.2B-Instruct](https://huggingface.co/HuggingFaceTB/SmolVLM2-2.2B-Instruct) architecture.
|
| 112 |
+
|
| 113 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 114 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 115 |
+
|
| 116 |
+
Args:
|
| 117 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 118 |
+
Whether or not the model should cache the key/value pairs of the attention mechanism. Only
|
| 119 |
+
relevant if `config.is_decoder=True`.
|
| 120 |
+
image_token_id (`int`, *optional*, defaults to 128257):
|
| 121 |
+
The id of the "image" token.
|
| 122 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
| 123 |
+
Whether or not to tie the word embeddings with the token embeddings.
|
| 124 |
+
vision_config (`IdeficsVisionConfig` or `dict`, *optional*, defaults to `IdeficsVisionConfig`):
|
| 125 |
+
Custom vision config or dict for the vision tower
|
| 126 |
+
text_config (`PretrainedConfig` or `dict`, *optional*, defaults to `LlamaConfig`):
|
| 127 |
+
Custom text config or dict for the text model
|
| 128 |
+
scale_factor (`int`, *optional*, defaults to 2):
|
| 129 |
+
The scale factor for the image encoder.
|
| 130 |
+
pad_token_id (`int`, *optional*, defaults to 128002):
|
| 131 |
+
The id of the padding token.
|
| 132 |
+
|
| 133 |
+
Example:
|
| 134 |
+
```python
|
| 135 |
+
>>> from transformers import SmolVLMModel, SmolVLMConfig
|
| 136 |
+
>>> # Initializing configuration
|
| 137 |
+
>>> configuration = SmolVLMConfig()
|
| 138 |
+
>>> # Initializing a model from the configuration
|
| 139 |
+
>>> model = SmolVLMModel(configuration)
|
| 140 |
+
>>> # Accessing the model configuration
|
| 141 |
+
>>> configuration = model.config
|
| 142 |
+
```"""
|
| 143 |
+
|
| 144 |
+
model_type = "smolvlm"
|
| 145 |
+
pass
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
class SmolVLMImageProcessor(Idefics3ImageProcessor):
|
| 149 |
+
pass
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class SmolVLMImageProcessorFast(Idefics3ImageProcessorFast):
|
| 153 |
+
pass
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class SmolVLMBaseModelOutputWithPast(Idefics3BaseModelOutputWithPast):
|
| 157 |
+
pass
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
class SmolVLMModel(Idefics3Model):
|
| 161 |
+
"""
|
| 162 |
+
A subclass of Idefics3Model. We do *not* remove or block the call to inputs_merger
|
| 163 |
+
in forward. Instead, we override inputs_merger here with custom logic.
|
| 164 |
+
"""
|
| 165 |
+
|
| 166 |
+
def inputs_merger(
|
| 167 |
+
self, input_ids: torch.LongTensor, inputs_embeds: torch.Tensor, image_hidden_states: torch.Tensor
|
| 168 |
+
):
|
| 169 |
+
_, patch_size, _ = image_hidden_states.shape
|
| 170 |
+
|
| 171 |
+
if input_ids is None:
|
| 172 |
+
image_mask = inputs_embeds == self.get_input_embeddings()(
|
| 173 |
+
torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
|
| 174 |
+
)
|
| 175 |
+
image_mask = image_mask[..., 0] # slice off the hidden dim
|
| 176 |
+
else:
|
| 177 |
+
image_mask = input_ids == self.config.image_token_id
|
| 178 |
+
|
| 179 |
+
num_image_tokens = image_mask.sum(dim=1)
|
| 180 |
+
if not torch.all(num_image_tokens % patch_size == 0):
|
| 181 |
+
raise ValueError("At least one sample has <image> tokens not divisible by patch_size.")
|
| 182 |
+
|
| 183 |
+
blocks_per_sample = num_image_tokens // patch_size
|
| 184 |
+
|
| 185 |
+
offsets = torch.nn.functional.pad(blocks_per_sample.cumsum(dim=0), (1, 0), value=0)
|
| 186 |
+
block_offset = offsets[:-1]
|
| 187 |
+
row_cum = image_mask.cumsum(dim=-1)
|
| 188 |
+
chunk_idx = (row_cum - 1) // patch_size
|
| 189 |
+
local_idx = (row_cum - 1) % patch_size
|
| 190 |
+
block_idx = block_offset.unsqueeze(1) + chunk_idx
|
| 191 |
+
|
| 192 |
+
image_embeds = torch.zeros_like(inputs_embeds)
|
| 193 |
+
image_embeds[image_mask] = image_hidden_states[block_idx[image_mask], local_idx[image_mask], :]
|
| 194 |
+
|
| 195 |
+
merged_embeds = torch.where(image_mask.unsqueeze(-1), image_embeds, inputs_embeds)
|
| 196 |
+
return merged_embeds
|
| 197 |
+
|
| 198 |
+
def get_image_features(self, pixel_values: torch.FloatTensor, pixel_attention_mask: torch.LongTensor = None):
|
| 199 |
+
"""
|
| 200 |
+
Encodes images into continuous embeddings that can be forwarded to the language model.
|
| 201 |
+
|
| 202 |
+
Args:
|
| 203 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
|
| 204 |
+
The tensors corresponding to the input images.
|
| 205 |
+
pixel_attention_mask (`torch.LongTensor`, *optional*):
|
| 206 |
+
The attention mask indicating padded regions in the image.
|
| 207 |
+
"""
|
| 208 |
+
batch_size, num_images, num_channels, height, width = pixel_values.shape
|
| 209 |
+
pixel_values = pixel_values.to(dtype=self.dtype) # fp16 compatibility
|
| 210 |
+
pixel_values = pixel_values.view(batch_size * num_images, *pixel_values.shape[2:])
|
| 211 |
+
|
| 212 |
+
# Remove padding images - padding images are full 0.
|
| 213 |
+
nb_values_per_image = pixel_values.shape[1:].numel()
|
| 214 |
+
real_images_inds = (pixel_values == 0.0).sum(dim=(-1, -2, -3)) != nb_values_per_image
|
| 215 |
+
|
| 216 |
+
if not any(real_images_inds):
|
| 217 |
+
# no images, leave one empty image.
|
| 218 |
+
real_images_inds[0] = True
|
| 219 |
+
|
| 220 |
+
pixel_values = pixel_values[real_images_inds].contiguous()
|
| 221 |
+
# Handle the vision attention mask
|
| 222 |
+
if pixel_attention_mask is None:
|
| 223 |
+
pixel_attention_mask = torch.ones(
|
| 224 |
+
size=[pixel_values.shape[i] for i in (0, 2, 3)],
|
| 225 |
+
dtype=torch.bool,
|
| 226 |
+
device=pixel_values.device,
|
| 227 |
+
)
|
| 228 |
+
else:
|
| 229 |
+
# Remove padding images from the mask
|
| 230 |
+
pixel_attention_mask = pixel_attention_mask.view(batch_size * num_images, *pixel_attention_mask.shape[2:])
|
| 231 |
+
pixel_attention_mask = pixel_attention_mask[real_images_inds].contiguous()
|
| 232 |
+
patch_size = self.config.vision_config.patch_size
|
| 233 |
+
patches_subgrid = pixel_attention_mask.unfold(dimension=1, size=patch_size, step=patch_size)
|
| 234 |
+
patches_subgrid = patches_subgrid.unfold(dimension=2, size=patch_size, step=patch_size)
|
| 235 |
+
patch_attention_mask = (patches_subgrid.sum(dim=(-1, -2)) > 0).bool()
|
| 236 |
+
|
| 237 |
+
# Get sequence from the vision encoder
|
| 238 |
+
image_hidden_states = self.vision_model(pixel_values=pixel_values, patch_attention_mask=patch_attention_mask)
|
| 239 |
+
image_hidden_states = image_hidden_states.last_hidden_state
|
| 240 |
+
|
| 241 |
+
# Modality projection & resampling
|
| 242 |
+
image_hidden_states = self.connector(image_hidden_states)
|
| 243 |
+
return image_hidden_states
|
| 244 |
+
|
| 245 |
+
@can_return_tuple
|
| 246 |
+
@auto_docstring(
|
| 247 |
+
custom_intro="""
|
| 248 |
+
Inputs fed to the model can have an arbitrary number of images. To account for this, pixel_values fed to
|
| 249 |
+
the model have image padding -> (batch_size, max_num_images, 3, max_heights, max_widths) where
|
| 250 |
+
max_num_images is the maximum number of images among the batch_size samples in the batch.
|
| 251 |
+
Padding images are not needed beyond padding the pixel_values at the entrance of the model.
|
| 252 |
+
For efficiency, we only pass through the vision_model's forward the real images by
|
| 253 |
+
discarding the padding images i.e. pixel_values of size (image_batch_size, 3, height, width) where
|
| 254 |
+
image_batch_size would be 7 when num_images_per_sample=[1, 3, 1, 2] and max_num_images would be 3.
|
| 255 |
+
"""
|
| 256 |
+
)
|
| 257 |
+
def forward(
|
| 258 |
+
self,
|
| 259 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 260 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 261 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 262 |
+
past_key_values: Optional[Cache] = None,
|
| 263 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 264 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 265 |
+
pixel_attention_mask: Optional[torch.BoolTensor] = None,
|
| 266 |
+
image_hidden_states: Optional[torch.FloatTensor] = None,
|
| 267 |
+
use_cache: Optional[bool] = None,
|
| 268 |
+
output_attentions: Optional[bool] = None,
|
| 269 |
+
output_hidden_states: Optional[bool] = None,
|
| 270 |
+
return_dict: Optional[bool] = None,
|
| 271 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 272 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 273 |
+
) -> Union[tuple, SmolVLMBaseModelOutputWithPast]:
|
| 274 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 275 |
+
output_hidden_states = (
|
| 276 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 277 |
+
)
|
| 278 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 279 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 280 |
+
|
| 281 |
+
if self.training and self.text_model.gradient_checkpointing and use_cache:
|
| 282 |
+
logger.warning_once(
|
| 283 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 284 |
+
)
|
| 285 |
+
use_cache = False
|
| 286 |
+
|
| 287 |
+
# retrieve input_ids and inputs_embeds
|
| 288 |
+
if input_ids is not None:
|
| 289 |
+
batch_size, seq_length = input_ids.shape
|
| 290 |
+
elif inputs_embeds is not None:
|
| 291 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
| 292 |
+
else:
|
| 293 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 294 |
+
|
| 295 |
+
if use_cache and past_key_values is None:
|
| 296 |
+
past_key_values = DynamicCache(config=self.config)
|
| 297 |
+
|
| 298 |
+
if inputs_embeds is None:
|
| 299 |
+
inputs_embeds = self.text_model.get_input_embeddings()(input_ids).to(input_ids.device)
|
| 300 |
+
|
| 301 |
+
# START VISUAL INPUTS INTEGRATION
|
| 302 |
+
if pixel_values is not None and image_hidden_states is not None:
|
| 303 |
+
raise ValueError("You cannot specify both pixel_values and image_hidden_states at the same time")
|
| 304 |
+
|
| 305 |
+
if pixel_values is not None:
|
| 306 |
+
image_hidden_states = self.get_image_features(pixel_values, pixel_attention_mask).to(inputs_embeds.device)
|
| 307 |
+
elif image_hidden_states is not None:
|
| 308 |
+
image_hidden_states = image_hidden_states.to(dtype=self.dtype, device=inputs_embeds.device)
|
| 309 |
+
|
| 310 |
+
if image_hidden_states is not None:
|
| 311 |
+
# When we generate, we don't want to replace the potential image_token_id that we generated by images
|
| 312 |
+
# that simply don't exist
|
| 313 |
+
inputs_embeds = self.inputs_merger(
|
| 314 |
+
input_ids=input_ids,
|
| 315 |
+
inputs_embeds=inputs_embeds,
|
| 316 |
+
image_hidden_states=image_hidden_states,
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
outputs = self.text_model(
|
| 320 |
+
inputs_embeds=inputs_embeds,
|
| 321 |
+
attention_mask=attention_mask,
|
| 322 |
+
position_ids=position_ids,
|
| 323 |
+
past_key_values=past_key_values,
|
| 324 |
+
use_cache=use_cache,
|
| 325 |
+
output_attentions=output_attentions,
|
| 326 |
+
output_hidden_states=output_hidden_states,
|
| 327 |
+
return_dict=True,
|
| 328 |
+
cache_position=cache_position,
|
| 329 |
+
**kwargs,
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
return SmolVLMBaseModelOutputWithPast(
|
| 333 |
+
last_hidden_state=outputs.last_hidden_state,
|
| 334 |
+
past_key_values=outputs.past_key_values,
|
| 335 |
+
hidden_states=outputs.hidden_states,
|
| 336 |
+
attentions=outputs.attentions,
|
| 337 |
+
image_hidden_states=image_hidden_states,
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
class SmolVLMForConditionalGeneration(Idefics3ForConditionalGeneration):
|
| 342 |
+
def __init__(self, config):
|
| 343 |
+
super().__init__(config)
|
| 344 |
+
self.model = SmolVLMModel(config)
|
| 345 |
+
self.model.text_model.generation_config = GenerationConfig.from_model_config(config)
|
| 346 |
+
self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
|
| 347 |
+
self.post_init()
|
| 348 |
+
|
| 349 |
+
def forward(self, **super_kwargs):
|
| 350 |
+
r"""
|
| 351 |
+
pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
|
| 352 |
+
Mask to avoid performing attention on padding pixel indices.
|
| 353 |
+
image_hidden_states (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
|
| 354 |
+
The hidden states of the image encoder after modality projection.
|
| 355 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 356 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 357 |
+
config.vocab_size]` or `model.image_token_id`. Tokens with indices set to `model.image_token_id` are
|
| 358 |
+
ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 359 |
+
|
| 360 |
+
Example:
|
| 361 |
+
|
| 362 |
+
```python
|
| 363 |
+
>>> import requests
|
| 364 |
+
>>> import torch
|
| 365 |
+
>>> from PIL import Image
|
| 366 |
+
>>> from io import BytesIO
|
| 367 |
+
|
| 368 |
+
>>> from transformers import AutoProcessor, AutoModelForImageTextToText
|
| 369 |
+
>>> from transformers.image_utils import load_image
|
| 370 |
+
|
| 371 |
+
>>> # Note that passing the image urls (instead of the actual pil images) to the processor is also possible
|
| 372 |
+
>>> image1 = load_image("https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg")
|
| 373 |
+
>>> image2 = load_image("https://cdn.britannica.com/59/94459-050-DBA42467/Skyline-Chicago.jpg")
|
| 374 |
+
>>> image3 = load_image("https://cdn.britannica.com/68/170868-050-8DDE8263/Golden-Gate-Bridge-San-Francisco.jpg")
|
| 375 |
+
|
| 376 |
+
>>> processor = AutoProcessor.from_pretrained("HuggingFaceTB/SmolVLM2-2.2B-Instruct")
|
| 377 |
+
>>> model = AutoModelForImageTextToText.from_pretrained("HuggingFaceTB/SmolVLM2-2.2B-Instruct", dtype=torch.bfloat16, device_map="auto")
|
| 378 |
+
|
| 379 |
+
>>> # Create inputs
|
| 380 |
+
>>> messages = [
|
| 381 |
+
... {
|
| 382 |
+
... "role": "user",
|
| 383 |
+
... "content": [
|
| 384 |
+
... {"type": "video", "path": path/to/video},
|
| 385 |
+
... {"type": "text", "text": "What is happening in this video?"},
|
| 386 |
+
... ]
|
| 387 |
+
... }
|
| 388 |
+
... ]
|
| 389 |
+
|
| 390 |
+
>>> inputs = processor.apply_chat_template([messages], add_generation_prompt=True)
|
| 391 |
+
|
| 392 |
+
>>> # Generate
|
| 393 |
+
>>> generated_ids = model.generate(**inputs, max_new_tokens=256)
|
| 394 |
+
>>> generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)
|
| 395 |
+
|
| 396 |
+
>>> print(generated_texts)
|
| 397 |
+
```"""
|
| 398 |
+
super().forward(**super_kwargs)
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
__all__ = [
|
| 402 |
+
"SmolVLMVisionConfig",
|
| 403 |
+
"SmolVLMConfig",
|
| 404 |
+
"SmolVLMImageProcessor",
|
| 405 |
+
"SmolVLMImageProcessorFast",
|
| 406 |
+
"SmolVLMForConditionalGeneration",
|
| 407 |
+
"SmolVLMPreTrainedModel",
|
| 408 |
+
"SmolVLMModel",
|
| 409 |
+
"SmolVLMVisionTransformer",
|
| 410 |
+
]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/smolvlm/processing_smolvlm.py
ADDED
|
@@ -0,0 +1,423 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Processor class for SmolVLM.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from datetime import timedelta
|
| 20 |
+
from typing import TYPE_CHECKING, Optional, Union
|
| 21 |
+
|
| 22 |
+
from ...feature_extraction_utils import BatchFeature
|
| 23 |
+
from ...image_utils import ImageInput, make_nested_list_of_images
|
| 24 |
+
from ...processing_utils import AllKwargsForChatTemplate, ImagesKwargs, ProcessingKwargs, ProcessorMixin, Unpack
|
| 25 |
+
from ...tokenization_utils_base import BatchEncoding, TextInput
|
| 26 |
+
from ...utils import is_num2words_available, is_vision_available, logging
|
| 27 |
+
from ...video_utils import VideoInput
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
if is_vision_available():
|
| 31 |
+
from .video_processing_smolvlm import (
|
| 32 |
+
DEFAULT_MEDIA_OUTTRO,
|
| 33 |
+
DEFAULT_VIDEO_INTRO,
|
| 34 |
+
FRAME_TIMESTAMP_MESSAGE,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
if is_vision_available():
|
| 38 |
+
from .video_processing_smolvlm import (
|
| 39 |
+
DEFAULT_MEDIA_OUTTRO,
|
| 40 |
+
DEFAULT_VIDEO_INTRO,
|
| 41 |
+
FRAME_TIMESTAMP_MESSAGE,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
if TYPE_CHECKING:
|
| 45 |
+
from ...tokenization_utils_base import PreTokenizedInput
|
| 46 |
+
|
| 47 |
+
logger = logging.get_logger(__name__)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
if is_num2words_available():
|
| 51 |
+
from num2words import num2words
|
| 52 |
+
else:
|
| 53 |
+
num2words = None
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
# The correct chat template to be used for videos after #38105
|
| 57 |
+
DEFAULT_CHAT_TEMPLATE = "<|im_start|>{% for message in messages %}{{message['role'] | capitalize}}{% if message['content'][0]['type'] == 'image' %}{{':'}}{% else %}{{': '}}{% endif %}{% for line in message['content'] %}{% if line['type'] == 'text' %}{{line['text']}}{% elif line['type'] == 'image' %}{{ '<image>' }}{% elif line['type'] == 'video' %}{{ '<video>' }}{% endif %}{% endfor %}<end_of_utterance>\n{% endfor %}{% if add_generation_prompt %}{{ 'Assistant:' }}{% endif %}"
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _prompt_split_image(
|
| 61 |
+
image_seq_len, image_rows, image_cols, fake_token_around_image, image_token, global_image_token
|
| 62 |
+
):
|
| 63 |
+
"""Prompt with expanded image tokens for when the image is split into patches."""
|
| 64 |
+
text_split_images = ""
|
| 65 |
+
for n_h in range(image_rows):
|
| 66 |
+
for n_w in range(image_cols):
|
| 67 |
+
text_split_images += (
|
| 68 |
+
f"{fake_token_around_image}" + f"<row_{n_h + 1}_col_{n_w + 1}>" + f"{image_token}" * image_seq_len
|
| 69 |
+
)
|
| 70 |
+
text_split_images += "\n"
|
| 71 |
+
|
| 72 |
+
text_split_images += (
|
| 73 |
+
f"\n{fake_token_around_image}"
|
| 74 |
+
+ f"{global_image_token}"
|
| 75 |
+
+ f"{image_token}" * image_seq_len
|
| 76 |
+
+ f"{fake_token_around_image}"
|
| 77 |
+
)
|
| 78 |
+
return text_split_images
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _prompt_single_image(image_seq_len, fake_token_around_image, image_token, global_image_token):
|
| 82 |
+
"""Prompt with expanded image tokens for a single image."""
|
| 83 |
+
return (
|
| 84 |
+
f"{fake_token_around_image}"
|
| 85 |
+
+ f"{global_image_token}"
|
| 86 |
+
+ f"{image_token}" * image_seq_len
|
| 87 |
+
+ f"{fake_token_around_image}"
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def get_image_prompt_string(
|
| 92 |
+
image_rows, image_cols, image_seq_len, fake_token_around_image, image_token, global_image_token
|
| 93 |
+
):
|
| 94 |
+
if image_rows == 0 and image_cols == 0:
|
| 95 |
+
return _prompt_single_image(
|
| 96 |
+
image_seq_len,
|
| 97 |
+
fake_token_around_image=fake_token_around_image,
|
| 98 |
+
image_token=image_token,
|
| 99 |
+
global_image_token=global_image_token,
|
| 100 |
+
)
|
| 101 |
+
return _prompt_split_image(
|
| 102 |
+
image_seq_len, image_rows, image_cols, fake_token_around_image, image_token, global_image_token
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class SmolVLMImagesKwargs(ImagesKwargs, total=False):
|
| 107 |
+
return_row_col_info: Optional[bool]
|
| 108 |
+
max_image_size: Optional[dict[str, int]]
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class SmolVLMProcessorKwargs(ProcessingKwargs, total=False):
|
| 112 |
+
images_kwargs: SmolVLMImagesKwargs
|
| 113 |
+
|
| 114 |
+
_defaults = {
|
| 115 |
+
"text_kwargs": {
|
| 116 |
+
"add_special_tokens": True,
|
| 117 |
+
"padding": False,
|
| 118 |
+
"is_split_into_words": False,
|
| 119 |
+
},
|
| 120 |
+
"images_kwargs": {
|
| 121 |
+
"return_row_col_info": True,
|
| 122 |
+
},
|
| 123 |
+
"videos_kwargs": {
|
| 124 |
+
"return_metadata": True,
|
| 125 |
+
},
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class SmolVLMProcessor(ProcessorMixin):
|
| 130 |
+
r"""
|
| 131 |
+
Constructs a SmolVLM processor which wraps a LLama tokenizer and SmolVLM image processor into a single processor.
|
| 132 |
+
|
| 133 |
+
[`SmolVLMProcessor`] offers all the functionalities of [`SmolVLMImageProcessor`] and [`SmolVLMTokenizerFast`]. See
|
| 134 |
+
the docstring of [`~IdeficsProcessor.__call__`] and [`~IdeficsProcessor.decode`] for more information.
|
| 135 |
+
|
| 136 |
+
Args:
|
| 137 |
+
image_processor (`SmolVLMImageProcessor`):
|
| 138 |
+
An instance of [`SmolVLMImageProcessor`]. The image processor is a required input.
|
| 139 |
+
tokenizer (`PreTrainedTokenizerBase`):
|
| 140 |
+
An instance of [`PreTrainedTokenizerBase`]. This should correspond with the model's text model. The tokenizer is a required input.
|
| 141 |
+
video_processor (`SmolVLMImageProcessor`):
|
| 142 |
+
n instance of [`SmolVLMImageProcessor`]. The video processor is a required input.
|
| 143 |
+
image_seq_len (`int`, *optional*, defaults to 169):
|
| 144 |
+
The length of the image sequence i.e. the number of <image> tokens per image in the input.
|
| 145 |
+
This parameter is used to build the string from the input prompt and image tokens and should match the
|
| 146 |
+
value the model used. It is computed as: image_seq_len = int(((image_size // patch_size) ** 2) / (scale_factor**2))
|
| 147 |
+
chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
|
| 148 |
+
in a chat into a tokenizable string.
|
| 149 |
+
"""
|
| 150 |
+
|
| 151 |
+
attributes = ["image_processor", "tokenizer", "video_processor"]
|
| 152 |
+
image_processor_class = "SmolVLMImageProcessor"
|
| 153 |
+
video_processor_class = "SmolVLMVideoProcessor" # NOTE: uses different interpolation than slow processors
|
| 154 |
+
tokenizer_class = "AutoTokenizer"
|
| 155 |
+
|
| 156 |
+
def __init__(
|
| 157 |
+
self,
|
| 158 |
+
image_processor,
|
| 159 |
+
tokenizer,
|
| 160 |
+
video_processor,
|
| 161 |
+
image_seq_len: int = 169,
|
| 162 |
+
chat_template: Optional[str] = None,
|
| 163 |
+
**kwargs,
|
| 164 |
+
):
|
| 165 |
+
self.fake_image_token = getattr(tokenizer, "fake_image_token", "<fake_token_around_image>")
|
| 166 |
+
self.image_token = getattr(tokenizer, "image_token", "<image>")
|
| 167 |
+
self.image_token_id = tokenizer.convert_tokens_to_ids(self.image_token)
|
| 168 |
+
self.end_of_utterance_token = getattr(tokenizer, "end_of_utterance_token", "<end_of_utterance>")
|
| 169 |
+
self.global_image_token = getattr(tokenizer, "global_image_token", "<global-img>")
|
| 170 |
+
self.image_seq_len = image_seq_len
|
| 171 |
+
self.video_token = getattr(tokenizer, "video_token", "<video>")
|
| 172 |
+
|
| 173 |
+
if not num2words:
|
| 174 |
+
raise ImportError(
|
| 175 |
+
"Package `num2words` is required to run SmolVLM processor. Install it with `pip install num2words`."
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
super().__init__(image_processor, tokenizer, video_processor, chat_template=chat_template, **kwargs)
|
| 179 |
+
|
| 180 |
+
def expand_text_with_image_tokens(self, text, image_rows, image_cols):
|
| 181 |
+
prompt_strings = []
|
| 182 |
+
image_rows = image_rows if image_rows is not None else [[0] * len(text)]
|
| 183 |
+
image_cols = image_cols if image_cols is not None else [[0] * len(text)]
|
| 184 |
+
for sample, sample_rows, sample_cols in zip(text, image_rows, image_cols):
|
| 185 |
+
# Replace the image token with fake tokens around the expanded image token sequence of length `image_seq_len`
|
| 186 |
+
image_prompt_strings = []
|
| 187 |
+
for n_rows, n_cols in zip(sample_rows, sample_cols):
|
| 188 |
+
image_prompt_string = get_image_prompt_string(
|
| 189 |
+
n_rows,
|
| 190 |
+
n_cols,
|
| 191 |
+
self.image_seq_len,
|
| 192 |
+
image_token=self.image_token,
|
| 193 |
+
fake_token_around_image=self.fake_image_token,
|
| 194 |
+
global_image_token=self.global_image_token,
|
| 195 |
+
)
|
| 196 |
+
image_prompt_strings.append(image_prompt_string)
|
| 197 |
+
|
| 198 |
+
split_sample = sample.split(self.image_token)
|
| 199 |
+
if len(split_sample) == 0:
|
| 200 |
+
raise ValueError("The image token should be present in the text.")
|
| 201 |
+
|
| 202 |
+
# Place in the image prompt strings where the image tokens are
|
| 203 |
+
sample = split_sample[0]
|
| 204 |
+
for i, image_prompt_string in enumerate(image_prompt_strings):
|
| 205 |
+
sample += image_prompt_string + split_sample[i + 1]
|
| 206 |
+
prompt_strings.append(sample)
|
| 207 |
+
|
| 208 |
+
return prompt_strings
|
| 209 |
+
|
| 210 |
+
def expand_text_with_video_tokens(self, text, video_inputs):
|
| 211 |
+
num_frames = video_inputs["pixel_values"].shape[1]
|
| 212 |
+
video_metadata = iter(video_inputs["video_metadata"])
|
| 213 |
+
|
| 214 |
+
prompt_strings = []
|
| 215 |
+
for sample in text:
|
| 216 |
+
while self.video_token in sample:
|
| 217 |
+
metadata = next(video_metadata)
|
| 218 |
+
if metadata.fps is None:
|
| 219 |
+
logger.warning_once(
|
| 220 |
+
"SmolVLM requires frame timestamps to construct prompts, but the `fps` of the input video could not be inferred. "
|
| 221 |
+
"Probably `video_metadata` was missing from inputs and you passed pre-sampled frames. "
|
| 222 |
+
"Defaulting to `fps=24`. Please provide `video_metadata` for more accurate results."
|
| 223 |
+
)
|
| 224 |
+
metadata.fps = 24 # Set the default fps to 24 for BC, otherwise `timestamps` can't be inferred
|
| 225 |
+
timestamps = [(int(second // 60), int(second % 60)) for second in metadata.timestamps]
|
| 226 |
+
duration = int(metadata.duration) if metadata.duration is not None else int(metadata.timestamps[-1])
|
| 227 |
+
duration_td = timedelta(seconds=int(duration))
|
| 228 |
+
image_prompt_strings = DEFAULT_VIDEO_INTRO.format(
|
| 229 |
+
frame_count=num2words(num_frames), video_duration=str(duration_td)
|
| 230 |
+
)
|
| 231 |
+
for timestamp in timestamps:
|
| 232 |
+
image_prompt_string = _prompt_single_image(
|
| 233 |
+
self.image_seq_len,
|
| 234 |
+
image_token=self.image_token,
|
| 235 |
+
fake_token_around_image=self.fake_image_token,
|
| 236 |
+
global_image_token=self.global_image_token,
|
| 237 |
+
)
|
| 238 |
+
timestamp = f"{timestamp[0]:02d}:{timestamp[1]:02d}"
|
| 239 |
+
image_prompt_string = FRAME_TIMESTAMP_MESSAGE.format(timestamp=timestamp) + image_prompt_string
|
| 240 |
+
image_prompt_strings += image_prompt_string
|
| 241 |
+
|
| 242 |
+
image_prompt_strings += DEFAULT_MEDIA_OUTTRO
|
| 243 |
+
sample = sample.replace(self.video_token, image_prompt_strings, 1)
|
| 244 |
+
prompt_strings.append(sample)
|
| 245 |
+
return prompt_strings
|
| 246 |
+
|
| 247 |
+
def __call__(
|
| 248 |
+
self,
|
| 249 |
+
images: Union[ImageInput, list[ImageInput], list[list[ImageInput]]] = None,
|
| 250 |
+
text: Union[TextInput, "PreTokenizedInput", list[TextInput], list["PreTokenizedInput"]] = None,
|
| 251 |
+
audio=None,
|
| 252 |
+
videos: VideoInput = None,
|
| 253 |
+
**kwargs: Unpack[SmolVLMProcessorKwargs],
|
| 254 |
+
) -> BatchEncoding:
|
| 255 |
+
"""
|
| 256 |
+
Processes the input prompts and returns a BatchEncoding.
|
| 257 |
+
|
| 258 |
+
Example:
|
| 259 |
+
|
| 260 |
+
```python
|
| 261 |
+
>>> import requests
|
| 262 |
+
>>> from transformers import SmolVLMProcessor
|
| 263 |
+
>>> from transformers.image_utils import load_image
|
| 264 |
+
|
| 265 |
+
>>> processor = SmolVLMProcessor.from_pretrained("HuggingFaceM4/SmolVLM2-256M-Video-Instruct")
|
| 266 |
+
>>> processor.image_processor.do_image_splitting = False # Force as False to simplify the example
|
| 267 |
+
|
| 268 |
+
>>> url1 = "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"
|
| 269 |
+
>>> url2 = "https://cdn.britannica.com/59/94459-050-DBA42467/Skyline-Chicago.jpg"
|
| 270 |
+
|
| 271 |
+
>>> image1, image2 = load_image(url1), load_image(url2)
|
| 272 |
+
>>> images = [[image1], [image2]]
|
| 273 |
+
|
| 274 |
+
>>> text = [
|
| 275 |
+
... "<image>In this image, we see",
|
| 276 |
+
... "bla bla bla<image>",
|
| 277 |
+
... ]
|
| 278 |
+
>>> outputs = processor(images=images, text=text, return_tensors="pt", padding=True)
|
| 279 |
+
>>> input_ids = outputs.input_ids
|
| 280 |
+
>>> input_tokens = processor.tokenizer.batch_decode(input_ids)
|
| 281 |
+
>>> print(input_tokens)
|
| 282 |
+
['<|begin_of_text|><fake_token_around_image><global-img>((<image>)*169)<fake_token_around_image> In this image, we see', '<|reserved_special_token_0|><|reserved_special_token_0|><|reserved_special_token_0|><|begin_of_text|>bla bla bla<fake_token_around_image><global-img>((<image>)*169)<fake_token_around_image>']
|
| 283 |
+
```
|
| 284 |
+
|
| 285 |
+
Args:
|
| 286 |
+
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`, *optional*):
|
| 287 |
+
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
| 288 |
+
tensor. If is of type `list[ImageInput]`, it's assumed that this is for a single prompt i.e. of batch size 1.
|
| 289 |
+
text (`Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]]`, *optional*):
|
| 290 |
+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
|
| 291 |
+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
| 292 |
+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
| 293 |
+
Wherever an image token, `<image>` is encountered it is expanded to
|
| 294 |
+
`<fake_token_around_image>` + `<row_x_col_y>` + `<image>` * `image_seq_len` * <fake_token_around_image>`.
|
| 295 |
+
videos (`list[PIL.Image.Image]`, `np.ndarray`, `torch.Tensor`, `list[np.ndarray]`, `list[torch.Tensor]`, *optional*):
|
| 296 |
+
The video or batch of videos to be prepared. Each video can be a list of PIL frames, NumPy array or PyTorch
|
| 297 |
+
tensor. If is of type `list[VideoInput]`, it's assumed that this is for a single prompt i.e. of batch size 1.
|
| 298 |
+
return_tensors (`Union[str, TensorType]`, *optional*):
|
| 299 |
+
If set, will return tensors of a particular framework. See [`PreTrainedTokenizerFast.__call__`] for more
|
| 300 |
+
information.
|
| 301 |
+
"""
|
| 302 |
+
if text is None and images is None and videos is None:
|
| 303 |
+
raise ValueError("You must provide one of `text`, `images` or `videos'.")
|
| 304 |
+
|
| 305 |
+
if text is None and ((images is None) ^ (videos is not None)):
|
| 306 |
+
raise ValueError("You must specify exactly one of `images` or `videos`")
|
| 307 |
+
|
| 308 |
+
output_kwargs = self._merge_kwargs(
|
| 309 |
+
SmolVLMProcessorKwargs,
|
| 310 |
+
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
|
| 311 |
+
**kwargs,
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
if text is not None:
|
| 315 |
+
if isinstance(text, str):
|
| 316 |
+
text = [text]
|
| 317 |
+
elif not isinstance(text, list) and not isinstance(text[0], str):
|
| 318 |
+
raise ValueError("Invalid input text. Please provide a string, or a list of strings")
|
| 319 |
+
n_images_in_text = sum([sample.count(self.image_token) for sample in text])
|
| 320 |
+
if n_images_in_text > 0 and (images is None and videos is None):
|
| 321 |
+
raise ValueError(f"We detected {n_images_in_text} tokens in the text but no images/videos were passed")
|
| 322 |
+
|
| 323 |
+
inputs = {}
|
| 324 |
+
# Images and videos are mutually exclusive, so process one which is present
|
| 325 |
+
if images is not None:
|
| 326 |
+
images = self.image_processor.fetch_images(images)
|
| 327 |
+
images = make_nested_list_of_images(images)
|
| 328 |
+
vision_inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
|
| 329 |
+
|
| 330 |
+
image_rows = vision_inputs.pop("rows", None)
|
| 331 |
+
image_cols = vision_inputs.pop("cols", None)
|
| 332 |
+
inputs.update(vision_inputs)
|
| 333 |
+
|
| 334 |
+
if text is not None:
|
| 335 |
+
n_images_in_text = [sample.count(self.image_token) for sample in text]
|
| 336 |
+
n_images_in_images = [len(sublist) for sublist in images]
|
| 337 |
+
if n_images_in_images != n_images_in_text:
|
| 338 |
+
raise ValueError(
|
| 339 |
+
f"The number of images in the text {n_images_in_text} and images {n_images_in_images} should be the same."
|
| 340 |
+
)
|
| 341 |
+
text = self.expand_text_with_image_tokens(text, image_rows=image_rows, image_cols=image_cols)
|
| 342 |
+
|
| 343 |
+
elif videos is not None:
|
| 344 |
+
vision_inputs = self.video_processor(videos, **output_kwargs["videos_kwargs"])
|
| 345 |
+
if text is not None:
|
| 346 |
+
n_videos_in_text = [sample.count(self.video_token) for sample in text]
|
| 347 |
+
n_videos_in_videos = [len(sublist) for sublist in videos]
|
| 348 |
+
if n_videos_in_videos != n_videos_in_text:
|
| 349 |
+
raise ValueError(
|
| 350 |
+
f"The number of videos in the text {n_videos_in_text} and videos {n_videos_in_videos} should be the same."
|
| 351 |
+
)
|
| 352 |
+
text = self.expand_text_with_video_tokens(text, vision_inputs)
|
| 353 |
+
|
| 354 |
+
# If user has not requested video metadata, pop it. By default metadata
|
| 355 |
+
# is always returned to expand video tokens correctly
|
| 356 |
+
if "return_metadata" not in kwargs:
|
| 357 |
+
vision_inputs.pop("video_metadata")
|
| 358 |
+
inputs.update(vision_inputs)
|
| 359 |
+
|
| 360 |
+
return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
|
| 361 |
+
|
| 362 |
+
if text is not None:
|
| 363 |
+
text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
|
| 364 |
+
self._check_special_mm_tokens(text, text_inputs, modalities=["image"])
|
| 365 |
+
inputs.update(text_inputs)
|
| 366 |
+
|
| 367 |
+
return BatchFeature(inputs, tensor_type=return_tensors)
|
| 368 |
+
|
| 369 |
+
def apply_chat_template(
|
| 370 |
+
self,
|
| 371 |
+
conversation: Union[list[dict[str, str]], list[list[dict[str, str]]]],
|
| 372 |
+
chat_template: Optional[str] = None,
|
| 373 |
+
**kwargs: Unpack[AllKwargsForChatTemplate],
|
| 374 |
+
) -> str:
|
| 375 |
+
"""
|
| 376 |
+
Similar to the `apply_chat_template` method on tokenizers, this method applies a Jinja template to input
|
| 377 |
+
conversations to turn them into a single tokenizable string.
|
| 378 |
+
|
| 379 |
+
The input is expected to be in the following format, where each message content is a list consisting of text and
|
| 380 |
+
optionally image or video inputs. One can also provide an image, video, URL or local path which will be used to form
|
| 381 |
+
`pixel_values` when `return_dict=True`. If not provided, one will get only the formatted text, optionally tokenized text.
|
| 382 |
+
|
| 383 |
+
conversation = [
|
| 384 |
+
{
|
| 385 |
+
"role": "user",
|
| 386 |
+
"content": [
|
| 387 |
+
{"type": "image", "url": "https://www.ilankelman.org/stopsigns/australia.jpg"},
|
| 388 |
+
{"type": "text", "text": "Please describe this image in detail."},
|
| 389 |
+
],
|
| 390 |
+
},
|
| 391 |
+
]
|
| 392 |
+
|
| 393 |
+
Args:
|
| 394 |
+
conversation (`Union[list[Dict, [str, str]], list[list[dict[str, str]]]]`):
|
| 395 |
+
The conversation to format.
|
| 396 |
+
chat_template (`Optional[str]`, *optional*):
|
| 397 |
+
The Jinja template to use for formatting the conversation. If not provided, the tokenizer's
|
| 398 |
+
chat template is used.
|
| 399 |
+
"""
|
| 400 |
+
if isinstance(conversation, (list, tuple)) and (
|
| 401 |
+
isinstance(conversation[0], (list, tuple)) or hasattr(conversation[0], "content")
|
| 402 |
+
):
|
| 403 |
+
conversations = conversation
|
| 404 |
+
else:
|
| 405 |
+
conversations = [conversation]
|
| 406 |
+
|
| 407 |
+
has_video = any(
|
| 408 |
+
(isinstance(content, dict) and content["type"] == "video")
|
| 409 |
+
for conversation in conversations
|
| 410 |
+
for message in conversation
|
| 411 |
+
for content in message["content"]
|
| 412 |
+
)
|
| 413 |
+
if chat_template is None and has_video:
|
| 414 |
+
# re-assign to the correct default template for BC, if user is not requesting their own template
|
| 415 |
+
chat_template = DEFAULT_CHAT_TEMPLATE
|
| 416 |
+
|
| 417 |
+
kwargs.setdefault("num_frames", self.video_processor.num_frames)
|
| 418 |
+
kwargs.setdefault("fps", self.video_processor.fps)
|
| 419 |
+
|
| 420 |
+
return super().apply_chat_template(conversation, chat_template, **kwargs)
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
__all__ = ["SmolVLMProcessor"]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/smolvlm/video_processing_smolvlm.py
ADDED
|
@@ -0,0 +1,377 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
from typing import Optional, Union
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
from ...image_processing_utils import (
|
| 21 |
+
BatchFeature,
|
| 22 |
+
get_size_dict,
|
| 23 |
+
)
|
| 24 |
+
from ...image_utils import (
|
| 25 |
+
IMAGENET_STANDARD_MEAN,
|
| 26 |
+
IMAGENET_STANDARD_STD,
|
| 27 |
+
SizeDict,
|
| 28 |
+
)
|
| 29 |
+
from ...processing_utils import Unpack, VideosKwargs
|
| 30 |
+
from ...utils import (
|
| 31 |
+
TensorType,
|
| 32 |
+
is_torch_available,
|
| 33 |
+
is_torchvision_available,
|
| 34 |
+
is_torchvision_v2_available,
|
| 35 |
+
is_vision_available,
|
| 36 |
+
)
|
| 37 |
+
from ...utils.import_utils import requires
|
| 38 |
+
from ...video_processing_utils import (
|
| 39 |
+
BaseVideoProcessor,
|
| 40 |
+
)
|
| 41 |
+
from ...video_utils import VideoMetadata, group_videos_by_shape, reorder_videos
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
if is_vision_available():
|
| 45 |
+
from ...image_utils import PILImageResampling
|
| 46 |
+
|
| 47 |
+
if is_torchvision_available():
|
| 48 |
+
if is_torchvision_v2_available():
|
| 49 |
+
from torchvision.transforms.v2 import functional as F
|
| 50 |
+
else:
|
| 51 |
+
from torchvision.transforms import functional as F
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
if is_torch_available():
|
| 55 |
+
import torch
|
| 56 |
+
|
| 57 |
+
from ...utils import logging
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
logger = logging.get_logger(__name__)
|
| 61 |
+
|
| 62 |
+
DEFAULT_SYSTEM_MESSAGE = "You are a helpful language and vision assistant. You are able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
|
| 63 |
+
DEFAULT_VIDEO_INTRO = (
|
| 64 |
+
"You are provided the following series of {frame_count} frames from a {video_duration} [H:MM:SS] video.\n"
|
| 65 |
+
)
|
| 66 |
+
DEFAULT_MEDIA_OUTTRO = "\n\n"
|
| 67 |
+
FRAME_TIMESTAMP_MESSAGE = "\nFrame from {timestamp}:"
|
| 68 |
+
MAX_IMAGE_SIZE = 4096 # 4k resolution as absolute maximum
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def get_max_height_width(videos: list["torch.Tensor"]) -> list[int]:
|
| 72 |
+
"""
|
| 73 |
+
Get the maximum height and width across all videos in a batch.
|
| 74 |
+
"""
|
| 75 |
+
max_height = max_width = float("-inf")
|
| 76 |
+
for video in videos:
|
| 77 |
+
height, width = video.size()[-2:]
|
| 78 |
+
max_height = max(height, max_height)
|
| 79 |
+
max_width = max(width, max_width)
|
| 80 |
+
return (max_height, max_width)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def get_resize_output_image_size(
|
| 84 |
+
video,
|
| 85 |
+
resolution_max_side: int,
|
| 86 |
+
) -> tuple[int, int]:
|
| 87 |
+
"""
|
| 88 |
+
Get the output size of the video after resizing given a dictionary specifying the max and min sizes.
|
| 89 |
+
Args:
|
| 90 |
+
video (`np.ndarray`):
|
| 91 |
+
Video to resize.
|
| 92 |
+
resolution_max_side (`int`):
|
| 93 |
+
The longest edge of the video will be resized to this value. The shortest edge will be resized to keep the
|
| 94 |
+
input aspect ratio.
|
| 95 |
+
Returns:
|
| 96 |
+
The output size of the video after resizing.
|
| 97 |
+
"""
|
| 98 |
+
height, width = video.size()[-2:]
|
| 99 |
+
|
| 100 |
+
# Find the output size, when rescaling the longest edge to max_len and preserving the aspect ratio
|
| 101 |
+
# The output size must be below the MAX_IMAGE_SIZE
|
| 102 |
+
resolution_max_side = min(MAX_IMAGE_SIZE, resolution_max_side)
|
| 103 |
+
resolution_max_side = max(height, width) if resolution_max_side is None else resolution_max_side
|
| 104 |
+
aspect_ratio = width / height
|
| 105 |
+
|
| 106 |
+
if width >= height:
|
| 107 |
+
width = resolution_max_side
|
| 108 |
+
height = int(width / aspect_ratio)
|
| 109 |
+
if height % 2 != 0:
|
| 110 |
+
height += 1
|
| 111 |
+
elif height > width:
|
| 112 |
+
height = resolution_max_side
|
| 113 |
+
width = int(height * aspect_ratio)
|
| 114 |
+
if width % 2 != 0:
|
| 115 |
+
width += 1
|
| 116 |
+
|
| 117 |
+
height = max(height, 1)
|
| 118 |
+
width = max(width, 1)
|
| 119 |
+
|
| 120 |
+
return height, width
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
class SmolVLMVideoProcessorInitKwargs(VideosKwargs):
|
| 124 |
+
max_image_size: dict[str, int] = None
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
@requires(backends=("torchvision",))
|
| 128 |
+
class SmolVLMVideoProcessor(BaseVideoProcessor):
|
| 129 |
+
resample = PILImageResampling.LANCZOS
|
| 130 |
+
size = {"longest_edge": 4 * 364}
|
| 131 |
+
max_image_size = {"longest_edge": 364}
|
| 132 |
+
image_mean = IMAGENET_STANDARD_MEAN
|
| 133 |
+
image_std = IMAGENET_STANDARD_STD
|
| 134 |
+
do_resize = True
|
| 135 |
+
do_rescale = True
|
| 136 |
+
do_normalize = True
|
| 137 |
+
do_convert_rgb = True
|
| 138 |
+
do_pad = True
|
| 139 |
+
do_sample_frames = False # Set to False for BC, recommended to set `True` in new models
|
| 140 |
+
valid_kwargs = SmolVLMVideoProcessorInitKwargs
|
| 141 |
+
model_input_names = ["pixel_values", "pixel_attention_mask"]
|
| 142 |
+
|
| 143 |
+
def __init__(self, **kwargs: Unpack[SmolVLMVideoProcessorInitKwargs]):
|
| 144 |
+
super().__init__(**kwargs)
|
| 145 |
+
# For BC pop values from `config.video_sampling`. In official config `video_sampling` is guaranteed to be present
|
| 146 |
+
# We check for `Noneness` only for certain tests such as `test_init_without_params`
|
| 147 |
+
if "size" in kwargs and "video_sampling" in kwargs:
|
| 148 |
+
kwargs["video_sampling"]["video_size"] = kwargs["size"]
|
| 149 |
+
|
| 150 |
+
if "video_sampling" in kwargs:
|
| 151 |
+
self.num_frames = kwargs["video_sampling"]["max_frames"]
|
| 152 |
+
self.fps = kwargs["video_sampling"]["fps"]
|
| 153 |
+
self.size = get_size_dict(kwargs["video_sampling"]["video_size"], default_to_square=self.default_to_square)
|
| 154 |
+
|
| 155 |
+
def resize(
|
| 156 |
+
self,
|
| 157 |
+
video: "torch.Tensor",
|
| 158 |
+
size: SizeDict,
|
| 159 |
+
interpolation: "F.InterpolationMode" = None,
|
| 160 |
+
antialias: bool = True,
|
| 161 |
+
**kwargs,
|
| 162 |
+
) -> "torch.Tensor":
|
| 163 |
+
"""
|
| 164 |
+
Resize an video to `(size["height"], size["width"])`.
|
| 165 |
+
Args:
|
| 166 |
+
video (`torch.Tensor`):
|
| 167 |
+
Video to resize.
|
| 168 |
+
size (`SizeDict`):
|
| 169 |
+
Dictionary in the format `{"height": int, "width": int}` specifying the size of the output video.
|
| 170 |
+
resample (`InterpolationMode`, *optional*, defaults to `InterpolationMode.BILINEAR`):
|
| 171 |
+
`InterpolationMode` filter to use when resizing the video e.g. `InterpolationMode.BICUBIC`.
|
| 172 |
+
Returns:
|
| 173 |
+
`torch.Tensor`: The resized video.
|
| 174 |
+
"""
|
| 175 |
+
interpolation = interpolation if interpolation is not None else F.InterpolationMode.BILINEAR
|
| 176 |
+
if interpolation == F.InterpolationMode.LANCZOS:
|
| 177 |
+
logger.warning_once(
|
| 178 |
+
"You have used fast image processor with LANCZOS resample which not yet supported for torch.Tensor. "
|
| 179 |
+
"BICUBIC resample will be used as an alternative. Please fall back to image processor if you "
|
| 180 |
+
"want full consistency with the original model."
|
| 181 |
+
)
|
| 182 |
+
interpolation = F.InterpolationMode.BICUBIC
|
| 183 |
+
|
| 184 |
+
if size.longest_edge:
|
| 185 |
+
# Resize the image so that the shortest edge or the longest edge is of the given size
|
| 186 |
+
# while maintaining the aspect ratio of the original image.
|
| 187 |
+
new_size = get_resize_output_image_size(
|
| 188 |
+
video,
|
| 189 |
+
resolution_max_side=size.longest_edge,
|
| 190 |
+
)
|
| 191 |
+
elif size.height and size.width:
|
| 192 |
+
new_size = (size.height, size.width)
|
| 193 |
+
else:
|
| 194 |
+
raise ValueError(f"Size must contain 'height' and 'width' keys, or 'longest_edge' key. Got {size}.")
|
| 195 |
+
|
| 196 |
+
video = F.resize(video, new_size, interpolation=interpolation, antialias=antialias)
|
| 197 |
+
|
| 198 |
+
# Resize again to match image processor when `do_image_splitting=False`. Frames have to be squared to `max_image_size`
|
| 199 |
+
# NOTE: videos are always processoed without image splitting
|
| 200 |
+
max_size = self.max_image_size["longest_edge"], self.max_image_size["longest_edge"]
|
| 201 |
+
video = F.resize(video, max_size, interpolation=interpolation, antialias=antialias)
|
| 202 |
+
return video
|
| 203 |
+
|
| 204 |
+
def pad(
|
| 205 |
+
self,
|
| 206 |
+
video: "torch.Tensor",
|
| 207 |
+
padded_size: tuple[int, int],
|
| 208 |
+
max_num_frames: int,
|
| 209 |
+
fill: int = 0,
|
| 210 |
+
return_pixel_mask: bool = True,
|
| 211 |
+
):
|
| 212 |
+
"""Pads the sample with empty video to the padded_size
|
| 213 |
+
Args:
|
| 214 |
+
video (`torch.Tensor`):
|
| 215 |
+
Video to pad.
|
| 216 |
+
padded_size (`tuple[int, int]`):
|
| 217 |
+
Height and width to pad.
|
| 218 |
+
max_num_frames (`int`):
|
| 219 |
+
The maximum number of frames to which video will be padded.
|
| 220 |
+
fill (`int`, *optional*):
|
| 221 |
+
The value to use for the padding.
|
| 222 |
+
return_pixel_mask (`bool`, *optional*, defaults to `True`):
|
| 223 |
+
Whether to return a pixel mask.
|
| 224 |
+
"""
|
| 225 |
+
original_size = video.size()[-2:]
|
| 226 |
+
padding_height = padded_size[0] - original_size[0]
|
| 227 |
+
padding_width = padded_size[1] - original_size[1]
|
| 228 |
+
padding_frame = max_num_frames - video.shape[0]
|
| 229 |
+
if padding_width < 0 or padding_height < 0:
|
| 230 |
+
raise ValueError(
|
| 231 |
+
f"Padding dimensions are negative. Please make sure that the padded size is larger than the "
|
| 232 |
+
f"original size. Got padded size: {padded_size}, original size: {original_size}."
|
| 233 |
+
)
|
| 234 |
+
if original_size != padded_size:
|
| 235 |
+
padding = [0, padding_width, 0, padding_height, 0, 0, 0, padding_frame]
|
| 236 |
+
video = F.pad(video, padding, fill=fill)
|
| 237 |
+
|
| 238 |
+
# Make a pixel mask for the video, where 1 indicates a valid pixel and 0 indicates padding.
|
| 239 |
+
# Mask shape is (num_frames, height, width) so we omit the channel dim
|
| 240 |
+
pixel_mask = None
|
| 241 |
+
if return_pixel_mask:
|
| 242 |
+
pixel_mask = torch.zeros_like(video[..., 0, :, :], dtype=torch.int64)
|
| 243 |
+
pixel_mask[..., : original_size[0], : original_size[1]] = 1
|
| 244 |
+
|
| 245 |
+
return video, pixel_mask
|
| 246 |
+
|
| 247 |
+
def sample_frames(
|
| 248 |
+
self,
|
| 249 |
+
metadata: VideoMetadata,
|
| 250 |
+
num_frames: Optional[int] = None,
|
| 251 |
+
fps: Optional[Union[int, float]] = None,
|
| 252 |
+
skip_secs: Optional[int] = 1,
|
| 253 |
+
**kwargs,
|
| 254 |
+
):
|
| 255 |
+
"""
|
| 256 |
+
Video sampling function which:
|
| 257 |
+
- Uses `num_frames` (if provided) or calculates it from `fps` and metadata.
|
| 258 |
+
- Applies a basic center-skip if fewer frames than available, otherwise
|
| 259 |
+
optionally skips `skip_secs` from both the start and end.
|
| 260 |
+
- Uniformly samples the desired number of frames between the start and end indices.
|
| 261 |
+
|
| 262 |
+
Args:
|
| 263 |
+
metadata (`VideoMetadata`):
|
| 264 |
+
Metadata of the video containing information about total duration, fps and total number of frames.
|
| 265 |
+
num_frames (`int`, *optional*):
|
| 266 |
+
Maximum number of frames to sample. Defaults to `self.num_frames`.
|
| 267 |
+
fps (`int` or `float`, *optional*):
|
| 268 |
+
Target frames to sample per second. Defaults to `self.fps`.
|
| 269 |
+
skip_secs (`float`, *optional*, defaults to `1`):
|
| 270 |
+
Number of seconds to skip from the start and end if the video is long enough.
|
| 271 |
+
|
| 272 |
+
Returns:
|
| 273 |
+
np.ndarray:
|
| 274 |
+
Indices to sample video frames.
|
| 275 |
+
"""
|
| 276 |
+
if metadata is None or getattr(metadata, "fps", None) is None:
|
| 277 |
+
raise ValueError(
|
| 278 |
+
"Asked to sample frames per second but no video metadata was provided which is required when sampling in SmolVLM. "
|
| 279 |
+
"Please pass in `VideoMetadata` object or set `do_sample_frames=False`"
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
num_frames = num_frames if num_frames is not None else self.num_frames
|
| 283 |
+
fps = fps if fps is not None else self.fps
|
| 284 |
+
total_num_frames = metadata.total_num_frames
|
| 285 |
+
|
| 286 |
+
# Step 1) Estimate how many frames we'd sample at `target_fps`, fallback if target_fps <= 0
|
| 287 |
+
estimated_frames = int(round(fps * metadata["duration"]))
|
| 288 |
+
|
| 289 |
+
# Step 2) desired_frames
|
| 290 |
+
desired_frames = min(estimated_frames, num_frames)
|
| 291 |
+
if desired_frames < 1:
|
| 292 |
+
desired_frames = 1
|
| 293 |
+
|
| 294 |
+
# Step 3) center skip logic
|
| 295 |
+
start_idx = 0
|
| 296 |
+
end_idx = total_num_frames - 1
|
| 297 |
+
|
| 298 |
+
if skip_secs > 0 and (metadata["duration"] - 2 * skip_secs) > (num_frames * fps):
|
| 299 |
+
start_idx = int(skip_secs * metadata["fps"])
|
| 300 |
+
end_idx = int(total_num_frames - skip_secs * metadata["fps"])
|
| 301 |
+
|
| 302 |
+
start_idx = max(0, start_idx)
|
| 303 |
+
end_idx = min(end_idx, total_num_frames - 1)
|
| 304 |
+
if start_idx >= end_idx:
|
| 305 |
+
start_idx, end_idx = 0, total_num_frames - 1
|
| 306 |
+
|
| 307 |
+
indices = np.linspace(start_idx, end_idx, desired_frames, dtype=int)
|
| 308 |
+
indices = np.unique(indices)
|
| 309 |
+
|
| 310 |
+
return indices
|
| 311 |
+
|
| 312 |
+
def _preprocess(
|
| 313 |
+
self,
|
| 314 |
+
videos: list["torch.Tensor"],
|
| 315 |
+
do_convert_rgb: bool,
|
| 316 |
+
do_resize: bool,
|
| 317 |
+
size: SizeDict,
|
| 318 |
+
interpolation: Optional["F.InterpolationMode"],
|
| 319 |
+
do_rescale: bool,
|
| 320 |
+
rescale_factor: float,
|
| 321 |
+
do_normalize: bool,
|
| 322 |
+
do_pad: bool,
|
| 323 |
+
image_mean: Optional[Union[float, list[float]]],
|
| 324 |
+
image_std: Optional[Union[float, list[float]]],
|
| 325 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 326 |
+
**kwargs,
|
| 327 |
+
):
|
| 328 |
+
grouped_videos, grouped_videos_index = group_videos_by_shape(videos)
|
| 329 |
+
resized_videos_grouped = {}
|
| 330 |
+
for shape, stacked_videos in grouped_videos.items():
|
| 331 |
+
if do_convert_rgb:
|
| 332 |
+
stacked_videos = self.convert_to_rgb(stacked_videos)
|
| 333 |
+
if do_resize:
|
| 334 |
+
stacked_videos = self.resize(stacked_videos, size=size, interpolation=interpolation)
|
| 335 |
+
resized_videos_grouped[shape] = stacked_videos
|
| 336 |
+
resized_videos = reorder_videos(resized_videos_grouped, grouped_videos_index)
|
| 337 |
+
|
| 338 |
+
grouped_videos, grouped_videos_index = group_videos_by_shape(resized_videos)
|
| 339 |
+
processed_videos_grouped = {}
|
| 340 |
+
for shape, stacked_videos in grouped_videos.items():
|
| 341 |
+
stacked_videos = self.rescale_and_normalize(
|
| 342 |
+
stacked_videos, do_rescale, rescale_factor, do_normalize, image_mean, image_std
|
| 343 |
+
)
|
| 344 |
+
processed_videos_grouped[shape] = stacked_videos
|
| 345 |
+
|
| 346 |
+
processed_videos = reorder_videos(processed_videos_grouped, grouped_videos_index)
|
| 347 |
+
|
| 348 |
+
if do_pad:
|
| 349 |
+
pad_size = get_max_height_width(processed_videos)
|
| 350 |
+
max_num_frames = max(len(video) for video in processed_videos)
|
| 351 |
+
grouped_videos, grouped_videos_index = group_videos_by_shape(processed_videos)
|
| 352 |
+
processed_padded_mask_grouped = {}
|
| 353 |
+
processed_videos_grouped = {}
|
| 354 |
+
|
| 355 |
+
for shape, stacked_videos in grouped_videos.items():
|
| 356 |
+
stacked_videos, padded_masks = self.pad(
|
| 357 |
+
stacked_videos, padded_size=pad_size, max_num_frames=max_num_frames
|
| 358 |
+
)
|
| 359 |
+
processed_videos_grouped[shape] = stacked_videos
|
| 360 |
+
processed_padded_mask_grouped[shape] = padded_masks
|
| 361 |
+
|
| 362 |
+
processed_videos = reorder_videos(processed_videos_grouped, grouped_videos_index)
|
| 363 |
+
pixel_attention_mask = reorder_videos(processed_padded_mask_grouped, grouped_videos_index)
|
| 364 |
+
|
| 365 |
+
processed_videos = torch.stack(processed_videos, dim=0) if return_tensors else processed_videos
|
| 366 |
+
data = {"pixel_values": processed_videos}
|
| 367 |
+
|
| 368 |
+
if do_pad:
|
| 369 |
+
data["pixel_attention_mask"] = (
|
| 370 |
+
torch.stack(pixel_attention_mask, dim=0)
|
| 371 |
+
if do_pad and return_tensors is not None
|
| 372 |
+
else pixel_attention_mask
|
| 373 |
+
)
|
| 374 |
+
return BatchFeature(data, tensor_type=return_tensors)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
__all__ = ["SmolVLMVideoProcessor"]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speech_encoder_decoder/__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_speech_encoder_decoder import *
|
| 22 |
+
from .modeling_flax_speech_encoder_decoder import *
|
| 23 |
+
from .modeling_speech_encoder_decoder 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__)
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speech_encoder_decoder/configuration_speech_encoder_decoder.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
from ...configuration_utils import PretrainedConfig
|
| 19 |
+
from ...utils import logging
|
| 20 |
+
from ..auto.configuration_auto import AutoConfig
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class SpeechEncoderDecoderConfig(PretrainedConfig):
|
| 27 |
+
r"""
|
| 28 |
+
[`SpeechEncoderDecoderConfig`] is the configuration class to store the configuration of a
|
| 29 |
+
[`SpeechEncoderDecoderModel`]. It is used to instantiate an Encoder Decoder model according to the specified
|
| 30 |
+
arguments, defining the encoder and decoder configs.
|
| 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 |
+
Args:
|
| 36 |
+
kwargs (*optional*):
|
| 37 |
+
Dictionary of keyword arguments. Notably:
|
| 38 |
+
|
| 39 |
+
- **encoder** ([`PretrainedConfig`], *optional*) -- An instance of a configuration object that defines
|
| 40 |
+
the encoder config.
|
| 41 |
+
- **decoder** ([`PretrainedConfig`], *optional*) -- An instance of a configuration object that defines
|
| 42 |
+
the decoder config.
|
| 43 |
+
|
| 44 |
+
Examples:
|
| 45 |
+
|
| 46 |
+
```python
|
| 47 |
+
>>> from transformers import BertConfig, Wav2Vec2Config, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel
|
| 48 |
+
|
| 49 |
+
>>> # Initializing a Wav2Vec2 & BERT style configuration
|
| 50 |
+
>>> config_encoder = Wav2Vec2Config()
|
| 51 |
+
>>> config_decoder = BertConfig()
|
| 52 |
+
|
| 53 |
+
>>> config = SpeechEncoderDecoderConfig.from_encoder_decoder_configs(config_encoder, config_decoder)
|
| 54 |
+
|
| 55 |
+
>>> # Initializing a Wav2Vec2Bert model from a Wav2Vec2 & google-bert/bert-base-uncased style configurations
|
| 56 |
+
>>> model = SpeechEncoderDecoderModel(config=config)
|
| 57 |
+
|
| 58 |
+
>>> # Accessing the model configuration
|
| 59 |
+
>>> config_encoder = model.config.encoder
|
| 60 |
+
>>> config_decoder = model.config.decoder
|
| 61 |
+
>>> # set decoder config to causal lm
|
| 62 |
+
>>> config_decoder.is_decoder = True
|
| 63 |
+
>>> config_decoder.add_cross_attention = True
|
| 64 |
+
|
| 65 |
+
>>> # Saving the model, including its configuration
|
| 66 |
+
>>> model.save_pretrained("my-model")
|
| 67 |
+
|
| 68 |
+
>>> # loading model and config from pretrained folder
|
| 69 |
+
>>> encoder_decoder_config = SpeechEncoderDecoderConfig.from_pretrained("my-model")
|
| 70 |
+
>>> model = SpeechEncoderDecoderModel.from_pretrained("my-model", config=encoder_decoder_config)
|
| 71 |
+
```"""
|
| 72 |
+
|
| 73 |
+
model_type = "speech-encoder-decoder"
|
| 74 |
+
sub_configs = {"encoder": AutoConfig, "decoder": AutoConfig}
|
| 75 |
+
has_no_defaults_at_init = True
|
| 76 |
+
|
| 77 |
+
def __init__(self, **kwargs):
|
| 78 |
+
super().__init__(**kwargs)
|
| 79 |
+
if "encoder" not in kwargs or "decoder" not in kwargs:
|
| 80 |
+
raise ValueError(
|
| 81 |
+
f"A configuration of type {self.model_type} cannot be instantiated because not both `encoder` and"
|
| 82 |
+
f" `decoder` sub-configurations are passed, but only {kwargs}"
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
encoder_config = kwargs.pop("encoder")
|
| 86 |
+
encoder_model_type = encoder_config.pop("model_type")
|
| 87 |
+
decoder_config = kwargs.pop("decoder")
|
| 88 |
+
decoder_model_type = decoder_config.pop("model_type")
|
| 89 |
+
|
| 90 |
+
self.encoder = AutoConfig.for_model(encoder_model_type, **encoder_config)
|
| 91 |
+
self.decoder = AutoConfig.for_model(decoder_model_type, **decoder_config)
|
| 92 |
+
self.is_encoder_decoder = True
|
| 93 |
+
|
| 94 |
+
@classmethod
|
| 95 |
+
def from_encoder_decoder_configs(
|
| 96 |
+
cls, encoder_config: PretrainedConfig, decoder_config: PretrainedConfig, **kwargs
|
| 97 |
+
) -> PretrainedConfig:
|
| 98 |
+
r"""
|
| 99 |
+
Instantiate a [`SpeechEncoderDecoderConfig`] (or a derived class) from a pre-trained encoder model
|
| 100 |
+
configuration and decoder model configuration.
|
| 101 |
+
|
| 102 |
+
Returns:
|
| 103 |
+
[`SpeechEncoderDecoderConfig`]: An instance of a configuration object
|
| 104 |
+
"""
|
| 105 |
+
logger.info("Setting `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config")
|
| 106 |
+
decoder_config.is_decoder = True
|
| 107 |
+
decoder_config.add_cross_attention = True
|
| 108 |
+
|
| 109 |
+
return cls(encoder=encoder_config.to_dict(), decoder=decoder_config.to_dict(), **kwargs)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
__all__ = ["SpeechEncoderDecoderConfig"]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speech_encoder_decoder/modeling_flax_speech_encoder_decoder.py
ADDED
|
@@ -0,0 +1,930 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Classes to support Flax Speech-Encoder-Decoder architectures"""
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
from typing import Optional, Union
|
| 19 |
+
|
| 20 |
+
import flax.linen as nn
|
| 21 |
+
import jax
|
| 22 |
+
import jax.numpy as jnp
|
| 23 |
+
from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
|
| 24 |
+
from flax.traverse_util import flatten_dict, unflatten_dict
|
| 25 |
+
from jax import lax
|
| 26 |
+
from jax.random import PRNGKey
|
| 27 |
+
|
| 28 |
+
from ...modeling_flax_outputs import FlaxBaseModelOutput, FlaxCausalLMOutputWithCrossAttentions, FlaxSeq2SeqLMOutput
|
| 29 |
+
from ...modeling_flax_utils import FlaxPreTrainedModel
|
| 30 |
+
from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
|
| 31 |
+
from ..auto.configuration_auto import AutoConfig
|
| 32 |
+
from ..auto.modeling_flax_auto import FlaxAutoModel, FlaxAutoModelForCausalLM
|
| 33 |
+
from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
logger = logging.get_logger(__name__)
|
| 37 |
+
|
| 38 |
+
_CONFIG_FOR_DOC = "SpeechEncoderDecoderConfig"
|
| 39 |
+
|
| 40 |
+
SPEECH_ENCODER_DECODER_START_DOCSTRING = r"""
|
| 41 |
+
This class can be used to initialize a speech-sequence-to-text-sequence model with any pretrained speech
|
| 42 |
+
autoencoding model as the encoder and any pretrained text autoregressive model as the decoder. The encoder is
|
| 43 |
+
loaded via [`~AutoModel.from_pretrained`] function and the decoder is loaded via
|
| 44 |
+
[`~AutoModelForCausalLM.from_pretrained`] function. Cross-attention layers are automatically added to the decoder
|
| 45 |
+
and should be fine-tuned on a downstream generative task, like summarization.
|
| 46 |
+
|
| 47 |
+
The effectiveness of initializing sequence-to-sequence models with pretrained checkpoints for sequence generation
|
| 48 |
+
tasks was shown in [Leveraging Pre-trained Checkpoints for Sequence Generation
|
| 49 |
+
Tasks](https://huggingface.co/papers/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn. Michael Matena, Yanqi
|
| 50 |
+
Zhou, Wei Li, Peter J. Liu.
|
| 51 |
+
|
| 52 |
+
Additionally, in [Large-Scale Self- and Semi-Supervised Learning for Speech
|
| 53 |
+
Translation](https://huggingface.co/papers/2104.06678) it is shown how leveraging large pretrained speech models for speech
|
| 54 |
+
translation yields a significant performance improvement.
|
| 55 |
+
|
| 56 |
+
After such an Speech-Encoder Decoder model has been trained/fine-tuned, it can be saved/loaded just like any other
|
| 57 |
+
models (see the examples for more information).
|
| 58 |
+
|
| 59 |
+
This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 60 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 61 |
+
etc.)
|
| 62 |
+
|
| 63 |
+
This model is also a Flax Linen
|
| 64 |
+
[flax.nn.Module](https://flax.readthedocs.io/en/latest/_autosummary/flax.nn.module.html) subclass. Use it as a
|
| 65 |
+
regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior.
|
| 66 |
+
|
| 67 |
+
Parameters:
|
| 68 |
+
config ([`SpeechEncoderDecoderConfig`]): Model configuration class with all the parameters of the model.
|
| 69 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 70 |
+
configuration. Check out the [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
|
| 71 |
+
dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
|
| 72 |
+
The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
|
| 73 |
+
`jax.numpy.bfloat16` (on TPUs).
|
| 74 |
+
|
| 75 |
+
This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
|
| 76 |
+
specified all the computation will be performed with the given `dtype`.
|
| 77 |
+
|
| 78 |
+
**Note that this only specifies the dtype of the computation and does not influence the dtype of model
|
| 79 |
+
parameters.**
|
| 80 |
+
|
| 81 |
+
If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
|
| 82 |
+
[`~FlaxPreTrainedModel.to_bf16`].
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
SPEECH_ENCODER_DECODER_INPUTS_DOCSTRING = r"""
|
| 86 |
+
Args:
|
| 87 |
+
inputs (`jnp.ndarray` of shape `(batch_size, sequence_length)` or `(batch_size, sequence_length, feature_dim)`, *optional*):
|
| 88 |
+
Float values of input raw speech waveform or speech features. Values can be obtained by loading a `.flac`
|
| 89 |
+
or `.wav` audio file into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.*
|
| 90 |
+
via the torchcodec library (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
|
| 91 |
+
To prepare the array into `inputs`, either the [`Wav2Vec2Processor`] or
|
| 92 |
+
[`Speech2TextProcessor`] should be used for padding and conversion into a tensor of type
|
| 93 |
+
`torch.FloatTensor`.
|
| 94 |
+
attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
| 95 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 96 |
+
|
| 97 |
+
- 1 for tokens that are **not masked**,
|
| 98 |
+
- 0 for tokens that are **masked**.
|
| 99 |
+
|
| 100 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 101 |
+
decoder_input_ids (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 102 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 103 |
+
|
| 104 |
+
Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 105 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 106 |
+
|
| 107 |
+
[What are input IDs?](../glossary#input-ids)
|
| 108 |
+
|
| 109 |
+
If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
| 110 |
+
`past_key_values`).
|
| 111 |
+
|
| 112 |
+
For sequence to sequence training, `decoder_input_ids` should be provided. `decoder_input_ids` should be
|
| 113 |
+
created outside of the model by shifting the `labels` to the right, replacing -100 by the `pad_token_id`
|
| 114 |
+
and prepending them with the `decoder_start_token_id`.
|
| 115 |
+
decoder_attention_mask (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 116 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 117 |
+
be used by default.
|
| 118 |
+
decoder_position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
| 119 |
+
Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
|
| 120 |
+
range `[0, config.decoder.max_position_embeddings - 1]`.
|
| 121 |
+
output_hidden_states (`bool`, *optional*):
|
| 122 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 123 |
+
more detail.
|
| 124 |
+
return_dict (`bool`, *optional*):
|
| 125 |
+
If set to `True`, the model will return a [`~utils.FlaxSeq2SeqLMOutput`] instead of a plain tuple.
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
SPEECH_ENCODER_DECODER_ENCODE_INPUTS_DOCSTRING = r"""
|
| 129 |
+
Args:
|
| 130 |
+
inputs (`jnp.ndarray` of shape `(batch_size, sequence_length)` or `(batch_size, sequence_length, feature_dim)`, *optional*):
|
| 131 |
+
Float values of input raw speech waveform or speech features. Values can be obtained by loading a *.flac*
|
| 132 |
+
or *.wav* audio file into an array of type *list[float]* or a *numpy.ndarray*, *e.g.* via the torchcodec library
|
| 133 |
+
(`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
|
| 134 |
+
To prepare the array into *inputs*, either the [`Wav2Vec2Processor`] or [`Speech2TextProcessor`] should be used
|
| 135 |
+
for padding and conversion into a tensor of type *torch.FloatTensor*.
|
| 136 |
+
attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
| 137 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 138 |
+
|
| 139 |
+
- 1 for tokens that are **not masked**,
|
| 140 |
+
- 0 for tokens that are **masked**.
|
| 141 |
+
|
| 142 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 143 |
+
output_attentions (`bool`, *optional*):
|
| 144 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 145 |
+
tensors for more detail.
|
| 146 |
+
output_hidden_states (`bool`, *optional*):
|
| 147 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 148 |
+
more detail.
|
| 149 |
+
return_dict (`bool`, *optional*):
|
| 150 |
+
If set to `True`, the model will return a [`~utils.FlaxBaseModelOutput`] instead of a plain tuple.
|
| 151 |
+
"""
|
| 152 |
+
|
| 153 |
+
SPEECH_ENCODER_DECODER_DECODE_INPUTS_DOCSTRING = r"""
|
| 154 |
+
Args:
|
| 155 |
+
decoder_input_ids (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 156 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 157 |
+
|
| 158 |
+
Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 159 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 160 |
+
|
| 161 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 162 |
+
|
| 163 |
+
If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
| 164 |
+
`past_key_values`).
|
| 165 |
+
|
| 166 |
+
For sequence to sequence training, `decoder_input_ids` should be provided. `decoder_input_ids` should be
|
| 167 |
+
created outside of the model by shifting the `labels` to the right, replacing -100 by the `pad_token_id`
|
| 168 |
+
and prepending them with the `decoder_start_token_id`.
|
| 169 |
+
encoder_outputs (`tuple(tuple(jnp.ndarray)`):
|
| 170 |
+
Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
|
| 171 |
+
`last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
|
| 172 |
+
hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
|
| 173 |
+
encoder_attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
| 174 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 175 |
+
|
| 176 |
+
- 1 for tokens that are **not masked**,
|
| 177 |
+
- 0 for tokens that are **masked**.
|
| 178 |
+
|
| 179 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 180 |
+
decoder_attention_mask (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 181 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 182 |
+
be used by default.
|
| 183 |
+
decoder_position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
| 184 |
+
Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
|
| 185 |
+
range `[0, config.decoder.max_position_embeddings - 1]`.
|
| 186 |
+
past_key_values (`dict[str, np.ndarray]`, *optional*, returned by `init_cache` or when passing previous `past_key_values`):
|
| 187 |
+
Dictionary of pre-computed hidden-states (key and values in the attention blocks) that can be used for fast
|
| 188 |
+
auto-regressive decoding. Pre-computed key and value hidden-states are of shape *[batch_size, max_length]*.
|
| 189 |
+
output_attentions (`bool`, *optional*):
|
| 190 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 191 |
+
tensors for more detail.
|
| 192 |
+
output_hidden_states (`bool`, *optional*):
|
| 193 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 194 |
+
more detail.
|
| 195 |
+
return_dict (`bool`, *optional*):
|
| 196 |
+
If set to `True`, the model will return a [`~utils.FlaxCausalLMOutputWithCrossAttentions`] instead of a
|
| 197 |
+
plain tuple.
|
| 198 |
+
"""
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
class FlaxSpeechEncoderDecoderModule(nn.Module):
|
| 202 |
+
config: SpeechEncoderDecoderConfig
|
| 203 |
+
dtype: jnp.dtype = jnp.float32
|
| 204 |
+
|
| 205 |
+
def setup(self):
|
| 206 |
+
encoder_config = self.config.encoder
|
| 207 |
+
decoder_config = self.config.decoder
|
| 208 |
+
|
| 209 |
+
# Copied from `modeling_hybrid_clip.py` with modifications.
|
| 210 |
+
from ...models.auto.modeling_flax_auto import FLAX_MODEL_FOR_CAUSAL_LM_MAPPING, FLAX_MODEL_MAPPING
|
| 211 |
+
|
| 212 |
+
encoder_module = FLAX_MODEL_MAPPING[encoder_config.__class__].module_class
|
| 213 |
+
decoder_module = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING[decoder_config.__class__].module_class
|
| 214 |
+
|
| 215 |
+
self.encoder = encoder_module(encoder_config, dtype=self.dtype)
|
| 216 |
+
self.decoder = decoder_module(decoder_config, dtype=self.dtype)
|
| 217 |
+
|
| 218 |
+
# encoder outputs might need to be projected to different dimension for decoder
|
| 219 |
+
if (
|
| 220 |
+
self.encoder.config.hidden_size != self.decoder.config.hidden_size
|
| 221 |
+
and self.decoder.config.cross_attention_hidden_size is None
|
| 222 |
+
):
|
| 223 |
+
self.enc_to_dec_proj = nn.Dense(
|
| 224 |
+
self.decoder.config.hidden_size,
|
| 225 |
+
kernel_init=jax.nn.initializers.normal(self.decoder.config.initializer_range),
|
| 226 |
+
dtype=self.dtype,
|
| 227 |
+
)
|
| 228 |
+
else:
|
| 229 |
+
self.enc_to_dec_proj = None
|
| 230 |
+
|
| 231 |
+
def _get_feat_extract_output_lengths(
|
| 232 |
+
self, input_lengths: Union[jnp.ndarray, int], add_adapter: Optional[bool] = None
|
| 233 |
+
):
|
| 234 |
+
"""
|
| 235 |
+
Computes the output length of the convolutional layers
|
| 236 |
+
"""
|
| 237 |
+
|
| 238 |
+
add_adapter = self.config.encoder.add_adapter if add_adapter is None else add_adapter
|
| 239 |
+
|
| 240 |
+
def _conv_out_length(input_length, kernel_size, stride):
|
| 241 |
+
# 1D convolutional layer output length formula taken
|
| 242 |
+
# from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
|
| 243 |
+
return (input_length - kernel_size) // stride + 1
|
| 244 |
+
|
| 245 |
+
for kernel_size, stride in zip(self.config.encoder.conv_kernel, self.config.encoder.conv_stride):
|
| 246 |
+
input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
|
| 247 |
+
|
| 248 |
+
if add_adapter:
|
| 249 |
+
for _ in range(self.config.encoder.num_adapter_layers):
|
| 250 |
+
input_lengths = _conv_out_length(input_lengths, 1, self.config.encoder.adapter_stride)
|
| 251 |
+
|
| 252 |
+
return input_lengths
|
| 253 |
+
|
| 254 |
+
def _get_encoder_module(self):
|
| 255 |
+
return self.encoder
|
| 256 |
+
|
| 257 |
+
def _get_projection_module(self):
|
| 258 |
+
return self.enc_to_dec_proj
|
| 259 |
+
|
| 260 |
+
def _get_decoder_module(self):
|
| 261 |
+
return self.decoder
|
| 262 |
+
|
| 263 |
+
def __call__(
|
| 264 |
+
self,
|
| 265 |
+
inputs,
|
| 266 |
+
attention_mask,
|
| 267 |
+
decoder_input_ids,
|
| 268 |
+
decoder_attention_mask,
|
| 269 |
+
decoder_position_ids,
|
| 270 |
+
encoder_outputs=None,
|
| 271 |
+
output_attentions: bool = False,
|
| 272 |
+
output_hidden_states: bool = False,
|
| 273 |
+
return_dict: bool = True,
|
| 274 |
+
deterministic: bool = True,
|
| 275 |
+
freeze_feature_encoder: bool = False,
|
| 276 |
+
):
|
| 277 |
+
if encoder_outputs is None:
|
| 278 |
+
encoder_outputs = self.encoder(
|
| 279 |
+
inputs,
|
| 280 |
+
attention_mask=attention_mask,
|
| 281 |
+
output_attentions=output_attentions,
|
| 282 |
+
output_hidden_states=output_hidden_states,
|
| 283 |
+
return_dict=return_dict,
|
| 284 |
+
deterministic=deterministic,
|
| 285 |
+
freeze_feature_encoder=freeze_feature_encoder,
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
encoder_hidden_states = encoder_outputs[0]
|
| 289 |
+
|
| 290 |
+
# optionally project encoder_hidden_states
|
| 291 |
+
if self.enc_to_dec_proj is not None:
|
| 292 |
+
encoder_hidden_states = self.enc_to_dec_proj(encoder_hidden_states)
|
| 293 |
+
|
| 294 |
+
# compute correct encoder attention mask
|
| 295 |
+
if attention_mask is not None:
|
| 296 |
+
encoder_attention_mask = self.encoder._get_feature_vector_attention_mask(
|
| 297 |
+
encoder_hidden_states.shape[1], attention_mask
|
| 298 |
+
)
|
| 299 |
+
else:
|
| 300 |
+
encoder_attention_mask = None
|
| 301 |
+
|
| 302 |
+
# flax script modeling_flax_wav2vec2.py
|
| 303 |
+
decoder_outputs = self.decoder(
|
| 304 |
+
input_ids=decoder_input_ids,
|
| 305 |
+
attention_mask=decoder_attention_mask,
|
| 306 |
+
position_ids=decoder_position_ids,
|
| 307 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 308 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 309 |
+
output_attentions=output_attentions,
|
| 310 |
+
output_hidden_states=output_hidden_states,
|
| 311 |
+
return_dict=return_dict,
|
| 312 |
+
deterministic=deterministic,
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
if not return_dict:
|
| 316 |
+
return decoder_outputs + encoder_outputs
|
| 317 |
+
|
| 318 |
+
return FlaxSeq2SeqLMOutput(
|
| 319 |
+
logits=decoder_outputs.logits,
|
| 320 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 321 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 322 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 323 |
+
encoder_last_hidden_state=encoder_hidden_states,
|
| 324 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 325 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
@add_start_docstrings(SPEECH_ENCODER_DECODER_START_DOCSTRING)
|
| 330 |
+
class FlaxSpeechEncoderDecoderModel(FlaxPreTrainedModel):
|
| 331 |
+
r"""
|
| 332 |
+
[`FlaxSpeechEncoderDecoderModel`] is a generic model class that will be instantiated as a transformer architecture
|
| 333 |
+
with the module (flax.nn.Module) of one of the base model classes of the library as encoder module and another one
|
| 334 |
+
as decoder module when created with the :meth*~transformers.FlaxAutoModel.from_pretrained* class method for the
|
| 335 |
+
encoder and :meth*~transformers.FlaxAutoModelForCausalLM.from_pretrained* class method for the decoder.
|
| 336 |
+
"""
|
| 337 |
+
|
| 338 |
+
config_class = SpeechEncoderDecoderConfig
|
| 339 |
+
base_model_prefix: str = "speech_encoder_decoder"
|
| 340 |
+
module_class = FlaxSpeechEncoderDecoderModule
|
| 341 |
+
|
| 342 |
+
def __init__(
|
| 343 |
+
self,
|
| 344 |
+
config: SpeechEncoderDecoderConfig,
|
| 345 |
+
input_shape: Optional[tuple] = None,
|
| 346 |
+
seed: int = 0,
|
| 347 |
+
dtype: jnp.dtype = jnp.float32,
|
| 348 |
+
_do_init: bool = True,
|
| 349 |
+
**kwargs,
|
| 350 |
+
):
|
| 351 |
+
if not _do_init:
|
| 352 |
+
raise ValueError(
|
| 353 |
+
"`FlaxSpeechEncoderDecoderModel` cannot be created without initializing, `_do_init` must be `True`."
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
if config.decoder.cross_attention_hidden_size is not None:
|
| 357 |
+
# Raise ValueError or option to project enc to dec hidden_size (eg EncAdapterLayer)
|
| 358 |
+
if config.decoder.cross_attention_hidden_size != config.encoder.hidden_size:
|
| 359 |
+
raise ValueError(
|
| 360 |
+
"If `cross_attention_hidden_size` is specified in the decoder's configuration, it has to be equal"
|
| 361 |
+
f" to the encoder's `hidden_size`. Got {config.decoder.cross_attention_hidden_size} for"
|
| 362 |
+
f" `config.decoder.cross_attention_hidden_size` and {config.encoder.hidden_size} for"
|
| 363 |
+
" `config.encoder.hidden_size`."
|
| 364 |
+
)
|
| 365 |
+
|
| 366 |
+
# make sure input & output embeddings are not tied
|
| 367 |
+
config.tie_word_embeddings = False
|
| 368 |
+
module = self.module_class(config=config, dtype=dtype, **kwargs)
|
| 369 |
+
|
| 370 |
+
if input_shape is None:
|
| 371 |
+
# speech encoders almost always downsample the sequence length dimension
|
| 372 |
+
encoder_input_length = 1024
|
| 373 |
+
decoder_input_length = module._get_feat_extract_output_lengths(encoder_input_length)
|
| 374 |
+
input_shape = ((1, encoder_input_length), (1, decoder_input_length))
|
| 375 |
+
|
| 376 |
+
super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
|
| 377 |
+
|
| 378 |
+
def init_weights(self, rng: jax.random.PRNGKey, input_shape: tuple, params: FrozenDict = None) -> FrozenDict:
|
| 379 |
+
encoder_input_shape, decoder_input_shape = input_shape
|
| 380 |
+
|
| 381 |
+
# init input DeviceArrays
|
| 382 |
+
inputs = jnp.zeros(encoder_input_shape, dtype="f4")
|
| 383 |
+
attention_mask = jnp.ones_like(inputs, dtype="i4")
|
| 384 |
+
decoder_input_ids = jnp.zeros(decoder_input_shape, dtype="i4")
|
| 385 |
+
decoder_attention_mask = jnp.ones_like(decoder_input_ids)
|
| 386 |
+
|
| 387 |
+
batch_size, sequence_length = inputs.shape
|
| 388 |
+
|
| 389 |
+
decoder_batch_size, decoder_sequence_length = decoder_input_ids.shape
|
| 390 |
+
if not decoder_batch_size == batch_size:
|
| 391 |
+
raise ValueError(
|
| 392 |
+
f"The inputs of encoder and decoder should have the same batch size, but got {batch_size} for encoder"
|
| 393 |
+
f" and {decoder_batch_size} for decoder."
|
| 394 |
+
)
|
| 395 |
+
decoder_position_ids = jnp.broadcast_to(
|
| 396 |
+
jnp.arange(decoder_sequence_length)[None, :], (decoder_batch_size, decoder_sequence_length)
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
params_rng, dropout_rng = jax.random.split(rng)
|
| 400 |
+
rngs = {"params": params_rng, "dropout": dropout_rng}
|
| 401 |
+
|
| 402 |
+
random_params = self.module.init(
|
| 403 |
+
rngs,
|
| 404 |
+
inputs,
|
| 405 |
+
attention_mask,
|
| 406 |
+
decoder_input_ids,
|
| 407 |
+
decoder_attention_mask,
|
| 408 |
+
decoder_position_ids,
|
| 409 |
+
)["params"]
|
| 410 |
+
|
| 411 |
+
if params is not None:
|
| 412 |
+
random_params = flatten_dict(unfreeze(random_params))
|
| 413 |
+
params = flatten_dict(unfreeze(params))
|
| 414 |
+
for missing_key in self._missing_keys:
|
| 415 |
+
params[missing_key] = random_params[missing_key]
|
| 416 |
+
self._missing_keys = set()
|
| 417 |
+
return freeze(unflatten_dict(params))
|
| 418 |
+
else:
|
| 419 |
+
return random_params
|
| 420 |
+
|
| 421 |
+
def init_cache(self, batch_size, max_length, encoder_outputs):
|
| 422 |
+
r"""
|
| 423 |
+
Args:
|
| 424 |
+
batch_size (`int`):
|
| 425 |
+
batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
|
| 426 |
+
max_length (`int`):
|
| 427 |
+
maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
|
| 428 |
+
cache.
|
| 429 |
+
encoder_outputs (`Union[FlaxBaseModelOutput, tuple(tuple(jnp.ndarray)]`):
|
| 430 |
+
`encoder_outputs` consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*:
|
| 431 |
+
`attentions`). `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*)
|
| 432 |
+
is a sequence of hidden-states at the output of the last layer of the encoder. Used in the
|
| 433 |
+
cross-attention of the decoder.
|
| 434 |
+
"""
|
| 435 |
+
# init input variables to retrieve cache
|
| 436 |
+
decoder_input_ids = jnp.ones((batch_size, max_length), dtype="i4")
|
| 437 |
+
decoder_attention_mask = jnp.ones_like(decoder_input_ids)
|
| 438 |
+
decoder_position_ids = jnp.broadcast_to(
|
| 439 |
+
jnp.arange(jnp.atleast_2d(decoder_input_ids).shape[-1]), decoder_input_ids.shape
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs):
|
| 443 |
+
decoder_module = module._get_decoder_module()
|
| 444 |
+
return decoder_module(
|
| 445 |
+
input_ids=decoder_input_ids,
|
| 446 |
+
attention_mask=decoder_attention_mask,
|
| 447 |
+
position_ids=decoder_position_ids,
|
| 448 |
+
**kwargs,
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
init_variables = self.module.init(
|
| 452 |
+
jax.random.PRNGKey(0),
|
| 453 |
+
decoder_input_ids=decoder_input_ids,
|
| 454 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 455 |
+
decoder_position_ids=decoder_position_ids,
|
| 456 |
+
encoder_hidden_states=encoder_outputs[0],
|
| 457 |
+
init_cache=True,
|
| 458 |
+
method=_decoder_forward, # we only need to call the decoder to init the cache
|
| 459 |
+
)
|
| 460 |
+
return unfreeze(init_variables["cache"])
|
| 461 |
+
|
| 462 |
+
def _get_feat_extract_output_lengths(
|
| 463 |
+
self, input_lengths: Union[jnp.ndarray, int], add_adapter: Optional[bool] = None
|
| 464 |
+
):
|
| 465 |
+
return self.module._get_feat_extract_output_lengths(input_lengths, add_adapter=add_adapter)
|
| 466 |
+
|
| 467 |
+
@add_start_docstrings(SPEECH_ENCODER_DECODER_ENCODE_INPUTS_DOCSTRING)
|
| 468 |
+
@replace_return_docstrings(output_type=FlaxBaseModelOutput, config_class=_CONFIG_FOR_DOC)
|
| 469 |
+
def encode(
|
| 470 |
+
self,
|
| 471 |
+
inputs: jnp.ndarray,
|
| 472 |
+
attention_mask: Optional[jnp.ndarray] = None,
|
| 473 |
+
output_attentions: Optional[bool] = None,
|
| 474 |
+
output_hidden_states: Optional[bool] = None,
|
| 475 |
+
return_dict: Optional[bool] = None,
|
| 476 |
+
train: bool = False,
|
| 477 |
+
freeze_feature_encoder: bool = False,
|
| 478 |
+
params: Optional[dict] = None,
|
| 479 |
+
dropout_rng: PRNGKey = None,
|
| 480 |
+
):
|
| 481 |
+
r"""
|
| 482 |
+
Returns:
|
| 483 |
+
|
| 484 |
+
Example:
|
| 485 |
+
|
| 486 |
+
```python
|
| 487 |
+
>>> from transformers import FlaxSpeechEncoderDecoderModel
|
| 488 |
+
|
| 489 |
+
>>> # initialize a wav2vec2-2-bart from pretrained wav2vec2 and bart models. Note that the cross-attention layers will be randomly initialized
|
| 490 |
+
>>> model = FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained(
|
| 491 |
+
... "facebook/wav2vec2-large-lv60", "facebook/bart-large"
|
| 492 |
+
... )
|
| 493 |
+
|
| 494 |
+
>>> inputs = jnp.ones((2, 5000), dtype=jnp.float32)
|
| 495 |
+
>>> encoder_outputs = model.encode(inputs)
|
| 496 |
+
```"""
|
| 497 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 498 |
+
output_hidden_states = (
|
| 499 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 500 |
+
)
|
| 501 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 502 |
+
|
| 503 |
+
if attention_mask is None:
|
| 504 |
+
attention_mask = jnp.ones_like(inputs, dtype="i4")
|
| 505 |
+
|
| 506 |
+
# Handle any PRNG if needed
|
| 507 |
+
rngs = {}
|
| 508 |
+
if dropout_rng is not None:
|
| 509 |
+
rngs["dropout"] = dropout_rng
|
| 510 |
+
|
| 511 |
+
def _encoder_forward(module, inputs, attention_mask, **kwargs):
|
| 512 |
+
encode_module = module._get_encoder_module()
|
| 513 |
+
return encode_module(inputs, attention_mask, **kwargs)
|
| 514 |
+
|
| 515 |
+
outputs = self.module.apply(
|
| 516 |
+
{"params": params or self.params},
|
| 517 |
+
inputs=jnp.array(inputs, dtype="f4"),
|
| 518 |
+
attention_mask=jnp.array(attention_mask, dtype="i4"),
|
| 519 |
+
output_attentions=output_attentions,
|
| 520 |
+
output_hidden_states=output_hidden_states,
|
| 521 |
+
return_dict=return_dict,
|
| 522 |
+
deterministic=not train,
|
| 523 |
+
freeze_feature_encoder=freeze_feature_encoder,
|
| 524 |
+
rngs=rngs,
|
| 525 |
+
method=_encoder_forward,
|
| 526 |
+
)
|
| 527 |
+
|
| 528 |
+
if return_dict:
|
| 529 |
+
outputs = FlaxBaseModelOutput(
|
| 530 |
+
last_hidden_state=outputs.last_hidden_state,
|
| 531 |
+
hidden_states=outputs.hidden_states,
|
| 532 |
+
attentions=outputs.attentions,
|
| 533 |
+
)
|
| 534 |
+
|
| 535 |
+
return outputs
|
| 536 |
+
|
| 537 |
+
@add_start_docstrings(SPEECH_ENCODER_DECODER_DECODE_INPUTS_DOCSTRING)
|
| 538 |
+
@replace_return_docstrings(output_type=FlaxCausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)
|
| 539 |
+
def decode(
|
| 540 |
+
self,
|
| 541 |
+
decoder_input_ids,
|
| 542 |
+
encoder_outputs,
|
| 543 |
+
encoder_attention_mask: Optional[jnp.ndarray] = None,
|
| 544 |
+
decoder_attention_mask: Optional[jnp.ndarray] = None,
|
| 545 |
+
decoder_position_ids: Optional[jnp.ndarray] = None,
|
| 546 |
+
past_key_values: Optional[dict] = None,
|
| 547 |
+
output_attentions: Optional[bool] = None,
|
| 548 |
+
output_hidden_states: Optional[bool] = None,
|
| 549 |
+
return_dict: Optional[bool] = None,
|
| 550 |
+
train: bool = False,
|
| 551 |
+
params: Optional[dict] = None,
|
| 552 |
+
dropout_rng: PRNGKey = None,
|
| 553 |
+
):
|
| 554 |
+
r"""
|
| 555 |
+
Returns:
|
| 556 |
+
|
| 557 |
+
Example:
|
| 558 |
+
|
| 559 |
+
```python
|
| 560 |
+
>>> from transformers import FlaxSpeechEncoderDecoderModel
|
| 561 |
+
>>> import jax.numpy as jnp
|
| 562 |
+
|
| 563 |
+
>>> # initialize a wav2vec2-2-bart from pretrained wav2vec2 and bart models. Note that the cross-attention layers will be randomly initialized
|
| 564 |
+
>>> model = FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained(
|
| 565 |
+
... "facebook/wav2vec2-large-lv60", "facebook/bart-large"
|
| 566 |
+
... )
|
| 567 |
+
|
| 568 |
+
>>> inputs = jnp.ones((2, 5000), dtype=jnp.float32)
|
| 569 |
+
>>> encoder_outputs = model.encode(inputs)
|
| 570 |
+
|
| 571 |
+
>>> decoder_start_token_id = model.config.decoder.bos_token_id
|
| 572 |
+
>>> decoder_input_ids = jnp.ones((inputs.shape[0], 1), dtype="i4") * decoder_start_token_id
|
| 573 |
+
|
| 574 |
+
>>> outputs = model.decode(decoder_input_ids, encoder_outputs)
|
| 575 |
+
>>> logits = outputs.logits
|
| 576 |
+
```"""
|
| 577 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 578 |
+
output_hidden_states = (
|
| 579 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 580 |
+
)
|
| 581 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 582 |
+
|
| 583 |
+
encoder_hidden_states = encoder_outputs[0]
|
| 584 |
+
if encoder_attention_mask is None:
|
| 585 |
+
batch_size, sequence_length = encoder_hidden_states.shape[:2]
|
| 586 |
+
encoder_attention_mask = jnp.ones((batch_size, sequence_length))
|
| 587 |
+
|
| 588 |
+
batch_size, sequence_length = decoder_input_ids.shape
|
| 589 |
+
if decoder_attention_mask is None:
|
| 590 |
+
decoder_attention_mask = jnp.ones((batch_size, sequence_length))
|
| 591 |
+
|
| 592 |
+
if decoder_position_ids is None:
|
| 593 |
+
if past_key_values is not None:
|
| 594 |
+
raise ValueError("Make sure to provide `decoder_position_ids` when passing `past_key_values`.")
|
| 595 |
+
|
| 596 |
+
decoder_position_ids = jnp.broadcast_to(
|
| 597 |
+
jnp.arange(sequence_length)[None, :], (batch_size, sequence_length)
|
| 598 |
+
)
|
| 599 |
+
|
| 600 |
+
# Handle any PRNG if needed
|
| 601 |
+
rngs = {}
|
| 602 |
+
if dropout_rng is not None:
|
| 603 |
+
rngs["dropout"] = dropout_rng
|
| 604 |
+
|
| 605 |
+
params = {"params": params or self.params}
|
| 606 |
+
|
| 607 |
+
# if past_key_values are passed then cache is already initialized a private flag init_cache has to be
|
| 608 |
+
# passed down to ensure cache is used. It has to be made sure that cache is marked as mutable so that
|
| 609 |
+
# it can be changed by FlaxBartAttention module
|
| 610 |
+
if past_key_values:
|
| 611 |
+
params["cache"] = past_key_values
|
| 612 |
+
mutable = ["cache"]
|
| 613 |
+
else:
|
| 614 |
+
mutable = False
|
| 615 |
+
|
| 616 |
+
def _decoder_forward(
|
| 617 |
+
module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, encoder_hidden_states, **kwargs
|
| 618 |
+
):
|
| 619 |
+
projection_module = module._get_projection_module()
|
| 620 |
+
decoder_module = module._get_decoder_module()
|
| 621 |
+
|
| 622 |
+
# optionally project encoder_hidden_states
|
| 623 |
+
if projection_module is not None:
|
| 624 |
+
encoder_hidden_states = projection_module(encoder_hidden_states)
|
| 625 |
+
|
| 626 |
+
return decoder_module(
|
| 627 |
+
decoder_input_ids,
|
| 628 |
+
decoder_attention_mask,
|
| 629 |
+
decoder_position_ids,
|
| 630 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 631 |
+
**kwargs,
|
| 632 |
+
)
|
| 633 |
+
|
| 634 |
+
outputs = self.module.apply(
|
| 635 |
+
params,
|
| 636 |
+
decoder_input_ids=jnp.array(decoder_input_ids, dtype="i4"),
|
| 637 |
+
decoder_attention_mask=jnp.array(decoder_attention_mask, dtype="i4"),
|
| 638 |
+
decoder_position_ids=jnp.array(decoder_position_ids, dtype="i4"),
|
| 639 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 640 |
+
encoder_attention_mask=jnp.array(encoder_attention_mask, dtype="i4"),
|
| 641 |
+
output_attentions=output_attentions,
|
| 642 |
+
output_hidden_states=output_hidden_states,
|
| 643 |
+
return_dict=return_dict,
|
| 644 |
+
deterministic=not train,
|
| 645 |
+
rngs=rngs,
|
| 646 |
+
mutable=mutable,
|
| 647 |
+
method=_decoder_forward,
|
| 648 |
+
)
|
| 649 |
+
|
| 650 |
+
# add updated cache to model output
|
| 651 |
+
if past_key_values is not None and return_dict:
|
| 652 |
+
outputs, past = outputs
|
| 653 |
+
outputs["past_key_values"] = unfreeze(past["cache"])
|
| 654 |
+
return outputs
|
| 655 |
+
elif past_key_values is not None and not return_dict:
|
| 656 |
+
outputs, past = outputs
|
| 657 |
+
outputs = outputs[:1] + (unfreeze(past["cache"]),) + outputs[1:]
|
| 658 |
+
|
| 659 |
+
return outputs
|
| 660 |
+
|
| 661 |
+
@add_start_docstrings_to_model_forward(SPEECH_ENCODER_DECODER_INPUTS_DOCSTRING)
|
| 662 |
+
@replace_return_docstrings(output_type=FlaxSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
|
| 663 |
+
def __call__(
|
| 664 |
+
self,
|
| 665 |
+
inputs: jnp.ndarray,
|
| 666 |
+
attention_mask: Optional[jnp.ndarray] = None,
|
| 667 |
+
decoder_input_ids: Optional[jnp.ndarray] = None,
|
| 668 |
+
decoder_attention_mask: Optional[jnp.ndarray] = None,
|
| 669 |
+
decoder_position_ids: Optional[jnp.ndarray] = None,
|
| 670 |
+
output_attentions: Optional[bool] = None,
|
| 671 |
+
output_hidden_states: Optional[bool] = None,
|
| 672 |
+
return_dict: Optional[bool] = None,
|
| 673 |
+
train: bool = False,
|
| 674 |
+
freeze_feature_encoder: bool = False,
|
| 675 |
+
params: Optional[dict] = None,
|
| 676 |
+
dropout_rng: PRNGKey = None,
|
| 677 |
+
):
|
| 678 |
+
r"""
|
| 679 |
+
Returns:
|
| 680 |
+
|
| 681 |
+
Examples:
|
| 682 |
+
|
| 683 |
+
```python
|
| 684 |
+
>>> from transformers import FlaxSpeechEncoderDecoderModel, AutoTokenizer
|
| 685 |
+
|
| 686 |
+
>>> # load a fine-tuned wav2vec2-2-bart model
|
| 687 |
+
>>> model = FlaxSpeechEncoderDecoderModel.from_pretrained("patrickvonplaten/wav2vec2-2-bart-large")
|
| 688 |
+
>>> # load output tokenizer
|
| 689 |
+
>>> tokenizer_output = AutoTokenizer.from_pretrained("facebook/bart-large")
|
| 690 |
+
|
| 691 |
+
>>> inputs = jnp.ones((2, 5000), dtype=jnp.float32)
|
| 692 |
+
|
| 693 |
+
>>> # use bart's special bos, pad and eos tokens
|
| 694 |
+
>>> model.config.decoder_start_token_id = model.decoder.config.bos_token_id
|
| 695 |
+
>>> model.config.pad_token_id = model.decoder.config.pad_token_id
|
| 696 |
+
>>> model.config.eos_token_id = model.decoder.config.eos_token_id
|
| 697 |
+
|
| 698 |
+
>>> outputs = model.generate(inputs)
|
| 699 |
+
# Assert something? More interesting input? dtype correct?
|
| 700 |
+
```
|
| 701 |
+
"""
|
| 702 |
+
|
| 703 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 704 |
+
output_hidden_states = (
|
| 705 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 706 |
+
)
|
| 707 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 708 |
+
|
| 709 |
+
# prepare encoder inputs
|
| 710 |
+
if attention_mask is None:
|
| 711 |
+
attention_mask = jnp.ones_like(inputs, dtype="i4")
|
| 712 |
+
|
| 713 |
+
# prepare decoder inputs
|
| 714 |
+
if decoder_input_ids is None:
|
| 715 |
+
raise ValueError(
|
| 716 |
+
"`decoder_input_ids` cannot be `None`. For sequence to sequence training, `decoder_position_ids` must"
|
| 717 |
+
" be specified as an input argument."
|
| 718 |
+
)
|
| 719 |
+
if decoder_attention_mask is None:
|
| 720 |
+
decoder_attention_mask = jnp.ones_like(decoder_input_ids)
|
| 721 |
+
if decoder_position_ids is None:
|
| 722 |
+
batch_size, sequence_length = decoder_input_ids.shape
|
| 723 |
+
decoder_position_ids = jnp.broadcast_to(
|
| 724 |
+
jnp.arange(sequence_length)[None, :], (batch_size, sequence_length)
|
| 725 |
+
)
|
| 726 |
+
|
| 727 |
+
# Handle any PRNG if needed
|
| 728 |
+
rngs = {"dropout": dropout_rng} if dropout_rng is not None else {}
|
| 729 |
+
|
| 730 |
+
return self.module.apply(
|
| 731 |
+
{"params": params or self.params},
|
| 732 |
+
inputs=jnp.array(inputs, dtype="f4"),
|
| 733 |
+
attention_mask=jnp.array(attention_mask, dtype="i4"),
|
| 734 |
+
decoder_input_ids=jnp.array(decoder_input_ids, dtype="i4"),
|
| 735 |
+
decoder_attention_mask=jnp.array(decoder_attention_mask, dtype="i4"),
|
| 736 |
+
decoder_position_ids=jnp.array(decoder_position_ids, dtype="i4"),
|
| 737 |
+
output_attentions=output_attentions,
|
| 738 |
+
output_hidden_states=output_hidden_states,
|
| 739 |
+
return_dict=return_dict,
|
| 740 |
+
deterministic=not train,
|
| 741 |
+
freeze_feature_encoder=freeze_feature_encoder,
|
| 742 |
+
rngs=rngs,
|
| 743 |
+
)
|
| 744 |
+
|
| 745 |
+
def prepare_inputs_for_generation(
|
| 746 |
+
self,
|
| 747 |
+
decoder_input_ids,
|
| 748 |
+
max_length,
|
| 749 |
+
attention_mask: Optional[jax.Array] = None,
|
| 750 |
+
decoder_attention_mask: Optional[jax.Array] = None,
|
| 751 |
+
encoder_outputs=None,
|
| 752 |
+
**kwargs,
|
| 753 |
+
):
|
| 754 |
+
# initializing the cache
|
| 755 |
+
batch_size, seq_length = decoder_input_ids.shape
|
| 756 |
+
|
| 757 |
+
past_key_values = self.init_cache(batch_size, max_length, encoder_outputs)
|
| 758 |
+
# Note that usually one would have to put 0's in the attention_mask for x > input.shape[-1] and x < cache_length.
|
| 759 |
+
# But since the decoder uses a causal mask, those positions are masked anyways.
|
| 760 |
+
# Thus we can create a single static attention_mask here, which is more efficient for compilation
|
| 761 |
+
extended_attention_mask = jnp.ones((batch_size, max_length), dtype="i4")
|
| 762 |
+
if decoder_attention_mask is not None:
|
| 763 |
+
decoder_position_ids = decoder_attention_mask.cumsum(axis=-1) - 1
|
| 764 |
+
extended_attention_mask = lax.dynamic_update_slice(extended_attention_mask, decoder_attention_mask, (0, 0))
|
| 765 |
+
else:
|
| 766 |
+
decoder_position_ids = jnp.broadcast_to(
|
| 767 |
+
jnp.arange(seq_length, dtype="i4")[None, :], (batch_size, seq_length)
|
| 768 |
+
)
|
| 769 |
+
|
| 770 |
+
return {
|
| 771 |
+
"past_key_values": past_key_values,
|
| 772 |
+
"encoder_outputs": encoder_outputs,
|
| 773 |
+
"encoder_attention_mask": attention_mask,
|
| 774 |
+
"decoder_attention_mask": extended_attention_mask,
|
| 775 |
+
"decoder_position_ids": decoder_position_ids,
|
| 776 |
+
}
|
| 777 |
+
|
| 778 |
+
def update_inputs_for_generation(self, model_outputs, model_kwargs):
|
| 779 |
+
model_kwargs["past_key_values"] = model_outputs.past_key_values
|
| 780 |
+
model_kwargs["decoder_position_ids"] = model_kwargs["decoder_position_ids"][:, -1:] + 1
|
| 781 |
+
return model_kwargs
|
| 782 |
+
|
| 783 |
+
@classmethod
|
| 784 |
+
def from_encoder_decoder_pretrained(
|
| 785 |
+
cls,
|
| 786 |
+
encoder_pretrained_model_name_or_path: Optional[Union[str, os.PathLike]] = None,
|
| 787 |
+
decoder_pretrained_model_name_or_path: Optional[Union[str, os.PathLike]] = None,
|
| 788 |
+
*model_args,
|
| 789 |
+
**kwargs,
|
| 790 |
+
) -> FlaxPreTrainedModel:
|
| 791 |
+
r"""
|
| 792 |
+
Instantiate an encoder and a decoder from one or two base classes of the library from pretrained model
|
| 793 |
+
checkpoints.
|
| 794 |
+
|
| 795 |
+
Params:
|
| 796 |
+
encoder_pretrained_model_name_or_path (`Union[str, os.PathLike]`, *optional*):
|
| 797 |
+
Information necessary to initiate the encoder. Can be either:
|
| 798 |
+
|
| 799 |
+
- A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
|
| 800 |
+
- A path to a *directory* containing model weights saved using
|
| 801 |
+
[`~FlaxPreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
|
| 802 |
+
|
| 803 |
+
decoder_pretrained_model_name_or_path (`Union[str, os.PathLike]`, *optional*, defaults to `None`):
|
| 804 |
+
Information necessary to initiate the decoder. Can be either:
|
| 805 |
+
|
| 806 |
+
- A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
|
| 807 |
+
- A path to a *directory* containing model weights saved using
|
| 808 |
+
[`~FlaxPreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
|
| 809 |
+
|
| 810 |
+
model_args (remaining positional arguments, *optional*):
|
| 811 |
+
All remaining positional arguments will be passed to the underlying model's `__init__` method.
|
| 812 |
+
|
| 813 |
+
kwargs (remaining dictionary of keyword arguments, *optional*):
|
| 814 |
+
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
|
| 815 |
+
`output_attentions=True`).
|
| 816 |
+
|
| 817 |
+
- To update the encoder configuration, use the prefix *encoder_* for each configuration parameter.
|
| 818 |
+
- To update the decoder configuration, use the prefix *decoder_* for each configuration parameter.
|
| 819 |
+
- To update the parent model configuration, do not use a prefix for each configuration parameter.
|
| 820 |
+
|
| 821 |
+
Behaves differently depending on whether a `config` is provided or automatically loaded.
|
| 822 |
+
|
| 823 |
+
Example:
|
| 824 |
+
|
| 825 |
+
```python
|
| 826 |
+
>>> from transformers import FlaxSpeechEncoderDecoderModel
|
| 827 |
+
|
| 828 |
+
>>> # initialize a wav2vec2-2-bart from pretrained wav2vec2 and bart models. Note that the cross-attention layers will be randomly initialized
|
| 829 |
+
>>> model = FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained(
|
| 830 |
+
... "facebook/wav2vec2-large-lv60", "facebook/bart-large"
|
| 831 |
+
... )
|
| 832 |
+
>>> # saving model after fine-tuning
|
| 833 |
+
>>> model.save_pretrained("./wav2vec2-2-bart-large")
|
| 834 |
+
>>> # load fine-tuned model
|
| 835 |
+
>>> model = FlaxSpeechEncoderDecoderModel.from_pretrained("./wav2vec2-2-bart-large")
|
| 836 |
+
```"""
|
| 837 |
+
|
| 838 |
+
kwargs_encoder = {
|
| 839 |
+
argument[len("encoder_") :]: value for argument, value in kwargs.items() if argument.startswith("encoder_")
|
| 840 |
+
}
|
| 841 |
+
|
| 842 |
+
kwargs_decoder = {
|
| 843 |
+
argument[len("decoder_") :]: value for argument, value in kwargs.items() if argument.startswith("decoder_")
|
| 844 |
+
}
|
| 845 |
+
|
| 846 |
+
# remove encoder, decoder kwargs from kwargs
|
| 847 |
+
for key in kwargs_encoder:
|
| 848 |
+
del kwargs["encoder_" + key]
|
| 849 |
+
for key in kwargs_decoder:
|
| 850 |
+
del kwargs["decoder_" + key]
|
| 851 |
+
|
| 852 |
+
# Load and initialize the encoder and decoder
|
| 853 |
+
# The distinction between encoder and decoder at the model level is made
|
| 854 |
+
# by the value of the flag `is_decoder` that we need to set correctly.
|
| 855 |
+
encoder = kwargs_encoder.pop("model", None)
|
| 856 |
+
if encoder is None:
|
| 857 |
+
if encoder_pretrained_model_name_or_path is None:
|
| 858 |
+
raise ValueError(
|
| 859 |
+
"If `encoder_model` is not defined as an argument, a `encoder_pretrained_model_name_or_path` has "
|
| 860 |
+
"to be defined."
|
| 861 |
+
)
|
| 862 |
+
|
| 863 |
+
if "config" not in kwargs_encoder:
|
| 864 |
+
encoder_config, kwargs_encoder = AutoConfig.from_pretrained(
|
| 865 |
+
encoder_pretrained_model_name_or_path, **kwargs_encoder, return_unused_kwargs=True
|
| 866 |
+
)
|
| 867 |
+
if encoder_config.is_decoder is True or encoder_config.add_cross_attention is True:
|
| 868 |
+
logger.info(
|
| 869 |
+
f"Initializing {encoder_pretrained_model_name_or_path} as a encoder model "
|
| 870 |
+
"from a decoder model. Cross-attention and causal mask are disabled."
|
| 871 |
+
)
|
| 872 |
+
encoder_config.is_decoder = False
|
| 873 |
+
encoder_config.add_cross_attention = False
|
| 874 |
+
|
| 875 |
+
kwargs_encoder["config"] = encoder_config
|
| 876 |
+
|
| 877 |
+
encoder = FlaxAutoModel.from_pretrained(
|
| 878 |
+
encoder_pretrained_model_name_or_path, *model_args, **kwargs_encoder
|
| 879 |
+
)
|
| 880 |
+
|
| 881 |
+
decoder = kwargs_decoder.pop("model", None)
|
| 882 |
+
if decoder is None:
|
| 883 |
+
if decoder_pretrained_model_name_or_path is None:
|
| 884 |
+
raise ValueError(
|
| 885 |
+
"If `decoder_model` is not defined as an argument, a `decoder_pretrained_model_name_or_path` has "
|
| 886 |
+
"to be defined."
|
| 887 |
+
)
|
| 888 |
+
|
| 889 |
+
if "config" not in kwargs_decoder:
|
| 890 |
+
decoder_config, kwargs_decoder = AutoConfig.from_pretrained(
|
| 891 |
+
decoder_pretrained_model_name_or_path, **kwargs_decoder, return_unused_kwargs=True
|
| 892 |
+
)
|
| 893 |
+
if decoder_config.is_decoder is False or decoder_config.add_cross_attention is False:
|
| 894 |
+
logger.info(
|
| 895 |
+
f"Initializing {decoder_pretrained_model_name_or_path} as a decoder model. Cross attention"
|
| 896 |
+
f" layers are added to {decoder_pretrained_model_name_or_path} and randomly initialized if"
|
| 897 |
+
f" {decoder_pretrained_model_name_or_path}'s architecture allows for cross attention layers."
|
| 898 |
+
)
|
| 899 |
+
decoder_config.is_decoder = True
|
| 900 |
+
decoder_config.add_cross_attention = True
|
| 901 |
+
|
| 902 |
+
kwargs_decoder["config"] = decoder_config
|
| 903 |
+
|
| 904 |
+
if kwargs_decoder["config"].is_decoder is False or kwargs_decoder["config"].add_cross_attention is False:
|
| 905 |
+
logger.warning(
|
| 906 |
+
f"Decoder model {decoder_pretrained_model_name_or_path} is not initialized as a decoder. "
|
| 907 |
+
f"In order to initialize {decoder_pretrained_model_name_or_path} as a decoder, "
|
| 908 |
+
"make sure that the attributes `is_decoder` and `add_cross_attention` of `decoder_config` "
|
| 909 |
+
"passed to `.from_encoder_decoder_pretrained(...)` are set to `True` or do not pass a "
|
| 910 |
+
"`decoder_config` to `.from_encoder_decoder_pretrained(...)`"
|
| 911 |
+
)
|
| 912 |
+
|
| 913 |
+
decoder = FlaxAutoModelForCausalLM.from_pretrained(decoder_pretrained_model_name_or_path, **kwargs_decoder)
|
| 914 |
+
|
| 915 |
+
# instantiate config with corresponding kwargs
|
| 916 |
+
dtype = kwargs.pop("dtype", jnp.float32)
|
| 917 |
+
config = SpeechEncoderDecoderConfig.from_encoder_decoder_configs(encoder.config, decoder.config, **kwargs)
|
| 918 |
+
|
| 919 |
+
# make sure input & output word embeddings are not tied
|
| 920 |
+
config.tie_word_embeddings = False
|
| 921 |
+
|
| 922 |
+
# init model
|
| 923 |
+
model = cls(config, dtype=dtype)
|
| 924 |
+
model.params["encoder"] = encoder.params
|
| 925 |
+
model.params["decoder"] = decoder.params
|
| 926 |
+
|
| 927 |
+
return model
|
| 928 |
+
|
| 929 |
+
|
| 930 |
+
__all__ = ["FlaxSpeechEncoderDecoderModel"]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speech_encoder_decoder/modeling_speech_encoder_decoder.py
ADDED
|
@@ -0,0 +1,504 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Classes to support Speech-Encoder-Text-Decoder architectures"""
|
| 16 |
+
|
| 17 |
+
from typing import Optional, Union
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
from torch import nn
|
| 21 |
+
from torch.nn import CrossEntropyLoss
|
| 22 |
+
|
| 23 |
+
from ...configuration_utils import PretrainedConfig
|
| 24 |
+
from ...generation import GenerationMixin
|
| 25 |
+
from ...modeling_outputs import BaseModelOutput, Seq2SeqLMOutput
|
| 26 |
+
from ...modeling_utils import PreTrainedModel
|
| 27 |
+
from ...utils import auto_docstring, logging
|
| 28 |
+
from ..auto.configuration_auto import AutoConfig
|
| 29 |
+
from ..auto.modeling_auto import AutoModel, AutoModelForCausalLM
|
| 30 |
+
from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
logger = logging.get_logger(__name__)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# Copied from transformers.models.encoder_decoder.modeling_encoder_decoder.shift_tokens_right
|
| 37 |
+
def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
|
| 38 |
+
"""
|
| 39 |
+
Shift input ids one token to the right.
|
| 40 |
+
"""
|
| 41 |
+
shifted_input_ids = input_ids.new_zeros(input_ids.shape)
|
| 42 |
+
shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
|
| 43 |
+
if decoder_start_token_id is None:
|
| 44 |
+
raise ValueError("Make sure to set the decoder_start_token_id attribute of the model's configuration.")
|
| 45 |
+
shifted_input_ids[:, 0] = decoder_start_token_id
|
| 46 |
+
|
| 47 |
+
if pad_token_id is None:
|
| 48 |
+
raise ValueError("Make sure to set the pad_token_id attribute of the model's configuration.")
|
| 49 |
+
# replace possible -100 values in labels by `pad_token_id`
|
| 50 |
+
shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
|
| 51 |
+
|
| 52 |
+
return shifted_input_ids
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@auto_docstring
|
| 56 |
+
class SpeechEncoderDecoderModel(PreTrainedModel, GenerationMixin):
|
| 57 |
+
r"""
|
| 58 |
+
[`SpeechEncoderDecoderModel`] is a generic model class that will be instantiated as a transformer architecture with
|
| 59 |
+
one of the base model classes of the library as encoder and another one as decoder when created with the
|
| 60 |
+
:meth*~transformers.AutoModel.from_pretrained* class method for the encoder and
|
| 61 |
+
:meth*~transformers.AutoModelForCausalLM.from_pretrained* class method for the decoder.
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
config: SpeechEncoderDecoderConfig
|
| 65 |
+
base_model_prefix = "speech_encoder_decoder"
|
| 66 |
+
main_input_name = "inputs"
|
| 67 |
+
supports_gradient_checkpointing = True
|
| 68 |
+
_supports_param_buffer_assignment = False
|
| 69 |
+
_supports_flash_attn = True
|
| 70 |
+
_supports_sdpa = True
|
| 71 |
+
|
| 72 |
+
def __init__(
|
| 73 |
+
self,
|
| 74 |
+
config: Optional[PretrainedConfig] = None,
|
| 75 |
+
encoder: Optional[PreTrainedModel] = None,
|
| 76 |
+
decoder: Optional[PreTrainedModel] = None,
|
| 77 |
+
):
|
| 78 |
+
r"""
|
| 79 |
+
encoder (`PreTrainedModel`, *optional*):
|
| 80 |
+
The encoder model to use.
|
| 81 |
+
decoder (`PreTrainedModel`, *optional*):
|
| 82 |
+
The decoder model to use.
|
| 83 |
+
"""
|
| 84 |
+
if config is None and (encoder is None or decoder is None):
|
| 85 |
+
raise ValueError("Either a configuration or an encoder and a decoder has to be provided.")
|
| 86 |
+
if config is None:
|
| 87 |
+
config = SpeechEncoderDecoderConfig.from_encoder_decoder_configs(encoder.config, decoder.config)
|
| 88 |
+
else:
|
| 89 |
+
if not isinstance(config, self.config_class):
|
| 90 |
+
raise ValueError(f"Config: {config} has to be of type {self.config_class}")
|
| 91 |
+
|
| 92 |
+
if config.decoder.cross_attention_hidden_size is not None:
|
| 93 |
+
if config.decoder.cross_attention_hidden_size != config.encoder.hidden_size:
|
| 94 |
+
raise ValueError(
|
| 95 |
+
"If `cross_attention_hidden_size` is specified in the decoder's configuration, it has to be equal"
|
| 96 |
+
f" to the encoder's `hidden_size`. Got {config.decoder.cross_attention_hidden_size} for"
|
| 97 |
+
f" `config.decoder.cross_attention_hidden_size` and {config.encoder.hidden_size} for"
|
| 98 |
+
" `config.encoder.hidden_size`."
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
# initialize with config
|
| 102 |
+
# make sure input & output embeddings is not tied
|
| 103 |
+
config.tie_word_embeddings = False
|
| 104 |
+
super().__init__(config)
|
| 105 |
+
|
| 106 |
+
if encoder is None:
|
| 107 |
+
encoder = AutoModel.from_config(config.encoder)
|
| 108 |
+
|
| 109 |
+
if decoder is None:
|
| 110 |
+
decoder = AutoModelForCausalLM.from_config(config.decoder)
|
| 111 |
+
|
| 112 |
+
self.encoder = encoder
|
| 113 |
+
self.decoder = decoder
|
| 114 |
+
|
| 115 |
+
if self.encoder.config.to_dict() != self.config.encoder.to_dict():
|
| 116 |
+
logger.warning(
|
| 117 |
+
f"Config of the encoder: {self.encoder.__class__} is overwritten by shared encoder config:"
|
| 118 |
+
f" {self.config.encoder}"
|
| 119 |
+
)
|
| 120 |
+
if self.decoder.config.to_dict() != self.config.decoder.to_dict():
|
| 121 |
+
logger.warning(
|
| 122 |
+
f"Config of the decoder: {self.decoder.__class__} is overwritten by shared decoder config:"
|
| 123 |
+
f" {self.config.decoder}"
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
# make sure that the individual model's config refers to the shared config
|
| 127 |
+
# so that the updates to the config will be synced
|
| 128 |
+
self.config.encoder._attn_implementation = self.encoder.config._attn_implementation
|
| 129 |
+
self.config.decoder._attn_implementation = self.decoder.config._attn_implementation
|
| 130 |
+
self.encoder.config = self.config.encoder
|
| 131 |
+
self.decoder.config = self.config.decoder
|
| 132 |
+
|
| 133 |
+
# get encoder output hidden size
|
| 134 |
+
self.encoder_output_dim = getattr(config.encoder, "output_hidden_size", config.encoder.hidden_size)
|
| 135 |
+
if (
|
| 136 |
+
self.encoder_output_dim != self.decoder.config.hidden_size
|
| 137 |
+
and self.decoder.config.cross_attention_hidden_size is None
|
| 138 |
+
):
|
| 139 |
+
# encoder outputs might need to be projected to different dimension for decoder
|
| 140 |
+
self.enc_to_dec_proj = nn.Linear(self.encoder.config.hidden_size, self.decoder.config.hidden_size)
|
| 141 |
+
|
| 142 |
+
if self.encoder.get_output_embeddings() is not None:
|
| 143 |
+
raise ValueError(
|
| 144 |
+
f"The encoder {self.encoder} should not have a LM Head. Please use a model without LM Head"
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
def get_encoder(self):
|
| 148 |
+
return self.encoder
|
| 149 |
+
|
| 150 |
+
def get_input_embeddings(self):
|
| 151 |
+
return self.decoder.get_input_embeddings()
|
| 152 |
+
|
| 153 |
+
def get_output_embeddings(self):
|
| 154 |
+
return self.decoder.get_output_embeddings()
|
| 155 |
+
|
| 156 |
+
def set_output_embeddings(self, new_embeddings):
|
| 157 |
+
return self.decoder.set_output_embeddings(new_embeddings)
|
| 158 |
+
|
| 159 |
+
def freeze_feature_encoder(self):
|
| 160 |
+
"""
|
| 161 |
+
Calling this function will disable the gradient computation for the feature encoder of the speech encoder so
|
| 162 |
+
that its parameters will not be updated during training.
|
| 163 |
+
"""
|
| 164 |
+
self.encoder.freeze_feature_encoder()
|
| 165 |
+
|
| 166 |
+
@classmethod
|
| 167 |
+
def from_encoder_decoder_pretrained(
|
| 168 |
+
cls,
|
| 169 |
+
encoder_pretrained_model_name_or_path: Optional[str] = None,
|
| 170 |
+
decoder_pretrained_model_name_or_path: Optional[str] = None,
|
| 171 |
+
*model_args,
|
| 172 |
+
**kwargs,
|
| 173 |
+
) -> PreTrainedModel:
|
| 174 |
+
r"""
|
| 175 |
+
Instantiate an encoder and a decoder from one or two base classes of the library from pretrained model
|
| 176 |
+
checkpoints.
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
The model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated). To train
|
| 180 |
+
the model, you need to first set it back in training mode with `model.train()`.
|
| 181 |
+
|
| 182 |
+
Params:
|
| 183 |
+
encoder_pretrained_model_name_or_path (`str`, *optional*):
|
| 184 |
+
Information necessary to initiate the encoder. Can be either:
|
| 185 |
+
|
| 186 |
+
- A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
|
| 187 |
+
- A path to a *directory* containing model weights saved using
|
| 188 |
+
[`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
|
| 189 |
+
- A path or url to a *tensorflow index checkpoint file* (e.g, `./tf_model/model.ckpt.index`). In
|
| 190 |
+
this case, `from_tf` should be set to `True` and a configuration object should be provided as
|
| 191 |
+
`config` argument. This loading path is slower than converting the TensorFlow checkpoint in a
|
| 192 |
+
PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
|
| 193 |
+
|
| 194 |
+
decoder_pretrained_model_name_or_path (`str`, *optional*, defaults to `None`):
|
| 195 |
+
Information necessary to initiate the decoder. Can be either:
|
| 196 |
+
|
| 197 |
+
- A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
|
| 198 |
+
- A path to a *directory* containing model weights saved using
|
| 199 |
+
[`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
|
| 200 |
+
- A path or url to a *tensorflow index checkpoint file* (e.g, `./tf_model/model.ckpt.index`). In
|
| 201 |
+
this case, `from_tf` should be set to `True` and a configuration object should be provided as
|
| 202 |
+
`config` argument. This loading path is slower than converting the TensorFlow checkpoint in a
|
| 203 |
+
PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
|
| 204 |
+
|
| 205 |
+
model_args (remaining positional arguments, *optional*):
|
| 206 |
+
All remaining positional arguments will be passed to the underlying model's `__init__` method.
|
| 207 |
+
|
| 208 |
+
kwargs (remaining dictionary of keyword arguments, *optional*):
|
| 209 |
+
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
|
| 210 |
+
`output_attentions=True`).
|
| 211 |
+
|
| 212 |
+
- To update the encoder configuration, use the prefix *encoder_* for each configuration parameter.
|
| 213 |
+
- To update the decoder configuration, use the prefix *decoder_* for each configuration parameter.
|
| 214 |
+
- To update the parent model configuration, do not use a prefix for each configuration parameter.
|
| 215 |
+
|
| 216 |
+
Behaves differently depending on whether a `config` is provided or automatically loaded.
|
| 217 |
+
|
| 218 |
+
Example:
|
| 219 |
+
|
| 220 |
+
```python
|
| 221 |
+
>>> from transformers import SpeechEncoderDecoderModel
|
| 222 |
+
|
| 223 |
+
>>> # initialize a wav2vec2bert from a pretrained Wav2Vec2 and a pretrained BERT model. Note that the cross-attention layers will be randomly initialized
|
| 224 |
+
>>> model = SpeechEncoderDecoderModel.from_encoder_decoder_pretrained(
|
| 225 |
+
... "facebook/wav2vec2-base-960h", "google-bert/bert-base-uncased"
|
| 226 |
+
... )
|
| 227 |
+
>>> # saving model after fine-tuning
|
| 228 |
+
>>> model.save_pretrained("./wav2vec2bert")
|
| 229 |
+
>>> # load fine-tuned model
|
| 230 |
+
>>> model = SpeechEncoderDecoderModel.from_pretrained("./wav2vec2bert")
|
| 231 |
+
```"""
|
| 232 |
+
|
| 233 |
+
kwargs_encoder = {
|
| 234 |
+
argument[len("encoder_") :]: value for argument, value in kwargs.items() if argument.startswith("encoder_")
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
kwargs_decoder = {
|
| 238 |
+
argument[len("decoder_") :]: value for argument, value in kwargs.items() if argument.startswith("decoder_")
|
| 239 |
+
}
|
| 240 |
+
|
| 241 |
+
# remove encoder, decoder kwargs from kwargs
|
| 242 |
+
for key in kwargs_encoder:
|
| 243 |
+
del kwargs["encoder_" + key]
|
| 244 |
+
for key in kwargs_decoder:
|
| 245 |
+
del kwargs["decoder_" + key]
|
| 246 |
+
|
| 247 |
+
# Load and initialize the encoder and decoder
|
| 248 |
+
# The distinction between encoder and decoder at the model level is made
|
| 249 |
+
# by the value of the flag `is_decoder` that we need to set correctly.
|
| 250 |
+
encoder = kwargs_encoder.pop("model", None)
|
| 251 |
+
if encoder is None:
|
| 252 |
+
if encoder_pretrained_model_name_or_path is None:
|
| 253 |
+
raise ValueError(
|
| 254 |
+
"If `encoder_model` is not defined as an argument, a `encoder_pretrained_model_name_or_path` has "
|
| 255 |
+
"to be defined."
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
if "config" not in kwargs_encoder:
|
| 259 |
+
encoder_config, kwargs_encoder = AutoConfig.from_pretrained(
|
| 260 |
+
encoder_pretrained_model_name_or_path, **kwargs_encoder, return_unused_kwargs=True
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
if encoder_config.is_decoder is True or encoder_config.add_cross_attention is True:
|
| 264 |
+
logger.info(
|
| 265 |
+
f"Initializing {encoder_pretrained_model_name_or_path} as a encoder model "
|
| 266 |
+
"from a decoder model. Cross-attention and causal mask are disabled."
|
| 267 |
+
)
|
| 268 |
+
encoder_config.is_decoder = False
|
| 269 |
+
encoder_config.add_cross_attention = False
|
| 270 |
+
|
| 271 |
+
kwargs_encoder["config"] = encoder_config
|
| 272 |
+
|
| 273 |
+
encoder = AutoModel.from_pretrained(encoder_pretrained_model_name_or_path, *model_args, **kwargs_encoder)
|
| 274 |
+
|
| 275 |
+
decoder = kwargs_decoder.pop("model", None)
|
| 276 |
+
if decoder is None:
|
| 277 |
+
if decoder_pretrained_model_name_or_path is None:
|
| 278 |
+
raise ValueError(
|
| 279 |
+
"If `decoder_model` is not defined as an argument, a `decoder_pretrained_model_name_or_path` has "
|
| 280 |
+
"to be defined."
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
if "config" not in kwargs_decoder:
|
| 284 |
+
decoder_config, kwargs_decoder = AutoConfig.from_pretrained(
|
| 285 |
+
decoder_pretrained_model_name_or_path, **kwargs_decoder, return_unused_kwargs=True
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
if decoder_config.is_decoder is False or decoder_config.add_cross_attention is False:
|
| 289 |
+
logger.info(
|
| 290 |
+
f"Initializing {decoder_pretrained_model_name_or_path} as a decoder model. Cross attention"
|
| 291 |
+
f" layers are added to {decoder_pretrained_model_name_or_path} and randomly initialized if"
|
| 292 |
+
f" {decoder_pretrained_model_name_or_path}'s architecture allows for cross attention layers."
|
| 293 |
+
)
|
| 294 |
+
decoder_config.is_decoder = True
|
| 295 |
+
decoder_config.add_cross_attention = True
|
| 296 |
+
|
| 297 |
+
kwargs_decoder["config"] = decoder_config
|
| 298 |
+
|
| 299 |
+
if kwargs_decoder["config"].is_decoder is False or kwargs_decoder["config"].add_cross_attention is False:
|
| 300 |
+
logger.warning(
|
| 301 |
+
f"Decoder model {decoder_pretrained_model_name_or_path} is not initialized as a decoder. "
|
| 302 |
+
f"In order to initialize {decoder_pretrained_model_name_or_path} as a decoder, "
|
| 303 |
+
"make sure that the attributes `is_decoder` and `add_cross_attention` of `decoder_config` "
|
| 304 |
+
"passed to `.from_encoder_decoder_pretrained(...)` are set to `True` or do not pass a "
|
| 305 |
+
"`decoder_config` to `.from_encoder_decoder_pretrained(...)`"
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
decoder = AutoModelForCausalLM.from_pretrained(decoder_pretrained_model_name_or_path, **kwargs_decoder)
|
| 309 |
+
|
| 310 |
+
# instantiate config with corresponding kwargs
|
| 311 |
+
config = SpeechEncoderDecoderConfig.from_encoder_decoder_configs(encoder.config, decoder.config, **kwargs)
|
| 312 |
+
|
| 313 |
+
# make sure input & output embeddings is not tied
|
| 314 |
+
config.tie_word_embeddings = False
|
| 315 |
+
return cls(encoder=encoder, decoder=decoder, config=config)
|
| 316 |
+
|
| 317 |
+
@auto_docstring
|
| 318 |
+
def forward(
|
| 319 |
+
self,
|
| 320 |
+
inputs: Optional[torch.FloatTensor] = None,
|
| 321 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 322 |
+
decoder_input_ids: Optional[torch.LongTensor] = None,
|
| 323 |
+
decoder_attention_mask: Optional[torch.BoolTensor] = None,
|
| 324 |
+
encoder_outputs: Optional[tuple[torch.FloatTensor]] = None,
|
| 325 |
+
past_key_values: Optional[tuple[tuple[torch.FloatTensor]]] = None,
|
| 326 |
+
decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 327 |
+
labels: Optional[torch.LongTensor] = None,
|
| 328 |
+
use_cache: Optional[bool] = None,
|
| 329 |
+
output_attentions: Optional[bool] = None,
|
| 330 |
+
output_hidden_states: Optional[bool] = None,
|
| 331 |
+
input_values: Optional[torch.FloatTensor] = None,
|
| 332 |
+
input_features: Optional[torch.FloatTensor] = None,
|
| 333 |
+
return_dict: Optional[bool] = None,
|
| 334 |
+
**kwargs,
|
| 335 |
+
) -> Union[tuple[torch.FloatTensor], Seq2SeqLMOutput]:
|
| 336 |
+
r"""
|
| 337 |
+
inputs (`torch.FloatTensor` of shape `(batch_size, sequence_length)` or `(batch_size, sequence_length, feature_dim)`, *optional*):
|
| 338 |
+
Float values of input raw speech waveform or speech features. Values can be obtained by loading a `.flac`
|
| 339 |
+
or `.wav` audio file into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.*
|
| 340 |
+
via the torchcodec library (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
|
| 341 |
+
To prepare the array into `inputs`, either the [`Wav2Vec2Processor`] or
|
| 342 |
+
[`Speech2TextProcessor`] should be used for padding and conversion into a tensor of type
|
| 343 |
+
`torch.FloatTensor`.
|
| 344 |
+
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 345 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 346 |
+
|
| 347 |
+
Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 348 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 349 |
+
|
| 350 |
+
[What are input IDs?](../glossary#input-ids)
|
| 351 |
+
|
| 352 |
+
If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
| 353 |
+
`past_key_values`).
|
| 354 |
+
|
| 355 |
+
For training, `decoder_input_ids` are automatically created by the model by shifting the `labels` to the
|
| 356 |
+
right, replacing -100 by the `pad_token_id` and prepending them with the `decoder_start_token_id`.
|
| 357 |
+
decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 358 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 359 |
+
be used by default.
|
| 360 |
+
decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
|
| 361 |
+
Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
|
| 362 |
+
representation. This is useful if you want more control over how to convert `decoder_input_ids` indices
|
| 363 |
+
into associated vectors than the model's internal embedding lookup matrix.
|
| 364 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 365 |
+
Labels for computing the masked language modeling loss for the decoder. Indices should be in `[-100, 0,
|
| 366 |
+
..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored
|
| 367 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 368 |
+
input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 369 |
+
Float values of input raw speech waveform. Values can be obtained by loading a *.flac* or *.wav* audio file
|
| 370 |
+
into an array of type *list[float]* or a *numpy.ndarray*, *e.g.* via the torchcodec library
|
| 371 |
+
(`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
|
| 372 |
+
To prepare the array into *input_values*, the [`Wav2Vec2Processor`] should be used for padding and conversion
|
| 373 |
+
into a tensor of type *torch.FloatTensor*. See [`Wav2Vec2Processor.__call__`] for details.
|
| 374 |
+
|
| 375 |
+
Examples:
|
| 376 |
+
|
| 377 |
+
```python
|
| 378 |
+
>>> from transformers import SpeechEncoderDecoderModel, AutoProcessor
|
| 379 |
+
>>> from datasets import load_dataset
|
| 380 |
+
>>> import torch
|
| 381 |
+
|
| 382 |
+
>>> processor = AutoProcessor.from_pretrained("facebook/wav2vec2-xls-r-300m-en-to-15")
|
| 383 |
+
>>> model = SpeechEncoderDecoderModel.from_pretrained("facebook/wav2vec2-xls-r-300m-en-to-15")
|
| 384 |
+
|
| 385 |
+
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
| 386 |
+
|
| 387 |
+
>>> input_values = processor(ds[0]["audio"]["array"], return_tensors="pt").input_values
|
| 388 |
+
>>> # Inference: Translate English speech to German
|
| 389 |
+
>>> generated = model.generate(input_values)
|
| 390 |
+
>>> decoded = processor.batch_decode(generated, skip_special_tokens=True)[0]
|
| 391 |
+
>>> decoded
|
| 392 |
+
'Mr. Quilter ist der Apostel der Mittelschicht und wir freuen uns, sein Evangelium willkommen heißen zu können.'
|
| 393 |
+
|
| 394 |
+
>>> # Training: Train model on English transcription
|
| 395 |
+
>>> labels = processor(text=ds[0]["text"], return_tensors="pt").input_ids
|
| 396 |
+
|
| 397 |
+
>>> loss = model(input_values, labels=labels).loss
|
| 398 |
+
>>> loss.backward()
|
| 399 |
+
```"""
|
| 400 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 401 |
+
|
| 402 |
+
kwargs_encoder = {argument: value for argument, value in kwargs.items() if not argument.startswith("decoder_")}
|
| 403 |
+
|
| 404 |
+
kwargs_decoder = {
|
| 405 |
+
argument[len("decoder_") :]: value for argument, value in kwargs.items() if argument.startswith("decoder_")
|
| 406 |
+
}
|
| 407 |
+
if "num_items_in_batch" in kwargs_encoder:
|
| 408 |
+
kwargs_decoder["num_items_in_batch"] = kwargs_encoder.pop("num_items_in_batch", None)
|
| 409 |
+
|
| 410 |
+
if encoder_outputs is None:
|
| 411 |
+
if inputs is None:
|
| 412 |
+
if input_values is not None and input_features is not None:
|
| 413 |
+
raise ValueError("You cannot specify both input_values and input_features at the same time")
|
| 414 |
+
elif input_values is not None:
|
| 415 |
+
inputs = input_values
|
| 416 |
+
elif input_features is not None:
|
| 417 |
+
inputs = input_features
|
| 418 |
+
else:
|
| 419 |
+
raise ValueError("You have to specify either input_values or input_features")
|
| 420 |
+
|
| 421 |
+
encoder_outputs = self.encoder(
|
| 422 |
+
inputs,
|
| 423 |
+
attention_mask=attention_mask,
|
| 424 |
+
output_attentions=output_attentions,
|
| 425 |
+
output_hidden_states=output_hidden_states,
|
| 426 |
+
return_dict=return_dict,
|
| 427 |
+
**kwargs_encoder,
|
| 428 |
+
)
|
| 429 |
+
elif isinstance(encoder_outputs, tuple):
|
| 430 |
+
encoder_outputs = BaseModelOutput(*encoder_outputs)
|
| 431 |
+
|
| 432 |
+
encoder_hidden_states = encoder_outputs[0]
|
| 433 |
+
|
| 434 |
+
# optionally project encoder_hidden_states
|
| 435 |
+
if (
|
| 436 |
+
self.encoder_output_dim != self.decoder.config.hidden_size
|
| 437 |
+
and self.decoder.config.cross_attention_hidden_size is None
|
| 438 |
+
):
|
| 439 |
+
encoder_hidden_states = self.enc_to_dec_proj(encoder_hidden_states)
|
| 440 |
+
|
| 441 |
+
# compute correct encoder attention mask
|
| 442 |
+
if attention_mask is not None:
|
| 443 |
+
encoder_attention_mask = self.encoder._get_feature_vector_attention_mask(
|
| 444 |
+
encoder_hidden_states.shape[1], attention_mask
|
| 445 |
+
)
|
| 446 |
+
else:
|
| 447 |
+
encoder_attention_mask = None
|
| 448 |
+
|
| 449 |
+
if (labels is not None) and (decoder_input_ids is None and decoder_inputs_embeds is None):
|
| 450 |
+
decoder_input_ids = shift_tokens_right(
|
| 451 |
+
labels, self.config.pad_token_id, self.config.decoder_start_token_id
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
# Decode
|
| 455 |
+
decoder_outputs = self.decoder(
|
| 456 |
+
input_ids=decoder_input_ids,
|
| 457 |
+
attention_mask=decoder_attention_mask,
|
| 458 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 459 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 460 |
+
inputs_embeds=decoder_inputs_embeds,
|
| 461 |
+
output_attentions=output_attentions,
|
| 462 |
+
output_hidden_states=output_hidden_states,
|
| 463 |
+
use_cache=use_cache,
|
| 464 |
+
past_key_values=past_key_values,
|
| 465 |
+
return_dict=return_dict,
|
| 466 |
+
**kwargs_decoder,
|
| 467 |
+
)
|
| 468 |
+
|
| 469 |
+
# Compute loss independent from decoder (as some shift the logits inside them)
|
| 470 |
+
loss = None
|
| 471 |
+
if labels is not None:
|
| 472 |
+
logits = decoder_outputs.logits if return_dict else decoder_outputs[0]
|
| 473 |
+
loss_fct = CrossEntropyLoss()
|
| 474 |
+
loss = loss_fct(logits.reshape(-1, self.decoder.config.vocab_size), labels.reshape(-1))
|
| 475 |
+
|
| 476 |
+
if not return_dict:
|
| 477 |
+
if loss is not None:
|
| 478 |
+
return (loss,) + decoder_outputs + encoder_outputs
|
| 479 |
+
else:
|
| 480 |
+
return decoder_outputs + encoder_outputs
|
| 481 |
+
|
| 482 |
+
return Seq2SeqLMOutput(
|
| 483 |
+
loss=loss,
|
| 484 |
+
logits=decoder_outputs.logits,
|
| 485 |
+
past_key_values=decoder_outputs.past_key_values,
|
| 486 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 487 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 488 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 489 |
+
encoder_last_hidden_state=encoder_hidden_states,
|
| 490 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 491 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 492 |
+
)
|
| 493 |
+
|
| 494 |
+
def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
|
| 495 |
+
return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id)
|
| 496 |
+
|
| 497 |
+
def resize_token_embeddings(self, *args, **kwargs):
|
| 498 |
+
raise NotImplementedError(
|
| 499 |
+
"Resizing the embedding layers via the SpeechEncoderDecoderModel directly is not supported. Please use the"
|
| 500 |
+
" respective methods of the wrapped decoder object (model.decoder.resize_token_embeddings(...))"
|
| 501 |
+
)
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
__all__ = ["SpeechEncoderDecoderModel"]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speech_to_text/__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_speech_to_text import *
|
| 22 |
+
from .feature_extraction_speech_to_text import *
|
| 23 |
+
from .modeling_speech_to_text import *
|
| 24 |
+
from .modeling_tf_speech_to_text import *
|
| 25 |
+
from .processing_speech_to_text import *
|
| 26 |
+
from .tokenization_speech_to_text 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__)
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speech_to_text/configuration_speech_to_text.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Speech2Text model configuration"""
|
| 16 |
+
|
| 17 |
+
from ...configuration_utils import PretrainedConfig
|
| 18 |
+
from ...utils import logging
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
logger = logging.get_logger(__name__)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class Speech2TextConfig(PretrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
This is the configuration class to store the configuration of a [`Speech2TextModel`]. It is used to instantiate a
|
| 27 |
+
Speech2Text model according to the specified arguments, defining the model architecture. Instantiating a
|
| 28 |
+
configuration with the defaults will yield a similar configuration to that of the Speech2Text
|
| 29 |
+
[facebook/s2t-small-librispeech-asr](https://huggingface.co/facebook/s2t-small-librispeech-asr) architecture.
|
| 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 |
+
vocab_size (`int`, *optional*, defaults to 10000):
|
| 37 |
+
Vocabulary size of the Speech2Text model. Defines the number of different tokens that can be represented by
|
| 38 |
+
the `inputs_ids` passed when calling [`Speech2TextModel`]
|
| 39 |
+
encoder_layers (`int`, *optional*, defaults to 12):
|
| 40 |
+
Number of encoder layers.
|
| 41 |
+
encoder_ffn_dim (`int`, *optional*, defaults to 2048):
|
| 42 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in encoder.
|
| 43 |
+
encoder_attention_heads (`int`, *optional*, defaults to 4):
|
| 44 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 45 |
+
decoder_layers (`int`, *optional*, defaults to 6):
|
| 46 |
+
Number of decoder layers.
|
| 47 |
+
decoder_ffn_dim (`int`, *optional*, defaults to 2048):
|
| 48 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
|
| 49 |
+
decoder_attention_heads (`int`, *optional*, defaults to 4):
|
| 50 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
| 51 |
+
encoder_layerdrop (`float`, *optional*, defaults to 0.0):
|
| 52 |
+
The LayerDrop probability for the encoder. See the [LayerDrop paper](https://huggingface.co/papers/1909.11556) for
|
| 53 |
+
more details.
|
| 54 |
+
decoder_layerdrop (`float`, *optional*, defaults to 0.0):
|
| 55 |
+
The LayerDrop probability for the decoder. See the [LayerDrop paper](https://huggingface.co/papers/1909.11556) for
|
| 56 |
+
more details.
|
| 57 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 58 |
+
Whether the model should return the last key/values attentions (not used by all models).
|
| 59 |
+
is_encoder_decoder (`bool`, *optional*, defaults to `True`):
|
| 60 |
+
Whether the model is set up as an encoder-decoder architecture for sequence-to-sequence tasks.
|
| 61 |
+
activation_function (`str` or `function`, *optional*, defaults to `"relu"`):
|
| 62 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 63 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 64 |
+
d_model (`int`, *optional*, defaults to 256):
|
| 65 |
+
Dimensionality of the layers and the pooler layer.
|
| 66 |
+
dropout (`float`, *optional*, defaults to 0.1):
|
| 67 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 68 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 69 |
+
The dropout ratio for the attention probabilities.
|
| 70 |
+
activation_dropout (`float`, *optional*, defaults to 0.0):
|
| 71 |
+
The dropout ratio for activations inside the fully connected layer.
|
| 72 |
+
init_std (`float`, *optional*, defaults to 0.02):
|
| 73 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 74 |
+
decoder_start_token_id (`int`, *optional*, defaults to 2):
|
| 75 |
+
The initial token ID of the decoder when decoding sequences.
|
| 76 |
+
scale_embedding (`bool`, *optional*, defaults to `True`):
|
| 77 |
+
Whether the embeddings are scaled by the square root of `d_model`.
|
| 78 |
+
pad_token_id (`int`, *optional*, defaults to 1):
|
| 79 |
+
Padding token id.
|
| 80 |
+
bos_token_id (`int`, *optional*, defaults to 0):
|
| 81 |
+
The id of the beginning-of-sequence token.
|
| 82 |
+
eos_token_id (`int`, *optional*, defaults to 2):
|
| 83 |
+
The id of the end-of-sequence token.
|
| 84 |
+
max_source_positions (`int`, *optional*, defaults to 6000):
|
| 85 |
+
The maximum sequence length of log-mel filter-bank features that this model might ever be used with.
|
| 86 |
+
max_target_positions (`int`, *optional*, defaults to 1024):
|
| 87 |
+
The maximum sequence length that this model might ever be used with. Typically, set this to something large
|
| 88 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 89 |
+
num_conv_layers (`int`, *optional*, defaults to 2):
|
| 90 |
+
Number of 1D convolutional layers in the conv module.
|
| 91 |
+
conv_kernel_sizes (`tuple[int]`, *optional*, defaults to `(5, 5)`):
|
| 92 |
+
A tuple of integers defining the kernel size of each 1D convolutional layer in the conv module. The length
|
| 93 |
+
of `conv_kernel_sizes` has to match `num_conv_layers`.
|
| 94 |
+
conv_channels (`int`, *optional*, defaults to 1024):
|
| 95 |
+
An integer defining the number of output channels of each convolution layers except the final one in the
|
| 96 |
+
conv module.
|
| 97 |
+
input_feat_per_channel (`int`, *optional*, defaults to 80):
|
| 98 |
+
An integer specifying the size of feature vector. This is also the dimensions of log-mel filter-bank
|
| 99 |
+
features.
|
| 100 |
+
input_channels (`int`, *optional*, defaults to 1):
|
| 101 |
+
An integer specifying number of input channels of the input feature vector.
|
| 102 |
+
|
| 103 |
+
Example:
|
| 104 |
+
|
| 105 |
+
```python
|
| 106 |
+
>>> from transformers import Speech2TextConfig, Speech2TextModel
|
| 107 |
+
|
| 108 |
+
>>> # Initializing a Speech2Text s2t_transformer_s style configuration
|
| 109 |
+
>>> configuration = Speech2TextConfig()
|
| 110 |
+
|
| 111 |
+
>>> # Initializing a model (with random weights) from the s2t_transformer_s style configuration
|
| 112 |
+
>>> model = Speech2TextModel(configuration)
|
| 113 |
+
|
| 114 |
+
>>> # Accessing the model configuration
|
| 115 |
+
>>> configuration = model.config
|
| 116 |
+
```"""
|
| 117 |
+
|
| 118 |
+
model_type = "speech_to_text"
|
| 119 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 120 |
+
attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
|
| 121 |
+
|
| 122 |
+
def __init__(
|
| 123 |
+
self,
|
| 124 |
+
vocab_size=10000,
|
| 125 |
+
encoder_layers=12,
|
| 126 |
+
encoder_ffn_dim=2048,
|
| 127 |
+
encoder_attention_heads=4,
|
| 128 |
+
decoder_layers=6,
|
| 129 |
+
decoder_ffn_dim=2048,
|
| 130 |
+
decoder_attention_heads=4,
|
| 131 |
+
encoder_layerdrop=0.0,
|
| 132 |
+
decoder_layerdrop=0.0,
|
| 133 |
+
use_cache=True,
|
| 134 |
+
is_encoder_decoder=True,
|
| 135 |
+
activation_function="relu",
|
| 136 |
+
d_model=256,
|
| 137 |
+
dropout=0.1,
|
| 138 |
+
attention_dropout=0.0,
|
| 139 |
+
activation_dropout=0.0,
|
| 140 |
+
init_std=0.02,
|
| 141 |
+
decoder_start_token_id=2,
|
| 142 |
+
scale_embedding=True,
|
| 143 |
+
pad_token_id=1,
|
| 144 |
+
bos_token_id=0,
|
| 145 |
+
eos_token_id=2,
|
| 146 |
+
max_source_positions=6000,
|
| 147 |
+
max_target_positions=1024,
|
| 148 |
+
num_conv_layers=2,
|
| 149 |
+
conv_kernel_sizes=(5, 5),
|
| 150 |
+
conv_channels=1024,
|
| 151 |
+
input_feat_per_channel=80,
|
| 152 |
+
input_channels=1,
|
| 153 |
+
**kwargs,
|
| 154 |
+
):
|
| 155 |
+
self.vocab_size = vocab_size
|
| 156 |
+
self.d_model = d_model
|
| 157 |
+
self.encoder_ffn_dim = encoder_ffn_dim
|
| 158 |
+
self.encoder_layers = encoder_layers
|
| 159 |
+
self.encoder_attention_heads = encoder_attention_heads
|
| 160 |
+
self.decoder_ffn_dim = decoder_ffn_dim
|
| 161 |
+
self.decoder_layers = decoder_layers
|
| 162 |
+
self.decoder_attention_heads = decoder_attention_heads
|
| 163 |
+
self.dropout = dropout
|
| 164 |
+
self.attention_dropout = attention_dropout
|
| 165 |
+
self.activation_dropout = activation_dropout
|
| 166 |
+
self.activation_function = activation_function
|
| 167 |
+
self.init_std = init_std
|
| 168 |
+
self.encoder_layerdrop = encoder_layerdrop
|
| 169 |
+
self.decoder_layerdrop = decoder_layerdrop
|
| 170 |
+
self.use_cache = use_cache
|
| 171 |
+
self.num_hidden_layers = encoder_layers
|
| 172 |
+
self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
|
| 173 |
+
self.max_source_positions = max_source_positions
|
| 174 |
+
self.max_target_positions = max_target_positions
|
| 175 |
+
self.num_conv_layers = num_conv_layers
|
| 176 |
+
self.conv_kernel_sizes = list(conv_kernel_sizes)
|
| 177 |
+
self.conv_channels = conv_channels
|
| 178 |
+
self.input_feat_per_channel = input_feat_per_channel
|
| 179 |
+
self.input_channels = input_channels
|
| 180 |
+
|
| 181 |
+
if len(self.conv_kernel_sizes) != self.num_conv_layers:
|
| 182 |
+
raise ValueError(
|
| 183 |
+
"Configuration for convolutional module is incorrect. "
|
| 184 |
+
"It is required that `len(config.conv_kernel_sizes)` == `config.num_conv_layers` "
|
| 185 |
+
f"but is `len(config.conv_kernel_sizes) = {len(self.conv_kernel_sizes)}`, "
|
| 186 |
+
f"`config.num_conv_layers = {self.num_conv_layers}`."
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
super().__init__(
|
| 190 |
+
pad_token_id=pad_token_id,
|
| 191 |
+
bos_token_id=bos_token_id,
|
| 192 |
+
eos_token_id=eos_token_id,
|
| 193 |
+
is_encoder_decoder=is_encoder_decoder,
|
| 194 |
+
decoder_start_token_id=decoder_start_token_id,
|
| 195 |
+
**kwargs,
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
__all__ = ["Speech2TextConfig"]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-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licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Feature extractor class for Speech2Text
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from typing import Optional, Union
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
|
| 23 |
+
from ...audio_utils import mel_filter_bank, spectrogram, window_function
|
| 24 |
+
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
|
| 25 |
+
from ...feature_extraction_utils import BatchFeature
|
| 26 |
+
from ...utils import PaddingStrategy, TensorType, is_speech_available, logging
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if is_speech_available():
|
| 30 |
+
import torch
|
| 31 |
+
import torchaudio.compliance.kaldi as ta_kaldi
|
| 32 |
+
|
| 33 |
+
logger = logging.get_logger(__name__)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class Speech2TextFeatureExtractor(SequenceFeatureExtractor):
|
| 37 |
+
r"""
|
| 38 |
+
Constructs a Speech2Text feature extractor.
|
| 39 |
+
|
| 40 |
+
This feature extractor inherits from [`Speech2TextFeatureExtractor`] which contains most of the main methods. Users
|
| 41 |
+
should refer to this superclass for more information regarding those methods.
|
| 42 |
+
|
| 43 |
+
This class extracts mel-filter bank features from raw speech using TorchAudio if installed or using numpy
|
| 44 |
+
otherwise, and applies utterance-level cepstral mean and variance normalization to the extracted features.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
feature_size (`int`, *optional*, defaults to 80):
|
| 48 |
+
The feature dimension of the extracted features.
|
| 49 |
+
sampling_rate (`int`, *optional*, defaults to 16000):
|
| 50 |
+
The sampling rate at which the audio files should be digitalized expressed in hertz (Hz).
|
| 51 |
+
num_mel_bins (`int`, *optional*, defaults to 80):
|
| 52 |
+
Number of Mel-frequency bins.
|
| 53 |
+
padding_value (`float`, *optional*, defaults to 0.0):
|
| 54 |
+
The value that is used to fill the padding vectors.
|
| 55 |
+
dither (`float`, *optional*, defaults to 0.0):
|
| 56 |
+
Adds dithering. In other words, adds a small Gaussian noise to each frame.
|
| 57 |
+
E.g. use 4.0 to add dithering with a normal distribution centered
|
| 58 |
+
around 0.0 with standard deviation 4.0 (assuming [-32k,+32k] range of kaldi waveform).
|
| 59 |
+
The value 0.0 means no dithering.
|
| 60 |
+
Dithering has similar effect as `mel_floor`. It reduces the high log_mel_fbank
|
| 61 |
+
values for signals with hard-zero sections, when VAD cutoff is present in the signal.
|
| 62 |
+
do_ceptral_normalize (`bool`, *optional*, defaults to `True`):
|
| 63 |
+
Whether or not to apply utterance-level cepstral mean and variance normalization to extracted features.
|
| 64 |
+
normalize_means (`bool`, *optional*, defaults to `True`):
|
| 65 |
+
Whether or not to zero-mean normalize the extracted features.
|
| 66 |
+
normalize_vars (`bool`, *optional*, defaults to `True`):
|
| 67 |
+
Whether or not to unit-variance normalize the extracted features.
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
model_input_names = ["input_features", "attention_mask"]
|
| 71 |
+
|
| 72 |
+
def __init__(
|
| 73 |
+
self,
|
| 74 |
+
feature_size=80,
|
| 75 |
+
sampling_rate=16000,
|
| 76 |
+
num_mel_bins=80,
|
| 77 |
+
padding_value=0.0,
|
| 78 |
+
dither=0.0,
|
| 79 |
+
do_ceptral_normalize=True,
|
| 80 |
+
normalize_means=True,
|
| 81 |
+
normalize_vars=True,
|
| 82 |
+
**kwargs,
|
| 83 |
+
):
|
| 84 |
+
super().__init__(feature_size=feature_size, sampling_rate=sampling_rate, padding_value=padding_value, **kwargs)
|
| 85 |
+
self.num_mel_bins = num_mel_bins
|
| 86 |
+
self.dither = dither
|
| 87 |
+
self.do_ceptral_normalize = do_ceptral_normalize
|
| 88 |
+
self.normalize_means = normalize_means
|
| 89 |
+
self.normalize_vars = normalize_vars
|
| 90 |
+
self.return_attention_mask = True
|
| 91 |
+
|
| 92 |
+
if not is_speech_available():
|
| 93 |
+
mel_filters = mel_filter_bank(
|
| 94 |
+
num_frequency_bins=257,
|
| 95 |
+
num_mel_filters=self.num_mel_bins,
|
| 96 |
+
min_frequency=20,
|
| 97 |
+
max_frequency=sampling_rate // 2,
|
| 98 |
+
sampling_rate=sampling_rate,
|
| 99 |
+
norm=None,
|
| 100 |
+
mel_scale="kaldi",
|
| 101 |
+
triangularize_in_mel_space=True,
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
self.mel_filters = mel_filters
|
| 105 |
+
self.window = window_function(400, "povey", periodic=False)
|
| 106 |
+
|
| 107 |
+
def _extract_fbank_features(
|
| 108 |
+
self,
|
| 109 |
+
waveform: np.ndarray,
|
| 110 |
+
) -> np.ndarray:
|
| 111 |
+
"""
|
| 112 |
+
Get mel-filter bank features using TorchAudio. Note that TorchAudio requires 16-bit signed integers as inputs
|
| 113 |
+
and hence the waveform should not be normalized before feature extraction.
|
| 114 |
+
"""
|
| 115 |
+
waveform = waveform * (2**15) # Kaldi compliance: 16-bit signed integers
|
| 116 |
+
if is_speech_available():
|
| 117 |
+
waveform = torch.from_numpy(waveform).unsqueeze(0)
|
| 118 |
+
features = ta_kaldi.fbank(
|
| 119 |
+
waveform,
|
| 120 |
+
dither=self.dither,
|
| 121 |
+
num_mel_bins=self.num_mel_bins,
|
| 122 |
+
sample_frequency=self.sampling_rate,
|
| 123 |
+
)
|
| 124 |
+
features = features.numpy()
|
| 125 |
+
else:
|
| 126 |
+
waveform = np.squeeze(waveform)
|
| 127 |
+
features = spectrogram(
|
| 128 |
+
waveform,
|
| 129 |
+
self.window,
|
| 130 |
+
frame_length=400,
|
| 131 |
+
hop_length=160,
|
| 132 |
+
fft_length=512,
|
| 133 |
+
power=2.0,
|
| 134 |
+
center=False,
|
| 135 |
+
dither=self.dither,
|
| 136 |
+
preemphasis=0.97,
|
| 137 |
+
mel_filters=self.mel_filters,
|
| 138 |
+
log_mel="log",
|
| 139 |
+
mel_floor=1.192092955078125e-07,
|
| 140 |
+
remove_dc_offset=True,
|
| 141 |
+
).T
|
| 142 |
+
return features
|
| 143 |
+
|
| 144 |
+
@staticmethod
|
| 145 |
+
def utterance_cmvn(
|
| 146 |
+
x: np.ndarray,
|
| 147 |
+
input_length: int,
|
| 148 |
+
normalize_means: Optional[bool] = True,
|
| 149 |
+
normalize_vars: Optional[bool] = True,
|
| 150 |
+
padding_value: float = 0.0,
|
| 151 |
+
) -> np.ndarray:
|
| 152 |
+
# make sure we normalize float32 arrays
|
| 153 |
+
if normalize_means:
|
| 154 |
+
mean = x[:input_length].mean(axis=0)
|
| 155 |
+
x = np.subtract(x, mean)
|
| 156 |
+
if normalize_vars:
|
| 157 |
+
std = x[:input_length].std(axis=0)
|
| 158 |
+
x = np.divide(x, std)
|
| 159 |
+
|
| 160 |
+
if input_length < x.shape[0]:
|
| 161 |
+
x[input_length:] = padding_value
|
| 162 |
+
|
| 163 |
+
# make sure array is in float32
|
| 164 |
+
x = x.astype(np.float32)
|
| 165 |
+
|
| 166 |
+
return x
|
| 167 |
+
|
| 168 |
+
def normalize(
|
| 169 |
+
self, input_features: list[np.ndarray], attention_mask: Optional[np.ndarray] = None
|
| 170 |
+
) -> list[np.ndarray]:
|
| 171 |
+
lengths = attention_mask.sum(-1) if attention_mask is not None else [x.shape[0] for x in input_features]
|
| 172 |
+
return [
|
| 173 |
+
self.utterance_cmvn(x, n, self.normalize_means, self.normalize_vars, self.padding_value)
|
| 174 |
+
for x, n in zip(input_features, lengths)
|
| 175 |
+
]
|
| 176 |
+
|
| 177 |
+
def __call__(
|
| 178 |
+
self,
|
| 179 |
+
raw_speech: Union[np.ndarray, list[float], list[np.ndarray], list[list[float]]],
|
| 180 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
| 181 |
+
max_length: Optional[int] = None,
|
| 182 |
+
truncation: bool = False,
|
| 183 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 184 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 185 |
+
sampling_rate: Optional[int] = None,
|
| 186 |
+
return_attention_mask: Optional[bool] = None,
|
| 187 |
+
**kwargs,
|
| 188 |
+
) -> BatchFeature:
|
| 189 |
+
"""
|
| 190 |
+
Main method to featurize and prepare for the model one or several sequence(s).
|
| 191 |
+
|
| 192 |
+
Args:
|
| 193 |
+
raw_speech (`np.ndarray`, `list[float]`, `list[np.ndarray]`, `list[list[float]]`):
|
| 194 |
+
The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float
|
| 195 |
+
values, a list of numpy arrays or a list of list of float values. Must be mono channel audio, not
|
| 196 |
+
stereo, i.e. single float per timestep.
|
| 197 |
+
padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):
|
| 198 |
+
Select a strategy to pad the returned sequences (according to the model's padding side and padding
|
| 199 |
+
index) among:
|
| 200 |
+
|
| 201 |
+
- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
|
| 202 |
+
sequence if provided).
|
| 203 |
+
- `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
|
| 204 |
+
acceptable input length for the model if that argument is not provided.
|
| 205 |
+
- `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
|
| 206 |
+
lengths).
|
| 207 |
+
max_length (`int`, *optional*):
|
| 208 |
+
Maximum length of the returned list and optionally padding length (see above).
|
| 209 |
+
truncation (`bool`):
|
| 210 |
+
Activates truncation to cut input sequences longer than *max_length* to *max_length*.
|
| 211 |
+
pad_to_multiple_of (`int`, *optional*):
|
| 212 |
+
If set will pad the sequence to a multiple of the provided value.
|
| 213 |
+
|
| 214 |
+
This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
|
| 215 |
+
`>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128.
|
| 216 |
+
return_attention_mask (`bool`, *optional*):
|
| 217 |
+
Whether to return the attention mask. If left to the default, will return the attention mask according
|
| 218 |
+
to the specific feature_extractor's default.
|
| 219 |
+
|
| 220 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 221 |
+
|
| 222 |
+
<Tip>
|
| 223 |
+
|
| 224 |
+
For Speech2TextTransformer models, `attention_mask` should always be passed for batched inference, to
|
| 225 |
+
avoid subtle bugs.
|
| 226 |
+
|
| 227 |
+
</Tip>
|
| 228 |
+
|
| 229 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 230 |
+
If set, will return tensors instead of list of python integers. Acceptable values are:
|
| 231 |
+
|
| 232 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 233 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 234 |
+
- `'np'`: Return Numpy `np.ndarray` objects.
|
| 235 |
+
sampling_rate (`int`, *optional*):
|
| 236 |
+
The sampling rate at which the `raw_speech` input was sampled. It is strongly recommended to pass
|
| 237 |
+
`sampling_rate` at the forward call to prevent silent errors.
|
| 238 |
+
padding_value (`float`, *optional*, defaults to 0.0):
|
| 239 |
+
The value that is used to fill the padding values / vectors.
|
| 240 |
+
"""
|
| 241 |
+
|
| 242 |
+
if sampling_rate is not None:
|
| 243 |
+
if sampling_rate != self.sampling_rate:
|
| 244 |
+
raise ValueError(
|
| 245 |
+
f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of"
|
| 246 |
+
f" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with"
|
| 247 |
+
f" {self.sampling_rate} and not {sampling_rate}."
|
| 248 |
+
)
|
| 249 |
+
else:
|
| 250 |
+
logger.warning(
|
| 251 |
+
f"It is strongly recommended to pass the `sampling_rate` argument to `{self.__class__.__name__}()`. "
|
| 252 |
+
"Failing to do so can result in silent errors that might be hard to debug."
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
is_batched_numpy = isinstance(raw_speech, np.ndarray) and len(raw_speech.shape) > 1
|
| 256 |
+
if is_batched_numpy and len(raw_speech.shape) > 2:
|
| 257 |
+
raise ValueError(f"Only mono-channel audio is supported for input to {self}")
|
| 258 |
+
is_batched = is_batched_numpy or (
|
| 259 |
+
isinstance(raw_speech, (list, tuple)) and (isinstance(raw_speech[0], (np.ndarray, tuple, list)))
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
if is_batched:
|
| 263 |
+
raw_speech = [np.asarray(speech, dtype=np.float32) for speech in raw_speech]
|
| 264 |
+
elif not is_batched and not isinstance(raw_speech, np.ndarray):
|
| 265 |
+
raw_speech = np.asarray(raw_speech, dtype=np.float32)
|
| 266 |
+
elif isinstance(raw_speech, np.ndarray) and raw_speech.dtype is np.dtype(np.float64):
|
| 267 |
+
raw_speech = raw_speech.astype(np.float32)
|
| 268 |
+
|
| 269 |
+
# always return batch
|
| 270 |
+
if not is_batched:
|
| 271 |
+
raw_speech = [raw_speech]
|
| 272 |
+
|
| 273 |
+
# extract fbank features
|
| 274 |
+
features = [self._extract_fbank_features(waveform) for waveform in raw_speech]
|
| 275 |
+
|
| 276 |
+
# convert into correct format for padding
|
| 277 |
+
encoded_inputs = BatchFeature({"input_features": features})
|
| 278 |
+
|
| 279 |
+
padded_inputs = self.pad(
|
| 280 |
+
encoded_inputs,
|
| 281 |
+
padding=padding,
|
| 282 |
+
max_length=max_length,
|
| 283 |
+
truncation=truncation,
|
| 284 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 285 |
+
return_attention_mask=return_attention_mask,
|
| 286 |
+
**kwargs,
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
# make sure list is in array format
|
| 290 |
+
input_features = padded_inputs.get("input_features")
|
| 291 |
+
if isinstance(input_features[0], list):
|
| 292 |
+
padded_inputs["input_features"] = [np.asarray(feature, dtype=np.float32) for feature in input_features]
|
| 293 |
+
|
| 294 |
+
attention_mask = padded_inputs.get("attention_mask")
|
| 295 |
+
if attention_mask is not None:
|
| 296 |
+
padded_inputs["attention_mask"] = [np.asarray(array, dtype=np.int32) for array in attention_mask]
|
| 297 |
+
|
| 298 |
+
# Utterance-level cepstral mean and variance normalization
|
| 299 |
+
if self.do_ceptral_normalize:
|
| 300 |
+
attention_mask = (
|
| 301 |
+
np.array(attention_mask, dtype=np.int32)
|
| 302 |
+
if self._get_padding_strategies(padding, max_length=max_length) is not PaddingStrategy.DO_NOT_PAD
|
| 303 |
+
else None
|
| 304 |
+
)
|
| 305 |
+
padded_inputs["input_features"] = self.normalize(
|
| 306 |
+
padded_inputs["input_features"], attention_mask=attention_mask
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
if return_tensors is not None:
|
| 310 |
+
padded_inputs = padded_inputs.convert_to_tensors(return_tensors)
|
| 311 |
+
|
| 312 |
+
return padded_inputs
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
__all__ = ["Speech2TextFeatureExtractor"]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speech_to_text/modeling_speech_to_text.py
ADDED
|
@@ -0,0 +1,1336 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch Speech2Text model."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
from typing import Callable, Optional, Union
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
from torch import nn
|
| 22 |
+
from torch.nn import CrossEntropyLoss
|
| 23 |
+
|
| 24 |
+
from ...activations import ACT2FN
|
| 25 |
+
from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
|
| 26 |
+
from ...generation import GenerationMixin
|
| 27 |
+
from ...modeling_attn_mask_utils import (
|
| 28 |
+
_prepare_4d_attention_mask,
|
| 29 |
+
_prepare_4d_attention_mask_for_sdpa,
|
| 30 |
+
_prepare_4d_causal_attention_mask,
|
| 31 |
+
_prepare_4d_causal_attention_mask_for_sdpa,
|
| 32 |
+
)
|
| 33 |
+
from ...modeling_flash_attention_utils import FlashAttentionKwargs
|
| 34 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 35 |
+
from ...modeling_outputs import (
|
| 36 |
+
BaseModelOutput,
|
| 37 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 38 |
+
Seq2SeqLMOutput,
|
| 39 |
+
Seq2SeqModelOutput,
|
| 40 |
+
)
|
| 41 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 42 |
+
from ...processing_utils import Unpack
|
| 43 |
+
from ...utils import (
|
| 44 |
+
auto_docstring,
|
| 45 |
+
is_torch_flex_attn_available,
|
| 46 |
+
logging,
|
| 47 |
+
)
|
| 48 |
+
from ...utils.deprecation import deprecate_kwarg
|
| 49 |
+
from .configuration_speech_to_text import Speech2TextConfig
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
if is_torch_flex_attn_available():
|
| 53 |
+
from ...integrations.flex_attention import make_flex_block_causal_mask
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
logger = logging.get_logger(__name__)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# Copied from transformers.models.bart.modeling_bart.shift_tokens_right
|
| 60 |
+
def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
|
| 61 |
+
"""
|
| 62 |
+
Shift input ids one token to the right.
|
| 63 |
+
"""
|
| 64 |
+
shifted_input_ids = input_ids.new_zeros(input_ids.shape)
|
| 65 |
+
shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
|
| 66 |
+
shifted_input_ids[:, 0] = decoder_start_token_id
|
| 67 |
+
|
| 68 |
+
if pad_token_id is None:
|
| 69 |
+
raise ValueError("self.model.config.pad_token_id has to be defined.")
|
| 70 |
+
# replace possible -100 values in labels by `pad_token_id`
|
| 71 |
+
shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
|
| 72 |
+
|
| 73 |
+
return shifted_input_ids
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class Conv1dSubsampler(nn.Module):
|
| 77 |
+
"""
|
| 78 |
+
Convolutional subsampler: a stack of 1D convolution (along temporal dimension) followed by non-linear activation
|
| 79 |
+
via gated linear units (https://huggingface.co/papers/1911.08460)
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
def __init__(self, config):
|
| 83 |
+
super().__init__()
|
| 84 |
+
self.config = config
|
| 85 |
+
self.num_layers = config.num_conv_layers
|
| 86 |
+
self.in_channels = config.input_feat_per_channel * config.input_channels
|
| 87 |
+
self.mid_channels = config.conv_channels
|
| 88 |
+
self.out_channels = config.d_model
|
| 89 |
+
self.kernel_sizes = config.conv_kernel_sizes
|
| 90 |
+
|
| 91 |
+
self.conv_layers = nn.ModuleList(
|
| 92 |
+
nn.Conv1d(
|
| 93 |
+
self.in_channels if i == 0 else self.mid_channels // 2,
|
| 94 |
+
self.mid_channels if i < self.num_layers - 1 else self.out_channels * 2,
|
| 95 |
+
kernel_size=k,
|
| 96 |
+
stride=2,
|
| 97 |
+
padding=k // 2,
|
| 98 |
+
)
|
| 99 |
+
for i, k in enumerate(self.kernel_sizes)
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
def forward(self, input_features):
|
| 103 |
+
hidden_states = input_features.transpose(1, 2).contiguous() # -> B x (C x D) x T
|
| 104 |
+
for conv in self.conv_layers:
|
| 105 |
+
hidden_states = conv(hidden_states)
|
| 106 |
+
hidden_states = nn.functional.glu(hidden_states, dim=1)
|
| 107 |
+
hidden_states = hidden_states.transpose(1, 2).contiguous() # -> T x B x (C x D)
|
| 108 |
+
return hidden_states
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class Speech2TextSinusoidalPositionalEmbedding(nn.Module):
|
| 112 |
+
"""This module produces sinusoidal positional embeddings of any length."""
|
| 113 |
+
|
| 114 |
+
def __init__(self, num_positions: int, embedding_dim: int, padding_idx: Optional[int] = None):
|
| 115 |
+
super().__init__()
|
| 116 |
+
self.offset = 2
|
| 117 |
+
self.embedding_dim = embedding_dim
|
| 118 |
+
self.padding_idx = padding_idx
|
| 119 |
+
self.make_weights(num_positions + self.offset, embedding_dim, padding_idx)
|
| 120 |
+
|
| 121 |
+
def make_weights(self, num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None):
|
| 122 |
+
emb_weights = self.get_embedding(num_embeddings, embedding_dim, padding_idx)
|
| 123 |
+
if hasattr(self, "weights"):
|
| 124 |
+
# in forward put the weights on the correct dtype and device of the param
|
| 125 |
+
emb_weights = emb_weights.to(dtype=self.weights.dtype, device=self.weights.device)
|
| 126 |
+
|
| 127 |
+
self.register_buffer("weights", emb_weights, persistent=False)
|
| 128 |
+
|
| 129 |
+
@staticmethod
|
| 130 |
+
def get_embedding(num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None):
|
| 131 |
+
"""
|
| 132 |
+
Build sinusoidal embeddings. This matches the implementation in tensor2tensor, but differs slightly from the
|
| 133 |
+
description in Section 3.5 of "Attention Is All You Need".
|
| 134 |
+
"""
|
| 135 |
+
half_dim = embedding_dim // 2
|
| 136 |
+
emb = math.log(10000) / (half_dim - 1)
|
| 137 |
+
emb = torch.exp(torch.arange(half_dim, dtype=torch.int64).float() * -emb)
|
| 138 |
+
emb = torch.arange(num_embeddings, dtype=torch.int64).float().unsqueeze(1) * emb.unsqueeze(0)
|
| 139 |
+
emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1)
|
| 140 |
+
if embedding_dim % 2 == 1:
|
| 141 |
+
# zero pad
|
| 142 |
+
emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1)
|
| 143 |
+
if padding_idx is not None:
|
| 144 |
+
emb[padding_idx, :] = 0
|
| 145 |
+
return emb.to(torch.get_default_dtype())
|
| 146 |
+
|
| 147 |
+
@torch.no_grad()
|
| 148 |
+
def forward(self, input_ids: torch.Tensor, past_key_values_length: int = 0):
|
| 149 |
+
bsz, seq_len = input_ids.size()
|
| 150 |
+
# Create the position ids from the input token ids. Any padded tokens remain padded.
|
| 151 |
+
position_ids = self.create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length).to(
|
| 152 |
+
input_ids.device
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
# expand embeddings if needed
|
| 156 |
+
max_pos = self.padding_idx + 1 + seq_len
|
| 157 |
+
if max_pos > self.weights.size(0):
|
| 158 |
+
self.make_weights(max_pos + self.offset, self.embedding_dim, self.padding_idx)
|
| 159 |
+
|
| 160 |
+
return self.weights.index_select(0, position_ids.view(-1)).view(bsz, seq_len, -1).detach()
|
| 161 |
+
|
| 162 |
+
def create_position_ids_from_input_ids(
|
| 163 |
+
self, input_ids: torch.Tensor, padding_idx: int, past_key_values_length: Optional[int] = 0
|
| 164 |
+
):
|
| 165 |
+
"""
|
| 166 |
+
Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding
|
| 167 |
+
symbols are ignored. This is modified from fairseq's `utils.make_positions`.
|
| 168 |
+
|
| 169 |
+
Args:
|
| 170 |
+
x: torch.Tensor x:
|
| 171 |
+
Returns: torch.Tensor
|
| 172 |
+
"""
|
| 173 |
+
# The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
|
| 174 |
+
mask = input_ids.ne(padding_idx).int()
|
| 175 |
+
incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
|
| 176 |
+
return incremental_indices.long() + padding_idx
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
# Copied from transformers.models.bart.modeling_bart.eager_attention_forward
|
| 180 |
+
def eager_attention_forward(
|
| 181 |
+
module: nn.Module,
|
| 182 |
+
query: torch.Tensor,
|
| 183 |
+
key: torch.Tensor,
|
| 184 |
+
value: torch.Tensor,
|
| 185 |
+
attention_mask: Optional[torch.Tensor],
|
| 186 |
+
scaling: Optional[float] = None,
|
| 187 |
+
dropout: float = 0.0,
|
| 188 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 189 |
+
**kwargs,
|
| 190 |
+
):
|
| 191 |
+
if scaling is None:
|
| 192 |
+
scaling = query.size(-1) ** -0.5
|
| 193 |
+
|
| 194 |
+
attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
|
| 195 |
+
if attention_mask is not None:
|
| 196 |
+
attn_weights = attn_weights + attention_mask
|
| 197 |
+
|
| 198 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 199 |
+
|
| 200 |
+
if head_mask is not None:
|
| 201 |
+
attn_weights = attn_weights * head_mask.view(1, -1, 1, 1)
|
| 202 |
+
|
| 203 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 204 |
+
attn_output = torch.matmul(attn_weights, value)
|
| 205 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 206 |
+
|
| 207 |
+
return attn_output, attn_weights
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
# Copied from transformers.models.musicgen.modeling_musicgen.MusicgenAttention with Musicgen->Speech2Text
|
| 211 |
+
class Speech2TextAttention(nn.Module):
|
| 212 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 213 |
+
|
| 214 |
+
def __init__(
|
| 215 |
+
self,
|
| 216 |
+
embed_dim: int,
|
| 217 |
+
num_heads: int,
|
| 218 |
+
dropout: Optional[float] = 0.0,
|
| 219 |
+
is_decoder: Optional[bool] = False,
|
| 220 |
+
bias: Optional[bool] = True,
|
| 221 |
+
is_causal: Optional[bool] = False,
|
| 222 |
+
config: Optional[Speech2TextConfig] = None,
|
| 223 |
+
layer_idx: Optional[int] = None,
|
| 224 |
+
):
|
| 225 |
+
super().__init__()
|
| 226 |
+
self.embed_dim = embed_dim
|
| 227 |
+
self.num_heads = num_heads
|
| 228 |
+
self.dropout = dropout
|
| 229 |
+
self.head_dim = embed_dim // num_heads
|
| 230 |
+
self.config = config
|
| 231 |
+
|
| 232 |
+
if (self.head_dim * num_heads) != self.embed_dim:
|
| 233 |
+
raise ValueError(
|
| 234 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
|
| 235 |
+
f" and `num_heads`: {num_heads})."
|
| 236 |
+
)
|
| 237 |
+
self.scaling = self.head_dim**-0.5
|
| 238 |
+
self.is_decoder = is_decoder
|
| 239 |
+
self.is_causal = is_causal
|
| 240 |
+
self.layer_idx = layer_idx
|
| 241 |
+
|
| 242 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 243 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 244 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 245 |
+
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 246 |
+
|
| 247 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 248 |
+
def forward(
|
| 249 |
+
self,
|
| 250 |
+
hidden_states: torch.Tensor,
|
| 251 |
+
key_value_states: Optional[torch.Tensor] = None,
|
| 252 |
+
past_key_values: Optional[Cache] = None,
|
| 253 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 254 |
+
layer_head_mask: Optional[torch.Tensor] = None,
|
| 255 |
+
output_attentions: Optional[bool] = False,
|
| 256 |
+
cache_position: Optional[torch.Tensor] = None,
|
| 257 |
+
# TODO: we need a refactor so that the different attention modules can get their specific kwargs
|
| 258 |
+
# ATM, we have mixed things encoder, decoder, and encoder-decoder attn
|
| 259 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 260 |
+
) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
|
| 261 |
+
"""Input shape: Batch x Time x Channel"""
|
| 262 |
+
|
| 263 |
+
# if key_value_states are provided this layer is used as a cross-attention layer
|
| 264 |
+
# for the decoder
|
| 265 |
+
is_cross_attention = key_value_states is not None
|
| 266 |
+
|
| 267 |
+
# determine input shapes
|
| 268 |
+
bsz, tgt_len = hidden_states.shape[:-1]
|
| 269 |
+
src_len = key_value_states.shape[1] if is_cross_attention else tgt_len
|
| 270 |
+
|
| 271 |
+
q_input_shape = (bsz, tgt_len, -1, self.head_dim)
|
| 272 |
+
kv_input_shape = (bsz, src_len, -1, self.head_dim)
|
| 273 |
+
|
| 274 |
+
# get query proj
|
| 275 |
+
query_states = self.q_proj(hidden_states).view(*q_input_shape).transpose(1, 2)
|
| 276 |
+
|
| 277 |
+
if past_key_values is not None:
|
| 278 |
+
if isinstance(past_key_values, EncoderDecoderCache):
|
| 279 |
+
is_updated = past_key_values.is_updated.get(self.layer_idx)
|
| 280 |
+
if is_cross_attention:
|
| 281 |
+
# after the first generated id, we can subsequently re-use all key/value_layer from cache
|
| 282 |
+
curr_past_key_value = past_key_values.cross_attention_cache
|
| 283 |
+
else:
|
| 284 |
+
curr_past_key_value = past_key_values.self_attention_cache
|
| 285 |
+
else:
|
| 286 |
+
curr_past_key_value = past_key_values
|
| 287 |
+
|
| 288 |
+
current_states = key_value_states if is_cross_attention else hidden_states
|
| 289 |
+
if is_cross_attention and past_key_values is not None and is_updated:
|
| 290 |
+
# reuse k,v, cross_attentions
|
| 291 |
+
key_states = curr_past_key_value.layers[self.layer_idx].keys
|
| 292 |
+
value_states = curr_past_key_value.layers[self.layer_idx].values
|
| 293 |
+
else:
|
| 294 |
+
key_states = self.k_proj(current_states).view(*kv_input_shape).transpose(1, 2)
|
| 295 |
+
value_states = self.v_proj(current_states).view(*kv_input_shape).transpose(1, 2)
|
| 296 |
+
|
| 297 |
+
if past_key_values is not None:
|
| 298 |
+
# save all key/value_states to cache to be re-used for fast auto-regressive generation
|
| 299 |
+
cache_position = cache_position if not is_cross_attention else None
|
| 300 |
+
key_states, value_states = curr_past_key_value.update(
|
| 301 |
+
key_states, value_states, self.layer_idx, {"cache_position": cache_position}
|
| 302 |
+
)
|
| 303 |
+
# set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
|
| 304 |
+
if is_cross_attention:
|
| 305 |
+
past_key_values.is_updated[self.layer_idx] = True
|
| 306 |
+
|
| 307 |
+
attention_interface: Callable = eager_attention_forward
|
| 308 |
+
if self.config._attn_implementation != "eager":
|
| 309 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 310 |
+
|
| 311 |
+
attn_output, attn_weights = attention_interface(
|
| 312 |
+
self,
|
| 313 |
+
query_states,
|
| 314 |
+
key_states,
|
| 315 |
+
value_states,
|
| 316 |
+
attention_mask,
|
| 317 |
+
dropout=0.0 if not self.training else self.dropout,
|
| 318 |
+
scaling=self.scaling,
|
| 319 |
+
output_attentions=output_attentions,
|
| 320 |
+
head_mask=layer_head_mask,
|
| 321 |
+
**kwargs,
|
| 322 |
+
)
|
| 323 |
+
|
| 324 |
+
attn_output = attn_output.reshape(bsz, tgt_len, -1).contiguous()
|
| 325 |
+
attn_output = self.out_proj(attn_output)
|
| 326 |
+
|
| 327 |
+
return attn_output, attn_weights
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
# Copied from transformers.models.mbart.modeling_mbart.MBartEncoderLayer with MBart->Speech2Text, MBART->SPEECH_TO_TEXT
|
| 331 |
+
class Speech2TextEncoderLayer(GradientCheckpointingLayer):
|
| 332 |
+
def __init__(self, config: Speech2TextConfig):
|
| 333 |
+
super().__init__()
|
| 334 |
+
self.embed_dim = config.d_model
|
| 335 |
+
|
| 336 |
+
self.self_attn = Speech2TextAttention(
|
| 337 |
+
embed_dim=self.embed_dim,
|
| 338 |
+
num_heads=config.encoder_attention_heads,
|
| 339 |
+
dropout=config.attention_dropout,
|
| 340 |
+
config=config,
|
| 341 |
+
)
|
| 342 |
+
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 343 |
+
self.dropout = config.dropout
|
| 344 |
+
self.activation_fn = ACT2FN[config.activation_function]
|
| 345 |
+
self.activation_dropout = config.activation_dropout
|
| 346 |
+
self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
|
| 347 |
+
self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
|
| 348 |
+
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 349 |
+
|
| 350 |
+
def forward(
|
| 351 |
+
self,
|
| 352 |
+
hidden_states: torch.Tensor,
|
| 353 |
+
attention_mask: torch.Tensor,
|
| 354 |
+
layer_head_mask: torch.Tensor,
|
| 355 |
+
output_attentions: bool = False,
|
| 356 |
+
) -> torch.Tensor:
|
| 357 |
+
"""
|
| 358 |
+
Args:
|
| 359 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 360 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
| 361 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 362 |
+
layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
|
| 363 |
+
`(encoder_attention_heads,)`.
|
| 364 |
+
output_attentions (`bool`, *optional*):
|
| 365 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 366 |
+
returned tensors for more detail.
|
| 367 |
+
"""
|
| 368 |
+
residual = hidden_states
|
| 369 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 370 |
+
hidden_states, attn_weights = self.self_attn(
|
| 371 |
+
hidden_states=hidden_states,
|
| 372 |
+
attention_mask=attention_mask,
|
| 373 |
+
layer_head_mask=layer_head_mask,
|
| 374 |
+
output_attentions=output_attentions,
|
| 375 |
+
)
|
| 376 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 377 |
+
hidden_states = residual + hidden_states
|
| 378 |
+
|
| 379 |
+
residual = hidden_states
|
| 380 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 381 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 382 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
|
| 383 |
+
hidden_states = self.fc2(hidden_states)
|
| 384 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 385 |
+
hidden_states = residual + hidden_states
|
| 386 |
+
|
| 387 |
+
if hidden_states.dtype == torch.float16:
|
| 388 |
+
clamp_value = torch.finfo(hidden_states.dtype).max - 1000
|
| 389 |
+
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
|
| 390 |
+
|
| 391 |
+
return hidden_states, attn_weights
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
# copied from transformers.models.mbart.modeling_mbart.MBartDecoderLayer with MBart->Speech2Text, MBART->SPEECH_TO_TEXT
|
| 395 |
+
# TODO: change copy when applying cache class
|
| 396 |
+
class Speech2TextDecoderLayer(GradientCheckpointingLayer):
|
| 397 |
+
def __init__(self, config: Speech2TextConfig, layer_idx=None):
|
| 398 |
+
super().__init__()
|
| 399 |
+
self.embed_dim = config.d_model
|
| 400 |
+
|
| 401 |
+
self.self_attn = Speech2TextAttention(
|
| 402 |
+
embed_dim=self.embed_dim,
|
| 403 |
+
num_heads=config.decoder_attention_heads,
|
| 404 |
+
dropout=config.attention_dropout,
|
| 405 |
+
is_decoder=True,
|
| 406 |
+
is_causal=True,
|
| 407 |
+
config=config,
|
| 408 |
+
layer_idx=layer_idx,
|
| 409 |
+
)
|
| 410 |
+
self.dropout = config.dropout
|
| 411 |
+
self.activation_fn = ACT2FN[config.activation_function]
|
| 412 |
+
self.activation_dropout = config.activation_dropout
|
| 413 |
+
|
| 414 |
+
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 415 |
+
self.encoder_attn = Speech2TextAttention(
|
| 416 |
+
self.embed_dim,
|
| 417 |
+
config.decoder_attention_heads,
|
| 418 |
+
dropout=config.attention_dropout,
|
| 419 |
+
is_decoder=True,
|
| 420 |
+
config=config,
|
| 421 |
+
layer_idx=layer_idx,
|
| 422 |
+
)
|
| 423 |
+
self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 424 |
+
self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
|
| 425 |
+
self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
|
| 426 |
+
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 427 |
+
|
| 428 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 429 |
+
# Copied from transformers.models.musicgen.modeling_musicgen.MusicgenDecoderLayer.forward
|
| 430 |
+
def forward(
|
| 431 |
+
self,
|
| 432 |
+
hidden_states: torch.Tensor,
|
| 433 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 434 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 435 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 436 |
+
layer_head_mask: Optional[torch.Tensor] = None,
|
| 437 |
+
cross_attn_layer_head_mask: Optional[torch.Tensor] = None,
|
| 438 |
+
past_key_values: Optional[Cache] = None,
|
| 439 |
+
output_attentions: Optional[bool] = False,
|
| 440 |
+
use_cache: Optional[bool] = True,
|
| 441 |
+
cache_position: Optional[torch.Tensor] = None,
|
| 442 |
+
) -> torch.Tensor:
|
| 443 |
+
"""
|
| 444 |
+
Args:
|
| 445 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 446 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
| 447 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 448 |
+
encoder_hidden_states (`torch.FloatTensor`):
|
| 449 |
+
cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 450 |
+
encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
|
| 451 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 452 |
+
layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
|
| 453 |
+
`(encoder_attention_heads,)`.
|
| 454 |
+
cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of
|
| 455 |
+
size `(decoder_attention_heads,)`.
|
| 456 |
+
past_key_values (`Tuple(torch.FloatTensor)`): cached past key and value projection states
|
| 457 |
+
output_attentions (`bool`, *optional*):
|
| 458 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 459 |
+
returned tensors for more detail.
|
| 460 |
+
"""
|
| 461 |
+
residual = hidden_states
|
| 462 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 463 |
+
|
| 464 |
+
# Self Attention
|
| 465 |
+
hidden_states, self_attn_weights = self.self_attn(
|
| 466 |
+
hidden_states=hidden_states,
|
| 467 |
+
past_key_values=past_key_values,
|
| 468 |
+
attention_mask=attention_mask,
|
| 469 |
+
layer_head_mask=layer_head_mask,
|
| 470 |
+
output_attentions=output_attentions,
|
| 471 |
+
cache_position=cache_position,
|
| 472 |
+
)
|
| 473 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 474 |
+
hidden_states = residual + hidden_states
|
| 475 |
+
|
| 476 |
+
# Cross-Attention Block
|
| 477 |
+
cross_attn_weights = None
|
| 478 |
+
if encoder_hidden_states is not None:
|
| 479 |
+
residual = hidden_states
|
| 480 |
+
hidden_states = self.encoder_attn_layer_norm(hidden_states)
|
| 481 |
+
|
| 482 |
+
hidden_states, cross_attn_weights = self.encoder_attn(
|
| 483 |
+
hidden_states=hidden_states,
|
| 484 |
+
key_value_states=encoder_hidden_states,
|
| 485 |
+
attention_mask=encoder_attention_mask,
|
| 486 |
+
layer_head_mask=cross_attn_layer_head_mask,
|
| 487 |
+
past_key_values=past_key_values,
|
| 488 |
+
output_attentions=output_attentions,
|
| 489 |
+
cache_position=cache_position,
|
| 490 |
+
)
|
| 491 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 492 |
+
hidden_states = residual + hidden_states
|
| 493 |
+
|
| 494 |
+
# Fully Connected
|
| 495 |
+
residual = hidden_states
|
| 496 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 497 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 498 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
|
| 499 |
+
hidden_states = self.fc2(hidden_states)
|
| 500 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 501 |
+
hidden_states = residual + hidden_states
|
| 502 |
+
|
| 503 |
+
outputs = (hidden_states,)
|
| 504 |
+
|
| 505 |
+
if output_attentions:
|
| 506 |
+
outputs += (self_attn_weights, cross_attn_weights)
|
| 507 |
+
|
| 508 |
+
return outputs
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
@auto_docstring
|
| 512 |
+
class Speech2TextPreTrainedModel(PreTrainedModel):
|
| 513 |
+
config: Speech2TextConfig
|
| 514 |
+
base_model_prefix = "model"
|
| 515 |
+
main_input_name = "input_features"
|
| 516 |
+
supports_gradient_checkpointing = True
|
| 517 |
+
# TODO: tests would need a rewrite to check for correct implementation
|
| 518 |
+
# Current tests always assume certain inputs to be passed
|
| 519 |
+
_supports_flash_attn = False
|
| 520 |
+
_supports_sdpa = False
|
| 521 |
+
_supports_flex_attn = False
|
| 522 |
+
|
| 523 |
+
def _init_weights(self, module):
|
| 524 |
+
std = self.config.init_std
|
| 525 |
+
if isinstance(module, (nn.Linear, nn.Conv1d)):
|
| 526 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 527 |
+
if module.bias is not None:
|
| 528 |
+
module.bias.data.zero_()
|
| 529 |
+
elif isinstance(module, nn.Embedding):
|
| 530 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 531 |
+
if module.padding_idx is not None:
|
| 532 |
+
module.weight.data[module.padding_idx].zero_()
|
| 533 |
+
|
| 534 |
+
def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor):
|
| 535 |
+
"""
|
| 536 |
+
Computes the output length of the convolutional layers
|
| 537 |
+
"""
|
| 538 |
+
for i in range(self.config.num_conv_layers):
|
| 539 |
+
input_lengths = (input_lengths - 1) // 2 + 1
|
| 540 |
+
|
| 541 |
+
return input_lengths
|
| 542 |
+
|
| 543 |
+
def _get_feature_vector_attention_mask(self, feature_vector_length, attention_mask):
|
| 544 |
+
# generate creates 3D attention mask, because of the shape of input_features
|
| 545 |
+
# convert it to 2D if that's the case
|
| 546 |
+
if len(attention_mask.shape) > 2:
|
| 547 |
+
attention_mask = attention_mask[:, :, -1]
|
| 548 |
+
|
| 549 |
+
subsampled_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1))
|
| 550 |
+
bsz = attention_mask.size()[0]
|
| 551 |
+
attention_mask = torch.zeros(
|
| 552 |
+
(bsz, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device
|
| 553 |
+
)
|
| 554 |
+
|
| 555 |
+
# these two operations makes sure that all values
|
| 556 |
+
# before the output lengths indices are attended to
|
| 557 |
+
attention_mask[(torch.arange(bsz, device=attention_mask.device), subsampled_lengths - 1)] = 1
|
| 558 |
+
attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).long()
|
| 559 |
+
return attention_mask
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
class Speech2TextEncoder(Speech2TextPreTrainedModel):
|
| 563 |
+
"""
|
| 564 |
+
Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
|
| 565 |
+
[`Speech2TextEncoderLayer`].
|
| 566 |
+
|
| 567 |
+
Args:
|
| 568 |
+
config: Speech2TextConfig
|
| 569 |
+
embed_tokens (nn.Embedding): output embedding
|
| 570 |
+
"""
|
| 571 |
+
|
| 572 |
+
def __init__(self, config: Speech2TextConfig):
|
| 573 |
+
super().__init__(config)
|
| 574 |
+
|
| 575 |
+
self.dropout = config.dropout
|
| 576 |
+
self.layerdrop = config.encoder_layerdrop
|
| 577 |
+
|
| 578 |
+
embed_dim = config.d_model
|
| 579 |
+
self.padding_idx = config.pad_token_id
|
| 580 |
+
self.max_source_positions = config.max_source_positions
|
| 581 |
+
self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
|
| 582 |
+
|
| 583 |
+
self.conv = Conv1dSubsampler(config)
|
| 584 |
+
|
| 585 |
+
self.embed_positions = Speech2TextSinusoidalPositionalEmbedding(
|
| 586 |
+
self.max_source_positions,
|
| 587 |
+
embed_dim,
|
| 588 |
+
self.padding_idx,
|
| 589 |
+
)
|
| 590 |
+
self.layers = nn.ModuleList([Speech2TextEncoderLayer(config) for _ in range(config.encoder_layers)])
|
| 591 |
+
self.layer_norm = nn.LayerNorm(config.d_model)
|
| 592 |
+
|
| 593 |
+
self.gradient_checkpointing = False
|
| 594 |
+
# Initialize weights and apply final processing
|
| 595 |
+
self.post_init()
|
| 596 |
+
|
| 597 |
+
def forward(
|
| 598 |
+
self,
|
| 599 |
+
input_features,
|
| 600 |
+
attention_mask=None,
|
| 601 |
+
head_mask=None,
|
| 602 |
+
output_attentions=None,
|
| 603 |
+
output_hidden_states=None,
|
| 604 |
+
return_dict=None,
|
| 605 |
+
):
|
| 606 |
+
r"""
|
| 607 |
+
Args:
|
| 608 |
+
input_features (`torch.LongTensor` of shape `(batch_size, sequence_length, feature_size)`):
|
| 609 |
+
Float values of fbank features extracted from the raw speech waveform. Raw speech waveform can be
|
| 610 |
+
obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
|
| 611 |
+
`numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
|
| 612 |
+
the soundfile library (`pip install soundfile`). To prepare the array into
|
| 613 |
+
`input_features`, the [`AutoFeatureExtractor`] should be used for extracting the fbank features,
|
| 614 |
+
padding and conversion into a tensor of type `torch.FloatTensor`. See
|
| 615 |
+
[`~Speech2TextFeatureExtractor.__call__`]
|
| 616 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 617 |
+
Mask to avoid performing convolution and attention on padding token indices. Mask values selected in
|
| 618 |
+
`[0, 1]`:
|
| 619 |
+
|
| 620 |
+
- 1 for tokens that are **not masked**,
|
| 621 |
+
- 0 for tokens that are **masked**.
|
| 622 |
+
|
| 623 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 624 |
+
head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
|
| 625 |
+
Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
|
| 626 |
+
|
| 627 |
+
- 1 indicates the head is **not masked**,
|
| 628 |
+
- 0 indicates the head is **masked**.
|
| 629 |
+
|
| 630 |
+
output_attentions (`bool`, *optional*):
|
| 631 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 632 |
+
returned tensors for more detail.
|
| 633 |
+
output_hidden_states (`bool`, *optional*):
|
| 634 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 635 |
+
for more detail.
|
| 636 |
+
return_dict (`bool`, *optional*):
|
| 637 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 638 |
+
"""
|
| 639 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 640 |
+
output_hidden_states = (
|
| 641 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 642 |
+
)
|
| 643 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 644 |
+
inputs_embeds = self.conv(input_features)
|
| 645 |
+
inputs_embeds = self.embed_scale * inputs_embeds
|
| 646 |
+
|
| 647 |
+
# subsample attention mask if necessary
|
| 648 |
+
if attention_mask is not None:
|
| 649 |
+
attention_mask = self._get_feature_vector_attention_mask(inputs_embeds.shape[1], attention_mask)
|
| 650 |
+
padding_mask = attention_mask.ne(1).long()
|
| 651 |
+
else:
|
| 652 |
+
padding_mask = torch.zeros(inputs_embeds.shape[:2], dtype=torch.long, device=inputs_embeds.device)
|
| 653 |
+
|
| 654 |
+
embed_pos = self.embed_positions(padding_mask)
|
| 655 |
+
|
| 656 |
+
hidden_states = inputs_embeds + embed_pos
|
| 657 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 658 |
+
|
| 659 |
+
attention_mask = self._update_full_mask(
|
| 660 |
+
attention_mask,
|
| 661 |
+
inputs_embeds,
|
| 662 |
+
)
|
| 663 |
+
|
| 664 |
+
encoder_states = () if output_hidden_states else None
|
| 665 |
+
all_attentions = () if output_attentions else None
|
| 666 |
+
|
| 667 |
+
# check if head_mask has a correct number of layers specified if desired
|
| 668 |
+
if head_mask is not None:
|
| 669 |
+
assert head_mask.size()[0] == (len(self.layers)), (
|
| 670 |
+
f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}."
|
| 671 |
+
)
|
| 672 |
+
|
| 673 |
+
for idx, encoder_layer in enumerate(self.layers):
|
| 674 |
+
if output_hidden_states:
|
| 675 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 676 |
+
# add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
|
| 677 |
+
to_drop = False
|
| 678 |
+
if self.training:
|
| 679 |
+
dropout_probability = torch.rand([])
|
| 680 |
+
if dropout_probability < self.layerdrop: # skip the layer
|
| 681 |
+
to_drop = True
|
| 682 |
+
|
| 683 |
+
if to_drop:
|
| 684 |
+
layer_outputs = (None, None)
|
| 685 |
+
else:
|
| 686 |
+
layer_outputs = encoder_layer(
|
| 687 |
+
hidden_states,
|
| 688 |
+
attention_mask,
|
| 689 |
+
layer_head_mask=(head_mask[idx] if head_mask is not None else None),
|
| 690 |
+
output_attentions=output_attentions,
|
| 691 |
+
)
|
| 692 |
+
|
| 693 |
+
hidden_states = layer_outputs[0]
|
| 694 |
+
|
| 695 |
+
if output_attentions:
|
| 696 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 697 |
+
|
| 698 |
+
hidden_states = self.layer_norm(hidden_states)
|
| 699 |
+
if output_hidden_states:
|
| 700 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 701 |
+
|
| 702 |
+
if not return_dict:
|
| 703 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
| 704 |
+
return BaseModelOutput(
|
| 705 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
|
| 706 |
+
)
|
| 707 |
+
|
| 708 |
+
# Copied from transformers.models.bart.modeling_bart.BartPreTrainedModel._update_full_mask
|
| 709 |
+
def _update_full_mask(
|
| 710 |
+
self,
|
| 711 |
+
attention_mask: Union[torch.Tensor, None],
|
| 712 |
+
inputs_embeds: torch.Tensor,
|
| 713 |
+
):
|
| 714 |
+
if attention_mask is not None:
|
| 715 |
+
if self.config._attn_implementation == "flash_attention_2":
|
| 716 |
+
attention_mask = attention_mask if 0 in attention_mask else None
|
| 717 |
+
elif self.config._attn_implementation == "sdpa":
|
| 718 |
+
# output_attentions=True & head_mask can not be supported when using SDPA, fall back to
|
| 719 |
+
# the manual implementation that requires a 4D causal mask in all cases.
|
| 720 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 721 |
+
attention_mask = _prepare_4d_attention_mask_for_sdpa(attention_mask, inputs_embeds.dtype)
|
| 722 |
+
elif self.config._attn_implementation == "flex_attention":
|
| 723 |
+
if isinstance(attention_mask, torch.Tensor):
|
| 724 |
+
attention_mask = make_flex_block_causal_mask(attention_mask, is_causal=False)
|
| 725 |
+
else:
|
| 726 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 727 |
+
attention_mask = _prepare_4d_attention_mask(attention_mask, inputs_embeds.dtype)
|
| 728 |
+
|
| 729 |
+
return attention_mask
|
| 730 |
+
|
| 731 |
+
|
| 732 |
+
class Speech2TextDecoder(Speech2TextPreTrainedModel):
|
| 733 |
+
"""
|
| 734 |
+
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`Speech2TextDecoderLayer`]
|
| 735 |
+
|
| 736 |
+
Args:
|
| 737 |
+
config: Speech2TextConfig
|
| 738 |
+
embed_tokens (nn.Embedding): output embedding
|
| 739 |
+
"""
|
| 740 |
+
|
| 741 |
+
def __init__(self, config: Speech2TextConfig):
|
| 742 |
+
super().__init__(config)
|
| 743 |
+
self.dropout = config.dropout
|
| 744 |
+
self.layerdrop = config.decoder_layerdrop
|
| 745 |
+
self.padding_idx = config.pad_token_id
|
| 746 |
+
self.max_target_positions = config.max_target_positions
|
| 747 |
+
self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
|
| 748 |
+
|
| 749 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model, self.padding_idx)
|
| 750 |
+
|
| 751 |
+
self.embed_positions = Speech2TextSinusoidalPositionalEmbedding(
|
| 752 |
+
self.max_target_positions,
|
| 753 |
+
config.d_model,
|
| 754 |
+
self.padding_idx,
|
| 755 |
+
)
|
| 756 |
+
|
| 757 |
+
self.layers = nn.ModuleList(
|
| 758 |
+
[Speech2TextDecoderLayer(config, layer_idx=i) for i in range(config.decoder_layers)]
|
| 759 |
+
)
|
| 760 |
+
|
| 761 |
+
self.layer_norm = nn.LayerNorm(config.d_model)
|
| 762 |
+
|
| 763 |
+
self.gradient_checkpointing = False
|
| 764 |
+
# Initialize weights and apply final processing
|
| 765 |
+
self.post_init()
|
| 766 |
+
|
| 767 |
+
def forward(
|
| 768 |
+
self,
|
| 769 |
+
input_ids=None,
|
| 770 |
+
attention_mask=None,
|
| 771 |
+
encoder_hidden_states=None,
|
| 772 |
+
encoder_attention_mask=None,
|
| 773 |
+
head_mask=None,
|
| 774 |
+
cross_attn_head_mask=None,
|
| 775 |
+
past_key_values=None,
|
| 776 |
+
inputs_embeds=None,
|
| 777 |
+
use_cache=None,
|
| 778 |
+
output_attentions=None,
|
| 779 |
+
output_hidden_states=None,
|
| 780 |
+
return_dict=None,
|
| 781 |
+
cache_position=None,
|
| 782 |
+
):
|
| 783 |
+
r"""
|
| 784 |
+
Args:
|
| 785 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 786 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
|
| 787 |
+
provide it.
|
| 788 |
+
|
| 789 |
+
Indices can be obtained using [`Speech2TextTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 790 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 791 |
+
|
| 792 |
+
[What are input IDs?](../glossary#input-ids)
|
| 793 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 794 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 795 |
+
|
| 796 |
+
- 1 for tokens that are **not masked**,
|
| 797 |
+
- 0 for tokens that are **masked**.
|
| 798 |
+
|
| 799 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 800 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
|
| 801 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
|
| 802 |
+
of the decoder.
|
| 803 |
+
encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
|
| 804 |
+
Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
|
| 805 |
+
selected in `[0, 1]`:
|
| 806 |
+
|
| 807 |
+
- 1 for tokens that are **not masked**,
|
| 808 |
+
- 0 for tokens that are **masked**.
|
| 809 |
+
|
| 810 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 811 |
+
head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 812 |
+
Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
|
| 813 |
+
|
| 814 |
+
- 1 indicates the head is **not masked**,
|
| 815 |
+
- 0 indicates the head is **masked**.
|
| 816 |
+
|
| 817 |
+
cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 818 |
+
Mask to nullify selected heads of the attention modules in encoder to avoid performing cross-attention
|
| 819 |
+
on hidden heads. Mask values selected in `[0, 1]`:
|
| 820 |
+
|
| 821 |
+
- 1 indicates the head is **not masked**,
|
| 822 |
+
- 0 indicates the head is **masked**.
|
| 823 |
+
|
| 824 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 825 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
| 826 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
|
| 827 |
+
shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
|
| 828 |
+
|
| 829 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
|
| 830 |
+
cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
| 831 |
+
|
| 832 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
|
| 833 |
+
that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
|
| 834 |
+
all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 835 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 836 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 837 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 838 |
+
than the model's internal embedding lookup matrix.
|
| 839 |
+
output_attentions (`bool`, *optional*):
|
| 840 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 841 |
+
returned tensors for more detail.
|
| 842 |
+
output_hidden_states (`bool`, *optional*):
|
| 843 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 844 |
+
for more detail.
|
| 845 |
+
return_dict (`bool`, *optional*):
|
| 846 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 847 |
+
"""
|
| 848 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 849 |
+
output_hidden_states = (
|
| 850 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 851 |
+
)
|
| 852 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 853 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 854 |
+
|
| 855 |
+
# retrieve input_ids and inputs_embeds
|
| 856 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 857 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
| 858 |
+
elif input_ids is not None:
|
| 859 |
+
input_shape = input_ids.size()
|
| 860 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
| 861 |
+
elif inputs_embeds is not None:
|
| 862 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 863 |
+
else:
|
| 864 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
| 865 |
+
|
| 866 |
+
if inputs_embeds is None:
|
| 867 |
+
inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
|
| 868 |
+
|
| 869 |
+
if self.gradient_checkpointing and self.training:
|
| 870 |
+
if use_cache:
|
| 871 |
+
logger.warning_once(
|
| 872 |
+
"`use_cache = True` is incompatible with gradient checkpointing. Setting `use_cache = False`..."
|
| 873 |
+
)
|
| 874 |
+
use_cache = False
|
| 875 |
+
|
| 876 |
+
if use_cache and past_key_values is None:
|
| 877 |
+
past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
|
| 878 |
+
if use_cache and isinstance(past_key_values, tuple):
|
| 879 |
+
logger.warning_once(
|
| 880 |
+
"Passing a tuple of `past_key_values` is deprecated and will be removed in Transformers v4.58.0. "
|
| 881 |
+
"You should pass an instance of `EncoderDecoderCache` instead, e.g. "
|
| 882 |
+
"`past_key_values=EncoderDecoderCache.from_legacy_cache(past_key_values)`."
|
| 883 |
+
)
|
| 884 |
+
past_key_values = EncoderDecoderCache.from_legacy_cache(past_key_values)
|
| 885 |
+
|
| 886 |
+
past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 887 |
+
attention_mask = self._update_causal_mask(
|
| 888 |
+
attention_mask,
|
| 889 |
+
input_shape,
|
| 890 |
+
inputs_embeds,
|
| 891 |
+
past_key_values_length,
|
| 892 |
+
)
|
| 893 |
+
encoder_attention_mask = self._update_cross_attn_mask(
|
| 894 |
+
encoder_hidden_states,
|
| 895 |
+
encoder_attention_mask,
|
| 896 |
+
input_shape,
|
| 897 |
+
inputs_embeds,
|
| 898 |
+
)
|
| 899 |
+
|
| 900 |
+
# embed positions
|
| 901 |
+
positions = self.embed_positions(input_ids, past_key_values_length=past_key_values_length)
|
| 902 |
+
|
| 903 |
+
hidden_states = inputs_embeds + positions
|
| 904 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 905 |
+
|
| 906 |
+
# decoder layers
|
| 907 |
+
all_hidden_states = () if output_hidden_states else None
|
| 908 |
+
all_self_attns = () if output_attentions else None
|
| 909 |
+
all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
|
| 910 |
+
|
| 911 |
+
# check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
|
| 912 |
+
for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
|
| 913 |
+
if attn_mask is not None:
|
| 914 |
+
assert attn_mask.size()[0] == (len(self.layers)), (
|
| 915 |
+
f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
|
| 916 |
+
f" {head_mask.size()[0]}."
|
| 917 |
+
)
|
| 918 |
+
for idx, decoder_layer in enumerate(self.layers):
|
| 919 |
+
# add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
|
| 920 |
+
if output_hidden_states:
|
| 921 |
+
all_hidden_states += (hidden_states,)
|
| 922 |
+
if self.training:
|
| 923 |
+
dropout_probability = torch.rand([])
|
| 924 |
+
if dropout_probability < self.layerdrop:
|
| 925 |
+
continue
|
| 926 |
+
|
| 927 |
+
layer_outputs = decoder_layer(
|
| 928 |
+
hidden_states,
|
| 929 |
+
attention_mask,
|
| 930 |
+
encoder_hidden_states, # as a positional argument for gradient checkpointing
|
| 931 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 932 |
+
layer_head_mask=(head_mask[idx] if head_mask is not None else None),
|
| 933 |
+
cross_attn_layer_head_mask=(cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None),
|
| 934 |
+
past_key_values=past_key_values,
|
| 935 |
+
output_attentions=output_attentions,
|
| 936 |
+
use_cache=use_cache,
|
| 937 |
+
cache_position=cache_position,
|
| 938 |
+
)
|
| 939 |
+
hidden_states = layer_outputs[0]
|
| 940 |
+
|
| 941 |
+
if output_attentions:
|
| 942 |
+
all_self_attns += (layer_outputs[1],)
|
| 943 |
+
|
| 944 |
+
if encoder_hidden_states is not None:
|
| 945 |
+
all_cross_attentions += (layer_outputs[2],)
|
| 946 |
+
|
| 947 |
+
hidden_states = self.layer_norm(hidden_states)
|
| 948 |
+
# add hidden states from the last decoder layer
|
| 949 |
+
if output_hidden_states:
|
| 950 |
+
all_hidden_states += (hidden_states,)
|
| 951 |
+
|
| 952 |
+
if not return_dict:
|
| 953 |
+
return tuple(
|
| 954 |
+
v
|
| 955 |
+
for v in [hidden_states, past_key_values, all_hidden_states, all_self_attns, all_cross_attentions]
|
| 956 |
+
if v is not None
|
| 957 |
+
)
|
| 958 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 959 |
+
last_hidden_state=hidden_states,
|
| 960 |
+
past_key_values=past_key_values,
|
| 961 |
+
hidden_states=all_hidden_states,
|
| 962 |
+
attentions=all_self_attns,
|
| 963 |
+
cross_attentions=all_cross_attentions,
|
| 964 |
+
)
|
| 965 |
+
|
| 966 |
+
# Copied from transformers.models.musicgen.modeling_musicgen.MusicgenDecoder._update_causal_mask
|
| 967 |
+
def _update_causal_mask(
|
| 968 |
+
self,
|
| 969 |
+
attention_mask: Union[torch.Tensor, None],
|
| 970 |
+
input_shape: torch.Size,
|
| 971 |
+
inputs_embeds: torch.Tensor,
|
| 972 |
+
past_key_values_length: int,
|
| 973 |
+
):
|
| 974 |
+
if self.config._attn_implementation == "flash_attention_2":
|
| 975 |
+
# 2d mask is passed through the layers
|
| 976 |
+
attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
|
| 977 |
+
elif self.config._attn_implementation == "sdpa":
|
| 978 |
+
# output_attentions=True & cross_attn_head_mask can not be supported when using SDPA, and we fall back on
|
| 979 |
+
# the manual implementation that requires a 4D causal mask in all cases.
|
| 980 |
+
attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
|
| 981 |
+
attention_mask,
|
| 982 |
+
input_shape,
|
| 983 |
+
inputs_embeds,
|
| 984 |
+
past_key_values_length,
|
| 985 |
+
)
|
| 986 |
+
elif self.config._attn_implementation == "flex_attention":
|
| 987 |
+
if isinstance(attention_mask, torch.Tensor):
|
| 988 |
+
attention_mask = make_flex_block_causal_mask(attention_mask)
|
| 989 |
+
# Other attention flavors support in-built causal (when `mask is None`)
|
| 990 |
+
# while we need to create our specific block mask regardless
|
| 991 |
+
elif attention_mask is None:
|
| 992 |
+
attention_mask = make_flex_block_causal_mask(
|
| 993 |
+
torch.ones(
|
| 994 |
+
size=(input_shape),
|
| 995 |
+
device=inputs_embeds.device,
|
| 996 |
+
)
|
| 997 |
+
)
|
| 998 |
+
else:
|
| 999 |
+
# 4d mask is passed through the layers
|
| 1000 |
+
attention_mask = _prepare_4d_causal_attention_mask(
|
| 1001 |
+
attention_mask, input_shape, inputs_embeds, past_key_values_length
|
| 1002 |
+
)
|
| 1003 |
+
|
| 1004 |
+
return attention_mask
|
| 1005 |
+
|
| 1006 |
+
# Copied from transformers.models.musicgen.modeling_musicgen.MusicgenDecoder._update_cross_attn_mask
|
| 1007 |
+
def _update_cross_attn_mask(
|
| 1008 |
+
self,
|
| 1009 |
+
encoder_hidden_states: Union[torch.Tensor, None],
|
| 1010 |
+
encoder_attention_mask: Union[torch.Tensor, None],
|
| 1011 |
+
input_shape: torch.Size,
|
| 1012 |
+
inputs_embeds: torch.Tensor,
|
| 1013 |
+
):
|
| 1014 |
+
# expand encoder attention mask
|
| 1015 |
+
if encoder_hidden_states is not None and encoder_attention_mask is not None:
|
| 1016 |
+
if self.config._attn_implementation == "flash_attention_2":
|
| 1017 |
+
encoder_attention_mask = encoder_attention_mask if 0 in encoder_attention_mask else None
|
| 1018 |
+
elif self.config._attn_implementation == "sdpa":
|
| 1019 |
+
# output_attentions=True & cross_attn_head_mask can not be supported when using SDPA, and we fall back on
|
| 1020 |
+
# the manual implementation that requires a 4D causal mask in all cases.
|
| 1021 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 1022 |
+
encoder_attention_mask = _prepare_4d_attention_mask_for_sdpa(
|
| 1023 |
+
encoder_attention_mask,
|
| 1024 |
+
inputs_embeds.dtype,
|
| 1025 |
+
tgt_len=input_shape[-1],
|
| 1026 |
+
)
|
| 1027 |
+
elif self.config._attn_implementation == "flex_attention":
|
| 1028 |
+
if isinstance(encoder_attention_mask, torch.Tensor):
|
| 1029 |
+
encoder_attention_mask = make_flex_block_causal_mask(
|
| 1030 |
+
encoder_attention_mask,
|
| 1031 |
+
query_length=input_shape[-1],
|
| 1032 |
+
is_causal=False,
|
| 1033 |
+
)
|
| 1034 |
+
else:
|
| 1035 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 1036 |
+
encoder_attention_mask = _prepare_4d_attention_mask(
|
| 1037 |
+
encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
|
| 1038 |
+
)
|
| 1039 |
+
|
| 1040 |
+
return encoder_attention_mask
|
| 1041 |
+
|
| 1042 |
+
|
| 1043 |
+
@auto_docstring
|
| 1044 |
+
class Speech2TextModel(Speech2TextPreTrainedModel):
|
| 1045 |
+
def __init__(self, config: Speech2TextConfig):
|
| 1046 |
+
super().__init__(config)
|
| 1047 |
+
|
| 1048 |
+
self.encoder = Speech2TextEncoder(config)
|
| 1049 |
+
self.decoder = Speech2TextDecoder(config)
|
| 1050 |
+
|
| 1051 |
+
# Initialize weights and apply final processing
|
| 1052 |
+
self.post_init()
|
| 1053 |
+
|
| 1054 |
+
def get_input_embeddings(self):
|
| 1055 |
+
return self.decoder.embed_tokens
|
| 1056 |
+
|
| 1057 |
+
def set_input_embeddings(self, value):
|
| 1058 |
+
self.decoder.embed_tokens = value
|
| 1059 |
+
|
| 1060 |
+
def get_encoder(self):
|
| 1061 |
+
return self.encoder
|
| 1062 |
+
|
| 1063 |
+
@auto_docstring
|
| 1064 |
+
def forward(
|
| 1065 |
+
self,
|
| 1066 |
+
input_features: Optional[torch.LongTensor] = None,
|
| 1067 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1068 |
+
decoder_input_ids: Optional[torch.LongTensor] = None,
|
| 1069 |
+
decoder_attention_mask: Optional[torch.LongTensor] = None,
|
| 1070 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1071 |
+
decoder_head_mask: Optional[torch.Tensor] = None,
|
| 1072 |
+
cross_attn_head_mask: Optional[torch.Tensor] = None,
|
| 1073 |
+
encoder_outputs: Optional[tuple[tuple[torch.FloatTensor]]] = None,
|
| 1074 |
+
past_key_values: Optional[tuple[tuple[torch.FloatTensor]]] = None,
|
| 1075 |
+
decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1076 |
+
use_cache: Optional[bool] = None,
|
| 1077 |
+
output_attentions: Optional[bool] = None,
|
| 1078 |
+
output_hidden_states: Optional[bool] = None,
|
| 1079 |
+
return_dict: Optional[bool] = None,
|
| 1080 |
+
cache_position: Optional[torch.Tensor] = None,
|
| 1081 |
+
) -> Union[tuple[torch.FloatTensor], Seq2SeqLMOutput]:
|
| 1082 |
+
r"""
|
| 1083 |
+
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 1084 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 1085 |
+
|
| 1086 |
+
Indices can be obtained using [`SpeechToTextTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1087 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 1088 |
+
|
| 1089 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 1090 |
+
|
| 1091 |
+
SpeechToText uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If
|
| 1092 |
+
`past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
| 1093 |
+
`past_key_values`).
|
| 1094 |
+
decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 1095 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 1096 |
+
be used by default.
|
| 1097 |
+
|
| 1098 |
+
If you want to change padding behavior, you should read
|
| 1099 |
+
[`modeling_speech_to_text._prepare_decoder_attention_mask`] and modify to your needs. See diagram 1 in [the
|
| 1100 |
+
paper](https://huggingface.co/papers/1910.13461) for more information on the default strategy.
|
| 1101 |
+
cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 1102 |
+
Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
|
| 1103 |
+
|
| 1104 |
+
- 1 indicates the head is **not masked**,
|
| 1105 |
+
- 0 indicates the head is **masked**.
|
| 1106 |
+
|
| 1107 |
+
Example:
|
| 1108 |
+
|
| 1109 |
+
```python
|
| 1110 |
+
>>> import torch
|
| 1111 |
+
>>> from transformers import Speech2TextModel, AutoFeatureExtractor
|
| 1112 |
+
>>> from datasets import load_dataset
|
| 1113 |
+
|
| 1114 |
+
>>> model = Speech2TextModel.from_pretrained("facebook/s2t-small-librispeech-asr")
|
| 1115 |
+
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/s2t-small-librispeech-asr")
|
| 1116 |
+
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
| 1117 |
+
>>> inputs = feature_extractor(
|
| 1118 |
+
... ds[0]["audio"]["array"], sampling_rate=ds[0]["audio"]["sampling_rate"], return_tensors="pt"
|
| 1119 |
+
... )
|
| 1120 |
+
>>> input_features = inputs.input_features
|
| 1121 |
+
>>> decoder_input_ids = torch.tensor([[1, 1]]) * model.config.decoder_start_token_id
|
| 1122 |
+
>>> last_hidden_state = model(input_features, decoder_input_ids=decoder_input_ids).last_hidden_state
|
| 1123 |
+
>>> list(last_hidden_state.shape)
|
| 1124 |
+
[1, 2, 256]
|
| 1125 |
+
```"""
|
| 1126 |
+
|
| 1127 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1128 |
+
output_hidden_states = (
|
| 1129 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1130 |
+
)
|
| 1131 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 1132 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1133 |
+
|
| 1134 |
+
if encoder_outputs is None:
|
| 1135 |
+
encoder_outputs = self.encoder(
|
| 1136 |
+
input_features,
|
| 1137 |
+
attention_mask=attention_mask,
|
| 1138 |
+
head_mask=head_mask,
|
| 1139 |
+
output_attentions=output_attentions,
|
| 1140 |
+
output_hidden_states=output_hidden_states,
|
| 1141 |
+
return_dict=return_dict,
|
| 1142 |
+
)
|
| 1143 |
+
# If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
|
| 1144 |
+
elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
|
| 1145 |
+
encoder_outputs = BaseModelOutput(
|
| 1146 |
+
last_hidden_state=encoder_outputs[0],
|
| 1147 |
+
hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
|
| 1148 |
+
attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
|
| 1149 |
+
)
|
| 1150 |
+
|
| 1151 |
+
# downsample encoder attention mask
|
| 1152 |
+
if attention_mask is not None:
|
| 1153 |
+
encoder_attention_mask = self._get_feature_vector_attention_mask(
|
| 1154 |
+
encoder_outputs[0].shape[1], attention_mask
|
| 1155 |
+
)
|
| 1156 |
+
else:
|
| 1157 |
+
encoder_attention_mask = None
|
| 1158 |
+
|
| 1159 |
+
# decoder outputs consists of (dec_features, past_key_values, dec_hidden, dec_attn)
|
| 1160 |
+
decoder_outputs = self.decoder(
|
| 1161 |
+
input_ids=decoder_input_ids,
|
| 1162 |
+
attention_mask=decoder_attention_mask,
|
| 1163 |
+
encoder_hidden_states=encoder_outputs[0],
|
| 1164 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1165 |
+
head_mask=decoder_head_mask,
|
| 1166 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 1167 |
+
past_key_values=past_key_values,
|
| 1168 |
+
inputs_embeds=decoder_inputs_embeds,
|
| 1169 |
+
use_cache=use_cache,
|
| 1170 |
+
output_attentions=output_attentions,
|
| 1171 |
+
output_hidden_states=output_hidden_states,
|
| 1172 |
+
return_dict=return_dict,
|
| 1173 |
+
cache_position=cache_position,
|
| 1174 |
+
)
|
| 1175 |
+
|
| 1176 |
+
if not return_dict:
|
| 1177 |
+
return decoder_outputs + encoder_outputs
|
| 1178 |
+
|
| 1179 |
+
return Seq2SeqModelOutput(
|
| 1180 |
+
last_hidden_state=decoder_outputs.last_hidden_state,
|
| 1181 |
+
past_key_values=decoder_outputs.past_key_values,
|
| 1182 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 1183 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 1184 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 1185 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
| 1186 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 1187 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 1188 |
+
)
|
| 1189 |
+
|
| 1190 |
+
|
| 1191 |
+
@auto_docstring(
|
| 1192 |
+
custom_intro="""
|
| 1193 |
+
The Speech2Text Model with a language modeling head. Can be used for summarization.
|
| 1194 |
+
"""
|
| 1195 |
+
)
|
| 1196 |
+
class Speech2TextForConditionalGeneration(Speech2TextPreTrainedModel, GenerationMixin):
|
| 1197 |
+
base_model_prefix = "model"
|
| 1198 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 1199 |
+
|
| 1200 |
+
def __init__(self, config: Speech2TextConfig):
|
| 1201 |
+
super().__init__(config)
|
| 1202 |
+
self.model = Speech2TextModel(config)
|
| 1203 |
+
self.lm_head = nn.Linear(config.d_model, self.config.vocab_size, bias=False)
|
| 1204 |
+
|
| 1205 |
+
# Initialize weights and apply final processing
|
| 1206 |
+
self.post_init()
|
| 1207 |
+
|
| 1208 |
+
def get_encoder(self):
|
| 1209 |
+
return self.model.get_encoder()
|
| 1210 |
+
|
| 1211 |
+
def get_decoder(self):
|
| 1212 |
+
return self.model.get_decoder()
|
| 1213 |
+
|
| 1214 |
+
@auto_docstring
|
| 1215 |
+
def forward(
|
| 1216 |
+
self,
|
| 1217 |
+
input_features: Optional[torch.LongTensor] = None,
|
| 1218 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1219 |
+
decoder_input_ids: Optional[torch.LongTensor] = None,
|
| 1220 |
+
decoder_attention_mask: Optional[torch.LongTensor] = None,
|
| 1221 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1222 |
+
decoder_head_mask: Optional[torch.Tensor] = None,
|
| 1223 |
+
cross_attn_head_mask: Optional[torch.Tensor] = None,
|
| 1224 |
+
encoder_outputs: Optional[tuple[tuple[torch.FloatTensor]]] = None,
|
| 1225 |
+
past_key_values: Optional[tuple[tuple[torch.FloatTensor]]] = None,
|
| 1226 |
+
decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1227 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1228 |
+
use_cache: Optional[bool] = None,
|
| 1229 |
+
output_attentions: Optional[bool] = None,
|
| 1230 |
+
output_hidden_states: Optional[bool] = None,
|
| 1231 |
+
return_dict: Optional[bool] = None,
|
| 1232 |
+
cache_position: Optional[torch.Tensor] = None,
|
| 1233 |
+
) -> Union[tuple[torch.FloatTensor], Seq2SeqLMOutput]:
|
| 1234 |
+
r"""
|
| 1235 |
+
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 1236 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 1237 |
+
|
| 1238 |
+
Indices can be obtained using [`SpeechToTextTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1239 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 1240 |
+
|
| 1241 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 1242 |
+
|
| 1243 |
+
SpeechToText uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If
|
| 1244 |
+
`past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
| 1245 |
+
`past_key_values`).
|
| 1246 |
+
decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 1247 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 1248 |
+
be used by default.
|
| 1249 |
+
|
| 1250 |
+
If you want to change padding behavior, you should read
|
| 1251 |
+
[`modeling_speech_to_text._prepare_decoder_attention_mask`] and modify to your needs. See diagram 1 in [the
|
| 1252 |
+
paper](https://huggingface.co/papers/1910.13461) for more information on the default strategy.
|
| 1253 |
+
cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 1254 |
+
Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
|
| 1255 |
+
|
| 1256 |
+
- 1 indicates the head is **not masked**,
|
| 1257 |
+
- 0 indicates the head is **masked**.
|
| 1258 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1259 |
+
Labels for computing the language modeling loss. Indices should either be in `[0, ..., config.vocab_size]`
|
| 1260 |
+
or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is
|
| 1261 |
+
only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 1262 |
+
|
| 1263 |
+
Example:
|
| 1264 |
+
|
| 1265 |
+
```python
|
| 1266 |
+
>>> import torch
|
| 1267 |
+
>>> from transformers import Speech2TextProcessor, Speech2TextForConditionalGeneration
|
| 1268 |
+
>>> from datasets import load_dataset
|
| 1269 |
+
|
| 1270 |
+
>>> model = Speech2TextForConditionalGeneration.from_pretrained("facebook/s2t-small-librispeech-asr")
|
| 1271 |
+
>>> processor = Speech2TextProcessor.from_pretrained("facebook/s2t-small-librispeech-asr")
|
| 1272 |
+
|
| 1273 |
+
|
| 1274 |
+
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
| 1275 |
+
|
| 1276 |
+
>>> inputs = processor(
|
| 1277 |
+
... ds[0]["audio"]["array"], sampling_rate=ds[0]["audio"]["sampling_rate"], return_tensors="pt"
|
| 1278 |
+
... )
|
| 1279 |
+
>>> input_features = inputs.input_features
|
| 1280 |
+
|
| 1281 |
+
>>> generated_ids = model.generate(inputs=input_features)
|
| 1282 |
+
|
| 1283 |
+
>>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 1284 |
+
>>> transcription
|
| 1285 |
+
'mister quilter is the apostle of the middle classes and we are glad to welcome his gospel'
|
| 1286 |
+
```"""
|
| 1287 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1288 |
+
|
| 1289 |
+
if labels is not None:
|
| 1290 |
+
if decoder_input_ids is None and decoder_inputs_embeds is None:
|
| 1291 |
+
decoder_input_ids = shift_tokens_right(
|
| 1292 |
+
labels, self.config.pad_token_id, self.config.decoder_start_token_id
|
| 1293 |
+
)
|
| 1294 |
+
|
| 1295 |
+
outputs = self.model(
|
| 1296 |
+
input_features,
|
| 1297 |
+
attention_mask=attention_mask,
|
| 1298 |
+
decoder_input_ids=decoder_input_ids,
|
| 1299 |
+
encoder_outputs=encoder_outputs,
|
| 1300 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1301 |
+
head_mask=head_mask,
|
| 1302 |
+
decoder_head_mask=decoder_head_mask,
|
| 1303 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 1304 |
+
past_key_values=past_key_values,
|
| 1305 |
+
decoder_inputs_embeds=decoder_inputs_embeds,
|
| 1306 |
+
use_cache=use_cache,
|
| 1307 |
+
output_attentions=output_attentions,
|
| 1308 |
+
output_hidden_states=output_hidden_states,
|
| 1309 |
+
return_dict=return_dict,
|
| 1310 |
+
cache_position=cache_position,
|
| 1311 |
+
)
|
| 1312 |
+
lm_logits = self.lm_head(outputs[0])
|
| 1313 |
+
|
| 1314 |
+
loss = None
|
| 1315 |
+
if labels is not None:
|
| 1316 |
+
loss_fct = CrossEntropyLoss()
|
| 1317 |
+
loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))
|
| 1318 |
+
|
| 1319 |
+
if not return_dict:
|
| 1320 |
+
output = (lm_logits,) + outputs[1:]
|
| 1321 |
+
return ((loss,) + output) if loss is not None else output
|
| 1322 |
+
|
| 1323 |
+
return Seq2SeqLMOutput(
|
| 1324 |
+
loss=loss,
|
| 1325 |
+
logits=lm_logits,
|
| 1326 |
+
past_key_values=outputs.past_key_values,
|
| 1327 |
+
decoder_hidden_states=outputs.decoder_hidden_states,
|
| 1328 |
+
decoder_attentions=outputs.decoder_attentions,
|
| 1329 |
+
cross_attentions=outputs.cross_attentions,
|
| 1330 |
+
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
|
| 1331 |
+
encoder_hidden_states=outputs.encoder_hidden_states,
|
| 1332 |
+
encoder_attentions=outputs.encoder_attentions,
|
| 1333 |
+
)
|
| 1334 |
+
|
| 1335 |
+
|
| 1336 |
+
__all__ = ["Speech2TextForConditionalGeneration", "Speech2TextModel", "Speech2TextPreTrainedModel"]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speech_to_text/modeling_tf_speech_to_text.py
ADDED
|
@@ -0,0 +1,1600 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""TensorFlow Speech2Text model."""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import random
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import tensorflow as tf
|
| 23 |
+
|
| 24 |
+
from ...activations_tf import get_tf_activation, glu
|
| 25 |
+
from ...modeling_tf_outputs import (
|
| 26 |
+
TFBaseModelOutput,
|
| 27 |
+
TFBaseModelOutputWithPastAndCrossAttentions,
|
| 28 |
+
TFSeq2SeqLMOutput,
|
| 29 |
+
TFSeq2SeqModelOutput,
|
| 30 |
+
)
|
| 31 |
+
from ...modeling_tf_utils import (
|
| 32 |
+
TFCausalLanguageModelingLoss,
|
| 33 |
+
TFModelInputType,
|
| 34 |
+
TFPreTrainedModel,
|
| 35 |
+
TFSharedEmbeddings,
|
| 36 |
+
keras,
|
| 37 |
+
keras_serializable,
|
| 38 |
+
unpack_inputs,
|
| 39 |
+
)
|
| 40 |
+
from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
|
| 41 |
+
from ...utils import (
|
| 42 |
+
add_code_sample_docstrings,
|
| 43 |
+
add_start_docstrings,
|
| 44 |
+
add_start_docstrings_to_model_forward,
|
| 45 |
+
logging,
|
| 46 |
+
replace_return_docstrings,
|
| 47 |
+
)
|
| 48 |
+
from .configuration_speech_to_text import Speech2TextConfig
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
logger = logging.get_logger(__name__)
|
| 52 |
+
|
| 53 |
+
_CONFIG_FOR_DOC = "Speech2TextConfig"
|
| 54 |
+
_CHECKPOINT_FOR_DOC = "facebook/s2t-small-librispeech-asr"
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
LARGE_NEGATIVE = -1e8
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
# Copied from transformers.models.bart.modeling_tf_bart.shift_tokens_right
|
| 61 |
+
def shift_tokens_right(input_ids: tf.Tensor, pad_token_id: int, decoder_start_token_id: int):
|
| 62 |
+
pad_token_id = tf.cast(pad_token_id, input_ids.dtype)
|
| 63 |
+
decoder_start_token_id = tf.cast(decoder_start_token_id, input_ids.dtype)
|
| 64 |
+
start_tokens = tf.fill(
|
| 65 |
+
(shape_list(input_ids)[0], 1), tf.convert_to_tensor(decoder_start_token_id, input_ids.dtype)
|
| 66 |
+
)
|
| 67 |
+
shifted_input_ids = tf.concat([start_tokens, input_ids[:, :-1]], -1)
|
| 68 |
+
# replace possible -100 values in labels by `pad_token_id`
|
| 69 |
+
shifted_input_ids = tf.where(
|
| 70 |
+
shifted_input_ids == -100,
|
| 71 |
+
tf.fill(shape_list(shifted_input_ids), tf.convert_to_tensor(pad_token_id, input_ids.dtype)),
|
| 72 |
+
shifted_input_ids,
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
# "Verify that `labels` has only positive values and -100"
|
| 76 |
+
assert_gte0 = tf.debugging.assert_greater_equal(shifted_input_ids, tf.constant(0, dtype=input_ids.dtype))
|
| 77 |
+
|
| 78 |
+
# Make sure the assertion op is called by wrapping the result in an identity no-op
|
| 79 |
+
with tf.control_dependencies([assert_gte0]):
|
| 80 |
+
shifted_input_ids = tf.identity(shifted_input_ids)
|
| 81 |
+
|
| 82 |
+
return shifted_input_ids
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
# Copied from transformers.models.bart.modeling_tf_bart._make_causal_mask
|
| 86 |
+
def _make_causal_mask(input_ids_shape: tf.TensorShape, past_key_values_length: int = 0):
|
| 87 |
+
"""
|
| 88 |
+
Make causal mask used for bi-directional self-attention.
|
| 89 |
+
"""
|
| 90 |
+
bsz = input_ids_shape[0]
|
| 91 |
+
tgt_len = input_ids_shape[1]
|
| 92 |
+
mask = tf.ones((tgt_len, tgt_len)) * LARGE_NEGATIVE
|
| 93 |
+
mask_cond = tf.range(shape_list(mask)[-1])
|
| 94 |
+
|
| 95 |
+
mask = tf.where(mask_cond < tf.reshape(mask_cond + 1, (shape_list(mask)[-1], 1)), 0.0, mask)
|
| 96 |
+
|
| 97 |
+
if past_key_values_length > 0:
|
| 98 |
+
mask = tf.concat([tf.zeros((tgt_len, past_key_values_length)), mask], axis=-1)
|
| 99 |
+
|
| 100 |
+
return tf.tile(mask[None, None, :, :], (bsz, 1, 1, 1))
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
# Copied from transformers.models.bart.modeling_tf_bart._expand_mask
|
| 104 |
+
def _expand_mask(mask: tf.Tensor, tgt_len: int | None = None):
|
| 105 |
+
"""
|
| 106 |
+
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
| 107 |
+
"""
|
| 108 |
+
src_len = shape_list(mask)[1]
|
| 109 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
| 110 |
+
one_cst = tf.constant(1.0)
|
| 111 |
+
mask = tf.cast(mask, dtype=one_cst.dtype)
|
| 112 |
+
expanded_mask = tf.tile(mask[:, None, None, :], (1, 1, tgt_len, 1))
|
| 113 |
+
|
| 114 |
+
return (one_cst - expanded_mask) * LARGE_NEGATIVE
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class TFConv1dSubsampler(keras.layers.Layer):
|
| 118 |
+
"""
|
| 119 |
+
Convolutional subsampler: a stack of 1D convolution (along temporal dimension) followed by non-linear activation
|
| 120 |
+
via gated linear units (https://huggingface.co/papers/1911.08460)
|
| 121 |
+
"""
|
| 122 |
+
|
| 123 |
+
def __init__(self, config: Speech2TextConfig, **kwargs):
|
| 124 |
+
super().__init__(**kwargs)
|
| 125 |
+
self.config = config
|
| 126 |
+
self.num_layers = config.num_conv_layers
|
| 127 |
+
self.in_channels = config.input_feat_per_channel * config.input_channels
|
| 128 |
+
self.mid_channels = config.conv_channels
|
| 129 |
+
self.out_channels = config.d_model
|
| 130 |
+
self.kernel_sizes = config.conv_kernel_sizes
|
| 131 |
+
|
| 132 |
+
self.conv_layers = [
|
| 133 |
+
keras.layers.Conv1D(
|
| 134 |
+
filters=self.mid_channels if i < self.num_layers - 1 else self.out_channels * 2,
|
| 135 |
+
kernel_size=k,
|
| 136 |
+
strides=2,
|
| 137 |
+
name=f"conv_layers.{i}",
|
| 138 |
+
)
|
| 139 |
+
for i, k in enumerate(self.kernel_sizes)
|
| 140 |
+
]
|
| 141 |
+
|
| 142 |
+
def call(self, input_features: tf.Tensor) -> tf.Tensor:
|
| 143 |
+
# TF Conv1D assumes Batch x Time x Channels, same as the input
|
| 144 |
+
hidden_states = tf.cast(input_features, tf.float32)
|
| 145 |
+
for i, conv in enumerate(self.conv_layers):
|
| 146 |
+
# equivalent to `padding=k // 2` on PT's `nn.Conv1d`
|
| 147 |
+
pad_len = self.kernel_sizes[i] // 2
|
| 148 |
+
hidden_shapes = shape_list(hidden_states)
|
| 149 |
+
hidden_states = tf.concat(
|
| 150 |
+
(
|
| 151 |
+
tf.zeros((hidden_shapes[0], pad_len, hidden_shapes[2])),
|
| 152 |
+
hidden_states,
|
| 153 |
+
tf.zeros((hidden_shapes[0], pad_len, hidden_shapes[2])),
|
| 154 |
+
),
|
| 155 |
+
axis=1,
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
hidden_states = conv(hidden_states)
|
| 159 |
+
hidden_states = glu(hidden_states, axis=2) # GLU over the Channel dimension
|
| 160 |
+
return hidden_states
|
| 161 |
+
|
| 162 |
+
def build(self, input_shape=None):
|
| 163 |
+
if self.built:
|
| 164 |
+
return
|
| 165 |
+
self.built = True
|
| 166 |
+
if getattr(self, "conv_layers", None) is not None:
|
| 167 |
+
for i, layer in enumerate(self.conv_layers):
|
| 168 |
+
with tf.name_scope(layer.name):
|
| 169 |
+
layer.build([None, None, self.in_channels] if i == 0 else [None, None, self.mid_channels // 2])
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
class TFSpeech2TextSinusoidalPositionalEmbedding(keras.layers.Layer):
|
| 173 |
+
"""This module produces sinusoidal positional embeddings of any length."""
|
| 174 |
+
|
| 175 |
+
def __init__(self, num_positions: int, embedding_dim: int, padding_idx: int | None = None, **kwargs):
|
| 176 |
+
super().__init__(**kwargs)
|
| 177 |
+
self.offset = 2
|
| 178 |
+
self.embedding_dim = embedding_dim
|
| 179 |
+
self.padding_idx = padding_idx
|
| 180 |
+
self.embedding_weights = self._get_embedding(num_positions + self.offset, embedding_dim, padding_idx)
|
| 181 |
+
|
| 182 |
+
@staticmethod
|
| 183 |
+
def _get_embedding(num_embeddings: int, embedding_dim: int, padding_idx: int | None = None) -> tf.Tensor:
|
| 184 |
+
"""
|
| 185 |
+
Build sinusoidal embeddings. This matches the implementation in tensor2tensor, but differs slightly from the
|
| 186 |
+
description in Section 3.5 of "Attention Is All You Need".
|
| 187 |
+
"""
|
| 188 |
+
half_dim = embedding_dim // 2
|
| 189 |
+
emb = tf.math.log(10000.0) / (half_dim - 1)
|
| 190 |
+
emb = tf.math.exp(tf.range(half_dim, dtype=tf.float32) * -emb)
|
| 191 |
+
emb = tf.expand_dims(tf.range(num_embeddings, dtype=tf.float32), axis=1) * tf.expand_dims(emb, axis=0)
|
| 192 |
+
emb = tf.reshape(tf.concat([tf.math.sin(emb), tf.math.cos(emb)], axis=1), shape=[num_embeddings, -1])
|
| 193 |
+
if embedding_dim % 2 == 1:
|
| 194 |
+
# zero pad
|
| 195 |
+
emb = tf.concat([emb, tf.zeros(num_embeddings, 1)], axis=1)
|
| 196 |
+
if padding_idx is not None:
|
| 197 |
+
emb = tf.concat([emb[:padding_idx, :], tf.zeros((1, tf.shape(emb)[1])), emb[padding_idx + 1 :, :]], axis=0)
|
| 198 |
+
return emb
|
| 199 |
+
|
| 200 |
+
def call(self, input_ids: tf.Tensor, past_key_values_length: int = 0) -> tf.Tensor:
|
| 201 |
+
bsz, seq_len = shape_list(input_ids)
|
| 202 |
+
# Create the position ids from the input token ids. Any padded tokens remain padded.
|
| 203 |
+
position_ids = self.create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length)
|
| 204 |
+
|
| 205 |
+
# Matt: The PyTorch code does a lot of work to cache the embeddings, setting the cached values as a
|
| 206 |
+
# model attribute in the forward pass. This is extremely forbidden in TF, which wants forward calls to be
|
| 207 |
+
# idempotent. TF doesn't need that caching anyway, since it can just store constants during compilation,
|
| 208 |
+
# so we just remove all of that code.
|
| 209 |
+
embeddings = self._get_embedding(
|
| 210 |
+
self.padding_idx + 1 + seq_len + self.offset + past_key_values_length, self.embedding_dim, self.padding_idx
|
| 211 |
+
)
|
| 212 |
+
return tf.reshape(tf.gather(embeddings, tf.reshape(position_ids, (-1,)), axis=0), (bsz, seq_len, -1))
|
| 213 |
+
|
| 214 |
+
@staticmethod
|
| 215 |
+
def create_position_ids_from_input_ids(
|
| 216 |
+
input_ids: tf.Tensor, padding_idx: int, past_key_values_length: int | None = 0
|
| 217 |
+
) -> tf.Tensor:
|
| 218 |
+
"""
|
| 219 |
+
Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding
|
| 220 |
+
symbols are ignored. This is modified from fairseq's `utils.make_positions`.
|
| 221 |
+
|
| 222 |
+
Args:
|
| 223 |
+
x: tf.Tensor x:
|
| 224 |
+
Returns: tf.Tensor
|
| 225 |
+
"""
|
| 226 |
+
mask = tf.cast(tf.math.not_equal(input_ids, padding_idx), dtype=tf.int32)
|
| 227 |
+
incremental_indices = (tf.math.cumsum(mask, axis=1) + past_key_values_length) * mask
|
| 228 |
+
return tf.cast(incremental_indices, dtype=tf.int64) + padding_idx
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
# Copied from transformers.models.bart.modeling_tf_bart.TFBartAttention with Bart->Speech2Text
|
| 232 |
+
class TFSpeech2TextAttention(keras.layers.Layer):
|
| 233 |
+
"""Multi-headed attention from "Attention Is All You Need"""
|
| 234 |
+
|
| 235 |
+
def __init__(
|
| 236 |
+
self,
|
| 237 |
+
embed_dim: int,
|
| 238 |
+
num_heads: int,
|
| 239 |
+
dropout: float = 0.0,
|
| 240 |
+
is_decoder: bool = False,
|
| 241 |
+
bias: bool = True,
|
| 242 |
+
**kwargs,
|
| 243 |
+
):
|
| 244 |
+
super().__init__(**kwargs)
|
| 245 |
+
self.embed_dim = embed_dim
|
| 246 |
+
|
| 247 |
+
self.num_heads = num_heads
|
| 248 |
+
self.dropout = keras.layers.Dropout(dropout)
|
| 249 |
+
self.head_dim = embed_dim // num_heads
|
| 250 |
+
if (self.head_dim * num_heads) != self.embed_dim:
|
| 251 |
+
raise ValueError(
|
| 252 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
|
| 253 |
+
f" and `num_heads`: {num_heads})."
|
| 254 |
+
)
|
| 255 |
+
self.scaling = self.head_dim**-0.5
|
| 256 |
+
self.is_decoder = is_decoder
|
| 257 |
+
|
| 258 |
+
self.k_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="k_proj")
|
| 259 |
+
self.q_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="q_proj")
|
| 260 |
+
self.v_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="v_proj")
|
| 261 |
+
self.out_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="out_proj")
|
| 262 |
+
|
| 263 |
+
def _shape(self, tensor: tf.Tensor, seq_len: int, bsz: int):
|
| 264 |
+
return tf.transpose(tf.reshape(tensor, (bsz, seq_len, self.num_heads, self.head_dim)), (0, 2, 1, 3))
|
| 265 |
+
|
| 266 |
+
def call(
|
| 267 |
+
self,
|
| 268 |
+
hidden_states: tf.Tensor,
|
| 269 |
+
key_value_states: tf.Tensor | None = None,
|
| 270 |
+
past_key_value: tuple[tuple[tf.Tensor]] | None = None,
|
| 271 |
+
attention_mask: tf.Tensor | None = None,
|
| 272 |
+
layer_head_mask: tf.Tensor | None = None,
|
| 273 |
+
training: bool | None = False,
|
| 274 |
+
) -> tuple[tf.Tensor, tf.Tensor | None]:
|
| 275 |
+
"""Input shape: Batch x Time x Channel"""
|
| 276 |
+
|
| 277 |
+
# if key_value_states are provided this layer is used as a cross-attention layer
|
| 278 |
+
# for the decoder
|
| 279 |
+
is_cross_attention = key_value_states is not None
|
| 280 |
+
bsz, tgt_len, embed_dim = shape_list(hidden_states)
|
| 281 |
+
|
| 282 |
+
# get query proj
|
| 283 |
+
query_states = self.q_proj(hidden_states) * self.scaling
|
| 284 |
+
# get key, value proj
|
| 285 |
+
if is_cross_attention and past_key_value is not None:
|
| 286 |
+
# reuse k,v, cross_attentions
|
| 287 |
+
key_states = past_key_value[0]
|
| 288 |
+
value_states = past_key_value[1]
|
| 289 |
+
elif is_cross_attention:
|
| 290 |
+
# cross_attentions
|
| 291 |
+
key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
|
| 292 |
+
value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
|
| 293 |
+
elif past_key_value is not None:
|
| 294 |
+
# reuse k, v, self_attention
|
| 295 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 296 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 297 |
+
key_states = tf.concat([past_key_value[0], key_states], axis=2)
|
| 298 |
+
value_states = tf.concat([past_key_value[1], value_states], axis=2)
|
| 299 |
+
else:
|
| 300 |
+
# self_attention
|
| 301 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 302 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 303 |
+
|
| 304 |
+
if self.is_decoder:
|
| 305 |
+
# if cross_attention save Tuple(tf.Tensor, tf.Tensor) of all cross attention key/value_states.
|
| 306 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
| 307 |
+
# key/value_states (first "if" case)
|
| 308 |
+
# if uni-directional self-attention (decoder) save Tuple(tf.Tensor, tf.Tensor) of
|
| 309 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
| 310 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
| 311 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
| 312 |
+
past_key_value = (key_states, value_states)
|
| 313 |
+
|
| 314 |
+
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
|
| 315 |
+
query_states = tf.reshape(self._shape(query_states, tgt_len, bsz), proj_shape)
|
| 316 |
+
key_states = tf.reshape(key_states, proj_shape)
|
| 317 |
+
value_states = tf.reshape(value_states, proj_shape)
|
| 318 |
+
|
| 319 |
+
src_len = shape_list(key_states)[1]
|
| 320 |
+
attn_weights = tf.matmul(query_states, key_states, transpose_b=True)
|
| 321 |
+
|
| 322 |
+
tf.debugging.assert_equal(
|
| 323 |
+
shape_list(attn_weights),
|
| 324 |
+
[bsz * self.num_heads, tgt_len, src_len],
|
| 325 |
+
message=(
|
| 326 |
+
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
|
| 327 |
+
f" {shape_list(attn_weights)}"
|
| 328 |
+
),
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
if attention_mask is not None:
|
| 332 |
+
tf.debugging.assert_equal(
|
| 333 |
+
shape_list(attention_mask),
|
| 334 |
+
[bsz, 1, tgt_len, src_len],
|
| 335 |
+
message=(
|
| 336 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
|
| 337 |
+
f" {shape_list(attention_mask)}"
|
| 338 |
+
),
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
attention_mask = tf.cast(attention_mask, dtype=attn_weights.dtype)
|
| 342 |
+
attn_weights = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len)) + attention_mask
|
| 343 |
+
attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len))
|
| 344 |
+
|
| 345 |
+
attn_weights = stable_softmax(attn_weights, axis=-1)
|
| 346 |
+
|
| 347 |
+
if layer_head_mask is not None:
|
| 348 |
+
tf.debugging.assert_equal(
|
| 349 |
+
shape_list(layer_head_mask),
|
| 350 |
+
[self.num_heads],
|
| 351 |
+
message=(
|
| 352 |
+
f"Head mask for a single layer should be of size {(self.num_heads)}, but is"
|
| 353 |
+
f" {shape_list(layer_head_mask)}"
|
| 354 |
+
),
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
+
attn_weights = tf.reshape(layer_head_mask, (1, -1, 1, 1)) * tf.reshape(
|
| 358 |
+
attn_weights, (bsz, self.num_heads, tgt_len, src_len)
|
| 359 |
+
)
|
| 360 |
+
attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len))
|
| 361 |
+
|
| 362 |
+
attn_probs = self.dropout(attn_weights, training=training)
|
| 363 |
+
attn_output = tf.matmul(attn_probs, value_states)
|
| 364 |
+
|
| 365 |
+
tf.debugging.assert_equal(
|
| 366 |
+
shape_list(attn_output),
|
| 367 |
+
[bsz * self.num_heads, tgt_len, self.head_dim],
|
| 368 |
+
message=(
|
| 369 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
|
| 370 |
+
f" {shape_list(attn_output)}"
|
| 371 |
+
),
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
attn_output = tf.transpose(
|
| 375 |
+
tf.reshape(attn_output, (bsz, self.num_heads, tgt_len, self.head_dim)), (0, 2, 1, 3)
|
| 376 |
+
)
|
| 377 |
+
attn_output = tf.reshape(attn_output, (bsz, tgt_len, embed_dim))
|
| 378 |
+
|
| 379 |
+
attn_output = self.out_proj(attn_output)
|
| 380 |
+
attn_weights: tf.Tensor = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len))
|
| 381 |
+
|
| 382 |
+
return attn_output, attn_weights, past_key_value
|
| 383 |
+
|
| 384 |
+
def build(self, input_shape=None):
|
| 385 |
+
if self.built:
|
| 386 |
+
return
|
| 387 |
+
self.built = True
|
| 388 |
+
if getattr(self, "k_proj", None) is not None:
|
| 389 |
+
with tf.name_scope(self.k_proj.name):
|
| 390 |
+
self.k_proj.build([None, None, self.embed_dim])
|
| 391 |
+
if getattr(self, "q_proj", None) is not None:
|
| 392 |
+
with tf.name_scope(self.q_proj.name):
|
| 393 |
+
self.q_proj.build([None, None, self.embed_dim])
|
| 394 |
+
if getattr(self, "v_proj", None) is not None:
|
| 395 |
+
with tf.name_scope(self.v_proj.name):
|
| 396 |
+
self.v_proj.build([None, None, self.embed_dim])
|
| 397 |
+
if getattr(self, "out_proj", None) is not None:
|
| 398 |
+
with tf.name_scope(self.out_proj.name):
|
| 399 |
+
self.out_proj.build([None, None, self.embed_dim])
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
class TFSpeech2TextEncoderLayer(keras.layers.Layer):
|
| 403 |
+
def __init__(self, config: Speech2TextConfig, **kwargs):
|
| 404 |
+
super().__init__(**kwargs)
|
| 405 |
+
self.embed_dim = config.d_model
|
| 406 |
+
self.self_attn = TFSpeech2TextAttention(
|
| 407 |
+
self.embed_dim, config.encoder_attention_heads, dropout=config.attention_dropout, name="self_attn"
|
| 408 |
+
)
|
| 409 |
+
self.self_attn_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="self_attn_layer_norm")
|
| 410 |
+
self.dropout = keras.layers.Dropout(config.dropout)
|
| 411 |
+
self.activation_fn = get_tf_activation(config.activation_function)
|
| 412 |
+
self.activation_dropout = keras.layers.Dropout(config.activation_dropout)
|
| 413 |
+
self.fc1 = keras.layers.Dense(config.encoder_ffn_dim, name="fc1")
|
| 414 |
+
self.fc2 = keras.layers.Dense(self.embed_dim, name="fc2")
|
| 415 |
+
self.final_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="final_layer_norm")
|
| 416 |
+
self.config = config
|
| 417 |
+
|
| 418 |
+
def call(
|
| 419 |
+
self, hidden_states: tf.Tensor, attention_mask: tf.Tensor, layer_head_mask: tf.Tensor, training: bool = False
|
| 420 |
+
):
|
| 421 |
+
"""
|
| 422 |
+
Args:
|
| 423 |
+
hidden_states (`tf.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 424 |
+
attention_mask (`tf.Tensor`): attention mask of size
|
| 425 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 426 |
+
layer_head_mask (`tf.Tensor`): mask for attention heads in a given layer of size
|
| 427 |
+
`(encoder_attention_heads,)`
|
| 428 |
+
"""
|
| 429 |
+
residual = hidden_states
|
| 430 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 431 |
+
hidden_states, self_attn_weights, _ = self.self_attn(
|
| 432 |
+
hidden_states=hidden_states,
|
| 433 |
+
attention_mask=attention_mask,
|
| 434 |
+
layer_head_mask=layer_head_mask,
|
| 435 |
+
training=training,
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
tf.debugging.assert_equal(
|
| 439 |
+
shape_list(hidden_states),
|
| 440 |
+
shape_list(residual),
|
| 441 |
+
message=f"Self attn modified the shape of query {shape_list(residual)} to {shape_list(hidden_states)}",
|
| 442 |
+
)
|
| 443 |
+
|
| 444 |
+
hidden_states = self.dropout(hidden_states, training=training)
|
| 445 |
+
hidden_states = residual + hidden_states
|
| 446 |
+
|
| 447 |
+
residual = hidden_states
|
| 448 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 449 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 450 |
+
hidden_states = self.activation_dropout(hidden_states, training=training)
|
| 451 |
+
hidden_states = self.fc2(hidden_states)
|
| 452 |
+
hidden_states = self.dropout(hidden_states, training=training)
|
| 453 |
+
hidden_states = residual + hidden_states
|
| 454 |
+
|
| 455 |
+
return hidden_states, self_attn_weights
|
| 456 |
+
|
| 457 |
+
def build(self, input_shape=None):
|
| 458 |
+
if self.built:
|
| 459 |
+
return
|
| 460 |
+
self.built = True
|
| 461 |
+
if getattr(self, "self_attn", None) is not None:
|
| 462 |
+
with tf.name_scope(self.self_attn.name):
|
| 463 |
+
self.self_attn.build(None)
|
| 464 |
+
if getattr(self, "self_attn_layer_norm", None) is not None:
|
| 465 |
+
with tf.name_scope(self.self_attn_layer_norm.name):
|
| 466 |
+
self.self_attn_layer_norm.build([None, None, self.embed_dim])
|
| 467 |
+
if getattr(self, "fc1", None) is not None:
|
| 468 |
+
with tf.name_scope(self.fc1.name):
|
| 469 |
+
self.fc1.build([None, None, self.embed_dim])
|
| 470 |
+
if getattr(self, "fc2", None) is not None:
|
| 471 |
+
with tf.name_scope(self.fc2.name):
|
| 472 |
+
self.fc2.build([None, None, self.config.encoder_ffn_dim])
|
| 473 |
+
if getattr(self, "final_layer_norm", None) is not None:
|
| 474 |
+
with tf.name_scope(self.final_layer_norm.name):
|
| 475 |
+
self.final_layer_norm.build([None, None, self.embed_dim])
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
class TFSpeech2TextDecoderLayer(keras.layers.Layer):
|
| 479 |
+
def __init__(self, config: Speech2TextConfig, **kwargs):
|
| 480 |
+
super().__init__(**kwargs)
|
| 481 |
+
self.embed_dim = config.d_model
|
| 482 |
+
|
| 483 |
+
self.self_attn = TFSpeech2TextAttention(
|
| 484 |
+
embed_dim=self.embed_dim,
|
| 485 |
+
num_heads=config.decoder_attention_heads,
|
| 486 |
+
dropout=config.attention_dropout,
|
| 487 |
+
name="self_attn",
|
| 488 |
+
is_decoder=True,
|
| 489 |
+
)
|
| 490 |
+
self.dropout = keras.layers.Dropout(config.dropout)
|
| 491 |
+
self.activation_fn = get_tf_activation(config.activation_function)
|
| 492 |
+
self.activation_dropout = keras.layers.Dropout(config.activation_dropout)
|
| 493 |
+
|
| 494 |
+
self.self_attn_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="self_attn_layer_norm")
|
| 495 |
+
self.encoder_attn = TFSpeech2TextAttention(
|
| 496 |
+
self.embed_dim,
|
| 497 |
+
config.decoder_attention_heads,
|
| 498 |
+
dropout=config.attention_dropout,
|
| 499 |
+
name="encoder_attn",
|
| 500 |
+
is_decoder=True,
|
| 501 |
+
)
|
| 502 |
+
self.encoder_attn_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="encoder_attn_layer_norm")
|
| 503 |
+
self.fc1 = keras.layers.Dense(config.decoder_ffn_dim, name="fc1")
|
| 504 |
+
self.fc2 = keras.layers.Dense(self.embed_dim, name="fc2")
|
| 505 |
+
self.final_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="final_layer_norm")
|
| 506 |
+
self.config = config
|
| 507 |
+
|
| 508 |
+
def call(
|
| 509 |
+
self,
|
| 510 |
+
hidden_states,
|
| 511 |
+
attention_mask: tf.Tensor | None = None,
|
| 512 |
+
encoder_hidden_states: tf.Tensor | None = None,
|
| 513 |
+
encoder_attention_mask: tf.Tensor | None = None,
|
| 514 |
+
layer_head_mask: tf.Tensor | None = None,
|
| 515 |
+
cross_attn_layer_head_mask: tf.Tensor | None = None,
|
| 516 |
+
past_key_value: tuple[tf.Tensor] | None = None,
|
| 517 |
+
training=False,
|
| 518 |
+
) -> tuple[tf.Tensor, tf.Tensor, tuple[tuple[tf.Tensor]]]:
|
| 519 |
+
"""
|
| 520 |
+
Args:
|
| 521 |
+
hidden_states (`tf.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 522 |
+
attention_mask (`tf.Tensor`): attention mask of size
|
| 523 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 524 |
+
encoder_hidden_states (`tf.Tensor`):
|
| 525 |
+
cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 526 |
+
encoder_attention_mask (`tf.Tensor`): encoder attention mask of size
|
| 527 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 528 |
+
layer_head_mask (`tf.Tensor`): mask for attention heads in a given layer of size
|
| 529 |
+
`(decoder_attention_heads,)`
|
| 530 |
+
cross_attn_layer_head_mask (`tf.Tensor`): mask for heads of the cross-attention module.
|
| 531 |
+
`(decoder_attention_heads,)`
|
| 532 |
+
past_key_value (`Tuple(tf.Tensor)`): cached past key and value projection states
|
| 533 |
+
"""
|
| 534 |
+
residual = hidden_states
|
| 535 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 536 |
+
|
| 537 |
+
# Self Attention
|
| 538 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
| 539 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
| 540 |
+
# add present self-attn cache to positions 1,2 of present_key_value tuple
|
| 541 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
| 542 |
+
hidden_states=hidden_states,
|
| 543 |
+
past_key_value=self_attn_past_key_value,
|
| 544 |
+
attention_mask=attention_mask,
|
| 545 |
+
layer_head_mask=layer_head_mask,
|
| 546 |
+
training=training,
|
| 547 |
+
)
|
| 548 |
+
hidden_states = self.dropout(hidden_states, training=training)
|
| 549 |
+
hidden_states = residual + hidden_states
|
| 550 |
+
|
| 551 |
+
# Cross-Attention Block
|
| 552 |
+
cross_attn_present_key_value = None
|
| 553 |
+
cross_attn_weights = None
|
| 554 |
+
if encoder_hidden_states is not None:
|
| 555 |
+
residual = hidden_states
|
| 556 |
+
hidden_states = self.encoder_attn_layer_norm(hidden_states)
|
| 557 |
+
|
| 558 |
+
# cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
|
| 559 |
+
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
|
| 560 |
+
hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
|
| 561 |
+
hidden_states=hidden_states,
|
| 562 |
+
key_value_states=encoder_hidden_states,
|
| 563 |
+
attention_mask=encoder_attention_mask,
|
| 564 |
+
layer_head_mask=cross_attn_layer_head_mask,
|
| 565 |
+
past_key_value=cross_attn_past_key_value,
|
| 566 |
+
training=training,
|
| 567 |
+
)
|
| 568 |
+
hidden_states = self.dropout(hidden_states, training=training)
|
| 569 |
+
hidden_states = residual + hidden_states
|
| 570 |
+
|
| 571 |
+
# add cross-attn to positions 3,4 of present_key_value tuple
|
| 572 |
+
present_key_value = present_key_value + cross_attn_present_key_value
|
| 573 |
+
|
| 574 |
+
# Fully Connected
|
| 575 |
+
residual = hidden_states
|
| 576 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 577 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 578 |
+
hidden_states = self.activation_dropout(hidden_states, training=training)
|
| 579 |
+
hidden_states = self.fc2(hidden_states)
|
| 580 |
+
hidden_states = self.dropout(hidden_states, training=training)
|
| 581 |
+
hidden_states = residual + hidden_states
|
| 582 |
+
|
| 583 |
+
return (
|
| 584 |
+
hidden_states,
|
| 585 |
+
self_attn_weights,
|
| 586 |
+
cross_attn_weights,
|
| 587 |
+
present_key_value,
|
| 588 |
+
)
|
| 589 |
+
|
| 590 |
+
def build(self, input_shape=None):
|
| 591 |
+
if self.built:
|
| 592 |
+
return
|
| 593 |
+
self.built = True
|
| 594 |
+
if getattr(self, "self_attn", None) is not None:
|
| 595 |
+
with tf.name_scope(self.self_attn.name):
|
| 596 |
+
self.self_attn.build(None)
|
| 597 |
+
if getattr(self, "self_attn_layer_norm", None) is not None:
|
| 598 |
+
with tf.name_scope(self.self_attn_layer_norm.name):
|
| 599 |
+
self.self_attn_layer_norm.build([None, None, self.embed_dim])
|
| 600 |
+
if getattr(self, "encoder_attn", None) is not None:
|
| 601 |
+
with tf.name_scope(self.encoder_attn.name):
|
| 602 |
+
self.encoder_attn.build(None)
|
| 603 |
+
if getattr(self, "encoder_attn_layer_norm", None) is not None:
|
| 604 |
+
with tf.name_scope(self.encoder_attn_layer_norm.name):
|
| 605 |
+
self.encoder_attn_layer_norm.build([None, None, self.embed_dim])
|
| 606 |
+
if getattr(self, "fc1", None) is not None:
|
| 607 |
+
with tf.name_scope(self.fc1.name):
|
| 608 |
+
self.fc1.build([None, None, self.embed_dim])
|
| 609 |
+
if getattr(self, "fc2", None) is not None:
|
| 610 |
+
with tf.name_scope(self.fc2.name):
|
| 611 |
+
self.fc2.build([None, None, self.config.decoder_ffn_dim])
|
| 612 |
+
if getattr(self, "final_layer_norm", None) is not None:
|
| 613 |
+
with tf.name_scope(self.final_layer_norm.name):
|
| 614 |
+
self.final_layer_norm.build([None, None, self.embed_dim])
|
| 615 |
+
|
| 616 |
+
|
| 617 |
+
class TFSpeech2TextPreTrainedModel(TFPreTrainedModel):
|
| 618 |
+
config_class = Speech2TextConfig
|
| 619 |
+
base_model_prefix = "model"
|
| 620 |
+
main_input_name = "input_features"
|
| 621 |
+
_keys_to_ignore_on_load_unexpected = [r"encoder.embed_positions.weights"]
|
| 622 |
+
|
| 623 |
+
def _get_feat_extract_output_lengths(self, input_lengths: tf.Tensor):
|
| 624 |
+
"""
|
| 625 |
+
Computes the output length of the convolutional layers
|
| 626 |
+
"""
|
| 627 |
+
for _ in range(self.config.num_conv_layers):
|
| 628 |
+
input_lengths = (input_lengths - 1) // 2 + 1
|
| 629 |
+
|
| 630 |
+
return input_lengths
|
| 631 |
+
|
| 632 |
+
@property
|
| 633 |
+
def input_signature(self):
|
| 634 |
+
return {
|
| 635 |
+
"input_features": tf.TensorSpec(
|
| 636 |
+
(None, None, self.config.input_feat_per_channel * self.config.input_channels),
|
| 637 |
+
tf.float32,
|
| 638 |
+
name="input_features",
|
| 639 |
+
),
|
| 640 |
+
"attention_mask": tf.TensorSpec((None, None), tf.int32, name="attention_mask"),
|
| 641 |
+
"decoder_input_ids": tf.TensorSpec((None, None), tf.int32, name="decoder_input_ids"),
|
| 642 |
+
"decoder_attention_mask": tf.TensorSpec((None, None), tf.int32, name="decoder_attention_mask"),
|
| 643 |
+
}
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
SPEECH_TO_TEXT_START_DOCSTRING = r"""
|
| 647 |
+
This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 648 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 649 |
+
etc.)
|
| 650 |
+
|
| 651 |
+
This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
|
| 652 |
+
as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
|
| 653 |
+
behavior.
|
| 654 |
+
|
| 655 |
+
<Tip>
|
| 656 |
+
|
| 657 |
+
TensorFlow models and layers in `transformers` accept two formats as input:
|
| 658 |
+
|
| 659 |
+
- having all inputs as keyword arguments (like PyTorch models), or
|
| 660 |
+
- having all inputs as a list, tuple or dict in the first positional argument.
|
| 661 |
+
|
| 662 |
+
The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
|
| 663 |
+
and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
|
| 664 |
+
pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
|
| 665 |
+
format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
|
| 666 |
+
the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
|
| 667 |
+
positional argument:
|
| 668 |
+
|
| 669 |
+
- a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
|
| 670 |
+
- a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
|
| 671 |
+
`model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
|
| 672 |
+
- a dictionary with one or several input Tensors associated to the input names given in the docstring:
|
| 673 |
+
`model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
|
| 674 |
+
|
| 675 |
+
Note that when creating models and layers with
|
| 676 |
+
[subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
|
| 677 |
+
about any of this, as you can just pass inputs like you would to any other Python function!
|
| 678 |
+
|
| 679 |
+
</Tip>
|
| 680 |
+
|
| 681 |
+
Parameters:
|
| 682 |
+
config ([`Speech2TextConfig`]):
|
| 683 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
| 684 |
+
load the weights associated with the model, only the configuration. Check out the
|
| 685 |
+
[`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
|
| 686 |
+
"""
|
| 687 |
+
|
| 688 |
+
|
| 689 |
+
SPEECH_TO_TEXT_INPUTS_DOCSTRING = r"""
|
| 690 |
+
Args:
|
| 691 |
+
input_features (`tf.Tensor` of shape `(batch_size, sequence_length, feature_size)`):
|
| 692 |
+
Float values of fbank features extracted from the raw speech waveform. Raw speech waveform can be obtained
|
| 693 |
+
by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a `numpy.ndarray or a
|
| 694 |
+
`torch.Tensor``, *e.g.* via the torchcodec library (`pip install torchcodec`) or the soundfile library
|
| 695 |
+
(`pip install soundfile`).
|
| 696 |
+
To prepare the arrayinto `input_features`, the [`AutoFeatureExtractor`] should be used for extracting
|
| 697 |
+
the fbank features, padding and conversion into a tensor of floats.
|
| 698 |
+
See [`~Speech2TextFeatureExtractor.__call__`]
|
| 699 |
+
attention_mask (`tf.Tensor` of shape `({0})`, *optional*):
|
| 700 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 701 |
+
|
| 702 |
+
- 1 for tokens that are **not masked**,
|
| 703 |
+
- 0 for tokens that are **masked**.
|
| 704 |
+
|
| 705 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 706 |
+
decoder_input_ids (`tf.Tensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 707 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 708 |
+
|
| 709 |
+
Indices can be obtained using [`Speech2TextTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 710 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 711 |
+
|
| 712 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 713 |
+
|
| 714 |
+
SpeechToText uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If
|
| 715 |
+
`past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
| 716 |
+
`past_key_values`).
|
| 717 |
+
|
| 718 |
+
For translation and summarization training, `decoder_input_ids` should be provided. If no
|
| 719 |
+
`decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
|
| 720 |
+
for denoising pre-training following the paper.
|
| 721 |
+
decoder_attention_mask (`tf.Tensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 722 |
+
will be made by default and ignore pad tokens. It is not recommended to set this for most use cases.
|
| 723 |
+
head_mask (`tf.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
|
| 724 |
+
Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
|
| 725 |
+
|
| 726 |
+
- 1 indicates the head is **not masked**,
|
| 727 |
+
- 0 indicates the head is **masked**.
|
| 728 |
+
|
| 729 |
+
decoder_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 730 |
+
Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
|
| 731 |
+
|
| 732 |
+
- 1 indicates the head is **not masked**,
|
| 733 |
+
- 0 indicates the head is **masked**.
|
| 734 |
+
|
| 735 |
+
cross_attn_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 736 |
+
Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
|
| 737 |
+
|
| 738 |
+
- 1 indicates the head is **not masked**,
|
| 739 |
+
- 0 indicates the head is **masked**.
|
| 740 |
+
|
| 741 |
+
encoder_outputs (`tf.FloatTensor`, *optional*):
|
| 742 |
+
hidden states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
|
| 743 |
+
of shape `(batch_size, sequence_length, hidden_size)` is a sequence of
|
| 744 |
+
past_key_values (`tuple[tuple[tf.Tensor]]` of length `config.n_layers`)
|
| 745 |
+
contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
| 746 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 747 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 748 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 749 |
+
decoder_inputs_embeds (`tf.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
|
| 750 |
+
Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
|
| 751 |
+
representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
|
| 752 |
+
input (see `past_key_values`). This is useful if you want more control over how to convert
|
| 753 |
+
`decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
|
| 754 |
+
use_cache (`bool`, *optional*):
|
| 755 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 756 |
+
`past_key_values`).
|
| 757 |
+
output_attentions (`bool`, *optional*):
|
| 758 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 759 |
+
tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
|
| 760 |
+
config will be used instead.
|
| 761 |
+
output_hidden_states (`bool`, *optional*):
|
| 762 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 763 |
+
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
|
| 764 |
+
used instead.
|
| 765 |
+
return_dict (`bool`, *optional*):
|
| 766 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
|
| 767 |
+
eager mode, in graph mode the value will always be set to True.
|
| 768 |
+
training (`bool`, *optional*, defaults to `False`):
|
| 769 |
+
Whether or not to use the model in training mode (some modules like dropout modules have different
|
| 770 |
+
behaviors between training and evaluation).
|
| 771 |
+
"""
|
| 772 |
+
|
| 773 |
+
|
| 774 |
+
@keras_serializable
|
| 775 |
+
class TFSpeech2TextEncoder(keras.layers.Layer):
|
| 776 |
+
config_class = Speech2TextConfig
|
| 777 |
+
"""
|
| 778 |
+
Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
|
| 779 |
+
[`TFSpeech2TextEncoderLayer`].
|
| 780 |
+
|
| 781 |
+
Args:
|
| 782 |
+
config: Speech2TextConfig
|
| 783 |
+
"""
|
| 784 |
+
|
| 785 |
+
def __init__(self, config: Speech2TextConfig, **kwargs):
|
| 786 |
+
super().__init__(**kwargs)
|
| 787 |
+
self.config = config
|
| 788 |
+
|
| 789 |
+
self.dropout = keras.layers.Dropout(config.dropout)
|
| 790 |
+
self.layerdrop = config.encoder_layerdrop
|
| 791 |
+
|
| 792 |
+
embed_dim = config.d_model
|
| 793 |
+
self.padding_idx = config.pad_token_id
|
| 794 |
+
self.max_source_positions = config.max_source_positions
|
| 795 |
+
self.embed_scale = tf.math.sqrt(float(embed_dim)) if config.scale_embedding else 1.0
|
| 796 |
+
|
| 797 |
+
self.conv = TFConv1dSubsampler(config, name="conv")
|
| 798 |
+
|
| 799 |
+
self.embed_positions = TFSpeech2TextSinusoidalPositionalEmbedding(
|
| 800 |
+
num_positions=config.max_source_positions,
|
| 801 |
+
embedding_dim=embed_dim,
|
| 802 |
+
padding_idx=self.padding_idx,
|
| 803 |
+
name="embed_positions",
|
| 804 |
+
)
|
| 805 |
+
self.layers = [TFSpeech2TextEncoderLayer(config, name=f"layers.{i}") for i in range(config.encoder_layers)]
|
| 806 |
+
self.layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="layer_norm")
|
| 807 |
+
|
| 808 |
+
def _get_feat_extract_output_lengths(self, input_lengths: tf.Tensor):
|
| 809 |
+
"""
|
| 810 |
+
Computes the output length of the convolutional layers
|
| 811 |
+
"""
|
| 812 |
+
for _ in range(self.config.num_conv_layers):
|
| 813 |
+
input_lengths = (input_lengths - 1) // 2 + 1
|
| 814 |
+
|
| 815 |
+
return input_lengths
|
| 816 |
+
|
| 817 |
+
def _get_feature_vector_attention_mask(self, feature_vector_length, attention_mask):
|
| 818 |
+
# generate creates 3D attention mask, because of the shape of input_features
|
| 819 |
+
# convert it to 2D if that's the case
|
| 820 |
+
if len(attention_mask.shape) > 2:
|
| 821 |
+
attention_mask = attention_mask[:, :, -1]
|
| 822 |
+
|
| 823 |
+
subsampled_lengths = self._get_feat_extract_output_lengths(tf.math.reduce_sum(attention_mask, -1))
|
| 824 |
+
bsz = shape_list(attention_mask)[0]
|
| 825 |
+
indices = tf.concat(
|
| 826 |
+
(
|
| 827 |
+
tf.expand_dims(tf.range(bsz, dtype=attention_mask.dtype), -1),
|
| 828 |
+
tf.expand_dims(subsampled_lengths - 1, -1),
|
| 829 |
+
),
|
| 830 |
+
axis=-1,
|
| 831 |
+
)
|
| 832 |
+
attention_mask = tf.scatter_nd(indices=indices, updates=tf.ones(bsz), shape=[bsz, feature_vector_length])
|
| 833 |
+
attention_mask = tf.cast(tf.reverse(tf.math.cumsum(tf.reverse(attention_mask, [-1]), -1), [-1]), tf.int64)
|
| 834 |
+
return attention_mask
|
| 835 |
+
|
| 836 |
+
@unpack_inputs
|
| 837 |
+
def call(
|
| 838 |
+
self,
|
| 839 |
+
input_features=None,
|
| 840 |
+
attention_mask=None,
|
| 841 |
+
head_mask=None,
|
| 842 |
+
output_attentions=None,
|
| 843 |
+
output_hidden_states=None,
|
| 844 |
+
return_dict=None,
|
| 845 |
+
training=False,
|
| 846 |
+
):
|
| 847 |
+
"""
|
| 848 |
+
Args:
|
| 849 |
+
input_features (`tf.Tensor` of shape `(batch_size, sequence_length, feature_size)`):
|
| 850 |
+
Float values of fbank features extracted from the raw speech waveform. Raw speech waveform can be
|
| 851 |
+
obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
|
| 852 |
+
`numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
|
| 853 |
+
the soundfile library (`pip install soundfile`). To prepare the array into
|
| 854 |
+
`input_features`, the [`AutoFeatureExtractor`] should be used for extracting the fbank features,
|
| 855 |
+
padding and conversion into a tensor of floats. See [`~Speech2TextFeatureExtractor.__call__`]
|
| 856 |
+
attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 857 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 858 |
+
|
| 859 |
+
- 1 for tokens that are **not masked**,
|
| 860 |
+
- 0 for tokens that are **masked**.
|
| 861 |
+
|
| 862 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 863 |
+
head_mask (`tf.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, `optional):
|
| 864 |
+
Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
|
| 865 |
+
|
| 866 |
+
- 1 indicates the head is **not masked**,
|
| 867 |
+
- 0 indicates the head is **masked**.
|
| 868 |
+
|
| 869 |
+
output_attentions (`bool`, *optional*):
|
| 870 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 871 |
+
returned tensors for more detail.
|
| 872 |
+
output_hidden_states (`bool`, *optional*):
|
| 873 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 874 |
+
for more detail.
|
| 875 |
+
return_dict (`bool`, *optional*):
|
| 876 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 877 |
+
"""
|
| 878 |
+
if input_features is None:
|
| 879 |
+
raise ValueError("You have to specify input_features")
|
| 880 |
+
|
| 881 |
+
inputs_embeds = self.conv(input_features)
|
| 882 |
+
inputs_embeds = self.embed_scale * inputs_embeds
|
| 883 |
+
|
| 884 |
+
# subsample attention mask if necessary
|
| 885 |
+
if attention_mask is not None:
|
| 886 |
+
attention_mask = self._get_feature_vector_attention_mask(tf.shape(inputs_embeds)[1], attention_mask)
|
| 887 |
+
padding_mask = tf.cast(tf.math.not_equal(attention_mask, 1), tf.int64)
|
| 888 |
+
else:
|
| 889 |
+
padding_mask = tf.zeros(tf.shape(inputs_embeds)[:-1], dtype=tf.int64)
|
| 890 |
+
|
| 891 |
+
embed_pos = self.embed_positions(padding_mask)
|
| 892 |
+
|
| 893 |
+
hidden_states = inputs_embeds + embed_pos
|
| 894 |
+
hidden_states = self.dropout(hidden_states, training=training)
|
| 895 |
+
|
| 896 |
+
# check attention mask and invert
|
| 897 |
+
if attention_mask is not None:
|
| 898 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 899 |
+
attention_mask = _expand_mask(attention_mask)
|
| 900 |
+
|
| 901 |
+
encoder_states = () if output_hidden_states else None
|
| 902 |
+
all_attentions = () if output_attentions else None
|
| 903 |
+
|
| 904 |
+
# check if head_mask has a correct number of layers specified if desired
|
| 905 |
+
if head_mask is not None:
|
| 906 |
+
tf.debugging.assert_equal(
|
| 907 |
+
shape_list(head_mask)[0],
|
| 908 |
+
len(self.layers),
|
| 909 |
+
message=(
|
| 910 |
+
f"The head_mask should be specified for {len(self.layers)} layers, but it is for"
|
| 911 |
+
f" {shape_list(head_mask)[0]}."
|
| 912 |
+
),
|
| 913 |
+
)
|
| 914 |
+
|
| 915 |
+
for idx, encoder_layer in enumerate(self.layers):
|
| 916 |
+
if output_hidden_states:
|
| 917 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 918 |
+
# add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
|
| 919 |
+
dropout_probability = random.uniform(0, 1)
|
| 920 |
+
if training and (dropout_probability < self.layerdrop): # skip the layer
|
| 921 |
+
continue
|
| 922 |
+
|
| 923 |
+
hidden_states, attn = encoder_layer(
|
| 924 |
+
hidden_states,
|
| 925 |
+
attention_mask,
|
| 926 |
+
head_mask[idx] if head_mask is not None else None,
|
| 927 |
+
training=training,
|
| 928 |
+
)
|
| 929 |
+
|
| 930 |
+
if output_attentions:
|
| 931 |
+
all_attentions += (attn,)
|
| 932 |
+
|
| 933 |
+
hidden_states = self.layer_norm(hidden_states)
|
| 934 |
+
if output_hidden_states:
|
| 935 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 936 |
+
|
| 937 |
+
if not return_dict:
|
| 938 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
| 939 |
+
return TFBaseModelOutput(
|
| 940 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
|
| 941 |
+
)
|
| 942 |
+
|
| 943 |
+
def build(self, input_shape=None):
|
| 944 |
+
if self.built:
|
| 945 |
+
return
|
| 946 |
+
self.built = True
|
| 947 |
+
if getattr(self, "conv", None) is not None:
|
| 948 |
+
with tf.name_scope(self.conv.name):
|
| 949 |
+
self.conv.build(None)
|
| 950 |
+
if getattr(self, "embed_positions", None) is not None:
|
| 951 |
+
with tf.name_scope(self.embed_positions.name):
|
| 952 |
+
self.embed_positions.build(None)
|
| 953 |
+
if getattr(self, "layer_norm", None) is not None:
|
| 954 |
+
with tf.name_scope(self.layer_norm.name):
|
| 955 |
+
self.layer_norm.build([None, None, self.config.d_model])
|
| 956 |
+
if getattr(self, "layers", None) is not None:
|
| 957 |
+
for layer in self.layers:
|
| 958 |
+
with tf.name_scope(layer.name):
|
| 959 |
+
layer.build(None)
|
| 960 |
+
|
| 961 |
+
|
| 962 |
+
@keras_serializable
|
| 963 |
+
class TFSpeech2TextDecoder(keras.layers.Layer):
|
| 964 |
+
config_class = Speech2TextConfig
|
| 965 |
+
"""
|
| 966 |
+
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`TFSpeech2TextDecoderLayer`]
|
| 967 |
+
|
| 968 |
+
Args:
|
| 969 |
+
config: Speech2TextConfig
|
| 970 |
+
"""
|
| 971 |
+
|
| 972 |
+
def __init__(self, config: Speech2TextConfig, **kwargs):
|
| 973 |
+
super().__init__(**kwargs)
|
| 974 |
+
self.config = config
|
| 975 |
+
self.layerdrop = config.decoder_layerdrop
|
| 976 |
+
self.padding_idx = config.pad_token_id
|
| 977 |
+
self.max_target_positions = config.max_target_positions
|
| 978 |
+
self.embed_scale = tf.math.sqrt(float(config.d_model)) if config.scale_embedding else 1.0
|
| 979 |
+
|
| 980 |
+
self.embed_tokens = TFSharedEmbeddings(config.vocab_size, config.d_model, name="embed_tokens")
|
| 981 |
+
|
| 982 |
+
self.embed_positions = TFSpeech2TextSinusoidalPositionalEmbedding(
|
| 983 |
+
num_positions=config.max_target_positions,
|
| 984 |
+
embedding_dim=config.d_model,
|
| 985 |
+
padding_idx=self.padding_idx,
|
| 986 |
+
name="embed_positions",
|
| 987 |
+
)
|
| 988 |
+
|
| 989 |
+
self.layers = [TFSpeech2TextDecoderLayer(config, name=f"layers.{i}") for i in range(config.decoder_layers)]
|
| 990 |
+
self.layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="layer_norm")
|
| 991 |
+
|
| 992 |
+
self.dropout = keras.layers.Dropout(config.dropout)
|
| 993 |
+
|
| 994 |
+
def get_embed_tokens(self):
|
| 995 |
+
return self.embed_tokens
|
| 996 |
+
|
| 997 |
+
def set_embed_tokens(self, embed_tokens):
|
| 998 |
+
self.embed_tokens = embed_tokens
|
| 999 |
+
|
| 1000 |
+
@unpack_inputs
|
| 1001 |
+
def call(
|
| 1002 |
+
self,
|
| 1003 |
+
input_ids=None,
|
| 1004 |
+
inputs_embeds=None,
|
| 1005 |
+
attention_mask=None,
|
| 1006 |
+
encoder_hidden_states=None,
|
| 1007 |
+
encoder_attention_mask=None,
|
| 1008 |
+
head_mask=None,
|
| 1009 |
+
cross_attn_head_mask=None,
|
| 1010 |
+
past_key_values=None,
|
| 1011 |
+
use_cache=None,
|
| 1012 |
+
output_attentions=None,
|
| 1013 |
+
output_hidden_states=None,
|
| 1014 |
+
return_dict=None,
|
| 1015 |
+
training=False,
|
| 1016 |
+
):
|
| 1017 |
+
r"""
|
| 1018 |
+
Args:
|
| 1019 |
+
input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
|
| 1020 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
|
| 1021 |
+
provide it.
|
| 1022 |
+
|
| 1023 |
+
Indices can be obtained using [`Speech2TextTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1024 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 1025 |
+
|
| 1026 |
+
[What are input IDs?](../glossary#input-ids)
|
| 1027 |
+
attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1028 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 1029 |
+
|
| 1030 |
+
- 1 for tokens that are **not masked**,
|
| 1031 |
+
- 0 for tokens that are **masked**.
|
| 1032 |
+
|
| 1033 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 1034 |
+
encoder_hidden_states (`tf.Tensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
|
| 1035 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
|
| 1036 |
+
of the decoder.
|
| 1037 |
+
encoder_attention_mask (`tf.Tensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
|
| 1038 |
+
Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
|
| 1039 |
+
selected in `[0, 1]`:
|
| 1040 |
+
|
| 1041 |
+
- 1 for tokens that are **not masked**,
|
| 1042 |
+
- 0 for tokens that are **masked**.
|
| 1043 |
+
|
| 1044 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 1045 |
+
head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 1046 |
+
Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
|
| 1047 |
+
|
| 1048 |
+
- 1 indicates the head is **not masked**,
|
| 1049 |
+
- 0 indicates the head is **masked**.
|
| 1050 |
+
|
| 1051 |
+
cross_attn_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 1052 |
+
Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
|
| 1053 |
+
|
| 1054 |
+
- 1 indicates the head is **not masked**,
|
| 1055 |
+
- 0 indicates the head is **masked**.
|
| 1056 |
+
|
| 1057 |
+
past_key_values (`tuple[tuple[tf.Tensor]]` of length `config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
|
| 1058 |
+
Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up
|
| 1059 |
+
decoding.
|
| 1060 |
+
|
| 1061 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
|
| 1062 |
+
that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
|
| 1063 |
+
all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 1064 |
+
inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 1065 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 1066 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 1067 |
+
than the model's internal embedding lookup matrix.
|
| 1068 |
+
output_attentions (`bool`, *optional*):
|
| 1069 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 1070 |
+
returned tensors for more detail.
|
| 1071 |
+
output_hidden_states (`bool`, *optional*):
|
| 1072 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 1073 |
+
for more detail.
|
| 1074 |
+
return_dict (`bool`, *optional*):
|
| 1075 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 1076 |
+
"""
|
| 1077 |
+
|
| 1078 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 1079 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
| 1080 |
+
elif input_ids is not None:
|
| 1081 |
+
input_shape = shape_list(input_ids)
|
| 1082 |
+
elif inputs_embeds is not None:
|
| 1083 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
| 1084 |
+
else:
|
| 1085 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
| 1086 |
+
|
| 1087 |
+
# past_key_values_length
|
| 1088 |
+
past_key_values_length = shape_list(past_key_values[0][0])[2] if past_key_values is not None else 0
|
| 1089 |
+
|
| 1090 |
+
if inputs_embeds is None:
|
| 1091 |
+
check_embeddings_within_bounds(input_ids, self.embed_tokens.vocab_size)
|
| 1092 |
+
inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
|
| 1093 |
+
else:
|
| 1094 |
+
inputs_embeds = inputs_embeds
|
| 1095 |
+
|
| 1096 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 1097 |
+
if input_shape[-1] > 1:
|
| 1098 |
+
combined_attention_mask = _make_causal_mask(input_shape, past_key_values_length=past_key_values_length)
|
| 1099 |
+
else:
|
| 1100 |
+
combined_attention_mask = _expand_mask(
|
| 1101 |
+
tf.ones((input_shape[0], input_shape[1] + past_key_values_length)), tgt_len=input_shape[-1]
|
| 1102 |
+
)
|
| 1103 |
+
|
| 1104 |
+
if attention_mask is not None:
|
| 1105 |
+
combined_attention_mask = combined_attention_mask + _expand_mask(attention_mask, tgt_len=input_shape[-1])
|
| 1106 |
+
|
| 1107 |
+
# expand encoder attention mask
|
| 1108 |
+
if encoder_hidden_states is not None and encoder_attention_mask is not None:
|
| 1109 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 1110 |
+
encoder_attention_mask = _expand_mask(encoder_attention_mask, tgt_len=input_shape[-1])
|
| 1111 |
+
|
| 1112 |
+
# embed positions
|
| 1113 |
+
positions = self.embed_positions(input_ids, past_key_values_length=past_key_values_length)
|
| 1114 |
+
|
| 1115 |
+
hidden_states = inputs_embeds + positions
|
| 1116 |
+
hidden_states = self.dropout(hidden_states, training=training)
|
| 1117 |
+
|
| 1118 |
+
# decoder layers
|
| 1119 |
+
all_hidden_states = () if output_hidden_states else None
|
| 1120 |
+
all_self_attns = () if output_attentions else None
|
| 1121 |
+
all_cross_attns = () if (output_attentions and encoder_hidden_states is not None) else None
|
| 1122 |
+
next_decoder_cache = () if use_cache else None
|
| 1123 |
+
|
| 1124 |
+
# check if head_mask and cross_attn_head_mask have a correct number of layers specified if desired
|
| 1125 |
+
for attn_mask_name, attn_mask in [("head_mask", head_mask), ("cross_attn_head_mask", cross_attn_head_mask)]:
|
| 1126 |
+
if attn_mask is not None:
|
| 1127 |
+
tf.debugging.assert_equal(
|
| 1128 |
+
shape_list(attn_mask)[0],
|
| 1129 |
+
len(self.layers),
|
| 1130 |
+
message=(
|
| 1131 |
+
f"The {attn_mask_name} should be specified for {len(self.layers)} layers, but it is for"
|
| 1132 |
+
f" {shape_list(attn_mask)[0]}."
|
| 1133 |
+
),
|
| 1134 |
+
)
|
| 1135 |
+
|
| 1136 |
+
for idx, decoder_layer in enumerate(self.layers):
|
| 1137 |
+
# add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
|
| 1138 |
+
if output_hidden_states:
|
| 1139 |
+
all_hidden_states += (hidden_states,)
|
| 1140 |
+
dropout_probability = random.uniform(0, 1)
|
| 1141 |
+
if training and (dropout_probability < self.layerdrop):
|
| 1142 |
+
continue
|
| 1143 |
+
|
| 1144 |
+
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
| 1145 |
+
cross_attn_layer_head_mask = cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None
|
| 1146 |
+
|
| 1147 |
+
hidden_states, layer_self_attn, layer_cross_attn, present_key_value = decoder_layer(
|
| 1148 |
+
hidden_states,
|
| 1149 |
+
attention_mask=combined_attention_mask,
|
| 1150 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1151 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1152 |
+
layer_head_mask=head_mask[idx] if head_mask is not None else None,
|
| 1153 |
+
cross_attn_layer_head_mask=cross_attn_layer_head_mask,
|
| 1154 |
+
past_key_value=past_key_value,
|
| 1155 |
+
)
|
| 1156 |
+
|
| 1157 |
+
if use_cache:
|
| 1158 |
+
next_decoder_cache += (present_key_value,)
|
| 1159 |
+
|
| 1160 |
+
if output_attentions:
|
| 1161 |
+
all_self_attns += (layer_self_attn,)
|
| 1162 |
+
|
| 1163 |
+
if encoder_hidden_states is not None:
|
| 1164 |
+
all_cross_attns += (layer_cross_attn,)
|
| 1165 |
+
|
| 1166 |
+
hidden_states = self.layer_norm(hidden_states)
|
| 1167 |
+
if output_hidden_states:
|
| 1168 |
+
all_hidden_states += (hidden_states,)
|
| 1169 |
+
|
| 1170 |
+
next_cache = next_decoder_cache if use_cache else None
|
| 1171 |
+
|
| 1172 |
+
if not return_dict:
|
| 1173 |
+
return hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attns
|
| 1174 |
+
else:
|
| 1175 |
+
return TFBaseModelOutputWithPastAndCrossAttentions(
|
| 1176 |
+
last_hidden_state=hidden_states,
|
| 1177 |
+
past_key_values=next_cache,
|
| 1178 |
+
hidden_states=all_hidden_states,
|
| 1179 |
+
attentions=all_self_attns,
|
| 1180 |
+
cross_attentions=all_cross_attns,
|
| 1181 |
+
)
|
| 1182 |
+
|
| 1183 |
+
def build(self, input_shape=None):
|
| 1184 |
+
if self.built:
|
| 1185 |
+
return
|
| 1186 |
+
self.built = True
|
| 1187 |
+
if getattr(self, "embed_tokens", None) is not None:
|
| 1188 |
+
with tf.name_scope(self.embed_tokens.name):
|
| 1189 |
+
self.embed_tokens.build(None)
|
| 1190 |
+
if getattr(self, "embed_positions", None) is not None:
|
| 1191 |
+
with tf.name_scope(self.embed_positions.name):
|
| 1192 |
+
self.embed_positions.build(None)
|
| 1193 |
+
if getattr(self, "layer_norm", None) is not None:
|
| 1194 |
+
with tf.name_scope(self.layer_norm.name):
|
| 1195 |
+
self.layer_norm.build([None, None, self.config.d_model])
|
| 1196 |
+
if getattr(self, "layers", None) is not None:
|
| 1197 |
+
for layer in self.layers:
|
| 1198 |
+
with tf.name_scope(layer.name):
|
| 1199 |
+
layer.build(None)
|
| 1200 |
+
|
| 1201 |
+
|
| 1202 |
+
@keras_serializable
|
| 1203 |
+
class TFSpeech2TextMainLayer(keras.layers.Layer):
|
| 1204 |
+
config_class = Speech2TextConfig
|
| 1205 |
+
|
| 1206 |
+
def __init__(self, config: Speech2TextConfig, **kwargs):
|
| 1207 |
+
super().__init__(**kwargs)
|
| 1208 |
+
self.config = config
|
| 1209 |
+
|
| 1210 |
+
self.encoder = TFSpeech2TextEncoder(config, name="encoder")
|
| 1211 |
+
self.decoder = TFSpeech2TextDecoder(config, name="decoder")
|
| 1212 |
+
|
| 1213 |
+
def get_input_embeddings(self):
|
| 1214 |
+
return self.decoder.embed_tokens
|
| 1215 |
+
|
| 1216 |
+
def set_input_embeddings(self, new_embeddings):
|
| 1217 |
+
self.decoder.embed_tokens = new_embeddings
|
| 1218 |
+
|
| 1219 |
+
@unpack_inputs
|
| 1220 |
+
def call(
|
| 1221 |
+
self,
|
| 1222 |
+
input_features=None,
|
| 1223 |
+
attention_mask=None,
|
| 1224 |
+
decoder_input_ids=None,
|
| 1225 |
+
decoder_attention_mask=None,
|
| 1226 |
+
head_mask=None,
|
| 1227 |
+
decoder_head_mask=None,
|
| 1228 |
+
cross_attn_head_mask=None,
|
| 1229 |
+
encoder_outputs=None,
|
| 1230 |
+
past_key_values=None,
|
| 1231 |
+
decoder_inputs_embeds=None,
|
| 1232 |
+
use_cache=None,
|
| 1233 |
+
output_attentions=None,
|
| 1234 |
+
output_hidden_states=None,
|
| 1235 |
+
return_dict=None,
|
| 1236 |
+
training=False,
|
| 1237 |
+
**kwargs,
|
| 1238 |
+
):
|
| 1239 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1240 |
+
output_hidden_states = (
|
| 1241 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1242 |
+
)
|
| 1243 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 1244 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1245 |
+
|
| 1246 |
+
if encoder_outputs is None:
|
| 1247 |
+
encoder_outputs = self.encoder(
|
| 1248 |
+
input_features=input_features,
|
| 1249 |
+
attention_mask=attention_mask,
|
| 1250 |
+
head_mask=head_mask,
|
| 1251 |
+
output_attentions=output_attentions,
|
| 1252 |
+
output_hidden_states=output_hidden_states,
|
| 1253 |
+
return_dict=return_dict,
|
| 1254 |
+
training=training,
|
| 1255 |
+
)
|
| 1256 |
+
# If the user passed a tuple for encoder_outputs, we wrap it in a TFBaseModelOutput when return_dict=True
|
| 1257 |
+
elif return_dict and not isinstance(encoder_outputs, TFBaseModelOutput):
|
| 1258 |
+
encoder_outputs = TFBaseModelOutput(
|
| 1259 |
+
last_hidden_state=encoder_outputs[0],
|
| 1260 |
+
hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
|
| 1261 |
+
attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
|
| 1262 |
+
)
|
| 1263 |
+
# If the user passed a TFBaseModelOutput for encoder_outputs, we wrap it in a tuple when return_dict=False
|
| 1264 |
+
elif not return_dict and not isinstance(encoder_outputs, tuple):
|
| 1265 |
+
encoder_outputs = encoder_outputs.to_tuple()
|
| 1266 |
+
|
| 1267 |
+
# downsample encoder attention mask
|
| 1268 |
+
if attention_mask is not None:
|
| 1269 |
+
encoder_attention_mask = self.encoder._get_feature_vector_attention_mask(
|
| 1270 |
+
tf.shape(encoder_outputs[0])[1], attention_mask
|
| 1271 |
+
)
|
| 1272 |
+
else:
|
| 1273 |
+
encoder_attention_mask = None
|
| 1274 |
+
|
| 1275 |
+
# decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)
|
| 1276 |
+
decoder_outputs = self.decoder(
|
| 1277 |
+
input_ids=decoder_input_ids,
|
| 1278 |
+
attention_mask=decoder_attention_mask,
|
| 1279 |
+
encoder_hidden_states=encoder_outputs[0],
|
| 1280 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1281 |
+
head_mask=decoder_head_mask,
|
| 1282 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 1283 |
+
past_key_values=past_key_values,
|
| 1284 |
+
inputs_embeds=decoder_inputs_embeds,
|
| 1285 |
+
use_cache=use_cache,
|
| 1286 |
+
output_attentions=output_attentions,
|
| 1287 |
+
output_hidden_states=output_hidden_states,
|
| 1288 |
+
return_dict=return_dict,
|
| 1289 |
+
training=training,
|
| 1290 |
+
)
|
| 1291 |
+
|
| 1292 |
+
if not return_dict:
|
| 1293 |
+
return decoder_outputs + encoder_outputs
|
| 1294 |
+
|
| 1295 |
+
return TFSeq2SeqModelOutput(
|
| 1296 |
+
last_hidden_state=decoder_outputs.last_hidden_state,
|
| 1297 |
+
past_key_values=decoder_outputs.past_key_values,
|
| 1298 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 1299 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 1300 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 1301 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
| 1302 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 1303 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 1304 |
+
)
|
| 1305 |
+
|
| 1306 |
+
def build(self, input_shape=None):
|
| 1307 |
+
if self.built:
|
| 1308 |
+
return
|
| 1309 |
+
self.built = True
|
| 1310 |
+
if getattr(self, "encoder", None) is not None:
|
| 1311 |
+
with tf.name_scope(self.encoder.name):
|
| 1312 |
+
self.encoder.build(None)
|
| 1313 |
+
if getattr(self, "decoder", None) is not None:
|
| 1314 |
+
with tf.name_scope(self.decoder.name):
|
| 1315 |
+
self.decoder.build(None)
|
| 1316 |
+
|
| 1317 |
+
|
| 1318 |
+
@add_start_docstrings(
|
| 1319 |
+
"The bare Speech2Text Model outputting raw hidden-states without any specific head on top.",
|
| 1320 |
+
SPEECH_TO_TEXT_START_DOCSTRING,
|
| 1321 |
+
)
|
| 1322 |
+
class TFSpeech2TextModel(TFSpeech2TextPreTrainedModel):
|
| 1323 |
+
def __init__(self, config: Speech2TextConfig, *inputs, **kwargs):
|
| 1324 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1325 |
+
|
| 1326 |
+
self.model = TFSpeech2TextMainLayer(config, name="model")
|
| 1327 |
+
|
| 1328 |
+
def get_encoder(self):
|
| 1329 |
+
return self.model.encoder
|
| 1330 |
+
|
| 1331 |
+
def get_decoder(self):
|
| 1332 |
+
return self.model.decoder
|
| 1333 |
+
|
| 1334 |
+
@unpack_inputs
|
| 1335 |
+
@add_start_docstrings_to_model_forward(SPEECH_TO_TEXT_INPUTS_DOCSTRING)
|
| 1336 |
+
@add_code_sample_docstrings(
|
| 1337 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1338 |
+
output_type=TFSeq2SeqModelOutput,
|
| 1339 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1340 |
+
)
|
| 1341 |
+
def call(
|
| 1342 |
+
self,
|
| 1343 |
+
input_features: TFModelInputType | None = None,
|
| 1344 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1345 |
+
decoder_input_ids: np.ndarray | tf.Tensor | None = None,
|
| 1346 |
+
decoder_attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1347 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1348 |
+
decoder_head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1349 |
+
cross_attn_head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1350 |
+
encoder_outputs: np.ndarray | tf.Tensor | None = None,
|
| 1351 |
+
past_key_values: tuple[tuple[np.ndarray | tf.Tensor]] | None = None,
|
| 1352 |
+
decoder_inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 1353 |
+
use_cache: bool | None = None,
|
| 1354 |
+
output_attentions: bool | None = None,
|
| 1355 |
+
output_hidden_states: bool | None = None,
|
| 1356 |
+
return_dict: bool | None = None,
|
| 1357 |
+
training: bool = False,
|
| 1358 |
+
**kwargs,
|
| 1359 |
+
) -> tuple | TFSeq2SeqModelOutput:
|
| 1360 |
+
outputs = self.model(
|
| 1361 |
+
input_features=input_features,
|
| 1362 |
+
attention_mask=attention_mask,
|
| 1363 |
+
decoder_input_ids=decoder_input_ids,
|
| 1364 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1365 |
+
head_mask=head_mask,
|
| 1366 |
+
decoder_head_mask=decoder_head_mask,
|
| 1367 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 1368 |
+
encoder_outputs=encoder_outputs,
|
| 1369 |
+
past_key_values=past_key_values,
|
| 1370 |
+
decoder_inputs_embeds=decoder_inputs_embeds,
|
| 1371 |
+
use_cache=use_cache,
|
| 1372 |
+
output_attentions=output_attentions,
|
| 1373 |
+
output_hidden_states=output_hidden_states,
|
| 1374 |
+
return_dict=return_dict,
|
| 1375 |
+
training=training,
|
| 1376 |
+
)
|
| 1377 |
+
|
| 1378 |
+
return outputs
|
| 1379 |
+
|
| 1380 |
+
def serving_output(self, output):
|
| 1381 |
+
pkv = tf.tuple(output.past_key_values)[1] if self.config.use_cache else None
|
| 1382 |
+
dec_hs = tf.convert_to_tensor(output.decoder_hidden_states) if self.config.output_hidden_states else None
|
| 1383 |
+
dec_attns = tf.convert_to_tensor(output.decoder_attentions) if self.config.output_attentions else None
|
| 1384 |
+
cross_attns = tf.convert_to_tensor(output.cross_attentions) if self.config.output_attentions else None
|
| 1385 |
+
enc_hs = tf.convert_to_tensor(output.encoder_hidden_states) if self.config.output_hidden_states else None
|
| 1386 |
+
enc_attns = tf.convert_to_tensor(output.encoder_attentions) if self.config.output_attentions else None
|
| 1387 |
+
|
| 1388 |
+
return TFSeq2SeqModelOutput(
|
| 1389 |
+
last_hidden_state=output.last_hidden_state,
|
| 1390 |
+
past_key_values=pkv,
|
| 1391 |
+
decoder_hidden_states=dec_hs,
|
| 1392 |
+
decoder_attentions=dec_attns,
|
| 1393 |
+
cross_attentions=cross_attns,
|
| 1394 |
+
encoder_last_hidden_state=output.encoder_last_hidden_state,
|
| 1395 |
+
encoder_hidden_states=enc_hs,
|
| 1396 |
+
encoder_attentions=enc_attns,
|
| 1397 |
+
)
|
| 1398 |
+
|
| 1399 |
+
def build(self, input_shape=None):
|
| 1400 |
+
if self.built:
|
| 1401 |
+
return
|
| 1402 |
+
self.built = True
|
| 1403 |
+
if getattr(self, "model", None) is not None:
|
| 1404 |
+
with tf.name_scope(self.model.name):
|
| 1405 |
+
self.model.build(None)
|
| 1406 |
+
|
| 1407 |
+
|
| 1408 |
+
@add_start_docstrings(
|
| 1409 |
+
"The Speech2Text Model with a language modeling head. Can be used for summarization.",
|
| 1410 |
+
SPEECH_TO_TEXT_START_DOCSTRING,
|
| 1411 |
+
)
|
| 1412 |
+
class TFSpeech2TextForConditionalGeneration(TFSpeech2TextPreTrainedModel, TFCausalLanguageModelingLoss):
|
| 1413 |
+
def __init__(self, config: Speech2TextConfig):
|
| 1414 |
+
super().__init__(config)
|
| 1415 |
+
self.model = TFSpeech2TextMainLayer(config, name="model")
|
| 1416 |
+
self.lm_head = keras.layers.Dense(self.config.vocab_size, use_bias=False, name="lm_head")
|
| 1417 |
+
# TODO (Joao): investigate why Speech2Text has numerical issues in XLA generate
|
| 1418 |
+
self.supports_xla_generation = False
|
| 1419 |
+
self.config = config
|
| 1420 |
+
|
| 1421 |
+
def get_encoder(self):
|
| 1422 |
+
return self.model.encoder
|
| 1423 |
+
|
| 1424 |
+
def get_decoder(self):
|
| 1425 |
+
return self.model.decoder
|
| 1426 |
+
|
| 1427 |
+
def resize_token_embeddings(self, new_num_tokens: int) -> tf.Variable:
|
| 1428 |
+
new_embeddings = super().resize_token_embeddings(new_num_tokens)
|
| 1429 |
+
return new_embeddings
|
| 1430 |
+
|
| 1431 |
+
@unpack_inputs
|
| 1432 |
+
@add_start_docstrings_to_model_forward(SPEECH_TO_TEXT_INPUTS_DOCSTRING)
|
| 1433 |
+
@replace_return_docstrings(output_type=TFSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
|
| 1434 |
+
def call(
|
| 1435 |
+
self,
|
| 1436 |
+
input_features: TFModelInputType | None = None,
|
| 1437 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1438 |
+
decoder_input_ids: np.ndarray | tf.Tensor | None = None,
|
| 1439 |
+
decoder_attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1440 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1441 |
+
decoder_head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1442 |
+
cross_attn_head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1443 |
+
encoder_outputs: np.ndarray | tf.Tensor | None = None,
|
| 1444 |
+
past_key_values: tuple[tuple[np.ndarray | tf.Tensor]] | None = None,
|
| 1445 |
+
decoder_inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 1446 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 1447 |
+
use_cache: bool | None = None,
|
| 1448 |
+
output_attentions: bool | None = None,
|
| 1449 |
+
output_hidden_states: bool | None = None,
|
| 1450 |
+
return_dict: bool | None = None,
|
| 1451 |
+
training: bool | None = False,
|
| 1452 |
+
**kwargs,
|
| 1453 |
+
) -> tuple | TFSeq2SeqLMOutput:
|
| 1454 |
+
r"""
|
| 1455 |
+
labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1456 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 1457 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 1458 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 1459 |
+
|
| 1460 |
+
Returns:
|
| 1461 |
+
|
| 1462 |
+
Example:
|
| 1463 |
+
|
| 1464 |
+
```python
|
| 1465 |
+
>>> import tensorflow as tf
|
| 1466 |
+
>>> from transformers import Speech2TextProcessor, TFSpeech2TextForConditionalGeneration
|
| 1467 |
+
>>> from datasets import load_dataset
|
| 1468 |
+
|
| 1469 |
+
>>> model = TFSpeech2TextForConditionalGeneration.from_pretrained(
|
| 1470 |
+
... "facebook/s2t-small-librispeech-asr", from_pt=True
|
| 1471 |
+
... )
|
| 1472 |
+
>>> processor = Speech2TextProcessor.from_pretrained("facebook/s2t-small-librispeech-asr")
|
| 1473 |
+
|
| 1474 |
+
|
| 1475 |
+
>>> def map_to_array(example):
|
| 1476 |
+
... example["speech"] = example["audio"]["array"]
|
| 1477 |
+
... return example
|
| 1478 |
+
|
| 1479 |
+
|
| 1480 |
+
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
| 1481 |
+
>>> ds = ds.map(map_to_array)
|
| 1482 |
+
>>> ds.set_format(type="tf")
|
| 1483 |
+
|
| 1484 |
+
>>> input_features = processor(
|
| 1485 |
+
... ds["speech"][0], sampling_rate=16000, return_tensors="tf"
|
| 1486 |
+
... ).input_features # Batch size 1
|
| 1487 |
+
>>> generated_ids = model.generate(input_features)
|
| 1488 |
+
|
| 1489 |
+
>>> transcription = processor.batch_decode(generated_ids)
|
| 1490 |
+
```"""
|
| 1491 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1492 |
+
|
| 1493 |
+
if labels is not None:
|
| 1494 |
+
if decoder_input_ids is None and decoder_inputs_embeds is None:
|
| 1495 |
+
decoder_input_ids = shift_tokens_right(
|
| 1496 |
+
labels, self.config.pad_token_id, self.config.decoder_start_token_id
|
| 1497 |
+
)
|
| 1498 |
+
|
| 1499 |
+
outputs = self.model(
|
| 1500 |
+
input_features=input_features,
|
| 1501 |
+
attention_mask=attention_mask,
|
| 1502 |
+
decoder_input_ids=decoder_input_ids,
|
| 1503 |
+
encoder_outputs=encoder_outputs,
|
| 1504 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1505 |
+
head_mask=head_mask,
|
| 1506 |
+
decoder_head_mask=decoder_head_mask,
|
| 1507 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 1508 |
+
past_key_values=past_key_values,
|
| 1509 |
+
decoder_inputs_embeds=decoder_inputs_embeds,
|
| 1510 |
+
use_cache=use_cache,
|
| 1511 |
+
output_attentions=output_attentions,
|
| 1512 |
+
output_hidden_states=output_hidden_states,
|
| 1513 |
+
return_dict=return_dict,
|
| 1514 |
+
training=training,
|
| 1515 |
+
)
|
| 1516 |
+
lm_logits = self.lm_head(outputs[0])
|
| 1517 |
+
masked_lm_loss = None if labels is None else self.hf_compute_loss(labels, lm_logits)
|
| 1518 |
+
|
| 1519 |
+
if not return_dict:
|
| 1520 |
+
output = (lm_logits,) + outputs[1:]
|
| 1521 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
| 1522 |
+
|
| 1523 |
+
return TFSeq2SeqLMOutput(
|
| 1524 |
+
loss=masked_lm_loss,
|
| 1525 |
+
logits=lm_logits,
|
| 1526 |
+
past_key_values=outputs.past_key_values,
|
| 1527 |
+
decoder_hidden_states=outputs.decoder_hidden_states,
|
| 1528 |
+
decoder_attentions=outputs.decoder_attentions,
|
| 1529 |
+
cross_attentions=outputs.cross_attentions,
|
| 1530 |
+
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
|
| 1531 |
+
encoder_hidden_states=outputs.encoder_hidden_states,
|
| 1532 |
+
encoder_attentions=outputs.encoder_attentions,
|
| 1533 |
+
)
|
| 1534 |
+
|
| 1535 |
+
def serving_output(self, output):
|
| 1536 |
+
pkv = tf.tuple(output.past_key_values)[1] if self.config.use_cache else None
|
| 1537 |
+
dec_hs = tf.convert_to_tensor(output.decoder_hidden_states) if self.config.output_hidden_states else None
|
| 1538 |
+
dec_attns = tf.convert_to_tensor(output.decoder_attentions) if self.config.output_attentions else None
|
| 1539 |
+
cross_attns = tf.convert_to_tensor(output.cross_attentions) if self.config.output_attentions else None
|
| 1540 |
+
enc_hs = tf.convert_to_tensor(output.encoder_hidden_states) if self.config.output_hidden_states else None
|
| 1541 |
+
enc_attns = tf.convert_to_tensor(output.encoder_attentions) if self.config.output_attentions else None
|
| 1542 |
+
|
| 1543 |
+
return TFSeq2SeqLMOutput(
|
| 1544 |
+
logits=output.logits,
|
| 1545 |
+
past_key_values=pkv,
|
| 1546 |
+
decoder_hidden_states=dec_hs,
|
| 1547 |
+
decoder_attentions=dec_attns,
|
| 1548 |
+
cross_attentions=cross_attns,
|
| 1549 |
+
encoder_last_hidden_state=output.encoder_last_hidden_state,
|
| 1550 |
+
encoder_hidden_states=enc_hs,
|
| 1551 |
+
encoder_attentions=enc_attns,
|
| 1552 |
+
)
|
| 1553 |
+
|
| 1554 |
+
def prepare_inputs_for_generation(
|
| 1555 |
+
self,
|
| 1556 |
+
decoder_input_ids,
|
| 1557 |
+
past_key_values=None,
|
| 1558 |
+
attention_mask=None,
|
| 1559 |
+
head_mask=None,
|
| 1560 |
+
decoder_head_mask=None,
|
| 1561 |
+
cross_attn_head_mask=None,
|
| 1562 |
+
use_cache=None,
|
| 1563 |
+
encoder_outputs=None,
|
| 1564 |
+
**kwargs,
|
| 1565 |
+
):
|
| 1566 |
+
# cut decoder_input_ids if past is used
|
| 1567 |
+
if past_key_values is not None:
|
| 1568 |
+
decoder_input_ids = decoder_input_ids[:, -1:]
|
| 1569 |
+
|
| 1570 |
+
return {
|
| 1571 |
+
"input_features": None, # needs to be passed to make Keras.layer.__call__ happy
|
| 1572 |
+
"encoder_outputs": encoder_outputs,
|
| 1573 |
+
"past_key_values": past_key_values,
|
| 1574 |
+
"decoder_input_ids": decoder_input_ids,
|
| 1575 |
+
"attention_mask": attention_mask,
|
| 1576 |
+
"head_mask": head_mask,
|
| 1577 |
+
"decoder_head_mask": decoder_head_mask,
|
| 1578 |
+
"cross_attn_head_mask": cross_attn_head_mask,
|
| 1579 |
+
"use_cache": use_cache, # change this to avoid caching (presumably for debugging)
|
| 1580 |
+
}
|
| 1581 |
+
|
| 1582 |
+
def build(self, input_shape=None):
|
| 1583 |
+
if self.built:
|
| 1584 |
+
return
|
| 1585 |
+
self.built = True
|
| 1586 |
+
if getattr(self, "model", None) is not None:
|
| 1587 |
+
with tf.name_scope(self.model.name):
|
| 1588 |
+
self.model.build(None)
|
| 1589 |
+
if getattr(self, "lm_head", None) is not None:
|
| 1590 |
+
with tf.name_scope(self.lm_head.name):
|
| 1591 |
+
self.lm_head.build([None, None, self.config.d_model])
|
| 1592 |
+
|
| 1593 |
+
def tf_to_pt_weight_rename(self, tf_weight):
|
| 1594 |
+
if tf_weight == "lm_head.weight":
|
| 1595 |
+
return tf_weight, "model.decoder.embed_tokens.weight"
|
| 1596 |
+
else:
|
| 1597 |
+
return (tf_weight,)
|
| 1598 |
+
|
| 1599 |
+
|
| 1600 |
+
__all__ = ["TFSpeech2TextForConditionalGeneration", "TFSpeech2TextModel", "TFSpeech2TextPreTrainedModel"]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speech_to_text/processing_speech_to_text.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Speech processor class for Speech2Text
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import warnings
|
| 20 |
+
from contextlib import contextmanager
|
| 21 |
+
|
| 22 |
+
from ...processing_utils import ProcessorMixin
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class Speech2TextProcessor(ProcessorMixin):
|
| 26 |
+
r"""
|
| 27 |
+
Constructs a Speech2Text processor which wraps a Speech2Text feature extractor and a Speech2Text tokenizer into a
|
| 28 |
+
single processor.
|
| 29 |
+
|
| 30 |
+
[`Speech2TextProcessor`] offers all the functionalities of [`Speech2TextFeatureExtractor`] and
|
| 31 |
+
[`Speech2TextTokenizer`]. See the [`~Speech2TextProcessor.__call__`] and [`~Speech2TextProcessor.decode`] for more
|
| 32 |
+
information.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
feature_extractor (`Speech2TextFeatureExtractor`):
|
| 36 |
+
An instance of [`Speech2TextFeatureExtractor`]. The feature extractor is a required input.
|
| 37 |
+
tokenizer (`Speech2TextTokenizer`):
|
| 38 |
+
An instance of [`Speech2TextTokenizer`]. The tokenizer is a required input.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
feature_extractor_class = "Speech2TextFeatureExtractor"
|
| 42 |
+
tokenizer_class = "Speech2TextTokenizer"
|
| 43 |
+
|
| 44 |
+
def __init__(self, feature_extractor, tokenizer):
|
| 45 |
+
super().__init__(feature_extractor, tokenizer)
|
| 46 |
+
self.current_processor = self.feature_extractor
|
| 47 |
+
self._in_target_context_manager = False
|
| 48 |
+
|
| 49 |
+
def __call__(self, *args, **kwargs):
|
| 50 |
+
"""
|
| 51 |
+
When used in normal mode, this method forwards all its arguments to Speech2TextFeatureExtractor's
|
| 52 |
+
[`~Speech2TextFeatureExtractor.__call__`] and returns its output. If used in the context
|
| 53 |
+
[`~Speech2TextProcessor.as_target_processor`] this method forwards all its arguments to Speech2TextTokenizer's
|
| 54 |
+
[`~Speech2TextTokenizer.__call__`]. Please refer to the docstring of the above two methods for more
|
| 55 |
+
information.
|
| 56 |
+
"""
|
| 57 |
+
# For backward compatibility
|
| 58 |
+
if self._in_target_context_manager:
|
| 59 |
+
return self.current_processor(*args, **kwargs)
|
| 60 |
+
|
| 61 |
+
if "raw_speech" in kwargs:
|
| 62 |
+
warnings.warn("Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.")
|
| 63 |
+
audio = kwargs.pop("raw_speech")
|
| 64 |
+
else:
|
| 65 |
+
audio = kwargs.pop("audio", None)
|
| 66 |
+
sampling_rate = kwargs.pop("sampling_rate", None)
|
| 67 |
+
text = kwargs.pop("text", None)
|
| 68 |
+
if len(args) > 0:
|
| 69 |
+
audio = args[0]
|
| 70 |
+
args = args[1:]
|
| 71 |
+
|
| 72 |
+
if audio is None and text is None:
|
| 73 |
+
raise ValueError("You need to specify either an `audio` or `text` input to process.")
|
| 74 |
+
|
| 75 |
+
if audio is not None:
|
| 76 |
+
inputs = self.feature_extractor(audio, *args, sampling_rate=sampling_rate, **kwargs)
|
| 77 |
+
if text is not None:
|
| 78 |
+
encodings = self.tokenizer(text, **kwargs)
|
| 79 |
+
|
| 80 |
+
if text is None:
|
| 81 |
+
return inputs
|
| 82 |
+
elif audio is None:
|
| 83 |
+
return encodings
|
| 84 |
+
else:
|
| 85 |
+
inputs["labels"] = encodings["input_ids"]
|
| 86 |
+
return inputs
|
| 87 |
+
|
| 88 |
+
@contextmanager
|
| 89 |
+
def as_target_processor(self):
|
| 90 |
+
"""
|
| 91 |
+
Temporarily sets the tokenizer for processing the input. Useful for encoding the labels when fine-tuning
|
| 92 |
+
Speech2Text.
|
| 93 |
+
"""
|
| 94 |
+
warnings.warn(
|
| 95 |
+
"`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your "
|
| 96 |
+
"labels by using the argument `text` of the regular `__call__` method (either in the same call as "
|
| 97 |
+
"your audio inputs, or in a separate call."
|
| 98 |
+
)
|
| 99 |
+
self._in_target_context_manager = True
|
| 100 |
+
self.current_processor = self.tokenizer
|
| 101 |
+
yield
|
| 102 |
+
self.current_processor = self.feature_extractor
|
| 103 |
+
self._in_target_context_manager = False
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
__all__ = ["Speech2TextProcessor"]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speech_to_text/tokenization_speech_to_text.py
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Tokenization classes for Speech2Text."""
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from shutil import copyfile
|
| 21 |
+
from typing import Any, Optional, Union
|
| 22 |
+
|
| 23 |
+
import sentencepiece
|
| 24 |
+
|
| 25 |
+
from ...tokenization_utils import PreTrainedTokenizer
|
| 26 |
+
from ...utils import logging
|
| 27 |
+
from ...utils.import_utils import requires
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
logger = logging.get_logger(__name__)
|
| 31 |
+
|
| 32 |
+
SPIECE_UNDERLINE = "▁"
|
| 33 |
+
|
| 34 |
+
VOCAB_FILES_NAMES = {
|
| 35 |
+
"vocab_file": "vocab.json",
|
| 36 |
+
"spm_file": "sentencepiece.bpe.model",
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
MAX_MODEL_INPUT_SIZES = {
|
| 41 |
+
"facebook/s2t-small-librispeech-asr": 1024,
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
MUSTC_LANGS = ["pt", "fr", "ru", "nl", "ro", "it", "es", "de"]
|
| 45 |
+
|
| 46 |
+
LANGUAGES = {"mustc": MUSTC_LANGS}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@requires(backends=("sentencepiece",))
|
| 50 |
+
class Speech2TextTokenizer(PreTrainedTokenizer):
|
| 51 |
+
"""
|
| 52 |
+
Construct an Speech2Text tokenizer.
|
| 53 |
+
|
| 54 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains some of the main methods. Users should refer to
|
| 55 |
+
the superclass for more information regarding such methods.
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
vocab_file (`str`):
|
| 59 |
+
File containing the vocabulary.
|
| 60 |
+
spm_file (`str`):
|
| 61 |
+
Path to the [SentencePiece](https://github.com/google/sentencepiece) model file
|
| 62 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 63 |
+
The beginning of sentence token.
|
| 64 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 65 |
+
The end of sentence token.
|
| 66 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 67 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 68 |
+
token instead.
|
| 69 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 70 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 71 |
+
do_upper_case (`bool`, *optional*, defaults to `False`):
|
| 72 |
+
Whether or not to uppercase the output when decoding.
|
| 73 |
+
do_lower_case (`bool`, *optional*, defaults to `False`):
|
| 74 |
+
Whether or not to lowercase the input when tokenizing.
|
| 75 |
+
tgt_lang (`str`, *optional*):
|
| 76 |
+
A string representing the target language.
|
| 77 |
+
sp_model_kwargs (`dict`, *optional*):
|
| 78 |
+
Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
|
| 79 |
+
SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
|
| 80 |
+
to set:
|
| 81 |
+
|
| 82 |
+
- `enable_sampling`: Enable subword regularization.
|
| 83 |
+
- `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
|
| 84 |
+
|
| 85 |
+
- `nbest_size = {0,1}`: No sampling is performed.
|
| 86 |
+
- `nbest_size > 1`: samples from the nbest_size results.
|
| 87 |
+
- `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
|
| 88 |
+
using forward-filtering-and-backward-sampling algorithm.
|
| 89 |
+
|
| 90 |
+
- `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
|
| 91 |
+
BPE-dropout.
|
| 92 |
+
|
| 93 |
+
**kwargs
|
| 94 |
+
Additional keyword arguments passed along to [`PreTrainedTokenizer`]
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 98 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 99 |
+
|
| 100 |
+
prefix_tokens: list[int] = []
|
| 101 |
+
|
| 102 |
+
def __init__(
|
| 103 |
+
self,
|
| 104 |
+
vocab_file,
|
| 105 |
+
spm_file,
|
| 106 |
+
bos_token="<s>",
|
| 107 |
+
eos_token="</s>",
|
| 108 |
+
pad_token="<pad>",
|
| 109 |
+
unk_token="<unk>",
|
| 110 |
+
do_upper_case=False,
|
| 111 |
+
do_lower_case=False,
|
| 112 |
+
tgt_lang=None,
|
| 113 |
+
lang_codes=None,
|
| 114 |
+
additional_special_tokens=None,
|
| 115 |
+
sp_model_kwargs: Optional[dict[str, Any]] = None,
|
| 116 |
+
**kwargs,
|
| 117 |
+
) -> None:
|
| 118 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
| 119 |
+
|
| 120 |
+
self.do_upper_case = do_upper_case
|
| 121 |
+
self.do_lower_case = do_lower_case
|
| 122 |
+
|
| 123 |
+
self.encoder = load_json(vocab_file)
|
| 124 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
| 125 |
+
self.spm_file = spm_file
|
| 126 |
+
self.sp_model = load_spm(spm_file, self.sp_model_kwargs)
|
| 127 |
+
|
| 128 |
+
if lang_codes is not None:
|
| 129 |
+
self.lang_codes = lang_codes
|
| 130 |
+
self.langs = LANGUAGES[lang_codes]
|
| 131 |
+
self.lang_tokens = [f"<lang:{lang}>" for lang in self.langs]
|
| 132 |
+
self.lang_code_to_id = {lang: self.sp_model.PieceToId(f"<lang:{lang}>") for lang in self.langs}
|
| 133 |
+
if additional_special_tokens is not None:
|
| 134 |
+
additional_special_tokens = self.lang_tokens + additional_special_tokens
|
| 135 |
+
else:
|
| 136 |
+
additional_special_tokens = self.lang_tokens
|
| 137 |
+
self._tgt_lang = tgt_lang if tgt_lang is not None else self.langs[0]
|
| 138 |
+
|
| 139 |
+
self.set_tgt_lang_special_tokens(self._tgt_lang)
|
| 140 |
+
else:
|
| 141 |
+
self.lang_code_to_id = {}
|
| 142 |
+
|
| 143 |
+
super().__init__(
|
| 144 |
+
bos_token=bos_token,
|
| 145 |
+
eos_token=eos_token,
|
| 146 |
+
unk_token=unk_token,
|
| 147 |
+
pad_token=pad_token,
|
| 148 |
+
do_upper_case=do_upper_case,
|
| 149 |
+
do_lower_case=do_lower_case,
|
| 150 |
+
tgt_lang=tgt_lang,
|
| 151 |
+
lang_codes=lang_codes,
|
| 152 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
| 153 |
+
additional_special_tokens=additional_special_tokens,
|
| 154 |
+
**kwargs,
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
@property
|
| 158 |
+
def vocab_size(self) -> int:
|
| 159 |
+
return len(self.encoder)
|
| 160 |
+
|
| 161 |
+
def get_vocab(self) -> dict:
|
| 162 |
+
vocab = self.encoder.copy()
|
| 163 |
+
vocab.update(self.added_tokens_encoder)
|
| 164 |
+
return vocab
|
| 165 |
+
|
| 166 |
+
@property
|
| 167 |
+
def tgt_lang(self) -> str:
|
| 168 |
+
return self._tgt_lang
|
| 169 |
+
|
| 170 |
+
@tgt_lang.setter
|
| 171 |
+
def tgt_lang(self, new_tgt_lang) -> None:
|
| 172 |
+
self._tgt_lang = new_tgt_lang
|
| 173 |
+
self.set_tgt_lang_special_tokens(new_tgt_lang)
|
| 174 |
+
|
| 175 |
+
def set_tgt_lang_special_tokens(self, tgt_lang: str) -> None:
|
| 176 |
+
"""Reset the special tokens to the target language setting. prefix=[eos, tgt_lang_code] and suffix=[eos]."""
|
| 177 |
+
lang_code_id = self.lang_code_to_id[tgt_lang]
|
| 178 |
+
self.prefix_tokens = [lang_code_id]
|
| 179 |
+
|
| 180 |
+
def _tokenize(self, text: str) -> list[str]:
|
| 181 |
+
return self.sp_model.encode(text, out_type=str)
|
| 182 |
+
|
| 183 |
+
def _convert_token_to_id(self, token):
|
| 184 |
+
return self.encoder.get(token, self.encoder[self.unk_token])
|
| 185 |
+
|
| 186 |
+
def _convert_id_to_token(self, index: int) -> str:
|
| 187 |
+
"""Converts an index (integer) in a token (str) using the decoder."""
|
| 188 |
+
return self.decoder.get(index, self.unk_token)
|
| 189 |
+
|
| 190 |
+
def convert_tokens_to_string(self, tokens: list[str]) -> str:
|
| 191 |
+
"""Converts a sequence of tokens (strings for sub-words) in a single string."""
|
| 192 |
+
current_sub_tokens = []
|
| 193 |
+
out_string = ""
|
| 194 |
+
for token in tokens:
|
| 195 |
+
# make sure that special tokens are not decoded using sentencepiece model
|
| 196 |
+
if token in self.all_special_tokens:
|
| 197 |
+
decoded = self.sp_model.decode(current_sub_tokens)
|
| 198 |
+
out_string += (decoded.upper() if self.do_upper_case else decoded) + token + " "
|
| 199 |
+
current_sub_tokens = []
|
| 200 |
+
else:
|
| 201 |
+
current_sub_tokens.append(token)
|
| 202 |
+
decoded = self.sp_model.decode(current_sub_tokens)
|
| 203 |
+
out_string += decoded.upper() if self.do_upper_case else decoded
|
| 204 |
+
return out_string.strip()
|
| 205 |
+
|
| 206 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None) -> list[int]:
|
| 207 |
+
"""Build model inputs from a sequence by appending eos_token_id."""
|
| 208 |
+
if token_ids_1 is None:
|
| 209 |
+
return self.prefix_tokens + token_ids_0 + [self.eos_token_id]
|
| 210 |
+
# We don't expect to process pairs, but leave the pair logic for API consistency
|
| 211 |
+
return self.prefix_tokens + token_ids_0 + token_ids_1 + [self.eos_token_id]
|
| 212 |
+
|
| 213 |
+
def get_special_tokens_mask(
|
| 214 |
+
self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
|
| 215 |
+
) -> list[int]:
|
| 216 |
+
"""
|
| 217 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 218 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
| 219 |
+
|
| 220 |
+
Args:
|
| 221 |
+
token_ids_0 (`list[int]`):
|
| 222 |
+
List of IDs.
|
| 223 |
+
token_ids_1 (`list[int]`, *optional*):
|
| 224 |
+
Optional second list of IDs for sequence pairs.
|
| 225 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 226 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 227 |
+
|
| 228 |
+
Returns:
|
| 229 |
+
`list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 230 |
+
"""
|
| 231 |
+
|
| 232 |
+
if already_has_special_tokens:
|
| 233 |
+
return super().get_special_tokens_mask(
|
| 234 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
prefix_ones = [1] * len(self.prefix_tokens)
|
| 238 |
+
suffix_ones = [1]
|
| 239 |
+
if token_ids_1 is None:
|
| 240 |
+
return prefix_ones + ([0] * len(token_ids_0)) + suffix_ones
|
| 241 |
+
return prefix_ones + ([0] * len(token_ids_0)) + ([0] * len(token_ids_1)) + suffix_ones
|
| 242 |
+
|
| 243 |
+
def __getstate__(self) -> dict:
|
| 244 |
+
state = self.__dict__.copy()
|
| 245 |
+
state["sp_model"] = None
|
| 246 |
+
return state
|
| 247 |
+
|
| 248 |
+
def __setstate__(self, d: dict) -> None:
|
| 249 |
+
self.__dict__ = d
|
| 250 |
+
|
| 251 |
+
# for backward compatibility
|
| 252 |
+
if not hasattr(self, "sp_model_kwargs"):
|
| 253 |
+
self.sp_model_kwargs = {}
|
| 254 |
+
|
| 255 |
+
self.sp_model = load_spm(self.spm_file, self.sp_model_kwargs)
|
| 256 |
+
|
| 257 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
|
| 258 |
+
save_dir = Path(save_directory)
|
| 259 |
+
assert save_dir.is_dir(), f"{save_directory} should be a directory"
|
| 260 |
+
vocab_save_path = save_dir / (
|
| 261 |
+
(filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"]
|
| 262 |
+
)
|
| 263 |
+
spm_save_path = save_dir / (
|
| 264 |
+
(filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["spm_file"]
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
save_json(self.encoder, vocab_save_path)
|
| 268 |
+
|
| 269 |
+
if os.path.abspath(self.spm_file) != os.path.abspath(spm_save_path) and os.path.isfile(self.spm_file):
|
| 270 |
+
copyfile(self.spm_file, spm_save_path)
|
| 271 |
+
elif not os.path.isfile(self.spm_file):
|
| 272 |
+
with open(spm_save_path, "wb") as fi:
|
| 273 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
| 274 |
+
fi.write(content_spiece_model)
|
| 275 |
+
|
| 276 |
+
return (str(vocab_save_path), str(spm_save_path))
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def load_spm(path: str, sp_model_kwargs: dict[str, Any]) -> sentencepiece.SentencePieceProcessor:
|
| 280 |
+
spm = sentencepiece.SentencePieceProcessor(**sp_model_kwargs)
|
| 281 |
+
spm.Load(str(path))
|
| 282 |
+
return spm
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def load_json(path: str) -> Union[dict, list]:
|
| 286 |
+
with open(path, "r") as f:
|
| 287 |
+
return json.load(f)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def save_json(data, path: str) -> None:
|
| 291 |
+
with open(path, "w") as f:
|
| 292 |
+
json.dump(data, f, indent=2)
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
__all__ = ["Speech2TextTokenizer"]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speecht5/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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_speecht5 import *
|
| 22 |
+
from .feature_extraction_speecht5 import *
|
| 23 |
+
from .modeling_speecht5 import *
|
| 24 |
+
from .processing_speecht5 import *
|
| 25 |
+
from .tokenization_speecht5 import *
|
| 26 |
+
else:
|
| 27 |
+
import sys
|
| 28 |
+
|
| 29 |
+
_file = globals()["__file__"]
|
| 30 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speecht5/configuration_speecht5.py
ADDED
|
@@ -0,0 +1,422 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The Fairseq Authors, Microsoft Research, and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""SpeechT5 model configuration"""
|
| 16 |
+
|
| 17 |
+
import functools
|
| 18 |
+
import operator
|
| 19 |
+
|
| 20 |
+
from ...configuration_utils import PretrainedConfig
|
| 21 |
+
from ...utils import logging
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
logger = logging.get_logger(__name__)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class SpeechT5Config(PretrainedConfig):
|
| 28 |
+
r"""
|
| 29 |
+
This is the configuration class to store the configuration of a [`SpeechT5Model`]. It is used to instantiate a
|
| 30 |
+
SpeechT5 model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 31 |
+
with the defaults will yield a similar configuration to that of the SpeechT5
|
| 32 |
+
[microsoft/speecht5_asr](https://huggingface.co/microsoft/speecht5_asr) architecture.
|
| 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 |
+
vocab_size (`int`, *optional*, defaults to 81):
|
| 39 |
+
Vocabulary size of the SpeechT5 model. Defines the number of different tokens that can be represented by
|
| 40 |
+
the `inputs_ids` passed to the forward method of [`SpeechT5Model`].
|
| 41 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 42 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 43 |
+
encoder_layers (`int`, *optional*, defaults to 12):
|
| 44 |
+
Number of hidden layers in the Transformer encoder.
|
| 45 |
+
encoder_attention_heads (`int`, *optional*, defaults to 12):
|
| 46 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 47 |
+
encoder_ffn_dim (`int`, *optional*, defaults to 3072):
|
| 48 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 49 |
+
encoder_layerdrop (`float`, *optional*, defaults to 0.1):
|
| 50 |
+
The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556)
|
| 51 |
+
for more details.
|
| 52 |
+
decoder_layers (`int`, *optional*, defaults to 6):
|
| 53 |
+
Number of hidden layers in the Transformer decoder.
|
| 54 |
+
decoder_attention_heads (`int`, *optional*, defaults to 12):
|
| 55 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
| 56 |
+
decoder_ffn_dim (`int`, *optional*, defaults to 3072):
|
| 57 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer decoder.
|
| 58 |
+
decoder_layerdrop (`float`, *optional*, defaults to 0.1):
|
| 59 |
+
The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556)
|
| 60 |
+
for more details.
|
| 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 |
+
positional_dropout (`float`, *optional*, defaults to 0.1):
|
| 65 |
+
The dropout probability for the text position encoding layers.
|
| 66 |
+
hidden_dropout (`float`, *optional*, defaults to 0.1):
|
| 67 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 68 |
+
attention_dropout (`float`, *optional*, defaults to 0.1):
|
| 69 |
+
The dropout ratio for the attention probabilities.
|
| 70 |
+
activation_dropout (`float`, *optional*, defaults to 0.1):
|
| 71 |
+
The dropout ratio for activations inside the fully connected layer.
|
| 72 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 73 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 74 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-5):
|
| 75 |
+
The epsilon used by the layer normalization layers.
|
| 76 |
+
scale_embedding (`bool`, *optional*, defaults to `False`):
|
| 77 |
+
Scale embeddings by diving by sqrt(d_model).
|
| 78 |
+
feat_extract_norm (`str`, *optional*, defaults to `"group"`):
|
| 79 |
+
The norm to be applied to 1D convolutional layers in the speech encoder pre-net. One of `"group"` for group
|
| 80 |
+
normalization of only the first 1D convolutional layer or `"layer"` for layer normalization of all 1D
|
| 81 |
+
convolutional layers.
|
| 82 |
+
feat_proj_dropout (`float`, *optional*, defaults to 0.0):
|
| 83 |
+
The dropout probability for output of the speech encoder pre-net.
|
| 84 |
+
feat_extract_activation (`str, `optional`, defaults to `"gelu"`):
|
| 85 |
+
The non-linear activation function (function or string) in the 1D convolutional layers of the feature
|
| 86 |
+
extractor. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` are supported.
|
| 87 |
+
conv_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 512, 512, 512)`):
|
| 88 |
+
A tuple of integers defining the number of input and output channels of each 1D convolutional layer in the
|
| 89 |
+
speech encoder pre-net. The length of *conv_dim* defines the number of 1D convolutional layers.
|
| 90 |
+
conv_stride (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 2, 2, 2, 2, 2, 2)`):
|
| 91 |
+
A tuple of integers defining the stride of each 1D convolutional layer in the speech encoder pre-net. The
|
| 92 |
+
length of *conv_stride* defines the number of convolutional layers and has to match the length of
|
| 93 |
+
*conv_dim*.
|
| 94 |
+
conv_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(10, 3, 3, 3, 3, 3, 3)`):
|
| 95 |
+
A tuple of integers defining the kernel size of each 1D convolutional layer in the speech encoder pre-net.
|
| 96 |
+
The length of *conv_kernel* defines the number of convolutional layers and has to match the length of
|
| 97 |
+
*conv_dim*.
|
| 98 |
+
conv_bias (`bool`, *optional*, defaults to `False`):
|
| 99 |
+
Whether the 1D convolutional layers have a bias.
|
| 100 |
+
num_conv_pos_embeddings (`int`, *optional*, defaults to 128):
|
| 101 |
+
Number of convolutional positional embeddings. Defines the kernel size of 1D convolutional positional
|
| 102 |
+
embeddings layer.
|
| 103 |
+
num_conv_pos_embedding_groups (`int`, *optional*, defaults to 16):
|
| 104 |
+
Number of groups of 1D convolutional positional embeddings layer.
|
| 105 |
+
apply_spec_augment (`bool`, *optional*, defaults to `True`):
|
| 106 |
+
Whether to apply *SpecAugment* data augmentation to the outputs of the speech encoder pre-net. For
|
| 107 |
+
reference see [SpecAugment: A Simple Data Augmentation Method for Automatic Speech
|
| 108 |
+
Recognition](https://huggingface.co/papers/1904.08779).
|
| 109 |
+
mask_time_prob (`float`, *optional*, defaults to 0.05):
|
| 110 |
+
Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking
|
| 111 |
+
procedure generates ''mask_time_prob*len(time_axis)/mask_time_length'' independent masks over the axis. If
|
| 112 |
+
reasoning from the probability of each feature vector to be chosen as the start of the vector span to be
|
| 113 |
+
masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the
|
| 114 |
+
actual percentage of masked vectors. This is only relevant if `apply_spec_augment is True`.
|
| 115 |
+
mask_time_length (`int`, *optional*, defaults to 10):
|
| 116 |
+
Length of vector span along the time axis.
|
| 117 |
+
mask_time_min_masks (`int`, *optional*, defaults to 2),:
|
| 118 |
+
The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
|
| 119 |
+
irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <
|
| 120 |
+
mask_time_min_masks''
|
| 121 |
+
mask_feature_prob (`float`, *optional*, defaults to 0.0):
|
| 122 |
+
Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
|
| 123 |
+
masking procedure generates ''mask_feature_prob*len(feature_axis)/mask_time_length'' independent masks over
|
| 124 |
+
the axis. If reasoning from the probability of each feature vector to be chosen as the start of the vector
|
| 125 |
+
span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap
|
| 126 |
+
may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is
|
| 127 |
+
True`.
|
| 128 |
+
mask_feature_length (`int`, *optional*, defaults to 10):
|
| 129 |
+
Length of vector span along the feature axis.
|
| 130 |
+
mask_feature_min_masks (`int`, *optional*, defaults to 0),:
|
| 131 |
+
The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time
|
| 132 |
+
step, irrespectively of `mask_feature_prob`. Only relevant if
|
| 133 |
+
''mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks''
|
| 134 |
+
num_mel_bins (`int`, *optional*, defaults to 80):
|
| 135 |
+
Number of mel features used per input features. Used by the speech decoder pre-net. Should correspond to
|
| 136 |
+
the value used in the [`SpeechT5Processor`] class.
|
| 137 |
+
speech_decoder_prenet_layers (`int`, *optional*, defaults to 2):
|
| 138 |
+
Number of layers in the speech decoder pre-net.
|
| 139 |
+
speech_decoder_prenet_units (`int`, *optional*, defaults to 256):
|
| 140 |
+
Dimensionality of the layers in the speech decoder pre-net.
|
| 141 |
+
speech_decoder_prenet_dropout (`float`, *optional*, defaults to 0.5):
|
| 142 |
+
The dropout probability for the speech decoder pre-net layers.
|
| 143 |
+
speaker_embedding_dim (`int`, *optional*, defaults to 512):
|
| 144 |
+
Dimensionality of the *XVector* embedding vectors.
|
| 145 |
+
speech_decoder_postnet_layers (`int`, *optional*, defaults to 5):
|
| 146 |
+
Number of layers in the speech decoder post-net.
|
| 147 |
+
speech_decoder_postnet_units (`int`, *optional*, defaults to 256):
|
| 148 |
+
Dimensionality of the layers in the speech decoder post-net.
|
| 149 |
+
speech_decoder_postnet_kernel (`int`, *optional*, defaults to 5):
|
| 150 |
+
Number of convolutional filter channels in the speech decoder post-net.
|
| 151 |
+
speech_decoder_postnet_dropout (`float`, *optional*, defaults to 0.5):
|
| 152 |
+
The dropout probability for the speech decoder post-net layers.
|
| 153 |
+
reduction_factor (`int`, *optional*, defaults to 2):
|
| 154 |
+
Spectrogram length reduction factor for the speech decoder inputs.
|
| 155 |
+
max_speech_positions (`int`, *optional*, defaults to 4000):
|
| 156 |
+
The maximum sequence length of speech features that this model might ever be used with.
|
| 157 |
+
max_text_positions (`int`, *optional*, defaults to 450):
|
| 158 |
+
The maximum sequence length of text features that this model might ever be used with.
|
| 159 |
+
encoder_max_relative_position (`int`, *optional*, defaults to 160):
|
| 160 |
+
Maximum distance for relative position embedding in the encoder.
|
| 161 |
+
use_guided_attention_loss (`bool`, *optional*, defaults to `True`):
|
| 162 |
+
Whether to apply guided attention loss while training the TTS model.
|
| 163 |
+
guided_attention_loss_num_heads (`int`, *optional*, defaults to 2):
|
| 164 |
+
Number of attention heads the guided attention loss will be applied to. Use -1 to apply this loss to all
|
| 165 |
+
attention heads.
|
| 166 |
+
guided_attention_loss_sigma (`float`, *optional*, defaults to 0.4):
|
| 167 |
+
Standard deviation for guided attention loss.
|
| 168 |
+
guided_attention_loss_scale (`float`, *optional*, defaults to 10.0):
|
| 169 |
+
Scaling coefficient for guided attention loss (also known as lambda).
|
| 170 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 171 |
+
Whether or not the model should return the last key/values attentions (not used by all models).
|
| 172 |
+
|
| 173 |
+
Example:
|
| 174 |
+
|
| 175 |
+
```python
|
| 176 |
+
>>> from transformers import SpeechT5Model, SpeechT5Config
|
| 177 |
+
|
| 178 |
+
>>> # Initializing a "microsoft/speecht5_asr" style configuration
|
| 179 |
+
>>> configuration = SpeechT5Config()
|
| 180 |
+
|
| 181 |
+
>>> # Initializing a model (with random weights) from the "microsoft/speecht5_asr" style configuration
|
| 182 |
+
>>> model = SpeechT5Model(configuration)
|
| 183 |
+
|
| 184 |
+
>>> # Accessing the model configuration
|
| 185 |
+
>>> configuration = model.config
|
| 186 |
+
```"""
|
| 187 |
+
|
| 188 |
+
model_type = "speecht5"
|
| 189 |
+
attribute_map = {"num_attention_heads": "encoder_attention_heads", "num_hidden_layers": "encoder_layers"}
|
| 190 |
+
|
| 191 |
+
def __init__(
|
| 192 |
+
self,
|
| 193 |
+
vocab_size=81,
|
| 194 |
+
hidden_size=768,
|
| 195 |
+
encoder_layers=12,
|
| 196 |
+
encoder_attention_heads=12,
|
| 197 |
+
encoder_ffn_dim=3072,
|
| 198 |
+
encoder_layerdrop=0.1,
|
| 199 |
+
decoder_layers=6,
|
| 200 |
+
decoder_ffn_dim=3072,
|
| 201 |
+
decoder_attention_heads=12,
|
| 202 |
+
decoder_layerdrop=0.1,
|
| 203 |
+
hidden_act="gelu",
|
| 204 |
+
positional_dropout=0.1,
|
| 205 |
+
hidden_dropout=0.1,
|
| 206 |
+
attention_dropout=0.1,
|
| 207 |
+
activation_dropout=0.1,
|
| 208 |
+
initializer_range=0.02,
|
| 209 |
+
layer_norm_eps=1e-5,
|
| 210 |
+
scale_embedding=False,
|
| 211 |
+
feat_extract_norm="group",
|
| 212 |
+
feat_proj_dropout=0.0,
|
| 213 |
+
feat_extract_activation="gelu",
|
| 214 |
+
conv_dim=(512, 512, 512, 512, 512, 512, 512),
|
| 215 |
+
conv_stride=(5, 2, 2, 2, 2, 2, 2),
|
| 216 |
+
conv_kernel=(10, 3, 3, 3, 3, 2, 2),
|
| 217 |
+
conv_bias=False,
|
| 218 |
+
num_conv_pos_embeddings=128,
|
| 219 |
+
num_conv_pos_embedding_groups=16,
|
| 220 |
+
apply_spec_augment=True,
|
| 221 |
+
mask_time_prob=0.05,
|
| 222 |
+
mask_time_length=10,
|
| 223 |
+
mask_time_min_masks=2,
|
| 224 |
+
mask_feature_prob=0.0,
|
| 225 |
+
mask_feature_length=10,
|
| 226 |
+
mask_feature_min_masks=0,
|
| 227 |
+
pad_token_id=1,
|
| 228 |
+
bos_token_id=0,
|
| 229 |
+
eos_token_id=2,
|
| 230 |
+
decoder_start_token_id=2,
|
| 231 |
+
num_mel_bins=80,
|
| 232 |
+
speech_decoder_prenet_layers=2,
|
| 233 |
+
speech_decoder_prenet_units=256,
|
| 234 |
+
speech_decoder_prenet_dropout=0.5,
|
| 235 |
+
speaker_embedding_dim=512,
|
| 236 |
+
speech_decoder_postnet_layers=5,
|
| 237 |
+
speech_decoder_postnet_units=256,
|
| 238 |
+
speech_decoder_postnet_kernel=5,
|
| 239 |
+
speech_decoder_postnet_dropout=0.5,
|
| 240 |
+
reduction_factor=2,
|
| 241 |
+
max_speech_positions=4000,
|
| 242 |
+
max_text_positions=450,
|
| 243 |
+
encoder_max_relative_position=160,
|
| 244 |
+
use_guided_attention_loss=True,
|
| 245 |
+
guided_attention_loss_num_heads=2,
|
| 246 |
+
guided_attention_loss_sigma=0.4,
|
| 247 |
+
guided_attention_loss_scale=10.0,
|
| 248 |
+
use_cache=True,
|
| 249 |
+
is_encoder_decoder=True,
|
| 250 |
+
**kwargs,
|
| 251 |
+
):
|
| 252 |
+
self.vocab_size = vocab_size
|
| 253 |
+
self.hidden_size = hidden_size
|
| 254 |
+
self.encoder_layers = encoder_layers
|
| 255 |
+
self.encoder_ffn_dim = encoder_ffn_dim
|
| 256 |
+
self.encoder_attention_heads = encoder_attention_heads
|
| 257 |
+
self.encoder_layerdrop = encoder_layerdrop
|
| 258 |
+
self.decoder_layers = decoder_layers
|
| 259 |
+
self.decoder_ffn_dim = decoder_ffn_dim
|
| 260 |
+
self.decoder_attention_heads = decoder_attention_heads
|
| 261 |
+
self.decoder_layerdrop = decoder_layerdrop
|
| 262 |
+
self.hidden_act = hidden_act
|
| 263 |
+
self.positional_dropout = positional_dropout
|
| 264 |
+
self.hidden_dropout = hidden_dropout
|
| 265 |
+
self.attention_dropout = attention_dropout
|
| 266 |
+
self.activation_dropout = activation_dropout
|
| 267 |
+
self.initializer_range = initializer_range
|
| 268 |
+
self.layer_norm_eps = layer_norm_eps
|
| 269 |
+
self.scale_embedding = scale_embedding
|
| 270 |
+
|
| 271 |
+
self.feat_extract_norm = feat_extract_norm
|
| 272 |
+
self.feat_proj_dropout = feat_proj_dropout
|
| 273 |
+
self.feat_extract_activation = feat_extract_activation
|
| 274 |
+
self.conv_dim = list(conv_dim)
|
| 275 |
+
self.conv_stride = list(conv_stride)
|
| 276 |
+
self.conv_kernel = list(conv_kernel)
|
| 277 |
+
self.conv_bias = conv_bias
|
| 278 |
+
self.num_conv_pos_embeddings = num_conv_pos_embeddings
|
| 279 |
+
self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups
|
| 280 |
+
self.num_feat_extract_layers = len(self.conv_dim)
|
| 281 |
+
|
| 282 |
+
if (
|
| 283 |
+
(len(self.conv_stride) != self.num_feat_extract_layers)
|
| 284 |
+
or (len(self.conv_kernel) != self.num_feat_extract_layers)
|
| 285 |
+
or (len(self.conv_dim) != self.num_feat_extract_layers)
|
| 286 |
+
):
|
| 287 |
+
raise ValueError(
|
| 288 |
+
"Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
|
| 289 |
+
" `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
|
| 290 |
+
f" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,"
|
| 291 |
+
f" `len(config.conv_kernel) = {len(self.conv_kernel)}`."
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
# fine-tuning config parameters for SpecAugment: https://huggingface.co/papers/1904.08779
|
| 295 |
+
self.apply_spec_augment = apply_spec_augment
|
| 296 |
+
self.mask_time_prob = mask_time_prob
|
| 297 |
+
self.mask_time_length = mask_time_length
|
| 298 |
+
self.mask_time_min_masks = mask_time_min_masks
|
| 299 |
+
self.mask_feature_prob = mask_feature_prob
|
| 300 |
+
self.mask_feature_length = mask_feature_length
|
| 301 |
+
self.mask_feature_min_masks = mask_feature_min_masks
|
| 302 |
+
|
| 303 |
+
self.num_mel_bins = num_mel_bins
|
| 304 |
+
self.speech_decoder_prenet_layers = speech_decoder_prenet_layers
|
| 305 |
+
self.speech_decoder_prenet_units = speech_decoder_prenet_units
|
| 306 |
+
self.speech_decoder_prenet_dropout = speech_decoder_prenet_dropout
|
| 307 |
+
self.speaker_embedding_dim = speaker_embedding_dim
|
| 308 |
+
|
| 309 |
+
self.speech_decoder_postnet_layers = speech_decoder_postnet_layers
|
| 310 |
+
self.speech_decoder_postnet_units = speech_decoder_postnet_units
|
| 311 |
+
self.speech_decoder_postnet_kernel = speech_decoder_postnet_kernel
|
| 312 |
+
self.speech_decoder_postnet_dropout = speech_decoder_postnet_dropout
|
| 313 |
+
self.reduction_factor = reduction_factor
|
| 314 |
+
|
| 315 |
+
self.max_speech_positions = max_speech_positions
|
| 316 |
+
self.max_text_positions = max_text_positions
|
| 317 |
+
self.encoder_max_relative_position = encoder_max_relative_position
|
| 318 |
+
|
| 319 |
+
self.use_guided_attention_loss = use_guided_attention_loss
|
| 320 |
+
self.guided_attention_loss_num_heads = guided_attention_loss_num_heads
|
| 321 |
+
self.guided_attention_loss_sigma = guided_attention_loss_sigma
|
| 322 |
+
self.guided_attention_loss_scale = guided_attention_loss_scale
|
| 323 |
+
|
| 324 |
+
self.use_cache = use_cache
|
| 325 |
+
self.is_encoder_decoder = is_encoder_decoder
|
| 326 |
+
|
| 327 |
+
super().__init__(
|
| 328 |
+
pad_token_id=pad_token_id,
|
| 329 |
+
bos_token_id=bos_token_id,
|
| 330 |
+
eos_token_id=eos_token_id,
|
| 331 |
+
is_encoder_decoder=is_encoder_decoder,
|
| 332 |
+
decoder_start_token_id=decoder_start_token_id,
|
| 333 |
+
**kwargs,
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
def inputs_to_logits_ratio(self):
|
| 337 |
+
return functools.reduce(operator.mul, self.conv_stride, 1)
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
class SpeechT5HifiGanConfig(PretrainedConfig):
|
| 341 |
+
r"""
|
| 342 |
+
This is the configuration class to store the configuration of a [`SpeechT5HifiGanModel`]. It is used to instantiate
|
| 343 |
+
a SpeechT5 HiFi-GAN vocoder model according to the specified arguments, defining the model architecture.
|
| 344 |
+
Instantiating a configuration with the defaults will yield a similar configuration to that of the SpeechT5
|
| 345 |
+
[microsoft/speecht5_hifigan](https://huggingface.co/microsoft/speecht5_hifigan) architecture.
|
| 346 |
+
|
| 347 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 348 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 349 |
+
|
| 350 |
+
Args:
|
| 351 |
+
model_in_dim (`int`, *optional*, defaults to 80):
|
| 352 |
+
The number of frequency bins in the input log-mel spectrogram.
|
| 353 |
+
sampling_rate (`int`, *optional*, defaults to 16000):
|
| 354 |
+
The sampling rate at which the output audio will be generated, expressed in hertz (Hz).
|
| 355 |
+
upsample_initial_channel (`int`, *optional*, defaults to 512):
|
| 356 |
+
The number of input channels into the upsampling network.
|
| 357 |
+
upsample_rates (`tuple[int]` or `list[int]`, *optional*, defaults to `[4, 4, 4, 4]`):
|
| 358 |
+
A tuple of integers defining the stride of each 1D convolutional layer in the upsampling network. The
|
| 359 |
+
length of *upsample_rates* defines the number of convolutional layers and has to match the length of
|
| 360 |
+
*upsample_kernel_sizes*.
|
| 361 |
+
upsample_kernel_sizes (`tuple[int]` or `list[int]`, *optional*, defaults to `[8, 8, 8, 8]`):
|
| 362 |
+
A tuple of integers defining the kernel size of each 1D convolutional layer in the upsampling network. The
|
| 363 |
+
length of *upsample_kernel_sizes* defines the number of convolutional layers and has to match the length of
|
| 364 |
+
*upsample_rates*.
|
| 365 |
+
resblock_kernel_sizes (`tuple[int]` or `list[int]`, *optional*, defaults to `[3, 7, 11]`):
|
| 366 |
+
A tuple of integers defining the kernel sizes of the 1D convolutional layers in the multi-receptive field
|
| 367 |
+
fusion (MRF) module.
|
| 368 |
+
resblock_dilation_sizes (`tuple[tuple[int]]` or `list[list[int]]`, *optional*, defaults to `[[1, 3, 5], [1, 3, 5], [1, 3, 5]]`):
|
| 369 |
+
A nested tuple of integers defining the dilation rates of the dilated 1D convolutional layers in the
|
| 370 |
+
multi-receptive field fusion (MRF) module.
|
| 371 |
+
initializer_range (`float`, *optional*, defaults to 0.01):
|
| 372 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 373 |
+
leaky_relu_slope (`float`, *optional*, defaults to 0.1):
|
| 374 |
+
The angle of the negative slope used by the leaky ReLU activation.
|
| 375 |
+
normalize_before (`bool`, *optional*, defaults to `True`):
|
| 376 |
+
Whether or not to normalize the spectrogram before vocoding using the vocoder's learned mean and variance.
|
| 377 |
+
|
| 378 |
+
Example:
|
| 379 |
+
|
| 380 |
+
```python
|
| 381 |
+
>>> from transformers import SpeechT5HifiGan, SpeechT5HifiGanConfig
|
| 382 |
+
|
| 383 |
+
>>> # Initializing a "microsoft/speecht5_hifigan" style configuration
|
| 384 |
+
>>> configuration = SpeechT5HifiGanConfig()
|
| 385 |
+
|
| 386 |
+
>>> # Initializing a model (with random weights) from the "microsoft/speecht5_hifigan" style configuration
|
| 387 |
+
>>> model = SpeechT5HifiGan(configuration)
|
| 388 |
+
|
| 389 |
+
>>> # Accessing the model configuration
|
| 390 |
+
>>> configuration = model.config
|
| 391 |
+
```"""
|
| 392 |
+
|
| 393 |
+
model_type = "hifigan"
|
| 394 |
+
|
| 395 |
+
def __init__(
|
| 396 |
+
self,
|
| 397 |
+
model_in_dim=80,
|
| 398 |
+
sampling_rate=16000,
|
| 399 |
+
upsample_initial_channel=512,
|
| 400 |
+
upsample_rates=[4, 4, 4, 4],
|
| 401 |
+
upsample_kernel_sizes=[8, 8, 8, 8],
|
| 402 |
+
resblock_kernel_sizes=[3, 7, 11],
|
| 403 |
+
resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5], [1, 3, 5]],
|
| 404 |
+
initializer_range=0.01,
|
| 405 |
+
leaky_relu_slope=0.1,
|
| 406 |
+
normalize_before=True,
|
| 407 |
+
**kwargs,
|
| 408 |
+
):
|
| 409 |
+
self.model_in_dim = model_in_dim
|
| 410 |
+
self.sampling_rate = sampling_rate
|
| 411 |
+
self.upsample_initial_channel = upsample_initial_channel
|
| 412 |
+
self.upsample_rates = upsample_rates
|
| 413 |
+
self.upsample_kernel_sizes = upsample_kernel_sizes
|
| 414 |
+
self.resblock_kernel_sizes = resblock_kernel_sizes
|
| 415 |
+
self.resblock_dilation_sizes = resblock_dilation_sizes
|
| 416 |
+
self.initializer_range = initializer_range
|
| 417 |
+
self.leaky_relu_slope = leaky_relu_slope
|
| 418 |
+
self.normalize_before = normalize_before
|
| 419 |
+
super().__init__(**kwargs)
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
__all__ = ["SpeechT5Config", "SpeechT5HifiGanConfig"]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speecht5/feature_extraction_speecht5.py
ADDED
|
@@ -0,0 +1,396 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Feature extractor class for SpeechT5."""
|
| 16 |
+
|
| 17 |
+
import warnings
|
| 18 |
+
from typing import Any, Optional, Union
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
from ...audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
|
| 23 |
+
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
|
| 24 |
+
from ...feature_extraction_utils import BatchFeature
|
| 25 |
+
from ...utils import PaddingStrategy, TensorType, logging
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
logger = logging.get_logger(__name__)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class SpeechT5FeatureExtractor(SequenceFeatureExtractor):
|
| 32 |
+
r"""
|
| 33 |
+
Constructs a SpeechT5 feature extractor.
|
| 34 |
+
|
| 35 |
+
This class can pre-process a raw speech signal by (optionally) normalizing to zero-mean unit-variance, for use by
|
| 36 |
+
the SpeechT5 speech encoder prenet.
|
| 37 |
+
|
| 38 |
+
This class can also extract log-mel filter bank features from raw speech, for use by the SpeechT5 speech decoder
|
| 39 |
+
prenet.
|
| 40 |
+
|
| 41 |
+
This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExtractor`] which contains
|
| 42 |
+
most of the main methods. Users should refer to this superclass for more information regarding those methods.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
feature_size (`int`, *optional*, defaults to 1):
|
| 46 |
+
The feature dimension of the extracted features.
|
| 47 |
+
sampling_rate (`int`, *optional*, defaults to 16000):
|
| 48 |
+
The sampling rate at which the audio files should be digitalized expressed in hertz (Hz).
|
| 49 |
+
padding_value (`float`, *optional*, defaults to 0.0):
|
| 50 |
+
The value that is used to fill the padding values.
|
| 51 |
+
do_normalize (`bool`, *optional*, defaults to `False`):
|
| 52 |
+
Whether or not to zero-mean unit-variance normalize the input. Normalizing can help to significantly
|
| 53 |
+
improve the performance for some models.
|
| 54 |
+
num_mel_bins (`int`, *optional*, defaults to 80):
|
| 55 |
+
The number of mel-frequency bins in the extracted spectrogram features.
|
| 56 |
+
hop_length (`int`, *optional*, defaults to 16):
|
| 57 |
+
Number of ms between windows. Otherwise referred to as "shift" in many papers.
|
| 58 |
+
win_length (`int`, *optional*, defaults to 64):
|
| 59 |
+
Number of ms per window.
|
| 60 |
+
win_function (`str`, *optional*, defaults to `"hann_window"`):
|
| 61 |
+
Name for the window function used for windowing, must be accessible via `torch.{win_function}`
|
| 62 |
+
frame_signal_scale (`float`, *optional*, defaults to 1.0):
|
| 63 |
+
Constant multiplied in creating the frames before applying DFT. This argument is deprecated.
|
| 64 |
+
fmin (`float`, *optional*, defaults to 80):
|
| 65 |
+
Minimum mel frequency in Hz.
|
| 66 |
+
fmax (`float`, *optional*, defaults to 7600):
|
| 67 |
+
Maximum mel frequency in Hz.
|
| 68 |
+
mel_floor (`float`, *optional*, defaults to 1e-10):
|
| 69 |
+
Minimum value of mel frequency banks.
|
| 70 |
+
reduction_factor (`int`, *optional*, defaults to 2):
|
| 71 |
+
Spectrogram length reduction factor. This argument is deprecated.
|
| 72 |
+
return_attention_mask (`bool`, *optional*, defaults to `True`):
|
| 73 |
+
Whether or not [`~SpeechT5FeatureExtractor.__call__`] should return `attention_mask`.
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
model_input_names = ["input_values", "attention_mask"]
|
| 77 |
+
|
| 78 |
+
def __init__(
|
| 79 |
+
self,
|
| 80 |
+
feature_size: int = 1,
|
| 81 |
+
sampling_rate: int = 16000,
|
| 82 |
+
padding_value: float = 0.0,
|
| 83 |
+
do_normalize: bool = False,
|
| 84 |
+
num_mel_bins: int = 80,
|
| 85 |
+
hop_length: int = 16,
|
| 86 |
+
win_length: int = 64,
|
| 87 |
+
win_function: str = "hann_window",
|
| 88 |
+
frame_signal_scale: float = 1.0,
|
| 89 |
+
fmin: float = 80,
|
| 90 |
+
fmax: float = 7600,
|
| 91 |
+
mel_floor: float = 1e-10,
|
| 92 |
+
reduction_factor: int = 2,
|
| 93 |
+
return_attention_mask: bool = True,
|
| 94 |
+
**kwargs,
|
| 95 |
+
):
|
| 96 |
+
super().__init__(feature_size=feature_size, sampling_rate=sampling_rate, padding_value=padding_value, **kwargs)
|
| 97 |
+
self.do_normalize = do_normalize
|
| 98 |
+
self.return_attention_mask = return_attention_mask
|
| 99 |
+
|
| 100 |
+
self.num_mel_bins = num_mel_bins
|
| 101 |
+
self.hop_length = hop_length
|
| 102 |
+
self.win_length = win_length
|
| 103 |
+
self.win_function = win_function
|
| 104 |
+
self.frame_signal_scale = frame_signal_scale
|
| 105 |
+
self.fmin = fmin
|
| 106 |
+
self.fmax = fmax
|
| 107 |
+
self.mel_floor = mel_floor
|
| 108 |
+
self.reduction_factor = reduction_factor
|
| 109 |
+
|
| 110 |
+
self.sample_size = win_length * sampling_rate // 1000
|
| 111 |
+
self.sample_stride = hop_length * sampling_rate // 1000
|
| 112 |
+
self.n_fft = optimal_fft_length(self.sample_size)
|
| 113 |
+
self.n_freqs = (self.n_fft // 2) + 1
|
| 114 |
+
|
| 115 |
+
self.window = window_function(window_length=self.sample_size, name=self.win_function, periodic=True)
|
| 116 |
+
|
| 117 |
+
self.mel_filters = mel_filter_bank(
|
| 118 |
+
num_frequency_bins=self.n_freqs,
|
| 119 |
+
num_mel_filters=self.num_mel_bins,
|
| 120 |
+
min_frequency=self.fmin,
|
| 121 |
+
max_frequency=self.fmax,
|
| 122 |
+
sampling_rate=self.sampling_rate,
|
| 123 |
+
norm="slaney",
|
| 124 |
+
mel_scale="slaney",
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
if frame_signal_scale != 1.0:
|
| 128 |
+
warnings.warn(
|
| 129 |
+
"The argument `frame_signal_scale` is deprecated and will be removed in version 4.30.0 of Transformers",
|
| 130 |
+
FutureWarning,
|
| 131 |
+
)
|
| 132 |
+
if reduction_factor != 2.0:
|
| 133 |
+
warnings.warn(
|
| 134 |
+
"The argument `reduction_factor` is deprecated and will be removed in version 4.30.0 of Transformers",
|
| 135 |
+
FutureWarning,
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
@staticmethod
|
| 139 |
+
# Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
|
| 140 |
+
def zero_mean_unit_var_norm(
|
| 141 |
+
input_values: list[np.ndarray], attention_mask: list[np.ndarray], padding_value: float = 0.0
|
| 142 |
+
) -> list[np.ndarray]:
|
| 143 |
+
"""
|
| 144 |
+
Every array in the list is normalized to have zero mean and unit variance
|
| 145 |
+
"""
|
| 146 |
+
if attention_mask is not None:
|
| 147 |
+
attention_mask = np.array(attention_mask, np.int32)
|
| 148 |
+
normed_input_values = []
|
| 149 |
+
|
| 150 |
+
for vector, length in zip(input_values, attention_mask.sum(-1)):
|
| 151 |
+
normed_slice = (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7)
|
| 152 |
+
if length < normed_slice.shape[0]:
|
| 153 |
+
normed_slice[length:] = padding_value
|
| 154 |
+
|
| 155 |
+
normed_input_values.append(normed_slice)
|
| 156 |
+
else:
|
| 157 |
+
normed_input_values = [(x - x.mean()) / np.sqrt(x.var() + 1e-7) for x in input_values]
|
| 158 |
+
|
| 159 |
+
return normed_input_values
|
| 160 |
+
|
| 161 |
+
def _extract_mel_features(
|
| 162 |
+
self,
|
| 163 |
+
one_waveform: np.ndarray,
|
| 164 |
+
) -> np.ndarray:
|
| 165 |
+
"""
|
| 166 |
+
Extracts log-mel filterbank features for one waveform array (unbatched).
|
| 167 |
+
"""
|
| 168 |
+
log_mel_spec = spectrogram(
|
| 169 |
+
one_waveform,
|
| 170 |
+
window=self.window,
|
| 171 |
+
frame_length=self.sample_size,
|
| 172 |
+
hop_length=self.sample_stride,
|
| 173 |
+
fft_length=self.n_fft,
|
| 174 |
+
mel_filters=self.mel_filters,
|
| 175 |
+
mel_floor=self.mel_floor,
|
| 176 |
+
log_mel="log10",
|
| 177 |
+
)
|
| 178 |
+
return log_mel_spec.T
|
| 179 |
+
|
| 180 |
+
def __call__(
|
| 181 |
+
self,
|
| 182 |
+
audio: Optional[Union[np.ndarray, list[float], list[np.ndarray], list[list[float]]]] = None,
|
| 183 |
+
audio_target: Optional[Union[np.ndarray, list[float], list[np.ndarray], list[list[float]]]] = None,
|
| 184 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
| 185 |
+
max_length: Optional[int] = None,
|
| 186 |
+
truncation: bool = False,
|
| 187 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 188 |
+
return_attention_mask: Optional[bool] = None,
|
| 189 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 190 |
+
sampling_rate: Optional[int] = None,
|
| 191 |
+
**kwargs,
|
| 192 |
+
) -> BatchFeature:
|
| 193 |
+
"""
|
| 194 |
+
Main method to featurize and prepare for the model one or several sequence(s).
|
| 195 |
+
|
| 196 |
+
Pass in a value for `audio` to extract waveform features. Pass in a value for `audio_target` to extract log-mel
|
| 197 |
+
spectrogram features.
|
| 198 |
+
|
| 199 |
+
Args:
|
| 200 |
+
audio (`np.ndarray`, `list[float]`, `list[np.ndarray]`, `list[list[float]]`, *optional*):
|
| 201 |
+
The sequence or batch of sequences to be processed. Each sequence can be a numpy array, a list of float
|
| 202 |
+
values, a list of numpy arrays or a list of list of float values. This outputs waveform features. Must
|
| 203 |
+
be mono channel audio, not stereo, i.e. single float per timestep.
|
| 204 |
+
audio_target (`np.ndarray`, `list[float]`, `list[np.ndarray]`, `list[list[float]]`, *optional*):
|
| 205 |
+
The sequence or batch of sequences to be processed as targets. Each sequence can be a numpy array, a
|
| 206 |
+
list of float values, a list of numpy arrays or a list of list of float values. This outputs log-mel
|
| 207 |
+
spectrogram features.
|
| 208 |
+
padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
|
| 209 |
+
Select a strategy to pad the returned sequences (according to the model's padding side and padding
|
| 210 |
+
index) among:
|
| 211 |
+
|
| 212 |
+
- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
|
| 213 |
+
sequence if provided).
|
| 214 |
+
- `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
|
| 215 |
+
acceptable input length for the model if that argument is not provided.
|
| 216 |
+
- `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
|
| 217 |
+
lengths).
|
| 218 |
+
max_length (`int`, *optional*):
|
| 219 |
+
Maximum length of the returned list and optionally padding length (see above).
|
| 220 |
+
truncation (`bool`):
|
| 221 |
+
Activates truncation to cut input sequences longer than *max_length* to *max_length*.
|
| 222 |
+
pad_to_multiple_of (`int`, *optional*):
|
| 223 |
+
If set will pad the sequence to a multiple of the provided value.
|
| 224 |
+
|
| 225 |
+
This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
|
| 226 |
+
`>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128.
|
| 227 |
+
return_attention_mask (`bool`, *optional*):
|
| 228 |
+
Whether to return the attention mask. If left to the default, will return the attention mask according
|
| 229 |
+
to the specific feature_extractor's default.
|
| 230 |
+
|
| 231 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 232 |
+
|
| 233 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 234 |
+
If set, will return tensors instead of list of python integers. Acceptable values are:
|
| 235 |
+
|
| 236 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 237 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 238 |
+
- `'np'`: Return Numpy `np.ndarray` objects.
|
| 239 |
+
sampling_rate (`int`, *optional*):
|
| 240 |
+
The sampling rate at which the `audio` or `audio_target` input was sampled. It is strongly recommended
|
| 241 |
+
to pass `sampling_rate` at the forward call to prevent silent errors.
|
| 242 |
+
"""
|
| 243 |
+
if audio is None and audio_target is None:
|
| 244 |
+
raise ValueError("You must provide either `audio` or `audio_target` values.")
|
| 245 |
+
|
| 246 |
+
if sampling_rate is not None:
|
| 247 |
+
if sampling_rate != self.sampling_rate:
|
| 248 |
+
raise ValueError(
|
| 249 |
+
f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of"
|
| 250 |
+
f" {self.sampling_rate}. Please make sure that the provided audio input was sampled with"
|
| 251 |
+
f" {self.sampling_rate} and not {sampling_rate}."
|
| 252 |
+
)
|
| 253 |
+
else:
|
| 254 |
+
logger.warning(
|
| 255 |
+
f"It is strongly recommended to pass the `sampling_rate` argument to `{self.__class__.__name__}()`. "
|
| 256 |
+
"Failing to do so can result in silent errors that might be hard to debug."
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
if audio is not None:
|
| 260 |
+
inputs = self._process_audio(
|
| 261 |
+
audio,
|
| 262 |
+
False,
|
| 263 |
+
padding,
|
| 264 |
+
max_length,
|
| 265 |
+
truncation,
|
| 266 |
+
pad_to_multiple_of,
|
| 267 |
+
return_attention_mask,
|
| 268 |
+
return_tensors,
|
| 269 |
+
**kwargs,
|
| 270 |
+
)
|
| 271 |
+
else:
|
| 272 |
+
inputs = None
|
| 273 |
+
|
| 274 |
+
if audio_target is not None:
|
| 275 |
+
inputs_target = self._process_audio(
|
| 276 |
+
audio_target,
|
| 277 |
+
True,
|
| 278 |
+
padding,
|
| 279 |
+
max_length,
|
| 280 |
+
truncation,
|
| 281 |
+
pad_to_multiple_of,
|
| 282 |
+
return_attention_mask,
|
| 283 |
+
return_tensors,
|
| 284 |
+
**kwargs,
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
if inputs is None:
|
| 288 |
+
return inputs_target
|
| 289 |
+
else:
|
| 290 |
+
inputs["labels"] = inputs_target["input_values"]
|
| 291 |
+
decoder_attention_mask = inputs_target.get("attention_mask")
|
| 292 |
+
if decoder_attention_mask is not None:
|
| 293 |
+
inputs["decoder_attention_mask"] = decoder_attention_mask
|
| 294 |
+
|
| 295 |
+
return inputs
|
| 296 |
+
|
| 297 |
+
def _process_audio(
|
| 298 |
+
self,
|
| 299 |
+
speech: Union[np.ndarray, list[float], list[np.ndarray], list[list[float]]],
|
| 300 |
+
is_target: bool = False,
|
| 301 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
| 302 |
+
max_length: Optional[int] = None,
|
| 303 |
+
truncation: bool = False,
|
| 304 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 305 |
+
return_attention_mask: Optional[bool] = None,
|
| 306 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 307 |
+
**kwargs,
|
| 308 |
+
) -> BatchFeature:
|
| 309 |
+
is_batched_numpy = isinstance(speech, np.ndarray) and len(speech.shape) > 1
|
| 310 |
+
if is_batched_numpy and len(speech.shape) > 2:
|
| 311 |
+
raise ValueError(f"Only mono-channel audio is supported for input to {self}")
|
| 312 |
+
is_batched = is_batched_numpy or (
|
| 313 |
+
isinstance(speech, (list, tuple)) and (isinstance(speech[0], (np.ndarray, tuple, list)))
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
if is_batched:
|
| 317 |
+
speech = [np.asarray(speech, dtype=np.float32) for speech in speech]
|
| 318 |
+
elif not is_batched and not isinstance(speech, np.ndarray):
|
| 319 |
+
speech = np.asarray(speech, dtype=np.float32)
|
| 320 |
+
elif isinstance(speech, np.ndarray) and speech.dtype is np.dtype(np.float64):
|
| 321 |
+
speech = speech.astype(np.float32)
|
| 322 |
+
|
| 323 |
+
# always return batch
|
| 324 |
+
if not is_batched:
|
| 325 |
+
speech = [speech]
|
| 326 |
+
|
| 327 |
+
# needed to make pad() work on spectrogram inputs
|
| 328 |
+
feature_size_hack = self.feature_size
|
| 329 |
+
|
| 330 |
+
# convert into correct format for padding
|
| 331 |
+
if is_target:
|
| 332 |
+
features = [self._extract_mel_features(waveform) for waveform in speech]
|
| 333 |
+
encoded_inputs = BatchFeature({"input_values": features})
|
| 334 |
+
self.feature_size = self.num_mel_bins
|
| 335 |
+
else:
|
| 336 |
+
encoded_inputs = BatchFeature({"input_values": speech})
|
| 337 |
+
|
| 338 |
+
padded_inputs = self.pad(
|
| 339 |
+
encoded_inputs,
|
| 340 |
+
padding=padding,
|
| 341 |
+
max_length=max_length,
|
| 342 |
+
truncation=truncation,
|
| 343 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 344 |
+
return_attention_mask=return_attention_mask,
|
| 345 |
+
**kwargs,
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
self.feature_size = feature_size_hack
|
| 349 |
+
|
| 350 |
+
# convert input values to correct format
|
| 351 |
+
input_values = padded_inputs["input_values"]
|
| 352 |
+
if not isinstance(input_values[0], np.ndarray):
|
| 353 |
+
padded_inputs["input_values"] = [np.asarray(array, dtype=np.float32) for array in input_values]
|
| 354 |
+
elif (
|
| 355 |
+
not isinstance(input_values, np.ndarray)
|
| 356 |
+
and isinstance(input_values[0], np.ndarray)
|
| 357 |
+
and input_values[0].dtype is np.dtype(np.float64)
|
| 358 |
+
):
|
| 359 |
+
padded_inputs["input_values"] = [array.astype(np.float32) for array in input_values]
|
| 360 |
+
elif isinstance(input_values, np.ndarray) and input_values.dtype is np.dtype(np.float64):
|
| 361 |
+
padded_inputs["input_values"] = input_values.astype(np.float32)
|
| 362 |
+
|
| 363 |
+
# convert attention_mask to correct format
|
| 364 |
+
attention_mask = padded_inputs.get("attention_mask")
|
| 365 |
+
if attention_mask is not None:
|
| 366 |
+
padded_inputs["attention_mask"] = [np.asarray(array, dtype=np.int32) for array in attention_mask]
|
| 367 |
+
|
| 368 |
+
# zero-mean and unit-variance normalization
|
| 369 |
+
if not is_target and self.do_normalize:
|
| 370 |
+
attention_mask = (
|
| 371 |
+
attention_mask
|
| 372 |
+
if self._get_padding_strategies(padding, max_length=max_length) is not PaddingStrategy.DO_NOT_PAD
|
| 373 |
+
else None
|
| 374 |
+
)
|
| 375 |
+
padded_inputs["input_values"] = self.zero_mean_unit_var_norm(
|
| 376 |
+
padded_inputs["input_values"], attention_mask=attention_mask, padding_value=self.padding_value
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
if return_tensors is not None:
|
| 380 |
+
padded_inputs = padded_inputs.convert_to_tensors(return_tensors)
|
| 381 |
+
|
| 382 |
+
return padded_inputs
|
| 383 |
+
|
| 384 |
+
def to_dict(self) -> dict[str, Any]:
|
| 385 |
+
output = super().to_dict()
|
| 386 |
+
|
| 387 |
+
# Don't serialize these as they are derived from the other properties.
|
| 388 |
+
names = ["window", "mel_filters", "sample_size", "sample_stride", "n_fft", "n_freqs"]
|
| 389 |
+
for name in names:
|
| 390 |
+
if name in output:
|
| 391 |
+
del output[name]
|
| 392 |
+
|
| 393 |
+
return output
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
__all__ = ["SpeechT5FeatureExtractor"]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speecht5/modeling_speecht5.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speecht5/number_normalizer.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The Fairseq Authors, Microsoft Research, and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Number Normalizer class for SpeechT5."""
|
| 16 |
+
|
| 17 |
+
import re
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class EnglishNumberNormalizer:
|
| 21 |
+
def __init__(self):
|
| 22 |
+
self.ones = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
|
| 23 |
+
self.teens = [
|
| 24 |
+
"",
|
| 25 |
+
"eleven",
|
| 26 |
+
"twelve",
|
| 27 |
+
"thirteen",
|
| 28 |
+
"fourteen",
|
| 29 |
+
"fifteen",
|
| 30 |
+
"sixteen",
|
| 31 |
+
"seventeen",
|
| 32 |
+
"eighteen",
|
| 33 |
+
"nineteen",
|
| 34 |
+
]
|
| 35 |
+
self.tens = ["", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
|
| 36 |
+
self.thousands = [
|
| 37 |
+
"",
|
| 38 |
+
"thousand",
|
| 39 |
+
"million",
|
| 40 |
+
"billion",
|
| 41 |
+
"trillion",
|
| 42 |
+
"quadrillion",
|
| 43 |
+
"quintillion",
|
| 44 |
+
"sextillion",
|
| 45 |
+
"septillion",
|
| 46 |
+
"octillion",
|
| 47 |
+
"nonillion",
|
| 48 |
+
"decillion",
|
| 49 |
+
]
|
| 50 |
+
|
| 51 |
+
# Define a dictionary to map currency symbols to their names
|
| 52 |
+
# Top most traded currencies according to
|
| 53 |
+
# https://en.wikipedia.org/wiki/Template:Most_traded_currencies
|
| 54 |
+
self.currency_symbols = {
|
| 55 |
+
"$": " dollars",
|
| 56 |
+
"€": " euros",
|
| 57 |
+
"£": " pounds",
|
| 58 |
+
"¢": " cents",
|
| 59 |
+
"¥": " japanese yen",
|
| 60 |
+
"﷼": " saudi riyal",
|
| 61 |
+
"₹": " indian rupees",
|
| 62 |
+
"₽": " russian rubles",
|
| 63 |
+
"฿": " thai baht",
|
| 64 |
+
"₺": " turkish liras",
|
| 65 |
+
"₴": " ukrainian hryvnia",
|
| 66 |
+
"₣": " swiss francs",
|
| 67 |
+
"₡": " costa rican colon",
|
| 68 |
+
"₱": " philippine peso",
|
| 69 |
+
"₪": " israeli shekels",
|
| 70 |
+
"₮": " mongolian tögrög",
|
| 71 |
+
"₩": " south korean won",
|
| 72 |
+
"₦": " nigerian naira",
|
| 73 |
+
"₫": " vietnamese Đồng",
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
def spell_number(self, num):
|
| 77 |
+
if num == 0:
|
| 78 |
+
return "zero"
|
| 79 |
+
|
| 80 |
+
parts = []
|
| 81 |
+
for i in range(0, len(self.thousands)):
|
| 82 |
+
if num % 1000 != 0:
|
| 83 |
+
part = ""
|
| 84 |
+
hundreds = num % 1000 // 100
|
| 85 |
+
tens_units = num % 100
|
| 86 |
+
|
| 87 |
+
if hundreds > 0:
|
| 88 |
+
part += self.ones[hundreds] + " hundred"
|
| 89 |
+
if tens_units > 0:
|
| 90 |
+
part += " and "
|
| 91 |
+
|
| 92 |
+
if tens_units > 10 and tens_units < 20:
|
| 93 |
+
part += self.teens[tens_units - 10]
|
| 94 |
+
else:
|
| 95 |
+
tens_digit = self.tens[tens_units // 10]
|
| 96 |
+
ones_digit = self.ones[tens_units % 10]
|
| 97 |
+
if tens_digit:
|
| 98 |
+
part += tens_digit
|
| 99 |
+
if ones_digit:
|
| 100 |
+
if tens_digit:
|
| 101 |
+
part += " "
|
| 102 |
+
part += ones_digit
|
| 103 |
+
|
| 104 |
+
parts.append(part)
|
| 105 |
+
|
| 106 |
+
num //= 1000
|
| 107 |
+
|
| 108 |
+
return " ".join(reversed(parts))
|
| 109 |
+
|
| 110 |
+
def convert(self, number):
|
| 111 |
+
"""
|
| 112 |
+
Converts an individual number passed in string form to spelt-out form
|
| 113 |
+
"""
|
| 114 |
+
if "." in number:
|
| 115 |
+
integer_part, decimal_part = number.split(".")
|
| 116 |
+
else:
|
| 117 |
+
integer_part, decimal_part = number, "00"
|
| 118 |
+
|
| 119 |
+
# Extract currency symbol if present
|
| 120 |
+
currency_symbol = ""
|
| 121 |
+
for symbol, name in self.currency_symbols.items():
|
| 122 |
+
if integer_part.startswith(symbol):
|
| 123 |
+
currency_symbol = name
|
| 124 |
+
integer_part = integer_part[len(symbol) :]
|
| 125 |
+
break
|
| 126 |
+
|
| 127 |
+
if integer_part.startswith("-"):
|
| 128 |
+
if integer_part[1:].startswith(symbol):
|
| 129 |
+
currency_symbol = name
|
| 130 |
+
integer_part = "-" + integer_part[len(symbol) + 1 :]
|
| 131 |
+
break
|
| 132 |
+
|
| 133 |
+
# Extract 'minus' prefix for negative numbers
|
| 134 |
+
minus_prefix = ""
|
| 135 |
+
if integer_part.startswith("-"):
|
| 136 |
+
minus_prefix = "minus "
|
| 137 |
+
integer_part = integer_part[1:]
|
| 138 |
+
elif integer_part.startswith("minus"):
|
| 139 |
+
minus_prefix = "minus "
|
| 140 |
+
integer_part = integer_part[len("minus") :]
|
| 141 |
+
|
| 142 |
+
percent_suffix = ""
|
| 143 |
+
if "%" in integer_part or "%" in decimal_part:
|
| 144 |
+
percent_suffix = " percent"
|
| 145 |
+
integer_part = integer_part.replace("%", "")
|
| 146 |
+
decimal_part = decimal_part.replace("%", "")
|
| 147 |
+
|
| 148 |
+
integer_part = integer_part.zfill(3 * ((len(integer_part) - 1) // 3 + 1))
|
| 149 |
+
|
| 150 |
+
parts = []
|
| 151 |
+
for i in range(0, len(integer_part), 3):
|
| 152 |
+
chunk = int(integer_part[i : i + 3])
|
| 153 |
+
if chunk > 0:
|
| 154 |
+
part = self.spell_number(chunk)
|
| 155 |
+
unit = self.thousands[len(integer_part[i:]) // 3 - 1]
|
| 156 |
+
if unit:
|
| 157 |
+
part += " " + unit
|
| 158 |
+
parts.append(part)
|
| 159 |
+
|
| 160 |
+
spelled_integer = " ".join(parts)
|
| 161 |
+
|
| 162 |
+
# Format the spelt-out number based on conditions, such as:
|
| 163 |
+
# If it has decimal parts, currency symbol, minus prefix, etc
|
| 164 |
+
if decimal_part == "00":
|
| 165 |
+
return (
|
| 166 |
+
f"{minus_prefix}{spelled_integer}{percent_suffix}{currency_symbol}"
|
| 167 |
+
if minus_prefix or currency_symbol
|
| 168 |
+
else f"{spelled_integer}{percent_suffix}"
|
| 169 |
+
)
|
| 170 |
+
else:
|
| 171 |
+
spelled_decimal = " ".join([self.spell_number(int(digit)) for digit in decimal_part])
|
| 172 |
+
return (
|
| 173 |
+
f"{minus_prefix}{spelled_integer} point {spelled_decimal}{percent_suffix}{currency_symbol}"
|
| 174 |
+
if minus_prefix or currency_symbol
|
| 175 |
+
else f"{minus_prefix}{spelled_integer} point {spelled_decimal}{percent_suffix}"
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
def __call__(self, text):
|
| 179 |
+
"""
|
| 180 |
+
Convert numbers / number-like quantities in a string to their spelt-out counterparts
|
| 181 |
+
"""
|
| 182 |
+
# Form part of the pattern for all currency symbols
|
| 183 |
+
pattern = r"(?<!\w)(-?\$?\€?\£?\¢?\¥?\₹?\₽?\฿?\₺?\₴?\₣?\₡?\₱?\₪?\₮?\₩?\₦?\₫?\﷼?\d+(?:\.\d{1,2})?%?)(?!\w)"
|
| 184 |
+
|
| 185 |
+
# Find and replace commas in numbers (15,000 -> 15000, etc)
|
| 186 |
+
text = re.sub(r"(\d+,\d+)", lambda match: match.group(1).replace(",", ""), text)
|
| 187 |
+
|
| 188 |
+
# Use regex to find and replace numbers in the text
|
| 189 |
+
converted_text = re.sub(pattern, lambda match: self.convert(match.group(1)), text)
|
| 190 |
+
converted_text = re.sub(" +", " ", converted_text)
|
| 191 |
+
|
| 192 |
+
return converted_text
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speecht5/processing_speecht5.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Speech processor class for SpeechT5."""
|
| 16 |
+
|
| 17 |
+
from ...processing_utils import ProcessorMixin
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class SpeechT5Processor(ProcessorMixin):
|
| 21 |
+
r"""
|
| 22 |
+
Constructs a SpeechT5 processor which wraps a feature extractor and a tokenizer into a single processor.
|
| 23 |
+
|
| 24 |
+
[`SpeechT5Processor`] offers all the functionalities of [`SpeechT5FeatureExtractor`] and [`SpeechT5Tokenizer`]. See
|
| 25 |
+
the docstring of [`~SpeechT5Processor.__call__`] and [`~SpeechT5Processor.decode`] for more information.
|
| 26 |
+
|
| 27 |
+
Args:
|
| 28 |
+
feature_extractor (`SpeechT5FeatureExtractor`):
|
| 29 |
+
An instance of [`SpeechT5FeatureExtractor`]. The feature extractor is a required input.
|
| 30 |
+
tokenizer (`SpeechT5Tokenizer`):
|
| 31 |
+
An instance of [`SpeechT5Tokenizer`]. The tokenizer is a required input.
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
feature_extractor_class = "SpeechT5FeatureExtractor"
|
| 35 |
+
tokenizer_class = "SpeechT5Tokenizer"
|
| 36 |
+
|
| 37 |
+
def __init__(self, feature_extractor, tokenizer):
|
| 38 |
+
super().__init__(feature_extractor, tokenizer)
|
| 39 |
+
|
| 40 |
+
def __call__(self, *args, **kwargs):
|
| 41 |
+
"""
|
| 42 |
+
Processes audio and text input, as well as audio and text targets.
|
| 43 |
+
|
| 44 |
+
You can process audio by using the argument `audio`, or process audio targets by using the argument
|
| 45 |
+
`audio_target`. This forwards the arguments to SpeechT5FeatureExtractor's
|
| 46 |
+
[`~SpeechT5FeatureExtractor.__call__`].
|
| 47 |
+
|
| 48 |
+
You can process text by using the argument `text`, or process text labels by using the argument `text_target`.
|
| 49 |
+
This forwards the arguments to SpeechT5Tokenizer's [`~SpeechT5Tokenizer.__call__`].
|
| 50 |
+
|
| 51 |
+
Valid input combinations are:
|
| 52 |
+
|
| 53 |
+
- `text` only
|
| 54 |
+
- `audio` only
|
| 55 |
+
- `text_target` only
|
| 56 |
+
- `audio_target` only
|
| 57 |
+
- `text` and `audio_target`
|
| 58 |
+
- `audio` and `audio_target`
|
| 59 |
+
- `text` and `text_target`
|
| 60 |
+
- `audio` and `text_target`
|
| 61 |
+
|
| 62 |
+
Please refer to the docstring of the above two methods for more information.
|
| 63 |
+
"""
|
| 64 |
+
audio = kwargs.pop("audio", None)
|
| 65 |
+
text = kwargs.pop("text", None)
|
| 66 |
+
text_target = kwargs.pop("text_target", None)
|
| 67 |
+
audio_target = kwargs.pop("audio_target", None)
|
| 68 |
+
sampling_rate = kwargs.pop("sampling_rate", None)
|
| 69 |
+
|
| 70 |
+
if audio is not None and text is not None:
|
| 71 |
+
raise ValueError(
|
| 72 |
+
"Cannot process both `audio` and `text` inputs. Did you mean `audio_target` or `text_target`?"
|
| 73 |
+
)
|
| 74 |
+
if audio_target is not None and text_target is not None:
|
| 75 |
+
raise ValueError(
|
| 76 |
+
"Cannot process both `audio_target` and `text_target` inputs. Did you mean `audio` or `text`?"
|
| 77 |
+
)
|
| 78 |
+
if audio is None and audio_target is None and text is None and text_target is None:
|
| 79 |
+
raise ValueError(
|
| 80 |
+
"You need to specify either an `audio`, `audio_target`, `text`, or `text_target` input to process."
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
if audio is not None:
|
| 84 |
+
inputs = self.feature_extractor(audio, *args, sampling_rate=sampling_rate, **kwargs)
|
| 85 |
+
elif text is not None:
|
| 86 |
+
inputs = self.tokenizer(text, **kwargs)
|
| 87 |
+
else:
|
| 88 |
+
inputs = None
|
| 89 |
+
|
| 90 |
+
if audio_target is not None:
|
| 91 |
+
targets = self.feature_extractor(audio_target=audio_target, *args, sampling_rate=sampling_rate, **kwargs)
|
| 92 |
+
labels = targets["input_values"]
|
| 93 |
+
elif text_target is not None:
|
| 94 |
+
targets = self.tokenizer(text_target, **kwargs)
|
| 95 |
+
labels = targets["input_ids"]
|
| 96 |
+
else:
|
| 97 |
+
targets = None
|
| 98 |
+
|
| 99 |
+
if inputs is None:
|
| 100 |
+
return targets
|
| 101 |
+
|
| 102 |
+
if targets is not None:
|
| 103 |
+
inputs["labels"] = labels
|
| 104 |
+
|
| 105 |
+
decoder_attention_mask = targets.get("attention_mask")
|
| 106 |
+
if decoder_attention_mask is not None:
|
| 107 |
+
inputs["decoder_attention_mask"] = decoder_attention_mask
|
| 108 |
+
|
| 109 |
+
return inputs
|
| 110 |
+
|
| 111 |
+
def pad(self, *args, **kwargs):
|
| 112 |
+
"""
|
| 113 |
+
Collates the audio and text inputs, as well as their targets, into a padded batch.
|
| 114 |
+
|
| 115 |
+
Audio inputs are padded by SpeechT5FeatureExtractor's [`~SpeechT5FeatureExtractor.pad`]. Text inputs are padded
|
| 116 |
+
by SpeechT5Tokenizer's [`~SpeechT5Tokenizer.pad`].
|
| 117 |
+
|
| 118 |
+
Valid input combinations are:
|
| 119 |
+
|
| 120 |
+
- `input_ids` only
|
| 121 |
+
- `input_values` only
|
| 122 |
+
- `labels` only, either log-mel spectrograms or text tokens
|
| 123 |
+
- `input_ids` and log-mel spectrogram `labels`
|
| 124 |
+
- `input_values` and text `labels`
|
| 125 |
+
|
| 126 |
+
Please refer to the docstring of the above two methods for more information.
|
| 127 |
+
"""
|
| 128 |
+
input_values = kwargs.pop("input_values", None)
|
| 129 |
+
input_ids = kwargs.pop("input_ids", None)
|
| 130 |
+
labels = kwargs.pop("labels", None)
|
| 131 |
+
|
| 132 |
+
if input_values is not None and input_ids is not None:
|
| 133 |
+
raise ValueError("Cannot process both `input_values` and `input_ids` inputs.")
|
| 134 |
+
if input_values is None and input_ids is None and labels is None:
|
| 135 |
+
raise ValueError(
|
| 136 |
+
"You need to specify either an `input_values`, `input_ids`, or `labels` input to be padded."
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
if input_values is not None:
|
| 140 |
+
inputs = self.feature_extractor.pad(input_values, *args, **kwargs)
|
| 141 |
+
elif input_ids is not None:
|
| 142 |
+
inputs = self.tokenizer.pad(input_ids, **kwargs)
|
| 143 |
+
else:
|
| 144 |
+
inputs = None
|
| 145 |
+
|
| 146 |
+
if labels is not None:
|
| 147 |
+
if "input_ids" in labels or (isinstance(labels, list) and "input_ids" in labels[0]):
|
| 148 |
+
targets = self.tokenizer.pad(labels, **kwargs)
|
| 149 |
+
labels = targets["input_ids"]
|
| 150 |
+
else:
|
| 151 |
+
feature_size_hack = self.feature_extractor.feature_size
|
| 152 |
+
self.feature_extractor.feature_size = self.feature_extractor.num_mel_bins
|
| 153 |
+
targets = self.feature_extractor.pad(labels, *args, **kwargs)
|
| 154 |
+
self.feature_extractor.feature_size = feature_size_hack
|
| 155 |
+
labels = targets["input_values"]
|
| 156 |
+
else:
|
| 157 |
+
targets = None
|
| 158 |
+
|
| 159 |
+
if inputs is None:
|
| 160 |
+
return targets
|
| 161 |
+
|
| 162 |
+
if targets is not None:
|
| 163 |
+
inputs["labels"] = labels
|
| 164 |
+
|
| 165 |
+
decoder_attention_mask = targets.get("attention_mask")
|
| 166 |
+
if decoder_attention_mask is not None:
|
| 167 |
+
inputs["decoder_attention_mask"] = decoder_attention_mask
|
| 168 |
+
|
| 169 |
+
return inputs
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
__all__ = ["SpeechT5Processor"]
|
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/transformers/models/speecht5/tokenization_speecht5.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The Facebook Inc. and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Tokenization class for SpeechT5."""
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
from shutil import copyfile
|
| 19 |
+
from typing import Any, Optional
|
| 20 |
+
|
| 21 |
+
import sentencepiece as spm
|
| 22 |
+
|
| 23 |
+
from ...tokenization_utils import PreTrainedTokenizer
|
| 24 |
+
from ...utils import logging
|
| 25 |
+
from ...utils.import_utils import requires
|
| 26 |
+
from .number_normalizer import EnglishNumberNormalizer
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
logger = logging.get_logger(__name__)
|
| 30 |
+
|
| 31 |
+
VOCAB_FILES_NAMES = {"vocab_file": "spm_char.model"}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@requires(backends=("sentencepiece",))
|
| 35 |
+
class SpeechT5Tokenizer(PreTrainedTokenizer):
|
| 36 |
+
"""
|
| 37 |
+
Construct a SpeechT5 tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
|
| 38 |
+
|
| 39 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 40 |
+
this superclass for more information regarding those methods.
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
vocab_file (`str`):
|
| 44 |
+
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
|
| 45 |
+
contains the vocabulary necessary to instantiate a tokenizer.
|
| 46 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 47 |
+
The begin of sequence token.
|
| 48 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 49 |
+
The end of sequence token.
|
| 50 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 51 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 52 |
+
token instead.
|
| 53 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 54 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 55 |
+
normalize (`bool`, *optional*, defaults to `False`):
|
| 56 |
+
Whether to convert numeric quantities in the text to their spelt-out english counterparts.
|
| 57 |
+
sp_model_kwargs (`dict`, *optional*):
|
| 58 |
+
Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
|
| 59 |
+
SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
|
| 60 |
+
to set:
|
| 61 |
+
|
| 62 |
+
- `enable_sampling`: Enable subword regularization.
|
| 63 |
+
- `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
|
| 64 |
+
|
| 65 |
+
- `nbest_size = {0,1}`: No sampling is performed.
|
| 66 |
+
- `nbest_size > 1`: samples from the nbest_size results.
|
| 67 |
+
- `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
|
| 68 |
+
using forward-filtering-and-backward-sampling algorithm.
|
| 69 |
+
|
| 70 |
+
- `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
|
| 71 |
+
BPE-dropout.
|
| 72 |
+
|
| 73 |
+
Attributes:
|
| 74 |
+
sp_model (`SentencePieceProcessor`):
|
| 75 |
+
The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 79 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 80 |
+
|
| 81 |
+
def __init__(
|
| 82 |
+
self,
|
| 83 |
+
vocab_file,
|
| 84 |
+
bos_token="<s>",
|
| 85 |
+
eos_token="</s>",
|
| 86 |
+
unk_token="<unk>",
|
| 87 |
+
pad_token="<pad>",
|
| 88 |
+
normalize=False,
|
| 89 |
+
sp_model_kwargs: Optional[dict[str, Any]] = None,
|
| 90 |
+
**kwargs,
|
| 91 |
+
) -> None:
|
| 92 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
| 93 |
+
self.vocab_file = vocab_file
|
| 94 |
+
self.normalize = normalize
|
| 95 |
+
self._normalizer = None
|
| 96 |
+
|
| 97 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 98 |
+
self.sp_model.Load(vocab_file)
|
| 99 |
+
|
| 100 |
+
super().__init__(
|
| 101 |
+
bos_token=bos_token,
|
| 102 |
+
eos_token=eos_token,
|
| 103 |
+
unk_token=unk_token,
|
| 104 |
+
pad_token=pad_token,
|
| 105 |
+
normalize=normalize,
|
| 106 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
| 107 |
+
**kwargs,
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
|
| 111 |
+
normalize = kwargs.pop("normalize", self.normalize)
|
| 112 |
+
if is_split_into_words:
|
| 113 |
+
text = " " + text
|
| 114 |
+
if normalize:
|
| 115 |
+
text = self.normalizer(text)
|
| 116 |
+
return (text, kwargs)
|
| 117 |
+
|
| 118 |
+
@property
|
| 119 |
+
def vocab_size(self):
|
| 120 |
+
return self.sp_model.get_piece_size()
|
| 121 |
+
|
| 122 |
+
@property
|
| 123 |
+
def normalizer(self):
|
| 124 |
+
if self._normalizer is None:
|
| 125 |
+
self._normalizer = EnglishNumberNormalizer()
|
| 126 |
+
return self._normalizer
|
| 127 |
+
|
| 128 |
+
@normalizer.setter
|
| 129 |
+
def normalizer(self, value):
|
| 130 |
+
self._normalizer = value
|
| 131 |
+
|
| 132 |
+
def get_vocab(self):
|
| 133 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
| 134 |
+
vocab.update(self.added_tokens_encoder)
|
| 135 |
+
return vocab
|
| 136 |
+
|
| 137 |
+
def __getstate__(self):
|
| 138 |
+
state = self.__dict__.copy()
|
| 139 |
+
state["sp_model"] = None
|
| 140 |
+
return state
|
| 141 |
+
|
| 142 |
+
def __setstate__(self, d):
|
| 143 |
+
self.__dict__ = d
|
| 144 |
+
|
| 145 |
+
# for backward compatibility
|
| 146 |
+
if not hasattr(self, "sp_model_kwargs"):
|
| 147 |
+
self.sp_model_kwargs = {}
|
| 148 |
+
|
| 149 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 150 |
+
self.sp_model.Load(self.vocab_file)
|
| 151 |
+
|
| 152 |
+
def _tokenize(self, text: str) -> list[str]:
|
| 153 |
+
"""Take as input a string and return a list of strings (tokens) for words/sub-words"""
|
| 154 |
+
return self.sp_model.encode(text, out_type=str)
|
| 155 |
+
|
| 156 |
+
def _convert_token_to_id(self, token):
|
| 157 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 158 |
+
return self.sp_model.piece_to_id(token)
|
| 159 |
+
|
| 160 |
+
def _convert_id_to_token(self, index):
|
| 161 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 162 |
+
token = self.sp_model.IdToPiece(index)
|
| 163 |
+
return token
|
| 164 |
+
|
| 165 |
+
# Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.convert_tokens_to_string
|
| 166 |
+
def convert_tokens_to_string(self, tokens):
|
| 167 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 168 |
+
current_sub_tokens = []
|
| 169 |
+
out_string = ""
|
| 170 |
+
prev_is_special = False
|
| 171 |
+
for token in tokens:
|
| 172 |
+
# make sure that special tokens are not decoded using sentencepiece model
|
| 173 |
+
if token in self.all_special_tokens:
|
| 174 |
+
if not prev_is_special:
|
| 175 |
+
out_string += " "
|
| 176 |
+
out_string += self.sp_model.decode(current_sub_tokens) + token
|
| 177 |
+
prev_is_special = True
|
| 178 |
+
current_sub_tokens = []
|
| 179 |
+
else:
|
| 180 |
+
current_sub_tokens.append(token)
|
| 181 |
+
prev_is_special = False
|
| 182 |
+
out_string += self.sp_model.decode(current_sub_tokens)
|
| 183 |
+
return out_string.strip()
|
| 184 |
+
|
| 185 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None) -> list[int]:
|
| 186 |
+
"""Build model inputs from a sequence by appending eos_token_id."""
|
| 187 |
+
if token_ids_1 is None:
|
| 188 |
+
return token_ids_0 + [self.eos_token_id]
|
| 189 |
+
# We don't expect to process pairs, but leave the pair logic for API consistency
|
| 190 |
+
return token_ids_0 + token_ids_1 + [self.eos_token_id]
|
| 191 |
+
|
| 192 |
+
def get_special_tokens_mask(
|
| 193 |
+
self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
|
| 194 |
+
) -> list[int]:
|
| 195 |
+
if already_has_special_tokens:
|
| 196 |
+
return super().get_special_tokens_mask(
|
| 197 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
suffix_ones = [1]
|
| 201 |
+
if token_ids_1 is None:
|
| 202 |
+
return ([0] * len(token_ids_0)) + suffix_ones
|
| 203 |
+
return ([0] * len(token_ids_0)) + ([0] * len(token_ids_1)) + suffix_ones
|
| 204 |
+
|
| 205 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
|
| 206 |
+
if not os.path.isdir(save_directory):
|
| 207 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 208 |
+
return
|
| 209 |
+
out_vocab_file = os.path.join(
|
| 210 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
| 214 |
+
copyfile(self.vocab_file, out_vocab_file)
|
| 215 |
+
elif not os.path.isfile(self.vocab_file):
|
| 216 |
+
with open(out_vocab_file, "wb") as fi:
|
| 217 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
| 218 |
+
fi.write(content_spiece_model)
|
| 219 |
+
|
| 220 |
+
return (out_vocab_file,)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
__all__ = ["SpeechT5Tokenizer"]
|