Add files using upload-large-folder tool
Browse files- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/fsspec-2026.4.0.dist-info/METADATA +257 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/fsspec-2026.4.0.dist-info/REQUESTED +0 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/bart/__init__.py +28 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/bart/configuration_bart.py +86 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/bart/modeling_bart.py +1321 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/bart/tokenization_bart.py +23 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/gptj/__init__.py +27 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mpt/__init__.py +27 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mpt/configuration_mpt.py +150 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/sam2_video/__init__.py +29 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/sam2_video/configuration_sam2_video.py +274 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/sam2_video/modular_sam2_video.py +0 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/sam2_video/processing_sam2_video.py +801 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/sam2_video/video_processing_sam2_video.py +104 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/cache/owt_llmclean_qwen36_35b_articlefull_10k_snapshot_docs24862_shards8/part-000.jsonl +0 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_002000.pt +3 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_008000.pt +3 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_085000.pt +3 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_129000.pt +3 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_152000.pt +3 -0
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/fsspec-2026.4.0.dist-info/METADATA
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: fsspec
|
| 3 |
+
Version: 2026.4.0
|
| 4 |
+
Summary: File-system specification
|
| 5 |
+
Project-URL: Changelog, https://filesystem-spec.readthedocs.io/en/latest/changelog.html
|
| 6 |
+
Project-URL: Documentation, https://filesystem-spec.readthedocs.io/en/latest/
|
| 7 |
+
Project-URL: Homepage, https://github.com/fsspec/filesystem_spec
|
| 8 |
+
Maintainer-email: Martin Durant <mdurant@anaconda.com>
|
| 9 |
+
License-Expression: BSD-3-Clause
|
| 10 |
+
License-File: LICENSE
|
| 11 |
+
Keywords: file
|
| 12 |
+
Classifier: Development Status :: 4 - Beta
|
| 13 |
+
Classifier: Intended Audience :: Developers
|
| 14 |
+
Classifier: Operating System :: OS Independent
|
| 15 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 16 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 17 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 18 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.14
|
| 20 |
+
Requires-Python: >=3.10
|
| 21 |
+
Provides-Extra: abfs
|
| 22 |
+
Requires-Dist: adlfs; extra == 'abfs'
|
| 23 |
+
Provides-Extra: adl
|
| 24 |
+
Requires-Dist: adlfs; extra == 'adl'
|
| 25 |
+
Provides-Extra: arrow
|
| 26 |
+
Requires-Dist: pyarrow>=1; extra == 'arrow'
|
| 27 |
+
Provides-Extra: dask
|
| 28 |
+
Requires-Dist: dask; extra == 'dask'
|
| 29 |
+
Requires-Dist: distributed; extra == 'dask'
|
| 30 |
+
Provides-Extra: dev
|
| 31 |
+
Requires-Dist: pre-commit; extra == 'dev'
|
| 32 |
+
Requires-Dist: ruff>=0.5; extra == 'dev'
|
| 33 |
+
Provides-Extra: doc
|
| 34 |
+
Requires-Dist: numpydoc; extra == 'doc'
|
| 35 |
+
Requires-Dist: sphinx; extra == 'doc'
|
| 36 |
+
Requires-Dist: sphinx-design; extra == 'doc'
|
| 37 |
+
Requires-Dist: sphinx-rtd-theme; extra == 'doc'
|
| 38 |
+
Requires-Dist: yarl; extra == 'doc'
|
| 39 |
+
Provides-Extra: dropbox
|
| 40 |
+
Requires-Dist: dropbox; extra == 'dropbox'
|
| 41 |
+
Requires-Dist: dropboxdrivefs; extra == 'dropbox'
|
| 42 |
+
Requires-Dist: requests; extra == 'dropbox'
|
| 43 |
+
Provides-Extra: entrypoints
|
| 44 |
+
Provides-Extra: full
|
| 45 |
+
Requires-Dist: adlfs; extra == 'full'
|
| 46 |
+
Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'full'
|
| 47 |
+
Requires-Dist: dask; extra == 'full'
|
| 48 |
+
Requires-Dist: distributed; extra == 'full'
|
| 49 |
+
Requires-Dist: dropbox; extra == 'full'
|
| 50 |
+
Requires-Dist: dropboxdrivefs; extra == 'full'
|
| 51 |
+
Requires-Dist: fusepy; extra == 'full'
|
| 52 |
+
Requires-Dist: gcsfs>2024.2.0; extra == 'full'
|
| 53 |
+
Requires-Dist: libarchive-c; extra == 'full'
|
| 54 |
+
Requires-Dist: ocifs; extra == 'full'
|
| 55 |
+
Requires-Dist: panel; extra == 'full'
|
| 56 |
+
Requires-Dist: paramiko; extra == 'full'
|
| 57 |
+
Requires-Dist: pyarrow>=1; extra == 'full'
|
| 58 |
+
Requires-Dist: pygit2; extra == 'full'
|
| 59 |
+
Requires-Dist: requests; extra == 'full'
|
| 60 |
+
Requires-Dist: s3fs>2024.2.0; extra == 'full'
|
| 61 |
+
Requires-Dist: smbprotocol; extra == 'full'
|
| 62 |
+
Requires-Dist: tqdm; extra == 'full'
|
| 63 |
+
Provides-Extra: fuse
|
| 64 |
+
Requires-Dist: fusepy; extra == 'fuse'
|
| 65 |
+
Provides-Extra: gcs
|
| 66 |
+
Requires-Dist: gcsfs>2024.2.0; extra == 'gcs'
|
| 67 |
+
Provides-Extra: git
|
| 68 |
+
Requires-Dist: pygit2; extra == 'git'
|
| 69 |
+
Provides-Extra: github
|
| 70 |
+
Requires-Dist: requests; extra == 'github'
|
| 71 |
+
Provides-Extra: gs
|
| 72 |
+
Requires-Dist: gcsfs; extra == 'gs'
|
| 73 |
+
Provides-Extra: gui
|
| 74 |
+
Requires-Dist: panel; extra == 'gui'
|
| 75 |
+
Provides-Extra: hdfs
|
| 76 |
+
Requires-Dist: pyarrow>=1; extra == 'hdfs'
|
| 77 |
+
Provides-Extra: http
|
| 78 |
+
Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'http'
|
| 79 |
+
Provides-Extra: libarchive
|
| 80 |
+
Requires-Dist: libarchive-c; extra == 'libarchive'
|
| 81 |
+
Provides-Extra: oci
|
| 82 |
+
Requires-Dist: ocifs; extra == 'oci'
|
| 83 |
+
Provides-Extra: s3
|
| 84 |
+
Requires-Dist: s3fs>2024.2.0; extra == 's3'
|
| 85 |
+
Provides-Extra: sftp
|
| 86 |
+
Requires-Dist: paramiko; extra == 'sftp'
|
| 87 |
+
Provides-Extra: smb
|
| 88 |
+
Requires-Dist: smbprotocol; extra == 'smb'
|
| 89 |
+
Provides-Extra: ssh
|
| 90 |
+
Requires-Dist: paramiko; extra == 'ssh'
|
| 91 |
+
Provides-Extra: test
|
| 92 |
+
Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'test'
|
| 93 |
+
Requires-Dist: numpy; extra == 'test'
|
| 94 |
+
Requires-Dist: pytest; extra == 'test'
|
| 95 |
+
Requires-Dist: pytest-asyncio!=0.22.0; extra == 'test'
|
| 96 |
+
Requires-Dist: pytest-benchmark; extra == 'test'
|
| 97 |
+
Requires-Dist: pytest-cov; extra == 'test'
|
| 98 |
+
Requires-Dist: pytest-mock; extra == 'test'
|
| 99 |
+
Requires-Dist: pytest-recording; extra == 'test'
|
| 100 |
+
Requires-Dist: pytest-rerunfailures; extra == 'test'
|
| 101 |
+
Requires-Dist: requests; extra == 'test'
|
| 102 |
+
Provides-Extra: test-downstream
|
| 103 |
+
Requires-Dist: aiobotocore<3.0.0,>=2.5.4; extra == 'test-downstream'
|
| 104 |
+
Requires-Dist: dask[dataframe,test]; extra == 'test-downstream'
|
| 105 |
+
Requires-Dist: moto[server]<5,>4; extra == 'test-downstream'
|
| 106 |
+
Requires-Dist: pytest-timeout; extra == 'test-downstream'
|
| 107 |
+
Requires-Dist: xarray; extra == 'test-downstream'
|
| 108 |
+
Provides-Extra: test-full
|
| 109 |
+
Requires-Dist: adlfs; extra == 'test-full'
|
| 110 |
+
Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'test-full'
|
| 111 |
+
Requires-Dist: backports-zstd; (python_version < '3.14') and extra == 'test-full'
|
| 112 |
+
Requires-Dist: cloudpickle; extra == 'test-full'
|
| 113 |
+
Requires-Dist: dask; extra == 'test-full'
|
| 114 |
+
Requires-Dist: distributed; extra == 'test-full'
|
| 115 |
+
Requires-Dist: dropbox; extra == 'test-full'
|
| 116 |
+
Requires-Dist: dropboxdrivefs; extra == 'test-full'
|
| 117 |
+
Requires-Dist: fastparquet; extra == 'test-full'
|
| 118 |
+
Requires-Dist: fusepy; extra == 'test-full'
|
| 119 |
+
Requires-Dist: gcsfs; extra == 'test-full'
|
| 120 |
+
Requires-Dist: jinja2; extra == 'test-full'
|
| 121 |
+
Requires-Dist: kerchunk; extra == 'test-full'
|
| 122 |
+
Requires-Dist: libarchive-c; extra == 'test-full'
|
| 123 |
+
Requires-Dist: lz4; extra == 'test-full'
|
| 124 |
+
Requires-Dist: notebook; extra == 'test-full'
|
| 125 |
+
Requires-Dist: numpy; extra == 'test-full'
|
| 126 |
+
Requires-Dist: ocifs; extra == 'test-full'
|
| 127 |
+
Requires-Dist: pandas<3.0.0; extra == 'test-full'
|
| 128 |
+
Requires-Dist: panel; extra == 'test-full'
|
| 129 |
+
Requires-Dist: paramiko; extra == 'test-full'
|
| 130 |
+
Requires-Dist: pyarrow; extra == 'test-full'
|
| 131 |
+
Requires-Dist: pyarrow>=1; extra == 'test-full'
|
| 132 |
+
Requires-Dist: pyftpdlib; extra == 'test-full'
|
| 133 |
+
Requires-Dist: pygit2; extra == 'test-full'
|
| 134 |
+
Requires-Dist: pytest; extra == 'test-full'
|
| 135 |
+
Requires-Dist: pytest-asyncio!=0.22.0; extra == 'test-full'
|
| 136 |
+
Requires-Dist: pytest-benchmark; extra == 'test-full'
|
| 137 |
+
Requires-Dist: pytest-cov; extra == 'test-full'
|
| 138 |
+
Requires-Dist: pytest-mock; extra == 'test-full'
|
| 139 |
+
Requires-Dist: pytest-recording; extra == 'test-full'
|
| 140 |
+
Requires-Dist: pytest-rerunfailures; extra == 'test-full'
|
| 141 |
+
Requires-Dist: python-snappy; extra == 'test-full'
|
| 142 |
+
Requires-Dist: requests; extra == 'test-full'
|
| 143 |
+
Requires-Dist: smbprotocol; extra == 'test-full'
|
| 144 |
+
Requires-Dist: tqdm; extra == 'test-full'
|
| 145 |
+
Requires-Dist: urllib3; extra == 'test-full'
|
| 146 |
+
Requires-Dist: zarr; extra == 'test-full'
|
| 147 |
+
Requires-Dist: zstandard; (python_version < '3.14') and extra == 'test-full'
|
| 148 |
+
Provides-Extra: tqdm
|
| 149 |
+
Requires-Dist: tqdm; extra == 'tqdm'
|
| 150 |
+
Description-Content-Type: text/markdown
|
| 151 |
+
|
| 152 |
+
# filesystem_spec
|
| 153 |
+
|
| 154 |
+
[](https://pypi.python.org/pypi/fsspec/)
|
| 155 |
+
[](https://anaconda.org/conda-forge/fsspec)
|
| 156 |
+

|
| 157 |
+
[](https://filesystem-spec.readthedocs.io/en/latest/?badge=latest)
|
| 158 |
+
|
| 159 |
+
A specification for pythonic filesystems.
|
| 160 |
+
|
| 161 |
+
## Install
|
| 162 |
+
|
| 163 |
+
```bash
|
| 164 |
+
pip install fsspec
|
| 165 |
+
```
|
| 166 |
+
|
| 167 |
+
would install the base fsspec. Various optionally supported features might require specification of custom
|
| 168 |
+
extra require, e.g. `pip install fsspec[ssh]` will install dependencies for `ssh` backends support.
|
| 169 |
+
Use `pip install fsspec[full]` for installation of all known extra dependencies.
|
| 170 |
+
|
| 171 |
+
Up-to-date package also provided through conda-forge distribution:
|
| 172 |
+
|
| 173 |
+
```bash
|
| 174 |
+
conda install -c conda-forge fsspec
|
| 175 |
+
```
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
## Purpose
|
| 179 |
+
|
| 180 |
+
To produce a template or specification for a file-system interface, that specific implementations should follow,
|
| 181 |
+
so that applications making use of them can rely on a common behaviour and not have to worry about the specific
|
| 182 |
+
internal implementation decisions with any given backend. Many such implementations are included in this package,
|
| 183 |
+
or in sister projects such as `s3fs` and `gcsfs`.
|
| 184 |
+
|
| 185 |
+
In addition, if this is well-designed, then additional functionality, such as a key-value store or FUSE
|
| 186 |
+
mounting of the file-system implementation may be available for all implementations "for free".
|
| 187 |
+
|
| 188 |
+
## Documentation
|
| 189 |
+
|
| 190 |
+
Please refer to [RTD](https://filesystem-spec.readthedocs.io/en/latest/?badge=latest)
|
| 191 |
+
|
| 192 |
+
## Develop
|
| 193 |
+
|
| 194 |
+
fsspec uses GitHub Actions for CI. Environment files can be found
|
| 195 |
+
in the "ci/" directory. Note that the main environment is called "py38",
|
| 196 |
+
but it is expected that the version of python installed be adjustable at
|
| 197 |
+
CI runtime. For local use, pick a version suitable for you.
|
| 198 |
+
|
| 199 |
+
```bash
|
| 200 |
+
# For a new environment (mamba / conda).
|
| 201 |
+
mamba create -n fsspec -c conda-forge python=3.10 -y
|
| 202 |
+
conda activate fsspec
|
| 203 |
+
|
| 204 |
+
# Standard dev install with docs and tests.
|
| 205 |
+
pip install -e ".[dev,doc,test]"
|
| 206 |
+
|
| 207 |
+
# Full tests except for downstream
|
| 208 |
+
pip install s3fs
|
| 209 |
+
pip uninstall s3fs
|
| 210 |
+
pip install -e .[dev,doc,test_full]
|
| 211 |
+
pip install s3fs --no-deps
|
| 212 |
+
pytest -v
|
| 213 |
+
|
| 214 |
+
# Downstream tests.
|
| 215 |
+
sh install_s3fs.sh
|
| 216 |
+
# Windows powershell.
|
| 217 |
+
install_s3fs.sh
|
| 218 |
+
```
|
| 219 |
+
|
| 220 |
+
### Testing
|
| 221 |
+
|
| 222 |
+
Tests can be run in the dev environment, if activated, via ``pytest fsspec``.
|
| 223 |
+
|
| 224 |
+
The full fsspec suite requires a system-level docker, docker-compose, and fuse
|
| 225 |
+
installation. If only making changes to one backend implementation, it is
|
| 226 |
+
not generally necessary to run all tests locally.
|
| 227 |
+
|
| 228 |
+
It is expected that contributors ensure that any change to fsspec does not
|
| 229 |
+
cause issues or regressions for either other fsspec-related packages such
|
| 230 |
+
as gcsfs and s3fs, nor for downstream users of fsspec. The "downstream" CI
|
| 231 |
+
run and corresponding environment file run a set of tests from the dask
|
| 232 |
+
test suite, and very minimal tests against pandas and zarr from the
|
| 233 |
+
test_downstream.py module in this repo.
|
| 234 |
+
|
| 235 |
+
### Code Formatting
|
| 236 |
+
|
| 237 |
+
fsspec uses [Black](https://black.readthedocs.io/en/stable) to ensure
|
| 238 |
+
a consistent code format throughout the project.
|
| 239 |
+
Run ``black fsspec`` from the root of the filesystem_spec repository to
|
| 240 |
+
auto-format your code. Additionally, many editors have plugins that will apply
|
| 241 |
+
``black`` as you edit files. ``black`` is included in the ``tox`` environments.
|
| 242 |
+
|
| 243 |
+
Optionally, you may wish to setup [pre-commit hooks](https://pre-commit.com) to
|
| 244 |
+
automatically run ``black`` when you make a git commit.
|
| 245 |
+
Run ``pre-commit install --install-hooks`` from the root of the
|
| 246 |
+
filesystem_spec repository to setup pre-commit hooks. ``black`` will now be run
|
| 247 |
+
before you commit, reformatting any changed files. You can format without
|
| 248 |
+
committing via ``pre-commit run`` or skip these checks with ``git commit
|
| 249 |
+
--no-verify``.
|
| 250 |
+
|
| 251 |
+
## Support
|
| 252 |
+
|
| 253 |
+
Work on this repository is supported in part by:
|
| 254 |
+
|
| 255 |
+
"Anaconda, Inc. - Advancing AI through open source."
|
| 256 |
+
|
| 257 |
+
<a href="https://anaconda.com/"><img src="https://camo.githubusercontent.com/b8555ef2222598ed37ce38ac86955febbd25de7619931bb7dd3c58432181d3b6/68747470733a2f2f626565776172652e6f72672f636f6d6d756e6974792f6d656d626572732f616e61636f6e64612f616e61636f6e64612d6c617267652e706e67" alt="anaconda logo" width="40%"/></a>
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/fsspec-2026.4.0.dist-info/REQUESTED
ADDED
|
File without changes
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/bart/__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 ..roberta.tokenization_roberta import RobertaTokenizer as BartTokenizer
|
| 22 |
+
from .configuration_bart import *
|
| 23 |
+
from .modeling_bart 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__)
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/bart/configuration_bart.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""BART model configuration"""
|
| 15 |
+
|
| 16 |
+
from huggingface_hub.dataclasses import strict
|
| 17 |
+
|
| 18 |
+
from ...configuration_utils import PreTrainedConfig
|
| 19 |
+
from ...utils import auto_docstring
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@auto_docstring(checkpoint="facebook/bart-large")
|
| 23 |
+
@strict
|
| 24 |
+
class BartConfig(PreTrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
Example:
|
| 27 |
+
|
| 28 |
+
```python
|
| 29 |
+
>>> from transformers import BartConfig, BartModel
|
| 30 |
+
|
| 31 |
+
>>> # Initializing a BART facebook/bart-large style configuration
|
| 32 |
+
>>> configuration = BartConfig()
|
| 33 |
+
|
| 34 |
+
>>> # Initializing a model (with random weights) from the facebook/bart-large style configuration
|
| 35 |
+
>>> model = BartModel(configuration)
|
| 36 |
+
|
| 37 |
+
>>> # Accessing the model configuration
|
| 38 |
+
>>> configuration = model.config
|
| 39 |
+
```"""
|
| 40 |
+
|
| 41 |
+
model_type = "bart"
|
| 42 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 43 |
+
attribute_map = {
|
| 44 |
+
"num_attention_heads": "encoder_attention_heads",
|
| 45 |
+
"hidden_size": "d_model",
|
| 46 |
+
"num_hidden_layers": "encoder_layers",
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
vocab_size: int = 50265
|
| 50 |
+
max_position_embeddings: int = 1024
|
| 51 |
+
encoder_layers: int | None = 12
|
| 52 |
+
encoder_ffn_dim: int | None = 4096
|
| 53 |
+
encoder_attention_heads: int | None = 16
|
| 54 |
+
decoder_layers: int | None = 12
|
| 55 |
+
decoder_ffn_dim: int | None = 4096
|
| 56 |
+
decoder_attention_heads: int | None = 16
|
| 57 |
+
encoder_layerdrop: float | None = 0.0
|
| 58 |
+
decoder_layerdrop: float | None = 0.0
|
| 59 |
+
activation_function: str | None = "gelu"
|
| 60 |
+
d_model: int | None = 1024
|
| 61 |
+
dropout: float | int | None = 0.1
|
| 62 |
+
attention_dropout: float | int | None = 0.0
|
| 63 |
+
activation_dropout: float | int | None = 0.0
|
| 64 |
+
init_std: float | None = 0.02
|
| 65 |
+
classifier_dropout: float | int | None = 0.0
|
| 66 |
+
scale_embedding: bool | None = False
|
| 67 |
+
use_cache: bool = True
|
| 68 |
+
pad_token_id: int | None = 1
|
| 69 |
+
bos_token_id: int | None = 0
|
| 70 |
+
eos_token_id: int | list[int] | None = 2
|
| 71 |
+
is_encoder_decoder: bool | None = True
|
| 72 |
+
decoder_start_token_id: int | None = 2
|
| 73 |
+
forced_eos_token_id: int | list[int] | None = 2
|
| 74 |
+
is_decoder: bool | None = False
|
| 75 |
+
tie_word_embeddings: bool = True
|
| 76 |
+
|
| 77 |
+
def __post_init__(self, **kwargs):
|
| 78 |
+
# Set the default `num_labels` only if `id2label` is not
|
| 79 |
+
# yet set, i.e. user didn't pass `id2label/lable2id` in kwargs
|
| 80 |
+
if self.id2label is None:
|
| 81 |
+
self.num_labels = kwargs.pop("num_labels", 3)
|
| 82 |
+
|
| 83 |
+
super().__post_init__(**kwargs)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
__all__ = ["BartConfig"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/bart/modeling_bart.py
ADDED
|
@@ -0,0 +1,1321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""PyTorch BART model."""
|
| 15 |
+
|
| 16 |
+
import math
|
| 17 |
+
import warnings
|
| 18 |
+
from collections.abc import Callable
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
from torch import nn
|
| 22 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 23 |
+
|
| 24 |
+
from ... import initialization as init
|
| 25 |
+
from ...activations import ACT2FN
|
| 26 |
+
from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
|
| 27 |
+
from ...generation import GenerationMixin
|
| 28 |
+
from ...masking_utils import create_bidirectional_mask, create_causal_mask
|
| 29 |
+
from ...modeling_flash_attention_utils import FlashAttentionKwargs
|
| 30 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 31 |
+
from ...modeling_outputs import (
|
| 32 |
+
BaseModelOutput,
|
| 33 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 34 |
+
CausalLMOutputWithCrossAttentions,
|
| 35 |
+
Seq2SeqLMOutput,
|
| 36 |
+
Seq2SeqModelOutput,
|
| 37 |
+
Seq2SeqQuestionAnsweringModelOutput,
|
| 38 |
+
Seq2SeqSequenceClassifierOutput,
|
| 39 |
+
)
|
| 40 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 41 |
+
from ...processing_utils import Unpack
|
| 42 |
+
from ...utils import (
|
| 43 |
+
TransformersKwargs,
|
| 44 |
+
auto_docstring,
|
| 45 |
+
can_return_tuple,
|
| 46 |
+
is_torchdynamo_compiling,
|
| 47 |
+
logging,
|
| 48 |
+
torch_compilable_check,
|
| 49 |
+
)
|
| 50 |
+
from ...utils.generic import merge_with_config_defaults
|
| 51 |
+
from ...utils.output_capturing import OutputRecorder, capture_outputs
|
| 52 |
+
from .configuration_bart import BartConfig
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
logger = logging.get_logger(__name__)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
|
| 59 |
+
"""
|
| 60 |
+
Shift input ids one token to the right.
|
| 61 |
+
"""
|
| 62 |
+
shifted_input_ids = input_ids.new_zeros(input_ids.shape)
|
| 63 |
+
shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
|
| 64 |
+
shifted_input_ids[:, 0] = decoder_start_token_id
|
| 65 |
+
|
| 66 |
+
if pad_token_id is None:
|
| 67 |
+
raise ValueError("self.model.config.pad_token_id has to be defined.")
|
| 68 |
+
# replace possible -100 values in labels by `pad_token_id`
|
| 69 |
+
shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
|
| 70 |
+
|
| 71 |
+
return shifted_input_ids
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class BartLearnedPositionalEmbedding(nn.Embedding):
|
| 75 |
+
"""
|
| 76 |
+
This module learns positional embeddings up to a fixed maximum size.
|
| 77 |
+
"""
|
| 78 |
+
|
| 79 |
+
def __init__(self, num_embeddings: int, embedding_dim: int):
|
| 80 |
+
# Bart is set up so that if padding_idx is specified then offset the embedding ids by 2
|
| 81 |
+
# and adjust num_embeddings appropriately. Other models don't have this hack
|
| 82 |
+
self.offset = 2
|
| 83 |
+
super().__init__(num_embeddings + self.offset, embedding_dim)
|
| 84 |
+
|
| 85 |
+
def forward(
|
| 86 |
+
self, input_ids: torch.Tensor, past_key_values_length: int = 0, position_ids: torch.Tensor | None = None
|
| 87 |
+
):
|
| 88 |
+
"""`input_ids' shape is expected to be [bsz x seqlen]."""
|
| 89 |
+
|
| 90 |
+
if position_ids is None:
|
| 91 |
+
bsz, seq_len = input_ids.shape[:2]
|
| 92 |
+
position_ids = torch.arange(
|
| 93 |
+
past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device
|
| 94 |
+
).expand(bsz, -1)
|
| 95 |
+
else:
|
| 96 |
+
position_ids = position_ids.unsqueeze(0)
|
| 97 |
+
|
| 98 |
+
return super().forward(position_ids + self.offset)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class BartScaledWordEmbedding(nn.Embedding):
|
| 102 |
+
"""
|
| 103 |
+
This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: float | None = 1.0):
|
| 107 |
+
super().__init__(num_embeddings, embedding_dim, padding_idx)
|
| 108 |
+
self.embed_scale = embed_scale
|
| 109 |
+
|
| 110 |
+
def forward(self, input_ids: torch.Tensor):
|
| 111 |
+
return super().forward(input_ids) * self.embed_scale
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
# Copied from transformers.models.bert.modeling_bert.eager_attention_forward
|
| 115 |
+
def eager_attention_forward(
|
| 116 |
+
module: nn.Module,
|
| 117 |
+
query: torch.Tensor,
|
| 118 |
+
key: torch.Tensor,
|
| 119 |
+
value: torch.Tensor,
|
| 120 |
+
attention_mask: torch.Tensor | None,
|
| 121 |
+
scaling: float | None = None,
|
| 122 |
+
dropout: float = 0.0,
|
| 123 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 124 |
+
):
|
| 125 |
+
if scaling is None:
|
| 126 |
+
scaling = query.size(-1) ** -0.5
|
| 127 |
+
|
| 128 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 129 |
+
attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
|
| 130 |
+
|
| 131 |
+
if attention_mask is not None:
|
| 132 |
+
attn_weights = attn_weights + attention_mask
|
| 133 |
+
|
| 134 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 135 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 136 |
+
|
| 137 |
+
attn_output = torch.matmul(attn_weights, value)
|
| 138 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 139 |
+
|
| 140 |
+
return attn_output, attn_weights
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class BartAttention(nn.Module):
|
| 144 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 145 |
+
|
| 146 |
+
def __init__(
|
| 147 |
+
self,
|
| 148 |
+
embed_dim: int,
|
| 149 |
+
num_heads: int,
|
| 150 |
+
dropout: float = 0.0,
|
| 151 |
+
is_decoder: bool = False,
|
| 152 |
+
bias: bool = True,
|
| 153 |
+
is_causal: bool = False,
|
| 154 |
+
config: BartConfig | None = None,
|
| 155 |
+
layer_idx: int | None = None,
|
| 156 |
+
):
|
| 157 |
+
super().__init__()
|
| 158 |
+
self.embed_dim = embed_dim
|
| 159 |
+
self.num_heads = num_heads
|
| 160 |
+
self.dropout = dropout
|
| 161 |
+
self.head_dim = embed_dim // num_heads
|
| 162 |
+
self.config = config
|
| 163 |
+
|
| 164 |
+
if (self.head_dim * num_heads) != self.embed_dim:
|
| 165 |
+
raise ValueError(
|
| 166 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
|
| 167 |
+
f" and `num_heads`: {num_heads})."
|
| 168 |
+
)
|
| 169 |
+
self.scaling = self.head_dim**-0.5
|
| 170 |
+
self.is_decoder = is_decoder
|
| 171 |
+
self.is_causal = is_causal
|
| 172 |
+
self.layer_idx = layer_idx
|
| 173 |
+
if layer_idx is None and self.is_decoder:
|
| 174 |
+
logger.warning_once(
|
| 175 |
+
f"Instantiating a decoder {self.__class__.__name__} without passing `layer_idx` is not recommended and "
|
| 176 |
+
"will lead to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
| 177 |
+
"when creating this class."
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 181 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 182 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 183 |
+
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 184 |
+
|
| 185 |
+
def forward(
|
| 186 |
+
self,
|
| 187 |
+
hidden_states: torch.Tensor,
|
| 188 |
+
key_value_states: torch.Tensor | None = None,
|
| 189 |
+
past_key_values: Cache | None = None,
|
| 190 |
+
attention_mask: torch.Tensor | None = None,
|
| 191 |
+
# TODO: we need a refactor so that the different attention modules can get their specific kwargs
|
| 192 |
+
# ATM, we have mixed things encoder, decoder, and encoder-decoder attn
|
| 193 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 194 |
+
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
| 195 |
+
"""Input shape: Batch x Time x Channel"""
|
| 196 |
+
|
| 197 |
+
# if key_value_states are provided this layer is used as a cross-attention layer
|
| 198 |
+
# for the decoder
|
| 199 |
+
is_cross_attention = key_value_states is not None
|
| 200 |
+
|
| 201 |
+
# determine input shapes
|
| 202 |
+
input_shape = hidden_states.shape[:-1]
|
| 203 |
+
|
| 204 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 205 |
+
|
| 206 |
+
# get query proj
|
| 207 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 208 |
+
|
| 209 |
+
is_updated = False
|
| 210 |
+
if past_key_values is not None:
|
| 211 |
+
if isinstance(past_key_values, EncoderDecoderCache):
|
| 212 |
+
is_updated = past_key_values.is_updated.get(self.layer_idx)
|
| 213 |
+
if is_cross_attention:
|
| 214 |
+
# after the first generated id, we can subsequently re-use all key/value_states from cache
|
| 215 |
+
curr_past_key_values = past_key_values.cross_attention_cache
|
| 216 |
+
else:
|
| 217 |
+
curr_past_key_values = past_key_values.self_attention_cache
|
| 218 |
+
else:
|
| 219 |
+
curr_past_key_values = past_key_values
|
| 220 |
+
|
| 221 |
+
current_states = key_value_states if is_cross_attention else hidden_states
|
| 222 |
+
if is_cross_attention and past_key_values is not None and is_updated:
|
| 223 |
+
# reuse k,v, cross_attentions
|
| 224 |
+
key_states = curr_past_key_values.layers[self.layer_idx].keys
|
| 225 |
+
value_states = curr_past_key_values.layers[self.layer_idx].values
|
| 226 |
+
else:
|
| 227 |
+
key_states = self.k_proj(current_states)
|
| 228 |
+
value_states = self.v_proj(current_states)
|
| 229 |
+
kv_shape = (*current_states.shape[:-1], -1, self.head_dim)
|
| 230 |
+
key_states = key_states.view(kv_shape).transpose(1, 2)
|
| 231 |
+
value_states = value_states.view(kv_shape).transpose(1, 2)
|
| 232 |
+
|
| 233 |
+
if past_key_values is not None:
|
| 234 |
+
key_states, value_states = curr_past_key_values.update(key_states, value_states, self.layer_idx)
|
| 235 |
+
# set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
|
| 236 |
+
if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
|
| 237 |
+
past_key_values.is_updated[self.layer_idx] = True
|
| 238 |
+
|
| 239 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 240 |
+
self.config._attn_implementation, eager_attention_forward
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
attn_output, attn_weights = attention_interface(
|
| 244 |
+
self,
|
| 245 |
+
query_states,
|
| 246 |
+
key_states,
|
| 247 |
+
value_states,
|
| 248 |
+
attention_mask,
|
| 249 |
+
dropout=0.0 if not self.training else self.dropout,
|
| 250 |
+
scaling=self.scaling,
|
| 251 |
+
**kwargs,
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 255 |
+
attn_output = self.out_proj(attn_output)
|
| 256 |
+
|
| 257 |
+
return attn_output, attn_weights
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
class BartEncoderLayer(GradientCheckpointingLayer):
|
| 261 |
+
def __init__(self, config: BartConfig, layer_idx: int | None = None):
|
| 262 |
+
super().__init__()
|
| 263 |
+
self.embed_dim = config.d_model
|
| 264 |
+
|
| 265 |
+
self.self_attn = BartAttention(
|
| 266 |
+
embed_dim=self.embed_dim,
|
| 267 |
+
num_heads=config.encoder_attention_heads,
|
| 268 |
+
dropout=config.attention_dropout,
|
| 269 |
+
config=config,
|
| 270 |
+
layer_idx=layer_idx,
|
| 271 |
+
)
|
| 272 |
+
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 273 |
+
self.dropout = config.dropout
|
| 274 |
+
self.activation_fn = ACT2FN[config.activation_function]
|
| 275 |
+
self.activation_dropout = config.activation_dropout
|
| 276 |
+
self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
|
| 277 |
+
self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
|
| 278 |
+
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 279 |
+
|
| 280 |
+
def forward(
|
| 281 |
+
self,
|
| 282 |
+
hidden_states: torch.FloatTensor,
|
| 283 |
+
attention_mask: torch.FloatTensor,
|
| 284 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 285 |
+
) -> torch.Tensor:
|
| 286 |
+
residual = hidden_states
|
| 287 |
+
hidden_states, _ = self.self_attn(
|
| 288 |
+
hidden_states,
|
| 289 |
+
attention_mask=attention_mask,
|
| 290 |
+
**kwargs,
|
| 291 |
+
)
|
| 292 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 293 |
+
hidden_states = residual + hidden_states
|
| 294 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 295 |
+
|
| 296 |
+
residual = hidden_states
|
| 297 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 298 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
|
| 299 |
+
hidden_states = self.fc2(hidden_states)
|
| 300 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 301 |
+
hidden_states = residual + hidden_states
|
| 302 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 303 |
+
|
| 304 |
+
if hidden_states.dtype == torch.float16 and not torch.isfinite(hidden_states).all():
|
| 305 |
+
clamp_value = torch.finfo(hidden_states.dtype).max - 1000
|
| 306 |
+
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
|
| 307 |
+
|
| 308 |
+
return hidden_states
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
class BartDecoderLayer(GradientCheckpointingLayer):
|
| 312 |
+
def __init__(self, config: BartConfig, layer_idx: int | None = None):
|
| 313 |
+
super().__init__()
|
| 314 |
+
self.embed_dim = config.d_model
|
| 315 |
+
|
| 316 |
+
self.self_attn = BartAttention(
|
| 317 |
+
embed_dim=self.embed_dim,
|
| 318 |
+
num_heads=config.decoder_attention_heads,
|
| 319 |
+
dropout=config.attention_dropout,
|
| 320 |
+
is_decoder=True,
|
| 321 |
+
is_causal=True,
|
| 322 |
+
config=config,
|
| 323 |
+
layer_idx=layer_idx,
|
| 324 |
+
)
|
| 325 |
+
self.dropout = config.dropout
|
| 326 |
+
self.activation_fn = ACT2FN[config.activation_function]
|
| 327 |
+
self.activation_dropout = config.activation_dropout
|
| 328 |
+
|
| 329 |
+
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 330 |
+
self.encoder_attn = BartAttention(
|
| 331 |
+
self.embed_dim,
|
| 332 |
+
config.decoder_attention_heads,
|
| 333 |
+
dropout=config.attention_dropout,
|
| 334 |
+
is_decoder=True,
|
| 335 |
+
config=config,
|
| 336 |
+
layer_idx=layer_idx,
|
| 337 |
+
)
|
| 338 |
+
self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 339 |
+
self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
|
| 340 |
+
self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
|
| 341 |
+
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 342 |
+
|
| 343 |
+
def forward(
|
| 344 |
+
self,
|
| 345 |
+
hidden_states: torch.Tensor,
|
| 346 |
+
attention_mask: torch.Tensor | None = None,
|
| 347 |
+
encoder_hidden_states: torch.Tensor | None = None,
|
| 348 |
+
encoder_attention_mask: torch.Tensor | None = None,
|
| 349 |
+
past_key_values: Cache | None = None,
|
| 350 |
+
use_cache: bool | None = True,
|
| 351 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 352 |
+
) -> torch.Tensor:
|
| 353 |
+
residual = hidden_states
|
| 354 |
+
|
| 355 |
+
# Self Attention
|
| 356 |
+
hidden_states, _ = self.self_attn(
|
| 357 |
+
hidden_states,
|
| 358 |
+
past_key_values=past_key_values,
|
| 359 |
+
attention_mask=attention_mask,
|
| 360 |
+
**kwargs,
|
| 361 |
+
)
|
| 362 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 363 |
+
hidden_states = residual + hidden_states
|
| 364 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 365 |
+
|
| 366 |
+
# Cross-Attention Block
|
| 367 |
+
if encoder_hidden_states is not None:
|
| 368 |
+
residual = hidden_states
|
| 369 |
+
|
| 370 |
+
hidden_states, _ = self.encoder_attn(
|
| 371 |
+
hidden_states,
|
| 372 |
+
key_value_states=encoder_hidden_states,
|
| 373 |
+
attention_mask=encoder_attention_mask,
|
| 374 |
+
past_key_values=past_key_values,
|
| 375 |
+
**kwargs,
|
| 376 |
+
)
|
| 377 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 378 |
+
hidden_states = residual + hidden_states
|
| 379 |
+
hidden_states = self.encoder_attn_layer_norm(hidden_states)
|
| 380 |
+
|
| 381 |
+
# Fully Connected
|
| 382 |
+
residual = hidden_states
|
| 383 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 384 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
|
| 385 |
+
hidden_states = self.fc2(hidden_states)
|
| 386 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 387 |
+
hidden_states = residual + hidden_states
|
| 388 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 389 |
+
|
| 390 |
+
return hidden_states
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
class BartClassificationHead(nn.Module):
|
| 394 |
+
"""Head for sentence-level classification tasks."""
|
| 395 |
+
|
| 396 |
+
def __init__(
|
| 397 |
+
self,
|
| 398 |
+
input_dim: int,
|
| 399 |
+
inner_dim: int,
|
| 400 |
+
num_classes: int,
|
| 401 |
+
pooler_dropout: float,
|
| 402 |
+
):
|
| 403 |
+
super().__init__()
|
| 404 |
+
self.dense = nn.Linear(input_dim, inner_dim)
|
| 405 |
+
self.dropout = nn.Dropout(p=pooler_dropout)
|
| 406 |
+
self.out_proj = nn.Linear(inner_dim, num_classes)
|
| 407 |
+
|
| 408 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 409 |
+
hidden_states = self.dropout(hidden_states)
|
| 410 |
+
hidden_states = self.dense(hidden_states)
|
| 411 |
+
hidden_states = torch.tanh(hidden_states)
|
| 412 |
+
hidden_states = self.dropout(hidden_states)
|
| 413 |
+
hidden_states = self.out_proj(hidden_states)
|
| 414 |
+
return hidden_states
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
@auto_docstring
|
| 418 |
+
class BartPreTrainedModel(PreTrainedModel):
|
| 419 |
+
config: BartConfig
|
| 420 |
+
base_model_prefix = "model"
|
| 421 |
+
supports_gradient_checkpointing = True
|
| 422 |
+
_keys_to_ignore_on_load_unexpected = ["encoder.version", "decoder.version"]
|
| 423 |
+
_no_split_modules = [r"BartEncoderLayer", r"BartDecoderLayer"]
|
| 424 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 425 |
+
_supports_flash_attn = True
|
| 426 |
+
_supports_sdpa = True
|
| 427 |
+
_supports_flex_attn = True
|
| 428 |
+
|
| 429 |
+
_can_compile_fullgraph = True
|
| 430 |
+
|
| 431 |
+
def _init_weights(self, module):
|
| 432 |
+
super()._init_weights(module)
|
| 433 |
+
if isinstance(module, BartForConditionalGeneration):
|
| 434 |
+
init.zeros_(module.final_logits_bias)
|
| 435 |
+
|
| 436 |
+
@property
|
| 437 |
+
def dummy_inputs(self):
|
| 438 |
+
pad_token = self.config.pad_token_id
|
| 439 |
+
input_ids = torch.tensor([[0, 6, 10, 4, 2], [0, 8, 12, 2, pad_token]], device=self.device)
|
| 440 |
+
dummy_inputs = {
|
| 441 |
+
"attention_mask": input_ids.ne(pad_token),
|
| 442 |
+
"input_ids": input_ids,
|
| 443 |
+
}
|
| 444 |
+
return dummy_inputs
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
class PretrainedBartModel(BartPreTrainedModel):
|
| 448 |
+
def __init_subclass__(self):
|
| 449 |
+
warnings.warn(
|
| 450 |
+
"The class `PretrainedBartModel` has been depreciated, please use `BartPreTrainedModel` instead.",
|
| 451 |
+
FutureWarning,
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
class BartPretrainedModel(BartPreTrainedModel):
|
| 456 |
+
def __init_subclass__(self):
|
| 457 |
+
warnings.warn(
|
| 458 |
+
"The class `PretrainedBartModel` has been depreciated, please use `BartPreTrainedModel` instead.",
|
| 459 |
+
FutureWarning,
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
class BartEncoder(BartPreTrainedModel):
|
| 464 |
+
"""
|
| 465 |
+
Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
|
| 466 |
+
[`BartEncoderLayer`].
|
| 467 |
+
|
| 468 |
+
Args:
|
| 469 |
+
config: BartConfig
|
| 470 |
+
embed_tokens (nn.Embedding): output embedding
|
| 471 |
+
"""
|
| 472 |
+
|
| 473 |
+
_can_record_outputs = {
|
| 474 |
+
"hidden_states": BartEncoderLayer,
|
| 475 |
+
"attentions": BartAttention,
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
def __init__(self, config: BartConfig):
|
| 479 |
+
super().__init__(config)
|
| 480 |
+
|
| 481 |
+
self.dropout = config.dropout
|
| 482 |
+
self.layerdrop = config.encoder_layerdrop
|
| 483 |
+
|
| 484 |
+
embed_dim = config.d_model
|
| 485 |
+
self.padding_idx = config.pad_token_id
|
| 486 |
+
self.max_source_positions = config.max_position_embeddings
|
| 487 |
+
embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
|
| 488 |
+
|
| 489 |
+
self.embed_tokens = BartScaledWordEmbedding(
|
| 490 |
+
config.vocab_size, embed_dim, self.padding_idx, embed_scale=embed_scale
|
| 491 |
+
)
|
| 492 |
+
|
| 493 |
+
self.embed_positions = BartLearnedPositionalEmbedding(
|
| 494 |
+
config.max_position_embeddings,
|
| 495 |
+
embed_dim,
|
| 496 |
+
)
|
| 497 |
+
self.layers = nn.ModuleList([BartEncoderLayer(config, layer_idx=i) for i in range(config.encoder_layers)])
|
| 498 |
+
self.layernorm_embedding = nn.LayerNorm(embed_dim)
|
| 499 |
+
|
| 500 |
+
self.gradient_checkpointing = False
|
| 501 |
+
# Initialize weights and apply final processing
|
| 502 |
+
self.post_init()
|
| 503 |
+
|
| 504 |
+
@merge_with_config_defaults
|
| 505 |
+
@capture_outputs
|
| 506 |
+
@auto_docstring
|
| 507 |
+
def forward(
|
| 508 |
+
self,
|
| 509 |
+
input_ids: torch.LongTensor | None = None,
|
| 510 |
+
attention_mask: torch.Tensor | None = None,
|
| 511 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 512 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 513 |
+
) -> BaseModelOutput:
|
| 514 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 515 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 516 |
+
|
| 517 |
+
if inputs_embeds is None:
|
| 518 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 519 |
+
|
| 520 |
+
embed_pos = self.embed_positions(inputs_embeds[:, :, -1]) # needed for the shape only
|
| 521 |
+
embed_pos = embed_pos.to(inputs_embeds.device)
|
| 522 |
+
|
| 523 |
+
hidden_states = inputs_embeds + embed_pos
|
| 524 |
+
hidden_states = self.layernorm_embedding(hidden_states)
|
| 525 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 526 |
+
|
| 527 |
+
attention_mask = create_bidirectional_mask(
|
| 528 |
+
config=self.config,
|
| 529 |
+
inputs_embeds=inputs_embeds,
|
| 530 |
+
attention_mask=attention_mask,
|
| 531 |
+
)
|
| 532 |
+
for idx, encoder_layer in enumerate(self.layers):
|
| 533 |
+
# add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
|
| 534 |
+
to_drop = False
|
| 535 |
+
if self.training:
|
| 536 |
+
dropout_probability = torch.rand([])
|
| 537 |
+
if dropout_probability < self.layerdrop: # skip the layer
|
| 538 |
+
to_drop = True
|
| 539 |
+
|
| 540 |
+
if not to_drop:
|
| 541 |
+
hidden_states = encoder_layer(
|
| 542 |
+
hidden_states,
|
| 543 |
+
attention_mask,
|
| 544 |
+
**kwargs,
|
| 545 |
+
)
|
| 546 |
+
|
| 547 |
+
return BaseModelOutput(
|
| 548 |
+
last_hidden_state=hidden_states,
|
| 549 |
+
)
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
class BartDecoder(BartPreTrainedModel):
|
| 553 |
+
"""
|
| 554 |
+
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`BartDecoderLayer`]
|
| 555 |
+
|
| 556 |
+
Args:
|
| 557 |
+
config: BartConfig
|
| 558 |
+
embed_tokens (nn.Embedding): output embedding
|
| 559 |
+
"""
|
| 560 |
+
|
| 561 |
+
_can_record_outputs = {
|
| 562 |
+
"hidden_states": BartDecoderLayer,
|
| 563 |
+
"attentions": OutputRecorder(BartAttention, index=1, layer_name="self_attn"),
|
| 564 |
+
"cross_attentions": OutputRecorder(BartAttention, index=1, layer_name="encoder_attn"),
|
| 565 |
+
}
|
| 566 |
+
|
| 567 |
+
def __init__(self, config: BartConfig):
|
| 568 |
+
super().__init__(config)
|
| 569 |
+
self.dropout = config.dropout
|
| 570 |
+
self.layerdrop = config.decoder_layerdrop
|
| 571 |
+
self.padding_idx = config.pad_token_id
|
| 572 |
+
self.max_target_positions = config.max_position_embeddings
|
| 573 |
+
embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
|
| 574 |
+
|
| 575 |
+
self.embed_tokens = BartScaledWordEmbedding(
|
| 576 |
+
config.vocab_size, config.d_model, self.padding_idx, embed_scale=embed_scale
|
| 577 |
+
)
|
| 578 |
+
|
| 579 |
+
self.embed_positions = BartLearnedPositionalEmbedding(
|
| 580 |
+
config.max_position_embeddings,
|
| 581 |
+
config.d_model,
|
| 582 |
+
)
|
| 583 |
+
self.layers = nn.ModuleList([BartDecoderLayer(config, layer_idx=i) for i in range(config.decoder_layers)])
|
| 584 |
+
|
| 585 |
+
self.layernorm_embedding = nn.LayerNorm(config.d_model)
|
| 586 |
+
|
| 587 |
+
self.gradient_checkpointing = False
|
| 588 |
+
# Initialize weights and apply final processing
|
| 589 |
+
self.post_init()
|
| 590 |
+
|
| 591 |
+
@merge_with_config_defaults
|
| 592 |
+
@capture_outputs
|
| 593 |
+
@auto_docstring
|
| 594 |
+
def forward(
|
| 595 |
+
self,
|
| 596 |
+
input_ids: torch.LongTensor | None = None,
|
| 597 |
+
attention_mask: torch.Tensor | None = None,
|
| 598 |
+
encoder_hidden_states: torch.FloatTensor | None = None,
|
| 599 |
+
encoder_attention_mask: torch.LongTensor | None = None,
|
| 600 |
+
past_key_values: Cache | None = None,
|
| 601 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 602 |
+
use_cache: bool | None = None,
|
| 603 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 604 |
+
) -> BaseModelOutputWithPastAndCrossAttentions:
|
| 605 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 606 |
+
raise ValueError("You must specify exactly one of decoder_input_ids or decoder_inputs_embeds")
|
| 607 |
+
|
| 608 |
+
if inputs_embeds is None:
|
| 609 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 610 |
+
|
| 611 |
+
# initialize `past_key_values`
|
| 612 |
+
if use_cache and past_key_values is None:
|
| 613 |
+
past_key_values = (
|
| 614 |
+
EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
|
| 615 |
+
if encoder_hidden_states is not None or self.config.is_encoder_decoder
|
| 616 |
+
else DynamicCache(config=self.config)
|
| 617 |
+
)
|
| 618 |
+
|
| 619 |
+
batch_size, seq_length = inputs_embeds.size()[:-1]
|
| 620 |
+
past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 621 |
+
position_ids = torch.arange(seq_length, device=inputs_embeds.device) + past_key_values_length
|
| 622 |
+
|
| 623 |
+
if attention_mask is None and not is_torchdynamo_compiling():
|
| 624 |
+
# required mask seq length can be calculated via length of past cache
|
| 625 |
+
mask_seq_length = past_key_values_length + seq_length
|
| 626 |
+
attention_mask = torch.ones(batch_size, mask_seq_length, device=inputs_embeds.device)
|
| 627 |
+
|
| 628 |
+
self_attn_cache = (
|
| 629 |
+
past_key_values.self_attention_cache
|
| 630 |
+
if isinstance(past_key_values, EncoderDecoderCache)
|
| 631 |
+
else past_key_values
|
| 632 |
+
)
|
| 633 |
+
|
| 634 |
+
attention_mask = create_causal_mask(
|
| 635 |
+
config=self.config,
|
| 636 |
+
inputs_embeds=inputs_embeds,
|
| 637 |
+
attention_mask=attention_mask,
|
| 638 |
+
past_key_values=self_attn_cache,
|
| 639 |
+
)
|
| 640 |
+
encoder_attention_mask = create_bidirectional_mask(
|
| 641 |
+
config=self.config,
|
| 642 |
+
inputs_embeds=inputs_embeds,
|
| 643 |
+
attention_mask=encoder_attention_mask,
|
| 644 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 645 |
+
)
|
| 646 |
+
|
| 647 |
+
# embed positions
|
| 648 |
+
positions = self.embed_positions(input_ids, past_key_values_length, position_ids=position_ids)
|
| 649 |
+
positions = positions.to(inputs_embeds.device)
|
| 650 |
+
|
| 651 |
+
hidden_states = inputs_embeds + positions
|
| 652 |
+
hidden_states = self.layernorm_embedding(hidden_states)
|
| 653 |
+
|
| 654 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 655 |
+
|
| 656 |
+
for idx, decoder_layer in enumerate(self.layers):
|
| 657 |
+
# add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
|
| 658 |
+
if self.training:
|
| 659 |
+
dropout_probability = torch.rand([])
|
| 660 |
+
if dropout_probability < self.layerdrop:
|
| 661 |
+
continue
|
| 662 |
+
|
| 663 |
+
hidden_states = decoder_layer(
|
| 664 |
+
hidden_states,
|
| 665 |
+
attention_mask,
|
| 666 |
+
encoder_hidden_states, # as a positional argument for gradient checkpointing
|
| 667 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 668 |
+
past_key_values=past_key_values,
|
| 669 |
+
use_cache=use_cache,
|
| 670 |
+
**kwargs,
|
| 671 |
+
)
|
| 672 |
+
|
| 673 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 674 |
+
last_hidden_state=hidden_states,
|
| 675 |
+
past_key_values=past_key_values,
|
| 676 |
+
)
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
@auto_docstring
|
| 680 |
+
class BartModel(BartPreTrainedModel):
|
| 681 |
+
_tied_weights_keys = {
|
| 682 |
+
"decoder.embed_tokens.weight": "shared.weight",
|
| 683 |
+
"encoder.embed_tokens.weight": "shared.weight",
|
| 684 |
+
}
|
| 685 |
+
|
| 686 |
+
def __init__(self, config: BartConfig):
|
| 687 |
+
super().__init__(config)
|
| 688 |
+
|
| 689 |
+
padding_idx, vocab_size = config.pad_token_id, config.vocab_size
|
| 690 |
+
embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
|
| 691 |
+
self.shared = BartScaledWordEmbedding(vocab_size, config.d_model, padding_idx, embed_scale=embed_scale)
|
| 692 |
+
|
| 693 |
+
self.encoder = BartEncoder(config)
|
| 694 |
+
self.decoder = BartDecoder(config)
|
| 695 |
+
|
| 696 |
+
# Initialize weights and apply final processing
|
| 697 |
+
self.post_init()
|
| 698 |
+
|
| 699 |
+
def get_input_embeddings(self):
|
| 700 |
+
return self.shared
|
| 701 |
+
|
| 702 |
+
def set_input_embeddings(self, value):
|
| 703 |
+
self.shared = value
|
| 704 |
+
self.encoder.embed_tokens = self.shared
|
| 705 |
+
self.decoder.embed_tokens = self.shared
|
| 706 |
+
|
| 707 |
+
@can_return_tuple
|
| 708 |
+
@auto_docstring
|
| 709 |
+
def forward(
|
| 710 |
+
self,
|
| 711 |
+
input_ids: torch.LongTensor | None = None,
|
| 712 |
+
attention_mask: torch.Tensor | None = None,
|
| 713 |
+
decoder_input_ids: torch.LongTensor | None = None,
|
| 714 |
+
decoder_attention_mask: torch.LongTensor | None = None,
|
| 715 |
+
encoder_outputs: list[torch.FloatTensor] | None = None,
|
| 716 |
+
past_key_values: Cache | None = None,
|
| 717 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 718 |
+
decoder_inputs_embeds: torch.FloatTensor | None = None,
|
| 719 |
+
use_cache: bool | None = None,
|
| 720 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 721 |
+
) -> tuple | Seq2SeqModelOutput:
|
| 722 |
+
r"""
|
| 723 |
+
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 724 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 725 |
+
|
| 726 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 727 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 728 |
+
|
| 729 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 730 |
+
|
| 731 |
+
Bart uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
|
| 732 |
+
is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
|
| 733 |
+
|
| 734 |
+
For translation and summarization training, `decoder_input_ids` should be provided. If no
|
| 735 |
+
`decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
|
| 736 |
+
for denoising pre-training following the paper.
|
| 737 |
+
decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 738 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 739 |
+
be used by default.
|
| 740 |
+
|
| 741 |
+
If you want to change padding behavior, you should read [`modeling_bart._prepare_decoder_attention_mask`]
|
| 742 |
+
and modify to your needs. See diagram 1 in [the paper](https://huggingface.co/papers/1910.13461) for more
|
| 743 |
+
information on the default strategy.
|
| 744 |
+
"""
|
| 745 |
+
# different to other models, Bart automatically creates decoder_input_ids from
|
| 746 |
+
# input_ids if no decoder_input_ids are provided
|
| 747 |
+
if decoder_input_ids is None and decoder_inputs_embeds is None:
|
| 748 |
+
if input_ids is None:
|
| 749 |
+
raise ValueError(
|
| 750 |
+
"If no `decoder_input_ids` or `decoder_inputs_embeds` are "
|
| 751 |
+
"passed, `input_ids` cannot be `None`. Please pass either "
|
| 752 |
+
"`input_ids` or `decoder_input_ids` or `decoder_inputs_embeds`."
|
| 753 |
+
)
|
| 754 |
+
|
| 755 |
+
decoder_input_ids = shift_tokens_right(
|
| 756 |
+
input_ids, self.config.pad_token_id, self.config.decoder_start_token_id
|
| 757 |
+
)
|
| 758 |
+
|
| 759 |
+
if encoder_outputs is None:
|
| 760 |
+
encoder_outputs: BaseModelOutput = self.encoder(
|
| 761 |
+
input_ids=input_ids,
|
| 762 |
+
attention_mask=attention_mask,
|
| 763 |
+
inputs_embeds=inputs_embeds,
|
| 764 |
+
**kwargs,
|
| 765 |
+
)
|
| 766 |
+
elif not isinstance(encoder_outputs, BaseModelOutput):
|
| 767 |
+
encoder_outputs = BaseModelOutput(
|
| 768 |
+
last_hidden_state=encoder_outputs[0],
|
| 769 |
+
hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
|
| 770 |
+
attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
|
| 771 |
+
)
|
| 772 |
+
|
| 773 |
+
decoder_outputs: BaseModelOutputWithPastAndCrossAttentions = self.decoder(
|
| 774 |
+
input_ids=decoder_input_ids,
|
| 775 |
+
attention_mask=decoder_attention_mask,
|
| 776 |
+
encoder_hidden_states=encoder_outputs[0],
|
| 777 |
+
encoder_attention_mask=attention_mask,
|
| 778 |
+
past_key_values=past_key_values,
|
| 779 |
+
inputs_embeds=decoder_inputs_embeds,
|
| 780 |
+
use_cache=use_cache,
|
| 781 |
+
**kwargs,
|
| 782 |
+
)
|
| 783 |
+
|
| 784 |
+
return Seq2SeqModelOutput(
|
| 785 |
+
last_hidden_state=decoder_outputs.last_hidden_state,
|
| 786 |
+
past_key_values=decoder_outputs.past_key_values,
|
| 787 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 788 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 789 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 790 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
| 791 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 792 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 793 |
+
)
|
| 794 |
+
|
| 795 |
+
|
| 796 |
+
@auto_docstring(
|
| 797 |
+
custom_intro="""
|
| 798 |
+
The BART Model with a language modeling head. Can be used for summarization.
|
| 799 |
+
"""
|
| 800 |
+
)
|
| 801 |
+
class BartForConditionalGeneration(BartPreTrainedModel, GenerationMixin):
|
| 802 |
+
base_model_prefix = "model"
|
| 803 |
+
_tied_weights_keys = {
|
| 804 |
+
"lm_head.weight": "model.shared.weight",
|
| 805 |
+
}
|
| 806 |
+
_keys_to_ignore_on_load_missing = ["final_logits_bias"]
|
| 807 |
+
|
| 808 |
+
def __init__(self, config: BartConfig):
|
| 809 |
+
super().__init__(config)
|
| 810 |
+
self.model = BartModel(config)
|
| 811 |
+
self.register_buffer("final_logits_bias", torch.zeros((1, self.model.shared.num_embeddings)))
|
| 812 |
+
self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)
|
| 813 |
+
|
| 814 |
+
# Initialize weights and apply final processing
|
| 815 |
+
self.post_init()
|
| 816 |
+
|
| 817 |
+
def resize_token_embeddings(
|
| 818 |
+
self, new_num_tokens: int, pad_to_multiple_of: int | None = None, mean_resizing: bool = True
|
| 819 |
+
) -> nn.Embedding:
|
| 820 |
+
new_embeddings = super().resize_token_embeddings(new_num_tokens, pad_to_multiple_of, mean_resizing)
|
| 821 |
+
self._resize_final_logits_bias(new_embeddings.weight.shape[0])
|
| 822 |
+
return new_embeddings
|
| 823 |
+
|
| 824 |
+
def _resize_final_logits_bias(self, new_num_tokens: int) -> None:
|
| 825 |
+
old_num_tokens = self.final_logits_bias.shape[-1]
|
| 826 |
+
if new_num_tokens <= old_num_tokens:
|
| 827 |
+
new_bias = self.final_logits_bias[:, :new_num_tokens]
|
| 828 |
+
else:
|
| 829 |
+
extra_bias = torch.zeros((1, new_num_tokens - old_num_tokens), device=self.final_logits_bias.device)
|
| 830 |
+
new_bias = torch.cat([self.final_logits_bias, extra_bias], dim=1)
|
| 831 |
+
self.register_buffer("final_logits_bias", new_bias)
|
| 832 |
+
|
| 833 |
+
@can_return_tuple
|
| 834 |
+
@auto_docstring
|
| 835 |
+
def forward(
|
| 836 |
+
self,
|
| 837 |
+
input_ids: torch.LongTensor | None = None,
|
| 838 |
+
attention_mask: torch.Tensor | None = None,
|
| 839 |
+
decoder_input_ids: torch.LongTensor | None = None,
|
| 840 |
+
decoder_attention_mask: torch.LongTensor | None = None,
|
| 841 |
+
encoder_outputs: list[torch.FloatTensor] | None = None,
|
| 842 |
+
past_key_values: Cache | None = None,
|
| 843 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 844 |
+
decoder_inputs_embeds: torch.FloatTensor | None = None,
|
| 845 |
+
labels: torch.LongTensor | None = None,
|
| 846 |
+
use_cache: bool | None = None,
|
| 847 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 848 |
+
) -> tuple | Seq2SeqLMOutput:
|
| 849 |
+
r"""
|
| 850 |
+
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 851 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 852 |
+
|
| 853 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 854 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 855 |
+
|
| 856 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 857 |
+
|
| 858 |
+
Bart uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
|
| 859 |
+
is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
|
| 860 |
+
|
| 861 |
+
For translation and summarization training, `decoder_input_ids` should be provided. If no
|
| 862 |
+
`decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
|
| 863 |
+
for denoising pre-training following the paper.
|
| 864 |
+
decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 865 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 866 |
+
be used by default.
|
| 867 |
+
|
| 868 |
+
If you want to change padding behavior, you should read [`modeling_bart._prepare_decoder_attention_mask`]
|
| 869 |
+
and modify to your needs. See diagram 1 in [the paper](https://huggingface.co/papers/1910.13461) for more
|
| 870 |
+
information on the default strategy.
|
| 871 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 872 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 873 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 874 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 875 |
+
|
| 876 |
+
Example summarization:
|
| 877 |
+
|
| 878 |
+
```python
|
| 879 |
+
>>> from transformers import AutoTokenizer, BartForConditionalGeneration
|
| 880 |
+
|
| 881 |
+
>>> model = BartForConditionalGeneration.from_pretrained("facebook/bart-large-cnn")
|
| 882 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/bart-large-cnn")
|
| 883 |
+
|
| 884 |
+
>>> ARTICLE_TO_SUMMARIZE = (
|
| 885 |
+
... "PG&E stated it scheduled the blackouts in response to forecasts for high winds "
|
| 886 |
+
... "amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were "
|
| 887 |
+
... "scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow."
|
| 888 |
+
... )
|
| 889 |
+
>>> inputs = tokenizer([ARTICLE_TO_SUMMARIZE], max_length=1024, return_tensors="pt")
|
| 890 |
+
|
| 891 |
+
>>> # Generate Summary
|
| 892 |
+
>>> summary_ids = model.generate(inputs["input_ids"], num_beams=2, min_length=0, max_length=20)
|
| 893 |
+
>>> tokenizer.batch_decode(summary_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 894 |
+
'PG&E scheduled the blackouts in response to forecasts for high winds amid dry conditions'
|
| 895 |
+
```
|
| 896 |
+
|
| 897 |
+
Mask filling example:
|
| 898 |
+
|
| 899 |
+
```python
|
| 900 |
+
>>> from transformers import AutoTokenizer, BartForConditionalGeneration
|
| 901 |
+
|
| 902 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/bart-base")
|
| 903 |
+
>>> model = BartForConditionalGeneration.from_pretrained("facebook/bart-base")
|
| 904 |
+
|
| 905 |
+
>>> TXT = "My friends are <mask> but they eat too many carbs."
|
| 906 |
+
>>> input_ids = tokenizer([TXT], return_tensors="pt")["input_ids"]
|
| 907 |
+
>>> logits = model(input_ids).logits
|
| 908 |
+
|
| 909 |
+
>>> masked_index = (input_ids[0] == tokenizer.mask_token_id).nonzero().item()
|
| 910 |
+
>>> probs = logits[0, masked_index].softmax(dim=0)
|
| 911 |
+
>>> values, predictions = probs.topk(5)
|
| 912 |
+
|
| 913 |
+
>>> tokenizer.decode(predictions).split()
|
| 914 |
+
['not', 'good', 'healthy', 'great', 'very']
|
| 915 |
+
```
|
| 916 |
+
"""
|
| 917 |
+
if labels is not None:
|
| 918 |
+
if use_cache:
|
| 919 |
+
logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
|
| 920 |
+
use_cache = False
|
| 921 |
+
if decoder_input_ids is None and decoder_inputs_embeds is None:
|
| 922 |
+
decoder_input_ids = shift_tokens_right(
|
| 923 |
+
labels, self.config.pad_token_id, self.config.decoder_start_token_id
|
| 924 |
+
)
|
| 925 |
+
|
| 926 |
+
outputs: Seq2SeqModelOutput = self.model(
|
| 927 |
+
input_ids,
|
| 928 |
+
attention_mask=attention_mask,
|
| 929 |
+
decoder_input_ids=decoder_input_ids,
|
| 930 |
+
encoder_outputs=encoder_outputs,
|
| 931 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 932 |
+
past_key_values=past_key_values,
|
| 933 |
+
inputs_embeds=inputs_embeds,
|
| 934 |
+
decoder_inputs_embeds=decoder_inputs_embeds,
|
| 935 |
+
use_cache=use_cache,
|
| 936 |
+
**kwargs,
|
| 937 |
+
)
|
| 938 |
+
|
| 939 |
+
lm_logits = self.lm_head(outputs[0])
|
| 940 |
+
lm_logits = lm_logits + self.final_logits_bias.to(lm_logits.device)
|
| 941 |
+
|
| 942 |
+
masked_lm_loss = None
|
| 943 |
+
if labels is not None:
|
| 944 |
+
labels = labels.to(lm_logits.device)
|
| 945 |
+
loss_fct = CrossEntropyLoss()
|
| 946 |
+
masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))
|
| 947 |
+
|
| 948 |
+
return Seq2SeqLMOutput(
|
| 949 |
+
loss=masked_lm_loss,
|
| 950 |
+
logits=lm_logits,
|
| 951 |
+
past_key_values=outputs.past_key_values,
|
| 952 |
+
decoder_hidden_states=outputs.decoder_hidden_states,
|
| 953 |
+
decoder_attentions=outputs.decoder_attentions,
|
| 954 |
+
cross_attentions=outputs.cross_attentions,
|
| 955 |
+
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
|
| 956 |
+
encoder_hidden_states=outputs.encoder_hidden_states,
|
| 957 |
+
encoder_attentions=outputs.encoder_attentions,
|
| 958 |
+
)
|
| 959 |
+
|
| 960 |
+
def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
|
| 961 |
+
return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id)
|
| 962 |
+
|
| 963 |
+
|
| 964 |
+
@auto_docstring(
|
| 965 |
+
custom_intro="""
|
| 966 |
+
Bart model with a sequence classification/head on top (a linear layer on top of the pooled output) e.g. for GLUE
|
| 967 |
+
tasks.
|
| 968 |
+
"""
|
| 969 |
+
)
|
| 970 |
+
class BartForSequenceClassification(BartPreTrainedModel):
|
| 971 |
+
def __init__(self, config: BartConfig, **kwargs):
|
| 972 |
+
super().__init__(config, **kwargs)
|
| 973 |
+
self.model = BartModel(config)
|
| 974 |
+
self.classification_head = BartClassificationHead(
|
| 975 |
+
config.d_model,
|
| 976 |
+
config.d_model,
|
| 977 |
+
config.num_labels,
|
| 978 |
+
config.classifier_dropout,
|
| 979 |
+
)
|
| 980 |
+
|
| 981 |
+
# Initialize weights and apply final processing
|
| 982 |
+
self.post_init()
|
| 983 |
+
|
| 984 |
+
@can_return_tuple
|
| 985 |
+
@auto_docstring
|
| 986 |
+
def forward(
|
| 987 |
+
self,
|
| 988 |
+
input_ids: torch.LongTensor | None = None,
|
| 989 |
+
attention_mask: torch.Tensor | None = None,
|
| 990 |
+
decoder_input_ids: torch.LongTensor | None = None,
|
| 991 |
+
decoder_attention_mask: torch.LongTensor | None = None,
|
| 992 |
+
encoder_outputs: list[torch.FloatTensor] | None = None,
|
| 993 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 994 |
+
decoder_inputs_embeds: torch.FloatTensor | None = None,
|
| 995 |
+
labels: torch.LongTensor | None = None,
|
| 996 |
+
use_cache: bool | None = None,
|
| 997 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 998 |
+
) -> tuple | Seq2SeqSequenceClassifierOutput:
|
| 999 |
+
r"""
|
| 1000 |
+
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 1001 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 1002 |
+
|
| 1003 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1004 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 1005 |
+
|
| 1006 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 1007 |
+
|
| 1008 |
+
Bart uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
|
| 1009 |
+
is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
|
| 1010 |
+
|
| 1011 |
+
For translation and summarization training, `decoder_input_ids` should be provided. If no
|
| 1012 |
+
`decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
|
| 1013 |
+
for denoising pre-training following the paper.
|
| 1014 |
+
decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 1015 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 1016 |
+
be used by default.
|
| 1017 |
+
|
| 1018 |
+
If you want to change padding behavior, you should read [`modeling_bart._prepare_decoder_attention_mask`]
|
| 1019 |
+
and modify to your needs. See diagram 1 in [the paper](https://huggingface.co/papers/1910.13461) for more
|
| 1020 |
+
information on the default strategy.
|
| 1021 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1022 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1023 |
+
config.num_labels - 1]`. If `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1024 |
+
"""
|
| 1025 |
+
if labels is not None:
|
| 1026 |
+
use_cache = False
|
| 1027 |
+
|
| 1028 |
+
if input_ids is None and inputs_embeds is not None:
|
| 1029 |
+
raise NotImplementedError(
|
| 1030 |
+
f"Passing input embeddings is currently not supported for {self.__class__.__name__}"
|
| 1031 |
+
)
|
| 1032 |
+
|
| 1033 |
+
outputs: Seq2SeqModelOutput = self.model(
|
| 1034 |
+
input_ids,
|
| 1035 |
+
attention_mask=attention_mask,
|
| 1036 |
+
decoder_input_ids=decoder_input_ids,
|
| 1037 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1038 |
+
encoder_outputs=encoder_outputs,
|
| 1039 |
+
inputs_embeds=inputs_embeds,
|
| 1040 |
+
decoder_inputs_embeds=decoder_inputs_embeds,
|
| 1041 |
+
use_cache=use_cache,
|
| 1042 |
+
**kwargs,
|
| 1043 |
+
)
|
| 1044 |
+
hidden_states = outputs[0] # last hidden state
|
| 1045 |
+
|
| 1046 |
+
eos_mask = input_ids.eq(self.config.eos_token_id).to(hidden_states.device)
|
| 1047 |
+
|
| 1048 |
+
torch_compilable_check(
|
| 1049 |
+
torch.unique_consecutive(eos_mask.sum(1)).numel() == 1,
|
| 1050 |
+
"All examples must have the same number of <eos> tokens.",
|
| 1051 |
+
)
|
| 1052 |
+
sentence_representation = hidden_states[eos_mask, :].view(hidden_states.size(0), -1, hidden_states.size(-1))[
|
| 1053 |
+
:, -1, :
|
| 1054 |
+
]
|
| 1055 |
+
logits = self.classification_head(sentence_representation)
|
| 1056 |
+
|
| 1057 |
+
loss = None
|
| 1058 |
+
if labels is not None:
|
| 1059 |
+
labels = labels.to(logits.device)
|
| 1060 |
+
if self.config.problem_type is None:
|
| 1061 |
+
if self.config.num_labels == 1:
|
| 1062 |
+
self.config.problem_type = "regression"
|
| 1063 |
+
elif self.config.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 1064 |
+
self.config.problem_type = "single_label_classification"
|
| 1065 |
+
else:
|
| 1066 |
+
self.config.problem_type = "multi_label_classification"
|
| 1067 |
+
|
| 1068 |
+
if self.config.problem_type == "regression":
|
| 1069 |
+
loss_fct = MSELoss()
|
| 1070 |
+
if self.config.num_labels == 1:
|
| 1071 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 1072 |
+
else:
|
| 1073 |
+
loss = loss_fct(logits, labels)
|
| 1074 |
+
elif self.config.problem_type == "single_label_classification":
|
| 1075 |
+
loss_fct = CrossEntropyLoss()
|
| 1076 |
+
loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
|
| 1077 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 1078 |
+
loss_fct = BCEWithLogitsLoss()
|
| 1079 |
+
loss = loss_fct(logits, labels)
|
| 1080 |
+
|
| 1081 |
+
return Seq2SeqSequenceClassifierOutput(
|
| 1082 |
+
loss=loss,
|
| 1083 |
+
logits=logits,
|
| 1084 |
+
past_key_values=outputs.past_key_values,
|
| 1085 |
+
decoder_hidden_states=outputs.decoder_hidden_states,
|
| 1086 |
+
decoder_attentions=outputs.decoder_attentions,
|
| 1087 |
+
cross_attentions=outputs.cross_attentions,
|
| 1088 |
+
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
|
| 1089 |
+
encoder_hidden_states=outputs.encoder_hidden_states,
|
| 1090 |
+
encoder_attentions=outputs.encoder_attentions,
|
| 1091 |
+
)
|
| 1092 |
+
|
| 1093 |
+
|
| 1094 |
+
@auto_docstring
|
| 1095 |
+
class BartForQuestionAnswering(BartPreTrainedModel):
|
| 1096 |
+
def __init__(self, config):
|
| 1097 |
+
super().__init__(config)
|
| 1098 |
+
|
| 1099 |
+
config.num_labels = 2
|
| 1100 |
+
self.num_labels = config.num_labels
|
| 1101 |
+
|
| 1102 |
+
self.model = BartModel(config)
|
| 1103 |
+
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
|
| 1104 |
+
|
| 1105 |
+
# Initialize weights and apply final processing
|
| 1106 |
+
self.post_init()
|
| 1107 |
+
|
| 1108 |
+
@can_return_tuple
|
| 1109 |
+
@auto_docstring
|
| 1110 |
+
def forward(
|
| 1111 |
+
self,
|
| 1112 |
+
input_ids: torch.Tensor | None = None,
|
| 1113 |
+
attention_mask: torch.Tensor | None = None,
|
| 1114 |
+
decoder_input_ids: torch.LongTensor | None = None,
|
| 1115 |
+
decoder_attention_mask: torch.LongTensor | None = None,
|
| 1116 |
+
encoder_outputs: list[torch.FloatTensor] | None = None,
|
| 1117 |
+
start_positions: torch.LongTensor | None = None,
|
| 1118 |
+
end_positions: torch.LongTensor | None = None,
|
| 1119 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 1120 |
+
decoder_inputs_embeds: torch.FloatTensor | None = None,
|
| 1121 |
+
use_cache: bool | None = None,
|
| 1122 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1123 |
+
) -> tuple | Seq2SeqQuestionAnsweringModelOutput:
|
| 1124 |
+
r"""
|
| 1125 |
+
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 1126 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 1127 |
+
|
| 1128 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1129 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 1130 |
+
|
| 1131 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 1132 |
+
|
| 1133 |
+
Bart uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
|
| 1134 |
+
is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
|
| 1135 |
+
|
| 1136 |
+
For translation and summarization training, `decoder_input_ids` should be provided. If no
|
| 1137 |
+
`decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
|
| 1138 |
+
for denoising pre-training following the paper.
|
| 1139 |
+
decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 1140 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 1141 |
+
be used by default.
|
| 1142 |
+
|
| 1143 |
+
If you want to change padding behavior, you should read [`modeling_bart._prepare_decoder_attention_mask`]
|
| 1144 |
+
and modify to your needs. See diagram 1 in [the paper](https://huggingface.co/papers/1910.13461) for more
|
| 1145 |
+
information on the default strategy.
|
| 1146 |
+
"""
|
| 1147 |
+
if start_positions is not None and end_positions is not None:
|
| 1148 |
+
use_cache = False
|
| 1149 |
+
|
| 1150 |
+
outputs: Seq2SeqModelOutput = self.model(
|
| 1151 |
+
input_ids,
|
| 1152 |
+
attention_mask=attention_mask,
|
| 1153 |
+
decoder_input_ids=decoder_input_ids,
|
| 1154 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1155 |
+
encoder_outputs=encoder_outputs,
|
| 1156 |
+
inputs_embeds=inputs_embeds,
|
| 1157 |
+
decoder_inputs_embeds=decoder_inputs_embeds,
|
| 1158 |
+
use_cache=use_cache,
|
| 1159 |
+
**kwargs,
|
| 1160 |
+
)
|
| 1161 |
+
|
| 1162 |
+
sequence_output = outputs[0]
|
| 1163 |
+
|
| 1164 |
+
logits = self.qa_outputs(sequence_output)
|
| 1165 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
| 1166 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
| 1167 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
| 1168 |
+
|
| 1169 |
+
total_loss = None
|
| 1170 |
+
if start_positions is not None and end_positions is not None:
|
| 1171 |
+
# If we are on multi-GPU, split add a dimension
|
| 1172 |
+
if len(start_positions.size()) > 1:
|
| 1173 |
+
start_positions = start_positions.squeeze(-1)
|
| 1174 |
+
if len(end_positions.size()) > 1:
|
| 1175 |
+
end_positions = end_positions.squeeze(-1)
|
| 1176 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
| 1177 |
+
ignored_index = start_logits.size(1)
|
| 1178 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
| 1179 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
| 1180 |
+
|
| 1181 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
| 1182 |
+
start_loss = loss_fct(start_logits, start_positions)
|
| 1183 |
+
end_loss = loss_fct(end_logits, end_positions)
|
| 1184 |
+
total_loss = (start_loss + end_loss) / 2
|
| 1185 |
+
|
| 1186 |
+
return Seq2SeqQuestionAnsweringModelOutput(
|
| 1187 |
+
loss=total_loss,
|
| 1188 |
+
start_logits=start_logits,
|
| 1189 |
+
end_logits=end_logits,
|
| 1190 |
+
past_key_values=outputs.past_key_values,
|
| 1191 |
+
decoder_hidden_states=outputs.decoder_hidden_states,
|
| 1192 |
+
decoder_attentions=outputs.decoder_attentions,
|
| 1193 |
+
cross_attentions=outputs.cross_attentions,
|
| 1194 |
+
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
|
| 1195 |
+
encoder_hidden_states=outputs.encoder_hidden_states,
|
| 1196 |
+
encoder_attentions=outputs.encoder_attentions,
|
| 1197 |
+
)
|
| 1198 |
+
|
| 1199 |
+
|
| 1200 |
+
class BartDecoderWrapper(BartPreTrainedModel):
|
| 1201 |
+
"""
|
| 1202 |
+
This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
|
| 1203 |
+
used in combination with the [`EncoderDecoderModel`] framework.
|
| 1204 |
+
"""
|
| 1205 |
+
|
| 1206 |
+
def __init__(self, config):
|
| 1207 |
+
super().__init__(config)
|
| 1208 |
+
self.decoder = BartDecoder(config)
|
| 1209 |
+
self.post_init()
|
| 1210 |
+
|
| 1211 |
+
def forward(self, *args, **kwargs):
|
| 1212 |
+
return self.decoder(*args, **kwargs)
|
| 1213 |
+
|
| 1214 |
+
|
| 1215 |
+
@auto_docstring(
|
| 1216 |
+
custom_intro="""
|
| 1217 |
+
BART decoder with a language modeling head on top (linear layer with weights tied to the input embeddings).
|
| 1218 |
+
"""
|
| 1219 |
+
)
|
| 1220 |
+
class BartForCausalLM(BartPreTrainedModel, GenerationMixin):
|
| 1221 |
+
_tied_weights_keys = {
|
| 1222 |
+
"lm_head.weight": "model.decoder.embed_tokens.weight",
|
| 1223 |
+
}
|
| 1224 |
+
|
| 1225 |
+
def __init__(self, config):
|
| 1226 |
+
config.is_decoder = True
|
| 1227 |
+
config.is_encoder_decoder = False
|
| 1228 |
+
super().__init__(config)
|
| 1229 |
+
self.model = BartDecoderWrapper(config)
|
| 1230 |
+
|
| 1231 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 1232 |
+
|
| 1233 |
+
# Initialize weights and apply final processing
|
| 1234 |
+
self.post_init()
|
| 1235 |
+
|
| 1236 |
+
def get_input_embeddings(self):
|
| 1237 |
+
return self.model.decoder.embed_tokens
|
| 1238 |
+
|
| 1239 |
+
def set_input_embeddings(self, value):
|
| 1240 |
+
self.model.decoder.embed_tokens = value
|
| 1241 |
+
|
| 1242 |
+
@can_return_tuple
|
| 1243 |
+
@auto_docstring
|
| 1244 |
+
def forward(
|
| 1245 |
+
self,
|
| 1246 |
+
input_ids: torch.LongTensor | None = None,
|
| 1247 |
+
attention_mask: torch.Tensor | None = None,
|
| 1248 |
+
encoder_hidden_states: torch.FloatTensor | None = None,
|
| 1249 |
+
encoder_attention_mask: torch.FloatTensor | None = None,
|
| 1250 |
+
past_key_values: Cache | None = None,
|
| 1251 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 1252 |
+
labels: torch.LongTensor | None = None,
|
| 1253 |
+
use_cache: bool | None = None,
|
| 1254 |
+
logits_to_keep: int | torch.Tensor = 0,
|
| 1255 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1256 |
+
) -> tuple | CausalLMOutputWithCrossAttentions:
|
| 1257 |
+
r"""
|
| 1258 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1259 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 1260 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 1261 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 1262 |
+
|
| 1263 |
+
Example:
|
| 1264 |
+
|
| 1265 |
+
```python
|
| 1266 |
+
>>> from transformers import AutoTokenizer, BartForCausalLM
|
| 1267 |
+
|
| 1268 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/bart-base")
|
| 1269 |
+
>>> model = BartForCausalLM.from_pretrained("facebook/bart-base")
|
| 1270 |
+
>>> assert model.config.is_decoder, f"{model.__class__} has to be configured as a decoder."
|
| 1271 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
|
| 1272 |
+
>>> outputs = model(**inputs)
|
| 1273 |
+
|
| 1274 |
+
>>> logits = outputs.logits
|
| 1275 |
+
>>> expected_shape = [1, inputs.input_ids.shape[-1], model.config.vocab_size]
|
| 1276 |
+
>>> list(logits.shape) == expected_shape
|
| 1277 |
+
True
|
| 1278 |
+
```"""
|
| 1279 |
+
|
| 1280 |
+
outputs: BaseModelOutputWithPastAndCrossAttentions = self.model.decoder(
|
| 1281 |
+
input_ids=input_ids,
|
| 1282 |
+
attention_mask=attention_mask,
|
| 1283 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1284 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1285 |
+
past_key_values=past_key_values,
|
| 1286 |
+
inputs_embeds=inputs_embeds,
|
| 1287 |
+
use_cache=use_cache,
|
| 1288 |
+
**kwargs,
|
| 1289 |
+
)
|
| 1290 |
+
|
| 1291 |
+
hidden_states = outputs[0]
|
| 1292 |
+
# Only compute necessary logits
|
| 1293 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 1294 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
| 1295 |
+
|
| 1296 |
+
loss = None
|
| 1297 |
+
if labels is not None:
|
| 1298 |
+
labels = labels.to(logits.device)
|
| 1299 |
+
loss_fct = CrossEntropyLoss()
|
| 1300 |
+
loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
|
| 1301 |
+
|
| 1302 |
+
return CausalLMOutputWithCrossAttentions(
|
| 1303 |
+
loss=loss,
|
| 1304 |
+
logits=logits,
|
| 1305 |
+
past_key_values=outputs.past_key_values,
|
| 1306 |
+
hidden_states=outputs.hidden_states,
|
| 1307 |
+
attentions=outputs.attentions,
|
| 1308 |
+
cross_attentions=outputs.cross_attentions,
|
| 1309 |
+
)
|
| 1310 |
+
|
| 1311 |
+
|
| 1312 |
+
__all__ = [
|
| 1313 |
+
"BartForCausalLM",
|
| 1314 |
+
"BartForConditionalGeneration",
|
| 1315 |
+
"BartForQuestionAnswering",
|
| 1316 |
+
"BartForSequenceClassification",
|
| 1317 |
+
"BartModel",
|
| 1318 |
+
"BartPreTrainedModel",
|
| 1319 |
+
"BartPretrainedModel",
|
| 1320 |
+
"PretrainedBartModel",
|
| 1321 |
+
]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/bart/tokenization_bart.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the Apache 2.0 license found in the
|
| 4 |
+
# LICENSE file in the root directory of this source tree.
|
| 5 |
+
|
| 6 |
+
"""
|
| 7 |
+
Compatibility shims for BART tokenizers in v5.
|
| 8 |
+
|
| 9 |
+
In v5 we consolidate on the tokenizers-library backend and remove separate
|
| 10 |
+
"slow" vs "fast" implementations. BART uses the same byte-level BPE
|
| 11 |
+
tokenizer as RoBERTa, so we expose `BartTokenizer` and `BartTokenizerFast`
|
| 12 |
+
as aliases to `RobertaTokenizer` to preserve the public API expected by
|
| 13 |
+
existing code and tests.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from ..roberta.tokenization_roberta import RobertaTokenizer as _RobertaTokenizer
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# Public aliases maintained for backwards compatibility
|
| 20 |
+
BartTokenizer = _RobertaTokenizer
|
| 21 |
+
BartTokenizerFast = _RobertaTokenizer
|
| 22 |
+
|
| 23 |
+
__all__ = ["BartTokenizer", "BartTokenizerFast"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/gptj/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_gptj import *
|
| 22 |
+
from .modeling_gptj 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__)
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mpt/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_mpt import *
|
| 22 |
+
from .modeling_mpt 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__)
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mpt/configuration_mpt.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 HuggingFace Inc. team and MosaicML NLP team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Mpt configuration"""
|
| 15 |
+
|
| 16 |
+
from typing import Literal
|
| 17 |
+
|
| 18 |
+
from huggingface_hub.dataclasses import strict
|
| 19 |
+
|
| 20 |
+
from ...configuration_utils import PreTrainedConfig
|
| 21 |
+
from ...utils import auto_docstring
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@auto_docstring(checkpoint="mosaicml/mpt-7b")
|
| 25 |
+
@strict
|
| 26 |
+
class MptAttentionConfig(PreTrainedConfig):
|
| 27 |
+
r"""
|
| 28 |
+
attn_type (`str`, *optional*, defaults to `"multihead_attention"`):
|
| 29 |
+
type of attention to use. Options: `"multihead_attention"`, `"multiquery_attention"`.
|
| 30 |
+
attn_pdrop (`float`, *optional*, defaults to `0.0`):
|
| 31 |
+
The dropout probability for the attention layers.
|
| 32 |
+
attn_impl (`str`, *optional*, defaults to `"torch"`):
|
| 33 |
+
The attention implementation to use. One of `"torch"`, `"flash"`, or `"triton"`.
|
| 34 |
+
clip_qkv (`float`, *optional*):
|
| 35 |
+
If not `None`, clip the queries, keys, and values in the attention layer to this value.
|
| 36 |
+
softmax_scale (`float`, *optional*):
|
| 37 |
+
If not `None`, scale the softmax in the attention layer by this value. If `None`, will default to
|
| 38 |
+
`1/sqrt(hidden_size)`.
|
| 39 |
+
prefix_lm (`bool`, *optional*, defaults to `False`):
|
| 40 |
+
Whether the model should operate as a Prefix LM. This requires passing an extra `prefix_mask` argument
|
| 41 |
+
which indicates which tokens belong to the prefix. Tokens in the prefix can attend to one another
|
| 42 |
+
bi-directionally. Tokens outside the prefix use causal attention.
|
| 43 |
+
qk_ln (`bool`, *optional*, defaults to `False`):
|
| 44 |
+
Whether to apply layer normalization to the queries and keys in the attention layer.
|
| 45 |
+
attn_uses_sequence_id (`bool`, *optional*, defaults to `False`):
|
| 46 |
+
Whether to restrict attention to tokens that have the same token_type_ids. When the model is in `train`
|
| 47 |
+
mode, this requires passing an extra *token_type_ids* argument which indicates which sub-sequence each
|
| 48 |
+
token belongs to. Defaults to `False` meaning any provided *token_type_ids* will be ignored.
|
| 49 |
+
alibi (`bool`, *optional*, defaults to `True`):
|
| 50 |
+
Whether or not to use the alibi bias instead of positional embedding.
|
| 51 |
+
alibi_bias_max (`int`, *optional*, defaults to 8):
|
| 52 |
+
The maximum value of the alibi bias.
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
base_config_key = "attn_config"
|
| 56 |
+
|
| 57 |
+
attn_type: Literal["multihead_attention", "multiquery_attention"] = "multihead_attention"
|
| 58 |
+
attn_pdrop: int = 0
|
| 59 |
+
attn_impl: str = "torch"
|
| 60 |
+
clip_qkv: float | None = None
|
| 61 |
+
softmax_scale: float | None = None
|
| 62 |
+
prefix_lm: bool = False
|
| 63 |
+
qk_ln: bool = False
|
| 64 |
+
attn_uses_sequence_id: bool = False
|
| 65 |
+
alibi: bool = True
|
| 66 |
+
alibi_bias_max: int = 8
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@auto_docstring(checkpoint="mosaicml/mpt-7b")
|
| 70 |
+
@strict
|
| 71 |
+
class MptConfig(PreTrainedConfig):
|
| 72 |
+
r"""
|
| 73 |
+
expansion_ratio (`int`, *optional*, defaults to 4):
|
| 74 |
+
The ratio of the up/down scale in the MLP.
|
| 75 |
+
max_seq_len (`int`, *optional*, defaults to 2048):
|
| 76 |
+
The maximum sequence length of the model.
|
| 77 |
+
layer_norm_epsilon (`float`, *optional*, defaults to 1e-05):
|
| 78 |
+
The epsilon to use in the layer normalization layers.
|
| 79 |
+
learned_pos_emb (`bool`, *optional*, defaults to `True`):
|
| 80 |
+
Whether to use learned positional embeddings.
|
| 81 |
+
attn_config (`dict`, *optional*):
|
| 82 |
+
A dictionary used to configure the model's attention module.
|
| 83 |
+
init_device (`str`, *optional*, defaults to `"cpu"`):
|
| 84 |
+
The device to use for parameter initialization. Defined for backward compatibility
|
| 85 |
+
logit_scale (`float`, *optional*):
|
| 86 |
+
If not None, scale the logits by this value.
|
| 87 |
+
no_bias (`bool`, *optional*, defaults to `True`):
|
| 88 |
+
Whether to use bias in all linear layers.
|
| 89 |
+
embedding_fraction (`float`, *optional*, defaults to 1.0):
|
| 90 |
+
The fraction to scale the gradients of the embedding layer by.
|
| 91 |
+
norm_type (`str`, *optional*, defaults to `"low_precision_layernorm"`):
|
| 92 |
+
Type of layer norm to use. All MPT models uses the same layer norm implementation. Defined for backward
|
| 93 |
+
compatibility.
|
| 94 |
+
|
| 95 |
+
Example:
|
| 96 |
+
|
| 97 |
+
```python
|
| 98 |
+
>>> from transformers import MptConfig, MptModel
|
| 99 |
+
|
| 100 |
+
>>> # Initializing a Mpt configuration
|
| 101 |
+
>>> configuration = MptConfig()
|
| 102 |
+
|
| 103 |
+
>>> # Initializing a model (with random weights) from the configuration
|
| 104 |
+
>>> model = MptModel(configuration)
|
| 105 |
+
|
| 106 |
+
>>> # Accessing the model configuration
|
| 107 |
+
>>> configuration = model.config
|
| 108 |
+
```
|
| 109 |
+
"""
|
| 110 |
+
|
| 111 |
+
model_type = "mpt"
|
| 112 |
+
sub_configs = {"attn_config": MptAttentionConfig}
|
| 113 |
+
attribute_map = {
|
| 114 |
+
"num_attention_heads": "n_heads",
|
| 115 |
+
"hidden_size": "d_model",
|
| 116 |
+
"num_hidden_layers": "n_layers",
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
d_model: int = 2048
|
| 120 |
+
n_heads: int = 16
|
| 121 |
+
n_layers: int = 24
|
| 122 |
+
expansion_ratio: int = 4
|
| 123 |
+
max_seq_len: int = 2048
|
| 124 |
+
vocab_size: int = 50368
|
| 125 |
+
resid_pdrop: float | int = 0.0
|
| 126 |
+
layer_norm_epsilon: float = 1e-5
|
| 127 |
+
emb_pdrop: float | int = 0.0
|
| 128 |
+
learned_pos_emb: bool = True
|
| 129 |
+
attn_config: dict | MptAttentionConfig | None = None
|
| 130 |
+
init_device: str = "cpu"
|
| 131 |
+
logit_scale: float | str | None = None
|
| 132 |
+
no_bias: bool = True
|
| 133 |
+
embedding_fraction: float = 1.0
|
| 134 |
+
norm_type: str = "low_precision_layernorm"
|
| 135 |
+
use_cache: bool = False
|
| 136 |
+
initializer_range: float = 0.02
|
| 137 |
+
tie_word_embeddings: bool = True
|
| 138 |
+
pad_token_id: int | None = None
|
| 139 |
+
bos_token_id: int | None = None
|
| 140 |
+
eos_token_id: int | list[int] | None = None
|
| 141 |
+
|
| 142 |
+
def __post_init__(self, **kwargs):
|
| 143 |
+
if self.attn_config is None:
|
| 144 |
+
self.attn_config = MptAttentionConfig()
|
| 145 |
+
elif isinstance(self.attn_config, dict):
|
| 146 |
+
self.attn_config = MptAttentionConfig(**self.attn_config)
|
| 147 |
+
super().__post_init__(**kwargs)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
__all__ = ["MptConfig"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/sam2_video/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_sam2_video import *
|
| 22 |
+
from .modeling_sam2_video import *
|
| 23 |
+
from .processing_sam2_video import *
|
| 24 |
+
from .video_processing_sam2_video import *
|
| 25 |
+
else:
|
| 26 |
+
import sys
|
| 27 |
+
|
| 28 |
+
_file = globals()["__file__"]
|
| 29 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/trans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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/sam2_video/modular_sam2_video.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_sam2_video.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2025 The Meta AI Authors and The HuggingFace Team. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
from huggingface_hub.dataclasses import strict
|
| 21 |
+
|
| 22 |
+
from ...configuration_utils import PreTrainedConfig
|
| 23 |
+
from ...utils import auto_docstring
|
| 24 |
+
from ..auto import CONFIG_MAPPING, AutoConfig
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@auto_docstring(checkpoint="facebook/sam2_video.1-hiera-tiny")
|
| 28 |
+
@strict
|
| 29 |
+
class Sam2VideoPromptEncoderConfig(PreTrainedConfig):
|
| 30 |
+
r"""
|
| 31 |
+
mask_input_channels (`int`, *optional*, defaults to 16):
|
| 32 |
+
The number of channels to be fed to the `MaskDecoder` module.
|
| 33 |
+
num_point_embeddings (`int`, *optional*, defaults to 4):
|
| 34 |
+
The number of point embeddings to be used.
|
| 35 |
+
scale (`float`, *optional*, defaults to 1):
|
| 36 |
+
The scale factor for the prompt encoder.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
base_config_key = "prompt_encoder_config"
|
| 40 |
+
|
| 41 |
+
hidden_size: int = 256
|
| 42 |
+
image_size: int | list[int] | tuple[int, int] = 1024
|
| 43 |
+
patch_size: int | list[int] | tuple[int, int] = 16
|
| 44 |
+
mask_input_channels: int = 16
|
| 45 |
+
num_point_embeddings: int = 4
|
| 46 |
+
hidden_act: str = "gelu"
|
| 47 |
+
layer_norm_eps: float = 1e-6
|
| 48 |
+
scale: int = 1
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@auto_docstring(checkpoint="facebook/sam2_video.1-hiera-tiny")
|
| 52 |
+
@strict
|
| 53 |
+
class Sam2VideoMaskDecoderConfig(PreTrainedConfig):
|
| 54 |
+
r"""
|
| 55 |
+
mlp_dim (`int`, *optional*, defaults to 2048):
|
| 56 |
+
The dimension of the MLP in the two-way transformer.
|
| 57 |
+
attention_downsample_rate (`int`, *optional*, defaults to 2):
|
| 58 |
+
The downsample rate for the attention layers.
|
| 59 |
+
num_multimask_outputs (`int`, *optional*, defaults to 3):
|
| 60 |
+
The number of multimask outputs.
|
| 61 |
+
iou_head_depth (`int`, *optional*, defaults to 3):
|
| 62 |
+
The depth of the IoU head.
|
| 63 |
+
iou_head_hidden_dim (`int`, *optional*, defaults to 256):
|
| 64 |
+
The hidden dimension of the IoU head.
|
| 65 |
+
dynamic_multimask_via_stability (`bool`, *optional*, defaults to `True`):
|
| 66 |
+
Whether to use dynamic multimask via stability.
|
| 67 |
+
dynamic_multimask_stability_delta (`float`, *optional*, defaults to 0.05):
|
| 68 |
+
The stability delta for the dynamic multimask.
|
| 69 |
+
dynamic_multimask_stability_thresh (`float`, *optional*, defaults to 0.98):
|
| 70 |
+
The stability threshold for the dynamic multimask.
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
base_config_key = "mask_decoder_config"
|
| 74 |
+
|
| 75 |
+
hidden_size: int = 256
|
| 76 |
+
hidden_act: str = "gelu"
|
| 77 |
+
mlp_dim: int = 2048
|
| 78 |
+
num_hidden_layers: int = 2
|
| 79 |
+
num_attention_heads: int = 8
|
| 80 |
+
attention_downsample_rate: int = 2
|
| 81 |
+
num_multimask_outputs: int = 3
|
| 82 |
+
iou_head_depth: int = 3
|
| 83 |
+
iou_head_hidden_dim: int = 256
|
| 84 |
+
dynamic_multimask_via_stability: bool = True
|
| 85 |
+
dynamic_multimask_stability_delta: float = 0.05
|
| 86 |
+
dynamic_multimask_stability_thresh: float = 0.98
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
@auto_docstring(checkpoint="facebook/sam2.1-hiera-tiny")
|
| 90 |
+
@strict
|
| 91 |
+
class Sam2VideoConfig(PreTrainedConfig):
|
| 92 |
+
r"""
|
| 93 |
+
prompt_encoder_config (Union[`dict`, `Sam2PromptEncoderConfig`], *optional*):
|
| 94 |
+
Dictionary of configuration options used to initialize [`Sam2PromptEncoderConfig`].
|
| 95 |
+
mask_decoder_config (Union[`dict`, `Sam2MaskDecoderConfig`], *optional*):
|
| 96 |
+
Dictionary of configuration options used to initialize [`Sam2MaskDecoderConfig`].
|
| 97 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 98 |
+
Standard deviation for parameter initialization.
|
| 99 |
+
num_maskmem (`int`, *optional*, defaults to 7):
|
| 100 |
+
The number of memory slots for the mask memory.
|
| 101 |
+
sigmoid_scale_for_mem_enc (`float`, *optional*, defaults to 20.0):
|
| 102 |
+
Scale factor for the sigmoid function in the memory encoder.
|
| 103 |
+
sigmoid_bias_for_mem_enc (`float`, *optional*, defaults to -10.0):
|
| 104 |
+
Bias for the sigmoid function in the memory encoder.
|
| 105 |
+
enable_occlusion_spatial_embedding (`bool`, *optional*, defaults to `True`):
|
| 106 |
+
Whether to enable spatial embedding for occlusions.
|
| 107 |
+
multimask_output_in_sam (`bool`, *optional*, defaults to `True`):
|
| 108 |
+
Whether to output multiple masks from the SAM head.
|
| 109 |
+
multimask_min_pt_num (`int`, *optional*, defaults to 0):
|
| 110 |
+
The minimum number of points to trigger multimask output.
|
| 111 |
+
multimask_max_pt_num (`int`, *optional*, defaults to 1):
|
| 112 |
+
The maximum number of points to trigger multimask output.
|
| 113 |
+
multimask_output_for_tracking (`bool`, *optional*, defaults to `True`):
|
| 114 |
+
Whether to use multimask output for tracking.
|
| 115 |
+
max_object_pointers_in_encoder (`int`, *optional*, defaults to 16):
|
| 116 |
+
The maximum number of object pointers in the encoder.
|
| 117 |
+
max_cond_frame_num (`int`, *optional*, defaults to -1):
|
| 118 |
+
Maximum number of conditioning frames to use in memory attention. Set to -1 to use all conditioning frames.
|
| 119 |
+
enable_temporal_pos_encoding_for_object_pointers (`bool`, *optional*, defaults to `True`):
|
| 120 |
+
Whether to enable temporal positional encoding for object pointers.
|
| 121 |
+
memory_attention_hidden_size (`int`, *optional*, defaults to 256):
|
| 122 |
+
Dimensionality of the memory attention hidden states.
|
| 123 |
+
memory_attention_num_layers (`int`, *optional*, defaults to 4):
|
| 124 |
+
The number of layers in the memory attention module.
|
| 125 |
+
memory_attention_num_attention_heads (`int`, *optional*, defaults to 1):
|
| 126 |
+
Number of attention heads for each attention layer in the memory attention.
|
| 127 |
+
memory_attention_downsample_rate (`int`, *optional*, defaults to 1):
|
| 128 |
+
The downsample rate for the attention layers.
|
| 129 |
+
memory_attention_feed_forward_hidden_size (`int`, *optional*, defaults to 2048):
|
| 130 |
+
The dimension of the feedforward network in the memory attention module.
|
| 131 |
+
memory_attention_feed_forward_hidden_act (`str`, *optional*, defaults to `"relu"`):
|
| 132 |
+
The non-linear activation function in the feedforward network in the memory attention module.
|
| 133 |
+
memory_attention_dropout (`float`, *optional*, defaults to 0.1):
|
| 134 |
+
The dropout rate for the memory attention module.
|
| 135 |
+
memory_attention_rope_theta (`float`, *optional*, defaults to 10000):
|
| 136 |
+
The Rope theta parameter.
|
| 137 |
+
memory_attention_rope_feat_sizes (`list[int]`, *optional*, defaults to `[64, 64]`):
|
| 138 |
+
The feature sizes for the Rope positional encoding.
|
| 139 |
+
memory_attention_rope_dropout (`float`, *optional*, defaults to 0.1):
|
| 140 |
+
The dropout rate for the Rope positional encoding.
|
| 141 |
+
memory_encoder_hidden_size (`int`, *optional*, defaults to 256):
|
| 142 |
+
Dimensionality of the memory encoder hidden states.
|
| 143 |
+
memory_encoder_output_channels (`int`, *optional*, defaults to 64):
|
| 144 |
+
The number of output channels for the memory encoder.
|
| 145 |
+
mask_downsampler_embed_dim (`int`, *optional*, defaults to 256):
|
| 146 |
+
The dimension of the mask downsampler embedding.
|
| 147 |
+
mask_downsampler_kernel_size (`int`, *optional*, defaults to 3):
|
| 148 |
+
The kernel size for the mask downsampler.
|
| 149 |
+
mask_downsampler_stride (`int`, *optional*, defaults to 2):
|
| 150 |
+
The stride for the mask downsampler.
|
| 151 |
+
mask_downsampler_padding (`int`, *optional*, defaults to 1):
|
| 152 |
+
The padding for the mask downsampler.
|
| 153 |
+
mask_downsampler_total_stride (`int`, *optional*, defaults to 16):
|
| 154 |
+
The total stride for the mask downsampler.
|
| 155 |
+
mask_downsampler_hidden_act (`str`, *optional*, defaults to `"gelu"`):
|
| 156 |
+
The non-linear activation function in the mask downsampler.
|
| 157 |
+
memory_fuser_num_layers (`int`, *optional*, defaults to 2):
|
| 158 |
+
The number of layers in the memory fuser.
|
| 159 |
+
memory_fuser_embed_dim (`int`, *optional*, defaults to 256):
|
| 160 |
+
The dimension of the embedding layer in the memory fuser.
|
| 161 |
+
memory_fuser_intermediate_dim (`int`, *optional*, defaults to 1024):
|
| 162 |
+
The dimension of the intermediate layer in the memory fuser.
|
| 163 |
+
memory_fuser_kernel_size (`int`, *optional*, defaults to 7):
|
| 164 |
+
The kernel size for the memory fuser.
|
| 165 |
+
memory_fuser_padding (`int`, *optional*, defaults to 3):
|
| 166 |
+
The padding for the memory fuser.
|
| 167 |
+
memory_fuser_layer_scale_init_value (`float`, *optional*, defaults to 1e-06):
|
| 168 |
+
The initial value for the layer scale in the memory fuser.
|
| 169 |
+
memory_fuser_hidden_act (`str`, *optional*, defaults to `"gelu"`):
|
| 170 |
+
The non-linear activation function in the memory fuser..
|
| 171 |
+
|
| 172 |
+
Example:
|
| 173 |
+
|
| 174 |
+
```python
|
| 175 |
+
>>> from transformers import (
|
| 176 |
+
... Sam2VisionConfig,
|
| 177 |
+
... Sam2PromptEncoderConfig,
|
| 178 |
+
... Sam2MaskDecoderConfig,
|
| 179 |
+
... Sam2Model,
|
| 180 |
+
... )
|
| 181 |
+
|
| 182 |
+
>>> # Initializing a Sam2Config with `"facebook/sam2.1_hiera_tiny"` style configuration
|
| 183 |
+
>>> configuration = Sam2config()
|
| 184 |
+
|
| 185 |
+
>>> # Initializing a Sam2Model (with random weights) from the `"facebook/sam2.1_hiera_tiny"` style configuration
|
| 186 |
+
>>> model = Sam2Model(configuration)
|
| 187 |
+
|
| 188 |
+
>>> # Accessing the model configuration
|
| 189 |
+
>>> configuration = model.config
|
| 190 |
+
|
| 191 |
+
>>> # We can also initialize a Sam2Config from a Sam2VisionConfig, Sam2PromptEncoderConfig, and Sam2MaskDecoderConfig
|
| 192 |
+
|
| 193 |
+
>>> # Initializing SAM2 vision encoder, memory attention, and memory encoder configurations
|
| 194 |
+
>>> vision_config = Sam2VisionConfig()
|
| 195 |
+
>>> prompt_encoder_config = Sam2PromptEncoderConfig()
|
| 196 |
+
>>> mask_decoder_config = Sam2MaskDecoderConfig()
|
| 197 |
+
|
| 198 |
+
>>> config = Sam2Config(vision_config, prompt_encoder_config, mask_decoder_config)
|
| 199 |
+
```"""
|
| 200 |
+
|
| 201 |
+
model_type = "sam2_video"
|
| 202 |
+
sub_configs = {
|
| 203 |
+
"vision_config": AutoConfig,
|
| 204 |
+
"prompt_encoder_config": Sam2VideoPromptEncoderConfig,
|
| 205 |
+
"mask_decoder_config": Sam2VideoMaskDecoderConfig,
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
vision_config: dict | PreTrainedConfig | None = None
|
| 209 |
+
prompt_encoder_config: dict | PreTrainedConfig | None = None
|
| 210 |
+
mask_decoder_config: dict | PreTrainedConfig | None = None
|
| 211 |
+
initializer_range: float = 0.02
|
| 212 |
+
num_maskmem: int = 7
|
| 213 |
+
image_size: int | list[int] | tuple[int, int] = 1024
|
| 214 |
+
sigmoid_scale_for_mem_enc: float = 20.0
|
| 215 |
+
sigmoid_bias_for_mem_enc: float = -10.0
|
| 216 |
+
enable_occlusion_spatial_embedding: bool = True
|
| 217 |
+
multimask_output_in_sam: bool = True
|
| 218 |
+
multimask_min_pt_num: int = 0
|
| 219 |
+
multimask_max_pt_num: int = 1
|
| 220 |
+
multimask_output_for_tracking: bool = True
|
| 221 |
+
max_object_pointers_in_encoder: int = 16
|
| 222 |
+
max_cond_frame_num: int = -1
|
| 223 |
+
enable_temporal_pos_encoding_for_object_pointers: bool = True
|
| 224 |
+
memory_attention_hidden_size: int = 256
|
| 225 |
+
memory_attention_num_layers: int = 4
|
| 226 |
+
memory_attention_num_attention_heads: int = 1
|
| 227 |
+
memory_attention_downsample_rate: int = 1
|
| 228 |
+
memory_attention_feed_forward_hidden_size: int = 2048
|
| 229 |
+
memory_attention_feed_forward_hidden_act: str = "relu"
|
| 230 |
+
memory_attention_dropout: float | int = 0.1
|
| 231 |
+
memory_attention_rope_theta: int = 10000
|
| 232 |
+
memory_attention_rope_feat_sizes: list[int] | None = None
|
| 233 |
+
memory_attention_rope_dropout: float | int = 0.1
|
| 234 |
+
memory_encoder_hidden_size: int = 256
|
| 235 |
+
memory_encoder_output_channels: int = 64
|
| 236 |
+
mask_downsampler_embed_dim: int = 256
|
| 237 |
+
mask_downsampler_kernel_size: int = 3
|
| 238 |
+
mask_downsampler_stride: int = 2
|
| 239 |
+
mask_downsampler_padding: int = 1
|
| 240 |
+
mask_downsampler_total_stride: int = 16
|
| 241 |
+
mask_downsampler_hidden_act: str = "gelu"
|
| 242 |
+
memory_fuser_num_layers: int = 2
|
| 243 |
+
memory_fuser_embed_dim: int = 256
|
| 244 |
+
memory_fuser_intermediate_dim: int = 1024
|
| 245 |
+
memory_fuser_kernel_size: int = 7
|
| 246 |
+
memory_fuser_padding: int = 3
|
| 247 |
+
memory_fuser_layer_scale_init_value: float = 1e-6
|
| 248 |
+
memory_fuser_hidden_act: str = "gelu"
|
| 249 |
+
|
| 250 |
+
def __post_init__(self, **kwargs):
|
| 251 |
+
self.memory_attention_rope_feat_sizes = (
|
| 252 |
+
[64, 64] if self.memory_attention_rope_feat_sizes is None else self.memory_attention_rope_feat_sizes
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
if isinstance(self.vision_config, dict):
|
| 256 |
+
self.vision_config["model_type"] = self.vision_config.get("model_type", "sam2_vision_model")
|
| 257 |
+
self.vision_config = CONFIG_MAPPING[self.vision_config["model_type"]](**self.vision_config)
|
| 258 |
+
elif self.vision_config is None:
|
| 259 |
+
self.vision_config = CONFIG_MAPPING["sam2_vision_model"]()
|
| 260 |
+
|
| 261 |
+
if isinstance(self.prompt_encoder_config, dict):
|
| 262 |
+
self.prompt_encoder_config = Sam2VideoPromptEncoderConfig(**self.prompt_encoder_config)
|
| 263 |
+
elif self.prompt_encoder_config is None:
|
| 264 |
+
self.prompt_encoder_config = Sam2VideoPromptEncoderConfig()
|
| 265 |
+
|
| 266 |
+
if isinstance(self.mask_decoder_config, dict):
|
| 267 |
+
self.mask_decoder_config = Sam2VideoPromptEncoderConfig(**self.mask_decoder_config)
|
| 268 |
+
elif self.mask_decoder_config is None:
|
| 269 |
+
self.mask_decoder_config = Sam2VideoMaskDecoderConfig()
|
| 270 |
+
|
| 271 |
+
super().__post_init__(**kwargs)
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
__all__ = ["Sam2VideoMaskDecoderConfig", "Sam2VideoPromptEncoderConfig", "Sam2VideoConfig"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/sam2_video/modular_sam2_video.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/sam2_video/processing_sam2_video.py
ADDED
|
@@ -0,0 +1,801 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/sam2_video/modular_sam2_video.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_sam2_video.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2025 The Meta AI Authors and The HuggingFace Team. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
from copy import deepcopy
|
| 21 |
+
from typing import Union
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
import torch
|
| 25 |
+
|
| 26 |
+
from ...image_utils import ImageInput
|
| 27 |
+
from ...processing_utils import ProcessorMixin
|
| 28 |
+
from ...tokenization_utils_base import BatchEncoding
|
| 29 |
+
from ...utils import TensorType, auto_docstring
|
| 30 |
+
from ...utils.import_utils import requires
|
| 31 |
+
from ...video_utils import VideoInput
|
| 32 |
+
from .modeling_sam2_video import Sam2VideoInferenceSession
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@requires(backends=("torch",))
|
| 36 |
+
@auto_docstring
|
| 37 |
+
class Sam2VideoProcessor(ProcessorMixin):
|
| 38 |
+
def __init__(
|
| 39 |
+
self, image_processor, video_processor, target_size: int | None = None, point_pad_value: int = -10, **kwargs
|
| 40 |
+
):
|
| 41 |
+
r"""
|
| 42 |
+
target_size (`int`, *optional*):
|
| 43 |
+
The target size (in pixels) for normalizing input points and bounding boxes. If not provided, defaults
|
| 44 |
+
to the image processor's size configuration. All input coordinates (points and boxes) are normalized
|
| 45 |
+
to this size before being passed to the model. This ensures consistent coordinate representation
|
| 46 |
+
regardless of the original image dimensions.
|
| 47 |
+
point_pad_value (`int`, *optional*, defaults to -10):
|
| 48 |
+
The value used for padding input points when batching sequences of different lengths. This value is
|
| 49 |
+
used to mark padded positions and is preserved during coordinate normalization.
|
| 50 |
+
"""
|
| 51 |
+
super().__init__(image_processor, video_processor, **kwargs)
|
| 52 |
+
self.point_pad_value = point_pad_value
|
| 53 |
+
self.target_size = target_size if target_size is not None else self.image_processor.size["height"]
|
| 54 |
+
|
| 55 |
+
@auto_docstring
|
| 56 |
+
def __call__(
|
| 57 |
+
self,
|
| 58 |
+
images: ImageInput | None = None,
|
| 59 |
+
segmentation_maps: ImageInput | None = None,
|
| 60 |
+
input_points: list[list[list[list[float]]]] | torch.Tensor | None = None,
|
| 61 |
+
input_labels: list[list[list[int]]] | torch.Tensor | None = None,
|
| 62 |
+
input_boxes: list[list[list[float]]] | torch.Tensor | None = None,
|
| 63 |
+
original_sizes: list[list[float]] | torch.Tensor | None = None,
|
| 64 |
+
return_tensors: str | TensorType | None = None,
|
| 65 |
+
**kwargs,
|
| 66 |
+
) -> BatchEncoding:
|
| 67 |
+
r"""
|
| 68 |
+
segmentation_maps (`ImageInput`, *optional*):
|
| 69 |
+
The segmentation maps to process.
|
| 70 |
+
input_points (`list[list[list[list[float]]]]`, `torch.Tensor`, *optional*):
|
| 71 |
+
The points to add to the frame.
|
| 72 |
+
input_labels (`list[list[list[int]]]`, `torch.Tensor`, *optional*):
|
| 73 |
+
The labels for the points.
|
| 74 |
+
input_boxes (`list[list[list[float]]]`, `torch.Tensor`, *optional*):
|
| 75 |
+
The bounding boxes to add to the frame.
|
| 76 |
+
original_sizes (`list[list[float]]`, `torch.Tensor`, *optional*):
|
| 77 |
+
The original sizes of the images.
|
| 78 |
+
|
| 79 |
+
Returns:
|
| 80 |
+
A [`BatchEncoding`] with the following fields:
|
| 81 |
+
- `pixel_values` (`torch.Tensor`): The processed image(s).
|
| 82 |
+
- `original_sizes` (`list[list[float]]`): The original sizes of the images.
|
| 83 |
+
- `labels` (`torch.Tensor`): The processed segmentation maps (if provided).
|
| 84 |
+
- `input_points` (`torch.Tensor`): The processed points.
|
| 85 |
+
- `input_labels` (`torch.Tensor`): The processed labels.
|
| 86 |
+
- `input_boxes` (`torch.Tensor`): The processed bounding boxes.
|
| 87 |
+
"""
|
| 88 |
+
if images is not None:
|
| 89 |
+
encoding_image_processor = self.image_processor(
|
| 90 |
+
images,
|
| 91 |
+
segmentation_maps=segmentation_maps,
|
| 92 |
+
return_tensors=return_tensors,
|
| 93 |
+
**kwargs,
|
| 94 |
+
)
|
| 95 |
+
elif original_sizes is not None:
|
| 96 |
+
if isinstance(original_sizes, torch.Tensor):
|
| 97 |
+
original_sizes = original_sizes.cpu().tolist()
|
| 98 |
+
encoding_image_processor = BatchEncoding({"original_sizes": original_sizes}, tensor_type=return_tensors)
|
| 99 |
+
else:
|
| 100 |
+
raise ValueError("Either images or original_sizes must be provided")
|
| 101 |
+
|
| 102 |
+
# pop arguments that are not used in the forward but used nevertheless
|
| 103 |
+
original_sizes = encoding_image_processor["original_sizes"]
|
| 104 |
+
# Check original_sizes is of length 1 or len(images)
|
| 105 |
+
if images is not None and len(original_sizes) != 1 and len(original_sizes) != len(images):
|
| 106 |
+
raise ValueError(
|
| 107 |
+
"original_sizes must be of length 1 or len(images). If you are passing a single image, you must pass a single original_size."
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
# Process input points, labels, and boxes if provided
|
| 111 |
+
if input_points is not None or input_labels is not None or input_boxes is not None:
|
| 112 |
+
# Validate and convert inputs to standardized format
|
| 113 |
+
processed_points = self._validate_single_input(
|
| 114 |
+
input_points,
|
| 115 |
+
expected_depth=4,
|
| 116 |
+
input_name="points",
|
| 117 |
+
expected_format="[image level, object level, point level, point coordinates]",
|
| 118 |
+
expected_coord_size=2,
|
| 119 |
+
)
|
| 120 |
+
processed_labels = self._validate_single_input(
|
| 121 |
+
input_labels,
|
| 122 |
+
expected_depth=3,
|
| 123 |
+
input_name="labels",
|
| 124 |
+
expected_format="[image level, object level, point level]",
|
| 125 |
+
)
|
| 126 |
+
processed_boxes = self._validate_single_input(
|
| 127 |
+
input_boxes,
|
| 128 |
+
expected_depth=3,
|
| 129 |
+
input_name="boxes",
|
| 130 |
+
expected_format="[image level, box level, box coordinates]",
|
| 131 |
+
expected_coord_size=4,
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
# Get padding requirements for all inputs
|
| 135 |
+
if processed_points is not None:
|
| 136 |
+
points_max_dims = self._get_nested_dimensions(processed_points)[:3]
|
| 137 |
+
if processed_labels is not None:
|
| 138 |
+
labels_max_dims = self._get_nested_dimensions(processed_labels)[:3]
|
| 139 |
+
if processed_boxes is not None:
|
| 140 |
+
boxes_max_dims = self._get_nested_dimensions(processed_boxes)[:2]
|
| 141 |
+
|
| 142 |
+
# Ensure points and labels have consistent dimensions
|
| 143 |
+
if processed_points is not None and processed_labels is not None:
|
| 144 |
+
if points_max_dims != labels_max_dims:
|
| 145 |
+
raise ValueError(
|
| 146 |
+
"Input points and labels have inconsistent dimensions. Please ensure they have the same dimensions."
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
# Check that boxes don't need padding (model limitation)
|
| 150 |
+
if processed_boxes is not None and len(processed_boxes) >= 2:
|
| 151 |
+
if any(len(img_boxes) < boxes_max_dims[1] for img_boxes in processed_boxes):
|
| 152 |
+
raise ValueError(
|
| 153 |
+
"Input boxes have inconsistent dimensions that would require padding, "
|
| 154 |
+
"but boxes cannot be padded due to model limitations. "
|
| 155 |
+
"Please ensure all images have the same number of boxes."
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
# Pad and normalize all inputs to final tensor format
|
| 159 |
+
if processed_points is not None:
|
| 160 |
+
padded_points = self._pad_nested_list(processed_points, points_max_dims + [2])
|
| 161 |
+
final_points = torch.tensor(padded_points, dtype=torch.float32)
|
| 162 |
+
self._normalize_tensor_coordinates(final_points, original_sizes, preserve_padding=True)
|
| 163 |
+
encoding_image_processor.update({"input_points": final_points})
|
| 164 |
+
|
| 165 |
+
if processed_labels is not None:
|
| 166 |
+
padded_labels = self._pad_nested_list(processed_labels, labels_max_dims)
|
| 167 |
+
final_labels = torch.tensor(padded_labels, dtype=torch.int64)
|
| 168 |
+
encoding_image_processor.update({"input_labels": final_labels})
|
| 169 |
+
|
| 170 |
+
if processed_boxes is not None:
|
| 171 |
+
final_boxes = torch.tensor(processed_boxes, dtype=torch.float32)
|
| 172 |
+
self._normalize_tensor_coordinates(final_boxes, original_sizes, is_bounding_box=True)
|
| 173 |
+
encoding_image_processor.update({"input_boxes": final_boxes})
|
| 174 |
+
|
| 175 |
+
return encoding_image_processor
|
| 176 |
+
|
| 177 |
+
def _normalize_coordinates(
|
| 178 |
+
self, target_size: int, coords: "torch.Tensor", original_size, is_bounding_box=False
|
| 179 |
+
) -> "torch.Tensor":
|
| 180 |
+
"""
|
| 181 |
+
Expects a numpy array of length 2 in the final dimension. Requires the original image size in (H, W) format.
|
| 182 |
+
|
| 183 |
+
Args:
|
| 184 |
+
target_size (`int`):
|
| 185 |
+
The target size of the image.
|
| 186 |
+
coords (`torch.Tensor`):
|
| 187 |
+
The coordinates to be normalized.
|
| 188 |
+
original_size (`tuple`):
|
| 189 |
+
The original size of the image.
|
| 190 |
+
is_bounding_box (`bool`, *optional*, defaults to `False`):
|
| 191 |
+
Whether the coordinates are bounding boxes.
|
| 192 |
+
"""
|
| 193 |
+
old_h, old_w = original_size
|
| 194 |
+
new_h, new_w = target_size, target_size
|
| 195 |
+
coords = deepcopy(coords).float()
|
| 196 |
+
|
| 197 |
+
if is_bounding_box:
|
| 198 |
+
coords = coords.reshape(-1, 2, 2)
|
| 199 |
+
coords[..., 0] = coords[..., 0] * (new_w / old_w)
|
| 200 |
+
coords[..., 1] = coords[..., 1] * (new_h / old_h)
|
| 201 |
+
|
| 202 |
+
if is_bounding_box:
|
| 203 |
+
coords = coords.reshape(-1, 4)
|
| 204 |
+
|
| 205 |
+
return coords
|
| 206 |
+
|
| 207 |
+
def _convert_to_nested_list(self, data, expected_depth, current_depth=0):
|
| 208 |
+
"""
|
| 209 |
+
Recursively convert various input formats (tensors, numpy arrays, lists) to nested lists.
|
| 210 |
+
|
| 211 |
+
Args:
|
| 212 |
+
data: Input data in any format
|
| 213 |
+
expected_depth: Expected nesting depth
|
| 214 |
+
current_depth: Current depth in recursion
|
| 215 |
+
|
| 216 |
+
Returns:
|
| 217 |
+
Nested list representation of the data
|
| 218 |
+
"""
|
| 219 |
+
if data is None:
|
| 220 |
+
return None
|
| 221 |
+
|
| 222 |
+
# Convert tensor/numpy to list if we're at a leaf level or if it's a multi-dimensional array
|
| 223 |
+
if isinstance(data, torch.Tensor): # PyTorch tensor
|
| 224 |
+
if current_depth == expected_depth - 2 or len(data.shape) <= 2: # At coordinate level or small tensor
|
| 225 |
+
return data.numpy().tolist()
|
| 226 |
+
else:
|
| 227 |
+
return [self._convert_to_nested_list(item, expected_depth, current_depth + 1) for item in data]
|
| 228 |
+
elif isinstance(data, np.ndarray): # NumPy array
|
| 229 |
+
if current_depth == expected_depth - 2 or len(data.shape) <= 2: # At coordinate level or small array
|
| 230 |
+
return data.tolist()
|
| 231 |
+
else:
|
| 232 |
+
return [self._convert_to_nested_list(item, expected_depth, current_depth + 1) for item in data]
|
| 233 |
+
elif isinstance(data, list):
|
| 234 |
+
if current_depth == expected_depth:
|
| 235 |
+
# We've reached the expected depth, return as is
|
| 236 |
+
return data
|
| 237 |
+
else:
|
| 238 |
+
# Continue recursion
|
| 239 |
+
return [self._convert_to_nested_list(item, expected_depth, current_depth + 1) for item in data]
|
| 240 |
+
elif isinstance(data, (int, float)):
|
| 241 |
+
return data
|
| 242 |
+
else:
|
| 243 |
+
raise TypeError(f"Unsupported data type: {type(data)}")
|
| 244 |
+
|
| 245 |
+
def _get_nested_dimensions(self, nested_list, max_dims=None):
|
| 246 |
+
"""
|
| 247 |
+
Get the maximum dimensions at each level of nesting.
|
| 248 |
+
|
| 249 |
+
Args:
|
| 250 |
+
nested_list (`list`):
|
| 251 |
+
Nested list structure.
|
| 252 |
+
max_dims (`list`, *optional*):
|
| 253 |
+
Current maximum dimensions (for recursion).
|
| 254 |
+
|
| 255 |
+
Returns:
|
| 256 |
+
`list`: A list of maximum dimensions for each nesting level.
|
| 257 |
+
"""
|
| 258 |
+
if max_dims is None:
|
| 259 |
+
max_dims = []
|
| 260 |
+
|
| 261 |
+
if not isinstance(nested_list, list):
|
| 262 |
+
return max_dims
|
| 263 |
+
|
| 264 |
+
if len(max_dims) == 0:
|
| 265 |
+
max_dims.append(len(nested_list))
|
| 266 |
+
else:
|
| 267 |
+
max_dims[0] = max(max_dims[0], len(nested_list))
|
| 268 |
+
|
| 269 |
+
if len(nested_list) > 0:
|
| 270 |
+
for item in nested_list:
|
| 271 |
+
if isinstance(item, list):
|
| 272 |
+
sub_dims = self._get_nested_dimensions(item)
|
| 273 |
+
# Merge sub_dims into max_dims
|
| 274 |
+
for i, dim in enumerate(sub_dims):
|
| 275 |
+
if i + 1 >= len(max_dims):
|
| 276 |
+
max_dims.append(dim)
|
| 277 |
+
else:
|
| 278 |
+
max_dims[i + 1] = max(max_dims[i + 1], dim)
|
| 279 |
+
|
| 280 |
+
return max_dims
|
| 281 |
+
|
| 282 |
+
def _pad_nested_list(self, nested_list, target_dims, current_level=0, pad_value=None):
|
| 283 |
+
"""
|
| 284 |
+
Recursively pad a nested list to match target dimensions.
|
| 285 |
+
|
| 286 |
+
Args:
|
| 287 |
+
nested_list (`list`):
|
| 288 |
+
Nested list to pad.
|
| 289 |
+
target_dims (`list`):
|
| 290 |
+
Target dimensions for each level.
|
| 291 |
+
current_level (`int`, *optional*, defaults to 0):
|
| 292 |
+
Current nesting level.
|
| 293 |
+
pad_value (`int`, *optional*):
|
| 294 |
+
Value to use for padding.
|
| 295 |
+
|
| 296 |
+
Returns:
|
| 297 |
+
`list`: The padded nested list.
|
| 298 |
+
"""
|
| 299 |
+
if pad_value is None:
|
| 300 |
+
pad_value = self.point_pad_value
|
| 301 |
+
|
| 302 |
+
if current_level >= len(target_dims):
|
| 303 |
+
return nested_list
|
| 304 |
+
|
| 305 |
+
# Ensure we have a list
|
| 306 |
+
if not isinstance(nested_list, list):
|
| 307 |
+
nested_list = [nested_list]
|
| 308 |
+
|
| 309 |
+
# Pad current level
|
| 310 |
+
current_size = len(nested_list)
|
| 311 |
+
target_size = target_dims[current_level]
|
| 312 |
+
|
| 313 |
+
# Pad with appropriate values
|
| 314 |
+
if current_level == len(target_dims) - 1:
|
| 315 |
+
# At the coordinate level, pad with pad_value
|
| 316 |
+
nested_list.extend([pad_value] * (target_size - current_size))
|
| 317 |
+
else:
|
| 318 |
+
# At higher levels, pad with nested structures
|
| 319 |
+
if current_size > 0:
|
| 320 |
+
# Create appropriately sized template
|
| 321 |
+
if current_level < len(target_dims) - 2:
|
| 322 |
+
# For non-coordinate levels, create empty nested structure
|
| 323 |
+
template_dims = target_dims[current_level + 1 :]
|
| 324 |
+
template = self._create_empty_nested_structure(template_dims, pad_value)
|
| 325 |
+
else:
|
| 326 |
+
# For coordinate level, create list of pad_values
|
| 327 |
+
template = [pad_value] * target_dims[current_level + 1]
|
| 328 |
+
|
| 329 |
+
nested_list.extend([deepcopy(template) for _ in range(target_size - current_size)])
|
| 330 |
+
else:
|
| 331 |
+
# Create from scratch
|
| 332 |
+
template_dims = target_dims[current_level + 1 :]
|
| 333 |
+
template = self._create_empty_nested_structure(template_dims, pad_value)
|
| 334 |
+
nested_list.extend([deepcopy(template) for _ in range(target_size)])
|
| 335 |
+
|
| 336 |
+
# Recursively pad sublists
|
| 337 |
+
if current_level < len(target_dims) - 1:
|
| 338 |
+
for i in range(len(nested_list)):
|
| 339 |
+
if isinstance(nested_list[i], list):
|
| 340 |
+
nested_list[i] = self._pad_nested_list(nested_list[i], target_dims, current_level + 1, pad_value)
|
| 341 |
+
|
| 342 |
+
return nested_list
|
| 343 |
+
|
| 344 |
+
def _create_empty_nested_structure(self, dims, pad_value):
|
| 345 |
+
"""
|
| 346 |
+
Create an empty nested structure with given dimensions filled with pad_value.
|
| 347 |
+
|
| 348 |
+
Args:
|
| 349 |
+
dims (`list`):
|
| 350 |
+
The dimensions of the nested structure.
|
| 351 |
+
pad_value (`int`):
|
| 352 |
+
The value to fill the structure with.
|
| 353 |
+
"""
|
| 354 |
+
if len(dims) == 1:
|
| 355 |
+
return [pad_value] * dims[0]
|
| 356 |
+
else:
|
| 357 |
+
return [self._create_empty_nested_structure(dims[1:], pad_value) for _ in range(dims[0])]
|
| 358 |
+
|
| 359 |
+
def _get_nesting_level(self, input_list):
|
| 360 |
+
"""
|
| 361 |
+
Get the nesting level of a list structure.
|
| 362 |
+
|
| 363 |
+
Args:
|
| 364 |
+
input_list (`list`):
|
| 365 |
+
The list to get the nesting level of.
|
| 366 |
+
"""
|
| 367 |
+
if isinstance(input_list, list):
|
| 368 |
+
if len(input_list) == 0:
|
| 369 |
+
return 1
|
| 370 |
+
return 1 + self._get_nesting_level(input_list[0])
|
| 371 |
+
elif isinstance(input_list, (np.ndarray, torch.Tensor)):
|
| 372 |
+
# For arrays/tensors, the nesting level is the number of dimensions
|
| 373 |
+
return len(input_list.shape)
|
| 374 |
+
return 0
|
| 375 |
+
|
| 376 |
+
def _validate_single_input(
|
| 377 |
+
self,
|
| 378 |
+
data: torch.Tensor | np.ndarray | list,
|
| 379 |
+
expected_depth: int,
|
| 380 |
+
input_name: str,
|
| 381 |
+
expected_format: str,
|
| 382 |
+
expected_coord_size: int | None = None,
|
| 383 |
+
) -> list:
|
| 384 |
+
"""
|
| 385 |
+
Validate a single input by ensuring proper nesting and raising an error if the input is not valid.
|
| 386 |
+
|
| 387 |
+
Args:
|
| 388 |
+
data (`torch.Tensor`, `np.ndarray`, or `list`):
|
| 389 |
+
Input data to process.
|
| 390 |
+
expected_depth (`int`):
|
| 391 |
+
Expected nesting depth.
|
| 392 |
+
input_name (`str`):
|
| 393 |
+
Name of the input for error messages.
|
| 394 |
+
expected_format (`str`):
|
| 395 |
+
The expected format of the input.
|
| 396 |
+
expected_coord_size (`int`, *optional*):
|
| 397 |
+
Expected coordinate size (2 for points, 4 for boxes, None for labels).
|
| 398 |
+
.
|
| 399 |
+
"""
|
| 400 |
+
if data is None:
|
| 401 |
+
return None
|
| 402 |
+
|
| 403 |
+
# Handle tensors and numpy arrays first
|
| 404 |
+
if isinstance(data, (torch.Tensor, np.ndarray)):
|
| 405 |
+
# For tensors/arrays, we can directly check the number of dimensions
|
| 406 |
+
if data.ndim != expected_depth:
|
| 407 |
+
raise ValueError(
|
| 408 |
+
f"Input {input_name} must be a tensor/array with {expected_depth} dimensions. The expected nesting format is {expected_format}. Got {data.ndim} dimensions."
|
| 409 |
+
)
|
| 410 |
+
elif expected_coord_size is not None:
|
| 411 |
+
if data.shape[-1] != expected_coord_size:
|
| 412 |
+
raise ValueError(
|
| 413 |
+
f"Input {input_name} must be a tensor/array with {expected_coord_size} as the last dimension, got {data.shape[-1]}."
|
| 414 |
+
)
|
| 415 |
+
return self._convert_to_nested_list(data, expected_depth)
|
| 416 |
+
|
| 417 |
+
# Handle nested lists
|
| 418 |
+
if isinstance(data, list):
|
| 419 |
+
current_depth = self._get_nesting_level(data)
|
| 420 |
+
if current_depth != expected_depth:
|
| 421 |
+
raise ValueError(
|
| 422 |
+
f"Input {input_name} must be a nested list with {expected_depth} levels. The expected nesting format is {expected_format}. Got {current_depth} levels."
|
| 423 |
+
)
|
| 424 |
+
return self._convert_to_nested_list(data, expected_depth)
|
| 425 |
+
|
| 426 |
+
def _normalize_tensor_coordinates(self, tensor, original_sizes, is_bounding_box=False, preserve_padding=False):
|
| 427 |
+
"""
|
| 428 |
+
Helper method to normalize coordinates in a tensor across multiple images.
|
| 429 |
+
|
| 430 |
+
Args:
|
| 431 |
+
tensor (`torch.Tensor`):
|
| 432 |
+
Input tensor with coordinates.
|
| 433 |
+
original_sizes (`list`):
|
| 434 |
+
Original image sizes.
|
| 435 |
+
is_bounding_box (`bool`, *optional*, defaults to `False`):
|
| 436 |
+
Whether coordinates are bounding boxes.
|
| 437 |
+
preserve_padding (`bool`, *optional*, defaults to `False`):
|
| 438 |
+
Whether to preserve padding values (for points).
|
| 439 |
+
"""
|
| 440 |
+
if preserve_padding:
|
| 441 |
+
# For points: avoid normalizing pad values
|
| 442 |
+
mask = tensor != self.point_pad_value
|
| 443 |
+
coord_mask = mask.all(dim=-1, keepdim=True)
|
| 444 |
+
|
| 445 |
+
for img_idx in range(len(original_sizes)):
|
| 446 |
+
if img_idx < tensor.shape[0]:
|
| 447 |
+
original_size = original_sizes[img_idx] if img_idx < len(original_sizes) else original_sizes[0]
|
| 448 |
+
normalized_coords = self._normalize_coordinates(
|
| 449 |
+
self.target_size, tensor[img_idx], original_size, is_bounding_box=is_bounding_box
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
if preserve_padding:
|
| 453 |
+
# Only update non-padded values
|
| 454 |
+
img_mask = coord_mask[img_idx]
|
| 455 |
+
tensor[img_idx] = torch.where(
|
| 456 |
+
img_mask.expand_as(tensor[img_idx]), normalized_coords, tensor[img_idx]
|
| 457 |
+
)
|
| 458 |
+
else:
|
| 459 |
+
tensor[img_idx] = normalized_coords
|
| 460 |
+
|
| 461 |
+
def post_process_masks(
|
| 462 |
+
self,
|
| 463 |
+
masks,
|
| 464 |
+
original_sizes,
|
| 465 |
+
mask_threshold=0.0,
|
| 466 |
+
binarize=True,
|
| 467 |
+
max_hole_area=0.0,
|
| 468 |
+
max_sprinkle_area=0.0,
|
| 469 |
+
apply_non_overlapping_constraints=False,
|
| 470 |
+
**kwargs,
|
| 471 |
+
):
|
| 472 |
+
"""
|
| 473 |
+
Remove padding and upscale masks to the original image size.
|
| 474 |
+
|
| 475 |
+
Args:
|
| 476 |
+
masks (`Union[List[torch.Tensor], List[np.ndarray]]`):
|
| 477 |
+
Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format.
|
| 478 |
+
original_sizes (`Union[torch.Tensor, List[Tuple[int,int]]]`):
|
| 479 |
+
The original sizes of each image before it was resized to the model's expected input shape, in (height,
|
| 480 |
+
width) format.
|
| 481 |
+
mask_threshold (`float`, *optional*, defaults to 0.0):
|
| 482 |
+
Threshold for binarization and post-processing operations.
|
| 483 |
+
binarize (`bool`, *optional*, defaults to `True`):
|
| 484 |
+
Whether to binarize the masks.
|
| 485 |
+
max_hole_area (`float`, *optional*, defaults to 0.0):
|
| 486 |
+
The maximum area of a hole to fill.
|
| 487 |
+
max_sprinkle_area (`float`, *optional*, defaults to 0.0):
|
| 488 |
+
The maximum area of a sprinkle to fill.
|
| 489 |
+
apply_non_overlapping_constraints (`bool`, *optional*, defaults to `False`):
|
| 490 |
+
Whether to apply non-overlapping constraints to the masks.
|
| 491 |
+
|
| 492 |
+
Returns:
|
| 493 |
+
(`torch.Tensor`): Batched masks in batch_size, num_channels, height, width) format, where (height, width)
|
| 494 |
+
is given by original_size.
|
| 495 |
+
"""
|
| 496 |
+
return self.image_processor.post_process_masks(
|
| 497 |
+
masks,
|
| 498 |
+
original_sizes,
|
| 499 |
+
mask_threshold,
|
| 500 |
+
binarize,
|
| 501 |
+
max_hole_area,
|
| 502 |
+
max_sprinkle_area,
|
| 503 |
+
apply_non_overlapping_constraints,
|
| 504 |
+
**kwargs,
|
| 505 |
+
)
|
| 506 |
+
|
| 507 |
+
@property
|
| 508 |
+
def model_input_names(self):
|
| 509 |
+
image_processor_input_names = self.image_processor.model_input_names
|
| 510 |
+
return list(image_processor_input_names + ["original_sizes"])
|
| 511 |
+
|
| 512 |
+
def init_video_session(
|
| 513 |
+
self,
|
| 514 |
+
video: VideoInput | None = None,
|
| 515 |
+
inference_device: Union[str, "torch.device"] = "cpu",
|
| 516 |
+
inference_state_device: Union[str, "torch.device"] | None = None,
|
| 517 |
+
processing_device: Union[str, "torch.device"] | None = None,
|
| 518 |
+
video_storage_device: Union[str, "torch.device"] | None = None,
|
| 519 |
+
max_vision_features_cache_size: int = 1,
|
| 520 |
+
dtype: torch.dtype = torch.float32,
|
| 521 |
+
):
|
| 522 |
+
"""
|
| 523 |
+
Initializes a video session for inference.
|
| 524 |
+
If a video is provided (async inference), the video will be processed and stored on the `video_storage_device`.
|
| 525 |
+
|
| 526 |
+
Args:
|
| 527 |
+
video (`VideoInput`, *optional*):
|
| 528 |
+
The video to process. No need to provide when streaming.
|
| 529 |
+
inference_device (`str` or `torch.device`, *optional*, defaults to "cpu"):
|
| 530 |
+
The device to use for inference.
|
| 531 |
+
inference_state_device (`str` or `torch.device`, *optional*):
|
| 532 |
+
The device to store the inference state on.
|
| 533 |
+
processing_device (`str` or `torch.device`, *optional*):
|
| 534 |
+
The device to use for video processing.
|
| 535 |
+
video_storage_device (`str` or `torch.device`, *optional*):
|
| 536 |
+
The device to store the processed video frames on.
|
| 537 |
+
max_vision_features_cache_size (`int`, *optional*, defaults to 1):
|
| 538 |
+
The maximum number of vision features to cache.
|
| 539 |
+
dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
|
| 540 |
+
The torch dtype to use for the whole session.
|
| 541 |
+
"""
|
| 542 |
+
video_storage_device = video_storage_device if video_storage_device is not None else inference_device
|
| 543 |
+
inference_state_device = inference_state_device if inference_state_device is not None else inference_device
|
| 544 |
+
processing_device = processing_device if processing_device is not None else inference_device
|
| 545 |
+
pixel_values_video = None
|
| 546 |
+
video_height = None
|
| 547 |
+
video_width = None
|
| 548 |
+
if video is not None:
|
| 549 |
+
processed_video = self.video_processor(videos=video, device=processing_device, return_tensors="pt")
|
| 550 |
+
pixel_values_video = processed_video.pixel_values_videos[0]
|
| 551 |
+
video_height = processed_video.original_sizes[0][0]
|
| 552 |
+
video_width = processed_video.original_sizes[0][1]
|
| 553 |
+
inference_session = Sam2VideoInferenceSession(
|
| 554 |
+
video=pixel_values_video,
|
| 555 |
+
video_height=video_height,
|
| 556 |
+
video_width=video_width,
|
| 557 |
+
inference_device=inference_device,
|
| 558 |
+
video_storage_device=video_storage_device,
|
| 559 |
+
inference_state_device=inference_state_device,
|
| 560 |
+
dtype=dtype,
|
| 561 |
+
max_vision_features_cache_size=max_vision_features_cache_size,
|
| 562 |
+
)
|
| 563 |
+
return inference_session
|
| 564 |
+
|
| 565 |
+
def add_inputs_to_inference_session(
|
| 566 |
+
self,
|
| 567 |
+
inference_session: Sam2VideoInferenceSession,
|
| 568 |
+
frame_idx: int,
|
| 569 |
+
obj_ids: list[int] | int,
|
| 570 |
+
input_points: list[list[list[list[float]]]] | torch.Tensor | None = None,
|
| 571 |
+
input_labels: list[list[list[int]]] | torch.Tensor | None = None,
|
| 572 |
+
input_boxes: list[list[list[float]]] | torch.Tensor | None = None,
|
| 573 |
+
input_masks: np.ndarray | torch.Tensor | list[np.ndarray] | list[torch.Tensor] | None = None,
|
| 574 |
+
original_size: tuple[int, int] | None = None,
|
| 575 |
+
clear_old_inputs: bool = True,
|
| 576 |
+
) -> Sam2VideoInferenceSession:
|
| 577 |
+
"""
|
| 578 |
+
Process new points, boxes, or masks for a video frame and add them to the inference session.
|
| 579 |
+
|
| 580 |
+
Args:
|
| 581 |
+
inference_session (`Sam2VideoInferenceSession`):
|
| 582 |
+
The inference session for the video.
|
| 583 |
+
frame_idx (`int`):
|
| 584 |
+
The index of the frame to process.
|
| 585 |
+
obj_ids (`list[int]` or `int`):
|
| 586 |
+
The object ID(s) to associate with the points or box.
|
| 587 |
+
These can be any integers and can be reused later on to specify an object.
|
| 588 |
+
input_points (`list[list[list[list[float]]]]`, `torch.Tensor`, *optional*):
|
| 589 |
+
The points to add to the frame.
|
| 590 |
+
input_labels (`list[list[list[int]]]`, `torch.Tensor`, *optional*):
|
| 591 |
+
The labels for the points.
|
| 592 |
+
input_boxes (`list[list[list[float]]]`, `torch.Tensor`, *optional*):
|
| 593 |
+
The bounding boxes to add to the frame.
|
| 594 |
+
input_masks (`np.ndarray`, `torch.Tensor`, `list[np.ndarray]`, or `list[torch.Tensor]`, *optional*):
|
| 595 |
+
The mask(s) to add to the frame.
|
| 596 |
+
original_size (`tuple[int, int]`, *optional*):
|
| 597 |
+
The original size of the video. Provide when streaming.
|
| 598 |
+
clear_old_inputs (`bool`, *optional*, defaults to `True`):
|
| 599 |
+
Whether to clear old inputs for the object.
|
| 600 |
+
"""
|
| 601 |
+
|
| 602 |
+
if isinstance(obj_ids, int):
|
| 603 |
+
obj_ids = [obj_ids]
|
| 604 |
+
|
| 605 |
+
# Validate inputs
|
| 606 |
+
if (input_points is not None) != (input_labels is not None):
|
| 607 |
+
raise ValueError("points and labels must be provided together")
|
| 608 |
+
if input_points is None and input_boxes is None and input_masks is None:
|
| 609 |
+
raise ValueError("at least one of points, boxes, or masks must be provided as input")
|
| 610 |
+
if input_masks is not None and (input_points is not None or input_boxes is not None):
|
| 611 |
+
raise ValueError("masks cannot be provided together with points or boxes")
|
| 612 |
+
|
| 613 |
+
if input_masks is not None:
|
| 614 |
+
return self.process_new_mask_for_video_frame(inference_session, frame_idx, obj_ids, input_masks)
|
| 615 |
+
else:
|
| 616 |
+
return self.process_new_points_or_boxes_for_video_frame(
|
| 617 |
+
inference_session,
|
| 618 |
+
frame_idx,
|
| 619 |
+
obj_ids,
|
| 620 |
+
input_points,
|
| 621 |
+
input_labels,
|
| 622 |
+
input_boxes,
|
| 623 |
+
original_size,
|
| 624 |
+
clear_old_inputs,
|
| 625 |
+
)
|
| 626 |
+
|
| 627 |
+
def process_new_points_or_boxes_for_video_frame(
|
| 628 |
+
self,
|
| 629 |
+
inference_session: Sam2VideoInferenceSession,
|
| 630 |
+
frame_idx: int,
|
| 631 |
+
obj_ids: list[int],
|
| 632 |
+
input_points: list[list[list[list[float]]]] | torch.Tensor | None = None,
|
| 633 |
+
input_labels: list[list[list[int]]] | torch.Tensor | None = None,
|
| 634 |
+
input_boxes: list[list[list[float]]] | torch.Tensor | None = None,
|
| 635 |
+
original_size: tuple[int, int] | None = None,
|
| 636 |
+
clear_old_inputs: bool = True,
|
| 637 |
+
) -> Sam2VideoInferenceSession:
|
| 638 |
+
"""
|
| 639 |
+
Process new points or boxes for a video frame and add them to the inference session.
|
| 640 |
+
|
| 641 |
+
Args:
|
| 642 |
+
inference_session (`Sam2VideoInferenceSession`):
|
| 643 |
+
The inference session for the video.
|
| 644 |
+
frame_idx (`int`):
|
| 645 |
+
The index of the frame to process.
|
| 646 |
+
obj_ids (`list[int]`):
|
| 647 |
+
The object ID(s) to associate with the points or box.
|
| 648 |
+
These can be any integers and can be reused later on to specify an object.
|
| 649 |
+
input_points (`list[list[list[list[float]]]]`, `torch.Tensor`, *optional*):
|
| 650 |
+
The points to add to the frame.
|
| 651 |
+
input_labels (`list[list[list[int]]]`, `torch.Tensor`, *optional*):
|
| 652 |
+
The labels for the points.
|
| 653 |
+
input_boxes (`list[list[list[float]]]`, `torch.Tensor`, *optional*):
|
| 654 |
+
The bounding boxes to add to the frame.
|
| 655 |
+
original_size (`tuple[int, int]`, *optional*):
|
| 656 |
+
The original size of the video. Provide when streaming.
|
| 657 |
+
clear_old_inputs (`bool`, *optional*, defaults to `True`):
|
| 658 |
+
Whether to clear old inputs for the object.
|
| 659 |
+
"""
|
| 660 |
+
if original_size is not None:
|
| 661 |
+
inference_session.video_height = original_size[0]
|
| 662 |
+
inference_session.video_width = original_size[1]
|
| 663 |
+
elif inference_session.video_height is None or inference_session.video_width is None:
|
| 664 |
+
raise ValueError("original_size must be provided when adding points or boxes on a first streamed frame")
|
| 665 |
+
|
| 666 |
+
original_sizes = [[inference_session.video_height, inference_session.video_width]]
|
| 667 |
+
|
| 668 |
+
encoded_inputs = self(
|
| 669 |
+
input_points=input_points,
|
| 670 |
+
input_labels=input_labels,
|
| 671 |
+
input_boxes=input_boxes,
|
| 672 |
+
original_sizes=original_sizes,
|
| 673 |
+
return_tensors="pt",
|
| 674 |
+
)
|
| 675 |
+
input_points = encoded_inputs.get("input_points", None)
|
| 676 |
+
input_labels = encoded_inputs.get("input_labels", None)
|
| 677 |
+
input_boxes = encoded_inputs.get("input_boxes", None)
|
| 678 |
+
|
| 679 |
+
if input_points is not None:
|
| 680 |
+
if input_points.shape[1] != len(obj_ids):
|
| 681 |
+
raise ValueError(
|
| 682 |
+
f"Number of object ids ({len(obj_ids)}) does not match number of points ({input_points.shape[1]})"
|
| 683 |
+
)
|
| 684 |
+
else:
|
| 685 |
+
input_points = torch.zeros(1, len(obj_ids), 0, 2, dtype=torch.float32)
|
| 686 |
+
if input_labels is not None:
|
| 687 |
+
if input_labels.shape[1] != len(obj_ids):
|
| 688 |
+
raise ValueError(
|
| 689 |
+
f"Number of object ids ({len(obj_ids)}) does not match number of labels ({input_labels.shape[1]})"
|
| 690 |
+
)
|
| 691 |
+
else:
|
| 692 |
+
input_labels = torch.zeros(1, len(obj_ids), 0, dtype=torch.int32)
|
| 693 |
+
if input_boxes is not None:
|
| 694 |
+
if input_boxes.shape[1] != len(obj_ids):
|
| 695 |
+
raise ValueError(
|
| 696 |
+
f"Number of object ids ({len(obj_ids)}) does not match number of boxes ({input_boxes.shape[1]})"
|
| 697 |
+
)
|
| 698 |
+
|
| 699 |
+
if input_boxes is not None:
|
| 700 |
+
if not clear_old_inputs:
|
| 701 |
+
raise ValueError(
|
| 702 |
+
"cannot add box without clearing old points, since "
|
| 703 |
+
"box prompt must be provided before any point prompt "
|
| 704 |
+
"(please use clear_old_points=True instead)"
|
| 705 |
+
)
|
| 706 |
+
box_coords = input_boxes.reshape(1, -1, 2, 2)
|
| 707 |
+
box_labels = torch.tensor([2, 3], dtype=torch.int32).repeat(1, box_coords.shape[1], 1)
|
| 708 |
+
input_points = torch.cat([box_coords, input_points], dim=2)
|
| 709 |
+
input_labels = torch.cat([box_labels, input_labels], dim=2)
|
| 710 |
+
|
| 711 |
+
for obj_id, idx in zip(obj_ids, range(len(obj_ids))):
|
| 712 |
+
obj_idx = inference_session.obj_id_to_idx(obj_id)
|
| 713 |
+
input_points_for_obj = input_points[:, idx, :, :].unsqueeze(1)
|
| 714 |
+
input_labels_for_obj = input_labels[:, idx, :].unsqueeze(1)
|
| 715 |
+
# Handle existing points
|
| 716 |
+
if not clear_old_inputs:
|
| 717 |
+
existing_points = inference_session.point_inputs_per_obj[obj_idx].get(frame_idx, None)
|
| 718 |
+
if existing_points is not None:
|
| 719 |
+
# Concatenate with existing points
|
| 720 |
+
input_points_for_obj = torch.cat(
|
| 721 |
+
[existing_points["point_coords"].to(input_points_for_obj.device), input_points_for_obj], dim=2
|
| 722 |
+
)
|
| 723 |
+
input_labels_for_obj = torch.cat(
|
| 724 |
+
[existing_points["point_labels"].to(input_labels_for_obj.device), input_labels_for_obj], dim=2
|
| 725 |
+
)
|
| 726 |
+
point_inputs = {
|
| 727 |
+
"point_coords": input_points_for_obj,
|
| 728 |
+
"point_labels": input_labels_for_obj,
|
| 729 |
+
}
|
| 730 |
+
|
| 731 |
+
inference_session.add_point_inputs(obj_idx, frame_idx, point_inputs)
|
| 732 |
+
inference_session.remove_mask_inputs(obj_idx, frame_idx) # Clear any mask inputs
|
| 733 |
+
|
| 734 |
+
inference_session.obj_with_new_inputs = obj_ids
|
| 735 |
+
|
| 736 |
+
def process_new_mask_for_video_frame(
|
| 737 |
+
self,
|
| 738 |
+
inference_session: Sam2VideoInferenceSession,
|
| 739 |
+
frame_idx: int,
|
| 740 |
+
obj_ids: list[int],
|
| 741 |
+
input_masks: np.ndarray | torch.Tensor | list[np.ndarray] | list[torch.Tensor],
|
| 742 |
+
):
|
| 743 |
+
"""
|
| 744 |
+
Add new mask to a frame and add them to the inference session.
|
| 745 |
+
|
| 746 |
+
Args:
|
| 747 |
+
inference_session (`Sam2VideoInferenceSession`):
|
| 748 |
+
The inference session for the video.
|
| 749 |
+
frame_idx (`int`):
|
| 750 |
+
The index of the frame to process.
|
| 751 |
+
obj_ids (`list[int]`):
|
| 752 |
+
The object ID(s) to associate with the mask.
|
| 753 |
+
These can be any integers and can be reused later on to specify an object.
|
| 754 |
+
input_masks (`np.ndarray`, `torch.Tensor`, `list[np.ndarray]`, or `list[torch.Tensor]`):
|
| 755 |
+
The mask(s) to add to the frame.
|
| 756 |
+
"""
|
| 757 |
+
if not isinstance(input_masks, list):
|
| 758 |
+
input_masks = [input_masks]
|
| 759 |
+
if len(input_masks) != len(obj_ids):
|
| 760 |
+
raise ValueError(
|
| 761 |
+
f"Number of object ids ({len(obj_ids)}) does not match number of masks ({len(input_masks)})"
|
| 762 |
+
)
|
| 763 |
+
|
| 764 |
+
for obj_id, mask in zip(obj_ids, input_masks):
|
| 765 |
+
obj_idx = inference_session.obj_id_to_idx(obj_id)
|
| 766 |
+
|
| 767 |
+
device = inference_session.inference_device
|
| 768 |
+
|
| 769 |
+
# Process mask
|
| 770 |
+
if not isinstance(mask, torch.Tensor):
|
| 771 |
+
mask = torch.tensor(mask, dtype=torch.bool)
|
| 772 |
+
nb_dim = mask.dim()
|
| 773 |
+
if nb_dim > 4 or nb_dim < 2:
|
| 774 |
+
raise ValueError(f"Mask has an unsupported number of dimensions: {nb_dim}")
|
| 775 |
+
for i in range(4 - nb_dim):
|
| 776 |
+
mask = mask.unsqueeze(0)
|
| 777 |
+
|
| 778 |
+
mask_H, mask_W = mask.shape[-2:]
|
| 779 |
+
mask_inputs_orig = mask.to(device)
|
| 780 |
+
mask_inputs_orig = mask_inputs_orig.float().to(device)
|
| 781 |
+
|
| 782 |
+
# Resize mask if needed
|
| 783 |
+
if mask_H != self.target_size or mask_W != self.target_size:
|
| 784 |
+
mask_inputs = torch.nn.functional.interpolate(
|
| 785 |
+
mask_inputs_orig,
|
| 786 |
+
size=(self.target_size, self.target_size),
|
| 787 |
+
align_corners=False,
|
| 788 |
+
mode="bilinear",
|
| 789 |
+
antialias=True,
|
| 790 |
+
)
|
| 791 |
+
mask_inputs = (mask_inputs >= 0.5).float()
|
| 792 |
+
else:
|
| 793 |
+
mask_inputs = mask_inputs_orig
|
| 794 |
+
|
| 795 |
+
inference_session.add_mask_inputs(obj_idx, frame_idx, mask_inputs)
|
| 796 |
+
inference_session.remove_point_inputs(obj_idx, frame_idx) # Clear any point inputs
|
| 797 |
+
|
| 798 |
+
inference_session.obj_with_new_inputs = obj_ids
|
| 799 |
+
|
| 800 |
+
|
| 801 |
+
__all__ = ["Sam2VideoProcessor"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/sam2_video/video_processing_sam2_video.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Fast Image processor class for SAM2."""
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
import torch
|
| 18 |
+
import torch.nn.functional as F
|
| 19 |
+
|
| 20 |
+
from ...image_processing_utils import BatchFeature
|
| 21 |
+
from ...image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling, SizeDict
|
| 22 |
+
from ...utils import TensorType
|
| 23 |
+
from ...video_processing_utils import BaseVideoProcessor
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class Sam2VideoVideoProcessor(BaseVideoProcessor):
|
| 27 |
+
resample = PILImageResampling.BILINEAR
|
| 28 |
+
image_mean = IMAGENET_DEFAULT_MEAN
|
| 29 |
+
image_std = IMAGENET_DEFAULT_STD
|
| 30 |
+
size = {"height": 1024, "width": 1024}
|
| 31 |
+
do_resize = True
|
| 32 |
+
do_rescale = True
|
| 33 |
+
do_normalize = True
|
| 34 |
+
do_convert_rgb = True
|
| 35 |
+
model_input_names = ["pixel_values"]
|
| 36 |
+
|
| 37 |
+
def _preprocess(
|
| 38 |
+
self,
|
| 39 |
+
videos: list["torch.Tensor"],
|
| 40 |
+
size: SizeDict,
|
| 41 |
+
return_tensors: str | TensorType | None,
|
| 42 |
+
**kwargs,
|
| 43 |
+
) -> BatchFeature:
|
| 44 |
+
original_sizes = [video.shape[-2:] for video in videos]
|
| 45 |
+
reshaped_input_sizes = [(size.height, size.width) for _ in range(len(videos))]
|
| 46 |
+
batch_feature = super()._preprocess(videos, size=size, return_tensors=return_tensors, **kwargs)
|
| 47 |
+
batch_feature = BatchFeature(
|
| 48 |
+
data={
|
| 49 |
+
"original_sizes": original_sizes,
|
| 50 |
+
"reshaped_input_sizes": reshaped_input_sizes,
|
| 51 |
+
**batch_feature.data,
|
| 52 |
+
},
|
| 53 |
+
tensor_type=return_tensors,
|
| 54 |
+
)
|
| 55 |
+
return batch_feature
|
| 56 |
+
|
| 57 |
+
def post_process_masks(
|
| 58 |
+
self, masks, original_sizes, reshaped_input_sizes, mask_threshold=0.0, binarize=True, pad_size=None
|
| 59 |
+
):
|
| 60 |
+
"""
|
| 61 |
+
Remove padding and upscale masks to the original image size.
|
| 62 |
+
|
| 63 |
+
Args:
|
| 64 |
+
masks (`Union[List[torch.Tensor], List[np.ndarray]]`):
|
| 65 |
+
Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format.
|
| 66 |
+
original_sizes (`Union[torch.Tensor, List[Tuple[int,int]]]`):
|
| 67 |
+
The original sizes of each image before it was resized to the model's expected input shape, in (height,
|
| 68 |
+
width) format.
|
| 69 |
+
reshaped_input_sizes (`Union[torch.Tensor, List[Tuple[int,int]]]`):
|
| 70 |
+
The size of each image as it is fed to the model, in (height, width) format. Used to remove padding.
|
| 71 |
+
mask_threshold (`float`, *optional*, defaults to 0.0):
|
| 72 |
+
The threshold to use for binarizing the masks.
|
| 73 |
+
binarize (`bool`, *optional*, defaults to `True`):
|
| 74 |
+
Whether to binarize the masks.
|
| 75 |
+
pad_size (`int`, *optional*, defaults to `self.pad_size`):
|
| 76 |
+
The target size the images were padded to before being passed to the model. If None, the target size is
|
| 77 |
+
assumed to be the processor's `pad_size`.
|
| 78 |
+
Returns:
|
| 79 |
+
(`torch.Tensor`): Batched masks in batch_size, num_channels, height, width) format, where (height, width)
|
| 80 |
+
is given by original_size.
|
| 81 |
+
"""
|
| 82 |
+
pad_size = self.size if pad_size is None else pad_size
|
| 83 |
+
target_image_size = (pad_size["height"], pad_size["width"])
|
| 84 |
+
if isinstance(original_sizes, (torch.Tensor, np.ndarray)):
|
| 85 |
+
original_sizes = original_sizes.tolist()
|
| 86 |
+
if isinstance(reshaped_input_sizes, (torch.Tensor, np.ndarray)):
|
| 87 |
+
reshaped_input_sizes = reshaped_input_sizes.tolist()
|
| 88 |
+
output_masks = []
|
| 89 |
+
for i, original_size in enumerate(original_sizes):
|
| 90 |
+
if isinstance(masks[i], np.ndarray):
|
| 91 |
+
masks[i] = torch.from_numpy(masks[i])
|
| 92 |
+
elif not isinstance(masks[i], torch.Tensor):
|
| 93 |
+
raise TypeError("Input masks should be a list of `torch.tensors` or a list of `np.ndarray`")
|
| 94 |
+
interpolated_mask = F.interpolate(masks[i], target_image_size, mode="bilinear", align_corners=False)
|
| 95 |
+
interpolated_mask = interpolated_mask[..., : reshaped_input_sizes[i][0], : reshaped_input_sizes[i][1]]
|
| 96 |
+
interpolated_mask = F.interpolate(interpolated_mask, original_size, mode="bilinear", align_corners=False)
|
| 97 |
+
if binarize:
|
| 98 |
+
interpolated_mask = interpolated_mask > mask_threshold
|
| 99 |
+
output_masks.append(interpolated_mask)
|
| 100 |
+
|
| 101 |
+
return output_masks
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
__all__ = ["Sam2VideoVideoProcessor"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/cache/owt_llmclean_qwen36_35b_articlefull_10k_snapshot_docs24862_shards8/part-000.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_002000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:16045de90b4658007a7de63582a664afe233fcabb3676dd8a3011c70f31a1b35
|
| 3 |
+
size 515519058
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_008000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5f44fc49a14ab890275dee93311c78cf5ba27be267ff95a1d1638391ee317295
|
| 3 |
+
size 515519058
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_085000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:913188aa60c3b2f1041560f0b1c0b627f26b179803f7de1286f8c8dfec481db0
|
| 3 |
+
size 515519058
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_129000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b0c6feefc24aef5be64e313be5d12884dd783d1372e093bebedcf868e8c9cf2b
|
| 3 |
+
size 515519058
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_152000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:88997ec48528982841d1e0161f06899ceaefc407ae24dbe3a9b270f601e22a56
|
| 3 |
+
size 515519058
|