Add files using upload-large-folder tool
Browse files- LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0109000_logistic_normal_t1p45.log +76 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/convnext/__init__.py +29 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/convnext/configuration_convnext.py +68 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/convnext/image_processing_convnext.py +145 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/convnext/image_processing_pil_convnext.py +136 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/convnext/modeling_convnext.py +404 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/fast_vlm/__init__.py +27 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/fast_vlm/configuration_fast_vlm.py +111 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/fast_vlm/modeling_fast_vlm.py +413 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/fast_vlm/modular_fast_vlm.py +337 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/imagegpt/modeling_imagegpt.py +826 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/trocr/__init__.py +28 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/trocr/configuration_trocr.py +79 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/trocr/modeling_trocr.py +777 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/trocr/processing_trocr.py +69 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr1e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260609_155046/step_123000.pt +3 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr1e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260609_155046/step_174000.pt +3 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr1e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260609_155046/step_218000.pt +3 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr1e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260609_155046/step_281000.pt +3 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr1e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260609_155046/step_358000.pt +3 -0
LTA_openwebtext_dualt/logs/lm1b_len128_lognormal_atoms_sde_watch/infer_lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522_step_0109000_logistic_normal_t1p45.log
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[watch-lognormal-sde] 2026-05-23_08:42:02 infer runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0109000.pt -> docs/lta_samples/metrics_20260522/lm1b_len128_lognormal_atoms_every1k_logistic_normal_sde_t1p45_steps128_n256/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0109000
|
| 2 |
+
[load] runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0109000.pt
|
| 3 |
+
[ckpt] step=109000
|
| 4 |
+
[sde] generated 16/256
|
| 5 |
+
[sde] generated 32/256
|
| 6 |
+
[sde] generated 48/256
|
| 7 |
+
[sde] generated 64/256
|
| 8 |
+
[sde] generated 80/256
|
| 9 |
+
[sde] generated 96/256
|
| 10 |
+
[sde] generated 112/256
|
| 11 |
+
[sde] generated 128/256
|
| 12 |
+
[sde] generated 144/256
|
| 13 |
+
[sde] generated 160/256
|
| 14 |
+
[sde] generated 176/256
|
| 15 |
+
[sde] generated 192/256
|
| 16 |
+
[sde] generated 208/256
|
| 17 |
+
[sde] generated 224/256
|
| 18 |
+
[sde] generated 240/256
|
| 19 |
+
[sde] generated 256/256
|
| 20 |
+
[score] loading scorer: /e2e-data/evad-tech-vla/wanghan58/models/flowtext_scorers/gpt2-large-standard
|
| 21 |
+
[summary] {
|
| 22 |
+
"type": "summary",
|
| 23 |
+
"checkpoint": "runs/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0109000.pt",
|
| 24 |
+
"step": 109000,
|
| 25 |
+
"decode": {
|
| 26 |
+
"decode_rule": "logistic_normal_resample_sde",
|
| 27 |
+
"steps": 128,
|
| 28 |
+
"model_t_mode": "const0.5",
|
| 29 |
+
"mean_mode": "anchor_semantic",
|
| 30 |
+
"endpoint_floor": 0.0,
|
| 31 |
+
"concentration_min": 1.0,
|
| 32 |
+
"concentration_max": 1024.0,
|
| 33 |
+
"endpoint_temp": 1.45,
|
| 34 |
+
"support_power": 1.0,
|
| 35 |
+
"semantic_power": 1.0,
|
| 36 |
+
"noise_init": "logistic_normal",
|
| 37 |
+
"noise_sigma": 3.0,
|
| 38 |
+
"noise_dirichlet_concentration": 1.0,
|
| 39 |
+
"sde_resample": "logistic_normal",
|
| 40 |
+
"logistic_normal_sigma_min": 0.18,
|
| 41 |
+
"logistic_normal_sigma_max": 3.0,
|
| 42 |
+
"logistic_normal_tau_min": 0.65,
|
| 43 |
+
"logistic_normal_tau_max": 1.0,
|
| 44 |
+
"final_from": "blend_0.5",
|
| 45 |
+
"n_samples": 256,
|
| 46 |
+
"seed": 20260522
|
| 47 |
+
},
|
| 48 |
+
"raw_genppl": {
|
| 49 |
+
"ppl": 28.57508931245214,
|
| 50 |
+
"nll_per_token": 3.3525353352211216,
|
| 51 |
+
"tokens": 31637,
|
| 52 |
+
"kept_samples": 256,
|
| 53 |
+
"total_samples": 256,
|
| 54 |
+
"empty_rate": 0.0,
|
| 55 |
+
"skipped_samples": 0
|
| 56 |
+
},
|
| 57 |
+
"stripped_genppl": {
|
| 58 |
+
"ppl": 31.725356989218035,
|
| 59 |
+
"nll_per_token": 3.457116266152367,
|
| 60 |
+
"tokens": 27821,
|
| 61 |
+
"kept_samples": 256,
|
| 62 |
+
"total_samples": 256,
|
| 63 |
+
"empty_rate": 0.0,
|
| 64 |
+
"skipped_samples": 0
|
| 65 |
+
},
|
| 66 |
+
"diversity": {
|
| 67 |
+
"sample_entropy": 2.876900664819445,
|
| 68 |
+
"unique_tokens": 2219,
|
| 69 |
+
"token_count": 32768,
|
| 70 |
+
"distinct_1": 0.067718505859375,
|
| 71 |
+
"distinct_2": 0.3112696850393701,
|
| 72 |
+
"top_token_mass": 0.113067626953125
|
| 73 |
+
}
|
| 74 |
+
}
|
| 75 |
+
[done] docs/lta_samples/metrics_20260522/lm1b_len128_lognormal_atoms_every1k_logistic_normal_sde_t1p45_steps128_n256/lta_lm1b_classic_c1024_len128_lognormalatoms_gbs512_4gpu_20260522/step_0109000/sde_steps128_samples256_scored.jsonl
|
| 76 |
+
[watch-lognormal-sde] 2026-05-23_08:43:30 done step_0109000
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/convnext/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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_convnext import *
|
| 22 |
+
from .image_processing_convnext import *
|
| 23 |
+
from .image_processing_pil_convnext import *
|
| 24 |
+
from .modeling_convnext 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/transformers/models/convnext/configuration_convnext.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 Meta Platforms, Inc. 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 |
+
"""ConvNeXT model configuration"""
|
| 15 |
+
|
| 16 |
+
from huggingface_hub.dataclasses import strict
|
| 17 |
+
|
| 18 |
+
from ...backbone_utils import BackboneConfigMixin
|
| 19 |
+
from ...configuration_utils import PreTrainedConfig
|
| 20 |
+
from ...utils import auto_docstring
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@auto_docstring(checkpoint="facebook/convnext-tiny-224")
|
| 24 |
+
@strict
|
| 25 |
+
class ConvNextConfig(BackboneConfigMixin, PreTrainedConfig):
|
| 26 |
+
r"""
|
| 27 |
+
num_stages (`int`, *optional*, defaults to 4):
|
| 28 |
+
The number of stages in the model.
|
| 29 |
+
|
| 30 |
+
Example:
|
| 31 |
+
```python
|
| 32 |
+
>>> from transformers import ConvNextConfig, ConvNextModel
|
| 33 |
+
|
| 34 |
+
>>> # Initializing a ConvNext convnext-tiny-224 style configuration
|
| 35 |
+
>>> configuration = ConvNextConfig()
|
| 36 |
+
|
| 37 |
+
>>> # Initializing a model (with random weights) from the convnext-tiny-224 style configuration
|
| 38 |
+
>>> model = ConvNextModel(configuration)
|
| 39 |
+
|
| 40 |
+
>>> # Accessing the model configuration
|
| 41 |
+
>>> configuration = model.config
|
| 42 |
+
```"""
|
| 43 |
+
|
| 44 |
+
model_type = "convnext"
|
| 45 |
+
|
| 46 |
+
num_channels: int = 3
|
| 47 |
+
patch_size: int | list[int] | tuple[int, int] = 4
|
| 48 |
+
num_stages: int = 4
|
| 49 |
+
hidden_sizes: list[int] | tuple[int, ...] | None = (96, 192, 384, 768)
|
| 50 |
+
depths: list[int] | tuple[int, ...] | None = (3, 3, 9, 3)
|
| 51 |
+
hidden_act: str = "gelu"
|
| 52 |
+
initializer_range: float = 0.02
|
| 53 |
+
layer_norm_eps: float = 1e-12
|
| 54 |
+
layer_scale_init_value: float = 1e-6
|
| 55 |
+
drop_path_rate: float | int = 0.0
|
| 56 |
+
image_size: int | list[int] | tuple[int, int] = 224
|
| 57 |
+
_out_features: list[str] | None = None
|
| 58 |
+
_out_indices: list[int] | None = None
|
| 59 |
+
|
| 60 |
+
def __post_init__(self, **kwargs):
|
| 61 |
+
self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(self.depths) + 1)]
|
| 62 |
+
self.set_output_features_output_indices(
|
| 63 |
+
out_indices=kwargs.pop("out_indices", None), out_features=kwargs.pop("out_features", None)
|
| 64 |
+
)
|
| 65 |
+
super().__post_init__(**kwargs)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
__all__ = ["ConvNextConfig"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/convnext/image_processing_convnext.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Image processor class for ConvNeXT."""
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from torchvision.transforms.v2 import functional as tvF
|
| 18 |
+
|
| 19 |
+
from ...image_processing_backends import TorchvisionBackend
|
| 20 |
+
from ...image_processing_utils import BatchFeature
|
| 21 |
+
from ...image_transforms import get_resize_output_image_size, group_images_by_shape, reorder_images
|
| 22 |
+
from ...image_utils import (
|
| 23 |
+
IMAGENET_STANDARD_MEAN,
|
| 24 |
+
IMAGENET_STANDARD_STD,
|
| 25 |
+
ChannelDimension,
|
| 26 |
+
PILImageResampling,
|
| 27 |
+
SizeDict,
|
| 28 |
+
)
|
| 29 |
+
from ...processing_utils import ImagesKwargs, Unpack
|
| 30 |
+
from ...utils import TensorType, auto_docstring
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class ConvNextImageProcessorKwargs(ImagesKwargs, total=False):
|
| 34 |
+
r"""
|
| 35 |
+
crop_pct (`float`, *optional*, defaults to `self.crop_pct`):
|
| 36 |
+
Percentage of the image to crop. Only has an effect if size < 384.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
crop_pct: float
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@auto_docstring
|
| 43 |
+
class ConvNextImageProcessor(TorchvisionBackend):
|
| 44 |
+
"""Torchvision backend for ConvNeXT with custom resize."""
|
| 45 |
+
|
| 46 |
+
valid_kwargs = ConvNextImageProcessorKwargs
|
| 47 |
+
|
| 48 |
+
resample = PILImageResampling.BICUBIC
|
| 49 |
+
image_mean = IMAGENET_STANDARD_MEAN
|
| 50 |
+
image_std = IMAGENET_STANDARD_STD
|
| 51 |
+
size = {"shortest_edge": 384}
|
| 52 |
+
default_to_square = False
|
| 53 |
+
do_resize = True
|
| 54 |
+
do_rescale = True
|
| 55 |
+
do_normalize = True
|
| 56 |
+
crop_pct = 224 / 256
|
| 57 |
+
|
| 58 |
+
def __init__(self, **kwargs: Unpack[ConvNextImageProcessorKwargs]):
|
| 59 |
+
super().__init__(**kwargs)
|
| 60 |
+
|
| 61 |
+
def resize(
|
| 62 |
+
self,
|
| 63 |
+
image: "torch.Tensor",
|
| 64 |
+
size: SizeDict,
|
| 65 |
+
resample: "PILImageResampling | tvF.InterpolationMode | int | None",
|
| 66 |
+
crop_pct: float = 224 / 256,
|
| 67 |
+
**kwargs,
|
| 68 |
+
) -> "torch.Tensor":
|
| 69 |
+
"""Resize with crop_pct support."""
|
| 70 |
+
if not size.shortest_edge:
|
| 71 |
+
raise ValueError(f"Size dictionary must contain 'shortest_edge' key. Got {size.keys()}")
|
| 72 |
+
shortest_edge = size.shortest_edge
|
| 73 |
+
|
| 74 |
+
if shortest_edge < 384:
|
| 75 |
+
# maintain same ratio, resizing shortest edge to shortest_edge/crop_pct
|
| 76 |
+
resize_shortest_edge = int(shortest_edge / crop_pct)
|
| 77 |
+
resize_size = get_resize_output_image_size(
|
| 78 |
+
image, size=resize_shortest_edge, default_to_square=False, input_data_format=ChannelDimension.FIRST
|
| 79 |
+
)
|
| 80 |
+
image = super().resize(
|
| 81 |
+
image,
|
| 82 |
+
SizeDict(height=resize_size[0], width=resize_size[1]),
|
| 83 |
+
resample=resample,
|
| 84 |
+
**kwargs,
|
| 85 |
+
)
|
| 86 |
+
# then crop to (shortest_edge, shortest_edge)
|
| 87 |
+
return self.center_crop(
|
| 88 |
+
image,
|
| 89 |
+
SizeDict(height=shortest_edge, width=shortest_edge),
|
| 90 |
+
**kwargs,
|
| 91 |
+
)
|
| 92 |
+
else:
|
| 93 |
+
# warping (no cropping) when evaluated at 384 or larger
|
| 94 |
+
return super().resize(
|
| 95 |
+
image,
|
| 96 |
+
SizeDict(height=shortest_edge, width=shortest_edge),
|
| 97 |
+
resample=resample,
|
| 98 |
+
**kwargs,
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
def _preprocess(
|
| 102 |
+
self,
|
| 103 |
+
images: list["torch.Tensor"],
|
| 104 |
+
do_resize: bool,
|
| 105 |
+
size: SizeDict,
|
| 106 |
+
resample: "PILImageResampling | tvF.InterpolationMode | int | None",
|
| 107 |
+
do_center_crop: bool,
|
| 108 |
+
crop_size: SizeDict,
|
| 109 |
+
do_rescale: bool,
|
| 110 |
+
rescale_factor: float,
|
| 111 |
+
do_normalize: bool,
|
| 112 |
+
image_mean: float | list[float] | None,
|
| 113 |
+
image_std: float | list[float] | None,
|
| 114 |
+
do_pad: bool | None,
|
| 115 |
+
pad_size: SizeDict | None,
|
| 116 |
+
disable_grouping: bool | None,
|
| 117 |
+
return_tensors: str | TensorType | None,
|
| 118 |
+
crop_pct: float = 224 / 256,
|
| 119 |
+
**kwargs,
|
| 120 |
+
) -> BatchFeature:
|
| 121 |
+
"""Custom preprocessing for ConvNeXT."""
|
| 122 |
+
grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
|
| 123 |
+
resized_images_grouped = {}
|
| 124 |
+
for shape, stacked_images in grouped_images.items():
|
| 125 |
+
if do_resize:
|
| 126 |
+
stacked_images = self.resize(stacked_images, size, resample, crop_pct)
|
| 127 |
+
resized_images_grouped[shape] = stacked_images
|
| 128 |
+
resized_images = reorder_images(resized_images_grouped, grouped_images_index)
|
| 129 |
+
|
| 130 |
+
grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
|
| 131 |
+
processed_images_grouped = {}
|
| 132 |
+
for shape, stacked_images in grouped_images.items():
|
| 133 |
+
if do_center_crop:
|
| 134 |
+
stacked_images = self.center_crop(stacked_images, crop_size)
|
| 135 |
+
stacked_images = self.rescale_and_normalize(
|
| 136 |
+
stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
|
| 137 |
+
)
|
| 138 |
+
processed_images_grouped[shape] = stacked_images
|
| 139 |
+
|
| 140 |
+
processed_images = reorder_images(processed_images_grouped, grouped_images_index)
|
| 141 |
+
|
| 142 |
+
return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
__all__ = ["ConvNextImageProcessor"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/convnext/image_processing_pil_convnext.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Image processor class for ConvNeXT."""
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
|
| 18 |
+
from ...image_processing_backends import PilBackend
|
| 19 |
+
from ...image_processing_utils import BatchFeature
|
| 20 |
+
from ...image_transforms import get_resize_output_image_size
|
| 21 |
+
from ...image_utils import (
|
| 22 |
+
IMAGENET_STANDARD_MEAN,
|
| 23 |
+
IMAGENET_STANDARD_STD,
|
| 24 |
+
ChannelDimension,
|
| 25 |
+
PILImageResampling,
|
| 26 |
+
SizeDict,
|
| 27 |
+
)
|
| 28 |
+
from ...processing_utils import ImagesKwargs, Unpack
|
| 29 |
+
from ...utils import TensorType, auto_docstring
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
# Adapted from transformers.models.convnext.image_processing_convnext.ConvNextImageProcessorKwargs
|
| 33 |
+
class ConvNextImageProcessorKwargs(ImagesKwargs, total=False):
|
| 34 |
+
r"""
|
| 35 |
+
crop_pct (`float`, *optional*, defaults to `self.crop_pct`):
|
| 36 |
+
Percentage of the image to crop. Only has an effect if size < 384.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
crop_pct: float
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@auto_docstring
|
| 43 |
+
class ConvNextImageProcessorPil(PilBackend):
|
| 44 |
+
"""PIL backend for ConvNeXT with custom resize."""
|
| 45 |
+
|
| 46 |
+
valid_kwargs = ConvNextImageProcessorKwargs
|
| 47 |
+
|
| 48 |
+
resample = PILImageResampling.BICUBIC
|
| 49 |
+
image_mean = IMAGENET_STANDARD_MEAN
|
| 50 |
+
image_std = IMAGENET_STANDARD_STD
|
| 51 |
+
size = {"shortest_edge": 384}
|
| 52 |
+
default_to_square = False
|
| 53 |
+
do_resize = True
|
| 54 |
+
do_rescale = True
|
| 55 |
+
do_normalize = True
|
| 56 |
+
crop_pct = 224 / 256
|
| 57 |
+
|
| 58 |
+
def __init__(self, **kwargs: Unpack[ConvNextImageProcessorKwargs]):
|
| 59 |
+
super().__init__(**kwargs)
|
| 60 |
+
|
| 61 |
+
def resize(
|
| 62 |
+
self,
|
| 63 |
+
image: np.ndarray,
|
| 64 |
+
size: SizeDict,
|
| 65 |
+
resample: "PILImageResampling | None",
|
| 66 |
+
crop_pct: float = 224 / 256,
|
| 67 |
+
**kwargs,
|
| 68 |
+
) -> np.ndarray:
|
| 69 |
+
"""Resize with crop_pct support."""
|
| 70 |
+
if not size.shortest_edge:
|
| 71 |
+
raise ValueError(f"Size dictionary must contain 'shortest_edge' key. Got {size.keys()}")
|
| 72 |
+
shortest_edge = size.shortest_edge
|
| 73 |
+
|
| 74 |
+
if shortest_edge < 384:
|
| 75 |
+
# maintain same ratio, resizing shortest edge to shortest_edge/crop_pct
|
| 76 |
+
resize_shortest_edge = int(shortest_edge / crop_pct)
|
| 77 |
+
resize_size = get_resize_output_image_size(
|
| 78 |
+
image, size=resize_shortest_edge, default_to_square=False, input_data_format=ChannelDimension.FIRST
|
| 79 |
+
)
|
| 80 |
+
image = super().resize(
|
| 81 |
+
image,
|
| 82 |
+
size=SizeDict(height=resize_size[0], width=resize_size[1]),
|
| 83 |
+
resample=resample,
|
| 84 |
+
**kwargs,
|
| 85 |
+
)
|
| 86 |
+
# then crop to (shortest_edge, shortest_edge)
|
| 87 |
+
return super().center_crop(
|
| 88 |
+
image,
|
| 89 |
+
size=SizeDict(height=shortest_edge, width=shortest_edge),
|
| 90 |
+
**kwargs,
|
| 91 |
+
)
|
| 92 |
+
else:
|
| 93 |
+
# warping (no cropping) when evaluated at 384 or larger
|
| 94 |
+
return super().resize(
|
| 95 |
+
image,
|
| 96 |
+
size=SizeDict(height=shortest_edge, width=shortest_edge),
|
| 97 |
+
resample=resample,
|
| 98 |
+
**kwargs,
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
def _preprocess(
|
| 102 |
+
self,
|
| 103 |
+
images: list[np.ndarray],
|
| 104 |
+
do_resize: bool,
|
| 105 |
+
size: SizeDict,
|
| 106 |
+
resample: "PILImageResampling | None",
|
| 107 |
+
do_center_crop: bool,
|
| 108 |
+
crop_size: SizeDict,
|
| 109 |
+
do_rescale: bool,
|
| 110 |
+
rescale_factor: float,
|
| 111 |
+
do_normalize: bool,
|
| 112 |
+
image_mean: float | list[float] | None,
|
| 113 |
+
image_std: float | list[float] | None,
|
| 114 |
+
do_pad: bool | None,
|
| 115 |
+
pad_size: SizeDict | None,
|
| 116 |
+
return_tensors: str | TensorType | None,
|
| 117 |
+
crop_pct: float = 224 / 256,
|
| 118 |
+
**kwargs,
|
| 119 |
+
) -> BatchFeature:
|
| 120 |
+
"""Custom preprocessing for ConvNeXT."""
|
| 121 |
+
processed_images = []
|
| 122 |
+
for image in images:
|
| 123 |
+
if do_resize:
|
| 124 |
+
image = self.resize(image, size, resample, crop_pct)
|
| 125 |
+
if do_center_crop:
|
| 126 |
+
image = self.center_crop(image, crop_size)
|
| 127 |
+
if do_rescale:
|
| 128 |
+
image = self.rescale(image, rescale_factor)
|
| 129 |
+
if do_normalize:
|
| 130 |
+
image = self.normalize(image, image_mean, image_std)
|
| 131 |
+
processed_images.append(image)
|
| 132 |
+
|
| 133 |
+
return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
__all__ = ["ConvNextImageProcessorPil"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/convnext/modeling_convnext.py
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 Meta Platforms, Inc. 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 ConvNext model."""
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from torch import nn
|
| 18 |
+
|
| 19 |
+
from ... import initialization as init
|
| 20 |
+
from ...activations import ACT2FN
|
| 21 |
+
from ...backbone_utils import BackboneMixin, filter_output_hidden_states
|
| 22 |
+
from ...modeling_outputs import (
|
| 23 |
+
BackboneOutput,
|
| 24 |
+
BaseModelOutputWithNoAttention,
|
| 25 |
+
BaseModelOutputWithPoolingAndNoAttention,
|
| 26 |
+
ImageClassifierOutputWithNoAttention,
|
| 27 |
+
)
|
| 28 |
+
from ...modeling_utils import PreTrainedModel
|
| 29 |
+
from ...processing_utils import Unpack
|
| 30 |
+
from ...utils import TransformersKwargs, auto_docstring, logging
|
| 31 |
+
from ...utils.generic import can_return_tuple, merge_with_config_defaults
|
| 32 |
+
from ...utils.output_capturing import capture_outputs
|
| 33 |
+
from .configuration_convnext import ConvNextConfig
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
logger = logging.get_logger(__name__)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class ConvNextLayerNorm(nn.LayerNorm):
|
| 40 |
+
r"""LayerNorm that supports two data formats: channels_last (default) or channels_first.
|
| 41 |
+
The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height,
|
| 42 |
+
width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width).
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
def __init__(self, normalized_shape, *, eps=1e-6, data_format="channels_last", **kwargs):
|
| 46 |
+
super().__init__(normalized_shape, eps=eps, **kwargs)
|
| 47 |
+
if data_format not in ["channels_last", "channels_first"]:
|
| 48 |
+
raise NotImplementedError(f"Unsupported data format: {data_format}")
|
| 49 |
+
self.data_format = data_format
|
| 50 |
+
|
| 51 |
+
def forward(self, features: torch.Tensor) -> torch.Tensor:
|
| 52 |
+
"""
|
| 53 |
+
Args:
|
| 54 |
+
features: Tensor of shape (batch_size, channels, height, width) OR (batch_size, height, width, channels)
|
| 55 |
+
"""
|
| 56 |
+
if self.data_format == "channels_first":
|
| 57 |
+
features = features.permute(0, 2, 3, 1)
|
| 58 |
+
features = super().forward(features)
|
| 59 |
+
features = features.permute(0, 3, 1, 2)
|
| 60 |
+
else:
|
| 61 |
+
features = super().forward(features)
|
| 62 |
+
return features
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class ConvNextEmbeddings(nn.Module):
|
| 66 |
+
"""This class is comparable to (and inspired by) the SwinEmbeddings class
|
| 67 |
+
found in src/transformers/models/swin/modeling_swin.py.
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
def __init__(self, config):
|
| 71 |
+
super().__init__()
|
| 72 |
+
self.patch_embeddings = nn.Conv2d(
|
| 73 |
+
config.num_channels, config.hidden_sizes[0], kernel_size=config.patch_size, stride=config.patch_size
|
| 74 |
+
)
|
| 75 |
+
self.layernorm = ConvNextLayerNorm(config.hidden_sizes[0], eps=1e-6, data_format="channels_first")
|
| 76 |
+
self.num_channels = config.num_channels
|
| 77 |
+
|
| 78 |
+
def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
|
| 79 |
+
num_channels = pixel_values.shape[1]
|
| 80 |
+
if num_channels != self.num_channels:
|
| 81 |
+
raise ValueError(
|
| 82 |
+
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
|
| 83 |
+
)
|
| 84 |
+
embeddings = self.patch_embeddings(pixel_values)
|
| 85 |
+
embeddings = self.layernorm(embeddings)
|
| 86 |
+
return embeddings
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# Copied from transformers.models.swin.modular_swin.SwinDropPath with SwinDropPath->ConvNextDropPath
|
| 90 |
+
class ConvNextDropPath(nn.Module):
|
| 91 |
+
"""Stochastic depth (DropPath) per sample, for residual blocks.
|
| 92 |
+
|
| 93 |
+
Identity when ``drop_prob`` is 0 or outside training. See `Deep Networks with Stochastic Depth
|
| 94 |
+
<https://arxiv.org/abs/1603.09382>`_.
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
def __init__(self, drop_prob: float = 0.0) -> None:
|
| 98 |
+
super().__init__()
|
| 99 |
+
self.drop_prob = drop_prob
|
| 100 |
+
|
| 101 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 102 |
+
if self.drop_prob == 0.0 or not self.training:
|
| 103 |
+
return hidden_states
|
| 104 |
+
keep_prob = 1 - self.drop_prob
|
| 105 |
+
shape = (hidden_states.shape[0],) + (1,) * (hidden_states.ndim - 1)
|
| 106 |
+
random_tensor = torch.rand(shape, dtype=hidden_states.dtype, device=hidden_states.device)
|
| 107 |
+
random_tensor = torch.floor(random_tensor + keep_prob)
|
| 108 |
+
return hidden_states.div(keep_prob) * random_tensor
|
| 109 |
+
|
| 110 |
+
def extra_repr(self) -> str:
|
| 111 |
+
return f"p={self.drop_prob}"
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class ConvNextLayer(nn.Module):
|
| 115 |
+
"""This corresponds to the `Block` class in the original implementation.
|
| 116 |
+
|
| 117 |
+
There are two equivalent implementations: [DwConv, LayerNorm (channels_first), Conv, GELU,1x1 Conv]; all in (N, C,
|
| 118 |
+
H, W) (2) [DwConv, Permute to (N, H, W, C), LayerNorm (channels_last), Linear, GELU, Linear]; Permute back
|
| 119 |
+
|
| 120 |
+
The authors used (2) as they find it slightly faster in PyTorch.
|
| 121 |
+
|
| 122 |
+
Args:
|
| 123 |
+
config ([`ConvNextConfig`]): Model configuration class.
|
| 124 |
+
dim (`int`): Number of input channels.
|
| 125 |
+
drop_path (`float`): Stochastic depth rate. Default: 0.0.
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
def __init__(self, config, dim, drop_path=0):
|
| 129 |
+
super().__init__()
|
| 130 |
+
self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim) # depthwise conv
|
| 131 |
+
self.layernorm = ConvNextLayerNorm(dim, eps=1e-6)
|
| 132 |
+
self.pwconv1 = nn.Linear(dim, 4 * dim) # pointwise/1x1 convs, implemented with linear layers
|
| 133 |
+
self.act = ACT2FN[config.hidden_act]
|
| 134 |
+
self.pwconv2 = nn.Linear(4 * dim, dim)
|
| 135 |
+
self.layer_scale_parameter = (
|
| 136 |
+
nn.Parameter(config.layer_scale_init_value * torch.ones(dim), requires_grad=True)
|
| 137 |
+
if config.layer_scale_init_value > 0
|
| 138 |
+
else None
|
| 139 |
+
)
|
| 140 |
+
self.drop_path = ConvNextDropPath(drop_path) if drop_path > 0.0 else nn.Identity()
|
| 141 |
+
|
| 142 |
+
def forward(self, features: torch.Tensor) -> torch.Tensor:
|
| 143 |
+
residual = features
|
| 144 |
+
features = self.dwconv(features)
|
| 145 |
+
features = features.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C)
|
| 146 |
+
features = self.layernorm(features)
|
| 147 |
+
features = self.pwconv1(features)
|
| 148 |
+
features = self.act(features)
|
| 149 |
+
features = self.pwconv2(features)
|
| 150 |
+
if self.layer_scale_parameter is not None:
|
| 151 |
+
features = self.layer_scale_parameter * features
|
| 152 |
+
features = features.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W)
|
| 153 |
+
features = residual + self.drop_path(features)
|
| 154 |
+
return features
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
class ConvNextStage(nn.Module):
|
| 158 |
+
"""ConvNeXT stage, consisting of an optional downsampling layer + multiple residual blocks.
|
| 159 |
+
|
| 160 |
+
Args:
|
| 161 |
+
config ([`ConvNextConfig`]): Model configuration class.
|
| 162 |
+
in_channels (`int`): Number of input channels.
|
| 163 |
+
out_channels (`int`): Number of output channels.
|
| 164 |
+
depth (`int`): Number of residual blocks.
|
| 165 |
+
drop_path_rates(`list[float]`): Stochastic depth rates for each layer.
|
| 166 |
+
"""
|
| 167 |
+
|
| 168 |
+
def __init__(self, config, in_channels, out_channels, kernel_size=2, stride=2, depth=2, drop_path_rates=None):
|
| 169 |
+
super().__init__()
|
| 170 |
+
|
| 171 |
+
if in_channels != out_channels or stride > 1:
|
| 172 |
+
self.downsampling_layer = nn.ModuleList(
|
| 173 |
+
[
|
| 174 |
+
ConvNextLayerNorm(in_channels, eps=1e-6, data_format="channels_first"),
|
| 175 |
+
nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride),
|
| 176 |
+
]
|
| 177 |
+
)
|
| 178 |
+
else:
|
| 179 |
+
self.downsampling_layer = nn.ModuleList()
|
| 180 |
+
drop_path_rates = drop_path_rates or [0.0] * depth
|
| 181 |
+
self.layers = nn.ModuleList(
|
| 182 |
+
[ConvNextLayer(config, dim=out_channels, drop_path=drop_path_rates[j]) for j in range(depth)]
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
def forward(self, features: torch.Tensor) -> torch.Tensor:
|
| 186 |
+
for layer in self.downsampling_layer:
|
| 187 |
+
features = layer(features)
|
| 188 |
+
for layer in self.layers:
|
| 189 |
+
features = layer(features)
|
| 190 |
+
return features
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
@auto_docstring
|
| 194 |
+
class ConvNextPreTrainedModel(PreTrainedModel):
|
| 195 |
+
config: ConvNextConfig
|
| 196 |
+
base_model_prefix = "convnext"
|
| 197 |
+
main_input_name = "pixel_values"
|
| 198 |
+
input_modalities = ("image",)
|
| 199 |
+
_no_split_modules = ["ConvNextLayer", "ConvNextStage"]
|
| 200 |
+
|
| 201 |
+
@torch.no_grad()
|
| 202 |
+
def _init_weights(self, module):
|
| 203 |
+
"""Initialize the weights"""
|
| 204 |
+
super()._init_weights(module)
|
| 205 |
+
if isinstance(module, ConvNextLayer):
|
| 206 |
+
if module.layer_scale_parameter is not None:
|
| 207 |
+
init.constant_(module.layer_scale_parameter, self.config.layer_scale_init_value)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
class ConvNextEncoder(ConvNextPreTrainedModel):
|
| 211 |
+
main_input_name = "hidden_states"
|
| 212 |
+
_can_record_outputs = {"hidden_states": ConvNextStage}
|
| 213 |
+
|
| 214 |
+
def __init__(self, config):
|
| 215 |
+
super().__init__(config)
|
| 216 |
+
self.stages = nn.ModuleList()
|
| 217 |
+
drop_path_rates = [
|
| 218 |
+
x.tolist()
|
| 219 |
+
for x in torch.linspace(0, config.drop_path_rate, sum(config.depths), device="cpu").split(config.depths)
|
| 220 |
+
]
|
| 221 |
+
prev_chs = config.hidden_sizes[0]
|
| 222 |
+
for i in range(config.num_stages):
|
| 223 |
+
out_chs = config.hidden_sizes[i]
|
| 224 |
+
stage = ConvNextStage(
|
| 225 |
+
config,
|
| 226 |
+
in_channels=prev_chs,
|
| 227 |
+
out_channels=out_chs,
|
| 228 |
+
stride=2 if i > 0 else 1,
|
| 229 |
+
depth=config.depths[i],
|
| 230 |
+
drop_path_rates=drop_path_rates[i],
|
| 231 |
+
)
|
| 232 |
+
self.stages.append(stage)
|
| 233 |
+
prev_chs = out_chs
|
| 234 |
+
|
| 235 |
+
self.post_init()
|
| 236 |
+
|
| 237 |
+
@merge_with_config_defaults
|
| 238 |
+
@capture_outputs(tie_last_hidden_states=False)
|
| 239 |
+
def forward(
|
| 240 |
+
self,
|
| 241 |
+
hidden_states: torch.Tensor,
|
| 242 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 243 |
+
) -> BaseModelOutputWithNoAttention:
|
| 244 |
+
for layer_module in self.stages:
|
| 245 |
+
hidden_states = layer_module(hidden_states)
|
| 246 |
+
|
| 247 |
+
return BaseModelOutputWithNoAttention(last_hidden_state=hidden_states)
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
@auto_docstring
|
| 251 |
+
class ConvNextModel(ConvNextPreTrainedModel):
|
| 252 |
+
def __init__(self, config):
|
| 253 |
+
super().__init__(config)
|
| 254 |
+
self.config = config
|
| 255 |
+
|
| 256 |
+
self.embeddings = ConvNextEmbeddings(config)
|
| 257 |
+
self.encoder = ConvNextEncoder(config)
|
| 258 |
+
|
| 259 |
+
# final layernorm layer
|
| 260 |
+
self.layernorm = nn.LayerNorm(config.hidden_sizes[-1], eps=config.layer_norm_eps)
|
| 261 |
+
|
| 262 |
+
# Initialize weights and apply final processing
|
| 263 |
+
self.post_init()
|
| 264 |
+
|
| 265 |
+
@can_return_tuple
|
| 266 |
+
@auto_docstring
|
| 267 |
+
def forward(
|
| 268 |
+
self, pixel_values: torch.FloatTensor | None = None, **kwargs: Unpack[TransformersKwargs]
|
| 269 |
+
) -> BaseModelOutputWithPoolingAndNoAttention:
|
| 270 |
+
if pixel_values is None:
|
| 271 |
+
raise ValueError("You have to specify pixel_values")
|
| 272 |
+
|
| 273 |
+
embedding_output = self.embeddings(pixel_values)
|
| 274 |
+
encoder_outputs: BaseModelOutputWithNoAttention = self.encoder(embedding_output, **kwargs)
|
| 275 |
+
last_hidden_state = encoder_outputs.last_hidden_state
|
| 276 |
+
|
| 277 |
+
# global average pooling, (N, C, H, W) -> (N, C)
|
| 278 |
+
pooled_output = self.layernorm(last_hidden_state.mean([-2, -1]))
|
| 279 |
+
|
| 280 |
+
return BaseModelOutputWithPoolingAndNoAttention(
|
| 281 |
+
last_hidden_state=last_hidden_state,
|
| 282 |
+
pooler_output=pooled_output,
|
| 283 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
@auto_docstring(
|
| 288 |
+
custom_intro="""
|
| 289 |
+
ConvNext Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
|
| 290 |
+
ImageNet.
|
| 291 |
+
"""
|
| 292 |
+
)
|
| 293 |
+
class ConvNextForImageClassification(ConvNextPreTrainedModel):
|
| 294 |
+
accepts_loss_kwargs = False
|
| 295 |
+
|
| 296 |
+
def __init__(self, config):
|
| 297 |
+
super().__init__(config)
|
| 298 |
+
|
| 299 |
+
self.num_labels = config.num_labels
|
| 300 |
+
self.convnext = ConvNextModel(config)
|
| 301 |
+
|
| 302 |
+
# Classifier head
|
| 303 |
+
if config.num_labels > 0:
|
| 304 |
+
self.classifier = nn.Linear(config.hidden_sizes[-1], config.num_labels)
|
| 305 |
+
else:
|
| 306 |
+
self.classifier = nn.Identity()
|
| 307 |
+
|
| 308 |
+
# Initialize weights and apply final processing
|
| 309 |
+
self.post_init()
|
| 310 |
+
|
| 311 |
+
@can_return_tuple
|
| 312 |
+
@auto_docstring
|
| 313 |
+
def forward(
|
| 314 |
+
self, pixel_values: torch.FloatTensor | None = None, labels: torch.LongTensor | None = None, **kwargs
|
| 315 |
+
) -> ImageClassifierOutputWithNoAttention:
|
| 316 |
+
r"""
|
| 317 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 318 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 319 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 320 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 321 |
+
"""
|
| 322 |
+
outputs: BaseModelOutputWithPoolingAndNoAttention = self.convnext(pixel_values, **kwargs)
|
| 323 |
+
pooled_output = outputs.pooler_output
|
| 324 |
+
logits = self.classifier(pooled_output)
|
| 325 |
+
|
| 326 |
+
loss = None
|
| 327 |
+
if labels is not None:
|
| 328 |
+
loss = self.loss_function(labels=labels, pooled_logits=logits, config=self.config)
|
| 329 |
+
|
| 330 |
+
return ImageClassifierOutputWithNoAttention(
|
| 331 |
+
loss=loss,
|
| 332 |
+
logits=logits,
|
| 333 |
+
hidden_states=outputs.hidden_states,
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
@auto_docstring(
|
| 338 |
+
custom_intro="""
|
| 339 |
+
ConvNeXt backbone, to be used with frameworks like DETR and MaskFormer.
|
| 340 |
+
"""
|
| 341 |
+
)
|
| 342 |
+
class ConvNextBackbone(BackboneMixin, ConvNextPreTrainedModel):
|
| 343 |
+
has_attentions = False
|
| 344 |
+
|
| 345 |
+
def __init__(self, config):
|
| 346 |
+
super().__init__(config)
|
| 347 |
+
|
| 348 |
+
self.embeddings = ConvNextEmbeddings(config)
|
| 349 |
+
self.encoder = ConvNextEncoder(config)
|
| 350 |
+
self.num_features = [config.hidden_sizes[0]] + config.hidden_sizes
|
| 351 |
+
|
| 352 |
+
# Add layer norms to hidden states of out_features
|
| 353 |
+
hidden_states_norms = {}
|
| 354 |
+
for stage, num_channels in zip(self.out_features, self.channels):
|
| 355 |
+
hidden_states_norms[stage] = ConvNextLayerNorm(num_channels, data_format="channels_first")
|
| 356 |
+
self.hidden_states_norms = nn.ModuleDict(hidden_states_norms)
|
| 357 |
+
|
| 358 |
+
# initialize weights and apply final processing
|
| 359 |
+
self.post_init()
|
| 360 |
+
|
| 361 |
+
@can_return_tuple
|
| 362 |
+
@filter_output_hidden_states
|
| 363 |
+
@auto_docstring
|
| 364 |
+
def forward(
|
| 365 |
+
self,
|
| 366 |
+
pixel_values: torch.Tensor,
|
| 367 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 368 |
+
) -> BackboneOutput:
|
| 369 |
+
r"""
|
| 370 |
+
Examples:
|
| 371 |
+
|
| 372 |
+
```python
|
| 373 |
+
>>> from transformers import AutoImageProcessor, AutoBackbone
|
| 374 |
+
>>> import torch
|
| 375 |
+
>>> from PIL import Image
|
| 376 |
+
>>> import httpx
|
| 377 |
+
>>> from io import BytesIO
|
| 378 |
+
|
| 379 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 380 |
+
>>> with httpx.stream("GET", url) as response:
|
| 381 |
+
... image = Image.open(BytesIO(response.read()))
|
| 382 |
+
|
| 383 |
+
>>> processor = AutoImageProcessor.from_pretrained("facebook/convnext-tiny-224")
|
| 384 |
+
>>> model = AutoBackbone.from_pretrained("facebook/convnext-tiny-224")
|
| 385 |
+
|
| 386 |
+
>>> inputs = processor(image, return_tensors="pt")
|
| 387 |
+
>>> outputs = model(**inputs)
|
| 388 |
+
```"""
|
| 389 |
+
kwargs["output_hidden_states"] = True # required to extract layers for the stages
|
| 390 |
+
|
| 391 |
+
embedding_output = self.embeddings(pixel_values)
|
| 392 |
+
encoder_outputs: BaseModelOutputWithNoAttention = self.encoder(embedding_output, **kwargs)
|
| 393 |
+
hidden_states = encoder_outputs.hidden_states
|
| 394 |
+
|
| 395 |
+
feature_maps = []
|
| 396 |
+
for stage, hidden_state in zip(self.stage_names, hidden_states):
|
| 397 |
+
if stage in self.out_features:
|
| 398 |
+
hidden_state = self.hidden_states_norms[stage](hidden_state)
|
| 399 |
+
feature_maps.append(hidden_state)
|
| 400 |
+
|
| 401 |
+
return BackboneOutput(feature_maps=tuple(feature_maps), hidden_states=hidden_states)
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
__all__ = ["ConvNextForImageClassification", "ConvNextModel", "ConvNextPreTrainedModel", "ConvNextBackbone"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/fast_vlm/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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_fast_vlm import *
|
| 22 |
+
from .modeling_fast_vlm 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/fast_vlm/configuration_fast_vlm.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/fast_vlm/modular_fast_vlm.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_fast_vlm.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2025 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 |
+
|
| 21 |
+
|
| 22 |
+
from huggingface_hub.dataclasses import strict
|
| 23 |
+
|
| 24 |
+
from ...configuration_utils import PreTrainedConfig
|
| 25 |
+
from ...utils import auto_docstring
|
| 26 |
+
from ..auto import CONFIG_MAPPING, AutoConfig
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@auto_docstring(checkpoint="KamilaMila/FastVLM-7B")
|
| 30 |
+
@strict
|
| 31 |
+
class FastVlmConfig(PreTrainedConfig):
|
| 32 |
+
r"""
|
| 33 |
+
Example:
|
| 34 |
+
|
| 35 |
+
```python
|
| 36 |
+
>>> from transformers import FastVlmForConditionalGeneration, FastVlmConfig
|
| 37 |
+
|
| 38 |
+
>>> # Initializing a FastVLM-7B style configuration
|
| 39 |
+
>>> configuration = FastVlmConfig()
|
| 40 |
+
|
| 41 |
+
>>> # Initializing a model from the FastVLM-7B style configuration
|
| 42 |
+
>>> model = FastVlmForConditionalGeneration(configuration)
|
| 43 |
+
|
| 44 |
+
>>> # Accessing the model configuration
|
| 45 |
+
>>> configuration = model.config
|
| 46 |
+
```"""
|
| 47 |
+
|
| 48 |
+
model_type = "fast_vlm"
|
| 49 |
+
attribute_map = {
|
| 50 |
+
"image_token_id": "image_token_index",
|
| 51 |
+
}
|
| 52 |
+
sub_configs = {"text_config": AutoConfig, "vision_config": AutoConfig}
|
| 53 |
+
|
| 54 |
+
vision_config: dict | PreTrainedConfig | None = None
|
| 55 |
+
text_config: dict | PreTrainedConfig | None = None
|
| 56 |
+
image_token_index: int = 151646
|
| 57 |
+
image_seq_length: int = 576
|
| 58 |
+
projector_hidden_act: str = "gelu"
|
| 59 |
+
vision_feature_select_strategy: str = "full"
|
| 60 |
+
vision_feature_layer: int | list[int] = -1
|
| 61 |
+
multimodal_projector_bias: bool = True
|
| 62 |
+
tie_word_embeddings: bool = False
|
| 63 |
+
|
| 64 |
+
def __post_init__(self, **kwargs):
|
| 65 |
+
if isinstance(self.vision_config, dict):
|
| 66 |
+
self.vision_config["model_type"] = self.vision_config.get("model_type", "timm_wrapper")
|
| 67 |
+
self.vision_config = CONFIG_MAPPING[self.vision_config["model_type"]](**self.vision_config)
|
| 68 |
+
elif self.vision_config is None:
|
| 69 |
+
self.vision_config = CONFIG_MAPPING["timm_wrapper"](
|
| 70 |
+
architecture="fastvit_mci3",
|
| 71 |
+
do_pooling=True,
|
| 72 |
+
global_pool="avg",
|
| 73 |
+
hidden_size=3072,
|
| 74 |
+
initializer_range=0.02,
|
| 75 |
+
model_args={"inference_mode": True},
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
if isinstance(self.text_config, dict):
|
| 79 |
+
self.text_config["model_type"] = self.text_config.get("model_type", "qwen2")
|
| 80 |
+
self.text_config = CONFIG_MAPPING[self.text_config["model_type"]](**self.text_config)
|
| 81 |
+
elif self.text_config is None:
|
| 82 |
+
self.text_config = CONFIG_MAPPING["qwen2"](
|
| 83 |
+
hidden_size=3584,
|
| 84 |
+
vocab_size=152128,
|
| 85 |
+
intermediate_size=18944,
|
| 86 |
+
num_attention_heads=28,
|
| 87 |
+
num_key_value_heads=4,
|
| 88 |
+
num_hidden_layers=28,
|
| 89 |
+
)
|
| 90 |
+
# The default value is `False` but this config is used with many model types
|
| 91 |
+
# Attr `tie_word_embeddings` was saved in text config for those models, so we
|
| 92 |
+
# need an ugly workaround and forward-pass the attr from text config
|
| 93 |
+
if not self.tie_word_embeddings and self.text_config.tie_word_embeddings:
|
| 94 |
+
self.tie_word_embeddings = self.text_config.tie_word_embeddings
|
| 95 |
+
|
| 96 |
+
super().__post_init__(**kwargs)
|
| 97 |
+
|
| 98 |
+
def validate_architecture(self):
|
| 99 |
+
"""Part of `@strict`-powered validation. Validates the architecture of the config."""
|
| 100 |
+
if self.vision_feature_select_strategy != "full":
|
| 101 |
+
raise ValueError(
|
| 102 |
+
f"Unexpected select feature strategy: {self.vision_feature_select_strategy}. Only 'full' is supported in FastVLM."
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
if self.vision_feature_layer != -1:
|
| 106 |
+
raise ValueError(
|
| 107 |
+
f"Unexpected vision feature layer: {self.vision_feature_layer}. Only -1 is supported in FastVLM."
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
__all__ = ["FastVlmConfig"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/fast_vlm/modeling_fast_vlm.py
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/fast_vlm/modular_fast_vlm.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_fast_vlm.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2025 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 |
+
|
| 21 |
+
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
from torch import nn
|
| 26 |
+
|
| 27 |
+
from ...activations import ACT2FN
|
| 28 |
+
from ...cache_utils import Cache
|
| 29 |
+
from ...generation import GenerationMixin
|
| 30 |
+
from ...modeling_outputs import BaseModelOutputWithPast, BaseModelOutputWithPooling, ModelOutput
|
| 31 |
+
from ...modeling_utils import PreTrainedModel
|
| 32 |
+
from ...processing_utils import Unpack
|
| 33 |
+
from ...utils import TransformersKwargs, auto_docstring, torch_compilable_check
|
| 34 |
+
from ...utils.generic import can_return_tuple, merge_with_config_defaults
|
| 35 |
+
from ..auto import AutoModel
|
| 36 |
+
from .configuration_fast_vlm import FastVlmConfig
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class FastVlmMultiModalProjector(nn.Module):
|
| 40 |
+
def __init__(self, config: FastVlmConfig):
|
| 41 |
+
super().__init__()
|
| 42 |
+
self.linear_1 = nn.Linear(
|
| 43 |
+
config.vision_config.hidden_size,
|
| 44 |
+
config.text_config.hidden_size,
|
| 45 |
+
bias=config.multimodal_projector_bias,
|
| 46 |
+
)
|
| 47 |
+
self.act = ACT2FN[config.projector_hidden_act]
|
| 48 |
+
self.linear_2 = nn.Linear(
|
| 49 |
+
config.text_config.hidden_size, config.text_config.hidden_size, bias=config.multimodal_projector_bias
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
def forward(self, image_features):
|
| 53 |
+
hidden_states = self.linear_1(image_features)
|
| 54 |
+
hidden_states = self.act(hidden_states)
|
| 55 |
+
hidden_states = self.linear_2(hidden_states)
|
| 56 |
+
return hidden_states
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@auto_docstring
|
| 60 |
+
class FastVlmPreTrainedModel(PreTrainedModel):
|
| 61 |
+
config: FastVlmConfig
|
| 62 |
+
base_model_prefix = "model"
|
| 63 |
+
input_modalities = ("image", "text")
|
| 64 |
+
supports_gradient_checkpointing = True
|
| 65 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 66 |
+
|
| 67 |
+
_supports_flash_attn = True
|
| 68 |
+
_supports_sdpa = True
|
| 69 |
+
|
| 70 |
+
_can_compile_fullgraph = True
|
| 71 |
+
_supports_flex_attn = True
|
| 72 |
+
_supports_attention_backend = True
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@auto_docstring(
|
| 76 |
+
custom_intro="""
|
| 77 |
+
Base class for FastVlm outputs, with hidden states and attentions.
|
| 78 |
+
"""
|
| 79 |
+
)
|
| 80 |
+
@dataclass
|
| 81 |
+
class FastVlmModelOutputWithPast(BaseModelOutputWithPast):
|
| 82 |
+
r"""
|
| 83 |
+
past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 84 |
+
It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
|
| 85 |
+
|
| 86 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
|
| 87 |
+
`past_key_values` input) to speed up sequential decoding.
|
| 88 |
+
image_hidden_states (`torch.FloatTensor`, *optional*):
|
| 89 |
+
A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
|
| 90 |
+
image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
image_hidden_states: torch.FloatTensor | None = None
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@auto_docstring(
|
| 97 |
+
custom_intro="""
|
| 98 |
+
The FastVlm model which consists of a vision backbone and a language model, without a language modeling head.
|
| 99 |
+
"""
|
| 100 |
+
)
|
| 101 |
+
class FastVlmModel(FastVlmPreTrainedModel):
|
| 102 |
+
def __init__(self, config: FastVlmConfig):
|
| 103 |
+
super().__init__(config)
|
| 104 |
+
self.vision_tower = AutoModel.from_config(config.vision_config)
|
| 105 |
+
|
| 106 |
+
self.multi_modal_projector = FastVlmMultiModalProjector(config)
|
| 107 |
+
self.language_model = AutoModel.from_config(config.text_config)
|
| 108 |
+
self.post_init()
|
| 109 |
+
|
| 110 |
+
@merge_with_config_defaults
|
| 111 |
+
@can_return_tuple
|
| 112 |
+
@auto_docstring(
|
| 113 |
+
custom_intro="Obtains image last hidden states from the vision tower and apply multimodal projection."
|
| 114 |
+
)
|
| 115 |
+
def get_image_features(
|
| 116 |
+
self,
|
| 117 |
+
pixel_values: torch.FloatTensor,
|
| 118 |
+
vision_feature_layer: int | list[int] | list[int] | None = None,
|
| 119 |
+
vision_feature_select_strategy: str | None = None,
|
| 120 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 121 |
+
) -> tuple | BaseModelOutputWithPooling:
|
| 122 |
+
r"""
|
| 123 |
+
pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`):
|
| 124 |
+
The tensors corresponding to the input images.
|
| 125 |
+
vision_feature_layer (`Union[int, list[int]]`, *optional*):
|
| 126 |
+
The index/indices of the layer to select the vision feature. Only -1 supported.
|
| 127 |
+
vision_feature_select_strategy (`str`, *optional*):
|
| 128 |
+
The feature selection strategy used to select the vision feature from the vision backbone.
|
| 129 |
+
Only "full" supported.
|
| 130 |
+
"""
|
| 131 |
+
kwargs = {k: v for k, v in kwargs.items() if v is not None}
|
| 132 |
+
image_outputs = self.vision_tower(pixel_values, return_dict=True, **kwargs)
|
| 133 |
+
|
| 134 |
+
# since the vision tower is hybrid in FastVLM, its output needs to be handled differently from Llava
|
| 135 |
+
selected_image_feature = image_outputs.last_hidden_state
|
| 136 |
+
selected_image_feature = selected_image_feature.flatten(2).permute(0, 2, 1)
|
| 137 |
+
image_features = self.multi_modal_projector(selected_image_feature)
|
| 138 |
+
image_outputs.pooler_output = list(image_features)
|
| 139 |
+
|
| 140 |
+
return image_outputs
|
| 141 |
+
|
| 142 |
+
def get_placeholder_mask(
|
| 143 |
+
self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: torch.FloatTensor
|
| 144 |
+
):
|
| 145 |
+
"""
|
| 146 |
+
Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
|
| 147 |
+
equal to the length of multimodal features. If the lengths are different, an error is raised.
|
| 148 |
+
"""
|
| 149 |
+
if input_ids is None:
|
| 150 |
+
special_image_mask = inputs_embeds == self.get_input_embeddings()(
|
| 151 |
+
torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
|
| 152 |
+
)
|
| 153 |
+
special_image_mask = special_image_mask.all(-1)
|
| 154 |
+
else:
|
| 155 |
+
special_image_mask = input_ids == self.config.image_token_id
|
| 156 |
+
|
| 157 |
+
n_image_tokens = special_image_mask.sum()
|
| 158 |
+
n_image_features = image_features.shape[0] * image_features.shape[1]
|
| 159 |
+
special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
|
| 160 |
+
torch_compilable_check(
|
| 161 |
+
inputs_embeds[special_image_mask].numel() == image_features.numel(),
|
| 162 |
+
f"Image features and image tokens do not match, tokens: {n_image_tokens}, features: {n_image_features}",
|
| 163 |
+
)
|
| 164 |
+
return special_image_mask
|
| 165 |
+
|
| 166 |
+
@can_return_tuple
|
| 167 |
+
@auto_docstring
|
| 168 |
+
def forward(
|
| 169 |
+
self,
|
| 170 |
+
input_ids: torch.LongTensor | None = None,
|
| 171 |
+
pixel_values: torch.FloatTensor | None = None,
|
| 172 |
+
attention_mask: torch.Tensor | None = None,
|
| 173 |
+
position_ids: torch.LongTensor | None = None,
|
| 174 |
+
past_key_values: Cache | None = None,
|
| 175 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 176 |
+
vision_feature_layer: int | list[int] | list[int] | None = None,
|
| 177 |
+
vision_feature_select_strategy: str | None = None,
|
| 178 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 179 |
+
) -> tuple | FastVlmModelOutputWithPast:
|
| 180 |
+
r"""
|
| 181 |
+
vision_feature_layer (`Union[int, list[int], NoneType]`, *optional*):
|
| 182 |
+
The index of the layer to select the vision feature. If multiple indices are provided, the vision feature of the
|
| 183 |
+
corresponding indices will be concatenated to form the vision features. Only -1 supported.
|
| 184 |
+
vision_feature_select_strategy (`str`, *optional*):
|
| 185 |
+
The feature selection strategy used to select the vision feature from the vision backbone. Only "full" supported.
|
| 186 |
+
"""
|
| 187 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 188 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 189 |
+
|
| 190 |
+
if inputs_embeds is None:
|
| 191 |
+
inputs_embeds = self.get_input_embeddings()(input_ids)
|
| 192 |
+
|
| 193 |
+
if pixel_values is not None:
|
| 194 |
+
image_features = self.get_image_features(
|
| 195 |
+
pixel_values=pixel_values,
|
| 196 |
+
vision_feature_layer=vision_feature_layer,
|
| 197 |
+
vision_feature_select_strategy=vision_feature_select_strategy,
|
| 198 |
+
return_dict=True,
|
| 199 |
+
).pooler_output
|
| 200 |
+
image_features = torch.cat(image_features, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
|
| 201 |
+
special_image_mask = self.get_placeholder_mask(
|
| 202 |
+
input_ids, inputs_embeds=inputs_embeds, image_features=image_features
|
| 203 |
+
)
|
| 204 |
+
inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
|
| 205 |
+
|
| 206 |
+
outputs = self.language_model(
|
| 207 |
+
attention_mask=attention_mask,
|
| 208 |
+
position_ids=position_ids,
|
| 209 |
+
past_key_values=past_key_values,
|
| 210 |
+
inputs_embeds=inputs_embeds,
|
| 211 |
+
**kwargs,
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
return FastVlmModelOutputWithPast(
|
| 215 |
+
last_hidden_state=outputs.last_hidden_state,
|
| 216 |
+
past_key_values=outputs.past_key_values,
|
| 217 |
+
hidden_states=outputs.hidden_states,
|
| 218 |
+
attentions=outputs.attentions,
|
| 219 |
+
image_hidden_states=image_features if pixel_values is not None else None,
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
@auto_docstring(
|
| 224 |
+
custom_intro="""
|
| 225 |
+
Base class for FastVlm causal language model (or autoregressive) outputs.
|
| 226 |
+
"""
|
| 227 |
+
)
|
| 228 |
+
@dataclass
|
| 229 |
+
class FastVlmCausalLMOutputWithPast(ModelOutput):
|
| 230 |
+
r"""
|
| 231 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
| 232 |
+
Language modeling loss (for next-token prediction).
|
| 233 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
| 234 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
| 235 |
+
past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 236 |
+
It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
|
| 237 |
+
|
| 238 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
|
| 239 |
+
`past_key_values` input) to speed up sequential decoding.
|
| 240 |
+
image_hidden_states (`torch.FloatTensor`, *optional*):
|
| 241 |
+
A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
|
| 242 |
+
image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
|
| 243 |
+
"""
|
| 244 |
+
|
| 245 |
+
loss: torch.FloatTensor | None = None
|
| 246 |
+
logits: torch.FloatTensor | None = None
|
| 247 |
+
past_key_values: Cache | None = None
|
| 248 |
+
hidden_states: tuple[torch.FloatTensor] | None = None
|
| 249 |
+
attentions: tuple[torch.FloatTensor] | None = None
|
| 250 |
+
image_hidden_states: torch.FloatTensor | None = None
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
@auto_docstring(
|
| 254 |
+
custom_intro="""
|
| 255 |
+
The FastVlm model which consists of a vision backbone and a language model.
|
| 256 |
+
"""
|
| 257 |
+
)
|
| 258 |
+
class FastVlmForConditionalGeneration(FastVlmPreTrainedModel, GenerationMixin):
|
| 259 |
+
_tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
|
| 260 |
+
|
| 261 |
+
def __init__(self, config: FastVlmConfig):
|
| 262 |
+
super().__init__(config)
|
| 263 |
+
self.model = FastVlmModel(config)
|
| 264 |
+
self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
|
| 265 |
+
self.post_init()
|
| 266 |
+
|
| 267 |
+
def get_output_embeddings(self) -> nn.Module:
|
| 268 |
+
return self.lm_head
|
| 269 |
+
|
| 270 |
+
@auto_docstring
|
| 271 |
+
def get_image_features(
|
| 272 |
+
self,
|
| 273 |
+
pixel_values: torch.FloatTensor,
|
| 274 |
+
vision_feature_layer: int | list[int] | list[int] | None = None,
|
| 275 |
+
vision_feature_select_strategy: str | None = None,
|
| 276 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 277 |
+
) -> tuple | BaseModelOutputWithPooling:
|
| 278 |
+
return self.model.get_image_features(
|
| 279 |
+
pixel_values=pixel_values,
|
| 280 |
+
vision_feature_layer=vision_feature_layer,
|
| 281 |
+
vision_feature_select_strategy=vision_feature_select_strategy,
|
| 282 |
+
**kwargs,
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
@can_return_tuple
|
| 286 |
+
@auto_docstring
|
| 287 |
+
def forward(
|
| 288 |
+
self,
|
| 289 |
+
input_ids: torch.LongTensor | None = None,
|
| 290 |
+
pixel_values: torch.FloatTensor | None = None,
|
| 291 |
+
attention_mask: torch.Tensor | None = None,
|
| 292 |
+
position_ids: torch.LongTensor | None = None,
|
| 293 |
+
past_key_values: Cache | None = None,
|
| 294 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 295 |
+
vision_feature_layer: int | list[int] | list[int] | None = None,
|
| 296 |
+
vision_feature_select_strategy: str | None = None,
|
| 297 |
+
labels: torch.LongTensor | None = None,
|
| 298 |
+
logits_to_keep: int | torch.Tensor = 0,
|
| 299 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 300 |
+
) -> tuple | FastVlmCausalLMOutputWithPast:
|
| 301 |
+
r"""
|
| 302 |
+
vision_feature_layer (`Union[int, list[int], NoneType]`, *optional*):
|
| 303 |
+
The index of the layer to select the vision feature. If multiple indices are provided, the vision feature of the
|
| 304 |
+
corresponding indices will be concatenated to form the vision features. Only -1 supported.
|
| 305 |
+
vision_feature_select_strategy (`str`, *optional*):
|
| 306 |
+
The feature selection strategy used to select the vision feature from the vision backbone. Only "full" supported.
|
| 307 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 308 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 309 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 310 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 311 |
+
|
| 312 |
+
Example:
|
| 313 |
+
|
| 314 |
+
```python
|
| 315 |
+
>>> from PIL import Image
|
| 316 |
+
>>> import httpx
|
| 317 |
+
>>> from io import BytesIO
|
| 318 |
+
>>> from transformers import AutoProcessor, AutoModelForImageTextToText
|
| 319 |
+
>>> import torch
|
| 320 |
+
|
| 321 |
+
>>> device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 322 |
+
|
| 323 |
+
>>> model = AutoModelForImageTextToText.from_pretrained("KamilaMila/FastVLM-0.5B").to(device)
|
| 324 |
+
>>> processor = AutoProcessor.from_pretrained("KamilaMila/FastVLM-0.5B")
|
| 325 |
+
|
| 326 |
+
>>> conversation = [
|
| 327 |
+
{
|
| 328 |
+
"role": "user",
|
| 329 |
+
"content": [
|
| 330 |
+
{"type": "text", "text": "What are these?"},
|
| 331 |
+
{"type": "image"}
|
| 332 |
+
]
|
| 333 |
+
}
|
| 334 |
+
]
|
| 335 |
+
|
| 336 |
+
>>> prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
|
| 337 |
+
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
|
| 338 |
+
>>> with httpx.stream("GET", url) as response:
|
| 339 |
+
... image = Image.open(BytesIO(response.read()))
|
| 340 |
+
|
| 341 |
+
>>> inputs = processor(images=image, text=prompt, return_tensors="pt").to(device)
|
| 342 |
+
|
| 343 |
+
>>> # Generate
|
| 344 |
+
>>> generated_ids = model.generate(**inputs, max_new_tokens=15)
|
| 345 |
+
>>> print(processor.batch_decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0])
|
| 346 |
+
system\n You are a helpful assistant.\n user\n What are these?\n assistant\n The image depicts a traditional Chinese street...
|
| 347 |
+
```"""
|
| 348 |
+
outputs = self.model(
|
| 349 |
+
input_ids=input_ids,
|
| 350 |
+
pixel_values=pixel_values,
|
| 351 |
+
attention_mask=attention_mask,
|
| 352 |
+
position_ids=position_ids,
|
| 353 |
+
past_key_values=past_key_values,
|
| 354 |
+
inputs_embeds=inputs_embeds,
|
| 355 |
+
vision_feature_layer=vision_feature_layer,
|
| 356 |
+
vision_feature_select_strategy=vision_feature_select_strategy,
|
| 357 |
+
**kwargs,
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
+
hidden_states = outputs[0]
|
| 361 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 362 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 363 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
| 364 |
+
|
| 365 |
+
loss = None
|
| 366 |
+
if labels is not None:
|
| 367 |
+
loss = self.loss_function(
|
| 368 |
+
logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
|
| 369 |
+
)
|
| 370 |
+
|
| 371 |
+
return FastVlmCausalLMOutputWithPast(
|
| 372 |
+
loss=loss,
|
| 373 |
+
logits=logits,
|
| 374 |
+
past_key_values=outputs.past_key_values,
|
| 375 |
+
hidden_states=outputs.hidden_states,
|
| 376 |
+
attentions=outputs.attentions,
|
| 377 |
+
image_hidden_states=outputs.image_hidden_states,
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
def prepare_inputs_for_generation(
|
| 381 |
+
self,
|
| 382 |
+
input_ids,
|
| 383 |
+
past_key_values=None,
|
| 384 |
+
inputs_embeds=None,
|
| 385 |
+
pixel_values=None,
|
| 386 |
+
attention_mask=None,
|
| 387 |
+
logits_to_keep=None,
|
| 388 |
+
is_first_iteration=False,
|
| 389 |
+
**kwargs,
|
| 390 |
+
):
|
| 391 |
+
# Overwritten -- in specific circumstances we don't want to forward image inputs to the model
|
| 392 |
+
|
| 393 |
+
model_inputs = super().prepare_inputs_for_generation(
|
| 394 |
+
input_ids,
|
| 395 |
+
past_key_values=past_key_values,
|
| 396 |
+
inputs_embeds=inputs_embeds,
|
| 397 |
+
attention_mask=attention_mask,
|
| 398 |
+
logits_to_keep=logits_to_keep,
|
| 399 |
+
is_first_iteration=is_first_iteration,
|
| 400 |
+
**kwargs,
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
if is_first_iteration or not kwargs.get("use_cache", True):
|
| 404 |
+
# Pixel values are used only in the first iteration if available
|
| 405 |
+
# In subsequent iterations, they are already merged with text and cached
|
| 406 |
+
# NOTE: first iteration doesn't have to be prefill, it can be the first
|
| 407 |
+
# iteration with a question and cached system prompt (continue generate from cache)
|
| 408 |
+
model_inputs["pixel_values"] = pixel_values
|
| 409 |
+
|
| 410 |
+
return model_inputs
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
__all__ = ["FastVlmForConditionalGeneration", "FastVlmModel", "FastVlmPreTrainedModel"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/fast_vlm/modular_fast_vlm.py
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from huggingface_hub.dataclasses import strict
|
| 18 |
+
from torch import nn
|
| 19 |
+
|
| 20 |
+
from ...activations import ACT2FN
|
| 21 |
+
from ...cache_utils import Cache
|
| 22 |
+
from ...configuration_utils import PreTrainedConfig
|
| 23 |
+
from ...modeling_outputs import BaseModelOutputWithPooling
|
| 24 |
+
from ...processing_utils import Unpack
|
| 25 |
+
from ...utils import TransformersKwargs, auto_docstring
|
| 26 |
+
from ...utils.generic import can_return_tuple, merge_with_config_defaults
|
| 27 |
+
from ..auto import CONFIG_MAPPING
|
| 28 |
+
from ..llava.configuration_llava import LlavaConfig
|
| 29 |
+
from ..llava.modeling_llava import (
|
| 30 |
+
LlavaCausalLMOutputWithPast,
|
| 31 |
+
LlavaForConditionalGeneration,
|
| 32 |
+
LlavaModel,
|
| 33 |
+
LlavaModelOutputWithPast,
|
| 34 |
+
LlavaMultiModalProjector,
|
| 35 |
+
LlavaPreTrainedModel,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@auto_docstring(checkpoint="KamilaMila/FastVLM-7B")
|
| 40 |
+
@strict
|
| 41 |
+
class FastVlmConfig(LlavaConfig):
|
| 42 |
+
r"""
|
| 43 |
+
Example:
|
| 44 |
+
|
| 45 |
+
```python
|
| 46 |
+
>>> from transformers import FastVlmForConditionalGeneration, FastVlmConfig
|
| 47 |
+
|
| 48 |
+
>>> # Initializing a FastVLM-7B style configuration
|
| 49 |
+
>>> configuration = FastVlmConfig()
|
| 50 |
+
|
| 51 |
+
>>> # Initializing a model from the FastVLM-7B style configuration
|
| 52 |
+
>>> model = FastVlmForConditionalGeneration(configuration)
|
| 53 |
+
|
| 54 |
+
>>> # Accessing the model configuration
|
| 55 |
+
>>> configuration = model.config
|
| 56 |
+
```"""
|
| 57 |
+
|
| 58 |
+
model_type = "fast_vlm"
|
| 59 |
+
|
| 60 |
+
vision_config: dict | PreTrainedConfig | None = None
|
| 61 |
+
text_config: dict | PreTrainedConfig | None = None
|
| 62 |
+
image_token_index: int = 151646
|
| 63 |
+
projector_hidden_act: str = "gelu"
|
| 64 |
+
vision_feature_select_strategy: str = "full"
|
| 65 |
+
vision_feature_layer: int | list[int] = -1
|
| 66 |
+
multimodal_projector_bias: bool = True
|
| 67 |
+
tie_word_embeddings: bool = False
|
| 68 |
+
|
| 69 |
+
def __post_init__(self, **kwargs):
|
| 70 |
+
if isinstance(self.vision_config, dict):
|
| 71 |
+
self.vision_config["model_type"] = self.vision_config.get("model_type", "timm_wrapper")
|
| 72 |
+
self.vision_config = CONFIG_MAPPING[self.vision_config["model_type"]](**self.vision_config)
|
| 73 |
+
elif self.vision_config is None:
|
| 74 |
+
self.vision_config = CONFIG_MAPPING["timm_wrapper"](
|
| 75 |
+
architecture="fastvit_mci3",
|
| 76 |
+
do_pooling=True,
|
| 77 |
+
global_pool="avg",
|
| 78 |
+
hidden_size=3072,
|
| 79 |
+
initializer_range=0.02,
|
| 80 |
+
model_args={"inference_mode": True},
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
if isinstance(self.text_config, dict):
|
| 84 |
+
self.text_config["model_type"] = self.text_config.get("model_type", "qwen2")
|
| 85 |
+
self.text_config = CONFIG_MAPPING[self.text_config["model_type"]](**self.text_config)
|
| 86 |
+
elif self.text_config is None:
|
| 87 |
+
self.text_config = CONFIG_MAPPING["qwen2"](
|
| 88 |
+
hidden_size=3584,
|
| 89 |
+
vocab_size=152128,
|
| 90 |
+
intermediate_size=18944,
|
| 91 |
+
num_attention_heads=28,
|
| 92 |
+
num_key_value_heads=4,
|
| 93 |
+
num_hidden_layers=28,
|
| 94 |
+
)
|
| 95 |
+
# The default value is `False` but this config is used with many model types
|
| 96 |
+
# Attr `tie_word_embeddings` was saved in text config for those models, so we
|
| 97 |
+
# need an ugly workaround and forward-pass the attr from text config
|
| 98 |
+
if not self.tie_word_embeddings and self.text_config.tie_word_embeddings:
|
| 99 |
+
self.tie_word_embeddings = self.text_config.tie_word_embeddings
|
| 100 |
+
|
| 101 |
+
PreTrainedConfig.__post_init__(**kwargs)
|
| 102 |
+
|
| 103 |
+
def validate_architecture(self):
|
| 104 |
+
"""Part of `@strict`-powered validation. Validates the architecture of the config."""
|
| 105 |
+
if self.vision_feature_select_strategy != "full":
|
| 106 |
+
raise ValueError(
|
| 107 |
+
f"Unexpected select feature strategy: {self.vision_feature_select_strategy}. Only 'full' is supported in FastVLM."
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
if self.vision_feature_layer != -1:
|
| 111 |
+
raise ValueError(
|
| 112 |
+
f"Unexpected vision feature layer: {self.vision_feature_layer}. Only -1 is supported in FastVLM."
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class FastVlmMultiModalProjector(LlavaMultiModalProjector):
|
| 117 |
+
def __init__(self, config: FastVlmConfig):
|
| 118 |
+
nn.Module.__init__()
|
| 119 |
+
self.linear_1 = nn.Linear(
|
| 120 |
+
config.vision_config.hidden_size,
|
| 121 |
+
config.text_config.hidden_size,
|
| 122 |
+
bias=config.multimodal_projector_bias,
|
| 123 |
+
)
|
| 124 |
+
self.act = ACT2FN[config.projector_hidden_act]
|
| 125 |
+
self.linear_2 = nn.Linear(
|
| 126 |
+
config.text_config.hidden_size, config.text_config.hidden_size, bias=config.multimodal_projector_bias
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class FastVlmPreTrainedModel(LlavaPreTrainedModel):
|
| 131 |
+
pass
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class FastVlmModelOutputWithPast(LlavaModelOutputWithPast):
|
| 135 |
+
pass
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class FastVlmModel(LlavaModel):
|
| 139 |
+
def __init__(self, config: FastVlmConfig):
|
| 140 |
+
super().__init__(config)
|
| 141 |
+
|
| 142 |
+
@merge_with_config_defaults
|
| 143 |
+
@can_return_tuple
|
| 144 |
+
@auto_docstring(
|
| 145 |
+
custom_intro="Obtains image last hidden states from the vision tower and apply multimodal projection."
|
| 146 |
+
)
|
| 147 |
+
def get_image_features(
|
| 148 |
+
self,
|
| 149 |
+
pixel_values: torch.FloatTensor,
|
| 150 |
+
vision_feature_layer: int | list[int] | list[int] | None = None,
|
| 151 |
+
vision_feature_select_strategy: str | None = None,
|
| 152 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 153 |
+
) -> tuple | BaseModelOutputWithPooling:
|
| 154 |
+
r"""
|
| 155 |
+
pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`):
|
| 156 |
+
The tensors corresponding to the input images.
|
| 157 |
+
vision_feature_layer (`Union[int, list[int]]`, *optional*):
|
| 158 |
+
The index/indices of the layer to select the vision feature. Only -1 supported.
|
| 159 |
+
vision_feature_select_strategy (`str`, *optional*):
|
| 160 |
+
The feature selection strategy used to select the vision feature from the vision backbone.
|
| 161 |
+
Only "full" supported.
|
| 162 |
+
"""
|
| 163 |
+
kwargs = {k: v for k, v in kwargs.items() if v is not None}
|
| 164 |
+
image_outputs = self.vision_tower(pixel_values, return_dict=True, **kwargs)
|
| 165 |
+
|
| 166 |
+
# since the vision tower is hybrid in FastVLM, its output needs to be handled differently from Llava
|
| 167 |
+
selected_image_feature = image_outputs.last_hidden_state
|
| 168 |
+
selected_image_feature = selected_image_feature.flatten(2).permute(0, 2, 1)
|
| 169 |
+
image_features = self.multi_modal_projector(selected_image_feature)
|
| 170 |
+
image_outputs.pooler_output = list(image_features)
|
| 171 |
+
|
| 172 |
+
return image_outputs
|
| 173 |
+
|
| 174 |
+
@can_return_tuple
|
| 175 |
+
@auto_docstring
|
| 176 |
+
def forward(
|
| 177 |
+
self,
|
| 178 |
+
input_ids: torch.LongTensor | None = None,
|
| 179 |
+
pixel_values: torch.FloatTensor | None = None,
|
| 180 |
+
attention_mask: torch.Tensor | None = None,
|
| 181 |
+
position_ids: torch.LongTensor | None = None,
|
| 182 |
+
past_key_values: Cache | None = None,
|
| 183 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 184 |
+
vision_feature_layer: int | list[int] | list[int] | None = None,
|
| 185 |
+
vision_feature_select_strategy: str | None = None,
|
| 186 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 187 |
+
) -> tuple | FastVlmModelOutputWithPast:
|
| 188 |
+
r"""
|
| 189 |
+
vision_feature_layer (`Union[int, list[int], NoneType]`, *optional*):
|
| 190 |
+
The index of the layer to select the vision feature. If multiple indices are provided, the vision feature of the
|
| 191 |
+
corresponding indices will be concatenated to form the vision features. Only -1 supported.
|
| 192 |
+
vision_feature_select_strategy (`str`, *optional*):
|
| 193 |
+
The feature selection strategy used to select the vision feature from the vision backbone. Only "full" supported.
|
| 194 |
+
"""
|
| 195 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 196 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 197 |
+
|
| 198 |
+
if inputs_embeds is None:
|
| 199 |
+
inputs_embeds = self.get_input_embeddings()(input_ids)
|
| 200 |
+
|
| 201 |
+
if pixel_values is not None:
|
| 202 |
+
image_features = self.get_image_features(
|
| 203 |
+
pixel_values=pixel_values,
|
| 204 |
+
vision_feature_layer=vision_feature_layer,
|
| 205 |
+
vision_feature_select_strategy=vision_feature_select_strategy,
|
| 206 |
+
return_dict=True,
|
| 207 |
+
).pooler_output
|
| 208 |
+
image_features = torch.cat(image_features, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
|
| 209 |
+
special_image_mask = self.get_placeholder_mask(
|
| 210 |
+
input_ids, inputs_embeds=inputs_embeds, image_features=image_features
|
| 211 |
+
)
|
| 212 |
+
inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
|
| 213 |
+
|
| 214 |
+
outputs = self.language_model(
|
| 215 |
+
attention_mask=attention_mask,
|
| 216 |
+
position_ids=position_ids,
|
| 217 |
+
past_key_values=past_key_values,
|
| 218 |
+
inputs_embeds=inputs_embeds,
|
| 219 |
+
**kwargs,
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
return FastVlmModelOutputWithPast(
|
| 223 |
+
last_hidden_state=outputs.last_hidden_state,
|
| 224 |
+
past_key_values=outputs.past_key_values,
|
| 225 |
+
hidden_states=outputs.hidden_states,
|
| 226 |
+
attentions=outputs.attentions,
|
| 227 |
+
image_hidden_states=image_features if pixel_values is not None else None,
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
class FastVlmCausalLMOutputWithPast(LlavaCausalLMOutputWithPast):
|
| 232 |
+
pass
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
@auto_docstring(
|
| 236 |
+
custom_intro="""
|
| 237 |
+
The FastVlm model which consists of a vision backbone and a language model.
|
| 238 |
+
"""
|
| 239 |
+
)
|
| 240 |
+
class FastVlmForConditionalGeneration(LlavaForConditionalGeneration):
|
| 241 |
+
@can_return_tuple
|
| 242 |
+
@auto_docstring
|
| 243 |
+
def forward(
|
| 244 |
+
self,
|
| 245 |
+
input_ids: torch.LongTensor | None = None,
|
| 246 |
+
pixel_values: torch.FloatTensor | None = None,
|
| 247 |
+
attention_mask: torch.Tensor | None = None,
|
| 248 |
+
position_ids: torch.LongTensor | None = None,
|
| 249 |
+
past_key_values: Cache | None = None,
|
| 250 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 251 |
+
vision_feature_layer: int | list[int] | list[int] | None = None,
|
| 252 |
+
vision_feature_select_strategy: str | None = None,
|
| 253 |
+
labels: torch.LongTensor | None = None,
|
| 254 |
+
logits_to_keep: int | torch.Tensor = 0,
|
| 255 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 256 |
+
) -> tuple | FastVlmCausalLMOutputWithPast:
|
| 257 |
+
r"""
|
| 258 |
+
vision_feature_layer (`Union[int, list[int], NoneType]`, *optional*):
|
| 259 |
+
The index of the layer to select the vision feature. If multiple indices are provided, the vision feature of the
|
| 260 |
+
corresponding indices will be concatenated to form the vision features. Only -1 supported.
|
| 261 |
+
vision_feature_select_strategy (`str`, *optional*):
|
| 262 |
+
The feature selection strategy used to select the vision feature from the vision backbone. Only "full" supported.
|
| 263 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 264 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 265 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 266 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 267 |
+
|
| 268 |
+
Example:
|
| 269 |
+
|
| 270 |
+
```python
|
| 271 |
+
>>> from PIL import Image
|
| 272 |
+
>>> import httpx
|
| 273 |
+
>>> from io import BytesIO
|
| 274 |
+
>>> from transformers import AutoProcessor, AutoModelForImageTextToText
|
| 275 |
+
>>> import torch
|
| 276 |
+
|
| 277 |
+
>>> device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 278 |
+
|
| 279 |
+
>>> model = AutoModelForImageTextToText.from_pretrained("KamilaMila/FastVLM-0.5B").to(device)
|
| 280 |
+
>>> processor = AutoProcessor.from_pretrained("KamilaMila/FastVLM-0.5B")
|
| 281 |
+
|
| 282 |
+
>>> conversation = [
|
| 283 |
+
{
|
| 284 |
+
"role": "user",
|
| 285 |
+
"content": [
|
| 286 |
+
{"type": "text", "text": "What are these?"},
|
| 287 |
+
{"type": "image"}
|
| 288 |
+
]
|
| 289 |
+
}
|
| 290 |
+
]
|
| 291 |
+
|
| 292 |
+
>>> prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
|
| 293 |
+
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
|
| 294 |
+
>>> with httpx.stream("GET", url) as response:
|
| 295 |
+
... image = Image.open(BytesIO(response.read()))
|
| 296 |
+
|
| 297 |
+
>>> inputs = processor(images=image, text=prompt, return_tensors="pt").to(device)
|
| 298 |
+
|
| 299 |
+
>>> # Generate
|
| 300 |
+
>>> generated_ids = model.generate(**inputs, max_new_tokens=15)
|
| 301 |
+
>>> print(processor.batch_decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0])
|
| 302 |
+
system\n You are a helpful assistant.\n user\n What are these?\n assistant\n The image depicts a traditional Chinese street...
|
| 303 |
+
```"""
|
| 304 |
+
outputs = self.model(
|
| 305 |
+
input_ids=input_ids,
|
| 306 |
+
pixel_values=pixel_values,
|
| 307 |
+
attention_mask=attention_mask,
|
| 308 |
+
position_ids=position_ids,
|
| 309 |
+
past_key_values=past_key_values,
|
| 310 |
+
inputs_embeds=inputs_embeds,
|
| 311 |
+
vision_feature_layer=vision_feature_layer,
|
| 312 |
+
vision_feature_select_strategy=vision_feature_select_strategy,
|
| 313 |
+
**kwargs,
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
hidden_states = outputs[0]
|
| 317 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 318 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 319 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
| 320 |
+
|
| 321 |
+
loss = None
|
| 322 |
+
if labels is not None:
|
| 323 |
+
loss = self.loss_function(
|
| 324 |
+
logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
return FastVlmCausalLMOutputWithPast(
|
| 328 |
+
loss=loss,
|
| 329 |
+
logits=logits,
|
| 330 |
+
past_key_values=outputs.past_key_values,
|
| 331 |
+
hidden_states=outputs.hidden_states,
|
| 332 |
+
attentions=outputs.attentions,
|
| 333 |
+
image_hidden_states=outputs.image_hidden_states,
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
__all__ = ["FastVlmForConditionalGeneration", "FastVlmModel", "FastVlmPreTrainedModel", "FastVlmConfig"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/imagegpt/modeling_imagegpt.py
ADDED
|
@@ -0,0 +1,826 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 The OpenAI Team Authors and HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""PyTorch OpenAI ImageGPT model."""
|
| 15 |
+
|
| 16 |
+
import math
|
| 17 |
+
from typing import Any
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
from torch import nn
|
| 21 |
+
from torch.nn import CrossEntropyLoss
|
| 22 |
+
|
| 23 |
+
from ... import initialization as init
|
| 24 |
+
from ...activations import ACT2FN
|
| 25 |
+
from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
|
| 26 |
+
from ...generation import GenerationMixin
|
| 27 |
+
from ...masking_utils import create_bidirectional_mask, create_causal_mask
|
| 28 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 29 |
+
from ...modeling_outputs import (
|
| 30 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 31 |
+
CausalLMOutputWithCrossAttentions,
|
| 32 |
+
SequenceClassifierOutputWithPast,
|
| 33 |
+
)
|
| 34 |
+
from ...modeling_utils import PreTrainedModel
|
| 35 |
+
from ...pytorch_utils import Conv1D
|
| 36 |
+
from ...utils import (
|
| 37 |
+
auto_docstring,
|
| 38 |
+
logging,
|
| 39 |
+
torch_float,
|
| 40 |
+
)
|
| 41 |
+
from ...utils.generic import maybe_autocast
|
| 42 |
+
from .configuration_imagegpt import ImageGPTConfig
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
logger = logging.get_logger(__name__)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class ImageGPTLayerNorm(nn.Module):
|
| 49 |
+
def __init__(self, hidden_size: tuple[int], eps: float = 1e-5):
|
| 50 |
+
super().__init__()
|
| 51 |
+
self.eps = eps
|
| 52 |
+
self.weight = nn.Parameter(torch.Tensor(hidden_size))
|
| 53 |
+
|
| 54 |
+
def forward(self, tensor: torch.Tensor) -> torch.Tensor:
|
| 55 |
+
# input is not mean centered
|
| 56 |
+
tensor = tensor / torch.sqrt(torch.mean(torch.square(tensor), axis=-1, keepdim=True) + self.eps)
|
| 57 |
+
tensor = tensor * self.weight
|
| 58 |
+
return tensor
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class ImageGPTAttention(nn.Module):
|
| 62 |
+
def __init__(self, config, is_cross_attention: bool | None = False, layer_idx: int | None = None):
|
| 63 |
+
super().__init__()
|
| 64 |
+
self.config = config
|
| 65 |
+
max_positions = config.max_position_embeddings
|
| 66 |
+
self.register_buffer(
|
| 67 |
+
"bias",
|
| 68 |
+
torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)).view(
|
| 69 |
+
1, 1, max_positions, max_positions
|
| 70 |
+
),
|
| 71 |
+
persistent=False,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
self.embed_dim = config.hidden_size
|
| 75 |
+
self.num_heads = config.num_attention_heads
|
| 76 |
+
self.head_dim = self.embed_dim // self.num_heads
|
| 77 |
+
self.split_size = self.embed_dim
|
| 78 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
| 79 |
+
raise ValueError(
|
| 80 |
+
f"`embed_dim` must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
|
| 81 |
+
f" {self.num_heads})."
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
self.scale_attn_weights = config.scale_attn_weights
|
| 85 |
+
self.is_cross_attention = is_cross_attention
|
| 86 |
+
|
| 87 |
+
# Layer-wise attention scaling, reordering, and upcasting
|
| 88 |
+
self.scale_attn_by_inverse_layer_idx = config.scale_attn_by_inverse_layer_idx
|
| 89 |
+
self.layer_idx = layer_idx
|
| 90 |
+
self.reorder_and_upcast_attn = config.reorder_and_upcast_attn
|
| 91 |
+
|
| 92 |
+
if self.is_cross_attention:
|
| 93 |
+
self.c_attn = Conv1D(2 * self.embed_dim, self.embed_dim)
|
| 94 |
+
self.q_attn = Conv1D(self.embed_dim, self.embed_dim)
|
| 95 |
+
else:
|
| 96 |
+
self.c_attn = Conv1D(3 * self.embed_dim, self.embed_dim)
|
| 97 |
+
self.c_proj = Conv1D(self.embed_dim, self.embed_dim)
|
| 98 |
+
|
| 99 |
+
self.attn_dropout = nn.Dropout(config.attn_pdrop)
|
| 100 |
+
self.resid_dropout = nn.Dropout(config.resid_pdrop)
|
| 101 |
+
|
| 102 |
+
def _attn(self, query, key, value, attention_mask=None):
|
| 103 |
+
attn_weights = torch.matmul(query, key.transpose(-1, -2))
|
| 104 |
+
|
| 105 |
+
if self.scale_attn_weights:
|
| 106 |
+
attn_weights = attn_weights / torch_float(value.size(-1) ** 0.5)
|
| 107 |
+
|
| 108 |
+
# Layer-wise attention scaling
|
| 109 |
+
if self.scale_attn_by_inverse_layer_idx:
|
| 110 |
+
attn_weights = attn_weights / float(self.layer_idx + 1)
|
| 111 |
+
|
| 112 |
+
if not self.is_cross_attention:
|
| 113 |
+
# if only "normal" attention layer implements causal mask
|
| 114 |
+
query_length, key_length = query.size(-2), key.size(-2)
|
| 115 |
+
causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length]
|
| 116 |
+
mask_value = torch.finfo(attn_weights.dtype).min
|
| 117 |
+
# Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
|
| 118 |
+
# Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
|
| 119 |
+
mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype, device=attn_weights.device)
|
| 120 |
+
attn_weights = torch.where(causal_mask, attn_weights, mask_value)
|
| 121 |
+
|
| 122 |
+
if attention_mask is not None:
|
| 123 |
+
# Apply the attention mask
|
| 124 |
+
attn_weights = attn_weights + attention_mask
|
| 125 |
+
|
| 126 |
+
attn_weights = nn.Softmax(dim=-1)(attn_weights)
|
| 127 |
+
|
| 128 |
+
# Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op otherwise
|
| 129 |
+
attn_weights = attn_weights.type(value.dtype)
|
| 130 |
+
attn_weights = self.attn_dropout(attn_weights)
|
| 131 |
+
|
| 132 |
+
attn_output = torch.matmul(attn_weights, value)
|
| 133 |
+
|
| 134 |
+
return attn_output, attn_weights
|
| 135 |
+
|
| 136 |
+
def _upcast_and_reordered_attn(self, query, key, value, attention_mask=None):
|
| 137 |
+
# Use `torch.baddbmm` (a bit more efficient w/ alpha param for scaling -- from Megatron-LM)
|
| 138 |
+
bsz, num_heads, q_seq_len, dk = query.size()
|
| 139 |
+
_, _, k_seq_len, _ = key.size()
|
| 140 |
+
|
| 141 |
+
# Preallocate attn_weights for `baddbmm`
|
| 142 |
+
attn_weights = torch.empty(bsz * num_heads, q_seq_len, k_seq_len, dtype=torch.float32, device=query.device)
|
| 143 |
+
|
| 144 |
+
# Compute Scale Factor
|
| 145 |
+
scale_factor = 1.0
|
| 146 |
+
if self.scale_attn_weights:
|
| 147 |
+
scale_factor /= float(value.size(-1)) ** 0.5
|
| 148 |
+
|
| 149 |
+
if self.scale_attn_by_inverse_layer_idx:
|
| 150 |
+
scale_factor /= float(self.layer_idx + 1)
|
| 151 |
+
|
| 152 |
+
# Upcast (turn off autocast) and reorder (Scale K by 1 / root(dk))
|
| 153 |
+
with maybe_autocast(query.device.type, enabled=False):
|
| 154 |
+
q, k = query.reshape(-1, q_seq_len, dk), key.transpose(-1, -2).reshape(-1, dk, k_seq_len)
|
| 155 |
+
attn_weights = torch.baddbmm(attn_weights, q.float(), k.float(), beta=0, alpha=scale_factor)
|
| 156 |
+
attn_weights = attn_weights.reshape(bsz, num_heads, q_seq_len, k_seq_len)
|
| 157 |
+
|
| 158 |
+
if not self.is_cross_attention:
|
| 159 |
+
# if only "normal" attention layer implements causal mask
|
| 160 |
+
query_length, key_length = query.size(-2), key.size(-2)
|
| 161 |
+
causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length]
|
| 162 |
+
mask_value = torch.finfo(attn_weights.dtype).min
|
| 163 |
+
# Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
|
| 164 |
+
# Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
|
| 165 |
+
mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype, device=attn_weights.device)
|
| 166 |
+
attn_weights = torch.where(causal_mask, attn_weights, mask_value)
|
| 167 |
+
|
| 168 |
+
if attention_mask is not None:
|
| 169 |
+
# Apply the attention mask
|
| 170 |
+
attn_weights = attn_weights + attention_mask
|
| 171 |
+
|
| 172 |
+
attn_weights = nn.Softmax(dim=-1)(attn_weights)
|
| 173 |
+
|
| 174 |
+
# Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op if otherwise
|
| 175 |
+
if attn_weights.dtype != torch.float32:
|
| 176 |
+
raise RuntimeError("Error with upcasting, attn_weights does not have dtype torch.float32")
|
| 177 |
+
attn_weights = attn_weights.type(value.dtype)
|
| 178 |
+
attn_weights = self.attn_dropout(attn_weights)
|
| 179 |
+
|
| 180 |
+
attn_output = torch.matmul(attn_weights, value)
|
| 181 |
+
|
| 182 |
+
return attn_output, attn_weights
|
| 183 |
+
|
| 184 |
+
def _split_heads(self, tensor, num_heads, attn_head_size):
|
| 185 |
+
"""
|
| 186 |
+
Splits hidden_size dim into attn_head_size and num_heads
|
| 187 |
+
"""
|
| 188 |
+
new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
|
| 189 |
+
tensor = tensor.view(*new_shape)
|
| 190 |
+
return tensor.permute(0, 2, 1, 3) # (batch, head, seq_length, head_features)
|
| 191 |
+
|
| 192 |
+
def _merge_heads(self, tensor, num_heads, attn_head_size):
|
| 193 |
+
"""
|
| 194 |
+
Merges attn_head_size dim and num_attn_heads dim into hidden_size
|
| 195 |
+
"""
|
| 196 |
+
tensor = tensor.permute(0, 2, 1, 3).contiguous()
|
| 197 |
+
new_shape = tensor.size()[:-2] + (num_heads * attn_head_size,)
|
| 198 |
+
return tensor.view(new_shape)
|
| 199 |
+
|
| 200 |
+
def forward(
|
| 201 |
+
self,
|
| 202 |
+
hidden_states: torch.Tensor,
|
| 203 |
+
layer_past: Cache | None = None,
|
| 204 |
+
attention_mask: torch.Tensor | None = None,
|
| 205 |
+
encoder_hidden_states: torch.Tensor | None = None,
|
| 206 |
+
encoder_attention_mask: torch.Tensor | None = None,
|
| 207 |
+
use_cache: bool | None = False,
|
| 208 |
+
output_attentions: bool | None = False,
|
| 209 |
+
**kwargs,
|
| 210 |
+
) -> tuple:
|
| 211 |
+
is_cross_attention = encoder_hidden_states is not None
|
| 212 |
+
bsz, seq_len, _ = hidden_states.shape
|
| 213 |
+
|
| 214 |
+
if layer_past is not None:
|
| 215 |
+
if isinstance(layer_past, EncoderDecoderCache):
|
| 216 |
+
is_updated = layer_past.is_updated.get(self.layer_idx)
|
| 217 |
+
if is_cross_attention:
|
| 218 |
+
# after the first generated id, we can subsequently re-use all key/value_states from cache
|
| 219 |
+
curr_past_key_values = layer_past.cross_attention_cache
|
| 220 |
+
else:
|
| 221 |
+
curr_past_key_values = layer_past.self_attention_cache
|
| 222 |
+
else:
|
| 223 |
+
curr_past_key_values = layer_past
|
| 224 |
+
|
| 225 |
+
current_states = encoder_hidden_states if is_cross_attention else hidden_states
|
| 226 |
+
if is_cross_attention:
|
| 227 |
+
if not hasattr(self, "q_attn"):
|
| 228 |
+
raise ValueError(
|
| 229 |
+
"If class is used as cross attention, the weights `q_attn` have to be defined. "
|
| 230 |
+
"Please make sure to instantiate class with `ImageGPTAttention(..., is_cross_attention=True)`."
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
if layer_past is not None and is_updated:
|
| 234 |
+
# reuse k,v, cross_attentions, and compute only q
|
| 235 |
+
query = self.q_attn(hidden_states)
|
| 236 |
+
key = curr_past_key_values.layers[self.layer_idx].keys
|
| 237 |
+
value = curr_past_key_values.layers[self.layer_idx].values
|
| 238 |
+
else:
|
| 239 |
+
query = self.q_attn(hidden_states)
|
| 240 |
+
key, value = self.c_attn(current_states).split(self.split_size, dim=2)
|
| 241 |
+
key = key.view(bsz, -1, self.num_heads, self.head_dim).transpose(1, 2)
|
| 242 |
+
value = value.view(bsz, -1, self.num_heads, self.head_dim).transpose(1, 2)
|
| 243 |
+
else:
|
| 244 |
+
query, key, value = self.c_attn(current_states).split(self.split_size, dim=2)
|
| 245 |
+
key = key.view(bsz, -1, self.num_heads, self.head_dim).transpose(1, 2)
|
| 246 |
+
value = value.view(bsz, -1, self.num_heads, self.head_dim).transpose(1, 2)
|
| 247 |
+
|
| 248 |
+
if layer_past is not None:
|
| 249 |
+
# save all key/value_states to cache to be re-used for fast auto-regressive generation
|
| 250 |
+
key, value = curr_past_key_values.update(key, value, self.layer_idx)
|
| 251 |
+
# set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
|
| 252 |
+
if is_cross_attention:
|
| 253 |
+
layer_past.is_updated[self.layer_idx] = True
|
| 254 |
+
|
| 255 |
+
query = query.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 256 |
+
|
| 257 |
+
if self.reorder_and_upcast_attn:
|
| 258 |
+
attn_output, attn_weights = self._upcast_and_reordered_attn(query, key, value, attention_mask)
|
| 259 |
+
else:
|
| 260 |
+
attn_output, attn_weights = self._attn(query, key, value, attention_mask)
|
| 261 |
+
|
| 262 |
+
attn_output = self._merge_heads(attn_output, self.num_heads, self.head_dim)
|
| 263 |
+
attn_output = self.c_proj(attn_output)
|
| 264 |
+
attn_output = self.resid_dropout(attn_output)
|
| 265 |
+
|
| 266 |
+
return attn_output, attn_weights
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
class ImageGPTMLP(nn.Module):
|
| 270 |
+
def __init__(self, intermediate_size, config):
|
| 271 |
+
super().__init__()
|
| 272 |
+
embed_dim = config.hidden_size
|
| 273 |
+
self.c_fc = Conv1D(intermediate_size, embed_dim)
|
| 274 |
+
self.c_proj = Conv1D(embed_dim, intermediate_size)
|
| 275 |
+
self.act = ACT2FN[config.activation_function]
|
| 276 |
+
self.dropout = nn.Dropout(config.resid_pdrop)
|
| 277 |
+
|
| 278 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 279 |
+
hidden_states = self.c_fc(hidden_states)
|
| 280 |
+
hidden_states = self.act(hidden_states)
|
| 281 |
+
hidden_states = self.c_proj(hidden_states)
|
| 282 |
+
hidden_states = self.dropout(hidden_states)
|
| 283 |
+
return hidden_states
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
class ImageGPTBlock(GradientCheckpointingLayer):
|
| 287 |
+
def __init__(self, config, layer_idx=None):
|
| 288 |
+
super().__init__()
|
| 289 |
+
hidden_size = config.hidden_size
|
| 290 |
+
inner_dim = config.n_inner if config.n_inner is not None else 4 * hidden_size
|
| 291 |
+
|
| 292 |
+
self.ln_1 = ImageGPTLayerNorm(hidden_size, eps=config.layer_norm_epsilon)
|
| 293 |
+
self.attn = ImageGPTAttention(config, layer_idx=layer_idx)
|
| 294 |
+
self.ln_2 = ImageGPTLayerNorm(hidden_size, eps=config.layer_norm_epsilon)
|
| 295 |
+
|
| 296 |
+
if config.add_cross_attention:
|
| 297 |
+
self.crossattention = ImageGPTAttention(config, is_cross_attention=True, layer_idx=layer_idx)
|
| 298 |
+
self.ln_cross_attn = ImageGPTLayerNorm(hidden_size, eps=config.layer_norm_epsilon)
|
| 299 |
+
|
| 300 |
+
self.mlp = ImageGPTMLP(inner_dim, config)
|
| 301 |
+
|
| 302 |
+
def forward(
|
| 303 |
+
self,
|
| 304 |
+
hidden_states: torch.Tensor,
|
| 305 |
+
layer_past: Cache | None = None,
|
| 306 |
+
attention_mask: torch.Tensor | None = None,
|
| 307 |
+
encoder_hidden_states: torch.Tensor | None = None,
|
| 308 |
+
encoder_attention_mask: torch.Tensor | None = None,
|
| 309 |
+
use_cache: bool | None = False,
|
| 310 |
+
output_attentions: bool | None = False,
|
| 311 |
+
**kwargs,
|
| 312 |
+
) -> tuple:
|
| 313 |
+
residual = hidden_states
|
| 314 |
+
hidden_states = self.ln_1(hidden_states)
|
| 315 |
+
attn_outputs = self.attn(
|
| 316 |
+
hidden_states,
|
| 317 |
+
layer_past=layer_past,
|
| 318 |
+
attention_mask=attention_mask,
|
| 319 |
+
use_cache=use_cache,
|
| 320 |
+
output_attentions=output_attentions,
|
| 321 |
+
)
|
| 322 |
+
attn_output = attn_outputs[0]
|
| 323 |
+
outputs = attn_outputs[1:]
|
| 324 |
+
# residual connection
|
| 325 |
+
hidden_states = attn_output + residual
|
| 326 |
+
|
| 327 |
+
if encoder_hidden_states is not None:
|
| 328 |
+
# add one self-attention block for cross-attention
|
| 329 |
+
if not hasattr(self, "crossattention"):
|
| 330 |
+
raise ValueError(
|
| 331 |
+
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with "
|
| 332 |
+
"cross-attention layers by setting `config.add_cross_attention=True`"
|
| 333 |
+
)
|
| 334 |
+
residual = hidden_states
|
| 335 |
+
hidden_states = self.ln_cross_attn(hidden_states)
|
| 336 |
+
cross_attn_outputs = self.crossattention(
|
| 337 |
+
hidden_states,
|
| 338 |
+
layer_past=layer_past,
|
| 339 |
+
attention_mask=attention_mask,
|
| 340 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 341 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 342 |
+
output_attentions=output_attentions,
|
| 343 |
+
)
|
| 344 |
+
attn_output = cross_attn_outputs[0]
|
| 345 |
+
# residual connection
|
| 346 |
+
hidden_states = residual + attn_output
|
| 347 |
+
outputs = outputs + cross_attn_outputs[1:] # add cross attentions if we output attention weights
|
| 348 |
+
|
| 349 |
+
residual = hidden_states
|
| 350 |
+
hidden_states = self.ln_2(hidden_states)
|
| 351 |
+
feed_forward_hidden_states = self.mlp(hidden_states)
|
| 352 |
+
# residual connection
|
| 353 |
+
hidden_states = residual + feed_forward_hidden_states
|
| 354 |
+
|
| 355 |
+
return (hidden_states,) + outputs
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
@auto_docstring
|
| 359 |
+
class ImageGPTPreTrainedModel(PreTrainedModel):
|
| 360 |
+
config: ImageGPTConfig
|
| 361 |
+
base_model_prefix = "transformer"
|
| 362 |
+
main_input_name = "input_ids"
|
| 363 |
+
input_modalities = ("image",)
|
| 364 |
+
supports_gradient_checkpointing = True
|
| 365 |
+
_no_split_modules = ["ImageGPTBlock"]
|
| 366 |
+
|
| 367 |
+
@torch.no_grad()
|
| 368 |
+
def _init_weights(self, module):
|
| 369 |
+
"""Initialize the weights."""
|
| 370 |
+
super()._init_weights(module)
|
| 371 |
+
|
| 372 |
+
# Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
|
| 373 |
+
# > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
|
| 374 |
+
# > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
|
| 375 |
+
# > -- GPT-2 :: https://openai.com/blog/better-language-models/
|
| 376 |
+
#
|
| 377 |
+
# Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
|
| 378 |
+
if isinstance(module, PreTrainedModel):
|
| 379 |
+
for name, p in module.named_parameters():
|
| 380 |
+
if "c_proj" in name and "weight" in name:
|
| 381 |
+
# Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
|
| 382 |
+
init.normal_(p, mean=0.0, std=self.config.initializer_range / math.sqrt(2 * self.config.n_layer))
|
| 383 |
+
elif isinstance(module, ImageGPTAttention):
|
| 384 |
+
max_positions = module.config.max_position_embeddings
|
| 385 |
+
init.copy_(
|
| 386 |
+
module.bias,
|
| 387 |
+
torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)).view(
|
| 388 |
+
1, 1, max_positions, max_positions
|
| 389 |
+
),
|
| 390 |
+
)
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
@auto_docstring
|
| 394 |
+
class ImageGPTModel(ImageGPTPreTrainedModel):
|
| 395 |
+
def __init__(self, config: ImageGPTConfig):
|
| 396 |
+
super().__init__(config)
|
| 397 |
+
|
| 398 |
+
self.embed_dim = config.hidden_size
|
| 399 |
+
|
| 400 |
+
self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
|
| 401 |
+
self.wpe = nn.Embedding(config.max_position_embeddings, self.embed_dim)
|
| 402 |
+
|
| 403 |
+
self.drop = nn.Dropout(config.embd_pdrop)
|
| 404 |
+
self.h = nn.ModuleList([ImageGPTBlock(config, layer_idx=i) for i in range(config.num_hidden_layers)])
|
| 405 |
+
self.ln_f = ImageGPTLayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
|
| 406 |
+
|
| 407 |
+
self.gradient_checkpointing = False
|
| 408 |
+
# Initialize weights and apply final processing
|
| 409 |
+
self.post_init()
|
| 410 |
+
|
| 411 |
+
def get_input_embeddings(self):
|
| 412 |
+
return self.wte
|
| 413 |
+
|
| 414 |
+
def set_input_embeddings(self, new_embeddings):
|
| 415 |
+
self.wte = new_embeddings
|
| 416 |
+
|
| 417 |
+
@auto_docstring
|
| 418 |
+
def forward(
|
| 419 |
+
self,
|
| 420 |
+
input_ids: torch.Tensor | None = None,
|
| 421 |
+
past_key_values: Cache | None = None,
|
| 422 |
+
attention_mask: torch.Tensor | None = None,
|
| 423 |
+
token_type_ids: torch.Tensor | None = None,
|
| 424 |
+
position_ids: torch.Tensor | None = None,
|
| 425 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 426 |
+
encoder_hidden_states: torch.Tensor | None = None,
|
| 427 |
+
encoder_attention_mask: torch.Tensor | None = None,
|
| 428 |
+
use_cache: bool | None = None,
|
| 429 |
+
output_attentions: bool | None = None,
|
| 430 |
+
output_hidden_states: bool | None = None,
|
| 431 |
+
return_dict: bool | None = None,
|
| 432 |
+
**kwargs: Any,
|
| 433 |
+
) -> tuple | BaseModelOutputWithPastAndCrossAttentions:
|
| 434 |
+
r"""
|
| 435 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
|
| 436 |
+
`input_ids_length` = `sequence_length` if `past_key_values` is `None` else
|
| 437 |
+
`past_key_values.get_seq_length()` (`sequence_length` of input past key value states). Indices of input
|
| 438 |
+
sequence tokens in the vocabulary.
|
| 439 |
+
|
| 440 |
+
If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
|
| 441 |
+
`input_ids`.
|
| 442 |
+
|
| 443 |
+
Indices can be obtained using [`AutoImageProcessor`]. See [`ImageGPTImageProcessor.__call__`] for details.
|
| 444 |
+
|
| 445 |
+
Examples:
|
| 446 |
+
|
| 447 |
+
```python
|
| 448 |
+
>>> from transformers import AutoImageProcessor, ImageGPTModel
|
| 449 |
+
>>> from PIL import Image
|
| 450 |
+
>>> import httpx
|
| 451 |
+
>>> from io import BytesIO
|
| 452 |
+
|
| 453 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 454 |
+
>>> with httpx.stream("GET", url) as response:
|
| 455 |
+
... image = Image.open(BytesIO(response.read()))
|
| 456 |
+
|
| 457 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("openai/imagegpt-small")
|
| 458 |
+
>>> model = ImageGPTModel.from_pretrained("openai/imagegpt-small")
|
| 459 |
+
|
| 460 |
+
>>> inputs = image_processor(images=image, return_tensors="pt")
|
| 461 |
+
>>> outputs = model(**inputs)
|
| 462 |
+
>>> last_hidden_states = outputs.last_hidden_state
|
| 463 |
+
```"""
|
| 464 |
+
|
| 465 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 466 |
+
output_hidden_states = (
|
| 467 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 468 |
+
)
|
| 469 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 470 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 471 |
+
|
| 472 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 473 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 474 |
+
elif input_ids is not None:
|
| 475 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 476 |
+
input_shape = input_ids.size()
|
| 477 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
| 478 |
+
batch_size = input_ids.shape[0]
|
| 479 |
+
elif inputs_embeds is not None:
|
| 480 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 481 |
+
batch_size = inputs_embeds.shape[0]
|
| 482 |
+
else:
|
| 483 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 484 |
+
|
| 485 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 486 |
+
|
| 487 |
+
if self.gradient_checkpointing and self.training:
|
| 488 |
+
if use_cache:
|
| 489 |
+
logger.warning_once(
|
| 490 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 491 |
+
)
|
| 492 |
+
use_cache = False
|
| 493 |
+
|
| 494 |
+
if token_type_ids is not None:
|
| 495 |
+
token_type_ids = token_type_ids.view(-1, input_shape[-1])
|
| 496 |
+
|
| 497 |
+
if use_cache and past_key_values is None:
|
| 498 |
+
past_key_values = DynamicCache(config=self.config)
|
| 499 |
+
|
| 500 |
+
if position_ids is None:
|
| 501 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 502 |
+
position_ids = torch.arange(input_shape[-1], device=device) + past_seen_tokens
|
| 503 |
+
position_ids = position_ids.unsqueeze(0)
|
| 504 |
+
|
| 505 |
+
if attention_mask is not None:
|
| 506 |
+
attention_mask = attention_mask.view(batch_size, -1)
|
| 507 |
+
|
| 508 |
+
if inputs_embeds is None:
|
| 509 |
+
inputs_embeds = self.wte(input_ids)
|
| 510 |
+
position_embeds = self.wpe(position_ids)
|
| 511 |
+
hidden_states = inputs_embeds + position_embeds.to(inputs_embeds.device)
|
| 512 |
+
|
| 513 |
+
if getattr(self.config, "is_decoder", False):
|
| 514 |
+
attention_mask = create_causal_mask(
|
| 515 |
+
config=self.config,
|
| 516 |
+
inputs_embeds=inputs_embeds,
|
| 517 |
+
attention_mask=attention_mask,
|
| 518 |
+
past_key_values=past_key_values,
|
| 519 |
+
)
|
| 520 |
+
else:
|
| 521 |
+
attention_mask = create_bidirectional_mask(
|
| 522 |
+
config=self.config,
|
| 523 |
+
inputs_embeds=inputs_embeds,
|
| 524 |
+
attention_mask=attention_mask,
|
| 525 |
+
)
|
| 526 |
+
|
| 527 |
+
if encoder_attention_mask is not None:
|
| 528 |
+
encoder_attention_mask = create_bidirectional_mask(
|
| 529 |
+
config=self.config,
|
| 530 |
+
inputs_embeds=inputs_embeds,
|
| 531 |
+
attention_mask=encoder_attention_mask,
|
| 532 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 533 |
+
)
|
| 534 |
+
|
| 535 |
+
if token_type_ids is not None:
|
| 536 |
+
token_type_embeds = self.wte(token_type_ids)
|
| 537 |
+
hidden_states = hidden_states + token_type_embeds
|
| 538 |
+
|
| 539 |
+
hidden_states = self.drop(hidden_states)
|
| 540 |
+
output_shape = input_shape + (hidden_states.size(-1),)
|
| 541 |
+
|
| 542 |
+
all_self_attentions = () if output_attentions else None
|
| 543 |
+
all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
|
| 544 |
+
all_hidden_states = () if output_hidden_states else None
|
| 545 |
+
for i, block in enumerate(self.h):
|
| 546 |
+
if output_hidden_states:
|
| 547 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 548 |
+
|
| 549 |
+
outputs = block(
|
| 550 |
+
hidden_states,
|
| 551 |
+
past_key_values,
|
| 552 |
+
attention_mask,
|
| 553 |
+
encoder_hidden_states, # as a positional argument for gradient checkpointing
|
| 554 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 555 |
+
use_cache=use_cache,
|
| 556 |
+
output_attentions=output_attentions,
|
| 557 |
+
)
|
| 558 |
+
|
| 559 |
+
hidden_states = outputs[0]
|
| 560 |
+
if output_attentions:
|
| 561 |
+
all_self_attentions = all_self_attentions + (outputs[1],)
|
| 562 |
+
if self.config.add_cross_attention:
|
| 563 |
+
all_cross_attentions = all_cross_attentions + (outputs[2],)
|
| 564 |
+
|
| 565 |
+
hidden_states = self.ln_f(hidden_states)
|
| 566 |
+
hidden_states = hidden_states.view(*output_shape)
|
| 567 |
+
|
| 568 |
+
# Add last hidden state
|
| 569 |
+
if output_hidden_states:
|
| 570 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 571 |
+
|
| 572 |
+
if not return_dict:
|
| 573 |
+
return tuple(
|
| 574 |
+
v
|
| 575 |
+
for v in [hidden_states, past_key_values, all_hidden_states, all_self_attentions, all_cross_attentions]
|
| 576 |
+
if v is not None
|
| 577 |
+
)
|
| 578 |
+
|
| 579 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 580 |
+
last_hidden_state=hidden_states,
|
| 581 |
+
past_key_values=past_key_values,
|
| 582 |
+
hidden_states=all_hidden_states,
|
| 583 |
+
attentions=all_self_attentions,
|
| 584 |
+
cross_attentions=all_cross_attentions,
|
| 585 |
+
)
|
| 586 |
+
|
| 587 |
+
|
| 588 |
+
@auto_docstring(
|
| 589 |
+
custom_intro="""
|
| 590 |
+
The ImageGPT Model transformer with a language modeling head on top (linear layer with weights tied to the input
|
| 591 |
+
embeddings).
|
| 592 |
+
"""
|
| 593 |
+
)
|
| 594 |
+
class ImageGPTForCausalImageModeling(ImageGPTPreTrainedModel, GenerationMixin):
|
| 595 |
+
_tied_weights_keys = {"lm_head.weight": "transformer.wte.weight"}
|
| 596 |
+
|
| 597 |
+
def __init__(self, config: ImageGPTConfig):
|
| 598 |
+
super().__init__(config)
|
| 599 |
+
self.transformer = ImageGPTModel(config)
|
| 600 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size - 1, bias=False)
|
| 601 |
+
|
| 602 |
+
# Initialize weights and apply final processing
|
| 603 |
+
self.post_init()
|
| 604 |
+
|
| 605 |
+
@auto_docstring
|
| 606 |
+
def forward(
|
| 607 |
+
self,
|
| 608 |
+
input_ids: torch.Tensor | None = None,
|
| 609 |
+
past_key_values: Cache | None = None,
|
| 610 |
+
attention_mask: torch.Tensor | None = None,
|
| 611 |
+
token_type_ids: torch.Tensor | None = None,
|
| 612 |
+
position_ids: torch.Tensor | None = None,
|
| 613 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 614 |
+
encoder_hidden_states: torch.Tensor | None = None,
|
| 615 |
+
encoder_attention_mask: torch.Tensor | None = None,
|
| 616 |
+
labels: torch.Tensor | None = None,
|
| 617 |
+
use_cache: bool | None = None,
|
| 618 |
+
output_attentions: bool | None = None,
|
| 619 |
+
output_hidden_states: bool | None = None,
|
| 620 |
+
return_dict: bool | None = None,
|
| 621 |
+
**kwargs: Any,
|
| 622 |
+
) -> tuple | CausalLMOutputWithCrossAttentions:
|
| 623 |
+
r"""
|
| 624 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
|
| 625 |
+
`input_ids_length` = `sequence_length` if `past_key_values` is `None` else
|
| 626 |
+
`past_key_values.get_seq_length()` (`sequence_length` of input past key value states). Indices of input
|
| 627 |
+
sequence tokens in the vocabulary.
|
| 628 |
+
|
| 629 |
+
If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
|
| 630 |
+
`input_ids`.
|
| 631 |
+
|
| 632 |
+
Indices can be obtained using [`AutoImageProcessor`]. See [`ImageGPTImageProcessor.__call__`] for details.
|
| 633 |
+
labels (`torch.LongTensor` of shape `(batch_size, input_ids_length)`, *optional*):
|
| 634 |
+
Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
|
| 635 |
+
`labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
|
| 636 |
+
are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
|
| 637 |
+
|
| 638 |
+
Examples:
|
| 639 |
+
|
| 640 |
+
```python
|
| 641 |
+
>>> from transformers import AutoImageProcessor, ImageGPTForCausalImageModeling
|
| 642 |
+
>>> import torch
|
| 643 |
+
>>> import matplotlib.pyplot as plt
|
| 644 |
+
>>> import numpy as np
|
| 645 |
+
|
| 646 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("openai/imagegpt-small")
|
| 647 |
+
>>> model = ImageGPTForCausalImageModeling.from_pretrained("openai/imagegpt-small")
|
| 648 |
+
>>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 649 |
+
>>> model.to(device) # doctest: +IGNORE_RESULT
|
| 650 |
+
|
| 651 |
+
>>> # unconditional generation of 8 images
|
| 652 |
+
>>> batch_size = 4
|
| 653 |
+
>>> context = torch.full((batch_size, 1), model.config.vocab_size - 1) # initialize with SOS token
|
| 654 |
+
>>> context = context.to(device)
|
| 655 |
+
>>> output = model.generate(
|
| 656 |
+
... input_ids=context, max_length=model.config.n_positions + 1, temperature=1.0, do_sample=True, top_k=40
|
| 657 |
+
... )
|
| 658 |
+
|
| 659 |
+
>>> clusters = image_processor.clusters
|
| 660 |
+
>>> height = image_processor.size["height"]
|
| 661 |
+
>>> width = image_processor.size["width"]
|
| 662 |
+
|
| 663 |
+
>>> samples = output[:, 1:].detach().cpu().numpy()
|
| 664 |
+
>>> samples_img = [
|
| 665 |
+
... np.reshape(np.rint(127.5 * (clusters[s] + 1.0)), [height, width, 3]).astype(np.uint8) for s in samples
|
| 666 |
+
... ] # convert color cluster tokens back to pixels
|
| 667 |
+
>>> f, axes = plt.subplots(1, batch_size, dpi=300)
|
| 668 |
+
|
| 669 |
+
>>> for img, ax in zip(samples_img, axes): # doctest: +IGNORE_RESULT
|
| 670 |
+
... ax.axis("off")
|
| 671 |
+
... ax.imshow(img)
|
| 672 |
+
```"""
|
| 673 |
+
|
| 674 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 675 |
+
|
| 676 |
+
transformer_outputs = self.transformer(
|
| 677 |
+
input_ids,
|
| 678 |
+
past_key_values=past_key_values,
|
| 679 |
+
attention_mask=attention_mask,
|
| 680 |
+
token_type_ids=token_type_ids,
|
| 681 |
+
position_ids=position_ids,
|
| 682 |
+
inputs_embeds=inputs_embeds,
|
| 683 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 684 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 685 |
+
use_cache=use_cache,
|
| 686 |
+
output_attentions=output_attentions,
|
| 687 |
+
output_hidden_states=output_hidden_states,
|
| 688 |
+
return_dict=return_dict,
|
| 689 |
+
)
|
| 690 |
+
hidden_states = transformer_outputs[0]
|
| 691 |
+
|
| 692 |
+
lm_logits = self.lm_head(hidden_states)
|
| 693 |
+
|
| 694 |
+
loss = None
|
| 695 |
+
if labels is not None:
|
| 696 |
+
# Shift so that tokens < n predict n
|
| 697 |
+
shift_logits = lm_logits[..., :-1, :].contiguous()
|
| 698 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 699 |
+
# Flatten the tokens
|
| 700 |
+
loss_fct = CrossEntropyLoss()
|
| 701 |
+
loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
|
| 702 |
+
|
| 703 |
+
if not return_dict:
|
| 704 |
+
output = (lm_logits,) + transformer_outputs[1:]
|
| 705 |
+
return ((loss,) + output) if loss is not None else output
|
| 706 |
+
|
| 707 |
+
return CausalLMOutputWithCrossAttentions(
|
| 708 |
+
loss=loss,
|
| 709 |
+
logits=lm_logits,
|
| 710 |
+
past_key_values=transformer_outputs.past_key_values,
|
| 711 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 712 |
+
attentions=transformer_outputs.attentions,
|
| 713 |
+
cross_attentions=transformer_outputs.cross_attentions,
|
| 714 |
+
)
|
| 715 |
+
|
| 716 |
+
|
| 717 |
+
@auto_docstring(
|
| 718 |
+
custom_intro="""
|
| 719 |
+
The ImageGPT Model transformer with an image classification head on top (linear layer).
|
| 720 |
+
[`ImageGPTForImageClassification`] average-pools the hidden states in order to do the classification.
|
| 721 |
+
"""
|
| 722 |
+
)
|
| 723 |
+
class ImageGPTForImageClassification(ImageGPTPreTrainedModel):
|
| 724 |
+
def __init__(self, config: ImageGPTConfig):
|
| 725 |
+
super().__init__(config)
|
| 726 |
+
self.num_labels = config.num_labels
|
| 727 |
+
self.transformer = ImageGPTModel(config)
|
| 728 |
+
self.score = nn.Linear(config.n_embd, self.num_labels, bias=False)
|
| 729 |
+
|
| 730 |
+
# Initialize weights and apply final processing
|
| 731 |
+
self.post_init()
|
| 732 |
+
|
| 733 |
+
@auto_docstring
|
| 734 |
+
def forward(
|
| 735 |
+
self,
|
| 736 |
+
input_ids: torch.Tensor | None = None,
|
| 737 |
+
past_key_values: Cache | None = None,
|
| 738 |
+
attention_mask: torch.Tensor | None = None,
|
| 739 |
+
token_type_ids: torch.Tensor | None = None,
|
| 740 |
+
position_ids: torch.Tensor | None = None,
|
| 741 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 742 |
+
labels: torch.Tensor | None = None,
|
| 743 |
+
use_cache: bool | None = None,
|
| 744 |
+
output_attentions: bool | None = None,
|
| 745 |
+
output_hidden_states: bool | None = None,
|
| 746 |
+
return_dict: bool | None = None,
|
| 747 |
+
**kwargs: Any,
|
| 748 |
+
) -> tuple | SequenceClassifierOutputWithPast:
|
| 749 |
+
r"""
|
| 750 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
|
| 751 |
+
`input_ids_length` = `sequence_length` if `past_key_values` is `None` else
|
| 752 |
+
`past_key_values.get_seq_length()` (`sequence_length` of input past key value states). Indices of input
|
| 753 |
+
sequence tokens in the vocabulary.
|
| 754 |
+
|
| 755 |
+
If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
|
| 756 |
+
`input_ids`.
|
| 757 |
+
|
| 758 |
+
Indices can be obtained using [`AutoImageProcessor`]. See [`ImageGPTImageProcessor.__call__`] for details.
|
| 759 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 760 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 761 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 762 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 763 |
+
|
| 764 |
+
Examples:
|
| 765 |
+
|
| 766 |
+
```python
|
| 767 |
+
>>> from transformers import AutoImageProcessor, ImageGPTForImageClassification
|
| 768 |
+
>>> from PIL import Image
|
| 769 |
+
>>> import httpx
|
| 770 |
+
>>> from io import BytesIO
|
| 771 |
+
|
| 772 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 773 |
+
>>> with httpx.stream("GET", url) as response:
|
| 774 |
+
... image = Image.open(BytesIO(response.read()))
|
| 775 |
+
|
| 776 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("openai/imagegpt-small")
|
| 777 |
+
>>> model = ImageGPTForImageClassification.from_pretrained("openai/imagegpt-small")
|
| 778 |
+
|
| 779 |
+
>>> inputs = image_processor(images=image, return_tensors="pt")
|
| 780 |
+
>>> outputs = model(**inputs)
|
| 781 |
+
>>> logits = outputs.logits
|
| 782 |
+
```"""
|
| 783 |
+
|
| 784 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 785 |
+
|
| 786 |
+
transformer_outputs = self.transformer(
|
| 787 |
+
input_ids,
|
| 788 |
+
past_key_values=past_key_values,
|
| 789 |
+
attention_mask=attention_mask,
|
| 790 |
+
token_type_ids=token_type_ids,
|
| 791 |
+
position_ids=position_ids,
|
| 792 |
+
inputs_embeds=inputs_embeds,
|
| 793 |
+
use_cache=use_cache,
|
| 794 |
+
output_attentions=output_attentions,
|
| 795 |
+
output_hidden_states=output_hidden_states,
|
| 796 |
+
return_dict=return_dict,
|
| 797 |
+
)
|
| 798 |
+
hidden_states = transformer_outputs[0]
|
| 799 |
+
# average-pool the hidden states along the sequence dimension
|
| 800 |
+
pooled_hidden_states = hidden_states.mean(dim=1)
|
| 801 |
+
# project from (batch_size, hidden_size) to (batch_size, num_labels)
|
| 802 |
+
logits = self.score(pooled_hidden_states)
|
| 803 |
+
|
| 804 |
+
loss = None
|
| 805 |
+
if labels is not None:
|
| 806 |
+
loss = self.loss_function(labels, logits, self.config)
|
| 807 |
+
|
| 808 |
+
if not return_dict:
|
| 809 |
+
output = (logits,) + transformer_outputs[1:]
|
| 810 |
+
return ((loss,) + output) if loss is not None else output
|
| 811 |
+
|
| 812 |
+
return SequenceClassifierOutputWithPast(
|
| 813 |
+
loss=loss,
|
| 814 |
+
logits=logits,
|
| 815 |
+
past_key_values=transformer_outputs.past_key_values,
|
| 816 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 817 |
+
attentions=transformer_outputs.attentions,
|
| 818 |
+
)
|
| 819 |
+
|
| 820 |
+
|
| 821 |
+
__all__ = [
|
| 822 |
+
"ImageGPTForCausalImageModeling",
|
| 823 |
+
"ImageGPTForImageClassification",
|
| 824 |
+
"ImageGPTModel",
|
| 825 |
+
"ImageGPTPreTrainedModel",
|
| 826 |
+
]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/trocr/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_trocr import *
|
| 22 |
+
from .modeling_trocr import *
|
| 23 |
+
from .processing_trocr 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/trocr/configuration_trocr.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 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 |
+
"""TrOCR 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="microsoft/trocr-base-handwritten")
|
| 23 |
+
@strict
|
| 24 |
+
class TrOCRConfig(PreTrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
use_learned_position_embeddings (`bool`, *optional*, defaults to `True`):
|
| 27 |
+
Whether or not to use learned position embeddings. If not, sinusoidal position embeddings will be used.
|
| 28 |
+
layernorm_embedding (`bool`, *optional*, defaults to `True`):
|
| 29 |
+
Whether or not to use a layernorm after the word + position embeddings.
|
| 30 |
+
|
| 31 |
+
Example:
|
| 32 |
+
|
| 33 |
+
```python
|
| 34 |
+
>>> from transformers import TrOCRConfig, TrOCRForCausalLM
|
| 35 |
+
|
| 36 |
+
>>> # Initializing a TrOCR-base style configuration
|
| 37 |
+
>>> configuration = TrOCRConfig()
|
| 38 |
+
|
| 39 |
+
>>> # Initializing a model (with random weights) from the TrOCR-base style configuration
|
| 40 |
+
>>> model = TrOCRForCausalLM(configuration)
|
| 41 |
+
|
| 42 |
+
>>> # Accessing the model configuration
|
| 43 |
+
>>> configuration = model.config
|
| 44 |
+
```"""
|
| 45 |
+
|
| 46 |
+
model_type = "trocr"
|
| 47 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 48 |
+
attribute_map = {
|
| 49 |
+
"num_attention_heads": "decoder_attention_heads",
|
| 50 |
+
"hidden_size": "d_model",
|
| 51 |
+
"num_hidden_layers": "decoder_layers",
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
vocab_size: int = 50265
|
| 55 |
+
d_model: int = 1024
|
| 56 |
+
decoder_layers: int = 12
|
| 57 |
+
decoder_attention_heads: int = 16
|
| 58 |
+
decoder_ffn_dim: int = 4096
|
| 59 |
+
activation_function: str = "gelu"
|
| 60 |
+
max_position_embeddings: int = 512
|
| 61 |
+
dropout: float | int = 0.1
|
| 62 |
+
attention_dropout: float | int = 0.0
|
| 63 |
+
activation_dropout: float | int = 0.0
|
| 64 |
+
decoder_start_token_id: int = 2
|
| 65 |
+
init_std: float = 0.02
|
| 66 |
+
decoder_layerdrop: float | int = 0.0
|
| 67 |
+
use_cache: bool = True
|
| 68 |
+
scale_embedding: bool = False
|
| 69 |
+
use_learned_position_embeddings: bool = True
|
| 70 |
+
layernorm_embedding: bool = True
|
| 71 |
+
pad_token_id: int | None = 1
|
| 72 |
+
bos_token_id: int | None = 0
|
| 73 |
+
eos_token_id: int | list[int] | None = 2
|
| 74 |
+
cross_attention_hidden_size: int | None = None
|
| 75 |
+
is_decoder: bool = False
|
| 76 |
+
tie_word_embeddings: bool = True
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
__all__ = ["TrOCRConfig"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qw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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 TrOCR decoder model (based on RoBERTa)."""
|
| 15 |
+
|
| 16 |
+
import math
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
from torch import nn
|
| 20 |
+
from torch.nn import CrossEntropyLoss
|
| 21 |
+
|
| 22 |
+
from ...activations import ACT2FN
|
| 23 |
+
from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
|
| 24 |
+
from ...generation import GenerationMixin
|
| 25 |
+
from ...masking_utils import create_bidirectional_mask, create_causal_mask
|
| 26 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 27 |
+
from ...modeling_outputs import BaseModelOutputWithPastAndCrossAttentions, CausalLMOutputWithCrossAttentions
|
| 28 |
+
from ...modeling_utils import PreTrainedModel
|
| 29 |
+
from ...utils import auto_docstring, logging
|
| 30 |
+
from .configuration_trocr import TrOCRConfig
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
logger = logging.get_logger(__name__)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# Copied from transformers.models.bart.modeling_bart.BartLearnedPositionalEmbedding with Bart->TrOCR
|
| 37 |
+
class TrOCRLearnedPositionalEmbedding(nn.Embedding):
|
| 38 |
+
"""
|
| 39 |
+
This module learns positional embeddings up to a fixed maximum size.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
def __init__(self, num_embeddings: int, embedding_dim: int):
|
| 43 |
+
# TrOCR is set up so that if padding_idx is specified then offset the embedding ids by 2
|
| 44 |
+
# and adjust num_embeddings appropriately. Other models don't have this hack
|
| 45 |
+
self.offset = 2
|
| 46 |
+
super().__init__(num_embeddings + self.offset, embedding_dim)
|
| 47 |
+
|
| 48 |
+
def forward(
|
| 49 |
+
self, input_ids: torch.Tensor, past_key_values_length: int = 0, position_ids: torch.Tensor | None = None
|
| 50 |
+
):
|
| 51 |
+
"""`input_ids' shape is expected to be [bsz x seqlen]."""
|
| 52 |
+
|
| 53 |
+
if position_ids is None:
|
| 54 |
+
bsz, seq_len = input_ids.shape[:2]
|
| 55 |
+
position_ids = torch.arange(
|
| 56 |
+
past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device
|
| 57 |
+
).expand(bsz, -1)
|
| 58 |
+
else:
|
| 59 |
+
position_ids = position_ids.unsqueeze(0)
|
| 60 |
+
|
| 61 |
+
return super().forward(position_ids + self.offset)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# Copied from transformers.models.bart.modeling_bart.BartScaledWordEmbedding with Bart->TrOCR
|
| 65 |
+
class TrOCRScaledWordEmbedding(nn.Embedding):
|
| 66 |
+
"""
|
| 67 |
+
This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: float | None = 1.0):
|
| 71 |
+
super().__init__(num_embeddings, embedding_dim, padding_idx)
|
| 72 |
+
self.embed_scale = embed_scale
|
| 73 |
+
|
| 74 |
+
def forward(self, input_ids: torch.Tensor):
|
| 75 |
+
return super().forward(input_ids) * self.embed_scale
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class TrOCRSinusoidalPositionalEmbedding(nn.Module):
|
| 79 |
+
"""This module produces sinusoidal positional embeddings of any length."""
|
| 80 |
+
|
| 81 |
+
def __init__(self, num_positions: int, embedding_dim: int, padding_idx: int | None = None):
|
| 82 |
+
super().__init__()
|
| 83 |
+
self.offset = 2
|
| 84 |
+
self.embedding_dim = embedding_dim
|
| 85 |
+
self.padding_idx = padding_idx
|
| 86 |
+
self.weights = self.get_embedding(num_positions, embedding_dim, padding_idx)
|
| 87 |
+
|
| 88 |
+
@staticmethod
|
| 89 |
+
def get_embedding(num_embeddings: int, embedding_dim: int, padding_idx: int | None = None):
|
| 90 |
+
"""
|
| 91 |
+
Build sinusoidal embeddings. This matches the implementation in tensor2tensor, but differs slightly from the
|
| 92 |
+
description in Section 3.5 of "Attention Is All You Need".
|
| 93 |
+
"""
|
| 94 |
+
half_dim = embedding_dim // 2
|
| 95 |
+
emb = math.log(10000) / (half_dim - 1)
|
| 96 |
+
emb = torch.exp(torch.arange(half_dim, dtype=torch.int64).float() * -emb)
|
| 97 |
+
emb = torch.arange(num_embeddings, dtype=torch.int64).float().unsqueeze(1) * emb.unsqueeze(0)
|
| 98 |
+
emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1)
|
| 99 |
+
if embedding_dim % 2 == 1:
|
| 100 |
+
# zero pad
|
| 101 |
+
emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1)
|
| 102 |
+
if padding_idx is not None:
|
| 103 |
+
emb[padding_idx, :] = 0
|
| 104 |
+
|
| 105 |
+
return emb.to(torch.get_default_dtype())
|
| 106 |
+
|
| 107 |
+
@torch.no_grad()
|
| 108 |
+
def forward(self, input_ids: torch.Tensor, past_key_values_length: int = 0):
|
| 109 |
+
bsz, seq_len = input_ids.size()
|
| 110 |
+
# Create the position ids from the input token ids. Any padded tokens remain padded.
|
| 111 |
+
position_ids = self.create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length).to(
|
| 112 |
+
input_ids.device
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
# expand embeddings if needed
|
| 116 |
+
max_pos = self.padding_idx + 1 + seq_len
|
| 117 |
+
if self.weights is None or max_pos > self.weights.size(0):
|
| 118 |
+
# recompute/expand embeddings if needed
|
| 119 |
+
self.weights = self.get_embedding(max_pos, self.embedding_dim, self.padding_idx)
|
| 120 |
+
|
| 121 |
+
x = self.weights.index_select(0, position_ids.view(-1)).view(bsz, seq_len, -1).detach()
|
| 122 |
+
|
| 123 |
+
return x
|
| 124 |
+
|
| 125 |
+
def create_position_ids_from_input_ids(
|
| 126 |
+
self, input_ids: torch.Tensor, padding_idx: int, past_key_values_length: int | None = 0
|
| 127 |
+
):
|
| 128 |
+
"""
|
| 129 |
+
Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding
|
| 130 |
+
symbols are ignored. This is modified from fairseq's `utils.make_positions`.
|
| 131 |
+
"""
|
| 132 |
+
# The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
|
| 133 |
+
mask = input_ids.ne(padding_idx).int()
|
| 134 |
+
incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
|
| 135 |
+
return incremental_indices.long() + padding_idx
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class TrOCRAttention(nn.Module):
|
| 139 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper."""
|
| 140 |
+
|
| 141 |
+
def __init__(
|
| 142 |
+
self,
|
| 143 |
+
config,
|
| 144 |
+
embed_dim: int,
|
| 145 |
+
num_heads: int,
|
| 146 |
+
kdim: int | None = None,
|
| 147 |
+
vdim: int | None = None,
|
| 148 |
+
dropout: float | None = 0.0,
|
| 149 |
+
is_decoder: bool | None = False,
|
| 150 |
+
bias: bool | None = True,
|
| 151 |
+
is_cross_attention: bool | None = False,
|
| 152 |
+
layer_idx: bool | None = None,
|
| 153 |
+
):
|
| 154 |
+
super().__init__()
|
| 155 |
+
self.embed_dim = embed_dim
|
| 156 |
+
self.kdim = kdim if kdim is not None else embed_dim
|
| 157 |
+
self.vdim = vdim if vdim is not None else embed_dim
|
| 158 |
+
self.num_heads = num_heads
|
| 159 |
+
self.dropout = dropout
|
| 160 |
+
self.head_dim = embed_dim // num_heads
|
| 161 |
+
if not (self.head_dim * num_heads == self.embed_dim):
|
| 162 |
+
raise ValueError(
|
| 163 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
|
| 164 |
+
f" {num_heads})."
|
| 165 |
+
)
|
| 166 |
+
self.scaling = self.head_dim**-0.5
|
| 167 |
+
self.is_decoder = is_decoder
|
| 168 |
+
self.layer_idx = layer_idx
|
| 169 |
+
|
| 170 |
+
self.k_proj = nn.Linear(self.kdim, embed_dim, bias=bias)
|
| 171 |
+
self.v_proj = nn.Linear(self.vdim, embed_dim, bias=bias)
|
| 172 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 173 |
+
|
| 174 |
+
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 175 |
+
|
| 176 |
+
def forward(
|
| 177 |
+
self,
|
| 178 |
+
hidden_states: torch.Tensor,
|
| 179 |
+
key_value_states: torch.Tensor | None = None,
|
| 180 |
+
past_key_values: Cache | None = None,
|
| 181 |
+
attention_mask: torch.Tensor | None = None,
|
| 182 |
+
output_attentions: bool | None = False,
|
| 183 |
+
**kwargs,
|
| 184 |
+
) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
|
| 185 |
+
"""Input shape: Batch x Time x Channel"""
|
| 186 |
+
|
| 187 |
+
# if key_value_states are provided this layer is used as a cross-attention layer
|
| 188 |
+
# for the decoder
|
| 189 |
+
is_cross_attention = key_value_states is not None
|
| 190 |
+
bsz, tgt_len, embed_dim = hidden_states.size()
|
| 191 |
+
|
| 192 |
+
# get query proj
|
| 193 |
+
query_states = self.q_proj(hidden_states) * self.scaling
|
| 194 |
+
|
| 195 |
+
is_updated = False
|
| 196 |
+
if past_key_values is not None:
|
| 197 |
+
if isinstance(past_key_values, EncoderDecoderCache):
|
| 198 |
+
is_updated = past_key_values.is_updated.get(self.layer_idx)
|
| 199 |
+
if is_cross_attention:
|
| 200 |
+
# after the first generated id, we can subsequently re-use all key/value_states from cache
|
| 201 |
+
curr_past_key_values = past_key_values.cross_attention_cache
|
| 202 |
+
else:
|
| 203 |
+
curr_past_key_values = past_key_values.self_attention_cache
|
| 204 |
+
else:
|
| 205 |
+
curr_past_key_values = past_key_values
|
| 206 |
+
|
| 207 |
+
current_states = key_value_states if is_cross_attention else hidden_states
|
| 208 |
+
if is_cross_attention and past_key_values is not None and is_updated:
|
| 209 |
+
# reuse k,v, cross_attentions
|
| 210 |
+
key_states = curr_past_key_values.layers[self.layer_idx].keys
|
| 211 |
+
value_states = curr_past_key_values.layers[self.layer_idx].values
|
| 212 |
+
else:
|
| 213 |
+
key_states = self.k_proj(current_states)
|
| 214 |
+
value_states = self.v_proj(current_states)
|
| 215 |
+
key_states = key_states.view(bsz, -1, self.num_heads, self.head_dim).transpose(1, 2)
|
| 216 |
+
value_states = value_states.view(bsz, -1, self.num_heads, self.head_dim).transpose(1, 2)
|
| 217 |
+
|
| 218 |
+
if past_key_values is not None:
|
| 219 |
+
# save all key/value_states to cache to be re-used for fast auto-regressive generation
|
| 220 |
+
key_states, value_states = curr_past_key_values.update(key_states, value_states, self.layer_idx)
|
| 221 |
+
# set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
|
| 222 |
+
if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
|
| 223 |
+
past_key_values.is_updated[self.layer_idx] = True
|
| 224 |
+
|
| 225 |
+
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
|
| 226 |
+
query_states = query_states.view(bsz, tgt_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 227 |
+
query_states = query_states.reshape(*proj_shape)
|
| 228 |
+
key_states = key_states.reshape(*proj_shape)
|
| 229 |
+
value_states = value_states.reshape(*proj_shape)
|
| 230 |
+
|
| 231 |
+
src_len = key_states.size(1)
|
| 232 |
+
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
|
| 233 |
+
|
| 234 |
+
if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
|
| 235 |
+
raise ValueError(
|
| 236 |
+
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
|
| 237 |
+
f" {attn_weights.size()}"
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
if attention_mask is not None:
|
| 241 |
+
if attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
| 242 |
+
raise ValueError(
|
| 243 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
|
| 244 |
+
)
|
| 245 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
|
| 246 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 247 |
+
|
| 248 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 249 |
+
|
| 250 |
+
if output_attentions:
|
| 251 |
+
# this operation is a bit awkward, but it's required to
|
| 252 |
+
# make sure that attn_weights keeps its gradient.
|
| 253 |
+
# In order to do so, attn_weights have to be reshaped
|
| 254 |
+
# twice and have to be reused in the following
|
| 255 |
+
attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 256 |
+
attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
|
| 257 |
+
else:
|
| 258 |
+
attn_weights_reshaped = None
|
| 259 |
+
|
| 260 |
+
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
| 261 |
+
|
| 262 |
+
attn_output = torch.bmm(attn_probs, value_states)
|
| 263 |
+
|
| 264 |
+
if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
|
| 265 |
+
raise ValueError(
|
| 266 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
|
| 267 |
+
f" {attn_output.size()}"
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
|
| 271 |
+
attn_output = attn_output.transpose(1, 2)
|
| 272 |
+
attn_output = attn_output.reshape(bsz, tgt_len, embed_dim)
|
| 273 |
+
|
| 274 |
+
attn_output = self.out_proj(attn_output)
|
| 275 |
+
|
| 276 |
+
return attn_output, attn_weights_reshaped
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
class TrOCRDecoderLayer(GradientCheckpointingLayer):
|
| 280 |
+
def __init__(self, config: TrOCRConfig, layer_idx=None):
|
| 281 |
+
super().__init__()
|
| 282 |
+
self.embed_dim = config.hidden_size
|
| 283 |
+
|
| 284 |
+
self.self_attn = TrOCRAttention(
|
| 285 |
+
config,
|
| 286 |
+
embed_dim=self.embed_dim,
|
| 287 |
+
num_heads=config.decoder_attention_heads,
|
| 288 |
+
dropout=config.attention_dropout,
|
| 289 |
+
is_decoder=True,
|
| 290 |
+
layer_idx=layer_idx,
|
| 291 |
+
)
|
| 292 |
+
self.dropout = config.dropout
|
| 293 |
+
self.activation_fn = ACT2FN[config.activation_function]
|
| 294 |
+
self.activation_dropout = config.activation_dropout
|
| 295 |
+
|
| 296 |
+
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 297 |
+
|
| 298 |
+
if config.is_decoder:
|
| 299 |
+
self.encoder_attn = TrOCRAttention(
|
| 300 |
+
config,
|
| 301 |
+
embed_dim=self.embed_dim,
|
| 302 |
+
num_heads=config.decoder_attention_heads,
|
| 303 |
+
kdim=config.cross_attention_hidden_size,
|
| 304 |
+
vdim=config.cross_attention_hidden_size,
|
| 305 |
+
dropout=config.attention_dropout,
|
| 306 |
+
is_decoder=True,
|
| 307 |
+
is_cross_attention=True,
|
| 308 |
+
layer_idx=layer_idx,
|
| 309 |
+
)
|
| 310 |
+
self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 311 |
+
|
| 312 |
+
self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
|
| 313 |
+
self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
|
| 314 |
+
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 315 |
+
|
| 316 |
+
def forward(
|
| 317 |
+
self,
|
| 318 |
+
hidden_states: torch.Tensor,
|
| 319 |
+
attention_mask: torch.Tensor | None = None,
|
| 320 |
+
encoder_hidden_states: torch.Tensor | None = None,
|
| 321 |
+
encoder_attention_mask: torch.Tensor | None = None,
|
| 322 |
+
past_key_values: Cache | None = None,
|
| 323 |
+
output_attentions: bool | None = False,
|
| 324 |
+
use_cache: bool | None = True,
|
| 325 |
+
**kwargs,
|
| 326 |
+
):
|
| 327 |
+
"""
|
| 328 |
+
Args:
|
| 329 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 330 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
| 331 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 332 |
+
encoder_hidden_states (`torch.FloatTensor`):
|
| 333 |
+
cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 334 |
+
encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
|
| 335 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 336 |
+
past_key_values (`Cache`): cached past key and value projection states
|
| 337 |
+
output_attentions (`bool`, *optional*):
|
| 338 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 339 |
+
returned tensors for more detail.
|
| 340 |
+
"""
|
| 341 |
+
residual = hidden_states
|
| 342 |
+
|
| 343 |
+
# Self Attention
|
| 344 |
+
hidden_states, self_attn_weights = self.self_attn(
|
| 345 |
+
hidden_states=hidden_states,
|
| 346 |
+
past_key_values=past_key_values,
|
| 347 |
+
attention_mask=attention_mask,
|
| 348 |
+
output_attentions=output_attentions,
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 352 |
+
hidden_states = residual + hidden_states
|
| 353 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 354 |
+
|
| 355 |
+
# Cross-Attention Block
|
| 356 |
+
cross_attn_weights = None
|
| 357 |
+
if encoder_hidden_states is not None:
|
| 358 |
+
residual = hidden_states
|
| 359 |
+
|
| 360 |
+
hidden_states, cross_attn_weights = self.encoder_attn(
|
| 361 |
+
hidden_states=hidden_states,
|
| 362 |
+
key_value_states=encoder_hidden_states,
|
| 363 |
+
attention_mask=encoder_attention_mask,
|
| 364 |
+
past_key_values=past_key_values,
|
| 365 |
+
output_attentions=output_attentions,
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 369 |
+
hidden_states = residual + hidden_states
|
| 370 |
+
hidden_states = self.encoder_attn_layer_norm(hidden_states)
|
| 371 |
+
|
| 372 |
+
# Fully Connected
|
| 373 |
+
residual = hidden_states
|
| 374 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 375 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
|
| 376 |
+
hidden_states = self.fc2(hidden_states)
|
| 377 |
+
|
| 378 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 379 |
+
hidden_states = residual + hidden_states
|
| 380 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 381 |
+
|
| 382 |
+
outputs = (hidden_states,)
|
| 383 |
+
|
| 384 |
+
if output_attentions:
|
| 385 |
+
outputs += (self_attn_weights, cross_attn_weights)
|
| 386 |
+
|
| 387 |
+
return outputs
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
@auto_docstring
|
| 391 |
+
class TrOCRPreTrainedModel(PreTrainedModel):
|
| 392 |
+
config: TrOCRConfig
|
| 393 |
+
base_model_prefix = "model"
|
| 394 |
+
supports_gradient_checkpointing = True
|
| 395 |
+
_no_split_modules = ["TrOCRDecoderLayer"]
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
class TrOCRDecoder(TrOCRPreTrainedModel):
|
| 399 |
+
"""
|
| 400 |
+
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`TrOCRDecoderLayer`]
|
| 401 |
+
|
| 402 |
+
Args:
|
| 403 |
+
config: TrOCRConfig
|
| 404 |
+
"""
|
| 405 |
+
|
| 406 |
+
def __init__(self, config: TrOCRConfig):
|
| 407 |
+
super().__init__(config)
|
| 408 |
+
self.dropout = config.dropout
|
| 409 |
+
self.layerdrop = config.decoder_layerdrop
|
| 410 |
+
self.padding_idx = config.pad_token_id
|
| 411 |
+
embed_scale = math.sqrt(config.hidden_size) if config.scale_embedding else 1.0
|
| 412 |
+
|
| 413 |
+
self.embed_tokens = TrOCRScaledWordEmbedding(
|
| 414 |
+
config.vocab_size, config.hidden_size, self.padding_idx, embed_scale=embed_scale
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
if config.use_learned_position_embeddings:
|
| 418 |
+
self.embed_positions = TrOCRLearnedPositionalEmbedding(config.max_position_embeddings, config.hidden_size)
|
| 419 |
+
else:
|
| 420 |
+
self.embed_positions = TrOCRSinusoidalPositionalEmbedding(
|
| 421 |
+
config.max_position_embeddings + self.padding_idx + 1,
|
| 422 |
+
config.hidden_size,
|
| 423 |
+
self.padding_idx,
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
if config.layernorm_embedding:
|
| 427 |
+
self.layernorm_embedding = nn.LayerNorm(config.hidden_size)
|
| 428 |
+
else:
|
| 429 |
+
self.layernorm_embedding = None
|
| 430 |
+
|
| 431 |
+
self.layers = nn.ModuleList([TrOCRDecoderLayer(config, layer_idx=i) for i in range(config.decoder_layers)])
|
| 432 |
+
|
| 433 |
+
self.gradient_checkpointing = False
|
| 434 |
+
# Initialize weights and apply final processing
|
| 435 |
+
self.post_init()
|
| 436 |
+
|
| 437 |
+
def forward(
|
| 438 |
+
self,
|
| 439 |
+
input_ids=None,
|
| 440 |
+
attention_mask=None,
|
| 441 |
+
encoder_hidden_states=None,
|
| 442 |
+
encoder_attention_mask=None,
|
| 443 |
+
past_key_values=None,
|
| 444 |
+
inputs_embeds=None,
|
| 445 |
+
use_cache=None,
|
| 446 |
+
output_attentions=None,
|
| 447 |
+
output_hidden_states=None,
|
| 448 |
+
return_dict=None,
|
| 449 |
+
**kwargs,
|
| 450 |
+
):
|
| 451 |
+
r"""
|
| 452 |
+
Args:
|
| 453 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 454 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
|
| 455 |
+
provide it.
|
| 456 |
+
|
| 457 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 458 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 459 |
+
|
| 460 |
+
[What are input IDs?](../glossary#input-ids)
|
| 461 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 462 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 463 |
+
|
| 464 |
+
- 1 for tokens that are **not masked**,
|
| 465 |
+
- 0 for tokens that are **masked**.
|
| 466 |
+
|
| 467 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 468 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
|
| 469 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
|
| 470 |
+
of the decoder.
|
| 471 |
+
encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
|
| 472 |
+
Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
|
| 473 |
+
selected in `[0, 1]`:
|
| 474 |
+
|
| 475 |
+
- 1 for tokens that are **not masked**,
|
| 476 |
+
- 0 for tokens that are **masked**.
|
| 477 |
+
|
| 478 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 479 |
+
past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 480 |
+
It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
|
| 481 |
+
|
| 482 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
|
| 483 |
+
cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
| 484 |
+
|
| 485 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
|
| 486 |
+
that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
|
| 487 |
+
all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 488 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 489 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 490 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 491 |
+
than the model's internal embedding lookup matrix.
|
| 492 |
+
output_attentions (`bool`, *optional*):
|
| 493 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 494 |
+
returned tensors for more detail.
|
| 495 |
+
output_hidden_states (`bool`, *optional*):
|
| 496 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 497 |
+
for more detail.
|
| 498 |
+
return_dict (`bool`, *optional*):
|
| 499 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 500 |
+
"""
|
| 501 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 502 |
+
output_hidden_states = (
|
| 503 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 504 |
+
)
|
| 505 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 506 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 507 |
+
|
| 508 |
+
# retrieve input_ids and inputs_embeds
|
| 509 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 510 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
| 511 |
+
elif input_ids is not None:
|
| 512 |
+
input = input_ids
|
| 513 |
+
input_ids = input_ids.view(-1, input.shape[-1])
|
| 514 |
+
elif inputs_embeds is not None:
|
| 515 |
+
input = inputs_embeds[:, :, -1]
|
| 516 |
+
else:
|
| 517 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
| 518 |
+
|
| 519 |
+
if self.gradient_checkpointing and self.training:
|
| 520 |
+
if use_cache:
|
| 521 |
+
logger.warning_once(
|
| 522 |
+
"`use_cache = True` is incompatible with gradient checkpointing. Setting `use_cache = False`..."
|
| 523 |
+
)
|
| 524 |
+
use_cache = False
|
| 525 |
+
|
| 526 |
+
if use_cache and past_key_values is None:
|
| 527 |
+
past_key_values = (
|
| 528 |
+
EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
|
| 529 |
+
if encoder_hidden_states is not None or self.config.is_encoder_decoder
|
| 530 |
+
else DynamicCache(config=self.config)
|
| 531 |
+
)
|
| 532 |
+
|
| 533 |
+
past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 534 |
+
|
| 535 |
+
if inputs_embeds is None:
|
| 536 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 537 |
+
|
| 538 |
+
if self.config.use_learned_position_embeddings:
|
| 539 |
+
embed_pos = self.embed_positions(input, past_key_values_length=past_key_values_length)
|
| 540 |
+
else:
|
| 541 |
+
embed_pos = self.embed_positions(input_ids, past_key_values_length=past_key_values_length)
|
| 542 |
+
|
| 543 |
+
hidden_states = inputs_embeds + embed_pos
|
| 544 |
+
|
| 545 |
+
if self.layernorm_embedding is not None:
|
| 546 |
+
hidden_states = self.layernorm_embedding(hidden_states)
|
| 547 |
+
|
| 548 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 549 |
+
|
| 550 |
+
attention_mask = create_causal_mask(
|
| 551 |
+
config=self.config,
|
| 552 |
+
inputs_embeds=inputs_embeds,
|
| 553 |
+
attention_mask=attention_mask,
|
| 554 |
+
past_key_values=past_key_values,
|
| 555 |
+
)
|
| 556 |
+
|
| 557 |
+
# expand encoder attention mask
|
| 558 |
+
if encoder_hidden_states is not None and encoder_attention_mask is not None:
|
| 559 |
+
encoder_attention_mask = create_bidirectional_mask(
|
| 560 |
+
config=self.config,
|
| 561 |
+
inputs_embeds=inputs_embeds,
|
| 562 |
+
attention_mask=encoder_attention_mask,
|
| 563 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 564 |
+
)
|
| 565 |
+
|
| 566 |
+
# decoder layers
|
| 567 |
+
all_hidden_states = () if output_hidden_states else None
|
| 568 |
+
all_self_attns = () if output_attentions else None
|
| 569 |
+
all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
|
| 570 |
+
|
| 571 |
+
for idx, decoder_layer in enumerate(self.layers):
|
| 572 |
+
# add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
|
| 573 |
+
if output_hidden_states:
|
| 574 |
+
all_hidden_states += (hidden_states,)
|
| 575 |
+
if self.training:
|
| 576 |
+
dropout_probability = torch.rand([])
|
| 577 |
+
if dropout_probability < self.layerdrop:
|
| 578 |
+
continue
|
| 579 |
+
|
| 580 |
+
layer_outputs = decoder_layer(
|
| 581 |
+
hidden_states,
|
| 582 |
+
attention_mask,
|
| 583 |
+
encoder_hidden_states, # as a positional argument for gradient checkpointing
|
| 584 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 585 |
+
past_key_values=past_key_values,
|
| 586 |
+
output_attentions=output_attentions,
|
| 587 |
+
use_cache=use_cache,
|
| 588 |
+
)
|
| 589 |
+
hidden_states = layer_outputs[0]
|
| 590 |
+
|
| 591 |
+
if output_attentions:
|
| 592 |
+
all_self_attns += (layer_outputs[1],)
|
| 593 |
+
|
| 594 |
+
if encoder_hidden_states is not None:
|
| 595 |
+
all_cross_attentions += (layer_outputs[2],)
|
| 596 |
+
|
| 597 |
+
# add hidden states from the last decoder layer
|
| 598 |
+
if output_hidden_states:
|
| 599 |
+
all_hidden_states += (hidden_states,)
|
| 600 |
+
|
| 601 |
+
if not return_dict:
|
| 602 |
+
return tuple(
|
| 603 |
+
v
|
| 604 |
+
for v in [hidden_states, past_key_values, all_hidden_states, all_self_attns, all_cross_attentions]
|
| 605 |
+
if v is not None
|
| 606 |
+
)
|
| 607 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 608 |
+
last_hidden_state=hidden_states,
|
| 609 |
+
past_key_values=past_key_values,
|
| 610 |
+
hidden_states=all_hidden_states,
|
| 611 |
+
attentions=all_self_attns,
|
| 612 |
+
cross_attentions=all_cross_attentions,
|
| 613 |
+
)
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
@auto_docstring(
|
| 617 |
+
custom_intro="""
|
| 618 |
+
The TrOCR Model with a language modeling head. Can be used for summarization.
|
| 619 |
+
This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
|
| 620 |
+
used in combination with the [`EncoderDecoderModel`] framework.
|
| 621 |
+
"""
|
| 622 |
+
)
|
| 623 |
+
class TrOCRDecoderWrapper(TrOCRPreTrainedModel):
|
| 624 |
+
def __init__(self, config):
|
| 625 |
+
super().__init__(config)
|
| 626 |
+
self.decoder = TrOCRDecoder(config)
|
| 627 |
+
self.post_init()
|
| 628 |
+
|
| 629 |
+
def forward(self, *args, **kwargs):
|
| 630 |
+
return self.decoder(*args, **kwargs)
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
@auto_docstring(
|
| 634 |
+
custom_intro="""
|
| 635 |
+
The TrOCR Decoder with a language modeling head. Can be used as the decoder part of [`EncoderDecoderModel`] and
|
| 636 |
+
"""
|
| 637 |
+
)
|
| 638 |
+
class TrOCRForCausalLM(TrOCRPreTrainedModel, GenerationMixin):
|
| 639 |
+
_tied_weights_keys = {"output_projection.weight": "model.decoder.embed_tokens.weight"}
|
| 640 |
+
|
| 641 |
+
def __init__(self, config):
|
| 642 |
+
config.is_decoder = True
|
| 643 |
+
config.is_encoder_decoder = False
|
| 644 |
+
super().__init__(config)
|
| 645 |
+
self.model = TrOCRDecoderWrapper(config)
|
| 646 |
+
|
| 647 |
+
self.output_projection = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 648 |
+
|
| 649 |
+
# Initialize weights and apply final processing
|
| 650 |
+
self.post_init()
|
| 651 |
+
|
| 652 |
+
def get_input_embeddings(self):
|
| 653 |
+
return self.model.decoder.embed_tokens
|
| 654 |
+
|
| 655 |
+
def set_input_embeddings(self, value):
|
| 656 |
+
self.model.decoder.embed_tokens = value
|
| 657 |
+
|
| 658 |
+
def get_output_embeddings(self):
|
| 659 |
+
return self.output_projection
|
| 660 |
+
|
| 661 |
+
def set_output_embeddings(self, new_embeddings):
|
| 662 |
+
self.output_projection = new_embeddings
|
| 663 |
+
|
| 664 |
+
@auto_docstring
|
| 665 |
+
def forward(
|
| 666 |
+
self,
|
| 667 |
+
input_ids: torch.LongTensor | None = None,
|
| 668 |
+
attention_mask: torch.Tensor | None = None,
|
| 669 |
+
encoder_hidden_states: torch.FloatTensor | None = None,
|
| 670 |
+
encoder_attention_mask: torch.LongTensor | None = None,
|
| 671 |
+
past_key_values: Cache | None = None,
|
| 672 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 673 |
+
labels: torch.LongTensor | None = None,
|
| 674 |
+
use_cache: bool | None = None,
|
| 675 |
+
output_attentions: bool | None = None,
|
| 676 |
+
output_hidden_states: bool | None = None,
|
| 677 |
+
return_dict: bool | None = None,
|
| 678 |
+
**kwargs,
|
| 679 |
+
) -> tuple | CausalLMOutputWithCrossAttentions:
|
| 680 |
+
r"""
|
| 681 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 682 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 683 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 684 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 685 |
+
|
| 686 |
+
Example:
|
| 687 |
+
|
| 688 |
+
```python
|
| 689 |
+
>>> from transformers import (
|
| 690 |
+
... TrOCRConfig,
|
| 691 |
+
... TrOCRProcessor,
|
| 692 |
+
... TrOCRForCausalLM,
|
| 693 |
+
... ViTConfig,
|
| 694 |
+
... ViTModel,
|
| 695 |
+
... VisionEncoderDecoderModel,
|
| 696 |
+
... )
|
| 697 |
+
>>> import httpx
|
| 698 |
+
>>> from io import BytesIO
|
| 699 |
+
>>> from PIL import Image
|
| 700 |
+
|
| 701 |
+
>>> # TrOCR is a decoder model and should be used within a VisionEncoderDecoderModel
|
| 702 |
+
>>> # init vision2text model with random weights
|
| 703 |
+
>>> encoder = ViTModel(ViTConfig())
|
| 704 |
+
>>> decoder = TrOCRForCausalLM(TrOCRConfig())
|
| 705 |
+
>>> model = VisionEncoderDecoderModel(encoder=encoder, decoder=decoder)
|
| 706 |
+
|
| 707 |
+
>>> # If you want to start from the pretrained model, load the checkpoint with `VisionEncoderDecoderModel`
|
| 708 |
+
>>> processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-handwritten")
|
| 709 |
+
>>> model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten")
|
| 710 |
+
|
| 711 |
+
>>> # load image from the IAM dataset
|
| 712 |
+
>>> url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg"
|
| 713 |
+
>>> with httpx.stream("GET", url) as response:
|
| 714 |
+
... image = Image.open(BytesIO(response.read())).convert("RGB")
|
| 715 |
+
>>> pixel_values = processor(image, return_tensors="pt").pixel_values
|
| 716 |
+
>>> text = "industry, ' Mr. Brown commented icily. ' Let us have a"
|
| 717 |
+
|
| 718 |
+
>>> # training
|
| 719 |
+
>>> model.config.decoder_start_token_id = processor.tokenizer.eos_token_id
|
| 720 |
+
>>> model.config.pad_token_id = processor.tokenizer.pad_token_id
|
| 721 |
+
>>> model.config.vocab_size = model.config.decoder.vocab_size
|
| 722 |
+
|
| 723 |
+
>>> labels = processor.tokenizer(text, return_tensors="pt").input_ids
|
| 724 |
+
>>> outputs = model(pixel_values, labels=labels)
|
| 725 |
+
>>> loss = outputs.loss
|
| 726 |
+
>>> round(loss.item(), 2)
|
| 727 |
+
5.30
|
| 728 |
+
|
| 729 |
+
>>> # inference
|
| 730 |
+
>>> generated_ids = model.generate(pixel_values)
|
| 731 |
+
>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 732 |
+
>>> generated_text
|
| 733 |
+
'industry, " Mr. Brown commented icily. " Let us have a'
|
| 734 |
+
```"""
|
| 735 |
+
|
| 736 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 737 |
+
output_hidden_states = (
|
| 738 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 739 |
+
)
|
| 740 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 741 |
+
|
| 742 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 743 |
+
outputs = self.model.decoder(
|
| 744 |
+
input_ids=input_ids,
|
| 745 |
+
attention_mask=attention_mask,
|
| 746 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 747 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 748 |
+
past_key_values=past_key_values,
|
| 749 |
+
inputs_embeds=inputs_embeds,
|
| 750 |
+
use_cache=use_cache,
|
| 751 |
+
output_attentions=output_attentions,
|
| 752 |
+
output_hidden_states=output_hidden_states,
|
| 753 |
+
return_dict=return_dict,
|
| 754 |
+
)
|
| 755 |
+
|
| 756 |
+
logits = self.output_projection(outputs[0])
|
| 757 |
+
|
| 758 |
+
loss = None
|
| 759 |
+
if labels is not None:
|
| 760 |
+
loss_fct = CrossEntropyLoss()
|
| 761 |
+
loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
|
| 762 |
+
|
| 763 |
+
if not return_dict:
|
| 764 |
+
output = (logits,) + outputs[1:]
|
| 765 |
+
return (loss,) + output if loss is not None else output
|
| 766 |
+
|
| 767 |
+
return CausalLMOutputWithCrossAttentions(
|
| 768 |
+
loss=loss,
|
| 769 |
+
logits=logits,
|
| 770 |
+
past_key_values=outputs.past_key_values,
|
| 771 |
+
hidden_states=outputs.hidden_states,
|
| 772 |
+
attentions=outputs.attentions,
|
| 773 |
+
cross_attentions=outputs.cross_attentions,
|
| 774 |
+
)
|
| 775 |
+
|
| 776 |
+
|
| 777 |
+
__all__ = ["TrOCRForCausalLM", "TrOCRPreTrainedModel"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/trocr/processing_trocr.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 The HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""
|
| 15 |
+
Processor class for TrOCR.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
from ...image_processing_utils import BatchFeature
|
| 19 |
+
from ...image_utils import ImageInput
|
| 20 |
+
from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
|
| 21 |
+
from ...tokenization_utils_base import PreTokenizedInput, TextInput
|
| 22 |
+
from ...utils import auto_docstring
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class TrOCRProcessorKwargs(ProcessingKwargs, total=False):
|
| 26 |
+
_defaults = {}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@auto_docstring
|
| 30 |
+
class TrOCRProcessor(ProcessorMixin):
|
| 31 |
+
def __init__(self, image_processor=None, tokenizer=None, **kwargs):
|
| 32 |
+
super().__init__(image_processor, tokenizer)
|
| 33 |
+
|
| 34 |
+
@auto_docstring
|
| 35 |
+
def __call__(
|
| 36 |
+
self,
|
| 37 |
+
images: ImageInput | None = None,
|
| 38 |
+
text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None,
|
| 39 |
+
**kwargs: Unpack[TrOCRProcessorKwargs],
|
| 40 |
+
) -> BatchFeature:
|
| 41 |
+
if images is None and text is None:
|
| 42 |
+
raise ValueError("You need to specify either an `images` or `text` input to process.")
|
| 43 |
+
|
| 44 |
+
output_kwargs = self._merge_kwargs(
|
| 45 |
+
TrOCRProcessorKwargs,
|
| 46 |
+
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
|
| 47 |
+
**kwargs,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
if images is not None:
|
| 51 |
+
inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
|
| 52 |
+
if text is not None:
|
| 53 |
+
encodings = self.tokenizer(text, **output_kwargs["text_kwargs"])
|
| 54 |
+
|
| 55 |
+
if text is None:
|
| 56 |
+
return inputs
|
| 57 |
+
elif images is None:
|
| 58 |
+
return encodings
|
| 59 |
+
else:
|
| 60 |
+
inputs["labels"] = encodings["input_ids"]
|
| 61 |
+
return inputs
|
| 62 |
+
|
| 63 |
+
@property
|
| 64 |
+
def model_input_names(self):
|
| 65 |
+
image_processor_input_names = self.image_processor.model_input_names
|
| 66 |
+
return image_processor_input_names + ["labels"]
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
__all__ = ["TrOCRProcessor"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr1e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260609_155046/step_123000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f18deaf2aa5bc4d128297f86d1f48f0254dc3bee05e24c86bbf4a1dcabc9ff30
|
| 3 |
+
size 927700322
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr1e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260609_155046/step_174000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6379283057ba00314a7a6ec562670828237821c0d84fd8733aafb528e15e52a8
|
| 3 |
+
size 927700322
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr1e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260609_155046/step_218000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:20056a9926558a324477113ff4c98e3d11ab260b899bcc5c67d26153a8bfa32d
|
| 3 |
+
size 927700322
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr1e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260609_155046/step_281000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7b223cb3527d3c0c7153506147326028f4456e18f7e2f738d7fc8ba7df0ba136
|
| 3 |
+
size 927700322
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr1e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260609_155046/step_358000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:050d1d521fe29f9d2ccc59e12e3c885f7b5dd10b6b9ce0ed987634660836a5e2
|
| 3 |
+
size 927700322
|