assassinlike commited on
Commit
a1977df
·
verified ·
1 Parent(s): a0ad151

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/__pycache__/__init__.cpython-311.pyc +0 -0
  2. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aimv2/__pycache__/__init__.cpython-311.pyc +0 -0
  3. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aimv2/__pycache__/configuration_aimv2.cpython-311.pyc +0 -0
  4. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aimv2/__pycache__/modeling_aimv2.cpython-311.pyc +0 -0
  5. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aimv2/__pycache__/modular_aimv2.cpython-311.pyc +0 -0
  6. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/align/__pycache__/__init__.cpython-311.pyc +0 -0
  7. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/align/__pycache__/configuration_align.cpython-311.pyc +0 -0
  8. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/align/__pycache__/modeling_align.cpython-311.pyc +0 -0
  9. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/align/__pycache__/processing_align.cpython-311.pyc +0 -0
  10. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/apertus/__pycache__/__init__.cpython-311.pyc +0 -0
  11. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/apertus/__pycache__/configuration_apertus.cpython-311.pyc +0 -0
  12. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/apertus/__pycache__/modeling_apertus.cpython-311.pyc +0 -0
  13. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/apertus/__pycache__/modular_apertus.cpython-311.pyc +0 -0
  14. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__init__.py +31 -0
  15. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/__init__.cpython-311.pyc +0 -0
  16. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/configuration_aria.cpython-311.pyc +0 -0
  17. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/image_processing_aria.cpython-311.pyc +0 -0
  18. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/image_processing_pil_aria.cpython-311.pyc +0 -0
  19. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/modeling_aria.cpython-311.pyc +0 -0
  20. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/modular_aria.cpython-311.pyc +0 -0
  21. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/processing_aria.cpython-311.pyc +0 -0
  22. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/configuration_aria.py +149 -0
  23. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/image_processing_aria.py +226 -0
  24. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/image_processing_pil_aria.py +230 -0
  25. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/modeling_aria.py +1198 -0
  26. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/modular_aria.py +1156 -0
  27. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/processing_aria.py +177 -0
  28. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/autoformer/__pycache__/__init__.cpython-311.pyc +0 -0
  29. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/autoformer/__pycache__/configuration_autoformer.cpython-311.pyc +0 -0
  30. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__init__.py +28 -0
  31. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__pycache__/__init__.cpython-311.pyc +0 -0
  32. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__pycache__/configuration_bert.cpython-311.pyc +0 -0
  33. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__pycache__/modeling_bert.cpython-311.pyc +0 -0
  34. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__pycache__/tokenization_bert.cpython-311.pyc +0 -0
  35. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__pycache__/tokenization_bert_legacy.cpython-311.pyc +0 -0
  36. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/configuration_bert.py +66 -0
  37. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/modeling_bert.py +1394 -0
  38. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/tokenization_bert.py +140 -0
  39. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/tokenization_bert_legacy.py +476 -0
  40. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bertweet/__init__.py +26 -0
  41. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bertweet/__pycache__/__init__.cpython-311.pyc +0 -0
  42. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bertweet/__pycache__/tokenization_bertweet.cpython-311.pyc +0 -0
  43. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bertweet/tokenization_bertweet.py +698 -0
  44. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/biogpt/__init__.py +28 -0
  45. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/biogpt/__pycache__/__init__.cpython-311.pyc +0 -0
  46. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/biogpt/__pycache__/configuration_biogpt.cpython-311.pyc +0 -0
  47. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/biogpt/__pycache__/modeling_biogpt.cpython-311.pyc +0 -0
  48. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/biogpt/__pycache__/modular_biogpt.cpython-311.pyc +0 -0
  49. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/biogpt/__pycache__/tokenization_biogpt.cpython-311.pyc +0 -0
  50. data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/biogpt/configuration_biogpt.py +64 -0
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (15.3 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aimv2/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (778 Bytes). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aimv2/__pycache__/configuration_aimv2.cpython-311.pyc ADDED
Binary file (7.59 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aimv2/__pycache__/modeling_aimv2.cpython-311.pyc ADDED
Binary file (42.2 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aimv2/__pycache__/modular_aimv2.cpython-311.pyc ADDED
Binary file (29 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/align/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (816 Bytes). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/align/__pycache__/configuration_align.cpython-311.pyc ADDED
Binary file (10.8 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/align/__pycache__/modeling_align.cpython-311.pyc ADDED
Binary file (60.1 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/align/__pycache__/processing_align.cpython-311.pyc ADDED
Binary file (1.45 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/apertus/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (784 Bytes). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/apertus/__pycache__/configuration_apertus.cpython-311.pyc ADDED
Binary file (3.8 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/apertus/__pycache__/modeling_apertus.cpython-311.pyc ADDED
Binary file (28.9 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/apertus/__pycache__/modular_apertus.cpython-311.pyc ADDED
Binary file (13.4 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__init__.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_aria import *
22
+ from .image_processing_aria import *
23
+ from .image_processing_pil_aria import *
24
+ from .modeling_aria import *
25
+ from .processing_aria import *
26
+
27
+ else:
28
+ import sys
29
+
30
+ _file = globals()["__file__"]
31
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (904 Bytes). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/configuration_aria.cpython-311.pyc ADDED
Binary file (7.29 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/image_processing_aria.cpython-311.pyc ADDED
Binary file (11.3 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/image_processing_pil_aria.cpython-311.pyc ADDED
Binary file (11.4 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/modeling_aria.cpython-311.pyc ADDED
Binary file (64.6 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/modular_aria.cpython-311.pyc ADDED
Binary file (60.6 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/processing_aria.cpython-311.pyc ADDED
Binary file (9.9 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/configuration_aria.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/aria/modular_aria.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_aria.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2024 The Rhymes-AI Teams Authors and The HuggingFace Inc. team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ from huggingface_hub.dataclasses import strict
21
+
22
+ from ...configuration_utils import PreTrainedConfig
23
+ from ...modeling_rope_utils import RopeParameters
24
+ from ...utils import auto_docstring
25
+ from ...utils.type_validators import interval
26
+ from ..auto import CONFIG_MAPPING, AutoConfig
27
+
28
+
29
+ @auto_docstring(checkpoint="rhymes-ai/Aria")
30
+ @strict
31
+ class AriaTextConfig(PreTrainedConfig):
32
+ r"""
33
+ moe_num_experts (`int`, *optional*, defaults to 8):
34
+ The number of experts in the MoE layer.
35
+ moe_topk (`int`, *optional*, defaults to 2):
36
+ The number of top experts to route to for each token.
37
+ moe_num_shared_experts (`int`, *optional*, defaults to 2):
38
+ The number of shared experts.
39
+ """
40
+
41
+ model_type = "aria_text"
42
+ keys_to_ignore_at_inference = ["past_key_values"]
43
+ base_model_tp_plan = {
44
+ "layers.*.self_attn.q_proj": "colwise",
45
+ "layers.*.self_attn.k_proj": "colwise",
46
+ "layers.*.self_attn.v_proj": "colwise",
47
+ "layers.*.self_attn.o_proj": "rowwise",
48
+ "layers.*.mlp.shared_experts.gate_proj": "colwise",
49
+ "layers.*.mlp.shared_experts.up_proj": "colwise",
50
+ "layers.*.mlp.shared_experts.down_proj": "rowwise",
51
+ }
52
+ base_model_pp_plan = {
53
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
54
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
55
+ "norm": (["hidden_states"], ["hidden_states"]),
56
+ }
57
+
58
+ vocab_size: int = 32000
59
+ hidden_size: int = 4096
60
+
61
+ intermediate_size: int = 4096
62
+ num_hidden_layers: int = 32
63
+ num_attention_heads: int = 32
64
+ num_key_value_heads: int | None = None
65
+ hidden_act: str = "silu"
66
+ max_position_embeddings: int = 2048
67
+ initializer_range: float = interval(min=0.0, max=1.0)(default=0.02)
68
+ rms_norm_eps: float = 1e-6
69
+ use_cache: bool = True
70
+ pad_token_id: int | None = 2
71
+ bos_token_id: int | None = 1
72
+ eos_token_id: int | list[int] | None = 2
73
+ pretraining_tp: int | None = 1
74
+ tie_word_embeddings: bool = False
75
+ rope_parameters: RopeParameters | dict | None = None
76
+ attention_bias: bool = False
77
+ attention_dropout: int | float | None = 0.0
78
+ mlp_bias: bool = False
79
+ head_dim: int | None = None
80
+ base_config_key = "text_config"
81
+ moe_num_experts: int = 8
82
+ moe_topk: int = 2
83
+ moe_num_shared_experts: int = 2
84
+
85
+ def __post_init__(self, **kwargs):
86
+ if self.head_dim is None:
87
+ self.head_dim = self.hidden_size // self.num_attention_heads
88
+ if self.num_key_value_heads is None:
89
+ self.num_key_value_heads = self.num_attention_heads
90
+
91
+ super().__post_init__(**kwargs)
92
+
93
+ def validate_architecture(self):
94
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
95
+ if self.hidden_size % self.num_attention_heads != 0:
96
+ raise ValueError(
97
+ f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention "
98
+ f"heads ({self.num_attention_heads})."
99
+ )
100
+
101
+
102
+ @auto_docstring(checkpoint="rhymes-ai/Aria")
103
+ @strict
104
+ class AriaConfig(PreTrainedConfig):
105
+ r"""
106
+ projector_patch_to_query_dict (`dict`, *optional*):
107
+ Mapping of patch sizes to query dimensions.
108
+ """
109
+
110
+ model_type = "aria"
111
+ attribute_map = {
112
+ "image_token_id": "image_token_index",
113
+ }
114
+ sub_configs = {"text_config": AriaTextConfig, "vision_config": AutoConfig}
115
+
116
+ vision_config: dict | PreTrainedConfig | None = None
117
+ text_config: dict | AriaTextConfig | None = None
118
+ vision_feature_layer: int | list[int] = -1
119
+ projector_patch_to_query_dict: dict | None = None
120
+ image_token_index: int = 9
121
+ initializer_range: float = 0.02
122
+ tie_word_embeddings: bool = False
123
+
124
+ def __post_init__(self, **kwargs):
125
+ # Convert the keys and values of projector_patch_to_query_dict to integers
126
+ # This ensures consistency even if they were provided as strings
127
+ if self.projector_patch_to_query_dict is None:
128
+ self.projector_patch_to_query_dict = {
129
+ 1225: 128,
130
+ 4900: 256,
131
+ }
132
+ self.projector_patch_to_query_dict = {int(k): int(v) for k, v in self.projector_patch_to_query_dict.items()}
133
+ self.max_value_projector_patch_to_query_dict = max(self.projector_patch_to_query_dict.values())
134
+
135
+ if isinstance(self.vision_config, dict):
136
+ self.vision_config["model_type"] = "idefics3_vision"
137
+ self.vision_config = CONFIG_MAPPING[self.vision_config["model_type"]](**self.vision_config)
138
+ elif self.vision_config is None:
139
+ self.vision_config = CONFIG_MAPPING["idefics3_vision"]()
140
+
141
+ if isinstance(self.text_config, dict) and "model_type" in self.text_config:
142
+ self.text_config = AriaTextConfig(**self.text_config)
143
+ elif self.text_config is None:
144
+ self.text_config = AriaTextConfig()
145
+
146
+ super().__post_init__(**kwargs)
147
+
148
+
149
+ __all__ = ["AriaConfig", "AriaTextConfig"]
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/image_processing_aria.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/aria/modular_aria.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_aria.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2024 The Rhymes-AI Teams Authors and The HuggingFace Inc. team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ import torch
21
+ from torchvision.transforms.v2 import functional as tvF
22
+
23
+ from ...image_processing_backends import TorchvisionBackend
24
+ from ...image_processing_utils import BatchFeature, get_patch_output_size, select_best_resolution
25
+ from ...image_transforms import divide_to_patches
26
+ from ...image_utils import ChannelDimension, PILImageResampling, SizeDict, get_image_size
27
+ from ...processing_utils import ImagesKwargs, Unpack
28
+ from ...utils import TensorType, auto_docstring
29
+
30
+
31
+ class AriaImageProcessorKwargs(ImagesKwargs, total=False):
32
+ r"""
33
+ max_image_size (`int`, *optional*, defaults to `self.max_image_size`):
34
+ Maximum image size. Must be either 490 or 980.
35
+ min_image_size (`int`, *optional*, defaults to `self.min_image_size`):
36
+ Minimum image size. Images smaller than this in any dimension will be scaled up.
37
+ split_resolutions (`list[list[int]]`, *optional*, defaults to `self.split_resolutions`):
38
+ A list of possible resolutions as (height, width) pairs for splitting high-resolution images into patches.
39
+ split_image (`bool`, *optional*, defaults to `self.split_image`):
40
+ Whether to split the image into patches using the best matching resolution from `split_resolutions`.
41
+ """
42
+
43
+ max_image_size: int
44
+ min_image_size: int
45
+ split_resolutions: list[list[int]]
46
+ split_image: bool
47
+
48
+
49
+ @auto_docstring
50
+ class AriaImageProcessor(TorchvisionBackend):
51
+ model_input_names = ["pixel_values", "pixel_mask", "num_crops"]
52
+ valid_kwargs = AriaImageProcessorKwargs
53
+
54
+ resample = PILImageResampling.BICUBIC
55
+ image_mean = [0.5, 0.5, 0.5]
56
+ image_std = [0.5, 0.5, 0.5]
57
+ max_image_size = 980
58
+ min_image_size = 336
59
+ split_image = False
60
+ split_resolutions = None
61
+ do_convert_rgb = True
62
+ do_rescale = True
63
+ do_normalize = True
64
+
65
+ def __init__(self, **kwargs: Unpack[AriaImageProcessorKwargs]):
66
+ if kwargs.get("split_resolutions") is None:
67
+ default_resolutions = [(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (2, 4), (2, 3), (2, 2), (2, 1), (3, 1), (3, 2), (4, 1), (4, 2), (5, 1), (6, 1), (7, 1), (8, 1)] # fmt: skip
68
+ kwargs["split_resolutions"] = [[el[0] * 490, el[1] * 490] for el in default_resolutions]
69
+ super().__init__(**kwargs)
70
+
71
+ def _get_padding_size(self, original_resolution: tuple, target_resolution: tuple) -> list[int]:
72
+ """Get padding size for patching, returns [left, top, right, bottom] for tvF.pad."""
73
+ original_height, original_width = original_resolution
74
+ target_height, target_width = target_resolution
75
+ paste_x, r_x = divmod(target_width - original_width, 2)
76
+ paste_y, r_y = divmod(target_height - original_height, 2)
77
+ return [paste_x, paste_y, paste_x + r_x, paste_y + r_y]
78
+
79
+ def _resize_for_patching(
80
+ self,
81
+ image: "torch.Tensor",
82
+ target_resolution: tuple,
83
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None",
84
+ ) -> "torch.Tensor":
85
+ """Resize an image to a target resolution while maintaining aspect ratio."""
86
+ new_height, new_width = get_patch_output_size(
87
+ image, target_resolution, input_data_format=ChannelDimension.FIRST
88
+ )
89
+ return self.resize(image, SizeDict(height=new_height, width=new_width), resample)
90
+
91
+ def _pad_for_patching(
92
+ self,
93
+ image: "torch.Tensor",
94
+ target_resolution: tuple,
95
+ ) -> "torch.Tensor":
96
+ """Pad an image to a target resolution while maintaining aspect ratio."""
97
+ new_resolution = get_patch_output_size(image, target_resolution, input_data_format=ChannelDimension.FIRST)
98
+ padding = self._get_padding_size(new_resolution, target_resolution)
99
+ return tvF.pad(image, padding=padding)
100
+
101
+ def get_image_patches(
102
+ self,
103
+ image: "torch.Tensor",
104
+ grid_pinpoints: list[list[int]],
105
+ patch_size: int,
106
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None",
107
+ ) -> list["torch.Tensor"]:
108
+ """
109
+ Process an image with variable resolutions by dividing it into patches.
110
+
111
+ Args:
112
+ image (`torch.Tensor`):
113
+ The input image to be processed (channels-first format).
114
+ grid_pinpoints (`list[list[int]]`):
115
+ A list of possible resolutions as (height, width) pairs.
116
+ patch_size (`int`):
117
+ Size of each square patch to divide the image into.
118
+ resample (`PILImageResampling | tvF.InterpolationMode | int | None`):
119
+ Resampling filter to use when resizing.
120
+
121
+ Returns:
122
+ `list[torch.Tensor]`: A list of image patches in channels-first format.
123
+ """
124
+ if not isinstance(grid_pinpoints, list):
125
+ raise TypeError("grid_pinpoints must be a list of possible resolutions.")
126
+
127
+ image_size = get_image_size(image, channel_dim=ChannelDimension.FIRST)
128
+ best_resolution = select_best_resolution(image_size, grid_pinpoints)
129
+ resized_image = self._resize_for_patching(image, best_resolution, resample)
130
+ padded_image = self._pad_for_patching(resized_image, best_resolution)
131
+ patches = divide_to_patches(padded_image, patch_size=patch_size)
132
+ return patches
133
+
134
+ def _preprocess(
135
+ self,
136
+ images: list["torch.Tensor"],
137
+ do_rescale: bool,
138
+ rescale_factor: float,
139
+ do_normalize: bool,
140
+ image_mean: float | list[float] | None,
141
+ image_std: float | list[float] | None,
142
+ disable_grouping: bool | None,
143
+ return_tensors: str | TensorType | None,
144
+ max_image_size: int = 980,
145
+ min_image_size: int = 336,
146
+ split_resolutions: list[list[int]] | None = None,
147
+ split_image: bool = False,
148
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None" = None,
149
+ **kwargs,
150
+ ) -> BatchFeature:
151
+ if max_image_size not in [490, 980]:
152
+ raise ValueError("max_image_size must be either 490 or 980")
153
+
154
+ pixel_masks = []
155
+ processed_crops = []
156
+ num_crops = None
157
+
158
+ for image in images:
159
+ if split_image:
160
+ crop_images = self.get_image_patches(image, split_resolutions, max_image_size, resample)
161
+ else:
162
+ crop_images = [image]
163
+
164
+ if num_crops is None or len(crop_images) > num_crops:
165
+ num_crops = len(crop_images)
166
+
167
+ for crop_image in crop_images:
168
+ h, w = crop_image.shape[-2], crop_image.shape[-1]
169
+ scale = max_image_size / max(h, w)
170
+ if w >= h:
171
+ new_h = max(int(h * scale), min_image_size)
172
+ new_w = max_image_size
173
+ else:
174
+ new_h = max_image_size
175
+ new_w = max(int(w * scale), min_image_size)
176
+
177
+ crop_image = self.resize(crop_image, SizeDict(height=new_h, width=new_w), resample)
178
+
179
+ padding_bottom = max_image_size - new_h
180
+ padding_right = max_image_size - new_w
181
+ crop_image = tvF.pad(crop_image, [0, 0, padding_right, padding_bottom])
182
+
183
+ pixel_mask = torch.zeros((max_image_size, max_image_size), dtype=torch.bool)
184
+ pixel_mask[:new_h, :new_w] = True
185
+ pixel_masks.append(pixel_mask)
186
+ processed_crops.append(crop_image)
187
+
188
+ stacked_images = torch.stack(processed_crops, dim=0)
189
+ stacked_images = self.rescale_and_normalize(
190
+ stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
191
+ )
192
+ stacked_masks = torch.stack(pixel_masks, dim=0)
193
+
194
+ return BatchFeature(
195
+ data={
196
+ "pixel_values": stacked_images,
197
+ "pixel_mask": stacked_masks,
198
+ "num_crops": num_crops,
199
+ },
200
+ tensor_type=return_tensors,
201
+ )
202
+
203
+ def get_number_of_image_patches(self, height: int, width: int, images_kwargs=None):
204
+ """
205
+ A utility that returns number of image patches for a given image size.
206
+
207
+ Args:
208
+ height (`int`):
209
+ Height of the input image.
210
+ width (`int`):
211
+ Width of the input image.
212
+ images_kwargs (`dict`, *optional*):
213
+ Any kwargs to override defaults of the image processor.
214
+
215
+ Returns:
216
+ `int`: Number of patches per image.
217
+ """
218
+ split_image = images_kwargs.get("split_image", self.split_image)
219
+ max_image_size = images_kwargs.get("max_image_size", self.max_image_size)
220
+
221
+ resized_height, resized_width = select_best_resolution((height, width), self.split_resolutions)
222
+ num_patches = 1 if not split_image else resized_height // max_image_size * resized_width // max_image_size
223
+ return num_patches
224
+
225
+
226
+ __all__ = ["AriaImageProcessor"]
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/image_processing_pil_aria.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The Rhymes-AI Teams 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
+ """Image processor class for Aria."""
15
+
16
+ import numpy as np
17
+
18
+ from ...image_processing_backends import PilBackend
19
+ from ...image_processing_utils import BatchFeature, get_patch_output_size, select_best_resolution
20
+ from ...image_transforms import divide_to_patches
21
+ from ...image_utils import (
22
+ ChannelDimension,
23
+ PILImageResampling,
24
+ SizeDict,
25
+ get_image_size,
26
+ )
27
+ from ...processing_utils import ImagesKwargs, Unpack
28
+ from ...utils import TensorType, auto_docstring
29
+
30
+
31
+ # Adapted from transformers.models.aria.image_processing_aria.AriaImageProcessorKwargs
32
+ class AriaImageProcessorKwargs(ImagesKwargs, total=False):
33
+ r"""
34
+ max_image_size (`int`, *optional*, defaults to `self.max_image_size`):
35
+ Maximum image size. Must be either 490 or 980.
36
+ min_image_size (`int`, *optional*, defaults to `self.min_image_size`):
37
+ Minimum image size. Images smaller than this in any dimension will be scaled up.
38
+ split_resolutions (`list[list[int]]`, *optional*, defaults to `self.split_resolutions`):
39
+ A list of possible resolutions as (height, width) pairs for splitting high-resolution images into patches.
40
+ split_image (`bool`, *optional*, defaults to `self.split_image`):
41
+ Whether to split the image into patches using the best matching resolution from `split_resolutions`.
42
+ """
43
+
44
+ max_image_size: int
45
+ min_image_size: int
46
+ split_resolutions: list[list[int]]
47
+ split_image: bool
48
+
49
+
50
+ @auto_docstring
51
+ class AriaImageProcessorPil(PilBackend):
52
+ model_input_names = ["pixel_values", "pixel_mask", "num_crops"]
53
+ valid_kwargs = AriaImageProcessorKwargs
54
+
55
+ resample = PILImageResampling.BICUBIC
56
+ image_mean = [0.5, 0.5, 0.5]
57
+ image_std = [0.5, 0.5, 0.5]
58
+ max_image_size = 980
59
+ min_image_size = 336
60
+ split_image = False
61
+ split_resolutions = None
62
+ do_convert_rgb = True
63
+ do_rescale = True
64
+ do_normalize = True
65
+
66
+ def __init__(self, **kwargs: Unpack[AriaImageProcessorKwargs]):
67
+ if kwargs.get("split_resolutions") is None:
68
+ default_resolutions = [(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (2, 4), (2, 3), (2, 2), (2, 1), (3, 1), (3, 2), (4, 1), (4, 2), (5, 1), (6, 1), (7, 1), (8, 1)] # fmt: skip
69
+ kwargs["split_resolutions"] = [[el[0] * 490, el[1] * 490] for el in default_resolutions]
70
+ super().__init__(**kwargs)
71
+
72
+ def _get_padding_size(self, original_resolution: tuple, target_resolution: tuple):
73
+ """Get padding size for patching, returns ((before_h, after_h), (before_w, after_w)) for np.pad."""
74
+ original_height, original_width = original_resolution
75
+ target_height, target_width = target_resolution
76
+ paste_x, r_x = divmod(target_width - original_width, 2)
77
+ paste_y, r_y = divmod(target_height - original_height, 2)
78
+ return (paste_y, paste_y + r_y), (paste_x, paste_x + r_x)
79
+
80
+ def _resize_for_patching(
81
+ self,
82
+ image: np.ndarray,
83
+ target_resolution: tuple,
84
+ resample: "PILImageResampling | None",
85
+ ) -> np.ndarray:
86
+ """Resize an image to a target resolution while maintaining aspect ratio."""
87
+ new_height, new_width = get_patch_output_size(
88
+ image, target_resolution, input_data_format=ChannelDimension.FIRST
89
+ )
90
+ return self.resize(image, SizeDict(height=new_height, width=new_width), resample)
91
+
92
+ def _pad_for_patching(
93
+ self,
94
+ image: np.ndarray,
95
+ target_resolution: tuple,
96
+ ) -> np.ndarray:
97
+ """Pad an image to a target resolution while maintaining aspect ratio."""
98
+ new_resolution = get_patch_output_size(image, target_resolution, input_data_format=ChannelDimension.FIRST)
99
+ padding_hw = self._get_padding_size(new_resolution, target_resolution)
100
+ # CHW format: pad channel dim with zeros, then height/width
101
+ padding = ((0, 0), padding_hw[0], padding_hw[1])
102
+ return np.pad(image, padding, mode="constant", constant_values=0)
103
+
104
+ def get_image_patches(
105
+ self,
106
+ image: np.ndarray,
107
+ grid_pinpoints: list[list[int]],
108
+ patch_size: int,
109
+ resample: "PILImageResampling | None",
110
+ ) -> list[np.ndarray]:
111
+ """
112
+ Process an image with variable resolutions by dividing it into patches.
113
+
114
+ Args:
115
+ image (`np.ndarray`):
116
+ The input image to be processed (channels-first format).
117
+ grid_pinpoints (`list[list[int]]`):
118
+ A list of possible resolutions as (height, width) pairs.
119
+ patch_size (`int`):
120
+ Size of each square patch to divide the image into.
121
+ resample (`PILImageResampling | int | None`):
122
+ Resampling filter to use when resizing.
123
+
124
+ Returns:
125
+ `list[np.ndarray]`: A list of image patches in channels-first format.
126
+ """
127
+ if not isinstance(grid_pinpoints, list):
128
+ raise TypeError("grid_pinpoints must be a list of possible resolutions.")
129
+
130
+ image_size = get_image_size(image, channel_dim=ChannelDimension.FIRST)
131
+ best_resolution = select_best_resolution(image_size, grid_pinpoints)
132
+ resized_image = self._resize_for_patching(image, best_resolution, resample)
133
+ padded_image = self._pad_for_patching(resized_image, best_resolution)
134
+ patches = divide_to_patches(padded_image, patch_size=patch_size)
135
+ return patches
136
+
137
+ def _preprocess(
138
+ self,
139
+ images: list[np.ndarray],
140
+ do_rescale: bool,
141
+ rescale_factor: float,
142
+ do_normalize: bool,
143
+ image_mean: float | list[float] | None,
144
+ image_std: float | list[float] | None,
145
+ return_tensors: str | TensorType | None,
146
+ max_image_size: int = 980,
147
+ min_image_size: int = 336,
148
+ split_resolutions: list[list[int]] | None = None,
149
+ split_image: bool = False,
150
+ resample: "PILImageResampling | None" = None,
151
+ **kwargs,
152
+ ) -> BatchFeature:
153
+ if max_image_size not in [490, 980]:
154
+ raise ValueError("max_image_size must be either 490 or 980")
155
+
156
+ pixel_values = []
157
+ pixel_masks = []
158
+ num_crops = None
159
+
160
+ for image in images:
161
+ if split_image:
162
+ crop_images = self.get_image_patches(image, split_resolutions, max_image_size, resample)
163
+ else:
164
+ crop_images = [image]
165
+
166
+ if num_crops is None or len(crop_images) > num_crops:
167
+ num_crops = len(crop_images)
168
+
169
+ for crop_image in crop_images:
170
+ h, w = crop_image.shape[-2], crop_image.shape[-1]
171
+ scale = max_image_size / max(h, w)
172
+ if w >= h:
173
+ new_h = max(int(h * scale), min_image_size)
174
+ new_w = max_image_size
175
+ else:
176
+ new_h = max_image_size
177
+ new_w = max(int(w * scale), min_image_size)
178
+
179
+ crop_image = self.resize(crop_image, SizeDict(height=new_h, width=new_w), resample)
180
+
181
+ padding_bottom = max_image_size - new_h
182
+ padding_right = max_image_size - new_w
183
+ crop_image = np.pad(
184
+ crop_image, ((0, 0), (0, padding_bottom), (0, padding_right)), mode="constant", constant_values=0
185
+ )
186
+
187
+ pixel_mask = np.zeros((max_image_size, max_image_size), dtype=bool)
188
+ pixel_mask[:new_h, :new_w] = True
189
+ pixel_masks.append(pixel_mask)
190
+
191
+ if do_rescale:
192
+ crop_image = self.rescale(crop_image, rescale_factor)
193
+ if do_normalize:
194
+ crop_image = self.normalize(crop_image, image_mean, image_std)
195
+
196
+ pixel_values.append(crop_image)
197
+
198
+ return BatchFeature(
199
+ data={
200
+ "pixel_values": np.stack(pixel_values, axis=0),
201
+ "pixel_mask": np.stack(pixel_masks, axis=0),
202
+ "num_crops": num_crops,
203
+ },
204
+ tensor_type=return_tensors,
205
+ )
206
+
207
+ def get_number_of_image_patches(self, height: int, width: int, images_kwargs=None):
208
+ """
209
+ A utility that returns number of image patches for a given image size.
210
+
211
+ Args:
212
+ height (`int`):
213
+ Height of the input image.
214
+ width (`int`):
215
+ Width of the input image.
216
+ images_kwargs (`dict`, *optional*):
217
+ Any kwargs to override defaults of the image processor.
218
+
219
+ Returns:
220
+ `int`: Number of patches per image.
221
+ """
222
+ split_image = images_kwargs.get("split_image", self.split_image)
223
+ max_image_size = images_kwargs.get("max_image_size", self.max_image_size)
224
+
225
+ resized_height, resized_width = select_best_resolution((height, width), self.split_resolutions)
226
+ num_patches = 1 if not split_image else resized_height // max_image_size * resized_width // max_image_size
227
+ return num_patches
228
+
229
+
230
+ __all__ = ["AriaImageProcessorPil"]
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/modeling_aria.py ADDED
@@ -0,0 +1,1198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/aria/modular_aria.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_aria.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2024 The Rhymes-AI Teams Authors and The HuggingFace Inc. team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ from collections.abc import Callable
21
+ from dataclasses import dataclass
22
+ from typing import Optional
23
+
24
+ import torch
25
+ from torch import nn
26
+
27
+ from ... import initialization as init
28
+ from ...activations import ACT2FN
29
+ from ...cache_utils import Cache, DynamicCache
30
+ from ...generation import GenerationMixin
31
+ from ...integrations import use_kernel_forward_from_hub, use_kernel_func_from_hub, use_kernelized_func
32
+ from ...masking_utils import create_causal_mask
33
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
34
+ from ...modeling_layers import GradientCheckpointingLayer
35
+ from ...modeling_outputs import (
36
+ BaseModelOutputWithPast,
37
+ BaseModelOutputWithPooling,
38
+ CausalLMOutputWithPast,
39
+ ModelOutput,
40
+ )
41
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
42
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
43
+ from ...processing_utils import Unpack
44
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, torch_compilable_check
45
+ from ...utils.generic import maybe_autocast, merge_with_config_defaults
46
+ from ...utils.output_capturing import capture_outputs
47
+ from ..auto import AutoModel
48
+ from .configuration_aria import AriaConfig, AriaTextConfig
49
+
50
+
51
+ @use_kernel_forward_from_hub("RMSNorm")
52
+ class AriaTextRMSNorm(nn.Module):
53
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
54
+ """
55
+ AriaTextRMSNorm is equivalent to T5LayerNorm
56
+ """
57
+ super().__init__()
58
+ self.weight = nn.Parameter(torch.ones(hidden_size))
59
+ self.variance_epsilon = eps
60
+
61
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
62
+ input_dtype = hidden_states.dtype
63
+ hidden_states = hidden_states.to(torch.float32)
64
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
65
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
66
+ return self.weight * hidden_states.to(input_dtype)
67
+
68
+ def extra_repr(self):
69
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
70
+
71
+
72
+ class AriaProjectorMLP(nn.Module):
73
+ """
74
+ Feed-Forward Network module for the Aria Projector.
75
+
76
+ Args:
77
+ in_features (`int`):
78
+ Input embedding dimension.
79
+ hidden_features (`int`):
80
+ Hidden dimension of the feed-forward network.
81
+ output_dim (`int`):
82
+ Output dimension.
83
+ """
84
+
85
+ def __init__(self, in_features, hidden_features, output_dim):
86
+ super().__init__()
87
+ self.linear_in = nn.Linear(in_features, hidden_features, bias=False)
88
+ self.linear_out = nn.Linear(hidden_features, output_dim, bias=False)
89
+ self.act = ACT2FN["gelu_new"]
90
+
91
+ def forward(self, hidden_states):
92
+ hidden_states = self.act(self.linear_in(hidden_states))
93
+ hidden_states = self.linear_out(hidden_states)
94
+ return hidden_states
95
+
96
+
97
+ class AriaCrossAttention(nn.Module):
98
+ """
99
+ Aria Cross-Attention module.
100
+
101
+ Args:
102
+ config (`AriaConfig`):
103
+ The configuration to use.
104
+ """
105
+
106
+ def __init__(self, config: AriaConfig, dropout_rate: float = 0):
107
+ super().__init__()
108
+ hidden_size = config.vision_config.hidden_size
109
+ num_heads = config.vision_config.num_attention_heads
110
+ self.num_heads = num_heads
111
+ self.q_proj = nn.Linear(hidden_size, hidden_size, bias=False)
112
+ self.k_proj = nn.Linear(hidden_size, hidden_size, bias=False)
113
+ self.v_proj = nn.Linear(hidden_size, hidden_size, bias=False)
114
+
115
+ # Original code here: https://github.com/rhymes-ai/Aria/blob/719ff4e52b727443cba3793b0e27fe64e0244fe1/aria/model/projector.py#L48
116
+ self.multihead_attn = nn.MultiheadAttention(hidden_size, num_heads, batch_first=True)
117
+ self.linear = nn.Linear(hidden_size, hidden_size)
118
+ self.dropout = nn.Dropout(dropout_rate)
119
+
120
+ self.layer_norm = nn.LayerNorm(hidden_size)
121
+ self.layer_norm_kv = nn.LayerNorm(hidden_size)
122
+
123
+ def forward(self, key_value_states, hidden_states, attn_mask=None):
124
+ """
125
+ Forward pass of the AriaCrossAttention module.
126
+
127
+ Args:
128
+ key_value_states (`torch.Tensor`):
129
+ Input tensor for key and value.
130
+ hidden_states (`torch.Tensor`):
131
+ Input tensor for query.
132
+ attn_mask (`torch.Tensor`, *optional*, defaults to None):
133
+ Attention mask.
134
+
135
+ Returns:
136
+ torch.Tensor:
137
+ Output tensor after cross-attention.
138
+ """
139
+ query = self.q_proj(self.layer_norm(hidden_states))
140
+
141
+ key_value_states = self.layer_norm_kv(key_value_states)
142
+ key = self.k_proj(key_value_states)
143
+ value = self.v_proj(key_value_states)
144
+
145
+ attn_output, _ = self.multihead_attn(query, key, value, attn_mask=attn_mask)
146
+
147
+ attn_output = self.dropout(self.linear(attn_output))
148
+
149
+ return attn_output
150
+
151
+
152
+ class AriaProjector(nn.Module):
153
+ """
154
+ Aria Projector module.
155
+
156
+ This module projects vision features into the language model's embedding space, enabling interaction between vision and language components.
157
+
158
+ Args:
159
+ config (`AriaConfig`):
160
+ Configuration object for the model.
161
+ """
162
+
163
+ def __init__(
164
+ self,
165
+ config: AriaConfig,
166
+ ):
167
+ super().__init__()
168
+
169
+ self.patch_to_query_dict = config.projector_patch_to_query_dict
170
+ self.in_features = config.vision_config.hidden_size
171
+ self.num_heads = config.vision_config.num_attention_heads
172
+ self.kv_dim = config.vision_config.hidden_size
173
+ self.hidden_features = config.text_config.hidden_size
174
+ self.output_dim = config.text_config.hidden_size
175
+
176
+ self.query = nn.Parameter(torch.zeros(config.max_value_projector_patch_to_query_dict, self.in_features))
177
+
178
+ self.cross_attn = AriaCrossAttention(config)
179
+
180
+ self.layer_norm = nn.LayerNorm(self.in_features)
181
+ self.feed_forward = AriaProjectorMLP(self.in_features, self.hidden_features, self.output_dim)
182
+
183
+ def forward(self, key_value_states: torch.Tensor, attn_mask: torch.Tensor | None = None):
184
+ """
185
+ Forward pass of the Projector module.
186
+
187
+ Args:
188
+ key_value_states (`torch.Tensor`):
189
+ Input tensor of shape (batch_size, num_patches, kv_dim).
190
+ attn_mask (`torch.Tensor`, *optional*, default is None):
191
+ Attention mask.
192
+
193
+ Returns:
194
+ `torch.Tensor`: Output tensor of shape (batch_size, query_number, output_dim).
195
+ """
196
+ batch_size, num_patches = key_value_states.shape[0], key_value_states.shape[1]
197
+
198
+ if num_patches not in self.patch_to_query_dict:
199
+ raise KeyError(
200
+ f"Number of patches {num_patches} not found in patch_to_query_dict amongst possible values {self.patch_to_query_dict.keys()}."
201
+ )
202
+ query_num = self.patch_to_query_dict[num_patches]
203
+
204
+ queries = self.query[:query_num].unsqueeze(0).repeat(batch_size, 1, 1)
205
+
206
+ if attn_mask is not None:
207
+ attn_mask = attn_mask.repeat_interleave(self.num_heads, 0)
208
+ attn_mask = attn_mask.unsqueeze(1).expand(-1, queries.size(1), -1)
209
+
210
+ attention_out = self.cross_attn(key_value_states, queries, attn_mask=attn_mask)
211
+
212
+ out = self.feed_forward(self.layer_norm(attention_out))
213
+
214
+ return out
215
+
216
+
217
+ class AriaSharedExpertsMLP(nn.Module):
218
+ """
219
+ Shared Expert MLP for shared experts.
220
+
221
+ Unlike routed experts, shared experts process all tokens without routing.
222
+ This class reconfigures the intermediate size in comparison to the LlamaMLP.
223
+
224
+ Args:
225
+ config (`AriaTextConfig`): Configuration object for the Aria language model.
226
+ """
227
+
228
+ def __init__(self, config: AriaTextConfig):
229
+ super().__init__()
230
+ self.config = config
231
+ self.hidden_size = config.hidden_size
232
+ self.intermediate_size = config.intermediate_size * config.moe_num_shared_experts
233
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
234
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
235
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
236
+ self.act_fn = ACT2FN[config.hidden_act]
237
+
238
+ def forward(self, x):
239
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
240
+ return down_proj
241
+
242
+
243
+ def sequential_experts_gemm(token_states, expert_weights, tokens_per_expert):
244
+ """
245
+ Compute the matrix multiplication (GEMM) for each expert sequentially. This approach is computationally inefficient, especially when dealing with a large number of experts.
246
+
247
+ Args:
248
+ token_states (torch.Tensor): Input tensor of shape (num_tokens, in_features).
249
+ expert_weights (torch.Tensor): Weight tensor of shape (num_experts, in_features, out_features).
250
+ tokens_per_expert (torch.Tensor): Number of tokens assigned to each expert.
251
+
252
+ Returns:
253
+ torch.Tensor: Output tensor of shape (num_tokens, out_features).
254
+ """
255
+ num_tokens = token_states.shape[0]
256
+ out_features = expert_weights.shape[-1]
257
+ output = torch.zeros(num_tokens, out_features, dtype=token_states.dtype, device=token_states.device)
258
+
259
+ cumsum_num_tokens = torch.cumsum(tokens_per_expert, dim=0)
260
+ # Insert zero at the beginning for offset index's convenience
261
+ zero_tensor = torch.zeros(1, dtype=torch.long, device=cumsum_num_tokens.device)
262
+ cumsum_num_tokens = torch.cat((zero_tensor, cumsum_num_tokens))
263
+
264
+ for expert_num in range(expert_weights.shape[0]):
265
+ start = cumsum_num_tokens[expert_num]
266
+ end = cumsum_num_tokens[expert_num + 1]
267
+ tokens = token_states[start:end]
268
+
269
+ out = torch.matmul(tokens, expert_weights[expert_num])
270
+ output[start:end] = out
271
+ return output
272
+
273
+
274
+ class AriaGroupedExpertsGemm(nn.Module):
275
+ """
276
+ Grouped GEMM (General Matrix Multiplication) module for efficient expert computation.
277
+ This module utilizes the grouped_gemm library (https://github.com/fanshiqing/grouped_gemm)
278
+ for optimized performance. If the grouped_gemm library is not installed, it gracefully
279
+ falls back to a sequential GEMM implementation, which may be slower but ensures
280
+ functionality.
281
+
282
+ Args:
283
+ in_features (`int`):
284
+ Number of input features.
285
+ out_features (`int`):
286
+ Number of output features.
287
+ groups (`int`):
288
+ Number of expert groups.
289
+ """
290
+
291
+ def __init__(self, in_features, out_features, groups):
292
+ super().__init__()
293
+ self.in_features = in_features
294
+ self.out_features = out_features
295
+ self.groups = groups
296
+ self.weight = nn.Parameter(torch.empty(groups, in_features, out_features))
297
+
298
+ def forward(self, input, tokens_per_expert):
299
+ """
300
+ Perform grouped matrix multiplication.
301
+
302
+ Args:
303
+ input (`torch.Tensor`):
304
+ Input tensor of shape (num_tokens, in_features).
305
+ tokens_per_expert (`torch.Tensor`):
306
+ Number of tokens assigned to each expert.
307
+
308
+ Returns:
309
+ torch.Tensor: Output tensor of shape (num_tokens, out_features).
310
+ """
311
+ return sequential_experts_gemm(
312
+ input,
313
+ self.weight,
314
+ tokens_per_expert.cpu(),
315
+ )
316
+
317
+
318
+ class AriaExperts(nn.Module):
319
+ def __init__(self, config: AriaTextConfig) -> None:
320
+ super().__init__()
321
+ self.config = config
322
+ self.fc1 = AriaGroupedExpertsGemm(config.hidden_size, config.intermediate_size * 2, config.moe_num_experts)
323
+ self.fc2 = AriaGroupedExpertsGemm(config.intermediate_size, config.hidden_size, config.moe_num_experts)
324
+
325
+ def route_tokens_to_experts(self, router_logits):
326
+ top_logits, top_indices = torch.topk(router_logits, k=self.config.moe_topk, dim=1)
327
+ scores = nn.functional.softmax(top_logits, dim=-1)
328
+ return top_indices, scores
329
+
330
+ def forward(self, hidden_states, router_logits) -> torch.Tensor:
331
+ top_k_index, top_k_weights = self.route_tokens_to_experts(router_logits)
332
+ original_dtype = top_k_index.dtype
333
+ tokens_per_expert = torch.histc(
334
+ top_k_index.flatten().to(torch.float32),
335
+ bins=self.config.moe_num_experts,
336
+ min=0,
337
+ max=self.config.moe_num_experts - 1,
338
+ ).to(original_dtype)
339
+ indices = top_k_index
340
+
341
+ flatten_indices = indices.view(-1)
342
+ sorted_indices = torch.argsort(flatten_indices)
343
+ permuted_tokens = hidden_states.index_select(0, sorted_indices // self.config.moe_topk)
344
+
345
+ fc1_output = self.fc1(permuted_tokens, tokens_per_expert)
346
+ projection, gate = torch.chunk(fc1_output, 2, dim=-1)
347
+ fc1_output = nn.functional.silu(projection) * gate
348
+ expert_output = self.fc2(fc1_output, tokens_per_expert)
349
+
350
+ unpermuted_tokens = torch.zeros(
351
+ (top_k_weights.shape[0] * self.config.moe_topk, expert_output.size(1)),
352
+ dtype=expert_output.dtype,
353
+ device=expert_output.device,
354
+ )
355
+ unpermuted_tokens.index_copy_(0, sorted_indices, expert_output)
356
+ unpermuted_tokens = unpermuted_tokens.view(-1, self.config.moe_topk, expert_output.size(1))
357
+
358
+ output = (unpermuted_tokens * top_k_weights.unsqueeze(-1)).sum(dim=1)
359
+ return output
360
+
361
+
362
+ class AriaTextMoELayer(nn.Module):
363
+ def __init__(self, config: AriaTextConfig):
364
+ super().__init__()
365
+ self.router = nn.Linear(config.hidden_size, config.moe_num_experts, bias=False)
366
+ self.experts = AriaExperts(config)
367
+ self.shared_experts = AriaSharedExpertsMLP(config)
368
+ self.config = config
369
+
370
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
371
+ original_shape = hidden_states.shape
372
+ hidden_states = hidden_states.view(-1, hidden_states.size(-1))
373
+ router_logits = self.router(hidden_states)
374
+ expert_output = self.experts(hidden_states, router_logits).view(original_shape)
375
+ shared_expert_output = self.shared_experts(hidden_states.view(original_shape))
376
+ return expert_output + shared_expert_output
377
+
378
+
379
+ def rotate_half(x):
380
+ """Rotates half the hidden dims of the input."""
381
+ x1 = x[..., : x.shape[-1] // 2]
382
+ x2 = x[..., x.shape[-1] // 2 :]
383
+ return torch.cat((-x2, x1), dim=-1)
384
+
385
+
386
+ @use_kernel_func_from_hub("rotary_pos_emb")
387
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
388
+ """Applies Rotary Position Embedding to the query and key tensors.
389
+
390
+ Args:
391
+ q (`torch.Tensor`): The query tensor.
392
+ k (`torch.Tensor`): The key tensor.
393
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
394
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
395
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
396
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
397
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
398
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
399
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
400
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
401
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
402
+ Returns:
403
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
404
+ """
405
+ cos = cos.unsqueeze(unsqueeze_dim)
406
+ sin = sin.unsqueeze(unsqueeze_dim)
407
+ q_embed = (q * cos) + (rotate_half(q) * sin)
408
+ k_embed = (k * cos) + (rotate_half(k) * sin)
409
+ return q_embed, k_embed
410
+
411
+
412
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
413
+ """
414
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
415
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
416
+ """
417
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
418
+ if n_rep == 1:
419
+ return hidden_states
420
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
421
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
422
+
423
+
424
+ def eager_attention_forward(
425
+ module: nn.Module,
426
+ query: torch.Tensor,
427
+ key: torch.Tensor,
428
+ value: torch.Tensor,
429
+ attention_mask: torch.Tensor | None,
430
+ scaling: float,
431
+ dropout: float = 0.0,
432
+ **kwargs: Unpack[TransformersKwargs],
433
+ ):
434
+ key_states = repeat_kv(key, module.num_key_value_groups)
435
+ value_states = repeat_kv(value, module.num_key_value_groups)
436
+
437
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
438
+ if attention_mask is not None:
439
+ attn_weights = attn_weights + attention_mask
440
+
441
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
442
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
443
+ attn_output = torch.matmul(attn_weights, value_states)
444
+ attn_output = attn_output.transpose(1, 2).contiguous()
445
+
446
+ return attn_output, attn_weights
447
+
448
+
449
+ @use_kernelized_func(apply_rotary_pos_emb)
450
+ class AriaTextAttention(nn.Module):
451
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
452
+
453
+ def __init__(self, config: AriaTextConfig, layer_idx: int):
454
+ super().__init__()
455
+ self.config = config
456
+ self.layer_idx = layer_idx
457
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
458
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
459
+ self.scaling = self.head_dim**-0.5
460
+ self.attention_dropout = config.attention_dropout
461
+ self.is_causal = True
462
+
463
+ self.q_proj = nn.Linear(
464
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
465
+ )
466
+ self.k_proj = nn.Linear(
467
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
468
+ )
469
+ self.v_proj = nn.Linear(
470
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
471
+ )
472
+ self.o_proj = nn.Linear(
473
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
474
+ )
475
+
476
+ def forward(
477
+ self,
478
+ hidden_states: torch.Tensor,
479
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
480
+ attention_mask: torch.Tensor | None = None,
481
+ past_key_values: Cache | None = None,
482
+ **kwargs: Unpack[TransformersKwargs],
483
+ ) -> tuple[torch.Tensor, torch.Tensor]:
484
+ input_shape = hidden_states.shape[:-1]
485
+ hidden_shape = (*input_shape, -1, self.head_dim)
486
+
487
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
488
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
489
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
490
+
491
+ cos, sin = position_embeddings
492
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
493
+
494
+ if past_key_values is not None:
495
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
496
+
497
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
498
+ self.config._attn_implementation, eager_attention_forward
499
+ )
500
+
501
+ attn_output, attn_weights = attention_interface(
502
+ self,
503
+ query_states,
504
+ key_states,
505
+ value_states,
506
+ attention_mask,
507
+ dropout=0.0 if not self.training else self.attention_dropout,
508
+ scaling=self.scaling,
509
+ **kwargs,
510
+ )
511
+
512
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
513
+ attn_output = self.o_proj(attn_output)
514
+ return attn_output, attn_weights
515
+
516
+
517
+ class AriaTextDecoderLayer(GradientCheckpointingLayer):
518
+ """
519
+ Aria Text Decoder Layer.
520
+
521
+ This class defines a single decoder layer in the language model, incorporating self-attention and Mixture of Experts (MoE) feed-forward network.
522
+
523
+ Args:
524
+ config (`AriaTextConfig`):
525
+ Configuration object for the text component of the model.
526
+ layer_idx (`int`):
527
+ Index of the layer.
528
+ """
529
+
530
+ def __init__(self, config: AriaTextConfig, layer_idx: int):
531
+ super().__init__()
532
+ self.hidden_size = config.hidden_size
533
+
534
+ self.self_attn = AriaTextAttention(config=config, layer_idx=layer_idx)
535
+ self.mlp = AriaTextMoELayer(config)
536
+ self.input_layernorm = AriaTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
537
+ self.post_attention_layernorm = AriaTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
538
+
539
+ def forward(
540
+ self,
541
+ hidden_states: torch.Tensor,
542
+ attention_mask: torch.Tensor | None = None,
543
+ position_ids: torch.LongTensor | None = None,
544
+ past_key_values: Cache | None = None,
545
+ use_cache: bool | None = False,
546
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
547
+ **kwargs: Unpack[TransformersKwargs],
548
+ ) -> torch.Tensor:
549
+ residual = hidden_states
550
+ hidden_states = self.input_layernorm(hidden_states)
551
+ # Self Attention
552
+ hidden_states, _ = self.self_attn(
553
+ hidden_states=hidden_states,
554
+ attention_mask=attention_mask,
555
+ position_ids=position_ids,
556
+ past_key_values=past_key_values,
557
+ use_cache=use_cache,
558
+ position_embeddings=position_embeddings,
559
+ **kwargs,
560
+ )
561
+ hidden_states = residual + hidden_states
562
+
563
+ # Fully Connected
564
+ residual = hidden_states
565
+ hidden_states = self.post_attention_layernorm(hidden_states)
566
+ hidden_states = self.mlp(hidden_states)
567
+ hidden_states = residual + hidden_states
568
+ return hidden_states
569
+
570
+
571
+ @auto_docstring
572
+ class AriaTextPreTrainedModel(PreTrainedModel):
573
+ config: AriaTextConfig
574
+ base_model_prefix = "model"
575
+ input_modalities = ("image", "text")
576
+ _no_split_modules = ["AriaTextDecoderLayer", "AriaGroupedExpertsGemm"]
577
+ supports_gradient_checkpointing = True
578
+ _skip_keys_device_placement = ["past_key_values"]
579
+ _supports_flash_attn = True
580
+ _supports_sdpa = True
581
+
582
+ _supports_attention_backend = True
583
+ _can_record_outputs = {
584
+ "hidden_states": AriaTextDecoderLayer,
585
+ "attentions": AriaTextAttention,
586
+ }
587
+
588
+ @torch.no_grad()
589
+ def _init_weights(self, module):
590
+ super()._init_weights(module)
591
+ if isinstance(module, AriaGroupedExpertsGemm):
592
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
593
+
594
+
595
+ @auto_docstring
596
+ class AriaPreTrainedModel(PreTrainedModel):
597
+ config: AriaConfig
598
+ base_model_prefix = "model"
599
+ supports_gradient_checkpointing = True
600
+ _no_split_modules = ["AriaDecoderLayer"]
601
+ _skip_keys_device_placement = ["past_key_values"]
602
+ _supports_flash_attn = True
603
+ _supports_sdpa = True
604
+ _supports_flex_attn = True
605
+ _can_compile_fullgraph = False # MoE models don't work with torch.compile (dynamic slicing)
606
+ _supports_attention_backend = True
607
+ _can_record_outputs = {
608
+ "hidden_states": AriaTextDecoderLayer,
609
+ "attentions": AriaTextAttention,
610
+ }
611
+
612
+ @torch.no_grad()
613
+ def _init_weights(self, module):
614
+ super()._init_weights(module)
615
+ if isinstance(module, AriaProjector):
616
+ init.trunc_normal_(module.query, std=self.config.initializer_range)
617
+
618
+
619
+ class AriaTextRotaryEmbedding(nn.Module):
620
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
621
+
622
+ def __init__(self, config: AriaTextConfig, device=None):
623
+ super().__init__()
624
+ self.max_seq_len_cached = config.max_position_embeddings
625
+ self.original_max_seq_len = config.max_position_embeddings
626
+
627
+ self.config = config
628
+
629
+ self.rope_type = self.config.rope_parameters["rope_type"]
630
+ rope_init_fn: Callable = self.compute_default_rope_parameters
631
+ if self.rope_type != "default":
632
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
633
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
634
+
635
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
636
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
637
+
638
+ @staticmethod
639
+ def compute_default_rope_parameters(
640
+ config: AriaTextConfig | None = None,
641
+ device: Optional["torch.device"] = None,
642
+ seq_len: int | None = None,
643
+ ) -> tuple["torch.Tensor", float]:
644
+ """
645
+ Computes the inverse frequencies according to the original RoPE implementation
646
+ Args:
647
+ config ([`~transformers.PreTrainedConfig`]):
648
+ The model configuration.
649
+ device (`torch.device`):
650
+ The device to use for initialization of the inverse frequencies.
651
+ seq_len (`int`, *optional*):
652
+ The current sequence length. Unused for this type of RoPE.
653
+ Returns:
654
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
655
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
656
+ """
657
+ base = config.rope_parameters["rope_theta"]
658
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
659
+
660
+ attention_factor = 1.0 # Unused in this type of RoPE
661
+
662
+ # Compute the inverse frequencies
663
+ inv_freq = 1.0 / (
664
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
665
+ )
666
+ return inv_freq, attention_factor
667
+
668
+ @torch.no_grad()
669
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
670
+ def forward(self, x, position_ids):
671
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
672
+ position_ids_expanded = position_ids[:, None, :].float()
673
+
674
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
675
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
676
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
677
+ emb = torch.cat((freqs, freqs), dim=-1)
678
+ cos = emb.cos() * self.attention_scaling
679
+ sin = emb.sin() * self.attention_scaling
680
+
681
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
682
+
683
+
684
+ @auto_docstring
685
+ class AriaTextModel(AriaTextPreTrainedModel):
686
+ def __init__(self, config: AriaTextConfig):
687
+ super().__init__(config)
688
+ self.padding_idx = config.pad_token_id
689
+ self.vocab_size = config.vocab_size
690
+
691
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
692
+ self.layers = nn.ModuleList(
693
+ [AriaTextDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
694
+ )
695
+ self.norm = AriaTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
696
+ self.rotary_emb = AriaTextRotaryEmbedding(config=config)
697
+ self.gradient_checkpointing = False
698
+
699
+ # Initialize weights and apply final processing
700
+ self.post_init()
701
+
702
+ @merge_with_config_defaults
703
+ @capture_outputs
704
+ @auto_docstring
705
+ def forward(
706
+ self,
707
+ input_ids: torch.LongTensor | None = None,
708
+ attention_mask: torch.Tensor | None = None,
709
+ position_ids: torch.LongTensor | None = None,
710
+ past_key_values: Cache | None = None,
711
+ inputs_embeds: torch.FloatTensor | None = None,
712
+ use_cache: bool | None = None,
713
+ **kwargs: Unpack[TransformersKwargs],
714
+ ) -> BaseModelOutputWithPast:
715
+ if (input_ids is None) ^ (inputs_embeds is not None):
716
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
717
+
718
+ if inputs_embeds is None:
719
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
720
+
721
+ if use_cache and past_key_values is None:
722
+ past_key_values = DynamicCache(config=self.config)
723
+
724
+ if position_ids is None:
725
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
726
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
727
+ position_ids = position_ids.unsqueeze(0)
728
+
729
+ causal_mask = create_causal_mask(
730
+ config=self.config,
731
+ inputs_embeds=inputs_embeds,
732
+ attention_mask=attention_mask,
733
+ past_key_values=past_key_values,
734
+ position_ids=position_ids,
735
+ )
736
+
737
+ hidden_states = inputs_embeds
738
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
739
+
740
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
741
+ hidden_states = decoder_layer(
742
+ hidden_states,
743
+ attention_mask=causal_mask,
744
+ position_embeddings=position_embeddings,
745
+ position_ids=position_ids,
746
+ past_key_values=past_key_values,
747
+ use_cache=use_cache,
748
+ **kwargs,
749
+ )
750
+
751
+ hidden_states = self.norm(hidden_states)
752
+ return BaseModelOutputWithPast(
753
+ last_hidden_state=hidden_states,
754
+ past_key_values=past_key_values,
755
+ )
756
+
757
+
758
+ @auto_docstring
759
+ class AriaTextForCausalLM(AriaTextPreTrainedModel, GenerationMixin):
760
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
761
+ _tp_plan = {"lm_head": "colwise_gather_output"}
762
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
763
+
764
+ def __init__(self, config: AriaTextConfig):
765
+ super().__init__(config)
766
+ self.model = AriaTextModel(config)
767
+ self.vocab_size = config.vocab_size
768
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
769
+
770
+ # Initialize weights and apply final processing
771
+ self.post_init()
772
+
773
+ @auto_docstring
774
+ def forward(
775
+ self,
776
+ input_ids: torch.LongTensor | None = None,
777
+ attention_mask: torch.Tensor | None = None,
778
+ position_ids: torch.LongTensor | None = None,
779
+ past_key_values: Cache | None = None,
780
+ inputs_embeds: torch.FloatTensor | None = None,
781
+ labels: torch.LongTensor | None = None,
782
+ use_cache: bool | None = None,
783
+ logits_to_keep: int | torch.Tensor = 0,
784
+ **kwargs: Unpack[TransformersKwargs],
785
+ ) -> CausalLMOutputWithPast:
786
+ r"""
787
+ Example:
788
+
789
+ ```python
790
+ >>> from transformers import AutoTokenizer, AriaTextForCausalLM
791
+
792
+ >>> model = AriaTextForCausalLM.from_pretrained("meta-aria_text/AriaText-2-7b-hf")
793
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-aria_text/AriaText-2-7b-hf")
794
+
795
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
796
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
797
+
798
+ >>> # Generate
799
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
800
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
801
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
802
+ ```"""
803
+ outputs: BaseModelOutputWithPast = self.model(
804
+ input_ids=input_ids,
805
+ attention_mask=attention_mask,
806
+ position_ids=position_ids,
807
+ past_key_values=past_key_values,
808
+ inputs_embeds=inputs_embeds,
809
+ use_cache=use_cache,
810
+ **kwargs,
811
+ )
812
+
813
+ hidden_states = outputs.last_hidden_state
814
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
815
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
816
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
817
+
818
+ loss = None
819
+ if labels is not None:
820
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
821
+
822
+ return CausalLMOutputWithPast(
823
+ loss=loss,
824
+ logits=logits,
825
+ past_key_values=outputs.past_key_values,
826
+ hidden_states=outputs.hidden_states,
827
+ attentions=outputs.attentions,
828
+ )
829
+
830
+
831
+ @auto_docstring(
832
+ custom_intro="""
833
+ Base class for Aria causal language model (or autoregressive) outputs.
834
+ """
835
+ )
836
+ @dataclass
837
+ class AriaCausalLMOutputWithPast(ModelOutput):
838
+ r"""
839
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
840
+ Language modeling loss (for next-token prediction).
841
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
842
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
843
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
844
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
845
+
846
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
847
+ `past_key_values` input) to speed up sequential decoding.
848
+ image_hidden_states (`torch.FloatTensor`, *optional*):
849
+ A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
850
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
851
+ """
852
+
853
+ loss: torch.FloatTensor | None = None
854
+ logits: torch.FloatTensor | None = None
855
+ past_key_values: Cache | None = None
856
+ hidden_states: tuple[torch.FloatTensor] | None = None
857
+ attentions: tuple[torch.FloatTensor] | None = None
858
+ image_hidden_states: torch.FloatTensor | None = None
859
+
860
+
861
+ @auto_docstring(
862
+ custom_intro="""
863
+ Base class for Aria outputs, with hidden states and attentions.
864
+ """
865
+ )
866
+ @dataclass
867
+ class AriaModelOutputWithPast(BaseModelOutputWithPast):
868
+ r"""
869
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
870
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
871
+
872
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
873
+ `past_key_values` input) to speed up sequential decoding.
874
+ image_hidden_states (`torch.FloatTensor`, *optional*):
875
+ A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
876
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
877
+ """
878
+
879
+ image_hidden_states: torch.FloatTensor | None = None
880
+
881
+
882
+ @auto_docstring(
883
+ custom_intro="""
884
+ The Aria model which consists of a vision backbone and a language model, without a language modeling head.
885
+ """
886
+ )
887
+ class AriaModel(AriaPreTrainedModel):
888
+ def __init__(self, config: AriaConfig):
889
+ super().__init__(config)
890
+ self.vision_tower = AutoModel.from_config(config.vision_config)
891
+ self.multi_modal_projector = AriaProjector(config)
892
+ self.language_model = AutoModel.from_config(config.text_config)
893
+ self.post_init()
894
+
895
+ @merge_with_config_defaults
896
+ @can_return_tuple
897
+ @auto_docstring(
898
+ custom_intro="Obtains image last hidden states from the vision tower and apply multimodal projection."
899
+ )
900
+ def get_image_features(
901
+ self,
902
+ pixel_values: torch.FloatTensor,
903
+ pixel_mask: torch.FloatTensor | None = None,
904
+ vision_feature_layer: int | list[int] = -1,
905
+ output_hidden_states: bool | None = None,
906
+ **kwargs: Unpack[TransformersKwargs],
907
+ ) -> tuple | BaseModelOutputWithPooling:
908
+ patch_attention_mask = self._create_patch_attention_mask(pixel_mask)
909
+ image_outputs = self.vision_tower(
910
+ pixel_values,
911
+ patch_attention_mask=patch_attention_mask,
912
+ output_hidden_states=True, # Ignore arg on purpose
913
+ return_dict=True,
914
+ **kwargs,
915
+ )
916
+ image_attn_mask = None
917
+ if patch_attention_mask is not None:
918
+ flattened_mask = patch_attention_mask.flatten(1)
919
+ image_attn_mask = torch.logical_not(flattened_mask)
920
+
921
+ selected_image_feature = image_outputs.hidden_states[vision_feature_layer]
922
+ image_outputs.pooler_output = self.multi_modal_projector(selected_image_feature, attn_mask=image_attn_mask)
923
+
924
+ return image_outputs
925
+
926
+ def get_placeholder_mask(
927
+ self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: torch.FloatTensor
928
+ ):
929
+ """
930
+ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
931
+ equal to the length of multimodal features. If the lengths are different, an error is raised.
932
+ """
933
+ if input_ids is None:
934
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
935
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
936
+ )
937
+ special_image_mask = special_image_mask.all(-1)
938
+ else:
939
+ special_image_mask = input_ids == self.config.image_token_id
940
+
941
+ n_image_tokens = special_image_mask.sum()
942
+ n_image_features = image_features.shape[0] * image_features.shape[1]
943
+ special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
944
+ torch_compilable_check(
945
+ inputs_embeds[special_image_mask].numel() == image_features.numel(),
946
+ f"Image features and image tokens do not match, tokens: {n_image_tokens}, features: {n_image_features}",
947
+ )
948
+ return special_image_mask
949
+
950
+ @can_return_tuple
951
+ @auto_docstring
952
+ def forward(
953
+ self,
954
+ input_ids: torch.LongTensor | None = None,
955
+ pixel_values: torch.FloatTensor | None = None,
956
+ pixel_mask: torch.LongTensor | None = None,
957
+ attention_mask: torch.Tensor | None = None,
958
+ position_ids: torch.LongTensor | None = None,
959
+ past_key_values: Cache | None = None,
960
+ inputs_embeds: torch.FloatTensor | None = None,
961
+ use_cache: bool | None = None,
962
+ **kwargs: Unpack[FlashAttentionKwargs],
963
+ ) -> tuple | AriaModelOutputWithPast:
964
+ if inputs_embeds is None:
965
+ inputs_embeds = self.get_input_embeddings()(input_ids)
966
+
967
+ # 2. Merge text and images
968
+ if pixel_values is not None and inputs_embeds.shape[1] != 1:
969
+ image_features = self.get_image_features(
970
+ pixel_values=pixel_values,
971
+ pixel_mask=pixel_mask,
972
+ vision_feature_layer=self.config.vision_feature_layer,
973
+ return_dict=True,
974
+ ).pooler_output
975
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
976
+ special_image_mask = self.get_placeholder_mask(
977
+ input_ids, inputs_embeds=inputs_embeds, image_features=image_features
978
+ )
979
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
980
+
981
+ outputs = self.language_model(
982
+ attention_mask=attention_mask,
983
+ position_ids=position_ids,
984
+ past_key_values=past_key_values,
985
+ inputs_embeds=inputs_embeds,
986
+ use_cache=use_cache,
987
+ **kwargs,
988
+ )
989
+
990
+ return AriaModelOutputWithPast(
991
+ last_hidden_state=outputs.last_hidden_state,
992
+ past_key_values=outputs.past_key_values if use_cache else None,
993
+ hidden_states=outputs.hidden_states,
994
+ attentions=outputs.attentions,
995
+ image_hidden_states=image_features if pixel_values is not None else None,
996
+ )
997
+
998
+ def _create_patch_attention_mask(self, pixel_mask):
999
+ if pixel_mask is None:
1000
+ return None
1001
+
1002
+ patches_subgrid = pixel_mask.unfold(
1003
+ dimension=1,
1004
+ size=self.vision_tower.config.patch_size,
1005
+ step=self.vision_tower.config.patch_size,
1006
+ )
1007
+ patches_subgrid = patches_subgrid.unfold(
1008
+ dimension=2,
1009
+ size=self.vision_tower.config.patch_size,
1010
+ step=self.vision_tower.config.patch_size,
1011
+ )
1012
+ return (patches_subgrid.sum(dim=(-1, -2)) > 0).bool()
1013
+
1014
+
1015
+ @auto_docstring(
1016
+ custom_intro="""
1017
+ Aria model for conditional generation tasks.
1018
+
1019
+ This model combines a vision tower, a multi-modal projector, and a language model
1020
+ to perform tasks that involve both image and text inputs.
1021
+ """
1022
+ )
1023
+ class AriaForConditionalGeneration(AriaPreTrainedModel, GenerationMixin):
1024
+ _tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
1025
+
1026
+ def __init__(self, config: AriaConfig):
1027
+ super().__init__(config)
1028
+ self.model = AriaModel(config)
1029
+ self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
1030
+ self.post_init()
1031
+
1032
+ def get_output_embeddings(self) -> nn.Module:
1033
+ return self.lm_head
1034
+
1035
+ @auto_docstring
1036
+ def get_image_features(
1037
+ self,
1038
+ pixel_values: torch.FloatTensor,
1039
+ pixel_mask: torch.FloatTensor | None = None,
1040
+ vision_feature_layer: int | list[int] = -1,
1041
+ **kwargs: Unpack[TransformersKwargs],
1042
+ ) -> tuple | BaseModelOutputWithPooling:
1043
+ return self.model.get_image_features(
1044
+ pixel_values=pixel_values,
1045
+ pixel_mask=pixel_mask,
1046
+ vision_feature_layer=vision_feature_layer,
1047
+ **kwargs,
1048
+ )
1049
+
1050
+ @can_return_tuple
1051
+ @auto_docstring
1052
+ def forward(
1053
+ self,
1054
+ input_ids: torch.LongTensor | None = None,
1055
+ pixel_values: torch.FloatTensor | None = None,
1056
+ pixel_mask: torch.LongTensor | None = None,
1057
+ attention_mask: torch.Tensor | None = None,
1058
+ position_ids: torch.LongTensor | None = None,
1059
+ past_key_values: Cache | None = None,
1060
+ inputs_embeds: torch.FloatTensor | None = None,
1061
+ labels: torch.LongTensor | None = None,
1062
+ use_cache: bool | None = None,
1063
+ logits_to_keep: int | torch.Tensor = 0,
1064
+ **kwargs: Unpack[TransformersKwargs],
1065
+ ) -> tuple | AriaCausalLMOutputWithPast:
1066
+ r"""
1067
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1068
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1069
+ config.vocab_size]` or `model.image_token_id` (where `model` is your instance of `AriaForConditionalGeneration`).
1070
+ Tokens with indices set to `model.image_token_id` are ignored (masked), the loss is only
1071
+ computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1072
+
1073
+ Example:
1074
+
1075
+ ```python
1076
+ >>> import httpx
1077
+ >>> from io import BytesIO
1078
+ >>> import torch
1079
+ >>> from PIL import Image
1080
+ >>> from io import BytesIO
1081
+
1082
+ >>> from transformers import AutoProcessor, AutoModel
1083
+ >>> from transformers.image_utils import load_image
1084
+
1085
+ >>> # Note that passing the image urls (instead of the actual pil images) to the processor is also possible
1086
+ >>> image1 = load_image("https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg")
1087
+ >>> image2 = load_image("https://cdn.britannica.com/59/94459-050-DBA42467/Skyline-Chicago.jpg")
1088
+ >>> image3 = load_image("https://cdn.britannica.com/68/170868-050-8DDE8263/Golden-Gate-Bridge-San-Francisco.jpg")
1089
+
1090
+ >>> processor = AutoProcessor.from_pretrained("Rhymes-AI/Aria")
1091
+ >>> model = AutoModel.from_pretrained("Rhymes-AI/Aria", dtype=torch.bfloat16, device_map="auto")
1092
+
1093
+ >>> # Create inputs
1094
+ >>> messages = [
1095
+ ... {
1096
+ ... "role": "user",
1097
+ ... "content": [
1098
+ ... {"type": "image"},
1099
+ ... {"type": "text", "text": "In this image, we can see the city of New York, and more specifically the Statue of Liberty."},
1100
+ ... {"type": "image"},
1101
+ ... {"type": "text", "text": "What can we see in this image?"},
1102
+ ... ]
1103
+ ... },
1104
+ ... {
1105
+ ... "role": "user",
1106
+ ... "content": [
1107
+ ... {"type": "image"},
1108
+ ... {"type": "text", "text": "In which city is that bridge located?"},
1109
+ ... ]
1110
+ ... }
1111
+ ... ]
1112
+
1113
+ >>> prompts = [processor.apply_chat_template([message], add_generation_prompt=True) for message in messages]
1114
+ >>> images = [[image1, image2], [image3]]
1115
+ >>> inputs = processor(text=prompts, images=images, padding=True, return_tensors="pt").to(model.device)
1116
+
1117
+ >>> # Generate
1118
+ >>> generated_ids = model.generate(**inputs, max_new_tokens=256)
1119
+ >>> generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)
1120
+
1121
+ >>> print(generated_texts[0])
1122
+ Assistant: There are buildings, trees, lights, and water visible in this image.
1123
+
1124
+ >>> print(generated_texts[1])
1125
+ Assistant: The bridge is in San Francisco.
1126
+ ```"""
1127
+ outputs = self.model(
1128
+ input_ids=input_ids,
1129
+ pixel_values=pixel_values,
1130
+ pixel_mask=pixel_mask,
1131
+ attention_mask=attention_mask,
1132
+ position_ids=position_ids,
1133
+ past_key_values=past_key_values,
1134
+ inputs_embeds=inputs_embeds,
1135
+ use_cache=use_cache,
1136
+ **kwargs,
1137
+ )
1138
+
1139
+ hidden_states = outputs[0]
1140
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1141
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1142
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1143
+
1144
+ loss = None
1145
+ if labels is not None:
1146
+ loss = self.loss_function(
1147
+ logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
1148
+ )
1149
+
1150
+ return AriaCausalLMOutputWithPast(
1151
+ loss=loss,
1152
+ logits=logits,
1153
+ past_key_values=outputs.past_key_values,
1154
+ hidden_states=outputs.hidden_states,
1155
+ attentions=outputs.attentions,
1156
+ )
1157
+
1158
+ def prepare_inputs_for_generation(
1159
+ self,
1160
+ input_ids,
1161
+ past_key_values=None,
1162
+ inputs_embeds=None,
1163
+ pixel_values=None,
1164
+ pixel_mask=None,
1165
+ attention_mask=None,
1166
+ logits_to_keep=None,
1167
+ is_first_iteration=False,
1168
+ **kwargs,
1169
+ ):
1170
+ model_inputs = super().prepare_inputs_for_generation(
1171
+ input_ids,
1172
+ past_key_values=past_key_values,
1173
+ inputs_embeds=inputs_embeds,
1174
+ attention_mask=attention_mask,
1175
+ logits_to_keep=logits_to_keep,
1176
+ is_first_iteration=is_first_iteration,
1177
+ **kwargs,
1178
+ )
1179
+
1180
+ if is_first_iteration or not kwargs.get("use_cache", True):
1181
+ # Pixel values are used only in the first iteration if available
1182
+ # In subsequent iterations, they are already merged with text and cached
1183
+ # NOTE: first iteration doesn't have to be prefill, it can be the first
1184
+ # iteration with a question and cached system prompt (continue generate from cache)
1185
+ model_inputs["pixel_values"] = pixel_values
1186
+ model_inputs["pixel_mask"] = pixel_mask
1187
+
1188
+ return model_inputs
1189
+
1190
+
1191
+ __all__ = [
1192
+ "AriaForConditionalGeneration",
1193
+ "AriaPreTrainedModel",
1194
+ "AriaTextPreTrainedModel",
1195
+ "AriaTextModel",
1196
+ "AriaModel",
1197
+ "AriaTextForCausalLM",
1198
+ ]
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/modular_aria.py ADDED
@@ -0,0 +1,1156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The Rhymes-AI Teams 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
+ import torch
15
+ from huggingface_hub.dataclasses import strict
16
+ from torch import nn
17
+ from torchvision.transforms.v2 import functional as tvF
18
+
19
+ from ... import initialization as init
20
+ from ...activations import ACT2FN
21
+ from ...cache_utils import Cache
22
+ from ...configuration_utils import PreTrainedConfig
23
+ from ...image_processing_backends import TorchvisionBackend
24
+ from ...image_processing_utils import BatchFeature, get_patch_output_size, select_best_resolution
25
+ from ...image_transforms import divide_to_patches
26
+ from ...image_utils import (
27
+ ChannelDimension,
28
+ ImageInput,
29
+ PILImageResampling,
30
+ SizeDict,
31
+ get_image_size,
32
+ )
33
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
34
+ from ...modeling_outputs import BaseModelOutputWithPooling
35
+ from ...modeling_utils import PreTrainedModel
36
+ from ...processing_utils import ImagesKwargs, MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack
37
+ from ...tokenization_python import PreTokenizedInput, TextInput
38
+ from ...utils import (
39
+ TensorType,
40
+ TransformersKwargs,
41
+ auto_docstring,
42
+ can_return_tuple,
43
+ logging,
44
+ )
45
+ from ..auto import CONFIG_MAPPING, AutoConfig, AutoTokenizer
46
+ from ..llama.configuration_llama import LlamaConfig
47
+ from ..llama.modeling_llama import (
48
+ LlamaAttention,
49
+ LlamaDecoderLayer,
50
+ LlamaForCausalLM,
51
+ LlamaMLP,
52
+ LlamaModel,
53
+ LlamaPreTrainedModel,
54
+ LlamaRMSNorm,
55
+ )
56
+ from ..llava.modeling_llava import (
57
+ LlavaCausalLMOutputWithPast,
58
+ LlavaForConditionalGeneration,
59
+ LlavaModel,
60
+ LlavaModelOutputWithPast,
61
+ )
62
+
63
+
64
+ logger = logging.get_logger(__name__)
65
+
66
+
67
+ def sequential_experts_gemm(token_states, expert_weights, tokens_per_expert):
68
+ """
69
+ Compute the matrix multiplication (GEMM) for each expert sequentially. This approach is computationally inefficient, especially when dealing with a large number of experts.
70
+
71
+ Args:
72
+ token_states (torch.Tensor): Input tensor of shape (num_tokens, in_features).
73
+ expert_weights (torch.Tensor): Weight tensor of shape (num_experts, in_features, out_features).
74
+ tokens_per_expert (torch.Tensor): Number of tokens assigned to each expert.
75
+
76
+ Returns:
77
+ torch.Tensor: Output tensor of shape (num_tokens, out_features).
78
+ """
79
+ num_tokens = token_states.shape[0]
80
+ out_features = expert_weights.shape[-1]
81
+ output = torch.zeros(num_tokens, out_features, dtype=token_states.dtype, device=token_states.device)
82
+
83
+ cumsum_num_tokens = torch.cumsum(tokens_per_expert, dim=0)
84
+ # Insert zero at the beginning for offset index's convenience
85
+ zero_tensor = torch.zeros(1, dtype=torch.long, device=cumsum_num_tokens.device)
86
+ cumsum_num_tokens = torch.cat((zero_tensor, cumsum_num_tokens))
87
+
88
+ for expert_num in range(expert_weights.shape[0]):
89
+ start = cumsum_num_tokens[expert_num]
90
+ end = cumsum_num_tokens[expert_num + 1]
91
+ tokens = token_states[start:end]
92
+
93
+ out = torch.matmul(tokens, expert_weights[expert_num])
94
+ output[start:end] = out
95
+ return output
96
+
97
+
98
+ @auto_docstring(checkpoint="rhymes-ai/Aria")
99
+ @strict
100
+ class AriaTextConfig(LlamaConfig):
101
+ r"""
102
+ moe_num_experts (`int`, *optional*, defaults to 8):
103
+ The number of experts in the MoE layer.
104
+ moe_topk (`int`, *optional*, defaults to 2):
105
+ The number of top experts to route to for each token.
106
+ moe_num_shared_experts (`int`, *optional*, defaults to 2):
107
+ The number of shared experts.
108
+ """
109
+
110
+ model_type = "aria_text"
111
+ base_config_key = "text_config"
112
+ base_model_tp_plan = {
113
+ "layers.*.self_attn.q_proj": "colwise",
114
+ "layers.*.self_attn.k_proj": "colwise",
115
+ "layers.*.self_attn.v_proj": "colwise",
116
+ "layers.*.self_attn.o_proj": "rowwise",
117
+ "layers.*.mlp.shared_experts.gate_proj": "colwise",
118
+ "layers.*.mlp.shared_experts.up_proj": "colwise",
119
+ "layers.*.mlp.shared_experts.down_proj": "rowwise",
120
+ }
121
+
122
+ intermediate_size: int = 4096
123
+ moe_num_experts: int = 8
124
+ moe_topk: int = 2
125
+ moe_num_shared_experts: int = 2
126
+ pad_token_id: int | None = 2
127
+
128
+
129
+ @auto_docstring(checkpoint="rhymes-ai/Aria")
130
+ @strict
131
+ class AriaConfig(PreTrainedConfig):
132
+ r"""
133
+ projector_patch_to_query_dict (`dict`, *optional*):
134
+ Mapping of patch sizes to query dimensions.
135
+ """
136
+
137
+ model_type = "aria"
138
+ attribute_map = {
139
+ "image_token_id": "image_token_index",
140
+ }
141
+ sub_configs = {"text_config": AriaTextConfig, "vision_config": AutoConfig}
142
+
143
+ vision_config: dict | PreTrainedConfig | None = None
144
+ text_config: dict | AriaTextConfig | None = None
145
+ vision_feature_layer: int | list[int] = -1
146
+ projector_patch_to_query_dict: dict | None = None
147
+ image_token_index: int = 9
148
+ initializer_range: float = 0.02
149
+ tie_word_embeddings: bool = False
150
+
151
+ def __post_init__(self, **kwargs):
152
+ # Convert the keys and values of projector_patch_to_query_dict to integers
153
+ # This ensures consistency even if they were provided as strings
154
+ if self.projector_patch_to_query_dict is None:
155
+ self.projector_patch_to_query_dict = {
156
+ 1225: 128,
157
+ 4900: 256,
158
+ }
159
+ self.projector_patch_to_query_dict = {int(k): int(v) for k, v in self.projector_patch_to_query_dict.items()}
160
+ self.max_value_projector_patch_to_query_dict = max(self.projector_patch_to_query_dict.values())
161
+
162
+ if isinstance(self.vision_config, dict):
163
+ self.vision_config["model_type"] = "idefics3_vision"
164
+ self.vision_config = CONFIG_MAPPING[self.vision_config["model_type"]](**self.vision_config)
165
+ elif self.vision_config is None:
166
+ self.vision_config = CONFIG_MAPPING["idefics3_vision"]()
167
+
168
+ if isinstance(self.text_config, dict) and "model_type" in self.text_config:
169
+ self.text_config = AriaTextConfig(**self.text_config)
170
+ elif self.text_config is None:
171
+ self.text_config = AriaTextConfig()
172
+
173
+ super().__post_init__(**kwargs)
174
+
175
+
176
+ class AriaTextRMSNorm(LlamaRMSNorm):
177
+ pass
178
+
179
+
180
+ class AriaProjectorMLP(nn.Module):
181
+ """
182
+ Feed-Forward Network module for the Aria Projector.
183
+
184
+ Args:
185
+ in_features (`int`):
186
+ Input embedding dimension.
187
+ hidden_features (`int`):
188
+ Hidden dimension of the feed-forward network.
189
+ output_dim (`int`):
190
+ Output dimension.
191
+ """
192
+
193
+ def __init__(self, in_features, hidden_features, output_dim):
194
+ super().__init__()
195
+ self.linear_in = nn.Linear(in_features, hidden_features, bias=False)
196
+ self.linear_out = nn.Linear(hidden_features, output_dim, bias=False)
197
+ self.act = ACT2FN["gelu_new"]
198
+
199
+ def forward(self, hidden_states):
200
+ hidden_states = self.act(self.linear_in(hidden_states))
201
+ hidden_states = self.linear_out(hidden_states)
202
+ return hidden_states
203
+
204
+
205
+ class AriaCrossAttention(nn.Module):
206
+ """
207
+ Aria Cross-Attention module.
208
+
209
+ Args:
210
+ config (`AriaConfig`):
211
+ The configuration to use.
212
+ """
213
+
214
+ def __init__(self, config: AriaConfig, dropout_rate: float = 0):
215
+ super().__init__()
216
+ hidden_size = config.vision_config.hidden_size
217
+ num_heads = config.vision_config.num_attention_heads
218
+ self.num_heads = num_heads
219
+ self.q_proj = nn.Linear(hidden_size, hidden_size, bias=False)
220
+ self.k_proj = nn.Linear(hidden_size, hidden_size, bias=False)
221
+ self.v_proj = nn.Linear(hidden_size, hidden_size, bias=False)
222
+
223
+ # Original code here: https://github.com/rhymes-ai/Aria/blob/719ff4e52b727443cba3793b0e27fe64e0244fe1/aria/model/projector.py#L48
224
+ self.multihead_attn = nn.MultiheadAttention(hidden_size, num_heads, batch_first=True)
225
+ self.linear = nn.Linear(hidden_size, hidden_size)
226
+ self.dropout = nn.Dropout(dropout_rate)
227
+
228
+ self.layer_norm = nn.LayerNorm(hidden_size)
229
+ self.layer_norm_kv = nn.LayerNorm(hidden_size)
230
+
231
+ def forward(self, key_value_states, hidden_states, attn_mask=None):
232
+ """
233
+ Forward pass of the AriaCrossAttention module.
234
+
235
+ Args:
236
+ key_value_states (`torch.Tensor`):
237
+ Input tensor for key and value.
238
+ hidden_states (`torch.Tensor`):
239
+ Input tensor for query.
240
+ attn_mask (`torch.Tensor`, *optional*, defaults to None):
241
+ Attention mask.
242
+
243
+ Returns:
244
+ torch.Tensor:
245
+ Output tensor after cross-attention.
246
+ """
247
+ query = self.q_proj(self.layer_norm(hidden_states))
248
+
249
+ key_value_states = self.layer_norm_kv(key_value_states)
250
+ key = self.k_proj(key_value_states)
251
+ value = self.v_proj(key_value_states)
252
+
253
+ attn_output, _ = self.multihead_attn(query, key, value, attn_mask=attn_mask)
254
+
255
+ attn_output = self.dropout(self.linear(attn_output))
256
+
257
+ return attn_output
258
+
259
+
260
+ class AriaProjector(nn.Module):
261
+ """
262
+ Aria Projector module.
263
+
264
+ This module projects vision features into the language model's embedding space, enabling interaction between vision and language components.
265
+
266
+ Args:
267
+ config (`AriaConfig`):
268
+ Configuration object for the model.
269
+ """
270
+
271
+ def __init__(
272
+ self,
273
+ config: AriaConfig,
274
+ ):
275
+ super().__init__()
276
+
277
+ self.patch_to_query_dict = config.projector_patch_to_query_dict
278
+ self.in_features = config.vision_config.hidden_size
279
+ self.num_heads = config.vision_config.num_attention_heads
280
+ self.kv_dim = config.vision_config.hidden_size
281
+ self.hidden_features = config.text_config.hidden_size
282
+ self.output_dim = config.text_config.hidden_size
283
+
284
+ self.query = nn.Parameter(torch.zeros(config.max_value_projector_patch_to_query_dict, self.in_features))
285
+
286
+ self.cross_attn = AriaCrossAttention(config)
287
+
288
+ self.layer_norm = nn.LayerNorm(self.in_features)
289
+ self.feed_forward = AriaProjectorMLP(self.in_features, self.hidden_features, self.output_dim)
290
+
291
+ def forward(self, key_value_states: torch.Tensor, attn_mask: torch.Tensor | None = None):
292
+ """
293
+ Forward pass of the Projector module.
294
+
295
+ Args:
296
+ key_value_states (`torch.Tensor`):
297
+ Input tensor of shape (batch_size, num_patches, kv_dim).
298
+ attn_mask (`torch.Tensor`, *optional*, default is None):
299
+ Attention mask.
300
+
301
+ Returns:
302
+ `torch.Tensor`: Output tensor of shape (batch_size, query_number, output_dim).
303
+ """
304
+ batch_size, num_patches = key_value_states.shape[0], key_value_states.shape[1]
305
+
306
+ if num_patches not in self.patch_to_query_dict:
307
+ raise KeyError(
308
+ f"Number of patches {num_patches} not found in patch_to_query_dict amongst possible values {self.patch_to_query_dict.keys()}."
309
+ )
310
+ query_num = self.patch_to_query_dict[num_patches]
311
+
312
+ queries = self.query[:query_num].unsqueeze(0).repeat(batch_size, 1, 1)
313
+
314
+ if attn_mask is not None:
315
+ attn_mask = attn_mask.repeat_interleave(self.num_heads, 0)
316
+ attn_mask = attn_mask.unsqueeze(1).expand(-1, queries.size(1), -1)
317
+
318
+ attention_out = self.cross_attn(key_value_states, queries, attn_mask=attn_mask)
319
+
320
+ out = self.feed_forward(self.layer_norm(attention_out))
321
+
322
+ return out
323
+
324
+
325
+ class AriaImageProcessorKwargs(ImagesKwargs, total=False):
326
+ r"""
327
+ max_image_size (`int`, *optional*, defaults to `self.max_image_size`):
328
+ Maximum image size. Must be either 490 or 980.
329
+ min_image_size (`int`, *optional*, defaults to `self.min_image_size`):
330
+ Minimum image size. Images smaller than this in any dimension will be scaled up.
331
+ split_resolutions (`list[list[int]]`, *optional*, defaults to `self.split_resolutions`):
332
+ A list of possible resolutions as (height, width) pairs for splitting high-resolution images into patches.
333
+ split_image (`bool`, *optional*, defaults to `self.split_image`):
334
+ Whether to split the image into patches using the best matching resolution from `split_resolutions`.
335
+ """
336
+
337
+ max_image_size: int
338
+ min_image_size: int
339
+ split_resolutions: list[list[int]]
340
+ split_image: bool
341
+
342
+
343
+ @auto_docstring
344
+ class AriaImageProcessor(TorchvisionBackend):
345
+ model_input_names = ["pixel_values", "pixel_mask", "num_crops"]
346
+ valid_kwargs = AriaImageProcessorKwargs
347
+
348
+ resample = PILImageResampling.BICUBIC
349
+ image_mean = [0.5, 0.5, 0.5]
350
+ image_std = [0.5, 0.5, 0.5]
351
+ max_image_size = 980
352
+ min_image_size = 336
353
+ split_image = False
354
+ split_resolutions = None
355
+ do_convert_rgb = True
356
+ do_rescale = True
357
+ do_normalize = True
358
+
359
+ def __init__(self, **kwargs: Unpack[AriaImageProcessorKwargs]):
360
+ if kwargs.get("split_resolutions") is None:
361
+ default_resolutions = [(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (2, 4), (2, 3), (2, 2), (2, 1), (3, 1), (3, 2), (4, 1), (4, 2), (5, 1), (6, 1), (7, 1), (8, 1)] # fmt: skip
362
+ kwargs["split_resolutions"] = [[el[0] * 490, el[1] * 490] for el in default_resolutions]
363
+ super().__init__(**kwargs)
364
+
365
+ def _get_padding_size(self, original_resolution: tuple, target_resolution: tuple) -> list[int]:
366
+ """Get padding size for patching, returns [left, top, right, bottom] for tvF.pad."""
367
+ original_height, original_width = original_resolution
368
+ target_height, target_width = target_resolution
369
+ paste_x, r_x = divmod(target_width - original_width, 2)
370
+ paste_y, r_y = divmod(target_height - original_height, 2)
371
+ return [paste_x, paste_y, paste_x + r_x, paste_y + r_y]
372
+
373
+ def _resize_for_patching(
374
+ self,
375
+ image: "torch.Tensor",
376
+ target_resolution: tuple,
377
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None",
378
+ ) -> "torch.Tensor":
379
+ """Resize an image to a target resolution while maintaining aspect ratio."""
380
+ new_height, new_width = get_patch_output_size(
381
+ image, target_resolution, input_data_format=ChannelDimension.FIRST
382
+ )
383
+ return self.resize(image, SizeDict(height=new_height, width=new_width), resample)
384
+
385
+ def _pad_for_patching(
386
+ self,
387
+ image: "torch.Tensor",
388
+ target_resolution: tuple,
389
+ ) -> "torch.Tensor":
390
+ """Pad an image to a target resolution while maintaining aspect ratio."""
391
+ new_resolution = get_patch_output_size(image, target_resolution, input_data_format=ChannelDimension.FIRST)
392
+ padding = self._get_padding_size(new_resolution, target_resolution)
393
+ return tvF.pad(image, padding=padding)
394
+
395
+ def get_image_patches(
396
+ self,
397
+ image: "torch.Tensor",
398
+ grid_pinpoints: list[list[int]],
399
+ patch_size: int,
400
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None",
401
+ ) -> list["torch.Tensor"]:
402
+ """
403
+ Process an image with variable resolutions by dividing it into patches.
404
+
405
+ Args:
406
+ image (`torch.Tensor`):
407
+ The input image to be processed (channels-first format).
408
+ grid_pinpoints (`list[list[int]]`):
409
+ A list of possible resolutions as (height, width) pairs.
410
+ patch_size (`int`):
411
+ Size of each square patch to divide the image into.
412
+ resample (`PILImageResampling | tvF.InterpolationMode | int | None`):
413
+ Resampling filter to use when resizing.
414
+
415
+ Returns:
416
+ `list[torch.Tensor]`: A list of image patches in channels-first format.
417
+ """
418
+ if not isinstance(grid_pinpoints, list):
419
+ raise TypeError("grid_pinpoints must be a list of possible resolutions.")
420
+
421
+ image_size = get_image_size(image, channel_dim=ChannelDimension.FIRST)
422
+ best_resolution = select_best_resolution(image_size, grid_pinpoints)
423
+ resized_image = self._resize_for_patching(image, best_resolution, resample)
424
+ padded_image = self._pad_for_patching(resized_image, best_resolution)
425
+ patches = divide_to_patches(padded_image, patch_size=patch_size)
426
+ return patches
427
+
428
+ def _preprocess(
429
+ self,
430
+ images: list["torch.Tensor"],
431
+ do_rescale: bool,
432
+ rescale_factor: float,
433
+ do_normalize: bool,
434
+ image_mean: float | list[float] | None,
435
+ image_std: float | list[float] | None,
436
+ disable_grouping: bool | None,
437
+ return_tensors: str | TensorType | None,
438
+ max_image_size: int = 980,
439
+ min_image_size: int = 336,
440
+ split_resolutions: list[list[int]] | None = None,
441
+ split_image: bool = False,
442
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None" = None,
443
+ **kwargs,
444
+ ) -> BatchFeature:
445
+ if max_image_size not in [490, 980]:
446
+ raise ValueError("max_image_size must be either 490 or 980")
447
+
448
+ pixel_masks = []
449
+ processed_crops = []
450
+ num_crops = None
451
+
452
+ for image in images:
453
+ if split_image:
454
+ crop_images = self.get_image_patches(image, split_resolutions, max_image_size, resample)
455
+ else:
456
+ crop_images = [image]
457
+
458
+ if num_crops is None or len(crop_images) > num_crops:
459
+ num_crops = len(crop_images)
460
+
461
+ for crop_image in crop_images:
462
+ h, w = crop_image.shape[-2], crop_image.shape[-1]
463
+ scale = max_image_size / max(h, w)
464
+ if w >= h:
465
+ new_h = max(int(h * scale), min_image_size)
466
+ new_w = max_image_size
467
+ else:
468
+ new_h = max_image_size
469
+ new_w = max(int(w * scale), min_image_size)
470
+
471
+ crop_image = self.resize(crop_image, SizeDict(height=new_h, width=new_w), resample)
472
+
473
+ padding_bottom = max_image_size - new_h
474
+ padding_right = max_image_size - new_w
475
+ crop_image = tvF.pad(crop_image, [0, 0, padding_right, padding_bottom])
476
+
477
+ pixel_mask = torch.zeros((max_image_size, max_image_size), dtype=torch.bool)
478
+ pixel_mask[:new_h, :new_w] = True
479
+ pixel_masks.append(pixel_mask)
480
+ processed_crops.append(crop_image)
481
+
482
+ stacked_images = torch.stack(processed_crops, dim=0)
483
+ stacked_images = self.rescale_and_normalize(
484
+ stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
485
+ )
486
+ stacked_masks = torch.stack(pixel_masks, dim=0)
487
+
488
+ return BatchFeature(
489
+ data={
490
+ "pixel_values": stacked_images,
491
+ "pixel_mask": stacked_masks,
492
+ "num_crops": num_crops,
493
+ },
494
+ tensor_type=return_tensors,
495
+ )
496
+
497
+ def get_number_of_image_patches(self, height: int, width: int, images_kwargs=None):
498
+ """
499
+ A utility that returns number of image patches for a given image size.
500
+
501
+ Args:
502
+ height (`int`):
503
+ Height of the input image.
504
+ width (`int`):
505
+ Width of the input image.
506
+ images_kwargs (`dict`, *optional*):
507
+ Any kwargs to override defaults of the image processor.
508
+
509
+ Returns:
510
+ `int`: Number of patches per image.
511
+ """
512
+ split_image = images_kwargs.get("split_image", self.split_image)
513
+ max_image_size = images_kwargs.get("max_image_size", self.max_image_size)
514
+
515
+ resized_height, resized_width = select_best_resolution((height, width), self.split_resolutions)
516
+ num_patches = 1 if not split_image else resized_height // max_image_size * resized_width // max_image_size
517
+ return num_patches
518
+
519
+
520
+ class AriaImagesKwargs(ImagesKwargs, total=False):
521
+ """
522
+ split_image (`bool`, *optional*, defaults to `False`):
523
+ Whether to split large images into multiple crops. When enabled, images exceeding the maximum size are
524
+ divided into overlapping crops that are processed separately and then combined. This allows processing
525
+ of very high-resolution images that exceed the model's input size limits.
526
+ max_image_size (`int`, *optional*, defaults to `980`):
527
+ Maximum image size (in pixels) for a single image crop. Images larger than this will be split into
528
+ multiple crops when `split_image=True`, or resized if splitting is disabled. This parameter controls
529
+ the maximum resolution of individual image patches processed by the model.
530
+ min_image_size (`int`, *optional*):
531
+ Minimum image size (in pixels) for a single image crop. Images smaller than this will be upscaled to
532
+ meet the minimum requirement. If not specified, images are processed at their original size (subject
533
+ to the maximum size constraint).
534
+ """
535
+
536
+ split_image: bool
537
+ max_image_size: int
538
+ min_image_size: int
539
+
540
+
541
+ class AriaProcessorKwargs(ProcessingKwargs, total=False):
542
+ images_kwargs: AriaImagesKwargs
543
+
544
+ _defaults = {
545
+ "text_kwargs": {
546
+ "padding": False,
547
+ "return_mm_token_type_ids": False,
548
+ },
549
+ "images_kwargs": {
550
+ "max_image_size": 980,
551
+ "split_image": False,
552
+ },
553
+ "return_tensors": TensorType.PYTORCH,
554
+ }
555
+
556
+
557
+ @auto_docstring
558
+ class AriaProcessor(ProcessorMixin):
559
+ def __init__(
560
+ self,
561
+ image_processor=None,
562
+ tokenizer: AutoTokenizer | str = None,
563
+ chat_template: str | None = None,
564
+ size_conversion: dict[float | int, int] | None = None,
565
+ ):
566
+ r"""
567
+ size_conversion (`Dict`, *optional*):
568
+ A dictionary indicating size conversions for images.
569
+ """
570
+ if size_conversion is None:
571
+ size_conversion = {490: 128, 980: 256}
572
+ self.size_conversion = {int(k): v for k, v in size_conversion.items()}
573
+
574
+ self.image_token = tokenizer.image_token
575
+ self.image_token_id = tokenizer.image_token_id
576
+ if tokenizer is not None and tokenizer.pad_token is None:
577
+ tokenizer.pad_token = tokenizer.unk_token
578
+
579
+ super().__init__(image_processor, tokenizer, chat_template=chat_template)
580
+
581
+ @auto_docstring
582
+ def __call__(
583
+ self,
584
+ text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput],
585
+ images: ImageInput | None = None,
586
+ **kwargs: Unpack[AriaProcessorKwargs],
587
+ ) -> BatchFeature:
588
+ r"""
589
+ Returns:
590
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
591
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
592
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
593
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
594
+ `None`).
595
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
596
+ - **pixel_mask** -- Pixel mask to be fed to a model. Returned when `images` is not `None`.
597
+ """
598
+ output_kwargs = self._merge_kwargs(
599
+ AriaProcessorKwargs,
600
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
601
+ **kwargs,
602
+ )
603
+
604
+ if isinstance(text, str):
605
+ text = [text]
606
+ elif not isinstance(text, list) and not isinstance(text[0], str):
607
+ raise TypeError("Invalid input text. Please provide a string, or a list of strings")
608
+
609
+ if images is not None:
610
+ image_inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
611
+ # expand the image_token according to the num_crops and tokens per image
612
+ tokens_per_image = self.size_conversion[image_inputs.pixel_values.shape[2]]
613
+ prompt_strings = []
614
+ num_crops = image_inputs.pop("num_crops") * tokens_per_image
615
+ for sample in text:
616
+ sample = sample.replace(self.tokenizer.image_token, self.tokenizer.image_token * num_crops)
617
+ prompt_strings.append(sample)
618
+
619
+ else:
620
+ image_inputs = {}
621
+ prompt_strings = text
622
+
623
+ return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
624
+ return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", False)
625
+ text_inputs = self.tokenizer(prompt_strings, **output_kwargs["text_kwargs"], return_tensors=None)
626
+ self._check_special_mm_tokens(prompt_strings, text_inputs, modalities=["image"])
627
+
628
+ if return_mm_token_type_ids:
629
+ text_inputs["mm_token_type_ids"] = self.create_mm_token_type_ids(text_inputs["input_ids"])
630
+ return BatchFeature(data={**text_inputs, **image_inputs}, tensor_type=return_tensors)
631
+
632
+ def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
633
+ """
634
+ Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
635
+ Args:
636
+ image_sizes (`list[list[int]]`, *optional*):
637
+ The input sizes formatted as (height, width) per each image.
638
+ Returns:
639
+ `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
640
+ input modalities, along with other useful data.
641
+ """
642
+
643
+ vision_data = {}
644
+ if image_sizes is not None:
645
+ images_kwargs = AriaProcessorKwargs._defaults.get("images_kwargs", {})
646
+ images_kwargs.update(kwargs)
647
+
648
+ max_size = images_kwargs.get("max_image_size", None) or self.image_processor.max_image_size
649
+ num_image_patches = [
650
+ self.image_processor.get_number_of_image_patches(*image_size, images_kwargs)
651
+ for image_size in image_sizes
652
+ ]
653
+ num_image_tokens = [self.size_conversion[max_size] * num_patches for num_patches in num_image_patches]
654
+ vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
655
+
656
+ return MultiModalData(**vision_data)
657
+
658
+ @property
659
+ def model_input_names(self):
660
+ tokenizer_input_names = self.tokenizer.model_input_names
661
+ image_processor_input_names = self.image_processor.model_input_names
662
+
663
+ # Remove `num_crops`, it is popped and used only when processing. Make a copy of list when removing
664
+ # otherwise `self.image_processor.model_input_names` is also modified
665
+ image_processor_input_names = [name for name in image_processor_input_names if name != "num_crops"]
666
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
667
+
668
+
669
+ class AriaSharedExpertsMLP(LlamaMLP):
670
+ """
671
+ Shared Expert MLP for shared experts.
672
+
673
+ Unlike routed experts, shared experts process all tokens without routing.
674
+ This class reconfigures the intermediate size in comparison to the LlamaMLP.
675
+
676
+ Args:
677
+ config (`AriaTextConfig`): Configuration object for the Aria language model.
678
+ """
679
+
680
+ def __init__(self, config: AriaTextConfig):
681
+ super().__init__(config)
682
+ self.intermediate_size = config.intermediate_size * config.moe_num_shared_experts
683
+
684
+
685
+ class AriaGroupedExpertsGemm(nn.Module):
686
+ """
687
+ Grouped GEMM (General Matrix Multiplication) module for efficient expert computation.
688
+ This module utilizes the grouped_gemm library (https://github.com/fanshiqing/grouped_gemm)
689
+ for optimized performance. If the grouped_gemm library is not installed, it gracefully
690
+ falls back to a sequential GEMM implementation, which may be slower but ensures
691
+ functionality.
692
+
693
+ Args:
694
+ in_features (`int`):
695
+ Number of input features.
696
+ out_features (`int`):
697
+ Number of output features.
698
+ groups (`int`):
699
+ Number of expert groups.
700
+ """
701
+
702
+ def __init__(self, in_features, out_features, groups):
703
+ super().__init__()
704
+ self.in_features = in_features
705
+ self.out_features = out_features
706
+ self.groups = groups
707
+ self.weight = nn.Parameter(torch.empty(groups, in_features, out_features))
708
+
709
+ def forward(self, input, tokens_per_expert):
710
+ """
711
+ Perform grouped matrix multiplication.
712
+
713
+ Args:
714
+ input (`torch.Tensor`):
715
+ Input tensor of shape (num_tokens, in_features).
716
+ tokens_per_expert (`torch.Tensor`):
717
+ Number of tokens assigned to each expert.
718
+
719
+ Returns:
720
+ torch.Tensor: Output tensor of shape (num_tokens, out_features).
721
+ """
722
+ return sequential_experts_gemm(
723
+ input,
724
+ self.weight,
725
+ tokens_per_expert.cpu(),
726
+ )
727
+
728
+
729
+ class AriaExperts(nn.Module):
730
+ def __init__(self, config: AriaTextConfig) -> None:
731
+ super().__init__()
732
+ self.config = config
733
+ self.fc1 = AriaGroupedExpertsGemm(config.hidden_size, config.intermediate_size * 2, config.moe_num_experts)
734
+ self.fc2 = AriaGroupedExpertsGemm(config.intermediate_size, config.hidden_size, config.moe_num_experts)
735
+
736
+ def route_tokens_to_experts(self, router_logits):
737
+ top_logits, top_indices = torch.topk(router_logits, k=self.config.moe_topk, dim=1)
738
+ scores = nn.functional.softmax(top_logits, dim=-1)
739
+ return top_indices, scores
740
+
741
+ def forward(self, hidden_states, router_logits) -> torch.Tensor:
742
+ top_k_index, top_k_weights = self.route_tokens_to_experts(router_logits)
743
+ original_dtype = top_k_index.dtype
744
+ tokens_per_expert = torch.histc(
745
+ top_k_index.flatten().to(torch.float32),
746
+ bins=self.config.moe_num_experts,
747
+ min=0,
748
+ max=self.config.moe_num_experts - 1,
749
+ ).to(original_dtype)
750
+ indices = top_k_index
751
+
752
+ flatten_indices = indices.view(-1)
753
+ sorted_indices = torch.argsort(flatten_indices)
754
+ permuted_tokens = hidden_states.index_select(0, sorted_indices // self.config.moe_topk)
755
+
756
+ fc1_output = self.fc1(permuted_tokens, tokens_per_expert)
757
+ projection, gate = torch.chunk(fc1_output, 2, dim=-1)
758
+ fc1_output = nn.functional.silu(projection) * gate
759
+ expert_output = self.fc2(fc1_output, tokens_per_expert)
760
+
761
+ unpermuted_tokens = torch.zeros(
762
+ (top_k_weights.shape[0] * self.config.moe_topk, expert_output.size(1)),
763
+ dtype=expert_output.dtype,
764
+ device=expert_output.device,
765
+ )
766
+ unpermuted_tokens.index_copy_(0, sorted_indices, expert_output)
767
+ unpermuted_tokens = unpermuted_tokens.view(-1, self.config.moe_topk, expert_output.size(1))
768
+
769
+ output = (unpermuted_tokens * top_k_weights.unsqueeze(-1)).sum(dim=1)
770
+ return output
771
+
772
+
773
+ class AriaTextMoELayer(nn.Module):
774
+ def __init__(self, config: AriaTextConfig):
775
+ super().__init__()
776
+ self.router = nn.Linear(config.hidden_size, config.moe_num_experts, bias=False)
777
+ self.experts = AriaExperts(config)
778
+ self.shared_experts = AriaSharedExpertsMLP(config)
779
+ self.config = config
780
+
781
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
782
+ original_shape = hidden_states.shape
783
+ hidden_states = hidden_states.view(-1, hidden_states.size(-1))
784
+ router_logits = self.router(hidden_states)
785
+ expert_output = self.experts(hidden_states, router_logits).view(original_shape)
786
+ shared_expert_output = self.shared_experts(hidden_states.view(original_shape))
787
+ return expert_output + shared_expert_output
788
+
789
+
790
+ class AriaTextAttention(LlamaAttention):
791
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
792
+
793
+
794
+ class AriaTextDecoderLayer(LlamaDecoderLayer):
795
+ """
796
+ Aria Text Decoder Layer.
797
+
798
+ This class defines a single decoder layer in the language model, incorporating self-attention and Mixture of Experts (MoE) feed-forward network.
799
+
800
+ Args:
801
+ config (`AriaTextConfig`):
802
+ Configuration object for the text component of the model.
803
+ layer_idx (`int`):
804
+ Index of the layer.
805
+ """
806
+
807
+ def __init__(self, config: AriaTextConfig, layer_idx: int):
808
+ super().__init__(config, layer_idx)
809
+ self.mlp = AriaTextMoELayer(config)
810
+
811
+
812
+ @auto_docstring
813
+ class AriaTextPreTrainedModel(PreTrainedModel):
814
+ config: AriaTextConfig
815
+ base_model_prefix = "model"
816
+ input_modalities = ("image", "text")
817
+ _no_split_modules = ["AriaTextDecoderLayer", "AriaGroupedExpertsGemm"]
818
+ supports_gradient_checkpointing = True
819
+ _skip_keys_device_placement = ["past_key_values"]
820
+ _supports_flash_attn = True
821
+ _supports_sdpa = True
822
+
823
+ _supports_attention_backend = True
824
+ _can_record_outputs = {
825
+ "hidden_states": AriaTextDecoderLayer,
826
+ "attentions": AriaTextAttention,
827
+ }
828
+
829
+ @torch.no_grad()
830
+ def _init_weights(self, module):
831
+ super()._init_weights(module)
832
+ if isinstance(module, AriaGroupedExpertsGemm):
833
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
834
+
835
+
836
+ class AriaPreTrainedModel(LlamaPreTrainedModel):
837
+ config: AriaConfig
838
+ base_model_prefix = "model"
839
+ _can_compile_fullgraph = False # MoE models don't work with torch.compile (dynamic slicing)
840
+ _supports_attention_backend = True
841
+
842
+ @torch.no_grad()
843
+ def _init_weights(self, module):
844
+ PreTrainedModel._init_weights(self, module)
845
+ if isinstance(module, AriaProjector):
846
+ init.trunc_normal_(module.query, std=self.config.initializer_range)
847
+
848
+
849
+ class AriaTextModel(LlamaModel):
850
+ def __init__(self, config: AriaTextConfig):
851
+ super().__init__(config)
852
+ self.layers = nn.ModuleList(
853
+ [AriaTextDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
854
+ )
855
+ self.gradient_checkpointing = False
856
+ self.post_init()
857
+
858
+
859
+ class AriaTextForCausalLM(AriaTextPreTrainedModel, LlamaForCausalLM):
860
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
861
+
862
+ def __init__(self, config: AriaTextConfig):
863
+ super().__init__(config)
864
+ self.model = AriaTextModel(config)
865
+ self.vocab_size = config.vocab_size
866
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
867
+
868
+ # Initialize weights and apply final processing
869
+ self.post_init()
870
+
871
+ @auto_docstring
872
+ def forward(self, **super_kwargs):
873
+ super().forward(self, **super_kwargs)
874
+
875
+
876
+ class AriaCausalLMOutputWithPast(LlavaCausalLMOutputWithPast):
877
+ pass
878
+
879
+
880
+ class AriaModelOutputWithPast(LlavaModelOutputWithPast):
881
+ pass
882
+
883
+
884
+ class AriaModel(LlavaModel):
885
+ def __init__(self, config: AriaConfig):
886
+ super().__init__(config)
887
+ self.multi_modal_projector = AriaProjector(config)
888
+
889
+ def _create_patch_attention_mask(self, pixel_mask):
890
+ if pixel_mask is None:
891
+ return None
892
+
893
+ patches_subgrid = pixel_mask.unfold(
894
+ dimension=1,
895
+ size=self.vision_tower.config.patch_size,
896
+ step=self.vision_tower.config.patch_size,
897
+ )
898
+ patches_subgrid = patches_subgrid.unfold(
899
+ dimension=2,
900
+ size=self.vision_tower.config.patch_size,
901
+ step=self.vision_tower.config.patch_size,
902
+ )
903
+ return (patches_subgrid.sum(dim=(-1, -2)) > 0).bool()
904
+
905
+ def get_image_features(
906
+ self,
907
+ pixel_values: torch.FloatTensor,
908
+ pixel_mask: torch.FloatTensor | None = None,
909
+ vision_feature_layer: int | list[int] = -1,
910
+ output_hidden_states: bool | None = None,
911
+ **kwargs: Unpack[TransformersKwargs],
912
+ ) -> tuple | BaseModelOutputWithPooling:
913
+ patch_attention_mask = self._create_patch_attention_mask(pixel_mask)
914
+ image_outputs = self.vision_tower(
915
+ pixel_values,
916
+ patch_attention_mask=patch_attention_mask,
917
+ output_hidden_states=True, # Ignore arg on purpose
918
+ return_dict=True,
919
+ **kwargs,
920
+ )
921
+ image_attn_mask = None
922
+ if patch_attention_mask is not None:
923
+ flattened_mask = patch_attention_mask.flatten(1)
924
+ image_attn_mask = torch.logical_not(flattened_mask)
925
+
926
+ selected_image_feature = image_outputs.hidden_states[vision_feature_layer]
927
+ image_outputs.pooler_output = self.multi_modal_projector(selected_image_feature, attn_mask=image_attn_mask)
928
+
929
+ return image_outputs
930
+
931
+ def forward(
932
+ self,
933
+ input_ids: torch.LongTensor | None = None,
934
+ pixel_values: torch.FloatTensor | None = None,
935
+ pixel_mask: torch.LongTensor | None = None,
936
+ attention_mask: torch.Tensor | None = None,
937
+ position_ids: torch.LongTensor | None = None,
938
+ past_key_values: Cache | None = None,
939
+ inputs_embeds: torch.FloatTensor | None = None,
940
+ use_cache: bool | None = None,
941
+ **kwargs: Unpack[FlashAttentionKwargs],
942
+ ) -> tuple | AriaModelOutputWithPast:
943
+ if inputs_embeds is None:
944
+ inputs_embeds = self.get_input_embeddings()(input_ids)
945
+
946
+ # 2. Merge text and images
947
+ if pixel_values is not None and inputs_embeds.shape[1] != 1:
948
+ image_features = self.get_image_features(
949
+ pixel_values=pixel_values,
950
+ pixel_mask=pixel_mask,
951
+ vision_feature_layer=self.config.vision_feature_layer,
952
+ return_dict=True,
953
+ ).pooler_output
954
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
955
+ special_image_mask = self.get_placeholder_mask(
956
+ input_ids, inputs_embeds=inputs_embeds, image_features=image_features
957
+ )
958
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
959
+
960
+ outputs = self.language_model(
961
+ attention_mask=attention_mask,
962
+ position_ids=position_ids,
963
+ past_key_values=past_key_values,
964
+ inputs_embeds=inputs_embeds,
965
+ use_cache=use_cache,
966
+ **kwargs,
967
+ )
968
+
969
+ return AriaModelOutputWithPast(
970
+ last_hidden_state=outputs.last_hidden_state,
971
+ past_key_values=outputs.past_key_values if use_cache else None,
972
+ hidden_states=outputs.hidden_states,
973
+ attentions=outputs.attentions,
974
+ image_hidden_states=image_features if pixel_values is not None else None,
975
+ )
976
+
977
+
978
+ @auto_docstring(
979
+ custom_intro="""
980
+ Aria model for conditional generation tasks.
981
+
982
+ This model combines a vision tower, a multi-modal projector, and a language model
983
+ to perform tasks that involve both image and text inputs.
984
+ """
985
+ )
986
+ class AriaForConditionalGeneration(LlavaForConditionalGeneration):
987
+ _tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
988
+
989
+ @auto_docstring
990
+ def get_image_features(
991
+ self,
992
+ pixel_values: torch.FloatTensor,
993
+ pixel_mask: torch.FloatTensor | None = None,
994
+ vision_feature_layer: int | list[int] = -1,
995
+ **kwargs: Unpack[TransformersKwargs],
996
+ ) -> tuple | BaseModelOutputWithPooling:
997
+ return self.model.get_image_features(
998
+ pixel_values=pixel_values,
999
+ pixel_mask=pixel_mask,
1000
+ vision_feature_layer=vision_feature_layer,
1001
+ **kwargs,
1002
+ )
1003
+
1004
+ @can_return_tuple
1005
+ @auto_docstring
1006
+ def forward(
1007
+ self,
1008
+ input_ids: torch.LongTensor | None = None,
1009
+ pixel_values: torch.FloatTensor | None = None,
1010
+ pixel_mask: torch.LongTensor | None = None,
1011
+ attention_mask: torch.Tensor | None = None,
1012
+ position_ids: torch.LongTensor | None = None,
1013
+ past_key_values: Cache | None = None,
1014
+ inputs_embeds: torch.FloatTensor | None = None,
1015
+ labels: torch.LongTensor | None = None,
1016
+ use_cache: bool | None = None,
1017
+ logits_to_keep: int | torch.Tensor = 0,
1018
+ **kwargs: Unpack[TransformersKwargs],
1019
+ ) -> tuple | AriaCausalLMOutputWithPast:
1020
+ r"""
1021
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1022
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1023
+ config.vocab_size]` or `model.image_token_id` (where `model` is your instance of `AriaForConditionalGeneration`).
1024
+ Tokens with indices set to `model.image_token_id` are ignored (masked), the loss is only
1025
+ computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1026
+
1027
+ Example:
1028
+
1029
+ ```python
1030
+ >>> import httpx
1031
+ >>> from io import BytesIO
1032
+ >>> import torch
1033
+ >>> from PIL import Image
1034
+ >>> from io import BytesIO
1035
+
1036
+ >>> from transformers import AutoProcessor, AutoModel
1037
+ >>> from transformers.image_utils import load_image
1038
+
1039
+ >>> # Note that passing the image urls (instead of the actual pil images) to the processor is also possible
1040
+ >>> image1 = load_image("https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg")
1041
+ >>> image2 = load_image("https://cdn.britannica.com/59/94459-050-DBA42467/Skyline-Chicago.jpg")
1042
+ >>> image3 = load_image("https://cdn.britannica.com/68/170868-050-8DDE8263/Golden-Gate-Bridge-San-Francisco.jpg")
1043
+
1044
+ >>> processor = AutoProcessor.from_pretrained("Rhymes-AI/Aria")
1045
+ >>> model = AutoModel.from_pretrained("Rhymes-AI/Aria", dtype=torch.bfloat16, device_map="auto")
1046
+
1047
+ >>> # Create inputs
1048
+ >>> messages = [
1049
+ ... {
1050
+ ... "role": "user",
1051
+ ... "content": [
1052
+ ... {"type": "image"},
1053
+ ... {"type": "text", "text": "In this image, we can see the city of New York, and more specifically the Statue of Liberty."},
1054
+ ... {"type": "image"},
1055
+ ... {"type": "text", "text": "What can we see in this image?"},
1056
+ ... ]
1057
+ ... },
1058
+ ... {
1059
+ ... "role": "user",
1060
+ ... "content": [
1061
+ ... {"type": "image"},
1062
+ ... {"type": "text", "text": "In which city is that bridge located?"},
1063
+ ... ]
1064
+ ... }
1065
+ ... ]
1066
+
1067
+ >>> prompts = [processor.apply_chat_template([message], add_generation_prompt=True) for message in messages]
1068
+ >>> images = [[image1, image2], [image3]]
1069
+ >>> inputs = processor(text=prompts, images=images, padding=True, return_tensors="pt").to(model.device)
1070
+
1071
+ >>> # Generate
1072
+ >>> generated_ids = model.generate(**inputs, max_new_tokens=256)
1073
+ >>> generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)
1074
+
1075
+ >>> print(generated_texts[0])
1076
+ Assistant: There are buildings, trees, lights, and water visible in this image.
1077
+
1078
+ >>> print(generated_texts[1])
1079
+ Assistant: The bridge is in San Francisco.
1080
+ ```"""
1081
+ outputs = self.model(
1082
+ input_ids=input_ids,
1083
+ pixel_values=pixel_values,
1084
+ pixel_mask=pixel_mask,
1085
+ attention_mask=attention_mask,
1086
+ position_ids=position_ids,
1087
+ past_key_values=past_key_values,
1088
+ inputs_embeds=inputs_embeds,
1089
+ use_cache=use_cache,
1090
+ **kwargs,
1091
+ )
1092
+
1093
+ hidden_states = outputs[0]
1094
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1095
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1096
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1097
+
1098
+ loss = None
1099
+ if labels is not None:
1100
+ loss = self.loss_function(
1101
+ logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
1102
+ )
1103
+
1104
+ return AriaCausalLMOutputWithPast(
1105
+ loss=loss,
1106
+ logits=logits,
1107
+ past_key_values=outputs.past_key_values,
1108
+ hidden_states=outputs.hidden_states,
1109
+ attentions=outputs.attentions,
1110
+ )
1111
+
1112
+ def prepare_inputs_for_generation(
1113
+ self,
1114
+ input_ids,
1115
+ past_key_values=None,
1116
+ inputs_embeds=None,
1117
+ pixel_values=None,
1118
+ pixel_mask=None,
1119
+ attention_mask=None,
1120
+ logits_to_keep=None,
1121
+ is_first_iteration=False,
1122
+ **kwargs,
1123
+ ):
1124
+ model_inputs = super().prepare_inputs_for_generation(
1125
+ input_ids,
1126
+ past_key_values=past_key_values,
1127
+ inputs_embeds=inputs_embeds,
1128
+ attention_mask=attention_mask,
1129
+ logits_to_keep=logits_to_keep,
1130
+ is_first_iteration=is_first_iteration,
1131
+ **kwargs,
1132
+ )
1133
+
1134
+ if is_first_iteration or not kwargs.get("use_cache", True):
1135
+ # Pixel values are used only in the first iteration if available
1136
+ # In subsequent iterations, they are already merged with text and cached
1137
+ # NOTE: first iteration doesn't have to be prefill, it can be the first
1138
+ # iteration with a question and cached system prompt (continue generate from cache)
1139
+ model_inputs["pixel_values"] = pixel_values
1140
+ model_inputs["pixel_mask"] = pixel_mask
1141
+
1142
+ return model_inputs
1143
+
1144
+
1145
+ __all__ = [
1146
+ "AriaConfig",
1147
+ "AriaTextConfig",
1148
+ "AriaImageProcessor",
1149
+ "AriaProcessor",
1150
+ "AriaForConditionalGeneration",
1151
+ "AriaPreTrainedModel",
1152
+ "AriaTextPreTrainedModel",
1153
+ "AriaTextModel",
1154
+ "AriaModel",
1155
+ "AriaTextForCausalLM",
1156
+ ]
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/processing_aria.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/aria/modular_aria.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_aria.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2024 The Rhymes-AI Teams Authors and The HuggingFace Inc. team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ from ...image_processing_utils import BatchFeature
21
+ from ...image_utils import ImageInput
22
+ from ...processing_utils import ImagesKwargs, MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack
23
+ from ...tokenization_python import PreTokenizedInput, TextInput
24
+ from ...utils import TensorType, auto_docstring
25
+ from ..auto import AutoTokenizer
26
+
27
+
28
+ class AriaImagesKwargs(ImagesKwargs, total=False):
29
+ """
30
+ split_image (`bool`, *optional*, defaults to `False`):
31
+ Whether to split large images into multiple crops. When enabled, images exceeding the maximum size are
32
+ divided into overlapping crops that are processed separately and then combined. This allows processing
33
+ of very high-resolution images that exceed the model's input size limits.
34
+ max_image_size (`int`, *optional*, defaults to `980`):
35
+ Maximum image size (in pixels) for a single image crop. Images larger than this will be split into
36
+ multiple crops when `split_image=True`, or resized if splitting is disabled. This parameter controls
37
+ the maximum resolution of individual image patches processed by the model.
38
+ min_image_size (`int`, *optional*):
39
+ Minimum image size (in pixels) for a single image crop. Images smaller than this will be upscaled to
40
+ meet the minimum requirement. If not specified, images are processed at their original size (subject
41
+ to the maximum size constraint).
42
+ """
43
+
44
+ split_image: bool
45
+ max_image_size: int
46
+ min_image_size: int
47
+
48
+
49
+ class AriaProcessorKwargs(ProcessingKwargs, total=False):
50
+ images_kwargs: AriaImagesKwargs
51
+
52
+ _defaults = {
53
+ "text_kwargs": {
54
+ "padding": False,
55
+ "return_mm_token_type_ids": False,
56
+ },
57
+ "images_kwargs": {
58
+ "max_image_size": 980,
59
+ "split_image": False,
60
+ },
61
+ "return_tensors": TensorType.PYTORCH,
62
+ }
63
+
64
+
65
+ @auto_docstring
66
+ class AriaProcessor(ProcessorMixin):
67
+ def __init__(
68
+ self,
69
+ image_processor=None,
70
+ tokenizer: AutoTokenizer | str = None,
71
+ chat_template: str | None = None,
72
+ size_conversion: dict[float | int, int] | None = None,
73
+ ):
74
+ r"""
75
+ size_conversion (`Dict`, *optional*):
76
+ A dictionary indicating size conversions for images.
77
+ """
78
+ if size_conversion is None:
79
+ size_conversion = {490: 128, 980: 256}
80
+ self.size_conversion = {int(k): v for k, v in size_conversion.items()}
81
+
82
+ self.image_token = tokenizer.image_token
83
+ self.image_token_id = tokenizer.image_token_id
84
+ if tokenizer is not None and tokenizer.pad_token is None:
85
+ tokenizer.pad_token = tokenizer.unk_token
86
+
87
+ super().__init__(image_processor, tokenizer, chat_template=chat_template)
88
+
89
+ @auto_docstring
90
+ def __call__(
91
+ self,
92
+ text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput],
93
+ images: ImageInput | None = None,
94
+ **kwargs: Unpack[AriaProcessorKwargs],
95
+ ) -> BatchFeature:
96
+ r"""
97
+ Returns:
98
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
99
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
100
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
101
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
102
+ `None`).
103
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
104
+ - **pixel_mask** -- Pixel mask to be fed to a model. Returned when `images` is not `None`.
105
+ """
106
+ output_kwargs = self._merge_kwargs(
107
+ AriaProcessorKwargs,
108
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
109
+ **kwargs,
110
+ )
111
+
112
+ if isinstance(text, str):
113
+ text = [text]
114
+ elif not isinstance(text, list) and not isinstance(text[0], str):
115
+ raise TypeError("Invalid input text. Please provide a string, or a list of strings")
116
+
117
+ if images is not None:
118
+ image_inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
119
+ # expand the image_token according to the num_crops and tokens per image
120
+ tokens_per_image = self.size_conversion[image_inputs.pixel_values.shape[2]]
121
+ prompt_strings = []
122
+ num_crops = image_inputs.pop("num_crops") * tokens_per_image
123
+ for sample in text:
124
+ sample = sample.replace(self.tokenizer.image_token, self.tokenizer.image_token * num_crops)
125
+ prompt_strings.append(sample)
126
+
127
+ else:
128
+ image_inputs = {}
129
+ prompt_strings = text
130
+
131
+ return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
132
+ return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", False)
133
+ text_inputs = self.tokenizer(prompt_strings, **output_kwargs["text_kwargs"], return_tensors=None)
134
+ self._check_special_mm_tokens(prompt_strings, text_inputs, modalities=["image"])
135
+
136
+ if return_mm_token_type_ids:
137
+ text_inputs["mm_token_type_ids"] = self.create_mm_token_type_ids(text_inputs["input_ids"])
138
+ return BatchFeature(data={**text_inputs, **image_inputs}, tensor_type=return_tensors)
139
+
140
+ def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
141
+ """
142
+ Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
143
+ Args:
144
+ image_sizes (`list[list[int]]`, *optional*):
145
+ The input sizes formatted as (height, width) per each image.
146
+ Returns:
147
+ `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
148
+ input modalities, along with other useful data.
149
+ """
150
+
151
+ vision_data = {}
152
+ if image_sizes is not None:
153
+ images_kwargs = AriaProcessorKwargs._defaults.get("images_kwargs", {})
154
+ images_kwargs.update(kwargs)
155
+
156
+ max_size = images_kwargs.get("max_image_size", None) or self.image_processor.max_image_size
157
+ num_image_patches = [
158
+ self.image_processor.get_number_of_image_patches(*image_size, images_kwargs)
159
+ for image_size in image_sizes
160
+ ]
161
+ num_image_tokens = [self.size_conversion[max_size] * num_patches for num_patches in num_image_patches]
162
+ vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
163
+
164
+ return MultiModalData(**vision_data)
165
+
166
+ @property
167
+ def model_input_names(self):
168
+ tokenizer_input_names = self.tokenizer.model_input_names
169
+ image_processor_input_names = self.image_processor.model_input_names
170
+
171
+ # Remove `num_crops`, it is popped and used only when processing. Make a copy of list when removing
172
+ # otherwise `self.image_processor.model_input_names` is also modified
173
+ image_processor_input_names = [name for name in image_processor_input_names if name != "num_crops"]
174
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
175
+
176
+
177
+ __all__ = ["AriaProcessor"]
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/autoformer/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (793 Bytes). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/autoformer/__pycache__/configuration_autoformer.cpython-311.pyc ADDED
Binary file (8.93 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__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_bert import *
22
+ from .modeling_bert import *
23
+ from .tokenization_bert 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__)
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (814 Bytes). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__pycache__/configuration_bert.cpython-311.pyc ADDED
Binary file (2.65 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__pycache__/modeling_bert.cpython-311.pyc ADDED
Binary file (68.8 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__pycache__/tokenization_bert.cpython-311.pyc ADDED
Binary file (6.96 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__pycache__/tokenization_bert_legacy.cpython-311.pyc ADDED
Binary file (23.3 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/configuration_bert.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
2
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """BERT model configuration"""
16
+
17
+ from huggingface_hub.dataclasses import strict
18
+
19
+ from ...configuration_utils import PreTrainedConfig
20
+ from ...utils import auto_docstring
21
+
22
+
23
+ @auto_docstring(checkpoint="google-bert/bert-base-uncased")
24
+ @strict
25
+ class BertConfig(PreTrainedConfig):
26
+ r"""
27
+ Examples:
28
+
29
+ ```python
30
+ >>> from transformers import BertConfig, BertModel
31
+
32
+ >>> # Initializing a BERT google-bert/bert-base-uncased style configuration
33
+ >>> configuration = BertConfig()
34
+
35
+ >>> # Initializing a model (with random weights) from the google-bert/bert-base-uncased style configuration
36
+ >>> model = BertModel(configuration)
37
+
38
+ >>> # Accessing the model configuration
39
+ >>> configuration = model.config
40
+ ```"""
41
+
42
+ model_type = "bert"
43
+
44
+ vocab_size: int = 30522
45
+ hidden_size: int = 768
46
+ num_hidden_layers: int = 12
47
+ num_attention_heads: int = 12
48
+ intermediate_size: int = 3072
49
+ hidden_act: str = "gelu"
50
+ hidden_dropout_prob: float | int = 0.1
51
+ attention_probs_dropout_prob: float | int = 0.1
52
+ max_position_embeddings: int = 512
53
+ type_vocab_size: int = 2
54
+ initializer_range: float = 0.02
55
+ layer_norm_eps: float = 1e-12
56
+ pad_token_id: int | None = 0
57
+ use_cache: bool = True
58
+ classifier_dropout: float | int | None = None
59
+ is_decoder: bool = False
60
+ add_cross_attention: bool = False
61
+ bos_token_id: int | None = None
62
+ eos_token_id: int | list[int] | None = None
63
+ tie_word_embeddings: bool = True
64
+
65
+
66
+ __all__ = ["BertConfig"]
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/modeling_bert.py ADDED
@@ -0,0 +1,1394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
2
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch BERT model."""
16
+
17
+ from collections.abc import Callable
18
+ from dataclasses import dataclass
19
+
20
+ import torch
21
+ from torch import nn
22
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
23
+
24
+ from ... import initialization as init
25
+ from ...activations import ACT2FN
26
+ from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
27
+ from ...generation import GenerationMixin
28
+ from ...masking_utils import create_bidirectional_mask, create_causal_mask
29
+ from ...modeling_layers import GradientCheckpointingLayer
30
+ from ...modeling_outputs import (
31
+ BaseModelOutputWithPastAndCrossAttentions,
32
+ BaseModelOutputWithPoolingAndCrossAttentions,
33
+ CausalLMOutputWithCrossAttentions,
34
+ MaskedLMOutput,
35
+ MultipleChoiceModelOutput,
36
+ NextSentencePredictorOutput,
37
+ QuestionAnsweringModelOutput,
38
+ SequenceClassifierOutput,
39
+ TokenClassifierOutput,
40
+ )
41
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
42
+ from ...processing_utils import Unpack
43
+ from ...pytorch_utils import apply_chunking_to_forward
44
+ from ...utils import ModelOutput, TransformersKwargs, auto_docstring, logging
45
+ from ...utils.generic import can_return_tuple, merge_with_config_defaults
46
+ from ...utils.output_capturing import capture_outputs
47
+ from .configuration_bert import BertConfig
48
+
49
+
50
+ logger = logging.get_logger(__name__)
51
+
52
+
53
+ class BertEmbeddings(nn.Module):
54
+ """Construct the embeddings from word, position and token_type embeddings."""
55
+
56
+ def __init__(self, config):
57
+ super().__init__()
58
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
59
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
60
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
61
+
62
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
63
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
64
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
65
+ self.register_buffer(
66
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
67
+ )
68
+ self.register_buffer(
69
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
70
+ )
71
+
72
+ def forward(
73
+ self,
74
+ input_ids: torch.LongTensor | None = None,
75
+ token_type_ids: torch.LongTensor | None = None,
76
+ position_ids: torch.LongTensor | None = None,
77
+ inputs_embeds: torch.FloatTensor | None = None,
78
+ past_key_values_length: int = 0,
79
+ ) -> torch.Tensor:
80
+ if input_ids is not None:
81
+ input_shape = input_ids.size()
82
+ else:
83
+ input_shape = inputs_embeds.size()[:-1]
84
+
85
+ batch_size, seq_length = input_shape
86
+
87
+ if position_ids is None:
88
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
89
+
90
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
91
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
92
+ # issue #5664
93
+ if token_type_ids is None:
94
+ if hasattr(self, "token_type_ids"):
95
+ # NOTE: We assume either pos ids to have bsz == 1 (broadcastable) or bsz == effective bsz (input_shape[0])
96
+ buffered_token_type_ids = self.token_type_ids.expand(position_ids.shape[0], -1)
97
+ buffered_token_type_ids = torch.gather(buffered_token_type_ids, dim=1, index=position_ids)
98
+ token_type_ids = buffered_token_type_ids.expand(batch_size, seq_length)
99
+ else:
100
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
101
+
102
+ if inputs_embeds is None:
103
+ inputs_embeds = self.word_embeddings(input_ids)
104
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
105
+ embeddings = inputs_embeds + token_type_embeddings
106
+
107
+ position_embeddings = self.position_embeddings(position_ids)
108
+ embeddings = embeddings + position_embeddings
109
+
110
+ embeddings = self.LayerNorm(embeddings)
111
+ embeddings = self.dropout(embeddings)
112
+ return embeddings
113
+
114
+
115
+ def eager_attention_forward(
116
+ module: nn.Module,
117
+ query: torch.Tensor,
118
+ key: torch.Tensor,
119
+ value: torch.Tensor,
120
+ attention_mask: torch.Tensor | None,
121
+ scaling: float | None = None,
122
+ dropout: float = 0.0,
123
+ **kwargs: Unpack[TransformersKwargs],
124
+ ):
125
+ if scaling is None:
126
+ scaling = query.size(-1) ** -0.5
127
+
128
+ # Take the dot product between "query" and "key" to get the raw attention scores.
129
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
130
+
131
+ if attention_mask is not None:
132
+ attn_weights = attn_weights + attention_mask
133
+
134
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
135
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
136
+
137
+ attn_output = torch.matmul(attn_weights, value)
138
+ attn_output = attn_output.transpose(1, 2).contiguous()
139
+
140
+ return attn_output, attn_weights
141
+
142
+
143
+ class BertSelfAttention(nn.Module):
144
+ def __init__(self, config, is_causal=False, layer_idx=None):
145
+ super().__init__()
146
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
147
+ raise ValueError(
148
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
149
+ f"heads ({config.num_attention_heads})"
150
+ )
151
+ self.config = config
152
+
153
+ self.num_attention_heads = config.num_attention_heads
154
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
155
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
156
+ self.scaling = self.attention_head_size**-0.5
157
+
158
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
159
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
160
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
161
+
162
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
163
+
164
+ self.is_decoder = config.is_decoder
165
+ self.is_causal = is_causal
166
+ self.layer_idx = layer_idx
167
+
168
+ def forward(
169
+ self,
170
+ hidden_states: torch.Tensor,
171
+ attention_mask: torch.FloatTensor | None = None,
172
+ past_key_values: Cache | None = None,
173
+ **kwargs: Unpack[TransformersKwargs],
174
+ ) -> tuple[torch.Tensor]:
175
+ input_shape = hidden_states.shape[:-1]
176
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
177
+
178
+ # get all proj
179
+ query_layer = self.query(hidden_states).view(*hidden_shape).transpose(1, 2)
180
+ key_layer = self.key(hidden_states).view(*hidden_shape).transpose(1, 2)
181
+ value_layer = self.value(hidden_states).view(*hidden_shape).transpose(1, 2)
182
+
183
+ if past_key_values is not None:
184
+ # decoder-only bert can have a simple dynamic cache for example
185
+ current_past_key_values = past_key_values
186
+ if isinstance(past_key_values, EncoderDecoderCache):
187
+ current_past_key_values = past_key_values.self_attention_cache
188
+
189
+ # save all key/value_layer to cache to be re-used for fast auto-regressive generation
190
+ key_layer, value_layer = current_past_key_values.update(key_layer, value_layer, self.layer_idx)
191
+
192
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
193
+ self.config._attn_implementation, eager_attention_forward
194
+ )
195
+
196
+ attn_output, attn_weights = attention_interface(
197
+ self,
198
+ query_layer,
199
+ key_layer,
200
+ value_layer,
201
+ attention_mask,
202
+ dropout=0.0 if not self.training else self.dropout.p,
203
+ scaling=self.scaling,
204
+ **kwargs,
205
+ )
206
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
207
+ return attn_output, attn_weights
208
+
209
+
210
+ class BertCrossAttention(nn.Module):
211
+ def __init__(self, config, is_causal=False, layer_idx=None):
212
+ super().__init__()
213
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
214
+ raise ValueError(
215
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
216
+ f"heads ({config.num_attention_heads})"
217
+ )
218
+ self.config = config
219
+
220
+ self.num_attention_heads = config.num_attention_heads
221
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
222
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
223
+ self.scaling = self.attention_head_size**-0.5
224
+
225
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
226
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
227
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
228
+
229
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
230
+
231
+ self.is_causal = is_causal
232
+ self.layer_idx = layer_idx
233
+
234
+ def forward(
235
+ self,
236
+ hidden_states: torch.Tensor,
237
+ encoder_hidden_states: torch.FloatTensor | None = None,
238
+ attention_mask: torch.FloatTensor | None = None,
239
+ past_key_values: EncoderDecoderCache | None = None,
240
+ **kwargs: Unpack[TransformersKwargs],
241
+ ) -> tuple[torch.Tensor]:
242
+ # determine input shapes
243
+ input_shape = hidden_states.shape[:-1]
244
+
245
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
246
+
247
+ # get query proj
248
+ query_layer = self.query(hidden_states).view(hidden_shape).transpose(1, 2)
249
+
250
+ is_updated = past_key_values.is_updated.get(self.layer_idx) if past_key_values is not None else False
251
+ if past_key_values is not None and is_updated:
252
+ # reuse k,v, cross_attentions
253
+ key_layer = past_key_values.cross_attention_cache.layers[self.layer_idx].keys
254
+ value_layer = past_key_values.cross_attention_cache.layers[self.layer_idx].values
255
+ else:
256
+ kv_shape = (*encoder_hidden_states.shape[:-1], -1, self.attention_head_size)
257
+ key_layer = self.key(encoder_hidden_states).view(kv_shape).transpose(1, 2)
258
+ value_layer = self.value(encoder_hidden_states).view(kv_shape).transpose(1, 2)
259
+
260
+ if past_key_values is not None:
261
+ # save all states to the cache
262
+ key_layer, value_layer = past_key_values.cross_attention_cache.update(
263
+ key_layer, value_layer, self.layer_idx
264
+ )
265
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
266
+ past_key_values.is_updated[self.layer_idx] = True
267
+
268
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
269
+ self.config._attn_implementation, eager_attention_forward
270
+ )
271
+
272
+ attn_output, attn_weights = attention_interface(
273
+ self,
274
+ query_layer,
275
+ key_layer,
276
+ value_layer,
277
+ attention_mask,
278
+ dropout=0.0 if not self.training else self.dropout.p,
279
+ scaling=self.scaling,
280
+ **kwargs,
281
+ )
282
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
283
+ return attn_output, attn_weights
284
+
285
+
286
+ class BertSelfOutput(nn.Module):
287
+ def __init__(self, config):
288
+ super().__init__()
289
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
290
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
291
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
292
+
293
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
294
+ hidden_states = self.dense(hidden_states)
295
+ hidden_states = self.dropout(hidden_states)
296
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
297
+ return hidden_states
298
+
299
+
300
+ class BertAttention(nn.Module):
301
+ def __init__(self, config, is_causal=False, layer_idx=None, is_cross_attention=False):
302
+ super().__init__()
303
+ self.is_cross_attention = is_cross_attention
304
+ attention_class = BertCrossAttention if is_cross_attention else BertSelfAttention
305
+ self.self = attention_class(config, is_causal=is_causal, layer_idx=layer_idx)
306
+ self.output = BertSelfOutput(config)
307
+
308
+ def forward(
309
+ self,
310
+ hidden_states: torch.Tensor,
311
+ attention_mask: torch.FloatTensor | None = None,
312
+ encoder_hidden_states: torch.FloatTensor | None = None,
313
+ encoder_attention_mask: torch.FloatTensor | None = None,
314
+ past_key_values: Cache | None = None,
315
+ **kwargs: Unpack[TransformersKwargs],
316
+ ) -> tuple[torch.Tensor]:
317
+ attention_mask = attention_mask if not self.is_cross_attention else encoder_attention_mask
318
+ attention_output, attn_weights = self.self(
319
+ hidden_states,
320
+ encoder_hidden_states=encoder_hidden_states,
321
+ attention_mask=attention_mask,
322
+ past_key_values=past_key_values,
323
+ **kwargs,
324
+ )
325
+ attention_output = self.output(attention_output, hidden_states)
326
+ return attention_output, attn_weights
327
+
328
+
329
+ class BertIntermediate(nn.Module):
330
+ def __init__(self, config):
331
+ super().__init__()
332
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
333
+ if isinstance(config.hidden_act, str):
334
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
335
+ else:
336
+ self.intermediate_act_fn = config.hidden_act
337
+
338
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
339
+ hidden_states = self.dense(hidden_states)
340
+ hidden_states = self.intermediate_act_fn(hidden_states)
341
+ return hidden_states
342
+
343
+
344
+ class BertOutput(nn.Module):
345
+ def __init__(self, config):
346
+ super().__init__()
347
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
348
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
349
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
350
+
351
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
352
+ hidden_states = self.dense(hidden_states)
353
+ hidden_states = self.dropout(hidden_states)
354
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
355
+ return hidden_states
356
+
357
+
358
+ class BertLayer(GradientCheckpointingLayer):
359
+ def __init__(self, config, layer_idx=None):
360
+ super().__init__()
361
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
362
+ self.seq_len_dim = 1
363
+ self.attention = BertAttention(config, is_causal=config.is_decoder, layer_idx=layer_idx)
364
+ self.is_decoder = config.is_decoder
365
+ self.add_cross_attention = config.add_cross_attention
366
+ if self.add_cross_attention:
367
+ if not self.is_decoder:
368
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
369
+ self.crossattention = BertAttention(
370
+ config,
371
+ is_causal=False,
372
+ layer_idx=layer_idx,
373
+ is_cross_attention=True,
374
+ )
375
+ self.intermediate = BertIntermediate(config)
376
+ self.output = BertOutput(config)
377
+
378
+ def forward(
379
+ self,
380
+ hidden_states: torch.Tensor,
381
+ attention_mask: torch.FloatTensor | None = None,
382
+ encoder_hidden_states: torch.FloatTensor | None = None,
383
+ encoder_attention_mask: torch.FloatTensor | None = None,
384
+ past_key_values: Cache | None = None,
385
+ **kwargs: Unpack[TransformersKwargs],
386
+ ) -> torch.Tensor:
387
+ self_attention_output, _ = self.attention(
388
+ hidden_states,
389
+ attention_mask,
390
+ past_key_values=past_key_values,
391
+ **kwargs,
392
+ )
393
+ attention_output = self_attention_output
394
+
395
+ if self.is_decoder and encoder_hidden_states is not None:
396
+ if not hasattr(self, "crossattention"):
397
+ raise ValueError(
398
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
399
+ " by setting `config.add_cross_attention=True`"
400
+ )
401
+
402
+ cross_attention_output, _ = self.crossattention(
403
+ self_attention_output,
404
+ None, # attention_mask
405
+ encoder_hidden_states,
406
+ encoder_attention_mask,
407
+ past_key_values=past_key_values,
408
+ **kwargs,
409
+ )
410
+ attention_output = cross_attention_output
411
+
412
+ layer_output = apply_chunking_to_forward(
413
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
414
+ )
415
+ return layer_output
416
+
417
+ def feed_forward_chunk(self, attention_output):
418
+ intermediate_output = self.intermediate(attention_output)
419
+ layer_output = self.output(intermediate_output, attention_output)
420
+ return layer_output
421
+
422
+
423
+ class BertEncoder(nn.Module):
424
+ def __init__(self, config):
425
+ super().__init__()
426
+ self.config = config
427
+ self.layer = nn.ModuleList([BertLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
428
+
429
+ def forward(
430
+ self,
431
+ hidden_states: torch.Tensor,
432
+ attention_mask: torch.FloatTensor | None = None,
433
+ encoder_hidden_states: torch.FloatTensor | None = None,
434
+ encoder_attention_mask: torch.FloatTensor | None = None,
435
+ past_key_values: Cache | None = None,
436
+ use_cache: bool | None = None,
437
+ **kwargs: Unpack[TransformersKwargs],
438
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPastAndCrossAttentions:
439
+ for i, layer_module in enumerate(self.layer):
440
+ hidden_states = layer_module(
441
+ hidden_states,
442
+ attention_mask,
443
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
444
+ encoder_attention_mask=encoder_attention_mask,
445
+ past_key_values=past_key_values,
446
+ **kwargs,
447
+ )
448
+
449
+ return BaseModelOutputWithPastAndCrossAttentions(
450
+ last_hidden_state=hidden_states,
451
+ past_key_values=past_key_values if use_cache else None,
452
+ )
453
+
454
+
455
+ class BertPooler(nn.Module):
456
+ def __init__(self, config):
457
+ super().__init__()
458
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
459
+ self.activation = nn.Tanh()
460
+
461
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
462
+ # We "pool" the model by simply taking the hidden state corresponding
463
+ # to the first token.
464
+ first_token_tensor = hidden_states[:, 0]
465
+ pooled_output = self.dense(first_token_tensor)
466
+ pooled_output = self.activation(pooled_output)
467
+ return pooled_output
468
+
469
+
470
+ class BertPredictionHeadTransform(nn.Module):
471
+ def __init__(self, config):
472
+ super().__init__()
473
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
474
+ if isinstance(config.hidden_act, str):
475
+ self.transform_act_fn = ACT2FN[config.hidden_act]
476
+ else:
477
+ self.transform_act_fn = config.hidden_act
478
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
479
+
480
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
481
+ hidden_states = self.dense(hidden_states)
482
+ hidden_states = self.transform_act_fn(hidden_states)
483
+ hidden_states = self.LayerNorm(hidden_states)
484
+ return hidden_states
485
+
486
+
487
+ class BertLMPredictionHead(nn.Module):
488
+ def __init__(self, config):
489
+ super().__init__()
490
+ self.transform = BertPredictionHeadTransform(config)
491
+
492
+ # The output weights are the same as the input embeddings, but there is
493
+ # an output-only bias for each token.
494
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
495
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
496
+
497
+ def forward(self, hidden_states):
498
+ hidden_states = self.transform(hidden_states)
499
+ hidden_states = self.decoder(hidden_states)
500
+ return hidden_states
501
+
502
+
503
+ class BertOnlyMLMHead(nn.Module):
504
+ def __init__(self, config):
505
+ super().__init__()
506
+ self.predictions = BertLMPredictionHead(config)
507
+
508
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
509
+ prediction_scores = self.predictions(sequence_output)
510
+ return prediction_scores
511
+
512
+
513
+ class BertOnlyNSPHead(nn.Module):
514
+ def __init__(self, config):
515
+ super().__init__()
516
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
517
+
518
+ def forward(self, pooled_output):
519
+ seq_relationship_score = self.seq_relationship(pooled_output)
520
+ return seq_relationship_score
521
+
522
+
523
+ class BertPreTrainingHeads(nn.Module):
524
+ def __init__(self, config):
525
+ super().__init__()
526
+ self.predictions = BertLMPredictionHead(config)
527
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
528
+
529
+ def forward(self, sequence_output, pooled_output):
530
+ prediction_scores = self.predictions(sequence_output)
531
+ seq_relationship_score = self.seq_relationship(pooled_output)
532
+ return prediction_scores, seq_relationship_score
533
+
534
+
535
+ @auto_docstring
536
+ class BertPreTrainedModel(PreTrainedModel):
537
+ config_class = BertConfig
538
+ base_model_prefix = "bert"
539
+ supports_gradient_checkpointing = True
540
+ _supports_flash_attn = True
541
+ _supports_sdpa = True
542
+ _supports_flex_attn = True
543
+ _supports_attention_backend = True
544
+ _can_record_outputs = {
545
+ "hidden_states": BertLayer,
546
+ "attentions": BertSelfAttention,
547
+ "cross_attentions": BertCrossAttention,
548
+ }
549
+
550
+ @torch.no_grad()
551
+ def _init_weights(self, module):
552
+ """Initialize the weights"""
553
+ super()._init_weights(module)
554
+ if isinstance(module, BertLMPredictionHead):
555
+ init.zeros_(module.bias)
556
+ elif isinstance(module, BertEmbeddings):
557
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
558
+ init.zeros_(module.token_type_ids)
559
+
560
+
561
+ @auto_docstring(
562
+ custom_intro="""
563
+ Output type of [`BertForPreTraining`].
564
+ """
565
+ )
566
+ @dataclass
567
+ class BertForPreTrainingOutput(ModelOutput):
568
+ r"""
569
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
570
+ Total loss as the sum of the masked language modeling loss and the next sequence prediction
571
+ (classification) loss.
572
+ prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
573
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
574
+ seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
575
+ Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
576
+ before SoftMax).
577
+ """
578
+
579
+ loss: torch.FloatTensor | None = None
580
+ prediction_logits: torch.FloatTensor | None = None
581
+ seq_relationship_logits: torch.FloatTensor | None = None
582
+ hidden_states: tuple[torch.FloatTensor] | None = None
583
+ attentions: tuple[torch.FloatTensor] | None = None
584
+
585
+
586
+ @auto_docstring(
587
+ custom_intro="""
588
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
589
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
590
+ all you need](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
591
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
592
+
593
+ To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
594
+ to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
595
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
596
+ """
597
+ )
598
+ class BertModel(BertPreTrainedModel):
599
+ _no_split_modules = ["BertEmbeddings", "BertLayer"]
600
+
601
+ def __init__(self, config, add_pooling_layer=True):
602
+ r"""
603
+ add_pooling_layer (bool, *optional*, defaults to `True`):
604
+ Whether to add a pooling layer
605
+ """
606
+ super().__init__(config)
607
+ self.config = config
608
+ self.gradient_checkpointing = False
609
+
610
+ self.embeddings = BertEmbeddings(config)
611
+ self.encoder = BertEncoder(config)
612
+
613
+ self.pooler = BertPooler(config) if add_pooling_layer else None
614
+
615
+ # Initialize weights and apply final processing
616
+ self.post_init()
617
+
618
+ def get_input_embeddings(self):
619
+ return self.embeddings.word_embeddings
620
+
621
+ def set_input_embeddings(self, value):
622
+ self.embeddings.word_embeddings = value
623
+
624
+ @merge_with_config_defaults
625
+ @capture_outputs
626
+ @auto_docstring
627
+ def forward(
628
+ self,
629
+ input_ids: torch.Tensor | None = None,
630
+ attention_mask: torch.Tensor | None = None,
631
+ token_type_ids: torch.Tensor | None = None,
632
+ position_ids: torch.Tensor | None = None,
633
+ inputs_embeds: torch.Tensor | None = None,
634
+ encoder_hidden_states: torch.Tensor | None = None,
635
+ encoder_attention_mask: torch.Tensor | None = None,
636
+ past_key_values: Cache | None = None,
637
+ use_cache: bool | None = None,
638
+ **kwargs: Unpack[TransformersKwargs],
639
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPoolingAndCrossAttentions:
640
+ if (input_ids is None) ^ (inputs_embeds is not None):
641
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
642
+
643
+ if self.config.is_decoder:
644
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
645
+ else:
646
+ use_cache = False
647
+
648
+ if use_cache and past_key_values is None:
649
+ past_key_values = (
650
+ EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
651
+ if encoder_hidden_states is not None or self.config.is_encoder_decoder
652
+ else DynamicCache(config=self.config)
653
+ )
654
+
655
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
656
+
657
+ embedding_output = self.embeddings(
658
+ input_ids=input_ids,
659
+ position_ids=position_ids,
660
+ token_type_ids=token_type_ids,
661
+ inputs_embeds=inputs_embeds,
662
+ past_key_values_length=past_key_values_length,
663
+ )
664
+
665
+ attention_mask, encoder_attention_mask = self._create_attention_masks(
666
+ attention_mask=attention_mask,
667
+ encoder_attention_mask=encoder_attention_mask,
668
+ embedding_output=embedding_output,
669
+ encoder_hidden_states=encoder_hidden_states,
670
+ past_key_values=past_key_values,
671
+ )
672
+
673
+ encoder_outputs = self.encoder(
674
+ embedding_output,
675
+ attention_mask=attention_mask,
676
+ encoder_hidden_states=encoder_hidden_states,
677
+ encoder_attention_mask=encoder_attention_mask,
678
+ past_key_values=past_key_values,
679
+ use_cache=use_cache,
680
+ position_ids=position_ids,
681
+ **kwargs,
682
+ )
683
+ sequence_output = encoder_outputs.last_hidden_state
684
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
685
+
686
+ return BaseModelOutputWithPoolingAndCrossAttentions(
687
+ last_hidden_state=sequence_output,
688
+ pooler_output=pooled_output,
689
+ past_key_values=encoder_outputs.past_key_values,
690
+ )
691
+
692
+ def _create_attention_masks(
693
+ self,
694
+ attention_mask,
695
+ encoder_attention_mask,
696
+ embedding_output,
697
+ encoder_hidden_states,
698
+ past_key_values,
699
+ ):
700
+ if self.config.is_decoder:
701
+ attention_mask = create_causal_mask(
702
+ config=self.config,
703
+ inputs_embeds=embedding_output,
704
+ attention_mask=attention_mask,
705
+ past_key_values=past_key_values,
706
+ )
707
+ else:
708
+ attention_mask = create_bidirectional_mask(
709
+ config=self.config,
710
+ inputs_embeds=embedding_output,
711
+ attention_mask=attention_mask,
712
+ )
713
+
714
+ if encoder_attention_mask is not None:
715
+ encoder_attention_mask = create_bidirectional_mask(
716
+ config=self.config,
717
+ inputs_embeds=embedding_output,
718
+ attention_mask=encoder_attention_mask,
719
+ encoder_hidden_states=encoder_hidden_states,
720
+ )
721
+
722
+ return attention_mask, encoder_attention_mask
723
+
724
+
725
+ @auto_docstring(
726
+ custom_intro="""
727
+ Bert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a `next
728
+ sentence prediction (classification)` head.
729
+ """
730
+ )
731
+ class BertForPreTraining(BertPreTrainedModel):
732
+ _tied_weights_keys = {
733
+ "cls.predictions.decoder.weight": "bert.embeddings.word_embeddings.weight",
734
+ "cls.predictions.decoder.bias": "cls.predictions.bias",
735
+ }
736
+
737
+ def __init__(self, config):
738
+ super().__init__(config)
739
+
740
+ self.bert = BertModel(config)
741
+ self.cls = BertPreTrainingHeads(config)
742
+
743
+ # Initialize weights and apply final processing
744
+ self.post_init()
745
+
746
+ def get_output_embeddings(self):
747
+ return self.cls.predictions.decoder
748
+
749
+ def set_output_embeddings(self, new_embeddings):
750
+ self.cls.predictions.decoder = new_embeddings
751
+ self.cls.predictions.bias = new_embeddings.bias
752
+
753
+ @can_return_tuple
754
+ @auto_docstring
755
+ def forward(
756
+ self,
757
+ input_ids: torch.Tensor | None = None,
758
+ attention_mask: torch.Tensor | None = None,
759
+ token_type_ids: torch.Tensor | None = None,
760
+ position_ids: torch.Tensor | None = None,
761
+ inputs_embeds: torch.Tensor | None = None,
762
+ labels: torch.Tensor | None = None,
763
+ next_sentence_label: torch.Tensor | None = None,
764
+ **kwargs: Unpack[TransformersKwargs],
765
+ ) -> tuple[torch.Tensor] | BertForPreTrainingOutput:
766
+ r"""
767
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
768
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
769
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked),
770
+ the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
771
+ next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
772
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence
773
+ pair (see `input_ids` docstring) Indices should be in `[0, 1]`:
774
+
775
+ - 0 indicates sequence B is a continuation of sequence A,
776
+ - 1 indicates sequence B is a random sequence.
777
+
778
+ Example:
779
+
780
+ ```python
781
+ >>> from transformers import AutoTokenizer, BertForPreTraining
782
+ >>> import torch
783
+
784
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
785
+ >>> model = BertForPreTraining.from_pretrained("google-bert/bert-base-uncased")
786
+
787
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
788
+ >>> outputs = model(**inputs)
789
+
790
+ >>> prediction_logits = outputs.prediction_logits
791
+ >>> seq_relationship_logits = outputs.seq_relationship_logits
792
+ ```
793
+ """
794
+ outputs = self.bert(
795
+ input_ids,
796
+ attention_mask=attention_mask,
797
+ token_type_ids=token_type_ids,
798
+ position_ids=position_ids,
799
+ inputs_embeds=inputs_embeds,
800
+ return_dict=True,
801
+ **kwargs,
802
+ )
803
+
804
+ sequence_output, pooled_output = outputs[:2]
805
+ prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
806
+
807
+ total_loss = None
808
+ if labels is not None and next_sentence_label is not None:
809
+ loss_fct = CrossEntropyLoss()
810
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
811
+ next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
812
+ total_loss = masked_lm_loss + next_sentence_loss
813
+
814
+ return BertForPreTrainingOutput(
815
+ loss=total_loss,
816
+ prediction_logits=prediction_scores,
817
+ seq_relationship_logits=seq_relationship_score,
818
+ hidden_states=outputs.hidden_states,
819
+ attentions=outputs.attentions,
820
+ )
821
+
822
+
823
+ @auto_docstring(
824
+ custom_intro="""
825
+ Bert Model with a `language modeling` head on top for CLM fine-tuning.
826
+ """
827
+ )
828
+ class BertLMHeadModel(BertPreTrainedModel, GenerationMixin):
829
+ _tied_weights_keys = {
830
+ "cls.predictions.decoder.weight": "bert.embeddings.word_embeddings.weight",
831
+ "cls.predictions.decoder.bias": "cls.predictions.bias",
832
+ }
833
+
834
+ def __init__(self, config):
835
+ super().__init__(config)
836
+
837
+ if not config.is_decoder:
838
+ logger.warning("If you want to use `BertLMHeadModel` as a standalone, add `is_decoder=True.`")
839
+
840
+ self.bert = BertModel(config, add_pooling_layer=False)
841
+ self.cls = BertOnlyMLMHead(config)
842
+
843
+ # Initialize weights and apply final processing
844
+ self.post_init()
845
+
846
+ def get_output_embeddings(self):
847
+ return self.cls.predictions.decoder
848
+
849
+ def set_output_embeddings(self, new_embeddings):
850
+ self.cls.predictions.decoder = new_embeddings
851
+ self.cls.predictions.bias = new_embeddings.bias
852
+
853
+ @can_return_tuple
854
+ @auto_docstring
855
+ def forward(
856
+ self,
857
+ input_ids: torch.Tensor | None = None,
858
+ attention_mask: torch.Tensor | None = None,
859
+ token_type_ids: torch.Tensor | None = None,
860
+ position_ids: torch.Tensor | None = None,
861
+ inputs_embeds: torch.Tensor | None = None,
862
+ encoder_hidden_states: torch.Tensor | None = None,
863
+ encoder_attention_mask: torch.Tensor | None = None,
864
+ labels: torch.Tensor | None = None,
865
+ past_key_values: Cache | None = None,
866
+ use_cache: bool | None = None,
867
+ logits_to_keep: int | torch.Tensor = 0,
868
+ **kwargs: Unpack[TransformersKwargs],
869
+ ) -> tuple[torch.Tensor] | CausalLMOutputWithCrossAttentions:
870
+ r"""
871
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
872
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
873
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
874
+ ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`
875
+ """
876
+ if labels is not None:
877
+ use_cache = False
878
+
879
+ outputs: BaseModelOutputWithPoolingAndCrossAttentions = self.bert(
880
+ input_ids,
881
+ attention_mask=attention_mask,
882
+ token_type_ids=token_type_ids,
883
+ position_ids=position_ids,
884
+ inputs_embeds=inputs_embeds,
885
+ encoder_hidden_states=encoder_hidden_states,
886
+ encoder_attention_mask=encoder_attention_mask,
887
+ past_key_values=past_key_values,
888
+ use_cache=use_cache,
889
+ return_dict=True,
890
+ **kwargs,
891
+ )
892
+
893
+ hidden_states = outputs.last_hidden_state
894
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
895
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
896
+ logits = self.cls(hidden_states[:, slice_indices, :])
897
+
898
+ loss = None
899
+ if labels is not None:
900
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
901
+
902
+ return CausalLMOutputWithCrossAttentions(
903
+ loss=loss,
904
+ logits=logits,
905
+ past_key_values=outputs.past_key_values,
906
+ hidden_states=outputs.hidden_states,
907
+ attentions=outputs.attentions,
908
+ cross_attentions=outputs.cross_attentions,
909
+ )
910
+
911
+
912
+ @auto_docstring
913
+ class BertForMaskedLM(BertPreTrainedModel):
914
+ _tied_weights_keys = {
915
+ "cls.predictions.decoder.weight": "bert.embeddings.word_embeddings.weight",
916
+ "cls.predictions.decoder.bias": "cls.predictions.bias",
917
+ }
918
+
919
+ def __init__(self, config):
920
+ super().__init__(config)
921
+
922
+ if config.is_decoder:
923
+ logger.warning(
924
+ "If you want to use `BertForMaskedLM` make sure `config.is_decoder=False` for "
925
+ "bi-directional self-attention."
926
+ )
927
+
928
+ self.bert = BertModel(config, add_pooling_layer=False)
929
+ self.cls = BertOnlyMLMHead(config)
930
+
931
+ # Initialize weights and apply final processing
932
+ self.post_init()
933
+
934
+ def get_output_embeddings(self):
935
+ return self.cls.predictions.decoder
936
+
937
+ def set_output_embeddings(self, new_embeddings):
938
+ self.cls.predictions.decoder = new_embeddings
939
+ self.cls.predictions.bias = new_embeddings.bias
940
+
941
+ @can_return_tuple
942
+ @auto_docstring
943
+ def forward(
944
+ self,
945
+ input_ids: torch.Tensor | None = None,
946
+ attention_mask: torch.Tensor | None = None,
947
+ token_type_ids: torch.Tensor | None = None,
948
+ position_ids: torch.Tensor | None = None,
949
+ inputs_embeds: torch.Tensor | None = None,
950
+ encoder_hidden_states: torch.Tensor | None = None,
951
+ encoder_attention_mask: torch.Tensor | None = None,
952
+ labels: torch.Tensor | None = None,
953
+ **kwargs: Unpack[TransformersKwargs],
954
+ ) -> tuple[torch.Tensor] | MaskedLMOutput:
955
+ r"""
956
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
957
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
958
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
959
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
960
+ """
961
+ outputs = self.bert(
962
+ input_ids,
963
+ attention_mask=attention_mask,
964
+ token_type_ids=token_type_ids,
965
+ position_ids=position_ids,
966
+ inputs_embeds=inputs_embeds,
967
+ encoder_hidden_states=encoder_hidden_states,
968
+ encoder_attention_mask=encoder_attention_mask,
969
+ return_dict=True,
970
+ **kwargs,
971
+ )
972
+
973
+ sequence_output = outputs[0]
974
+ prediction_scores = self.cls(sequence_output)
975
+
976
+ masked_lm_loss = None
977
+ if labels is not None:
978
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
979
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
980
+
981
+ return MaskedLMOutput(
982
+ loss=masked_lm_loss,
983
+ logits=prediction_scores,
984
+ hidden_states=outputs.hidden_states,
985
+ attentions=outputs.attentions,
986
+ )
987
+
988
+
989
+ @auto_docstring(
990
+ custom_intro="""
991
+ Bert Model with a `next sentence prediction (classification)` head on top.
992
+ """
993
+ )
994
+ class BertForNextSentencePrediction(BertPreTrainedModel):
995
+ def __init__(self, config):
996
+ super().__init__(config)
997
+
998
+ self.bert = BertModel(config)
999
+ self.cls = BertOnlyNSPHead(config)
1000
+
1001
+ # Initialize weights and apply final processing
1002
+ self.post_init()
1003
+
1004
+ @can_return_tuple
1005
+ @auto_docstring
1006
+ def forward(
1007
+ self,
1008
+ input_ids: torch.Tensor | None = None,
1009
+ attention_mask: torch.Tensor | None = None,
1010
+ token_type_ids: torch.Tensor | None = None,
1011
+ position_ids: torch.Tensor | None = None,
1012
+ inputs_embeds: torch.Tensor | None = None,
1013
+ labels: torch.Tensor | None = None,
1014
+ **kwargs: Unpack[TransformersKwargs],
1015
+ ) -> tuple[torch.Tensor] | NextSentencePredictorOutput:
1016
+ r"""
1017
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1018
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
1019
+ (see `input_ids` docstring). Indices should be in `[0, 1]`:
1020
+
1021
+ - 0 indicates sequence B is a continuation of sequence A,
1022
+ - 1 indicates sequence B is a random sequence.
1023
+
1024
+ Example:
1025
+
1026
+ ```python
1027
+ >>> from transformers import AutoTokenizer, BertForNextSentencePrediction
1028
+ >>> import torch
1029
+
1030
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
1031
+ >>> model = BertForNextSentencePrediction.from_pretrained("google-bert/bert-base-uncased")
1032
+
1033
+ >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
1034
+ >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
1035
+ >>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt")
1036
+
1037
+ >>> outputs = model(**encoding, labels=torch.LongTensor([1]))
1038
+ >>> logits = outputs.logits
1039
+ >>> assert logits[0, 0] < logits[0, 1] # next sentence was random
1040
+ ```
1041
+ """
1042
+
1043
+ outputs = self.bert(
1044
+ input_ids,
1045
+ attention_mask=attention_mask,
1046
+ token_type_ids=token_type_ids,
1047
+ position_ids=position_ids,
1048
+ inputs_embeds=inputs_embeds,
1049
+ return_dict=True,
1050
+ **kwargs,
1051
+ )
1052
+
1053
+ pooled_output = outputs[1]
1054
+
1055
+ seq_relationship_scores = self.cls(pooled_output)
1056
+
1057
+ next_sentence_loss = None
1058
+ if labels is not None:
1059
+ loss_fct = CrossEntropyLoss()
1060
+ next_sentence_loss = loss_fct(seq_relationship_scores.view(-1, 2), labels.view(-1))
1061
+
1062
+ return NextSentencePredictorOutput(
1063
+ loss=next_sentence_loss,
1064
+ logits=seq_relationship_scores,
1065
+ hidden_states=outputs.hidden_states,
1066
+ attentions=outputs.attentions,
1067
+ )
1068
+
1069
+
1070
+ @auto_docstring(
1071
+ custom_intro="""
1072
+ Bert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
1073
+ output) e.g. for GLUE tasks.
1074
+ """
1075
+ )
1076
+ class BertForSequenceClassification(BertPreTrainedModel):
1077
+ def __init__(self, config):
1078
+ super().__init__(config)
1079
+ self.num_labels = config.num_labels
1080
+ self.config = config
1081
+
1082
+ self.bert = BertModel(config)
1083
+ classifier_dropout = (
1084
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1085
+ )
1086
+ self.dropout = nn.Dropout(classifier_dropout)
1087
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1088
+
1089
+ # Initialize weights and apply final processing
1090
+ self.post_init()
1091
+
1092
+ @can_return_tuple
1093
+ @auto_docstring
1094
+ def forward(
1095
+ self,
1096
+ input_ids: torch.Tensor | None = None,
1097
+ attention_mask: torch.Tensor | None = None,
1098
+ token_type_ids: torch.Tensor | None = None,
1099
+ position_ids: torch.Tensor | None = None,
1100
+ inputs_embeds: torch.Tensor | None = None,
1101
+ labels: torch.Tensor | None = None,
1102
+ **kwargs: Unpack[TransformersKwargs],
1103
+ ) -> tuple[torch.Tensor] | SequenceClassifierOutput:
1104
+ r"""
1105
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1106
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1107
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1108
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1109
+ """
1110
+ outputs = self.bert(
1111
+ input_ids,
1112
+ attention_mask=attention_mask,
1113
+ token_type_ids=token_type_ids,
1114
+ position_ids=position_ids,
1115
+ inputs_embeds=inputs_embeds,
1116
+ return_dict=True,
1117
+ **kwargs,
1118
+ )
1119
+
1120
+ pooled_output = outputs[1]
1121
+
1122
+ pooled_output = self.dropout(pooled_output)
1123
+ logits = self.classifier(pooled_output)
1124
+
1125
+ loss = None
1126
+ if labels is not None:
1127
+ if self.config.problem_type is None:
1128
+ if self.num_labels == 1:
1129
+ self.config.problem_type = "regression"
1130
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1131
+ self.config.problem_type = "single_label_classification"
1132
+ else:
1133
+ self.config.problem_type = "multi_label_classification"
1134
+
1135
+ if self.config.problem_type == "regression":
1136
+ loss_fct = MSELoss()
1137
+ if self.num_labels == 1:
1138
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1139
+ else:
1140
+ loss = loss_fct(logits, labels)
1141
+ elif self.config.problem_type == "single_label_classification":
1142
+ loss_fct = CrossEntropyLoss()
1143
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1144
+ elif self.config.problem_type == "multi_label_classification":
1145
+ loss_fct = BCEWithLogitsLoss()
1146
+ loss = loss_fct(logits, labels)
1147
+
1148
+ return SequenceClassifierOutput(
1149
+ loss=loss,
1150
+ logits=logits,
1151
+ hidden_states=outputs.hidden_states,
1152
+ attentions=outputs.attentions,
1153
+ )
1154
+
1155
+
1156
+ @auto_docstring
1157
+ class BertForMultipleChoice(BertPreTrainedModel):
1158
+ def __init__(self, config):
1159
+ super().__init__(config)
1160
+
1161
+ self.bert = BertModel(config)
1162
+ classifier_dropout = (
1163
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1164
+ )
1165
+ self.dropout = nn.Dropout(classifier_dropout)
1166
+ self.classifier = nn.Linear(config.hidden_size, 1)
1167
+
1168
+ # Initialize weights and apply final processing
1169
+ self.post_init()
1170
+
1171
+ @can_return_tuple
1172
+ @auto_docstring
1173
+ def forward(
1174
+ self,
1175
+ input_ids: torch.Tensor | None = None,
1176
+ attention_mask: torch.Tensor | None = None,
1177
+ token_type_ids: torch.Tensor | None = None,
1178
+ position_ids: torch.Tensor | None = None,
1179
+ inputs_embeds: torch.Tensor | None = None,
1180
+ labels: torch.Tensor | None = None,
1181
+ **kwargs: Unpack[TransformersKwargs],
1182
+ ) -> tuple[torch.Tensor] | MultipleChoiceModelOutput:
1183
+ r"""
1184
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
1185
+ Indices of input sequence tokens in the vocabulary.
1186
+
1187
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1188
+ [`PreTrainedTokenizer.__call__`] for details.
1189
+
1190
+ [What are input IDs?](../glossary#input-ids)
1191
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
1192
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
1193
+ 1]`:
1194
+
1195
+ - 0 corresponds to a *sentence A* token,
1196
+ - 1 corresponds to a *sentence B* token.
1197
+
1198
+ [What are token type IDs?](../glossary#token-type-ids)
1199
+ position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
1200
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1201
+ config.max_position_embeddings - 1]`.
1202
+
1203
+ [What are position IDs?](../glossary#position-ids)
1204
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
1205
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1206
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1207
+ model's internal embedding lookup matrix.
1208
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1209
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
1210
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
1211
+ `input_ids` above)
1212
+ """
1213
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
1214
+
1215
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
1216
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
1217
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
1218
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
1219
+ inputs_embeds = (
1220
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
1221
+ if inputs_embeds is not None
1222
+ else None
1223
+ )
1224
+
1225
+ outputs = self.bert(
1226
+ input_ids,
1227
+ attention_mask=attention_mask,
1228
+ token_type_ids=token_type_ids,
1229
+ position_ids=position_ids,
1230
+ inputs_embeds=inputs_embeds,
1231
+ return_dict=True,
1232
+ **kwargs,
1233
+ )
1234
+
1235
+ pooled_output = outputs[1]
1236
+
1237
+ pooled_output = self.dropout(pooled_output)
1238
+ logits = self.classifier(pooled_output)
1239
+ reshaped_logits = logits.view(-1, num_choices)
1240
+
1241
+ loss = None
1242
+ if labels is not None:
1243
+ loss_fct = CrossEntropyLoss()
1244
+ loss = loss_fct(reshaped_logits, labels)
1245
+
1246
+ return MultipleChoiceModelOutput(
1247
+ loss=loss,
1248
+ logits=reshaped_logits,
1249
+ hidden_states=outputs.hidden_states,
1250
+ attentions=outputs.attentions,
1251
+ )
1252
+
1253
+
1254
+ @auto_docstring
1255
+ class BertForTokenClassification(BertPreTrainedModel):
1256
+ def __init__(self, config):
1257
+ super().__init__(config)
1258
+ self.num_labels = config.num_labels
1259
+
1260
+ self.bert = BertModel(config, add_pooling_layer=False)
1261
+ classifier_dropout = (
1262
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1263
+ )
1264
+ self.dropout = nn.Dropout(classifier_dropout)
1265
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1266
+
1267
+ # Initialize weights and apply final processing
1268
+ self.post_init()
1269
+
1270
+ @can_return_tuple
1271
+ @auto_docstring
1272
+ def forward(
1273
+ self,
1274
+ input_ids: torch.Tensor | None = None,
1275
+ attention_mask: torch.Tensor | None = None,
1276
+ token_type_ids: torch.Tensor | None = None,
1277
+ position_ids: torch.Tensor | None = None,
1278
+ inputs_embeds: torch.Tensor | None = None,
1279
+ labels: torch.Tensor | None = None,
1280
+ **kwargs: Unpack[TransformersKwargs],
1281
+ ) -> tuple[torch.Tensor] | TokenClassifierOutput:
1282
+ r"""
1283
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1284
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1285
+ """
1286
+ outputs = self.bert(
1287
+ input_ids,
1288
+ attention_mask=attention_mask,
1289
+ token_type_ids=token_type_ids,
1290
+ position_ids=position_ids,
1291
+ inputs_embeds=inputs_embeds,
1292
+ return_dict=True,
1293
+ **kwargs,
1294
+ )
1295
+
1296
+ sequence_output = outputs[0]
1297
+
1298
+ sequence_output = self.dropout(sequence_output)
1299
+ logits = self.classifier(sequence_output)
1300
+
1301
+ loss = None
1302
+ if labels is not None:
1303
+ loss_fct = CrossEntropyLoss()
1304
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1305
+
1306
+ return TokenClassifierOutput(
1307
+ loss=loss,
1308
+ logits=logits,
1309
+ hidden_states=outputs.hidden_states,
1310
+ attentions=outputs.attentions,
1311
+ )
1312
+
1313
+
1314
+ @auto_docstring
1315
+ class BertForQuestionAnswering(BertPreTrainedModel):
1316
+ def __init__(self, config):
1317
+ super().__init__(config)
1318
+ self.num_labels = config.num_labels
1319
+
1320
+ self.bert = BertModel(config, add_pooling_layer=False)
1321
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1322
+
1323
+ # Initialize weights and apply final processing
1324
+ self.post_init()
1325
+
1326
+ @can_return_tuple
1327
+ @auto_docstring
1328
+ def forward(
1329
+ self,
1330
+ input_ids: torch.Tensor | None = None,
1331
+ attention_mask: torch.Tensor | None = None,
1332
+ token_type_ids: torch.Tensor | None = None,
1333
+ position_ids: torch.Tensor | None = None,
1334
+ inputs_embeds: torch.Tensor | None = None,
1335
+ start_positions: torch.Tensor | None = None,
1336
+ end_positions: torch.Tensor | None = None,
1337
+ **kwargs: Unpack[TransformersKwargs],
1338
+ ) -> tuple[torch.Tensor] | QuestionAnsweringModelOutput:
1339
+ outputs = self.bert(
1340
+ input_ids,
1341
+ attention_mask=attention_mask,
1342
+ token_type_ids=token_type_ids,
1343
+ position_ids=position_ids,
1344
+ inputs_embeds=inputs_embeds,
1345
+ return_dict=True,
1346
+ **kwargs,
1347
+ )
1348
+
1349
+ sequence_output = outputs[0]
1350
+
1351
+ logits = self.qa_outputs(sequence_output)
1352
+ start_logits, end_logits = logits.split(1, dim=-1)
1353
+ start_logits = start_logits.squeeze(-1).contiguous()
1354
+ end_logits = end_logits.squeeze(-1).contiguous()
1355
+
1356
+ total_loss = None
1357
+ if start_positions is not None and end_positions is not None:
1358
+ # If we are on multi-GPU, split add a dimension
1359
+ if len(start_positions.size()) > 1:
1360
+ start_positions = start_positions.squeeze(-1)
1361
+ if len(end_positions.size()) > 1:
1362
+ end_positions = end_positions.squeeze(-1)
1363
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1364
+ ignored_index = start_logits.size(1)
1365
+ start_positions = start_positions.clamp(0, ignored_index)
1366
+ end_positions = end_positions.clamp(0, ignored_index)
1367
+
1368
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1369
+ start_loss = loss_fct(start_logits, start_positions)
1370
+ end_loss = loss_fct(end_logits, end_positions)
1371
+ total_loss = (start_loss + end_loss) / 2
1372
+
1373
+ return QuestionAnsweringModelOutput(
1374
+ loss=total_loss,
1375
+ start_logits=start_logits,
1376
+ end_logits=end_logits,
1377
+ hidden_states=outputs.hidden_states,
1378
+ attentions=outputs.attentions,
1379
+ )
1380
+
1381
+
1382
+ __all__ = [
1383
+ "BertForMaskedLM",
1384
+ "BertForMultipleChoice",
1385
+ "BertForNextSentencePrediction",
1386
+ "BertForPreTraining",
1387
+ "BertForQuestionAnswering",
1388
+ "BertForSequenceClassification",
1389
+ "BertForTokenClassification",
1390
+ "BertLayer",
1391
+ "BertLMHeadModel",
1392
+ "BertModel",
1393
+ "BertPreTrainedModel",
1394
+ ]
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/tokenization_bert.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tokenization classes for Bert."""
15
+
16
+ import collections
17
+
18
+ from tokenizers import Tokenizer, decoders, normalizers, pre_tokenizers, processors
19
+ from tokenizers.models import WordPiece
20
+
21
+ from ...tokenization_utils_tokenizers import TokenizersBackend
22
+ from ...utils import logging
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
28
+
29
+
30
+ def load_vocab(vocab_file):
31
+ """Loads a vocabulary file into a dictionary."""
32
+ vocab = collections.OrderedDict()
33
+ with open(vocab_file, "r", encoding="utf-8") as reader:
34
+ tokens = reader.readlines()
35
+ for index, token in enumerate(tokens):
36
+ token = token.rstrip("\n")
37
+ vocab[token] = index
38
+ return vocab
39
+
40
+
41
+ class BertTokenizer(TokenizersBackend):
42
+ r"""
43
+ Construct a BERT tokenizer (backed by HuggingFace's tokenizers library). Based on WordPiece.
44
+
45
+ This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should refer to
46
+ this superclass for more information regarding those methods.
47
+
48
+ Args:
49
+ vocab (`str` or `dict[str, int]`, *optional*):
50
+ Custom vocabulary dictionary. If not provided, vocabulary is loaded from `vocab_file`.
51
+ do_lower_case (`bool`, *optional*, defaults to `True`):
52
+ Whether or not to lowercase the input when tokenizing.
53
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
54
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
55
+ token instead.
56
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
57
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
58
+ sequence classification or for a text and a question for question answering. It is also used as the last
59
+ token of a sequence built with special tokens.
60
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
61
+ The token used for padding, for example when batching sequences of different lengths.
62
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
63
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
64
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
65
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
66
+ The token used for masking values. This is the token used when training this model with masked language
67
+ modeling. This is the token which the model will try to predict.
68
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
69
+ Whether or not to tokenize Chinese characters.
70
+ strip_accents (`bool`, *optional*):
71
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
72
+ value for `lowercase` (as in the original BERT).
73
+ """
74
+
75
+ vocab_files_names = VOCAB_FILES_NAMES
76
+ model_input_names = ["input_ids", "token_type_ids", "attention_mask"]
77
+ model = WordPiece
78
+
79
+ def __init__(
80
+ self,
81
+ vocab: str | dict[str, int] | None = None,
82
+ do_lower_case: bool = True,
83
+ unk_token: str = "[UNK]",
84
+ sep_token: str = "[SEP]",
85
+ pad_token: str = "[PAD]",
86
+ cls_token: str = "[CLS]",
87
+ mask_token: str = "[MASK]",
88
+ tokenize_chinese_chars: bool = True,
89
+ strip_accents: bool | None = None,
90
+ **kwargs,
91
+ ):
92
+ self.do_lower_case = do_lower_case
93
+ self.tokenize_chinese_chars = tokenize_chinese_chars
94
+ self.strip_accents = strip_accents
95
+ if vocab is None:
96
+ vocab = {
97
+ str(pad_token): 0,
98
+ str(unk_token): 1,
99
+ str(cls_token): 2,
100
+ str(sep_token): 3,
101
+ str(mask_token): 4,
102
+ }
103
+ self._vocab = vocab
104
+ self._tokenizer = Tokenizer(WordPiece(self._vocab, unk_token=str(unk_token)))
105
+ self._tokenizer.normalizer = normalizers.BertNormalizer(
106
+ clean_text=True,
107
+ handle_chinese_chars=tokenize_chinese_chars,
108
+ strip_accents=strip_accents,
109
+ lowercase=do_lower_case,
110
+ )
111
+ self._tokenizer.pre_tokenizer = pre_tokenizers.BertPreTokenizer()
112
+ self._tokenizer.decoder = decoders.WordPiece(prefix="##")
113
+ super().__init__(
114
+ do_lower_case=do_lower_case,
115
+ unk_token=unk_token,
116
+ sep_token=sep_token,
117
+ pad_token=pad_token,
118
+ cls_token=cls_token,
119
+ mask_token=mask_token,
120
+ tokenize_chinese_chars=tokenize_chinese_chars,
121
+ strip_accents=strip_accents,
122
+ **kwargs,
123
+ )
124
+
125
+ cls_token_id = self.cls_token_id if self.cls_token_id is not None else 2
126
+ sep_token_id = self.sep_token_id if self.sep_token_id is not None else 3
127
+
128
+ self._tokenizer.post_processor = processors.TemplateProcessing(
129
+ single=f"{str(self.cls_token)}:0 $A:0 {str(self.sep_token)}:0",
130
+ pair=f"{str(self.cls_token)}:0 $A:0 {str(self.sep_token)}:0 $B:1 {str(self.sep_token)}:1",
131
+ special_tokens=[
132
+ (str(self.cls_token), cls_token_id),
133
+ (str(self.sep_token), sep_token_id),
134
+ ],
135
+ )
136
+
137
+
138
+ __all__ = ["BertTokenizer"]
139
+
140
+ BertTokenizerFast = BertTokenizer
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/tokenization_bert_legacy.py ADDED
@@ -0,0 +1,476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tokenization classes for Bert."""
15
+
16
+ import collections
17
+ import os
18
+ import unicodedata
19
+
20
+ from ...tokenization_python import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
21
+ from ...utils import logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
27
+
28
+
29
+ def load_vocab(vocab_file):
30
+ """Loads a vocabulary file into a dictionary."""
31
+ vocab = collections.OrderedDict()
32
+ with open(vocab_file, "r", encoding="utf-8") as reader:
33
+ tokens = reader.readlines()
34
+ for index, token in enumerate(tokens):
35
+ token = token.rstrip("\n")
36
+ vocab[token] = index
37
+ return vocab
38
+
39
+
40
+ def whitespace_tokenize(text):
41
+ """Runs basic whitespace cleaning and splitting on a piece of text."""
42
+ text = text.strip()
43
+ if not text:
44
+ return []
45
+ tokens = text.split()
46
+ return tokens
47
+
48
+
49
+ class BertTokenizerLegacy(PreTrainedTokenizer):
50
+ r"""
51
+ Construct a BERT tokenizer. Based on WordPiece.
52
+
53
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
54
+ this superclass for more information regarding those methods.
55
+
56
+ Args:
57
+ vocab_file (`str`):
58
+ File containing the vocabulary.
59
+ do_lower_case (`bool`, *optional*, defaults to `True`):
60
+ Whether or not to lowercase the input when tokenizing.
61
+ do_basic_tokenize (`bool`, *optional*, defaults to `True`):
62
+ Whether or not to do basic tokenization before WordPiece.
63
+ never_split (`Iterable`, *optional*):
64
+ Collection of tokens which will never be split during tokenization. Only has an effect when
65
+ `do_basic_tokenize=True`
66
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
67
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
68
+ token instead.
69
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
70
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
71
+ sequence classification or for a text and a question for question answering. It is also used as the last
72
+ token of a sequence built with special tokens.
73
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
74
+ The token used for padding, for example when batching sequences of different lengths.
75
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
76
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
77
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
78
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
79
+ The token used for masking values. This is the token used when training this model with masked language
80
+ modeling. This is the token which the model will try to predict.
81
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
82
+ Whether or not to tokenize Chinese characters.
83
+
84
+ This should likely be deactivated for Japanese (see this
85
+ [issue](https://github.com/huggingface/transformers/issues/328)).
86
+ strip_accents (`bool`, *optional*):
87
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
88
+ value for `lowercase` (as in the original BERT).
89
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`):
90
+ Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
91
+ extra spaces.
92
+ """
93
+
94
+ vocab_files_names = VOCAB_FILES_NAMES
95
+
96
+ def __init__(
97
+ self,
98
+ vocab_file,
99
+ do_lower_case=True,
100
+ do_basic_tokenize=True,
101
+ never_split=None,
102
+ unk_token="[UNK]",
103
+ sep_token="[SEP]",
104
+ pad_token="[PAD]",
105
+ cls_token="[CLS]",
106
+ mask_token="[MASK]",
107
+ tokenize_chinese_chars=True,
108
+ strip_accents=None,
109
+ clean_up_tokenization_spaces=True,
110
+ **kwargs,
111
+ ):
112
+ if not os.path.isfile(vocab_file):
113
+ raise ValueError(
114
+ f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
115
+ " model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
116
+ )
117
+ self.vocab = load_vocab(vocab_file)
118
+ self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
119
+ self.do_basic_tokenize = do_basic_tokenize
120
+ if do_basic_tokenize:
121
+ self.basic_tokenizer = BasicTokenizer(
122
+ do_lower_case=do_lower_case,
123
+ never_split=never_split,
124
+ tokenize_chinese_chars=tokenize_chinese_chars,
125
+ strip_accents=strip_accents,
126
+ )
127
+
128
+ self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
129
+
130
+ super().__init__(
131
+ do_lower_case=do_lower_case,
132
+ do_basic_tokenize=do_basic_tokenize,
133
+ never_split=never_split,
134
+ unk_token=unk_token,
135
+ sep_token=sep_token,
136
+ pad_token=pad_token,
137
+ cls_token=cls_token,
138
+ mask_token=mask_token,
139
+ tokenize_chinese_chars=tokenize_chinese_chars,
140
+ strip_accents=strip_accents,
141
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
142
+ **kwargs,
143
+ )
144
+
145
+ @property
146
+ def do_lower_case(self):
147
+ return self.basic_tokenizer.do_lower_case
148
+
149
+ @property
150
+ def vocab_size(self):
151
+ return len(self.vocab)
152
+
153
+ def get_vocab(self):
154
+ return dict(self.vocab, **self.added_tokens_encoder)
155
+
156
+ def _tokenize(self, text, split_special_tokens=False):
157
+ split_tokens = []
158
+ if self.do_basic_tokenize:
159
+ for token in self.basic_tokenizer.tokenize(
160
+ text, never_split=self.all_special_tokens if not split_special_tokens else None
161
+ ):
162
+ # If the token is part of the never_split set
163
+ if token in self.basic_tokenizer.never_split:
164
+ split_tokens.append(token)
165
+ else:
166
+ split_tokens += self.wordpiece_tokenizer.tokenize(token)
167
+ else:
168
+ split_tokens = self.wordpiece_tokenizer.tokenize(text)
169
+ return split_tokens
170
+
171
+ def _convert_token_to_id(self, token):
172
+ """Converts a token (str) in an id using the vocab."""
173
+ return self.vocab.get(token, self.vocab.get(self.unk_token))
174
+
175
+ def _convert_id_to_token(self, index):
176
+ """Converts an index (integer) in a token (str) using the vocab."""
177
+ return self.ids_to_tokens.get(index, self.unk_token)
178
+
179
+ def convert_tokens_to_string(self, tokens):
180
+ """Converts a sequence of tokens (string) in a single string."""
181
+ out_string = " ".join(tokens).replace(" ##", "").strip()
182
+ return out_string
183
+
184
+ def build_inputs_with_special_tokens(
185
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None
186
+ ) -> list[int]:
187
+ """
188
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
189
+ adding special tokens. A BERT sequence has the following format:
190
+
191
+ - single sequence: `[CLS] X [SEP]`
192
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
193
+
194
+ Args:
195
+ token_ids_0 (`List[int]`):
196
+ List of IDs to which the special tokens will be added.
197
+ token_ids_1 (`List[int]`, *optional*):
198
+ Optional second list of IDs for sequence pairs.
199
+
200
+ Returns:
201
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
202
+ """
203
+ if token_ids_1 is None:
204
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
205
+ cls = [self.cls_token_id]
206
+ sep = [self.sep_token_id]
207
+ return cls + token_ids_0 + sep + token_ids_1 + sep
208
+
209
+ def get_special_tokens_mask(
210
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False
211
+ ) -> list[int]:
212
+ """
213
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
214
+ special tokens using the tokenizer `prepare_for_model` method.
215
+
216
+ Args:
217
+ token_ids_0 (`List[int]`):
218
+ List of IDs.
219
+ token_ids_1 (`List[int]`, *optional*):
220
+ Optional second list of IDs for sequence pairs.
221
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
222
+ Whether or not the token list is already formatted with special tokens for the model.
223
+
224
+ Returns:
225
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
226
+ """
227
+
228
+ if already_has_special_tokens:
229
+ return super().get_special_tokens_mask(
230
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
231
+ )
232
+
233
+ if token_ids_1 is not None:
234
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
235
+ return [1] + ([0] * len(token_ids_0)) + [1]
236
+
237
+ def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
238
+ index = 0
239
+ if os.path.isdir(save_directory):
240
+ vocab_file = os.path.join(
241
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
242
+ )
243
+ else:
244
+ vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
245
+ with open(vocab_file, "w", encoding="utf-8") as writer:
246
+ for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
247
+ if index != token_index:
248
+ logger.warning(
249
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
250
+ " Please check that the vocabulary is not corrupted!"
251
+ )
252
+ index = token_index
253
+ writer.write(token + "\n")
254
+ index += 1
255
+ return (vocab_file,)
256
+
257
+
258
+ class BasicTokenizer:
259
+ """
260
+ Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
261
+
262
+ Args:
263
+ do_lower_case (`bool`, *optional*, defaults to `True`):
264
+ Whether or not to lowercase the input when tokenizing.
265
+ never_split (`Iterable`, *optional*):
266
+ Collection of tokens which will never be split during tokenization. Only has an effect when
267
+ `do_basic_tokenize=True`
268
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
269
+ Whether or not to tokenize Chinese characters.
270
+
271
+ This should likely be deactivated for Japanese (see this
272
+ [issue](https://github.com/huggingface/transformers/issues/328)).
273
+ strip_accents (`bool`, *optional*):
274
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
275
+ value for `lowercase` (as in the original BERT).
276
+ do_split_on_punc (`bool`, *optional*, defaults to `True`):
277
+ In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
278
+ the full context of the words, such as contractions.
279
+ """
280
+
281
+ def __init__(
282
+ self,
283
+ do_lower_case=True,
284
+ never_split=None,
285
+ tokenize_chinese_chars=True,
286
+ strip_accents=None,
287
+ do_split_on_punc=True,
288
+ ):
289
+ if never_split is None:
290
+ never_split = []
291
+ self.do_lower_case = do_lower_case
292
+ self.never_split = set(never_split)
293
+ self.tokenize_chinese_chars = tokenize_chinese_chars
294
+ self.strip_accents = strip_accents
295
+ self.do_split_on_punc = do_split_on_punc
296
+
297
+ def tokenize(self, text, never_split=None):
298
+ """
299
+ Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
300
+
301
+ Args:
302
+ never_split (`List[str]`, *optional*)
303
+ Kept for backward compatibility purposes. Now implemented directly at the base class level (see
304
+ [`PreTrainedTokenizer.tokenize`]) List of token not to split.
305
+ """
306
+ # union() returns a new set by concatenating the two sets.
307
+ never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
308
+ text = self._clean_text(text)
309
+
310
+ # This was added on November 1st, 2018 for the multilingual and Chinese
311
+ # models. This is also applied to the English models now, but it doesn't
312
+ # matter since the English models were not trained on any Chinese data
313
+ # and generally don't have any Chinese data in them (there are Chinese
314
+ # characters in the vocabulary because Wikipedia does have some Chinese
315
+ # words in the English Wikipedia.).
316
+ if self.tokenize_chinese_chars:
317
+ text = self._tokenize_chinese_chars(text)
318
+ # prevents treating the same character with different unicode codepoints as different characters
319
+ unicode_normalized_text = unicodedata.normalize("NFC", text)
320
+ orig_tokens = whitespace_tokenize(unicode_normalized_text)
321
+ split_tokens = []
322
+ for token in orig_tokens:
323
+ if token not in never_split:
324
+ if self.do_lower_case:
325
+ token = token.lower()
326
+ if self.strip_accents is not False:
327
+ token = self._run_strip_accents(token)
328
+ elif self.strip_accents:
329
+ token = self._run_strip_accents(token)
330
+ split_tokens.extend(self._run_split_on_punc(token, never_split))
331
+
332
+ output_tokens = whitespace_tokenize(" ".join(split_tokens))
333
+ return output_tokens
334
+
335
+ def _run_strip_accents(self, text):
336
+ """Strips accents from a piece of text."""
337
+ text = unicodedata.normalize("NFD", text)
338
+ output = []
339
+ for char in text:
340
+ cat = unicodedata.category(char)
341
+ if cat == "Mn":
342
+ continue
343
+ output.append(char)
344
+ return "".join(output)
345
+
346
+ def _run_split_on_punc(self, text, never_split=None):
347
+ """Splits punctuation on a piece of text."""
348
+ if not self.do_split_on_punc or (never_split is not None and text in never_split):
349
+ return [text]
350
+ chars = list(text)
351
+ i = 0
352
+ start_new_word = True
353
+ output = []
354
+ while i < len(chars):
355
+ char = chars[i]
356
+ if _is_punctuation(char):
357
+ output.append([char])
358
+ start_new_word = True
359
+ else:
360
+ if start_new_word:
361
+ output.append([])
362
+ start_new_word = False
363
+ output[-1].append(char)
364
+ i += 1
365
+
366
+ return ["".join(x) for x in output]
367
+
368
+ def _tokenize_chinese_chars(self, text):
369
+ """Adds whitespace around any CJK character."""
370
+ output = []
371
+ for char in text:
372
+ cp = ord(char)
373
+ if self._is_chinese_char(cp):
374
+ output.append(" ")
375
+ output.append(char)
376
+ output.append(" ")
377
+ else:
378
+ output.append(char)
379
+ return "".join(output)
380
+
381
+ def _is_chinese_char(self, cp):
382
+ """Checks whether CP is the codepoint of a CJK character."""
383
+ # This defines a "chinese character" as anything in the CJK Unicode block:
384
+ # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
385
+ #
386
+ # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
387
+ # despite its name. The modern Korean Hangul alphabet is a different block,
388
+ # as is Japanese Hiragana and Katakana. Those alphabets are used to write
389
+ # space-separated words, so they are not treated specially and handled
390
+ # like the all of the other languages.
391
+ if (
392
+ (cp >= 0x4E00 and cp <= 0x9FFF)
393
+ or (cp >= 0x3400 and cp <= 0x4DBF)
394
+ or (cp >= 0x20000 and cp <= 0x2A6DF)
395
+ or (cp >= 0x2A700 and cp <= 0x2B73F)
396
+ or (cp >= 0x2B740 and cp <= 0x2B81F)
397
+ or (cp >= 0x2B820 and cp <= 0x2CEAF)
398
+ or (cp >= 0xF900 and cp <= 0xFAFF)
399
+ or (cp >= 0x2F800 and cp <= 0x2FA1F)
400
+ ):
401
+ return True
402
+
403
+ return False
404
+
405
+ def _clean_text(self, text):
406
+ """Performs invalid character removal and whitespace cleanup on text."""
407
+ output = []
408
+ for char in text:
409
+ cp = ord(char)
410
+ if cp == 0 or cp == 0xFFFD or _is_control(char):
411
+ continue
412
+ if _is_whitespace(char):
413
+ output.append(" ")
414
+ else:
415
+ output.append(char)
416
+ return "".join(output)
417
+
418
+
419
+ class WordpieceTokenizer:
420
+ """Runs WordPiece tokenization."""
421
+
422
+ def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
423
+ self.vocab = vocab
424
+ self.unk_token = unk_token
425
+ self.max_input_chars_per_word = max_input_chars_per_word
426
+
427
+ def tokenize(self, text):
428
+ """
429
+ Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
430
+ tokenization using the given vocabulary.
431
+
432
+ For example, `input = "unaffable"` will return as output `["un", "##aff", "##able"]`.
433
+
434
+ Args:
435
+ text: A single token or whitespace separated tokens. This should have
436
+ already been passed through *BasicTokenizer*.
437
+
438
+ Returns:
439
+ A list of wordpiece tokens.
440
+ """
441
+
442
+ output_tokens = []
443
+ for token in whitespace_tokenize(text):
444
+ chars = list(token)
445
+ if len(chars) > self.max_input_chars_per_word:
446
+ output_tokens.append(self.unk_token)
447
+ continue
448
+
449
+ is_bad = False
450
+ start = 0
451
+ sub_tokens = []
452
+ while start < len(chars):
453
+ end = len(chars)
454
+ cur_substr = None
455
+ while start < end:
456
+ substr = "".join(chars[start:end])
457
+ if start > 0:
458
+ substr = "##" + substr
459
+ if substr in self.vocab:
460
+ cur_substr = substr
461
+ break
462
+ end -= 1
463
+ if cur_substr is None:
464
+ is_bad = True
465
+ break
466
+ sub_tokens.append(cur_substr)
467
+ start = end
468
+
469
+ if is_bad:
470
+ output_tokens.append(self.unk_token)
471
+ else:
472
+ output_tokens.extend(sub_tokens)
473
+ return output_tokens
474
+
475
+
476
+ __all__ = ["BasicTokenizer", "BertTokenizerLegacy", "WordpieceTokenizer"]
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bertweet/__init__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 .tokenization_bertweet import *
22
+ else:
23
+ import sys
24
+
25
+ _file = globals()["__file__"]
26
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bertweet/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (747 Bytes). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bertweet/__pycache__/tokenization_bertweet.cpython-311.pyc ADDED
Binary file (28.1 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bertweet/tokenization_bertweet.py ADDED
@@ -0,0 +1,698 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020, VinAI Research and the HuggingFace Inc. team.
2
+ # Copyright 2018 The Open AI Team Authors and The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Tokenization classes for BERTweet"""
16
+
17
+ import html
18
+ import os
19
+ import re
20
+
21
+ import regex
22
+
23
+ from ...tokenization_python import PreTrainedTokenizer
24
+ from ...utils import logging
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+ VOCAB_FILES_NAMES = {
30
+ "vocab_file": "vocab.txt",
31
+ "merges_file": "bpe.codes",
32
+ }
33
+
34
+
35
+ def get_pairs(word):
36
+ """
37
+ Return set of symbol pairs in a word.
38
+
39
+ Word is represented as tuple of symbols (symbols being variable-length strings).
40
+ """
41
+ pairs = set()
42
+ prev_char = word[0]
43
+ for char in word[1:]:
44
+ pairs.add((prev_char, char))
45
+ prev_char = char
46
+
47
+ pairs = set(pairs)
48
+ return pairs
49
+
50
+
51
+ class BertweetTokenizer(PreTrainedTokenizer):
52
+ """
53
+ Constructs a BERTweet tokenizer, using Byte-Pair-Encoding.
54
+
55
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
56
+ this superclass for more information regarding those methods.
57
+
58
+ Args:
59
+ vocab_file (`str`):
60
+ Path to the vocabulary file.
61
+ merges_file (`str`):
62
+ Path to the merges file.
63
+ normalization (`bool`, *optional*, defaults to `False`):
64
+ Whether or not to apply a normalization preprocess.
65
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
66
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
67
+
68
+ <Tip>
69
+
70
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
71
+ sequence. The token used is the `cls_token`.
72
+
73
+ </Tip>
74
+
75
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
76
+ The end of sequence token.
77
+
78
+ <Tip>
79
+
80
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
81
+ The token used is the `sep_token`.
82
+
83
+ </Tip>
84
+
85
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
86
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
87
+ sequence classification or for a text and a question for question answering. It is also used as the last
88
+ token of a sequence built with special tokens.
89
+ cls_token (`str`, *optional*, defaults to `"<s>"`):
90
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
91
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
92
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
93
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
94
+ token instead.
95
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
96
+ The token used for padding, for example when batching sequences of different lengths.
97
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
98
+ The token used for masking values. This is the token used when training this model with masked language
99
+ modeling. This is the token which the model will try to predict.
100
+ """
101
+
102
+ vocab_files_names = VOCAB_FILES_NAMES
103
+
104
+ def __init__(
105
+ self,
106
+ vocab_file,
107
+ merges_file,
108
+ normalization=False,
109
+ bos_token="<s>",
110
+ eos_token="</s>",
111
+ sep_token="</s>",
112
+ cls_token="<s>",
113
+ unk_token="<unk>",
114
+ pad_token="<pad>",
115
+ mask_token="<mask>",
116
+ **kwargs,
117
+ ):
118
+ try:
119
+ from emoji import demojize
120
+
121
+ self.demojizer = demojize
122
+ except ImportError:
123
+ logger.warning(
124
+ "emoji is not installed, thus not converting emoticons or emojis into text. Install emoji: pip3"
125
+ " install emoji==0.6.0"
126
+ )
127
+ self.demojizer = None
128
+
129
+ self.vocab_file = vocab_file
130
+ self.merges_file = merges_file
131
+
132
+ self.encoder = {}
133
+ self.encoder[str(bos_token)] = 0
134
+ self.encoder[str(pad_token)] = 1
135
+ self.encoder[str(eos_token)] = 2
136
+ self.encoder[str(unk_token)] = 3
137
+
138
+ self.add_from_file(vocab_file)
139
+
140
+ self.decoder = {v: k for k, v in self.encoder.items()}
141
+
142
+ with open(merges_file, encoding="utf-8") as merges_handle:
143
+ merges = merges_handle.read().split("\n")[:-1]
144
+ merges = [tuple(merge.split()[:-1]) for merge in merges]
145
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
146
+ self.cache = {}
147
+
148
+ self.normalization = normalization
149
+ self.tweetPreprocessor = TweetTokenizer()
150
+ self.special_puncts = {"’": "'", "…": "..."}
151
+
152
+ super().__init__(
153
+ normalization=normalization,
154
+ bos_token=bos_token,
155
+ eos_token=eos_token,
156
+ sep_token=sep_token,
157
+ cls_token=cls_token,
158
+ unk_token=unk_token,
159
+ pad_token=pad_token,
160
+ mask_token=mask_token,
161
+ # Configure patterns instead of overriding methods
162
+ token_type_ids_pattern="all_zeros", # BERTweet doesn't use token type IDs
163
+ token_type_ids_include_special_tokens=True,
164
+ special_tokens_pattern="cls_double_sep", # <s> X </s></s> Y </s>
165
+ **kwargs,
166
+ )
167
+
168
+ @property
169
+ def vocab_size(self):
170
+ return len(self.encoder)
171
+
172
+ def get_vocab(self):
173
+ return dict(self.encoder, **self.added_tokens_encoder)
174
+
175
+ def bpe(self, token):
176
+ if token in self.cache:
177
+ return self.cache[token]
178
+ word = tuple(token)
179
+ word = tuple(list(word[:-1]) + [word[-1] + "</w>"])
180
+ pairs = get_pairs(word)
181
+
182
+ if not pairs:
183
+ return token
184
+
185
+ while True:
186
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
187
+ if bigram not in self.bpe_ranks:
188
+ break
189
+ first, second = bigram
190
+ new_word = []
191
+ i = 0
192
+ while i < len(word):
193
+ try:
194
+ j = word.index(first, i)
195
+ except ValueError:
196
+ new_word.extend(word[i:])
197
+ break
198
+ else:
199
+ new_word.extend(word[i:j])
200
+ i = j
201
+
202
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
203
+ new_word.append(first + second)
204
+ i += 2
205
+ else:
206
+ new_word.append(word[i])
207
+ i += 1
208
+ new_word = tuple(new_word)
209
+ word = new_word
210
+ if len(word) == 1:
211
+ break
212
+ else:
213
+ pairs = get_pairs(word)
214
+ word = "@@ ".join(word)
215
+ word = word[:-4]
216
+ self.cache[token] = word
217
+ return word
218
+
219
+ def _tokenize(self, text):
220
+ """Tokenize a string."""
221
+ if self.normalization: # Perform Tweet normalization before performing BPE
222
+ text = self.normalizeTweet(text)
223
+
224
+ split_tokens = []
225
+ words = re.findall(r"\S+\n?", text)
226
+ for token in words:
227
+ split_tokens.extend(list(self.bpe(token).split(" ")))
228
+ return split_tokens
229
+
230
+ def normalizeTweet(self, tweet):
231
+ """
232
+ Normalize a raw Tweet
233
+ """
234
+ for punct in self.special_puncts:
235
+ tweet = tweet.replace(punct, self.special_puncts[punct])
236
+
237
+ tokens = self.tweetPreprocessor.tokenize(tweet)
238
+ normTweet = " ".join([self.normalizeToken(token) for token in tokens])
239
+
240
+ normTweet = (
241
+ normTweet.replace("cannot ", "can not ")
242
+ .replace("n't ", " n't ")
243
+ .replace("n 't ", " n't ")
244
+ .replace("ca n't", "can't")
245
+ .replace("ai n't", "ain't")
246
+ )
247
+ normTweet = (
248
+ normTweet.replace("'m ", " 'm ")
249
+ .replace("'re ", " 're ")
250
+ .replace("'s ", " 's ")
251
+ .replace("'ll ", " 'll ")
252
+ .replace("'d ", " 'd ")
253
+ .replace("'ve ", " 've ")
254
+ )
255
+ normTweet = (
256
+ normTweet.replace(" p . m .", " p.m.")
257
+ .replace(" p . m ", " p.m ")
258
+ .replace(" a . m .", " a.m.")
259
+ .replace(" a . m ", " a.m ")
260
+ )
261
+
262
+ return " ".join(normTweet.split())
263
+
264
+ def normalizeToken(self, token):
265
+ """
266
+ Normalize tokens in a Tweet
267
+ """
268
+ lowercased_token = token.lower()
269
+ if token.startswith("@"):
270
+ return "@USER"
271
+ elif lowercased_token.startswith("http") or lowercased_token.startswith("www"):
272
+ return "HTTPURL"
273
+ elif len(token) == 1:
274
+ if token in self.special_puncts:
275
+ return self.special_puncts[token]
276
+ if self.demojizer is not None:
277
+ return self.demojizer(token)
278
+ else:
279
+ return token
280
+ else:
281
+ return token
282
+
283
+ def _convert_token_to_id(self, token):
284
+ """Converts a token (str) in an id using the vocab."""
285
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
286
+
287
+ def _convert_id_to_token(self, index):
288
+ """Converts an index (integer) in a token (str) using the vocab."""
289
+ return self.decoder.get(index, self.unk_token)
290
+
291
+ def convert_tokens_to_string(self, tokens):
292
+ """Converts a sequence of tokens (string) in a single string."""
293
+ out_string = " ".join(tokens).replace("@@ ", "").strip()
294
+ return out_string
295
+
296
+ # def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True):
297
+ # filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens))
298
+ # tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens)
299
+ # tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far)
300
+ # return ''.join(tokens_generated_so_far)
301
+
302
+ def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str, ...]:
303
+ """
304
+ Save the vocabulary and merges files to a directory.
305
+ """
306
+ if not os.path.isdir(save_directory):
307
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
308
+ return ()
309
+
310
+ vocab_files_names = getattr(self, "vocab_files_names", {})
311
+ prefix = f"{filename_prefix}-" if filename_prefix else ""
312
+
313
+ # Save vocabulary in the format expected by add_from_file: <token> <id>
314
+ # Exclude special tokens (IDs 0-3) as they are added in __init__ before add_from_file
315
+ vocab_file = os.path.join(save_directory, prefix + vocab_files_names.get("vocab_file", "vocab.txt"))
316
+ with open(vocab_file, "w", encoding="utf-8") as f:
317
+ for token, token_id in sorted(self.encoder.items(), key=lambda kv: kv[1]):
318
+ # Only save tokens with ID >= 4, as IDs 0-3 are reserved for special tokens
319
+ if token_id >= 4:
320
+ f.write(f"{token} {token_id}\n")
321
+
322
+ # Save BPE merges
323
+ merge_file = os.path.join(save_directory, prefix + vocab_files_names.get("merges_file", "bpe.codes"))
324
+ with open(merge_file, "w", encoding="utf-8") as writer:
325
+ writer.writelines(
326
+ " ".join(bpe_tokens) + "\n"
327
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1])
328
+ )
329
+
330
+ return (vocab_file, merge_file)
331
+
332
+ def add_from_file(self, f):
333
+ """
334
+ Loads a pre-existing dictionary from a text file and adds its symbols to this instance.
335
+ """
336
+ if isinstance(f, str):
337
+ try:
338
+ with open(f, "r", encoding="utf-8") as fd:
339
+ self.add_from_file(fd)
340
+ except FileNotFoundError as fnfe:
341
+ raise fnfe
342
+ except UnicodeError:
343
+ raise Exception(f"Incorrect encoding detected in {f}, please rebuild the dataset")
344
+ return
345
+
346
+ lines = f.readlines()
347
+ for lineTmp in lines:
348
+ line = lineTmp.strip()
349
+ idx = line.rfind(" ")
350
+ if idx == -1:
351
+ raise ValueError("Incorrect dictionary format, expected '<token> <cnt>'")
352
+ word = line[:idx]
353
+ self.encoder[word] = len(self.encoder)
354
+
355
+
356
+ # Natural Language Toolkit: Twitter Tokenizer
357
+ #
358
+ # Copyright (C) 2001-2020 NLTK Project
359
+ # Author: Christopher Potts <cgpotts@stanford.edu>
360
+ # Ewan Klein <ewan@inf.ed.ac.uk> (modifications)
361
+ # Pierpaolo Pantone <> (modifications)
362
+ # URL: http://nltk.org/
363
+ # For license information, see LICENSE.TXT
364
+ #
365
+
366
+
367
+ """
368
+ Twitter-aware tokenizer, designed to be flexible and easy to adapt to new domains and tasks. The basic logic is this:
369
+
370
+ 1. The tuple regex_strings defines a list of regular expression strings.
371
+
372
+ 2. The regex_strings strings are put, in order, into a compiled regular expression object called word_re.
373
+
374
+ 3. The tokenization is done by word_re.findall(s), where s is the user-supplied string, inside the tokenize() method of
375
+ the class Tokenizer.
376
+
377
+ 4. When instantiating Tokenizer objects, there is a single option: preserve_case. By default, it is set to True. If it
378
+ is set to False, then the tokenizer will lowercase everything except for emoticons.
379
+
380
+ """
381
+
382
+
383
+ ######################################################################
384
+ #
385
+ # import regex # https://github.com/nltk/nltk/issues/2409
386
+ # import html
387
+ #
388
+ ######################################################################
389
+ # The following strings are components in the regular expression
390
+ # that is used for tokenizing. It's important that phone_number
391
+ # appears first in the final regex (since it can contain whitespace).
392
+ # It also could matter that tags comes after emoticons, due to the
393
+ # possibility of having text like
394
+ #
395
+ # <:| and some text >:)
396
+ #
397
+ # Most importantly, the final element should always be last, since it
398
+ # does a last ditch whitespace-based tokenization of whatever is left.
399
+
400
+ # ToDo: Update with http://en.wikipedia.org/wiki/List_of_emoticons ?
401
+
402
+ # This particular element is used in a couple ways, so we define it
403
+ # with a name:
404
+ # docstyle-ignore
405
+ EMOTICONS = r"""
406
+ (?:
407
+ [<>]?
408
+ [:;=8] # eyes
409
+ [\-o\*\']? # optional nose
410
+ [\)\]\(\[dDpP/\:\}\{@\|\\] # mouth
411
+ |
412
+ [\)\]\(\[dDpP/\:\}\{@\|\\] # mouth
413
+ [\-o\*\']? # optional nose
414
+ [:;=8] # eyes
415
+ [<>]?
416
+ |
417
+ <3 # heart
418
+ )"""
419
+
420
+ # URL pattern due to John Gruber, modified by Tom Winzig. See
421
+ # https://gist.github.com/winzig/8894715
422
+ # docstyle-ignore
423
+ URLS = r""" # Capture 1: entire matched URL
424
+ (?:
425
+ https?: # URL protocol and colon
426
+ (?:
427
+ /{1,3} # 1-3 slashes
428
+ | # or
429
+ [a-z0-9%] # Single letter or digit or '%'
430
+ # (Trying not to match e.g. "URI::Escape")
431
+ )
432
+ | # or
433
+ # looks like domain name followed by a slash:
434
+ [a-z0-9.\-]+[.]
435
+ (?:[a-z]{2,13})
436
+ /
437
+ )
438
+ (?: # One or more:
439
+ [^\s()<>{}\[\]]+ # Run of non-space, non-()<>{}[]
440
+ | # or
441
+ \([^\s()]*?\([^\s()]+\)[^\s()]*?\) # balanced parens, one level deep: (...(...)...)
442
+ |
443
+ \([^\s]+?\) # balanced parens, non-recursive: (...)
444
+ )+
445
+ (?: # End with:
446
+ \([^\s()]*?\([^\s()]+\)[^\s()]*?\) # balanced parens, one level deep: (...(...)...)
447
+ |
448
+ \([^\s]+?\) # balanced parens, non-recursive: (...)
449
+ | # or
450
+ [^\s`!()\[\]{};:'".,<>?«»“”‘’] # not a space or one of these punct chars
451
+ )
452
+ | # OR, the following to match naked domains:
453
+ (?:
454
+ (?<!@) # not preceded by a @, avoid matching foo@_gmail.com_
455
+ [a-z0-9]+
456
+ (?:[.\-][a-z0-9]+)*
457
+ [.]
458
+ (?:[a-z]{2,13})
459
+ \b
460
+ /?
461
+ (?!@) # not succeeded by a @,
462
+ # avoid matching "foo.na" in "foo.na@example.com"
463
+ )
464
+ """
465
+
466
+ # docstyle-ignore
467
+ # The components of the tokenizer:
468
+ REGEXPS = (
469
+ URLS,
470
+ # Phone numbers:
471
+ r"""
472
+ (?:
473
+ (?: # (international)
474
+ \+?[01]
475
+ [ *\-.\)]*
476
+ )?
477
+ (?: # (area code)
478
+ [\(]?
479
+ \d{3}
480
+ [ *\-.\)]*
481
+ )?
482
+ \d{3} # exchange
483
+ [ *\-.\)]*
484
+ \d{4} # base
485
+ )""",
486
+ # ASCII Emoticons
487
+ EMOTICONS,
488
+ # HTML tags:
489
+ r"""<[^>\s]+>""",
490
+ # ASCII Arrows
491
+ r"""[\-]+>|<[\-]+""",
492
+ # Twitter username:
493
+ r"""(?:@[\w_]+)""",
494
+ # Twitter hashtags:
495
+ r"""(?:\#+[\w_]+[\w\'_\-]*[\w_]+)""",
496
+ # email addresses
497
+ r"""[\w.+-]+@[\w-]+\.(?:[\w-]\.?)+[\w-]""",
498
+ # docstyle-ignore
499
+ # Remaining word types:
500
+ r"""
501
+ (?:[^\W\d_](?:[^\W\d_]|['\-_])+[^\W\d_]) # Words with apostrophes or dashes.
502
+ |
503
+ (?:[+\-]?\d+[,/.:-]\d+[+\-]?) # Numbers, including fractions, decimals.
504
+ |
505
+ (?:[\w_]+) # Words without apostrophes or dashes.
506
+ |
507
+ (?:\.(?:\s*\.){1,}) # Ellipsis dots.
508
+ |
509
+ (?:\S) # Everything else that isn't whitespace.
510
+ """,
511
+ )
512
+
513
+ ######################################################################
514
+ # This is the core tokenizing regex:
515
+
516
+ WORD_RE = regex.compile(r"""(%s)""" % "|".join(REGEXPS), regex.VERBOSE | regex.I | regex.UNICODE)
517
+
518
+ # WORD_RE performs poorly on these patterns:
519
+ HANG_RE = regex.compile(r"([^a-zA-Z0-9])\1{3,}")
520
+
521
+ # The emoticon string gets its own regex so that we can preserve case for
522
+ # them as needed:
523
+ EMOTICON_RE = regex.compile(EMOTICONS, regex.VERBOSE | regex.I | regex.UNICODE)
524
+
525
+ # These are for regularizing HTML entities to Unicode:
526
+ ENT_RE = regex.compile(r"&(#?(x?))([^&;\s]+);")
527
+
528
+
529
+ ######################################################################
530
+ # Functions for converting html entities
531
+ ######################################################################
532
+
533
+
534
+ def _str_to_unicode(text, encoding=None, errors="strict"):
535
+ if encoding is None:
536
+ encoding = "utf-8"
537
+ if isinstance(text, bytes):
538
+ return text.decode(encoding, errors)
539
+ return text
540
+
541
+
542
+ def _replace_html_entities(text, keep=(), remove_illegal=True, encoding="utf-8"):
543
+ """
544
+ Remove entities from text by converting them to their corresponding unicode character.
545
+
546
+ Args:
547
+ text:
548
+ A unicode string or a byte string encoded in the given *encoding* (which defaults to 'utf-8').
549
+ keep (list):
550
+ List of entity names which should not be replaced. This supports both numeric entities (`&#nnnn;` and
551
+ `&#hhhh;`) and named entities (such as `&nbsp;` or `&gt;`).
552
+ remove_illegal (bool):
553
+ If `True`, entities that can't be converted are removed. Otherwise, entities that can't be converted are
554
+ kept "as is".
555
+ Returns: A unicode string with the entities removed.
556
+
557
+ See https://github.com/scrapy/w3lib/blob/master/w3lib/html.py
558
+
559
+ Examples:
560
+
561
+ ```python
562
+ >>> from nltk.tokenize.casual import _replace_html_entities
563
+
564
+ >>> _replace_html_entities(b"Price: &pound;100")
565
+ 'Price: \\xa3100'
566
+
567
+ >>> print(_replace_html_entities(b"Price: &pound;100"))
568
+ Price: £100
569
+ ```"""
570
+
571
+ def _convert_entity(match):
572
+ entity_body = match.group(3)
573
+ if match.group(1):
574
+ try:
575
+ if match.group(2):
576
+ number = int(entity_body, 16)
577
+ else:
578
+ number = int(entity_body, 10)
579
+ # Numeric character references in the 80-9F range are typically
580
+ # interpreted by browsers as representing the characters mapped
581
+ # to bytes 80-9F in the Windows-1252 encoding. For more info
582
+ # see: https://en.wikipedia.org/wiki/ISO/IEC_8859-1#Similar_character_sets
583
+ if 0x80 <= number <= 0x9F:
584
+ return bytes((number,)).decode("cp1252")
585
+ except ValueError:
586
+ number = None
587
+ else:
588
+ if entity_body in keep:
589
+ return match.group(0)
590
+ else:
591
+ number = html.entities.name2codepoint.get(entity_body)
592
+ if number is not None:
593
+ try:
594
+ return chr(number)
595
+ except (ValueError, OverflowError):
596
+ pass
597
+
598
+ return "" if remove_illegal else match.group(0)
599
+
600
+ return ENT_RE.sub(_convert_entity, _str_to_unicode(text, encoding))
601
+
602
+
603
+ ######################################################################
604
+
605
+
606
+ class TweetTokenizer:
607
+ r"""
608
+ Examples:
609
+
610
+ ```python
611
+ >>> # Tokenizer for tweets.
612
+ >>> from nltk.tokenize import TweetTokenizer
613
+
614
+ >>> tknzr = TweetTokenizer()
615
+ >>> s0 = "This is a cooool #dummysmiley: :-) :-P <3 and some arrows < > -> <--"
616
+ >>> tknzr.tokenize(s0)
617
+ ['This', 'is', 'a', 'cooool', '#dummysmiley', ':', ':-)', ':-P', '<3', 'and', 'some', 'arrows', '<', '>', '->', '<--']
618
+
619
+ >>> # Examples using *strip_handles* and *reduce_len parameters*:
620
+ >>> tknzr = TweetTokenizer(strip_handles=True, reduce_len=True)
621
+ >>> s1 = "@remy: This is waaaaayyyy too much for you!!!!!!"
622
+ >>> tknzr.tokenize(s1)
623
+ [':', 'This', 'is', 'waaayyy', 'too', 'much', 'for', 'you', '!', '!', '!']
624
+ ```"""
625
+
626
+ def __init__(self, preserve_case=True, reduce_len=False, strip_handles=False):
627
+ self.preserve_case = preserve_case
628
+ self.reduce_len = reduce_len
629
+ self.strip_handles = strip_handles
630
+
631
+ def tokenize(self, text):
632
+ """
633
+ Args:
634
+ text: str
635
+
636
+ Returns: list(str) A tokenized list of strings; concatenating this list returns the original string if
637
+ `preserve_case=False`
638
+ """
639
+ # Fix HTML character entities:
640
+ text = _replace_html_entities(text)
641
+ # Remove username handles
642
+ if self.strip_handles:
643
+ text = remove_handles(text)
644
+ # Normalize word lengthening
645
+ if self.reduce_len:
646
+ text = reduce_lengthening(text)
647
+ # Shorten problematic sequences of characters
648
+ safe_text = HANG_RE.sub(r"\1\1\1", text)
649
+ # Tokenize:
650
+ words = WORD_RE.findall(safe_text)
651
+ # Possibly alter the case, but avoid changing emoticons like :D into :d:
652
+ if not self.preserve_case:
653
+ words = [x if EMOTICON_RE.search(x) else x.lower() for x in words]
654
+ return words
655
+
656
+
657
+ ######################################################################
658
+ # Normalization Functions
659
+ ######################################################################
660
+
661
+
662
+ def reduce_lengthening(text):
663
+ """
664
+ Replace repeated character sequences of length 3 or greater with sequences of length 3.
665
+ """
666
+ pattern = regex.compile(r"(.)\1{2,}")
667
+ return pattern.sub(r"\1\1\1", text)
668
+
669
+
670
+ def remove_handles(text):
671
+ """
672
+ Remove Twitter username handles from text.
673
+ """
674
+ pattern = regex.compile(
675
+ r"(?<![A-Za-z0-9_!@#\$%&*])@(([A-Za-z0-9_]){20}(?!@))|(?<![A-Za-z0-9_!@#\$%&*])@(([A-Za-z0-9_]){1,19})(?![A-Za-z0-9_]*@)"
676
+ )
677
+ # Substitute handles with ' ' to ensure that text on either side of removed handles are tokenized correctly
678
+ return pattern.sub(" ", text)
679
+
680
+
681
+ ######################################################################
682
+ # Tokenization Function
683
+ ######################################################################
684
+
685
+
686
+ def casual_tokenize(text, preserve_case=True, reduce_len=False, strip_handles=False):
687
+ """
688
+ Convenience function for wrapping the tokenizer.
689
+ """
690
+ return TweetTokenizer(preserve_case=preserve_case, reduce_len=reduce_len, strip_handles=strip_handles).tokenize(
691
+ text
692
+ )
693
+
694
+
695
+ ###############################################################################
696
+
697
+
698
+ __all__ = ["BertweetTokenizer"]
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/biogpt/__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_biogpt import *
22
+ from .modeling_biogpt import *
23
+ from .tokenization_biogpt 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__)
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/biogpt/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (822 Bytes). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/biogpt/__pycache__/configuration_biogpt.cpython-311.pyc ADDED
Binary file (2.56 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/biogpt/__pycache__/modeling_biogpt.cpython-311.pyc ADDED
Binary file (32 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/biogpt/__pycache__/modular_biogpt.cpython-311.pyc ADDED
Binary file (24 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/biogpt/__pycache__/tokenization_biogpt.cpython-311.pyc ADDED
Binary file (17.4 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/biogpt/configuration_biogpt.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team and Microsoft Research AI4Science 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
+ """BioGPT 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/biogpt")
23
+ @strict
24
+ class BioGptConfig(PreTrainedConfig):
25
+ r"""
26
+ Example:
27
+
28
+ ```python
29
+ >>> from transformers import BioGptModel, BioGptConfig
30
+
31
+ >>> # Initializing a BioGPT microsoft/biogpt style configuration
32
+ >>> configuration = BioGptConfig()
33
+
34
+ >>> # Initializing a model from the microsoft/biogpt style configuration
35
+ >>> model = BioGptModel(configuration)
36
+
37
+ >>> # Accessing the model configuration
38
+ >>> configuration = model.config
39
+ ```"""
40
+
41
+ model_type = "biogpt"
42
+
43
+ vocab_size: int = 42384
44
+ hidden_size: int = 1024
45
+ num_hidden_layers: int = 24
46
+ num_attention_heads: int = 16
47
+ intermediate_size: int = 4096
48
+ hidden_act: str = "gelu"
49
+ hidden_dropout_prob: float | int = 0.1
50
+ attention_probs_dropout_prob: float | int = 0.1
51
+ max_position_embeddings: int = 1024
52
+ initializer_range: float = 0.02
53
+ layer_norm_eps: float = 1e-12
54
+ scale_embedding: bool = True
55
+ use_cache: bool = True
56
+ layerdrop: float | int = 0.0
57
+ activation_dropout: float | int = 0.0
58
+ pad_token_id: int | None = 1
59
+ bos_token_id: int | None = 0
60
+ eos_token_id: int | list[int] | None = 2
61
+ tie_word_embeddings: bool = True
62
+
63
+
64
+ __all__ = ["BioGptConfig"]