JinghuiLuAstronaut commited on
Commit
3d07b55
·
verified ·
1 Parent(s): 1fbeba4

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/glm_ocr/__init__.py +28 -0
  2. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/glm_ocr/configuration_glm_ocr.py +185 -0
  3. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/glm_ocr/modeling_glm_ocr.py +1603 -0
  4. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/glm_ocr/modular_glm_ocr.py +319 -0
  5. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/jina_embeddings_v3/__init__.py +29 -0
  6. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/jina_embeddings_v3/modular_jina_embeddings_v3.py +406 -0
  7. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/lasr/__init__.py +29 -0
  8. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/lasr/configuration_lasr.py +149 -0
  9. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/lasr/feature_extraction_lasr.py +275 -0
  10. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/lasr/modular_lasr.py +606 -0
  11. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/pegasus_x/modeling_pegasus_x.py +1350 -0
  12. LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_012000.pt +3 -0
  13. LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_018000.pt +3 -0
  14. LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_019000.pt +3 -0
  15. LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_027000.pt +3 -0
  16. LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_081000.pt +3 -0
  17. LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_097000.pt +3 -0
  18. LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_177000.pt +3 -0
  19. LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_181000.pt +3 -0
  20. LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_216000.pt +3 -0
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/glm_ocr/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 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
+
15
+ from typing import TYPE_CHECKING
16
+
17
+ from ...utils import _LazyModule
18
+ from ...utils.import_utils import define_import_structure
19
+
20
+
21
+ if TYPE_CHECKING:
22
+ from .configuration_glm_ocr import *
23
+ from .modeling_glm_ocr import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/glm_ocr/configuration_glm_ocr.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/glm_ocr/modular_glm_ocr.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_glm_ocr.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2026 the HuggingFace Team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ from huggingface_hub.dataclasses import strict
22
+
23
+ from ...configuration_utils import PreTrainedConfig
24
+ from ...modeling_rope_utils import RopeParameters
25
+ from ...utils import auto_docstring
26
+
27
+
28
+ @auto_docstring(checkpoint="zai-org/GLM-OCR")
29
+ @strict
30
+ class GlmOcrVisionConfig(PreTrainedConfig):
31
+ r"""
32
+ out_hidden_size (`int`, *optional*, defaults to 4096):
33
+ The output hidden size of the vision model.
34
+
35
+ Example:
36
+
37
+ ```python
38
+ >>> from transformers import GlmOcrVisionConfig, GlmOcrVisionModel
39
+
40
+ >>> # Initializing a GlmOcrVisionConfig GLM-4.1V-9B style configuration
41
+ >>> configuration = GlmOcrVisionConfig()
42
+
43
+ >>> # Initializing a model (with random weights) from the GLM-4.1V-9B configuration
44
+ >>> model = GlmOcrVisionModel(configuration)
45
+
46
+ >>> # Accessing the model configuration
47
+ >>> configuration = model.config
48
+ ```"""
49
+
50
+ model_type = "glm_ocr_vision"
51
+ base_config_key = "vision_config"
52
+
53
+ depth: int = 24
54
+ hidden_size: int = 1024
55
+ hidden_act: str = "silu"
56
+ attention_bias: bool = True
57
+ attention_dropout: float | int = 0.0
58
+ num_heads: int = 16
59
+ in_channels: int = 3
60
+ image_size: int | list[int] | tuple[int, int] = 336
61
+ patch_size: int | list[int] | tuple[int, int] = 14
62
+ rms_norm_eps: float = 1e-05
63
+ spatial_merge_size: int = 2
64
+ temporal_patch_size: int | list[int] | tuple[int, int] = 2
65
+ out_hidden_size: int = 1536
66
+ intermediate_size: int = 4096
67
+ initializer_range: float = 0.02
68
+
69
+
70
+ @auto_docstring(checkpoint="zai-org/GLM-OCR")
71
+ @strict
72
+ class GlmOcrTextConfig(PreTrainedConfig):
73
+ r"""
74
+ Example:
75
+
76
+ ```python
77
+ >>> from transformers import GlmOcrTextModel, GlmOcrConfig
78
+
79
+ >>> # Initializing a GLM-OCR style configuration
80
+ >>> configuration = GlmOcrConfig()
81
+
82
+ >>> # Initializing a model from the GLM-OCR style configuration
83
+ >>> model = GlmOcrTextModel(configuration)
84
+
85
+ >>> # Accessing the model configuration
86
+ >>> configuration = model.config
87
+ ```"""
88
+
89
+ model_type = "glm_ocr_text"
90
+ base_config_key = "text_config"
91
+ keys_to_ignore_at_inference = ["past_key_values"]
92
+ # Default tensor parallel plan for base model `GlmOcr`
93
+ base_model_tp_plan = {
94
+ "layers.*.self_attn.q_proj": "colwise",
95
+ "layers.*.self_attn.k_proj": "colwise",
96
+ "layers.*.self_attn.v_proj": "colwise",
97
+ "layers.*.self_attn.o_proj": "rowwise",
98
+ "layers.*.mlp.gate_up_proj": "colwise_gather_output", # we need to replicate here due to the `chunk` operation
99
+ "layers.*.mlp.down_proj": "rowwise_split_input", # input is replicated due to the `chunk` operation
100
+ }
101
+ base_model_pp_plan = {
102
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
103
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
104
+ "norm": (["hidden_states"], ["hidden_states"]),
105
+ }
106
+ ignore_keys_at_rope_validation = {"mrope_section"}
107
+
108
+ vocab_size: int = 59392
109
+ hidden_size: int = 1024
110
+ intermediate_size: int = 4096
111
+ num_hidden_layers: int = 16
112
+ num_attention_heads: int = 16
113
+ num_key_value_heads: int = 8
114
+ hidden_act: str = "silu"
115
+ max_position_embeddings: int = 131072
116
+ initializer_range: float = 0.02
117
+ rms_norm_eps: float = 1e-05
118
+ use_cache: bool = True
119
+ attention_dropout: float | int = 0.0
120
+ rope_parameters: RopeParameters | dict | None = None
121
+ pad_token_id: int | None = None
122
+
123
+ def __post_init__(self, **kwargs):
124
+ if self.num_key_value_heads is None:
125
+ self.num_key_value_heads = self.num_attention_heads
126
+
127
+ super().__post_init__(**kwargs)
128
+
129
+
130
+ @auto_docstring(checkpoint="zai-org/GLM-OCR")
131
+ @strict
132
+ class GlmOcrConfig(PreTrainedConfig):
133
+ r"""
134
+ image_start_token_id (`int`, *optional*, defaults to 59256):
135
+ The image start token index to encode the start of image.
136
+ image_end_token_id (`int`, *optional*, defaults to 59257):
137
+ The image end token index to encode the end of image.
138
+ video_start_token_id (`int`, *optional*, defaults to 59258):
139
+ The video start token index to encode the start of video.
140
+ video_end_token_id (`int`, *optional*, defaults to 59259):
141
+ The video end token index to encode the end of video.
142
+
143
+ ```python
144
+ >>> from transformers import GlmOcrForConditionalGeneration, GlmOcrConfig
145
+
146
+ >>> # Initializing a GLM-OCR style configuration
147
+ >>> configuration = GlmOcrConfig()
148
+
149
+ >>> # Initializing a model from the GLM-OCR style configuration
150
+ >>> model = GlmOcrForConditionalGeneration(configuration)
151
+
152
+ >>> # Accessing the model configuration
153
+ >>> configuration = model.config
154
+ ```"""
155
+
156
+ model_type = "glm_ocr"
157
+ sub_configs = {"vision_config": GlmOcrVisionConfig, "text_config": GlmOcrTextConfig}
158
+ keys_to_ignore_at_inference = ["past_key_values"]
159
+
160
+ text_config: dict | PreTrainedConfig | None = None
161
+ vision_config: dict | PreTrainedConfig | None = None
162
+
163
+ image_token_id: int = 59280
164
+ video_token_id: int = 59281
165
+ image_start_token_id: int = 59256
166
+ image_end_token_id: int = 59257
167
+ video_start_token_id: int = 59258
168
+ video_end_token_id: int = 59259
169
+ tie_word_embeddings: bool = False
170
+
171
+ def __post_init__(self, **kwargs):
172
+ if isinstance(self.vision_config, dict):
173
+ self.vision_config = self.sub_configs["vision_config"](**self.vision_config)
174
+ elif self.vision_config is None:
175
+ self.vision_config = self.sub_configs["vision_config"](**kwargs)
176
+
177
+ if isinstance(self.text_config, dict):
178
+ self.text_config = self.sub_configs["text_config"](**self.text_config)
179
+ elif self.text_config is None:
180
+ self.text_config = self.sub_configs["text_config"](**kwargs)
181
+
182
+ super().__post_init__(**kwargs)
183
+
184
+
185
+ __all__ = ["GlmOcrConfig", "GlmOcrTextConfig", "GlmOcrVisionConfig"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/glm_ocr/modeling_glm_ocr.py ADDED
@@ -0,0 +1,1603 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/glm_ocr/modular_glm_ocr.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_glm_ocr.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2026 the HuggingFace Team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ import itertools
22
+ import warnings
23
+ from collections.abc import Callable
24
+ from dataclasses import dataclass
25
+ from typing import Any, Optional
26
+
27
+ import torch
28
+ import torch.nn as nn
29
+ from torch.nn import LayerNorm
30
+
31
+ from ... import initialization as init
32
+ from ...activations import ACT2FN
33
+ from ...cache_utils import Cache, DynamicCache
34
+ from ...generation import GenerationMixin
35
+ from ...integrations import use_kernel_forward_from_hub
36
+ from ...masking_utils import create_causal_mask
37
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
38
+ from ...modeling_layers import GradientCheckpointingLayer
39
+ from ...modeling_outputs import BaseModelOutputWithPast, BaseModelOutputWithPooling, ModelOutput
40
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
41
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
42
+ from ...processing_utils import Unpack
43
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, torch_compilable_check
44
+ from ...utils.generic import (
45
+ accepts_precomputed_kwargs,
46
+ is_flash_attention_requested,
47
+ maybe_autocast,
48
+ merge_with_config_defaults,
49
+ )
50
+ from ...utils.output_capturing import capture_outputs
51
+ from ...vision_utils import get_vision_cu_seqlens, get_vision_position_ids
52
+ from .configuration_glm_ocr import GlmOcrConfig, GlmOcrTextConfig, GlmOcrVisionConfig
53
+
54
+
55
+ @use_kernel_forward_from_hub("RMSNorm")
56
+ class GlmOcrRMSNorm(nn.Module):
57
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
58
+ """
59
+ GlmOcrRMSNorm is equivalent to T5LayerNorm
60
+ """
61
+ super().__init__()
62
+ self.weight = nn.Parameter(torch.ones(hidden_size))
63
+ self.variance_epsilon = eps
64
+
65
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
66
+ input_dtype = hidden_states.dtype
67
+ hidden_states = hidden_states.to(torch.float32)
68
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
69
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
70
+ return self.weight * hidden_states.to(input_dtype)
71
+
72
+ def extra_repr(self):
73
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
74
+
75
+
76
+ class GlmOcrVisionMlp(nn.Module):
77
+ def __init__(self, config, bias: bool = True):
78
+ super().__init__()
79
+ self.hidden_size = config.hidden_size
80
+ self.intermediate_size = config.intermediate_size
81
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=bias)
82
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=bias)
83
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=bias)
84
+ self.act_fn = ACT2FN[config.hidden_act]
85
+
86
+ def forward(self, hidden_state):
87
+ return self.down_proj(self.act_fn(self.gate_proj(hidden_state)) * self.up_proj(hidden_state))
88
+
89
+
90
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
91
+ """
92
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
93
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
94
+ """
95
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
96
+ if n_rep == 1:
97
+ return hidden_states
98
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
99
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
100
+
101
+
102
+ def eager_attention_forward(
103
+ module: nn.Module,
104
+ query: torch.Tensor,
105
+ key: torch.Tensor,
106
+ value: torch.Tensor,
107
+ attention_mask: torch.Tensor | None,
108
+ scaling: float,
109
+ dropout: float = 0.0,
110
+ **kwargs: Unpack[TransformersKwargs],
111
+ ):
112
+ key_states = repeat_kv(key, module.num_key_value_groups)
113
+ value_states = repeat_kv(value, module.num_key_value_groups)
114
+
115
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
116
+ if attention_mask is not None:
117
+ attn_weights = attn_weights + attention_mask
118
+
119
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
120
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
121
+ attn_output = torch.matmul(attn_weights, value_states)
122
+ attn_output = attn_output.transpose(1, 2).contiguous()
123
+
124
+ return attn_output, attn_weights
125
+
126
+
127
+ def rotate_half_llm(x):
128
+ """Rotates half the hidden dims of the input."""
129
+ x1 = x[..., 0::2]
130
+ x2 = x[..., 1::2]
131
+ return torch.stack((-x2, x1), dim=-1).flatten(-2)
132
+
133
+
134
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
135
+ """Applies Rotary Position Embedding to the query and key tensors.
136
+
137
+ Args:
138
+ q (`torch.Tensor`): The query tensor.
139
+ k (`torch.Tensor`): The key tensor.
140
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
141
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
142
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
143
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
144
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
145
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
146
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
147
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
148
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
149
+ Returns:
150
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
151
+ """
152
+ cos = cos.unsqueeze(unsqueeze_dim)
153
+ sin = sin.unsqueeze(unsqueeze_dim)
154
+
155
+ # Interleave them instead of usual shape
156
+ cos = cos[..., : cos.shape[-1] // 2].repeat_interleave(2, dim=-1)
157
+ sin = sin[..., : sin.shape[-1] // 2].repeat_interleave(2, dim=-1)
158
+
159
+ # Keep half or full tensor for later concatenation
160
+ rotary_dim = cos.shape[-1]
161
+ q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
162
+ k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
163
+
164
+ # Apply rotary embeddings on the first half or full tensor
165
+ q_embed = (q_rot * cos) + (rotate_half_llm(q_rot) * sin)
166
+ k_embed = (k_rot * cos) + (rotate_half_llm(k_rot) * sin)
167
+
168
+ # Concatenate back to full shape
169
+ q_embed = torch.cat([q_embed, q_pass], dim=-1)
170
+ k_embed = torch.cat([k_embed, k_pass], dim=-1)
171
+ return q_embed, k_embed
172
+
173
+
174
+ class GlmOcrTextAttention(nn.Module):
175
+ """
176
+ Multi-headed attention from 'Attention Is All You Need' paper.
177
+ and "Generating Long Sequences with Sparse Transformers".
178
+ """
179
+
180
+ def __init__(self, config: GlmOcrTextConfig, layer_idx: int | None = None):
181
+ super().__init__()
182
+ self.config = config
183
+ self.layer_idx = layer_idx
184
+
185
+ self.hidden_size = config.hidden_size
186
+ self.num_heads = config.num_attention_heads
187
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
188
+ self.num_key_value_heads = config.num_key_value_heads
189
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
190
+ self.is_causal = True
191
+ self.attention_dropout = config.attention_dropout
192
+ self.rope_parameters = config.rope_parameters
193
+ self.scaling = self.head_dim**-0.5
194
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
195
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
196
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
197
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
198
+
199
+ def forward(
200
+ self,
201
+ hidden_states: torch.Tensor,
202
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
203
+ attention_mask: torch.Tensor | None = None,
204
+ past_key_values: Cache | None = None,
205
+ **kwargs: Unpack[FlashAttentionKwargs],
206
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
207
+ bsz, q_len, _ = hidden_states.size()
208
+
209
+ query_states = self.q_proj(hidden_states)
210
+ key_states = self.k_proj(hidden_states)
211
+ value_states = self.v_proj(hidden_states)
212
+
213
+ query_states = query_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
214
+ key_states = key_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
215
+ value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
216
+
217
+ cos, sin = position_embeddings
218
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
219
+
220
+ if past_key_values is not None:
221
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
222
+
223
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
224
+ self.config._attn_implementation, eager_attention_forward
225
+ )
226
+
227
+ attn_output, attn_weights = attention_interface(
228
+ self,
229
+ query_states,
230
+ key_states,
231
+ value_states,
232
+ attention_mask,
233
+ dropout=0.0 if not self.training else self.attention_dropout,
234
+ scaling=self.scaling,
235
+ **kwargs,
236
+ )
237
+
238
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
239
+ attn_output = self.o_proj(attn_output)
240
+ return attn_output, attn_weights
241
+
242
+
243
+ class GlmOcrTextMLP(nn.Module):
244
+ def __init__(self, config):
245
+ super().__init__()
246
+
247
+ self.config = config
248
+ self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)
249
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
250
+ self.activation_fn = ACT2FN[config.hidden_act]
251
+
252
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
253
+ up_states = self.gate_up_proj(hidden_states)
254
+
255
+ gate, up_states = up_states.chunk(2, dim=-1)
256
+ up_states = up_states * self.activation_fn(gate)
257
+
258
+ return self.down_proj(up_states)
259
+
260
+
261
+ class GlmOcrTextDecoderLayer(GradientCheckpointingLayer):
262
+ def __init__(self, config: GlmOcrTextConfig, layer_idx: int):
263
+ super().__init__()
264
+ self.hidden_size = config.hidden_size
265
+ self.self_attn = GlmOcrTextAttention(config, layer_idx)
266
+ self.mlp = GlmOcrTextMLP(config)
267
+ self.input_layernorm = GlmOcrRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
268
+ self.post_attention_layernorm = GlmOcrRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
269
+ self.post_self_attn_layernorm = GlmOcrRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
270
+ self.post_mlp_layernorm = GlmOcrRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
271
+
272
+ @auto_docstring
273
+ def forward(
274
+ self,
275
+ hidden_states: torch.Tensor,
276
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
277
+ attention_mask: torch.Tensor | None = None,
278
+ position_ids: torch.LongTensor | None = None,
279
+ past_key_values: Cache | None = None,
280
+ use_cache: bool | None = False,
281
+ **kwargs,
282
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
283
+ residual = hidden_states
284
+
285
+ hidden_states = self.input_layernorm(hidden_states)
286
+
287
+ # Self Attention
288
+ hidden_states, _ = self.self_attn(
289
+ hidden_states=hidden_states,
290
+ position_embeddings=position_embeddings,
291
+ attention_mask=attention_mask,
292
+ position_ids=position_ids,
293
+ past_key_values=past_key_values,
294
+ use_cache=use_cache,
295
+ **kwargs,
296
+ )
297
+
298
+ hidden_states = self.post_self_attn_layernorm(hidden_states)
299
+ hidden_states = residual + hidden_states
300
+
301
+ # Fully Connected
302
+ residual = hidden_states
303
+ hidden_states = self.post_attention_layernorm(hidden_states)
304
+ hidden_states = self.mlp(hidden_states)
305
+ hidden_states = self.post_mlp_layernorm(hidden_states)
306
+ hidden_states = residual + hidden_states
307
+
308
+ return hidden_states
309
+
310
+
311
+ class GlmOcrVisionRotaryEmbedding(nn.Module):
312
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
313
+
314
+ def __init__(self, dim: int, theta: float = 10000.0) -> None:
315
+ super().__init__()
316
+ self.dim = dim
317
+ self.theta = theta
318
+ inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim))
319
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
320
+
321
+ def forward(self, position_ids: torch.Tensor) -> torch.Tensor:
322
+ return (position_ids.unsqueeze(-1) * self.inv_freq).flatten(1)
323
+
324
+
325
+ @auto_docstring
326
+ class GlmOcrPreTrainedModel(PreTrainedModel):
327
+ config: GlmOcrConfig
328
+ base_model_prefix = "model"
329
+ input_modalities = ("image", "video", "text")
330
+ supports_gradient_checkpointing = True
331
+ _no_split_modules = ["GlmOcrTextDecoderLayer", "GlmOcrVisionBlock"]
332
+ _skip_keys_device_placement = ["past_key_values"]
333
+ _supports_flash_attn = True
334
+ _supports_sdpa = True
335
+
336
+ _can_compile_fullgraph = True
337
+ _supports_attention_backend = True
338
+ _keys_to_ignore_on_load_unexpected = [r"model\.language_model\.layers\.16.*"]
339
+
340
+ def _init_weights(self, module):
341
+ super()._init_weights(module)
342
+ if isinstance(module, GlmOcrVisionRotaryEmbedding):
343
+ inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim))
344
+ init.copy_(module.inv_freq, inv_freq)
345
+
346
+
347
+ @auto_docstring(
348
+ custom_intro="""
349
+ Base class for Llava outputs, with hidden states and attentions.
350
+ """
351
+ )
352
+ @dataclass
353
+ class GlmOcrModelOutputWithPast(ModelOutput):
354
+ r"""
355
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
356
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
357
+
358
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
359
+ `past_key_values` input) to speed up sequential decoding.
360
+ rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
361
+ The rope index difference between sequence length and multimodal rope.
362
+ """
363
+
364
+ last_hidden_state: torch.FloatTensor | None = None
365
+ past_key_values: Cache | None = None
366
+ hidden_states: tuple[torch.FloatTensor] | None = None
367
+ attentions: tuple[torch.FloatTensor] | None = None
368
+ rope_deltas: torch.LongTensor | None = None
369
+
370
+
371
+ def rotate_half(x):
372
+ """Rotates half the hidden dims of the input."""
373
+ x1 = x[..., : x.shape[-1] // 2]
374
+ x2 = x[..., x.shape[-1] // 2 :]
375
+ return torch.cat((-x2, x1), dim=-1)
376
+
377
+
378
+ def apply_rotary_pos_emb_vision(
379
+ q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor
380
+ ) -> tuple[torch.Tensor, torch.Tensor]:
381
+ orig_q_dtype = q.dtype
382
+ orig_k_dtype = k.dtype
383
+ q, k = q.float(), k.float()
384
+ cos, sin = cos.unsqueeze(-2).float(), sin.unsqueeze(-2).float()
385
+ q_embed = (q * cos) + (rotate_half(q) * sin)
386
+ k_embed = (k * cos) + (rotate_half(k) * sin)
387
+ q_embed = q_embed.to(orig_q_dtype)
388
+ k_embed = k_embed.to(orig_k_dtype)
389
+ return q_embed, k_embed
390
+
391
+
392
+ class GlmOcrVisionAttention(nn.Module):
393
+ def __init__(self, config: GlmOcrVisionConfig) -> None:
394
+ super().__init__()
395
+ self.dim = config.hidden_size
396
+ self.num_heads = config.num_heads
397
+ self.head_dim = self.dim // self.num_heads
398
+ self.num_key_value_groups = 1 # needed for eager attention
399
+ self.qkv = nn.Linear(config.hidden_size, config.hidden_size * 3, bias=config.attention_bias)
400
+ self.proj = nn.Linear(config.hidden_size, config.hidden_size, bias=config.attention_bias)
401
+ self.scaling = self.head_dim**-0.5
402
+ self.config = config
403
+ self.attention_dropout = config.attention_dropout
404
+ self.is_causal = False
405
+ self.q_norm = GlmOcrRMSNorm(self.head_dim, eps=config.rms_norm_eps)
406
+ self.k_norm = GlmOcrRMSNorm(self.head_dim, eps=config.rms_norm_eps)
407
+
408
+ def forward(
409
+ self,
410
+ hidden_states: torch.Tensor,
411
+ cu_seqlens: torch.Tensor,
412
+ rotary_pos_emb: torch.Tensor | None = None,
413
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
414
+ **kwargs,
415
+ ) -> torch.Tensor:
416
+ seq_length = hidden_states.shape[0]
417
+ query_states, key_states, value_states = (
418
+ self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
419
+ )
420
+
421
+ query_states = self.q_norm(query_states)
422
+ key_states = self.k_norm(key_states)
423
+
424
+ cos, sin = position_embeddings
425
+ query_states, key_states = apply_rotary_pos_emb_vision(query_states, key_states, cos, sin)
426
+ query_states = query_states.transpose(0, 1).unsqueeze(0)
427
+ key_states = key_states.transpose(0, 1).unsqueeze(0)
428
+ value_states = value_states.transpose(0, 1).unsqueeze(0)
429
+
430
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
431
+ self.config._attn_implementation, eager_attention_forward
432
+ )
433
+
434
+ if is_flash_attention_requested(self.config):
435
+ # Flash Attention: Use cu_seqlens for variable length attention
436
+ max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max()
437
+ attn_output, _ = attention_interface(
438
+ self,
439
+ query_states,
440
+ key_states,
441
+ value_states,
442
+ attention_mask=None,
443
+ scaling=self.scaling,
444
+ dropout=0.0 if not self.training else self.attention_dropout,
445
+ cu_seq_lens_q=cu_seqlens,
446
+ cu_seq_lens_k=cu_seqlens,
447
+ max_length_q=max_seqlen,
448
+ max_length_k=max_seqlen,
449
+ is_causal=False,
450
+ **kwargs,
451
+ )
452
+ else:
453
+ # Other implementations: Process each chunk separately
454
+ lengths = cu_seqlens[1:] - cu_seqlens[:-1]
455
+ splits = [
456
+ torch.split(tensor, lengths.tolist(), dim=2) for tensor in (query_states, key_states, value_states)
457
+ ]
458
+
459
+ attn_outputs = [
460
+ attention_interface(
461
+ self,
462
+ q,
463
+ k,
464
+ v,
465
+ attention_mask=None,
466
+ scaling=self.scaling,
467
+ dropout=0.0 if not self.training else self.attention_dropout,
468
+ is_causal=False,
469
+ **kwargs,
470
+ )[0]
471
+ for q, k, v in zip(*splits)
472
+ ]
473
+ attn_output = torch.cat(attn_outputs, dim=1)
474
+
475
+ attn_output = attn_output.reshape(seq_length, -1).contiguous()
476
+ attn_output = self.proj(attn_output)
477
+ return attn_output
478
+
479
+
480
+ class GlmOcrVisionBlock(GradientCheckpointingLayer):
481
+ def __init__(self, config) -> None:
482
+ super().__init__()
483
+ self.norm1 = GlmOcrRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
484
+ self.norm2 = GlmOcrRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
485
+ self.attn = GlmOcrVisionAttention(config)
486
+ self.mlp = GlmOcrVisionMlp(config, bias=config.attention_bias)
487
+
488
+ @auto_docstring
489
+ def forward(
490
+ self,
491
+ hidden_states: torch.Tensor,
492
+ cu_seqlens: torch.Tensor,
493
+ rotary_pos_emb: torch.Tensor | None = None,
494
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
495
+ **kwargs,
496
+ ) -> torch.Tensor:
497
+ r"""
498
+ cu_seqlens (`torch.Tensor`):
499
+ Cumulative sequence lengths used for packed variable-length attention in Flash Attention kernels.
500
+ rotary_pos_emb (`torch.Tensor`, *optional*):
501
+ Precomputed rotary positional embeddings applied to the vision attention query/key states.
502
+ """
503
+ hidden_states = hidden_states + self.attn(
504
+ self.norm1(hidden_states),
505
+ cu_seqlens=cu_seqlens,
506
+ rotary_pos_emb=rotary_pos_emb,
507
+ position_embeddings=position_embeddings,
508
+ **kwargs,
509
+ )
510
+ hidden_states = hidden_states + self.mlp(self.norm2(hidden_states))
511
+ return hidden_states
512
+
513
+
514
+ class GlmOcrVisionPatchMerger(nn.Module):
515
+ def __init__(self, dim: int, context_dim: int, hidden_act: str, bias: bool = False) -> None:
516
+ super().__init__()
517
+ self.proj = nn.Linear(dim, dim, bias=bias)
518
+ self.post_projection_norm = LayerNorm(dim)
519
+ self.gate_proj = nn.Linear(dim, context_dim, bias=bias)
520
+ self.up_proj = nn.Linear(dim, context_dim, bias=bias)
521
+ self.down_proj = nn.Linear(context_dim, dim, bias=bias)
522
+ self.act1 = nn.GELU()
523
+ self.act_fn = ACT2FN[hidden_act]
524
+
525
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
526
+ hidden_state = self.proj(hidden_state)
527
+ hidden_state = self.act1(self.post_projection_norm(hidden_state))
528
+ return self.down_proj(self.act_fn(self.gate_proj(hidden_state)) * self.up_proj(hidden_state))
529
+
530
+
531
+ class GlmOcrVisionPatchEmbed(nn.Module):
532
+ def __init__(self, config: GlmOcrVisionConfig) -> None:
533
+ super().__init__()
534
+ self.patch_size = config.patch_size
535
+ self.temporal_patch_size = config.temporal_patch_size
536
+ self.in_channels = config.in_channels
537
+ self.embed_dim = config.hidden_size
538
+
539
+ kernel_size = [self.temporal_patch_size, self.patch_size, self.patch_size]
540
+ self.proj = nn.Conv3d(self.in_channels, self.embed_dim, kernel_size=kernel_size, stride=kernel_size)
541
+
542
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
543
+ target_dtype = self.proj.weight.dtype
544
+ hidden_states = hidden_states.view(
545
+ -1, self.in_channels, self.temporal_patch_size, self.patch_size, self.patch_size
546
+ )
547
+ hidden_states = self.proj(hidden_states.to(dtype=target_dtype)).view(-1, self.embed_dim)
548
+ return hidden_states
549
+
550
+
551
+ class GlmOcrVisionModel(GlmOcrPreTrainedModel):
552
+ config: GlmOcrVisionConfig
553
+ input_modalities = ("image", "video")
554
+ _no_split_modules = ["GlmOcrVisionBlock"]
555
+ _can_record_outputs = {
556
+ "hidden_states": GlmOcrVisionBlock,
557
+ "attentions": GlmOcrVisionAttention,
558
+ }
559
+
560
+ def __init__(self, config) -> None:
561
+ super().__init__(config)
562
+ self.spatial_merge_size = config.spatial_merge_size
563
+ self.patch_size = config.patch_size
564
+ self.patch_embed = GlmOcrVisionPatchEmbed(config)
565
+
566
+ head_dim = config.hidden_size // config.num_heads
567
+ self.rotary_pos_emb = GlmOcrVisionRotaryEmbedding(head_dim // 2)
568
+
569
+ self.blocks = nn.ModuleList([GlmOcrVisionBlock(config) for _ in range(config.depth)])
570
+ self.merger = GlmOcrVisionPatchMerger(
571
+ dim=config.out_hidden_size,
572
+ context_dim=config.out_hidden_size * config.in_channels,
573
+ hidden_act=config.hidden_act,
574
+ )
575
+ self.downsample = nn.Conv2d(
576
+ in_channels=config.hidden_size,
577
+ out_channels=config.out_hidden_size,
578
+ kernel_size=config.spatial_merge_size,
579
+ stride=config.spatial_merge_size,
580
+ )
581
+ self.post_layernorm = GlmOcrRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
582
+
583
+ self.gradient_checkpointing = False
584
+ self.post_init()
585
+
586
+ def rot_pos_emb(self, grid_thw):
587
+ warnings.warn(
588
+ f"`{self.__class__.__name__}.rot_pos_emb` is deprecated and will be removed in v5.11. Use `get_vision_position_ids` from `transformers.vision_utils` and apply the rotary embedding module.",
589
+ FutureWarning,
590
+ stacklevel=2,
591
+ )
592
+ position_ids = get_vision_position_ids(grid_thw, self.spatial_merge_size)
593
+ rotary_pos_emb = self.rotary_pos_emb(position_ids)
594
+ return rotary_pos_emb, position_ids
595
+
596
+ @merge_with_config_defaults
597
+ @capture_outputs
598
+ @auto_docstring
599
+ def forward(
600
+ self,
601
+ hidden_states: torch.Tensor,
602
+ grid_thw: torch.Tensor,
603
+ **kwargs,
604
+ ) -> torch.Tensor:
605
+ r"""
606
+ hidden_states (`torch.Tensor` of shape `(seq_len, hidden_size)`):
607
+ The final hidden states of the model.
608
+ grid_thw (`torch.Tensor` of shape `(num_images_or_videos, 3)`):
609
+ The temporal, height and width of feature shape of each image in LLM.
610
+
611
+ Returns:
612
+ `torch.Tensor`: hidden_states.
613
+ """
614
+ position_ids = get_vision_position_ids(grid_thw, self.spatial_merge_size, kwargs=kwargs)
615
+ cu_seqlens = get_vision_cu_seqlens(grid_thw, kwargs=kwargs)
616
+
617
+ hidden_states = self.patch_embed(hidden_states)
618
+ rotary_emb = self.rotary_pos_emb(position_ids)
619
+ emb = torch.cat((rotary_emb, rotary_emb), dim=-1)
620
+ position_embeddings = (emb.cos(), emb.sin())
621
+
622
+ for blk in self.blocks:
623
+ hidden_states = blk(
624
+ hidden_states,
625
+ cu_seqlens=cu_seqlens,
626
+ position_embeddings=position_embeddings,
627
+ )
628
+
629
+ hidden_states = self.post_layernorm(hidden_states)
630
+
631
+ hidden_states = hidden_states.view(
632
+ -1, self.spatial_merge_size, self.spatial_merge_size, hidden_states.shape[-1]
633
+ )
634
+ hidden_states = hidden_states.permute(0, 3, 1, 2)
635
+ hidden_states = self.downsample(hidden_states).view(-1, self.config.out_hidden_size)
636
+
637
+ merged_hidden_states = self.merger(hidden_states)
638
+ return BaseModelOutputWithPooling(
639
+ last_hidden_state=hidden_states,
640
+ pooler_output=merged_hidden_states,
641
+ )
642
+
643
+
644
+ class GlmOcrTextRotaryEmbedding(nn.Module):
645
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
646
+
647
+ def __init__(self, config: GlmOcrTextConfig, device=None):
648
+ super().__init__()
649
+ self.max_seq_len_cached = config.max_position_embeddings
650
+ self.original_max_seq_len = config.max_position_embeddings
651
+
652
+ self.config = config
653
+
654
+ self.rope_type = self.config.rope_parameters["rope_type"]
655
+ rope_init_fn: Callable = self.compute_default_rope_parameters
656
+ if self.rope_type != "default":
657
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
658
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
659
+
660
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
661
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
662
+ self.mrope_section = config.rope_parameters.get("mrope_section", [8, 12, 12])
663
+
664
+ @staticmethod
665
+ def compute_default_rope_parameters(
666
+ config: GlmOcrTextConfig | None = None,
667
+ device: Optional["torch.device"] = None,
668
+ seq_len: int | None = None,
669
+ ) -> tuple["torch.Tensor", float]:
670
+ """
671
+ Computes the inverse frequencies according to the original RoPE implementation
672
+ Args:
673
+ config ([`~transformers.PreTrainedConfig`]):
674
+ The model configuration.
675
+ device (`torch.device`):
676
+ The device to use for initialization of the inverse frequencies.
677
+ seq_len (`int`, *optional*):
678
+ The current sequence length. Unused for this type of RoPE.
679
+ Returns:
680
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
681
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
682
+ """
683
+ base = config.rope_parameters["rope_theta"]
684
+ partial_rotary_factor = config.rope_parameters.get("partial_rotary_factor", 1.0)
685
+ head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
686
+ dim = int(head_dim * partial_rotary_factor)
687
+
688
+ attention_factor = 1.0 # Unused in this type of RoPE
689
+
690
+ # Compute the inverse frequencies
691
+ inv_freq = 1.0 / (
692
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
693
+ )
694
+ return inv_freq, attention_factor
695
+
696
+ @torch.no_grad()
697
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
698
+ def forward(self, x, position_ids):
699
+ # In contrast to other models, GLM-V has different position ids for the grids
700
+ # So we expand the inv_freq to shape (3, ...)
701
+ inv_freq_expanded = self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1)
702
+ position_ids_expanded = position_ids[:, :, None, :].float() # shape (3, bs, 1, positions)
703
+
704
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
705
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
706
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3)
707
+ freqs = self.apply_mrope(freqs, self.mrope_section)
708
+ emb = torch.cat((freqs, freqs), dim=-1)
709
+ cos = emb.cos() * self.attention_scaling
710
+ sin = emb.sin() * self.attention_scaling
711
+
712
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
713
+
714
+ def apply_mrope(self, freqs, mrope_section):
715
+ section = mrope_section
716
+ chunks = freqs.split(section, dim=-1)
717
+ result = torch.cat([chunk[i % 3] for i, chunk in enumerate(chunks)], dim=-1)
718
+ return result
719
+
720
+
721
+ @auto_docstring
722
+ class GlmOcrTextModel(GlmOcrPreTrainedModel):
723
+ config: GlmOcrTextConfig
724
+ input_modalities = ("text",)
725
+ _can_record_outputs = {
726
+ "hidden_states": GlmOcrTextDecoderLayer,
727
+ "attentions": GlmOcrTextAttention,
728
+ }
729
+
730
+ def __init__(self, config: GlmOcrTextConfig):
731
+ super().__init__(config)
732
+ self.padding_idx = config.pad_token_id
733
+ self.vocab_size = config.vocab_size
734
+
735
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
736
+ self.layers = nn.ModuleList(
737
+ [GlmOcrTextDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
738
+ )
739
+ self.norm = GlmOcrRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
740
+ self.rotary_emb = GlmOcrTextRotaryEmbedding(config=config)
741
+
742
+ self.gradient_checkpointing = False
743
+ # Initialize weights and apply final processing
744
+ self.post_init()
745
+
746
+ @auto_docstring
747
+ @merge_with_config_defaults
748
+ @capture_outputs
749
+ def forward(
750
+ self,
751
+ input_ids: torch.LongTensor | None = None,
752
+ attention_mask: torch.Tensor | None = None,
753
+ position_ids: torch.LongTensor | None = None,
754
+ past_key_values: Cache | None = None,
755
+ inputs_embeds: torch.FloatTensor | None = None,
756
+ use_cache: bool | None = None,
757
+ **kwargs: Unpack[FlashAttentionKwargs],
758
+ ) -> tuple | BaseModelOutputWithPast:
759
+ if (input_ids is None) ^ (inputs_embeds is not None):
760
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
761
+
762
+ # torch.jit.trace() doesn't support cache objects in the output
763
+ if use_cache and past_key_values is None and not torch.jit.is_tracing():
764
+ past_key_values = DynamicCache(config=self.config)
765
+
766
+ if inputs_embeds is None:
767
+ inputs_embeds = self.embed_tokens(input_ids)
768
+
769
+ # the hard coded `3` is for temporal, height and width.
770
+ if position_ids is None:
771
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
772
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
773
+ position_ids = position_ids.view(1, 1, -1).expand(3, inputs_embeds.shape[0], -1)
774
+ elif position_ids.ndim == 2:
775
+ position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1)
776
+
777
+ # NOTE: we need to pass text position ids for packing. Qwen2-VL uses 3D positions
778
+ # where each dim indicates visual spatial positions for temporal/height/width grids.
779
+ # There are two scenarios when FA2-like packed masking might be activated.
780
+ # 1. User specifically passed packed `position_ids` and no attention mask.
781
+ # In this case we expect the useer to create correct position ids for all 3 grids
782
+ # and prepend text-only position ids to it. The final tensor will be [4, bs, seq-len]
783
+ # 2. User runs forward with no attention mask and no position ids. In this case, position ids
784
+ # are prepared by the model (`get_rope_index`) as `[4, bs, seq-len]` tensor. Text-only positions are
785
+ # prepended by us when creating positions so that the mask is constructed correctly. NOTE: failing to pass
786
+ # text-only positions will cause incorrect mask construction, do not change `prepare_input_for_generation`
787
+ if position_ids.ndim == 3 and position_ids.shape[0] == 4:
788
+ text_position_ids = position_ids[0]
789
+ position_ids = position_ids[1:]
790
+ else:
791
+ # If inputs are not packed (usual 3D positions), do not prepare mask from position_ids
792
+ text_position_ids = None
793
+
794
+ mask_kwargs = {
795
+ "config": self.config,
796
+ "inputs_embeds": inputs_embeds,
797
+ "attention_mask": attention_mask,
798
+ "past_key_values": past_key_values,
799
+ "position_ids": text_position_ids,
800
+ }
801
+ # Create the masks
802
+ causal_mask = create_causal_mask(**mask_kwargs)
803
+
804
+ hidden_states = inputs_embeds
805
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
806
+
807
+ for decoder_layer in self.layers:
808
+ layer_outputs = decoder_layer(
809
+ hidden_states,
810
+ attention_mask=causal_mask,
811
+ position_ids=text_position_ids,
812
+ past_key_values=past_key_values,
813
+ position_embeddings=position_embeddings,
814
+ **kwargs,
815
+ )
816
+ hidden_states = layer_outputs
817
+
818
+ hidden_states = self.norm(hidden_states)
819
+
820
+ return BaseModelOutputWithPast(
821
+ last_hidden_state=hidden_states,
822
+ past_key_values=past_key_values,
823
+ )
824
+
825
+
826
+ @auto_docstring
827
+ class GlmOcrModel(GlmOcrPreTrainedModel):
828
+ base_model_prefix = "model"
829
+ # Reference: fix gemma3 grad acc #37208
830
+ accepts_loss_kwargs = False
831
+ _no_split_modules = ["GlmOcrTextDecoderLayer", "GlmOcrVisionBlock"]
832
+
833
+ def __init__(self, config):
834
+ super().__init__(config)
835
+ self.visual = GlmOcrVisionModel._from_config(config.vision_config)
836
+ self.language_model = GlmOcrTextModel._from_config(config.text_config)
837
+ self.rope_deltas = None # cache rope_deltas here
838
+
839
+ # Initialize weights and apply final processing
840
+ self.post_init()
841
+
842
+ def get_vision_position_ids(
843
+ self,
844
+ start_position: int,
845
+ grid_thw: list[int, int, int] | torch.Tensor,
846
+ temp_merge_size: int = 1,
847
+ spatial_merge_size: int = 1,
848
+ time_interval: int = 1,
849
+ device: str | torch.device | None = None,
850
+ ):
851
+ """
852
+ Compute 3D positional indices for vision tokens derived from a single image or video input.
853
+
854
+ The positions are generated from the input grid defined by temporal (T), height (H), and
855
+ width (W) dimensions. Temporal and spatial dimensions can be downscaled according to the
856
+ merge sizes used in the vision backbone. The resulting positions are offset by `start_position`.
857
+
858
+ Args:
859
+ start_position (`int`):
860
+ Offset added to all computed positional indices.
861
+ grid_thw (`Sequence[int]` or `torch.Tensor` of shape `(3,)`):
862
+ The (T, H, W) grid representing the feature layout of the current image or video after patch embedding.
863
+ temp_merge_size (`int`, *optional*):
864
+ Factor by which the temporal dimension is reduced in the backbone. The temporal grid size is divided
865
+ by this value. Defaults to 1.
866
+ spatial_merge_size (`int`, *optional*):
867
+ Factor by which the spatial dimensions (H and W) are reduced in the backbone. Both H and W are divided
868
+ by this value. Defaults to 1.
869
+ time_interval (`int`, *optional*):
870
+ Spacing factor applied between consecutive temporal position indices.Defaults to 1.
871
+ device (`str` or `torch.device`, *optional*):
872
+ Device on which the resulting tensor is allocated. If `None`, uses the current default device.
873
+
874
+ Returns:
875
+ torch.LongTensor of shape (3, sequence_length):
876
+ Positional indices for temporal, height, and width dimensions,
877
+ flattened into sequence form and offset by `start_position`.
878
+ """
879
+ llm_grid_t, llm_grid_h, llm_grid_w = (
880
+ grid_thw[0].item() // temp_merge_size,
881
+ grid_thw[1].item() // spatial_merge_size,
882
+ grid_thw[2].item() // spatial_merge_size,
883
+ )
884
+
885
+ # Add `start_position` after arange for compile
886
+ position_temporal = torch.arange(llm_grid_t, device=device) * time_interval
887
+ position_width = torch.arange(llm_grid_w, device=device) + start_position
888
+ position_height = torch.arange(llm_grid_h, device=device) + start_position
889
+
890
+ # Repeat the positions per each grid and per video frame. Repeat patterns are important
891
+ # do not modify without checking values!
892
+ position_width = position_width.repeat(llm_grid_h * llm_grid_t)
893
+ position_height = position_height.repeat_interleave(llm_grid_w).repeat(llm_grid_t)
894
+ # Important: add `start_positions` after applying `time_interval`, order matters
895
+ position_temporal = position_temporal.repeat_interleave(llm_grid_h * llm_grid_w) + start_position
896
+ vision_position_ids = torch.stack([position_temporal, position_height, position_width], dim=0)
897
+
898
+ return vision_position_ids
899
+
900
+ def get_rope_index(
901
+ self,
902
+ input_ids: torch.LongTensor,
903
+ mm_token_type_ids: torch.IntTensor,
904
+ image_grid_thw: torch.LongTensor | None = None,
905
+ video_grid_thw: torch.LongTensor | None = None,
906
+ attention_mask: torch.Tensor | None = None,
907
+ **kwargs,
908
+ ) -> tuple[torch.Tensor, torch.Tensor]:
909
+ """
910
+ Difference from Qwen2VL/Qwen2.5VL's get_rope_index:
911
+ - GLM_OCR uses timestamps to separate each video frame, so the video_grid_thw should also be split too.
912
+
913
+ Args:
914
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
915
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
916
+ it.
917
+ mm_token_type_ids (`torch.IntTensor` of shape `(batch_size, sequence_length)`):
918
+ Token type ids matching each modality to a different value in the input sequence, i.e. text (0), image (1), video (2).
919
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
920
+ The temporal, height and width of feature shape of each image in LLM.
921
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
922
+ The temporal, height and width of feature shape of each video in LLM.
923
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
924
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
925
+
926
+ - 1 for tokens that are **not masked**,
927
+ - 0 for tokens that are **masked**.
928
+
929
+ Returns:
930
+ position_ids (`torch.LongTensor` of shape `(3, batch_size, sequence_length)`)
931
+ mrope_position_deltas (`torch.Tensor` of shape `(batch_size)`)
932
+ """
933
+
934
+ # Separate video grid thw into multiple grids because timestamps are used to separate videos.
935
+ if video_grid_thw is not None:
936
+ video_grid_thw = torch.repeat_interleave(video_grid_thw, video_grid_thw[:, 0], dim=0)
937
+ video_grid_thw[:, 0] = 1
938
+ spatial_merge_size = self.config.vision_config.spatial_merge_size
939
+
940
+ mrope_position_deltas = []
941
+ position_ids = torch.zeros(
942
+ 3,
943
+ input_ids.shape[0],
944
+ input_ids.shape[1],
945
+ dtype=input_ids.dtype,
946
+ device=input_ids.device,
947
+ )
948
+ grid_iters = {
949
+ 1: iter(image_grid_thw) if image_grid_thw is not None else None,
950
+ 2: iter(video_grid_thw) if video_grid_thw is not None else None,
951
+ }
952
+
953
+ for batch_idx, current_input_ids in enumerate(input_ids):
954
+ input_token_type = mm_token_type_ids[batch_idx]
955
+ if attention_mask is not None:
956
+ current_input_ids = current_input_ids[attention_mask[batch_idx].bool()]
957
+ input_token_type = input_token_type[attention_mask[batch_idx].bool()]
958
+
959
+ input_type_group = []
960
+ for key, group in itertools.groupby(enumerate(input_token_type.tolist()), lambda x: x[1]):
961
+ group = list(group)
962
+ start_index = group[0][0]
963
+ end_index = group[-1][0] + 1
964
+ input_type_group.append((key, start_index, end_index))
965
+
966
+ current_pos = 0
967
+ llm_pos_ids_list = []
968
+ for modality_type, start_idx, end_idx in input_type_group:
969
+ # text == 0
970
+ if modality_type == 0:
971
+ text_len = end_idx - start_idx
972
+ llm_pos_ids_list.append(
973
+ torch.arange(text_len, device=input_ids.device).view(1, -1).expand(3, -1) + current_pos
974
+ )
975
+ current_pos += text_len
976
+ # image == 1, video == 2
977
+ else:
978
+ grid_thw = next(grid_iters[modality_type])
979
+ vision_position_ids = self.get_vision_position_ids(
980
+ current_pos, grid_thw, 1, spatial_merge_size, device=input_ids.device
981
+ )
982
+ llm_pos_ids_list.append(vision_position_ids)
983
+ current_pos += max(grid_thw[1], grid_thw[2]) // spatial_merge_size
984
+ llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1)
985
+ if attention_mask is not None:
986
+ position_ids[:, batch_idx, attention_mask[batch_idx].bool()] = llm_positions.to(position_ids.device)
987
+ else:
988
+ position_ids[:, batch_idx] = llm_positions.to(position_ids.device)
989
+ mrope_position_deltas.append(llm_positions.max() + 1 - len(current_input_ids))
990
+ mrope_position_deltas = torch.tensor(mrope_position_deltas, device=input_ids.device).unsqueeze(1)
991
+ return position_ids, mrope_position_deltas
992
+
993
+ @accepts_precomputed_kwargs(modality="video")
994
+ @can_return_tuple
995
+ @auto_docstring
996
+ def get_video_features(
997
+ self,
998
+ pixel_values_videos: torch.FloatTensor,
999
+ video_grid_thw: torch.LongTensor | None = None,
1000
+ **kwargs: Unpack[TransformersKwargs],
1001
+ ) -> tuple | BaseModelOutputWithPooling:
1002
+ r"""
1003
+ pixel_values_videos (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
1004
+ The tensors corresponding to the input videos.
1005
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
1006
+ The temporal, height and width of feature shape of each video in LLM.
1007
+ """
1008
+ pixel_values_videos = pixel_values_videos.type(self.visual.dtype)
1009
+ # reshape video_grid_thw -> [b, 3] -> [1, h, w] * frames
1010
+ t = video_grid_thw[:, 0]
1011
+ hw = video_grid_thw[:, 1:]
1012
+ # repeat each (h,w) row `t` times
1013
+ flattened_hw = torch.repeat_interleave(hw, t, dim=0)
1014
+ prefix_ones = video_grid_thw.new_ones(flattened_hw.shape[0], 1)
1015
+ flattened_video_grid_thw = torch.cat([prefix_ones, flattened_hw], dim=1)
1016
+ vision_outputs = self.visual(
1017
+ pixel_values_videos, grid_thw=flattened_video_grid_thw, return_dict=True, **kwargs
1018
+ )
1019
+ split_sizes = (video_grid_thw.prod(-1) // self.visual.spatial_merge_size**2).tolist()
1020
+ video_embeds = torch.split(vision_outputs.pooler_output, split_sizes)
1021
+ vision_outputs.pooler_output = video_embeds
1022
+
1023
+ return vision_outputs
1024
+
1025
+ @accepts_precomputed_kwargs(modality="image")
1026
+ @can_return_tuple
1027
+ @auto_docstring
1028
+ def get_image_features(
1029
+ self,
1030
+ pixel_values: torch.FloatTensor,
1031
+ image_grid_thw: torch.LongTensor | None = None,
1032
+ **kwargs: Unpack[TransformersKwargs],
1033
+ ) -> tuple | BaseModelOutputWithPooling:
1034
+ r"""
1035
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
1036
+ The tensors corresponding to the input images.
1037
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
1038
+ The temporal, height and width of feature shape of each image in LLM.
1039
+ """
1040
+ pixel_values = pixel_values.type(self.visual.dtype)
1041
+ vision_outputs = self.visual(pixel_values, grid_thw=image_grid_thw, **kwargs)
1042
+ split_sizes = (image_grid_thw.prod(-1) // self.visual.spatial_merge_size**2).tolist()
1043
+ image_embeds = torch.split(vision_outputs.pooler_output, split_sizes)
1044
+ vision_outputs.pooler_output = image_embeds
1045
+
1046
+ return vision_outputs
1047
+
1048
+ def get_placeholder_mask(
1049
+ self,
1050
+ input_ids: torch.LongTensor,
1051
+ inputs_embeds: torch.FloatTensor,
1052
+ image_features: torch.FloatTensor | None = None,
1053
+ video_features: torch.FloatTensor | None = None,
1054
+ ):
1055
+ """
1056
+ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
1057
+ equal to the length of multimodal features. If the lengths are different, an error is raised.
1058
+ """
1059
+ if input_ids is None:
1060
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
1061
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
1062
+ )
1063
+ special_image_mask = special_image_mask.all(-1)
1064
+ special_video_mask = inputs_embeds == self.get_input_embeddings()(
1065
+ torch.tensor(self.config.video_token_id, dtype=torch.long, device=inputs_embeds.device)
1066
+ )
1067
+ special_video_mask = special_video_mask.all(-1)
1068
+ else:
1069
+ # GLM-4.1V and GLM-4.5V special_video_mask is special_image_mask
1070
+ special_image_mask = input_ids == self.config.image_token_id
1071
+ special_video_mask = input_ids == self.config.image_token_id
1072
+
1073
+ n_image_tokens = special_image_mask.sum()
1074
+ special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
1075
+ if image_features is not None:
1076
+ torch_compilable_check(
1077
+ inputs_embeds[special_image_mask].numel() == image_features.numel(),
1078
+ f"Image features and image tokens do not match, tokens: {n_image_tokens}, features: {image_features.shape[0]}",
1079
+ )
1080
+
1081
+ n_video_tokens = special_video_mask.sum()
1082
+ special_video_mask = special_video_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
1083
+ if video_features is not None:
1084
+ torch_compilable_check(
1085
+ inputs_embeds[special_video_mask].numel() == video_features.numel(),
1086
+ f"Video features and video tokens do not match, tokens: {n_video_tokens}, features: {video_features.shape[0]}",
1087
+ )
1088
+ return special_image_mask, special_video_mask
1089
+
1090
+ def compute_3d_position_ids(
1091
+ self,
1092
+ input_ids: torch.Tensor | None,
1093
+ inputs_embeds: torch.Tensor | None,
1094
+ image_grid_thw: torch.Tensor | None = None,
1095
+ video_grid_thw: torch.Tensor | None = None,
1096
+ attention_mask: torch.Tensor | None = None,
1097
+ past_key_values: torch.Tensor | None = None,
1098
+ mm_token_type_ids: torch.IntTensor | None = None,
1099
+ ) -> torch.Tensor | None:
1100
+ past_key_values_length = 0 if past_key_values is None else past_key_values.get_seq_length()
1101
+ has_multimodal = image_grid_thw is not None or video_grid_thw is not None
1102
+ if has_multimodal and mm_token_type_ids is None and input_ids is not None:
1103
+ raise ValueError(
1104
+ "Multimodal data was passed (via `image_grid_thw` or `video_grid_thw`) but `mm_token_type_ids` is "
1105
+ "missing. Please pass `mm_token_type_ids` to the model so that multimodal RoPE (M-RoPE) can be "
1106
+ "computed correctly. `mm_token_type_ids` is returned by the processor alongside `input_ids`."
1107
+ )
1108
+ can_compute_mrope = input_ids is not None and mm_token_type_ids is not None and has_multimodal
1109
+
1110
+ if can_compute_mrope and (self.rope_deltas is None or past_key_values_length == 0):
1111
+ position_ids, rope_deltas = self.get_rope_index(
1112
+ input_ids,
1113
+ image_grid_thw=image_grid_thw,
1114
+ video_grid_thw=video_grid_thw,
1115
+ attention_mask=attention_mask,
1116
+ mm_token_type_ids=mm_token_type_ids,
1117
+ )
1118
+ self.rope_deltas = rope_deltas
1119
+ # Use pre-calculated rope-deltas to infer correct 3D position ids during incremental
1120
+ # generation (past_key_values_length > 0) or when only inputs_embeds is provided (no input_ids
1121
+ # to recompute from). Skip when input_ids is provided without past_key_values to avoid shape
1122
+ # mismatches from stale rope_deltas (e.g., training forward pass after generation).
1123
+ elif self.rope_deltas is not None and (past_key_values_length > 0 or input_ids is None):
1124
+ batch_size, seq_length, _ = inputs_embeds.shape
1125
+ if attention_mask is not None:
1126
+ position_ids = attention_mask.long().cumsum(-1) - 1
1127
+ position_ids = position_ids.masked_fill(attention_mask == 0, 0)
1128
+ position_ids = position_ids.view(1, batch_size, -1).repeat(3, 1, 1).to(inputs_embeds.device)
1129
+ else:
1130
+ position_ids = torch.arange(past_key_values_length, past_key_values_length + seq_length)
1131
+ position_ids = position_ids.view(1, 1, -1).expand(3, batch_size, -1).to(inputs_embeds.device)
1132
+ delta = self.rope_deltas.repeat_interleave(batch_size // self.rope_deltas.shape[0], dim=0)
1133
+ position_ids = position_ids + delta.to(device=inputs_embeds.device)
1134
+ else:
1135
+ # Can't build correct 3D positions. Let the model infer it
1136
+ position_ids = None
1137
+ return position_ids
1138
+
1139
+ @auto_docstring
1140
+ @can_return_tuple
1141
+ def forward(
1142
+ self,
1143
+ input_ids: torch.LongTensor | None = None,
1144
+ attention_mask: torch.Tensor | None = None,
1145
+ position_ids: torch.LongTensor | None = None,
1146
+ past_key_values: Cache | None = None,
1147
+ inputs_embeds: torch.FloatTensor | None = None,
1148
+ pixel_values: torch.Tensor | None = None,
1149
+ pixel_values_videos: torch.FloatTensor | None = None,
1150
+ image_grid_thw: torch.LongTensor | None = None,
1151
+ video_grid_thw: torch.LongTensor | None = None,
1152
+ rope_deltas: torch.LongTensor | None = None,
1153
+ mm_token_type_ids: torch.IntTensor | None = None,
1154
+ **kwargs: Unpack[TransformersKwargs],
1155
+ ) -> tuple | GlmOcrModelOutputWithPast:
1156
+ r"""
1157
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
1158
+ The temporal, height and width of feature shape of each image in LLM.
1159
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
1160
+ The temporal, height and width of feature shape of each video in LLM.
1161
+ rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
1162
+ The rope index difference between sequence length and multimodal rope.
1163
+ """
1164
+ if (input_ids is None) ^ (inputs_embeds is not None):
1165
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
1166
+
1167
+ if inputs_embeds is None:
1168
+ inputs_embeds = self.get_input_embeddings()(input_ids)
1169
+
1170
+ if pixel_values is not None:
1171
+ image_embeds = self.get_image_features(
1172
+ pixel_values, image_grid_thw, return_dict=True, **kwargs
1173
+ ).pooler_output
1174
+ image_embeds = torch.cat(image_embeds, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
1175
+ image_mask, _ = self.get_placeholder_mask(input_ids, inputs_embeds, image_features=image_embeds)
1176
+ inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
1177
+
1178
+ if pixel_values_videos is not None:
1179
+ video_embeds = self.get_video_features(
1180
+ pixel_values_videos, video_grid_thw, return_dict=True, **kwargs
1181
+ ).pooler_output
1182
+ video_embeds = torch.cat(video_embeds, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
1183
+ _, video_mask = self.get_placeholder_mask(input_ids, inputs_embeds, video_features=video_embeds)
1184
+ inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds)
1185
+
1186
+ if position_ids is None:
1187
+ position_ids = self.compute_3d_position_ids(
1188
+ input_ids=input_ids,
1189
+ image_grid_thw=image_grid_thw,
1190
+ video_grid_thw=video_grid_thw,
1191
+ inputs_embeds=inputs_embeds,
1192
+ attention_mask=attention_mask,
1193
+ past_key_values=past_key_values,
1194
+ mm_token_type_ids=mm_token_type_ids,
1195
+ )
1196
+
1197
+ outputs = self.language_model(
1198
+ input_ids=None,
1199
+ position_ids=position_ids,
1200
+ attention_mask=attention_mask,
1201
+ past_key_values=past_key_values,
1202
+ inputs_embeds=inputs_embeds,
1203
+ **kwargs,
1204
+ )
1205
+
1206
+ return GlmOcrModelOutputWithPast(
1207
+ **outputs,
1208
+ rope_deltas=self.rope_deltas,
1209
+ )
1210
+
1211
+
1212
+ @auto_docstring(
1213
+ custom_intro="""
1214
+ Base class for GlmOcr causal language model (or autoregressive) outputs.
1215
+ """
1216
+ )
1217
+ @dataclass
1218
+ class GlmOcrCausalLMOutputWithPast(ModelOutput):
1219
+ r"""
1220
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
1221
+ Language modeling loss (for next-token prediction).
1222
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
1223
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
1224
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
1225
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
1226
+
1227
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
1228
+ `past_key_values` input) to speed up sequential decoding.
1229
+ rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
1230
+ The rope index difference between sequence length and multimodal rope.
1231
+ """
1232
+
1233
+ loss: torch.FloatTensor | None = None
1234
+ logits: torch.FloatTensor | None = None
1235
+ past_key_values: Cache | None = None
1236
+ hidden_states: tuple[torch.FloatTensor] | None = None
1237
+ attentions: tuple[torch.FloatTensor] | None = None
1238
+ rope_deltas: torch.LongTensor | None = None
1239
+
1240
+
1241
+ class GlmOcrForConditionalGeneration(GlmOcrPreTrainedModel, GenerationMixin):
1242
+ _tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
1243
+ # Reference: fix gemma3 grad acc #37208
1244
+ accepts_loss_kwargs = False
1245
+
1246
+ def __init__(self, config):
1247
+ super().__init__(config)
1248
+ self.model = GlmOcrModel(config)
1249
+ self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
1250
+
1251
+ self.post_init()
1252
+
1253
+ @auto_docstring
1254
+ def get_video_features(
1255
+ self,
1256
+ pixel_values_videos: torch.FloatTensor,
1257
+ video_grid_thw: torch.LongTensor | None = None,
1258
+ **kwargs: Unpack[TransformersKwargs],
1259
+ ) -> tuple | BaseModelOutputWithPooling:
1260
+ r"""
1261
+ pixel_values_videos (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
1262
+ The tensors corresponding to the input videos.
1263
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
1264
+ The temporal, height and width of feature shape of each video in LLM.
1265
+ """
1266
+ return self.model.get_video_features(pixel_values_videos, video_grid_thw, **kwargs)
1267
+
1268
+ @auto_docstring
1269
+ def get_image_features(
1270
+ self,
1271
+ pixel_values: torch.FloatTensor,
1272
+ image_grid_thw: torch.LongTensor | None = None,
1273
+ **kwargs: Unpack[TransformersKwargs],
1274
+ ) -> tuple | BaseModelOutputWithPooling:
1275
+ r"""
1276
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
1277
+ The tensors corresponding to the input images.
1278
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
1279
+ The temporal, height and width of feature shape of each image in LLM.
1280
+ """
1281
+ return self.model.get_image_features(pixel_values, image_grid_thw, **kwargs)
1282
+
1283
+ @can_return_tuple
1284
+ @auto_docstring
1285
+ def forward(
1286
+ self,
1287
+ input_ids: torch.LongTensor | None = None,
1288
+ attention_mask: torch.Tensor | None = None,
1289
+ position_ids: torch.LongTensor | None = None,
1290
+ past_key_values: Cache | None = None,
1291
+ inputs_embeds: torch.FloatTensor | None = None,
1292
+ labels: torch.LongTensor | None = None,
1293
+ pixel_values: torch.Tensor | None = None,
1294
+ pixel_values_videos: torch.FloatTensor | None = None,
1295
+ image_grid_thw: torch.LongTensor | None = None,
1296
+ video_grid_thw: torch.LongTensor | None = None,
1297
+ mm_token_type_ids: torch.IntTensor | None = None,
1298
+ logits_to_keep: int | torch.Tensor = 0,
1299
+ **kwargs: Unpack[TransformersKwargs],
1300
+ ) -> tuple | GlmOcrCausalLMOutputWithPast:
1301
+ r"""
1302
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1303
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1304
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1305
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1306
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
1307
+ The temporal, height and width of feature shape of each image in LLM.
1308
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
1309
+ The temporal, height and width of feature shape of each video in LLM.
1310
+
1311
+ Example:
1312
+
1313
+ ```python
1314
+ >>> from PIL import Image
1315
+ >>> import httpx
1316
+ >>> from io import BytesIO
1317
+ >>> from transformers import AutoProcessor, GlmOcrForConditionalGeneration
1318
+
1319
+ >>> model = GlmOcrForConditionalGeneration.from_pretrained("zai-org/GLM-4.1V-9B-Thinking")
1320
+ >>> processor = AutoProcessor.from_pretrained("zai-org/GLM-4.1V-9B-Thinking")
1321
+
1322
+ >>> messages = [
1323
+ {
1324
+ "role": "user",
1325
+ "content": [
1326
+ {"type": "image", "url": "https://www.ilankelman.org/stopsigns/australia.jpg"},
1327
+ {"type": "text", "text": "What is shown in this image?"},
1328
+ ],
1329
+ },
1330
+ ]
1331
+ >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
1332
+ >>> with httpx.stream("GET", url) as response:
1333
+ ... image = Image.open(BytesIO(response.read()))
1334
+
1335
+ >>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
1336
+ >>> inputs = processor(text=[text], images=[image], vision_infos=[vision_infos])
1337
+
1338
+ >>> # Generate
1339
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1340
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1341
+ "The image shows a street scene with a red stop sign in the foreground. In the background, there is a large red gate with Chinese characters ..."
1342
+ ```"""
1343
+ outputs = self.model(
1344
+ input_ids=input_ids,
1345
+ pixel_values=pixel_values,
1346
+ pixel_values_videos=pixel_values_videos,
1347
+ image_grid_thw=image_grid_thw,
1348
+ video_grid_thw=video_grid_thw,
1349
+ mm_token_type_ids=mm_token_type_ids,
1350
+ position_ids=position_ids,
1351
+ attention_mask=attention_mask,
1352
+ past_key_values=past_key_values,
1353
+ inputs_embeds=inputs_embeds,
1354
+ **kwargs,
1355
+ )
1356
+
1357
+ hidden_states = outputs[0]
1358
+
1359
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1360
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1361
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1362
+
1363
+ loss = None
1364
+ if labels is not None:
1365
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size)
1366
+
1367
+ return GlmOcrCausalLMOutputWithPast(
1368
+ loss=loss,
1369
+ logits=logits,
1370
+ past_key_values=outputs.past_key_values,
1371
+ hidden_states=outputs.hidden_states,
1372
+ attentions=outputs.attentions,
1373
+ rope_deltas=outputs.rope_deltas,
1374
+ )
1375
+
1376
+ def prepare_inputs_for_generation(
1377
+ self,
1378
+ input_ids,
1379
+ past_key_values=None,
1380
+ attention_mask=None,
1381
+ inputs_embeds=None,
1382
+ position_ids=None,
1383
+ use_cache=True,
1384
+ pixel_values=None,
1385
+ pixel_values_videos=None,
1386
+ image_grid_thw=None,
1387
+ video_grid_thw=None,
1388
+ is_first_iteration=False,
1389
+ **kwargs,
1390
+ ):
1391
+ # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
1392
+
1393
+ model_inputs = super().prepare_inputs_for_generation(
1394
+ input_ids,
1395
+ past_key_values=past_key_values,
1396
+ attention_mask=attention_mask,
1397
+ inputs_embeds=inputs_embeds,
1398
+ position_ids=position_ids,
1399
+ pixel_values=pixel_values,
1400
+ pixel_values_videos=pixel_values_videos,
1401
+ image_grid_thw=image_grid_thw,
1402
+ video_grid_thw=video_grid_thw,
1403
+ use_cache=use_cache,
1404
+ is_first_iteration=is_first_iteration,
1405
+ **kwargs,
1406
+ )
1407
+
1408
+ if not is_first_iteration and use_cache:
1409
+ model_inputs["pixel_values"] = None
1410
+ model_inputs["pixel_values_videos"] = None
1411
+
1412
+ return model_inputs
1413
+
1414
+ def _prepare_position_ids_for_generation(self, inputs_tensor, model_kwargs):
1415
+ # Overwritten -- requires 3D position ids
1416
+
1417
+ text_positions = super()._prepare_position_ids_for_generation(inputs_tensor, model_kwargs)
1418
+
1419
+ # Early exit in case we are continuing generation from past kv
1420
+ past_length = 0
1421
+ if (cache := model_kwargs.get("past_key_values")) is not None:
1422
+ past_length = cache.get_seq_length()
1423
+ if past_length != 0 and self.model.rope_deltas is not None:
1424
+ position_ids = text_positions[None, ...] + self.model.rope_deltas
1425
+ return position_ids
1426
+
1427
+ # Otherwise compute 3d position ids for vision tokens and concat with text position ids
1428
+ if "input_ids" in model_kwargs and model_kwargs["input_ids"].shape[1] > 0:
1429
+ inputs_tensor = model_kwargs["input_ids"]
1430
+
1431
+ is_input_ids = len(inputs_tensor.shape) == 2 and inputs_tensor.dtype in [torch.int, torch.long]
1432
+ if (
1433
+ is_input_ids
1434
+ and model_kwargs.get("mm_token_type_ids") is not None
1435
+ and (model_kwargs.get("image_grid_thw") is not None or model_kwargs.get("video_grid_thw") is not None)
1436
+ ):
1437
+ model_kwargs = {k: v for k, v in model_kwargs.items() if k != "input_ids"}
1438
+ vision_positions, rope_deltas = self.model.get_rope_index(inputs_tensor, **model_kwargs)
1439
+ self.model.rope_deltas = rope_deltas
1440
+ else:
1441
+ vision_positions = text_positions.unsqueeze(0).expand(3, -1, -1)
1442
+ self.model.rope_deltas = torch.zeros(
1443
+ inputs_tensor.shape[0], 1, dtype=torch.long, device=inputs_tensor.device
1444
+ )
1445
+
1446
+ # Concatenate "text + vision" positions into [4, bs, seq-len]
1447
+ text_positions = text_positions[None, ...]
1448
+ position_ids = torch.cat([text_positions, vision_positions], dim=0)
1449
+
1450
+ return position_ids
1451
+
1452
+ def _get_image_nums_and_video_nums(
1453
+ self,
1454
+ input_ids: torch.LongTensor | None,
1455
+ inputs_embeds: torch.Tensor | None = None,
1456
+ ) -> tuple[torch.Tensor, torch.Tensor]:
1457
+ """
1458
+ Get the number of images and videos for each sample to calculate the separation length of the sample tensor.
1459
+ These parameters are not passed through the processor to avoid unpredictable impacts from interface modifications.
1460
+
1461
+ Args:
1462
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1463
+ Indices of input sequence tokens in the vocabulary.
1464
+
1465
+ Returns:
1466
+ image_nums (`torch.LongTensor` of shape `(batch_size, num_images_sample)`)
1467
+ video_nums (`torch.LongTensor` of shape `(batch_size, num_videos_sample)`)
1468
+ """
1469
+
1470
+ if inputs_embeds is not None:
1471
+ is_image = (
1472
+ inputs_embeds
1473
+ == self.get_input_embeddings()(
1474
+ torch.tensor(self.config.image_start_token_id, dtype=torch.long, device=inputs_embeds.device)
1475
+ )
1476
+ )[..., 0]
1477
+ is_video_start = (
1478
+ inputs_embeds
1479
+ == self.get_input_embeddings()(
1480
+ torch.tensor(self.config.video_start_token_id, dtype=torch.long, device=inputs_embeds.device)
1481
+ )
1482
+ )[..., 0]
1483
+ is_video_end = (
1484
+ inputs_embeds
1485
+ == self.get_input_embeddings()(
1486
+ torch.tensor(self.config.video_end_token_id, dtype=torch.long, device=inputs_embeds.device)
1487
+ )
1488
+ )[..., 0]
1489
+ else:
1490
+ is_image = input_ids == self.config.image_start_token_id
1491
+ is_video_start = input_ids == self.config.video_start_token_id
1492
+ is_video_end = input_ids == self.config.video_end_token_id
1493
+
1494
+ # Cumulative sum to track if we're inside a video span
1495
+ # We'll assume well-formed video tags (i.e. matching starts and ends)
1496
+ video_level = torch.cumsum(is_video_start.int() - is_video_end.int(), dim=1)
1497
+ inside_video = video_level > 0 # shape (batch_size, seq_length)
1498
+
1499
+ # Mask out image tokens that are inside video spans
1500
+ standalone_images = is_image & (~inside_video)
1501
+
1502
+ # Count per batch
1503
+ image_counts = standalone_images.sum(dim=1)
1504
+ video_counts = is_video_start.sum(dim=1)
1505
+
1506
+ return image_counts, video_counts
1507
+
1508
+ def _expand_inputs_for_generation(
1509
+ self,
1510
+ expand_size: int = 1,
1511
+ is_encoder_decoder: bool = False,
1512
+ input_ids: torch.LongTensor | None = None,
1513
+ **model_kwargs,
1514
+ ) -> tuple[torch.LongTensor, dict[str, Any]]:
1515
+ # Overwritten -- Support for expanding tensors without a batch size dimension
1516
+ # e.g., pixel_values, image_grid_thw, pixel_values_videos, video_grid_thw, second_per_grid_t
1517
+ # pixel_values.shape[0] is sum(seqlen_images for samples)
1518
+ # image_grid_thw.shape[0] is sum(num_images for samples)
1519
+
1520
+ if expand_size == 1:
1521
+ return input_ids, model_kwargs
1522
+
1523
+ visual_keys = ["pixel_values", "image_grid_thw", "pixel_values_videos", "video_grid_thw", "second_per_grid_ts"]
1524
+
1525
+ def _expand_dict_for_generation_visual(dict_to_expand):
1526
+ image_grid_thw = model_kwargs.get("image_grid_thw", None)
1527
+ video_grid_thw = model_kwargs.get("video_grid_thw", None)
1528
+ image_nums, video_nums = self._get_image_nums_and_video_nums(
1529
+ input_ids, inputs_embeds=model_kwargs.get("inputs_embeds", None)
1530
+ )
1531
+
1532
+ def _repeat_interleave_samples(x, lengths, repeat_times):
1533
+ samples = torch.split(x, lengths)
1534
+ repeat_args = [repeat_times] + [1] * (x.dim() - 1)
1535
+ result = torch.cat([sample.repeat(*repeat_args) for sample in samples], dim=0)
1536
+ return result
1537
+
1538
+ for key in dict_to_expand:
1539
+ if key == "pixel_values":
1540
+ # split images into samples
1541
+ samples = torch.split(image_grid_thw, list(image_nums))
1542
+ # compute the sequence length of images for each sample
1543
+ lengths = [torch.prod(sample, dim=1).sum() for sample in samples]
1544
+ dict_to_expand[key] = _repeat_interleave_samples(
1545
+ dict_to_expand[key], lengths=lengths, repeat_times=expand_size
1546
+ )
1547
+ elif key == "image_grid_thw":
1548
+ # get the num of images for each sample
1549
+ lengths = list(image_nums)
1550
+ dict_to_expand[key] = _repeat_interleave_samples(
1551
+ dict_to_expand[key], lengths=lengths, repeat_times=expand_size
1552
+ )
1553
+ elif key == "pixel_values_videos":
1554
+ samples = torch.split(video_grid_thw, list(video_nums))
1555
+ lengths = [torch.prod(sample, dim=1).sum() for sample in samples]
1556
+ dict_to_expand[key] = _repeat_interleave_samples(
1557
+ dict_to_expand[key], lengths=lengths, repeat_times=expand_size
1558
+ )
1559
+ elif key == "video_grid_thw":
1560
+ lengths = list(video_nums)
1561
+ dict_to_expand[key] = _repeat_interleave_samples(
1562
+ dict_to_expand[key], lengths=lengths, repeat_times=expand_size
1563
+ )
1564
+ elif key == "second_per_grid_ts":
1565
+ dict_to_expand[key] = _repeat_interleave_samples(
1566
+ dict_to_expand[key], lengths=list(video_nums), repeat_times=expand_size
1567
+ )
1568
+ return dict_to_expand
1569
+
1570
+ def _expand_dict_for_generation(dict_to_expand):
1571
+ for key in dict_to_expand:
1572
+ if key == "position_ids" and dict_to_expand[key].ndim == 3:
1573
+ dict_to_expand[key] = dict_to_expand[key].repeat_interleave(expand_size, dim=1)
1574
+ elif (
1575
+ dict_to_expand[key] is not None
1576
+ and isinstance(dict_to_expand[key], torch.Tensor)
1577
+ and key not in visual_keys
1578
+ ):
1579
+ dict_to_expand[key] = dict_to_expand[key].repeat_interleave(expand_size, dim=0)
1580
+ return dict_to_expand
1581
+
1582
+ model_kwargs = _expand_dict_for_generation_visual(model_kwargs)
1583
+
1584
+ if input_ids is not None:
1585
+ input_ids = input_ids.repeat_interleave(expand_size, dim=0)
1586
+
1587
+ model_kwargs = _expand_dict_for_generation(model_kwargs)
1588
+
1589
+ if is_encoder_decoder:
1590
+ if model_kwargs.get("encoder_outputs") is None:
1591
+ raise ValueError("If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined.")
1592
+ model_kwargs["encoder_outputs"] = _expand_dict_for_generation(model_kwargs["encoder_outputs"])
1593
+
1594
+ return input_ids, model_kwargs
1595
+
1596
+
1597
+ __all__ = [
1598
+ "GlmOcrTextModel",
1599
+ "GlmOcrVisionModel",
1600
+ "GlmOcrModel",
1601
+ "GlmOcrPreTrainedModel",
1602
+ "GlmOcrForConditionalGeneration",
1603
+ ]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/glm_ocr/modular_glm_ocr.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 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
+
15
+ from collections.abc import Callable
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+ from huggingface_hub.dataclasses import strict
20
+
21
+ from ...modeling_outputs import BaseModelOutputWithPooling
22
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
23
+ from ...utils import auto_docstring
24
+ from ...vision_utils import get_vision_cu_seqlens, get_vision_position_ids
25
+ from ..glm4v.configuration_glm4v import Glm4vConfig, Glm4vTextConfig, Glm4vVisionConfig
26
+ from ..glm4v.modeling_glm4v import (
27
+ Glm4vForConditionalGeneration,
28
+ Glm4VisionMlp,
29
+ Glm4vModel,
30
+ Glm4vModelOutputWithPast,
31
+ Glm4vPreTrainedModel,
32
+ Glm4vRMSNorm,
33
+ Glm4vTextAttention,
34
+ Glm4vTextDecoderLayer,
35
+ Glm4vTextModel,
36
+ Glm4vVisionAttention,
37
+ Glm4vVisionBlock,
38
+ Glm4vVisionModel,
39
+ Glm4vVisionPatchMerger,
40
+ apply_rotary_pos_emb_vision,
41
+ eager_attention_forward,
42
+ is_flash_attention_requested,
43
+ )
44
+
45
+
46
+ class GlmOcrRMSNorm(Glm4vRMSNorm):
47
+ pass
48
+
49
+
50
+ class GlmOcrVisionMlp(Glm4VisionMlp):
51
+ def __init__(self, config, bias: bool = True):
52
+ super().__init__(config)
53
+ self.intermediate_size = config.intermediate_size
54
+
55
+
56
+ @auto_docstring(checkpoint="zai-org/GLM-OCR")
57
+ @strict
58
+ class GlmOcrVisionConfig(Glm4vVisionConfig):
59
+ hidden_size: int = 1024
60
+ attention_bias: bool = True
61
+ num_heads: int = 16
62
+ out_hidden_size: int = 1536
63
+ intermediate_size: int = 4096
64
+
65
+
66
+ @auto_docstring(checkpoint="zai-org/GLM-OCR")
67
+ @strict
68
+ class GlmOcrTextConfig(Glm4vTextConfig):
69
+ r"""
70
+ Example:
71
+
72
+ ```python
73
+ >>> from transformers import GlmOcrTextModel, GlmOcrConfig
74
+
75
+ >>> # Initializing a GLM-OCR style configuration
76
+ >>> configuration = GlmOcrConfig()
77
+
78
+ >>> # Initializing a model from the GLM-OCR style configuration
79
+ >>> model = GlmOcrTextModel(configuration)
80
+
81
+ >>> # Accessing the model configuration
82
+ >>> configuration = model.config
83
+ ```"""
84
+
85
+ vocab_size: int = 59392
86
+ hidden_size: int = 1024
87
+ intermediate_size: int = 4096
88
+ num_hidden_layers: int = 16
89
+ num_attention_heads: int = 16
90
+ num_key_value_heads: int = 8
91
+ max_position_embeddings: int = 131072
92
+
93
+
94
+ @auto_docstring(checkpoint="zai-org/GLM-OCR")
95
+ @strict
96
+ class GlmOcrConfig(Glm4vConfig):
97
+ r"""
98
+ image_start_token_id (`int`, *optional*, defaults to 59256):
99
+ The image start token index to encode the start of image.
100
+ image_end_token_id (`int`, *optional*, defaults to 59257):
101
+ The image end token index to encode the end of image.
102
+ video_start_token_id (`int`, *optional*, defaults to 59258):
103
+ The video start token index to encode the start of video.
104
+ video_end_token_id (`int`, *optional*, defaults to 59259):
105
+ The video end token index to encode the end of video.
106
+
107
+ ```python
108
+ >>> from transformers import GlmOcrForConditionalGeneration, GlmOcrConfig
109
+
110
+ >>> # Initializing a GLM-OCR style configuration
111
+ >>> configuration = GlmOcrConfig()
112
+
113
+ >>> # Initializing a model from the GLM-OCR style configuration
114
+ >>> model = GlmOcrForConditionalGeneration(configuration)
115
+
116
+ >>> # Accessing the model configuration
117
+ >>> configuration = model.config
118
+ ```"""
119
+
120
+ image_token_id: int = 59280
121
+ video_token_id: int = 59281
122
+ image_start_token_id: int = 59256
123
+ image_end_token_id: int = 59257
124
+ video_start_token_id: int = 59258
125
+ video_end_token_id: int = 59259
126
+
127
+
128
+ class GlmOcrTextAttention(Glm4vTextAttention, nn.Module):
129
+ def __init__(self, config: GlmOcrTextConfig, layer_idx: int | None = None):
130
+ super().__init__()
131
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
132
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
133
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
134
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
135
+
136
+
137
+ class GlmOcrTextDecoderLayer(Glm4vTextDecoderLayer):
138
+ pass
139
+
140
+
141
+ class GlmOcrPreTrainedModel(Glm4vPreTrainedModel):
142
+ _keys_to_ignore_on_load_unexpected = [r"model\.language_model\.layers\.16.*"]
143
+
144
+
145
+ class GlmOcrModelOutputWithPast(Glm4vModelOutputWithPast):
146
+ pass
147
+
148
+
149
+ class GlmOcrVisionAttention(Glm4vVisionAttention):
150
+ def __init__(self, config: GlmOcrVisionConfig) -> None:
151
+ super().__init__()
152
+ self.qkv = nn.Linear(config.hidden_size, config.hidden_size * 3, bias=config.attention_bias)
153
+ self.proj = nn.Linear(config.hidden_size, config.hidden_size, bias=config.attention_bias)
154
+ self.q_norm = GlmOcrRMSNorm(self.head_dim, eps=config.rms_norm_eps)
155
+ self.k_norm = GlmOcrRMSNorm(self.head_dim, eps=config.rms_norm_eps)
156
+
157
+ def forward(
158
+ self,
159
+ hidden_states: torch.Tensor,
160
+ cu_seqlens: torch.Tensor,
161
+ rotary_pos_emb: torch.Tensor | None = None,
162
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
163
+ **kwargs,
164
+ ) -> torch.Tensor:
165
+ seq_length = hidden_states.shape[0]
166
+ query_states, key_states, value_states = (
167
+ self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
168
+ )
169
+
170
+ query_states = self.q_norm(query_states)
171
+ key_states = self.k_norm(key_states)
172
+
173
+ cos, sin = position_embeddings
174
+ query_states, key_states = apply_rotary_pos_emb_vision(query_states, key_states, cos, sin)
175
+ query_states = query_states.transpose(0, 1).unsqueeze(0)
176
+ key_states = key_states.transpose(0, 1).unsqueeze(0)
177
+ value_states = value_states.transpose(0, 1).unsqueeze(0)
178
+
179
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
180
+ self.config._attn_implementation, eager_attention_forward
181
+ )
182
+
183
+ if is_flash_attention_requested(self.config):
184
+ # Flash Attention: Use cu_seqlens for variable length attention
185
+ max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max()
186
+ attn_output, _ = attention_interface(
187
+ self,
188
+ query_states,
189
+ key_states,
190
+ value_states,
191
+ attention_mask=None,
192
+ scaling=self.scaling,
193
+ dropout=0.0 if not self.training else self.attention_dropout,
194
+ cu_seq_lens_q=cu_seqlens,
195
+ cu_seq_lens_k=cu_seqlens,
196
+ max_length_q=max_seqlen,
197
+ max_length_k=max_seqlen,
198
+ is_causal=False,
199
+ **kwargs,
200
+ )
201
+ else:
202
+ # Other implementations: Process each chunk separately
203
+ lengths = cu_seqlens[1:] - cu_seqlens[:-1]
204
+ splits = [
205
+ torch.split(tensor, lengths.tolist(), dim=2) for tensor in (query_states, key_states, value_states)
206
+ ]
207
+
208
+ attn_outputs = [
209
+ attention_interface(
210
+ self,
211
+ q,
212
+ k,
213
+ v,
214
+ attention_mask=None,
215
+ scaling=self.scaling,
216
+ dropout=0.0 if not self.training else self.attention_dropout,
217
+ is_causal=False,
218
+ **kwargs,
219
+ )[0]
220
+ for q, k, v in zip(*splits)
221
+ ]
222
+ attn_output = torch.cat(attn_outputs, dim=1)
223
+
224
+ attn_output = attn_output.reshape(seq_length, -1).contiguous()
225
+ attn_output = self.proj(attn_output)
226
+ return attn_output
227
+
228
+
229
+ class GlmOcrVisionBlock(Glm4vVisionBlock):
230
+ def __init__(self, config) -> None:
231
+ super().__init__()
232
+ self.mlp = GlmOcrVisionMlp(config, bias=config.attention_bias)
233
+
234
+
235
+ class GlmOcrVisionPatchMerger(Glm4vVisionPatchMerger):
236
+ pass
237
+
238
+
239
+ class GlmOcrVisionModel(Glm4vVisionModel):
240
+ def __init__(self, config) -> None:
241
+ super().__init__(config)
242
+ del self.embeddings
243
+ del self.post_conv_layernorm
244
+ self.merger = GlmOcrVisionPatchMerger(
245
+ dim=config.out_hidden_size,
246
+ context_dim=config.out_hidden_size * config.in_channels,
247
+ hidden_act=config.hidden_act,
248
+ )
249
+
250
+ def forward(
251
+ self,
252
+ hidden_states: torch.Tensor,
253
+ grid_thw: torch.Tensor,
254
+ **kwargs,
255
+ ) -> torch.Tensor:
256
+ r"""
257
+ hidden_states (`torch.Tensor` of shape `(seq_len, hidden_size)`):
258
+ The final hidden states of the model.
259
+ grid_thw (`torch.Tensor` of shape `(num_images_or_videos, 3)`):
260
+ The temporal, height and width of feature shape of each image in LLM.
261
+
262
+ Returns:
263
+ `torch.Tensor`: hidden_states.
264
+ """
265
+ position_ids = get_vision_position_ids(grid_thw, self.spatial_merge_size, kwargs=kwargs)
266
+ cu_seqlens = get_vision_cu_seqlens(grid_thw, kwargs=kwargs)
267
+
268
+ hidden_states = self.patch_embed(hidden_states)
269
+ rotary_emb = self.rotary_pos_emb(position_ids)
270
+ emb = torch.cat((rotary_emb, rotary_emb), dim=-1)
271
+ position_embeddings = (emb.cos(), emb.sin())
272
+
273
+ for blk in self.blocks:
274
+ hidden_states = blk(
275
+ hidden_states,
276
+ cu_seqlens=cu_seqlens,
277
+ position_embeddings=position_embeddings,
278
+ )
279
+
280
+ hidden_states = self.post_layernorm(hidden_states)
281
+
282
+ hidden_states = hidden_states.view(
283
+ -1, self.spatial_merge_size, self.spatial_merge_size, hidden_states.shape[-1]
284
+ )
285
+ hidden_states = hidden_states.permute(0, 3, 1, 2)
286
+ hidden_states = self.downsample(hidden_states).view(-1, self.config.out_hidden_size)
287
+
288
+ merged_hidden_states = self.merger(hidden_states)
289
+ return BaseModelOutputWithPooling(
290
+ last_hidden_state=hidden_states,
291
+ pooler_output=merged_hidden_states,
292
+ )
293
+
294
+
295
+ class GlmOcrTextModel(Glm4vTextModel):
296
+ _can_record_outputs = {
297
+ "hidden_states": GlmOcrTextDecoderLayer,
298
+ "attentions": GlmOcrTextAttention,
299
+ }
300
+
301
+
302
+ class GlmOcrModel(Glm4vModel):
303
+ pass
304
+
305
+
306
+ class GlmOcrForConditionalGeneration(Glm4vForConditionalGeneration):
307
+ pass
308
+
309
+
310
+ __all__ = [
311
+ "GlmOcrConfig",
312
+ "GlmOcrTextConfig",
313
+ "GlmOcrVisionConfig",
314
+ "GlmOcrTextModel",
315
+ "GlmOcrVisionModel",
316
+ "GlmOcrModel",
317
+ "GlmOcrPreTrainedModel",
318
+ "GlmOcrForConditionalGeneration",
319
+ ]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/jina_embeddings_v3/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 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
+
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ from typing import TYPE_CHECKING
17
+
18
+ from ...utils import _LazyModule
19
+ from ...utils.import_utils import define_import_structure
20
+
21
+
22
+ if TYPE_CHECKING:
23
+ from .configuration_jina_embeddings_v3 import *
24
+ from .modeling_jina_embeddings_v3 import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/jina_embeddings_v3/modular_jina_embeddings_v3.py ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The Jina-AI and HuggingFace Inc. teams. All rights reserved.
2
+ #
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from collections.abc import Callable
17
+
18
+ import torch
19
+ from huggingface_hub.dataclasses import strict
20
+ from torch import nn
21
+ from torch.nn import CrossEntropyLoss
22
+
23
+ from ...integrations import use_kernelized_func
24
+ from ...masking_utils import create_bidirectional_mask
25
+ from ...modeling_outputs import (
26
+ BaseModelOutputWithPooling,
27
+ MaskedLMOutput,
28
+ )
29
+ from ...modeling_rope_utils import RopeParameters
30
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
31
+ from ...processing_utils import Unpack
32
+ from ...utils import TransformersKwargs, auto_docstring, logging
33
+ from ...utils.generic import can_return_tuple, merge_with_config_defaults
34
+ from ...utils.output_capturing import capture_outputs
35
+ from ..clip.modeling_clip import CLIPMLP
36
+ from ..gpt_neox.modeling_gpt_neox import GPTNeoXLayer
37
+ from ..llama.modeling_llama import LlamaAttention, LlamaRotaryEmbedding, apply_rotary_pos_emb
38
+ from ..xlm_roberta.configuration_xlm_roberta import XLMRobertaConfig
39
+ from ..xlm_roberta.modeling_xlm_roberta import (
40
+ XLMRobertaEmbeddings,
41
+ XLMRobertaForMaskedLM,
42
+ XLMRobertaForQuestionAnswering,
43
+ XLMRobertaForSequenceClassification,
44
+ XLMRobertaForTokenClassification,
45
+ XLMRobertaLMHead,
46
+ XLMRobertaModel,
47
+ XLMRobertaPooler,
48
+ XLMRobertaPreTrainedModel,
49
+ eager_attention_forward,
50
+ )
51
+
52
+
53
+ logger = logging.get_logger(__name__)
54
+
55
+
56
+ @auto_docstring(checkpoint="jinaai/jina-embeddings-v3-hf")
57
+ @strict
58
+ class JinaEmbeddingsV3Config(XLMRobertaConfig):
59
+ r"""
60
+ Examples:
61
+
62
+ ```python
63
+ >>> from transformers import JinaEmbeddingsV3Config, JinaEmbeddingsV3Model
64
+
65
+ >>> # Initializing a Jina-Embeddings-V3 jinaai/jina-embeddings-v3-hf style configuration
66
+ >>> configuration = JinaEmbeddingsV3Config()
67
+
68
+ >>> # Initializing a model (with random weights) from the jinaai/jina-embeddings-v3-hf style configuration
69
+ >>> model = JinaEmbeddingsV3Model(configuration)
70
+
71
+ >>> # Accessing the model configuration
72
+ >>> configuration = model.config
73
+ ```"""
74
+
75
+ model_type = "jina_embeddings_v3"
76
+ default_theta = 20000.0
77
+
78
+ vocab_size: int = 250002
79
+ hidden_size: int = 1024
80
+ num_hidden_layers: int = 24
81
+ num_attention_heads: int = 16
82
+ intermediate_size: int = 4096
83
+ max_position_embeddings: int = 8194
84
+ type_vocab_size: int = 1
85
+ layer_norm_eps: float = 1e-5
86
+ rope_parameters: RopeParameters | dict | None = None
87
+
88
+ add_cross_attention = AttributeError()
89
+ is_decoder = AttributeError()
90
+
91
+
92
+ class JinaEmbeddingsV3Embeddings(XLMRobertaEmbeddings):
93
+ def __init__(self, config: JinaEmbeddingsV3Config):
94
+ super().__init__(config)
95
+
96
+ del self.padding_idx
97
+ del self.position_embeddings
98
+
99
+ def create_position_ids_from_inputs_embeds():
100
+ raise AttributeError("Not needed for JinaEmbeddingsV3")
101
+
102
+ def create_position_ids_from_input_ids():
103
+ raise AttributeError("Not needed for JinaEmbeddingsV3")
104
+
105
+ def forward(
106
+ self,
107
+ input_ids: torch.LongTensor | None = None,
108
+ token_type_ids: torch.LongTensor | None = None,
109
+ position_ids: torch.LongTensor | None = None,
110
+ inputs_embeds: torch.FloatTensor | None = None,
111
+ ) -> torch.Tensor:
112
+ embeddings = inputs_embeds
113
+ if inputs_embeds is None:
114
+ embeddings = self.word_embeddings(input_ids)
115
+
116
+ input_shape = embeddings.shape[:-1]
117
+ device = embeddings.device
118
+
119
+ if token_type_ids is None:
120
+ if hasattr(self, "token_type_ids"):
121
+ # NOTE: We assume either pos ids to have bsz == 1 (broadcastable) or bsz == effective bsz (input_shape[0])
122
+ buffered_token_type_ids = self.token_type_ids.expand(position_ids.shape[0], -1)
123
+ buffered_token_type_ids = torch.gather(buffered_token_type_ids, dim=1, index=position_ids)
124
+ token_type_ids = buffered_token_type_ids.expand(*input_shape)
125
+ else:
126
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
127
+
128
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
129
+
130
+ embeddings = embeddings + token_type_embeddings
131
+ embeddings = self.LayerNorm(embeddings)
132
+ embeddings = self.dropout(embeddings)
133
+
134
+ return embeddings
135
+
136
+
137
+ class JinaEmbeddingsV3RotaryEmbedding(LlamaRotaryEmbedding):
138
+ pass
139
+
140
+
141
+ @use_kernelized_func(apply_rotary_pos_emb)
142
+ class JinaEmbeddingsV3Attention(LlamaAttention):
143
+ def __init__(self, config: JinaEmbeddingsV3Config):
144
+ super().__init__(config)
145
+ self.is_causal = False
146
+ self.attention_dropout = config.attention_probs_dropout_prob
147
+
148
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=True)
149
+ self.k_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=True)
150
+ self.v_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=True)
151
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=True)
152
+
153
+ del self.layer_idx
154
+ del self.num_key_value_groups
155
+
156
+ def forward(
157
+ self,
158
+ hidden_states: torch.Tensor,
159
+ attention_mask: torch.Tensor | None = None,
160
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
161
+ **kwargs: Unpack[TransformersKwargs],
162
+ ) -> tuple[torch.Tensor]:
163
+ input_shape = hidden_states.shape[:-1]
164
+ hidden_shape = (*input_shape, -1, self.head_dim)
165
+
166
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
167
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
168
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
169
+
170
+ cos, sin = position_embeddings
171
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
172
+
173
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
174
+ self.config._attn_implementation, eager_attention_forward
175
+ )
176
+
177
+ attn_output, attn_weights = attention_interface(
178
+ self,
179
+ query_states,
180
+ key_states,
181
+ value_states,
182
+ attention_mask,
183
+ dropout=0.0 if not self.training else self.attention_dropout,
184
+ scaling=self.scaling,
185
+ **kwargs,
186
+ )
187
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
188
+ attn_output = self.o_proj(attn_output)
189
+ return attn_output, attn_weights
190
+
191
+
192
+ class JinaEmbeddingsV3MLP(CLIPMLP):
193
+ pass
194
+
195
+
196
+ class JinaEmbeddingsV3Layer(GPTNeoXLayer):
197
+ def __init__(self, config: JinaEmbeddingsV3Config):
198
+ super().__init__(config)
199
+ self.self_attn = JinaEmbeddingsV3Attention(config=config)
200
+
201
+ self.post_attention_dropout = nn.Dropout(config.hidden_dropout_prob)
202
+ self.post_mlp_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
203
+ self.post_mlp_dropout = nn.Dropout(config.hidden_dropout_prob)
204
+
205
+ del self.use_parallel_residual
206
+ del self.input_layernorm
207
+ del self.attention
208
+
209
+ def forward(
210
+ self,
211
+ hidden_states: torch.Tensor,
212
+ attention_mask: torch.Tensor | None = None,
213
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
214
+ **kwargs: Unpack[TransformersKwargs],
215
+ ) -> torch.FloatTensor:
216
+ residual = hidden_states
217
+ attention_output, _ = self.self_attn(
218
+ hidden_states,
219
+ attention_mask=attention_mask,
220
+ position_embeddings=position_embeddings,
221
+ **kwargs,
222
+ )
223
+ hidden_states = residual + self.post_attention_dropout(attention_output)
224
+ hidden_states = self.post_attention_layernorm(hidden_states)
225
+
226
+ residual = hidden_states
227
+ hidden_states = self.mlp(hidden_states)
228
+ hidden_states = residual + self.post_mlp_dropout(hidden_states)
229
+ hidden_states = self.post_mlp_layernorm(hidden_states)
230
+ return hidden_states
231
+
232
+
233
+ class JinaEmbeddingsV3Pooler(XLMRobertaPooler):
234
+ pass
235
+
236
+
237
+ class JinaEmbeddingsV3PreTrainedModel(XLMRobertaPreTrainedModel):
238
+ _can_record_outputs = {
239
+ "hidden_states": JinaEmbeddingsV3Layer,
240
+ "attentions": JinaEmbeddingsV3Attention,
241
+ }
242
+
243
+
244
+ @auto_docstring
245
+ class JinaEmbeddingsV3Model(XLMRobertaModel):
246
+ def __init__(self, config: JinaEmbeddingsV3Config, add_pooling_layer=True):
247
+ super().__init__(config)
248
+ self.rotary_emb = JinaEmbeddingsV3RotaryEmbedding(config)
249
+ self.layers = nn.ModuleList([JinaEmbeddingsV3Layer(config) for _ in range(config.num_hidden_layers)])
250
+ del self.encoder
251
+
252
+ # Initialize weights and apply final processing
253
+ self.post_init()
254
+
255
+ @merge_with_config_defaults
256
+ @capture_outputs
257
+ @auto_docstring
258
+ def forward(
259
+ self,
260
+ input_ids: torch.Tensor | None = None,
261
+ attention_mask: torch.Tensor | None = None,
262
+ token_type_ids: torch.Tensor | None = None,
263
+ position_ids: torch.Tensor | None = None,
264
+ inputs_embeds: torch.Tensor | None = None,
265
+ **kwargs: Unpack[TransformersKwargs],
266
+ ) -> BaseModelOutputWithPooling | tuple:
267
+ if (input_ids is None) ^ (inputs_embeds is not None):
268
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
269
+
270
+ if input_ids is not None:
271
+ seq_length = input_ids.shape[1]
272
+ device = input_ids.device
273
+ else:
274
+ seq_length = inputs_embeds.shape[1]
275
+ device = inputs_embeds.device
276
+
277
+ if position_ids is None:
278
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=device)[None, :]
279
+
280
+ embedding_output = self.embeddings(
281
+ input_ids=input_ids,
282
+ position_ids=position_ids,
283
+ token_type_ids=token_type_ids,
284
+ inputs_embeds=inputs_embeds,
285
+ )
286
+
287
+ attention_mask = create_bidirectional_mask(
288
+ config=self.config,
289
+ inputs_embeds=embedding_output,
290
+ attention_mask=attention_mask,
291
+ )
292
+
293
+ hidden_states = embedding_output
294
+ position_embeddings = self.rotary_emb(embedding_output, position_ids)
295
+
296
+ for encoder_layer in self.layers[: self.config.num_hidden_layers]:
297
+ hidden_states = encoder_layer(
298
+ hidden_states,
299
+ attention_mask=attention_mask,
300
+ position_embeddings=position_embeddings,
301
+ **kwargs,
302
+ )
303
+
304
+ sequence_output = hidden_states
305
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
306
+
307
+ return BaseModelOutputWithPooling(
308
+ last_hidden_state=sequence_output,
309
+ pooler_output=pooled_output,
310
+ )
311
+
312
+ def _create_attention_masks(self):
313
+ raise AttributeError("Not needed for JinaEmbeddingsV3")
314
+
315
+
316
+ class JinaEmbeddingsV3LMHead(XLMRobertaLMHead):
317
+ pass
318
+
319
+
320
+ class JinaEmbeddingsV3ForMaskedLM(XLMRobertaForMaskedLM):
321
+ def __init__(self, config):
322
+ JinaEmbeddingsV3PreTrainedModel.__init__(self, config=config)
323
+
324
+ self.lm_head = JinaEmbeddingsV3LMHead(config)
325
+ self.roberta = JinaEmbeddingsV3Model(config, add_pooling_layer=False)
326
+
327
+ # Initialize weights and apply final processing
328
+ self.post_init()
329
+
330
+ @can_return_tuple
331
+ @auto_docstring
332
+ def forward(
333
+ self,
334
+ input_ids: torch.LongTensor | None = None,
335
+ attention_mask: torch.FloatTensor | None = None,
336
+ token_type_ids: torch.LongTensor | None = None,
337
+ position_ids: torch.LongTensor | None = None,
338
+ inputs_embeds: torch.FloatTensor | None = None,
339
+ labels: torch.LongTensor | None = None,
340
+ **kwargs: Unpack[TransformersKwargs],
341
+ ) -> tuple[torch.Tensor] | MaskedLMOutput:
342
+ r"""
343
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
344
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
345
+
346
+ - 0 corresponds to a *sentence A* token,
347
+ - 1 corresponds to a *sentence B* token.
348
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
349
+ >= 2. All the value in this tensor should be always < type_vocab_size.
350
+
351
+ [What are token type IDs?](../glossary#token-type-ids)
352
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
353
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
354
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
355
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
356
+ """
357
+ outputs = self.roberta(
358
+ input_ids=input_ids,
359
+ attention_mask=attention_mask,
360
+ token_type_ids=token_type_ids,
361
+ position_ids=position_ids,
362
+ inputs_embeds=inputs_embeds,
363
+ return_dict=True,
364
+ **kwargs,
365
+ )
366
+ sequence_output = outputs[0]
367
+
368
+ prediction_scores = self.lm_head(sequence_output)
369
+
370
+ masked_lm_loss = None
371
+ if labels is not None:
372
+ # move labels to correct device
373
+ labels = labels.to(prediction_scores.device)
374
+ loss_fct = CrossEntropyLoss()
375
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
376
+
377
+ return MaskedLMOutput(
378
+ loss=masked_lm_loss,
379
+ logits=prediction_scores,
380
+ hidden_states=outputs.hidden_states,
381
+ attentions=outputs.attentions,
382
+ )
383
+
384
+
385
+ class JinaEmbeddingsV3ForSequenceClassification(XLMRobertaForSequenceClassification):
386
+ pass
387
+
388
+
389
+ class JinaEmbeddingsV3ForTokenClassification(XLMRobertaForTokenClassification):
390
+ pass
391
+
392
+
393
+ class JinaEmbeddingsV3ForQuestionAnswering(XLMRobertaForQuestionAnswering):
394
+ pass
395
+
396
+
397
+ __all__ = [
398
+ "JinaEmbeddingsV3Config",
399
+ "JinaEmbeddingsV3PreTrainedModel",
400
+ "JinaEmbeddingsV3Model",
401
+ "JinaEmbeddingsV3ForMaskedLM",
402
+ "JinaEmbeddingsV3ForSequenceClassification",
403
+ "JinaEmbeddingsV3ForTokenClassification",
404
+ "JinaEmbeddingsV3ForQuestionAnswering",
405
+ "JinaEmbeddingsV3Layer",
406
+ ]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/lasr/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_lasr import *
22
+ from .feature_extraction_lasr import *
23
+ from .modeling_lasr import *
24
+ from .tokenization_lasr import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/lasr/configuration_lasr.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/lasr/modular_lasr.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_lasr.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2025 The HuggingFace Inc. team and Google LLC. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ from huggingface_hub.dataclasses import strict
22
+
23
+ from ...configuration_utils import PreTrainedConfig
24
+ from ...utils import auto_docstring
25
+
26
+
27
+ @auto_docstring(checkpoint="google/medasr")
28
+ @strict
29
+ class LasrEncoderConfig(PreTrainedConfig):
30
+ r"""
31
+ convolution_bias (`bool`, *optional*, defaults to `False`):
32
+ Whether to use bias in convolutions of the conformer's convolution module.
33
+ conv_kernel_size (`int`, *optional*, defaults to 32):
34
+ The kernel size of the convolution layers in the Conformer block.
35
+ subsampling_conv_channels (`int`, *optional*, defaults to 256):
36
+ The number of channels in the subsampling convolution layers.
37
+ subsampling_conv_kernel_size (`int`, *optional*, defaults to 5):
38
+ The kernel size of the subsampling convolution layers.
39
+ subsampling_conv_stride (`int`, *optional*, defaults to 2):
40
+ The stride of the subsampling convolution layers.
41
+ dropout_positions (`float`, *optional*, defaults to 0.0):
42
+ The dropout ratio for the positions in the input sequence.
43
+ feed_forward_residual_weights (`tuple[float, float]`, *optional*, defaults to `[1.5, 0.5]`):
44
+ The residual weights for the feed forward layers.
45
+ conv_residual_weights (`tuple[float, float]`, *optional*, defaults to `[2.0, 1.0]`):
46
+ The residual weights for the convolution layers.
47
+ batch_norm_momentum (`float`, *optional*, defaults to 0.01):
48
+ The momentum for the batch normalization layers
49
+
50
+ Example:
51
+ ```python
52
+ >>> from transformers import LasrEncoderModel, LasrEncoderConfig
53
+
54
+ >>> # Initializing a `LasrEncoder` configuration
55
+ >>> configuration = LasrEncoderConfig()
56
+
57
+ >>> # Initializing a model from the configuration
58
+ >>> model = LasrEncoderModel(configuration)
59
+
60
+ >>> # Accessing the model configuration
61
+ >>> configuration = model.config
62
+ ```
63
+
64
+ This configuration class is based on the LasrEncoder architecture from Google Health AI. You can find more details
65
+ and pre-trained models at [google/medasr](https://huggingface.co/google/medasr).
66
+ """
67
+
68
+ model_type = "lasr_encoder"
69
+ keys_to_ignore_at_inference = ["past_key_values"]
70
+
71
+ hidden_size: int = 512
72
+ num_hidden_layers: int = 17
73
+ num_attention_heads: int = 8
74
+ intermediate_size: int = 2048
75
+ hidden_act: str = "silu"
76
+ attention_bias: bool = False
77
+ convolution_bias: bool = False
78
+ conv_kernel_size: int = 32
79
+ subsampling_conv_channels: int = 256
80
+ num_mel_bins: int = 128
81
+ subsampling_conv_kernel_size: int = 5
82
+ subsampling_conv_stride: int = 2
83
+ dropout: float | int = 0.1
84
+ dropout_positions: float | int = 0.0
85
+ layerdrop: float | int = 0.1
86
+ activation_dropout: float | int = 0.1
87
+ attention_dropout: float | int = 0.1
88
+ max_position_embeddings: int = 10000
89
+ initializer_range: float = 0.02
90
+ layer_norm_eps: float = 1e-6
91
+ feed_forward_residual_weights: list[float] | tuple[float, ...] = (1.5, 0.5)
92
+ conv_residual_weights: list[float] | tuple[float, ...] = (2.0, 1.0)
93
+ batch_norm_momentum: float = 0.01
94
+ rope_parameters: dict | None = None
95
+
96
+ def __post_init__(self, **kwargs):
97
+ self.num_key_value_heads = self.num_attention_heads
98
+ super().__post_init__(**kwargs)
99
+
100
+
101
+ @auto_docstring(checkpoint="google/medasr")
102
+ @strict
103
+ class LasrCTCConfig(PreTrainedConfig):
104
+ r"""
105
+ ctc_loss_reduction (`str`, *optional*, defaults to `"mean"`):
106
+ Specifies the reduction to apply to the output of `torch.nn.CTCLoss`. Only relevant when training an
107
+ instance of [`LasrForCTC`].
108
+ ctc_zero_infinity (`bool`, *optional*, defaults to `True`):
109
+ Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly
110
+ occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance
111
+ of [`LasrForCTC`].
112
+
113
+ Example:
114
+ ```python
115
+ >>> from transformers import LasrForCTC, LasrCTCConfig
116
+ >>> # Initializing a Lasr configuration
117
+ >>> configuration = LasrCTCConfig()
118
+ >>> # Initializing a model from the configuration
119
+ >>> model = LasrForCTC(configuration)
120
+ >>> # Accessing the model configuration
121
+ >>> configuration = model.config
122
+ ```
123
+ This configuration class is based on the Lasr CTC architecture from Google Health AI. You can find more details
124
+ and pre-trained models at [google/medasr](https://huggingface.co/google/medasr).
125
+ """
126
+
127
+ model_type = "lasr_ctc"
128
+ sub_configs = {"encoder_config": LasrEncoderConfig}
129
+
130
+ vocab_size: int = 512
131
+ ctc_loss_reduction: str = "mean"
132
+ ctc_zero_infinity: bool = True
133
+ encoder_config: dict | PreTrainedConfig | None = None
134
+ pad_token_id: int = 0
135
+
136
+ def __post_init__(self, **kwargs):
137
+ if isinstance(self.encoder_config, dict):
138
+ self.encoder_config = LasrEncoderConfig(**self.encoder_config)
139
+ elif self.encoder_config is None:
140
+ self.encoder_config = LasrEncoderConfig()
141
+ self.initializer_range = self.encoder_config.initializer_range
142
+ super().__post_init__(**kwargs)
143
+
144
+ @property
145
+ def inputs_to_logits_ratio(self):
146
+ return self.encoder_config.subsampling_conv_stride**2
147
+
148
+
149
+ __all__ = ["LasrEncoderConfig", "LasrCTCConfig"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/lasr/feature_extraction_lasr.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Inc. team and Google LLC. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import numpy as np
16
+ import torch
17
+
18
+ from ...audio_utils import hertz_to_mel
19
+ from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
20
+ from ...feature_extraction_utils import BatchFeature
21
+ from ...utils import TensorType, logging
22
+ from ...utils.import_utils import requires
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+
28
+ # TODO: @eustlb, we should be able to remove this and use mel_filter_bank from audio_utils
29
+ def linear_to_mel_weight_matrix(
30
+ num_mel_bins: int,
31
+ num_spectrogram_bins: int,
32
+ sample_rate: float,
33
+ lower_edge_hertz: float,
34
+ upper_edge_hertz: float,
35
+ dtype,
36
+ ) -> np.ndarray:
37
+ """NumPy-port of the JAX mel weight matrix logic."""
38
+ # We use float64 for precision, matching the JAX implementation.
39
+ internal_dtype = np.float64
40
+
41
+ # HTK excludes the spectrogram DC bin.
42
+ bands_to_zero = 1
43
+ nyquist_hertz = sample_rate / 2.0
44
+ linear_frequencies = np.linspace(0.0, nyquist_hertz, num_spectrogram_bins, dtype=internal_dtype)[bands_to_zero:]
45
+ spectrogram_bins_mel = hertz_to_mel(linear_frequencies, mel_scale="kaldi")[:, np.newaxis]
46
+
47
+ edges = np.linspace(
48
+ hertz_to_mel(lower_edge_hertz, mel_scale="kaldi"),
49
+ hertz_to_mel(upper_edge_hertz, mel_scale="kaldi"),
50
+ num_mel_bins + 2,
51
+ dtype=internal_dtype,
52
+ )
53
+
54
+ lower_edge_mel, center_mel, upper_edge_mel = (
55
+ edges[:-2][np.newaxis, :],
56
+ edges[1:-1][np.newaxis, :],
57
+ edges[2:][np.newaxis, :],
58
+ )
59
+
60
+ lower_slopes = (spectrogram_bins_mel - lower_edge_mel) / (center_mel - lower_edge_mel)
61
+ upper_slopes = (upper_edge_mel - spectrogram_bins_mel) / (upper_edge_mel - center_mel)
62
+ mel_weights_matrix = np.maximum(0.0, np.minimum(lower_slopes, upper_slopes))
63
+ return np.pad(mel_weights_matrix, [[bands_to_zero, 0], [0, 0]]).astype(dtype)
64
+
65
+
66
+ @requires(backends=("torch",))
67
+ class LasrFeatureExtractor(SequenceFeatureExtractor):
68
+ r"""
69
+ Constructs a LASR feature extractor.
70
+
71
+ This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExtractor`] which contains
72
+ most of the main methods. Users should refer to this superclass for more information regarding those methods.
73
+
74
+ This class extracts mel-filter bank features from raw speech using a custom numpy implementation of the `Short Time
75
+ Fourier Transform` which should match pytorch's `torch.stft` equivalent.
76
+
77
+ Args:
78
+ feature_size (`int`, *optional*, defaults to 128):
79
+ The feature dimension of the extracted features.
80
+ sampling_rate (`int`, *optional*, defaults to 16000):
81
+ The sampling rate at which the audio files should be digitalized expressed in hertz (Hz).
82
+ hop_length (`int`, *optional*, defaults to 160):
83
+ Length of the overlapping windows for the STFT used to obtain the Mel Frequency coefficients.
84
+ n_fft (`int`, *optional*, defaults to 512):
85
+ Size of the Fourier transform.
86
+ win_length (`int`, *optional*, defaults to 400):
87
+ The window length for the STFT computation.
88
+ padding_value (`float`, *optional*, defaults to 0.0):
89
+ Padding value used to pad the audio. Should correspond to silences.
90
+ """
91
+
92
+ model_input_names = ["input_features", "attention_mask"]
93
+
94
+ def __init__(
95
+ self,
96
+ feature_size=128,
97
+ sampling_rate=16000,
98
+ hop_length=160,
99
+ n_fft=512,
100
+ win_length=400,
101
+ padding_value=0.0,
102
+ **kwargs,
103
+ ):
104
+ super().__init__(feature_size=feature_size, sampling_rate=sampling_rate, padding_value=padding_value, **kwargs)
105
+
106
+ self.hop_length = hop_length
107
+ self.n_fft = n_fft
108
+ self.win_length = win_length
109
+ self.mel_filters = torch.from_numpy(
110
+ linear_to_mel_weight_matrix(
111
+ num_mel_bins=feature_size,
112
+ num_spectrogram_bins=n_fft // 2 + 1,
113
+ sample_rate=sampling_rate,
114
+ lower_edge_hertz=125.0,
115
+ upper_edge_hertz=7500.0,
116
+ dtype=np.float64,
117
+ )
118
+ )
119
+
120
+ def _torch_extract_fbank_features(self, waveform, device="cpu"):
121
+ # spectrogram
122
+ window = torch.hann_window(self.win_length, periodic=False, device=device, dtype=torch.float64)
123
+ waveform = waveform.to(torch.float64)
124
+
125
+ # TODO: @eustlb, to be standardized
126
+ # here we cannot use directly torch.stft because every fft frame is padded with zeros
127
+ # due to unfold then rfft, while torch.stft unfolds with the number of fft points
128
+ frames = waveform.unfold(-1, self.win_length, self.hop_length)
129
+ stft = torch.fft.rfft(window * frames, n=self.n_fft)
130
+ power_spec = torch.abs(stft) ** 2
131
+
132
+ # log mel spectrogram
133
+ mel_filters = self.mel_filters.to(device)
134
+ mel_spec = torch.clamp(power_spec @ mel_filters, min=1e-5)
135
+ mel_spec = torch.log(mel_spec)
136
+
137
+ return mel_spec
138
+
139
+ def __call__(
140
+ self,
141
+ raw_speech: np.ndarray | list[float] | list[np.ndarray] | list[list[float]],
142
+ truncation: bool = False,
143
+ pad_to_multiple_of: int | None = None,
144
+ return_tensors: str | TensorType | None = None,
145
+ return_attention_mask: bool | None = None,
146
+ padding: str | None = "longest",
147
+ max_length: int | None = None,
148
+ sampling_rate: int | None = None,
149
+ do_normalize: bool | None = None,
150
+ device: str | None = "cpu",
151
+ return_token_timestamps: bool | None = None,
152
+ **kwargs,
153
+ ) -> BatchFeature:
154
+ """
155
+ Main method to featurize and prepare for the model one or several sequence(s). Implementation uses PyTorch for
156
+ the STFT computation if available, otherwise a slower NumPy based one.
157
+
158
+ Args:
159
+ raw_speech (`np.ndarray`, `list[float]`, `list[np.ndarray]`, `list[list[float]]`):
160
+ The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float
161
+ values, a list of numpy arrays or a list of list of float values. Must be mono channel audio, not
162
+ stereo, i.e. single float per timestep.
163
+ truncation (`bool`, *optional*, default to `True`):
164
+ Activates truncation to cut input sequences longer than *max_length* to *max_length*.
165
+ pad_to_multiple_of (`int`, *optional*, defaults to None):
166
+ If set will pad the sequence to a multiple of the provided value.
167
+
168
+ This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
169
+ `>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128.
170
+ return_attention_mask (`bool`, *optional*):
171
+ Whether to return the attention mask. If left to the default, will return the attention mask according
172
+ to the specific feature_extractor's default.
173
+
174
+ [What are attention masks?](../glossary#attention-mask)
175
+
176
+ <Tip>
177
+
178
+ For Parakeet models, `attention_mask` should always be passed for batched inference, to avoid subtle
179
+ bugs.
180
+
181
+ </Tip>
182
+
183
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
184
+ If set, will return tensors instead of list of python integers. Acceptable values are:
185
+
186
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
187
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
188
+ - `'np'`: Return Numpy `np.ndarray` objects.
189
+ sampling_rate (`int`, *optional*):
190
+ The sampling rate at which the `raw_speech` input was sampled. It is strongly recommended to pass
191
+ `sampling_rate` at the forward call to prevent silent errors and allow automatic speech recognition
192
+ pipeline.
193
+ padding_value (`float`, *optional*, defaults to 0.0):
194
+ The value that is used to fill the padding values / vectors.
195
+ do_normalize (`bool`, *optional*, defaults to `False`):
196
+ Whether or not to zero-mean unit-variance normalize the input. Normalizing can help to significantly
197
+ improve the performance of the model.
198
+ device (`str`, *optional*, defaults to `'cpu'`):
199
+ Specifies the device for computation of the log-mel spectrogram of audio signals in the
200
+ `_torch_extract_fbank_features` method. (e.g., "cpu", "cuda")
201
+ return_token_timestamps (`bool`, *optional*, defaults to `None`):
202
+ Deprecated. Use `return_attention_mask` instead from which the number of frames can be inferred.
203
+
204
+ Whether or not to return the number of frames of the input raw_speech.
205
+ These num_frames can be used by the model to compute word level timestamps.
206
+ """
207
+ if sampling_rate is not None:
208
+ if sampling_rate != self.sampling_rate:
209
+ raise ValueError(
210
+ f"The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a"
211
+ f" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input"
212
+ f" was sampled with {self.sampling_rate} and not {sampling_rate}."
213
+ )
214
+ else:
215
+ logger.warning(
216
+ f"It is strongly recommended to pass the `sampling_rate` argument to `{self.__class__.__name__}()`. "
217
+ "Failing to do so can result in silent errors that might be hard to debug."
218
+ )
219
+
220
+ # Convert to torch tensor
221
+ if isinstance(raw_speech, np.ndarray):
222
+ raw_speech = torch.tensor(raw_speech)
223
+ elif isinstance(raw_speech, (list, tuple)):
224
+ if isinstance(raw_speech[0], (list, np.ndarray)):
225
+ raw_speech = [torch.tensor(speech) for speech in raw_speech]
226
+ else: # list[float]
227
+ raw_speech = torch.tensor(raw_speech)
228
+
229
+ is_batched_torch = isinstance(raw_speech, torch.Tensor) and len(raw_speech.shape) > 1
230
+ if is_batched_torch and len(raw_speech.shape) > 2:
231
+ logger.warning(
232
+ f"Only mono-channel audio is supported for input to {self.__class__.__name__}. "
233
+ "We will take the mean of the channels to convert to mono."
234
+ )
235
+ raw_speech = raw_speech.mean(-1)
236
+
237
+ is_batched_sequence = isinstance(raw_speech, (list, tuple))
238
+ if is_batched_sequence:
239
+ for speech in raw_speech:
240
+ if len(speech.shape) > 1:
241
+ logger.warning(
242
+ f"Only mono-channel audio is supported for input to {self.__class__.__name__}. "
243
+ "We will take the mean of the channels to convert to mono."
244
+ )
245
+ speech = speech.mean(-1)
246
+
247
+ if is_batched_torch or is_batched_sequence:
248
+ raw_speech = [speech[:, None].to(torch.float32) for speech in raw_speech]
249
+ else:
250
+ raw_speech = [raw_speech[:, None].to(torch.float32)]
251
+
252
+ batched_speech = BatchFeature({"input_features": raw_speech})
253
+ padded_inputs = self.pad(
254
+ batched_speech,
255
+ padding=padding,
256
+ max_length=max_length,
257
+ truncation=truncation,
258
+ pad_to_multiple_of=pad_to_multiple_of,
259
+ return_attention_mask=return_attention_mask,
260
+ return_tensors="pt",
261
+ )
262
+ input_features = padded_inputs.input_features.squeeze(-1)
263
+ input_features = self._torch_extract_fbank_features(input_features, device)
264
+ data = {
265
+ "input_features": input_features.to(torch.float32),
266
+ }
267
+
268
+ if return_attention_mask:
269
+ attention_mask = padded_inputs.attention_mask[:, self.win_length - 1 :: self.hop_length]
270
+ data["attention_mask"] = attention_mask.to(torch.bool)
271
+
272
+ return BatchFeature(data=data, tensor_type=return_tensors)
273
+
274
+
275
+ __all__ = ["LasrFeatureExtractor"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/lasr/modular_lasr.py ADDED
@@ -0,0 +1,606 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Inc. team and Google LLC. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import itertools
16
+ from collections.abc import Callable
17
+
18
+ import torch
19
+ from huggingface_hub.dataclasses import strict
20
+ from tokenizers import Tokenizer, decoders, normalizers, pre_tokenizers, processors
21
+ from tokenizers.models import Unigram
22
+ from torch import nn
23
+
24
+ from ...audio_utils import AudioInput, make_list_of_audio
25
+ from ...masking_utils import create_bidirectional_mask
26
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
27
+ from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
28
+ from ...tokenization_utils_base import PreTokenizedInput, TextInput
29
+ from ...tokenization_utils_tokenizers import TokenizersBackend
30
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
31
+ from ...utils.generic import merge_with_config_defaults
32
+ from ...utils.output_capturing import capture_outputs
33
+ from ..llama.modeling_llama import LlamaAttention, LlamaRotaryEmbedding, apply_rotary_pos_emb, eager_attention_forward
34
+ from ..parakeet.configuration_parakeet import ParakeetCTCConfig, ParakeetEncoderConfig
35
+ from ..parakeet.modeling_parakeet import (
36
+ ParakeetEncoderBlock,
37
+ ParakeetEncoderConvolutionModule,
38
+ ParakeetEncoderModelOutput,
39
+ ParakeetForCTC,
40
+ ParakeetPreTrainedModel,
41
+ )
42
+ from ..t5.tokenization_t5 import T5Tokenizer
43
+
44
+
45
+ logger = logging.get_logger(__name__)
46
+
47
+
48
+ class LasrTokenizer(T5Tokenizer, TokenizersBackend):
49
+ def __init__(
50
+ self,
51
+ eos_token="</s>",
52
+ unk_token="<unk>",
53
+ pad_token="<pad>",
54
+ _spm_precompiled_charsmap=None,
55
+ extra_ids=100,
56
+ additional_special_tokens=None,
57
+ vocab=None,
58
+ vocab_file=None,
59
+ **kwargs,
60
+ ):
61
+ self._extra_ids = extra_ids
62
+
63
+ # Handle extra_ids and additional_special_tokens
64
+ if additional_special_tokens is not None:
65
+ extra_tokens = [x for x in additional_special_tokens if "<extra_id_" in str(x)]
66
+ if len(extra_tokens) < 1:
67
+ additional_special_tokens += [f"<extra_id_{i}>" for i in range(extra_ids)]
68
+ elif extra_ids > 0 and extra_ids != len(extra_tokens):
69
+ raise ValueError(
70
+ f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are"
71
+ " provided to LasrTokenizer. In this case the additional_special_tokens must include the extra_ids"
72
+ " tokens"
73
+ )
74
+ else:
75
+ extra_tokens = [f"<extra_id_{i}>" for i in range(extra_ids)]
76
+ additional_special_tokens = extra_tokens
77
+
78
+ # LASR vocab structure: <pad>=0, </s>=1, <unk>=2, then regular vocab, then extra_ids in reverse
79
+ if vocab is not None:
80
+ self._vocab_scores = vocab
81
+ else:
82
+ self._vocab_scores = [
83
+ (str(pad_token), 0.0),
84
+ (str(eos_token), 0.0),
85
+ (str(unk_token), 0.0),
86
+ ("▁", -2.0), # Space token
87
+ ]
88
+ for i in range(extra_ids - 1, -1, -1):
89
+ self._vocab_scores.append((f"<extra_id_{i}>", 0.0))
90
+ self._tokenizer = Tokenizer(
91
+ Unigram(
92
+ self._vocab_scores,
93
+ unk_id=3,
94
+ byte_fallback=False,
95
+ )
96
+ )
97
+
98
+ if _spm_precompiled_charsmap is not None:
99
+ self._tokenizer.normalizer = normalizers.Precompiled(_spm_precompiled_charsmap)
100
+
101
+ self._tokenizer.pre_tokenizer = pre_tokenizers.Sequence(
102
+ [
103
+ pre_tokenizers.WhitespaceSplit(),
104
+ pre_tokenizers.Metaspace(replacement="▁", prepend_scheme="always", split=True),
105
+ ]
106
+ )
107
+ self._tokenizer.decoder = decoders.Metaspace(replacement="▁", prepend_scheme="always", split=True)
108
+
109
+ TokenizersBackend.__init__(
110
+ eos_token=eos_token,
111
+ unk_token=unk_token,
112
+ pad_token=pad_token,
113
+ extra_ids=extra_ids,
114
+ additional_special_tokens=additional_special_tokens,
115
+ **kwargs,
116
+ )
117
+
118
+ self._tokenizer.post_processor = processors.TemplateProcessing(
119
+ single=["$A", "</s>"],
120
+ pair=["$A", "</s>", "$B", "</s>"],
121
+ special_tokens=[
122
+ ("</s>", self.eos_token_id),
123
+ ],
124
+ )
125
+
126
+ def _decode(
127
+ self,
128
+ token_ids: int | list[int],
129
+ skip_special_tokens: bool = False,
130
+ clean_up_tokenization_spaces: bool | None = None,
131
+ group_tokens: bool = True,
132
+ **kwargs,
133
+ ) -> str:
134
+ if isinstance(token_ids, int):
135
+ token_ids = [token_ids]
136
+ if group_tokens:
137
+ token_ids = [token_group[0] for token_group in itertools.groupby(token_ids)]
138
+
139
+ # for CTC we filter out the blank token, which is the pad token
140
+ token_ids = [token for token in token_ids if token != self.pad_token_id]
141
+
142
+ return TokenizersBackend._decode(
143
+ self,
144
+ token_ids=token_ids,
145
+ skip_special_tokens=skip_special_tokens,
146
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
147
+ **kwargs,
148
+ )
149
+
150
+
151
+ class LasrProcessorKwargs(ProcessingKwargs, total=False):
152
+ _defaults = {
153
+ "audio_kwargs": {
154
+ "sampling_rate": 16000,
155
+ "padding": "longest",
156
+ "return_attention_mask": True,
157
+ },
158
+ "text_kwargs": {
159
+ "padding": True,
160
+ "padding_side": "right",
161
+ "add_special_tokens": False,
162
+ },
163
+ "common_kwargs": {"return_tensors": "pt"},
164
+ }
165
+
166
+
167
+ @auto_docstring
168
+ class LasrProcessor(ProcessorMixin):
169
+ def __init__(self, feature_extractor, tokenizer):
170
+ super().__init__(feature_extractor, tokenizer)
171
+
172
+ @auto_docstring
173
+ def __call__(
174
+ self,
175
+ audio: AudioInput,
176
+ text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None,
177
+ sampling_rate: int | None = None,
178
+ **kwargs: Unpack[LasrProcessorKwargs],
179
+ ):
180
+ r"""
181
+ sampling_rate (`int`, *optional*):
182
+ The sampling rate of the input audio in Hz. This should match the sampling rate expected by the feature
183
+ extractor (defaults to 16000 Hz). If provided, it will be validated against the processor's expected
184
+ sampling rate, and an error will be raised if they don't match. If not provided, a warning will be
185
+ issued and the default sampling rate will be assumed.
186
+ """
187
+ audio = make_list_of_audio(audio)
188
+
189
+ output_kwargs = self._merge_kwargs(
190
+ LasrProcessorKwargs,
191
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
192
+ **kwargs,
193
+ )
194
+
195
+ if sampling_rate is None:
196
+ logger.warning_once(
197
+ f"You've provided audio without specifying the sampling rate. It will be assumed to be {output_kwargs['audio_kwargs']['sampling_rate']}, which can result in silent errors."
198
+ )
199
+ elif sampling_rate != output_kwargs["audio_kwargs"]["sampling_rate"]:
200
+ raise ValueError(
201
+ f"The sampling rate of the audio ({sampling_rate}) does not match the sampling rate of the processor ({output_kwargs['audio_kwargs']['sampling_rate']}). Please provide resampled the audio to the expected sampling rate."
202
+ )
203
+
204
+ if audio is not None:
205
+ inputs = self.feature_extractor(audio, **output_kwargs["audio_kwargs"])
206
+ if text is not None:
207
+ encodings = self.tokenizer(text, **output_kwargs["text_kwargs"])
208
+
209
+ if text is None:
210
+ return inputs
211
+ else:
212
+ inputs["labels"] = encodings["input_ids"]
213
+ return inputs
214
+
215
+ @property
216
+ def model_input_names(self):
217
+ feature_extractor_input_names = self.feature_extractor.model_input_names
218
+ return feature_extractor_input_names + ["labels"]
219
+
220
+
221
+ @auto_docstring(checkpoint="google/medasr")
222
+ @strict
223
+ class LasrEncoderConfig(ParakeetEncoderConfig):
224
+ r"""
225
+ convolution_bias (`bool`, *optional*, defaults to `False`):
226
+ Whether to use bias in convolutions of the conformer's convolution module.
227
+ conv_kernel_size (`int`, *optional*, defaults to 32):
228
+ The kernel size of the convolution layers in the Conformer block.
229
+ subsampling_conv_channels (`int`, *optional*, defaults to 256):
230
+ The number of channels in the subsampling convolution layers.
231
+ subsampling_conv_kernel_size (`int`, *optional*, defaults to 5):
232
+ The kernel size of the subsampling convolution layers.
233
+ subsampling_conv_stride (`int`, *optional*, defaults to 2):
234
+ The stride of the subsampling convolution layers.
235
+ dropout_positions (`float`, *optional*, defaults to 0.0):
236
+ The dropout ratio for the positions in the input sequence.
237
+ feed_forward_residual_weights (`tuple[float, float]`, *optional*, defaults to `[1.5, 0.5]`):
238
+ The residual weights for the feed forward layers.
239
+ conv_residual_weights (`tuple[float, float]`, *optional*, defaults to `[2.0, 1.0]`):
240
+ The residual weights for the convolution layers.
241
+ batch_norm_momentum (`float`, *optional*, defaults to 0.01):
242
+ The momentum for the batch normalization layers
243
+
244
+ Example:
245
+ ```python
246
+ >>> from transformers import LasrEncoderModel, LasrEncoderConfig
247
+
248
+ >>> # Initializing a `LasrEncoder` configuration
249
+ >>> configuration = LasrEncoderConfig()
250
+
251
+ >>> # Initializing a model from the configuration
252
+ >>> model = LasrEncoderModel(configuration)
253
+
254
+ >>> # Accessing the model configuration
255
+ >>> configuration = model.config
256
+ ```
257
+
258
+ This configuration class is based on the LasrEncoder architecture from Google Health AI. You can find more details
259
+ and pre-trained models at [google/medasr](https://huggingface.co/google/medasr).
260
+ """
261
+
262
+ hidden_size: int = 512
263
+ num_hidden_layers: int = 17
264
+ intermediate_size: int = 2048
265
+ attention_bias: bool = False
266
+ convolution_bias: bool = False
267
+ conv_kernel_size: int = 32
268
+ subsampling_conv_kernel_size: int = 5
269
+ num_mel_bins: int = 128
270
+ max_position_embeddings: int = 10000
271
+ layer_norm_eps: float = 1e-6
272
+ feed_forward_residual_weights: list[float] | tuple[float, ...] = (1.5, 0.5)
273
+ conv_residual_weights: list[float] | tuple[float, ...] = (2.0, 1.0)
274
+ batch_norm_momentum: float = 0.01
275
+ rope_parameters: dict | None = None
276
+
277
+ subsampling_factor = AttributeError()
278
+ scale_input = AttributeError()
279
+
280
+
281
+ @auto_docstring(checkpoint="google/medasr")
282
+ @strict
283
+ class LasrCTCConfig(ParakeetCTCConfig):
284
+ r"""
285
+ ctc_loss_reduction (`str`, *optional*, defaults to `"mean"`):
286
+ Specifies the reduction to apply to the output of `torch.nn.CTCLoss`. Only relevant when training an
287
+ instance of [`LasrForCTC`].
288
+ ctc_zero_infinity (`bool`, *optional*, defaults to `True`):
289
+ Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly
290
+ occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance
291
+ of [`LasrForCTC`].
292
+
293
+ Example:
294
+ ```python
295
+ >>> from transformers import LasrForCTC, LasrCTCConfig
296
+ >>> # Initializing a Lasr configuration
297
+ >>> configuration = LasrCTCConfig()
298
+ >>> # Initializing a model from the configuration
299
+ >>> model = LasrForCTC(configuration)
300
+ >>> # Accessing the model configuration
301
+ >>> configuration = model.config
302
+ ```
303
+ This configuration class is based on the Lasr CTC architecture from Google Health AI. You can find more details
304
+ and pre-trained models at [google/medasr](https://huggingface.co/google/medasr).
305
+ """
306
+
307
+ vocab_size: int = 512
308
+ pad_token_id: int = 0
309
+
310
+ @property
311
+ def inputs_to_logits_ratio(self):
312
+ return self.encoder_config.subsampling_conv_stride**2
313
+
314
+
315
+ class LasrEncoderSubsampling(nn.Module):
316
+ def __init__(self, config: LasrEncoderConfig):
317
+ super().__init__()
318
+ self.dense_0 = nn.Linear(config.num_mel_bins, config.hidden_size)
319
+ self.conv_0 = nn.Conv1d(
320
+ config.hidden_size,
321
+ config.hidden_size,
322
+ kernel_size=config.subsampling_conv_kernel_size,
323
+ stride=config.subsampling_conv_stride,
324
+ )
325
+ self.conv_1 = nn.Conv1d(
326
+ config.hidden_size,
327
+ config.subsampling_conv_channels,
328
+ kernel_size=config.subsampling_conv_kernel_size,
329
+ stride=config.subsampling_conv_stride,
330
+ )
331
+ self.dense_1 = nn.Linear(config.subsampling_conv_channels, config.hidden_size)
332
+ self.act_fn = nn.ReLU()
333
+
334
+ def forward(self, input_features: torch.Tensor) -> torch.Tensor:
335
+ hidden_states = self.act_fn(self.dense_0(input_features))
336
+ hidden_states = hidden_states.transpose(1, 2)
337
+ hidden_states = self.act_fn(self.conv_0(hidden_states))
338
+ hidden_states = self.act_fn(self.conv_1(hidden_states))
339
+ hidden_states = hidden_states.transpose(1, 2)
340
+ return self.dense_1(hidden_states)
341
+
342
+
343
+ class LasrEncoderRotaryEmbedding(LlamaRotaryEmbedding): ...
344
+
345
+
346
+ class LasrEncoderAttention(LlamaAttention):
347
+ def __init__(self, config: LasrEncoderConfig, layer_idx: int):
348
+ super().__init__(config, layer_idx)
349
+ self.is_causal = False
350
+
351
+ def forward(
352
+ self,
353
+ hidden_states: torch.Tensor,
354
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
355
+ attention_mask: torch.Tensor | None = None,
356
+ **kwargs: Unpack[TransformersKwargs],
357
+ ) -> tuple[torch.Tensor, torch.Tensor]:
358
+ input_shape = hidden_states.shape[:-1]
359
+ hidden_shape = (*input_shape, -1, self.head_dim)
360
+
361
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
362
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
363
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
364
+
365
+ cos, sin = position_embeddings
366
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
367
+
368
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
369
+ self.config._attn_implementation, eager_attention_forward
370
+ )
371
+
372
+ attn_output, attn_weights = attention_interface(
373
+ self,
374
+ query_states,
375
+ key_states,
376
+ value_states,
377
+ attention_mask,
378
+ dropout=0.0 if not self.training else self.attention_dropout,
379
+ scaling=self.scaling,
380
+ **kwargs,
381
+ )
382
+
383
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
384
+ attn_output = self.o_proj(attn_output)
385
+ return attn_output, attn_weights
386
+
387
+
388
+ class LasrEncoderConvolutionModule(ParakeetEncoderConvolutionModule):
389
+ def __init__(self, config: LasrEncoderConfig, module_config=None):
390
+ super().__init__(config, module_config)
391
+ self.padding = "same"
392
+ self.norm = nn.BatchNorm1d(config.hidden_size, momentum=config.batch_norm_momentum)
393
+
394
+
395
+ class LasrEncoderBlock(ParakeetEncoderBlock):
396
+ def __init__(self, config: LasrEncoderConfig, layer_idx: int):
397
+ super().__init__(config, layer_idx)
398
+
399
+ self.feed_forward_residual_weights = config.feed_forward_residual_weights
400
+ self.conv_residual_weights = config.conv_residual_weights
401
+
402
+ self.norm_feed_forward1 = nn.LayerNorm(config.hidden_size, config.layer_norm_eps, bias=False)
403
+ self.norm_self_att = nn.LayerNorm(config.hidden_size, config.layer_norm_eps, bias=False)
404
+ self.norm_conv = nn.LayerNorm(config.hidden_size, config.layer_norm_eps, bias=False)
405
+ self.norm_feed_forward2 = nn.LayerNorm(config.hidden_size, config.layer_norm_eps, bias=False)
406
+ self.norm_out = nn.LayerNorm(config.hidden_size, config.layer_norm_eps, bias=False)
407
+
408
+ def forward(
409
+ self,
410
+ hidden_states: torch.Tensor,
411
+ attention_mask: torch.Tensor | None = None,
412
+ position_embeddings: torch.Tensor | None = None,
413
+ **kwargs: Unpack[TransformersKwargs],
414
+ ) -> torch.Tensor:
415
+ residual = hidden_states
416
+ hidden_states = self.feed_forward1(self.norm_feed_forward1(hidden_states))
417
+ hidden_states = (
418
+ self.feed_forward_residual_weights[0] * residual + self.feed_forward_residual_weights[1] * hidden_states
419
+ )
420
+
421
+ normalized_hidden_states = self.norm_self_att(hidden_states)
422
+ attn_output, _ = self.self_attn(
423
+ hidden_states=normalized_hidden_states,
424
+ attention_mask=attention_mask,
425
+ position_embeddings=position_embeddings,
426
+ **kwargs,
427
+ )
428
+ hidden_states = hidden_states + attn_output
429
+
430
+ conv_output = self.conv(self.norm_conv(hidden_states), attention_mask=attention_mask)
431
+ hidden_states = self.conv_residual_weights[0] * hidden_states + self.conv_residual_weights[1] * conv_output
432
+
433
+ residual = hidden_states
434
+ hidden_states = self.feed_forward2(self.norm_feed_forward2(hidden_states))
435
+ hidden_states = (
436
+ self.feed_forward_residual_weights[0] * residual + self.feed_forward_residual_weights[1] * hidden_states
437
+ )
438
+
439
+ hidden_states = self.norm_out(hidden_states)
440
+
441
+ return hidden_states
442
+
443
+
444
+ class LasrPreTrainedModel(ParakeetPreTrainedModel):
445
+ # padding is incompatible with flex attention as the resulting mask cannot be used to apply padding
446
+ _supports_flex_attn = False
447
+
448
+ def _init_weights(self, module):
449
+ PreTrainedModel._init_weights(module)
450
+
451
+ def _get_subsampling_output_length(self, input_lengths: torch.Tensor):
452
+ encoder_config = self.config.encoder_config if isinstance(self.config, LasrCTCConfig) else self.config
453
+ kernel_size = encoder_config.subsampling_conv_kernel_size
454
+ stride = encoder_config.subsampling_conv_stride
455
+
456
+ num_layers = 2
457
+ for _ in range(num_layers):
458
+ input_lengths = (input_lengths - kernel_size) // stride + 1
459
+
460
+ return input_lengths
461
+
462
+
463
+ class LasrEncoderModelOutput(ParakeetEncoderModelOutput):
464
+ pass
465
+
466
+
467
+ @auto_docstring(
468
+ custom_intro="""
469
+ The LasrEncoder model, based on the Conformer architecture](https://arxiv.org/abs/2005.08100).
470
+ """
471
+ )
472
+ class LasrEncoder(LasrPreTrainedModel):
473
+ config: LasrEncoderConfig
474
+ base_model_prefix = "encoder"
475
+
476
+ def __init__(self, config: LasrEncoderConfig):
477
+ super().__init__(config)
478
+ self.gradient_checkpointing = False
479
+
480
+ self.dropout = config.dropout
481
+ self.dropout_positions = config.dropout_positions
482
+ self.layerdrop = config.layerdrop
483
+
484
+ self.subsampler = LasrEncoderSubsampling(config)
485
+ self.rotary_emb = LasrEncoderRotaryEmbedding(config)
486
+ self.layers = nn.ModuleList(
487
+ [LasrEncoderBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
488
+ )
489
+ self.out_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps, bias=False)
490
+
491
+ self.post_init()
492
+
493
+ @auto_docstring
494
+ @merge_with_config_defaults
495
+ @capture_outputs
496
+ @can_return_tuple
497
+ def forward(
498
+ self,
499
+ input_features: torch.Tensor,
500
+ attention_mask: torch.Tensor | None = None,
501
+ output_attention_mask: bool | None = None,
502
+ **kwargs: Unpack[TransformersKwargs],
503
+ ) -> LasrEncoderModelOutput:
504
+ r"""
505
+ output_attention_mask (`bool`, *optional*):
506
+ Whether to return the output attention mask.
507
+
508
+ Example:
509
+
510
+ ```python
511
+ >>> from transformers import AutoProcessor, LasrEncoder
512
+ >>> from datasets import load_dataset, Audio
513
+
514
+ >>> model_id = "google/medasr"
515
+ >>> processor = AutoProcessor.from_pretrained(model_id)
516
+ >>> encoder = ParakeetEncoder.from_pretrained(model_id)
517
+
518
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
519
+ >>> ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
520
+
521
+ >>> inputs = processor(ds[0]["audio"]["array"])
522
+ >>> encoder_outputs = encoder(**inputs)
523
+
524
+ >>> print(encoder_outputs.last_hidden_state.shape)
525
+ ```
526
+ """
527
+
528
+ hidden_states = self.subsampler(input_features)
529
+ cos, sin = self.rotary_emb(
530
+ hidden_states, torch.arange(hidden_states.shape[1], device=hidden_states.device).unsqueeze(0)
531
+ )
532
+
533
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
534
+ cos = nn.functional.dropout(cos, p=self.dropout_positions, training=self.training)
535
+ sin = nn.functional.dropout(sin, p=self.dropout_positions, training=self.training)
536
+
537
+ output_mask = None
538
+ if attention_mask is not None:
539
+ output_mask = self._get_output_attention_mask(attention_mask, target_length=hidden_states.shape[1])
540
+ attention_mask = output_mask
541
+
542
+ attention_mask = create_bidirectional_mask(
543
+ config=self.config,
544
+ inputs_embeds=hidden_states,
545
+ attention_mask=attention_mask,
546
+ )
547
+
548
+ for encoder_layer in self.layers:
549
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
550
+ to_drop = False
551
+ if self.training:
552
+ dropout_probability = torch.rand([])
553
+ if dropout_probability < self.layerdrop: # skip the layer
554
+ to_drop = True
555
+
556
+ if not to_drop:
557
+ hidden_states = encoder_layer(
558
+ hidden_states,
559
+ attention_mask=attention_mask,
560
+ position_embeddings=(cos, sin),
561
+ **kwargs,
562
+ )
563
+
564
+ hidden_states = self.out_norm(hidden_states)
565
+
566
+ return LasrEncoderModelOutput(
567
+ last_hidden_state=hidden_states,
568
+ attention_mask=output_mask.int() if output_attention_mask and output_mask is not None else None,
569
+ )
570
+
571
+
572
+ class LasrForCTC(ParakeetForCTC):
573
+ def generate(**super_kwargs):
574
+ r"""
575
+ Example:
576
+
577
+ ```python
578
+ >>> from transformers import AutoProcessor, LasrForCTC
579
+ >>> from datasets import load_dataset, Audio
580
+
581
+ >>> model_id = "google/medasr"
582
+ >>> processor = AutoProcessor.from_pretrained(model_id)
583
+ >>> model = LasrForCTC.from_pretrained(model_id)
584
+
585
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
586
+ >>> ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
587
+
588
+ >>> inputs = processor(ds[0]["audio"]["array"], text=ds[0]["text"])
589
+ >>> predicted_ids = model.generate(**inputs)
590
+ >>> transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)
591
+
592
+ >>> print(transcription)
593
+ ```
594
+ """
595
+ return super().generate(**super_kwargs)
596
+
597
+
598
+ __all__ = [
599
+ "LasrForCTC",
600
+ "LasrEncoder",
601
+ "LasrPreTrainedModel",
602
+ "LasrProcessor",
603
+ "LasrEncoderConfig",
604
+ "LasrCTCConfig",
605
+ "LasrTokenizer",
606
+ ]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/pegasus_x/modeling_pegasus_x.py ADDED
@@ -0,0 +1,1350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022, Google and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """PyTorch PEGASUS-X model."""
15
+
16
+ import math
17
+ from collections.abc import Callable
18
+ from dataclasses import dataclass
19
+
20
+ import numpy as np
21
+ import torch
22
+ from torch import nn
23
+ from torch.nn import CrossEntropyLoss
24
+
25
+ from ...activations import ACT2FN
26
+ from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
27
+ from ...generation import GenerationMixin
28
+ from ...masking_utils import create_bidirectional_mask, create_causal_mask
29
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
30
+ from ...modeling_layers import GradientCheckpointingLayer
31
+ from ...modeling_outputs import (
32
+ BaseModelOutput,
33
+ BaseModelOutputWithPastAndCrossAttentions,
34
+ Seq2SeqLMOutput,
35
+ Seq2SeqModelOutput,
36
+ )
37
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
38
+ from ...processing_utils import Unpack
39
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, is_torchdynamo_compiling, logging
40
+ from ...utils.generic import merge_with_config_defaults
41
+ from ...utils.output_capturing import OutputRecorder, capture_outputs
42
+ from .configuration_pegasus_x import PegasusXConfig
43
+
44
+
45
+ logger = logging.get_logger(__name__)
46
+
47
+
48
+ @dataclass
49
+ class DimensionInfo:
50
+ """Wrapper for dimension info."""
51
+
52
+ batch_size: int # batch size
53
+ seq_len: int # token length
54
+ block_size: int # block size
55
+ num_heads: int # num heads
56
+ hidden_dim: int # hidden dim
57
+ dim_per_head: int # dim per head
58
+ num_blocks: int # num blocks
59
+ global_len: int # global length
60
+ padded_seq_len: int # padded token seq length
61
+
62
+
63
+ # Copied from transformers.models.bart.modeling_bart.shift_tokens_right
64
+ def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
65
+ """
66
+ Shift input ids one token to the right.
67
+ """
68
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
69
+ shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
70
+ shifted_input_ids[:, 0] = decoder_start_token_id
71
+
72
+ if pad_token_id is None:
73
+ raise ValueError("self.model.config.pad_token_id has to be defined.")
74
+ # replace possible -100 values in labels by `pad_token_id`
75
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
76
+
77
+ return shifted_input_ids
78
+
79
+
80
+ # Copied from transformers.models.bart.modeling_bart.BartScaledWordEmbedding with Bart->PegasusX
81
+ class PegasusXScaledWordEmbedding(nn.Embedding):
82
+ """
83
+ This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
84
+ """
85
+
86
+ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: float | None = 1.0):
87
+ super().__init__(num_embeddings, embedding_dim, padding_idx)
88
+ self.embed_scale = embed_scale
89
+
90
+ def forward(self, input_ids: torch.Tensor):
91
+ return super().forward(input_ids) * self.embed_scale
92
+
93
+
94
+ class PegasusXSinusoidalPositionalEmbedding(nn.Module):
95
+ """This module produces sinusoidal positional embeddings of any length."""
96
+
97
+ def __init__(self, embed_dim, max_scale: int = 10000.0):
98
+ super().__init__()
99
+ self.embed_dim = embed_dim
100
+ self.max_scale = max_scale
101
+
102
+ @torch.no_grad()
103
+ def forward(
104
+ self, inputs_embeds: torch.Tensor, past_key_values_length: int = 0, position_ids: torch.Tensor | None = None
105
+ ) -> torch.Tensor:
106
+ """`input_ids_shape` is expected to be [bsz x seqlen]."""
107
+ batch_size, seq_len = inputs_embeds.shape[:2]
108
+ if position_ids is None:
109
+ position_ids = torch.arange(
110
+ past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=inputs_embeds.device
111
+ )[:, None]
112
+
113
+ pe = torch.zeros((seq_len, self.embed_dim), device=inputs_embeds.device, dtype=inputs_embeds.dtype)
114
+ half_d_feature = self.embed_dim // 2
115
+ div_term = torch.exp(
116
+ torch.arange(half_d_feature, device=inputs_embeds.device, dtype=torch.int64).type_as(inputs_embeds)
117
+ * -(np.log(float(self.max_scale)) / (half_d_feature - 1))
118
+ )
119
+ pe[:, :half_d_feature] = torch.sin(position_ids * div_term)
120
+ pe[:, half_d_feature:] = torch.cos(position_ids * div_term)
121
+ return pe[None].expand(batch_size, -1, -1)
122
+
123
+
124
+ # Copied from transformers.models.bert.modeling_bert.eager_attention_forward
125
+ def eager_attention_forward(
126
+ module: nn.Module,
127
+ query: torch.Tensor,
128
+ key: torch.Tensor,
129
+ value: torch.Tensor,
130
+ attention_mask: torch.Tensor | None,
131
+ scaling: float | None = None,
132
+ dropout: float = 0.0,
133
+ **kwargs: Unpack[TransformersKwargs],
134
+ ):
135
+ if scaling is None:
136
+ scaling = query.size(-1) ** -0.5
137
+
138
+ # Take the dot product between "query" and "key" to get the raw attention scores.
139
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
140
+
141
+ if attention_mask is not None:
142
+ attn_weights = attn_weights + attention_mask
143
+
144
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
145
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
146
+
147
+ attn_output = torch.matmul(attn_weights, value)
148
+ attn_output = attn_output.transpose(1, 2).contiguous()
149
+
150
+ return attn_output, attn_weights
151
+
152
+
153
+ # Copied from transformers.models.bart.modeling_bart.BartAttention with Bart->PegasusX
154
+ class PegasusXAttention(nn.Module):
155
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
156
+
157
+ def __init__(
158
+ self,
159
+ embed_dim: int,
160
+ num_heads: int,
161
+ dropout: float = 0.0,
162
+ is_decoder: bool = False,
163
+ bias: bool = True,
164
+ is_causal: bool = False,
165
+ config: PegasusXConfig | None = None,
166
+ layer_idx: int | None = None,
167
+ ):
168
+ super().__init__()
169
+ self.embed_dim = embed_dim
170
+ self.num_heads = num_heads
171
+ self.dropout = dropout
172
+ self.head_dim = embed_dim // num_heads
173
+ self.config = config
174
+
175
+ if (self.head_dim * num_heads) != self.embed_dim:
176
+ raise ValueError(
177
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
178
+ f" and `num_heads`: {num_heads})."
179
+ )
180
+ self.scaling = self.head_dim**-0.5
181
+ self.is_decoder = is_decoder
182
+ self.is_causal = is_causal
183
+ self.layer_idx = layer_idx
184
+ if layer_idx is None and self.is_decoder:
185
+ logger.warning_once(
186
+ f"Instantiating a decoder {self.__class__.__name__} without passing `layer_idx` is not recommended and "
187
+ "will lead to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
188
+ "when creating this class."
189
+ )
190
+
191
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
192
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
193
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
194
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
195
+
196
+ def forward(
197
+ self,
198
+ hidden_states: torch.Tensor,
199
+ key_value_states: torch.Tensor | None = None,
200
+ past_key_values: Cache | None = None,
201
+ attention_mask: torch.Tensor | None = None,
202
+ # TODO: we need a refactor so that the different attention modules can get their specific kwargs
203
+ # ATM, we have mixed things encoder, decoder, and encoder-decoder attn
204
+ **kwargs: Unpack[FlashAttentionKwargs],
205
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
206
+ """Input shape: Batch x Time x Channel"""
207
+
208
+ # if key_value_states are provided this layer is used as a cross-attention layer
209
+ # for the decoder
210
+ is_cross_attention = key_value_states is not None
211
+
212
+ # determine input shapes
213
+ input_shape = hidden_states.shape[:-1]
214
+
215
+ hidden_shape = (*input_shape, -1, self.head_dim)
216
+
217
+ # get query proj
218
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
219
+
220
+ is_updated = False
221
+ if past_key_values is not None:
222
+ if isinstance(past_key_values, EncoderDecoderCache):
223
+ is_updated = past_key_values.is_updated.get(self.layer_idx)
224
+ if is_cross_attention:
225
+ # after the first generated id, we can subsequently re-use all key/value_states from cache
226
+ curr_past_key_values = past_key_values.cross_attention_cache
227
+ else:
228
+ curr_past_key_values = past_key_values.self_attention_cache
229
+ else:
230
+ curr_past_key_values = past_key_values
231
+
232
+ current_states = key_value_states if is_cross_attention else hidden_states
233
+ if is_cross_attention and past_key_values is not None and is_updated:
234
+ # reuse k,v, cross_attentions
235
+ key_states = curr_past_key_values.layers[self.layer_idx].keys
236
+ value_states = curr_past_key_values.layers[self.layer_idx].values
237
+ else:
238
+ key_states = self.k_proj(current_states)
239
+ value_states = self.v_proj(current_states)
240
+ kv_shape = (*current_states.shape[:-1], -1, self.head_dim)
241
+ key_states = key_states.view(kv_shape).transpose(1, 2)
242
+ value_states = value_states.view(kv_shape).transpose(1, 2)
243
+
244
+ if past_key_values is not None:
245
+ key_states, value_states = curr_past_key_values.update(key_states, value_states, self.layer_idx)
246
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
247
+ if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
248
+ past_key_values.is_updated[self.layer_idx] = True
249
+
250
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
251
+ self.config._attn_implementation, eager_attention_forward
252
+ )
253
+
254
+ attn_output, attn_weights = attention_interface(
255
+ self,
256
+ query_states,
257
+ key_states,
258
+ value_states,
259
+ attention_mask,
260
+ dropout=0.0 if not self.training else self.dropout,
261
+ scaling=self.scaling,
262
+ **kwargs,
263
+ )
264
+
265
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
266
+ attn_output = self.out_proj(attn_output)
267
+
268
+ return attn_output, attn_weights
269
+
270
+
271
+ class PegasusXGlobalLocalAttention(nn.Module):
272
+ """Global + Local attention. For use with Encoder only."""
273
+
274
+ def __init__(
275
+ self,
276
+ embed_dim: int,
277
+ num_heads: int,
278
+ block_size: int,
279
+ dropout: float = 0.0,
280
+ is_decoder: bool = False,
281
+ ):
282
+ super().__init__()
283
+ self.embed_dim = embed_dim
284
+ self.num_heads = num_heads
285
+ self.block_size = block_size
286
+ self.dropout = dropout
287
+ self.head_dim = embed_dim // num_heads
288
+
289
+ if (self.head_dim * num_heads) != self.embed_dim:
290
+ raise ValueError(
291
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
292
+ f" and `num_heads`: {num_heads})."
293
+ )
294
+ self.scaling = self.head_dim**-0.5
295
+ self.is_decoder = is_decoder
296
+
297
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=False)
298
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=False)
299
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=False)
300
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=False)
301
+
302
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
303
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
304
+
305
+ def forward(
306
+ self,
307
+ token_hidden_states: torch.Tensor,
308
+ global_hidden_states: torch.Tensor,
309
+ attention_mask: torch.Tensor | None = None,
310
+ **kwargs: Unpack[TransformersKwargs],
311
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
312
+ """Input shape: Batch x Time x Channel"""
313
+ dim = DimensionInfo(
314
+ batch_size=token_hidden_states.shape[0],
315
+ seq_len=token_hidden_states.shape[1],
316
+ block_size=self.block_size,
317
+ num_heads=self.num_heads,
318
+ hidden_dim=token_hidden_states.shape[2],
319
+ dim_per_head=self.head_dim,
320
+ num_blocks=token_hidden_states.shape[1] // self.block_size,
321
+ global_len=global_hidden_states.shape[1],
322
+ padded_seq_len=token_hidden_states.shape[1],
323
+ )
324
+
325
+ # [batch_size, num_heads, padded_seq_len, dim_per_head]
326
+ local_q = self._shape(
327
+ self.q_proj(token_hidden_states) * self.scaling,
328
+ seq_len=dim.padded_seq_len,
329
+ bsz=dim.batch_size,
330
+ )
331
+ local_k = self._shape(
332
+ self.k_proj(token_hidden_states),
333
+ seq_len=dim.padded_seq_len,
334
+ bsz=dim.batch_size,
335
+ )
336
+ local_v = self._shape(
337
+ self.v_proj(token_hidden_states),
338
+ seq_len=dim.padded_seq_len,
339
+ bsz=dim.batch_size,
340
+ )
341
+
342
+ # [batch_size, num_heads, global_len, dim_per_head]
343
+ global_q = self._shape(
344
+ self.q_proj(global_hidden_states) * self.scaling,
345
+ seq_len=dim.global_len,
346
+ bsz=dim.batch_size,
347
+ )
348
+ global_k = self._shape(
349
+ self.k_proj(global_hidden_states),
350
+ seq_len=dim.global_len,
351
+ bsz=dim.batch_size,
352
+ )
353
+ global_v = self._shape(
354
+ self.v_proj(global_hidden_states),
355
+ seq_len=dim.global_len,
356
+ bsz=dim.batch_size,
357
+ )
358
+
359
+ global_attn_output, global_attn_probs = self.compute_global_attention_representations(
360
+ global_q=global_q,
361
+ global_k=global_k,
362
+ global_v=global_v,
363
+ local_k=local_k,
364
+ local_v=local_v,
365
+ mask=attention_mask,
366
+ dim=dim,
367
+ )
368
+ local_attn_output, local_attn_probs = self.compute_local_attention_representations(
369
+ global_k=global_k,
370
+ global_v=global_v,
371
+ local_q=local_q,
372
+ local_k=local_k,
373
+ local_v=local_v,
374
+ mask=attention_mask,
375
+ dim=dim,
376
+ )
377
+
378
+ # [batch_size, global_len, hidden_dim]
379
+ global_attn_output = (
380
+ global_attn_output.transpose(1, 2).contiguous().view(dim.batch_size, dim.global_len, dim.hidden_dim)
381
+ )
382
+ # [batch_size, global_len, hidden_dim]
383
+ global_attn_output = self.out_proj(global_attn_output)
384
+ # [batch_size, num_heads, block_size, num_heads, dim_per_head]
385
+ local_attn_output = local_attn_output.permute(0, 2, 3, 1, 4).contiguous()
386
+ # [batch_size, padded_seq_len, hidden_dim]
387
+ local_attn_output = local_attn_output.view(dim.batch_size, dim.padded_seq_len, dim.hidden_dim)
388
+ # [batch_size, padded_seq_len, hidden_dim]
389
+ local_attn_output = self.out_proj(local_attn_output)
390
+
391
+ attn_probs = {"global": global_attn_probs, "local": local_attn_probs}
392
+
393
+ return local_attn_output, global_attn_output, attn_probs
394
+
395
+ def compute_global_attention_representations(
396
+ self, global_q, global_k, global_v, local_k, local_v, mask, dim: DimensionInfo
397
+ ):
398
+ """Compute attention representations for global tokens.
399
+
400
+ Global tokens will attend to both global tokens as well as all input sequence tokens. Because the input
401
+ sequence tokens are arranged in blocks for local attention, we unblock them and compute attention.
402
+
403
+ Args:
404
+ global_q (`torch.FloatTensor`) of shape [batch_size, num_heads, global_len, dim_per_head]:
405
+ query vectors from global tokens
406
+ global_k (`torch.FloatTensor`) of shape [batch_size, num_heads, global_len, dim_per_head]:
407
+ key vectors from global tokens
408
+ global_v (`torch.FloatTensor`) of shape [batch_size, num_heads, global_len, dim_per_head]:
409
+ value vectors from global tokens
410
+ local_k (`torch.FloatTensor`) of shape [batch_size, num_heads, padded_seq_len, dim_per_head]:
411
+ key vectors from local tokens
412
+ local_v (`torch.FloatTensor`) of shape [batch_size, num_heads, padded_seq_len, dim_per_head]:
413
+ value vectors from local tokens
414
+ mask (`torch.FloatTensor`) of shape [batch_size, padded_seq_len]: attention mask
415
+ dim (DimensionInfo): DimensionInfo wrapper for dimensions
416
+
417
+ Returns:
418
+ output of shape `[batch_sizes, length, features]`. where length will be padded to a multiple of block_size
419
+ """
420
+ # [batch_size, num_heads, global_len+padded_seq_len, dim_per_head]
421
+ global_and_local_k = torch.cat([global_k, local_k], dim=2)
422
+ # [batch_size, num_heads, global_len+padded_seq_len, dim_per_head]
423
+ global_and_local_v = torch.cat([global_v, local_v], dim=2)
424
+
425
+ # [batch_size, global_len+padded_seq_len]
426
+ extended_mask = nn.functional.pad(mask, pad=(dim.global_len, 0), value=0)
427
+
428
+ # [batch_size, num_heads, global_len, global_len+padded_seq_len]
429
+ attn_weights = torch.einsum("BHGF,BHXF->BHGX", global_q, global_and_local_k)
430
+ attn_weights = attn_weights + extended_mask[:, None, None, :]
431
+ attn_probs = nn.functional.softmax(attn_weights, dim=-1)
432
+ attn_probs = nn.functional.dropout(attn_probs, p=self.dropout, training=self.training)
433
+
434
+ # [batch_size, num_heads, global_len, F]
435
+ attn_output = torch.einsum("BHGX,BHXF->BHGF", attn_probs, global_and_local_v)
436
+ return attn_output, attn_probs
437
+
438
+ def compute_local_attention_representations(
439
+ self, global_k, global_v, local_q, local_k, local_v, mask, dim: DimensionInfo
440
+ ):
441
+ """Compute attention representations for local tokens.
442
+
443
+ Local tokens will attend to both global tokens as well as all other tokens within the same local block. Hence,
444
+ we need to tile and concatenate the global tokens to every local block
445
+
446
+ Args:
447
+ global_k (`torch.FloatTensor`) of shape [batch_size, num_heads, global_len, dim_per_head]:
448
+ key vectors from global tokens
449
+ global_v (`torch.FloatTensor`) of shape [batch_size, num_heads, global_len, dim_per_head]:
450
+ value vectors from global tokens
451
+ local_q (`torch.FloatTensor`) of shape [batch_size, num_heads, padded_seq_len, dim_per_head]:
452
+ query vectors from local tokens
453
+ local_k (`torch.FloatTensor`) of shape [batch_size, num_heads, padded_seq_len, dim_per_head]:
454
+ key vectors from local tokens
455
+ local_v (`torch.FloatTensor`) of shape [batch_size, num_heads, padded_seq_len, dim_per_head]:
456
+ value vectors from local tokens
457
+ mask (`torch.FloatTensor`) of shape [batch_size, padded_seq_len]: attention mask
458
+ dim (DimensionInfo): DimensionInfo wrapper for dimensions
459
+
460
+ Returns:
461
+ output of shape `[batch_sizes, length, features]`. where length will be padded to a multiple of block_size
462
+ """
463
+ # [batch_size, num_heads, num_blocks, block_size, dim_per_head]
464
+ blocked_local_q = local_q.view(dim.batch_size, dim.num_heads, dim.num_blocks, dim.block_size, dim.dim_per_head)
465
+ # [batch_size, num_heads, num_blocks, block_size, dim_per_head]
466
+ blocked_local_k = local_k.view(dim.batch_size, dim.num_heads, dim.num_blocks, dim.block_size, dim.dim_per_head)
467
+ # [batch_size, num_heads, num_blocks, block_size, dim_per_head]
468
+ blocked_local_v = local_v.view(dim.batch_size, dim.num_heads, dim.num_blocks, dim.block_size, dim.dim_per_head)
469
+
470
+ # [batch_size, num_blocks, global_len+block_size]
471
+ extended_mask = nn.functional.pad(
472
+ mask.view(dim.batch_size, dim.num_blocks, dim.block_size),
473
+ pad=(dim.global_len, 0),
474
+ value=0,
475
+ )
476
+
477
+ # [batch_size, num_heads, num_blocks, block_size, global_len]
478
+ blocked_local2global = torch.einsum("BHNKF,BHGF->BHNKG", blocked_local_q, global_k)
479
+ # [batch_size, num_heads, num_blocks, block_size, block_size]
480
+ blocked_local2local = torch.einsum("BHNKF,BHNXF->BHNKX", blocked_local_q, blocked_local_k)
481
+
482
+ # [batch_size, num_heads, num_blocks, block_size, global_len+block_size]
483
+ attn_weights = torch.cat([blocked_local2global, blocked_local2local], dim=-1)
484
+ attn_weights = attn_weights + extended_mask[:, None, :, None, :]
485
+ attn_probs = nn.functional.softmax(attn_weights, dim=-1)
486
+ attn_probs = nn.functional.dropout(attn_probs, p=self.dropout, training=self.training)
487
+
488
+ # [batch_size, num_heads, num_blocks, block_size, global_len]
489
+ local2global_attn_probs = attn_probs[:, :, :, :, : dim.global_len]
490
+ # [batch_size, num_heads, num_blocks, block_size, block_size]
491
+ local2local_attn_probs = attn_probs[:, :, :, :, dim.global_len :]
492
+
493
+ # [batch_size, num_heads, num_blocks, block_size, dim_per_head]
494
+ local2global_attn_output = torch.einsum("BHNKG,BHGF->BHNKF", local2global_attn_probs, global_v)
495
+ # [batch_size, num_heads, num_blocks, block_size, dim_per_head]
496
+ local2local_attn_output = torch.einsum("BHNKX,BHNXF->BHNKF", local2local_attn_probs, blocked_local_v)
497
+ # [batch_size, num_heads, num_blocks, block_size, dim_per_head]
498
+ attn_output = local2global_attn_output + local2local_attn_output
499
+ return attn_output, attn_probs
500
+
501
+
502
+ class PegasusXEncoderLayer(GradientCheckpointingLayer):
503
+ def __init__(self, stagger_blocks_this_layer: bool, config: PegasusXConfig):
504
+ super().__init__()
505
+ self.embed_dim = config.d_model
506
+ self.self_attn = PegasusXGlobalLocalAttention(
507
+ embed_dim=self.embed_dim,
508
+ num_heads=config.encoder_attention_heads,
509
+ block_size=config.block_size,
510
+ dropout=config.attention_dropout,
511
+ )
512
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
513
+ self.global_self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
514
+ self.dropout = config.dropout
515
+ self.activation_fn = ACT2FN[config.activation_function]
516
+ self.activation_dropout = config.activation_dropout
517
+ self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
518
+ self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
519
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
520
+ self.stagger_blocks_this_layer = stagger_blocks_this_layer
521
+ self.block_size = config.block_size
522
+
523
+ def forward(
524
+ self,
525
+ hidden_states: torch.Tensor,
526
+ global_hidden_states: torch.Tensor,
527
+ attention_mask: torch.Tensor,
528
+ **kwargs: Unpack[TransformersKwargs],
529
+ ) -> torch.Tensor:
530
+ """
531
+ Args:
532
+ hidden_states (`torch.FloatTensor`): input to the layer of shape *(seq_len, batch, embed_dim)*
533
+ global_hidden_states (`torch.FloatTensor`): global token hidden states
534
+ *(seq_len, num_global_tokens, embed_dim)*
535
+ attention_mask (`torch.FloatTensor`): attention mask of size
536
+ *(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
537
+ output_attentions (`bool`, *optional*):
538
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
539
+ returned tensors for more detail.
540
+ """
541
+ residual = hidden_states
542
+ global_residual = global_hidden_states
543
+
544
+ hidden_states = self.self_attn_layer_norm(hidden_states)
545
+ global_hidden_states = self.global_self_attn_layer_norm(global_hidden_states)
546
+
547
+ if self.stagger_blocks_this_layer:
548
+ # Pad the blocks to simulate staggering
549
+ hidden_states, attention_mask = self.pad_local_tokens(
550
+ hidden_states=hidden_states, attention_mask=attention_mask, block_size=self.block_size
551
+ )
552
+
553
+ hidden_states, global_hidden_states, _ = self.self_attn(
554
+ token_hidden_states=hidden_states,
555
+ global_hidden_states=global_hidden_states,
556
+ attention_mask=attention_mask,
557
+ **kwargs,
558
+ )
559
+
560
+ if self.stagger_blocks_this_layer:
561
+ # Undo the padding
562
+ hidden_states = self.unpad_local_tokens(padded_hidden_states=hidden_states, block_size=self.block_size)
563
+
564
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
565
+ hidden_states = residual + hidden_states
566
+
567
+ global_hidden_states = nn.functional.dropout(global_hidden_states, p=self.dropout, training=self.training)
568
+ global_hidden_states = global_residual + global_hidden_states
569
+
570
+ residual = hidden_states
571
+ hidden_states = self.final_layer_norm(hidden_states)
572
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
573
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
574
+ hidden_states = self.fc2(hidden_states)
575
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
576
+ hidden_states = residual + hidden_states
577
+
578
+ global_residual = global_hidden_states
579
+ global_hidden_states = self.final_layer_norm(global_hidden_states)
580
+ global_hidden_states = self.activation_fn(self.fc1(global_hidden_states))
581
+ global_hidden_states = nn.functional.dropout(
582
+ global_hidden_states, p=self.activation_dropout, training=self.training
583
+ )
584
+ global_hidden_states = self.fc2(global_hidden_states)
585
+ global_hidden_states = nn.functional.dropout(global_hidden_states, p=self.dropout, training=self.training)
586
+ global_hidden_states = global_residual + global_hidden_states
587
+
588
+ return hidden_states, global_hidden_states
589
+
590
+ @classmethod
591
+ def pad_local_tokens(cls, hidden_states, attention_mask, block_size):
592
+ # hidden_states: [batch_size, seq_len, hidden_dim]
593
+ pad_size = block_size // 2
594
+ mask_min_value = torch.finfo(hidden_states.dtype).min
595
+ padded_hidden_states = torch.nn.functional.pad(
596
+ hidden_states,
597
+ pad=(0, 0, pad_size, pad_size),
598
+ )
599
+ padded_mask = torch.nn.functional.pad(
600
+ attention_mask,
601
+ pad=(pad_size, pad_size),
602
+ value=mask_min_value,
603
+ )
604
+ return padded_hidden_states, padded_mask
605
+
606
+ @classmethod
607
+ def unpad_local_tokens(cls, padded_hidden_states, block_size):
608
+ # padded_hidden_states: [batch_size, padded seq_len, hidden_dim]
609
+ pad_size = block_size // 2
610
+ return padded_hidden_states[:, pad_size:-pad_size, :]
611
+
612
+
613
+ class PegasusXDecoderLayer(GradientCheckpointingLayer):
614
+ def __init__(self, config: PegasusXConfig, layer_idx: int | None = None):
615
+ super().__init__()
616
+ self.embed_dim = config.d_model
617
+
618
+ self.self_attn = PegasusXAttention(
619
+ embed_dim=self.embed_dim,
620
+ num_heads=config.decoder_attention_heads,
621
+ dropout=config.attention_dropout,
622
+ is_decoder=True,
623
+ bias=False,
624
+ config=config,
625
+ layer_idx=layer_idx,
626
+ )
627
+ self.dropout = config.dropout
628
+ self.activation_fn = ACT2FN[config.activation_function]
629
+ self.activation_dropout = config.activation_dropout
630
+
631
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
632
+ self.encoder_attn = PegasusXAttention(
633
+ self.embed_dim,
634
+ config.decoder_attention_heads,
635
+ dropout=config.attention_dropout,
636
+ is_decoder=True,
637
+ bias=False,
638
+ config=config,
639
+ layer_idx=layer_idx,
640
+ )
641
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
642
+ self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
643
+ self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
644
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
645
+
646
+ def forward(
647
+ self,
648
+ hidden_states: torch.Tensor,
649
+ attention_mask: torch.Tensor | None = None,
650
+ encoder_hidden_states: torch.Tensor | None = None,
651
+ encoder_attention_mask: torch.Tensor | None = None,
652
+ past_key_values: Cache | None = None,
653
+ use_cache: bool | None = True,
654
+ **kwargs,
655
+ ) -> torch.Tensor:
656
+ """
657
+ Args:
658
+ hidden_states (`torch.FloatTensor`): input to the layer of shape *(seq_len, batch, embed_dim)*
659
+ attention_mask (`torch.FloatTensor`): attention mask of size
660
+ *(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
661
+ encoder_hidden_states (`torch.FloatTensor`):
662
+ cross attention input to the layer of shape *(seq_len, batch, embed_dim)*
663
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
664
+ *(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
665
+ past_key_values (`Cache`): cached past key and value projection states
666
+ use_cache: Whether to us KV cache for decoding
667
+ """
668
+ residual = hidden_states
669
+ hidden_states = self.self_attn_layer_norm(hidden_states)
670
+
671
+ # Self Attention
672
+ hidden_states, _ = self.self_attn(
673
+ hidden_states=hidden_states,
674
+ past_key_values=past_key_values,
675
+ attention_mask=attention_mask,
676
+ **kwargs,
677
+ )
678
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
679
+ hidden_states = residual + hidden_states
680
+
681
+ # Cross-Attention Block
682
+ if encoder_hidden_states is not None:
683
+ residual = hidden_states
684
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
685
+
686
+ hidden_states, _ = self.encoder_attn(
687
+ hidden_states=hidden_states,
688
+ key_value_states=encoder_hidden_states,
689
+ attention_mask=encoder_attention_mask,
690
+ past_key_values=past_key_values,
691
+ **kwargs,
692
+ )
693
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
694
+ hidden_states = residual + hidden_states
695
+
696
+ # Fully Connected
697
+ residual = hidden_states
698
+ hidden_states = self.final_layer_norm(hidden_states)
699
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
700
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
701
+ hidden_states = self.fc2(hidden_states)
702
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
703
+ hidden_states = residual + hidden_states
704
+
705
+ return hidden_states
706
+
707
+
708
+ @auto_docstring
709
+ class PegasusXPreTrainedModel(PreTrainedModel):
710
+ config: PegasusXConfig
711
+ base_model_prefix = "model"
712
+ supports_gradient_checkpointing = True
713
+ _no_split_modules = [r"PegasusXEncoderLayer", r"PegasusXDecoderLayer"]
714
+ _supports_flash_attn = True
715
+ # Flaky logits
716
+ _supports_sdpa = False
717
+ _supports_flex_attn = True
718
+ _can_compile_fullgraph = True
719
+
720
+
721
+ class PegasusXEncoder(PegasusXPreTrainedModel):
722
+ _can_record_outputs = {"attentions": OutputRecorder(PegasusXGlobalLocalAttention, index=2)}
723
+
724
+ """
725
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
726
+ [`PegasusXEncoderLayer`].
727
+
728
+ Args:
729
+ config: PegasusXConfig
730
+ embed_tokens (nn.Embedding): output embedding
731
+ """
732
+
733
+ def __init__(self, config: PegasusXConfig):
734
+ super().__init__(config)
735
+
736
+ self.dropout = config.dropout
737
+ self.layerdrop = config.encoder_layerdrop
738
+
739
+ embed_dim = config.d_model
740
+ padding_idx = config.pad_token_id
741
+ self.max_source_positions = config.max_position_embeddings
742
+ embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
743
+
744
+ self.embed_tokens = PegasusXScaledWordEmbedding(
745
+ config.vocab_size, embed_dim, padding_idx, embed_scale=embed_scale
746
+ )
747
+
748
+ self.embed_global = nn.Embedding(config.num_global_tokens, embed_dim)
749
+ self.embed_positions = PegasusXSinusoidalPositionalEmbedding(embed_dim)
750
+ self.layers = nn.ModuleList(
751
+ [
752
+ PegasusXEncoderLayer(
753
+ stagger_blocks_this_layer=i % 2 == 1 and config.stagger_local_blocks, config=config
754
+ )
755
+ for i in range(config.encoder_layers)
756
+ ]
757
+ )
758
+ self.layer_norm = nn.LayerNorm(config.d_model)
759
+
760
+ self.gradient_checkpointing = False
761
+ # Initialize weights and apply final processing
762
+ self.post_init()
763
+
764
+ def resize_position_embeddings(self, new_num_position_embeddings: int):
765
+ """
766
+ Resizes position embeddings matrix of the model if `new_num_position_embeddings !=
767
+ config.max_position_embeddings`.
768
+
769
+ Arguments:
770
+ new_num_position_embeddings (`int`):
771
+ The number of new position embeddings. If position embeddings are learned, increasing the size will add
772
+ newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If
773
+ position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will
774
+ add correct vectors at the end following the position encoding algorithm, whereas reducing the size
775
+ will remove vectors from the end.
776
+ """
777
+ logger.info(f"Setting `config.max_position_embeddings={new_num_position_embeddings}`...")
778
+ self.config.max_position_embeddings = new_num_position_embeddings
779
+
780
+ self.embed_positions = PegasusXSinusoidalPositionalEmbedding(self.config.d_model)
781
+ self.embed_positions.to(self.device)
782
+
783
+ def get_position_embeddings(self) -> nn.Embedding:
784
+ """
785
+ Returns the position embeddings matrix
786
+ """
787
+ return self.embed_positions
788
+
789
+ @merge_with_config_defaults
790
+ @capture_outputs
791
+ def forward(
792
+ self,
793
+ input_ids=None,
794
+ attention_mask=None,
795
+ inputs_embeds=None,
796
+ output_hidden_states=None,
797
+ **kwargs: Unpack[TransformersKwargs],
798
+ ):
799
+ r"""
800
+ Args:
801
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
802
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
803
+ provide it.
804
+
805
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
806
+ [`PreTrainedTokenizer.__call__`] for details.
807
+
808
+ [What are input IDs?](../glossary#input-ids)
809
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
810
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
811
+
812
+ - 1 for tokens that are **not masked**,
813
+ - 0 for tokens that are **masked**.
814
+
815
+ [What are attention masks?](../glossary#attention-mask)
816
+
817
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
818
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
819
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
820
+ than the model's internal embedding lookup matrix.
821
+ output_attentions (`bool`, *optional*):
822
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
823
+ returned tensors for more detail.
824
+ output_hidden_states (`bool`, *optional*):
825
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
826
+ for more detail.
827
+ """
828
+ # We need to treat this special because it only adds the last global state which is unique
829
+ output_hidden_states = (
830
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
831
+ )
832
+
833
+ if (input_ids is None) ^ (inputs_embeds is not None):
834
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
835
+
836
+ if inputs_embeds is None:
837
+ inputs_embeds = self.embed_tokens(input_ids)
838
+
839
+ embed_pos = self.embed_positions(inputs_embeds)
840
+
841
+ hidden_states = inputs_embeds + embed_pos
842
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
843
+
844
+ batch_size, seq_len, _ = hidden_states.shape
845
+
846
+ # Setup mask
847
+ if attention_mask is None:
848
+ attention_mask = torch.ones(
849
+ *inputs_embeds.shape[:-1], dtype=inputs_embeds.dtype, device=inputs_embeds.device
850
+ )
851
+ attention_mask = attention_mask.to(dtype=hidden_states.dtype)
852
+ mask_min_value = torch.finfo(hidden_states.dtype).min
853
+ inverted_mask = 1.0 - attention_mask
854
+ attention_mask = inverted_mask.masked_fill(
855
+ inverted_mask.to(torch.bool),
856
+ mask_min_value,
857
+ )
858
+
859
+ # padding to block_size
860
+ if seq_len % self.config.block_size != 0:
861
+ pad_len = self.config.block_size - seq_len % self.config.block_size
862
+ hidden_states = nn.functional.pad(hidden_states, pad=(0, 0, 0, pad_len), value=0)
863
+ attention_mask = nn.functional.pad(attention_mask, pad=(0, pad_len), value=mask_min_value)
864
+
865
+ # Global tokens
866
+ global_hidden_states = self.embed_global(
867
+ torch.arange(self.config.num_global_tokens, device=hidden_states.device)[None].expand(batch_size, -1)
868
+ )
869
+
870
+ encoder_states = () if output_hidden_states else None
871
+ for encoder_layer in self.layers:
872
+ if output_hidden_states:
873
+ encoder_states = encoder_states + (hidden_states,)
874
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
875
+ to_drop = False
876
+ if self.training:
877
+ dropout_probability = torch.rand([])
878
+ if dropout_probability < self.layerdrop: # skip the layer
879
+ to_drop = True
880
+
881
+ if to_drop:
882
+ hidden_states, global_hidden_states = (None, None)
883
+ else:
884
+ hidden_states, global_hidden_states = encoder_layer(
885
+ hidden_states,
886
+ global_hidden_states,
887
+ attention_mask,
888
+ **kwargs,
889
+ )
890
+
891
+ # Undo padding-to-block-size
892
+ hidden_states = hidden_states[:, :seq_len]
893
+
894
+ hidden_states = self.layer_norm(hidden_states)
895
+
896
+ if output_hidden_states:
897
+ encoder_states = encoder_states + ((hidden_states, global_hidden_states),)
898
+
899
+ return BaseModelOutput(last_hidden_state=hidden_states, hidden_states=encoder_states)
900
+
901
+
902
+ class PegasusXDecoder(PegasusXPreTrainedModel):
903
+ """
904
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`PegasusDecoderLayer`]
905
+
906
+ Args:
907
+ config: PegasusXConfig
908
+ embed_tokens (nn.Embedding): output embedding
909
+ """
910
+
911
+ _can_record_outputs = {
912
+ "hidden_states": PegasusXDecoderLayer,
913
+ "attentions": OutputRecorder(PegasusXAttention, index=1, layer_name="self_attn"),
914
+ "cross_attentions": OutputRecorder(PegasusXAttention, index=1, layer_name="encoder_attn"),
915
+ }
916
+
917
+ def __init__(self, config: PegasusXConfig):
918
+ super().__init__(config)
919
+ self.dropout = config.dropout
920
+ self.layerdrop = config.decoder_layerdrop
921
+ self.max_target_positions = config.max_position_embeddings
922
+ embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
923
+ padding_idx = config.pad_token_id
924
+
925
+ self.embed_tokens = PegasusXScaledWordEmbedding(
926
+ config.vocab_size, config.d_model, padding_idx=padding_idx, embed_scale=embed_scale
927
+ )
928
+
929
+ self.embed_positions = PegasusXSinusoidalPositionalEmbedding(config.d_model)
930
+ self.layers = nn.ModuleList([PegasusXDecoderLayer(config, layer_idx=i) for i in range(config.decoder_layers)])
931
+ self.layer_norm = nn.LayerNorm(config.d_model)
932
+
933
+ self.gradient_checkpointing = False
934
+ # Initialize weights and apply final processing
935
+ self.post_init()
936
+
937
+ @capture_outputs
938
+ @merge_with_config_defaults
939
+ def forward(
940
+ self,
941
+ input_ids=None,
942
+ attention_mask=None,
943
+ encoder_hidden_states=None,
944
+ encoder_attention_mask=None,
945
+ past_key_values=None,
946
+ inputs_embeds=None,
947
+ use_cache=None,
948
+ **kwargs: Unpack[TransformersKwargs],
949
+ ):
950
+ r"""
951
+ Args:
952
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
953
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
954
+ provide it.
955
+
956
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
957
+ [`PreTrainedTokenizer.__call__`] for details.
958
+
959
+ [What are input IDs?](../glossary#input-ids)
960
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
961
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
962
+
963
+ - 1 for tokens that are **not masked**,
964
+ - 0 for tokens that are **masked**.
965
+
966
+ [What are attention masks?](../glossary#attention-mask)
967
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
968
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
969
+ of the decoder.
970
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
971
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
972
+ selected in `[0, 1]`:
973
+
974
+ - 1 for tokens that are **not masked**,
975
+ - 0 for tokens that are **masked**.
976
+
977
+ [What are attention masks?](../glossary#attention-mask)
978
+
979
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
980
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
981
+
982
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
983
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
984
+
985
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
986
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
987
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
988
+ inputs_embeds (`torch.FloatTensor` of
989
+ shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing
990
+ `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more
991
+ control over how to convert `input_ids` indices into associated vectors than the model's internal
992
+ embedding lookup matrix.
993
+ output_attentions (`bool`, *optional*):
994
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
995
+ returned tensors for more detail.
996
+ output_hidden_states (`bool`, *optional*):
997
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
998
+ for more detail.
999
+ return_dict (`bool`, *optional*):
1000
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1001
+ """
1002
+ if (input_ids is None) ^ (inputs_embeds is not None):
1003
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
1004
+
1005
+ if inputs_embeds is None:
1006
+ inputs_embeds = self.embed_tokens(input_ids)
1007
+
1008
+ # initialize `past_key_values`
1009
+ if use_cache and past_key_values is None:
1010
+ past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
1011
+
1012
+ batch_size, seq_length = inputs_embeds.size()[:-1]
1013
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
1014
+
1015
+ if attention_mask is None and not is_torchdynamo_compiling():
1016
+ # required mask seq length can be calculated via length of past cache
1017
+ mask_seq_length = past_key_values_length + seq_length
1018
+ attention_mask = torch.ones(batch_size, mask_seq_length, device=inputs_embeds.device)
1019
+
1020
+ self_attn_cache = (
1021
+ past_key_values.self_attention_cache
1022
+ if isinstance(past_key_values, EncoderDecoderCache)
1023
+ else past_key_values
1024
+ )
1025
+
1026
+ causal_mask = create_causal_mask(
1027
+ config=self.config,
1028
+ inputs_embeds=inputs_embeds,
1029
+ attention_mask=attention_mask,
1030
+ past_key_values=self_attn_cache,
1031
+ )
1032
+ encoder_attention_mask = create_bidirectional_mask(
1033
+ config=self.config,
1034
+ inputs_embeds=inputs_embeds,
1035
+ attention_mask=encoder_attention_mask,
1036
+ encoder_hidden_states=encoder_hidden_states,
1037
+ )
1038
+
1039
+ # embed positions
1040
+ position_ids = torch.arange(seq_length, device=inputs_embeds.device) + past_key_values_length
1041
+ position_ids = position_ids.unsqueeze(1)
1042
+ position_ids = self.embed_positions(inputs_embeds, past_key_values_length, position_ids)
1043
+ position_ids = position_ids.to(inputs_embeds.device)
1044
+ hidden_states = inputs_embeds + position_ids
1045
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
1046
+
1047
+ # decoder layers
1048
+ for idx, decoder_layer in enumerate(self.layers):
1049
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
1050
+ if self.training:
1051
+ dropout_probability = torch.rand([])
1052
+ if dropout_probability < self.layerdrop:
1053
+ continue
1054
+
1055
+ hidden_states = decoder_layer(
1056
+ hidden_states,
1057
+ causal_mask,
1058
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
1059
+ encoder_attention_mask=encoder_attention_mask,
1060
+ past_key_values=past_key_values,
1061
+ use_cache=use_cache,
1062
+ **kwargs,
1063
+ )
1064
+
1065
+ hidden_states = self.layer_norm(hidden_states)
1066
+
1067
+ return BaseModelOutputWithPastAndCrossAttentions(
1068
+ last_hidden_state=hidden_states,
1069
+ past_key_values=past_key_values,
1070
+ )
1071
+
1072
+
1073
+ @auto_docstring
1074
+ class PegasusXModel(PegasusXPreTrainedModel):
1075
+ _tied_weights_keys = {
1076
+ "encoder.embed_tokens.weight": "shared.weight",
1077
+ "decoder.embed_tokens.weight": "shared.weight",
1078
+ }
1079
+
1080
+ def __init__(self, config: PegasusXConfig):
1081
+ super().__init__(config)
1082
+
1083
+ vocab_size = config.vocab_size
1084
+ embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
1085
+ padding_idx = config.pad_token_id
1086
+ self.shared = PegasusXScaledWordEmbedding(
1087
+ vocab_size, config.d_model, padding_idx=padding_idx, embed_scale=embed_scale
1088
+ )
1089
+
1090
+ self.encoder = PegasusXEncoder(config)
1091
+ self.decoder = PegasusXDecoder(config)
1092
+
1093
+ # Initialize weights and apply final processing
1094
+ self.post_init()
1095
+
1096
+ def get_input_embeddings(self):
1097
+ return self.shared
1098
+
1099
+ def set_input_embeddings(self, value):
1100
+ self.shared = value
1101
+ self.encoder.embed_tokens = self.shared
1102
+ self.decoder.embed_tokens = self.shared
1103
+
1104
+ def resize_position_embeddings(self, new_num_position_embeddings: int):
1105
+ """
1106
+ Resizes position embeddings matrix of the model if `new_num_position_embeddings !=
1107
+ config.max_position_embeddings`.
1108
+
1109
+ Arguments:
1110
+ new_num_position_embeddings (`int`):
1111
+ The number of new position embeddings. If position embeddings are learned, increasing the size will add
1112
+ newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If
1113
+ position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will
1114
+ add correct vectors at the end following the position encoding algorithm, whereas reducing the size
1115
+ will remove vectors from the end.
1116
+ """
1117
+ self.config.max_position_embeddings = new_num_position_embeddings
1118
+ self.encoder.resize_position_embeddings(new_num_position_embeddings)
1119
+ self.decoder.resize_position_embeddings(new_num_position_embeddings)
1120
+
1121
+ def get_position_embeddings(self) -> tuple[nn.Embedding]:
1122
+ """
1123
+ Returns the position embeddings matrix
1124
+ """
1125
+ return (self.encoder.get_position_embeddings(), self.decoder.get_position_embeddings())
1126
+
1127
+ @can_return_tuple
1128
+ @auto_docstring
1129
+ def forward(
1130
+ self,
1131
+ input_ids: torch.Tensor | None = None,
1132
+ attention_mask: torch.Tensor | None = None,
1133
+ decoder_input_ids: torch.Tensor | None = None,
1134
+ decoder_attention_mask: torch.Tensor | None = None,
1135
+ encoder_outputs: tuple[torch.FloatTensor] | None = None,
1136
+ past_key_values: Cache | None = None,
1137
+ inputs_embeds: torch.Tensor | None = None,
1138
+ decoder_inputs_embeds: torch.Tensor | None = None,
1139
+ use_cache: bool | None = None,
1140
+ **kwargs: Unpack[TransformersKwargs],
1141
+ ) -> tuple | Seq2SeqModelOutput:
1142
+ r"""
1143
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1144
+ Indices of decoder input sequence tokens in the vocabulary.
1145
+
1146
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1147
+ [`PreTrainedTokenizer.__call__`] for details.
1148
+
1149
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
1150
+
1151
+ PEGASUS-X uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If
1152
+ `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
1153
+ `past_key_values`).
1154
+ decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1155
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
1156
+ be used by default.
1157
+
1158
+ Example:
1159
+
1160
+ ```python
1161
+ >>> from transformers import AutoTokenizer, PegasusModel
1162
+
1163
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/pegasus-x-large")
1164
+ >>> model = PegasusModel.from_pretrained("google/pegasus-x-large")
1165
+
1166
+ >>> inputs = tokenizer("Studies have been shown that owning a dog is good for you", return_tensors="pt")
1167
+ >>> decoder_inputs = tokenizer("Studies show that", return_tensors="pt")
1168
+ >>> outputs = model(input_ids=inputs.input_ids, decoder_input_ids=decoder_inputs.input_ids)
1169
+
1170
+ >>> last_hidden_states = outputs.last_hidden_state
1171
+ >>> list(last_hidden_states.shape)
1172
+ [1, 4, 1024]
1173
+ ```"""
1174
+
1175
+ if encoder_outputs is None:
1176
+ encoder_outputs: BaseModelOutput = self.encoder(
1177
+ input_ids=input_ids,
1178
+ attention_mask=attention_mask,
1179
+ inputs_embeds=inputs_embeds,
1180
+ **kwargs,
1181
+ )
1182
+ elif not isinstance(encoder_outputs, BaseModelOutput):
1183
+ encoder_outputs = BaseModelOutput(
1184
+ last_hidden_state=encoder_outputs[0],
1185
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1186
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1187
+ )
1188
+
1189
+ decoder_outputs: BaseModelOutputWithPastAndCrossAttentions = self.decoder(
1190
+ input_ids=decoder_input_ids,
1191
+ attention_mask=decoder_attention_mask,
1192
+ encoder_hidden_states=encoder_outputs[0],
1193
+ encoder_attention_mask=attention_mask,
1194
+ past_key_values=past_key_values,
1195
+ inputs_embeds=decoder_inputs_embeds,
1196
+ use_cache=use_cache,
1197
+ **kwargs,
1198
+ )
1199
+
1200
+ return Seq2SeqModelOutput(
1201
+ last_hidden_state=decoder_outputs.last_hidden_state,
1202
+ past_key_values=decoder_outputs.past_key_values,
1203
+ decoder_hidden_states=decoder_outputs.hidden_states,
1204
+ decoder_attentions=decoder_outputs.attentions,
1205
+ cross_attentions=decoder_outputs.cross_attentions,
1206
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1207
+ encoder_hidden_states=encoder_outputs.hidden_states,
1208
+ encoder_attentions=encoder_outputs.attentions,
1209
+ )
1210
+
1211
+
1212
+ @auto_docstring(
1213
+ custom_intro="""
1214
+ The PEGASUS-X for conditional generation (e.g. summarization).
1215
+ """
1216
+ )
1217
+ class PegasusXForConditionalGeneration(PegasusXPreTrainedModel, GenerationMixin):
1218
+ base_model_prefix = "model"
1219
+ _tied_weights_keys = {
1220
+ "lm_head.weight": "model.shared.weight",
1221
+ }
1222
+
1223
+ def __init__(self, config: PegasusXConfig):
1224
+ super().__init__(config)
1225
+ self.model = PegasusXModel(config)
1226
+ self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)
1227
+
1228
+ # Initialize weights and apply final processing
1229
+ self.post_init()
1230
+
1231
+ def resize_position_embeddings(self, new_num_position_embeddings: int):
1232
+ """
1233
+ Resizes position embeddings matrix of the model if `new_num_position_embeddings !=
1234
+ config.max_position_embeddings`.
1235
+
1236
+ Arguments:
1237
+ new_num_position_embeddings (`int`):
1238
+ The number of new position embeddings. If position embeddings are learned, increasing the size will add
1239
+ newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If
1240
+ position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will
1241
+ add correct vectors at the end following the position encoding algorithm, whereas reducing the size
1242
+ will remove vectors from the end.
1243
+ """
1244
+ self.config.max_position_embeddings = new_num_position_embeddings
1245
+ self.model.encoder.resize_position_embeddings(new_num_position_embeddings)
1246
+ self.model.decoder.resize_position_embeddings(new_num_position_embeddings)
1247
+
1248
+ def get_position_embeddings(self) -> tuple[nn.Embedding]:
1249
+ """
1250
+ Returns the position embeddings matrix
1251
+ """
1252
+ return (self.model.encoder.get_position_embeddings(), self.model.decoder.get_position_embeddings())
1253
+
1254
+ @can_return_tuple
1255
+ @auto_docstring
1256
+ def forward(
1257
+ self,
1258
+ input_ids: torch.Tensor | None = None,
1259
+ attention_mask: torch.Tensor | None = None,
1260
+ decoder_input_ids: torch.Tensor | None = None,
1261
+ decoder_attention_mask: torch.Tensor | None = None,
1262
+ encoder_outputs: tuple[torch.FloatTensor] | None = None,
1263
+ past_key_values: Cache | None = None,
1264
+ inputs_embeds: torch.Tensor | None = None,
1265
+ decoder_inputs_embeds: torch.Tensor | None = None,
1266
+ labels: torch.Tensor | None = None,
1267
+ use_cache: bool | None = None,
1268
+ **kwargs: Unpack[TransformersKwargs],
1269
+ ) -> tuple | Seq2SeqLMOutput:
1270
+ r"""
1271
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1272
+ Indices of decoder input sequence tokens in the vocabulary.
1273
+
1274
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1275
+ [`PreTrainedTokenizer.__call__`] for details.
1276
+
1277
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
1278
+
1279
+ PEGASUS-X uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If
1280
+ `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
1281
+ `past_key_values`).
1282
+ decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1283
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
1284
+ be used by default.
1285
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1286
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1287
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1288
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1289
+ """
1290
+ if labels is not None:
1291
+ if use_cache:
1292
+ logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
1293
+ use_cache = False
1294
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
1295
+ decoder_input_ids = shift_tokens_right(
1296
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
1297
+ )
1298
+
1299
+ outputs: Seq2SeqModelOutput = self.model(
1300
+ input_ids,
1301
+ attention_mask=attention_mask,
1302
+ decoder_input_ids=decoder_input_ids,
1303
+ encoder_outputs=encoder_outputs,
1304
+ decoder_attention_mask=decoder_attention_mask,
1305
+ past_key_values=past_key_values,
1306
+ inputs_embeds=inputs_embeds,
1307
+ decoder_inputs_embeds=decoder_inputs_embeds,
1308
+ use_cache=use_cache,
1309
+ **kwargs,
1310
+ )
1311
+ lm_logits = self.lm_head(outputs.last_hidden_state)
1312
+
1313
+ masked_lm_loss = None
1314
+ if labels is not None:
1315
+ loss_fct = CrossEntropyLoss()
1316
+ masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))
1317
+
1318
+ return Seq2SeqLMOutput(
1319
+ loss=masked_lm_loss,
1320
+ logits=lm_logits,
1321
+ past_key_values=outputs.past_key_values,
1322
+ decoder_hidden_states=outputs.decoder_hidden_states,
1323
+ decoder_attentions=outputs.decoder_attentions,
1324
+ cross_attentions=outputs.cross_attentions,
1325
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1326
+ encoder_hidden_states=outputs.encoder_hidden_states,
1327
+ encoder_attentions=outputs.encoder_attentions,
1328
+ )
1329
+
1330
+ def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
1331
+ return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id)
1332
+
1333
+
1334
+ # Copied from transformers.models.bart.modeling_bart.BartDecoderWrapper with Bart->PegasusX
1335
+ class PegasusXDecoderWrapper(PegasusXPreTrainedModel):
1336
+ """
1337
+ This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
1338
+ used in combination with the [`EncoderDecoderModel`] framework.
1339
+ """
1340
+
1341
+ def __init__(self, config):
1342
+ super().__init__(config)
1343
+ self.decoder = PegasusXDecoder(config)
1344
+ self.post_init()
1345
+
1346
+ def forward(self, *args, **kwargs):
1347
+ return self.decoder(*args, **kwargs)
1348
+
1349
+
1350
+ __all__ = ["PegasusXForConditionalGeneration", "PegasusXModel", "PegasusXPreTrainedModel"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_012000.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4d8fbfdddd55eb0202266fed8fa62f27ba1be1355fa21d50e582e02745238d46
3
+ size 515519058
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_018000.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:df64692a35671a273e2a18044da2dbb181073849914f93ff5d608b2afab0e8f5
3
+ size 515519058
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_019000.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c42b2084717aad80a3d6b8d919bcd78d15954a1f7819c06f5edcca250ab1d746
3
+ size 515519058
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_027000.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9840ef37d2113a78aa855f7ea46ae6747c877aa2c271d8fb78ad55977a755a3b
3
+ size 515519058
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_081000.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fc30d1544fab24a8c3a39a3bae9ec62b51a5d1e3d48d8eb888ef01b103ec7516
3
+ size 515519058
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_097000.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2896722b434cdac0cfaaf7ce8b556cbe80d7565678b7c0be6a7bd24279620c2e
3
+ size 515519058
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_177000.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d4b2045e0ab38f3386af111184e1560308897f191f024942d951cf469389a0b8
3
+ size 515519058
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_181000.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b29bc92a7587ed356f6da524ecf52de0c272ed492c9902ebeeaf097d72372c26
3
+ size 515519058
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_8gpu_50ep_lr3e4_elfopt_t5embed_unfixed_stateprobadd_selfcond_ce_fast_20260531_230026/step_216000.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:deec65499cc1560feb3c8c69bc59e1c7fc1e4dfe074e52a36572e075227ad424
3
+ size 515519058