AdithyaSK HF Staff commited on
Commit
3a40184
·
verified ·
1 Parent(s): b98a72e

Stage Harbor release files 37501-38000

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2/modular_qwen2.py +212 -0
  2. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2/tokenization_qwen2.py +342 -0
  3. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2/tokenization_qwen2_fast.py +137 -0
  4. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_5_omni/__init__.py +28 -0
  5. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_5_omni/configuration_qwen2_5_omni.py +1091 -0
  6. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py +0 -0
  7. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_5_omni/modular_qwen2_5_omni.py +0 -0
  8. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_5_omni/processing_qwen2_5_omni.py +371 -0
  9. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_5_vl/__init__.py +28 -0
  10. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_5_vl/configuration_qwen2_5_vl.py +336 -0
  11. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py +1749 -0
  12. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_5_vl/modular_qwen2_5_vl.py +1034 -0
  13. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_5_vl/processing_qwen2_5_vl.py +292 -0
  14. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_audio/__init__.py +28 -0
  15. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_audio/configuration_qwen2_audio.py +203 -0
  16. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_audio/modeling_qwen2_audio.py +897 -0
  17. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_audio/processing_qwen2_audio.py +254 -0
  18. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_moe/__init__.py +27 -0
  19. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_moe/configuration_qwen2_moe.py +244 -0
  20. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_moe/modeling_qwen2_moe.py +1187 -0
  21. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_vl/__init__.py +30 -0
  22. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_vl/configuration_qwen2_vl.py +325 -0
  23. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_vl/image_processing_qwen2_vl.py +518 -0
  24. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_vl/image_processing_qwen2_vl_fast.py +315 -0
  25. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_vl/modeling_qwen2_vl.py +1635 -0
  26. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_vl/processing_qwen2_vl.py +275 -0
  27. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_vl/video_processing_qwen2_vl.py +360 -0
  28. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen3/__init__.py +27 -0
  29. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen3/configuration_qwen3.py +226 -0
  30. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen3/modeling_qwen3.py +534 -0
  31. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen3/modular_qwen3.py +174 -0
  32. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen3_moe/__init__.py +27 -0
  33. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen3_moe/configuration_qwen3_moe.py +240 -0
  34. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen3_moe/modeling_qwen3_moe.py +718 -0
  35. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen3_moe/modular_qwen3_moe.py +296 -0
  36. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/rag/__init__.py +30 -0
  37. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/rag/configuration_rag.py +186 -0
  38. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/rag/modeling_rag.py +1669 -0
  39. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/rag/modeling_tf_rag.py +1776 -0
  40. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/rag/retrieval_rag.py +682 -0
  41. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/rag/tokenization_rag.py +124 -0
  42. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/recurrent_gemma/__init__.py +27 -0
  43. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/recurrent_gemma/configuration_recurrent_gemma.py +161 -0
  44. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/recurrent_gemma/convert_recurrent_gemma_to_hf.py +222 -0
  45. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/recurrent_gemma/modeling_recurrent_gemma.py +791 -0
  46. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/reformer/__init__.py +29 -0
  47. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/reformer/configuration_reformer.py +235 -0
  48. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/reformer/convert_reformer_trax_checkpoint_to_pytorch.py +226 -0
  49. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/reformer/modeling_reformer.py +0 -0
  50. tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/reformer/tokenization_reformer.py +176 -0
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2/modular_qwen2.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, Optional
2
+
3
+ import torch
4
+ import torch.utils.checkpoint
5
+ from torch import nn
6
+
7
+ from ...cache_utils import Cache, DynamicCache
8
+ from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask
9
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
10
+ from ...modeling_outputs import (
11
+ BaseModelOutputWithPast,
12
+ )
13
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
14
+ from ...processing_utils import Unpack
15
+ from ...utils import TransformersKwargs, auto_docstring, logging
16
+ from ...utils.deprecation import deprecate_kwarg
17
+ from ...utils.generic import check_model_inputs
18
+ from ..llama.modeling_llama import (
19
+ LlamaAttention,
20
+ LlamaDecoderLayer,
21
+ LlamaForCausalLM,
22
+ LlamaForQuestionAnswering,
23
+ LlamaForSequenceClassification,
24
+ LlamaForTokenClassification,
25
+ LlamaMLP,
26
+ LlamaPreTrainedModel,
27
+ apply_rotary_pos_emb,
28
+ eager_attention_forward,
29
+ )
30
+ from ..mistral.modeling_mistral import MistralModel
31
+ from .configuration_qwen2 import Qwen2Config
32
+
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ class Qwen2MLP(LlamaMLP):
38
+ def __init__(self, config):
39
+ super().__init__(config)
40
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
41
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
42
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
43
+
44
+
45
+ class Qwen2Attention(LlamaAttention):
46
+ def __init__(self, config: Qwen2Config, layer_idx: int):
47
+ super().__init__(config, layer_idx)
48
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=True)
49
+ self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
50
+ self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
51
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
52
+ self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None
53
+
54
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
55
+ def forward(
56
+ self,
57
+ hidden_states: torch.Tensor,
58
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
59
+ attention_mask: Optional[torch.Tensor],
60
+ past_key_values: Optional[Cache] = None,
61
+ cache_position: Optional[torch.LongTensor] = None,
62
+ **kwargs: Unpack[FlashAttentionKwargs],
63
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
64
+ input_shape = hidden_states.shape[:-1]
65
+ hidden_shape = (*input_shape, -1, self.head_dim)
66
+
67
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
68
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
69
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
70
+
71
+ cos, sin = position_embeddings
72
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
73
+
74
+ if past_key_values is not None:
75
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
76
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
77
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
78
+
79
+ attention_interface: Callable = eager_attention_forward
80
+ if self.config._attn_implementation != "eager":
81
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
82
+
83
+ attn_output, attn_weights = attention_interface(
84
+ self,
85
+ query_states,
86
+ key_states,
87
+ value_states,
88
+ attention_mask,
89
+ dropout=0.0 if not self.training else self.attention_dropout,
90
+ scaling=self.scaling,
91
+ sliding_window=self.sliding_window, # main diff with Llama
92
+ **kwargs,
93
+ )
94
+
95
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
96
+ attn_output = self.o_proj(attn_output)
97
+ return attn_output, attn_weights
98
+
99
+
100
+ class Qwen2DecoderLayer(LlamaDecoderLayer):
101
+ def __init__(self, config: Qwen2Config, layer_idx: int):
102
+ super().__init__()
103
+ self.attention_type = config.layer_types[layer_idx]
104
+
105
+
106
+ class Qwen2PreTrainedModel(LlamaPreTrainedModel):
107
+ pass
108
+
109
+
110
+ class Qwen2Model(MistralModel):
111
+ def __init__(self, config: Qwen2Config):
112
+ super().__init__(config)
113
+ self.has_sliding_layers = "sliding_attention" in self.config.layer_types
114
+
115
+ @check_model_inputs
116
+ @auto_docstring
117
+ def forward(
118
+ self,
119
+ input_ids: Optional[torch.LongTensor] = None,
120
+ attention_mask: Optional[torch.Tensor] = None,
121
+ position_ids: Optional[torch.LongTensor] = None,
122
+ past_key_values: Optional[Cache] = None,
123
+ inputs_embeds: Optional[torch.FloatTensor] = None,
124
+ use_cache: Optional[bool] = None,
125
+ cache_position: Optional[torch.LongTensor] = None,
126
+ **kwargs: Unpack[TransformersKwargs],
127
+ ) -> BaseModelOutputWithPast:
128
+ if (input_ids is None) ^ (inputs_embeds is not None):
129
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
130
+
131
+ if inputs_embeds is None:
132
+ inputs_embeds = self.embed_tokens(input_ids)
133
+
134
+ if use_cache and past_key_values is None:
135
+ past_key_values = DynamicCache(config=self.config)
136
+
137
+ if cache_position is None:
138
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
139
+ cache_position = torch.arange(
140
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
141
+ )
142
+
143
+ if position_ids is None:
144
+ position_ids = cache_position.unsqueeze(0)
145
+
146
+ # It may already have been prepared by e.g. `generate`
147
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
148
+ # Prepare mask arguments
149
+ mask_kwargs = {
150
+ "config": self.config,
151
+ "input_embeds": inputs_embeds,
152
+ "attention_mask": attention_mask,
153
+ "cache_position": cache_position,
154
+ "past_key_values": past_key_values,
155
+ "position_ids": position_ids,
156
+ }
157
+ # Create the masks
158
+ causal_mask_mapping = {
159
+ "full_attention": create_causal_mask(**mask_kwargs),
160
+ }
161
+ # The sliding window alternating layers are not always activated depending on the config
162
+ if self.has_sliding_layers:
163
+ causal_mask_mapping["sliding_attention"] = create_sliding_window_causal_mask(**mask_kwargs)
164
+
165
+ hidden_states = inputs_embeds
166
+
167
+ # create position embeddings to be shared across the decoder layers
168
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
169
+
170
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
171
+ hidden_states = decoder_layer(
172
+ hidden_states,
173
+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],
174
+ position_ids=position_ids,
175
+ past_key_values=past_key_values,
176
+ use_cache=use_cache,
177
+ cache_position=cache_position,
178
+ position_embeddings=position_embeddings,
179
+ **kwargs,
180
+ )
181
+
182
+ hidden_states = self.norm(hidden_states)
183
+ return BaseModelOutputWithPast(
184
+ last_hidden_state=hidden_states,
185
+ past_key_values=past_key_values if use_cache else None,
186
+ )
187
+
188
+
189
+ class Qwen2ForCausalLM(LlamaForCausalLM):
190
+ pass
191
+
192
+
193
+ class Qwen2ForSequenceClassification(LlamaForSequenceClassification):
194
+ pass
195
+
196
+
197
+ class Qwen2ForTokenClassification(LlamaForTokenClassification):
198
+ pass
199
+
200
+
201
+ class Qwen2ForQuestionAnswering(LlamaForQuestionAnswering):
202
+ pass
203
+
204
+
205
+ __all__ = [
206
+ "Qwen2PreTrainedModel",
207
+ "Qwen2Model",
208
+ "Qwen2ForCausalLM",
209
+ "Qwen2ForSequenceClassification",
210
+ "Qwen2ForTokenClassification",
211
+ "Qwen2ForQuestionAnswering",
212
+ ]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2/tokenization_qwen2.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Tokenization classes for Qwen2."""
16
+
17
+ import json
18
+ import os
19
+ import unicodedata
20
+ from functools import lru_cache
21
+ from typing import Optional
22
+
23
+ import regex as re
24
+
25
+ from ...tokenization_utils import AddedToken, PreTrainedTokenizer
26
+ from ...utils import logging
27
+
28
+
29
+ logger = logging.get_logger(__name__)
30
+
31
+ VOCAB_FILES_NAMES = {
32
+ "vocab_file": "vocab.json",
33
+ "merges_file": "merges.txt",
34
+ }
35
+
36
+
37
+ MAX_MODEL_INPUT_SIZES = {"qwen/qwen-tokenizer": 32768}
38
+
39
+ PRETOKENIZE_REGEX = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
40
+
41
+
42
+ @lru_cache
43
+ # Copied from transformers.models.gpt2.tokenization_gpt2.bytes_to_unicode
44
+ def bytes_to_unicode():
45
+ """
46
+ Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
47
+ characters the bpe code barfs on.
48
+
49
+ The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
50
+ if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
51
+ decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
52
+ tables between utf-8 bytes and unicode strings.
53
+ """
54
+ bs = (
55
+ list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
56
+ )
57
+ cs = bs[:]
58
+ n = 0
59
+ for b in range(2**8):
60
+ if b not in bs:
61
+ bs.append(b)
62
+ cs.append(2**8 + n)
63
+ n += 1
64
+ cs = [chr(n) for n in cs]
65
+ return dict(zip(bs, cs))
66
+
67
+
68
+ # Copied from transformers.models.gpt2.tokenization_gpt2.get_pairs
69
+ def get_pairs(word):
70
+ """
71
+ Return set of symbol pairs in a word.
72
+
73
+ Word is represented as tuple of symbols (symbols being variable-length strings).
74
+ """
75
+ pairs = set()
76
+ prev_char = word[0]
77
+ for char in word[1:]:
78
+ pairs.add((prev_char, char))
79
+ prev_char = char
80
+ return pairs
81
+
82
+
83
+ class Qwen2Tokenizer(PreTrainedTokenizer):
84
+ """
85
+ Construct a Qwen2 tokenizer. Based on byte-level Byte-Pair-Encoding.
86
+
87
+ Same with GPT2Tokenizer, this tokenizer has been trained to treat spaces like parts of the tokens so a word will
88
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
89
+
90
+ ```python
91
+ >>> from transformers import Qwen2Tokenizer
92
+
93
+ >>> tokenizer = Qwen2Tokenizer.from_pretrained("Qwen/Qwen-tokenizer")
94
+ >>> tokenizer("Hello world")["input_ids"]
95
+ [9707, 1879]
96
+
97
+ >>> tokenizer(" Hello world")["input_ids"]
98
+ [21927, 1879]
99
+ ```
100
+ This is expected.
101
+
102
+ You should not use GPT2Tokenizer instead, because of the different pretokenization rules.
103
+
104
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
105
+ this superclass for more information regarding those methods.
106
+
107
+ Args:
108
+ vocab_file (`str`):
109
+ Path to the vocabulary file.
110
+ merges_file (`str`):
111
+ Path to the merges file.
112
+ errors (`str`, *optional*, defaults to `"replace"`):
113
+ Paradigm to follow when decoding bytes to UTF-8. See
114
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
115
+ unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
116
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
117
+ token instead.
118
+ bos_token (`str`, *optional*):
119
+ The beginning of sequence token. Not applicable for this tokenizer.
120
+ eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
121
+ The end of sequence token.
122
+ pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
123
+ The token used for padding, for example when batching sequences of different lengths.
124
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
125
+ Whether or not the model should cleanup the spaces that were added when splitting the input text during the
126
+ tokenization process. Not applicable to this tokenizer, since tokenization does not add spaces.
127
+ split_special_tokens (`bool`, *optional*, defaults to `False`):
128
+ Whether or not the special tokens should be split during the tokenization process. The default behavior is
129
+ to not split special tokens. This means that if `<|endoftext|>` is the `eos_token`, then `tokenizer.tokenize("<|endoftext|>") =
130
+ ['<|endoftext|>`]. Otherwise, if `split_special_tokens=True`, then `tokenizer.tokenize("<|endoftext|>")` will be give `['<',
131
+ '|', 'endo', 'ft', 'ext', '|', '>']`. This argument is only supported for `slow` tokenizers for the moment.
132
+ """
133
+
134
+ vocab_files_names = VOCAB_FILES_NAMES
135
+ model_input_names = ["input_ids", "attention_mask"]
136
+
137
+ def __init__(
138
+ self,
139
+ vocab_file,
140
+ merges_file,
141
+ errors="replace",
142
+ unk_token="<|endoftext|>",
143
+ bos_token=None,
144
+ eos_token="<|endoftext|>",
145
+ pad_token="<|endoftext|>",
146
+ clean_up_tokenization_spaces=False,
147
+ split_special_tokens=False,
148
+ **kwargs,
149
+ ):
150
+ # Qwen vocab does not contain control tokens; added tokens need to be special
151
+ bos_token = (
152
+ AddedToken(bos_token, lstrip=False, rstrip=False, special=True, normalized=False)
153
+ if isinstance(bos_token, str)
154
+ else bos_token
155
+ )
156
+ eos_token = (
157
+ AddedToken(eos_token, lstrip=False, rstrip=False, special=True, normalized=False)
158
+ if isinstance(eos_token, str)
159
+ else eos_token
160
+ )
161
+ unk_token = (
162
+ AddedToken(unk_token, lstrip=False, rstrip=False, special=True, normalized=False)
163
+ if isinstance(unk_token, str)
164
+ else unk_token
165
+ )
166
+ pad_token = (
167
+ AddedToken(pad_token, lstrip=False, rstrip=False, special=True, normalized=False)
168
+ if isinstance(pad_token, str)
169
+ else pad_token
170
+ )
171
+
172
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
173
+ self.encoder = json.load(vocab_handle)
174
+ self.decoder = {v: k for k, v in self.encoder.items()}
175
+ self.errors = errors # how to handle errors in decoding
176
+ self.byte_encoder = bytes_to_unicode()
177
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
178
+ bpe_merges = []
179
+ with open(merges_file, encoding="utf-8") as merges_handle:
180
+ for i, line in enumerate(merges_handle):
181
+ line = line.strip()
182
+ if (i == 0 and line.startswith("#version:")) or not line:
183
+ continue
184
+ bpe_merges.append(tuple(line.split()))
185
+ self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
186
+ # NOTE: the cache can grow without bound and will get really large for long running processes
187
+ # (esp. for texts of language that do not use space between word, e.g. Chinese); technically
188
+ # not a memory leak but appears as one.
189
+ # GPT2Tokenizer has the same problem, so let's be consistent.
190
+ self.cache = {}
191
+
192
+ self.pat = re.compile(PRETOKENIZE_REGEX)
193
+
194
+ if kwargs.get("add_prefix_space", False):
195
+ logger.warning_once(
196
+ f"{self.__class__.__name} does not support `add_prefix_space`, setting it to True has no effect."
197
+ )
198
+
199
+ super().__init__(
200
+ errors=errors,
201
+ bos_token=bos_token,
202
+ eos_token=eos_token,
203
+ pad_token=pad_token,
204
+ unk_token=unk_token,
205
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
206
+ split_special_tokens=split_special_tokens,
207
+ **kwargs,
208
+ )
209
+
210
+ @property
211
+ def vocab_size(self) -> int:
212
+ return len(self.encoder)
213
+
214
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.get_vocab
215
+ def get_vocab(self):
216
+ return dict(self.encoder, **self.added_tokens_encoder)
217
+
218
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.bpe
219
+ def bpe(self, token):
220
+ if token in self.cache:
221
+ return self.cache[token]
222
+ word = tuple(token)
223
+ pairs = get_pairs(word)
224
+
225
+ if not pairs:
226
+ return token
227
+
228
+ while True:
229
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
230
+ if bigram not in self.bpe_ranks:
231
+ break
232
+ first, second = bigram
233
+ new_word = []
234
+ i = 0
235
+ while i < len(word):
236
+ try:
237
+ j = word.index(first, i)
238
+ except ValueError:
239
+ new_word.extend(word[i:])
240
+ break
241
+ else:
242
+ new_word.extend(word[i:j])
243
+ i = j
244
+
245
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
246
+ new_word.append(first + second)
247
+ i += 2
248
+ else:
249
+ new_word.append(word[i])
250
+ i += 1
251
+ new_word = tuple(new_word)
252
+ word = new_word
253
+ if len(word) == 1:
254
+ break
255
+ else:
256
+ pairs = get_pairs(word)
257
+ word = " ".join(word)
258
+ self.cache[token] = word
259
+ return word
260
+
261
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._tokenize
262
+ def _tokenize(self, text):
263
+ """Tokenize a string."""
264
+ bpe_tokens = []
265
+ for token in re.findall(self.pat, text):
266
+ token = "".join(
267
+ self.byte_encoder[b] for b in token.encode("utf-8")
268
+ ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
269
+ bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
270
+ return bpe_tokens
271
+
272
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._convert_token_to_id
273
+ def _convert_token_to_id(self, token):
274
+ """Converts a token (str) in an id using the vocab."""
275
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
276
+
277
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._convert_id_to_token
278
+ def _convert_id_to_token(self, index):
279
+ """Converts an index (integer) in a token (str) using the vocab."""
280
+ return self.decoder.get(index)
281
+
282
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.convert_tokens_to_string
283
+ def convert_tokens_to_string(self, tokens):
284
+ """Converts a sequence of tokens (string) in a single string."""
285
+ text = "".join(tokens)
286
+ text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
287
+ return text
288
+
289
+ def decode(
290
+ self,
291
+ token_ids,
292
+ skip_special_tokens: bool = False,
293
+ clean_up_tokenization_spaces: Optional[bool] = False,
294
+ spaces_between_special_tokens: bool = False,
295
+ **kwargs,
296
+ ) -> str:
297
+ # `spaces_between_special_tokens` defaults to True for _decode in slow tokenizers
298
+ # and cannot be configured elsewhere, but it should default to False for Qwen2Tokenizer
299
+ return super().decode(
300
+ token_ids,
301
+ skip_special_tokens=skip_special_tokens,
302
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
303
+ spaces_between_special_tokens=spaces_between_special_tokens,
304
+ **kwargs,
305
+ )
306
+
307
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.save_vocabulary
308
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
309
+ if not os.path.isdir(save_directory):
310
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
311
+ return
312
+ vocab_file = os.path.join(
313
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
314
+ )
315
+ merge_file = os.path.join(
316
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
317
+ )
318
+
319
+ with open(vocab_file, "w", encoding="utf-8") as f:
320
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
321
+
322
+ index = 0
323
+ with open(merge_file, "w", encoding="utf-8") as writer:
324
+ writer.write("#version: 0.2\n")
325
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
326
+ if index != token_index:
327
+ logger.warning(
328
+ f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
329
+ " Please check that the tokenizer is not corrupted!"
330
+ )
331
+ index = token_index
332
+ writer.write(" ".join(bpe_tokens) + "\n")
333
+ index += 1
334
+
335
+ return vocab_file, merge_file
336
+
337
+ def prepare_for_tokenization(self, text, **kwargs):
338
+ text = unicodedata.normalize("NFC", text)
339
+ return (text, kwargs)
340
+
341
+
342
+ __all__ = ["Qwen2Tokenizer"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2/tokenization_qwen2_fast.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Tokenization classes for Qwen2."""
16
+
17
+ from typing import Optional
18
+
19
+ from ...tokenization_utils import AddedToken
20
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
21
+ from ...utils import logging
22
+ from .tokenization_qwen2 import Qwen2Tokenizer
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+ VOCAB_FILES_NAMES = {
28
+ "vocab_file": "vocab.json",
29
+ "merges_file": "merges.txt",
30
+ "tokenizer_file": "tokenizer.json",
31
+ }
32
+
33
+
34
+ MAX_MODEL_INPUT_SIZES = {"qwen/qwen-tokenizer": 32768}
35
+
36
+
37
+ class Qwen2TokenizerFast(PreTrainedTokenizerFast):
38
+ """
39
+ Construct a "fast" Qwen2 tokenizer (backed by HuggingFace's *tokenizers* library). Based on byte-level
40
+ Byte-Pair-Encoding.
41
+
42
+ Same with GPT2Tokenizer, this tokenizer has been trained to treat spaces like parts of the tokens so a word will
43
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
44
+
45
+ ```python
46
+ >>> from transformers import Qwen2TokenizerFast
47
+
48
+ >>> tokenizer = Qwen2TokenizerFast.from_pretrained("Qwen/Qwen-tokenizer")
49
+ >>> tokenizer("Hello world")["input_ids"]
50
+ [9707, 1879]
51
+
52
+ >>> tokenizer(" Hello world")["input_ids"]
53
+ [21927, 1879]
54
+ ```
55
+ This is expected.
56
+
57
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
58
+ refer to this superclass for more information regarding those methods.
59
+
60
+ Args:
61
+ vocab_file (`str`, *optional*):
62
+ Path to the vocabulary file.
63
+ merges_file (`str`, *optional*):
64
+ Path to the merges file.
65
+ tokenizer_file (`str`, *optional*):
66
+ Path to [tokenizers](https://github.com/huggingface/tokenizers) file (generally has a .json extension) that
67
+ contains everything needed to load the tokenizer.
68
+ unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
69
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
70
+ token instead. Not applicable to this tokenizer.
71
+ bos_token (`str`, *optional*):
72
+ The beginning of sequence token. Not applicable for this tokenizer.
73
+ eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
74
+ The end of sequence token.
75
+ pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
76
+ The token used for padding, for example when batching sequences of different lengths.
77
+ """
78
+
79
+ vocab_files_names = VOCAB_FILES_NAMES
80
+ model_input_names = ["input_ids", "attention_mask"]
81
+ slow_tokenizer_class = Qwen2Tokenizer
82
+
83
+ def __init__(
84
+ self,
85
+ vocab_file=None,
86
+ merges_file=None,
87
+ tokenizer_file=None,
88
+ unk_token="<|endoftext|>",
89
+ bos_token=None,
90
+ eos_token="<|endoftext|>",
91
+ pad_token="<|endoftext|>",
92
+ **kwargs,
93
+ ):
94
+ # We need to at least pass vocab_file and merges_file to base class
95
+ # in case a slow tokenizer needs to be initialized; other can be
96
+ # configured through files.
97
+ # following GPT2TokenizerFast, also adding unk_token, bos_token, and eos_token
98
+
99
+ bos_token = (
100
+ AddedToken(bos_token, lstrip=False, rstrip=False, special=True, normalized=False)
101
+ if isinstance(bos_token, str)
102
+ else bos_token
103
+ )
104
+ eos_token = (
105
+ AddedToken(eos_token, lstrip=False, rstrip=False, special=True, normalized=False)
106
+ if isinstance(eos_token, str)
107
+ else eos_token
108
+ )
109
+ unk_token = (
110
+ AddedToken(unk_token, lstrip=False, rstrip=False, special=True, normalized=False)
111
+ if isinstance(unk_token, str)
112
+ else unk_token
113
+ )
114
+ pad_token = (
115
+ AddedToken(pad_token, lstrip=False, rstrip=False, special=True, normalized=False)
116
+ if isinstance(pad_token, str)
117
+ else pad_token
118
+ )
119
+
120
+ super().__init__(
121
+ vocab_file=vocab_file,
122
+ merges_file=merges_file,
123
+ tokenizer_file=tokenizer_file,
124
+ unk_token=unk_token,
125
+ bos_token=bos_token,
126
+ eos_token=eos_token,
127
+ pad_token=pad_token,
128
+ **kwargs,
129
+ )
130
+
131
+ # Copied from transformers.models.gpt2.tokenization_gpt2_fast.GPT2TokenizerFast.save_vocabulary
132
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
133
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
134
+ return tuple(files)
135
+
136
+
137
+ __all__ = ["Qwen2TokenizerFast"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_5_omni/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The Qwen Team 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
+ 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_qwen2_5_omni import *
22
+ from .modeling_qwen2_5_omni import *
23
+ from .processing_qwen2_5_omni 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__)
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_5_omni/configuration_qwen2_5_omni.py ADDED
@@ -0,0 +1,1091 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/qwen2_5_omni/modular_qwen2_5_omni.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_qwen2_5_omni.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2025 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ #
11
+ # Licensed under the Apache License, Version 2.0 (the "License");
12
+ # you may not use this file except in compliance with the License.
13
+ # You may obtain a copy of the License at
14
+ #
15
+ # http://www.apache.org/licenses/LICENSE-2.0
16
+ #
17
+ # Unless required by applicable law or agreed to in writing, software
18
+ # distributed under the License is distributed on an "AS IS" BASIS,
19
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ # See the License for the specific language governing permissions and
21
+ # limitations under the License.
22
+ from ...configuration_utils import PretrainedConfig, layer_type_validation
23
+ from ...modeling_rope_utils import rope_config_validation
24
+ from ...utils import logging
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+
30
+ class Qwen2_5OmniVisionEncoderConfig(PretrainedConfig):
31
+ r"""
32
+ This is the configuration class to store the configuration of a [`Qwen2_5OmniThinkerVision`]. It is used to instantiate a
33
+ Qwen2.5-VL vision encoder according to the specified arguments, defining the model architecture. Instantiating a
34
+ configuration with the defaults will yield a similar configuration to that of the audio encoder of the Qwen2.5-VL
35
+ architecture.
36
+
37
+ e.g. [Qwen/Qwen2.5-Omni-7B](https://huggingface.co/Qwen/Qwen2.5-Omni-7B)
38
+
39
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
40
+ documentation from [`PretrainedConfig`] for more information.
41
+
42
+ Args:
43
+ depth (`int`, *optional*, defaults to 32):
44
+ Number of layers (depth) in the model.
45
+ hidden_size (`int`, *optional*, defaults to 3584):
46
+ The size of the hidden layers.
47
+ hidden_act (`str`, *optional*, defaults to `"quick_gelu"`):
48
+ The non-linear activation function used in the model. Supported options include `"quick_gelu"` and others as applicable.
49
+ mlp_ratio (`float`, *optional*, defaults to 4):
50
+ The ratio used to determine the size of the MLP (Multi-Layer Perceptron) hidden layer.
51
+ num_heads (`int`, *optional*, defaults to 16):
52
+ Number of attention heads for each attention layer.
53
+ in_channels (`int`, *optional*, defaults to 3):
54
+ Number of input channels.
55
+ patch_size (`int`, *optional*, defaults to 14):
56
+ The size of the patches extracted from the input.
57
+ spatial_merge_size (`int`, *optional*, defaults to 2):
58
+ The size used for merging spatial dimensions.
59
+ temporal_patch_size (`int`, *optional*, defaults to 2):
60
+ The size used for patches along the temporal dimension.
61
+
62
+ Example:
63
+
64
+ ```python
65
+ >>> from transformers import Qwen2_5OmniVisionEncoderConfig, Qwen2_5OmniVisionEncoder
66
+
67
+ >>> # Initializing a Qwen2_5OmniVisionEncoderConfig
68
+ >>> configuration = Qwen2_5OmniVisionEncoderConfig()
69
+
70
+ >>> # Initializing a Qwen2_5OmniVisionEncoder (with random weights)
71
+ >>> model = Qwen2_5OmniVisionEncoder(configuration)
72
+
73
+ >>> # Accessing the model configuration
74
+ >>> configuration = model.config
75
+ ```"""
76
+
77
+ model_type = "qwen2_5_omni_vision_encoder"
78
+ base_config_key = "vision_config"
79
+
80
+ def __init__(
81
+ self,
82
+ depth=32,
83
+ hidden_size=3584,
84
+ hidden_act="silu",
85
+ intermediate_size=3420,
86
+ num_heads=16,
87
+ in_channels=3,
88
+ patch_size=14,
89
+ spatial_merge_size=2,
90
+ temporal_patch_size=2,
91
+ window_size=112,
92
+ out_hidden_size=3584,
93
+ fullatt_block_indexes=[7, 15, 23, 31],
94
+ initializer_range=0.02,
95
+ **kwargs,
96
+ ):
97
+ super().__init__(**kwargs)
98
+
99
+ self.depth = depth
100
+ self.hidden_size = hidden_size
101
+ self.hidden_act = hidden_act
102
+ self.intermediate_size = intermediate_size
103
+ self.num_heads = num_heads
104
+ self.in_channels = in_channels
105
+ self.patch_size = patch_size
106
+ self.spatial_merge_size = spatial_merge_size
107
+ self.temporal_patch_size = temporal_patch_size
108
+ self.window_size = window_size
109
+ self.fullatt_block_indexes = fullatt_block_indexes
110
+ self.out_hidden_size = out_hidden_size
111
+ self.initializer_range = initializer_range
112
+
113
+
114
+ class Qwen2_5OmniAudioEncoderConfig(PretrainedConfig):
115
+ r"""
116
+ This is the configuration class to store the configuration of a [`Qwen2_5OmniAudioEncoder`]. It is used to instantiate a
117
+ Qwen2.5-Omni-Thinker audio encoder according to the specified arguments, defining the model architecture. Instantiating a
118
+ configuration with the defaults will yield a similar configuration to that of the audio encoder of the Qwen2-Audio
119
+ architecture.
120
+
121
+ e.g. [Qwen/Qwen2.5-Omni-7B](https://huggingface.co/Qwen/Qwen2.5-Omni-7B)
122
+
123
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
124
+ documentation from [`PretrainedConfig`] for more information.
125
+
126
+ Args:
127
+ num_mel_bins (`int`, *optional*, defaults to 128):
128
+ Number of mel features used per input features. Should correspond to the value used in the
129
+ `Qwen2_5OmniProcessor` class.
130
+ encoder_layers (`int`, *optional*, defaults to 32):
131
+ Number of encoder layers.
132
+ encoder_attention_heads (`int`, *optional*, defaults to 20):
133
+ Number of attention heads for each attention layer in the Transformer encoder.
134
+ encoder_ffn_dim (`int`, *optional*, defaults to 5120):
135
+ Dimensionality of the "intermediate" (often named feed-forward) layer in encoder.
136
+ d_model (`int`, *optional*, defaults to 1280):
137
+ Dimensionality of the layers.
138
+ dropout (`float`, *optional*, defaults to 0.0):
139
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
140
+ attention_dropout (`float`, *optional*, defaults to 0.0):
141
+ The dropout ratio for the attention probabilities.
142
+ activation_function (`str`, *optional*, defaults to `"gelu"`):
143
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
144
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
145
+ activation_dropout (`float`, *optional*, defaults to 0.0):
146
+ The dropout ratio for activations inside the fully connected layer.
147
+ scale_embedding (`bool`, *optional*, defaults to `False`):
148
+ Scale embeddings by diving by sqrt(d_model).
149
+ initializer_range (`float`, *optional*, defaults to 0.02):
150
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
151
+ max_source_positions (`int`, *optional*, defaults to 1500):
152
+ The maximum sequence length of log-mel filter-bank features that this model might ever be used with.
153
+ n_window (`int`, *optional*, defaults to 100):
154
+ The chunk for conv and flash attn in AudioEncoder.
155
+ output_dim (`int`, *optional*, defaults to 3584):
156
+ The output dimension of AudioEncoder.
157
+
158
+ Example:
159
+
160
+ ```python
161
+ >>> from transformers import Qwen2_5OmniAudioEncoderConfig, Qwen2_5OmniAudioEncoder
162
+
163
+ >>> # Initializing a Qwen2_5OmniAudioEncoderConfig
164
+ >>> configuration = Qwen2_5OmniAudioEncoderConfig()
165
+
166
+ >>> # Initializing a Qwen2_5OmniAudioEncoder (with random weights)
167
+ >>> model = Qwen2_5OmniAudioEncoder(configuration)
168
+
169
+ >>> # Accessing the model configuration
170
+ >>> configuration = model.config
171
+ ```"""
172
+
173
+ model_type = "qwen2_5_omni_audio_encoder"
174
+
175
+ def __init__(
176
+ self,
177
+ num_mel_bins=128,
178
+ encoder_layers=32,
179
+ encoder_attention_heads=20,
180
+ encoder_ffn_dim=5120,
181
+ d_model=1280,
182
+ dropout=0,
183
+ attention_dropout=0,
184
+ activation_function="gelu",
185
+ activation_dropout=0,
186
+ scale_embedding=False,
187
+ initializer_range=0.02,
188
+ max_source_positions=1500,
189
+ n_window=100,
190
+ output_dim=3584,
191
+ **kwargs,
192
+ ):
193
+ super().__init__(**kwargs)
194
+
195
+ self.num_mel_bins = num_mel_bins
196
+ self.d_model = d_model
197
+ self.encoder_layers = encoder_layers
198
+ self.encoder_attention_heads = encoder_attention_heads
199
+ self.encoder_ffn_dim = encoder_ffn_dim
200
+ self.dropout = dropout
201
+ self.attention_dropout = attention_dropout
202
+ self.activation_function = activation_function
203
+ self.activation_dropout = activation_dropout
204
+ self.num_hidden_layers = encoder_layers
205
+ self.initializer_range = initializer_range
206
+ self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
207
+ self.max_source_positions = max_source_positions
208
+ self.n_window = n_window
209
+ self.output_dim = output_dim
210
+
211
+
212
+ class Qwen2_5OmniTextConfig(PretrainedConfig):
213
+ r"""
214
+ This is the configuration class to store the configuration of a [`Qwen2_5OmniThinkerForConditionalGeneration`]. It is used to instantiate an
215
+ Qwen2.5-Omni-Thinker model according to the specified arguments, defining the model architecture. Instantiating a configuration
216
+ with the defaults will yield a similar configuration to that of the Qwen2.5-Omni-Thinker.
217
+
218
+ e.g. [Qwen/Qwen2.5-Omni-7B](https://huggingface.co/Qwen/Qwen2.5-Omni-7B)
219
+
220
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
221
+ documentation from [`PretrainedConfig`] for more information.
222
+
223
+ Args:
224
+ vocab_size (`int`, *optional*, defaults to 152064):
225
+ Vocabulary size of the QwenOmni model. Defines the number of different tokens that can be represented by the
226
+ `inputs_ids` passed when calling [`Qwen2VLModel`]
227
+ hidden_size (`int`, *optional*, defaults to 3584):
228
+ Dimension of the hidden representations.
229
+ intermediate_size (`int`, *optional*, defaults to 18944):
230
+ Dimension of the MLP representations.
231
+ num_hidden_layers (`int`, *optional*, defaults to 28):
232
+ Number of hidden layers in the Transformer encoder.
233
+ num_attention_heads (`int`, *optional*, defaults to 28):
234
+ Number of attention heads for each attention layer in the Transformer encoder.
235
+ num_key_value_heads (`int`, *optional*, defaults to 4):
236
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
237
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
238
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
239
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
240
+ by meanpooling all the original heads within that group. For more details, check out [this
241
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`.
242
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
243
+ The non-linear activation function (function or string) in the decoder.
244
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
245
+ The maximum sequence length that this model might ever be used with.
246
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
247
+ The epsilon used by the rms normalization layers.
248
+ use_cache (`bool`, *optional*, defaults to `True`):
249
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
250
+ relevant if `config.is_decoder=True`.
251
+ rope_theta (`float`, *optional*, defaults to 1000000.0):
252
+ The base period of the RoPE embeddings.
253
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
254
+ Whether to use sliding window attention.
255
+ sliding_window (`int`, *optional*, defaults to 32768):
256
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
257
+ max_window_layers (`int`, *optional*, defaults to 28):
258
+ The number of layers using full attention. The first `max_window_layers` layers will use full attention, while any
259
+ additional layer afterwards will use SWA (Sliding Window Attention).
260
+ layer_types (`list`, *optional*):
261
+ Attention pattern for each layer.
262
+ attention_dropout (`float`, *optional*, defaults to 0.0):
263
+ The dropout ratio for the attention probabilities.
264
+ rope_scaling (`Dict`, *optional*):
265
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
266
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
267
+ accordingly.
268
+ Expected contents:
269
+ `rope_type` (`str`):
270
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
271
+ 'llama3'], with 'default' being the original RoPE implementation.
272
+ `factor` (`float`, *optional*):
273
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
274
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
275
+ original maximum pre-trained length.
276
+ `original_max_position_embeddings` (`int`, *optional*):
277
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
278
+ pretraining.
279
+ `attention_factor` (`float`, *optional*):
280
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
281
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
282
+ `factor` field to infer the suggested value.
283
+ `beta_fast` (`float`, *optional*):
284
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
285
+ ramp function. If unspecified, it defaults to 32.
286
+ `beta_slow` (`float`, *optional*):
287
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
288
+ ramp function. If unspecified, it defaults to 1.
289
+ `short_factor` (`list[float]`, *optional*):
290
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
291
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
292
+ size divided by the number of attention heads divided by 2
293
+ `long_factor` (`list[float]`, *optional*):
294
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
295
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
296
+ size divided by the number of attention heads divided by 2
297
+ `low_freq_factor` (`float`, *optional*):
298
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
299
+ `high_freq_factor` (`float`, *optional*):
300
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
301
+ initializer_range (`float`, *optional*, defaults to 0.02):
302
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
303
+
304
+ Example:
305
+
306
+ ```python
307
+ >>> from transformers import Qwen2_5OmniThinkerForConditionalGeneration, Qwen2_5OmniThinkerConfig, Qwen2_5OmniAudioEncoderConfig, Qwen2_5OmniVisionEncoderConfig
308
+
309
+ >>> # Initializing a Qwen2_5OmniAudioEncoder config
310
+ >>> audio_config = Qwen2_5OmniAudioEncoderConfig()
311
+
312
+ >>> # Initializing a Qwen2_5OmniVisionEncoder config
313
+ >>> vision_config = Qwen2_5OmniVisionEncoderConfig()
314
+
315
+ >>> # Initializing a Qwen2.5OmniThinker configuration
316
+ >>> configuration = Qwen2_5OmniThinkerConfig(audio_config, vision_config)
317
+
318
+ >>> # Initializing a model from the Qwen-Omni style configuration
319
+ >>> model = Qwen2_5OmniThinkerForConditionalGeneration(configuration)
320
+
321
+ >>> # Accessing the model configuration
322
+ >>> configuration = model.config
323
+ ```"""
324
+
325
+ model_type = "qwen2_5_omni_text"
326
+ keys_to_ignore_at_inference = ["past_key_values"]
327
+
328
+ # Default tensor parallel plan for base model `Qwen25OmniText`
329
+ base_model_tp_plan = {
330
+ "layers.*.self_attn.q_proj": "colwise",
331
+ "layers.*.self_attn.k_proj": "colwise",
332
+ "layers.*.self_attn.v_proj": "colwise",
333
+ "layers.*.self_attn.o_proj": "rowwise",
334
+ "layers.*.mlp.gate_proj": "colwise",
335
+ "layers.*.mlp.up_proj": "colwise",
336
+ "layers.*.mlp.down_proj": "rowwise",
337
+ }
338
+ base_model_pp_plan = {
339
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
340
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
341
+ "norm": (["hidden_states"], ["hidden_states"]),
342
+ }
343
+
344
+ def __init__(
345
+ self,
346
+ vocab_size=152064,
347
+ hidden_size=3584,
348
+ intermediate_size=18944,
349
+ num_hidden_layers=28,
350
+ num_attention_heads=28,
351
+ num_key_value_heads=4,
352
+ hidden_act="silu",
353
+ max_position_embeddings=32768,
354
+ initializer_range=0.02,
355
+ rms_norm_eps=1e-6,
356
+ use_cache=True,
357
+ tie_word_embeddings=False,
358
+ rope_theta=1000000.0,
359
+ rope_scaling=None,
360
+ use_sliding_window=False,
361
+ sliding_window=32768,
362
+ max_window_layers=28,
363
+ layer_types=None,
364
+ attention_dropout=0.0,
365
+ **kwargs,
366
+ ):
367
+ super().__init__(
368
+ tie_word_embeddings=tie_word_embeddings,
369
+ **kwargs,
370
+ )
371
+ self.vocab_size = vocab_size
372
+ self.max_position_embeddings = max_position_embeddings
373
+ self.hidden_size = hidden_size
374
+ self.intermediate_size = intermediate_size
375
+ self.num_hidden_layers = num_hidden_layers
376
+ self.num_attention_heads = num_attention_heads
377
+ self.use_sliding_window = use_sliding_window
378
+ self.sliding_window = sliding_window if self.use_sliding_window else None
379
+ self.max_window_layers = max_window_layers
380
+
381
+ # for backward compatibility
382
+ if num_key_value_heads is None:
383
+ num_key_value_heads = num_attention_heads
384
+
385
+ self.num_key_value_heads = num_key_value_heads
386
+ self.hidden_act = hidden_act
387
+ self.initializer_range = initializer_range
388
+ self.rms_norm_eps = rms_norm_eps
389
+ self.use_cache = use_cache
390
+ self.rope_theta = rope_theta
391
+ self.rope_scaling = rope_scaling
392
+ self.attention_dropout = attention_dropout
393
+ # Validate the correctness of rotary position embeddings parameters
394
+ # BC: if there is a 'type' field, move it to 'rope_type'.
395
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
396
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
397
+ rope_config_validation(self)
398
+
399
+ if self.rope_scaling is None:
400
+ self.rope_scaling = {"mrope_section": [16, 24, 24], "rope_type": "default", "type": "default"}
401
+
402
+ self.layer_types = layer_types
403
+ if self.layer_types is None:
404
+ self.layer_types = [
405
+ "sliding_attention"
406
+ if self.sliding_window is not None and i >= self.max_window_layers
407
+ else "full_attention"
408
+ for i in range(self.num_hidden_layers)
409
+ ]
410
+ layer_type_validation(self.layer_types)
411
+
412
+
413
+ class Qwen2_5OmniThinkerConfig(PretrainedConfig):
414
+ r"""
415
+ This is the configuration class to store the configuration of a [`Qwen2_5OmniThinkerForConditionalGeneration`]. It is used to instantiate an
416
+ Qwen2.5-Omni-Thinker model according to the specified arguments, defining the model architecture. Instantiating a configuration
417
+ with the defaults will yield a similar configuration to that of the Qwen2.5-Omni-Thinker.
418
+
419
+ e.g. [Qwen/Qwen2.5-Omni-7B](https://huggingface.co/Qwen/Qwen2.5-Omni-7B)
420
+
421
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
422
+ documentation from [`PretrainedConfig`] for more information.
423
+
424
+ Args:
425
+ audio_config (`dict`, *optional*):
426
+ The config dictionary of the audio backbone.
427
+ vision_config (`dict`, *optional*):
428
+ The config dictionary of the vision backbone.
429
+ text_config (`dict`, *optional*):
430
+ The config dictionary of the text backbone.
431
+ audio_token_index (`int`, *optional*, defaults to 151646):
432
+ The audio token index to encode the audio prompt.
433
+ image_token_index (`int`, *optional*, defaults to 151655):
434
+ The image token index to encode the image prompt.
435
+ video_token_index (`int`, *optional*, defaults to 151656):
436
+ The video token index to encode the video prompt.
437
+ position_id_per_seconds (`int`, *optional*, defaults to 25):
438
+ The increment of position id per second.
439
+ seconds_per_chunk (`int`, *optional*, defaults to 2):
440
+ The duration in seconds of the chunk of audio and video data.
441
+ audio_start_token_id (`int`, *optional*, defaults to 151647):
442
+ The audio start token index to encode the audio prompt.
443
+ audio_end_token_id (`int`, *optional*, defaults to 151648):
444
+ The audio end token index to encode the audio prompt.
445
+ user_token_id (`int, *optional*, defaults to 872):
446
+ The user token index to encode the user token.
447
+ initializer_range (`float`, *optional*, defaults to 0.02):
448
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
449
+
450
+ Example:
451
+
452
+ ```python
453
+ >>> from transformers import Qwen2_5OmniThinkerForConditionalGeneration, Qwen2_5OmniThinkerConfig, Qwen2_5OmniAudioEncoderConfig, Qwen2_5OmniVisionEncoderConfig
454
+
455
+ >>> # Initializing a Qwen2_5OmniAudioEncoder config
456
+ >>> audio_config = Qwen2_5OmniAudioEncoderConfig()
457
+
458
+ >>> # Initializing a Qwen2_5OmniVisionEncoder config
459
+ >>> vision_config = Qwen2_5OmniVisionEncoderConfig()
460
+
461
+ >>> # Initializing a Qwen2_5OmniTextConfig config
462
+ >>> text_config = Qwen2_5OmniTextConfig()
463
+
464
+ >>> # Initializing a Qwen2.5OmniThinker configuration
465
+ >>> configuration = Qwen2_5OmniThinkerConfig(audio_config, vision_config, text_config)
466
+
467
+ >>> # Initializing a model from the Qwen-Omni style configuration
468
+ >>> model = Qwen2_5OmniThinkerForConditionalGeneration(configuration)
469
+
470
+ >>> # Accessing the model configuration
471
+ >>> configuration = model.config
472
+ ```"""
473
+
474
+ model_type = "qwen2_5_omni_thinker"
475
+ attribute_map = {
476
+ "image_token_id": "image_token_index",
477
+ "video_token_id": "video_token_index",
478
+ "audio_token_id": "audio_token_index",
479
+ }
480
+ sub_configs = {
481
+ "audio_config": Qwen2_5OmniAudioEncoderConfig,
482
+ "vision_config": Qwen2_5OmniVisionEncoderConfig,
483
+ "text_config": Qwen2_5OmniTextConfig,
484
+ }
485
+
486
+ def __init__(
487
+ self,
488
+ audio_config=None,
489
+ vision_config=None,
490
+ text_config=None,
491
+ audio_token_index=151646,
492
+ image_token_index=151655,
493
+ video_token_index=151656,
494
+ position_id_per_seconds=25,
495
+ seconds_per_chunk=2,
496
+ audio_start_token_id=151647,
497
+ audio_end_token_id=151648,
498
+ user_token_id=872,
499
+ initializer_range=0.02,
500
+ **kwargs,
501
+ ):
502
+ self.audio_token_index = audio_token_index
503
+ self.image_token_index = image_token_index
504
+ self.video_token_index = video_token_index
505
+ self.user_token_id = user_token_id
506
+ self.position_id_per_seconds = position_id_per_seconds
507
+ self.seconds_per_chunk = seconds_per_chunk
508
+ self.audio_start_token_id = audio_start_token_id
509
+ self.audio_end_token_id = audio_end_token_id
510
+ self.initializer_range = initializer_range
511
+
512
+ if isinstance(vision_config, dict):
513
+ vision_config = Qwen2_5OmniVisionEncoderConfig(**vision_config)
514
+ elif vision_config is None:
515
+ vision_config = Qwen2_5OmniVisionEncoderConfig()
516
+ self.vision_config = vision_config
517
+
518
+ if isinstance(audio_config, dict):
519
+ audio_config = Qwen2_5OmniAudioEncoderConfig(**audio_config)
520
+ elif audio_config is None:
521
+ audio_config = Qwen2_5OmniAudioEncoderConfig()
522
+ self.audio_config = audio_config
523
+
524
+ if isinstance(text_config, dict):
525
+ text_config = Qwen2_5OmniTextConfig(**text_config)
526
+ elif text_config is None:
527
+ text_config = Qwen2_5OmniTextConfig()
528
+ self.text_config = text_config
529
+
530
+ super().__init__(**kwargs)
531
+
532
+
533
+ class Qwen2_5OmniTalkerConfig(PretrainedConfig):
534
+ r"""
535
+ This is the configuration class to store the configuration of a [`Qwen2_5OmniTalkerForConditionalGeneration`]. It is used to instantiate an
536
+ Qwen2.5-Omni-Talker model according to the specified arguments, defining the model architecture. Instantiating a configuration
537
+ with the defaults will yield a similar configuration to that of the Qwen2.5-Omni-Thinker.
538
+
539
+ e.g. [Qwen/Qwen2.5-Omni-7B](https://huggingface.co/Qwen/Qwen2.5-Omni-7B)
540
+
541
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
542
+ documentation from [`PretrainedConfig`] for more information.
543
+
544
+ Args:
545
+ audio_token_index (`int`, *optional*, defaults to 151646):
546
+ The audio token index to encode the audio prompt.
547
+ image_token_index (`int`, *optional*, defaults to 151655):
548
+ The image token index to encode the image prompt.
549
+ video_token_index (`int`, *optional*, defaults to 151656):
550
+ The video token index to encode the video prompt.
551
+ vocab_size (`int`, *optional*, defaults to 8448):
552
+ Vocabulary size of the QwenOmni model. Defines the number of different tokens that can be represented by the
553
+ `inputs_ids` passed when calling [`Qwen2VLModel`]
554
+ tts_text_start_token_id (`int`, *optional*, defaults to 151860):
555
+ The tts text start token index to encode the start of tts text.
556
+ tts_text_end_token_id (`int`, *optional*, defaults to 151861):
557
+ The tts text end token index to encode the end of tts text.
558
+ tts_text_pad_token_id (`int`, *optional*, defaults to 151859):
559
+ The tts text pad token index to encode the pad of tts text.
560
+ tts_codec_start_token_id (`int`, *optional*, defaults to 8293):
561
+ The tts codec start token index to encode the start of tts codec.
562
+ tts_codec_end_token_id (`int`, *optional*, defaults to 8294):
563
+ The tts codec end token index to encode the end of tts codec.
564
+ tts_codec_pad_token_id (`int`, *optional*, defaults to 8292):
565
+ The tts codec pad token index to encode the pad of tts codec.
566
+ tts_codec_mask_token_id (`int`, *optional*, defaults to 8296):
567
+ The tts codec mask token index to encode the mask of tts codec.
568
+ vision_start_token_id (`int`, *optional*, defaults to 151652):
569
+ The tts vision start token index to encode the start of vision.
570
+ vision_end_token_id (`int`, *optional*, defaults to 151653):
571
+ The tts vision end token index to encode the end of vision.
572
+ embedding_size (`int`, *optional*, defaults to 3584):
573
+ Dimension of the embedding representations.
574
+ hidden_size (`int`, *optional*, defaults to 3584):
575
+ Dimension of the hidden representations.
576
+ intermediate_size (`int`, *optional*, defaults to 18944):
577
+ Dimension of the MLP representations.
578
+ num_hidden_layers (`int`, *optional*, defaults to 28):
579
+ Number of hidden layers in the Transformer encoder.
580
+ num_attention_heads (`int`, *optional*, defaults to 28):
581
+ Number of attention heads for each attention layer in the Transformer encoder.
582
+ num_key_value_heads (`int`, *optional*, defaults to 4):
583
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
584
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
585
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
586
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
587
+ by meanpooling all the original heads within that group. For more details, check out [this
588
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`.
589
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
590
+ The non-linear activation function (function or string) in the decoder.
591
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
592
+ The maximum sequence length that this model might ever be used with.
593
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
594
+ The epsilon used by the rms normalization layers.
595
+ head_dim (`int`, *optional*, defaults to 128):
596
+ The dimension of each attention head.
597
+ use_cache (`bool`, *optional*, defaults to `True`):
598
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
599
+ relevant if `config.is_decoder=True`.
600
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
601
+ Whether the model's input and output word embeddings should be tied.
602
+ rope_theta (`float`, *optional*, defaults to 1000000.0):
603
+ The base period of the RoPE embeddings.
604
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
605
+ Whether to use sliding window attention.
606
+ sliding_window (`int`, *optional*, defaults to 32768):
607
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
608
+ max_window_layers (`int`, *optional*, defaults to 28):
609
+ The number of layers using full attention. The first `max_window_layers` layers will use full attention, while any
610
+ additional layer afterwards will use SWA (Sliding Window Attention).
611
+ attention_dropout (`float`, *optional*, defaults to 0.0):
612
+ The dropout ratio for the attention probabilities.
613
+ rope_scaling (`Dict`, *optional*):
614
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
615
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
616
+ accordingly.
617
+ Expected contents:
618
+ `rope_type` (`str`):
619
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
620
+ 'llama3'], with 'default' being the original RoPE implementation.
621
+ `factor` (`float`, *optional*):
622
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
623
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
624
+ original maximum pre-trained length.
625
+ `original_max_position_embeddings` (`int`, *optional*):
626
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
627
+ pretraining.
628
+ `attention_factor` (`float`, *optional*):
629
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
630
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
631
+ `factor` field to infer the suggested value.
632
+ `beta_fast` (`float`, *optional*):
633
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
634
+ ramp function. If unspecified, it defaults to 32.
635
+ `beta_slow` (`float`, *optional*):
636
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
637
+ ramp function. If unspecified, it defaults to 1.
638
+ `short_factor` (`list[float]`, *optional*):
639
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
640
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
641
+ size divided by the number of attention heads divided by 2
642
+ `long_factor` (`list[float]`, *optional*):
643
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
644
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
645
+ size divided by the number of attention heads divided by 2
646
+ `low_freq_factor` (`float`, *optional*):
647
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
648
+ `high_freq_factor` (`float`, *optional*):
649
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
650
+ position_id_per_seconds (`int`, *optional*, defaults to 25):
651
+ The increment of position id per second.
652
+ seconds_per_chunk (`int`, *optional*, defaults to 2):
653
+ The duration in seconds of the chunk of audio and video data.
654
+ audio_start_token_id (`int`, *optional*, defaults to 151647):
655
+ The audio start token index to encode the audio prompt.
656
+ audio_end_token_id (`int`, *optional*, defaults to 151648):
657
+ The audio end token index to encode the audio prompt.
658
+ initializer_range (`float`, *optional*, defaults to 0.02):
659
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
660
+ spatial_merge_size (`int`, *optional*, defaults to 2):
661
+ The size used for merging spatial dimensions.
662
+ layer_types (`list`, *optional*):
663
+ Attention pattern for each layer.
664
+
665
+ Example:
666
+
667
+ ```python
668
+ >>> from transformers import Qwen2_5OmniTalkerForConditionalGeneration, Qwen2_5OmniThinkerConfig, Qwen2_5OmniAudioEncoderConfig, Qwen2_5OmniVisionEncoderConfig
669
+
670
+ >>> # Initializing a Qwen2_5OmniAudioEncoder config
671
+ >>> audio_config = Qwen2_5OmniAudioEncoderConfig()
672
+
673
+ >>> # Initializing a Qwen2 config
674
+ >>> text_config = Qwen2Config()
675
+
676
+ >>> # Initializing a Qwen2_5Omni configuration
677
+ >>> configuration = Qwen2_5OmniThinkerConfig(audio_config, text_config)
678
+
679
+ >>> # Initializing a model from the qwen2-audio style configuration
680
+ >>> model = Qwen2_5OmniTalkerForConditionalGeneration(configuration)
681
+
682
+ >>> # Accessing the model configuration
683
+ >>> configuration = model.config
684
+ ```"""
685
+
686
+ model_type = "qwen2_5_omni_talker"
687
+ attribute_map = {
688
+ "image_token_id": "image_token_index",
689
+ "video_token_id": "video_token_index",
690
+ "audio_token_id": "audio_token_index",
691
+ }
692
+
693
+ def __init__(
694
+ self,
695
+ audio_token_index=151646,
696
+ image_token_index=151655,
697
+ video_token_index=151656,
698
+ vocab_size=8448,
699
+ tts_text_start_token_id=151860,
700
+ tts_text_end_token_id=151861,
701
+ tts_text_pad_token_id=151859,
702
+ tts_codec_start_token_id=8293,
703
+ tts_codec_end_token_id=8294,
704
+ tts_codec_pad_token_id=8292,
705
+ tts_codec_mask_token_id=8296,
706
+ vision_start_token_id=151652,
707
+ vision_end_token_id=151653,
708
+ embedding_size=3584,
709
+ hidden_size=3584,
710
+ intermediate_size=18944,
711
+ num_hidden_layers=28,
712
+ num_attention_heads=28,
713
+ num_key_value_heads=4,
714
+ hidden_act="silu",
715
+ max_position_embeddings=32768,
716
+ rms_norm_eps=1e-06,
717
+ head_dim=128,
718
+ use_cache=True,
719
+ tie_word_embeddings=False,
720
+ rope_theta=1000000.0,
721
+ use_sliding_window=False,
722
+ sliding_window=32768,
723
+ max_window_layers=28,
724
+ attention_dropout=0.0,
725
+ rope_scaling=None,
726
+ position_id_per_seconds=25,
727
+ seconds_per_chunk=2,
728
+ audio_start_token_id=151647,
729
+ audio_end_token_id=151648,
730
+ initializer_range=0.02,
731
+ spatial_merge_size=2,
732
+ layer_types=None,
733
+ **kwargs,
734
+ ):
735
+ self.audio_token_index = audio_token_index
736
+ self.image_token_index = image_token_index
737
+ self.video_token_index = video_token_index
738
+
739
+ self.tts_text_start_token_id = tts_text_start_token_id
740
+ self.tts_text_end_token_id = tts_text_end_token_id
741
+ self.tts_text_pad_token_id = tts_text_pad_token_id
742
+ self.tts_codec_start_token_id = tts_codec_start_token_id
743
+ self.tts_codec_end_token_id = tts_codec_end_token_id
744
+ self.tts_codec_pad_token_id = tts_codec_pad_token_id
745
+
746
+ self.tts_codec_mask_token_id = tts_codec_mask_token_id
747
+
748
+ self.vision_start_token_id = vision_start_token_id
749
+ self.vision_end_token_id = vision_end_token_id
750
+
751
+ self.vocab_size = vocab_size
752
+ self.head_dim = head_dim
753
+ self.embedding_size = embedding_size
754
+ self.max_position_embeddings = max_position_embeddings
755
+ self.hidden_size = hidden_size
756
+ self.intermediate_size = intermediate_size
757
+ self.num_hidden_layers = num_hidden_layers
758
+ self.num_attention_heads = num_attention_heads
759
+ self.use_sliding_window = use_sliding_window
760
+ self.sliding_window = sliding_window if self.use_sliding_window else None
761
+ self.max_window_layers = max_window_layers
762
+
763
+ # for backward compatibility
764
+ if num_key_value_heads is None:
765
+ num_key_value_heads = num_attention_heads
766
+
767
+ self.num_key_value_heads = num_key_value_heads
768
+ self.hidden_act = hidden_act
769
+ self.rms_norm_eps = rms_norm_eps
770
+ self.use_cache = use_cache
771
+ self.rope_theta = rope_theta
772
+ self.attention_dropout = attention_dropout
773
+ self.rope_scaling = rope_scaling
774
+ self.position_id_per_seconds = position_id_per_seconds # zf
775
+ self.seconds_per_chunk = seconds_per_chunk # zf
776
+ self.audio_start_token_id = audio_start_token_id # zf
777
+ self.audio_end_token_id = audio_end_token_id # zf
778
+
779
+ self.initializer_range = initializer_range
780
+ self.spatial_merge_size = spatial_merge_size
781
+
782
+ self.layer_types = layer_types
783
+ if self.layer_types is None:
784
+ self.layer_types = [
785
+ "sliding_attention"
786
+ if self.sliding_window is not None and i >= self.max_window_layers
787
+ else "full_attention"
788
+ for i in range(self.num_hidden_layers)
789
+ ]
790
+ layer_type_validation(self.layer_types)
791
+
792
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
793
+
794
+
795
+ class Qwen2_5OmniDiTConfig(PretrainedConfig):
796
+ r"""
797
+ This is the configuration class to store the configuration of the Qwen2_5OmniToken2WavDiT used in the Qwen2.5-Omni-Token2Wav model.
798
+ It defines the architecture of the DiT model, which is used for generating mel-spectrograms from tokens.
799
+
800
+ Args:
801
+ hidden_size (`int`, *optional*, defaults to 1024):
802
+ The dimension of the model.
803
+ num_hidden_layers (`int`, *optional*, defaults to 22):
804
+ The number of transformer blocks in the DiT model.
805
+ num_attention_heads (`int`, *optional*, defaults to 16):
806
+ The number of attention heads in each transformer block.
807
+ ff_mult (`int`, *optional*, defaults to 2):
808
+ The multiplier for the feedforward layer in each transformer block.
809
+ emb_dim (`int`, *optional*, defaults to 512):
810
+ The dimension of the embedding layer.
811
+ head_dim (`int`, *optional*, defaults to 64):
812
+ The dimension of each attention head.
813
+ repeats (`int`, *optional*, defaults to 2):
814
+ The number of times the codec embeddings are repeated.
815
+ num_embeds (`int`, *optional*, defaults to 8193):
816
+ The number of unique embeddings in the codec.
817
+ mel_dim (`int`, *optional*, defaults to 80):
818
+ The dimension of the mel-spectrogram.
819
+ dropout (`float`, *optional*, defaults to 0.1):
820
+ The dropout rate for the transformer blocks.
821
+
822
+ enc_emb_dim (`int`, *optional*, defaults to 192):
823
+ The dimension of the pre-trained speaker embedding.
824
+ enc_dim (`int`, *optional*, defaults to 128):
825
+ The dimension of the encoder output.
826
+ enc_channels (`list[int]`, *optional*, defaults to `[256, 256, 256, 256, 768]`):
827
+ A list of output channels for each TDNN/SERes2Net layer in the encoder.
828
+ enc_kernel_sizes (`list[int]`, *optional*, defaults to `[5, 3, 3, 3, 1]`):
829
+ A list of kernel sizes for each layer in the encoder.
830
+ enc_dilations (`list[int]`, *optional*, defaults to `[1, 2, 3, 4, 1]`):
831
+ A list of dilations for each layer in the encoder.
832
+ enc_attention_channels (`int`, *optional*, defaults to 64):
833
+ The number of attention channels in the SqueezeExcitationBlock.
834
+ enc_res2net_scale (`int`, *optional*, defaults to 2):
835
+ The scale of the Res2Net block in the encoder.
836
+ enc_se_channels (`int`, *optional*, defaults to 64):
837
+ The number of output channels after squeeze in the SqueezeExcitationBlock.
838
+ """
839
+
840
+ model_type = "qwen2_5_omni_dit"
841
+
842
+ def __init__(
843
+ self,
844
+ hidden_size=1024,
845
+ num_hidden_layers=22,
846
+ num_attention_heads=16,
847
+ ff_mult=2,
848
+ emb_dim=512,
849
+ head_dim=64,
850
+ rope_theta=10000.0,
851
+ max_position_embeddings=32768,
852
+ block_size=24,
853
+ look_ahead_layers=[10],
854
+ look_backward_layers=[0, 20],
855
+ repeats=2,
856
+ num_embeds=8193,
857
+ mel_dim=80,
858
+ dropout=0.1,
859
+ enc_emb_dim=192,
860
+ enc_dim=128,
861
+ enc_channels=[256, 256, 256, 256, 768],
862
+ enc_kernel_sizes=[5, 3, 3, 3, 1],
863
+ enc_dilations=[1, 2, 3, 4, 1],
864
+ enc_attention_channels=64,
865
+ enc_res2net_scale=2,
866
+ enc_se_channels=64,
867
+ **kwargs,
868
+ ):
869
+ self.hidden_size = hidden_size
870
+ self.num_hidden_layers = num_hidden_layers
871
+ self.num_attention_heads = num_attention_heads
872
+ self.ff_mult = ff_mult
873
+ self.emb_dim = emb_dim
874
+ self.head_dim = head_dim
875
+ self.rope_theta = rope_theta
876
+ self.max_position_embeddings = max_position_embeddings
877
+ self.block_size = block_size
878
+ self.look_ahead_layers = look_ahead_layers
879
+ self.look_backward_layers = look_backward_layers
880
+ self.repeats = repeats
881
+ self.num_embeds = num_embeds
882
+ self.mel_dim = mel_dim
883
+ self.dropout = dropout
884
+ self.enc_emb_dim = enc_emb_dim
885
+ self.enc_dim = enc_dim
886
+ self.enc_channels = enc_channels
887
+ self.enc_kernel_sizes = enc_kernel_sizes
888
+ self.enc_dilations = enc_dilations
889
+ self.enc_attention_channels = enc_attention_channels
890
+ self.enc_res2net_scale = enc_res2net_scale
891
+ self.enc_se_channels = enc_se_channels
892
+ super().__init__(**kwargs)
893
+
894
+
895
+ class Qwen2_5OmniBigVGANConfig(PretrainedConfig):
896
+ r"""
897
+ This is the configuration class to store the configuration of the Qwen2_5OmniToken2WavBigVGAN module used in the Qwen2.5-Omni-Token2Wav model.
898
+ It defines the architecture of the BigVGAN model, which is used for converting mel-spectrograms to waveforms.
899
+
900
+ Args:
901
+ mel_dim (`int`, *optional*, defaults to 80):
902
+ The dimension of the mel-spectrogram.
903
+ upsample_initial_channel (`int`, *optional*, defaults to 1536):
904
+ The number of channels in the initial upsampling layer.
905
+ resblock_kernel_sizes (`list[int]`, *optional*, defaults to `[3, 7, 11]`):
906
+ A list of kernel sizes for each residual block.
907
+ resblock_dilation_sizes (`list[list[int]]`, *optional*, defaults to `[[1, 3, 5], [1, 3, 5], [1, 3, 5]]`):
908
+ A list of dilation sizes for each residual block.
909
+ upsample_rates (`list[int]`, *optional*, defaults to `[5, 3, 2, 2, 2, 2]`):
910
+ A list of upsampling rates for each upsampling layer.
911
+ upsample_kernel_sizes (`list[int]`, *optional*, defaults to `[11, 7, 4, 4, 4, 4]`):
912
+ A list of kernel sizes for each upsampling layer.
913
+ """
914
+
915
+ model_type = "qwen2_5_omni_bigvgan"
916
+
917
+ def __init__(
918
+ self,
919
+ mel_dim=80,
920
+ upsample_initial_channel=1536,
921
+ resblock_kernel_sizes=[3, 7, 11],
922
+ resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5], [1, 3, 5]],
923
+ upsample_rates=[5, 3, 2, 2, 2, 2],
924
+ upsample_kernel_sizes=[11, 7, 4, 4, 4, 4],
925
+ **kwargs,
926
+ ):
927
+ self.mel_dim = mel_dim
928
+ self.upsample_initial_channel = upsample_initial_channel
929
+ self.resblock_kernel_sizes = resblock_kernel_sizes
930
+ self.resblock_dilation_sizes = resblock_dilation_sizes
931
+ self.upsample_rates = upsample_rates
932
+ self.upsample_kernel_sizes = upsample_kernel_sizes
933
+ super().__init__(**kwargs)
934
+
935
+
936
+ class Qwen2_5OmniToken2WavConfig(PretrainedConfig):
937
+ r"""
938
+ This is the configuration class to store the configuration of a [`Qwen2_5OmniToken2WavModel`].
939
+ It is used to instantiate the Qwen2.5-Omni-Token2Wav model which combines a Diffusion Transformer (DiT) for mel-spectrogram generation with a BigVGAN model for waveform synthesis. The configuration contains sub-configurations for both components.
940
+
941
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
942
+ documentation from [`PretrainedConfig`] for more information.
943
+
944
+ Args:
945
+ dit_config ([`DiT_Args`], *optional*):
946
+ Configuration class for the Diffusion Transformer (DiT) module responsible for generating mel-spectrograms.
947
+ bigvgan_config ([`BigVGAN_Args`], *optional*):
948
+ Configuration class for the BigVGAN module responsible for converting mel-spectrograms to waveforms.
949
+ Example:
950
+
951
+ ```python
952
+ >>> from transformers import Qwen2_5OmniToken2WavModel, DiT_Args, BigVGAN_Args
953
+
954
+ >>> # Initialize DiT configuration
955
+ >>> dit_config = DiT_Args(
956
+ ... dim=1024,
957
+ ... depth=22,
958
+ ... heads=16,
959
+ ... ff_mult=2
960
+ ... )
961
+
962
+ >>> # Initialize BigVGAN configuration
963
+ >>> bigvgan_config = BigVGAN_Args(
964
+ ... mel_dim=80,
965
+ ... upsample_rates=[5,3,2,2,2,2]
966
+ ... )
967
+
968
+ >>> # Initialize main configuration
969
+ >>> config = Qwen2_5OmniToken2WavConfig(dit_config, bigvgan_config)
970
+
971
+ >>> # Initialize model with config
972
+ >>> model = Qwen2_5OmniToken2Wav(config)
973
+
974
+ >>> # Accessing the model configuration
975
+ >>> configuration = model.config
976
+ ```
977
+ """
978
+
979
+ model_type = "qwen2_5_omni_token2wav"
980
+ sub_configs = {
981
+ "dit_config": Qwen2_5OmniDiTConfig,
982
+ "bigvgan_config": Qwen2_5OmniBigVGANConfig,
983
+ }
984
+
985
+ def __init__(self, dit_config=None, bigvgan_config=None, **kwargs):
986
+ if dit_config is None:
987
+ dit_config = {}
988
+ if bigvgan_config is None:
989
+ bigvgan_config = {}
990
+ self.dit_config = Qwen2_5OmniDiTConfig(**dit_config)
991
+ self.bigvgan_config = Qwen2_5OmniBigVGANConfig(**bigvgan_config)
992
+ super().__init__(**kwargs)
993
+
994
+
995
+ class Qwen2_5OmniConfig(PretrainedConfig):
996
+ """
997
+ This is the configuration class to store the configuration of a [`Qwen2_5OmniForConditionalGeneration`]. It is used to instantiate a Qwen2.5Omni
998
+ model according to the specified sub-models configurations, defining the model architecture.
999
+
1000
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the
1001
+ [Qwen/Qwen2.5-Omni-7B](https://huggingface.co/Qwen/Qwen2.5-Omni-7B) architecture.
1002
+
1003
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
1004
+ documentation from [`PretrainedConfig`] for more information.
1005
+
1006
+ Args:
1007
+ thinker_config (`dict`, *optional*): Configuration of the underlying thinker sub-model.
1008
+ talker_config (`dict`, *optional*): Configuration of the underlying talker sub-model.
1009
+ token2wav_config (`dict`, *optional*): Configuration of the underlying codec sub-model.
1010
+ enable_audio_output (`bool`, *optional*, defaults to `True`): Whether enable audio output and load talker and token2wav module.
1011
+
1012
+ Example:
1013
+
1014
+ ```python
1015
+ >>> from transformers import (
1016
+ ... Qwen2_5OmniThinkerConfig,
1017
+ ... Qwen2_5OmniTalkerConfig,
1018
+ ... Qwen2_5OmniToken2WavConfig,
1019
+ ... Qwen2_5OmniForConditionalGeneration,
1020
+ ... Qwen2_5OmniConfig,
1021
+ ... )
1022
+
1023
+ >>> # Initializing sub-modules configurations.
1024
+ >>> thinker_config = Qwen2_5OmniThinkerConfig()
1025
+ >>> talker_config = Qwen2_5OmniTalkerConfig()
1026
+ >>> token2wav_config = Qwen2_5OmniToken2WavConfig()
1027
+
1028
+
1029
+ >>> # Initializing a module style configuration
1030
+ >>> configuration = Qwen2_5OmniConfig.from_sub_model_configs(
1031
+ ... thinker_config, talker_config, token2wav_config
1032
+ ... )
1033
+
1034
+ >>> # Initializing a model (with random weights)
1035
+ >>> model = Qwen2_5OmniForConditionalGeneration(configuration)
1036
+
1037
+ >>> # Accessing the model configuration
1038
+ >>> configuration = model.config
1039
+ ```
1040
+ """
1041
+
1042
+ model_type = "qwen2_5_omni"
1043
+ sub_configs = {
1044
+ "thinker_config": Qwen2_5OmniThinkerConfig,
1045
+ "talker_config": Qwen2_5OmniTalkerConfig,
1046
+ "token2wav_config": Qwen2_5OmniToken2WavConfig,
1047
+ }
1048
+
1049
+ def __init__(
1050
+ self,
1051
+ thinker_config=None,
1052
+ talker_config=None,
1053
+ token2wav_config=None,
1054
+ enable_audio_output: bool = True,
1055
+ **kwargs,
1056
+ ):
1057
+ if thinker_config is None:
1058
+ thinker_config = {}
1059
+ logger.info("thinker_config is None. Initializing thinker model with default values")
1060
+
1061
+ if talker_config is None:
1062
+ talker_config = {}
1063
+ logger.info("talker_config is None. Initializing talker model with default values")
1064
+
1065
+ if token2wav_config is None:
1066
+ token2wav_config = {}
1067
+ logger.info("token2wav_config is None. Initializing token2wav model with default values")
1068
+
1069
+ self.thinker_config = Qwen2_5OmniThinkerConfig(**thinker_config)
1070
+ self.talker_config = Qwen2_5OmniTalkerConfig(**talker_config)
1071
+ self.token2wav_config = Qwen2_5OmniToken2WavConfig(**token2wav_config)
1072
+ self.enable_audio_output = enable_audio_output
1073
+
1074
+ super().__init__(**kwargs)
1075
+
1076
+ def get_text_config(self, decoder=False):
1077
+ """
1078
+ Returns the config that is meant to be used with text IO. On most models, it is the original config instance
1079
+ itself. On specific composite models, it is under a set of valid names.
1080
+
1081
+ Args:
1082
+ decoder (`Optional[bool]`, *optional*, defaults to `False`):
1083
+ If set to `True`, then only search for decoder config names.
1084
+ """
1085
+ # Overridden for deeply nested config like Qwen2-Omni. We don't have any omni model
1086
+ # except for Qwen yet. This has to be generalized if more deeply nested configs are
1087
+ # added. NOTE: currently method used only by vLLM
1088
+ return self.thinker_config.get_text_config()
1089
+
1090
+
1091
+ __all__ = ["Qwen2_5OmniConfig", "Qwen2_5OmniThinkerConfig", "Qwen2_5OmniTalkerConfig", "Qwen2_5OmniToken2WavConfig"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_5_omni/modular_qwen2_5_omni.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_5_omni/processing_qwen2_5_omni.py ADDED
@@ -0,0 +1,371 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """
17
+ Processor class for Qwen2.5Omni.
18
+ """
19
+
20
+ import logging
21
+ import re
22
+ from typing import Optional, Union
23
+
24
+ import numpy as np
25
+
26
+ from ...feature_extraction_utils import BatchFeature
27
+ from ...image_utils import ImageInput
28
+ from ...processing_utils import ImagesKwargs, ProcessingKwargs, ProcessorMixin, Unpack, VideosKwargs
29
+ from ...tokenization_utils_base import AudioInput, PreTokenizedInput, TextInput
30
+ from ...video_utils import VideoInput, make_batched_videos
31
+
32
+
33
+ class Qwen2_5_OmniVideosKwargs(VideosKwargs):
34
+ fps: Optional[list[Union[int, float]]] = None
35
+ use_audio_in_video: Optional[bool] = None
36
+ seconds_per_chunk: Optional[float] = None
37
+ position_id_per_seconds: Optional[int] = None
38
+ min_pixels: Optional[int]
39
+ max_pixels: Optional[int]
40
+ patch_size: Optional[int]
41
+ temporal_patch_size: Optional[int]
42
+ merge_size: Optional[int]
43
+
44
+
45
+ class Qwen2_5_OmniImagesKwargs(ImagesKwargs):
46
+ min_pixels: Optional[int]
47
+ max_pixels: Optional[int]
48
+ patch_size: Optional[int]
49
+ temporal_patch_size: Optional[int]
50
+ merge_size: Optional[int]
51
+
52
+
53
+ class Qwen2_5OmniProcessorKwargs(ProcessingKwargs, total=False):
54
+ videos_kwargs: Qwen2_5_OmniVideosKwargs
55
+ images_kwargs: Qwen2_5_OmniImagesKwargs
56
+ _defaults = {
57
+ "text_kwargs": {
58
+ "padding": False,
59
+ "padding_side": "left",
60
+ },
61
+ "videos_kwargs": {
62
+ "seconds_per_chunk": 2.0,
63
+ "position_id_per_seconds": 25,
64
+ "use_audio_in_video": False,
65
+ "min_pixels": 128 * 28 * 28,
66
+ "max_pixels": 768 * 28 * 28,
67
+ },
68
+ "audio_kwargs": {
69
+ "sampling_rate": 16000,
70
+ "padding": "max_length",
71
+ "return_attention_mask": True,
72
+ },
73
+ }
74
+
75
+
76
+ class Qwen2_5OmniProcessor(ProcessorMixin):
77
+ r"""
78
+ Constructs a Qwen2.5Omni processor.
79
+ [`Qwen2_5OmniProcessor`] offers all the functionalities of [`Qwen2VLImageProcessor`], [`WhisperFeatureExtractor`], and [`Qwen2TokenizerFast`]. See the
80
+ [`~Qwen2_5OmniProcessor.__call__`] and [`~Qwen2_5OmniProcessor.decode`] for more information.
81
+
82
+ Args:
83
+ image_processor ([`Qwen2VLImageProcessor`], *optional*):
84
+ The image processor.
85
+ video_processor ([`Qwen2VLVideoProcessor`], *optional*):
86
+ The video processor.
87
+ feature_extractor ([`WhisperFeatureExtractor`], *optional*):
88
+ The audio feature extractor.
89
+ tokenizer ([`Qwen2TokenizerFast`], *optional*):
90
+ The text tokenizer.
91
+ chat_template (`Optional[str]`, *optional*):
92
+ The Jinja template to use for formatting the conversation. If not provided, the default chat template is used.
93
+ """
94
+
95
+ attributes = ["image_processor", "video_processor", "feature_extractor", "tokenizer"]
96
+ image_processor_class = "AutoImageProcessor"
97
+ video_processor_class = "AutoVideoProcessor"
98
+ feature_extractor_class = "WhisperFeatureExtractor"
99
+ tokenizer_class = ("Qwen2Tokenizer", "Qwen2TokenizerFast")
100
+
101
+ def __init__(
102
+ self, image_processor=None, video_processor=None, feature_extractor=None, tokenizer=None, chat_template=None
103
+ ):
104
+ super().__init__(image_processor, video_processor, feature_extractor, tokenizer, chat_template=chat_template)
105
+ self.image_token = self.tokenizer.image_token
106
+ self.audio_token = self.tokenizer.audio_token
107
+ self.video_token = self.tokenizer.video_token
108
+ self.vision_bos_token = self.tokenizer.vision_bos_token
109
+ self.vision_eos_token = self.tokenizer.vision_eos_token
110
+ self.audio_bos_token = self.tokenizer.audio_bos_token
111
+ self.audio_eos_token = self.tokenizer.audio_eos_token
112
+
113
+ def __call__(
114
+ self,
115
+ text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
116
+ images: ImageInput = None,
117
+ videos: VideoInput = None,
118
+ audio: AudioInput = None,
119
+ **kwargs: Unpack[Qwen2_5OmniProcessorKwargs],
120
+ ) -> BatchFeature:
121
+ """
122
+ Main method to prepare for the model one or several sequences(s) and audio(s). This method forwards the `text`
123
+ and `kwargs` arguments to Qwen2TokenizerFast's [`~Qwen2TokenizerFast.__call__`] if `text` is not `None` to encode
124
+ the text. To prepare the audio(s), this method forwards the `audio` and `kwargs` arguments to
125
+ WhisperFeatureExtractor's [`~WhisperFeatureExtractor.__call__`] if `audio` is not `None`. To prepare the vision inputs,
126
+ this method forwards the `vision_infos` and `kwargs` arguments to Qwen2VLImageProcessor's [`~Qwen2VLImageProcessor.__call__`]
127
+ if `vision_infos` is not `None`. Please refer to the doctsring
128
+ of the above two methods for more information.
129
+
130
+ Args:
131
+ text (`str`, `list[str]`, `list[list[str]]`):
132
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
133
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
134
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
135
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
136
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
137
+ tensor. Both channels-first and channels-last formats are supported.
138
+ videos (`np.ndarray`, `torch.Tensor`, `list[np.ndarray]`, `list[torch.Tensor]`):
139
+ The image or batch of videos to be prepared. Each video can be a 4D NumPy array or PyTorch
140
+ tensor, or a nested list of 3D frames. Both channels-first and channels-last formats are supported.
141
+ audio (`np.ndarray`, `list[np.ndarray]`):
142
+ The audio or batch of audio to be prepared. Each audio can be a NumPy array.
143
+ """
144
+
145
+ if text is None:
146
+ raise ValueError("You need to specify either a `text` input to process.")
147
+
148
+ output_kwargs = self._merge_kwargs(
149
+ Qwen2_5OmniProcessorKwargs,
150
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
151
+ **kwargs,
152
+ )
153
+
154
+ seconds_per_chunk = output_kwargs["videos_kwargs"].pop("seconds_per_chunk")
155
+ position_id_per_seconds = output_kwargs["videos_kwargs"].pop("position_id_per_seconds")
156
+ use_audio_in_video = output_kwargs["videos_kwargs"].pop("use_audio_in_video")
157
+ fps = output_kwargs["videos_kwargs"].get("fps", 2.0)
158
+
159
+ if audio is not None:
160
+ output_kwargs["audio_kwargs"]["padding"] = "max_length" # Support "max_length" padding only here
161
+ audio_inputs = self.feature_extractor(audio, **output_kwargs["audio_kwargs"])
162
+ audio_inputs["feature_attention_mask"] = audio_inputs.pop(
163
+ "attention_mask"
164
+ ) # rename feature_attention_mask to prevent conflicts later on
165
+ audio_inputs["input_features"] = audio_inputs.pop(
166
+ "input_features"
167
+ ) # rename input_features to prevent conflicts later on
168
+ input_lengths = (audio_inputs["feature_attention_mask"].sum(-1) - 1) // 2 + 1
169
+ audio_lengths = iter((input_lengths - 2) // 2 + 1)
170
+ else:
171
+ audio_inputs = {}
172
+ audio_lengths = iter([])
173
+
174
+ if images is not None:
175
+ images_inputs = self.image_processor(images=images, **output_kwargs["images_kwargs"])
176
+ image_grid_thw = iter(images_inputs["image_grid_thw"])
177
+ else:
178
+ images_inputs = {}
179
+ image_grid_thw = iter([])
180
+
181
+ if videos is not None:
182
+ videos = make_batched_videos(videos)
183
+ videos_inputs = self.video_processor(videos=videos, **output_kwargs["videos_kwargs"])
184
+ fps = [fps] * len(videos)
185
+ videos_inputs["video_second_per_grid"] = [
186
+ self.video_processor.temporal_patch_size / fps[i] for i in range(len(fps))
187
+ ]
188
+ video_grid_thw = iter(videos_inputs["video_grid_thw"])
189
+ video_second_per_grid = iter(videos_inputs["video_second_per_grid"])
190
+ else:
191
+ videos_inputs = {}
192
+ video_grid_thw = iter([])
193
+ video_second_per_grid = iter([])
194
+
195
+ if not isinstance(text, list):
196
+ text = [text]
197
+
198
+ text = self.replace_multimodal_special_tokens(
199
+ text,
200
+ audio_lengths,
201
+ image_grid_thw,
202
+ video_grid_thw,
203
+ video_second_per_grid=video_second_per_grid,
204
+ use_audio_in_video=use_audio_in_video,
205
+ position_id_per_seconds=position_id_per_seconds,
206
+ seconds_per_chunk=seconds_per_chunk,
207
+ )
208
+
209
+ texts_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
210
+
211
+ return BatchFeature(
212
+ data={**texts_inputs, **images_inputs, **videos_inputs, **audio_inputs},
213
+ tensor_type=kwargs.get("return_tensors"),
214
+ )
215
+
216
+ def replace_multimodal_special_tokens(
217
+ self,
218
+ text,
219
+ audio_lengths,
220
+ image_grid_thw,
221
+ video_grid_thw,
222
+ video_second_per_grid,
223
+ use_audio_in_video,
224
+ position_id_per_seconds,
225
+ seconds_per_chunk,
226
+ ):
227
+ # Extend mm token length
228
+ merge_length_image = self.image_processor.merge_size**2
229
+ merge_length_video = self.video_processor.merge_size**2
230
+
231
+ processed_text = []
232
+ for sample in text:
233
+ positions = []
234
+ special_tokens = [re.escape(tok) for tok in [self.audio_token, self.image_token, self.video_token]]
235
+ pattern = "|".join(special_tokens)
236
+ positions = sorted([(match.start(), match.group()) for match in re.finditer(pattern, sample)])
237
+ positions.sort(key=lambda x: x[0])
238
+
239
+ for _, special_token in positions:
240
+ if special_token == self.audio_token:
241
+ sample = sample.replace(self.audio_token, "<|audio_placeholder|>" * next(audio_lengths), 1)
242
+ elif special_token == self.image_token:
243
+ image_seq_length = next(image_grid_thw).prod() // merge_length_image
244
+ sample = sample.replace(self.image_token, "<|image_placeholder|>" * image_seq_length, 1)
245
+ elif special_token == self.video_token:
246
+ if not use_audio_in_video:
247
+ video_seq_length = next(video_grid_thw).prod() // merge_length_video
248
+ sample = sample.replace(self.video_token, "<|video_placeholder|>" * video_seq_length, 1)
249
+ else:
250
+ audio_token_indices = np.arange(next(audio_lengths))
251
+ curr_video_grid_thw = next(video_grid_thw)
252
+ height = curr_video_grid_thw[1] // self.video_processor.merge_size
253
+ width = curr_video_grid_thw[2] // self.video_processor.merge_size
254
+ video_token_indices = np.arange(curr_video_grid_thw[0]).reshape(-1, 1, 1)
255
+ video_token_indices = np.broadcast_to(
256
+ video_token_indices, (video_token_indices.shape[0], height, width)
257
+ ).reshape(-1)
258
+ video_token_indices = (
259
+ video_token_indices * next(video_second_per_grid) * position_id_per_seconds
260
+ )
261
+
262
+ tokens_per_chunk = int(position_id_per_seconds * seconds_per_chunk)
263
+ video_chunk_indexes = self.get_chunked_index(video_token_indices, tokens_per_chunk)
264
+ audio_chunk_indexes = self.get_chunked_index(audio_token_indices, tokens_per_chunk)
265
+
266
+ placeholder_string = self.vision_bos_token + self.audio_bos_token
267
+ for j in range(max(len(video_chunk_indexes), len(audio_chunk_indexes))):
268
+ if j < len(video_chunk_indexes):
269
+ video_seq_length = video_chunk_indexes[j][1] - video_chunk_indexes[j][0]
270
+ placeholder_string += "<|video_placeholder|>" * video_seq_length
271
+ if j < len(audio_chunk_indexes):
272
+ audio_seq_length = audio_chunk_indexes[j][1] - audio_chunk_indexes[j][0]
273
+ placeholder_string += "<|audio_placeholder|>" * audio_seq_length
274
+ placeholder_string += self.audio_eos_token + self.vision_eos_token
275
+ sample = sample.replace(
276
+ self.vision_bos_token + self.video_token + self.vision_eos_token,
277
+ placeholder_string,
278
+ 1,
279
+ )
280
+
281
+ sample = sample.replace("<|audio_placeholder|>", self.audio_token)
282
+ sample = sample.replace("<|image_placeholder|>", self.image_token)
283
+ sample = sample.replace("<|video_placeholder|>", self.video_token)
284
+ processed_text.append(sample)
285
+ return processed_text
286
+
287
+ def get_chunked_index(self, token_indices: np.ndarray, tokens_per_chunk: int) -> list[tuple[int, int]]:
288
+ """
289
+ Splits token index list into chunks based on token value ranges.
290
+
291
+ Given a list of token indices, returns a list of (start, end) index tuples representing
292
+ slices of the list where the token values fall within successive ranges of `t_ntoken_per_chunk`.
293
+
294
+ For example, if `t_ntoken_per_chunk` is 1000, the function will create chunks such that:
295
+ - the first chunk contains token values < 1000,
296
+ - the second chunk contains values >= 1000 and < 2000, and so on.
297
+
298
+ Parameters:
299
+ token_indices (`np.ndarray`): A monotonically increasing list of token index values.
300
+ t_ntoken_per_chunk (`int`): Number of tokens per chunk (used as the chunk size threshold).
301
+
302
+ Returns:
303
+ `list[tuple[int, int]]`: A list of tuples, each representing the start (inclusive)
304
+ and end (exclusive) indices of a chunk in `token_indices`.
305
+ """
306
+
307
+ def _iter():
308
+ i, start_idx = 0, 0 # skip bos token
309
+ current_chunk = 1
310
+ while i < len(token_indices): # skip eos token
311
+ if token_indices[i] >= current_chunk * tokens_per_chunk:
312
+ yield (start_idx, i)
313
+ start_idx = i
314
+ current_chunk += 1
315
+ i += 1
316
+ yield (start_idx, len(token_indices))
317
+
318
+ return list(_iter())
319
+
320
+ def batch_decode(self, *args, **kwargs):
321
+ """
322
+ This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
323
+ refer to the docstring of this method for more information.
324
+ """
325
+ return self.tokenizer.batch_decode(*args, **kwargs)
326
+
327
+ def decode(self, *args, **kwargs):
328
+ """
329
+ This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
330
+ the docstring of this method for more information.
331
+ """
332
+ return self.tokenizer.decode(*args, **kwargs)
333
+
334
+ def apply_chat_template(self, conversations, chat_template=None, **kwargs):
335
+ is_batched = False
336
+ if isinstance(conversations[0], dict):
337
+ conversations = [conversations]
338
+ is_batched = True
339
+
340
+ for conversation in conversations:
341
+ if (
342
+ conversation[0]["role"] != "system"
343
+ or conversation[0]["content"][0]["text"]
344
+ != "You are Qwen, a virtual human developed by the Qwen Team, Alibaba Group, capable of perceiving auditory and visual inputs, as well as generating text and speech."
345
+ ):
346
+ logging.warning(
347
+ "System prompt modified, audio output may not work as expected. "
348
+ + "Audio output mode only works when using default system prompt 'You are Qwen, a virtual human developed by the Qwen Team, Alibaba Group, capable of perceiving auditory and visual inputs, as well as generating text and speech.'"
349
+ )
350
+ if is_batched:
351
+ conversations = conversations[0]
352
+
353
+ return super().apply_chat_template(conversations, chat_template, **kwargs)
354
+
355
+ @property
356
+ def model_input_names(self):
357
+ tokenizer_input_names = self.tokenizer.model_input_names
358
+ feature_extractor_input_names = self.feature_extractor.model_input_names
359
+ image_processor_input_names = self.image_processor.model_input_names
360
+ return list(
361
+ dict.fromkeys(
362
+ tokenizer_input_names
363
+ + feature_extractor_input_names
364
+ + image_processor_input_names
365
+ + ["feature_attention_mask"]
366
+ + ["video_second_per_grid"]
367
+ )
368
+ )
369
+
370
+
371
+ __all__ = ["Qwen2_5OmniProcessor"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_5_vl/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The Qwen Team 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
+ 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_qwen2_5_vl import *
22
+ from .modeling_qwen2_5_vl import *
23
+ from .processing_qwen2_5_vl 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__)
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_5_vl/configuration_qwen2_5_vl.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/qwen2_5_vl/modular_qwen2_5_vl.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_qwen2_5_vl.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2025 The Qwen Team and The HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
11
+ # and OPT implementations in this library. It has been modified from its
12
+ # original forms to accommodate minor architectural differences compared
13
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
14
+ #
15
+ # Licensed under the Apache License, Version 2.0 (the "License");
16
+ # you may not use this file except in compliance with the License.
17
+ # You may obtain a copy of the License at
18
+ #
19
+ # http://www.apache.org/licenses/LICENSE-2.0
20
+ #
21
+ # Unless required by applicable law or agreed to in writing, software
22
+ # distributed under the License is distributed on an "AS IS" BASIS,
23
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24
+ # See the License for the specific language governing permissions and
25
+ # limitations under the License.
26
+ from ...configuration_utils import PretrainedConfig, layer_type_validation
27
+ from ...modeling_rope_utils import rope_config_validation
28
+
29
+
30
+ class Qwen2_5_VLVisionConfig(PretrainedConfig):
31
+ model_type = "qwen2_5_vl"
32
+ base_config_key = "vision_config"
33
+
34
+ def __init__(
35
+ self,
36
+ depth=32,
37
+ hidden_size=3584,
38
+ hidden_act="silu",
39
+ intermediate_size=3420,
40
+ num_heads=16,
41
+ in_channels=3,
42
+ patch_size=14,
43
+ spatial_merge_size=2,
44
+ temporal_patch_size=2,
45
+ tokens_per_second=4,
46
+ window_size=112,
47
+ out_hidden_size=3584,
48
+ fullatt_block_indexes=[7, 15, 23, 31],
49
+ initializer_range=0.02,
50
+ **kwargs,
51
+ ):
52
+ super().__init__(**kwargs)
53
+
54
+ self.depth = depth
55
+ self.hidden_size = hidden_size
56
+ self.hidden_act = hidden_act
57
+ self.intermediate_size = intermediate_size
58
+ self.num_heads = num_heads
59
+ self.in_channels = in_channels
60
+ self.patch_size = patch_size
61
+ self.spatial_merge_size = spatial_merge_size
62
+ self.temporal_patch_size = temporal_patch_size
63
+ self.tokens_per_second = tokens_per_second
64
+ self.window_size = window_size
65
+ self.fullatt_block_indexes = fullatt_block_indexes
66
+ self.out_hidden_size = out_hidden_size
67
+ self.initializer_range = initializer_range
68
+
69
+
70
+ class Qwen2_5_VLTextConfig(PretrainedConfig):
71
+ r"""
72
+ This is the configuration class to store the configuration of a [`Qwen2_5_VLTextModel`]. It is used to instantiate a
73
+ Qwen2-VL model according to the specified arguments, defining the model architecture. Instantiating a configuration
74
+ with the defaults will yield a similar configuration to that of
75
+ Qwen2-VL-7B-Instruct [Qwen/Qwen2-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2-VL-7B-Instruct).
76
+
77
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
78
+ documentation from [`PretrainedConfig`] for more information.
79
+
80
+ Args:
81
+ vocab_size (`int`, *optional*, defaults to 152064):
82
+ Vocabulary size of the Qwen2_5_VL model. Defines the number of different tokens that can be represented by the
83
+ `inputs_ids` passed when calling [`Qwen2_5_VLModel`]
84
+ hidden_size (`int`, *optional*, defaults to 8192):
85
+ Dimension of the hidden representations.
86
+ intermediate_size (`int`, *optional*, defaults to 29568):
87
+ Dimension of the MLP representations.
88
+ num_hidden_layers (`int`, *optional*, defaults to 80):
89
+ Number of hidden layers in the Transformer encoder.
90
+ num_attention_heads (`int`, *optional*, defaults to 64):
91
+ Number of attention heads for each attention layer in the Transformer encoder.
92
+ num_key_value_heads (`int`, *optional*, defaults to 8):
93
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
94
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
95
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
96
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
97
+ by meanpooling all the original heads within that group. For more details, check out [this
98
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`.
99
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
100
+ The non-linear activation function (function or string) in the decoder.
101
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
102
+ The maximum sequence length that this model might ever be used with.
103
+ initializer_range (`float`, *optional*, defaults to 0.02):
104
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
105
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
106
+ The epsilon used by the rms normalization layers.
107
+ use_cache (`bool`, *optional*, defaults to `True`):
108
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
109
+ relevant if `config.is_decoder=True`.
110
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
111
+ Whether the model's input and output word embeddings should be tied.
112
+ rope_theta (`float`, *optional*, defaults to 1000000.0):
113
+ The base period of the RoPE embeddings.
114
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
115
+ Whether to use sliding window attention.
116
+ sliding_window (`int`, *optional*, defaults to 4096):
117
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
118
+ max_window_layers (`int`, *optional*, defaults to 80):
119
+ The number of layers using full attention. The first `max_window_layers` layers will use full attention, while any
120
+ additional layer afterwards will use SWA (Sliding Window Attention).
121
+ layer_types (`list`, *optional*):
122
+ Attention pattern for each layer.
123
+ attention_dropout (`float`, *optional*, defaults to 0.0):
124
+ The dropout ratio for the attention probabilities.
125
+ rope_scaling (`Dict`, *optional*):
126
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
127
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
128
+ accordingly.
129
+ Expected contents:
130
+ `rope_type` (`str`):
131
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
132
+ 'llama3'], with 'default' being the original RoPE implementation.
133
+ `factor` (`float`, *optional*):
134
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
135
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
136
+ original maximum pre-trained length.
137
+ `original_max_position_embeddings` (`int`, *optional*):
138
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
139
+ pretraining.
140
+ `attention_factor` (`float`, *optional*):
141
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
142
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
143
+ `factor` field to infer the suggested value.
144
+ `beta_fast` (`float`, *optional*):
145
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
146
+ ramp function. If unspecified, it defaults to 32.
147
+ `beta_slow` (`float`, *optional*):
148
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
149
+ ramp function. If unspecified, it defaults to 1.
150
+ `short_factor` (`list[float]`, *optional*):
151
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
152
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
153
+ size divided by the number of attention heads divided by 2
154
+ `long_factor` (`list[float]`, *optional*):
155
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
156
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
157
+ size divided by the number of attention heads divided by 2
158
+ `low_freq_factor` (`float`, *optional*):
159
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
160
+ `high_freq_factor` (`float`, *optional*):
161
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
162
+ image_token_id (`int`, *optional*):
163
+ Token index used as placeholder for image embeddings.
164
+ video_token_id (`int`, *optional*):
165
+ Token index used as placeholder for video embeddings.
166
+
167
+ ```python
168
+ >>> from transformers import Qwen2_5_VLTextModel, Qwen2_5_VLConfig
169
+
170
+ >>> # Initializing a Qwen2_5_VL style configuration
171
+ >>> configuration = Qwen2_5_VLConfig()
172
+
173
+ >>> # Initializing a model from the Qwen2-VL-7B style configuration
174
+ >>> model = Qwen2_5_VLTextModel(configuration)
175
+
176
+ >>> # Accessing the model configuration
177
+ >>> configuration = model.config
178
+ ```"""
179
+
180
+ model_type = "qwen2_5_vl_text"
181
+ base_config_key = "text_config"
182
+ keys_to_ignore_at_inference = ["past_key_values"]
183
+ # Default tensor parallel plan for base model `Qwen2_5_VL`
184
+ base_model_tp_plan = {
185
+ "layers.*.self_attn.q_proj": "colwise",
186
+ "layers.*.self_attn.k_proj": "colwise",
187
+ "layers.*.self_attn.v_proj": "colwise",
188
+ "layers.*.self_attn.o_proj": "rowwise",
189
+ "layers.*.mlp.gate_proj": "colwise",
190
+ "layers.*.mlp.up_proj": "colwise",
191
+ "layers.*.mlp.down_proj": "rowwise",
192
+ }
193
+ base_model_pp_plan = {
194
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
195
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
196
+ "norm": (["hidden_states"], ["hidden_states"]),
197
+ }
198
+
199
+ def __init__(
200
+ self,
201
+ vocab_size=152064,
202
+ hidden_size=8192,
203
+ intermediate_size=29568,
204
+ num_hidden_layers=80,
205
+ num_attention_heads=64,
206
+ num_key_value_heads=8,
207
+ hidden_act="silu",
208
+ max_position_embeddings=32768,
209
+ initializer_range=0.02,
210
+ rms_norm_eps=1e-05,
211
+ use_cache=True,
212
+ tie_word_embeddings=False,
213
+ rope_theta=1000000.0,
214
+ use_sliding_window=False,
215
+ sliding_window=4096,
216
+ max_window_layers=80,
217
+ layer_types=None,
218
+ attention_dropout=0.0,
219
+ rope_scaling=None,
220
+ image_token_id=None,
221
+ video_token_id=None,
222
+ **kwargs,
223
+ ):
224
+ self.vocab_size = vocab_size
225
+ self.max_position_embeddings = max_position_embeddings
226
+ self.hidden_size = hidden_size
227
+ self.intermediate_size = intermediate_size
228
+ self.num_hidden_layers = num_hidden_layers
229
+ self.num_attention_heads = num_attention_heads
230
+ self.use_sliding_window = use_sliding_window
231
+ self.sliding_window = sliding_window if self.use_sliding_window else None
232
+ self.max_window_layers = max_window_layers
233
+
234
+ # for backward compatibility
235
+ if num_key_value_heads is None:
236
+ num_key_value_heads = num_attention_heads
237
+
238
+ self.num_key_value_heads = num_key_value_heads
239
+ self.hidden_act = hidden_act
240
+ self.initializer_range = initializer_range
241
+ self.rms_norm_eps = rms_norm_eps
242
+ self.use_cache = use_cache
243
+ self.rope_theta = rope_theta
244
+ self.attention_dropout = attention_dropout
245
+ self.rope_scaling = rope_scaling
246
+
247
+ self.layer_types = layer_types
248
+ if self.layer_types is None:
249
+ self.layer_types = [
250
+ "sliding_attention"
251
+ if self.sliding_window is not None and i >= self.max_window_layers
252
+ else "full_attention"
253
+ for i in range(self.num_hidden_layers)
254
+ ]
255
+ layer_type_validation(self.layer_types)
256
+
257
+ # Validate the correctness of rotary position embeddings parameters
258
+ # BC: if there is a 'type' field, move it to 'rope_type'.
259
+ # and change type from 'mrope' to 'default' because `mrope` does default RoPE calculations
260
+ # one can set it to "linear"/"dynamic" etc. to have scaled RoPE
261
+ # TODO: @raushan update config in the hub
262
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
263
+ if self.rope_scaling["type"] == "mrope":
264
+ self.rope_scaling["type"] = "default"
265
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
266
+ rope_config_validation(self, ignore_keys={"mrope_section"})
267
+ self.image_token_id = image_token_id
268
+ self.video_token_id = video_token_id
269
+
270
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
271
+
272
+
273
+ class Qwen2_5_VLConfig(PretrainedConfig):
274
+ r"""
275
+ This is the configuration class to store the configuration of a [`Qwen2_5_VLModel`]. It is used to instantiate a
276
+ Qwen2-VL model according to the specified arguments, defining the model architecture. Instantiating a configuration
277
+ with the defaults will yield a similar configuration to that of
278
+ Qwen2-VL-7B-Instruct [Qwen/Qwen2-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2-VL-7B-Instruct).
279
+
280
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
281
+ documentation from [`PretrainedConfig`] for more information.
282
+
283
+
284
+ Args:
285
+ text_config (`Union[PreTrainedConfig, dict]`, *optional*, defaults to `Qwen2_5_VLTextConfig`):
286
+ The config object or dictionary of the text backbone.
287
+ vision_config (`Union[PreTrainedConfig, dict]`, *optional*, defaults to `Qwen2_5_VLVisionConfig`):
288
+ The config object or dictionary of the vision backbone.
289
+ image_token_id (`int`, *optional*, defaults to 151655):
290
+ The image token index to encode the image prompt.
291
+ video_token_id (`int`, *optional*, defaults to 151656):
292
+ The video token index to encode the image prompt.
293
+
294
+ ```python
295
+ >>> from transformers import Qwen2_5_VLForConditionalGeneration, Qwen2_5_VLConfig
296
+
297
+ >>> # Initializing a Qwen2_5_VL style configuration
298
+ >>> configuration = Qwen2_5_VLConfig()
299
+
300
+ >>> # Initializing a model from the Qwen2-VL-7B style configuration
301
+ >>> model = Qwen2_5_VLForConditionalGeneration(configuration)
302
+
303
+ >>> # Accessing the model configuration
304
+ >>> configuration = model.config
305
+ ```"""
306
+
307
+ model_type = "qwen2_5_vl"
308
+ sub_configs = {"vision_config": Qwen2_5_VLVisionConfig, "text_config": Qwen2_5_VLTextConfig}
309
+ keys_to_ignore_at_inference = ["past_key_values"]
310
+
311
+ def __init__(
312
+ self,
313
+ text_config=None,
314
+ vision_config=None,
315
+ image_token_id=151655,
316
+ video_token_id=151656,
317
+ **kwargs,
318
+ ):
319
+ if isinstance(vision_config, dict):
320
+ self.vision_config = self.sub_configs["vision_config"](**vision_config)
321
+ elif vision_config is None:
322
+ self.vision_config = self.sub_configs["vision_config"]()
323
+
324
+ if isinstance(text_config, dict):
325
+ self.text_config = self.sub_configs["text_config"](**text_config)
326
+ elif text_config is None:
327
+ # For BC use all kwargs to init `TextConfig`
328
+ self.text_config = self.sub_configs["text_config"](**kwargs)
329
+
330
+ self.image_token_id = image_token_id
331
+ self.video_token_id = video_token_id
332
+
333
+ super().__init__(**kwargs)
334
+
335
+
336
+ __all__ = ["Qwen2_5_VLConfig", "Qwen2_5_VLTextConfig"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py ADDED
@@ -0,0 +1,1749 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/qwen2_5_vl/modular_qwen2_5_vl.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_qwen2_5_vl.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2025 The Qwen Team and The HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
11
+ # and OPT implementations in this library. It has been modified from its
12
+ # original forms to accommodate minor architectural differences compared
13
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
14
+ #
15
+ # Licensed under the Apache License, Version 2.0 (the "License");
16
+ # you may not use this file except in compliance with the License.
17
+ # You may obtain a copy of the License at
18
+ #
19
+ # http://www.apache.org/licenses/LICENSE-2.0
20
+ #
21
+ # Unless required by applicable law or agreed to in writing, software
22
+ # distributed under the License is distributed on an "AS IS" BASIS,
23
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24
+ # See the License for the specific language governing permissions and
25
+ # limitations under the License.
26
+
27
+ from dataclasses import dataclass
28
+ from typing import Any, Callable, Optional, Union
29
+
30
+ import torch
31
+ import torch.nn as nn
32
+ import torch.nn.functional as F
33
+
34
+ from ...activations import ACT2FN
35
+ from ...cache_utils import Cache, DynamicCache
36
+ from ...generation import GenerationMixin
37
+ from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask
38
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
39
+ from ...modeling_layers import GradientCheckpointingLayer
40
+ from ...modeling_outputs import BaseModelOutputWithPast, ModelOutput
41
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
42
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
43
+ from ...processing_utils import Unpack
44
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, is_torchdynamo_compiling, logging
45
+ from ...utils.deprecation import deprecate_kwarg
46
+ from .configuration_qwen2_5_vl import Qwen2_5_VLConfig, Qwen2_5_VLTextConfig, Qwen2_5_VLVisionConfig
47
+
48
+
49
+ logger = logging.get_logger(__name__)
50
+
51
+
52
+ class Qwen2_5_VLMLP(nn.Module):
53
+ def __init__(self, config, bias: bool = False):
54
+ super().__init__()
55
+ self.hidden_size = config.hidden_size
56
+ self.intermediate_size = config.intermediate_size
57
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=bias)
58
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=bias)
59
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=bias)
60
+ self.act_fn = ACT2FN[config.hidden_act]
61
+
62
+ def forward(self, hidden_state):
63
+ return self.down_proj(self.act_fn(self.gate_proj(hidden_state)) * self.up_proj(hidden_state))
64
+
65
+
66
+ class Qwen2_5_VisionPatchEmbed(nn.Module):
67
+ def __init__(
68
+ self,
69
+ patch_size: int = 14,
70
+ temporal_patch_size: int = 2,
71
+ in_channels: int = 3,
72
+ embed_dim: int = 1152,
73
+ ) -> None:
74
+ super().__init__()
75
+ self.patch_size = patch_size
76
+ self.temporal_patch_size = temporal_patch_size
77
+ self.in_channels = in_channels
78
+ self.embed_dim = embed_dim
79
+
80
+ kernel_size = [temporal_patch_size, patch_size, patch_size]
81
+ self.proj = nn.Conv3d(in_channels, embed_dim, kernel_size=kernel_size, stride=kernel_size, bias=False)
82
+
83
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
84
+ target_dtype = self.proj.weight.dtype
85
+ hidden_states = hidden_states.view(
86
+ -1, self.in_channels, self.temporal_patch_size, self.patch_size, self.patch_size
87
+ )
88
+ hidden_states = self.proj(hidden_states.to(dtype=target_dtype)).view(-1, self.embed_dim)
89
+ return hidden_states
90
+
91
+
92
+ class Qwen2_5_VisionRotaryEmbedding(nn.Module):
93
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
94
+
95
+ def __init__(self, dim: int, theta: float = 10000.0) -> None:
96
+ super().__init__()
97
+ inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim))
98
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
99
+
100
+ def forward(self, seqlen: int) -> torch.Tensor:
101
+ seq = torch.arange(seqlen, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
102
+ freqs = torch.outer(seq, self.inv_freq)
103
+ return freqs
104
+
105
+
106
+ class Qwen2RMSNorm(nn.Module):
107
+ def __init__(self, hidden_size, eps=1e-6):
108
+ """
109
+ Qwen2RMSNorm is equivalent to T5LayerNorm
110
+ """
111
+ super().__init__()
112
+ self.weight = nn.Parameter(torch.ones(hidden_size))
113
+ self.variance_epsilon = eps
114
+
115
+ def forward(self, hidden_states):
116
+ input_dtype = hidden_states.dtype
117
+ hidden_states = hidden_states.to(torch.float32)
118
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
119
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
120
+ return self.weight * hidden_states.to(input_dtype)
121
+
122
+ def extra_repr(self):
123
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
124
+
125
+
126
+ class Qwen2_5_VLPatchMerger(nn.Module):
127
+ def __init__(self, dim: int, context_dim: int, spatial_merge_size: int = 2) -> None:
128
+ super().__init__()
129
+ self.hidden_size = context_dim * (spatial_merge_size**2)
130
+ self.ln_q = Qwen2RMSNorm(context_dim, eps=1e-6)
131
+ self.mlp = nn.Sequential(
132
+ nn.Linear(self.hidden_size, self.hidden_size),
133
+ nn.GELU(),
134
+ nn.Linear(self.hidden_size, dim),
135
+ )
136
+
137
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
138
+ x = self.mlp(self.ln_q(x).view(-1, self.hidden_size))
139
+ return x
140
+
141
+
142
+ def rotate_half(x):
143
+ """Rotates half the hidden dims of the input."""
144
+ x1 = x[..., : x.shape[-1] // 2]
145
+ x2 = x[..., x.shape[-1] // 2 :]
146
+ return torch.cat((-x2, x1), dim=-1)
147
+
148
+
149
+ def apply_rotary_pos_emb_vision(
150
+ q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor
151
+ ) -> tuple[torch.Tensor, torch.Tensor]:
152
+ orig_q_dtype = q.dtype
153
+ orig_k_dtype = k.dtype
154
+ q, k = q.float(), k.float()
155
+ cos, sin = cos.unsqueeze(-2).float(), sin.unsqueeze(-2).float()
156
+ q_embed = (q * cos) + (rotate_half(q) * sin)
157
+ k_embed = (k * cos) + (rotate_half(k) * sin)
158
+ q_embed = q_embed.to(orig_q_dtype)
159
+ k_embed = k_embed.to(orig_k_dtype)
160
+ return q_embed, k_embed
161
+
162
+
163
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
164
+ """
165
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
166
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
167
+ """
168
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
169
+ if n_rep == 1:
170
+ return hidden_states
171
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
172
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
173
+
174
+
175
+ def eager_attention_forward(
176
+ module: nn.Module,
177
+ query: torch.Tensor,
178
+ key: torch.Tensor,
179
+ value: torch.Tensor,
180
+ attention_mask: Optional[torch.Tensor],
181
+ scaling: float,
182
+ dropout: float = 0.0,
183
+ **kwargs,
184
+ ):
185
+ key_states = repeat_kv(key, module.num_key_value_groups)
186
+ value_states = repeat_kv(value, module.num_key_value_groups)
187
+
188
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
189
+ if attention_mask is not None:
190
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
191
+ attn_weights = attn_weights + causal_mask
192
+
193
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
194
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
195
+ attn_output = torch.matmul(attn_weights, value_states)
196
+ attn_output = attn_output.transpose(1, 2).contiguous()
197
+
198
+ return attn_output, attn_weights
199
+
200
+
201
+ class Qwen2_5_VLVisionAttention(nn.Module):
202
+ def __init__(self, config: Qwen2_5_VLVisionConfig) -> None:
203
+ super().__init__()
204
+ self.dim = config.hidden_size
205
+ self.num_heads = config.num_heads
206
+ self.head_dim = self.dim // self.num_heads
207
+ self.num_key_value_groups = 1 # needed for eager attention
208
+ self.qkv = nn.Linear(self.dim, self.dim * 3, bias=True)
209
+ self.proj = nn.Linear(self.dim, self.dim)
210
+ self.scaling = self.head_dim**-0.5
211
+ self.config = config
212
+ self.attention_dropout = 0.0
213
+ self.is_causal = False
214
+
215
+ def forward(
216
+ self,
217
+ hidden_states: torch.Tensor,
218
+ cu_seqlens: torch.Tensor,
219
+ rotary_pos_emb: Optional[torch.Tensor] = None,
220
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
221
+ **kwargs,
222
+ ) -> torch.Tensor:
223
+ seq_length = hidden_states.shape[0]
224
+ query_states, key_states, value_states = (
225
+ self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
226
+ )
227
+ if position_embeddings is None:
228
+ logger.warning_once(
229
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
230
+ "through `rotary_pos_emb` (2D tensor of RoPE theta values), to using externally computed "
231
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.54 `rotary_pos_emb` will be "
232
+ "removed and `position_embeddings` will be mandatory."
233
+ )
234
+ emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1)
235
+ cos = emb.cos()
236
+ sin = emb.sin()
237
+ else:
238
+ cos, sin = position_embeddings
239
+ query_states, key_states = apply_rotary_pos_emb_vision(query_states, key_states, cos, sin)
240
+
241
+ query_states = query_states.transpose(0, 1).unsqueeze(0)
242
+ key_states = key_states.transpose(0, 1).unsqueeze(0)
243
+ value_states = value_states.transpose(0, 1).unsqueeze(0)
244
+
245
+ attention_interface: Callable = eager_attention_forward
246
+ if self.config._attn_implementation != "eager":
247
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
248
+
249
+ if self.config._attn_implementation == "flash_attention_2":
250
+ # Flash Attention 2: Use cu_seqlens for variable length attention
251
+ max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max()
252
+ attn_output, _ = attention_interface(
253
+ self,
254
+ query_states,
255
+ key_states,
256
+ value_states,
257
+ attention_mask=None,
258
+ scaling=self.scaling,
259
+ dropout=0.0 if not self.training else self.attention_dropout,
260
+ cu_seq_lens_q=cu_seqlens,
261
+ cu_seq_lens_k=cu_seqlens,
262
+ max_length_q=max_seqlen,
263
+ max_length_k=max_seqlen,
264
+ is_causal=False,
265
+ **kwargs,
266
+ )
267
+ else:
268
+ # Other implementations: Process each chunk separately
269
+ lengths = cu_seqlens[1:] - cu_seqlens[:-1]
270
+ splits = [
271
+ torch.split(tensor, lengths.tolist(), dim=2) for tensor in (query_states, key_states, value_states)
272
+ ]
273
+
274
+ attn_outputs = [
275
+ attention_interface(
276
+ self,
277
+ q,
278
+ k,
279
+ v,
280
+ attention_mask=None,
281
+ scaling=self.scaling,
282
+ dropout=0.0 if not self.training else self.attention_dropout,
283
+ is_causal=False,
284
+ **kwargs,
285
+ )[0]
286
+ for q, k, v in zip(*splits)
287
+ ]
288
+ attn_output = torch.cat(attn_outputs, dim=1)
289
+
290
+ attn_output = attn_output.reshape(seq_length, -1).contiguous()
291
+ attn_output = self.proj(attn_output)
292
+ return attn_output
293
+
294
+
295
+ class Qwen2_5_VLVisionBlock(GradientCheckpointingLayer):
296
+ def __init__(self, config, attn_implementation: str = "sdpa") -> None:
297
+ super().__init__()
298
+ self.norm1 = Qwen2RMSNorm(config.hidden_size, eps=1e-6)
299
+ self.norm2 = Qwen2RMSNorm(config.hidden_size, eps=1e-6)
300
+ self.attn = Qwen2_5_VLVisionAttention(config=config)
301
+ self.mlp = Qwen2_5_VLMLP(config, bias=True)
302
+
303
+ def forward(
304
+ self,
305
+ hidden_states: torch.Tensor,
306
+ cu_seqlens: torch.Tensor,
307
+ rotary_pos_emb: Optional[torch.Tensor] = None,
308
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
309
+ **kwargs,
310
+ ) -> torch.Tensor:
311
+ hidden_states = hidden_states + self.attn(
312
+ self.norm1(hidden_states),
313
+ cu_seqlens=cu_seqlens,
314
+ rotary_pos_emb=rotary_pos_emb,
315
+ position_embeddings=position_embeddings,
316
+ **kwargs,
317
+ )
318
+ hidden_states = hidden_states + self.mlp(self.norm2(hidden_states))
319
+ return hidden_states
320
+
321
+
322
+ @auto_docstring
323
+ class Qwen2_5_VLPreTrainedModel(PreTrainedModel):
324
+ config: Qwen2_5_VLConfig
325
+ base_model_prefix = "model"
326
+ supports_gradient_checkpointing = True
327
+ _no_split_modules = ["Qwen2_5_VLDecoderLayer", "Qwen2_5_VLVisionBlock"]
328
+ _skip_keys_device_placement = "past_key_values"
329
+ _supports_flash_attn = True
330
+ _supports_sdpa = True
331
+
332
+ _can_compile_fullgraph = True
333
+ _supports_attention_backend = True
334
+
335
+
336
+ class Qwen2_5_VisionTransformerPretrainedModel(Qwen2_5_VLPreTrainedModel):
337
+ config: Qwen2_5_VLVisionConfig
338
+ _no_split_modules = ["Qwen2_5_VLVisionBlock"]
339
+
340
+ def __init__(self, config, *inputs, **kwargs) -> None:
341
+ super().__init__(config, *inputs, **kwargs)
342
+ self.spatial_merge_size = config.spatial_merge_size
343
+ self.patch_size = config.patch_size
344
+ self.fullatt_block_indexes = config.fullatt_block_indexes
345
+ self.window_size = config.window_size
346
+ self.spatial_merge_unit = self.spatial_merge_size * self.spatial_merge_size
347
+
348
+ self.patch_embed = Qwen2_5_VisionPatchEmbed(
349
+ patch_size=config.patch_size,
350
+ temporal_patch_size=config.temporal_patch_size,
351
+ in_channels=config.in_channels,
352
+ embed_dim=config.hidden_size,
353
+ )
354
+
355
+ head_dim = config.hidden_size // config.num_heads
356
+ self.rotary_pos_emb = Qwen2_5_VisionRotaryEmbedding(head_dim // 2)
357
+
358
+ self.blocks = nn.ModuleList([Qwen2_5_VLVisionBlock(config) for _ in range(config.depth)])
359
+ self.merger = Qwen2_5_VLPatchMerger(
360
+ dim=config.out_hidden_size,
361
+ context_dim=config.hidden_size,
362
+ spatial_merge_size=config.spatial_merge_size,
363
+ )
364
+ self.gradient_checkpointing = False
365
+
366
+ def rot_pos_emb(self, grid_thw):
367
+ pos_ids = []
368
+ for t, h, w in grid_thw:
369
+ hpos_ids = torch.arange(h).unsqueeze(1).expand(-1, w)
370
+ hpos_ids = hpos_ids.reshape(
371
+ h // self.spatial_merge_size,
372
+ self.spatial_merge_size,
373
+ w // self.spatial_merge_size,
374
+ self.spatial_merge_size,
375
+ )
376
+ hpos_ids = hpos_ids.permute(0, 2, 1, 3)
377
+ hpos_ids = hpos_ids.flatten()
378
+
379
+ wpos_ids = torch.arange(w).unsqueeze(0).expand(h, -1)
380
+ wpos_ids = wpos_ids.reshape(
381
+ h // self.spatial_merge_size,
382
+ self.spatial_merge_size,
383
+ w // self.spatial_merge_size,
384
+ self.spatial_merge_size,
385
+ )
386
+ wpos_ids = wpos_ids.permute(0, 2, 1, 3)
387
+ wpos_ids = wpos_ids.flatten()
388
+ pos_ids.append(torch.stack([hpos_ids, wpos_ids], dim=-1).repeat(t, 1))
389
+ pos_ids = torch.cat(pos_ids, dim=0)
390
+ max_grid_size = grid_thw[:, 1:].max()
391
+ rotary_pos_emb_full = self.rotary_pos_emb(max_grid_size)
392
+ rotary_pos_emb = rotary_pos_emb_full[pos_ids].flatten(1)
393
+ return rotary_pos_emb
394
+
395
+ def get_window_index(self, grid_thw):
396
+ window_index: list = []
397
+ cu_window_seqlens: list = [0]
398
+ window_index_id = 0
399
+ vit_merger_window_size = self.window_size // self.spatial_merge_size // self.patch_size
400
+
401
+ for grid_t, grid_h, grid_w in grid_thw:
402
+ llm_grid_h, llm_grid_w = (
403
+ grid_h // self.spatial_merge_size,
404
+ grid_w // self.spatial_merge_size,
405
+ )
406
+ index = torch.arange(grid_t * llm_grid_h * llm_grid_w).reshape(grid_t, llm_grid_h, llm_grid_w)
407
+ pad_h = vit_merger_window_size - llm_grid_h % vit_merger_window_size
408
+ pad_w = vit_merger_window_size - llm_grid_w % vit_merger_window_size
409
+ num_windows_h = (llm_grid_h + pad_h) // vit_merger_window_size
410
+ num_windows_w = (llm_grid_w + pad_w) // vit_merger_window_size
411
+ index_padded = F.pad(index, (0, pad_w, 0, pad_h), "constant", -100)
412
+ index_padded = index_padded.reshape(
413
+ grid_t,
414
+ num_windows_h,
415
+ vit_merger_window_size,
416
+ num_windows_w,
417
+ vit_merger_window_size,
418
+ )
419
+ index_padded = index_padded.permute(0, 1, 3, 2, 4).reshape(
420
+ grid_t,
421
+ num_windows_h * num_windows_w,
422
+ vit_merger_window_size,
423
+ vit_merger_window_size,
424
+ )
425
+ seqlens = (index_padded != -100).sum([2, 3]).reshape(-1)
426
+ index_padded = index_padded.reshape(-1)
427
+ index_new = index_padded[index_padded != -100]
428
+ window_index.append(index_new + window_index_id)
429
+ cu_seqlens_tmp = seqlens.cumsum(0) * self.spatial_merge_unit + cu_window_seqlens[-1]
430
+ cu_window_seqlens.extend(cu_seqlens_tmp.tolist())
431
+ window_index_id += (grid_t * llm_grid_h * llm_grid_w).item()
432
+ window_index = torch.cat(window_index, dim=0)
433
+
434
+ return window_index, cu_window_seqlens
435
+
436
+ def forward(self, hidden_states: torch.Tensor, grid_thw: torch.Tensor, **kwargs) -> torch.Tensor:
437
+ """
438
+ Args:
439
+ hidden_states (`torch.Tensor` of shape `(seq_len, hidden_size)`):
440
+ The final hidden states of the model.
441
+ grid_thw (`torch.Tensor` of shape `(num_images_or_videos, 3)`):
442
+ The temporal, height and width of feature shape of each image in LLM.
443
+
444
+ Returns:
445
+ `torch.Tensor`: hidden_states.
446
+ """
447
+ hidden_states = self.patch_embed(hidden_states)
448
+ rotary_pos_emb = self.rot_pos_emb(grid_thw)
449
+ window_index, cu_window_seqlens = self.get_window_index(grid_thw)
450
+ cu_window_seqlens = torch.tensor(
451
+ cu_window_seqlens,
452
+ device=hidden_states.device,
453
+ dtype=grid_thw.dtype if torch.jit.is_tracing() else torch.int32,
454
+ )
455
+ cu_window_seqlens = torch.unique_consecutive(cu_window_seqlens)
456
+
457
+ seq_len, _ = hidden_states.size()
458
+ hidden_states = hidden_states.reshape(seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1)
459
+ hidden_states = hidden_states[window_index, :, :]
460
+ hidden_states = hidden_states.reshape(seq_len, -1)
461
+ rotary_pos_emb = rotary_pos_emb.reshape(seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1)
462
+ rotary_pos_emb = rotary_pos_emb[window_index, :, :]
463
+ rotary_pos_emb = rotary_pos_emb.reshape(seq_len, -1)
464
+ emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1)
465
+ position_embeddings = (emb.cos(), emb.sin())
466
+
467
+ cu_seqlens = torch.repeat_interleave(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]).cumsum(
468
+ dim=0,
469
+ # Select dtype based on the following factors:
470
+ # - FA2 requires that cu_seqlens_q must have dtype int32
471
+ # - torch.onnx.export requires that cu_seqlens_q must have same dtype as grid_thw
472
+ # See https://github.com/huggingface/transformers/pull/34852 for more information
473
+ dtype=grid_thw.dtype if torch.jit.is_tracing() else torch.int32,
474
+ )
475
+ cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0)
476
+
477
+ for layer_num, blk in enumerate(self.blocks):
478
+ if layer_num in self.fullatt_block_indexes:
479
+ cu_seqlens_now = cu_seqlens
480
+ else:
481
+ cu_seqlens_now = cu_window_seqlens
482
+
483
+ hidden_states = blk(
484
+ hidden_states,
485
+ cu_seqlens=cu_seqlens_now,
486
+ position_embeddings=position_embeddings,
487
+ **kwargs,
488
+ )
489
+
490
+ hidden_states = self.merger(hidden_states)
491
+ reverse_indices = torch.argsort(window_index)
492
+ hidden_states = hidden_states[reverse_indices, :]
493
+
494
+ return hidden_states
495
+
496
+
497
+ @dataclass
498
+ @auto_docstring(
499
+ custom_intro="""
500
+ Base class for Llava outputs, with hidden states and attentions.
501
+ """
502
+ )
503
+ class Qwen2_5_VLModelOutputWithPast(ModelOutput):
504
+ r"""
505
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
506
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
507
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
508
+
509
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
510
+ `past_key_values` input) to speed up sequential decoding.
511
+ rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
512
+ The rope index difference between sequence length and multimodal rope.
513
+ """
514
+
515
+ last_hidden_state: torch.FloatTensor = None
516
+ past_key_values: Optional[list[torch.FloatTensor]] = None
517
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
518
+ attentions: Optional[tuple[torch.FloatTensor]] = None
519
+ rope_deltas: Optional[torch.LongTensor] = None
520
+
521
+
522
+ class Qwen2_5_VLRotaryEmbedding(nn.Module):
523
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
524
+
525
+ def __init__(self, config: Qwen2_5_VLTextConfig, device=None):
526
+ super().__init__()
527
+ # BC: "rope_type" was originally "type"
528
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
529
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
530
+ else:
531
+ self.rope_type = "default"
532
+ self.max_seq_len_cached = config.max_position_embeddings
533
+ self.original_max_seq_len = config.max_position_embeddings
534
+
535
+ self.config = config
536
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
537
+
538
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
539
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
540
+ self.original_inv_freq = self.inv_freq
541
+
542
+ @torch.no_grad()
543
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
544
+ def forward(self, x, position_ids):
545
+ # In contrast to other models, Qwen2_5_VL has different position ids for the grids
546
+ # So we expand the inv_freq to shape (3, ...)
547
+ inv_freq_expanded = self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1)
548
+ position_ids_expanded = position_ids[:, :, None, :].float() # shape (3, bs, 1, positions)
549
+
550
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
551
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
552
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3)
553
+ emb = torch.cat((freqs, freqs), dim=-1)
554
+ cos = emb.cos() * self.attention_scaling
555
+ sin = emb.sin() * self.attention_scaling
556
+
557
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
558
+
559
+
560
+ class Qwen2MLP(nn.Module):
561
+ def __init__(self, config):
562
+ super().__init__()
563
+ self.config = config
564
+ self.hidden_size = config.hidden_size
565
+ self.intermediate_size = config.intermediate_size
566
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
567
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
568
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
569
+ self.act_fn = ACT2FN[config.hidden_act]
570
+
571
+ def forward(self, x):
572
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
573
+ return down_proj
574
+
575
+
576
+ def apply_multimodal_rotary_pos_emb(q, k, cos, sin, mrope_section, unsqueeze_dim=1):
577
+ """Applies Rotary Position Embedding with Multimodal Sections to the query and key tensors (https://qwenlm.github.io/blog/qwen2-vl/).
578
+
579
+ Explanation:
580
+ Multimodal 3D rotary position embedding is an extension to 1D rotary position embedding. The input embedding
581
+ sequence contains vision (images / videos) embedding and text embedding or just contains text embedding. For
582
+ vision embedding part, we apply rotary position embedding on temporal, height and width dimension separately.
583
+ Here we split the channel dimension to 3 chunks for the temporal, height and width rotary position embedding.
584
+ For text embedding part, we just apply 1D rotary position embedding. The three rotary position index (temporal,
585
+ height and width) of text embedding is always the same, so the text embedding rotary position embedding has no
586
+ difference with modern LLMs.
587
+
588
+ Args:
589
+ q (`torch.Tensor`): The query tensor.
590
+ k (`torch.Tensor`): The key tensor.
591
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
592
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
593
+ position_ids (`torch.Tensor`):
594
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
595
+ used to pass offsetted position ids when working with a KV-cache.
596
+ mrope_section(`List(int)`):
597
+ Multimodal rope section is for channel dimension of temporal, height and width in rope calculation.
598
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
599
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
600
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
601
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
602
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
603
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
604
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
605
+ Returns:
606
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
607
+ """
608
+ mrope_section = mrope_section * 2
609
+ cos = torch.cat([m[i % 3] for i, m in enumerate(cos.split(mrope_section, dim=-1))], dim=-1).unsqueeze(
610
+ unsqueeze_dim
611
+ )
612
+ sin = torch.cat([m[i % 3] for i, m in enumerate(sin.split(mrope_section, dim=-1))], dim=-1).unsqueeze(
613
+ unsqueeze_dim
614
+ )
615
+
616
+ q_embed = (q * cos) + (rotate_half(q) * sin)
617
+ k_embed = (k * cos) + (rotate_half(k) * sin)
618
+ return q_embed, k_embed
619
+
620
+
621
+ class Qwen2_5_VLAttention(nn.Module):
622
+ """
623
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
624
+ and "Generating Long Sequences with Sparse Transformers".
625
+ """
626
+
627
+ def __init__(self, config: Qwen2_5_VLTextConfig, layer_idx: Optional[int] = None):
628
+ super().__init__()
629
+ self.config = config
630
+ self.layer_idx = layer_idx
631
+ if layer_idx is None:
632
+ logger.warning_once(
633
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
634
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
635
+ "when creating this class."
636
+ )
637
+
638
+ self.hidden_size = config.hidden_size
639
+ self.num_heads = config.num_attention_heads
640
+ self.head_dim = self.hidden_size // self.num_heads
641
+ self.num_key_value_heads = config.num_key_value_heads
642
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
643
+ self.is_causal = True
644
+ self.attention_dropout = config.attention_dropout
645
+ self.rope_scaling = config.rope_scaling
646
+ self.scaling = self.head_dim**-0.5
647
+
648
+ if (self.head_dim * self.num_heads) != self.hidden_size:
649
+ raise ValueError(
650
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
651
+ f" and `num_heads`: {self.num_heads})."
652
+ )
653
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
654
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
655
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
656
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
657
+ self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None
658
+
659
+ self.rotary_emb = Qwen2_5_VLRotaryEmbedding(config=config)
660
+
661
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
662
+ def forward(
663
+ self,
664
+ hidden_states: torch.Tensor,
665
+ attention_mask: Optional[torch.Tensor] = None,
666
+ position_ids: Optional[torch.LongTensor] = None,
667
+ past_key_values: Optional[Cache] = None,
668
+ output_attentions: bool = False,
669
+ use_cache: bool = False,
670
+ cache_position: Optional[torch.LongTensor] = None,
671
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
672
+ **kwargs: Unpack[FlashAttentionKwargs],
673
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
674
+ bsz, q_len, _ = hidden_states.size()
675
+
676
+ query_states = self.q_proj(hidden_states)
677
+ key_states = self.k_proj(hidden_states)
678
+ value_states = self.v_proj(hidden_states)
679
+
680
+ query_states = query_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
681
+ key_states = key_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
682
+ value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
683
+
684
+ cos, sin = position_embeddings
685
+ query_states, key_states = apply_multimodal_rotary_pos_emb(
686
+ query_states, key_states, cos, sin, self.rope_scaling["mrope_section"]
687
+ )
688
+
689
+ if past_key_values is not None:
690
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
691
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
692
+
693
+ attention_interface: Callable = eager_attention_forward
694
+ if self.config._attn_implementation != "eager":
695
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
696
+
697
+ attn_output, attn_weights = attention_interface(
698
+ self,
699
+ query_states,
700
+ key_states,
701
+ value_states,
702
+ attention_mask,
703
+ dropout=0.0 if not self.training else self.attention_dropout,
704
+ scaling=self.scaling,
705
+ sliding_window=self.sliding_window,
706
+ position_ids=position_ids, # pass positions for FA2
707
+ **kwargs,
708
+ )
709
+
710
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
711
+ attn_output = self.o_proj(attn_output)
712
+ return attn_output, attn_weights
713
+
714
+
715
+ class Qwen2_5_VLDecoderLayer(GradientCheckpointingLayer):
716
+ def __init__(self, config: Qwen2_5_VLTextConfig, layer_idx: int):
717
+ super().__init__()
718
+ self.hidden_size = config.hidden_size
719
+
720
+ if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
721
+ logger.warning_once(
722
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
723
+ "unexpected results may be encountered."
724
+ )
725
+ self.self_attn = Qwen2_5_VLAttention(config, layer_idx)
726
+
727
+ self.mlp = Qwen2MLP(config)
728
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
729
+ self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
730
+ self.attention_type = config.layer_types[layer_idx]
731
+
732
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
733
+ def forward(
734
+ self,
735
+ hidden_states: torch.Tensor,
736
+ attention_mask: Optional[torch.Tensor] = None,
737
+ position_ids: Optional[torch.LongTensor] = None,
738
+ past_key_values: Optional[tuple[torch.Tensor]] = None,
739
+ output_attentions: Optional[bool] = False,
740
+ use_cache: Optional[bool] = False,
741
+ cache_position: Optional[torch.LongTensor] = None,
742
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
743
+ **kwargs: Unpack[FlashAttentionKwargs],
744
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
745
+ """
746
+ Args:
747
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
748
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
749
+ `(batch, sequence_length)` where padding elements are indicated by 0.
750
+ output_attentions (`bool`, *optional*):
751
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
752
+ returned tensors for more detail.
753
+ use_cache (`bool`, *optional*):
754
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
755
+ (see `past_key_values`).
756
+ past_key_values (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
757
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
758
+ Indices depicting the position of the input sequence tokens in the sequence.
759
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
760
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
761
+ with `head_dim` being the embedding dimension of each attention head.
762
+ kwargs (`dict`, *optional*):
763
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
764
+ into the model
765
+ """
766
+
767
+ residual = hidden_states
768
+
769
+ hidden_states = self.input_layernorm(hidden_states)
770
+
771
+ # Self Attention
772
+ hidden_states, self_attn_weights = self.self_attn(
773
+ hidden_states=hidden_states,
774
+ attention_mask=attention_mask,
775
+ position_ids=position_ids,
776
+ past_key_values=past_key_values,
777
+ output_attentions=output_attentions,
778
+ use_cache=use_cache,
779
+ cache_position=cache_position,
780
+ position_embeddings=position_embeddings,
781
+ **kwargs,
782
+ )
783
+ hidden_states = residual + hidden_states
784
+
785
+ # Fully Connected
786
+ residual = hidden_states
787
+ hidden_states = self.post_attention_layernorm(hidden_states)
788
+ hidden_states = self.mlp(hidden_states)
789
+ hidden_states = residual + hidden_states
790
+
791
+ outputs = (hidden_states,)
792
+
793
+ if output_attentions:
794
+ outputs += (self_attn_weights,)
795
+
796
+ return outputs
797
+
798
+
799
+ @auto_docstring
800
+ class Qwen2_5_VLTextModel(Qwen2_5_VLPreTrainedModel):
801
+ config: Qwen2_5_VLTextConfig
802
+
803
+ def __init__(self, config: Qwen2_5_VLTextConfig):
804
+ super().__init__(config)
805
+ self.padding_idx = config.pad_token_id
806
+ self.vocab_size = config.vocab_size
807
+
808
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
809
+ self.layers = nn.ModuleList(
810
+ [Qwen2_5_VLDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
811
+ )
812
+ self._attn_implementation = config._attn_implementation
813
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
814
+ self.rotary_emb = Qwen2_5_VLRotaryEmbedding(config=config)
815
+ self.has_sliding_layers = "sliding_attention" in self.config.layer_types
816
+
817
+ self.gradient_checkpointing = False
818
+ # Initialize weights and apply final processing
819
+ self.post_init()
820
+
821
+ @auto_docstring
822
+ def forward(
823
+ self,
824
+ input_ids: Optional[torch.LongTensor] = None,
825
+ attention_mask: Optional[torch.Tensor] = None,
826
+ position_ids: Optional[torch.LongTensor] = None,
827
+ past_key_values: Optional[Cache] = None,
828
+ inputs_embeds: Optional[torch.FloatTensor] = None,
829
+ use_cache: Optional[bool] = None,
830
+ output_attentions: Optional[bool] = None,
831
+ output_hidden_states: Optional[bool] = None,
832
+ return_dict: Optional[bool] = None,
833
+ cache_position: Optional[torch.LongTensor] = None,
834
+ **kwargs: Unpack[FlashAttentionKwargs],
835
+ ) -> Union[tuple, BaseModelOutputWithPast]:
836
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
837
+ output_hidden_states = (
838
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
839
+ )
840
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
841
+
842
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
843
+
844
+ if (input_ids is None) ^ (inputs_embeds is not None):
845
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
846
+
847
+ if self.gradient_checkpointing and self.training:
848
+ if use_cache:
849
+ logger.warning_once(
850
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
851
+ )
852
+ use_cache = False
853
+
854
+ # torch.jit.trace() doesn't support cache objects in the output
855
+ if use_cache and past_key_values is None and not torch.jit.is_tracing():
856
+ past_key_values = DynamicCache(config=self.config)
857
+
858
+ if inputs_embeds is None:
859
+ inputs_embeds = self.embed_tokens(input_ids)
860
+
861
+ if cache_position is None:
862
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
863
+ cache_position = torch.arange(
864
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
865
+ )
866
+
867
+ # the hard coded `3` is for temporal, height and width.
868
+ if position_ids is None:
869
+ position_ids = cache_position.view(1, 1, -1).expand(3, inputs_embeds.shape[0], -1)
870
+ elif position_ids.ndim == 2:
871
+ position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1)
872
+
873
+ # NOTE: we need to pass text position ids for packing. Qwen2-VL uses 3D positions
874
+ # where each dim indicates visual spatial positions for temporal/height/width grids.
875
+ # There are two scenarios when FA2-like packed masking might be activated.
876
+ # 1. User specifically passed packed `position_ids` and no attention mask.
877
+ # In this case we expect the useer to create correct position ids for all 3 grids
878
+ # and prepend text-only position ids to it. The final tensor will be [4, bs, seq-len]
879
+ # 2. User runs forward with no attention mask and no position ids. In this case, position ids
880
+ # are prepared by the model (`get_rope_index`) as `[4, bs, seq-len]` tensor. Text-only positions are
881
+ # prepended by us when creating positions so that the mask is constructed correctly. NOTE: failing to pass
882
+ # text-only positions will cause incorrect mask construction, do not change `prepare_input_for_generation`
883
+ if position_ids.ndim == 3 and position_ids.shape[0] == 4:
884
+ text_position_ids = position_ids[0]
885
+ position_ids = position_ids[1:]
886
+ else:
887
+ text_position_ids = position_ids[0]
888
+
889
+ # It may already have been prepared by e.g. `generate`
890
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
891
+ # Prepare mask arguments
892
+ mask_kwargs = {
893
+ "config": self.config,
894
+ "input_embeds": inputs_embeds,
895
+ "attention_mask": attention_mask,
896
+ "cache_position": cache_position,
897
+ "past_key_values": past_key_values,
898
+ "position_ids": text_position_ids,
899
+ }
900
+ # Create the masks
901
+ causal_mask_mapping = {
902
+ "full_attention": create_causal_mask(**mask_kwargs),
903
+ }
904
+ # The sliding window alternating layers are not always activated depending on the config
905
+ if self.has_sliding_layers:
906
+ causal_mask_mapping["sliding_attention"] = create_sliding_window_causal_mask(**mask_kwargs)
907
+
908
+ hidden_states = inputs_embeds
909
+
910
+ # create position embeddings to be shared across the decoder layers
911
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
912
+
913
+ # decoder layers
914
+ all_hidden_states = () if output_hidden_states else None
915
+ all_self_attns = () if output_attentions else None
916
+
917
+ for decoder_layer in self.layers:
918
+ if output_hidden_states:
919
+ all_hidden_states += (hidden_states,)
920
+
921
+ layer_outputs = decoder_layer(
922
+ hidden_states,
923
+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],
924
+ position_ids=text_position_ids,
925
+ past_key_values=past_key_values,
926
+ output_attentions=output_attentions,
927
+ use_cache=use_cache,
928
+ cache_position=cache_position,
929
+ position_embeddings=position_embeddings,
930
+ **kwargs,
931
+ )
932
+
933
+ hidden_states = layer_outputs[0]
934
+
935
+ if output_attentions:
936
+ all_self_attns += (layer_outputs[1],)
937
+
938
+ hidden_states = self.norm(hidden_states)
939
+
940
+ # add hidden states from the last decoder layer
941
+ if output_hidden_states:
942
+ all_hidden_states += (hidden_states,)
943
+
944
+ if not return_dict:
945
+ return tuple(
946
+ v for v in [hidden_states, past_key_values, all_hidden_states, all_self_attns] if v is not None
947
+ )
948
+ return BaseModelOutputWithPast(
949
+ last_hidden_state=hidden_states,
950
+ past_key_values=past_key_values,
951
+ hidden_states=all_hidden_states,
952
+ attentions=all_self_attns,
953
+ )
954
+
955
+
956
+ @auto_docstring
957
+ class Qwen2_5_VLModel(Qwen2_5_VLPreTrainedModel):
958
+ base_model_prefix = ""
959
+ _checkpoint_conversion_mapping = {"^model": "language_model"}
960
+ config: Qwen2_5_VLConfig
961
+ _no_split_modules = ["Qwen2_5_VLDecoderLayer", "Qwen2_5_VLVisionBlock"]
962
+
963
+ def __init__(self, config):
964
+ super().__init__(config)
965
+ self.visual = Qwen2_5_VisionTransformerPretrainedModel._from_config(config.vision_config)
966
+ self.language_model = Qwen2_5_VLTextModel._from_config(config.text_config)
967
+ self.rope_deltas = None # cache rope_deltas here
968
+
969
+ # Initialize weights and apply final processing
970
+ self.post_init()
971
+
972
+ def get_input_embeddings(self):
973
+ return self.language_model.get_input_embeddings()
974
+
975
+ def set_input_embeddings(self, value):
976
+ self.language_model.set_input_embeddings(value)
977
+
978
+ def set_decoder(self, decoder):
979
+ self.language_model = decoder
980
+
981
+ def get_decoder(self):
982
+ return self.language_model
983
+
984
+ def get_rope_index(
985
+ self,
986
+ input_ids: Optional[torch.LongTensor] = None,
987
+ image_grid_thw: Optional[torch.LongTensor] = None,
988
+ video_grid_thw: Optional[torch.LongTensor] = None,
989
+ second_per_grid_ts: Optional[torch.Tensor] = None,
990
+ attention_mask: Optional[torch.Tensor] = None,
991
+ ) -> tuple[torch.Tensor, torch.Tensor]:
992
+ """
993
+ Calculate the 3D rope index based on image and video's temporal, height and width in LLM.
994
+
995
+ Explanation:
996
+ Each embedding sequence contains vision embedding and text embedding or just contains text embedding.
997
+
998
+ For pure text embedding sequence, the rotary position embedding has no difference with modern LLMs.
999
+ Examples:
1000
+ input_ids: [T T T T T], here T is for text.
1001
+ temporal position_ids: [0, 1, 2, 3, 4]
1002
+ height position_ids: [0, 1, 2, 3, 4]
1003
+ width position_ids: [0, 1, 2, 3, 4]
1004
+
1005
+ For vision and text embedding sequence, we calculate 3D rotary position embedding for vision part
1006
+ and 1D rotary position embedding for text part.
1007
+ Examples:
1008
+ Temporal (Time): 3 patches, representing different segments of the video in time.
1009
+ Height: 2 patches, dividing each frame vertically.
1010
+ Width: 2 patches, dividing each frame horizontally.
1011
+ We also have some important parameters:
1012
+ fps (Frames Per Second): The video's frame rate, set to 1. This means one frame is processed each second.
1013
+ tokens_per_second: This is a crucial parameter. It dictates how many "time-steps" or "temporal tokens" are conceptually packed into a one-second interval of the video. In this case, we have 25 tokens per second. So each second of the video will be represented with 25 separate time points. It essentially defines the temporal granularity.
1014
+ temporal_patch_size: The number of frames that compose one temporal patch. Here, it's 2 frames.
1015
+ interval: The step size for the temporal position IDs, calculated as tokens_per_second * temporal_patch_size / fps. In this case, 25 * 2 / 1 = 50. This means that each temporal patch will be have a difference of 50 in the temporal position IDs.
1016
+ input_ids: [V V V V V V V V V V V V T T T T T], here V is for vision.
1017
+ vision temporal position_ids: [0, 0, 0, 0, 50, 50, 50, 50, 100, 100, 100, 100]
1018
+ vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1]
1019
+ vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
1020
+ text temporal position_ids: [101, 102, 103, 104, 105]
1021
+ text height position_ids: [101, 102, 103, 104, 105]
1022
+ text width position_ids: [101, 102, 103, 104, 105]
1023
+ Here we calculate the text start position_ids as the max vision position_ids plus 1.
1024
+
1025
+ Args:
1026
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1027
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1028
+ it.
1029
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
1030
+ The temporal, height and width of feature shape of each image in LLM.
1031
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
1032
+ The temporal, height and width of feature shape of each video in LLM.
1033
+ second_per_grid_ts (`torch.Tensor` of shape `(num_videos)`, *optional*):
1034
+ The time interval (in seconds) for each grid along the temporal dimension in the 3D position IDs.
1035
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1036
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1037
+
1038
+ - 1 for tokens that are **not masked**,
1039
+ - 0 for tokens that are **masked**.
1040
+
1041
+ Returns:
1042
+ position_ids (`torch.LongTensor` of shape `(3, batch_size, sequence_length)`)
1043
+ mrope_position_deltas (`torch.Tensor` of shape `(batch_size)`)
1044
+ """
1045
+ spatial_merge_size = self.config.vision_config.spatial_merge_size
1046
+ image_token_id = self.config.image_token_id
1047
+ video_token_id = self.config.video_token_id
1048
+ vision_start_token_id = self.config.vision_start_token_id
1049
+ mrope_position_deltas = []
1050
+ if input_ids is not None and (image_grid_thw is not None or video_grid_thw is not None):
1051
+ total_input_ids = input_ids
1052
+ if attention_mask is None:
1053
+ attention_mask = torch.ones_like(total_input_ids)
1054
+ position_ids = torch.ones(
1055
+ 3,
1056
+ input_ids.shape[0],
1057
+ input_ids.shape[1],
1058
+ dtype=input_ids.dtype,
1059
+ device=input_ids.device,
1060
+ )
1061
+ image_index, video_index = 0, 0
1062
+ attention_mask = attention_mask.to(total_input_ids.device)
1063
+ for i, input_ids in enumerate(total_input_ids):
1064
+ input_ids = input_ids[attention_mask[i] == 1]
1065
+ image_nums, video_nums = 0, 0
1066
+ vision_start_indices = torch.argwhere(input_ids == vision_start_token_id).squeeze(1)
1067
+ vision_tokens = input_ids[vision_start_indices + 1]
1068
+ image_nums = (vision_tokens == image_token_id).sum()
1069
+ video_nums = (vision_tokens == video_token_id).sum()
1070
+ input_tokens = input_ids.tolist()
1071
+ llm_pos_ids_list: list = []
1072
+ st = 0
1073
+ remain_images, remain_videos = image_nums, video_nums
1074
+ for _ in range(image_nums + video_nums):
1075
+ if image_token_id in input_tokens and remain_images > 0:
1076
+ ed_image = input_tokens.index(image_token_id, st)
1077
+ else:
1078
+ ed_image = len(input_tokens) + 1
1079
+ if video_token_id in input_tokens and remain_videos > 0:
1080
+ ed_video = input_tokens.index(video_token_id, st)
1081
+ else:
1082
+ ed_video = len(input_tokens) + 1
1083
+ if ed_image < ed_video:
1084
+ t, h, w = (
1085
+ image_grid_thw[image_index][0],
1086
+ image_grid_thw[image_index][1],
1087
+ image_grid_thw[image_index][2],
1088
+ )
1089
+ second_per_grid_t = 0
1090
+ image_index += 1
1091
+ remain_images -= 1
1092
+ ed = ed_image
1093
+
1094
+ else:
1095
+ t, h, w = (
1096
+ video_grid_thw[video_index][0],
1097
+ video_grid_thw[video_index][1],
1098
+ video_grid_thw[video_index][2],
1099
+ )
1100
+ if second_per_grid_ts is not None:
1101
+ second_per_grid_t = second_per_grid_ts[video_index]
1102
+ else:
1103
+ second_per_grid_t = 1.0
1104
+ video_index += 1
1105
+ remain_videos -= 1
1106
+ ed = ed_video
1107
+ llm_grid_t, llm_grid_h, llm_grid_w = (
1108
+ t.item(),
1109
+ h.item() // spatial_merge_size,
1110
+ w.item() // spatial_merge_size,
1111
+ )
1112
+ text_len = ed - st
1113
+
1114
+ st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
1115
+ llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx)
1116
+
1117
+ range_tensor = torch.arange(llm_grid_t).view(-1, 1)
1118
+ expanded_range = range_tensor.expand(-1, llm_grid_h * llm_grid_w)
1119
+
1120
+ ## normalize type, send to device.
1121
+ second_per_grid_t = torch.as_tensor(
1122
+ second_per_grid_t, dtype=range_tensor.dtype, device=range_tensor.device
1123
+ )
1124
+
1125
+ time_tensor = expanded_range * second_per_grid_t * self.config.vision_config.tokens_per_second
1126
+
1127
+ time_tensor_long = time_tensor.long()
1128
+ t_index = time_tensor_long.flatten()
1129
+
1130
+ h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(llm_grid_t, -1, llm_grid_w).flatten()
1131
+ w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(llm_grid_t, llm_grid_h, -1).flatten()
1132
+ llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + text_len + st_idx)
1133
+ st = ed + llm_grid_t * llm_grid_h * llm_grid_w
1134
+
1135
+ if st < len(input_tokens):
1136
+ st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
1137
+ text_len = len(input_tokens) - st
1138
+ llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx)
1139
+
1140
+ llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1)
1141
+ position_ids[..., i, attention_mask[i] == 1] = llm_positions.to(position_ids.device)
1142
+ mrope_position_deltas.append(llm_positions.max() + 1 - len(total_input_ids[i]))
1143
+ mrope_position_deltas = torch.tensor(mrope_position_deltas, device=input_ids.device).unsqueeze(1)
1144
+ return position_ids, mrope_position_deltas
1145
+ else:
1146
+ if attention_mask is not None:
1147
+ position_ids = attention_mask.long().cumsum(-1) - 1
1148
+ position_ids.masked_fill_(attention_mask == 0, 1)
1149
+ position_ids = position_ids.unsqueeze(0).expand(3, -1, -1).to(attention_mask.device)
1150
+ max_position_ids = position_ids.max(0, keepdim=False)[0].max(-1, keepdim=True)[0]
1151
+ mrope_position_deltas = max_position_ids + 1 - attention_mask.shape[-1]
1152
+ else:
1153
+ position_ids = (
1154
+ torch.arange(input_ids.shape[1], device=input_ids.device)
1155
+ .view(1, 1, -1)
1156
+ .expand(3, input_ids.shape[0], -1)
1157
+ )
1158
+ mrope_position_deltas = torch.zeros(
1159
+ [input_ids.shape[0], 1],
1160
+ device=input_ids.device,
1161
+ dtype=input_ids.dtype,
1162
+ )
1163
+
1164
+ return position_ids, mrope_position_deltas
1165
+
1166
+ def get_video_features(
1167
+ self, pixel_values_videos: torch.FloatTensor, video_grid_thw: Optional[torch.LongTensor] = None
1168
+ ):
1169
+ """
1170
+ Encodes videos into continuous embeddings that can be forwarded to the language model.
1171
+
1172
+ Args:
1173
+ pixel_values_videos (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
1174
+ The tensors corresponding to the input videos.
1175
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
1176
+ The temporal, height and width of feature shape of each video in LLM.
1177
+ """
1178
+ pixel_values_videos = pixel_values_videos.type(self.visual.dtype)
1179
+ video_embeds = self.visual(pixel_values_videos, grid_thw=video_grid_thw)
1180
+ split_sizes = (video_grid_thw.prod(-1) // self.visual.spatial_merge_size**2).tolist()
1181
+ video_embeds = torch.split(video_embeds, split_sizes)
1182
+ return video_embeds
1183
+
1184
+ def get_image_features(self, pixel_values: torch.FloatTensor, image_grid_thw: Optional[torch.LongTensor] = None):
1185
+ """
1186
+ Encodes images into continuous embeddings that can be forwarded to the language model.
1187
+
1188
+ Args:
1189
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
1190
+ The tensors corresponding to the input images.
1191
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
1192
+ The temporal, height and width of feature shape of each image in LLM.
1193
+ """
1194
+ pixel_values = pixel_values.type(self.visual.dtype)
1195
+ image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw)
1196
+ split_sizes = (image_grid_thw.prod(-1) // self.visual.spatial_merge_size**2).tolist()
1197
+ image_embeds = torch.split(image_embeds, split_sizes)
1198
+ return image_embeds
1199
+
1200
+ def get_placeholder_mask(
1201
+ self,
1202
+ input_ids: torch.LongTensor,
1203
+ inputs_embeds: torch.FloatTensor,
1204
+ image_features: torch.FloatTensor = None,
1205
+ video_features: torch.FloatTensor = None,
1206
+ ):
1207
+ """
1208
+ Obtains multimodal placeholdr mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
1209
+ equal to the length of multimodal features. If the lengths are different, an error is raised.
1210
+ """
1211
+ if input_ids is None:
1212
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
1213
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
1214
+ )
1215
+ special_image_mask = special_image_mask.all(-1)
1216
+ special_video_mask = inputs_embeds == self.get_input_embeddings()(
1217
+ torch.tensor(self.config.video_token_id, dtype=torch.long, device=inputs_embeds.device)
1218
+ )
1219
+ special_video_mask = special_video_mask.all(-1)
1220
+ else:
1221
+ special_image_mask = input_ids == self.config.image_token_id
1222
+ special_video_mask = input_ids == self.config.video_token_id
1223
+
1224
+ n_image_tokens = special_image_mask.sum()
1225
+ special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
1226
+ if image_features is not None and inputs_embeds[special_image_mask].numel() != image_features.numel():
1227
+ raise ValueError(
1228
+ f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {image_features.shape[0]}"
1229
+ )
1230
+
1231
+ n_video_tokens = special_video_mask.sum()
1232
+ special_video_mask = special_video_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
1233
+ if video_features is not None and inputs_embeds[special_video_mask].numel() != video_features.numel():
1234
+ raise ValueError(
1235
+ f"Videos features and video tokens do not match: tokens: {n_video_tokens}, features {video_features.shape[0]}"
1236
+ )
1237
+
1238
+ return special_image_mask, special_video_mask
1239
+
1240
+ @auto_docstring
1241
+ def forward(
1242
+ self,
1243
+ input_ids: torch.LongTensor = None,
1244
+ attention_mask: Optional[torch.Tensor] = None,
1245
+ position_ids: Optional[torch.LongTensor] = None,
1246
+ past_key_values: Optional[Cache] = None,
1247
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1248
+ use_cache: Optional[bool] = None,
1249
+ output_attentions: Optional[bool] = None,
1250
+ output_hidden_states: Optional[bool] = None,
1251
+ return_dict: Optional[bool] = None,
1252
+ pixel_values: Optional[torch.Tensor] = None,
1253
+ pixel_values_videos: Optional[torch.FloatTensor] = None,
1254
+ image_grid_thw: Optional[torch.LongTensor] = None,
1255
+ video_grid_thw: Optional[torch.LongTensor] = None,
1256
+ rope_deltas: Optional[torch.LongTensor] = None,
1257
+ cache_position: Optional[torch.LongTensor] = None,
1258
+ second_per_grid_ts: Optional[torch.Tensor] = None,
1259
+ **kwargs: Unpack[TransformersKwargs],
1260
+ ) -> Union[tuple, Qwen2_5_VLModelOutputWithPast]:
1261
+ r"""
1262
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
1263
+ The temporal, height and width of feature shape of each image in LLM.
1264
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
1265
+ The temporal, height and width of feature shape of each video in LLM.
1266
+ rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
1267
+ The rope index difference between sequence length and multimodal rope.
1268
+ second_per_grid_ts (`torch.Tensor` of shape `(num_videos)`, *optional*):
1269
+ The time interval (in seconds) for each grid along the temporal dimension in the 3D position IDs.
1270
+ """
1271
+
1272
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1273
+ output_hidden_states = (
1274
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1275
+ )
1276
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1277
+
1278
+ if inputs_embeds is None:
1279
+ inputs_embeds = self.get_input_embeddings()(input_ids)
1280
+
1281
+ if pixel_values is not None:
1282
+ image_embeds = self.get_image_features(pixel_values, image_grid_thw)
1283
+ image_embeds = torch.cat(image_embeds, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
1284
+ image_mask, _ = self.get_placeholder_mask(
1285
+ input_ids, inputs_embeds=inputs_embeds, image_features=image_embeds
1286
+ )
1287
+ inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
1288
+
1289
+ if pixel_values_videos is not None:
1290
+ video_embeds = self.get_video_features(pixel_values_videos, video_grid_thw)
1291
+ video_embeds = torch.cat(video_embeds, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
1292
+ _, video_mask = self.get_placeholder_mask(
1293
+ input_ids, inputs_embeds=inputs_embeds, video_features=video_embeds
1294
+ )
1295
+ inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds)
1296
+
1297
+ if position_ids is None:
1298
+ # Calculate RoPE index once per generation in the pre-fill stage only.
1299
+ # When compiling, we can't check tensor values thus we check only input length
1300
+ # It is safe to assume that `length!=1` means we're in pre-fill because compiled
1301
+ # models currently cannot do asssisted decoding
1302
+ prefill_compiled_stage = is_torchdynamo_compiling() and (
1303
+ (input_ids is not None and input_ids.shape[1] != 1)
1304
+ or (inputs_embeds is not None and inputs_embeds.shape[1] != 1)
1305
+ )
1306
+ prefill_noncompiled_stage = not is_torchdynamo_compiling() and (
1307
+ (cache_position is not None and cache_position[0] == 0)
1308
+ or (past_key_values is None or past_key_values.get_seq_length() == 0)
1309
+ )
1310
+ if (prefill_compiled_stage or prefill_noncompiled_stage) or self.rope_deltas is None:
1311
+ position_ids, rope_deltas = self.get_rope_index(
1312
+ input_ids,
1313
+ image_grid_thw,
1314
+ video_grid_thw,
1315
+ second_per_grid_ts=second_per_grid_ts,
1316
+ attention_mask=attention_mask,
1317
+ )
1318
+ self.rope_deltas = rope_deltas
1319
+ else:
1320
+ batch_size, seq_length, _ = inputs_embeds.shape
1321
+ position_ids = torch.arange(seq_length, device=inputs_embeds.device)
1322
+ position_ids = position_ids.view(1, 1, -1).expand(3, batch_size, -1)
1323
+ if cache_position is not None:
1324
+ delta = (cache_position[0] + self.rope_deltas).to(inputs_embeds.device)
1325
+ else:
1326
+ delta = torch.zeros((batch_size, seq_length), device=inputs_embeds.device)
1327
+ delta = delta.repeat_interleave(batch_size // delta.shape[0], dim=1)
1328
+ position_ids += delta.to(position_ids.device)
1329
+
1330
+ outputs = self.language_model(
1331
+ input_ids=None,
1332
+ position_ids=position_ids,
1333
+ attention_mask=attention_mask,
1334
+ past_key_values=past_key_values,
1335
+ inputs_embeds=inputs_embeds,
1336
+ use_cache=use_cache,
1337
+ output_attentions=output_attentions,
1338
+ output_hidden_states=output_hidden_states,
1339
+ return_dict=True,
1340
+ cache_position=cache_position,
1341
+ **kwargs,
1342
+ )
1343
+
1344
+ output = Qwen2_5_VLModelOutputWithPast(
1345
+ last_hidden_state=outputs.last_hidden_state,
1346
+ past_key_values=outputs.past_key_values,
1347
+ hidden_states=outputs.hidden_states,
1348
+ attentions=outputs.attentions,
1349
+ rope_deltas=self.rope_deltas,
1350
+ )
1351
+ return output if return_dict else output.to_tuple()
1352
+
1353
+
1354
+ @dataclass
1355
+ @auto_docstring(
1356
+ custom_intro="""
1357
+ Base class for Qwen2_5_VL causal language model (or autoregressive) outputs.
1358
+ """
1359
+ )
1360
+ class Qwen2_5_VLCausalLMOutputWithPast(ModelOutput):
1361
+ r"""
1362
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
1363
+ Language modeling loss (for next-token prediction).
1364
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
1365
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
1366
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
1367
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
1368
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
1369
+
1370
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
1371
+ `past_key_values` input) to speed up sequential decoding.
1372
+ rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
1373
+ The rope index difference between sequence length and multimodal rope.
1374
+ """
1375
+
1376
+ loss: Optional[torch.FloatTensor] = None
1377
+ logits: Optional[torch.FloatTensor] = None
1378
+ past_key_values: Optional[list[torch.FloatTensor]] = None
1379
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
1380
+ attentions: Optional[tuple[torch.FloatTensor]] = None
1381
+ rope_deltas: Optional[torch.LongTensor] = None
1382
+
1383
+
1384
+ class Qwen2_5_VLForConditionalGeneration(Qwen2_5_VLPreTrainedModel, GenerationMixin):
1385
+ _checkpoint_conversion_mapping = {
1386
+ "^visual": "model.visual",
1387
+ r"^model(?!\.(language_model|visual))": "model.language_model",
1388
+ }
1389
+ _tied_weights_keys = ["lm_head.weight"]
1390
+
1391
+ def __init__(self, config):
1392
+ super().__init__(config)
1393
+ self.model = Qwen2_5_VLModel(config)
1394
+ self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
1395
+
1396
+ self.post_init()
1397
+
1398
+ def get_input_embeddings(self):
1399
+ return self.model.get_input_embeddings()
1400
+
1401
+ def set_input_embeddings(self, value):
1402
+ self.model.set_input_embeddings(value)
1403
+
1404
+ def set_decoder(self, decoder):
1405
+ self.model.set_decoder(decoder)
1406
+
1407
+ def get_decoder(self):
1408
+ return self.model.get_decoder()
1409
+
1410
+ def get_video_features(
1411
+ self, pixel_values_videos: torch.FloatTensor, video_grid_thw: Optional[torch.LongTensor] = None
1412
+ ):
1413
+ return self.model.get_video_features(pixel_values_videos, video_grid_thw)
1414
+
1415
+ def get_image_features(self, pixel_values: torch.FloatTensor, image_grid_thw: Optional[torch.LongTensor] = None):
1416
+ return self.model.get_image_features(pixel_values, image_grid_thw)
1417
+
1418
+ # Make modules available through conditional class for BC
1419
+ @property
1420
+ def language_model(self):
1421
+ return self.model.language_model
1422
+
1423
+ @property
1424
+ def visual(self):
1425
+ return self.model.visual
1426
+
1427
+ @can_return_tuple
1428
+ @auto_docstring
1429
+ def forward(
1430
+ self,
1431
+ input_ids: torch.LongTensor = None,
1432
+ attention_mask: Optional[torch.Tensor] = None,
1433
+ position_ids: Optional[torch.LongTensor] = None,
1434
+ past_key_values: Optional[Cache] = None,
1435
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1436
+ labels: Optional[torch.LongTensor] = None,
1437
+ use_cache: Optional[bool] = None,
1438
+ output_attentions: Optional[bool] = None,
1439
+ output_hidden_states: Optional[bool] = None,
1440
+ pixel_values: Optional[torch.Tensor] = None,
1441
+ pixel_values_videos: Optional[torch.FloatTensor] = None,
1442
+ image_grid_thw: Optional[torch.LongTensor] = None,
1443
+ video_grid_thw: Optional[torch.LongTensor] = None,
1444
+ rope_deltas: Optional[torch.LongTensor] = None,
1445
+ cache_position: Optional[torch.LongTensor] = None,
1446
+ second_per_grid_ts: Optional[torch.Tensor] = None,
1447
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1448
+ **kwargs: Unpack[TransformersKwargs],
1449
+ ) -> Union[tuple, Qwen2_5_VLCausalLMOutputWithPast]:
1450
+ r"""
1451
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1452
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1453
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1454
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1455
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
1456
+ The temporal, height and width of feature shape of each image in LLM.
1457
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
1458
+ The temporal, height and width of feature shape of each video in LLM.
1459
+ rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
1460
+ The rope index difference between sequence length and multimodal rope.
1461
+ second_per_grid_ts (`torch.Tensor` of shape `(num_videos)`, *optional*):
1462
+ The time interval (in seconds) for each grid along the temporal dimension in the 3D position IDs.
1463
+
1464
+ Example:
1465
+
1466
+ ```python
1467
+ >>> from PIL import Image
1468
+ >>> import requests
1469
+ >>> from transformers import AutoProcessor, Qwen2_5_VLForConditionalGeneration
1470
+
1471
+ >>> model = Qwen2_5_VLForConditionalGeneration.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct")
1472
+ >>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct")
1473
+
1474
+ >>> messages = [
1475
+ {
1476
+ "role": "user",
1477
+ "content": [
1478
+ {"type": "image"},
1479
+ {"type": "text", "text": "What is shown in this image?"},
1480
+ ],
1481
+ },
1482
+ ]
1483
+ >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
1484
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1485
+
1486
+ >>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
1487
+ >>> inputs = processor(text=[text], images=[image], vision_infos=[vision_infos])
1488
+
1489
+ >>> # Generate
1490
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1491
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1492
+ "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 ..."
1493
+ ```"""
1494
+
1495
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1496
+ output_hidden_states = (
1497
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1498
+ )
1499
+
1500
+ outputs = self.model(
1501
+ input_ids=input_ids,
1502
+ pixel_values=pixel_values,
1503
+ pixel_values_videos=pixel_values_videos,
1504
+ image_grid_thw=image_grid_thw,
1505
+ video_grid_thw=video_grid_thw,
1506
+ second_per_grid_ts=second_per_grid_ts,
1507
+ position_ids=position_ids,
1508
+ attention_mask=attention_mask,
1509
+ past_key_values=past_key_values,
1510
+ inputs_embeds=inputs_embeds,
1511
+ use_cache=use_cache,
1512
+ output_attentions=output_attentions,
1513
+ output_hidden_states=output_hidden_states,
1514
+ return_dict=True,
1515
+ cache_position=cache_position,
1516
+ **kwargs,
1517
+ )
1518
+
1519
+ hidden_states = outputs[0]
1520
+
1521
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1522
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1523
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1524
+
1525
+ loss = None
1526
+ if labels is not None:
1527
+ loss = self.loss_function(
1528
+ logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
1529
+ )
1530
+
1531
+ return Qwen2_5_VLCausalLMOutputWithPast(
1532
+ loss=loss,
1533
+ logits=logits,
1534
+ past_key_values=outputs.past_key_values,
1535
+ hidden_states=outputs.hidden_states,
1536
+ attentions=outputs.attentions,
1537
+ rope_deltas=outputs.rope_deltas,
1538
+ )
1539
+
1540
+ def prepare_inputs_for_generation(
1541
+ self,
1542
+ input_ids,
1543
+ past_key_values=None,
1544
+ attention_mask=None,
1545
+ inputs_embeds=None,
1546
+ cache_position=None,
1547
+ position_ids=None,
1548
+ use_cache=True,
1549
+ pixel_values=None,
1550
+ pixel_values_videos=None,
1551
+ image_grid_thw=None,
1552
+ video_grid_thw=None,
1553
+ second_per_grid_ts=None,
1554
+ **kwargs,
1555
+ ):
1556
+ # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
1557
+
1558
+ model_inputs = super().prepare_inputs_for_generation(
1559
+ input_ids,
1560
+ past_key_values=past_key_values,
1561
+ attention_mask=attention_mask,
1562
+ inputs_embeds=inputs_embeds,
1563
+ cache_position=cache_position,
1564
+ position_ids=position_ids,
1565
+ pixel_values=pixel_values,
1566
+ pixel_values_videos=pixel_values_videos,
1567
+ image_grid_thw=image_grid_thw,
1568
+ video_grid_thw=video_grid_thw,
1569
+ second_per_grid_ts=second_per_grid_ts,
1570
+ use_cache=use_cache,
1571
+ **kwargs,
1572
+ )
1573
+
1574
+ # Qwen2-5-VL position_ids are prepared with rope_deltas
1575
+ if position_ids is None:
1576
+ # Calculate RoPE index once per generation in the pre-fill stage only.
1577
+ # When compiling, we can't check tensor values thus we check only input length
1578
+ # It is safe to assume that `length!=1` means we're in pre-fill because compiled
1579
+ # models currently cannot do asssisted decoding
1580
+ if cache_position[0] == 0 or self.model.rope_deltas is None:
1581
+ vision_positions, rope_deltas = self.model.get_rope_index(
1582
+ model_inputs.get("input_ids", None),
1583
+ image_grid_thw=image_grid_thw,
1584
+ video_grid_thw=video_grid_thw,
1585
+ second_per_grid_ts=second_per_grid_ts,
1586
+ attention_mask=attention_mask,
1587
+ )
1588
+ self.model.rope_deltas = rope_deltas
1589
+ # then use the prev pre-calculated rope-deltas to get the correct position ids
1590
+ elif "position_ids" in model_inputs:
1591
+ position_ids = model_inputs["position_ids"][None, ...]
1592
+ delta = self.model.rope_deltas
1593
+ delta = delta.repeat_interleave(position_ids.shape[1] // delta.shape[0], dim=0)
1594
+ vision_positions = position_ids + delta.expand_as(position_ids)
1595
+ vision_positions = vision_positions.expand(3, vision_positions.shape[1], -1)
1596
+
1597
+ # Concatenate "text + vision" positions into [4, bs, seq-len]
1598
+ if "position_ids" not in model_inputs:
1599
+ text_positions = torch.arange(input_ids, device=input_ids.device)[None, None, :]
1600
+ else:
1601
+ text_positions = model_inputs["position_ids"][None, ...]
1602
+ model_inputs["position_ids"] = torch.cat([text_positions, vision_positions], dim=0)
1603
+
1604
+ if cache_position[0] != 0:
1605
+ model_inputs["pixel_values"] = None
1606
+ model_inputs["pixel_values_videos"] = None
1607
+
1608
+ return model_inputs
1609
+
1610
+ def _get_image_nums_and_video_nums(
1611
+ self,
1612
+ input_ids: Optional[torch.LongTensor],
1613
+ inputs_embeds: Optional[torch.Tensor] = None,
1614
+ ) -> tuple[torch.Tensor, torch.Tensor]:
1615
+ """
1616
+ Get the number of images and videos for each sample to calculate the separation length of the sample tensor.
1617
+ These parameters are not passed through the processor to avoid unpredictable impacts from interface modifications.
1618
+
1619
+ Args:
1620
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1621
+ Indices of input sequence tokens in the vocabulary.
1622
+
1623
+ Returns:
1624
+ image_nums (`torch.LongTensor` of shape `(batch_size, num_images_sample)`)
1625
+ video_nums (`torch.LongTensor` of shape `(batch_size, num_videos_sample)`)
1626
+ """
1627
+ image_token_id = self.config.image_token_id
1628
+ video_token_id = self.config.video_token_id
1629
+ vision_start_token_id = self.config.vision_start_token_id
1630
+
1631
+ if inputs_embeds is not None:
1632
+ vision_start_mask = (
1633
+ inputs_embeds
1634
+ == self.get_input_embeddings()(
1635
+ torch.tensor(vision_start_token_id, dtype=torch.long, device=inputs_embeds.device)
1636
+ )
1637
+ )[..., 0]
1638
+ image_mask = (
1639
+ inputs_embeds
1640
+ == self.get_input_embeddings()(
1641
+ torch.tensor(image_token_id, dtype=torch.long, device=inputs_embeds.device)
1642
+ )
1643
+ )[..., 0]
1644
+ video_mask = (
1645
+ inputs_embeds
1646
+ == self.get_input_embeddings()(
1647
+ torch.tensor(video_token_id, dtype=torch.long, device=inputs_embeds.device)
1648
+ )
1649
+ )[..., 0]
1650
+ else:
1651
+ vision_start_mask = input_ids == vision_start_token_id
1652
+ image_mask = input_ids == image_token_id
1653
+ video_mask = input_ids == video_token_id
1654
+
1655
+ vision_first_mask = torch.roll(vision_start_mask, shifts=1, dims=1)
1656
+ image_nums = torch.sum(vision_first_mask & image_mask, dim=1)
1657
+ video_nums = torch.sum(vision_first_mask & video_mask, dim=1)
1658
+
1659
+ return image_nums, video_nums
1660
+
1661
+ def _expand_inputs_for_generation(
1662
+ self,
1663
+ expand_size: int = 1,
1664
+ is_encoder_decoder: bool = False,
1665
+ input_ids: Optional[torch.LongTensor] = None,
1666
+ **model_kwargs,
1667
+ ) -> tuple[torch.LongTensor, dict[str, Any]]:
1668
+ # Overwritten -- Support for expanding tensors without a batch size dimension
1669
+ # e.g., pixel_values, image_grid_thw, pixel_values_videos, video_grid_thw, second_per_grid_t
1670
+ # pixel_values.shape[0] is sum(seqlen_images for samples)
1671
+ # image_grid_thw.shape[0] is sum(num_images for samples)
1672
+
1673
+ if expand_size == 1:
1674
+ return input_ids, model_kwargs
1675
+
1676
+ visual_keys = ["pixel_values", "image_grid_thw", "pixel_values_videos", "video_grid_thw", "second_per_grid_ts"]
1677
+
1678
+ def _expand_dict_for_generation_visual(dict_to_expand):
1679
+ image_grid_thw = model_kwargs.get("image_grid_thw", None)
1680
+ video_grid_thw = model_kwargs.get("video_grid_thw", None)
1681
+ image_nums, video_nums = self._get_image_nums_and_video_nums(
1682
+ input_ids, inputs_embeds=model_kwargs.get("inputs_embeds", None)
1683
+ )
1684
+
1685
+ def _repeat_interleave_samples(x, lengths, repeat_times):
1686
+ samples = torch.split(x, lengths)
1687
+ repeat_args = [repeat_times] + [1] * (x.dim() - 1)
1688
+ result = torch.cat([sample.repeat(*repeat_args) for sample in samples], dim=0)
1689
+ return result
1690
+
1691
+ for key in dict_to_expand:
1692
+ if key == "pixel_values":
1693
+ # split images into samples
1694
+ samples = torch.split(image_grid_thw, list(image_nums))
1695
+ # compute the sequence length of images for each sample
1696
+ lengths = [torch.prod(sample, dim=1).sum() for sample in samples]
1697
+ dict_to_expand[key] = _repeat_interleave_samples(
1698
+ dict_to_expand[key], lengths=lengths, repeat_times=expand_size
1699
+ )
1700
+ elif key == "image_grid_thw":
1701
+ # get the num of images for each sample
1702
+ lengths = list(image_nums)
1703
+ dict_to_expand[key] = _repeat_interleave_samples(
1704
+ dict_to_expand[key], lengths=lengths, repeat_times=expand_size
1705
+ )
1706
+ elif key == "pixel_values_videos":
1707
+ samples = torch.split(video_grid_thw, list(video_nums))
1708
+ lengths = [torch.prod(sample, dim=1).sum() for sample in samples]
1709
+ dict_to_expand[key] = _repeat_interleave_samples(
1710
+ dict_to_expand[key], lengths=lengths, repeat_times=expand_size
1711
+ )
1712
+ elif key == "video_grid_thw":
1713
+ lengths = list(video_nums)
1714
+ dict_to_expand[key] = _repeat_interleave_samples(
1715
+ dict_to_expand[key], lengths=lengths, repeat_times=expand_size
1716
+ )
1717
+ elif key == "second_per_grid_ts":
1718
+ dict_to_expand[key] = _repeat_interleave_samples(
1719
+ dict_to_expand[key], lengths=list(video_nums), repeat_times=expand_size
1720
+ )
1721
+ return dict_to_expand
1722
+
1723
+ def _expand_dict_for_generation(dict_to_expand):
1724
+ for key in dict_to_expand:
1725
+ if (
1726
+ key != "cache_position"
1727
+ and dict_to_expand[key] is not None
1728
+ and isinstance(dict_to_expand[key], torch.Tensor)
1729
+ and key not in visual_keys
1730
+ ):
1731
+ dict_to_expand[key] = dict_to_expand[key].repeat_interleave(expand_size, dim=0)
1732
+ return dict_to_expand
1733
+
1734
+ model_kwargs = _expand_dict_for_generation_visual(model_kwargs)
1735
+
1736
+ if input_ids is not None:
1737
+ input_ids = input_ids.repeat_interleave(expand_size, dim=0)
1738
+
1739
+ model_kwargs = _expand_dict_for_generation(model_kwargs)
1740
+
1741
+ if is_encoder_decoder:
1742
+ if model_kwargs.get("encoder_outputs") is None:
1743
+ raise ValueError("If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined.")
1744
+ model_kwargs["encoder_outputs"] = _expand_dict_for_generation(model_kwargs["encoder_outputs"])
1745
+
1746
+ return input_ids, model_kwargs
1747
+
1748
+
1749
+ __all__ = ["Qwen2_5_VLForConditionalGeneration", "Qwen2_5_VLModel", "Qwen2_5_VLPreTrainedModel", "Qwen2_5_VLTextModel"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_5_vl/modular_qwen2_5_vl.py ADDED
@@ -0,0 +1,1034 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The Qwen Team and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
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
+ """PyTorch Qwen2.5-VL model."""
21
+
22
+ from typing import Optional, Union
23
+
24
+ import numpy as np
25
+ import torch
26
+ import torch.nn as nn
27
+ import torch.nn.functional as F
28
+ import torch.utils.checkpoint
29
+
30
+ from transformers.models.qwen2_vl.configuration_qwen2_vl import Qwen2VLConfig, Qwen2VLTextConfig
31
+ from transformers.models.qwen2_vl.modeling_qwen2_vl import (
32
+ PatchEmbed,
33
+ PatchMerger,
34
+ Qwen2RMSNorm,
35
+ Qwen2VLCausalLMOutputWithPast,
36
+ Qwen2VLForConditionalGeneration,
37
+ Qwen2VLModel,
38
+ Qwen2VLModelOutputWithPast,
39
+ Qwen2VLPreTrainedModel,
40
+ TransformersKwargs,
41
+ VisionAttention,
42
+ VisionRotaryEmbedding,
43
+ )
44
+ from transformers.models.qwen2_vl.processing_qwen2_vl import Qwen2VLImagesKwargs, Qwen2VLProcessor
45
+
46
+ from ...activations import ACT2FN
47
+ from ...cache_utils import Cache
48
+ from ...configuration_utils import PretrainedConfig
49
+ from ...feature_extraction_utils import BatchFeature
50
+ from ...image_utils import ImageInput
51
+ from ...modeling_flash_attention_utils import is_flash_attn_available
52
+ from ...modeling_layers import GradientCheckpointingLayer
53
+ from ...processing_utils import MultiModalData, ProcessingKwargs, Unpack, VideosKwargs
54
+ from ...tokenization_utils_base import PreTokenizedInput, TextInput
55
+ from ...utils import is_torchdynamo_compiling, logging
56
+ from ...video_utils import VideoInput
57
+
58
+
59
+ if is_flash_attn_available():
60
+ pass
61
+
62
+
63
+ logger = logging.get_logger(__name__)
64
+
65
+
66
+ class Qwen2_5_VLVisionConfig(PretrainedConfig):
67
+ model_type = "qwen2_5_vl"
68
+ base_config_key = "vision_config"
69
+
70
+ def __init__(
71
+ self,
72
+ depth=32,
73
+ hidden_size=3584,
74
+ hidden_act="silu",
75
+ intermediate_size=3420,
76
+ num_heads=16,
77
+ in_channels=3,
78
+ patch_size=14,
79
+ spatial_merge_size=2,
80
+ temporal_patch_size=2,
81
+ tokens_per_second=4,
82
+ window_size=112,
83
+ out_hidden_size=3584,
84
+ fullatt_block_indexes=[7, 15, 23, 31],
85
+ initializer_range=0.02,
86
+ **kwargs,
87
+ ):
88
+ super().__init__(**kwargs)
89
+
90
+ self.depth = depth
91
+ self.hidden_size = hidden_size
92
+ self.hidden_act = hidden_act
93
+ self.intermediate_size = intermediate_size
94
+ self.num_heads = num_heads
95
+ self.in_channels = in_channels
96
+ self.patch_size = patch_size
97
+ self.spatial_merge_size = spatial_merge_size
98
+ self.temporal_patch_size = temporal_patch_size
99
+ self.tokens_per_second = tokens_per_second
100
+ self.window_size = window_size
101
+ self.fullatt_block_indexes = fullatt_block_indexes
102
+ self.out_hidden_size = out_hidden_size
103
+ self.initializer_range = initializer_range
104
+
105
+
106
+ class Qwen2_5_VLTextConfig(Qwen2VLTextConfig):
107
+ model_type = "qwen2_5_vl_text"
108
+
109
+
110
+ class Qwen2_5_VLConfig(Qwen2VLConfig):
111
+ model_type = "qwen2_5_vl"
112
+ sub_configs = {"vision_config": Qwen2_5_VLVisionConfig, "text_config": Qwen2_5_VLTextConfig}
113
+
114
+
115
+ class Qwen2_5_VLMLP(nn.Module):
116
+ def __init__(self, config, bias: bool = False):
117
+ super().__init__()
118
+ self.hidden_size = config.hidden_size
119
+ self.intermediate_size = config.intermediate_size
120
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=bias)
121
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=bias)
122
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=bias)
123
+ self.act_fn = ACT2FN[config.hidden_act]
124
+
125
+ def forward(self, hidden_state):
126
+ return self.down_proj(self.act_fn(self.gate_proj(hidden_state)) * self.up_proj(hidden_state))
127
+
128
+
129
+ class Qwen2_5_VisionPatchEmbed(PatchEmbed):
130
+ pass
131
+
132
+
133
+ class Qwen2_5_VisionRotaryEmbedding(VisionRotaryEmbedding):
134
+ pass
135
+
136
+
137
+ class Qwen2_5_VLPatchMerger(PatchMerger):
138
+ def __init__(self, dim: int, context_dim: int, spatial_merge_size: int = 2) -> None:
139
+ super().__init__(dim, context_dim, spatial_merge_size)
140
+ self.ln_q = Qwen2RMSNorm(context_dim, eps=1e-6)
141
+
142
+
143
+ class Qwen2_5_VLVisionAttention(VisionAttention):
144
+ def __init__(self, config: Qwen2_5_VLVisionConfig) -> None:
145
+ super().__init__()
146
+ self.dim = config.hidden_size
147
+
148
+
149
+ class Qwen2_5_VLVisionBlock(GradientCheckpointingLayer):
150
+ def __init__(self, config, attn_implementation: str = "sdpa") -> None:
151
+ super().__init__()
152
+ self.norm1 = Qwen2RMSNorm(config.hidden_size, eps=1e-6)
153
+ self.norm2 = Qwen2RMSNorm(config.hidden_size, eps=1e-6)
154
+ self.attn = Qwen2_5_VLVisionAttention(config=config)
155
+ self.mlp = Qwen2_5_VLMLP(config, bias=True)
156
+
157
+ def forward(
158
+ self,
159
+ hidden_states: torch.Tensor,
160
+ cu_seqlens: torch.Tensor,
161
+ rotary_pos_emb: Optional[torch.Tensor] = None,
162
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
163
+ **kwargs,
164
+ ) -> torch.Tensor:
165
+ hidden_states = hidden_states + self.attn(
166
+ self.norm1(hidden_states),
167
+ cu_seqlens=cu_seqlens,
168
+ rotary_pos_emb=rotary_pos_emb,
169
+ position_embeddings=position_embeddings,
170
+ **kwargs,
171
+ )
172
+ hidden_states = hidden_states + self.mlp(self.norm2(hidden_states))
173
+ return hidden_states
174
+
175
+
176
+ class Qwen2_5_VLPreTrainedModel(Qwen2VLPreTrainedModel):
177
+ pass
178
+
179
+
180
+ class Qwen2_5_VisionTransformerPretrainedModel(Qwen2_5_VLPreTrainedModel):
181
+ config: Qwen2_5_VLVisionConfig
182
+ _no_split_modules = ["Qwen2_5_VLVisionBlock"]
183
+
184
+ def __init__(self, config, *inputs, **kwargs) -> None:
185
+ super().__init__(config, *inputs, **kwargs)
186
+ self.spatial_merge_size = config.spatial_merge_size
187
+ self.patch_size = config.patch_size
188
+ self.fullatt_block_indexes = config.fullatt_block_indexes
189
+ self.window_size = config.window_size
190
+ self.spatial_merge_unit = self.spatial_merge_size * self.spatial_merge_size
191
+
192
+ self.patch_embed = Qwen2_5_VisionPatchEmbed(
193
+ patch_size=config.patch_size,
194
+ temporal_patch_size=config.temporal_patch_size,
195
+ in_channels=config.in_channels,
196
+ embed_dim=config.hidden_size,
197
+ )
198
+
199
+ head_dim = config.hidden_size // config.num_heads
200
+ self.rotary_pos_emb = Qwen2_5_VisionRotaryEmbedding(head_dim // 2)
201
+
202
+ self.blocks = nn.ModuleList([Qwen2_5_VLVisionBlock(config) for _ in range(config.depth)])
203
+ self.merger = Qwen2_5_VLPatchMerger(
204
+ dim=config.out_hidden_size,
205
+ context_dim=config.hidden_size,
206
+ spatial_merge_size=config.spatial_merge_size,
207
+ )
208
+ self.gradient_checkpointing = False
209
+
210
+ def rot_pos_emb(self, grid_thw):
211
+ pos_ids = []
212
+ for t, h, w in grid_thw:
213
+ hpos_ids = torch.arange(h).unsqueeze(1).expand(-1, w)
214
+ hpos_ids = hpos_ids.reshape(
215
+ h // self.spatial_merge_size,
216
+ self.spatial_merge_size,
217
+ w // self.spatial_merge_size,
218
+ self.spatial_merge_size,
219
+ )
220
+ hpos_ids = hpos_ids.permute(0, 2, 1, 3)
221
+ hpos_ids = hpos_ids.flatten()
222
+
223
+ wpos_ids = torch.arange(w).unsqueeze(0).expand(h, -1)
224
+ wpos_ids = wpos_ids.reshape(
225
+ h // self.spatial_merge_size,
226
+ self.spatial_merge_size,
227
+ w // self.spatial_merge_size,
228
+ self.spatial_merge_size,
229
+ )
230
+ wpos_ids = wpos_ids.permute(0, 2, 1, 3)
231
+ wpos_ids = wpos_ids.flatten()
232
+ pos_ids.append(torch.stack([hpos_ids, wpos_ids], dim=-1).repeat(t, 1))
233
+ pos_ids = torch.cat(pos_ids, dim=0)
234
+ max_grid_size = grid_thw[:, 1:].max()
235
+ rotary_pos_emb_full = self.rotary_pos_emb(max_grid_size)
236
+ rotary_pos_emb = rotary_pos_emb_full[pos_ids].flatten(1)
237
+ return rotary_pos_emb
238
+
239
+ def get_window_index(self, grid_thw):
240
+ window_index: list = []
241
+ cu_window_seqlens: list = [0]
242
+ window_index_id = 0
243
+ vit_merger_window_size = self.window_size // self.spatial_merge_size // self.patch_size
244
+
245
+ for grid_t, grid_h, grid_w in grid_thw:
246
+ llm_grid_h, llm_grid_w = (
247
+ grid_h // self.spatial_merge_size,
248
+ grid_w // self.spatial_merge_size,
249
+ )
250
+ index = torch.arange(grid_t * llm_grid_h * llm_grid_w).reshape(grid_t, llm_grid_h, llm_grid_w)
251
+ pad_h = vit_merger_window_size - llm_grid_h % vit_merger_window_size
252
+ pad_w = vit_merger_window_size - llm_grid_w % vit_merger_window_size
253
+ num_windows_h = (llm_grid_h + pad_h) // vit_merger_window_size
254
+ num_windows_w = (llm_grid_w + pad_w) // vit_merger_window_size
255
+ index_padded = F.pad(index, (0, pad_w, 0, pad_h), "constant", -100)
256
+ index_padded = index_padded.reshape(
257
+ grid_t,
258
+ num_windows_h,
259
+ vit_merger_window_size,
260
+ num_windows_w,
261
+ vit_merger_window_size,
262
+ )
263
+ index_padded = index_padded.permute(0, 1, 3, 2, 4).reshape(
264
+ grid_t,
265
+ num_windows_h * num_windows_w,
266
+ vit_merger_window_size,
267
+ vit_merger_window_size,
268
+ )
269
+ seqlens = (index_padded != -100).sum([2, 3]).reshape(-1)
270
+ index_padded = index_padded.reshape(-1)
271
+ index_new = index_padded[index_padded != -100]
272
+ window_index.append(index_new + window_index_id)
273
+ cu_seqlens_tmp = seqlens.cumsum(0) * self.spatial_merge_unit + cu_window_seqlens[-1]
274
+ cu_window_seqlens.extend(cu_seqlens_tmp.tolist())
275
+ window_index_id += (grid_t * llm_grid_h * llm_grid_w).item()
276
+ window_index = torch.cat(window_index, dim=0)
277
+
278
+ return window_index, cu_window_seqlens
279
+
280
+ def forward(self, hidden_states: torch.Tensor, grid_thw: torch.Tensor, **kwargs) -> torch.Tensor:
281
+ """
282
+ Args:
283
+ hidden_states (`torch.Tensor` of shape `(seq_len, hidden_size)`):
284
+ The final hidden states of the model.
285
+ grid_thw (`torch.Tensor` of shape `(num_images_or_videos, 3)`):
286
+ The temporal, height and width of feature shape of each image in LLM.
287
+
288
+ Returns:
289
+ `torch.Tensor`: hidden_states.
290
+ """
291
+ hidden_states = self.patch_embed(hidden_states)
292
+ rotary_pos_emb = self.rot_pos_emb(grid_thw)
293
+ window_index, cu_window_seqlens = self.get_window_index(grid_thw)
294
+ cu_window_seqlens = torch.tensor(
295
+ cu_window_seqlens,
296
+ device=hidden_states.device,
297
+ dtype=grid_thw.dtype if torch.jit.is_tracing() else torch.int32,
298
+ )
299
+ cu_window_seqlens = torch.unique_consecutive(cu_window_seqlens)
300
+
301
+ seq_len, _ = hidden_states.size()
302
+ hidden_states = hidden_states.reshape(seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1)
303
+ hidden_states = hidden_states[window_index, :, :]
304
+ hidden_states = hidden_states.reshape(seq_len, -1)
305
+ rotary_pos_emb = rotary_pos_emb.reshape(seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1)
306
+ rotary_pos_emb = rotary_pos_emb[window_index, :, :]
307
+ rotary_pos_emb = rotary_pos_emb.reshape(seq_len, -1)
308
+ emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1)
309
+ position_embeddings = (emb.cos(), emb.sin())
310
+
311
+ cu_seqlens = torch.repeat_interleave(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]).cumsum(
312
+ dim=0,
313
+ # Select dtype based on the following factors:
314
+ # - FA2 requires that cu_seqlens_q must have dtype int32
315
+ # - torch.onnx.export requires that cu_seqlens_q must have same dtype as grid_thw
316
+ # See https://github.com/huggingface/transformers/pull/34852 for more information
317
+ dtype=grid_thw.dtype if torch.jit.is_tracing() else torch.int32,
318
+ )
319
+ cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0)
320
+
321
+ for layer_num, blk in enumerate(self.blocks):
322
+ if layer_num in self.fullatt_block_indexes:
323
+ cu_seqlens_now = cu_seqlens
324
+ else:
325
+ cu_seqlens_now = cu_window_seqlens
326
+
327
+ hidden_states = blk(
328
+ hidden_states,
329
+ cu_seqlens=cu_seqlens_now,
330
+ position_embeddings=position_embeddings,
331
+ **kwargs,
332
+ )
333
+
334
+ hidden_states = self.merger(hidden_states)
335
+ reverse_indices = torch.argsort(window_index)
336
+ hidden_states = hidden_states[reverse_indices, :]
337
+
338
+ return hidden_states
339
+
340
+
341
+ class Qwen2_5_VLModelOutputWithPast(Qwen2VLModelOutputWithPast):
342
+ pass
343
+
344
+
345
+ class Qwen2_5_VLModel(Qwen2VLModel):
346
+ config: Qwen2_5_VLConfig
347
+ base_model_prefix = ""
348
+ _no_split_modules = ["Qwen2_5_VLDecoderLayer", "Qwen2_5_VLVisionBlock"]
349
+
350
+ def __init__(self, config):
351
+ super().__init__(config)
352
+ self.visual = Qwen2_5_VisionTransformerPretrainedModel._from_config(config.vision_config)
353
+
354
+ def get_rope_index(
355
+ self,
356
+ input_ids: Optional[torch.LongTensor] = None,
357
+ image_grid_thw: Optional[torch.LongTensor] = None,
358
+ video_grid_thw: Optional[torch.LongTensor] = None,
359
+ second_per_grid_ts: Optional[torch.Tensor] = None,
360
+ attention_mask: Optional[torch.Tensor] = None,
361
+ ) -> tuple[torch.Tensor, torch.Tensor]:
362
+ """
363
+ Calculate the 3D rope index based on image and video's temporal, height and width in LLM.
364
+
365
+ Explanation:
366
+ Each embedding sequence contains vision embedding and text embedding or just contains text embedding.
367
+
368
+ For pure text embedding sequence, the rotary position embedding has no difference with modern LLMs.
369
+ Examples:
370
+ input_ids: [T T T T T], here T is for text.
371
+ temporal position_ids: [0, 1, 2, 3, 4]
372
+ height position_ids: [0, 1, 2, 3, 4]
373
+ width position_ids: [0, 1, 2, 3, 4]
374
+
375
+ For vision and text embedding sequence, we calculate 3D rotary position embedding for vision part
376
+ and 1D rotary position embedding for text part.
377
+ Examples:
378
+ Temporal (Time): 3 patches, representing different segments of the video in time.
379
+ Height: 2 patches, dividing each frame vertically.
380
+ Width: 2 patches, dividing each frame horizontally.
381
+ We also have some important parameters:
382
+ fps (Frames Per Second): The video's frame rate, set to 1. This means one frame is processed each second.
383
+ tokens_per_second: This is a crucial parameter. It dictates how many "time-steps" or "temporal tokens" are conceptually packed into a one-second interval of the video. In this case, we have 25 tokens per second. So each second of the video will be represented with 25 separate time points. It essentially defines the temporal granularity.
384
+ temporal_patch_size: The number of frames that compose one temporal patch. Here, it's 2 frames.
385
+ interval: The step size for the temporal position IDs, calculated as tokens_per_second * temporal_patch_size / fps. In this case, 25 * 2 / 1 = 50. This means that each temporal patch will be have a difference of 50 in the temporal position IDs.
386
+ input_ids: [V V V V V V V V V V V V T T T T T], here V is for vision.
387
+ vision temporal position_ids: [0, 0, 0, 0, 50, 50, 50, 50, 100, 100, 100, 100]
388
+ vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1]
389
+ vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
390
+ text temporal position_ids: [101, 102, 103, 104, 105]
391
+ text height position_ids: [101, 102, 103, 104, 105]
392
+ text width position_ids: [101, 102, 103, 104, 105]
393
+ Here we calculate the text start position_ids as the max vision position_ids plus 1.
394
+
395
+ Args:
396
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
397
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
398
+ it.
399
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
400
+ The temporal, height and width of feature shape of each image in LLM.
401
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
402
+ The temporal, height and width of feature shape of each video in LLM.
403
+ second_per_grid_ts (`torch.Tensor` of shape `(num_videos)`, *optional*):
404
+ The time interval (in seconds) for each grid along the temporal dimension in the 3D position IDs.
405
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
406
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
407
+
408
+ - 1 for tokens that are **not masked**,
409
+ - 0 for tokens that are **masked**.
410
+
411
+ Returns:
412
+ position_ids (`torch.LongTensor` of shape `(3, batch_size, sequence_length)`)
413
+ mrope_position_deltas (`torch.Tensor` of shape `(batch_size)`)
414
+ """
415
+ spatial_merge_size = self.config.vision_config.spatial_merge_size
416
+ image_token_id = self.config.image_token_id
417
+ video_token_id = self.config.video_token_id
418
+ vision_start_token_id = self.config.vision_start_token_id
419
+ mrope_position_deltas = []
420
+ if input_ids is not None and (image_grid_thw is not None or video_grid_thw is not None):
421
+ total_input_ids = input_ids
422
+ if attention_mask is None:
423
+ attention_mask = torch.ones_like(total_input_ids)
424
+ position_ids = torch.ones(
425
+ 3,
426
+ input_ids.shape[0],
427
+ input_ids.shape[1],
428
+ dtype=input_ids.dtype,
429
+ device=input_ids.device,
430
+ )
431
+ image_index, video_index = 0, 0
432
+ attention_mask = attention_mask.to(total_input_ids.device)
433
+ for i, input_ids in enumerate(total_input_ids):
434
+ input_ids = input_ids[attention_mask[i] == 1]
435
+ image_nums, video_nums = 0, 0
436
+ vision_start_indices = torch.argwhere(input_ids == vision_start_token_id).squeeze(1)
437
+ vision_tokens = input_ids[vision_start_indices + 1]
438
+ image_nums = (vision_tokens == image_token_id).sum()
439
+ video_nums = (vision_tokens == video_token_id).sum()
440
+ input_tokens = input_ids.tolist()
441
+ llm_pos_ids_list: list = []
442
+ st = 0
443
+ remain_images, remain_videos = image_nums, video_nums
444
+ for _ in range(image_nums + video_nums):
445
+ if image_token_id in input_tokens and remain_images > 0:
446
+ ed_image = input_tokens.index(image_token_id, st)
447
+ else:
448
+ ed_image = len(input_tokens) + 1
449
+ if video_token_id in input_tokens and remain_videos > 0:
450
+ ed_video = input_tokens.index(video_token_id, st)
451
+ else:
452
+ ed_video = len(input_tokens) + 1
453
+ if ed_image < ed_video:
454
+ t, h, w = (
455
+ image_grid_thw[image_index][0],
456
+ image_grid_thw[image_index][1],
457
+ image_grid_thw[image_index][2],
458
+ )
459
+ second_per_grid_t = 0
460
+ image_index += 1
461
+ remain_images -= 1
462
+ ed = ed_image
463
+
464
+ else:
465
+ t, h, w = (
466
+ video_grid_thw[video_index][0],
467
+ video_grid_thw[video_index][1],
468
+ video_grid_thw[video_index][2],
469
+ )
470
+ if second_per_grid_ts is not None:
471
+ second_per_grid_t = second_per_grid_ts[video_index]
472
+ else:
473
+ second_per_grid_t = 1.0
474
+ video_index += 1
475
+ remain_videos -= 1
476
+ ed = ed_video
477
+ llm_grid_t, llm_grid_h, llm_grid_w = (
478
+ t.item(),
479
+ h.item() // spatial_merge_size,
480
+ w.item() // spatial_merge_size,
481
+ )
482
+ text_len = ed - st
483
+
484
+ st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
485
+ llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx)
486
+
487
+ range_tensor = torch.arange(llm_grid_t).view(-1, 1)
488
+ expanded_range = range_tensor.expand(-1, llm_grid_h * llm_grid_w)
489
+
490
+ ## normalize type, send to device.
491
+ second_per_grid_t = torch.as_tensor(
492
+ second_per_grid_t, dtype=range_tensor.dtype, device=range_tensor.device
493
+ )
494
+
495
+ time_tensor = expanded_range * second_per_grid_t * self.config.vision_config.tokens_per_second
496
+
497
+ time_tensor_long = time_tensor.long()
498
+ t_index = time_tensor_long.flatten()
499
+
500
+ h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(llm_grid_t, -1, llm_grid_w).flatten()
501
+ w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(llm_grid_t, llm_grid_h, -1).flatten()
502
+ llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + text_len + st_idx)
503
+ st = ed + llm_grid_t * llm_grid_h * llm_grid_w
504
+
505
+ if st < len(input_tokens):
506
+ st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
507
+ text_len = len(input_tokens) - st
508
+ llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx)
509
+
510
+ llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1)
511
+ position_ids[..., i, attention_mask[i] == 1] = llm_positions.to(position_ids.device)
512
+ mrope_position_deltas.append(llm_positions.max() + 1 - len(total_input_ids[i]))
513
+ mrope_position_deltas = torch.tensor(mrope_position_deltas, device=input_ids.device).unsqueeze(1)
514
+ return position_ids, mrope_position_deltas
515
+ else:
516
+ if attention_mask is not None:
517
+ position_ids = attention_mask.long().cumsum(-1) - 1
518
+ position_ids.masked_fill_(attention_mask == 0, 1)
519
+ position_ids = position_ids.unsqueeze(0).expand(3, -1, -1).to(attention_mask.device)
520
+ max_position_ids = position_ids.max(0, keepdim=False)[0].max(-1, keepdim=True)[0]
521
+ mrope_position_deltas = max_position_ids + 1 - attention_mask.shape[-1]
522
+ else:
523
+ position_ids = (
524
+ torch.arange(input_ids.shape[1], device=input_ids.device)
525
+ .view(1, 1, -1)
526
+ .expand(3, input_ids.shape[0], -1)
527
+ )
528
+ mrope_position_deltas = torch.zeros(
529
+ [input_ids.shape[0], 1],
530
+ device=input_ids.device,
531
+ dtype=input_ids.dtype,
532
+ )
533
+
534
+ return position_ids, mrope_position_deltas
535
+
536
+ def forward(
537
+ self,
538
+ input_ids: torch.LongTensor = None,
539
+ attention_mask: Optional[torch.Tensor] = None,
540
+ position_ids: Optional[torch.LongTensor] = None,
541
+ past_key_values: Optional[Cache] = None,
542
+ inputs_embeds: Optional[torch.FloatTensor] = None,
543
+ use_cache: Optional[bool] = None,
544
+ output_attentions: Optional[bool] = None,
545
+ output_hidden_states: Optional[bool] = None,
546
+ return_dict: Optional[bool] = None,
547
+ pixel_values: Optional[torch.Tensor] = None,
548
+ pixel_values_videos: Optional[torch.FloatTensor] = None,
549
+ image_grid_thw: Optional[torch.LongTensor] = None,
550
+ video_grid_thw: Optional[torch.LongTensor] = None,
551
+ rope_deltas: Optional[torch.LongTensor] = None,
552
+ cache_position: Optional[torch.LongTensor] = None,
553
+ second_per_grid_ts: Optional[torch.Tensor] = None,
554
+ **kwargs: Unpack[TransformersKwargs],
555
+ ) -> Union[tuple, Qwen2_5_VLModelOutputWithPast]:
556
+ r"""
557
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
558
+ The temporal, height and width of feature shape of each image in LLM.
559
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
560
+ The temporal, height and width of feature shape of each video in LLM.
561
+ rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
562
+ The rope index difference between sequence length and multimodal rope.
563
+ second_per_grid_ts (`torch.Tensor` of shape `(num_videos)`, *optional*):
564
+ The time interval (in seconds) for each grid along the temporal dimension in the 3D position IDs.
565
+ """
566
+
567
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
568
+ output_hidden_states = (
569
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
570
+ )
571
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
572
+
573
+ if inputs_embeds is None:
574
+ inputs_embeds = self.get_input_embeddings()(input_ids)
575
+
576
+ if pixel_values is not None:
577
+ image_embeds = self.get_image_features(pixel_values, image_grid_thw)
578
+ image_embeds = torch.cat(image_embeds, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
579
+ image_mask, _ = self.get_placeholder_mask(
580
+ input_ids, inputs_embeds=inputs_embeds, image_features=image_embeds
581
+ )
582
+ inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
583
+
584
+ if pixel_values_videos is not None:
585
+ video_embeds = self.get_video_features(pixel_values_videos, video_grid_thw)
586
+ video_embeds = torch.cat(video_embeds, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
587
+ _, video_mask = self.get_placeholder_mask(
588
+ input_ids, inputs_embeds=inputs_embeds, video_features=video_embeds
589
+ )
590
+ inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds)
591
+
592
+ if position_ids is None:
593
+ # Calculate RoPE index once per generation in the pre-fill stage only.
594
+ # When compiling, we can't check tensor values thus we check only input length
595
+ # It is safe to assume that `length!=1` means we're in pre-fill because compiled
596
+ # models currently cannot do asssisted decoding
597
+ prefill_compiled_stage = is_torchdynamo_compiling() and (
598
+ (input_ids is not None and input_ids.shape[1] != 1)
599
+ or (inputs_embeds is not None and inputs_embeds.shape[1] != 1)
600
+ )
601
+ prefill_noncompiled_stage = not is_torchdynamo_compiling() and (
602
+ (cache_position is not None and cache_position[0] == 0)
603
+ or (past_key_values is None or past_key_values.get_seq_length() == 0)
604
+ )
605
+ if (prefill_compiled_stage or prefill_noncompiled_stage) or self.rope_deltas is None:
606
+ position_ids, rope_deltas = self.get_rope_index(
607
+ input_ids,
608
+ image_grid_thw,
609
+ video_grid_thw,
610
+ second_per_grid_ts=second_per_grid_ts,
611
+ attention_mask=attention_mask,
612
+ )
613
+ self.rope_deltas = rope_deltas
614
+ else:
615
+ batch_size, seq_length, _ = inputs_embeds.shape
616
+ position_ids = torch.arange(seq_length, device=inputs_embeds.device)
617
+ position_ids = position_ids.view(1, 1, -1).expand(3, batch_size, -1)
618
+ if cache_position is not None:
619
+ delta = (cache_position[0] + self.rope_deltas).to(inputs_embeds.device)
620
+ else:
621
+ delta = torch.zeros((batch_size, seq_length), device=inputs_embeds.device)
622
+ delta = delta.repeat_interleave(batch_size // delta.shape[0], dim=1)
623
+ position_ids += delta.to(position_ids.device)
624
+
625
+ outputs = self.language_model(
626
+ input_ids=None,
627
+ position_ids=position_ids,
628
+ attention_mask=attention_mask,
629
+ past_key_values=past_key_values,
630
+ inputs_embeds=inputs_embeds,
631
+ use_cache=use_cache,
632
+ output_attentions=output_attentions,
633
+ output_hidden_states=output_hidden_states,
634
+ return_dict=True,
635
+ cache_position=cache_position,
636
+ **kwargs,
637
+ )
638
+
639
+ output = Qwen2_5_VLModelOutputWithPast(
640
+ last_hidden_state=outputs.last_hidden_state,
641
+ past_key_values=outputs.past_key_values,
642
+ hidden_states=outputs.hidden_states,
643
+ attentions=outputs.attentions,
644
+ rope_deltas=self.rope_deltas,
645
+ )
646
+ return output if return_dict else output.to_tuple()
647
+
648
+
649
+ class Qwen2_5_VLCausalLMOutputWithPast(Qwen2VLCausalLMOutputWithPast):
650
+ pass
651
+
652
+
653
+ class Qwen2_5_VLForConditionalGeneration(Qwen2VLForConditionalGeneration):
654
+ def forward(
655
+ self,
656
+ input_ids: torch.LongTensor = None,
657
+ attention_mask: Optional[torch.Tensor] = None,
658
+ position_ids: Optional[torch.LongTensor] = None,
659
+ past_key_values: Optional[Cache] = None,
660
+ inputs_embeds: Optional[torch.FloatTensor] = None,
661
+ labels: Optional[torch.LongTensor] = None,
662
+ use_cache: Optional[bool] = None,
663
+ output_attentions: Optional[bool] = None,
664
+ output_hidden_states: Optional[bool] = None,
665
+ pixel_values: Optional[torch.Tensor] = None,
666
+ pixel_values_videos: Optional[torch.FloatTensor] = None,
667
+ image_grid_thw: Optional[torch.LongTensor] = None,
668
+ video_grid_thw: Optional[torch.LongTensor] = None,
669
+ rope_deltas: Optional[torch.LongTensor] = None,
670
+ cache_position: Optional[torch.LongTensor] = None,
671
+ second_per_grid_ts: Optional[torch.Tensor] = None,
672
+ logits_to_keep: Union[int, torch.Tensor] = 0,
673
+ **kwargs: Unpack[TransformersKwargs],
674
+ ) -> Union[tuple, Qwen2_5_VLCausalLMOutputWithPast]:
675
+ r"""
676
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
677
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
678
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
679
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
680
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
681
+ The temporal, height and width of feature shape of each image in LLM.
682
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
683
+ The temporal, height and width of feature shape of each video in LLM.
684
+ rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
685
+ The rope index difference between sequence length and multimodal rope.
686
+ second_per_grid_ts (`torch.Tensor` of shape `(num_videos)`, *optional*):
687
+ The time interval (in seconds) for each grid along the temporal dimension in the 3D position IDs.
688
+
689
+ Example:
690
+
691
+ ```python
692
+ >>> from PIL import Image
693
+ >>> import requests
694
+ >>> from transformers import AutoProcessor, Qwen2_5_VLForConditionalGeneration
695
+
696
+ >>> model = Qwen2_5_VLForConditionalGeneration.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct")
697
+ >>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct")
698
+
699
+ >>> messages = [
700
+ {
701
+ "role": "user",
702
+ "content": [
703
+ {"type": "image"},
704
+ {"type": "text", "text": "What is shown in this image?"},
705
+ ],
706
+ },
707
+ ]
708
+ >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
709
+ >>> image = Image.open(requests.get(url, stream=True).raw)
710
+
711
+ >>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
712
+ >>> inputs = processor(text=[text], images=[image], vision_infos=[vision_infos])
713
+
714
+ >>> # Generate
715
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
716
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
717
+ "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 ..."
718
+ ```"""
719
+
720
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
721
+ output_hidden_states = (
722
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
723
+ )
724
+
725
+ outputs = self.model(
726
+ input_ids=input_ids,
727
+ pixel_values=pixel_values,
728
+ pixel_values_videos=pixel_values_videos,
729
+ image_grid_thw=image_grid_thw,
730
+ video_grid_thw=video_grid_thw,
731
+ second_per_grid_ts=second_per_grid_ts,
732
+ position_ids=position_ids,
733
+ attention_mask=attention_mask,
734
+ past_key_values=past_key_values,
735
+ inputs_embeds=inputs_embeds,
736
+ use_cache=use_cache,
737
+ output_attentions=output_attentions,
738
+ output_hidden_states=output_hidden_states,
739
+ return_dict=True,
740
+ cache_position=cache_position,
741
+ **kwargs,
742
+ )
743
+
744
+ hidden_states = outputs[0]
745
+
746
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
747
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
748
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
749
+
750
+ loss = None
751
+ if labels is not None:
752
+ loss = self.loss_function(
753
+ logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
754
+ )
755
+
756
+ return Qwen2_5_VLCausalLMOutputWithPast(
757
+ loss=loss,
758
+ logits=logits,
759
+ past_key_values=outputs.past_key_values,
760
+ hidden_states=outputs.hidden_states,
761
+ attentions=outputs.attentions,
762
+ rope_deltas=outputs.rope_deltas,
763
+ )
764
+
765
+ def prepare_inputs_for_generation(
766
+ self,
767
+ input_ids,
768
+ past_key_values=None,
769
+ attention_mask=None,
770
+ inputs_embeds=None,
771
+ cache_position=None,
772
+ position_ids=None,
773
+ use_cache=True,
774
+ pixel_values=None,
775
+ pixel_values_videos=None,
776
+ image_grid_thw=None,
777
+ video_grid_thw=None,
778
+ second_per_grid_ts=None,
779
+ **kwargs,
780
+ ):
781
+ # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
782
+
783
+ model_inputs = super().prepare_inputs_for_generation(
784
+ input_ids,
785
+ past_key_values=past_key_values,
786
+ attention_mask=attention_mask,
787
+ inputs_embeds=inputs_embeds,
788
+ cache_position=cache_position,
789
+ position_ids=position_ids,
790
+ pixel_values=pixel_values,
791
+ pixel_values_videos=pixel_values_videos,
792
+ image_grid_thw=image_grid_thw,
793
+ video_grid_thw=video_grid_thw,
794
+ second_per_grid_ts=second_per_grid_ts,
795
+ use_cache=use_cache,
796
+ **kwargs,
797
+ )
798
+
799
+ # Qwen2-5-VL position_ids are prepared with rope_deltas
800
+ if position_ids is None:
801
+ # Calculate RoPE index once per generation in the pre-fill stage only.
802
+ # When compiling, we can't check tensor values thus we check only input length
803
+ # It is safe to assume that `length!=1` means we're in pre-fill because compiled
804
+ # models currently cannot do asssisted decoding
805
+ if cache_position[0] == 0 or self.model.rope_deltas is None:
806
+ vision_positions, rope_deltas = self.model.get_rope_index(
807
+ model_inputs.get("input_ids", None),
808
+ image_grid_thw=image_grid_thw,
809
+ video_grid_thw=video_grid_thw,
810
+ second_per_grid_ts=second_per_grid_ts,
811
+ attention_mask=attention_mask,
812
+ )
813
+ self.model.rope_deltas = rope_deltas
814
+ # then use the prev pre-calculated rope-deltas to get the correct position ids
815
+ elif "position_ids" in model_inputs:
816
+ position_ids = model_inputs["position_ids"][None, ...]
817
+ delta = self.model.rope_deltas
818
+ delta = delta.repeat_interleave(position_ids.shape[1] // delta.shape[0], dim=0)
819
+ vision_positions = position_ids + delta.expand_as(position_ids)
820
+ vision_positions = vision_positions.expand(3, vision_positions.shape[1], -1)
821
+
822
+ # Concatenate "text + vision" positions into [4, bs, seq-len]
823
+ if "position_ids" not in model_inputs:
824
+ text_positions = torch.arange(input_ids, device=input_ids.device)[None, None, :]
825
+ else:
826
+ text_positions = model_inputs["position_ids"][None, ...]
827
+ model_inputs["position_ids"] = torch.cat([text_positions, vision_positions], dim=0)
828
+
829
+ if cache_position[0] != 0:
830
+ model_inputs["pixel_values"] = None
831
+ model_inputs["pixel_values_videos"] = None
832
+
833
+ return model_inputs
834
+
835
+
836
+ class Qwen2_5_VLVideosProcessorKwargs(VideosKwargs, total=False):
837
+ fps: Union[list[float], float]
838
+
839
+
840
+ class Qwen2_5_VLImagesKwargs(Qwen2VLImagesKwargs):
841
+ pass
842
+
843
+
844
+ class Qwen2_5_VLProcessorKwargs(ProcessingKwargs, total=False):
845
+ images_kwargs: Qwen2_5_VLImagesKwargs
846
+ videos_kwargs: Qwen2_5_VLVideosProcessorKwargs
847
+ _defaults = {
848
+ "text_kwargs": {
849
+ "padding": False,
850
+ "return_mm_token_type_ids": False,
851
+ },
852
+ }
853
+
854
+
855
+ class Qwen2_5_VLProcessor(Qwen2VLProcessor):
856
+ r"""
857
+ Constructs a Qwen2.5-VL processor which wraps a Qwen2.5-VL image processor and a Qwen2 tokenizer into a single processor.
858
+ [`Qwen2_5_VLProcessor`] offers all the functionalities of [`Qwen2VLImageProcessor`] and [`Qwen2TokenizerFast`]. See the
859
+ [`~Qwen2_5_VLProcessor.__call__`] and [`~Qwen2_5_VLProcessor.decode`] for more information.
860
+ Args:
861
+ image_processor ([`Qwen2VLImageProcessor`], *optional*):
862
+ The image processor is a required input.
863
+ tokenizer ([`Qwen2TokenizerFast`], *optional*):
864
+ The tokenizer is a required input.
865
+ video_processor ([`Qwen2_5_VLVideoProcessor`], *optional*):
866
+ The video processor is a required input.
867
+ chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
868
+ in a chat into a tokenizable string.
869
+ """
870
+
871
+ image_processor_class = "AutoImageProcessor"
872
+
873
+ @property
874
+ def model_input_names(self):
875
+ tokenizer_input_names = self.tokenizer.model_input_names
876
+ image_processor_input_names = self.image_processor.model_input_names
877
+ names_from_processor = list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
878
+ return names_from_processor + ["second_per_grid_ts"]
879
+
880
+ def __call__(
881
+ self,
882
+ images: ImageInput = None,
883
+ text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
884
+ videos: VideoInput = None,
885
+ **kwargs: Unpack[Qwen2_5_VLProcessorKwargs],
886
+ ) -> BatchFeature:
887
+ """
888
+ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
889
+ and `kwargs` arguments to Qwen2TokenizerFast's [`~Qwen2TokenizerFast.__call__`] if `text` is not `None` to encode
890
+ the text. To prepare the vision inputs, this method forwards the `vision_infos` and `kwrags` arguments to
891
+ Qwen2VLImageProcessor's [`~Qwen2VLImageProcessor.__call__`] if `vision_infos` is not `None`.
892
+
893
+ Args:
894
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
895
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
896
+ tensor. Both channels-first and channels-last formats are supported.
897
+ text (`str`, `list[str]`, `list[list[str]]`):
898
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
899
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
900
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
901
+ videos (`np.ndarray`, `torch.Tensor`, `list[np.ndarray]`, `list[torch.Tensor]`):
902
+ The image or batch of videos to be prepared. Each video can be a 4D NumPy array or PyTorch
903
+ tensor, or a nested list of 3D frames. Both channels-first and channels-last formats are supported.
904
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
905
+ If set, will return tensors of a particular framework. Acceptable values are:
906
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
907
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
908
+ - `'np'`: Return NumPy `np.ndarray` objects.
909
+ - `'jax'`: Return JAX `jnp.ndarray` objects.
910
+
911
+ Returns:
912
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
913
+
914
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
915
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
916
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
917
+ `None`).
918
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
919
+ - **pixel_values_videos** -- Pixel values of videos to be fed to a model. Returned when `videos` is not `None`.
920
+ - **image_grid_thw** -- List of image 3D grid in LLM. Returned when `images` is not `None`.
921
+ - **video_grid_thw** -- List of video 3D grid in LLM. Returned when `videos` is not `None`.
922
+ - **second_per_grid_ts** -- List of video seconds per time grid. Returned when `videos` is not `None`.
923
+ """
924
+ output_kwargs = self._merge_kwargs(
925
+ Qwen2_5_VLProcessorKwargs,
926
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
927
+ **kwargs,
928
+ )
929
+
930
+ image_inputs = videos_inputs = {}
931
+ if images is not None:
932
+ image_inputs = self.image_processor(images=images, **output_kwargs["images_kwargs"])
933
+ image_grid_thw = image_inputs["image_grid_thw"]
934
+
935
+ if videos is not None:
936
+ fps = output_kwargs["videos_kwargs"].get("fps", 2.0)
937
+ videos_inputs = self.video_processor(videos=videos, **output_kwargs["videos_kwargs"])
938
+ video_grid_thw = videos_inputs["video_grid_thw"]
939
+
940
+ if isinstance(fps, (int, float)):
941
+ second_per_grid_ts = [self.video_processor.temporal_patch_size / fps] * len(video_grid_thw)
942
+ elif hasattr(fps, "__len__") and len(fps) == len(video_grid_thw):
943
+ second_per_grid_ts = [self.video_processor.temporal_patch_size / tmp for tmp in fps]
944
+ else:
945
+ raise ValueError(
946
+ f"The length of fps ({len(fps) if hasattr(fps, '__len__') else fps}) must be equal to the length of video_grid_thw ({len(video_grid_thw)}) or fps should be a single number."
947
+ )
948
+ videos_inputs.update({"second_per_grid_ts": second_per_grid_ts})
949
+
950
+ if not isinstance(text, list):
951
+ text = [text]
952
+
953
+ text = text.copy() # below lines change text in-place
954
+ if images is not None:
955
+ merge_length = self.image_processor.merge_size**2
956
+ index = 0
957
+ for i in range(len(text)):
958
+ while self.image_token in text[i]:
959
+ num_image_tokens = image_grid_thw[index].prod() // merge_length
960
+ text[i] = text[i].replace(self.image_token, "<|placeholder|>" * num_image_tokens, 1)
961
+ index += 1
962
+ text[i] = text[i].replace("<|placeholder|>", self.image_token)
963
+
964
+ if videos is not None:
965
+ merge_length = self.video_processor.merge_size**2
966
+ index = 0
967
+ for i in range(len(text)):
968
+ while self.video_token in text[i]:
969
+ num_video_tokens = video_grid_thw[index].prod() // merge_length
970
+ text[i] = text[i].replace(self.video_token, "<|placeholder|>" * num_video_tokens, 1)
971
+ index += 1
972
+ text[i] = text[i].replace("<|placeholder|>", self.video_token)
973
+
974
+ return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
975
+ return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", None)
976
+ text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
977
+ self._check_special_mm_tokens(text, text_inputs, modalities=["image", "video"])
978
+
979
+ if return_mm_token_type_ids:
980
+ array_ids = np.array(text_inputs["input_ids"])
981
+ mm_token_type_ids = np.zeros_like(text_inputs["input_ids"])
982
+ mm_token_type_ids[array_ids == self.image_token_id] = 1
983
+ text_inputs["mm_token_type_ids"] = mm_token_type_ids.tolist()
984
+
985
+ return BatchFeature(data={**text_inputs, **image_inputs, **videos_inputs}, tensor_type=return_tensors)
986
+
987
+ def _get_num_multimodal_tokens(self, image_sizes=None, video_sizes=None, **kwargs):
988
+ """
989
+ Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
990
+ Args:
991
+ image_sizes (`list[list[int]]`, *optional*):
992
+ The input sizes formatted as (height, width) per each image.
993
+ video_sizes (`list[list[int]]`, *optional*):
994
+ The input sizes formatted as (num_frames, height, width) per each video.
995
+ Returns:
996
+ `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
997
+ input modalities, along with other useful data.
998
+ """
999
+
1000
+ vision_data = {}
1001
+ if image_sizes is not None:
1002
+ images_kwargs = Qwen2_5_VLProcessorKwargs._defaults.get("images_kwargs", {})
1003
+ images_kwargs.update(kwargs)
1004
+ merge_size = images_kwargs.get("merge_size", None) or self.image_processor.merge_size
1005
+
1006
+ num_image_patches = [
1007
+ self.image_processor.get_number_of_image_patches(*image_size, images_kwargs)
1008
+ for image_size in image_sizes
1009
+ ]
1010
+ num_image_tokens = [(num_patches // merge_size**2) for num_patches in num_image_patches]
1011
+ vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
1012
+
1013
+ if video_sizes is not None:
1014
+ videos_kwargs = Qwen2_5_VLProcessorKwargs._defaults.get("videos_kwargs", {})
1015
+ videos_kwargs.update(kwargs)
1016
+ num_video_patches = [
1017
+ self.video_processor.get_number_of_video_patches(*video_size, videos_kwargs)
1018
+ for video_size in video_sizes
1019
+ ]
1020
+ num_video_tokens = [(num_patches // merge_size**2) for num_patches in num_video_patches]
1021
+ vision_data["num_video_tokens"] = num_video_tokens
1022
+
1023
+ return MultiModalData(**vision_data)
1024
+
1025
+
1026
+ __all__ = [
1027
+ "Qwen2_5_VLConfig",
1028
+ "Qwen2_5_VLTextConfig",
1029
+ "Qwen2_5_VLForConditionalGeneration",
1030
+ "Qwen2_5_VLModel",
1031
+ "Qwen2_5_VLPreTrainedModel",
1032
+ "Qwen2_5_VLProcessor",
1033
+ "Qwen2_5_VLTextModel", # noqa: F822
1034
+ ]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_5_vl/processing_qwen2_5_vl.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/qwen2_5_vl/modular_qwen2_5_vl.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_qwen2_5_vl.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2025 The Qwen Team and The HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
11
+ # and OPT implementations in this library. It has been modified from its
12
+ # original forms to accommodate minor architectural differences compared
13
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
14
+ #
15
+ # Licensed under the Apache License, Version 2.0 (the "License");
16
+ # you may not use this file except in compliance with the License.
17
+ # You may obtain a copy of the License at
18
+ #
19
+ # http://www.apache.org/licenses/LICENSE-2.0
20
+ #
21
+ # Unless required by applicable law or agreed to in writing, software
22
+ # distributed under the License is distributed on an "AS IS" BASIS,
23
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24
+ # See the License for the specific language governing permissions and
25
+ # limitations under the License.
26
+
27
+ from typing import Optional, Union
28
+
29
+ import numpy as np
30
+
31
+ from ...feature_extraction_utils import BatchFeature
32
+ from ...image_utils import ImageInput
33
+ from ...processing_utils import ImagesKwargs, MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack, VideosKwargs
34
+ from ...tokenization_utils_base import PreTokenizedInput, TextInput
35
+ from ...video_utils import VideoInput
36
+
37
+
38
+ class Qwen2_5_VLVideosProcessorKwargs(VideosKwargs, total=False):
39
+ fps: Union[list[float], float]
40
+
41
+
42
+ class Qwen2_5_VLImagesKwargs(ImagesKwargs):
43
+ min_pixels: Optional[int]
44
+ max_pixels: Optional[int]
45
+ patch_size: Optional[int]
46
+ temporal_patch_size: Optional[int]
47
+ merge_size: Optional[int]
48
+
49
+
50
+ class Qwen2_5_VLProcessorKwargs(ProcessingKwargs, total=False):
51
+ images_kwargs: Qwen2_5_VLImagesKwargs
52
+ videos_kwargs: Qwen2_5_VLVideosProcessorKwargs
53
+ _defaults = {
54
+ "text_kwargs": {
55
+ "padding": False,
56
+ "return_mm_token_type_ids": False,
57
+ },
58
+ }
59
+
60
+
61
+ class Qwen2_5_VLProcessor(ProcessorMixin):
62
+ r"""
63
+ Constructs a Qwen2.5-VL processor which wraps a Qwen2.5-VL image processor and a Qwen2 tokenizer into a single processor.
64
+ [`Qwen2_5_VLProcessor`] offers all the functionalities of [`Qwen2VLImageProcessor`] and [`Qwen2TokenizerFast`]. See the
65
+ [`~Qwen2_5_VLProcessor.__call__`] and [`~Qwen2_5_VLProcessor.decode`] for more information.
66
+ Args:
67
+ image_processor ([`Qwen2VLImageProcessor`], *optional*):
68
+ The image processor is a required input.
69
+ tokenizer ([`Qwen2TokenizerFast`], *optional*):
70
+ The tokenizer is a required input.
71
+ video_processor ([`Qwen2_5_VLVideoProcessor`], *optional*):
72
+ The video processor is a required input.
73
+ chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
74
+ in a chat into a tokenizable string.
75
+ """
76
+
77
+ attributes = ["image_processor", "tokenizer", "video_processor"]
78
+
79
+ image_processor_class = "AutoImageProcessor"
80
+ video_processor_class = "AutoVideoProcessor"
81
+ tokenizer_class = ("Qwen2Tokenizer", "Qwen2TokenizerFast")
82
+
83
+ def __init__(self, image_processor=None, tokenizer=None, video_processor=None, chat_template=None, **kwargs):
84
+ self.image_token = "<|image_pad|>" if not hasattr(tokenizer, "image_token") else tokenizer.image_token
85
+ self.video_token = "<|video_pad|>" if not hasattr(tokenizer, "video_token") else tokenizer.video_token
86
+ self.image_token_id = (
87
+ tokenizer.image_token_id
88
+ if getattr(tokenizer, "image_token_id", None)
89
+ else tokenizer.convert_tokens_to_ids(self.image_token)
90
+ )
91
+ self.video_token_id = (
92
+ tokenizer.video_token_id
93
+ if getattr(tokenizer, "video_token_id", None)
94
+ else tokenizer.convert_tokens_to_ids(self.video_token)
95
+ )
96
+ super().__init__(image_processor, tokenizer, video_processor, chat_template=chat_template)
97
+
98
+ def __call__(
99
+ self,
100
+ images: ImageInput = None,
101
+ text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
102
+ videos: VideoInput = None,
103
+ **kwargs: Unpack[Qwen2_5_VLProcessorKwargs],
104
+ ) -> BatchFeature:
105
+ """
106
+ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
107
+ and `kwargs` arguments to Qwen2TokenizerFast's [`~Qwen2TokenizerFast.__call__`] if `text` is not `None` to encode
108
+ the text. To prepare the vision inputs, this method forwards the `vision_infos` and `kwrags` arguments to
109
+ Qwen2VLImageProcessor's [`~Qwen2VLImageProcessor.__call__`] if `vision_infos` is not `None`.
110
+
111
+ Args:
112
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
113
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
114
+ tensor. Both channels-first and channels-last formats are supported.
115
+ text (`str`, `list[str]`, `list[list[str]]`):
116
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
117
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
118
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
119
+ videos (`np.ndarray`, `torch.Tensor`, `list[np.ndarray]`, `list[torch.Tensor]`):
120
+ The image or batch of videos to be prepared. Each video can be a 4D NumPy array or PyTorch
121
+ tensor, or a nested list of 3D frames. Both channels-first and channels-last formats are supported.
122
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
123
+ If set, will return tensors of a particular framework. Acceptable values are:
124
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
125
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
126
+ - `'np'`: Return NumPy `np.ndarray` objects.
127
+ - `'jax'`: Return JAX `jnp.ndarray` objects.
128
+
129
+ Returns:
130
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
131
+
132
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
133
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
134
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
135
+ `None`).
136
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
137
+ - **pixel_values_videos** -- Pixel values of videos to be fed to a model. Returned when `videos` is not `None`.
138
+ - **image_grid_thw** -- List of image 3D grid in LLM. Returned when `images` is not `None`.
139
+ - **video_grid_thw** -- List of video 3D grid in LLM. Returned when `videos` is not `None`.
140
+ - **second_per_grid_ts** -- List of video seconds per time grid. Returned when `videos` is not `None`.
141
+ """
142
+ output_kwargs = self._merge_kwargs(
143
+ Qwen2_5_VLProcessorKwargs,
144
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
145
+ **kwargs,
146
+ )
147
+
148
+ image_inputs = videos_inputs = {}
149
+ if images is not None:
150
+ image_inputs = self.image_processor(images=images, **output_kwargs["images_kwargs"])
151
+ image_grid_thw = image_inputs["image_grid_thw"]
152
+
153
+ if videos is not None:
154
+ fps = output_kwargs["videos_kwargs"].get("fps", 2.0)
155
+ videos_inputs = self.video_processor(videos=videos, **output_kwargs["videos_kwargs"])
156
+ video_grid_thw = videos_inputs["video_grid_thw"]
157
+
158
+ if isinstance(fps, (int, float)):
159
+ second_per_grid_ts = [self.video_processor.temporal_patch_size / fps] * len(video_grid_thw)
160
+ elif hasattr(fps, "__len__") and len(fps) == len(video_grid_thw):
161
+ second_per_grid_ts = [self.video_processor.temporal_patch_size / tmp for tmp in fps]
162
+ else:
163
+ raise ValueError(
164
+ f"The length of fps ({len(fps) if hasattr(fps, '__len__') else fps}) must be equal to the length of video_grid_thw ({len(video_grid_thw)}) or fps should be a single number."
165
+ )
166
+ videos_inputs.update({"second_per_grid_ts": second_per_grid_ts})
167
+
168
+ if not isinstance(text, list):
169
+ text = [text]
170
+
171
+ text = text.copy() # below lines change text in-place
172
+ if images is not None:
173
+ merge_length = self.image_processor.merge_size**2
174
+ index = 0
175
+ for i in range(len(text)):
176
+ while self.image_token in text[i]:
177
+ num_image_tokens = image_grid_thw[index].prod() // merge_length
178
+ text[i] = text[i].replace(self.image_token, "<|placeholder|>" * num_image_tokens, 1)
179
+ index += 1
180
+ text[i] = text[i].replace("<|placeholder|>", self.image_token)
181
+
182
+ if videos is not None:
183
+ merge_length = self.video_processor.merge_size**2
184
+ index = 0
185
+ for i in range(len(text)):
186
+ while self.video_token in text[i]:
187
+ num_video_tokens = video_grid_thw[index].prod() // merge_length
188
+ text[i] = text[i].replace(self.video_token, "<|placeholder|>" * num_video_tokens, 1)
189
+ index += 1
190
+ text[i] = text[i].replace("<|placeholder|>", self.video_token)
191
+
192
+ return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
193
+ return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", None)
194
+ text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
195
+ self._check_special_mm_tokens(text, text_inputs, modalities=["image", "video"])
196
+
197
+ if return_mm_token_type_ids:
198
+ array_ids = np.array(text_inputs["input_ids"])
199
+ mm_token_type_ids = np.zeros_like(text_inputs["input_ids"])
200
+ mm_token_type_ids[array_ids == self.image_token_id] = 1
201
+ text_inputs["mm_token_type_ids"] = mm_token_type_ids.tolist()
202
+
203
+ return BatchFeature(data={**text_inputs, **image_inputs, **videos_inputs}, tensor_type=return_tensors)
204
+
205
+ def _get_num_multimodal_tokens(self, image_sizes=None, video_sizes=None, **kwargs):
206
+ """
207
+ Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
208
+ Args:
209
+ image_sizes (`list[list[int]]`, *optional*):
210
+ The input sizes formatted as (height, width) per each image.
211
+ video_sizes (`list[list[int]]`, *optional*):
212
+ The input sizes formatted as (num_frames, height, width) per each video.
213
+ Returns:
214
+ `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
215
+ input modalities, along with other useful data.
216
+ """
217
+
218
+ vision_data = {}
219
+ if image_sizes is not None:
220
+ images_kwargs = Qwen2_5_VLProcessorKwargs._defaults.get("images_kwargs", {})
221
+ images_kwargs.update(kwargs)
222
+ merge_size = images_kwargs.get("merge_size", None) or self.image_processor.merge_size
223
+
224
+ num_image_patches = [
225
+ self.image_processor.get_number_of_image_patches(*image_size, images_kwargs)
226
+ for image_size in image_sizes
227
+ ]
228
+ num_image_tokens = [(num_patches // merge_size**2) for num_patches in num_image_patches]
229
+ vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
230
+
231
+ if video_sizes is not None:
232
+ videos_kwargs = Qwen2_5_VLProcessorKwargs._defaults.get("videos_kwargs", {})
233
+ videos_kwargs.update(kwargs)
234
+ num_video_patches = [
235
+ self.video_processor.get_number_of_video_patches(*video_size, videos_kwargs)
236
+ for video_size in video_sizes
237
+ ]
238
+ num_video_tokens = [(num_patches // merge_size**2) for num_patches in num_video_patches]
239
+ vision_data["num_video_tokens"] = num_video_tokens
240
+
241
+ return MultiModalData(**vision_data)
242
+
243
+ def batch_decode(self, *args, **kwargs):
244
+ """
245
+ This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
246
+ refer to the docstring of this method for more information.
247
+ """
248
+ return self.tokenizer.batch_decode(*args, **kwargs)
249
+
250
+ def decode(self, *args, **kwargs):
251
+ """
252
+ This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
253
+ the docstring of this method for more information.
254
+ """
255
+ return self.tokenizer.decode(*args, **kwargs)
256
+
257
+ def post_process_image_text_to_text(
258
+ self, generated_outputs, skip_special_tokens=True, clean_up_tokenization_spaces=False, **kwargs
259
+ ):
260
+ """
261
+ Post-process the output of the model to decode the text.
262
+
263
+ Args:
264
+ generated_outputs (`torch.Tensor` or `np.ndarray`):
265
+ The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)`
266
+ or `(sequence_length,)`.
267
+ skip_special_tokens (`bool`, *optional*, defaults to `True`):
268
+ Whether or not to remove special tokens in the output. Argument passed to the tokenizer's `batch_decode` method.
269
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
270
+ Whether or not to clean up the tokenization spaces. Argument passed to the tokenizer's `batch_decode` method.
271
+ **kwargs:
272
+ Additional arguments to be passed to the tokenizer's `batch_decode method`.
273
+
274
+ Returns:
275
+ `list[str]`: The decoded text.
276
+ """
277
+ return self.tokenizer.batch_decode(
278
+ generated_outputs,
279
+ skip_special_tokens=skip_special_tokens,
280
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
281
+ **kwargs,
282
+ )
283
+
284
+ @property
285
+ def model_input_names(self):
286
+ tokenizer_input_names = self.tokenizer.model_input_names
287
+ image_processor_input_names = self.image_processor.model_input_names
288
+ names_from_processor = list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
289
+ return names_from_processor + ["second_per_grid_ts"]
290
+
291
+
292
+ __all__ = ["Qwen2_5_VLProcessor"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_audio/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_qwen2_audio import *
22
+ from .modeling_qwen2_audio import *
23
+ from .processing_qwen2_audio 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__)
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_audio/configuration_qwen2_audio.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft Research & University of Wisconsin-Madison and the HuggingFace Inc. team. All rights reserved.
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
+ """Qwen2Audio model configuration"""
15
+
16
+ from ...configuration_utils import PretrainedConfig
17
+ from ...utils import logging
18
+ from ..auto import CONFIG_MAPPING, AutoConfig
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class Qwen2AudioEncoderConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`Qwen2AudioEncoder`]. It is used to instantiate a
27
+ Qwen2-Audio audio encoder according to the specified arguments, defining the model architecture. Instantiating a
28
+ configuration with the defaults will yield a similar configuration to that of the audio encoder of the Qwen2-Audio
29
+ architecture.
30
+
31
+ e.g. [Qwen/Qwen2-Audio-7B](https://huggingface.co/Qwen/Qwen2-Audio-7B)
32
+
33
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
34
+ documentation from [`PretrainedConfig`] for more information.
35
+
36
+ Args:
37
+ num_mel_bins (`int`, *optional*, defaults to 128):
38
+ Number of mel features used per input features. Should correspond to the value used in the
39
+ `Qwen2AudioProcessor` class.
40
+ encoder_layers (`int`, *optional*, defaults to 32):
41
+ Number of encoder layers.
42
+ encoder_attention_heads (`int`, *optional*, defaults to 20):
43
+ Number of attention heads for each attention layer in the Transformer encoder.
44
+ encoder_ffn_dim (`int`, *optional*, defaults to 5120):
45
+ Dimensionality of the "intermediate" (often named feed-forward) layer in encoder.
46
+ encoder_layerdrop (`float`, *optional*, defaults to 0.0):
47
+ The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556)
48
+ for more details.
49
+ d_model (`int`, *optional*, defaults to 1280):
50
+ Dimensionality of the layers.
51
+ dropout (`float`, *optional*, defaults to 0.0):
52
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
53
+ attention_dropout (`float`, *optional*, defaults to 0.0):
54
+ The dropout ratio for the attention probabilities.
55
+ activation_function (`str`, *optional*, defaults to `"gelu"`):
56
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
57
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
58
+ activation_dropout (`float`, *optional*, defaults to 0.0):
59
+ The dropout ratio for activations inside the fully connected layer.
60
+ scale_embedding (`bool`, *optional*, defaults to `False`):
61
+ Scale embeddings by diving by sqrt(d_model).
62
+ initializer_range (`float`, *optional*, defaults to 0.02):
63
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
64
+ max_source_positions (`int`, *optional*, defaults to 1500):
65
+ The maximum sequence length of log-mel filter-bank features that this model might ever be used with.
66
+
67
+ Example:
68
+
69
+ ```python
70
+ >>> from transformers import Qwen2AudioEncoderConfig, Qwen2AudioEncoder
71
+
72
+ >>> # Initializing a Qwen2AudioEncoderConfig
73
+ >>> configuration = Qwen2AudioEncoderConfig()
74
+
75
+ >>> # Initializing a Qwen2AudioEncoder (with random weights)
76
+ >>> model = Qwen2AudioEncoder(configuration)
77
+
78
+ >>> # Accessing the model configuration
79
+ >>> configuration = model.config
80
+ ```"""
81
+
82
+ model_type = "qwen2_audio_encoder"
83
+
84
+ def __init__(
85
+ self,
86
+ num_mel_bins=128,
87
+ encoder_layers=32,
88
+ encoder_attention_heads=20,
89
+ encoder_ffn_dim=5120,
90
+ encoder_layerdrop=0.0,
91
+ d_model=1280,
92
+ dropout=0.0,
93
+ attention_dropout=0.0,
94
+ activation_function="gelu",
95
+ activation_dropout=0.0,
96
+ scale_embedding=False,
97
+ initializer_range=0.02,
98
+ max_source_positions=1500,
99
+ **kwargs,
100
+ ):
101
+ super().__init__(**kwargs)
102
+
103
+ self.num_mel_bins = num_mel_bins
104
+ self.d_model = d_model
105
+ self.encoder_layers = encoder_layers
106
+ self.encoder_attention_heads = encoder_attention_heads
107
+ self.encoder_ffn_dim = encoder_ffn_dim
108
+ self.dropout = dropout
109
+ self.attention_dropout = attention_dropout
110
+ self.activation_function = activation_function
111
+ self.activation_dropout = activation_dropout
112
+ self.encoder_layerdrop = encoder_layerdrop
113
+ self.num_hidden_layers = encoder_layers
114
+ self.initializer_range = initializer_range
115
+ self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
116
+ self.max_source_positions = max_source_positions
117
+
118
+
119
+ class Qwen2AudioConfig(PretrainedConfig):
120
+ r"""
121
+ This is the configuration class to store the configuration of a [`Qwen2AudioForConditionalGeneration`]. It is used to instantiate an
122
+ Qwen2-Audio model according to the specified arguments, defining the model architecture. Instantiating a configuration
123
+ with the defaults will yield a similar configuration to that of the Qwen2-Audio.
124
+
125
+ e.g. [Qwen/Qwen2-Audio-7B](https://huggingface.co/Qwen/Qwen2-Audio-7B)
126
+
127
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
128
+ documentation from [`PretrainedConfig`] for more information.
129
+
130
+ Args:
131
+ audio_config (`Union[AutoConfig, dict]`, *optional*, defaults to `CLIPVisionConfig`):
132
+ The config object or dictionary of the audio backbone.
133
+ text_config (`Union[AutoConfig, dict]`, *optional*, defaults to `LlamaConfig`):
134
+ The config object or dictionary of the text backbone.
135
+ audio_token_index (`int`, *optional*, defaults to 151646):
136
+ The image token index to encode the image prompt.
137
+
138
+ Example:
139
+
140
+ ```python
141
+ >>> from transformers import Qwen2AudioForConditionalGeneration, Qwen2AudioConfig, Qwen2AudioEncoderConfig, Qwen2Config
142
+
143
+ >>> # Initializing a Qwen2AudioEncoder config
144
+ >>> audio_config = Qwen2AudioEncoderConfig()
145
+
146
+ >>> # Initializing a Qwen2 config
147
+ >>> text_config = Qwen2Config()
148
+
149
+ >>> # Initializing a Qwen2Audio configuration
150
+ >>> configuration = Qwen2AudioConfig(audio_config, text_config)
151
+
152
+ >>> # Initializing a model from the qwen2-audio style configuration
153
+ >>> model = Qwen2AudioForConditionalGeneration(configuration)
154
+
155
+ >>> # Accessing the model configuration
156
+ >>> configuration = model.config
157
+ ```"""
158
+
159
+ model_type = "qwen2_audio"
160
+ attribute_map = {
161
+ "audio_token_id": "audio_token_index",
162
+ }
163
+ sub_configs = {"text_config": AutoConfig, "audio_config": AutoConfig}
164
+
165
+ def __init__(
166
+ self,
167
+ audio_config=None,
168
+ text_config=None,
169
+ audio_token_index=151646,
170
+ **kwargs,
171
+ ):
172
+ self.audio_token_index = audio_token_index
173
+
174
+ if isinstance(audio_config, dict):
175
+ audio_config["model_type"] = audio_config.get("model_type", "qwen2_audio_encoder")
176
+ audio_config = CONFIG_MAPPING[audio_config["model_type"]](**audio_config)
177
+ elif audio_config is None:
178
+ audio_config = CONFIG_MAPPING["qwen2_audio_encoder"](
179
+ d_model=1280,
180
+ encoder_attention_heads=20,
181
+ encoder_ffn_dim=5120,
182
+ encoder_layerdrop=0.0,
183
+ encoder_layers=32,
184
+ num_mel_bins=128,
185
+ max_source_positions=1500,
186
+ scale_embedding=False,
187
+ activation_function="gelu",
188
+ )
189
+
190
+ self.audio_config = audio_config
191
+
192
+ if isinstance(text_config, dict):
193
+ text_config["model_type"] = text_config.get("model_type", "qwen2")
194
+ text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config)
195
+ elif text_config is None:
196
+ text_config = CONFIG_MAPPING["qwen2"]()
197
+
198
+ self.text_config = text_config
199
+
200
+ super().__init__(**kwargs)
201
+
202
+
203
+ __all__ = ["Qwen2AudioConfig", "Qwen2AudioEncoderConfig"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_audio/modeling_qwen2_audio.py ADDED
@@ -0,0 +1,897 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch Qwen2Audio model."""
16
+
17
+ import math
18
+ from dataclasses import dataclass
19
+ from typing import Callable, Optional, Union
20
+
21
+ import torch
22
+ from torch import nn
23
+
24
+ from ...activations import ACT2FN
25
+ from ...cache_utils import Cache
26
+ from ...generation import GenerationMixin
27
+ from ...modeling_layers import GradientCheckpointingLayer
28
+ from ...modeling_outputs import BaseModelOutput, ModelOutput
29
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
30
+ from ...utils import auto_docstring, logging
31
+ from ..auto import AutoModel, AutoModelForCausalLM
32
+ from .configuration_qwen2_audio import Qwen2AudioConfig, Qwen2AudioEncoderConfig
33
+
34
+
35
+ logger = logging.get_logger(__name__)
36
+
37
+
38
+ @dataclass
39
+ @auto_docstring(
40
+ custom_intro="""
41
+ Base class for Qwen2Audio causal language model (or autoregressive) outputs.
42
+ """
43
+ )
44
+ class Qwen2AudioCausalLMOutputWithPast(ModelOutput):
45
+ r"""
46
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
47
+ Language modeling loss (for next-token prediction).
48
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
49
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
50
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
51
+ Pre-computed hidden-states that can be used to speed up auto-regressive (sequential) decoding. There are
52
+ two sets of pre-computed hidden-states: key and values states in the self-attention blocks.
53
+ The `past_key_values` are returned when `use_cache=True` is passed or when `config.use_cache=True`.
54
+ It is a [`~cache_utils.Cache`] instance.
55
+
56
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those
57
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
58
+ all `input_ids` of shape `(batch_size, sequence_length)`.
59
+ attention_mask (`torch.FloatTensor`, *optional*):
60
+ Attentions mask, used to update attention mask and position_ids.
61
+ """
62
+
63
+ loss: Optional[torch.FloatTensor] = None
64
+ logits: Optional[torch.FloatTensor] = None
65
+ past_key_values: Optional[Cache] = None
66
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
67
+ attentions: Optional[tuple[torch.FloatTensor]] = None
68
+ attention_mask: Optional[torch.FloatTensor] = None
69
+
70
+
71
+ # Copied from transformers.models.whisper.modeling_whisper.eager_attention_forward
72
+ def eager_attention_forward(
73
+ module: nn.Module,
74
+ query: torch.Tensor,
75
+ key: torch.Tensor,
76
+ value: torch.Tensor,
77
+ attention_mask: Optional[torch.Tensor],
78
+ scaling: Optional[float] = None,
79
+ dropout: float = 0.0,
80
+ head_mask: Optional[torch.Tensor] = None,
81
+ **kwargs,
82
+ ):
83
+ if scaling is None:
84
+ scaling = query.size(-1) ** -0.5
85
+
86
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
87
+ if attention_mask is not None and attention_mask.ndim == 4:
88
+ attn_weights = attn_weights + attention_mask[:, :, :, : key.shape[-2]]
89
+
90
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
91
+
92
+ if head_mask is not None:
93
+ attn_weights = attn_weights * head_mask.view(1, -1, 1, 1)
94
+
95
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
96
+ attn_output = torch.matmul(attn_weights, value)
97
+ attn_output = attn_output.transpose(1, 2).contiguous()
98
+
99
+ return attn_output, attn_weights
100
+
101
+
102
+ class Qwen2AudioAttention(nn.Module):
103
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
104
+
105
+ # Copied from transformers.models.whisper.modeling_whisper.WhisperAttention.__init__ with Whisper->Qwen2Audio
106
+ def __init__(
107
+ self,
108
+ embed_dim: int,
109
+ num_heads: int,
110
+ dropout: float = 0.0,
111
+ is_decoder: bool = False,
112
+ bias: bool = True,
113
+ is_causal: bool = False,
114
+ layer_idx: Optional[int] = None,
115
+ config: Optional[Qwen2AudioConfig] = None,
116
+ ):
117
+ super().__init__()
118
+ self.embed_dim = embed_dim
119
+ self.num_heads = num_heads
120
+ self.dropout = dropout
121
+ self.head_dim = embed_dim // num_heads
122
+ self.config = config
123
+
124
+ if (self.head_dim * num_heads) != self.embed_dim:
125
+ raise ValueError(
126
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
127
+ f" and `num_heads`: {num_heads})."
128
+ )
129
+ self.scaling = self.head_dim**-0.5
130
+ self.is_decoder = is_decoder
131
+ self.is_causal = is_causal
132
+
133
+ if layer_idx is None and is_decoder:
134
+ logger.warning_once(
135
+ f"Instantiating a decoder {self.__class__.__name__} without passing `layer_idx` is not recommended and "
136
+ "will to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
137
+ "when creating this class."
138
+ )
139
+ self.layer_idx = layer_idx
140
+
141
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=False)
142
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
143
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
144
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
145
+
146
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
147
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
148
+
149
+ def forward(
150
+ self,
151
+ hidden_states: torch.Tensor,
152
+ attention_mask: Optional[torch.Tensor] = None,
153
+ layer_head_mask: Optional[torch.Tensor] = None,
154
+ output_attentions: bool = False,
155
+ **kwargs,
156
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
157
+ """Input shape: Batch x Time x Channel"""
158
+
159
+ bsz, tgt_len, _ = hidden_states.size()
160
+
161
+ # Scaling is susceptible to floating point arithmetics' inprecisions
162
+ # which can lead to different results (this is dependent from model
163
+ # to model, e.g. whisper is one such case). We therefore keep the
164
+ # original order of scaling to follow the original implementation
165
+ # and enforce no scaling (1.0) in the attention call below.
166
+ query_states = self._shape(self.q_proj(hidden_states) * self.scaling, tgt_len, bsz)
167
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
168
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
169
+
170
+ attention_interface: Callable = eager_attention_forward
171
+ if self.config._attn_implementation != "eager":
172
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
173
+
174
+ attn_output, attn_weights = attention_interface(
175
+ self,
176
+ query_states,
177
+ key_states,
178
+ value_states,
179
+ attention_mask,
180
+ dropout=0.0 if not self.training else self.dropout,
181
+ scaling=1.0,
182
+ output_attentions=output_attentions,
183
+ head_mask=layer_head_mask,
184
+ **kwargs,
185
+ )
186
+
187
+ attn_output = attn_output.reshape(bsz, tgt_len, -1).contiguous()
188
+ attn_output = self.out_proj(attn_output)
189
+
190
+ return attn_output, attn_weights
191
+
192
+
193
+ # Copied from transformers.models.whisper.modeling_whisper.WhisperEncoderLayer with Whisper->Qwen2Audio, WHISPER->QWEN2AUDIO
194
+ class Qwen2AudioEncoderLayer(GradientCheckpointingLayer):
195
+ def __init__(self, config: Qwen2AudioConfig):
196
+ super().__init__()
197
+ self.embed_dim = config.d_model
198
+
199
+ self.self_attn = Qwen2AudioAttention(
200
+ embed_dim=self.embed_dim,
201
+ num_heads=config.encoder_attention_heads,
202
+ dropout=config.attention_dropout,
203
+ config=config,
204
+ )
205
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
206
+ self.dropout = config.dropout
207
+ self.activation_fn = ACT2FN[config.activation_function]
208
+ self.activation_dropout = config.activation_dropout
209
+ self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
210
+ self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
211
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
212
+
213
+ def forward(
214
+ self,
215
+ hidden_states: torch.Tensor,
216
+ attention_mask: torch.Tensor,
217
+ layer_head_mask: torch.Tensor,
218
+ output_attentions: bool = False,
219
+ ) -> torch.Tensor:
220
+ """
221
+ Args:
222
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
223
+ attention_mask (`torch.FloatTensor`): attention mask of size
224
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
225
+ layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
226
+ `(encoder_attention_heads,)`.
227
+ output_attentions (`bool`, *optional*):
228
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
229
+ returned tensors for more detail.
230
+ """
231
+ residual = hidden_states
232
+ hidden_states = self.self_attn_layer_norm(hidden_states)
233
+ hidden_states, attn_weights = self.self_attn(
234
+ hidden_states=hidden_states,
235
+ attention_mask=attention_mask,
236
+ layer_head_mask=layer_head_mask,
237
+ output_attentions=output_attentions,
238
+ )
239
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
240
+ hidden_states = residual + hidden_states
241
+
242
+ residual = hidden_states
243
+ hidden_states = self.final_layer_norm(hidden_states)
244
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
245
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
246
+ hidden_states = self.fc2(hidden_states)
247
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
248
+ hidden_states = residual + hidden_states
249
+
250
+ if hidden_states.dtype == torch.float16:
251
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
252
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
253
+
254
+ return hidden_states, attn_weights
255
+
256
+
257
+ @auto_docstring
258
+ class Qwen2AudioPreTrainedModel(PreTrainedModel):
259
+ config: Qwen2AudioConfig
260
+ base_model_prefix = "model"
261
+ supports_gradient_checkpointing = True
262
+ _no_split_modules = ["Qwen2AudioAttention"]
263
+ _skip_keys_device_placement = "past_key_values"
264
+ _supports_flash_attn = True
265
+ _supports_sdpa = True
266
+
267
+ def _init_weights(self, module):
268
+ # important: this ported version of Qwen2Audio isn't meant for training from scratch - only
269
+ # inference and fine-tuning - so the proper init weights code has been removed
270
+ std = (
271
+ self.config.initializer_range
272
+ if hasattr(self.config, "initializer_range")
273
+ else self.config.audio_config.initializer_range
274
+ )
275
+
276
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
277
+ module.weight.data.normal_(mean=0.0, std=std)
278
+ if module.bias is not None:
279
+ module.bias.data.zero_()
280
+ elif isinstance(module, nn.LayerNorm):
281
+ module.weight.data.fill_(1.0)
282
+ module.bias.data.zero_()
283
+ elif isinstance(module, nn.Embedding):
284
+ module.weight.data.normal_(mean=0.0, std=std)
285
+ if module.padding_idx is not None:
286
+ module.weight.data[module.padding_idx].zero_()
287
+
288
+
289
+ @auto_docstring(
290
+ custom_intro="""
291
+ The audio model from Qwen2Audio without any head or projection on top.
292
+ """
293
+ )
294
+ # Copied from transformers.models.whisper.modeling_whisper.WhisperEncoder with Whisper->Qwen2Audio
295
+ class Qwen2AudioEncoder(Qwen2AudioPreTrainedModel):
296
+ """
297
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
298
+ [`Qwen2AudioEncoderLayer`].
299
+
300
+ Args:
301
+ config: Qwen2AudioEncoderConfig
302
+ """
303
+
304
+ # Ignore copy
305
+ config: Qwen2AudioEncoderConfig
306
+ main_input_name = "input_features"
307
+ _no_split_modules = ["Qwen2AudioEncoderLayer"]
308
+
309
+ def __init__(self, config: Qwen2AudioEncoderConfig):
310
+ super().__init__(config)
311
+ self.dropout = config.dropout
312
+ self.layerdrop = config.encoder_layerdrop
313
+
314
+ embed_dim = config.d_model
315
+ self.num_mel_bins = config.num_mel_bins
316
+ self.padding_idx = config.pad_token_id
317
+ self.max_source_positions = config.max_source_positions
318
+ self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
319
+
320
+ self.conv1 = nn.Conv1d(self.num_mel_bins, embed_dim, kernel_size=3, padding=1)
321
+ self.conv2 = nn.Conv1d(embed_dim, embed_dim, kernel_size=3, stride=2, padding=1)
322
+
323
+ self.embed_positions = nn.Embedding(self.max_source_positions, embed_dim)
324
+ self.embed_positions.requires_grad_(False)
325
+
326
+ self.layers = nn.ModuleList([Qwen2AudioEncoderLayer(config) for _ in range(config.encoder_layers)])
327
+ self.layer_norm = nn.LayerNorm(config.d_model)
328
+ # Ignore copy
329
+ self.avg_pooler = nn.AvgPool1d(2, stride=2)
330
+
331
+ self.gradient_checkpointing = False
332
+ # Initialize weights and apply final processing
333
+ self.post_init()
334
+
335
+ def _freeze_parameters(self):
336
+ for param in self.parameters():
337
+ param.requires_grad = False
338
+ self._requires_grad = False
339
+
340
+ def get_input_embeddings(self) -> nn.Module:
341
+ return self.conv1
342
+
343
+ def set_input_embeddings(self, value: nn.Module):
344
+ self.conv1 = value
345
+
346
+ def forward(
347
+ self,
348
+ input_features,
349
+ attention_mask=None,
350
+ head_mask=None,
351
+ output_attentions=None,
352
+ output_hidden_states=None,
353
+ return_dict=None,
354
+ ):
355
+ r"""
356
+ Args:
357
+ attention_mask (`torch.Tensor`)`, *optional*):
358
+ Qwen2Audio does not support masking of the `input_features`, this argument is preserved for compatibility,
359
+ but it is not used. By default the silence in the input log mel spectrogram are ignored.
360
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
361
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
362
+
363
+ - 1 indicates the head is **not masked**,
364
+ - 0 indicates the head is **masked**.
365
+ output_attentions (`bool`, *optional*):
366
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
367
+ returned tensors for more detail.
368
+ output_hidden_states (`bool`, *optional*):
369
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
370
+ for more detail.
371
+ return_dict (`bool`, *optional*):
372
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
373
+ """
374
+
375
+ expected_seq_length = self.config.max_source_positions * self.conv1.stride[0] * self.conv2.stride[0]
376
+ if input_features.shape[-1] != expected_seq_length:
377
+ raise ValueError(
378
+ f"Qwen2Audio expects the mel input features to be of length {expected_seq_length}, but found {input_features.shape[-1]}. Make sure to pad the input mel features to {expected_seq_length}."
379
+ )
380
+
381
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
382
+ output_hidden_states = (
383
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
384
+ )
385
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
386
+
387
+ # Ignore copy
388
+ input_features = input_features.to(dtype=self.conv1.weight.dtype, device=self.conv1.weight.device)
389
+
390
+ inputs_embeds = nn.functional.gelu(self.conv1(input_features))
391
+ inputs_embeds = nn.functional.gelu(self.conv2(inputs_embeds))
392
+
393
+ inputs_embeds = inputs_embeds.permute(0, 2, 1)
394
+ embed_pos = self.embed_positions.weight
395
+
396
+ hidden_states = inputs_embeds + embed_pos
397
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
398
+
399
+ encoder_states = () if output_hidden_states else None
400
+ all_attentions = () if output_attentions else None
401
+
402
+ # check if head_mask has a correct number of layers specified if desired
403
+ if head_mask is not None:
404
+ assert head_mask.size()[0] == (len(self.layers)), (
405
+ f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}."
406
+ )
407
+
408
+ for idx, encoder_layer in enumerate(self.layers):
409
+ if output_hidden_states:
410
+ encoder_states = encoder_states + (hidden_states,)
411
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
412
+ to_drop = False
413
+ if self.training:
414
+ dropout_probability = torch.rand([])
415
+ if dropout_probability < self.layerdrop: # skip the layer
416
+ to_drop = True
417
+
418
+ # Ignore copy
419
+ if to_drop:
420
+ layer_outputs = (None, None)
421
+ else:
422
+ layer_outputs = encoder_layer(
423
+ hidden_states,
424
+ attention_mask,
425
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
426
+ output_attentions=output_attentions,
427
+ )
428
+
429
+ hidden_states = layer_outputs[0]
430
+
431
+ if output_attentions:
432
+ all_attentions = all_attentions + (layer_outputs[1],)
433
+
434
+ # Ignore copy
435
+ hidden_states = hidden_states.permute(0, 2, 1)
436
+ hidden_states = self.avg_pooler(hidden_states)
437
+ hidden_states = hidden_states.permute(0, 2, 1)
438
+
439
+ hidden_states = self.layer_norm(hidden_states)
440
+ if output_hidden_states:
441
+ encoder_states = encoder_states + (hidden_states,)
442
+
443
+ if not return_dict:
444
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
445
+ return BaseModelOutput(
446
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
447
+ )
448
+
449
+ # Ignore copy
450
+ def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor):
451
+ """
452
+ Computes the output length of the convolutional layers and the output length of the audio encoder
453
+ """
454
+ input_lengths = (input_lengths - 1) // 2 + 1
455
+ output_lengths = (input_lengths - 2) // 2 + 1
456
+ return input_lengths, output_lengths
457
+
458
+
459
+ class Qwen2AudioMultiModalProjector(nn.Module):
460
+ def __init__(self, config: Qwen2AudioConfig):
461
+ super().__init__()
462
+ self.linear = nn.Linear(config.audio_config.d_model, config.text_config.hidden_size, bias=True)
463
+
464
+ def forward(self, audio_features):
465
+ hidden_states = self.linear(audio_features)
466
+ return hidden_states
467
+
468
+
469
+ @auto_docstring(
470
+ custom_intro="""
471
+ The QWEN2AUDIO model which consists of a audio backbone and a language model.
472
+ """
473
+ )
474
+ class Qwen2AudioForConditionalGeneration(Qwen2AudioPreTrainedModel, GenerationMixin):
475
+ def __init__(self, config: Qwen2AudioConfig):
476
+ super().__init__(config)
477
+ self.audio_tower = AutoModel.from_config(config.audio_config) # Usually a `Qwen2AudioEncoder` instance
478
+
479
+ self.multi_modal_projector = Qwen2AudioMultiModalProjector(config)
480
+ self.vocab_size = config.text_config.vocab_size
481
+ self.language_model = AutoModelForCausalLM.from_config(config.text_config)
482
+ if self.language_model._tied_weights_keys is not None:
483
+ self._tied_weights_keys = [f"language_model.{k}" for k in self.language_model._tied_weights_keys]
484
+
485
+ self.pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else -1
486
+ self._padding_side = "left" # set it to left by default, user can use setter to change padding_sides
487
+ self.post_init()
488
+
489
+ @property
490
+ def padding_side(self):
491
+ return self._padding_side
492
+
493
+ @padding_side.setter
494
+ def padding_side(self, padding_side: str):
495
+ if padding_side not in ["left", "right"]:
496
+ raise ValueError(f"{padding_side} is not `left` or `right`.")
497
+ self._padding_side = padding_side
498
+
499
+ def get_input_embeddings(self):
500
+ return self.language_model.get_input_embeddings()
501
+
502
+ def set_input_embeddings(self, value):
503
+ self.language_model.set_input_embeddings(value)
504
+
505
+ def get_output_embeddings(self):
506
+ return self.language_model.get_output_embeddings()
507
+
508
+ def set_output_embeddings(self, new_embeddings):
509
+ self.language_model.set_output_embeddings(new_embeddings)
510
+
511
+ def set_decoder(self, decoder):
512
+ self.language_model.set_decoder(decoder)
513
+
514
+ def get_decoder(self):
515
+ return self.language_model.get_decoder()
516
+
517
+ def _merge_input_ids_with_audio_features(
518
+ self, audio_features, num_audio_tokens, inputs_embeds, input_ids, attention_mask, labels
519
+ ):
520
+ """
521
+ Merge input_ids with with audio features into final embeddings
522
+
523
+ Args:
524
+ audio_features (`torch.Tensor` of shape `(num_audios, max_audio_tokens, embed_dim)`):
525
+ All audio vectors of all audios in the batch
526
+ num_audio_tokens (`torch.LongTensor` of shape `(num_audios)`):
527
+ The length of audio embeddings of each audio as stacked in `audio_features`
528
+ inputs_embeds (`torch.Tensor` of shape `(batch_size, sequence_length, embed_dim)`):
529
+ Token embeddings before merging with audio embeddings
530
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
531
+ Input_ids of tokens, possibly filled with audio token
532
+ attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
533
+ Mask to avoid performing attention on padding token indices.
534
+ labels (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*)
535
+ labels need to be recalculated to support training (if provided)
536
+ Returns:
537
+ final_embedding, final_attention_mask, final_labels, position_ids, final_input_ids
538
+
539
+ Explanation:
540
+ each audio has variable length embeddings, with length specified by num_audio_tokens
541
+ audio_features is concatenation of all audio embed vectors
542
+ task: fill each <|AUDIO|> with the correct number of audio embeddings
543
+ Example:
544
+ X (5 tokens), Y (3 tokens), Z (8 tokens)
545
+ X, Y are in the same sequence (in-context learning)
546
+ if right padding
547
+ input_ids: [
548
+ a b c d e f X g h i j k Y l m
549
+ o p q r Z s t u v _ _ _ _ _ _
550
+ ]
551
+ input_ids should be: [
552
+ a b c d e f X X X X X g h i j k Y Y Y l m
553
+ o p q r Z Z Z Z Z Z Z Z s t u v _ _ _ _ _
554
+ ]
555
+ labels should be: [
556
+ a b c d e f _ _ _ _ _ g h i j k _ _ _ l m
557
+ o p q r _ _ _ _ _ _ _ _ s t u v _ _ _ _ _
558
+ ]
559
+ elif left padding
560
+ input_ids: [
561
+ a b c d e f X g h i j k Y l m
562
+ _ _ _ _ _ _ o p q r Z s t u v
563
+ ]
564
+ input_ids should be: [
565
+ a b c d e f X X X X X g h i j k Y Y Y l m
566
+ _ _ _ _ _ o p q r Z Z Z Z Z Z Z Z s t u v
567
+ ]
568
+ labels should be: [
569
+ a b c d e f _ _ _ _ _ g h i j k _ _ _ l m
570
+ _ _ _ _ _ o p q r _ _ _ _ _ _ _ _ s t u v
571
+ ]
572
+ Edge cases:
573
+ * If tokens are same but audio token sizes are different, then cannot infer left or right padding
574
+ ```python
575
+ url1 = "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/glass-breaking-151256.mp3"
576
+ audio1, _ = librosa.load(BytesIO(urlopen(url1).read()), sr=processor.feature_extractor.sampling_rate)
577
+ url2 = "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/f2641_0_throatclearing.wav"
578
+ audio2, _ = librosa.load(BytesIO(urlopen(url2).read()), sr=processor.feature_extractor.sampling_rate)
579
+ prompts = [
580
+ "[INST] <|AUDIO|>\nWhat is that in this audio? [/INST]",
581
+ "[INST] <|AUDIO|>\nWhat is that in this audio? [/INST]",
582
+ ]
583
+ inputs = processor(text=prompts, audios=[audio1, audio2], return_tensors='pt', padding=True).to("cuda")
584
+ audio1 has 101 tokens, while audio2 has 72 tokens
585
+ ```
586
+
587
+ input_ids: [
588
+ a b c d X g h
589
+ i j Y k l m n
590
+ ]
591
+ where X is 3 tokens while Y is 5, this mean after merge
592
+ if left-padding (batched generation)
593
+ input_ids should be: [
594
+ _ _ a b c d X X X g h
595
+ i j Y Y Y Y Y k l m n
596
+ ]
597
+ elif (right padding) (training)
598
+ input_ids should be: [
599
+ a b c d X X X g h _ _
600
+ i j Y Y Y Y Y k l m n
601
+ ]
602
+ """
603
+ num_audios, max_audio_tokens, embed_dim = audio_features.shape
604
+ audio_features_mask = torch.arange(max_audio_tokens).expand(num_audios, max_audio_tokens).to(
605
+ num_audio_tokens.device
606
+ ) < num_audio_tokens.unsqueeze(1)
607
+ masked_audio_features = audio_features[audio_features_mask].view(-1, embed_dim)
608
+ batch_size, sequence_length = input_ids.shape
609
+ _left_padding = torch.any(attention_mask[:, 0] == 0)
610
+ _right_padding = torch.any(attention_mask[:, -1] == 0)
611
+
612
+ left_padding = True
613
+ if batch_size > 1:
614
+ if _left_padding and not _right_padding:
615
+ left_padding = True
616
+ elif not _left_padding and _right_padding:
617
+ left_padding = False
618
+ elif not _left_padding and not _right_padding:
619
+ # both side is 1, so cannot tell
620
+ left_padding = self.padding_side == "left"
621
+ else:
622
+ # invalid attention_mask
623
+ raise ValueError(f"both side of attention_mask has zero, invalid. {attention_mask}")
624
+
625
+ # 1. Create a mask to know where special audio tokens are
626
+ special_audio_token_mask = input_ids == self.config.audio_token_id
627
+ num_special_audio_tokens = torch.sum(special_audio_token_mask, dim=-1)
628
+
629
+ # In case the Audio model or the Language model has been offloaded to CPU, we need to manually
630
+ # set the corresponding tensors into their correct target device.
631
+ target_device = inputs_embeds.device
632
+ attention_mask = attention_mask.to(target_device)
633
+ input_ids = input_ids.to(target_device)
634
+ num_audio_tokens = num_audio_tokens.to(target_device)
635
+ batch_indices, non_audio_indices = torch.where(
636
+ (input_ids != self.config.audio_token_id) & (attention_mask == 1)
637
+ )
638
+
639
+ # 2. Compute the positions where text should be written
640
+ # Calculate new positions for text tokens in merged audio-text sequence.
641
+ # `special_audio_token_mask` identifies audio tokens. Each audio token will be replaced by `audio_feat_lengths - 1` text tokens.
642
+ # `torch.cumsum` computes how each audio token shifts subsequent text token positions.
643
+ token_placeholder_num = torch.zeros_like(input_ids)
644
+ token_placeholder_num[special_audio_token_mask] = num_audio_tokens.long() - 1
645
+ token_placeholder_num = token_placeholder_num + 1
646
+ new_token_positions = torch.cumsum(token_placeholder_num, -1) - 1
647
+ max_token_num = token_placeholder_num.sum(-1).max()
648
+ nb_audio_pad = max_token_num - 1 - new_token_positions[:, -1]
649
+ if left_padding:
650
+ new_token_positions += nb_audio_pad[:, None] # offset for left padding
651
+ text_to_overwrite = new_token_positions[batch_indices, non_audio_indices]
652
+ batch_indices, non_audio_indices, text_to_overwrite = (
653
+ batch_indices.to(target_device),
654
+ non_audio_indices.to(target_device),
655
+ text_to_overwrite.to(target_device),
656
+ )
657
+
658
+ # 3. Create the full embedding, already padded to the maximum position
659
+ final_embedding = torch.zeros(
660
+ batch_size, max_token_num, embed_dim, dtype=inputs_embeds.dtype, device=inputs_embeds.device
661
+ )
662
+ final_attention_mask = torch.zeros(
663
+ batch_size, max_token_num, dtype=attention_mask.dtype, device=inputs_embeds.device
664
+ )
665
+ final_input_ids = torch.full(
666
+ (batch_size, max_token_num), self.pad_token_id, dtype=input_ids.dtype, device=inputs_embeds.device
667
+ )
668
+
669
+ # 4. Fill the embeddings based on the mask. If we have ["hey" "<audio>", "how", "are"]
670
+ # we need to index copy on [0, 577, 578, 579] for the text and [1:576] for the audio features
671
+ final_embedding[batch_indices, text_to_overwrite] = inputs_embeds[batch_indices, non_audio_indices]
672
+ final_attention_mask[batch_indices, text_to_overwrite] = attention_mask[batch_indices, non_audio_indices]
673
+ final_input_ids[batch_indices, text_to_overwrite] = input_ids[batch_indices, non_audio_indices]
674
+ final_labels = None
675
+ if labels is not None:
676
+ labels = labels.to(target_device)
677
+ final_labels = torch.full_like(final_attention_mask, self.config.ignore_index).to(torch.long)
678
+ final_labels[batch_indices, text_to_overwrite] = labels[batch_indices, non_audio_indices]
679
+
680
+ # 5. Fill the embeddings corresponding to the audios. Anything that is still zeros needs filling
681
+ audio_to_overwrite = torch.full(
682
+ (batch_size, max_token_num), True, dtype=torch.bool, device=inputs_embeds.device
683
+ )
684
+ audio_to_overwrite[batch_indices, text_to_overwrite] = False
685
+ seq_indices = torch.arange(max_token_num).unsqueeze(0).to(target_device)
686
+ seq_indices = seq_indices.expand(batch_size, max_token_num)
687
+
688
+ if left_padding:
689
+ # exclude padding on the left
690
+ max_token_num = max_token_num.to(target_device)
691
+ val = (max_token_num - seq_indices) <= (
692
+ token_placeholder_num.sum(-1) - (attention_mask == 0).long().sum(-1)
693
+ )[:, None]
694
+ else:
695
+ # exclude padding on the right
696
+ val = seq_indices < (token_placeholder_num.sum(-1) - (attention_mask == 0).long().sum(-1))[:, None]
697
+
698
+ audio_to_overwrite &= val
699
+
700
+ if audio_to_overwrite.sum() != num_audio_tokens.sum():
701
+ raise ValueError(
702
+ f"The input provided to the model are wrong. The number of audio tokens is {num_special_audio_tokens} while"
703
+ f" the number of audio given to the model is {num_audios}. This prevents correct indexing and breaks batch generation."
704
+ )
705
+
706
+ final_embedding[audio_to_overwrite] = (
707
+ masked_audio_features.contiguous().reshape(-1, embed_dim).to(target_device)
708
+ )
709
+ final_attention_mask |= audio_to_overwrite
710
+ position_ids = (final_attention_mask.cumsum(-1) - 1).masked_fill_((final_attention_mask == 0), 1)
711
+
712
+ return final_embedding, final_attention_mask, final_labels, position_ids, final_input_ids
713
+
714
+ @auto_docstring
715
+ def forward(
716
+ self,
717
+ input_ids: Optional[torch.LongTensor] = None,
718
+ input_features: Optional[torch.FloatTensor] = None,
719
+ attention_mask: Optional[torch.Tensor] = None,
720
+ feature_attention_mask: Optional[torch.Tensor] = None,
721
+ position_ids: Optional[torch.LongTensor] = None,
722
+ past_key_values: Optional[Cache] = None,
723
+ inputs_embeds: Optional[torch.FloatTensor] = None,
724
+ labels: Optional[torch.LongTensor] = None,
725
+ use_cache: Optional[bool] = None,
726
+ output_attentions: Optional[bool] = None,
727
+ output_hidden_states: Optional[bool] = None,
728
+ return_dict: Optional[bool] = None,
729
+ cache_position: Optional[torch.LongTensor] = None,
730
+ ) -> Union[tuple, Qwen2AudioCausalLMOutputWithPast]:
731
+ r"""
732
+ feature_attention_mask (`torch.Tensor` of shape `(batch_size, feature_sequence_length)`):
733
+ Mask to avoid performing attention on padding feature indices. Mask values selected in `[0, 1]`:
734
+
735
+ - 1 for tokens that are **not masked**,
736
+ - 0 for tokens that are **masked**.
737
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
738
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
739
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
740
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
741
+
742
+ Example:
743
+
744
+ ```python
745
+ >>> from io import BytesIO
746
+ >>> from urllib.request import urlopen
747
+ >>> import librosa
748
+ >>> from transformers import AutoProcessor, Qwen2AudioForConditionalGeneration
749
+
750
+ >>> model = Qwen2AudioForConditionalGeneration.from_pretrained("Qwen/Qwen2-Audio-7B")
751
+ >>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2-Audio-7B")
752
+
753
+ >>> prompt = "<|audio_bos|><|AUDIO|><|audio_eos|>Generate the caption in English:"
754
+ >>> url = "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/glass-breaking-151256.mp3"
755
+ >>> audio, _ = librosa.load(BytesIO(urlopen(url).read()), sr=self.processor.feature_extractor.sampling_rate)
756
+
757
+ >>> inputs = processor(text=prompt, audios=audio, return_tensors="pt")
758
+
759
+ >>> # Generate
760
+ >>> generate_ids = model.generate(**inputs, max_length=30)
761
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
762
+ "Generate the caption in English: Glass is breaking."
763
+ ```"""
764
+
765
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
766
+ output_hidden_states = (
767
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
768
+ )
769
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
770
+
771
+ target_device = self.audio_tower.device
772
+
773
+ if input_features is not None:
774
+ input_features = input_features.to(target_device)
775
+ feature_attention_mask = feature_attention_mask.to(target_device)
776
+
777
+ if inputs_embeds is None:
778
+ # 1. Extract the input embeddings
779
+ inputs_embeds = self.get_input_embeddings()(input_ids)
780
+
781
+ # 2. Merge text and audios
782
+ if input_features is not None and input_ids.shape[1] != 1:
783
+ audio_feat_lengths, audio_output_lengths = self.audio_tower._get_feat_extract_output_lengths(
784
+ feature_attention_mask.sum(-1)
785
+ )
786
+ batch_size, _, max_mel_seq_len = input_features.shape
787
+ max_seq_len = (max_mel_seq_len - 2) // 2 + 1
788
+ # Create a sequence tensor of shape (batch_size, max_seq_len)
789
+ seq_range = (
790
+ torch.arange(0, max_seq_len, dtype=audio_feat_lengths.dtype, device=audio_feat_lengths.device)
791
+ .unsqueeze(0)
792
+ .expand(batch_size, max_seq_len)
793
+ )
794
+ lengths_expand = audio_feat_lengths.unsqueeze(1).expand(batch_size, max_seq_len)
795
+ # Create mask
796
+ padding_mask = seq_range >= lengths_expand
797
+
798
+ audio_attention_mask_ = padding_mask.view(batch_size, 1, 1, max_seq_len).expand(
799
+ batch_size, 1, max_seq_len, max_seq_len
800
+ )
801
+ audio_attention_mask = audio_attention_mask_.to(
802
+ dtype=self.audio_tower.conv1.weight.dtype, device=self.audio_tower.conv1.weight.device
803
+ )
804
+ audio_attention_mask[audio_attention_mask_] = float("-inf")
805
+
806
+ audio_outputs = self.audio_tower(input_features, attention_mask=audio_attention_mask)
807
+ selected_audio_feature = audio_outputs.last_hidden_state
808
+ audio_features = self.multi_modal_projector(selected_audio_feature)
809
+
810
+ # if we have consecutive audio tokens, then it means we expanded input_ids in processing
811
+ audio_tokens = input_ids == self.config.audio_token_id
812
+ legacy_processing = (audio_tokens[:, :-1] & audio_tokens[:, 1:]).sum() == 0
813
+
814
+ if legacy_processing:
815
+ logger.warning_once(
816
+ "Expanding inputs for audio tokens in Qwen2Audio should be done in processing."
817
+ )
818
+ inputs_embeds, attention_mask, labels, position_ids, _ = self._merge_input_ids_with_audio_features(
819
+ audio_features, audio_output_lengths, inputs_embeds, input_ids, attention_mask, labels
820
+ )
821
+ else:
822
+ num_audios, max_audio_tokens, embed_dim = audio_features.shape
823
+ audio_features_mask = torch.arange(max_audio_tokens, device=audio_output_lengths.device)[None, :]
824
+ audio_features_mask = audio_features_mask < audio_output_lengths[:, None]
825
+ audio_features = audio_features[audio_features_mask]
826
+
827
+ n_audio_tokens = (input_ids == self.config.audio_token_id).sum().item()
828
+ n_audio_features = audio_features.shape[0]
829
+
830
+ if n_audio_tokens != n_audio_features:
831
+ raise ValueError(
832
+ f"Audio features and audio tokens do not match: tokens: {n_audio_tokens}, features {n_audio_features}"
833
+ )
834
+ special_audio_mask = (input_ids == self.config.audio_token_id).to(inputs_embeds.device)
835
+ special_audio_mask = special_audio_mask.unsqueeze(-1).expand_as(inputs_embeds)
836
+ audio_features = audio_features.to(inputs_embeds.device, inputs_embeds.dtype)
837
+ inputs_embeds = inputs_embeds.masked_scatter(special_audio_mask, audio_features)
838
+
839
+ outputs = self.language_model(
840
+ attention_mask=attention_mask,
841
+ position_ids=position_ids,
842
+ past_key_values=past_key_values,
843
+ inputs_embeds=inputs_embeds,
844
+ use_cache=use_cache,
845
+ output_attentions=output_attentions,
846
+ output_hidden_states=output_hidden_states,
847
+ return_dict=return_dict,
848
+ cache_position=cache_position,
849
+ )
850
+
851
+ logits = outputs[0]
852
+
853
+ loss = None
854
+ if labels is not None:
855
+ # Shift so that tokens < n predict n
856
+ if attention_mask is not None:
857
+ shift_attention_mask = attention_mask[..., 1:]
858
+ shift_logits = logits[..., :-1, :][shift_attention_mask.to(logits.device) != 0].contiguous()
859
+ shift_labels = labels[..., 1:][shift_attention_mask.to(labels.device) != 0].contiguous()
860
+ else:
861
+ shift_logits = logits[..., :-1, :].contiguous()
862
+ shift_labels = labels[..., 1:].contiguous()
863
+ # Flatten the tokens
864
+ loss_fct = nn.CrossEntropyLoss()
865
+ loss = loss_fct(
866
+ shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1).to(shift_logits.device)
867
+ )
868
+
869
+ if not return_dict:
870
+ output = (logits,) + outputs[1:]
871
+ return (loss,) + output if loss is not None else output
872
+
873
+ return Qwen2AudioCausalLMOutputWithPast(
874
+ loss=loss,
875
+ logits=logits,
876
+ past_key_values=outputs.past_key_values,
877
+ hidden_states=outputs.hidden_states,
878
+ attentions=outputs.attentions,
879
+ attention_mask=attention_mask,
880
+ )
881
+
882
+ def prepare_inputs_for_generation(self, *args, **kwargs):
883
+ # Overwritten -- we should not pass input_features when we are in cached decoding stage
884
+
885
+ input_features = kwargs.pop("input_features", None)
886
+ cache_position = kwargs.get("cache_position")
887
+
888
+ model_inputs = super().prepare_inputs_for_generation(*args, **kwargs)
889
+
890
+ if cache_position is not None and cache_position[0] == 0:
891
+ # input_features should only be passed when we are not in cached decoding stage
892
+ model_inputs["input_features"] = input_features
893
+
894
+ return model_inputs
895
+
896
+
897
+ __all__ = ["Qwen2AudioForConditionalGeneration", "Qwen2AudioPreTrainedModel", "Qwen2AudioEncoder"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_audio/processing_qwen2_audio.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """
16
+ Processor class for Qwen2Audio.
17
+ """
18
+
19
+ from typing import Union
20
+
21
+ import numpy as np
22
+
23
+ from ...feature_extraction_utils import BatchFeature
24
+ from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
25
+ from ...tokenization_utils_base import PreTokenizedInput, TextInput
26
+
27
+
28
+ class Qwen2AudioProcessorKwargs(ProcessingKwargs, total=False):
29
+ _defaults = {
30
+ "text_kwargs": {
31
+ "padding": False,
32
+ },
33
+ "audio_kwargs": {},
34
+ }
35
+
36
+
37
+ class Qwen2AudioProcessor(ProcessorMixin):
38
+ r"""
39
+ Constructs a Qwen2Audio processor which wraps a Qwen2Audio feature extractor and a Qwen2Audio tokenizer into a single processor.
40
+
41
+ [`Qwen2AudioProcessor`] offers all the functionalities of [`WhisperFeatureExtractor`] and [`Qwen2TokenizerFast`]. See the
42
+ [`~Qwen2AudioProcessor.__call__`] and [`~Qwen2AudioProcessor.decode`] for more information.
43
+
44
+ Args:
45
+ feature_extractor ([`WhisperFeatureExtractor`], *optional*):
46
+ The feature extractor is a required input.
47
+ tokenizer ([`Qwen2TokenizerFast`], *optional*):
48
+ The tokenizer is a required input.
49
+ chat_template (`Optional[str]`, *optional*):
50
+ The Jinja template to use for formatting the conversation. If not provided, the default chat template
51
+ is used.
52
+ audio_token (`str`, *optional*, defaults to `"<|AUDIO|>"`):
53
+ The token to use for audio tokens.
54
+ audio_bos_token (`str`, *optional*, defaults to `"<|audio_bos|>"`):
55
+ The token to use for audio bos tokens.
56
+ audio_eos_token (`str`, *optional*, defaults to `"<|audio_eos|>"`):
57
+ The token to use for audio eos tokens.
58
+ """
59
+
60
+ attributes = ["feature_extractor", "tokenizer"]
61
+ feature_extractor_class = "WhisperFeatureExtractor"
62
+ tokenizer_class = "AutoTokenizer"
63
+
64
+ def __init__(
65
+ self,
66
+ feature_extractor=None,
67
+ tokenizer=None,
68
+ chat_template=None,
69
+ audio_token="<|AUDIO|>",
70
+ audio_bos_token="<|audio_bos|>",
71
+ audio_eos_token="<|audio_eos|>",
72
+ ):
73
+ if chat_template is None:
74
+ chat_template = self.default_chat_template
75
+ self.audio_token = tokenizer.audio_token if hasattr(tokenizer, "audio_token") else audio_token
76
+ self.audio_token_id = tokenizer.convert_tokens_to_ids(self.audio_token)
77
+ self.audio_bos_token = tokenizer.audio_bos_token if hasattr(tokenizer, "audio_bos_token") else audio_bos_token
78
+ self.audio_eos_token = tokenizer.audio_eos_token if hasattr(tokenizer, "audio_eos_token") else audio_eos_token
79
+ super().__init__(feature_extractor, tokenizer, chat_template=chat_template)
80
+
81
+ def __call__(
82
+ self,
83
+ text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
84
+ audio: Union[np.ndarray, list[np.ndarray]] = None,
85
+ **kwargs: Unpack[Qwen2AudioProcessorKwargs],
86
+ ) -> BatchFeature:
87
+ """
88
+ Main method to prepare for the model one or several sequences(s) and audio(s). This method forwards the `text`
89
+ and `kwargs` arguments to Qwen2TokenizerFast's [`~Qwen2TokenizerFast.__call__`] if `text` is not `None` to encode
90
+ the text. To prepare the audio(s), this method forwards the `audios` and `kwrags` arguments to
91
+ WhisperFeatureExtractor's [`~WhisperFeatureExtractor.__call__`] if `audios` is not `None`. Please refer to the docstring
92
+ of the above two methods for more information.
93
+
94
+ Args:
95
+ text (`str`, `list[str]`, `list[list[str]]`):
96
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
97
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
98
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
99
+ audio (`np.ndarray`, `list[np.ndarray]`):
100
+ The audio or batch of audios to be prepared. Each audio can be a NumPy array.
101
+ """
102
+ if text is None:
103
+ raise ValueError("You need to specify `text` input to process.")
104
+ elif isinstance(text, str):
105
+ text = [text]
106
+ elif not isinstance(text, list) and not isinstance(text[0], str):
107
+ raise ValueError("Invalid input text. Please provide a string, or a list of strings")
108
+
109
+ output_kwargs = self._merge_kwargs(
110
+ Qwen2AudioProcessorKwargs,
111
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
112
+ **kwargs,
113
+ )
114
+
115
+ if audio is not None:
116
+ # ensure we have as much audios as audio tokens
117
+ num_audio_tokens = sum(sample.count(self.audio_token) for sample in text)
118
+ num_audios = 1 if type(audio) is np.ndarray else len(audio)
119
+ if num_audio_tokens != num_audios:
120
+ raise ValueError(
121
+ f"Found {num_audio_tokens} {self.audio_token} token{'s' if num_audio_tokens > 1 else ''} in provided text but received {num_audios} audio{'s' if num_audios > 1 else ''}"
122
+ )
123
+
124
+ # Some kwargs should not be changed so we can expand text with audio tokens below
125
+ output_kwargs["audio_kwargs"]["return_attention_mask"] = True
126
+ output_kwargs["audio_kwargs"]["padding"] = "max_length"
127
+ audio_inputs = self.feature_extractor(audio, **output_kwargs["audio_kwargs"])
128
+
129
+ # rename attention_mask to prevent conflicts later on
130
+ audio_inputs["feature_attention_mask"] = audio_inputs.pop("attention_mask")
131
+
132
+ expanded_text = []
133
+ audio_lengths = audio_inputs["feature_attention_mask"].sum(-1).tolist()
134
+
135
+ for sample in text:
136
+ replace_str = []
137
+ while self.audio_token in sample:
138
+ audio_length = audio_lengths.pop(0)
139
+ input_length = (audio_length - 1) // 2 + 1
140
+ num_audio_tokens = (input_length - 2) // 2 + 1
141
+
142
+ expanded_audio_token = self.audio_token * num_audio_tokens
143
+
144
+ audio_token_start_idx = sample.find(self.audio_token)
145
+ audio_token_end_idx = audio_token_start_idx + len(self.audio_token)
146
+
147
+ has_bos = (
148
+ sample[audio_token_start_idx - len(self.audio_bos_token) : audio_token_start_idx]
149
+ == self.audio_bos_token
150
+ )
151
+ has_eos = (
152
+ sample[audio_token_end_idx : audio_token_end_idx + len(self.audio_eos_token)]
153
+ == self.audio_eos_token
154
+ )
155
+
156
+ # Check if this audio token is surrounded by bos/eos tokens
157
+ if not has_bos and not has_eos:
158
+ expanded_audio_token = self.audio_bos_token + expanded_audio_token + self.audio_eos_token
159
+
160
+ replace_str.append(expanded_audio_token)
161
+ sample = sample.replace(self.audio_token, "<placeholder>", 1)
162
+
163
+ while "<placeholder>" in sample:
164
+ sample = sample.replace("<placeholder>", replace_str.pop(0), 1)
165
+ expanded_text.append(sample)
166
+ text = expanded_text
167
+
168
+ return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
169
+ inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
170
+ self._check_special_mm_tokens(text, inputs, modalities=["audio"])
171
+
172
+ if audio is not None:
173
+ inputs.update(audio_inputs)
174
+
175
+ return BatchFeature(data={**inputs}, tensor_type=return_tensors)
176
+
177
+ def batch_decode(self, *args, **kwargs):
178
+ """
179
+ This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
180
+ refer to the docstring of this method for more information.
181
+ """
182
+ return self.tokenizer.batch_decode(*args, **kwargs)
183
+
184
+ def decode(self, *args, **kwargs):
185
+ """
186
+ This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
187
+ the docstring of this method for more information.
188
+ """
189
+ return self.tokenizer.decode(*args, **kwargs)
190
+
191
+ @property
192
+ def model_input_names(self):
193
+ tokenizer_input_names = self.tokenizer.model_input_names
194
+ feature_extractor_input_names = self.feature_extractor.model_input_names
195
+ return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names + ["feature_attention_mask"]))
196
+
197
+ @property
198
+ # NOTE: we don't have default templates anymore, and the below is kept only because the hub config is not yet updated!
199
+ def default_chat_template(self):
200
+ """
201
+ This default vicuna template formats inputs in the form of a chat history. For each message in the chat history:
202
+ * the template will output the role of the speaker followed by the content of the message.
203
+ * content is a list of strings and audios.
204
+ * If the content element is an audio, the template will output a sequence of <|AUDIO|> tokens
205
+
206
+ Example:
207
+
208
+ ```python
209
+ messages = [
210
+ {'role': 'system', 'content': 'You are a helpful assistant.'},
211
+ {"role": "user", "content": [
212
+ {"type": "audio", "audio_url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/glass-breaking-151256.mp3"},
213
+ {"type": "text", "text": "What's that sound?"},
214
+ ]},
215
+ {"role": "assistant", "content": "It is the sound of glass shattering."},
216
+ {"role": "user", "content": [
217
+ {"type": "audio", "audio_url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/f2641_0_throatclearing.wav"},
218
+ {"type": "text", "text": "How about this one?"},
219
+ ]},
220
+ ]
221
+
222
+ result = template.render(messages=messages, add_generation_prompt=True)
223
+ ```
224
+ """
225
+ # fmt: off
226
+ return (
227
+ "{% set audio_count = namespace(value=0) %}"
228
+ "{% for message in messages %}"
229
+ "{% if loop.first and message['role'] != 'system' %}"
230
+ "<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n"
231
+ "{% endif %}"
232
+ "<|im_start|>{{ message['role'] }}\n"
233
+ "{% if message['content'] is string %}"
234
+ "{{ message['content'] }}<|im_end|>\n"
235
+ "{% else %}"
236
+ "{% for content in message['content'] %}"
237
+ "{% if 'audio' in content or 'audio_url' in content or message['type'] == 'audio' or content['type'] == 'audio' %}"
238
+ "{% set audio_count.value = audio_count.value + 1 %}"
239
+ "Audio {{ audio_count.value }}: <|audio_bos|><|AUDIO|><|audio_eos|>\n"
240
+ "{% elif 'text' in content %}"
241
+ "{{ content['text'] }}"
242
+ "{% endif %}"
243
+ "{% endfor %}"
244
+ "<|im_end|>\n"
245
+ "{% endif %}"
246
+ "{% endfor %}"
247
+ "{% if add_generation_prompt %}"
248
+ "<|im_start|>assistant\n"
249
+ "{% endif %}"
250
+ )
251
+ # fmt: on
252
+
253
+
254
+ __all__ = ["Qwen2AudioProcessor"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_moe/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_qwen2_moe import *
22
+ from .modeling_qwen2_moe import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_moe/configuration_qwen2_moe.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Qwen2MoE model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...modeling_rope_utils import rope_config_validation
19
+ from ...utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class Qwen2MoeConfig(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`Qwen2MoeModel`]. It is used to instantiate a
28
+ Qwen2MoE model according to the specified arguments, defining the model architecture. Instantiating a configuration
29
+ with the defaults will yield a similar configuration to that of [Qwen/Qwen1.5-MoE-A2.7B](https://huggingface.co/Qwen/Qwen1.5-MoE-A2.7B).
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 151936):
37
+ Vocabulary size of the Qwen2MoE model. Defines the number of different tokens that can be represented by the
38
+ `inputs_ids` passed when calling [`Qwen2MoeModel`]
39
+ hidden_size (`int`, *optional*, defaults to 2048):
40
+ Dimension of the hidden representations.
41
+ intermediate_size (`int`, *optional*, defaults to 5632):
42
+ Dimension of the MLP representations.
43
+ num_hidden_layers (`int`, *optional*, defaults to 24):
44
+ Number of hidden layers in the Transformer encoder.
45
+ num_attention_heads (`int`, *optional*, defaults to 16):
46
+ Number of attention heads for each attention layer in the Transformer encoder.
47
+ num_key_value_heads (`int`, *optional*, defaults to 16):
48
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
49
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
50
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
51
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
52
+ by meanpooling all the original heads within that group. For more details, check out [this
53
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`.
54
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
55
+ The non-linear activation function (function or string) in the decoder.
56
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
57
+ The maximum sequence length that this model might ever be used with.
58
+ initializer_range (`float`, *optional*, defaults to 0.02):
59
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
60
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
61
+ The epsilon used by the rms normalization layers.
62
+ use_cache (`bool`, *optional*, defaults to `True`):
63
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
64
+ relevant if `config.is_decoder=True`.
65
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
66
+ Whether the model's input and output word embeddings should be tied.
67
+ rope_theta (`float`, *optional*, defaults to 10000.0):
68
+ The base period of the RoPE embeddings.
69
+ rope_scaling (`Dict`, *optional*):
70
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
71
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
72
+ accordingly.
73
+ Expected contents:
74
+ `rope_type` (`str`):
75
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
76
+ 'llama3'], with 'default' being the original RoPE implementation.
77
+ `factor` (`float`, *optional*):
78
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
79
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
80
+ original maximum pre-trained length.
81
+ `original_max_position_embeddings` (`int`, *optional*):
82
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
83
+ pretraining.
84
+ `attention_factor` (`float`, *optional*):
85
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
86
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
87
+ `factor` field to infer the suggested value.
88
+ `beta_fast` (`float`, *optional*):
89
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
90
+ ramp function. If unspecified, it defaults to 32.
91
+ `beta_slow` (`float`, *optional*):
92
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
93
+ ramp function. If unspecified, it defaults to 1.
94
+ `short_factor` (`list[float]`, *optional*):
95
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
96
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
97
+ size divided by the number of attention heads divided by 2
98
+ `long_factor` (`list[float]`, *optional*):
99
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
100
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
101
+ size divided by the number of attention heads divided by 2
102
+ `low_freq_factor` (`float`, *optional*):
103
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
104
+ `high_freq_factor` (`float`, *optional*):
105
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
106
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
107
+ Whether to use sliding window attention.
108
+ sliding_window (`int`, *optional*, defaults to 4096):
109
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
110
+ max_window_layers (`int`, *optional*, defaults to 28):
111
+ The number of layers using full attention. The first `max_window_layers` layers will use full attention, while any
112
+ additional layer afterwards will use SWA (Sliding Window Attention).
113
+ attention_dropout (`float`, *optional*, defaults to 0.0):
114
+ The dropout ratio for the attention probabilities.
115
+ decoder_sparse_step (`int`, *optional*, defaults to 1):
116
+ The frequency of the MoE layer.
117
+ moe_intermediate_size (`int`, *optional*, defaults to 1408):
118
+ Intermediate size of the routed expert.
119
+ shared_expert_intermediate_size (`int`, *optional*, defaults to 5632):
120
+ Intermediate size of the shared expert.
121
+ num_experts_per_tok (`int`, *optional*, defaults to 4):
122
+ Number of selected experts.
123
+ num_experts (`int`, *optional*, defaults to 60):
124
+ Number of routed experts.
125
+ norm_topk_prob (`bool`, *optional*, defaults to `False`):
126
+ Whether to normalize the topk probabilities.
127
+ output_router_logits (`bool`, *optional*, defaults to `False`):
128
+ Whether or not the router logits should be returned by the model. Enabling this will also
129
+ allow the model to output the auxiliary loss, including load balancing loss and router z-loss.
130
+ router_aux_loss_coef (`float`, *optional*, defaults to 0.001):
131
+ The aux loss factor for the total loss.
132
+ mlp_only_layers (`list[int]`, *optional*, defaults to `[]`):
133
+ Indicate which layers use Qwen2MoeMLP rather than Qwen2MoeSparseMoeBlock
134
+ The list contains layer index, from 0 to num_layers-1 if we have num_layers layers
135
+ If `mlp_only_layers` is empty, `decoder_sparse_step` is used to determine the sparsity.
136
+ qkv_bias (`bool`, *optional*, defaults to `True`):
137
+ Whether to add a bias to the queries, keys and values.
138
+ ```python
139
+ >>> from transformers import Qwen2MoeModel, Qwen2MoeConfig
140
+
141
+ >>> # Initializing a Qwen2MoE style configuration
142
+ >>> configuration = Qwen2MoeConfig()
143
+
144
+ >>> # Initializing a model from the Qwen1.5-MoE-A2.7B" style configuration
145
+ >>> model = Qwen2MoeModel(configuration)
146
+
147
+ >>> # Accessing the model configuration
148
+ >>> configuration = model.config
149
+ ```"""
150
+
151
+ model_type = "qwen2_moe"
152
+ keys_to_ignore_at_inference = ["past_key_values"]
153
+
154
+ # Default tensor parallel plan for base model `Qwen2Moe`
155
+ base_model_tp_plan = {
156
+ "layers.*.self_attn.q_proj": "colwise",
157
+ "layers.*.self_attn.k_proj": "colwise",
158
+ "layers.*.self_attn.v_proj": "colwise",
159
+ "layers.*.self_attn.o_proj": "rowwise",
160
+ "layers.*.mlp.gate_proj": "colwise",
161
+ "layers.*.mlp.up_proj": "colwise",
162
+ "layers.*.mlp.down_proj": "rowwise",
163
+ }
164
+ base_model_pp_plan = {
165
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
166
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
167
+ "norm": (["hidden_states"], ["hidden_states"]),
168
+ }
169
+
170
+ def __init__(
171
+ self,
172
+ vocab_size=151936,
173
+ hidden_size=2048,
174
+ intermediate_size=5632,
175
+ num_hidden_layers=24,
176
+ num_attention_heads=16,
177
+ num_key_value_heads=16,
178
+ hidden_act="silu",
179
+ max_position_embeddings=32768,
180
+ initializer_range=0.02,
181
+ rms_norm_eps=1e-6,
182
+ use_cache=True,
183
+ tie_word_embeddings=False,
184
+ rope_theta=10000.0,
185
+ rope_scaling=None,
186
+ use_sliding_window=False,
187
+ sliding_window=4096,
188
+ max_window_layers=28,
189
+ attention_dropout=0.0,
190
+ decoder_sparse_step=1,
191
+ moe_intermediate_size=1408,
192
+ shared_expert_intermediate_size=5632,
193
+ num_experts_per_tok=4,
194
+ num_experts=60,
195
+ norm_topk_prob=False,
196
+ output_router_logits=False,
197
+ router_aux_loss_coef=0.001,
198
+ mlp_only_layers=None,
199
+ qkv_bias=True,
200
+ **kwargs,
201
+ ):
202
+ self.vocab_size = vocab_size
203
+ self.max_position_embeddings = max_position_embeddings
204
+ self.hidden_size = hidden_size
205
+ self.intermediate_size = intermediate_size
206
+ self.num_hidden_layers = num_hidden_layers
207
+ self.num_attention_heads = num_attention_heads
208
+ self.use_sliding_window = use_sliding_window
209
+ self.sliding_window = sliding_window if use_sliding_window else None
210
+ self.max_window_layers = max_window_layers
211
+
212
+ self.num_key_value_heads = num_key_value_heads
213
+ self.hidden_act = hidden_act
214
+ self.initializer_range = initializer_range
215
+ self.rms_norm_eps = rms_norm_eps
216
+ self.use_cache = use_cache
217
+ self.rope_theta = rope_theta
218
+ self.rope_scaling = rope_scaling
219
+ self.attention_dropout = attention_dropout
220
+ # Validate the correctness of rotary position embeddings parameters
221
+ # BC: if there is a 'type' field, move it to 'rope_type'.
222
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
223
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
224
+ rope_config_validation(self)
225
+
226
+ # MoE arguments
227
+ self.decoder_sparse_step = decoder_sparse_step
228
+ self.moe_intermediate_size = moe_intermediate_size
229
+ self.shared_expert_intermediate_size = shared_expert_intermediate_size
230
+ self.num_experts_per_tok = num_experts_per_tok
231
+ self.num_experts = num_experts
232
+ self.norm_topk_prob = norm_topk_prob
233
+ self.output_router_logits = output_router_logits
234
+ self.router_aux_loss_coef = router_aux_loss_coef
235
+ self.mlp_only_layers = [] if mlp_only_layers is None else mlp_only_layers
236
+ self.qkv_bias = qkv_bias
237
+
238
+ super().__init__(
239
+ tie_word_embeddings=tie_word_embeddings,
240
+ **kwargs,
241
+ )
242
+
243
+
244
+ __all__ = ["Qwen2MoeConfig"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_moe/modeling_qwen2_moe.py ADDED
@@ -0,0 +1,1187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
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
+ """PyTorch Qwen2MoE model."""
21
+
22
+ import math
23
+ from typing import Optional, Union
24
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+
30
+ from ...activations import ACT2FN
31
+ from ...cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
32
+ from ...generation import GenerationMixin
33
+ from ...modeling_attn_mask_utils import AttentionMaskConverter
34
+ from ...modeling_flash_attention_utils import flash_attn_supports_top_left_mask, is_flash_attn_available
35
+ from ...modeling_layers import (
36
+ GenericForQuestionAnswering,
37
+ GenericForSequenceClassification,
38
+ GenericForTokenClassification,
39
+ GradientCheckpointingLayer,
40
+ )
41
+ from ...modeling_outputs import (
42
+ MoeCausalLMOutputWithPast,
43
+ MoeModelOutputWithPast,
44
+ )
45
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
46
+ from ...modeling_utils import PreTrainedModel
47
+ from ...utils import auto_docstring, can_return_tuple, is_torch_flex_attn_available, logging
48
+ from ...utils.deprecation import deprecate_kwarg
49
+ from .configuration_qwen2_moe import Qwen2MoeConfig
50
+
51
+
52
+ if is_flash_attn_available():
53
+ from ...modeling_flash_attention_utils import _flash_attention_forward
54
+
55
+ if is_torch_flex_attn_available():
56
+ from torch.nn.attention.flex_attention import BlockMask
57
+
58
+ from ...integrations.flex_attention import make_flex_block_causal_mask
59
+
60
+ logger = logging.get_logger(__name__)
61
+
62
+
63
+ def load_balancing_loss_func(
64
+ gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
65
+ num_experts: Optional[int] = None,
66
+ top_k=2,
67
+ attention_mask: Optional[torch.Tensor] = None,
68
+ ) -> Union[torch.Tensor, int]:
69
+ r"""
70
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
71
+
72
+ See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
73
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
74
+ experts is too unbalanced.
75
+
76
+ Args:
77
+ gate_logits:
78
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
79
+ shape [batch_size X sequence_length, num_experts].
80
+ num_experts:
81
+ Number of experts
82
+ top_k:
83
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
84
+ parameter.
85
+ attention_mask (`torch.Tensor`, *optional*):
86
+ The attention_mask used in forward function
87
+ shape [batch_size X sequence_length] if not None.
88
+
89
+ Returns:
90
+ The auxiliary loss.
91
+ """
92
+ if gate_logits is None or not isinstance(gate_logits, tuple):
93
+ return 0
94
+
95
+ if isinstance(gate_logits, tuple):
96
+ compute_device = gate_logits[0].device
97
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
98
+
99
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
100
+
101
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
102
+
103
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
104
+
105
+ if attention_mask is None:
106
+ # Compute the percentage of tokens routed to each experts
107
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
108
+
109
+ # Compute the average probability of routing to these experts
110
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
111
+ else:
112
+ batch_size, sequence_length = attention_mask.shape
113
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
114
+
115
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
116
+ expert_attention_mask = (
117
+ attention_mask[None, :, :, None, None]
118
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
119
+ .reshape(-1, top_k, num_experts)
120
+ .to(compute_device)
121
+ )
122
+
123
+ # Compute the percentage of tokens routed to each experts
124
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
125
+ expert_attention_mask, dim=0
126
+ )
127
+
128
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
129
+ router_per_expert_attention_mask = (
130
+ attention_mask[None, :, :, None]
131
+ .expand((num_hidden_layers, batch_size, sequence_length, routing_weights.shape[1]))
132
+ .reshape(-1, routing_weights.shape[1])
133
+ .to(compute_device)
134
+ )
135
+
136
+ # Compute the average probability of routing to these experts
137
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
138
+ router_per_expert_attention_mask, dim=0
139
+ )
140
+
141
+ device_index = routing_weights.device.index if routing_weights.device.index is not None else 0
142
+ rank = routing_weights.shape[1] * int(device_index)
143
+ overall_loss = torch.sum(
144
+ tokens_per_expert[:, rank : rank + routing_weights.shape[1]] * router_prob_per_expert.unsqueeze(0)
145
+ )
146
+ return overall_loss * num_experts
147
+
148
+
149
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Qwen2Moe
150
+ class Qwen2MoeRMSNorm(nn.Module):
151
+ def __init__(self, hidden_size, eps=1e-6):
152
+ """
153
+ Qwen2MoeRMSNorm is equivalent to T5LayerNorm
154
+ """
155
+ super().__init__()
156
+ self.weight = nn.Parameter(torch.ones(hidden_size))
157
+ self.variance_epsilon = eps
158
+
159
+ def forward(self, hidden_states):
160
+ input_dtype = hidden_states.dtype
161
+ hidden_states = hidden_states.to(torch.float32)
162
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
163
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
164
+ return self.weight * hidden_states.to(input_dtype)
165
+
166
+ def extra_repr(self):
167
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
168
+
169
+
170
+ # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Qwen2Moe
171
+ class Qwen2MoeRotaryEmbedding(nn.Module):
172
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
173
+
174
+ def __init__(self, config: Qwen2MoeConfig, device=None):
175
+ super().__init__()
176
+ # BC: "rope_type" was originally "type"
177
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
178
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
179
+ else:
180
+ self.rope_type = "default"
181
+ self.max_seq_len_cached = config.max_position_embeddings
182
+ self.original_max_seq_len = config.max_position_embeddings
183
+
184
+ self.config = config
185
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
186
+
187
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
188
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
189
+ self.original_inv_freq = self.inv_freq
190
+
191
+ @torch.no_grad()
192
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
193
+ def forward(self, x, position_ids):
194
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
195
+ position_ids_expanded = position_ids[:, None, :].float()
196
+
197
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
198
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
199
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
200
+ emb = torch.cat((freqs, freqs), dim=-1)
201
+ cos = emb.cos() * self.attention_scaling
202
+ sin = emb.sin() * self.attention_scaling
203
+
204
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
205
+
206
+
207
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
208
+ def rotate_half(x):
209
+ """Rotates half the hidden dims of the input."""
210
+ x1 = x[..., : x.shape[-1] // 2]
211
+ x2 = x[..., x.shape[-1] // 2 :]
212
+ return torch.cat((-x2, x1), dim=-1)
213
+
214
+
215
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
216
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
217
+ """Applies Rotary Position Embedding to the query and key tensors.
218
+
219
+ Args:
220
+ q (`torch.Tensor`): The query tensor.
221
+ k (`torch.Tensor`): The key tensor.
222
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
223
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
224
+ position_ids (`torch.Tensor`, *optional*):
225
+ Deprecated and unused.
226
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
227
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
228
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
229
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
230
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
231
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
232
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
233
+ Returns:
234
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
235
+ """
236
+ cos = cos.unsqueeze(unsqueeze_dim)
237
+ sin = sin.unsqueeze(unsqueeze_dim)
238
+ q_embed = (q * cos) + (rotate_half(q) * sin)
239
+ k_embed = (k * cos) + (rotate_half(k) * sin)
240
+ return q_embed, k_embed
241
+
242
+
243
+ # Modified from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Qwen2Moe
244
+ class Qwen2MoeMLP(nn.Module):
245
+ def __init__(self, config, intermediate_size=None):
246
+ super().__init__()
247
+ self.config = config
248
+ self.hidden_size = config.hidden_size
249
+ self.intermediate_size = intermediate_size
250
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
251
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
252
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
253
+ self.act_fn = ACT2FN[config.hidden_act]
254
+
255
+ def forward(self, x):
256
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
257
+
258
+
259
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
260
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
261
+ """
262
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
263
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
264
+ """
265
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
266
+ if n_rep == 1:
267
+ return hidden_states
268
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
269
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
270
+
271
+
272
+ # copied from transformers.models.qwen2.modeling_qwen2.Qwen2Attention with Qwen2->Qwen2Moe
273
+ # no longer copied after attention refactors
274
+ class Qwen2MoeAttention(nn.Module):
275
+ """
276
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
277
+ and "Generating Long Sequences with Sparse Transformers".
278
+ """
279
+
280
+ def __init__(self, config: Qwen2MoeConfig, layer_idx: Optional[int] = None):
281
+ super().__init__()
282
+ self.config = config
283
+ self.layer_idx = layer_idx
284
+ if layer_idx is None:
285
+ logger.warning_once(
286
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
287
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
288
+ "when creating this class."
289
+ )
290
+
291
+ self.hidden_size = config.hidden_size
292
+ self.num_heads = config.num_attention_heads
293
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
294
+ self.num_key_value_heads = config.num_key_value_heads
295
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
296
+ self.max_position_embeddings = config.max_position_embeddings
297
+ self.rope_theta = config.rope_theta
298
+ self.is_causal = True
299
+ self.attention_dropout = config.attention_dropout
300
+
301
+ if (self.head_dim * self.num_heads) != self.hidden_size:
302
+ raise ValueError(
303
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
304
+ f" and `num_heads`: {self.num_heads})."
305
+ )
306
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=self.config.qkv_bias)
307
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=self.config.qkv_bias)
308
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=self.config.qkv_bias)
309
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
310
+
311
+ self.rotary_emb = Qwen2MoeRotaryEmbedding(config=self.config)
312
+
313
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
314
+ def forward(
315
+ self,
316
+ hidden_states: torch.Tensor,
317
+ attention_mask: Optional[torch.Tensor] = None,
318
+ position_ids: Optional[torch.LongTensor] = None,
319
+ past_key_values: Optional[Cache] = None,
320
+ output_attentions: bool = False,
321
+ use_cache: bool = False,
322
+ cache_position: Optional[torch.LongTensor] = None,
323
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
324
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
325
+ bsz, q_len, _ = hidden_states.size()
326
+
327
+ query_states = self.q_proj(hidden_states)
328
+ key_states = self.k_proj(hidden_states)
329
+ value_states = self.v_proj(hidden_states)
330
+
331
+ query_states = query_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
332
+ key_states = key_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
333
+ value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
334
+
335
+ cos, sin = position_embeddings
336
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
337
+
338
+ if past_key_values is not None:
339
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
340
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
341
+
342
+ # repeat k/v heads if n_kv_heads < n_heads
343
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
344
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
345
+
346
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
347
+
348
+ if attention_mask is not None: # no matter the length, we just slice it
349
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
350
+ attn_weights = attn_weights + causal_mask
351
+
352
+ # upcast attention to fp32
353
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
354
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
355
+ attn_output = torch.matmul(attn_weights, value_states)
356
+
357
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
358
+ raise ValueError(
359
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
360
+ f" {attn_output.size()}"
361
+ )
362
+
363
+ attn_output = attn_output.transpose(1, 2).contiguous()
364
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
365
+
366
+ attn_output = self.o_proj(attn_output)
367
+
368
+ if not output_attentions:
369
+ attn_weights = None
370
+
371
+ return attn_output, attn_weights
372
+
373
+
374
+ # NO LONGER EXIST Copied from transformers.models.qwen2.modeling_qwen2.Qwen2FlashAttention2 with Qwen2->Qwen2Moe
375
+ # TODO cyril: modular
376
+ class Qwen2MoeFlashAttention2(Qwen2MoeAttention):
377
+ """
378
+ Qwen2Moe flash attention module, following Qwen2Moe attention module. This module inherits from `Qwen2MoeAttention`
379
+ as the weights of the module stays untouched. The only required change would be on the forward pass
380
+ where it needs to correctly call the public API of flash attention and deal with padding tokens
381
+ in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
382
+ config.max_window_layers layers.
383
+ """
384
+
385
+ def __init__(self, *args, **kwargs):
386
+ super().__init__(*args, **kwargs)
387
+
388
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
389
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignment, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
390
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
391
+ self._flash_attn_uses_top_left_mask = flash_attn_supports_top_left_mask()
392
+
393
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
394
+ def forward(
395
+ self,
396
+ hidden_states: torch.Tensor,
397
+ attention_mask: Optional[torch.Tensor] = None,
398
+ position_ids: Optional[torch.LongTensor] = None,
399
+ past_key_values: Optional[Cache] = None,
400
+ output_attentions: bool = False,
401
+ use_cache: bool = False,
402
+ cache_position: Optional[torch.LongTensor] = None,
403
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
404
+ ):
405
+ bsz, q_len, _ = hidden_states.size()
406
+
407
+ query_states = self.q_proj(hidden_states)
408
+ key_states = self.k_proj(hidden_states)
409
+ value_states = self.v_proj(hidden_states)
410
+
411
+ query_states = query_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
412
+ key_states = key_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
413
+ value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
414
+
415
+ cos, sin = position_embeddings
416
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
417
+
418
+ if past_key_values is not None:
419
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
420
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
421
+
422
+ # repeat k/v heads if n_kv_heads < n_heads
423
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
424
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
425
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
426
+
427
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
428
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
429
+ # cast them back in float16 just to be sure everything works as expected.
430
+ input_dtype = query_states.dtype
431
+ device_type = query_states.device.type if query_states.device.type != "mps" else "cpu"
432
+ if input_dtype == torch.float32:
433
+ if torch.is_autocast_enabled():
434
+ target_dtype = (
435
+ torch.get_autocast_dtype(device_type)
436
+ if hasattr(torch, "get_autocast_dtype")
437
+ else torch.get_autocast_gpu_dtype()
438
+ )
439
+ # Handle the case where the model is quantized
440
+ elif hasattr(self.config, "_pre_quantization_dtype"):
441
+ target_dtype = self.config._pre_quantization_dtype
442
+ else:
443
+ target_dtype = self.q_proj.weight.dtype
444
+
445
+ logger.warning_once(
446
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
447
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
448
+ f" {target_dtype}."
449
+ )
450
+
451
+ query_states = query_states.to(target_dtype)
452
+ key_states = key_states.to(target_dtype)
453
+ value_states = value_states.to(target_dtype)
454
+
455
+ # Reashape to the expected shape for Flash Attention
456
+ query_states = query_states.transpose(1, 2)
457
+ key_states = key_states.transpose(1, 2)
458
+ value_states = value_states.transpose(1, 2)
459
+
460
+ if (
461
+ self.config.use_sliding_window
462
+ and getattr(self.config, "sliding_window", None) is not None
463
+ and self.layer_idx >= self.config.max_window_layers
464
+ ):
465
+ sliding_window = self.config.sliding_window
466
+ else:
467
+ sliding_window = None
468
+
469
+ attn_output = _flash_attention_forward(
470
+ query_states,
471
+ key_states,
472
+ value_states,
473
+ attention_mask,
474
+ q_len,
475
+ position_ids=position_ids,
476
+ dropout=dropout_rate,
477
+ sliding_window=sliding_window,
478
+ is_causal=self.is_causal,
479
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
480
+ )
481
+
482
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
483
+ attn_output = self.o_proj(attn_output)
484
+
485
+ if not output_attentions:
486
+ attn_weights = None
487
+
488
+ return attn_output, attn_weights
489
+
490
+
491
+ # NO LONGER EXIST Copied from transformers.models.qwen2.modeling_qwen2.Qwen2SdpaAttention with Qwen2->Qwen2Moe
492
+ # TODO cyril: modular
493
+ class Qwen2MoeSdpaAttention(Qwen2MoeAttention):
494
+ """
495
+ Qwen2Moe attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
496
+ `Qwen2MoeAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
497
+ SDPA API.
498
+ """
499
+
500
+ # Adapted from Qwen2MoeAttention.forward
501
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
502
+ def forward(
503
+ self,
504
+ hidden_states: torch.Tensor,
505
+ attention_mask: Optional[torch.Tensor] = None,
506
+ position_ids: Optional[torch.LongTensor] = None,
507
+ past_key_values: Optional[Cache] = None,
508
+ output_attentions: bool = False,
509
+ use_cache: bool = False,
510
+ cache_position: Optional[torch.LongTensor] = None,
511
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
512
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
513
+ if output_attentions:
514
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
515
+ logger.warning_once(
516
+ "Qwen2MoeModel is using Qwen2MoeSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
517
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
518
+ )
519
+ return super().forward(
520
+ hidden_states=hidden_states,
521
+ attention_mask=attention_mask,
522
+ position_ids=position_ids,
523
+ past_key_values=past_key_values,
524
+ output_attentions=output_attentions,
525
+ use_cache=use_cache,
526
+ cache_position=cache_position,
527
+ position_embeddings=position_embeddings,
528
+ )
529
+
530
+ bsz, q_len, _ = hidden_states.size()
531
+
532
+ query_states = self.q_proj(hidden_states)
533
+ key_states = self.k_proj(hidden_states)
534
+ value_states = self.v_proj(hidden_states)
535
+
536
+ query_states = query_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
537
+ key_states = key_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
538
+ value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
539
+
540
+ cos, sin = position_embeddings
541
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
542
+
543
+ if past_key_values is not None:
544
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
545
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
546
+
547
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
548
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
549
+
550
+ causal_mask = attention_mask
551
+ if attention_mask is not None: # no matter the length, we just slice it
552
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
553
+
554
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
555
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
556
+ if query_states.device.type == "cuda" and attention_mask is not None:
557
+ query_states = query_states.contiguous()
558
+ key_states = key_states.contiguous()
559
+ value_states = value_states.contiguous()
560
+
561
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
562
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
563
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
564
+ is_causal = bool(causal_mask is None and q_len > 1)
565
+
566
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
567
+ query_states,
568
+ key_states,
569
+ value_states,
570
+ attn_mask=causal_mask,
571
+ dropout_p=self.attention_dropout if self.training else 0.0,
572
+ is_causal=is_causal,
573
+ )
574
+
575
+ attn_output = attn_output.transpose(1, 2).contiguous()
576
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
577
+
578
+ attn_output = self.o_proj(attn_output)
579
+
580
+ return attn_output, None
581
+
582
+
583
+ QWEN2MOE_ATTENTION_CLASSES = {
584
+ "eager": Qwen2MoeAttention,
585
+ "flash_attention_2": Qwen2MoeFlashAttention2,
586
+ "sdpa": Qwen2MoeSdpaAttention,
587
+ }
588
+
589
+
590
+ class Qwen2MoeSparseMoeBlock(nn.Module):
591
+ def __init__(self, config):
592
+ super().__init__()
593
+ self.num_experts = config.num_experts
594
+ self.top_k = config.num_experts_per_tok
595
+ self.norm_topk_prob = config.norm_topk_prob
596
+
597
+ # gating
598
+ self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False)
599
+ self.experts = nn.ModuleList(
600
+ [Qwen2MoeMLP(config, intermediate_size=config.moe_intermediate_size) for _ in range(self.num_experts)]
601
+ )
602
+
603
+ self.shared_expert = Qwen2MoeMLP(config, intermediate_size=config.shared_expert_intermediate_size)
604
+ self.shared_expert_gate = torch.nn.Linear(config.hidden_size, 1, bias=False)
605
+
606
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
607
+ """ """
608
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
609
+ hidden_states = hidden_states.view(-1, hidden_dim)
610
+ # router_logits: (batch * sequence_length, n_experts)
611
+ router_logits = self.gate(hidden_states)
612
+
613
+ routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
614
+ routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
615
+ if self.norm_topk_prob:
616
+ routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
617
+ # we cast back to the input dtype
618
+ routing_weights = routing_weights.to(hidden_states.dtype)
619
+
620
+ final_hidden_states = torch.zeros(
621
+ (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
622
+ )
623
+
624
+ # One hot encode the selected experts to create an expert mask
625
+ # this will be used to easily index which expert is going to be sollicitated
626
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
627
+
628
+ # Loop over all available experts in the model and perform the computation on each expert
629
+ expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
630
+ for expert_idx in expert_hit:
631
+ expert_layer = self.experts[expert_idx]
632
+ idx, top_x = torch.where(expert_mask[expert_idx].squeeze(0))
633
+
634
+ # Index the correct hidden states and compute the expert hidden state for
635
+ # the current expert. We need to make sure to multiply the output hidden
636
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
637
+ current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
638
+ current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
639
+
640
+ # However `index_add_` only support torch tensors for indexing so we'll use
641
+ # the `top_x` tensor here.
642
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
643
+
644
+ shared_expert_output = self.shared_expert(hidden_states)
645
+ shared_expert_output = F.sigmoid(self.shared_expert_gate(hidden_states)) * shared_expert_output
646
+
647
+ final_hidden_states = final_hidden_states + shared_expert_output
648
+
649
+ final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
650
+ return final_hidden_states, router_logits
651
+
652
+
653
+ class Qwen2MoeDecoderLayer(GradientCheckpointingLayer):
654
+ def __init__(self, config: Qwen2MoeConfig, layer_idx: int):
655
+ super().__init__()
656
+ self.hidden_size = config.hidden_size
657
+
658
+ self.self_attn = QWEN2MOE_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
659
+
660
+ if (layer_idx not in config.mlp_only_layers) and (
661
+ config.num_experts > 0 and (layer_idx + 1) % config.decoder_sparse_step == 0
662
+ ):
663
+ self.mlp = Qwen2MoeSparseMoeBlock(config)
664
+ else:
665
+ self.mlp = Qwen2MoeMLP(config, intermediate_size=config.intermediate_size)
666
+
667
+ self.input_layernorm = Qwen2MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
668
+ self.post_attention_layernorm = Qwen2MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
669
+
670
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
671
+ def forward(
672
+ self,
673
+ hidden_states: torch.Tensor,
674
+ attention_mask: Optional[torch.Tensor] = None,
675
+ position_ids: Optional[torch.LongTensor] = None,
676
+ past_key_values: Optional[tuple[torch.Tensor]] = None,
677
+ output_attentions: Optional[bool] = False,
678
+ output_router_logits: Optional[bool] = False,
679
+ use_cache: Optional[bool] = False,
680
+ cache_position: Optional[torch.LongTensor] = None,
681
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
682
+ **kwargs,
683
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
684
+ """
685
+ Args:
686
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
687
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
688
+ `(batch, sequence_length)` where padding elements are indicated by 0.
689
+ output_attentions (`bool`, *optional*):
690
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
691
+ returned tensors for more detail.
692
+ output_router_logits (`bool`, *optional*):
693
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss,
694
+ and should not be returned during inference.
695
+ use_cache (`bool`, *optional*):
696
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
697
+ (see `past_key_values`).
698
+ past_key_values (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
699
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
700
+ Indices depicting the position of the input sequence tokens in the sequence.
701
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
702
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
703
+ with `head_dim` being the embedding dimension of each attention head.
704
+ kwargs (`dict`, *optional*):
705
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
706
+ into the model
707
+ """
708
+
709
+ residual = hidden_states
710
+
711
+ hidden_states = self.input_layernorm(hidden_states)
712
+
713
+ # Self Attention
714
+ hidden_states, self_attn_weights = self.self_attn(
715
+ hidden_states=hidden_states,
716
+ attention_mask=attention_mask,
717
+ position_ids=position_ids,
718
+ past_key_values=past_key_values,
719
+ output_attentions=output_attentions,
720
+ use_cache=use_cache,
721
+ cache_position=cache_position,
722
+ position_embeddings=position_embeddings,
723
+ )
724
+ hidden_states = residual + hidden_states
725
+
726
+ # Fully Connected
727
+ residual = hidden_states
728
+ hidden_states = self.post_attention_layernorm(hidden_states)
729
+
730
+ hidden_states = self.mlp(hidden_states)
731
+ if isinstance(hidden_states, tuple):
732
+ hidden_states, router_logits = hidden_states
733
+ else:
734
+ router_logits = None
735
+
736
+ hidden_states = residual + hidden_states
737
+
738
+ outputs = (hidden_states,)
739
+
740
+ if output_attentions:
741
+ outputs += (self_attn_weights,)
742
+
743
+ if output_router_logits:
744
+ outputs += (router_logits,)
745
+
746
+ return outputs
747
+
748
+
749
+ @auto_docstring
750
+ class Qwen2MoePreTrainedModel(PreTrainedModel):
751
+ config: Qwen2MoeConfig
752
+ base_model_prefix = "model"
753
+ supports_gradient_checkpointing = True
754
+ _no_split_modules = ["Qwen2MoeDecoderLayer"]
755
+ _skip_keys_device_placement = "past_key_values"
756
+ _supports_flash_attn = True
757
+ _supports_sdpa = True
758
+
759
+ def _init_weights(self, module):
760
+ std = self.config.initializer_range
761
+ if isinstance(module, nn.Linear):
762
+ module.weight.data.normal_(mean=0.0, std=std)
763
+ if module.bias is not None:
764
+ module.bias.data.zero_()
765
+ elif isinstance(module, nn.Embedding):
766
+ module.weight.data.normal_(mean=0.0, std=std)
767
+ if module.padding_idx is not None:
768
+ module.weight.data[module.padding_idx].zero_()
769
+ elif isinstance(module, Qwen2MoeRMSNorm):
770
+ module.weight.data.fill_(1.0)
771
+
772
+
773
+ @auto_docstring
774
+ class Qwen2MoeModel(Qwen2MoePreTrainedModel):
775
+ def __init__(self, config: Qwen2MoeConfig):
776
+ super().__init__(config)
777
+ self.padding_idx = config.pad_token_id
778
+ self.vocab_size = config.vocab_size
779
+
780
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
781
+ self.layers = nn.ModuleList(
782
+ [Qwen2MoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
783
+ )
784
+ self._attn_implementation = config._attn_implementation
785
+ self.norm = Qwen2MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
786
+ self.rotary_emb = Qwen2MoeRotaryEmbedding(config=config)
787
+
788
+ self.gradient_checkpointing = False
789
+ # Initialize weights and apply final processing
790
+ self.post_init()
791
+
792
+ @can_return_tuple
793
+ @auto_docstring
794
+ def forward(
795
+ self,
796
+ input_ids: Optional[torch.LongTensor] = None,
797
+ attention_mask: Optional[torch.Tensor] = None,
798
+ position_ids: Optional[torch.LongTensor] = None,
799
+ past_key_values: Optional[Cache] = None,
800
+ inputs_embeds: Optional[torch.FloatTensor] = None,
801
+ use_cache: Optional[bool] = None,
802
+ output_attentions: Optional[bool] = None,
803
+ output_hidden_states: Optional[bool] = None,
804
+ output_router_logits: Optional[bool] = None,
805
+ cache_position: Optional[torch.LongTensor] = None,
806
+ ) -> MoeModelOutputWithPast:
807
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
808
+ output_router_logits = (
809
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
810
+ )
811
+ output_hidden_states = (
812
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
813
+ )
814
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
815
+
816
+ if (input_ids is None) ^ (inputs_embeds is not None):
817
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
818
+
819
+ if self.gradient_checkpointing and self.training:
820
+ if use_cache:
821
+ logger.warning_once(
822
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
823
+ )
824
+ use_cache = False
825
+
826
+ # TODO (joao): remove this exception in v4.56 -- it exists for users that try to pass a legacy cache
827
+ if not isinstance(past_key_values, (type(None), Cache)):
828
+ raise ValueError("The `past_key_values` should be either a `Cache` object or `None`.")
829
+
830
+ if use_cache and past_key_values is None:
831
+ past_key_values = DynamicCache(config=self.config)
832
+
833
+ if inputs_embeds is None:
834
+ inputs_embeds = self.embed_tokens(input_ids)
835
+
836
+ if cache_position is None:
837
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
838
+ cache_position = torch.arange(
839
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
840
+ )
841
+ if position_ids is None:
842
+ position_ids = cache_position.unsqueeze(0)
843
+
844
+ causal_mask = self._update_causal_mask(
845
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
846
+ )
847
+
848
+ hidden_states = inputs_embeds
849
+
850
+ # create position embeddings to be shared across the decoder layers
851
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
852
+
853
+ # decoder layers
854
+ all_hidden_states = () if output_hidden_states else None
855
+ all_self_attns = () if output_attentions else None
856
+ all_router_logits = () if output_router_logits else None
857
+
858
+ for decoder_layer in self.layers:
859
+ if output_hidden_states:
860
+ all_hidden_states += (hidden_states,)
861
+
862
+ layer_outputs = decoder_layer(
863
+ hidden_states,
864
+ attention_mask=causal_mask,
865
+ position_ids=position_ids,
866
+ past_key_values=past_key_values,
867
+ output_attentions=output_attentions,
868
+ output_router_logits=output_router_logits,
869
+ use_cache=use_cache,
870
+ cache_position=cache_position,
871
+ position_embeddings=position_embeddings,
872
+ )
873
+
874
+ hidden_states = layer_outputs[0]
875
+
876
+ if output_attentions:
877
+ all_self_attns += (layer_outputs[1],)
878
+
879
+ if output_router_logits and layer_outputs[-1] is not None:
880
+ all_router_logits += (layer_outputs[-1],)
881
+
882
+ hidden_states = self.norm(hidden_states)
883
+
884
+ # add hidden states from the last decoder layer
885
+ if output_hidden_states:
886
+ all_hidden_states += (hidden_states,)
887
+
888
+ return MoeModelOutputWithPast(
889
+ last_hidden_state=hidden_states,
890
+ past_key_values=past_key_values,
891
+ hidden_states=all_hidden_states,
892
+ attentions=all_self_attns,
893
+ router_logits=all_router_logits,
894
+ )
895
+
896
+ # Copied from transformers.models.phimoe.modeling_phimoe.PhimoeModel._update_causal_mask with Phimoe->Qwen2Moe
897
+ def _update_causal_mask(
898
+ self,
899
+ attention_mask: Union[torch.Tensor, "BlockMask"],
900
+ input_tensor: torch.Tensor,
901
+ cache_position: torch.Tensor,
902
+ past_key_values: Cache,
903
+ output_attentions: bool = False,
904
+ ):
905
+ if self.config._attn_implementation == "flash_attention_2":
906
+ if attention_mask is not None and past_key_values is not None:
907
+ is_padding_right = attention_mask[:, -1].sum().item() != input_tensor.size()[0]
908
+ if is_padding_right:
909
+ raise ValueError(
910
+ "You are attempting to perform batched generation with padding_side='right'"
911
+ " this may lead to unexpected behaviour for Flash Attention version of Qwen2Moe. Make sure to "
912
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
913
+ )
914
+ if attention_mask is not None and 0.0 in attention_mask:
915
+ return attention_mask
916
+ return None
917
+ if self.config._attn_implementation == "flex_attention":
918
+ if isinstance(attention_mask, torch.Tensor):
919
+ attention_mask = make_flex_block_causal_mask(attention_mask)
920
+ return attention_mask
921
+
922
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
923
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
924
+ # to infer the attention mask.
925
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
926
+ using_static_cache = isinstance(past_key_values, StaticCache)
927
+ using_sliding_window_cache = isinstance(past_key_values, SlidingWindowCache)
928
+
929
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
930
+ if (
931
+ self.config._attn_implementation == "sdpa"
932
+ and not (using_static_cache or using_sliding_window_cache)
933
+ and not output_attentions
934
+ ):
935
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
936
+ attention_mask,
937
+ inputs_embeds=input_tensor,
938
+ past_key_values_length=past_seen_tokens,
939
+ sliding_window=self.config.sliding_window,
940
+ is_training=self.training,
941
+ ):
942
+ return None
943
+
944
+ dtype = input_tensor.dtype
945
+ min_dtype = torch.finfo(dtype).min
946
+ sequence_length = input_tensor.shape[1]
947
+ # SlidingWindowCache or StaticCache
948
+ if using_sliding_window_cache or using_static_cache:
949
+ target_length = past_key_values.get_max_cache_shape()
950
+ # DynamicCache or no cache
951
+ else:
952
+ target_length = (
953
+ attention_mask.shape[-1]
954
+ if isinstance(attention_mask, torch.Tensor)
955
+ else past_seen_tokens + sequence_length + 1
956
+ )
957
+
958
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
959
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
960
+ attention_mask,
961
+ sequence_length=sequence_length,
962
+ target_length=target_length,
963
+ dtype=dtype,
964
+ cache_position=cache_position,
965
+ batch_size=input_tensor.shape[0],
966
+ config=self.config,
967
+ past_key_values=past_key_values,
968
+ )
969
+
970
+ if (
971
+ self.config._attn_implementation == "sdpa"
972
+ and attention_mask is not None
973
+ and attention_mask.device.type in ["cuda", "xpu", "npu"]
974
+ and not output_attentions
975
+ ):
976
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
977
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
978
+ # Details: https://github.com/pytorch/pytorch/issues/110213
979
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
980
+
981
+ return causal_mask
982
+
983
+ @staticmethod
984
+ # Copied from transformers.models.phimoe.modeling_phimoe.PhimoeModel._prepare_4d_causal_attention_mask_with_cache_position with Phimoe->Qwen2Moe
985
+ def _prepare_4d_causal_attention_mask_with_cache_position(
986
+ attention_mask: torch.Tensor,
987
+ sequence_length: int,
988
+ target_length: int,
989
+ dtype: torch.dtype,
990
+ cache_position: torch.Tensor,
991
+ batch_size: int,
992
+ config: Qwen2MoeConfig,
993
+ past_key_values: Cache,
994
+ ):
995
+ """
996
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
997
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
998
+
999
+ Args:
1000
+ attention_mask (`torch.Tensor`):
1001
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
1002
+ sequence_length (`int`):
1003
+ The sequence length being processed.
1004
+ target_length (`int`):
1005
+ The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
1006
+ dtype (`torch.dtype`):
1007
+ The dtype to use for the 4D attention mask.
1008
+ cache_position (`torch.Tensor`):
1009
+ Indices depicting the position of the input sequence tokens in the sequence.
1010
+ batch_size (`torch.Tensor`):
1011
+ Batch size.
1012
+ config (`Qwen2MoeConfig`):
1013
+ The model's configuration class
1014
+ past_key_values (`Cache`):
1015
+ The cache class that is being used currently to generate
1016
+ """
1017
+ if attention_mask is not None and attention_mask.dim() == 4:
1018
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
1019
+ causal_mask = attention_mask
1020
+ else:
1021
+ min_dtype = torch.finfo(dtype).min
1022
+ causal_mask = torch.full(
1023
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
1024
+ )
1025
+ diagonal_attend_mask = torch.arange(target_length, device=cache_position.device) > cache_position.reshape(
1026
+ -1, 1
1027
+ )
1028
+ text_config = config.get_text_config()
1029
+ if getattr(text_config, "use_sliding_window", True) and text_config.sliding_window is not None:
1030
+ # if we have sliding window, we should not attend to tokens beyond sliding window length, so we mask them out also
1031
+ # the check is needed to verify is current checkpoint was trained with sliding window or not
1032
+ if not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length:
1033
+ sliding_attend_mask = torch.arange(target_length, device=cache_position.device) <= (
1034
+ cache_position.reshape(-1, 1) - text_config.sliding_window
1035
+ )
1036
+ diagonal_attend_mask.bitwise_or_(sliding_attend_mask)
1037
+ causal_mask *= diagonal_attend_mask
1038
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
1039
+ if attention_mask is not None:
1040
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1041
+ if attention_mask.shape[-1] > target_length:
1042
+ attention_mask = attention_mask[:, :target_length]
1043
+ mask_length = attention_mask.shape[-1]
1044
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
1045
+ causal_mask.device
1046
+ )
1047
+ padding_mask = padding_mask == 0
1048
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1049
+ padding_mask, min_dtype
1050
+ )
1051
+ return causal_mask
1052
+
1053
+
1054
+ class Qwen2MoeForCausalLM(Qwen2MoePreTrainedModel, GenerationMixin):
1055
+ _tied_weights_keys = ["lm_head.weight"]
1056
+ _tp_plan = {"lm_head": "colwise_rep"}
1057
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
1058
+
1059
+ def __init__(self, config):
1060
+ super().__init__(config)
1061
+ self.model = Qwen2MoeModel(config)
1062
+ self.vocab_size = config.vocab_size
1063
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1064
+
1065
+ self.router_aux_loss_coef = config.router_aux_loss_coef
1066
+ self.num_experts = config.num_experts
1067
+ self.num_experts_per_tok = config.num_experts_per_tok
1068
+ # Initialize weights and apply final processing
1069
+ self.post_init()
1070
+
1071
+ def set_decoder(self, decoder):
1072
+ self.model = decoder
1073
+
1074
+ def get_decoder(self):
1075
+ return self.model
1076
+
1077
+ @can_return_tuple
1078
+ @auto_docstring
1079
+ def forward(
1080
+ self,
1081
+ input_ids: Optional[torch.LongTensor] = None,
1082
+ attention_mask: Optional[torch.Tensor] = None,
1083
+ position_ids: Optional[torch.LongTensor] = None,
1084
+ past_key_values: Optional[Cache] = None,
1085
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1086
+ labels: Optional[torch.LongTensor] = None,
1087
+ use_cache: Optional[bool] = None,
1088
+ output_attentions: Optional[bool] = None,
1089
+ output_hidden_states: Optional[bool] = None,
1090
+ output_router_logits: Optional[bool] = None,
1091
+ cache_position: Optional[torch.LongTensor] = None,
1092
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1093
+ **kwargs,
1094
+ ) -> MoeCausalLMOutputWithPast:
1095
+ r"""
1096
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1097
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1098
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1099
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1100
+
1101
+ Example:
1102
+
1103
+ ```python
1104
+ >>> from transformers import AutoTokenizer, Qwen2MoeForCausalLM
1105
+
1106
+ >>> model = Qwen2MoeForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1107
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1108
+
1109
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1110
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1111
+
1112
+ >>> # Generate
1113
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1114
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1115
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1116
+ ```"""
1117
+
1118
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1119
+ output_router_logits = (
1120
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1121
+ )
1122
+ output_hidden_states = (
1123
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1124
+ )
1125
+
1126
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1127
+ outputs: MoeModelOutputWithPast = self.model(
1128
+ input_ids=input_ids,
1129
+ attention_mask=attention_mask,
1130
+ position_ids=position_ids,
1131
+ past_key_values=past_key_values,
1132
+ inputs_embeds=inputs_embeds,
1133
+ use_cache=use_cache,
1134
+ output_attentions=output_attentions,
1135
+ output_hidden_states=output_hidden_states,
1136
+ output_router_logits=output_router_logits,
1137
+ cache_position=cache_position,
1138
+ )
1139
+
1140
+ hidden_states = outputs.last_hidden_state
1141
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1142
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1143
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1144
+
1145
+ loss = None
1146
+ if labels is not None:
1147
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
1148
+
1149
+ aux_loss = None
1150
+ if output_router_logits:
1151
+ aux_loss = load_balancing_loss_func(
1152
+ outputs.router_logits,
1153
+ self.num_experts,
1154
+ self.num_experts_per_tok,
1155
+ attention_mask,
1156
+ )
1157
+ if labels is not None:
1158
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
1159
+
1160
+ return MoeCausalLMOutputWithPast(
1161
+ loss=loss,
1162
+ aux_loss=aux_loss,
1163
+ logits=logits,
1164
+ past_key_values=outputs.past_key_values,
1165
+ hidden_states=outputs.hidden_states,
1166
+ attentions=outputs.attentions,
1167
+ router_logits=outputs.router_logits,
1168
+ )
1169
+
1170
+
1171
+ class Qwen2MoeForSequenceClassification(GenericForSequenceClassification, Qwen2MoePreTrainedModel): ...
1172
+
1173
+
1174
+ class Qwen2MoeForTokenClassification(GenericForTokenClassification, Qwen2MoePreTrainedModel): ...
1175
+
1176
+
1177
+ class Qwen2MoeForQuestionAnswering(GenericForQuestionAnswering, Qwen2MoePreTrainedModel): ...
1178
+
1179
+
1180
+ __all__ = [
1181
+ "Qwen2MoeForCausalLM",
1182
+ "Qwen2MoeForQuestionAnswering",
1183
+ "Qwen2MoeModel",
1184
+ "Qwen2MoePreTrainedModel",
1185
+ "Qwen2MoeForSequenceClassification",
1186
+ "Qwen2MoeForTokenClassification",
1187
+ ]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_vl/__init__.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_qwen2_vl import *
22
+ from .image_processing_qwen2_vl import *
23
+ from .image_processing_qwen2_vl_fast import *
24
+ from .modeling_qwen2_vl import *
25
+ from .processing_qwen2_vl import *
26
+ else:
27
+ import sys
28
+
29
+ _file = globals()["__file__"]
30
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_vl/configuration_qwen2_vl.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Qwen2VL model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig, layer_type_validation
18
+ from ...modeling_rope_utils import rope_config_validation
19
+ from ...utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class Qwen2VLVisionConfig(PretrainedConfig):
26
+ model_type = "qwen2_vl"
27
+ base_config_key = "vision_config"
28
+
29
+ def __init__(
30
+ self,
31
+ depth=32,
32
+ embed_dim=1280,
33
+ hidden_size=3584,
34
+ hidden_act="quick_gelu",
35
+ mlp_ratio=4,
36
+ num_heads=16,
37
+ in_channels=3,
38
+ patch_size=14,
39
+ spatial_merge_size=2,
40
+ temporal_patch_size=2,
41
+ initializer_range=0.02,
42
+ **kwargs,
43
+ ):
44
+ super().__init__(**kwargs)
45
+
46
+ self.depth = depth
47
+ self.embed_dim = embed_dim
48
+ self.hidden_size = hidden_size
49
+ self.hidden_act = hidden_act
50
+ self.mlp_ratio = mlp_ratio
51
+ self.num_heads = num_heads
52
+ self.in_channels = in_channels
53
+ self.patch_size = patch_size
54
+ self.spatial_merge_size = spatial_merge_size
55
+ self.temporal_patch_size = temporal_patch_size
56
+ self.initializer_range = initializer_range
57
+
58
+
59
+ class Qwen2VLTextConfig(PretrainedConfig):
60
+ r"""
61
+ This is the configuration class to store the configuration of a [`Qwen2VLTextModel`]. It is used to instantiate a
62
+ Qwen2-VL model according to the specified arguments, defining the model architecture. Instantiating a configuration
63
+ with the defaults will yield a similar configuration to that of
64
+ Qwen2-VL-7B-Instruct [Qwen/Qwen2-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2-VL-7B-Instruct).
65
+
66
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
67
+ documentation from [`PretrainedConfig`] for more information.
68
+
69
+ Args:
70
+ vocab_size (`int`, *optional*, defaults to 152064):
71
+ Vocabulary size of the Qwen2VL model. Defines the number of different tokens that can be represented by the
72
+ `inputs_ids` passed when calling [`Qwen2VLModel`]
73
+ hidden_size (`int`, *optional*, defaults to 8192):
74
+ Dimension of the hidden representations.
75
+ intermediate_size (`int`, *optional*, defaults to 29568):
76
+ Dimension of the MLP representations.
77
+ num_hidden_layers (`int`, *optional*, defaults to 80):
78
+ Number of hidden layers in the Transformer encoder.
79
+ num_attention_heads (`int`, *optional*, defaults to 64):
80
+ Number of attention heads for each attention layer in the Transformer encoder.
81
+ num_key_value_heads (`int`, *optional*, defaults to 8):
82
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
83
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
84
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
85
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
86
+ by meanpooling all the original heads within that group. For more details, check out [this
87
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`.
88
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
89
+ The non-linear activation function (function or string) in the decoder.
90
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
91
+ The maximum sequence length that this model might ever be used with.
92
+ initializer_range (`float`, *optional*, defaults to 0.02):
93
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
94
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
95
+ The epsilon used by the rms normalization layers.
96
+ use_cache (`bool`, *optional*, defaults to `True`):
97
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
98
+ relevant if `config.is_decoder=True`.
99
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
100
+ Whether the model's input and output word embeddings should be tied.
101
+ rope_theta (`float`, *optional*, defaults to 1000000.0):
102
+ The base period of the RoPE embeddings.
103
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
104
+ Whether to use sliding window attention.
105
+ sliding_window (`int`, *optional*, defaults to 4096):
106
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
107
+ max_window_layers (`int`, *optional*, defaults to 80):
108
+ The number of layers using full attention. The first `max_window_layers` layers will use full attention, while any
109
+ additional layer afterwards will use SWA (Sliding Window Attention).
110
+ layer_types (`list`, *optional*):
111
+ Attention pattern for each layer.
112
+ attention_dropout (`float`, *optional*, defaults to 0.0):
113
+ The dropout ratio for the attention probabilities.
114
+ rope_scaling (`Dict`, *optional*):
115
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
116
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
117
+ accordingly.
118
+ Expected contents:
119
+ `rope_type` (`str`):
120
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
121
+ 'llama3'], with 'default' being the original RoPE implementation.
122
+ `factor` (`float`, *optional*):
123
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
124
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
125
+ original maximum pre-trained length.
126
+ `original_max_position_embeddings` (`int`, *optional*):
127
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
128
+ pretraining.
129
+ `attention_factor` (`float`, *optional*):
130
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
131
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
132
+ `factor` field to infer the suggested value.
133
+ `beta_fast` (`float`, *optional*):
134
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
135
+ ramp function. If unspecified, it defaults to 32.
136
+ `beta_slow` (`float`, *optional*):
137
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
138
+ ramp function. If unspecified, it defaults to 1.
139
+ `short_factor` (`list[float]`, *optional*):
140
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
141
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
142
+ size divided by the number of attention heads divided by 2
143
+ `long_factor` (`list[float]`, *optional*):
144
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
145
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
146
+ size divided by the number of attention heads divided by 2
147
+ `low_freq_factor` (`float`, *optional*):
148
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
149
+ `high_freq_factor` (`float`, *optional*):
150
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
151
+ image_token_id (`int`, *optional*):
152
+ Token index used as placeholder for image embeddings.
153
+ video_token_id (`int`, *optional*):
154
+ Token index used as placeholder for video embeddings.
155
+
156
+ ```python
157
+ >>> from transformers import Qwen2VLTextModel, Qwen2VLConfig
158
+
159
+ >>> # Initializing a Qwen2VL style configuration
160
+ >>> configuration = Qwen2VLConfig()
161
+
162
+ >>> # Initializing a model from the Qwen2-VL-7B style configuration
163
+ >>> model = Qwen2VLTextModel(configuration)
164
+
165
+ >>> # Accessing the model configuration
166
+ >>> configuration = model.config
167
+ ```"""
168
+
169
+ model_type = "qwen2_vl_text"
170
+ base_config_key = "text_config"
171
+ keys_to_ignore_at_inference = ["past_key_values"]
172
+ # Default tensor parallel plan for base model `Qwen2VL`
173
+ base_model_tp_plan = {
174
+ "layers.*.self_attn.q_proj": "colwise",
175
+ "layers.*.self_attn.k_proj": "colwise",
176
+ "layers.*.self_attn.v_proj": "colwise",
177
+ "layers.*.self_attn.o_proj": "rowwise",
178
+ "layers.*.mlp.gate_proj": "colwise",
179
+ "layers.*.mlp.up_proj": "colwise",
180
+ "layers.*.mlp.down_proj": "rowwise",
181
+ }
182
+ base_model_pp_plan = {
183
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
184
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
185
+ "norm": (["hidden_states"], ["hidden_states"]),
186
+ }
187
+
188
+ def __init__(
189
+ self,
190
+ vocab_size=152064,
191
+ hidden_size=8192,
192
+ intermediate_size=29568,
193
+ num_hidden_layers=80,
194
+ num_attention_heads=64,
195
+ num_key_value_heads=8,
196
+ hidden_act="silu",
197
+ max_position_embeddings=32768,
198
+ initializer_range=0.02,
199
+ rms_norm_eps=1e-05,
200
+ use_cache=True,
201
+ tie_word_embeddings=False,
202
+ rope_theta=1000000.0,
203
+ use_sliding_window=False,
204
+ sliding_window=4096,
205
+ max_window_layers=80,
206
+ layer_types=None,
207
+ attention_dropout=0.0,
208
+ rope_scaling=None,
209
+ image_token_id=None,
210
+ video_token_id=None,
211
+ **kwargs,
212
+ ):
213
+ self.vocab_size = vocab_size
214
+ self.max_position_embeddings = max_position_embeddings
215
+ self.hidden_size = hidden_size
216
+ self.intermediate_size = intermediate_size
217
+ self.num_hidden_layers = num_hidden_layers
218
+ self.num_attention_heads = num_attention_heads
219
+ self.use_sliding_window = use_sliding_window
220
+ self.sliding_window = sliding_window if self.use_sliding_window else None
221
+ self.max_window_layers = max_window_layers
222
+
223
+ # for backward compatibility
224
+ if num_key_value_heads is None:
225
+ num_key_value_heads = num_attention_heads
226
+
227
+ self.num_key_value_heads = num_key_value_heads
228
+ self.hidden_act = hidden_act
229
+ self.initializer_range = initializer_range
230
+ self.rms_norm_eps = rms_norm_eps
231
+ self.use_cache = use_cache
232
+ self.rope_theta = rope_theta
233
+ self.attention_dropout = attention_dropout
234
+ self.rope_scaling = rope_scaling
235
+
236
+ self.layer_types = layer_types
237
+ if self.layer_types is None:
238
+ self.layer_types = [
239
+ "sliding_attention"
240
+ if self.sliding_window is not None and i >= self.max_window_layers
241
+ else "full_attention"
242
+ for i in range(self.num_hidden_layers)
243
+ ]
244
+ layer_type_validation(self.layer_types)
245
+
246
+ # Validate the correctness of rotary position embeddings parameters
247
+ # BC: if there is a 'type' field, move it to 'rope_type'.
248
+ # and change type from 'mrope' to 'default' because `mrope` does default RoPE calculations
249
+ # one can set it to "linear"/"dynamic" etc. to have scaled RoPE
250
+ # TODO: @raushan update config in the hub
251
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
252
+ if self.rope_scaling["type"] == "mrope":
253
+ self.rope_scaling["type"] = "default"
254
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
255
+ rope_config_validation(self, ignore_keys={"mrope_section"})
256
+ self.image_token_id = image_token_id
257
+ self.video_token_id = video_token_id
258
+
259
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
260
+
261
+
262
+ class Qwen2VLConfig(PretrainedConfig):
263
+ r"""
264
+ This is the configuration class to store the configuration of a [`Qwen2VLModel`]. It is used to instantiate a
265
+ Qwen2-VL model according to the specified arguments, defining the model architecture. Instantiating a configuration
266
+ with the defaults will yield a similar configuration to that of
267
+ Qwen2-VL-7B-Instruct [Qwen/Qwen2-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2-VL-7B-Instruct).
268
+
269
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
270
+ documentation from [`PretrainedConfig`] for more information.
271
+
272
+
273
+ Args:
274
+ text_config (`Union[PreTrainedConfig, dict]`, *optional*, defaults to `Qwen2_5_VLTextConfig`):
275
+ The config object or dictionary of the text backbone.
276
+ vision_config (`Union[PreTrainedConfig, dict]`, *optional*, defaults to `Qwen2_5_VLVisionConfig`):
277
+ The config object or dictionary of the vision backbone.
278
+ image_token_id (`int`, *optional*, defaults to 151655):
279
+ The image token index to encode the image prompt.
280
+ video_token_id (`int`, *optional*, defaults to 151656):
281
+ The video token index to encode the image prompt.
282
+
283
+ ```python
284
+ >>> from transformers import Qwen2_5_VLForConditionalGeneration, Qwen2_5_VLConfig
285
+
286
+ >>> # Initializing a Qwen2_5_VL style configuration
287
+ >>> configuration = Qwen2_5_VLConfig()
288
+
289
+ >>> # Initializing a model from the Qwen2-VL-7B style configuration
290
+ >>> model = Qwen2_5_VLForConditionalGeneration(configuration)
291
+
292
+ >>> # Accessing the model configuration
293
+ >>> configuration = model.config
294
+ ```"""
295
+
296
+ model_type = "qwen2_vl"
297
+ sub_configs = {"vision_config": Qwen2VLVisionConfig, "text_config": Qwen2VLTextConfig}
298
+ keys_to_ignore_at_inference = ["past_key_values"]
299
+
300
+ def __init__(
301
+ self,
302
+ text_config=None,
303
+ vision_config=None,
304
+ image_token_id=151655,
305
+ video_token_id=151656,
306
+ **kwargs,
307
+ ):
308
+ if isinstance(vision_config, dict):
309
+ self.vision_config = self.sub_configs["vision_config"](**vision_config)
310
+ elif vision_config is None:
311
+ self.vision_config = self.sub_configs["vision_config"]()
312
+
313
+ if isinstance(text_config, dict):
314
+ self.text_config = self.sub_configs["text_config"](**text_config)
315
+ elif text_config is None:
316
+ # For BC use all kwargs to init `TextConfig`
317
+ self.text_config = self.sub_configs["text_config"](**kwargs)
318
+
319
+ self.image_token_id = image_token_id
320
+ self.video_token_id = video_token_id
321
+
322
+ super().__init__(**kwargs)
323
+
324
+
325
+ __all__ = ["Qwen2VLConfig", "Qwen2VLTextConfig"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_vl/image_processing_qwen2_vl.py ADDED
@@ -0,0 +1,518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
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
+ """Image processor class for Qwen2-VL."""
21
+
22
+ import math
23
+ from typing import Optional, Union
24
+
25
+ import numpy as np
26
+
27
+ from ...image_processing_utils import BaseImageProcessor, BatchFeature
28
+ from ...image_transforms import (
29
+ convert_to_rgb,
30
+ resize,
31
+ to_channel_dimension_format,
32
+ )
33
+ from ...image_utils import (
34
+ OPENAI_CLIP_MEAN,
35
+ OPENAI_CLIP_STD,
36
+ ChannelDimension,
37
+ ImageInput,
38
+ PILImageResampling,
39
+ get_image_size,
40
+ infer_channel_dimension_format,
41
+ is_scaled_image,
42
+ make_flat_list_of_images,
43
+ make_list_of_images,
44
+ to_numpy_array,
45
+ valid_images,
46
+ validate_preprocess_arguments,
47
+ )
48
+ from ...utils import TensorType, logging
49
+ from ...video_utils import VideoInput, make_batched_videos
50
+
51
+
52
+ logger = logging.get_logger(__name__)
53
+
54
+
55
+ def smart_resize(
56
+ height: int, width: int, factor: int = 28, min_pixels: int = 56 * 56, max_pixels: int = 14 * 14 * 4 * 1280
57
+ ):
58
+ """Rescales the image so that the following conditions are met:
59
+
60
+ 1. Both dimensions (height and width) are divisible by 'factor'.
61
+
62
+ 2. The total number of pixels is within the range ['min_pixels', 'max_pixels'].
63
+
64
+ 3. The aspect ratio of the image is maintained as closely as possible.
65
+
66
+ """
67
+ if max(height, width) / min(height, width) > 200:
68
+ raise ValueError(
69
+ f"absolute aspect ratio must be smaller than 200, got {max(height, width) / min(height, width)}"
70
+ )
71
+ h_bar = round(height / factor) * factor
72
+ w_bar = round(width / factor) * factor
73
+ if h_bar * w_bar > max_pixels:
74
+ beta = math.sqrt((height * width) / max_pixels)
75
+ h_bar = max(factor, math.floor(height / beta / factor) * factor)
76
+ w_bar = max(factor, math.floor(width / beta / factor) * factor)
77
+ elif h_bar * w_bar < min_pixels:
78
+ beta = math.sqrt(min_pixels / (height * width))
79
+ h_bar = math.ceil(height * beta / factor) * factor
80
+ w_bar = math.ceil(width * beta / factor) * factor
81
+ return h_bar, w_bar
82
+
83
+
84
+ class Qwen2VLImageProcessor(BaseImageProcessor):
85
+ r"""
86
+ Constructs a Qwen2-VL image processor that dynamically resizes images based on the original images.
87
+
88
+ Args:
89
+ do_resize (`bool`, *optional*, defaults to `True`):
90
+ Whether to resize the image's (height, width) dimensions.
91
+ size (`dict[str, int]`, *optional*, defaults to `{"shortest_edge": 56 * 56, "longest_edge": 28 * 28 * 1280}`):
92
+ Size of the image after resizing. `shortest_edge` and `longest_edge` keys must be present.
93
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
94
+ Resampling filter to use when resizing the image.
95
+ do_rescale (`bool`, *optional*, defaults to `True`):
96
+ Whether to rescale the image by the specified scale `rescale_factor`.
97
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
98
+ Scale factor to use if rescaling the image.
99
+ do_normalize (`bool`, *optional*, defaults to `True`):
100
+ Whether to normalize the image.
101
+ image_mean (`float` or `list[float]`, *optional*, defaults to `[0.48145466, 0.4578275, 0.40821073]`):
102
+ Mean to use if normalizing the image. This is a float or list of floats for each channel in the image.
103
+ image_std (`float` or `list[float]`, *optional*, defaults to `[0.26862954, 0.26130258, 0.27577711]`):
104
+ Standard deviation to use if normalizing the image. This is a float or list of floats for each channel in the image.
105
+ do_convert_rgb (`bool`, *optional*, defaults to `True`):
106
+ Whether to convert the image to RGB.
107
+ min_pixels (`int`, *optional*, defaults to `56 * 56`):
108
+ The min pixels of the image to resize the image.
109
+ max_pixels (`int`, *optional*, defaults to `28 * 28 * 1280`):
110
+ The max pixels of the image to resize the image.
111
+ patch_size (`int`, *optional*, defaults to 14):
112
+ The spatial patch size of the vision encoder.
113
+ temporal_patch_size (`int`, *optional*, defaults to 2):
114
+ The temporal patch size of the vision encoder.
115
+ merge_size (`int`, *optional*, defaults to 2):
116
+ The merge size of the vision encoder to llm encoder.
117
+ """
118
+
119
+ model_input_names = ["pixel_values", "image_grid_thw", "pixel_values_videos", "video_grid_thw"]
120
+
121
+ def __init__(
122
+ self,
123
+ do_resize: bool = True,
124
+ size: Optional[dict[str, int]] = None,
125
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
126
+ do_rescale: bool = True,
127
+ rescale_factor: Union[int, float] = 1 / 255,
128
+ do_normalize: bool = True,
129
+ image_mean: Optional[Union[float, list[float]]] = None,
130
+ image_std: Optional[Union[float, list[float]]] = None,
131
+ do_convert_rgb: bool = True,
132
+ min_pixels: Optional[int] = None,
133
+ max_pixels: Optional[int] = None,
134
+ patch_size: int = 14,
135
+ temporal_patch_size: int = 2,
136
+ merge_size: int = 2,
137
+ **kwargs,
138
+ ) -> None:
139
+ super().__init__(**kwargs)
140
+ if size is not None and ("shortest_edge" not in size or "longest_edge" not in size):
141
+ raise ValueError("size must contain 'shortest_edge' and 'longest_edge' keys.")
142
+ else:
143
+ size = {"shortest_edge": 56 * 56, "longest_edge": 28 * 28 * 1280}
144
+ # backward compatibility: override size with min_pixels and max_pixels if they are provided
145
+ if min_pixels is not None:
146
+ size["shortest_edge"] = min_pixels
147
+ if max_pixels is not None:
148
+ size["longest_edge"] = max_pixels
149
+ self.min_pixels = size["shortest_edge"]
150
+ self.max_pixels = size["longest_edge"]
151
+ self.size = size
152
+
153
+ self.do_resize = do_resize
154
+ self.resample = resample
155
+ self.do_rescale = do_rescale
156
+ self.rescale_factor = rescale_factor
157
+ self.do_normalize = do_normalize
158
+ self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
159
+ self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
160
+
161
+ self.patch_size = patch_size
162
+ self.temporal_patch_size = temporal_patch_size
163
+ self.merge_size = merge_size
164
+ self.do_convert_rgb = do_convert_rgb
165
+
166
+ def _preprocess(
167
+ self,
168
+ images: Union[ImageInput, VideoInput],
169
+ do_resize: Optional[bool] = None,
170
+ size: Optional[dict[str, int]] = None,
171
+ resample: PILImageResampling = None,
172
+ do_rescale: Optional[bool] = None,
173
+ rescale_factor: Optional[float] = None,
174
+ do_normalize: Optional[bool] = None,
175
+ image_mean: Optional[Union[float, list[float]]] = None,
176
+ image_std: Optional[Union[float, list[float]]] = None,
177
+ patch_size: Optional[int] = None,
178
+ temporal_patch_size: Optional[int] = None,
179
+ merge_size: Optional[int] = None,
180
+ do_convert_rgb: Optional[bool] = None,
181
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
182
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
183
+ ):
184
+ """
185
+ Preprocess an image or batch of images. Copy of the `preprocess` method from `CLIPImageProcessor`.
186
+
187
+ Args:
188
+ images (`ImageInput`):
189
+ Image or batch of images to preprocess. Expects pixel values ranging from 0 to 255. If pixel values range from 0 to 1, set `do_rescale=False`.
190
+ vision_info (`list[Dict]`, *optional*):
191
+ Optional list of dictionaries containing additional information about vision inputs.
192
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
193
+ Whether to resize the image.
194
+ size (`dict[str, int]`, *optional*, defaults to `self.size`):
195
+ Size of the image after resizing. `shortest_edge` and `longest_edge` keys must be present.
196
+ resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
197
+ Resampling filter to use if resizing the image. This can be one of the `PILImageResampling` enums.
198
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
199
+ Whether to rescale the image.
200
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
201
+ Scale factor to use if rescaling the image.
202
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
203
+ Whether to normalize the image.
204
+ image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
205
+ Mean to use if normalizing the image. Can be a float or a list of floats corresponding to the number of channels in the image.
206
+ image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
207
+ Standard deviation to use if normalizing the image. Can be a float or a list of floats corresponding to the number of channels in the image.
208
+ patch_size (`int`, *optional*, defaults to `self.patch_size`):
209
+ The spatial patch size of the vision encoder.
210
+ temporal_patch_size (`int`, *optional*, defaults to `self.temporal_patch_size`):
211
+ The temporal patch size of the vision encoder.
212
+ merge_size (`int`, *optional*, defaults to `self.merge_size`):
213
+ The merge size of the vision encoder to llm encoder.
214
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
215
+ Whether to convert the image to RGB.
216
+ data_format (`ChannelDimension`, *optional*, defaults to `ChannelDimension.FIRST`):
217
+ The channel dimension format for the output image. Can be one of:
218
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
219
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
220
+ - Unset: Use the channel dimension format of the input image.
221
+ input_data_format (`ChannelDimension` or `str`, *optional*):
222
+ The channel dimension format for the input image. Can be one of:
223
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
224
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
225
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
226
+ """
227
+ images = make_list_of_images(images)
228
+
229
+ if do_convert_rgb:
230
+ images = [convert_to_rgb(image) for image in images]
231
+
232
+ # All transformations expect numpy arrays.
233
+ images = [to_numpy_array(image) for image in images]
234
+
235
+ if do_rescale and is_scaled_image(images[0]):
236
+ logger.warning_once(
237
+ "It looks like you are trying to rescale already rescaled images. If the input"
238
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
239
+ )
240
+ if input_data_format is None:
241
+ # We assume that all images have the same channel dimension format.
242
+ input_data_format = infer_channel_dimension_format(images[0])
243
+
244
+ height, width = get_image_size(images[0], channel_dim=input_data_format)
245
+ resized_height, resized_width = height, width
246
+ processed_images = []
247
+ for image in images:
248
+ if do_resize:
249
+ resized_height, resized_width = smart_resize(
250
+ height,
251
+ width,
252
+ factor=patch_size * merge_size,
253
+ min_pixels=size["shortest_edge"],
254
+ max_pixels=size["longest_edge"],
255
+ )
256
+ image = resize(
257
+ image, size=(resized_height, resized_width), resample=resample, input_data_format=input_data_format
258
+ )
259
+
260
+ if do_rescale:
261
+ image = self.rescale(image, scale=rescale_factor, input_data_format=input_data_format)
262
+
263
+ if do_normalize:
264
+ image = self.normalize(
265
+ image=image, mean=image_mean, std=image_std, input_data_format=input_data_format
266
+ )
267
+
268
+ image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
269
+ processed_images.append(image)
270
+
271
+ patches = np.array(processed_images)
272
+ if data_format == ChannelDimension.LAST:
273
+ patches = patches.transpose(0, 3, 1, 2)
274
+ if patches.shape[0] % temporal_patch_size != 0:
275
+ repeats = np.repeat(
276
+ patches[-1][np.newaxis], temporal_patch_size - (patches.shape[0] % temporal_patch_size), axis=0
277
+ )
278
+ patches = np.concatenate([patches, repeats], axis=0)
279
+ channel = patches.shape[1]
280
+ grid_t = patches.shape[0] // temporal_patch_size
281
+ grid_h, grid_w = resized_height // patch_size, resized_width // patch_size
282
+ patches = patches.reshape(
283
+ grid_t,
284
+ temporal_patch_size,
285
+ channel,
286
+ grid_h // merge_size,
287
+ merge_size,
288
+ patch_size,
289
+ grid_w // merge_size,
290
+ merge_size,
291
+ patch_size,
292
+ )
293
+ patches = patches.transpose(0, 3, 6, 4, 7, 2, 1, 5, 8)
294
+ flatten_patches = patches.reshape(
295
+ grid_t * grid_h * grid_w, channel * temporal_patch_size * patch_size * patch_size
296
+ )
297
+
298
+ return flatten_patches, (grid_t, grid_h, grid_w)
299
+
300
+ def preprocess(
301
+ self,
302
+ images: ImageInput,
303
+ videos: VideoInput = None,
304
+ do_resize: Optional[bool] = None,
305
+ size: Optional[dict[str, int]] = None,
306
+ min_pixels: Optional[int] = None,
307
+ max_pixels: Optional[int] = None,
308
+ resample: PILImageResampling = None,
309
+ do_rescale: Optional[bool] = None,
310
+ rescale_factor: Optional[float] = None,
311
+ do_normalize: Optional[bool] = None,
312
+ image_mean: Optional[Union[float, list[float]]] = None,
313
+ image_std: Optional[Union[float, list[float]]] = None,
314
+ patch_size: Optional[int] = None,
315
+ temporal_patch_size: Optional[int] = None,
316
+ merge_size: Optional[int] = None,
317
+ do_convert_rgb: Optional[bool] = None,
318
+ return_tensors: Optional[Union[str, TensorType]] = None,
319
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
320
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
321
+ ):
322
+ """
323
+ Args:
324
+ images (`ImageInput`):
325
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
326
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
327
+ videos (`VideoInput`):
328
+ Video to preprocess. Expects a single or batch of videos with pixel values ranging from 0 to 255. If
329
+ passing in videos with pixel values between 0 and 1, set `do_rescale=False`.
330
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
331
+ Whether to resize the image.
332
+ size (`dict[str, int]`, *optional*, defaults to `self.size`):
333
+ Size of the image after resizing. Shortest edge of the image is resized to size["shortest_edge"], with
334
+ the longest edge resized to keep the input aspect ratio.
335
+ resample (`int`, *optional*, defaults to `self.resample`):
336
+ Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
337
+ has an effect if `do_resize` is set to `True`.
338
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
339
+ Whether to rescale the image.
340
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
341
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
342
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
343
+ Whether to normalize the image.
344
+ image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
345
+ Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
346
+ image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
347
+ Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
348
+ `True`.
349
+ min_pixels (`int`, *optional*, defaults to `self.min_pixels`):
350
+ The min pixels of the image to resize the image.
351
+ max_pixels (`int`, *optional*, defaults to `self.max_pixels`):
352
+ The max pixels of the image to resize the image.
353
+ patch_size (`int`, *optional*, defaults to `self.patch_size`):
354
+ The spatial patch size of the vision encoder.
355
+ temporal_patch_size (`int`, *optional*, defaults to `self.temporal_patch_size`):
356
+ The temporal patch size of the vision encoder.
357
+ merge_size (`int`, *optional*, defaults to `self.merge_size`):
358
+ The merge size of the vision encoder to llm encoder.
359
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
360
+ Whether to convert the image to RGB.
361
+ return_tensors (`str` or `TensorType`, *optional*):
362
+ The type of tensors to return. Can be one of:
363
+ - Unset: Return a list of `np.ndarray`.
364
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
365
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
366
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
367
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
368
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
369
+ The channel dimension format for the output image. Can be one of:
370
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
371
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
372
+ - Unset: Use the channel dimension format of the input image.
373
+ input_data_format (`ChannelDimension` or `str`, *optional*):
374
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
375
+ from the input image. Can be one of:
376
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
377
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
378
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
379
+
380
+ """
381
+ min_pixels = min_pixels if min_pixels is not None else self.min_pixels
382
+ max_pixels = max_pixels if max_pixels is not None else self.max_pixels
383
+
384
+ if size is not None:
385
+ if "shortest_edge" not in size or "longest_edge" not in size:
386
+ raise ValueError("size must contain 'shortest_edge' and 'longest_edge' keys.")
387
+ min_pixels = size["shortest_edge"]
388
+ elif min_pixels is not None and max_pixels is not None:
389
+ # backward compatibility: override size with min_pixels and max_pixels if they are provided
390
+ size = {"shortest_edge": min_pixels, "longest_edge": max_pixels}
391
+ else:
392
+ size = {**self.size}
393
+
394
+ do_resize = do_resize if do_resize is not None else self.do_resize
395
+
396
+ resample = resample if resample is not None else self.resample
397
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
398
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
399
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
400
+ image_mean = image_mean if image_mean is not None else self.image_mean
401
+ image_std = image_std if image_std is not None else self.image_std
402
+ patch_size = patch_size if patch_size is not None else self.patch_size
403
+ temporal_patch_size = temporal_patch_size if temporal_patch_size is not None else self.temporal_patch_size
404
+ merge_size = merge_size if merge_size is not None else self.merge_size
405
+ do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
406
+
407
+ if images is not None:
408
+ images = make_flat_list_of_images(images)
409
+
410
+ if images is not None and not valid_images(images):
411
+ raise ValueError(
412
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
413
+ "torch.Tensor, tf.Tensor or jax.ndarray."
414
+ )
415
+
416
+ validate_preprocess_arguments(
417
+ rescale_factor=rescale_factor,
418
+ do_normalize=do_normalize,
419
+ image_mean=image_mean,
420
+ image_std=image_std,
421
+ do_resize=do_resize,
422
+ size=size,
423
+ resample=resample,
424
+ )
425
+
426
+ data = {}
427
+ if images is not None:
428
+ pixel_values, vision_grid_thws = [], []
429
+ for image in images:
430
+ patches, image_grid_thw = self._preprocess(
431
+ image,
432
+ do_resize=do_resize,
433
+ size=size,
434
+ resample=resample,
435
+ do_rescale=do_rescale,
436
+ rescale_factor=rescale_factor,
437
+ do_normalize=do_normalize,
438
+ image_mean=image_mean,
439
+ image_std=image_std,
440
+ patch_size=patch_size,
441
+ temporal_patch_size=temporal_patch_size,
442
+ merge_size=merge_size,
443
+ data_format=data_format,
444
+ do_convert_rgb=do_convert_rgb,
445
+ input_data_format=input_data_format,
446
+ )
447
+ pixel_values.extend(patches)
448
+ vision_grid_thws.append(image_grid_thw)
449
+ pixel_values = np.array(pixel_values)
450
+ vision_grid_thws = np.array(vision_grid_thws)
451
+ data.update({"pixel_values": pixel_values, "image_grid_thw": vision_grid_thws})
452
+
453
+ # kept for BC only and should be removed after v5.0
454
+ if videos is not None:
455
+ logger.warning(
456
+ "`Qwen2VLImageProcessor` works only with image inputs and doesn't process videos anymore. "
457
+ "This is a deprecated behavior and will be removed in v5.0. "
458
+ "Your videos should be forwarded to `Qwen2VLVideoProcessor`. "
459
+ )
460
+ videos = make_batched_videos(videos)
461
+ pixel_values_videos, vision_grid_thws_videos = [], []
462
+ for images in videos:
463
+ patches, video_grid_thw = self._preprocess(
464
+ images,
465
+ do_resize=do_resize,
466
+ size=size,
467
+ resample=resample,
468
+ do_rescale=do_rescale,
469
+ rescale_factor=rescale_factor,
470
+ do_normalize=do_normalize,
471
+ image_mean=image_mean,
472
+ image_std=image_std,
473
+ patch_size=patch_size,
474
+ temporal_patch_size=temporal_patch_size,
475
+ merge_size=merge_size,
476
+ data_format=data_format,
477
+ do_convert_rgb=do_convert_rgb,
478
+ input_data_format=input_data_format,
479
+ )
480
+ pixel_values_videos.extend(patches)
481
+ vision_grid_thws_videos.append(video_grid_thw)
482
+ data.update(
483
+ {
484
+ "pixel_values_videos": np.array(pixel_values_videos),
485
+ "video_grid_thw": np.array(vision_grid_thws_videos),
486
+ }
487
+ )
488
+
489
+ return BatchFeature(data=data, tensor_type=return_tensors)
490
+
491
+ def get_number_of_image_patches(self, height: int, width: int, images_kwargs=None):
492
+ """
493
+ A utility that returns number of image patches for a given image size.
494
+
495
+ Args:
496
+ height (`int`):
497
+ Height of the input image.
498
+ width (`int`):
499
+ Width of the input image.
500
+ images_kwargs (`dict`, *optional*)
501
+ Any kwargs to override defaults of the image processor.
502
+ Returns:
503
+ `int`: Number of image patches per image.
504
+ """
505
+ min_pixels = images_kwargs["min_pixels"] if "min_pixels" in images_kwargs else self.size["shortest_edge"]
506
+ max_pixels = images_kwargs["max_pixels"] if "max_pixels" in images_kwargs else self.size["longest_edge"]
507
+ patch_size = images_kwargs.get("patch_size", self.patch_size)
508
+ merge_size = images_kwargs.get("merge_size", self.merge_size)
509
+
510
+ factor = patch_size * merge_size
511
+ resized_height, resized_width = smart_resize(
512
+ height, width, factor, min_pixels=min_pixels, max_pixels=max_pixels
513
+ )
514
+ grid_h, grid_w = resized_height // patch_size, resized_width // patch_size
515
+ return grid_h * grid_w
516
+
517
+
518
+ __all__ = ["Qwen2VLImageProcessor"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_vl/image_processing_qwen2_vl_fast.py ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
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
+ """Fast Image processor class for Qwen2-VL."""
21
+
22
+ from typing import Optional, Union
23
+
24
+ from ...image_processing_utils import BatchFeature
25
+ from ...image_processing_utils_fast import (
26
+ BaseImageProcessorFast,
27
+ DefaultFastImageProcessorKwargs,
28
+ group_images_by_shape,
29
+ reorder_images,
30
+ )
31
+ from ...image_utils import (
32
+ OPENAI_CLIP_MEAN,
33
+ OPENAI_CLIP_STD,
34
+ ChannelDimension,
35
+ ImageInput,
36
+ PILImageResampling,
37
+ SizeDict,
38
+ )
39
+ from ...processing_utils import Unpack
40
+ from ...utils import (
41
+ TensorType,
42
+ auto_docstring,
43
+ is_torch_available,
44
+ is_torchvision_available,
45
+ is_torchvision_v2_available,
46
+ logging,
47
+ )
48
+ from ...video_utils import VideoInput, make_batched_videos
49
+ from .image_processing_qwen2_vl import smart_resize
50
+
51
+
52
+ if is_torch_available():
53
+ import torch
54
+
55
+
56
+ if is_torchvision_available():
57
+ if is_torchvision_v2_available():
58
+ from torchvision.transforms.v2 import functional as F
59
+ else:
60
+ from torchvision.transforms import functional as F
61
+
62
+ logger = logging.get_logger(__name__)
63
+
64
+
65
+ class Qwen2VLFastImageProcessorKwargs(DefaultFastImageProcessorKwargs):
66
+ """
67
+ min_pixels (`int`, *optional*, defaults to `56 * 56`):
68
+ The min pixels of the image to resize the image.
69
+ max_pixels (`int`, *optional*, defaults to `28 * 28 * 1280`):
70
+ The max pixels of the image to resize the image.
71
+ patch_size (`int`, *optional*, defaults to 14):
72
+ The spatial patch size of the vision encoder.
73
+ temporal_patch_size (`int`, *optional*, defaults to 2):
74
+ The temporal patch size of the vision encoder.
75
+ merge_size (`int`, *optional*, defaults to 2):
76
+ The merge size of the vision encoder to llm encoder.
77
+ """
78
+
79
+ min_pixels: Optional[int]
80
+ max_pixels: Optional[int]
81
+ patch_size: Optional[int]
82
+ temporal_patch_size: Optional[int]
83
+ merge_size: Optional[int]
84
+
85
+
86
+ @auto_docstring
87
+ class Qwen2VLImageProcessorFast(BaseImageProcessorFast):
88
+ do_resize = True
89
+ resample = PILImageResampling.BICUBIC
90
+ size = {"shortest_edge": 56 * 56, "longest_edge": 28 * 28 * 1280}
91
+ do_rescale = True
92
+ do_normalize = True
93
+ image_mean = OPENAI_CLIP_MEAN
94
+ image_std = OPENAI_CLIP_STD
95
+ do_convert_rgb = True
96
+ patch_size = 14
97
+ temporal_patch_size = 2
98
+ merge_size = 2
99
+ min_pixels = None
100
+ max_pixels = None
101
+ valid_kwargs = Qwen2VLFastImageProcessorKwargs
102
+ model_input_names = ["pixel_values", "image_grid_thw", "pixel_values_videos", "video_grid_thw"]
103
+
104
+ def __init__(self, **kwargs: Unpack[Qwen2VLFastImageProcessorKwargs]):
105
+ size = kwargs.pop("size", None)
106
+ min_pixels = kwargs.pop("min_pixels", None)
107
+ max_pixels = kwargs.pop("max_pixels", None)
108
+ # backward compatibility: override size with min_pixels and max_pixels if they are provided
109
+ size = self.size if size is None else size
110
+ if min_pixels is not None:
111
+ size["shortest_edge"] = min_pixels
112
+ size.pop("min_pixels", None)
113
+ if max_pixels is not None:
114
+ size["longest_edge"] = max_pixels
115
+ size.pop("max_pixels", None)
116
+ if "shortest_edge" not in size or "longest_edge" not in size:
117
+ raise ValueError("size must contain 'shortest_edge' and 'longest_edge' keys.")
118
+
119
+ super().__init__(size=size, min_pixels=min_pixels, max_pixels=max_pixels, **kwargs)
120
+
121
+ def _further_process_kwargs(
122
+ self,
123
+ size: Optional[SizeDict] = None,
124
+ min_pixels: Optional[int] = None,
125
+ max_pixels: Optional[int] = None,
126
+ **kwargs,
127
+ ) -> dict:
128
+ """
129
+ Update kwargs that need further processing before being validated
130
+ Can be overridden by subclasses to customize the processing of kwargs.
131
+ """
132
+ if min_pixels is not None and max_pixels is not None:
133
+ size = {"shortest_edge": min_pixels, "longest_edge": max_pixels}
134
+ elif size is not None:
135
+ if "shortest_edge" not in size or "longest_edge" not in size:
136
+ raise ValueError("size must contain 'shortest_edge' and 'longest_edge' keys.")
137
+ min_pixels = size["shortest_edge"]
138
+ max_pixels = size["longest_edge"]
139
+ else:
140
+ size = {**self.size}
141
+
142
+ return super()._further_process_kwargs(size=size, min_pixels=min_pixels, max_pixels=max_pixels, **kwargs)
143
+
144
+ @auto_docstring
145
+ def preprocess(
146
+ self,
147
+ images: ImageInput,
148
+ videos: Optional[VideoInput] = None,
149
+ **kwargs: Unpack[Qwen2VLFastImageProcessorKwargs],
150
+ ) -> BatchFeature:
151
+ return super().preprocess(images, videos, **kwargs)
152
+
153
+ def _preprocess_image_like_inputs(
154
+ self,
155
+ images: ImageInput,
156
+ videos: VideoInput,
157
+ do_convert_rgb: bool,
158
+ input_data_format: ChannelDimension,
159
+ device: Optional[Union[str, "torch.device"]] = None,
160
+ **kwargs: Unpack[DefaultFastImageProcessorKwargs],
161
+ ) -> BatchFeature:
162
+ """
163
+ Preprocess image-like inputs.
164
+ To be overridden by subclasses when image-like inputs other than images should be processed.
165
+ It can be used for segmentation maps, depth maps, etc.
166
+ """
167
+ # Prepare input images
168
+ batch_feature = BatchFeature()
169
+ if images is not None:
170
+ images = self._prepare_image_like_inputs(
171
+ images=images, do_convert_rgb=do_convert_rgb, input_data_format=input_data_format, device=device
172
+ )
173
+ batch_feature = self._preprocess(images, **kwargs)
174
+ if videos is not None:
175
+ logger.warning(
176
+ "`Qwen2VLImageProcessorFast` works only with image inputs and doesn't process videos anymore. "
177
+ "This is a deprecated behavior and will be removed in v5.0. "
178
+ "Your videos should be forwarded to `Qwen2VLVideoProcessor`. "
179
+ )
180
+ # Can't change _prepare_images_structure to work with videos because it also needs to work with images.
181
+ videos = make_batched_videos(videos)
182
+ videos = [
183
+ torch.stack(self._prepare_image_like_inputs(video, do_convert_rgb, input_data_format, device))
184
+ for video in videos
185
+ ]
186
+ video_outputs = self._preprocess(videos, **kwargs)
187
+ batch_feature.update(
188
+ {"pixel_values_videos": video_outputs.pixel_values, "video_grid_thw": video_outputs.image_grid_thw}
189
+ )
190
+ return batch_feature
191
+
192
+ def _preprocess(
193
+ self,
194
+ images: list["torch.Tensor"],
195
+ do_resize: bool,
196
+ size: SizeDict,
197
+ interpolation: Optional["F.InterpolationMode"],
198
+ do_rescale: bool,
199
+ rescale_factor: float,
200
+ do_normalize: bool,
201
+ image_mean: Optional[Union[float, list[float]]],
202
+ image_std: Optional[Union[float, list[float]]],
203
+ patch_size: int,
204
+ temporal_patch_size: int,
205
+ merge_size: int,
206
+ disable_grouping: Optional[bool],
207
+ return_tensors: Optional[Union[str, TensorType]],
208
+ **kwargs,
209
+ ):
210
+ # Group images by size for batched resizing
211
+ grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
212
+ resized_images_grouped = {}
213
+ for shape, stacked_images in grouped_images.items():
214
+ height, width = stacked_images.shape[-2:]
215
+ if do_resize:
216
+ resized_height, resized_width = smart_resize(
217
+ height,
218
+ width,
219
+ factor=patch_size * merge_size,
220
+ min_pixels=size["shortest_edge"],
221
+ max_pixels=size["longest_edge"],
222
+ )
223
+ stacked_images = self.resize(
224
+ image=stacked_images,
225
+ size=SizeDict(height=resized_height, width=resized_width),
226
+ interpolation=interpolation,
227
+ )
228
+ resized_images_grouped[shape] = stacked_images
229
+ resized_images = reorder_images(resized_images_grouped, grouped_images_index)
230
+
231
+ # Group images by size for further processing
232
+ # Needed in case do_resize is False, or resize returns images with different sizes
233
+ grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
234
+ processed_images_grouped = {}
235
+ processed_grids = {}
236
+ for shape, stacked_images in grouped_images.items():
237
+ resized_height, resized_width = stacked_images.shape[-2:]
238
+ # Fused rescale and normalize
239
+ patches = self.rescale_and_normalize(
240
+ stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
241
+ )
242
+ if patches.ndim == 4:
243
+ # add a temporal dimension if we have images
244
+ patches = patches.unsqueeze(1)
245
+ if patches.shape[1] % temporal_patch_size != 0:
246
+ repeats = patches[:, -1:].repeat(1, temporal_patch_size - 1, 1, 1, 1)
247
+ patches = torch.cat([patches, repeats], dim=1)
248
+ batch_size, grid_t, channel = patches.shape[:3]
249
+ grid_t = grid_t // temporal_patch_size
250
+ grid_h, grid_w = resized_height // patch_size, resized_width // patch_size
251
+
252
+ patches = patches.view(
253
+ batch_size,
254
+ grid_t,
255
+ temporal_patch_size,
256
+ channel,
257
+ grid_h // merge_size,
258
+ merge_size,
259
+ patch_size,
260
+ grid_w // merge_size,
261
+ merge_size,
262
+ patch_size,
263
+ )
264
+ # Reorder dimensions to group grid and patch information for subsequent flattening.
265
+ # (batch, grid_t, grid_h, grid_w, merge_h, merge_w, channel, temp_patch_size, patch_h, patch_w)
266
+ patches = patches.permute(0, 1, 4, 7, 5, 8, 3, 2, 6, 9)
267
+ flatten_patches = patches.reshape(
268
+ batch_size,
269
+ grid_t * grid_h * grid_w,
270
+ channel * temporal_patch_size * patch_size * patch_size,
271
+ )
272
+
273
+ processed_images_grouped[shape] = flatten_patches
274
+ processed_grids[shape] = [[grid_t, grid_h, grid_w]] * batch_size
275
+
276
+ processed_images = reorder_images(processed_images_grouped, grouped_images_index)
277
+ processed_grids = reorder_images(processed_grids, grouped_images_index)
278
+ pixel_values = torch.cat(processed_images, dim=0)
279
+ image_grid_thw = torch.tensor(processed_grids)
280
+
281
+ return BatchFeature(
282
+ data={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw}, tensor_type=return_tensors
283
+ )
284
+
285
+ def get_number_of_image_patches(self, height: int, width: int, images_kwargs=None):
286
+ """
287
+ A utility that returns number of image patches for a given image size.
288
+
289
+ Note: Do not remove this method! It is used by vLLM to infer the number of patches and placeholders
290
+ without an image input.
291
+
292
+ Args:
293
+ height (`int`):
294
+ Height of the input image.
295
+ width (`int`):
296
+ Width of the input image.
297
+ images_kwargs (`dict`, *optional*)
298
+ Any kwargs to override defaults of the image processor.
299
+ Returns:
300
+ `int`: Number of image patches per image.
301
+ """
302
+ min_pixels = images_kwargs["min_pixels"] if "min_pixels" in images_kwargs else self.size["shortest_edge"]
303
+ max_pixels = images_kwargs["max_pixels"] if "max_pixels" in images_kwargs else self.size["longest_edge"]
304
+ patch_size = images_kwargs.get("patch_size", self.patch_size)
305
+ merge_size = images_kwargs.get("merge_size", self.merge_size)
306
+
307
+ factor = patch_size * merge_size
308
+ resized_height, resized_width = smart_resize(
309
+ height, width, factor, min_pixels=min_pixels, max_pixels=max_pixels
310
+ )
311
+ grid_h, grid_w = resized_height // patch_size, resized_width // patch_size
312
+ return grid_h * grid_w
313
+
314
+
315
+ __all__ = ["Qwen2VLImageProcessorFast"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_vl/modeling_qwen2_vl.py ADDED
@@ -0,0 +1,1635 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
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
+ """PyTorch Qwen2-VL model."""
21
+
22
+ from dataclasses import dataclass
23
+ from typing import Any, Callable, Optional, Union
24
+
25
+ import torch
26
+ import torch.nn as nn
27
+ import torch.nn.functional as F
28
+ import torch.utils.checkpoint
29
+ from torch.nn import LayerNorm
30
+
31
+ from ...activations import ACT2FN
32
+ from ...cache_utils import Cache, DynamicCache
33
+ from ...generation import GenerationMixin
34
+ from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask
35
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
36
+ from ...modeling_layers import GradientCheckpointingLayer
37
+ from ...modeling_outputs import BaseModelOutputWithPast, ModelOutput
38
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
39
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
40
+ from ...processing_utils import Unpack
41
+ from ...utils import (
42
+ TransformersKwargs,
43
+ auto_docstring,
44
+ can_return_tuple,
45
+ is_torchdynamo_compiling,
46
+ logging,
47
+ )
48
+ from ...utils.deprecation import deprecate_kwarg
49
+ from .configuration_qwen2_vl import Qwen2VLConfig, Qwen2VLTextConfig, Qwen2VLVisionConfig
50
+
51
+
52
+ logger = logging.get_logger(__name__)
53
+
54
+
55
+ @dataclass
56
+ @auto_docstring(
57
+ custom_intro="""
58
+ Base class for Llava outputs, with hidden states and attentions.
59
+ """
60
+ )
61
+ class Qwen2VLModelOutputWithPast(ModelOutput):
62
+ r"""
63
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
64
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
65
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
66
+
67
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
68
+ `past_key_values` input) to speed up sequential decoding.
69
+ rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
70
+ The rope index difference between sequence length and multimodal rope.
71
+ """
72
+
73
+ last_hidden_state: torch.FloatTensor = None
74
+ past_key_values: Optional[list[torch.FloatTensor]] = None
75
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
76
+ attentions: Optional[tuple[torch.FloatTensor]] = None
77
+ rope_deltas: Optional[torch.LongTensor] = None
78
+
79
+
80
+ @dataclass
81
+ @auto_docstring(
82
+ custom_intro="""
83
+ Base class for Qwen2VL causal language model (or autoregressive) outputs.
84
+ """
85
+ )
86
+ class Qwen2VLCausalLMOutputWithPast(ModelOutput):
87
+ r"""
88
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
89
+ Language modeling loss (for next-token prediction).
90
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
91
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
92
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
93
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
94
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
95
+
96
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
97
+ `past_key_values` input) to speed up sequential decoding.
98
+ rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
99
+ The rope index difference between sequence length and multimodal rope.
100
+ """
101
+
102
+ loss: Optional[torch.FloatTensor] = None
103
+ logits: Optional[torch.FloatTensor] = None
104
+ past_key_values: Optional[list[torch.FloatTensor]] = None
105
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
106
+ attentions: Optional[tuple[torch.FloatTensor]] = None
107
+ rope_deltas: Optional[torch.LongTensor] = None
108
+
109
+
110
+ class Qwen2VLRotaryEmbedding(nn.Module):
111
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
112
+
113
+ def __init__(self, config: Qwen2VLTextConfig, device=None):
114
+ super().__init__()
115
+ # BC: "rope_type" was originally "type"
116
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
117
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
118
+ else:
119
+ self.rope_type = "default"
120
+ self.max_seq_len_cached = config.max_position_embeddings
121
+ self.original_max_seq_len = config.max_position_embeddings
122
+
123
+ self.config = config
124
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
125
+
126
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
127
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
128
+ self.original_inv_freq = self.inv_freq
129
+
130
+ @torch.no_grad()
131
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
132
+ def forward(self, x, position_ids):
133
+ # In contrast to other models, Qwen2_VL has different position ids for the grids
134
+ # So we expand the inv_freq to shape (3, ...)
135
+ inv_freq_expanded = self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1)
136
+ position_ids_expanded = position_ids[:, :, None, :].float() # shape (3, bs, 1, positions)
137
+
138
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
139
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
140
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3)
141
+ emb = torch.cat((freqs, freqs), dim=-1)
142
+ cos = emb.cos() * self.attention_scaling
143
+ sin = emb.sin() * self.attention_scaling
144
+
145
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
146
+
147
+
148
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
149
+ def rotate_half(x):
150
+ """Rotates half the hidden dims of the input."""
151
+ x1 = x[..., : x.shape[-1] // 2]
152
+ x2 = x[..., x.shape[-1] // 2 :]
153
+ return torch.cat((-x2, x1), dim=-1)
154
+
155
+
156
+ def apply_multimodal_rotary_pos_emb(q, k, cos, sin, mrope_section, unsqueeze_dim=1):
157
+ """Applies Rotary Position Embedding with Multimodal Sections to the query and key tensors (https://qwenlm.github.io/blog/qwen2-vl/).
158
+
159
+ Explanation:
160
+ Multimodal 3D rotary position embedding is an extension to 1D rotary position embedding. The input embedding
161
+ sequence contains vision (images / videos) embedding and text embedding or just contains text embedding. For
162
+ vision embedding part, we apply rotary position embedding on temporal, height and width dimension separately.
163
+ Here we split the channel dimension to 3 chunks for the temporal, height and width rotary position embedding.
164
+ For text embedding part, we just apply 1D rotary position embedding. The three rotary position index (temporal,
165
+ height and width) of text embedding is always the same, so the text embedding rotary position embedding has no
166
+ difference with modern LLMs.
167
+
168
+ Args:
169
+ q (`torch.Tensor`): The query tensor.
170
+ k (`torch.Tensor`): The key tensor.
171
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
172
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
173
+ position_ids (`torch.Tensor`):
174
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
175
+ used to pass offsetted position ids when working with a KV-cache.
176
+ mrope_section(`List(int)`):
177
+ Multimodal rope section is for channel dimension of temporal, height and width in rope calculation.
178
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
179
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
180
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
181
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
182
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
183
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
184
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
185
+ Returns:
186
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
187
+ """
188
+ mrope_section = mrope_section * 2
189
+ cos = torch.cat([m[i % 3] for i, m in enumerate(cos.split(mrope_section, dim=-1))], dim=-1).unsqueeze(
190
+ unsqueeze_dim
191
+ )
192
+ sin = torch.cat([m[i % 3] for i, m in enumerate(sin.split(mrope_section, dim=-1))], dim=-1).unsqueeze(
193
+ unsqueeze_dim
194
+ )
195
+
196
+ q_embed = (q * cos) + (rotate_half(q) * sin)
197
+ k_embed = (k * cos) + (rotate_half(k) * sin)
198
+ return q_embed, k_embed
199
+
200
+
201
+ def apply_rotary_pos_emb_vision(
202
+ q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor
203
+ ) -> tuple[torch.Tensor, torch.Tensor]:
204
+ orig_q_dtype = q.dtype
205
+ orig_k_dtype = k.dtype
206
+ q, k = q.float(), k.float()
207
+ cos, sin = cos.unsqueeze(-2).float(), sin.unsqueeze(-2).float()
208
+ q_embed = (q * cos) + (rotate_half(q) * sin)
209
+ k_embed = (k * cos) + (rotate_half(k) * sin)
210
+ q_embed = q_embed.to(orig_q_dtype)
211
+ k_embed = k_embed.to(orig_k_dtype)
212
+ return q_embed, k_embed
213
+
214
+
215
+ class VisionRotaryEmbedding(nn.Module):
216
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
217
+
218
+ def __init__(self, dim: int, theta: float = 10000.0) -> None:
219
+ super().__init__()
220
+ inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim))
221
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
222
+
223
+ def forward(self, seqlen: int) -> torch.Tensor:
224
+ seq = torch.arange(seqlen, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
225
+ freqs = torch.outer(seq, self.inv_freq)
226
+ return freqs
227
+
228
+
229
+ class PatchEmbed(nn.Module):
230
+ def __init__(
231
+ self,
232
+ patch_size: int = 14,
233
+ temporal_patch_size: int = 2,
234
+ in_channels: int = 3,
235
+ embed_dim: int = 1152,
236
+ ) -> None:
237
+ super().__init__()
238
+ self.patch_size = patch_size
239
+ self.temporal_patch_size = temporal_patch_size
240
+ self.in_channels = in_channels
241
+ self.embed_dim = embed_dim
242
+
243
+ kernel_size = [temporal_patch_size, patch_size, patch_size]
244
+ self.proj = nn.Conv3d(in_channels, embed_dim, kernel_size=kernel_size, stride=kernel_size, bias=False)
245
+
246
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
247
+ target_dtype = self.proj.weight.dtype
248
+ hidden_states = hidden_states.view(
249
+ -1, self.in_channels, self.temporal_patch_size, self.patch_size, self.patch_size
250
+ )
251
+ hidden_states = self.proj(hidden_states.to(dtype=target_dtype)).view(-1, self.embed_dim)
252
+ return hidden_states
253
+
254
+
255
+ class PatchMerger(nn.Module):
256
+ def __init__(self, dim: int, context_dim: int, spatial_merge_size: int = 2) -> None:
257
+ super().__init__()
258
+ self.hidden_size = context_dim * (spatial_merge_size**2)
259
+ self.ln_q = LayerNorm(context_dim, eps=1e-6)
260
+ self.mlp = nn.Sequential(
261
+ nn.Linear(self.hidden_size, self.hidden_size),
262
+ nn.GELU(),
263
+ nn.Linear(self.hidden_size, dim),
264
+ )
265
+
266
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
267
+ x = self.mlp(self.ln_q(x).view(-1, self.hidden_size))
268
+ return x
269
+
270
+
271
+ class VisionMlp(nn.Module):
272
+ def __init__(self, dim: int, hidden_dim: int, hidden_act: str) -> None:
273
+ super().__init__()
274
+ self.fc1 = nn.Linear(dim, hidden_dim)
275
+ self.act = ACT2FN[hidden_act]
276
+ self.fc2 = nn.Linear(hidden_dim, dim)
277
+
278
+ def forward(self, x) -> torch.Tensor:
279
+ return self.fc2(self.act(self.fc1(x)))
280
+
281
+
282
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
283
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
284
+ """
285
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
286
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
287
+ """
288
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
289
+ if n_rep == 1:
290
+ return hidden_states
291
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
292
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
293
+
294
+
295
+ def eager_attention_forward(
296
+ module: nn.Module,
297
+ query: torch.Tensor,
298
+ key: torch.Tensor,
299
+ value: torch.Tensor,
300
+ attention_mask: Optional[torch.Tensor],
301
+ scaling: float,
302
+ dropout: float = 0.0,
303
+ **kwargs,
304
+ ):
305
+ key_states = repeat_kv(key, module.num_key_value_groups)
306
+ value_states = repeat_kv(value, module.num_key_value_groups)
307
+
308
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
309
+ if attention_mask is not None:
310
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
311
+ attn_weights = attn_weights + causal_mask
312
+
313
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
314
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
315
+ attn_output = torch.matmul(attn_weights, value_states)
316
+ attn_output = attn_output.transpose(1, 2).contiguous()
317
+
318
+ return attn_output, attn_weights
319
+
320
+
321
+ class VisionAttention(nn.Module):
322
+ def __init__(self, config: Qwen2VLVisionConfig) -> None:
323
+ super().__init__()
324
+ self.dim = config.embed_dim
325
+ self.num_heads = config.num_heads
326
+ self.head_dim = self.dim // self.num_heads
327
+ self.num_key_value_groups = 1 # needed for eager attention
328
+ self.qkv = nn.Linear(self.dim, self.dim * 3, bias=True)
329
+ self.proj = nn.Linear(self.dim, self.dim)
330
+ self.scaling = self.head_dim**-0.5
331
+ self.config = config
332
+ self.attention_dropout = 0.0
333
+ self.is_causal = False
334
+
335
+ def forward(
336
+ self,
337
+ hidden_states: torch.Tensor,
338
+ cu_seqlens: torch.Tensor,
339
+ rotary_pos_emb: Optional[torch.Tensor] = None,
340
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
341
+ **kwargs,
342
+ ) -> torch.Tensor:
343
+ seq_length = hidden_states.shape[0]
344
+ query_states, key_states, value_states = (
345
+ self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
346
+ )
347
+ if position_embeddings is None:
348
+ logger.warning_once(
349
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
350
+ "through `rotary_pos_emb` (2D tensor of RoPE theta values), to using externally computed "
351
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.54 `rotary_pos_emb` will be "
352
+ "removed and `position_embeddings` will be mandatory."
353
+ )
354
+ emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1)
355
+ cos = emb.cos()
356
+ sin = emb.sin()
357
+ else:
358
+ cos, sin = position_embeddings
359
+ query_states, key_states = apply_rotary_pos_emb_vision(query_states, key_states, cos, sin)
360
+
361
+ query_states = query_states.transpose(0, 1).unsqueeze(0)
362
+ key_states = key_states.transpose(0, 1).unsqueeze(0)
363
+ value_states = value_states.transpose(0, 1).unsqueeze(0)
364
+
365
+ attention_interface: Callable = eager_attention_forward
366
+ if self.config._attn_implementation != "eager":
367
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
368
+
369
+ if self.config._attn_implementation == "flash_attention_2":
370
+ # Flash Attention 2: Use cu_seqlens for variable length attention
371
+ max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max()
372
+ attn_output, _ = attention_interface(
373
+ self,
374
+ query_states,
375
+ key_states,
376
+ value_states,
377
+ attention_mask=None,
378
+ scaling=self.scaling,
379
+ dropout=0.0 if not self.training else self.attention_dropout,
380
+ cu_seq_lens_q=cu_seqlens,
381
+ cu_seq_lens_k=cu_seqlens,
382
+ max_length_q=max_seqlen,
383
+ max_length_k=max_seqlen,
384
+ is_causal=False,
385
+ **kwargs,
386
+ )
387
+ else:
388
+ # Other implementations: Process each chunk separately
389
+ lengths = cu_seqlens[1:] - cu_seqlens[:-1]
390
+ splits = [
391
+ torch.split(tensor, lengths.tolist(), dim=2) for tensor in (query_states, key_states, value_states)
392
+ ]
393
+
394
+ attn_outputs = [
395
+ attention_interface(
396
+ self,
397
+ q,
398
+ k,
399
+ v,
400
+ attention_mask=None,
401
+ scaling=self.scaling,
402
+ dropout=0.0 if not self.training else self.attention_dropout,
403
+ is_causal=False,
404
+ **kwargs,
405
+ )[0]
406
+ for q, k, v in zip(*splits)
407
+ ]
408
+ attn_output = torch.cat(attn_outputs, dim=1)
409
+
410
+ attn_output = attn_output.reshape(seq_length, -1).contiguous()
411
+ attn_output = self.proj(attn_output)
412
+ return attn_output
413
+
414
+
415
+ class Qwen2VLVisionBlock(GradientCheckpointingLayer):
416
+ def __init__(self, config, attn_implementation: str = "sdpa") -> None:
417
+ super().__init__()
418
+ self.norm1 = LayerNorm(config.embed_dim, eps=1e-6)
419
+ self.norm2 = LayerNorm(config.embed_dim, eps=1e-6)
420
+ mlp_hidden_dim = int(config.embed_dim * config.mlp_ratio)
421
+
422
+ self.attn = VisionAttention(config=config)
423
+ self.mlp = VisionMlp(dim=config.embed_dim, hidden_dim=mlp_hidden_dim, hidden_act=config.hidden_act)
424
+
425
+ def forward(
426
+ self,
427
+ hidden_states: torch.Tensor,
428
+ cu_seqlens: torch.Tensor,
429
+ rotary_pos_emb: Optional[torch.Tensor] = None,
430
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
431
+ **kwargs,
432
+ ) -> torch.Tensor:
433
+ hidden_states = hidden_states + self.attn(
434
+ self.norm1(hidden_states),
435
+ cu_seqlens=cu_seqlens,
436
+ rotary_pos_emb=rotary_pos_emb,
437
+ position_embeddings=position_embeddings,
438
+ **kwargs,
439
+ )
440
+ hidden_states = hidden_states + self.mlp(self.norm2(hidden_states))
441
+ return hidden_states
442
+
443
+
444
+ # Copied from transformers.models.qwen2.modeling_qwen2.Qwen2RMSNorm
445
+ class Qwen2RMSNorm(nn.Module):
446
+ def __init__(self, hidden_size, eps=1e-6):
447
+ """
448
+ Qwen2RMSNorm is equivalent to T5LayerNorm
449
+ """
450
+ super().__init__()
451
+ self.weight = nn.Parameter(torch.ones(hidden_size))
452
+ self.variance_epsilon = eps
453
+
454
+ def forward(self, hidden_states):
455
+ input_dtype = hidden_states.dtype
456
+ hidden_states = hidden_states.to(torch.float32)
457
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
458
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
459
+ return self.weight * hidden_states.to(input_dtype)
460
+
461
+ def extra_repr(self):
462
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
463
+
464
+
465
+ # Copied from transformers.models.qwen2.modeling_qwen2.Qwen2MLP
466
+ class Qwen2MLP(nn.Module):
467
+ def __init__(self, config):
468
+ super().__init__()
469
+ self.config = config
470
+ self.hidden_size = config.hidden_size
471
+ self.intermediate_size = config.intermediate_size
472
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
473
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
474
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
475
+ self.act_fn = ACT2FN[config.hidden_act]
476
+
477
+ def forward(self, x):
478
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
479
+ return down_proj
480
+
481
+
482
+ class Qwen2VLAttention(nn.Module):
483
+ """
484
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
485
+ and "Generating Long Sequences with Sparse Transformers".
486
+ """
487
+
488
+ def __init__(self, config: Qwen2VLTextConfig, layer_idx: Optional[int] = None):
489
+ super().__init__()
490
+ self.config = config
491
+ self.layer_idx = layer_idx
492
+ if layer_idx is None:
493
+ logger.warning_once(
494
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
495
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
496
+ "when creating this class."
497
+ )
498
+
499
+ self.hidden_size = config.hidden_size
500
+ self.num_heads = config.num_attention_heads
501
+ self.head_dim = self.hidden_size // self.num_heads
502
+ self.num_key_value_heads = config.num_key_value_heads
503
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
504
+ self.is_causal = True
505
+ self.attention_dropout = config.attention_dropout
506
+ self.rope_scaling = config.rope_scaling
507
+ self.scaling = self.head_dim**-0.5
508
+
509
+ if (self.head_dim * self.num_heads) != self.hidden_size:
510
+ raise ValueError(
511
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
512
+ f" and `num_heads`: {self.num_heads})."
513
+ )
514
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
515
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
516
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
517
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
518
+ self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None
519
+
520
+ self.rotary_emb = Qwen2VLRotaryEmbedding(config=config)
521
+
522
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
523
+ def forward(
524
+ self,
525
+ hidden_states: torch.Tensor,
526
+ attention_mask: Optional[torch.Tensor] = None,
527
+ position_ids: Optional[torch.LongTensor] = None,
528
+ past_key_values: Optional[Cache] = None,
529
+ output_attentions: bool = False,
530
+ use_cache: bool = False,
531
+ cache_position: Optional[torch.LongTensor] = None,
532
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
533
+ **kwargs: Unpack[FlashAttentionKwargs],
534
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
535
+ bsz, q_len, _ = hidden_states.size()
536
+
537
+ query_states = self.q_proj(hidden_states)
538
+ key_states = self.k_proj(hidden_states)
539
+ value_states = self.v_proj(hidden_states)
540
+
541
+ query_states = query_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
542
+ key_states = key_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
543
+ value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
544
+
545
+ cos, sin = position_embeddings
546
+ query_states, key_states = apply_multimodal_rotary_pos_emb(
547
+ query_states, key_states, cos, sin, self.rope_scaling["mrope_section"]
548
+ )
549
+
550
+ if past_key_values is not None:
551
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
552
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
553
+
554
+ attention_interface: Callable = eager_attention_forward
555
+ if self.config._attn_implementation != "eager":
556
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
557
+
558
+ attn_output, attn_weights = attention_interface(
559
+ self,
560
+ query_states,
561
+ key_states,
562
+ value_states,
563
+ attention_mask,
564
+ dropout=0.0 if not self.training else self.attention_dropout,
565
+ scaling=self.scaling,
566
+ sliding_window=self.sliding_window,
567
+ position_ids=position_ids, # pass positions for FA2
568
+ **kwargs,
569
+ )
570
+
571
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
572
+ attn_output = self.o_proj(attn_output)
573
+ return attn_output, attn_weights
574
+
575
+
576
+ class Qwen2VLDecoderLayer(GradientCheckpointingLayer):
577
+ def __init__(self, config: Qwen2VLTextConfig, layer_idx: int):
578
+ super().__init__()
579
+ self.hidden_size = config.hidden_size
580
+
581
+ if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
582
+ logger.warning_once(
583
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
584
+ "unexpected results may be encountered."
585
+ )
586
+ self.self_attn = Qwen2VLAttention(config, layer_idx)
587
+
588
+ self.mlp = Qwen2MLP(config)
589
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
590
+ self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
591
+ self.attention_type = config.layer_types[layer_idx]
592
+
593
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
594
+ def forward(
595
+ self,
596
+ hidden_states: torch.Tensor,
597
+ attention_mask: Optional[torch.Tensor] = None,
598
+ position_ids: Optional[torch.LongTensor] = None,
599
+ past_key_values: Optional[tuple[torch.Tensor]] = None,
600
+ output_attentions: Optional[bool] = False,
601
+ use_cache: Optional[bool] = False,
602
+ cache_position: Optional[torch.LongTensor] = None,
603
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
604
+ **kwargs: Unpack[FlashAttentionKwargs],
605
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
606
+ """
607
+ Args:
608
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
609
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
610
+ `(batch, sequence_length)` where padding elements are indicated by 0.
611
+ output_attentions (`bool`, *optional*):
612
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
613
+ returned tensors for more detail.
614
+ use_cache (`bool`, *optional*):
615
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
616
+ (see `past_key_values`).
617
+ past_key_values (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
618
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
619
+ Indices depicting the position of the input sequence tokens in the sequence.
620
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
621
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
622
+ with `head_dim` being the embedding dimension of each attention head.
623
+ kwargs (`dict`, *optional*):
624
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
625
+ into the model
626
+ """
627
+
628
+ residual = hidden_states
629
+
630
+ hidden_states = self.input_layernorm(hidden_states)
631
+
632
+ # Self Attention
633
+ hidden_states, self_attn_weights = self.self_attn(
634
+ hidden_states=hidden_states,
635
+ attention_mask=attention_mask,
636
+ position_ids=position_ids,
637
+ past_key_values=past_key_values,
638
+ output_attentions=output_attentions,
639
+ use_cache=use_cache,
640
+ cache_position=cache_position,
641
+ position_embeddings=position_embeddings,
642
+ **kwargs,
643
+ )
644
+ hidden_states = residual + hidden_states
645
+
646
+ # Fully Connected
647
+ residual = hidden_states
648
+ hidden_states = self.post_attention_layernorm(hidden_states)
649
+ hidden_states = self.mlp(hidden_states)
650
+ hidden_states = residual + hidden_states
651
+
652
+ outputs = (hidden_states,)
653
+
654
+ if output_attentions:
655
+ outputs += (self_attn_weights,)
656
+
657
+ return outputs
658
+
659
+
660
+ @auto_docstring
661
+ class Qwen2VLPreTrainedModel(PreTrainedModel):
662
+ config: Qwen2VLConfig
663
+ base_model_prefix = "model"
664
+ supports_gradient_checkpointing = True
665
+ _no_split_modules = ["Qwen2VLDecoderLayer", "Qwen2VLVisionBlock"]
666
+ _skip_keys_device_placement = "past_key_values"
667
+ _supports_flash_attn = True
668
+ _supports_sdpa = True
669
+
670
+ _can_compile_fullgraph = True
671
+ _supports_attention_backend = True
672
+
673
+
674
+ @auto_docstring
675
+ class Qwen2VisionTransformerPretrainedModel(Qwen2VLPreTrainedModel):
676
+ config: Qwen2VLVisionConfig
677
+ _no_split_modules = ["Qwen2VLVisionBlock"]
678
+
679
+ def __init__(self, config) -> None:
680
+ super().__init__(config)
681
+ self.spatial_merge_size = config.spatial_merge_size
682
+
683
+ self.patch_embed = PatchEmbed(
684
+ patch_size=config.patch_size,
685
+ temporal_patch_size=config.temporal_patch_size,
686
+ in_channels=config.in_channels,
687
+ embed_dim=config.embed_dim,
688
+ )
689
+
690
+ head_dim = config.embed_dim // config.num_heads
691
+ self.rotary_pos_emb = VisionRotaryEmbedding(head_dim // 2)
692
+
693
+ self.blocks = nn.ModuleList([Qwen2VLVisionBlock(config) for _ in range(config.depth)])
694
+ self.merger = PatchMerger(
695
+ dim=config.hidden_size, context_dim=config.embed_dim, spatial_merge_size=config.spatial_merge_size
696
+ )
697
+ self.gradient_checkpointing = False
698
+
699
+ def get_dtype(self) -> torch.dtype:
700
+ return self.blocks[0].mlp.fc2.weight.dtype
701
+
702
+ def get_device(self) -> torch.device:
703
+ return self.blocks[0].mlp.fc2.weight.device
704
+
705
+ def rot_pos_emb(self, grid_thw):
706
+ pos_ids = []
707
+ for t, h, w in grid_thw:
708
+ hpos_ids = torch.arange(h).unsqueeze(1).expand(-1, w)
709
+ hpos_ids = hpos_ids.reshape(
710
+ h // self.spatial_merge_size,
711
+ self.spatial_merge_size,
712
+ w // self.spatial_merge_size,
713
+ self.spatial_merge_size,
714
+ )
715
+ hpos_ids = hpos_ids.permute(0, 2, 1, 3)
716
+ hpos_ids = hpos_ids.flatten()
717
+
718
+ wpos_ids = torch.arange(w).unsqueeze(0).expand(h, -1)
719
+ wpos_ids = wpos_ids.reshape(
720
+ h // self.spatial_merge_size,
721
+ self.spatial_merge_size,
722
+ w // self.spatial_merge_size,
723
+ self.spatial_merge_size,
724
+ )
725
+ wpos_ids = wpos_ids.permute(0, 2, 1, 3)
726
+ wpos_ids = wpos_ids.flatten()
727
+ pos_ids.append(torch.stack([hpos_ids, wpos_ids], dim=-1).repeat(t, 1))
728
+ pos_ids = torch.cat(pos_ids, dim=0)
729
+ max_grid_size = grid_thw[:, 1:].max()
730
+ rotary_pos_emb_full = self.rotary_pos_emb(max_grid_size)
731
+ rotary_pos_emb = rotary_pos_emb_full[pos_ids].flatten(1)
732
+ return rotary_pos_emb
733
+
734
+ @auto_docstring
735
+ def forward(
736
+ self,
737
+ hidden_states: torch.Tensor,
738
+ grid_thw: torch.Tensor,
739
+ **kwargs,
740
+ ) -> torch.Tensor:
741
+ r"""
742
+ grid_thw (`torch.LongTensor` of shape `(num_images, 3)`):
743
+ The temporal, height and width dimensions of feature shape for each image. Each row contains [t, h, w] values.
744
+ """
745
+ hidden_states = self.patch_embed(hidden_states)
746
+ rotary_pos_emb = self.rot_pos_emb(grid_thw)
747
+ emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1)
748
+ position_embeddings = (emb.cos(), emb.sin())
749
+
750
+ cu_seqlens = torch.repeat_interleave(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]).cumsum(
751
+ dim=0,
752
+ # Select dtype based on the following factors:
753
+ # - FA2 requires that cu_seqlens_q must have dtype int32
754
+ # - torch.onnx.export requires that cu_seqlens_q must have same dtype as grid_thw
755
+ # See https://github.com/huggingface/transformers/pull/34852 for more information
756
+ dtype=grid_thw.dtype if torch.jit.is_tracing() else torch.int32,
757
+ )
758
+ cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0)
759
+
760
+ for blk in self.blocks:
761
+ hidden_states = blk(
762
+ hidden_states,
763
+ cu_seqlens=cu_seqlens,
764
+ position_embeddings=position_embeddings,
765
+ **kwargs,
766
+ )
767
+
768
+ return self.merger(hidden_states)
769
+
770
+
771
+ @auto_docstring
772
+ class Qwen2VLTextModel(Qwen2VLPreTrainedModel):
773
+ config: Qwen2VLTextConfig
774
+
775
+ def __init__(self, config: Qwen2VLTextConfig):
776
+ super().__init__(config)
777
+ self.padding_idx = config.pad_token_id
778
+ self.vocab_size = config.vocab_size
779
+
780
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
781
+ self.layers = nn.ModuleList(
782
+ [Qwen2VLDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
783
+ )
784
+ self._attn_implementation = config._attn_implementation
785
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
786
+ self.rotary_emb = Qwen2VLRotaryEmbedding(config=config)
787
+ self.has_sliding_layers = "sliding_attention" in self.config.layer_types
788
+
789
+ self.gradient_checkpointing = False
790
+ # Initialize weights and apply final processing
791
+ self.post_init()
792
+
793
+ @auto_docstring
794
+ def forward(
795
+ self,
796
+ input_ids: Optional[torch.LongTensor] = None,
797
+ attention_mask: Optional[torch.Tensor] = None,
798
+ position_ids: Optional[torch.LongTensor] = None,
799
+ past_key_values: Optional[Cache] = None,
800
+ inputs_embeds: Optional[torch.FloatTensor] = None,
801
+ use_cache: Optional[bool] = None,
802
+ output_attentions: Optional[bool] = None,
803
+ output_hidden_states: Optional[bool] = None,
804
+ return_dict: Optional[bool] = None,
805
+ cache_position: Optional[torch.LongTensor] = None,
806
+ **kwargs: Unpack[FlashAttentionKwargs],
807
+ ) -> Union[tuple, BaseModelOutputWithPast]:
808
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
809
+ output_hidden_states = (
810
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
811
+ )
812
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
813
+
814
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
815
+
816
+ if (input_ids is None) ^ (inputs_embeds is not None):
817
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
818
+
819
+ if self.gradient_checkpointing and self.training:
820
+ if use_cache:
821
+ logger.warning_once(
822
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
823
+ )
824
+ use_cache = False
825
+
826
+ # torch.jit.trace() doesn't support cache objects in the output
827
+ if use_cache and past_key_values is None and not torch.jit.is_tracing():
828
+ past_key_values = DynamicCache(config=self.config)
829
+
830
+ if inputs_embeds is None:
831
+ inputs_embeds = self.embed_tokens(input_ids)
832
+
833
+ if cache_position is None:
834
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
835
+ cache_position = torch.arange(
836
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
837
+ )
838
+
839
+ # the hard coded `3` is for temporal, height and width.
840
+ if position_ids is None:
841
+ position_ids = cache_position.view(1, 1, -1).expand(3, inputs_embeds.shape[0], -1)
842
+ elif position_ids.ndim == 2:
843
+ position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1)
844
+
845
+ # NOTE: we need to pass text position ids for packing. Qwen2-VL uses 3D positions
846
+ # where each dim indicates visual spatial positions for temporal/height/width grids.
847
+ # There are two scenarios when FA2-like packed masking might be activated.
848
+ # 1. User specifically passed packed `position_ids` and no attention mask.
849
+ # In this case we expect the useer to create correct position ids for all 3 grids
850
+ # and prepend text-only position ids to it. The final tensor will be [4, bs, seq-len]
851
+ # 2. User runs forward with no attention mask and no position ids. In this case, position ids
852
+ # are prepared by the model (`get_rope_index`) as `[4, bs, seq-len]` tensor. Text-only positions are
853
+ # prepended by us when creating positions so that the mask is constructed correctly. NOTE: failing to pass
854
+ # text-only positions will cause incorrect mask construction, do not change `prepare_input_for_generation`
855
+ if position_ids.ndim == 3 and position_ids.shape[0] == 4:
856
+ text_position_ids = position_ids[0]
857
+ position_ids = position_ids[1:]
858
+ else:
859
+ text_position_ids = position_ids[0]
860
+
861
+ # It may already have been prepared by e.g. `generate`
862
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
863
+ # Prepare mask arguments
864
+ mask_kwargs = {
865
+ "config": self.config,
866
+ "input_embeds": inputs_embeds,
867
+ "attention_mask": attention_mask,
868
+ "cache_position": cache_position,
869
+ "past_key_values": past_key_values,
870
+ "position_ids": text_position_ids,
871
+ }
872
+ # Create the masks
873
+ causal_mask_mapping = {
874
+ "full_attention": create_causal_mask(**mask_kwargs),
875
+ }
876
+ # The sliding window alternating layers are not always activated depending on the config
877
+ if self.has_sliding_layers:
878
+ causal_mask_mapping["sliding_attention"] = create_sliding_window_causal_mask(**mask_kwargs)
879
+
880
+ hidden_states = inputs_embeds
881
+
882
+ # create position embeddings to be shared across the decoder layers
883
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
884
+
885
+ # decoder layers
886
+ all_hidden_states = () if output_hidden_states else None
887
+ all_self_attns = () if output_attentions else None
888
+
889
+ for decoder_layer in self.layers:
890
+ if output_hidden_states:
891
+ all_hidden_states += (hidden_states,)
892
+
893
+ layer_outputs = decoder_layer(
894
+ hidden_states,
895
+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],
896
+ position_ids=text_position_ids,
897
+ past_key_values=past_key_values,
898
+ output_attentions=output_attentions,
899
+ use_cache=use_cache,
900
+ cache_position=cache_position,
901
+ position_embeddings=position_embeddings,
902
+ **kwargs,
903
+ )
904
+
905
+ hidden_states = layer_outputs[0]
906
+
907
+ if output_attentions:
908
+ all_self_attns += (layer_outputs[1],)
909
+
910
+ hidden_states = self.norm(hidden_states)
911
+
912
+ # add hidden states from the last decoder layer
913
+ if output_hidden_states:
914
+ all_hidden_states += (hidden_states,)
915
+
916
+ if not return_dict:
917
+ return tuple(
918
+ v for v in [hidden_states, past_key_values, all_hidden_states, all_self_attns] if v is not None
919
+ )
920
+ return BaseModelOutputWithPast(
921
+ last_hidden_state=hidden_states,
922
+ past_key_values=past_key_values,
923
+ hidden_states=all_hidden_states,
924
+ attentions=all_self_attns,
925
+ )
926
+
927
+
928
+ @auto_docstring
929
+ class Qwen2VLModel(Qwen2VLPreTrainedModel):
930
+ base_model_prefix = ""
931
+ _checkpoint_conversion_mapping = {"^model": "language_model"}
932
+
933
+ def __init__(self, config: Qwen2VLConfig):
934
+ super().__init__(config)
935
+ self.visual = Qwen2VisionTransformerPretrainedModel._from_config(config.vision_config)
936
+ self.language_model = Qwen2VLTextModel._from_config(config.text_config)
937
+ self.rope_deltas = None # cache rope_deltas here
938
+
939
+ # Initialize weights and apply final processing
940
+ self.post_init()
941
+
942
+ def get_input_embeddings(self):
943
+ return self.language_model.get_input_embeddings()
944
+
945
+ def set_input_embeddings(self, value):
946
+ self.language_model.set_input_embeddings(value)
947
+
948
+ def set_decoder(self, decoder):
949
+ self.language_model = decoder
950
+
951
+ def get_decoder(self):
952
+ return self.language_model
953
+
954
+ def get_rope_index(
955
+ self,
956
+ input_ids: Optional[torch.LongTensor] = None,
957
+ image_grid_thw: Optional[torch.LongTensor] = None,
958
+ video_grid_thw: Optional[torch.LongTensor] = None,
959
+ attention_mask: Optional[torch.Tensor] = None,
960
+ ) -> tuple[torch.Tensor, torch.Tensor]:
961
+ """
962
+ Calculate the 3D rope index based on image and video's temporal, height and width in LLM.
963
+
964
+ Explanation:
965
+ Each embedding sequence contains vision embedding and text embedding or just contains text embedding.
966
+
967
+ For pure text embedding sequence, the rotary position embedding has no difference with modern LLMs.
968
+ Examples:
969
+ input_ids: [T T T T T], here T is for text.
970
+ temporal position_ids: [0, 1, 2, 3, 4]
971
+ height position_ids: [0, 1, 2, 3, 4]
972
+ width position_ids: [0, 1, 2, 3, 4]
973
+
974
+ For vision and text embedding sequence, we calculate 3D rotary position embedding for vision part
975
+ and 1D rotary position embedding for text part.
976
+ Examples:
977
+ Assume we have a video input with 3 temporal patches, 2 height patches and 2 width patches.
978
+ input_ids: [V V V V V V V V V V V V T T T T T], here V is for vision.
979
+ vision temporal position_ids: [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2]
980
+ vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1]
981
+ vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
982
+ text temporal position_ids: [3, 4, 5, 6, 7]
983
+ text height position_ids: [3, 4, 5, 6, 7]
984
+ text width position_ids: [3, 4, 5, 6, 7]
985
+ Here we calculate the text start position_ids as the max vision position_ids plus 1.
986
+
987
+ Args:
988
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
989
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
990
+ it.
991
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
992
+ The temporal, height and width of feature shape of each image in LLM.
993
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
994
+ The temporal, height and width of feature shape of each video in LLM.
995
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
996
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
997
+
998
+ - 1 for tokens that are **not masked**,
999
+ - 0 for tokens that are **masked**.
1000
+
1001
+ Returns:
1002
+ position_ids (`torch.LongTensor` of shape `(3, batch_size, sequence_length)`)
1003
+ mrope_position_deltas (`torch.Tensor` of shape `(batch_size)`)
1004
+ """
1005
+ spatial_merge_size = self.config.vision_config.spatial_merge_size
1006
+ image_token_id = self.config.image_token_id
1007
+ video_token_id = self.config.video_token_id
1008
+ vision_start_token_id = self.config.vision_start_token_id
1009
+ mrope_position_deltas = []
1010
+ if input_ids is not None and (image_grid_thw is not None or video_grid_thw is not None):
1011
+ total_input_ids = input_ids
1012
+ if attention_mask is None:
1013
+ attention_mask = torch.ones_like(total_input_ids)
1014
+ position_ids = torch.ones(
1015
+ 3, input_ids.shape[0], input_ids.shape[1], dtype=input_ids.dtype, device=input_ids.device
1016
+ )
1017
+ image_index, video_index = 0, 0
1018
+ for i, input_ids in enumerate(total_input_ids):
1019
+ input_ids = input_ids[attention_mask[i].to(input_ids.device) == 1]
1020
+ image_nums, video_nums = 0, 0
1021
+ vision_start_indices = torch.argwhere(input_ids == vision_start_token_id).squeeze(1)
1022
+ vision_tokens = input_ids[vision_start_indices + 1]
1023
+ image_nums = (vision_tokens == image_token_id).sum()
1024
+ video_nums = (vision_tokens == video_token_id).sum()
1025
+ input_tokens = input_ids.tolist()
1026
+ llm_pos_ids_list: list = []
1027
+ st = 0
1028
+ remain_images, remain_videos = image_nums, video_nums
1029
+ for _ in range(image_nums + video_nums):
1030
+ if image_token_id in input_tokens and remain_images > 0:
1031
+ ed_image = input_tokens.index(image_token_id, st)
1032
+ else:
1033
+ ed_image = len(input_tokens) + 1
1034
+ if video_token_id in input_tokens and remain_videos > 0:
1035
+ ed_video = input_tokens.index(video_token_id, st)
1036
+ else:
1037
+ ed_video = len(input_tokens) + 1
1038
+ if ed_image < ed_video:
1039
+ t, h, w = (
1040
+ image_grid_thw[image_index][0],
1041
+ image_grid_thw[image_index][1],
1042
+ image_grid_thw[image_index][2],
1043
+ )
1044
+ image_index += 1
1045
+ remain_images -= 1
1046
+ ed = ed_image
1047
+ else:
1048
+ t, h, w = (
1049
+ video_grid_thw[video_index][0],
1050
+ video_grid_thw[video_index][1],
1051
+ video_grid_thw[video_index][2],
1052
+ )
1053
+ video_index += 1
1054
+ remain_videos -= 1
1055
+ ed = ed_video
1056
+ llm_grid_t, llm_grid_h, llm_grid_w = (
1057
+ t.item(),
1058
+ h.item() // spatial_merge_size,
1059
+ w.item() // spatial_merge_size,
1060
+ )
1061
+ text_len = ed - st
1062
+
1063
+ st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
1064
+ llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx)
1065
+
1066
+ t_index = torch.arange(llm_grid_t).view(-1, 1).expand(-1, llm_grid_h * llm_grid_w).flatten()
1067
+ h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(llm_grid_t, -1, llm_grid_w).flatten()
1068
+ w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(llm_grid_t, llm_grid_h, -1).flatten()
1069
+ llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + text_len + st_idx)
1070
+ st = ed + llm_grid_t * llm_grid_h * llm_grid_w
1071
+
1072
+ if st < len(input_tokens):
1073
+ st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
1074
+ text_len = len(input_tokens) - st
1075
+ llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx)
1076
+
1077
+ llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1)
1078
+ position_ids[..., i, attention_mask[i] == 1] = llm_positions.to(position_ids.device)
1079
+ mrope_position_deltas.append(llm_positions.max() + 1 - len(total_input_ids[i]))
1080
+ mrope_position_deltas = torch.tensor(mrope_position_deltas, device=input_ids.device).unsqueeze(1)
1081
+ return position_ids, mrope_position_deltas
1082
+ else:
1083
+ if attention_mask is not None:
1084
+ position_ids = attention_mask.long().cumsum(-1) - 1
1085
+ position_ids.masked_fill_(attention_mask == 0, 1)
1086
+ position_ids = position_ids.unsqueeze(0).expand(3, -1, -1).to(attention_mask.device)
1087
+ max_position_ids = position_ids.max(0, keepdim=False)[0].max(-1, keepdim=True)[0]
1088
+ mrope_position_deltas = max_position_ids + 1 - attention_mask.shape[-1]
1089
+ else:
1090
+ position_ids = (
1091
+ torch.arange(input_ids.shape[1], device=input_ids.device)
1092
+ .view(1, 1, -1)
1093
+ .expand(3, input_ids.shape[0], -1)
1094
+ )
1095
+ mrope_position_deltas = torch.zeros(
1096
+ [input_ids.shape[0], 1],
1097
+ device=input_ids.device,
1098
+ dtype=input_ids.dtype,
1099
+ )
1100
+
1101
+ return position_ids, mrope_position_deltas
1102
+
1103
+ def get_video_features(
1104
+ self, pixel_values_videos: torch.FloatTensor, video_grid_thw: Optional[torch.LongTensor] = None
1105
+ ):
1106
+ """
1107
+ Encodes videos into continuous embeddings that can be forwarded to the language model.
1108
+
1109
+ Args:
1110
+ pixel_values_videos (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
1111
+ The tensors corresponding to the input videos.
1112
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
1113
+ The temporal, height and width of feature shape of each video in LLM.
1114
+ """
1115
+ pixel_values_videos = pixel_values_videos.type(self.visual.dtype)
1116
+ video_embeds = self.visual(pixel_values_videos, grid_thw=video_grid_thw)
1117
+ split_sizes = (video_grid_thw.prod(-1) // self.visual.spatial_merge_size**2).tolist()
1118
+ video_embeds = torch.split(video_embeds, split_sizes)
1119
+ return video_embeds
1120
+
1121
+ def get_image_features(self, pixel_values: torch.FloatTensor, image_grid_thw: Optional[torch.LongTensor] = None):
1122
+ """
1123
+ Encodes images into continuous embeddings that can be forwarded to the language model.
1124
+
1125
+ Args:
1126
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
1127
+ The tensors corresponding to the input images.
1128
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
1129
+ The temporal, height and width of feature shape of each image in LLM.
1130
+ """
1131
+ pixel_values = pixel_values.type(self.visual.dtype)
1132
+ image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw)
1133
+ split_sizes = (image_grid_thw.prod(-1) // self.visual.spatial_merge_size**2).tolist()
1134
+ image_embeds = torch.split(image_embeds, split_sizes)
1135
+ return image_embeds
1136
+
1137
+ def get_placeholder_mask(
1138
+ self,
1139
+ input_ids: torch.LongTensor,
1140
+ inputs_embeds: torch.FloatTensor,
1141
+ image_features: torch.FloatTensor = None,
1142
+ video_features: torch.FloatTensor = None,
1143
+ ):
1144
+ """
1145
+ Obtains multimodal placeholdr mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
1146
+ equal to the length of multimodal features. If the lengths are different, an error is raised.
1147
+ """
1148
+ if input_ids is None:
1149
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
1150
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
1151
+ )
1152
+ special_image_mask = special_image_mask.all(-1)
1153
+ special_video_mask = inputs_embeds == self.get_input_embeddings()(
1154
+ torch.tensor(self.config.video_token_id, dtype=torch.long, device=inputs_embeds.device)
1155
+ )
1156
+ special_video_mask = special_video_mask.all(-1)
1157
+ else:
1158
+ special_image_mask = input_ids == self.config.image_token_id
1159
+ special_video_mask = input_ids == self.config.video_token_id
1160
+
1161
+ n_image_tokens = special_image_mask.sum()
1162
+ special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
1163
+ if image_features is not None and inputs_embeds[special_image_mask].numel() != image_features.numel():
1164
+ raise ValueError(
1165
+ f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {image_features.shape[0]}"
1166
+ )
1167
+
1168
+ n_video_tokens = special_video_mask.sum()
1169
+ special_video_mask = special_video_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
1170
+ if video_features is not None and inputs_embeds[special_video_mask].numel() != video_features.numel():
1171
+ raise ValueError(
1172
+ f"Videos features and video tokens do not match: tokens: {n_video_tokens}, features {video_features.shape[0]}"
1173
+ )
1174
+
1175
+ return special_image_mask, special_video_mask
1176
+
1177
+ @auto_docstring
1178
+ def forward(
1179
+ self,
1180
+ input_ids: torch.LongTensor = None,
1181
+ attention_mask: Optional[torch.Tensor] = None,
1182
+ position_ids: Optional[torch.LongTensor] = None,
1183
+ past_key_values: Optional[Cache] = None,
1184
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1185
+ use_cache: Optional[bool] = None,
1186
+ output_attentions: Optional[bool] = None,
1187
+ output_hidden_states: Optional[bool] = None,
1188
+ return_dict: Optional[bool] = None,
1189
+ pixel_values: Optional[torch.Tensor] = None,
1190
+ pixel_values_videos: Optional[torch.FloatTensor] = None,
1191
+ image_grid_thw: Optional[torch.LongTensor] = None,
1192
+ video_grid_thw: Optional[torch.LongTensor] = None,
1193
+ rope_deltas: Optional[torch.LongTensor] = None,
1194
+ cache_position: Optional[torch.LongTensor] = None,
1195
+ **kwargs: Unpack[TransformersKwargs],
1196
+ ) -> Union[tuple, Qwen2VLModelOutputWithPast]:
1197
+ r"""
1198
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
1199
+ The temporal, height and width of feature shape of each image in LLM.
1200
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
1201
+ The temporal, height and width of feature shape of each video in LLM.
1202
+ rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
1203
+ The rope index difference between sequence length and multimodal rope.
1204
+ """
1205
+
1206
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1207
+ output_hidden_states = (
1208
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1209
+ )
1210
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1211
+
1212
+ if inputs_embeds is None:
1213
+ inputs_embeds = self.get_input_embeddings()(input_ids)
1214
+
1215
+ if pixel_values is not None:
1216
+ image_embeds = self.get_image_features(pixel_values, image_grid_thw)
1217
+ image_embeds = torch.cat(image_embeds, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
1218
+ image_mask, _ = self.get_placeholder_mask(
1219
+ input_ids, inputs_embeds=inputs_embeds, image_features=image_embeds
1220
+ )
1221
+ inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
1222
+
1223
+ if pixel_values_videos is not None:
1224
+ video_embeds = self.get_video_features(pixel_values_videos, video_grid_thw)
1225
+ video_embeds = torch.cat(video_embeds, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
1226
+ _, video_mask = self.get_placeholder_mask(
1227
+ input_ids, inputs_embeds=inputs_embeds, video_features=video_embeds
1228
+ )
1229
+ inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds)
1230
+
1231
+ if position_ids is None:
1232
+ if self.rope_deltas is None or cache_position is None or cache_position[0] == 0:
1233
+ position_ids, rope_deltas = self.get_rope_index(
1234
+ input_ids, image_grid_thw, video_grid_thw, attention_mask
1235
+ )
1236
+ self.rope_deltas = rope_deltas
1237
+ # then use the prev pre-calculated rope-deltas to get the correct position ids
1238
+ else:
1239
+ batch_size, seq_length, _ = inputs_embeds.shape
1240
+ position_ids = torch.arange(seq_length, device=inputs_embeds.device)
1241
+ position_ids = position_ids.view(1, 1, -1).expand(3, batch_size, -1)
1242
+ if cache_position is not None:
1243
+ delta = (cache_position[0] + self.rope_deltas).to(inputs_embeds.device)
1244
+ else:
1245
+ delta = torch.zeros((batch_size, seq_length), device=inputs_embeds.device)
1246
+ delta = delta.repeat_interleave(batch_size // delta.shape[0], dim=0)
1247
+ position_ids += delta.to(position_ids.device)
1248
+
1249
+ outputs = self.language_model(
1250
+ input_ids=None,
1251
+ position_ids=position_ids,
1252
+ attention_mask=attention_mask,
1253
+ past_key_values=past_key_values,
1254
+ inputs_embeds=inputs_embeds,
1255
+ use_cache=use_cache,
1256
+ output_attentions=output_attentions,
1257
+ output_hidden_states=output_hidden_states,
1258
+ return_dict=True,
1259
+ cache_position=cache_position,
1260
+ **kwargs,
1261
+ )
1262
+
1263
+ output = Qwen2VLModelOutputWithPast(
1264
+ last_hidden_state=outputs.last_hidden_state,
1265
+ past_key_values=outputs.past_key_values,
1266
+ hidden_states=outputs.hidden_states,
1267
+ attentions=outputs.attentions,
1268
+ rope_deltas=self.rope_deltas,
1269
+ )
1270
+ return output if return_dict else output.to_tuple()
1271
+
1272
+
1273
+ class Qwen2VLForConditionalGeneration(Qwen2VLPreTrainedModel, GenerationMixin):
1274
+ _checkpoint_conversion_mapping = {
1275
+ "^visual": "model.visual",
1276
+ r"^model(?!\.(language_model|visual))": "model.language_model",
1277
+ }
1278
+ _tied_weights_keys = ["lm_head.weight"]
1279
+
1280
+ def __init__(self, config):
1281
+ super().__init__(config)
1282
+ self.model = Qwen2VLModel(config)
1283
+ self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
1284
+
1285
+ self.post_init()
1286
+
1287
+ def get_input_embeddings(self):
1288
+ return self.model.get_input_embeddings()
1289
+
1290
+ def set_input_embeddings(self, value):
1291
+ self.model.set_input_embeddings(value)
1292
+
1293
+ def set_decoder(self, decoder):
1294
+ self.model.set_decoder(decoder)
1295
+
1296
+ def get_decoder(self):
1297
+ return self.model.get_decoder()
1298
+
1299
+ def get_video_features(
1300
+ self, pixel_values_videos: torch.FloatTensor, video_grid_thw: Optional[torch.LongTensor] = None
1301
+ ):
1302
+ return self.model.get_video_features(pixel_values_videos, video_grid_thw)
1303
+
1304
+ def get_image_features(self, pixel_values: torch.FloatTensor, image_grid_thw: Optional[torch.LongTensor] = None):
1305
+ return self.model.get_image_features(pixel_values, image_grid_thw)
1306
+
1307
+ # Make modules available through conditional class for BC
1308
+ @property
1309
+ def language_model(self):
1310
+ return self.model.language_model
1311
+
1312
+ @property
1313
+ def visual(self):
1314
+ return self.model.visual
1315
+
1316
+ @can_return_tuple
1317
+ @auto_docstring
1318
+ def forward(
1319
+ self,
1320
+ input_ids: torch.LongTensor = None,
1321
+ attention_mask: Optional[torch.Tensor] = None,
1322
+ position_ids: Optional[torch.LongTensor] = None,
1323
+ past_key_values: Optional[Cache] = None,
1324
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1325
+ labels: Optional[torch.LongTensor] = None,
1326
+ use_cache: Optional[bool] = None,
1327
+ output_attentions: Optional[bool] = None,
1328
+ output_hidden_states: Optional[bool] = None,
1329
+ pixel_values: Optional[torch.Tensor] = None,
1330
+ pixel_values_videos: Optional[torch.FloatTensor] = None,
1331
+ image_grid_thw: Optional[torch.LongTensor] = None,
1332
+ video_grid_thw: Optional[torch.LongTensor] = None,
1333
+ rope_deltas: Optional[torch.LongTensor] = None,
1334
+ cache_position: Optional[torch.LongTensor] = None,
1335
+ **kwargs: Unpack[TransformersKwargs],
1336
+ ) -> Union[tuple, Qwen2VLCausalLMOutputWithPast]:
1337
+ r"""
1338
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1339
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1340
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1341
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1342
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
1343
+ The temporal, height and width of feature shape of each image in LLM.
1344
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
1345
+ The temporal, height and width of feature shape of each video in LLM.
1346
+ rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
1347
+ The rope index difference between sequence length and multimodal rope.
1348
+
1349
+ Example:
1350
+
1351
+ ```python
1352
+ >>> from PIL import Image
1353
+ >>> import requests
1354
+ >>> from transformers import AutoProcessor, Qwen2VLForConditionalGeneration
1355
+
1356
+ >>> model = Qwen2VLForConditionalGeneration.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
1357
+ >>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
1358
+
1359
+ >>> messages = [
1360
+ {
1361
+ "role": "user",
1362
+ "content": [
1363
+ {"type": "image"},
1364
+ {"type": "text", "text": "What is shown in this image?"},
1365
+ ],
1366
+ },
1367
+ ]
1368
+ >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
1369
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1370
+
1371
+ >>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
1372
+ >>> inputs = processor(text=[text], images=[image], vision_infos=[vision_infos])
1373
+
1374
+ >>> # Generate
1375
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1376
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1377
+ "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 ..."
1378
+ ```"""
1379
+
1380
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1381
+ output_hidden_states = (
1382
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1383
+ )
1384
+
1385
+ outputs = self.model(
1386
+ input_ids=input_ids,
1387
+ pixel_values=pixel_values,
1388
+ pixel_values_videos=pixel_values_videos,
1389
+ image_grid_thw=image_grid_thw,
1390
+ video_grid_thw=video_grid_thw,
1391
+ position_ids=position_ids,
1392
+ attention_mask=attention_mask,
1393
+ past_key_values=past_key_values,
1394
+ inputs_embeds=inputs_embeds,
1395
+ use_cache=use_cache,
1396
+ output_attentions=output_attentions,
1397
+ output_hidden_states=output_hidden_states,
1398
+ return_dict=True,
1399
+ cache_position=cache_position,
1400
+ **kwargs,
1401
+ )
1402
+
1403
+ hidden_states = outputs[0]
1404
+ logits = self.lm_head(hidden_states)
1405
+
1406
+ loss = None
1407
+ if labels is not None:
1408
+ loss = self.loss_function(
1409
+ logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
1410
+ )
1411
+
1412
+ return Qwen2VLCausalLMOutputWithPast(
1413
+ loss=loss,
1414
+ logits=logits,
1415
+ past_key_values=outputs.past_key_values,
1416
+ hidden_states=outputs.hidden_states,
1417
+ attentions=outputs.attentions,
1418
+ rope_deltas=outputs.rope_deltas,
1419
+ )
1420
+
1421
+ def prepare_inputs_for_generation(
1422
+ self,
1423
+ input_ids,
1424
+ past_key_values=None,
1425
+ attention_mask=None,
1426
+ inputs_embeds=None,
1427
+ cache_position=None,
1428
+ position_ids=None,
1429
+ use_cache=True,
1430
+ pixel_values=None,
1431
+ pixel_values_videos=None,
1432
+ image_grid_thw=None,
1433
+ video_grid_thw=None,
1434
+ **kwargs,
1435
+ ):
1436
+ # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
1437
+
1438
+ model_inputs = super().prepare_inputs_for_generation(
1439
+ input_ids,
1440
+ past_key_values=past_key_values,
1441
+ attention_mask=attention_mask,
1442
+ inputs_embeds=inputs_embeds,
1443
+ cache_position=cache_position,
1444
+ position_ids=position_ids,
1445
+ pixel_values=pixel_values,
1446
+ pixel_values_videos=pixel_values_videos,
1447
+ image_grid_thw=image_grid_thw,
1448
+ video_grid_thw=video_grid_thw,
1449
+ use_cache=use_cache,
1450
+ **kwargs,
1451
+ )
1452
+
1453
+ # Qwen2-VL position_ids are prepareed with rope_deltas in forward
1454
+ if position_ids is None:
1455
+ # Calculate RoPE index once per generation in the pre-fill stage only.
1456
+ # When compiling, we can't check tensor values thus we check only input length
1457
+ # It is safe to assume that `length!=1` means we're in pre-fill because compiled
1458
+ # models currently cannot do asssisted decoding
1459
+ prefill_compiled_stage = is_torchdynamo_compiling() and (
1460
+ (input_ids is not None and input_ids.shape[1] != 1)
1461
+ or (inputs_embeds is not None and inputs_embeds.shape[1] != 1)
1462
+ )
1463
+ prefill_noncompiled_stage = not is_torchdynamo_compiling() and (
1464
+ (cache_position is not None and cache_position[0] == 0)
1465
+ or (past_key_values is None or past_key_values.get_seq_length() == 0)
1466
+ )
1467
+ if (prefill_compiled_stage or prefill_noncompiled_stage) or self.model.rope_deltas is None:
1468
+ vision_positions, rope_deltas = self.model.get_rope_index(
1469
+ model_inputs.get("input_ids", None),
1470
+ image_grid_thw=image_grid_thw,
1471
+ video_grid_thw=video_grid_thw,
1472
+ attention_mask=attention_mask,
1473
+ )
1474
+ self.model.rope_deltas = rope_deltas
1475
+ # then use the prev pre-calculated rope-deltas to get the correct position ids
1476
+ elif "position_ids" in model_inputs:
1477
+ position_ids = model_inputs["position_ids"][None, ...]
1478
+ delta = self.model.rope_deltas
1479
+ delta = delta.repeat_interleave(position_ids.shape[1] // delta.shape[0], dim=0)
1480
+ vision_positions = position_ids + delta.expand_as(position_ids)
1481
+ vision_positions = vision_positions.expand(3, vision_positions.shape[1], -1)
1482
+
1483
+ # Concatenate "text + vision" positions into [4, bs, seq-len]
1484
+ if "position_ids" not in model_inputs:
1485
+ text_positions = torch.arange(input_ids, device=input_ids.device)[None, None, :]
1486
+ else:
1487
+ text_positions = model_inputs["position_ids"][None, ...]
1488
+ model_inputs["position_ids"] = torch.cat([text_positions, vision_positions], dim=0)
1489
+
1490
+ if model_inputs["cache_position"][0] != 0:
1491
+ model_inputs["pixel_values"] = None
1492
+ model_inputs["pixel_values_videos"] = None
1493
+
1494
+ return model_inputs
1495
+
1496
+ def _get_image_nums_and_video_nums(
1497
+ self,
1498
+ input_ids: Optional[torch.LongTensor],
1499
+ inputs_embeds: Optional[torch.Tensor] = None,
1500
+ ) -> tuple[torch.Tensor, torch.Tensor]:
1501
+ """
1502
+ Get the number of images and videos for each sample to calculate the separation length of the sample tensor.
1503
+ These parameters are not passed through the processor to avoid unpredictable impacts from interface modifications.
1504
+
1505
+ Args:
1506
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1507
+ Indices of input sequence tokens in the vocabulary.
1508
+
1509
+ Returns:
1510
+ image_nums (`torch.LongTensor` of shape `(batch_size, num_images_sample)`)
1511
+ video_nums (`torch.LongTensor` of shape `(batch_size, num_videos_sample)`)
1512
+ """
1513
+ image_token_id = self.config.image_token_id
1514
+ video_token_id = self.config.video_token_id
1515
+ vision_start_token_id = self.config.vision_start_token_id
1516
+
1517
+ if inputs_embeds is not None:
1518
+ vision_start_mask = (
1519
+ inputs_embeds
1520
+ == self.get_input_embeddings()(
1521
+ torch.tensor(vision_start_token_id, dtype=torch.long, device=inputs_embeds.device)
1522
+ )
1523
+ )[..., 0]
1524
+ image_mask = (
1525
+ inputs_embeds
1526
+ == self.get_input_embeddings()(
1527
+ torch.tensor(image_token_id, dtype=torch.long, device=inputs_embeds.device)
1528
+ )
1529
+ )[..., 0]
1530
+ video_mask = (
1531
+ inputs_embeds
1532
+ == self.get_input_embeddings()(
1533
+ torch.tensor(video_token_id, dtype=torch.long, device=inputs_embeds.device)
1534
+ )
1535
+ )[..., 0]
1536
+ else:
1537
+ vision_start_mask = input_ids == vision_start_token_id
1538
+ image_mask = input_ids == image_token_id
1539
+ video_mask = input_ids == video_token_id
1540
+
1541
+ vision_first_mask = torch.roll(vision_start_mask, shifts=1, dims=1)
1542
+ image_nums = torch.sum(vision_first_mask & image_mask, dim=1)
1543
+ video_nums = torch.sum(vision_first_mask & video_mask, dim=1)
1544
+
1545
+ return image_nums, video_nums
1546
+
1547
+ def _expand_inputs_for_generation(
1548
+ self,
1549
+ expand_size: int = 1,
1550
+ is_encoder_decoder: bool = False,
1551
+ input_ids: Optional[torch.LongTensor] = None,
1552
+ **model_kwargs,
1553
+ ) -> tuple[torch.LongTensor, dict[str, Any]]:
1554
+ # Overwritten -- Support for expanding tensors without a batch size dimension
1555
+ # e.g., pixel_values, image_grid_thw, pixel_values_videos, video_grid_thw, second_per_grid_t
1556
+ # pixel_values.shape[0] is sum(seqlen_images for samples)
1557
+ # image_grid_thw.shape[0] is sum(num_images for samples)
1558
+
1559
+ if expand_size == 1:
1560
+ return input_ids, model_kwargs
1561
+
1562
+ visual_keys = ["pixel_values", "image_grid_thw", "pixel_values_videos", "video_grid_thw", "second_per_grid_ts"]
1563
+
1564
+ def _expand_dict_for_generation_visual(dict_to_expand):
1565
+ image_grid_thw = model_kwargs.get("image_grid_thw", None)
1566
+ video_grid_thw = model_kwargs.get("video_grid_thw", None)
1567
+ image_nums, video_nums = self._get_image_nums_and_video_nums(
1568
+ input_ids, inputs_embeds=model_kwargs.get("inputs_embeds", None)
1569
+ )
1570
+
1571
+ def _repeat_interleave_samples(x, lengths, repeat_times):
1572
+ samples = torch.split(x, lengths)
1573
+ repeat_args = [repeat_times] + [1] * (x.dim() - 1)
1574
+ result = torch.cat([sample.repeat(*repeat_args) for sample in samples], dim=0)
1575
+ return result
1576
+
1577
+ for key in dict_to_expand:
1578
+ if key == "pixel_values":
1579
+ # split images into samples
1580
+ samples = torch.split(image_grid_thw, list(image_nums))
1581
+ # compute the sequence length of images for each sample
1582
+ lengths = [torch.prod(sample, dim=1).sum() for sample in samples]
1583
+ dict_to_expand[key] = _repeat_interleave_samples(
1584
+ dict_to_expand[key], lengths=lengths, repeat_times=expand_size
1585
+ )
1586
+ elif key == "image_grid_thw":
1587
+ # get the num of images for each sample
1588
+ lengths = list(image_nums)
1589
+ dict_to_expand[key] = _repeat_interleave_samples(
1590
+ dict_to_expand[key], lengths=lengths, repeat_times=expand_size
1591
+ )
1592
+ elif key == "pixel_values_videos":
1593
+ samples = torch.split(video_grid_thw, list(video_nums))
1594
+ lengths = [torch.prod(sample, dim=1).sum() for sample in samples]
1595
+ dict_to_expand[key] = _repeat_interleave_samples(
1596
+ dict_to_expand[key], lengths=lengths, repeat_times=expand_size
1597
+ )
1598
+ elif key == "video_grid_thw":
1599
+ lengths = list(video_nums)
1600
+ dict_to_expand[key] = _repeat_interleave_samples(
1601
+ dict_to_expand[key], lengths=lengths, repeat_times=expand_size
1602
+ )
1603
+ elif key == "second_per_grid_ts":
1604
+ dict_to_expand[key] = _repeat_interleave_samples(
1605
+ dict_to_expand[key], lengths=list(video_nums), repeat_times=expand_size
1606
+ )
1607
+ return dict_to_expand
1608
+
1609
+ def _expand_dict_for_generation(dict_to_expand):
1610
+ for key in dict_to_expand:
1611
+ if (
1612
+ key != "cache_position"
1613
+ and dict_to_expand[key] is not None
1614
+ and isinstance(dict_to_expand[key], torch.Tensor)
1615
+ and key not in visual_keys
1616
+ ):
1617
+ dict_to_expand[key] = dict_to_expand[key].repeat_interleave(expand_size, dim=0)
1618
+ return dict_to_expand
1619
+
1620
+ model_kwargs = _expand_dict_for_generation_visual(model_kwargs)
1621
+
1622
+ if input_ids is not None:
1623
+ input_ids = input_ids.repeat_interleave(expand_size, dim=0)
1624
+
1625
+ model_kwargs = _expand_dict_for_generation(model_kwargs)
1626
+
1627
+ if is_encoder_decoder:
1628
+ if model_kwargs.get("encoder_outputs") is None:
1629
+ raise ValueError("If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined.")
1630
+ model_kwargs["encoder_outputs"] = _expand_dict_for_generation(model_kwargs["encoder_outputs"])
1631
+
1632
+ return input_ids, model_kwargs
1633
+
1634
+
1635
+ __all__ = ["Qwen2VLForConditionalGeneration", "Qwen2VLModel", "Qwen2VLPreTrainedModel", "Qwen2VLTextModel"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_vl/processing_qwen2_vl.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
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
+ Processor class for Qwen2-VL.
22
+ """
23
+
24
+ from typing import Optional, Union
25
+
26
+ import numpy as np
27
+
28
+ from ...feature_extraction_utils import BatchFeature
29
+ from ...image_utils import ImageInput
30
+ from ...processing_utils import ImagesKwargs, MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack
31
+ from ...tokenization_utils_base import PreTokenizedInput, TextInput
32
+ from ...utils import logging
33
+ from ...video_utils import VideoInput
34
+
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+
39
+ class Qwen2VLImagesKwargs(ImagesKwargs):
40
+ min_pixels: Optional[int]
41
+ max_pixels: Optional[int]
42
+ patch_size: Optional[int]
43
+ temporal_patch_size: Optional[int]
44
+ merge_size: Optional[int]
45
+
46
+
47
+ class Qwen2VLProcessorKwargs(ProcessingKwargs, total=False):
48
+ images_kwargs: Qwen2VLImagesKwargs
49
+ _defaults = {
50
+ "text_kwargs": {
51
+ "padding": False,
52
+ "return_mm_token_type_ids": False,
53
+ },
54
+ }
55
+
56
+
57
+ class Qwen2VLProcessor(ProcessorMixin):
58
+ r"""
59
+ Constructs a Qwen2-VL processor which wraps a Qwen2-VL image processor and a Qwen2 tokenizer into a single processor.
60
+ [`Qwen2VLProcessor`] offers all the functionalities of [`Qwen2VLImageProcessor`] and [`Qwen2TokenizerFast`]. See the
61
+ [`~Qwen2VLProcessor.__call__`] and [`~Qwen2VLProcessor.decode`] for more information.
62
+ Args:
63
+ image_processor ([`Qwen2VLImageProcessor`], *optional*):
64
+ The image processor is a required input.
65
+ tokenizer ([`Qwen2TokenizerFast`], *optional*):
66
+ The tokenizer is a required input.
67
+ video_processor ([`Qwen2VLVideoProcessor`], *optional*):
68
+ The video processor is a required input.
69
+ chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
70
+ in a chat into a tokenizable string.
71
+ """
72
+
73
+ attributes = ["image_processor", "tokenizer", "video_processor"]
74
+ image_processor_class = "AutoImageProcessor"
75
+ video_processor_class = "AutoVideoProcessor"
76
+ tokenizer_class = ("Qwen2Tokenizer", "Qwen2TokenizerFast")
77
+
78
+ def __init__(self, image_processor=None, tokenizer=None, video_processor=None, chat_template=None, **kwargs):
79
+ self.image_token = "<|image_pad|>" if not hasattr(tokenizer, "image_token") else tokenizer.image_token
80
+ self.video_token = "<|video_pad|>" if not hasattr(tokenizer, "video_token") else tokenizer.video_token
81
+ self.image_token_id = (
82
+ tokenizer.image_token_id
83
+ if getattr(tokenizer, "image_token_id", None)
84
+ else tokenizer.convert_tokens_to_ids(self.image_token)
85
+ )
86
+ self.video_token_id = (
87
+ tokenizer.video_token_id
88
+ if getattr(tokenizer, "video_token_id", None)
89
+ else tokenizer.convert_tokens_to_ids(self.video_token)
90
+ )
91
+ super().__init__(image_processor, tokenizer, video_processor, chat_template=chat_template)
92
+
93
+ def __call__(
94
+ self,
95
+ images: ImageInput = None,
96
+ text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
97
+ videos: VideoInput = None,
98
+ **kwargs: Unpack[Qwen2VLProcessorKwargs],
99
+ ) -> BatchFeature:
100
+ """
101
+ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
102
+ and `kwargs` arguments to Qwen2TokenizerFast's [`~Qwen2TokenizerFast.__call__`] if `text` is not `None` to encode
103
+ the text. To prepare the vision inputs, this method forwards the `vision_infos` and `kwrags` arguments to
104
+ Qwen2VLImageProcessor's [`~Qwen2VLImageProcessor.__call__`] if `vision_infos` is not `None`.
105
+
106
+ Args:
107
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
108
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
109
+ tensor. Both channels-first and channels-last formats are supported.
110
+ text (`str`, `list[str]`, `list[list[str]]`):
111
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
112
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
113
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
114
+ videos (`np.ndarray`, `torch.Tensor`, `list[np.ndarray]`, `list[torch.Tensor]`):
115
+ The image or batch of videos to be prepared. Each video can be a 4D NumPy array or PyTorch
116
+ tensor, or a nested list of 3D frames. Both channels-first and channels-last formats are supported.
117
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
118
+ If set, will return tensors of a particular framework. Acceptable values are:
119
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
120
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
121
+ - `'np'`: Return NumPy `np.ndarray` objects.
122
+ - `'jax'`: Return JAX `jnp.ndarray` objects.
123
+
124
+ Returns:
125
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
126
+
127
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
128
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
129
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
130
+ `None`).
131
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
132
+ - **pixel_values_videos** -- Pixel values of videos to be fed to a model. Returned when `videos` is not `None`.
133
+ - **image_grid_thw** -- List of image 3D grid in LLM. Returned when `images` is not `None`.
134
+ - **video_grid_thw** -- List of video 3D grid in LLM. Returned when `videos` is not `None`.
135
+ """
136
+ output_kwargs = self._merge_kwargs(
137
+ Qwen2VLProcessorKwargs,
138
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
139
+ **kwargs,
140
+ )
141
+
142
+ image_inputs = videos_inputs = {}
143
+ if images is not None:
144
+ image_inputs = self.image_processor(images=images, **output_kwargs["images_kwargs"])
145
+ image_grid_thw = image_inputs["image_grid_thw"]
146
+
147
+ if videos is not None:
148
+ videos_inputs = self.video_processor(videos=videos, **output_kwargs["videos_kwargs"])
149
+ video_grid_thw = videos_inputs["video_grid_thw"]
150
+
151
+ if not isinstance(text, list):
152
+ text = [text]
153
+
154
+ text = text.copy() # below lines change text in-place
155
+
156
+ if images is not None:
157
+ merge_length = self.image_processor.merge_size**2
158
+ index = 0
159
+ for i in range(len(text)):
160
+ while self.image_token in text[i]:
161
+ num_image_tokens = image_grid_thw[index].prod() // merge_length
162
+ text[i] = text[i].replace(self.image_token, "<|placeholder|>" * num_image_tokens, 1)
163
+ index += 1
164
+ text[i] = text[i].replace("<|placeholder|>", self.image_token)
165
+
166
+ if videos is not None:
167
+ merge_length = self.video_processor.merge_size**2
168
+ index = 0
169
+ for i in range(len(text)):
170
+ while self.video_token in text[i]:
171
+ num_video_tokens = video_grid_thw[index].prod() // merge_length
172
+ text[i] = text[i].replace(self.video_token, "<|placeholder|>" * num_video_tokens, 1)
173
+ index += 1
174
+ text[i] = text[i].replace("<|placeholder|>", self.video_token)
175
+
176
+ return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
177
+ return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", False)
178
+ text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"], return_tensors=None)
179
+ self._check_special_mm_tokens(text, text_inputs, modalities=["image", "video"])
180
+
181
+ if return_mm_token_type_ids:
182
+ array_ids = np.array(text_inputs["input_ids"])
183
+ mm_token_type_ids = np.zeros_like(text_inputs["input_ids"])
184
+ mm_token_type_ids[array_ids == self.image_token_id] = 1
185
+ text_inputs["mm_token_type_ids"] = mm_token_type_ids.tolist()
186
+
187
+ return BatchFeature(data={**text_inputs, **image_inputs, **videos_inputs}, tensor_type=return_tensors)
188
+
189
+ def _get_num_multimodal_tokens(self, image_sizes=None, video_sizes=None, **kwargs):
190
+ """
191
+ Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
192
+ Args:
193
+ image_sizes (`list[list[int]]`, *optional*):
194
+ The input sizes formatted as (height, width) per each image.
195
+ video_sizes (`list[list[int]]`, *optional*):
196
+ The input sizes formatted as (num_frames, height, width) per each video.
197
+ Returns:
198
+ `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
199
+ input modalities, along with other useful data.
200
+ """
201
+
202
+ vision_data = {}
203
+ if image_sizes is not None:
204
+ images_kwargs = Qwen2VLProcessorKwargs._defaults.get("images_kwargs", {})
205
+ images_kwargs.update(kwargs)
206
+ merge_size = images_kwargs.get("merge_size", None) or self.image_processor.merge_size
207
+
208
+ num_image_patches = [
209
+ self.image_processor.get_number_of_image_patches(*image_size, images_kwargs)
210
+ for image_size in image_sizes
211
+ ]
212
+ num_image_tokens = [(num_patches // merge_size**2) for num_patches in num_image_patches]
213
+ vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
214
+
215
+ if video_sizes is not None:
216
+ videos_kwargs = Qwen2VLProcessorKwargs._defaults.get("videos_kwargs", {})
217
+ videos_kwargs.update(kwargs)
218
+ num_video_patches = [
219
+ self.video_processor.get_number_of_video_patches(*video_size, videos_kwargs)
220
+ for video_size in video_sizes
221
+ ]
222
+ num_video_tokens = [(num_patches // merge_size**2) for num_patches in num_video_patches]
223
+ vision_data["num_video_tokens"] = num_video_tokens
224
+
225
+ return MultiModalData(**vision_data)
226
+
227
+ def batch_decode(self, *args, **kwargs):
228
+ """
229
+ This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
230
+ refer to the docstring of this method for more information.
231
+ """
232
+ return self.tokenizer.batch_decode(*args, **kwargs)
233
+
234
+ def decode(self, *args, **kwargs):
235
+ """
236
+ This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
237
+ the docstring of this method for more information.
238
+ """
239
+ return self.tokenizer.decode(*args, **kwargs)
240
+
241
+ def post_process_image_text_to_text(
242
+ self, generated_outputs, skip_special_tokens=True, clean_up_tokenization_spaces=False, **kwargs
243
+ ):
244
+ """
245
+ Post-process the output of the model to decode the text.
246
+
247
+ Args:
248
+ generated_outputs (`torch.Tensor` or `np.ndarray`):
249
+ The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)`
250
+ or `(sequence_length,)`.
251
+ skip_special_tokens (`bool`, *optional*, defaults to `True`):
252
+ Whether or not to remove special tokens in the output. Argument passed to the tokenizer's `batch_decode` method.
253
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
254
+ Whether or not to clean up the tokenization spaces. Argument passed to the tokenizer's `batch_decode` method.
255
+ **kwargs:
256
+ Additional arguments to be passed to the tokenizer's `batch_decode method`.
257
+
258
+ Returns:
259
+ `list[str]`: The decoded text.
260
+ """
261
+ return self.tokenizer.batch_decode(
262
+ generated_outputs,
263
+ skip_special_tokens=skip_special_tokens,
264
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
265
+ **kwargs,
266
+ )
267
+
268
+ @property
269
+ def model_input_names(self):
270
+ tokenizer_input_names = self.tokenizer.model_input_names
271
+ image_processor_input_names = self.image_processor.model_input_names
272
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
273
+
274
+
275
+ __all__ = ["Qwen2VLProcessor"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen2_vl/video_processing_qwen2_vl.py ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
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
+ """video processor class for Qwen2-VL."""
21
+
22
+ import math
23
+ from typing import Optional, Union
24
+
25
+ from ...image_processing_utils import (
26
+ BatchFeature,
27
+ )
28
+ from ...image_utils import (
29
+ OPENAI_CLIP_MEAN,
30
+ OPENAI_CLIP_STD,
31
+ ChannelDimension,
32
+ SizeDict,
33
+ get_image_size,
34
+ )
35
+ from ...processing_utils import Unpack, VideosKwargs
36
+ from ...utils import (
37
+ TensorType,
38
+ add_start_docstrings,
39
+ is_torch_available,
40
+ is_torchvision_available,
41
+ is_torchvision_v2_available,
42
+ is_vision_available,
43
+ )
44
+ from ...utils.import_utils import requires
45
+ from ...video_processing_utils import (
46
+ BASE_VIDEO_PROCESSOR_DOCSTRING,
47
+ BaseVideoProcessor,
48
+ )
49
+ from ...video_utils import VideoMetadata, group_videos_by_shape, reorder_videos
50
+
51
+
52
+ if is_vision_available():
53
+ from ...image_utils import PILImageResampling
54
+ from .image_processing_qwen2_vl import smart_resize
55
+
56
+ if is_torchvision_available():
57
+ if is_torchvision_v2_available():
58
+ from torchvision.transforms.v2 import functional as F
59
+ else:
60
+ from torchvision.transforms import functional as F
61
+
62
+
63
+ if is_torch_available():
64
+ import torch
65
+
66
+
67
+ class Qwen2VLVideoProcessorInitKwargs(VideosKwargs):
68
+ min_pixels: Optional[int]
69
+ max_pixels: Optional[int]
70
+ patch_size: Optional[int]
71
+ temporal_patch_size: Optional[int]
72
+ merge_size: Optional[int]
73
+ min_frames: Optional[int]
74
+ max_frames: Optional[int]
75
+
76
+
77
+ @add_start_docstrings(
78
+ "Constructs a fast Qwen2-VL image processor that dynamically resizes videos based on the original videos.",
79
+ BASE_VIDEO_PROCESSOR_DOCSTRING,
80
+ """
81
+ min_pixels (`int`, *optional*, defaults to `56 * 56`):
82
+ The min pixels of the image to resize the image.
83
+ max_pixels (`int`, *optional*, defaults to `28 * 28 * 1280`):
84
+ The max pixels of the image to resize the image.
85
+ patch_size (`int`, *optional*, defaults to 14):
86
+ The spacial patch size of the vision encoder.
87
+ temporal_patch_size (`int`, *optional*, defaults to 2):
88
+ The temporal patch size of the vision encoder.
89
+ merge_size (`int`, *optional*, defaults to 2):
90
+ The merge size of the vision encoder to llm encoder.
91
+ min_frames (`int`, *optional*, defaults to 4):
92
+ The minimum number of frames that can be sampled.
93
+ max_frames (`int`, *optional*, defaults to 768):
94
+ The maximum number of frames that can be sampled.
95
+ """,
96
+ )
97
+ @requires(backends=("torchvision",))
98
+ class Qwen2VLVideoProcessor(BaseVideoProcessor):
99
+ resample = PILImageResampling.BICUBIC
100
+ size = {"shortest_edge": 128 * 28 * 28, "longest_edge": 28 * 28 * 768}
101
+ image_mean = OPENAI_CLIP_MEAN
102
+ image_std = OPENAI_CLIP_STD
103
+ do_resize = True
104
+ do_rescale = True
105
+ do_normalize = True
106
+ do_convert_rgb = True
107
+ min_pixels = 128 * 28 * 28
108
+ max_pixels = 28 * 28 * 768
109
+ patch_size = 14
110
+ temporal_patch_size = 2
111
+ merge_size = 2
112
+ min_frames = 4
113
+ max_frames = 768
114
+ do_sample_frames = False # Set to False for BC, recommended to set `True` in new models
115
+ valid_kwargs = Qwen2VLVideoProcessorInitKwargs
116
+ model_input_names = ["pixel_values_videos", "video_grid_thw"]
117
+
118
+ def __init__(self, **kwargs: Unpack[Qwen2VLVideoProcessorInitKwargs]):
119
+ size = kwargs.pop("size", None)
120
+ min_pixels = kwargs.pop("min_pixels", None)
121
+ max_pixels = kwargs.pop("max_pixels", None)
122
+ # backward compatibility: override size with min_pixels and max_pixels if they are provided
123
+ size = self.size if size is None else size
124
+ if min_pixels is not None:
125
+ size["shortest_edge"] = min_pixels
126
+ size.pop("min_pixels", None)
127
+ if max_pixels is not None:
128
+ size["longest_edge"] = max_pixels
129
+ size.pop("max_pixels", None)
130
+ if "shortest_edge" not in size or "longest_edge" not in size:
131
+ raise ValueError("size must contain 'shortest_edge' and 'longest_edge' keys.")
132
+
133
+ super().__init__(size=size, min_pixels=min_pixels, max_pixels=max_pixels, **kwargs)
134
+
135
+ def sample_frames(
136
+ self,
137
+ video: "torch.Tensor",
138
+ frame_factor: int,
139
+ min_frames: int,
140
+ max_frames: int,
141
+ metadata: Optional[Union[VideoMetadata, dict]] = None,
142
+ num_frames: Optional[int] = None,
143
+ fps: Optional[Union[int, float]] = None,
144
+ ):
145
+ """
146
+ Default sampling function which uniformly samples the desired number of frames between 0 and total number of frames.
147
+ If `fps` is passed along with metadata, `fps` frames per second are sampled uniformty. Arguments `num_frames`
148
+ and `fps` are mutually exclusive.
149
+
150
+ Args:
151
+ video (`torch.Tensor`):
152
+ Video that need to be sampled.
153
+ frame_factor (`int`):
154
+ The temporal patch size of the vision encoder. Number of sampled frames will be rounded to be divisible by frame factor.
155
+ min_frames (`int`):
156
+ The minimum number of frames that can be sampled.
157
+ max_frames (`int`):
158
+ The maximum number of frames that can be sampled.
159
+ metadata (`VideoMetadata`, *optional*):
160
+ Metadata of the video containing information about total duration, fps and total number of frames.
161
+ num_frames (`int`, *optional*):
162
+ Maximum number of frames to sample. Defaults to `self.num_frames`.
163
+ fps (`int` or `float`, *optional*):
164
+ Target frames to sample per second. Defaults to `self.fps`.
165
+
166
+ Returns:
167
+ torch.Tensor:
168
+ Sampled video frames.
169
+ """
170
+ if fps is not None and num_frames is not None:
171
+ raise ValueError("`num_frames` and `fps` are mutually exclusive arguments, please use only one!")
172
+
173
+ num_frames = num_frames if num_frames is not None else self.num_frames
174
+ fps = fps if fps is not None else self.fps
175
+ total_num_frames = video.shape[0]
176
+
177
+ # If num_frames is not given but fps is, calculate num_frames from fps
178
+ if num_frames is not None:
179
+ num_frames = round(num_frames / frame_factor) * frame_factor
180
+ elif fps is not None:
181
+ if metadata is None:
182
+ raise ValueError(
183
+ "Asked to sample `fps` frames per second but no video metadata was provided which is required when sampling with `fps`. "
184
+ "Please pass in `VideoMetadata` object or use a fixed `num_frames` per input video"
185
+ )
186
+ max_frames = math.floor(min(max_frames, total_num_frames) / frame_factor) * frame_factor
187
+ num_frames = total_num_frames / metadata["fps"] * fps
188
+ num_frames = min(min(max(num_frames, min_frames), max_frames), total_num_frames)
189
+ num_frames = math.floor(num_frames / frame_factor) * frame_factor
190
+
191
+ if num_frames > total_num_frames:
192
+ raise ValueError(
193
+ f"Video can't be sampled. The inferred `num_frames={num_frames}` exceeds `total_num_frames={total_num_frames}`. "
194
+ "Decrease `num_frames` or `fps` for sampling."
195
+ )
196
+
197
+ if num_frames is not None:
198
+ indices = torch.arange(0, total_num_frames, total_num_frames / num_frames).int()
199
+ else:
200
+ indices = torch.arange(0, total_num_frames).int()
201
+ video = video[indices].contiguous()
202
+
203
+ return video
204
+
205
+ def _preprocess(
206
+ self,
207
+ videos: list["torch.Tensor"],
208
+ video_metadata: Union[list[VideoMetadata], list[dict]],
209
+ do_convert_rgb: bool,
210
+ do_resize: bool,
211
+ size: SizeDict,
212
+ interpolation: Optional["F.InterpolationMode"],
213
+ do_rescale: bool,
214
+ rescale_factor: float,
215
+ do_normalize: bool,
216
+ do_sample_frames: bool,
217
+ image_mean: Optional[Union[float, list[float]]],
218
+ image_std: Optional[Union[float, list[float]]],
219
+ min_pixels: Optional[int] = None,
220
+ max_pixels: Optional[int] = None,
221
+ patch_size: Optional[int] = None,
222
+ temporal_patch_size: Optional[int] = None,
223
+ merge_size: Optional[int] = None,
224
+ fps: Optional[Union[int, float]] = None,
225
+ num_frames: Optional[int] = None,
226
+ min_frames: Optional[int] = None,
227
+ max_frames: Optional[int] = None,
228
+ return_tensors: Optional[Union[str, TensorType]] = None,
229
+ device: Optional["torch.Tensor"] = None,
230
+ **kwargs,
231
+ ):
232
+ if do_sample_frames:
233
+ # Sample video frames
234
+ videos = [
235
+ self.sample_frames(
236
+ video,
237
+ frame_factor=temporal_patch_size,
238
+ min_frames=min_frames,
239
+ max_frames=max_frames,
240
+ metadata=metadata,
241
+ num_frames=num_frames,
242
+ fps=fps,
243
+ )
244
+ for video, metadata in zip(videos, video_metadata)
245
+ ]
246
+
247
+ # We need to sample frames first before moving to device, if `do_sample_frames=True`. Otherwise
248
+ # moving the whole video incurs high GPU mem usage for long videos
249
+ if device is not None:
250
+ videos = [video.to(device) for video in videos]
251
+
252
+ # Group videos by size for batched resizing
253
+ grouped_videos, grouped_videos_index = group_videos_by_shape(videos)
254
+ resized_videos_grouped = {}
255
+ for shape, stacked_videos in grouped_videos.items():
256
+ height, width = get_image_size(stacked_videos[0], channel_dim=ChannelDimension.FIRST)
257
+ resized_height, resized_width = height, width
258
+ if do_resize:
259
+ resized_height, resized_width = smart_resize(
260
+ height,
261
+ width,
262
+ factor=patch_size * merge_size,
263
+ min_pixels=min_pixels,
264
+ max_pixels=max_pixels,
265
+ )
266
+ stacked_videos = self.resize(
267
+ image=stacked_videos,
268
+ size=SizeDict(height=resized_height, width=resized_width),
269
+ interpolation=interpolation,
270
+ )
271
+ resized_videos_grouped[shape] = stacked_videos
272
+ resized_videos = reorder_videos(resized_videos_grouped, grouped_videos_index)
273
+
274
+ # Group videos by size for further processing
275
+ # Needed in case do_resize is False, or resize returns videos with different sizes
276
+ grouped_videos, grouped_videos_index = group_videos_by_shape(resized_videos)
277
+ processed_videos_grouped = {}
278
+ processed_grids = {}
279
+ for shape, stacked_videos in grouped_videos.items():
280
+ resized_height, resized_width = get_image_size(stacked_videos[0], channel_dim=ChannelDimension.FIRST)
281
+
282
+ # Fused rescale and normalize
283
+ stacked_videos = self.rescale_and_normalize(
284
+ stacked_videos, do_rescale, rescale_factor, do_normalize, image_mean, image_std
285
+ )
286
+ patches = stacked_videos
287
+
288
+ # Check that videos have `num_frames` divisible by `temporal_patch_size`
289
+ if patches.shape[1] % temporal_patch_size != 0:
290
+ repeats = patches[:, -1:].repeat(1, self.temporal_patch_size - 1, 1, 1, 1)
291
+ patches = torch.cat([patches, repeats], dim=1)
292
+
293
+ batch_size, grid_t, channel = patches.shape[:3]
294
+ grid_t = grid_t // temporal_patch_size
295
+ grid_h, grid_w = resized_height // patch_size, resized_width // patch_size
296
+
297
+ patches = patches.view(
298
+ batch_size,
299
+ grid_t,
300
+ temporal_patch_size,
301
+ channel,
302
+ grid_h // merge_size,
303
+ merge_size,
304
+ patch_size,
305
+ grid_w // merge_size,
306
+ merge_size,
307
+ patch_size,
308
+ )
309
+ patches = patches.permute(0, 1, 4, 7, 5, 8, 3, 2, 6, 9)
310
+ flatten_patches = patches.reshape(
311
+ batch_size,
312
+ grid_t * grid_h * grid_w,
313
+ channel * temporal_patch_size * patch_size * patch_size,
314
+ )
315
+
316
+ processed_videos_grouped[shape] = flatten_patches
317
+ processed_grids[shape] = [[grid_t, grid_h, grid_w]] * batch_size
318
+
319
+ processed_videos = reorder_videos(processed_videos_grouped, grouped_videos_index)
320
+ processed_grids = reorder_videos(processed_grids, grouped_videos_index)
321
+ pixel_values_videos = torch.cat(processed_videos, dim=0)
322
+ video_grid_thw = torch.tensor(processed_grids)
323
+
324
+ return BatchFeature(
325
+ data={"pixel_values_videos": pixel_values_videos, "video_grid_thw": video_grid_thw},
326
+ tensor_type=return_tensors,
327
+ )
328
+
329
+ def get_num_of_video_patches(self, num_frames: int, height: int, width: int, videos_kwargs=None):
330
+ """
331
+ A utility that returns number of video patches a given video size.
332
+
333
+ Args:
334
+ num_frames (`int`):
335
+ Number of frames in the input video.
336
+ height (`int`):
337
+ Height of the input video.
338
+ width (`int`):
339
+ Width of the input video.
340
+ videos_kwargs (`dict`, *optional*)
341
+ Any kwargs to override defaults of the video processor.
342
+ Returns:
343
+ `Tuple(int, int)`: Number of placeholder tokens required and number of patches per image.
344
+ """
345
+ min_pixels = videos_kwargs.get("min_pixels", None) or self.size["shortest_edge"]
346
+ max_pixels = videos_kwargs.get("max_pixels", None) or self.size["longest_edge"]
347
+ patch_size = videos_kwargs.get("patch_size", None) or self.patch_size
348
+ merge_size = videos_kwargs.get("merge_size", None) or self.merge_size
349
+ temporal_patch_size = videos_kwargs.get("temporal_patch_size", None) or self.temporal_patch_size
350
+
351
+ factor = patch_size * merge_size
352
+ resized_height, resized_width = smart_resize(
353
+ height, width, factor, min_pixels=min_pixels, max_pixels=max_pixels
354
+ )
355
+ grid_h, grid_w = resized_height // patch_size, resized_width // patch_size
356
+ grid_t = num_frames // temporal_patch_size
357
+ return grid_t * grid_h * grid_w
358
+
359
+
360
+ __all__ = ["Qwen2VLVideoProcessor"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen3/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The Qwen Team 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
+ 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_qwen3 import *
22
+ from .modeling_qwen3 import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen3/configuration_qwen3.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Qwen3 model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig, layer_type_validation
18
+ from ...modeling_rope_utils import rope_config_validation
19
+ from ...utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class Qwen3Config(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`Qwen3Model`]. It is used to instantiate a
28
+ Qwen3 model according to the specified arguments, defining the model architecture. Instantiating a configuration
29
+ with the defaults will yield a similar configuration to that of
30
+ Qwen3-8B [Qwen/Qwen3-8B](https://huggingface.co/Qwen/Qwen3-8B).
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+
36
+ Args:
37
+ vocab_size (`int`, *optional*, defaults to 151936):
38
+ Vocabulary size of the Qwen3 model. Defines the number of different tokens that can be represented by the
39
+ `inputs_ids` passed when calling [`Qwen3Model`]
40
+ hidden_size (`int`, *optional*, defaults to 4096):
41
+ Dimension of the hidden representations.
42
+ intermediate_size (`int`, *optional*, defaults to 22016):
43
+ Dimension of the MLP representations.
44
+ num_hidden_layers (`int`, *optional*, defaults to 32):
45
+ Number of hidden layers in the Transformer encoder.
46
+ num_attention_heads (`int`, *optional*, defaults to 32):
47
+ Number of attention heads for each attention layer in the Transformer encoder.
48
+ num_key_value_heads (`int`, *optional*, defaults to 32):
49
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
50
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
51
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
52
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
53
+ by meanpooling all the original heads within that group. For more details, check out [this
54
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`.
55
+ head_dim (`int`, *optional*, defaults to 128):
56
+ The attention head dimension.
57
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
58
+ The non-linear activation function (function or string) in the decoder.
59
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
60
+ The maximum sequence length that this model might ever be used with.
61
+ initializer_range (`float`, *optional*, defaults to 0.02):
62
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
63
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
64
+ The epsilon used by the rms normalization layers.
65
+ use_cache (`bool`, *optional*, defaults to `True`):
66
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
67
+ relevant if `config.is_decoder=True`.
68
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
69
+ Whether the model's input and output word embeddings should be tied.
70
+ rope_theta (`float`, *optional*, defaults to 10000.0):
71
+ The base period of the RoPE embeddings.
72
+ rope_scaling (`Dict`, *optional*):
73
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
74
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
75
+ accordingly.
76
+ Expected contents:
77
+ `rope_type` (`str`):
78
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
79
+ 'llama3'], with 'default' being the original RoPE implementation.
80
+ `factor` (`float`, *optional*):
81
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
82
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
83
+ original maximum pre-trained length.
84
+ `original_max_position_embeddings` (`int`, *optional*):
85
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
86
+ pretraining.
87
+ `attention_factor` (`float`, *optional*):
88
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
89
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
90
+ `factor` field to infer the suggested value.
91
+ `beta_fast` (`float`, *optional*):
92
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
93
+ ramp function. If unspecified, it defaults to 32.
94
+ `beta_slow` (`float`, *optional*):
95
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
96
+ ramp function. If unspecified, it defaults to 1.
97
+ `short_factor` (`list[float]`, *optional*):
98
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
99
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
100
+ size divided by the number of attention heads divided by 2
101
+ `long_factor` (`list[float]`, *optional*):
102
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
103
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
104
+ size divided by the number of attention heads divided by 2
105
+ `low_freq_factor` (`float`, *optional*):
106
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
107
+ `high_freq_factor` (`float`, *optional*):
108
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
109
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
110
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
111
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
112
+ Whether to use sliding window attention.
113
+ sliding_window (`int`, *optional*, defaults to 4096):
114
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
115
+ max_window_layers (`int`, *optional*, defaults to 28):
116
+ The number of layers using full attention. The first `max_window_layers` layers will use full attention, while any
117
+ additional layer afterwards will use SWA (Sliding Window Attention).
118
+ layer_types (`list`, *optional*):
119
+ Attention pattern for each layer.
120
+ attention_dropout (`float`, *optional*, defaults to 0.0):
121
+ The dropout ratio for the attention probabilities.
122
+
123
+ ```python
124
+ >>> from transformers import Qwen3Model, Qwen3Config
125
+
126
+ >>> # Initializing a Qwen3 style configuration
127
+ >>> configuration = Qwen3Config()
128
+
129
+ >>> # Initializing a model from the Qwen3-8B style configuration
130
+ >>> model = Qwen3Model(configuration)
131
+
132
+ >>> # Accessing the model configuration
133
+ >>> configuration = model.config
134
+ ```"""
135
+
136
+ model_type = "qwen3"
137
+ keys_to_ignore_at_inference = ["past_key_values"]
138
+
139
+ # Default tensor parallel plan for base model `Qwen3`
140
+ base_model_tp_plan = {
141
+ "layers.*.self_attn.q_proj": "colwise",
142
+ "layers.*.self_attn.k_proj": "colwise",
143
+ "layers.*.self_attn.v_proj": "colwise",
144
+ "layers.*.self_attn.o_proj": "rowwise",
145
+ "layers.*.mlp.gate_proj": "colwise",
146
+ "layers.*.mlp.up_proj": "colwise",
147
+ "layers.*.mlp.down_proj": "rowwise",
148
+ }
149
+ base_model_pp_plan = {
150
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
151
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
152
+ "norm": (["hidden_states"], ["hidden_states"]),
153
+ }
154
+
155
+ def __init__(
156
+ self,
157
+ vocab_size=151936,
158
+ hidden_size=4096,
159
+ intermediate_size=22016,
160
+ num_hidden_layers=32,
161
+ num_attention_heads=32,
162
+ num_key_value_heads=32,
163
+ head_dim=128,
164
+ hidden_act="silu",
165
+ max_position_embeddings=32768,
166
+ initializer_range=0.02,
167
+ rms_norm_eps=1e-6,
168
+ use_cache=True,
169
+ tie_word_embeddings=False,
170
+ rope_theta=10000.0,
171
+ rope_scaling=None,
172
+ attention_bias=False,
173
+ use_sliding_window=False,
174
+ sliding_window=4096,
175
+ max_window_layers=28,
176
+ layer_types=None,
177
+ attention_dropout=0.0,
178
+ **kwargs,
179
+ ):
180
+ self.vocab_size = vocab_size
181
+ self.max_position_embeddings = max_position_embeddings
182
+ self.hidden_size = hidden_size
183
+ self.intermediate_size = intermediate_size
184
+ self.num_hidden_layers = num_hidden_layers
185
+ self.num_attention_heads = num_attention_heads
186
+ self.use_sliding_window = use_sliding_window
187
+ self.sliding_window = sliding_window if self.use_sliding_window else None
188
+ self.max_window_layers = max_window_layers
189
+
190
+ # for backward compatibility
191
+ if num_key_value_heads is None:
192
+ num_key_value_heads = num_attention_heads
193
+
194
+ self.num_key_value_heads = num_key_value_heads
195
+ self.head_dim = head_dim
196
+ self.hidden_act = hidden_act
197
+ self.initializer_range = initializer_range
198
+ self.rms_norm_eps = rms_norm_eps
199
+ self.use_cache = use_cache
200
+ self.rope_theta = rope_theta
201
+ self.rope_scaling = rope_scaling
202
+ self.attention_bias = attention_bias
203
+ self.attention_dropout = attention_dropout
204
+ # Validate the correctness of rotary position embeddings parameters
205
+ # BC: if there is a 'type' field, move it to 'rope_type'.
206
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
207
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
208
+ rope_config_validation(self)
209
+
210
+ self.layer_types = layer_types
211
+ if self.layer_types is None:
212
+ self.layer_types = [
213
+ "sliding_attention"
214
+ if self.sliding_window is not None and i >= self.max_window_layers
215
+ else "full_attention"
216
+ for i in range(self.num_hidden_layers)
217
+ ]
218
+ layer_type_validation(self.layer_types)
219
+
220
+ super().__init__(
221
+ tie_word_embeddings=tie_word_embeddings,
222
+ **kwargs,
223
+ )
224
+
225
+
226
+ __all__ = ["Qwen3Config"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen3/modeling_qwen3.py ADDED
@@ -0,0 +1,534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/qwen3/modular_qwen3.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_qwen3.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2025 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+
22
+ from typing import Callable, Optional, Union
23
+
24
+ import torch
25
+ from torch import nn
26
+
27
+ from ...activations import ACT2FN
28
+ from ...cache_utils import Cache, DynamicCache
29
+ from ...generation import GenerationMixin
30
+ from ...integrations import use_kernel_forward_from_hub
31
+ from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask
32
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
33
+ from ...modeling_layers import (
34
+ GenericForQuestionAnswering,
35
+ GenericForSequenceClassification,
36
+ GenericForTokenClassification,
37
+ GradientCheckpointingLayer,
38
+ )
39
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
40
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
41
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
42
+ from ...processing_utils import Unpack
43
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
44
+ from ...utils.deprecation import deprecate_kwarg
45
+ from ...utils.generic import check_model_inputs
46
+ from .configuration_qwen3 import Qwen3Config
47
+
48
+
49
+ @use_kernel_forward_from_hub("RMSNorm")
50
+ class Qwen3RMSNorm(nn.Module):
51
+ def __init__(self, hidden_size, eps=1e-6):
52
+ """
53
+ Qwen3RMSNorm is equivalent to T5LayerNorm
54
+ """
55
+ super().__init__()
56
+ self.weight = nn.Parameter(torch.ones(hidden_size))
57
+ self.variance_epsilon = eps
58
+
59
+ def forward(self, hidden_states):
60
+ input_dtype = hidden_states.dtype
61
+ hidden_states = hidden_states.to(torch.float32)
62
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
63
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
64
+ return self.weight * hidden_states.to(input_dtype)
65
+
66
+ def extra_repr(self):
67
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
68
+
69
+
70
+ class Qwen3MLP(nn.Module):
71
+ def __init__(self, config):
72
+ super().__init__()
73
+ self.config = config
74
+ self.hidden_size = config.hidden_size
75
+ self.intermediate_size = config.intermediate_size
76
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
77
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
78
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
79
+ self.act_fn = ACT2FN[config.hidden_act]
80
+
81
+ def forward(self, x):
82
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
83
+ return down_proj
84
+
85
+
86
+ def rotate_half(x):
87
+ """Rotates half the hidden dims of the input."""
88
+ x1 = x[..., : x.shape[-1] // 2]
89
+ x2 = x[..., x.shape[-1] // 2 :]
90
+ return torch.cat((-x2, x1), dim=-1)
91
+
92
+
93
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
94
+ """Applies Rotary Position Embedding to the query and key tensors.
95
+
96
+ Args:
97
+ q (`torch.Tensor`): The query tensor.
98
+ k (`torch.Tensor`): The key tensor.
99
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
100
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
101
+ position_ids (`torch.Tensor`, *optional*):
102
+ Deprecated and unused.
103
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
104
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
105
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
106
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
107
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
108
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
109
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
110
+ Returns:
111
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
112
+ """
113
+ cos = cos.unsqueeze(unsqueeze_dim)
114
+ sin = sin.unsqueeze(unsqueeze_dim)
115
+ q_embed = (q * cos) + (rotate_half(q) * sin)
116
+ k_embed = (k * cos) + (rotate_half(k) * sin)
117
+ return q_embed, k_embed
118
+
119
+
120
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
121
+ """
122
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
123
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
124
+ """
125
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
126
+ if n_rep == 1:
127
+ return hidden_states
128
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
129
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
130
+
131
+
132
+ def eager_attention_forward(
133
+ module: nn.Module,
134
+ query: torch.Tensor,
135
+ key: torch.Tensor,
136
+ value: torch.Tensor,
137
+ attention_mask: Optional[torch.Tensor],
138
+ scaling: float,
139
+ dropout: float = 0.0,
140
+ **kwargs: Unpack[TransformersKwargs],
141
+ ):
142
+ key_states = repeat_kv(key, module.num_key_value_groups)
143
+ value_states = repeat_kv(value, module.num_key_value_groups)
144
+
145
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
146
+ if attention_mask is not None:
147
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
148
+ attn_weights = attn_weights + causal_mask
149
+
150
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
151
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
152
+ attn_output = torch.matmul(attn_weights, value_states)
153
+ attn_output = attn_output.transpose(1, 2).contiguous()
154
+
155
+ return attn_output, attn_weights
156
+
157
+
158
+ class Qwen3Attention(nn.Module):
159
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
160
+
161
+ def __init__(self, config: Qwen3Config, layer_idx: int):
162
+ super().__init__()
163
+ self.config = config
164
+ self.layer_idx = layer_idx
165
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
166
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
167
+ self.scaling = self.head_dim**-0.5
168
+ self.attention_dropout = config.attention_dropout
169
+ self.is_causal = True
170
+
171
+ self.q_proj = nn.Linear(
172
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
173
+ )
174
+ self.k_proj = nn.Linear(
175
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
176
+ )
177
+ self.v_proj = nn.Linear(
178
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
179
+ )
180
+ self.o_proj = nn.Linear(
181
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
182
+ )
183
+ self.q_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps) # unlike olmo, only on the head dim!
184
+ self.k_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps) # thus post q_norm does not need reshape
185
+ self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None
186
+
187
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
188
+ def forward(
189
+ self,
190
+ hidden_states: torch.Tensor,
191
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
192
+ attention_mask: Optional[torch.Tensor],
193
+ past_key_values: Optional[Cache] = None,
194
+ cache_position: Optional[torch.LongTensor] = None,
195
+ **kwargs: Unpack[FlashAttentionKwargs],
196
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
197
+ input_shape = hidden_states.shape[:-1]
198
+ hidden_shape = (*input_shape, -1, self.head_dim)
199
+
200
+ query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
201
+ key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
202
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
203
+
204
+ cos, sin = position_embeddings
205
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
206
+
207
+ if past_key_values is not None:
208
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
209
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
210
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
211
+
212
+ attention_interface: Callable = eager_attention_forward
213
+ if self.config._attn_implementation != "eager":
214
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
215
+
216
+ attn_output, attn_weights = attention_interface(
217
+ self,
218
+ query_states,
219
+ key_states,
220
+ value_states,
221
+ attention_mask,
222
+ dropout=0.0 if not self.training else self.attention_dropout,
223
+ scaling=self.scaling,
224
+ sliding_window=self.sliding_window, # diff with Llama
225
+ **kwargs,
226
+ )
227
+
228
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
229
+ attn_output = self.o_proj(attn_output)
230
+ return attn_output, attn_weights
231
+
232
+
233
+ class Qwen3DecoderLayer(GradientCheckpointingLayer):
234
+ def __init__(self, config: Qwen3Config, layer_idx: int):
235
+ super().__init__()
236
+ self.hidden_size = config.hidden_size
237
+
238
+ self.self_attn = Qwen3Attention(config=config, layer_idx=layer_idx)
239
+
240
+ self.mlp = Qwen3MLP(config)
241
+ self.input_layernorm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
242
+ self.post_attention_layernorm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
243
+ self.attention_type = config.layer_types[layer_idx]
244
+
245
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
246
+ def forward(
247
+ self,
248
+ hidden_states: torch.Tensor,
249
+ attention_mask: Optional[torch.Tensor] = None,
250
+ position_ids: Optional[torch.LongTensor] = None,
251
+ past_key_values: Optional[Cache] = None,
252
+ use_cache: Optional[bool] = False,
253
+ cache_position: Optional[torch.LongTensor] = None,
254
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
255
+ **kwargs: Unpack[TransformersKwargs],
256
+ ) -> torch.Tensor:
257
+ residual = hidden_states
258
+ hidden_states = self.input_layernorm(hidden_states)
259
+ # Self Attention
260
+ hidden_states, _ = self.self_attn(
261
+ hidden_states=hidden_states,
262
+ attention_mask=attention_mask,
263
+ position_ids=position_ids,
264
+ past_key_values=past_key_values,
265
+ use_cache=use_cache,
266
+ cache_position=cache_position,
267
+ position_embeddings=position_embeddings,
268
+ **kwargs,
269
+ )
270
+ hidden_states = residual + hidden_states
271
+
272
+ # Fully Connected
273
+ residual = hidden_states
274
+ hidden_states = self.post_attention_layernorm(hidden_states)
275
+ hidden_states = self.mlp(hidden_states)
276
+ hidden_states = residual + hidden_states
277
+ return hidden_states
278
+
279
+
280
+ @auto_docstring
281
+ class Qwen3PreTrainedModel(PreTrainedModel):
282
+ config: Qwen3Config
283
+ base_model_prefix = "model"
284
+ supports_gradient_checkpointing = True
285
+ _no_split_modules = ["Qwen3DecoderLayer"]
286
+ _skip_keys_device_placement = ["past_key_values"]
287
+ _supports_flash_attn = True
288
+ _supports_sdpa = True
289
+ _supports_flex_attn = True
290
+
291
+ _can_compile_fullgraph = True
292
+ _supports_attention_backend = True
293
+ _can_record_outputs = {
294
+ "hidden_states": Qwen3DecoderLayer,
295
+ "attentions": Qwen3Attention,
296
+ }
297
+
298
+
299
+ class Qwen3RotaryEmbedding(nn.Module):
300
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
301
+
302
+ def __init__(self, config: Qwen3Config, device=None):
303
+ super().__init__()
304
+ # BC: "rope_type" was originally "type"
305
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
306
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
307
+ else:
308
+ self.rope_type = "default"
309
+ self.max_seq_len_cached = config.max_position_embeddings
310
+ self.original_max_seq_len = config.max_position_embeddings
311
+
312
+ self.config = config
313
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
314
+
315
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
316
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
317
+ self.original_inv_freq = self.inv_freq
318
+
319
+ @torch.no_grad()
320
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
321
+ def forward(self, x, position_ids):
322
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
323
+ position_ids_expanded = position_ids[:, None, :].float()
324
+
325
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
326
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
327
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
328
+ emb = torch.cat((freqs, freqs), dim=-1)
329
+ cos = emb.cos() * self.attention_scaling
330
+ sin = emb.sin() * self.attention_scaling
331
+
332
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
333
+
334
+
335
+ @auto_docstring
336
+ class Qwen3Model(Qwen3PreTrainedModel):
337
+ def __init__(self, config: Qwen3Config):
338
+ super().__init__(config)
339
+ self.padding_idx = config.pad_token_id
340
+ self.vocab_size = config.vocab_size
341
+
342
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
343
+ self.layers = nn.ModuleList(
344
+ [Qwen3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
345
+ )
346
+ self.norm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
347
+ self.rotary_emb = Qwen3RotaryEmbedding(config=config)
348
+ self.gradient_checkpointing = False
349
+ self.has_sliding_layers = "sliding_attention" in self.config.layer_types
350
+
351
+ # Initialize weights and apply final processing
352
+ self.post_init()
353
+
354
+ @check_model_inputs
355
+ @auto_docstring
356
+ def forward(
357
+ self,
358
+ input_ids: Optional[torch.LongTensor] = None,
359
+ attention_mask: Optional[torch.Tensor] = None,
360
+ position_ids: Optional[torch.LongTensor] = None,
361
+ past_key_values: Optional[Cache] = None,
362
+ inputs_embeds: Optional[torch.FloatTensor] = None,
363
+ use_cache: Optional[bool] = None,
364
+ cache_position: Optional[torch.LongTensor] = None,
365
+ **kwargs: Unpack[TransformersKwargs],
366
+ ) -> BaseModelOutputWithPast:
367
+ if (input_ids is None) ^ (inputs_embeds is not None):
368
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
369
+
370
+ if inputs_embeds is None:
371
+ inputs_embeds = self.embed_tokens(input_ids)
372
+
373
+ if use_cache and past_key_values is None:
374
+ past_key_values = DynamicCache(config=self.config)
375
+
376
+ if cache_position is None:
377
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
378
+ cache_position = torch.arange(
379
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
380
+ )
381
+
382
+ if position_ids is None:
383
+ position_ids = cache_position.unsqueeze(0)
384
+
385
+ # It may already have been prepared by e.g. `generate`
386
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
387
+ # Prepare mask arguments
388
+ mask_kwargs = {
389
+ "config": self.config,
390
+ "input_embeds": inputs_embeds,
391
+ "attention_mask": attention_mask,
392
+ "cache_position": cache_position,
393
+ "past_key_values": past_key_values,
394
+ "position_ids": position_ids,
395
+ }
396
+ # Create the masks
397
+ causal_mask_mapping = {
398
+ "full_attention": create_causal_mask(**mask_kwargs),
399
+ }
400
+ # The sliding window alternating layers are not always activated depending on the config
401
+ if self.has_sliding_layers:
402
+ causal_mask_mapping["sliding_attention"] = create_sliding_window_causal_mask(**mask_kwargs)
403
+
404
+ hidden_states = inputs_embeds
405
+
406
+ # create position embeddings to be shared across the decoder layers
407
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
408
+
409
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
410
+ hidden_states = decoder_layer(
411
+ hidden_states,
412
+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],
413
+ position_ids=position_ids,
414
+ past_key_values=past_key_values,
415
+ use_cache=use_cache,
416
+ cache_position=cache_position,
417
+ position_embeddings=position_embeddings,
418
+ **kwargs,
419
+ )
420
+
421
+ hidden_states = self.norm(hidden_states)
422
+ return BaseModelOutputWithPast(
423
+ last_hidden_state=hidden_states,
424
+ past_key_values=past_key_values if use_cache else None,
425
+ )
426
+
427
+
428
+ @auto_docstring
429
+ class Qwen3ForCausalLM(Qwen3PreTrainedModel, GenerationMixin):
430
+ _tied_weights_keys = ["lm_head.weight"]
431
+ _tp_plan = {"lm_head": "colwise_rep"}
432
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
433
+
434
+ def __init__(self, config):
435
+ super().__init__(config)
436
+ self.model = Qwen3Model(config)
437
+ self.vocab_size = config.vocab_size
438
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
439
+
440
+ # Initialize weights and apply final processing
441
+ self.post_init()
442
+
443
+ def set_decoder(self, decoder):
444
+ self.model = decoder
445
+
446
+ def get_decoder(self):
447
+ return self.model
448
+
449
+ @can_return_tuple
450
+ @auto_docstring
451
+ def forward(
452
+ self,
453
+ input_ids: Optional[torch.LongTensor] = None,
454
+ attention_mask: Optional[torch.Tensor] = None,
455
+ position_ids: Optional[torch.LongTensor] = None,
456
+ past_key_values: Optional[Cache] = None,
457
+ inputs_embeds: Optional[torch.FloatTensor] = None,
458
+ labels: Optional[torch.LongTensor] = None,
459
+ use_cache: Optional[bool] = None,
460
+ cache_position: Optional[torch.LongTensor] = None,
461
+ logits_to_keep: Union[int, torch.Tensor] = 0,
462
+ **kwargs: Unpack[TransformersKwargs],
463
+ ) -> CausalLMOutputWithPast:
464
+ r"""
465
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
466
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
467
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
468
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
469
+
470
+ Example:
471
+
472
+ ```python
473
+ >>> from transformers import AutoTokenizer, Qwen3ForCausalLM
474
+
475
+ >>> model = Qwen3ForCausalLM.from_pretrained("Qwen/Qwen3-8B")
476
+ >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-8B")
477
+
478
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
479
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
480
+
481
+ >>> # Generate
482
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
483
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
484
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
485
+ ```"""
486
+ outputs: BaseModelOutputWithPast = self.model(
487
+ input_ids=input_ids,
488
+ attention_mask=attention_mask,
489
+ position_ids=position_ids,
490
+ past_key_values=past_key_values,
491
+ inputs_embeds=inputs_embeds,
492
+ use_cache=use_cache,
493
+ cache_position=cache_position,
494
+ **kwargs,
495
+ )
496
+
497
+ hidden_states = outputs.last_hidden_state
498
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
499
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
500
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
501
+
502
+ loss = None
503
+ if labels is not None:
504
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
505
+
506
+ return CausalLMOutputWithPast(
507
+ loss=loss,
508
+ logits=logits,
509
+ past_key_values=outputs.past_key_values,
510
+ hidden_states=outputs.hidden_states,
511
+ attentions=outputs.attentions,
512
+ )
513
+
514
+
515
+ class Qwen3ForSequenceClassification(GenericForSequenceClassification, Qwen3PreTrainedModel):
516
+ pass
517
+
518
+
519
+ class Qwen3ForTokenClassification(GenericForTokenClassification, Qwen3PreTrainedModel):
520
+ pass
521
+
522
+
523
+ class Qwen3ForQuestionAnswering(GenericForQuestionAnswering, Qwen3PreTrainedModel):
524
+ base_model_prefix = "transformer" # For BC, where `transformer` was used instead of `model`
525
+
526
+
527
+ __all__ = [
528
+ "Qwen3ForCausalLM",
529
+ "Qwen3ForQuestionAnswering",
530
+ "Qwen3PreTrainedModel",
531
+ "Qwen3Model",
532
+ "Qwen3ForSequenceClassification",
533
+ "Qwen3ForTokenClassification",
534
+ ]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen3/modular_qwen3.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch Qwen3 model."""
16
+
17
+ from typing import Callable, Optional
18
+
19
+ import torch
20
+
21
+ from ...cache_utils import Cache
22
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
23
+ from ...modeling_outputs import CausalLMOutputWithPast
24
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
25
+ from ...processing_utils import Unpack
26
+ from ...utils import TransformersKwargs, logging
27
+ from ...utils.deprecation import deprecate_kwarg
28
+ from ..gemma.modeling_gemma import GemmaMLP
29
+ from ..llama.modeling_llama import (
30
+ LlamaAttention,
31
+ )
32
+ from ..qwen2.modeling_qwen2 import (
33
+ Qwen2DecoderLayer,
34
+ Qwen2ForCausalLM,
35
+ Qwen2ForQuestionAnswering,
36
+ Qwen2ForSequenceClassification,
37
+ Qwen2ForTokenClassification,
38
+ Qwen2Model,
39
+ Qwen2PreTrainedModel,
40
+ Qwen2RMSNorm,
41
+ apply_rotary_pos_emb,
42
+ eager_attention_forward,
43
+ )
44
+ from .configuration_qwen3 import Qwen3Config
45
+
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+ _CHECKPOINT_FOR_DOC = "Qwen/Qwen3-8B"
50
+
51
+
52
+ class Qwen3RMSNorm(Qwen2RMSNorm):
53
+ pass
54
+
55
+
56
+ class Qwen3MLP(GemmaMLP):
57
+ pass
58
+
59
+
60
+ class Qwen3Attention(LlamaAttention):
61
+ def __init__(self, config: Qwen3Config, layer_idx: int):
62
+ super().__init__(config, layer_idx)
63
+ self.q_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps) # unlike olmo, only on the head dim!
64
+ self.k_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps) # thus post q_norm does not need reshape
65
+ self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None
66
+
67
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
68
+ def forward(
69
+ self,
70
+ hidden_states: torch.Tensor,
71
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
72
+ attention_mask: Optional[torch.Tensor],
73
+ past_key_values: Optional[Cache] = None,
74
+ cache_position: Optional[torch.LongTensor] = None,
75
+ **kwargs: Unpack[FlashAttentionKwargs],
76
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
77
+ input_shape = hidden_states.shape[:-1]
78
+ hidden_shape = (*input_shape, -1, self.head_dim)
79
+
80
+ query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
81
+ key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
82
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
83
+
84
+ cos, sin = position_embeddings
85
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
86
+
87
+ if past_key_values is not None:
88
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
89
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
90
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
91
+
92
+ attention_interface: Callable = eager_attention_forward
93
+ if self.config._attn_implementation != "eager":
94
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
95
+
96
+ attn_output, attn_weights = attention_interface(
97
+ self,
98
+ query_states,
99
+ key_states,
100
+ value_states,
101
+ attention_mask,
102
+ dropout=0.0 if not self.training else self.attention_dropout,
103
+ scaling=self.scaling,
104
+ sliding_window=self.sliding_window, # diff with Llama
105
+ **kwargs,
106
+ )
107
+
108
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
109
+ attn_output = self.o_proj(attn_output)
110
+ return attn_output, attn_weights
111
+
112
+
113
+ class Qwen3DecoderLayer(Qwen2DecoderLayer):
114
+ pass
115
+
116
+
117
+ class Qwen3PreTrainedModel(Qwen2PreTrainedModel):
118
+ pass
119
+
120
+
121
+ class Qwen3Model(Qwen2Model):
122
+ pass
123
+
124
+
125
+ class Qwen3ForCausalLM(Qwen2ForCausalLM):
126
+ def forward(
127
+ self,
128
+ **super_kwargs: Unpack[TransformersKwargs],
129
+ ) -> CausalLMOutputWithPast:
130
+ r"""
131
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
132
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
133
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
134
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
135
+
136
+ Example:
137
+
138
+ ```python
139
+ >>> from transformers import AutoTokenizer, Qwen3ForCausalLM
140
+
141
+ >>> model = Qwen3ForCausalLM.from_pretrained("Qwen/Qwen3-8B")
142
+ >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-8B")
143
+
144
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
145
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
146
+
147
+ >>> # Generate
148
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
149
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
150
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
151
+ ```"""
152
+ return super().forward(**super_kwargs)
153
+
154
+
155
+ class Qwen3ForSequenceClassification(Qwen2ForSequenceClassification):
156
+ pass
157
+
158
+
159
+ class Qwen3ForTokenClassification(Qwen2ForTokenClassification):
160
+ pass
161
+
162
+
163
+ class Qwen3ForQuestionAnswering(Qwen2ForQuestionAnswering):
164
+ pass
165
+
166
+
167
+ __all__ = [
168
+ "Qwen3ForCausalLM",
169
+ "Qwen3ForQuestionAnswering",
170
+ "Qwen3PreTrainedModel",
171
+ "Qwen3Model",
172
+ "Qwen3ForSequenceClassification",
173
+ "Qwen3ForTokenClassification",
174
+ ]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen3_moe/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_qwen3_moe import *
22
+ from .modeling_qwen3_moe import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen3_moe/configuration_qwen3_moe.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Qwen3MoE model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...modeling_rope_utils import rope_config_validation
19
+ from ...utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class Qwen3MoeConfig(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`Qwen3MoeModel`]. It is used to instantiate a
28
+ Qwen3MoE model according to the specified arguments, defining the model architecture. Instantiating a configuration
29
+ with the defaults will yield a similar configuration to that of [Qwen/Qwen3-15B-A2B](https://huggingface.co/Qwen/Qwen3-15B-A2B).
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 151936):
37
+ Vocabulary size of the Qwen3MoE model. Defines the number of different tokens that can be represented by the
38
+ `inputs_ids` passed when calling [`Qwen3MoeModel`]
39
+ hidden_size (`int`, *optional*, defaults to 2048):
40
+ Dimension of the hidden representations.
41
+ intermediate_size (`int`, *optional*, defaults to 6144):
42
+ Dimension of the MLP representations.
43
+ num_hidden_layers (`int`, *optional*, defaults to 24):
44
+ Number of hidden layers in the Transformer encoder.
45
+ num_attention_heads (`int`, *optional*, defaults to 32):
46
+ Number of attention heads for each attention layer in the Transformer encoder.
47
+ num_key_value_heads (`int`, *optional*, defaults to 4):
48
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
49
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
50
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
51
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
52
+ by meanpooling all the original heads within that group. For more details, check out [this
53
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`.
54
+
55
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
56
+ The non-linear activation function (function or string) in the decoder.
57
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
58
+ The maximum sequence length that this model might ever be used with.
59
+ initializer_range (`float`, *optional*, defaults to 0.02):
60
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
61
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
62
+ The epsilon used by the rms normalization layers.
63
+ use_cache (`bool`, *optional*, defaults to `True`):
64
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
65
+ relevant if `config.is_decoder=True`.
66
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
67
+ Whether the model's input and output word embeddings should be tied.
68
+ rope_theta (`float`, *optional*, defaults to 10000.0):
69
+ The base period of the RoPE embeddings.
70
+ rope_scaling (`Dict`, *optional*):
71
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
72
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
73
+ accordingly.
74
+ Expected contents:
75
+ `rope_type` (`str`):
76
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
77
+ 'llama3'], with 'default' being the original RoPE implementation.
78
+ `factor` (`float`, *optional*):
79
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
80
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
81
+ original maximum pre-trained length.
82
+ `original_max_position_embeddings` (`int`, *optional*):
83
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
84
+ pretraining.
85
+ `attention_factor` (`float`, *optional*):
86
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
87
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
88
+ `factor` field to infer the suggested value.
89
+ `beta_fast` (`float`, *optional*):
90
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
91
+ ramp function. If unspecified, it defaults to 32.
92
+ `beta_slow` (`float`, *optional*):
93
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
94
+ ramp function. If unspecified, it defaults to 1.
95
+ `short_factor` (`list[float]`, *optional*):
96
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
97
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
98
+ size divided by the number of attention heads divided by 2
99
+ `long_factor` (`list[float]`, *optional*):
100
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
101
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
102
+ size divided by the number of attention heads divided by 2
103
+ `low_freq_factor` (`float`, *optional*):
104
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
105
+ `high_freq_factor` (`float`, *optional*):
106
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
107
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
108
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
109
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
110
+ Whether to use sliding window attention.
111
+ sliding_window (`int`, *optional*, defaults to 4096):
112
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
113
+ attention_dropout (`float`, *optional*, defaults to 0.0):
114
+ The dropout ratio for the attention probabilities.
115
+ decoder_sparse_step (`int`, *optional*, defaults to 1):
116
+ The frequency of the MoE layer.
117
+ moe_intermediate_size (`int`, *optional*, defaults to 768):
118
+ Intermediate size of the routed expert.
119
+ num_experts_per_tok (`int`, *optional*, defaults to 8):
120
+ Number of selected experts.
121
+ num_experts (`int`, *optional*, defaults to 128):
122
+ Number of routed experts.
123
+ norm_topk_prob (`bool`, *optional*, defaults to `False`):
124
+ Whether to normalize the topk probabilities.
125
+ output_router_logits (`bool`, *optional*, defaults to `False`):
126
+ Whether or not the router logits should be returned by the model. Enabling this will also
127
+ allow the model to output the auxiliary loss, including load balancing loss and router z-loss.
128
+ router_aux_loss_coef (`float`, *optional*, defaults to 0.001):
129
+ The aux loss factor for the total loss.
130
+ mlp_only_layers (`list[int]`, *optional*, defaults to `[]`):
131
+ Indicate which layers use Qwen3MoeMLP rather than Qwen3MoeSparseMoeBlock
132
+ The list contains layer index, from 0 to num_layers-1 if we have num_layers layers
133
+ If `mlp_only_layers` is empty, `decoder_sparse_step` is used to determine the sparsity.
134
+
135
+ ```python
136
+ >>> from transformers import Qwen3MoeModel, Qwen3MoeConfig
137
+
138
+ >>> # Initializing a Qwen3MoE style configuration
139
+ >>> configuration = Qwen3MoeConfig()
140
+
141
+ >>> # Initializing a model from the Qwen3-15B-A2B" style configuration
142
+ >>> model = Qwen3MoeModel(configuration)
143
+
144
+ >>> # Accessing the model configuration
145
+ >>> configuration = model.config
146
+ ```"""
147
+
148
+ model_type = "qwen3_moe"
149
+ keys_to_ignore_at_inference = ["past_key_values"]
150
+
151
+ # Default tensor parallel plan for base model `Qwen3Moe`
152
+ base_model_tp_plan = {
153
+ "layers.*.self_attn.q_proj": "colwise",
154
+ "layers.*.self_attn.k_proj": "colwise",
155
+ "layers.*.self_attn.v_proj": "colwise",
156
+ "layers.*.self_attn.o_proj": "rowwise",
157
+ "layers.*.mlp.experts.*.gate_proj": "colwise",
158
+ "layers.*.mlp.experts.*.up_proj": "colwise",
159
+ "layers.*.mlp.experts.*.down_proj": "rowwise",
160
+ "layers.*.mlp.gate_proj": "colwise",
161
+ "layers.*.mlp.up_proj": "colwise",
162
+ "layers.*.mlp.down_proj": "rowwise",
163
+ }
164
+ base_model_pp_plan = {
165
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
166
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
167
+ "norm": (["hidden_states"], ["hidden_states"]),
168
+ }
169
+
170
+ def __init__(
171
+ self,
172
+ vocab_size=151936,
173
+ hidden_size=2048,
174
+ intermediate_size=6144,
175
+ num_hidden_layers=24,
176
+ num_attention_heads=32,
177
+ num_key_value_heads=4,
178
+ hidden_act="silu",
179
+ max_position_embeddings=32768,
180
+ initializer_range=0.02,
181
+ rms_norm_eps=1e-6,
182
+ use_cache=True,
183
+ tie_word_embeddings=False,
184
+ rope_theta=10000.0,
185
+ rope_scaling=None,
186
+ attention_bias=False,
187
+ use_sliding_window=False,
188
+ sliding_window=4096,
189
+ attention_dropout=0.0,
190
+ decoder_sparse_step=1,
191
+ moe_intermediate_size=768,
192
+ num_experts_per_tok=8,
193
+ num_experts=128,
194
+ norm_topk_prob=False,
195
+ output_router_logits=False,
196
+ router_aux_loss_coef=0.001,
197
+ mlp_only_layers=None,
198
+ **kwargs,
199
+ ):
200
+ self.vocab_size = vocab_size
201
+ self.max_position_embeddings = max_position_embeddings
202
+ self.hidden_size = hidden_size
203
+ self.intermediate_size = intermediate_size
204
+ self.num_hidden_layers = num_hidden_layers
205
+ self.num_attention_heads = num_attention_heads
206
+ self.use_sliding_window = use_sliding_window
207
+ self.sliding_window = sliding_window if use_sliding_window else None
208
+
209
+ self.num_key_value_heads = num_key_value_heads
210
+ self.hidden_act = hidden_act
211
+ self.initializer_range = initializer_range
212
+ self.rms_norm_eps = rms_norm_eps
213
+ self.use_cache = use_cache
214
+ self.rope_theta = rope_theta
215
+ self.rope_scaling = rope_scaling
216
+ self.attention_bias = attention_bias
217
+ self.attention_dropout = attention_dropout
218
+ # Validate the correctness of rotary position embeddings parameters
219
+ # BC: if there is a 'type' field, move it to 'rope_type'.
220
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
221
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
222
+ rope_config_validation(self)
223
+
224
+ # MoE arguments
225
+ self.decoder_sparse_step = decoder_sparse_step
226
+ self.moe_intermediate_size = moe_intermediate_size
227
+ self.num_experts_per_tok = num_experts_per_tok
228
+ self.num_experts = num_experts
229
+ self.norm_topk_prob = norm_topk_prob
230
+ self.output_router_logits = output_router_logits
231
+ self.router_aux_loss_coef = router_aux_loss_coef
232
+ self.mlp_only_layers = [] if mlp_only_layers is None else mlp_only_layers
233
+
234
+ super().__init__(
235
+ tie_word_embeddings=tie_word_embeddings,
236
+ **kwargs,
237
+ )
238
+
239
+
240
+ __all__ = ["Qwen3MoeConfig"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen3_moe/modeling_qwen3_moe.py ADDED
@@ -0,0 +1,718 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/qwen3_moe/modular_qwen3_moe.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_qwen3_moe.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2025 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+
22
+ from typing import Callable, Optional, Union
23
+
24
+ import torch
25
+ import torch.nn.functional as F
26
+ from torch import nn
27
+
28
+ from ...activations import ACT2FN
29
+ from ...cache_utils import Cache, DynamicCache
30
+ from ...generation import GenerationMixin
31
+ from ...integrations import use_kernel_forward_from_hub
32
+ from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask
33
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
34
+ from ...modeling_layers import (
35
+ GenericForQuestionAnswering,
36
+ GenericForSequenceClassification,
37
+ GenericForTokenClassification,
38
+ GradientCheckpointingLayer,
39
+ )
40
+ from ...modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
41
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
42
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
43
+ from ...processing_utils import Unpack
44
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
45
+ from ...utils.deprecation import deprecate_kwarg
46
+ from ...utils.generic import OutputRecorder, check_model_inputs
47
+ from .configuration_qwen3_moe import Qwen3MoeConfig
48
+
49
+
50
+ def rotate_half(x):
51
+ """Rotates half the hidden dims of the input."""
52
+ x1 = x[..., : x.shape[-1] // 2]
53
+ x2 = x[..., x.shape[-1] // 2 :]
54
+ return torch.cat((-x2, x1), dim=-1)
55
+
56
+
57
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
58
+ """Applies Rotary Position Embedding to the query and key tensors.
59
+
60
+ Args:
61
+ q (`torch.Tensor`): The query tensor.
62
+ k (`torch.Tensor`): The key tensor.
63
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
64
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
65
+ position_ids (`torch.Tensor`, *optional*):
66
+ Deprecated and unused.
67
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
68
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
69
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
70
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
71
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
72
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
73
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
74
+ Returns:
75
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
76
+ """
77
+ cos = cos.unsqueeze(unsqueeze_dim)
78
+ sin = sin.unsqueeze(unsqueeze_dim)
79
+ q_embed = (q * cos) + (rotate_half(q) * sin)
80
+ k_embed = (k * cos) + (rotate_half(k) * sin)
81
+ return q_embed, k_embed
82
+
83
+
84
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
85
+ """
86
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
87
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
88
+ """
89
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
90
+ if n_rep == 1:
91
+ return hidden_states
92
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
93
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
94
+
95
+
96
+ def eager_attention_forward(
97
+ module: nn.Module,
98
+ query: torch.Tensor,
99
+ key: torch.Tensor,
100
+ value: torch.Tensor,
101
+ attention_mask: Optional[torch.Tensor],
102
+ scaling: float,
103
+ dropout: float = 0.0,
104
+ **kwargs: Unpack[TransformersKwargs],
105
+ ):
106
+ key_states = repeat_kv(key, module.num_key_value_groups)
107
+ value_states = repeat_kv(value, module.num_key_value_groups)
108
+
109
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
110
+ if attention_mask is not None:
111
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
112
+ attn_weights = attn_weights + causal_mask
113
+
114
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
115
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
116
+ attn_output = torch.matmul(attn_weights, value_states)
117
+ attn_output = attn_output.transpose(1, 2).contiguous()
118
+
119
+ return attn_output, attn_weights
120
+
121
+
122
+ class Qwen3MoeAttention(nn.Module):
123
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
124
+
125
+ def __init__(self, config: Qwen3MoeConfig, layer_idx: int):
126
+ super().__init__()
127
+ self.config = config
128
+ self.layer_idx = layer_idx
129
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
130
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
131
+ self.scaling = self.head_dim**-0.5
132
+ self.attention_dropout = config.attention_dropout
133
+ self.is_causal = True
134
+
135
+ self.q_proj = nn.Linear(
136
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
137
+ )
138
+ self.k_proj = nn.Linear(
139
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
140
+ )
141
+ self.v_proj = nn.Linear(
142
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
143
+ )
144
+ self.o_proj = nn.Linear(
145
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
146
+ )
147
+ self.q_norm = Qwen3MoeRMSNorm(self.head_dim, eps=config.rms_norm_eps) # unlike olmo, only on the head dim!
148
+ self.k_norm = Qwen3MoeRMSNorm(self.head_dim, eps=config.rms_norm_eps) # thus post q_norm does not need reshape
149
+ self.sliding_window = getattr(config, "sliding_window", None)
150
+
151
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
152
+ def forward(
153
+ self,
154
+ hidden_states: torch.Tensor,
155
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
156
+ attention_mask: Optional[torch.Tensor],
157
+ past_key_values: Optional[Cache] = None,
158
+ cache_position: Optional[torch.LongTensor] = None,
159
+ **kwargs: Unpack[FlashAttentionKwargs],
160
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
161
+ input_shape = hidden_states.shape[:-1]
162
+ hidden_shape = (*input_shape, -1, self.head_dim)
163
+
164
+ query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
165
+ key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
166
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
167
+
168
+ cos, sin = position_embeddings
169
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
170
+
171
+ if past_key_values is not None:
172
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
173
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
174
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
175
+
176
+ attention_interface: Callable = eager_attention_forward
177
+ if self.config._attn_implementation != "eager":
178
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
179
+
180
+ attn_output, attn_weights = attention_interface(
181
+ self,
182
+ query_states,
183
+ key_states,
184
+ value_states,
185
+ attention_mask,
186
+ dropout=0.0 if not self.training else self.attention_dropout,
187
+ scaling=self.scaling,
188
+ sliding_window=self.sliding_window, # diff with Llama
189
+ **kwargs,
190
+ )
191
+
192
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
193
+ attn_output = self.o_proj(attn_output)
194
+ return attn_output, attn_weights
195
+
196
+
197
+ class Qwen3MoeMLP(nn.Module):
198
+ def __init__(self, config, intermediate_size=None):
199
+ super().__init__()
200
+ self.config = config
201
+ self.hidden_size = config.hidden_size
202
+ self.intermediate_size = intermediate_size if intermediate_size is not None else config.intermediate_size
203
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
204
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
205
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
206
+ self.act_fn = ACT2FN[config.hidden_act]
207
+
208
+ def forward(self, x):
209
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
210
+ return down_proj
211
+
212
+
213
+ class Qwen3MoeSparseMoeBlock(nn.Module):
214
+ def __init__(self, config):
215
+ super().__init__()
216
+ self.num_experts = config.num_experts
217
+ self.top_k = config.num_experts_per_tok
218
+ self.norm_topk_prob = config.norm_topk_prob
219
+
220
+ # gating
221
+ self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False)
222
+ self.experts = nn.ModuleList(
223
+ [Qwen3MoeMLP(config, intermediate_size=config.moe_intermediate_size) for _ in range(self.num_experts)]
224
+ )
225
+
226
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
227
+ """ """
228
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
229
+ hidden_states = hidden_states.view(-1, hidden_dim)
230
+ # router_logits: (batch * sequence_length, n_experts)
231
+ router_logits = self.gate(hidden_states)
232
+
233
+ routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
234
+ routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
235
+ if self.norm_topk_prob: # only diff with mixtral sparse moe block!
236
+ routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
237
+ # we cast back to the input dtype
238
+ routing_weights = routing_weights.to(hidden_states.dtype)
239
+
240
+ final_hidden_states = torch.zeros(
241
+ (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
242
+ )
243
+
244
+ # One hot encode the selected experts to create an expert mask
245
+ # this will be used to easily index which expert is going to be sollicitated
246
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
247
+
248
+ # Loop over all available experts in the model and perform the computation on each expert
249
+ expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
250
+ for expert_idx in expert_hit:
251
+ expert_layer = self.experts[expert_idx]
252
+ idx, top_x = torch.where(expert_mask[expert_idx].squeeze(0))
253
+
254
+ # Index the correct hidden states and compute the expert hidden state for
255
+ # the current expert. We need to make sure to multiply the output hidden
256
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
257
+ current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
258
+ current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
259
+
260
+ # However `index_add_` only support torch tensors for indexing so we'll use
261
+ # the `top_x` tensor here.
262
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
263
+ final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
264
+ return final_hidden_states, router_logits
265
+
266
+
267
+ @use_kernel_forward_from_hub("RMSNorm")
268
+ class Qwen3MoeRMSNorm(nn.Module):
269
+ def __init__(self, hidden_size, eps=1e-6):
270
+ """
271
+ Qwen3MoeRMSNorm is equivalent to T5LayerNorm
272
+ """
273
+ super().__init__()
274
+ self.weight = nn.Parameter(torch.ones(hidden_size))
275
+ self.variance_epsilon = eps
276
+
277
+ def forward(self, hidden_states):
278
+ input_dtype = hidden_states.dtype
279
+ hidden_states = hidden_states.to(torch.float32)
280
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
281
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
282
+ return self.weight * hidden_states.to(input_dtype)
283
+
284
+ def extra_repr(self):
285
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
286
+
287
+
288
+ class Qwen3MoeDecoderLayer(GradientCheckpointingLayer):
289
+ def __init__(self, config: Qwen3MoeConfig, layer_idx: int):
290
+ super().__init__()
291
+ self.hidden_size = config.hidden_size
292
+
293
+ self.self_attn = Qwen3MoeAttention(config, layer_idx)
294
+
295
+ if (layer_idx not in config.mlp_only_layers) and (
296
+ config.num_experts > 0 and (layer_idx + 1) % config.decoder_sparse_step == 0
297
+ ):
298
+ self.mlp = Qwen3MoeSparseMoeBlock(config)
299
+ else:
300
+ self.mlp = Qwen3MoeMLP(config, intermediate_size=config.intermediate_size)
301
+
302
+ self.input_layernorm = Qwen3MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
303
+ self.post_attention_layernorm = Qwen3MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
304
+
305
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
306
+ def forward(
307
+ self,
308
+ hidden_states: torch.Tensor,
309
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
310
+ attention_mask: Optional[torch.Tensor] = None,
311
+ position_ids: Optional[torch.LongTensor] = None,
312
+ past_key_values: Optional[tuple[torch.Tensor]] = None,
313
+ cache_position: Optional[torch.LongTensor] = None,
314
+ **kwargs: Unpack[FlashAttentionKwargs],
315
+ ) -> torch.FloatTensor:
316
+ """
317
+ Args:
318
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
319
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
320
+ `(batch, sequence_length)` where padding elements are indicated by 0.
321
+ output_attentions (`bool`, *optional*):
322
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
323
+ returned tensors for more detail.
324
+ output_router_logits (`bool`, *optional*):
325
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss,
326
+ and should not be returned during inference.
327
+ use_cache (`bool`, *optional*):
328
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
329
+ (see `past_key_values`).
330
+ past_key_values (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
331
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
332
+ Indices depicting the position of the input sequence tokens in the sequence.
333
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
334
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
335
+ with `head_dim` being the embedding dimension of each attention head.
336
+ kwargs (`dict`, *optional*):
337
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
338
+ into the model
339
+ """
340
+ residual = hidden_states
341
+
342
+ hidden_states = self.input_layernorm(hidden_states)
343
+
344
+ # Self Attention
345
+ hidden_states, _ = self.self_attn(
346
+ hidden_states=hidden_states,
347
+ position_embeddings=position_embeddings,
348
+ attention_mask=attention_mask,
349
+ position_ids=position_ids,
350
+ past_key_values=past_key_values,
351
+ cache_position=cache_position,
352
+ **kwargs,
353
+ )
354
+ hidden_states = residual + hidden_states
355
+
356
+ # Fully Connected
357
+ residual = hidden_states
358
+ hidden_states = self.post_attention_layernorm(hidden_states)
359
+ hidden_states = self.mlp(hidden_states)
360
+ # For the MoE layers, we need to unpack
361
+ if isinstance(hidden_states, tuple):
362
+ hidden_states, _ = hidden_states
363
+ hidden_states = residual + hidden_states
364
+
365
+ return hidden_states
366
+
367
+
368
+ class Qwen3MoeRotaryEmbedding(nn.Module):
369
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
370
+
371
+ def __init__(self, config: Qwen3MoeConfig, device=None):
372
+ super().__init__()
373
+ # BC: "rope_type" was originally "type"
374
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
375
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
376
+ else:
377
+ self.rope_type = "default"
378
+ self.max_seq_len_cached = config.max_position_embeddings
379
+ self.original_max_seq_len = config.max_position_embeddings
380
+
381
+ self.config = config
382
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
383
+
384
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
385
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
386
+ self.original_inv_freq = self.inv_freq
387
+
388
+ @torch.no_grad()
389
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
390
+ def forward(self, x, position_ids):
391
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
392
+ position_ids_expanded = position_ids[:, None, :].float()
393
+
394
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
395
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
396
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
397
+ emb = torch.cat((freqs, freqs), dim=-1)
398
+ cos = emb.cos() * self.attention_scaling
399
+ sin = emb.sin() * self.attention_scaling
400
+
401
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
402
+
403
+
404
+ @auto_docstring
405
+ class Qwen3MoePreTrainedModel(PreTrainedModel):
406
+ config: Qwen3MoeConfig
407
+ base_model_prefix = "model"
408
+ supports_gradient_checkpointing = True
409
+ _no_split_modules = ["Qwen3MoeDecoderLayer"]
410
+ _skip_keys_device_placement = ["past_key_values"]
411
+ _supports_flash_attn = True
412
+ _supports_sdpa = True
413
+ _supports_flex_attn = True
414
+ _can_compile_fullgraph = False # MoE models don't work with torch.compile (`torch.where(condition)` not supported)
415
+ _supports_attention_backend = True
416
+ _can_record_outputs = {
417
+ "router_logits": OutputRecorder(Qwen3MoeSparseMoeBlock, index=1),
418
+ "hidden_states": Qwen3MoeDecoderLayer,
419
+ "attentions": Qwen3MoeAttention,
420
+ }
421
+
422
+
423
+ @auto_docstring
424
+ class Qwen3MoeModel(Qwen3MoePreTrainedModel):
425
+ def __init__(self, config: Qwen3MoeConfig):
426
+ super().__init__(config)
427
+ self.padding_idx = config.pad_token_id
428
+ self.vocab_size = config.vocab_size
429
+
430
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
431
+ self.layers = nn.ModuleList(
432
+ [Qwen3MoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
433
+ )
434
+ self.norm = Qwen3MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
435
+ self.rotary_emb = Qwen3MoeRotaryEmbedding(config=config)
436
+ self.gradient_checkpointing = False
437
+
438
+ # Initialize weights and apply final processing
439
+ self.post_init()
440
+
441
+ @check_model_inputs
442
+ @auto_docstring
443
+ def forward(
444
+ self,
445
+ input_ids: Optional[torch.LongTensor] = None,
446
+ attention_mask: Optional[torch.Tensor] = None,
447
+ position_ids: Optional[torch.LongTensor] = None,
448
+ past_key_values: Optional[Cache] = None,
449
+ inputs_embeds: Optional[torch.FloatTensor] = None,
450
+ use_cache: Optional[bool] = None,
451
+ cache_position: Optional[torch.LongTensor] = None,
452
+ **kwargs: Unpack[TransformersKwargs],
453
+ ) -> MoeModelOutputWithPast:
454
+ if (input_ids is None) ^ (inputs_embeds is not None):
455
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
456
+
457
+ if use_cache and past_key_values is None:
458
+ past_key_values = DynamicCache(config=self.config)
459
+
460
+ if inputs_embeds is None:
461
+ inputs_embeds = self.embed_tokens(input_ids)
462
+
463
+ if cache_position is None:
464
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
465
+ cache_position = torch.arange(
466
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
467
+ )
468
+ if position_ids is None:
469
+ position_ids = cache_position.unsqueeze(0)
470
+
471
+ mask_function = create_causal_mask if self.config.sliding_window is None else create_sliding_window_causal_mask
472
+ causal_mask = mask_function(
473
+ config=self.config,
474
+ input_embeds=inputs_embeds,
475
+ attention_mask=attention_mask,
476
+ cache_position=cache_position,
477
+ past_key_values=past_key_values,
478
+ position_ids=position_ids,
479
+ )
480
+
481
+ hidden_states = inputs_embeds
482
+
483
+ # create position embeddings to be shared across the decoder layers
484
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
485
+
486
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
487
+ hidden_states = decoder_layer(
488
+ hidden_states,
489
+ position_embeddings=position_embeddings,
490
+ attention_mask=causal_mask,
491
+ position_ids=position_ids,
492
+ past_key_values=past_key_values,
493
+ use_cache=use_cache,
494
+ cache_position=cache_position,
495
+ **kwargs,
496
+ )
497
+
498
+ hidden_states = self.norm(hidden_states)
499
+
500
+ return MoeModelOutputWithPast( # only diff with Mistral is the output type, we need MoE
501
+ last_hidden_state=hidden_states,
502
+ past_key_values=past_key_values,
503
+ )
504
+
505
+
506
+ def load_balancing_loss_func(
507
+ gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
508
+ num_experts: Optional[int] = None,
509
+ top_k=2,
510
+ attention_mask: Optional[torch.Tensor] = None,
511
+ ) -> Union[torch.Tensor, int]:
512
+ r"""
513
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
514
+
515
+ See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
516
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
517
+ experts is too unbalanced.
518
+
519
+ Args:
520
+ gate_logits:
521
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
522
+ shape [batch_size X sequence_length, num_experts].
523
+ num_experts:
524
+ Number of experts
525
+ top_k:
526
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
527
+ parameter.
528
+ attention_mask (`torch.Tensor`, *optional*):
529
+ The attention_mask used in forward function
530
+ shape [batch_size X sequence_length] if not None.
531
+
532
+ Returns:
533
+ The auxiliary loss.
534
+ """
535
+ if gate_logits is None or not isinstance(gate_logits, tuple):
536
+ return 0
537
+
538
+ if isinstance(gate_logits, tuple):
539
+ compute_device = gate_logits[0].device
540
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
541
+
542
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
543
+
544
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
545
+
546
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
547
+
548
+ if attention_mask is None:
549
+ # Compute the percentage of tokens routed to each experts
550
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
551
+
552
+ # Compute the average probability of routing to these experts
553
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
554
+ else:
555
+ batch_size, sequence_length = attention_mask.shape
556
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
557
+
558
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
559
+ expert_attention_mask = (
560
+ attention_mask[None, :, :, None, None]
561
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
562
+ .reshape(-1, top_k, num_experts)
563
+ .to(compute_device)
564
+ )
565
+
566
+ # Compute the percentage of tokens routed to each experts
567
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
568
+ expert_attention_mask, dim=0
569
+ )
570
+
571
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
572
+ router_per_expert_attention_mask = (
573
+ attention_mask[None, :, :, None]
574
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
575
+ .reshape(-1, num_experts)
576
+ .to(compute_device)
577
+ )
578
+
579
+ # Compute the average probability of routing to these experts
580
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
581
+ router_per_expert_attention_mask, dim=0
582
+ )
583
+
584
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
585
+ return overall_loss * num_experts
586
+
587
+
588
+ @auto_docstring
589
+ class Qwen3MoeForCausalLM(Qwen3MoePreTrainedModel, GenerationMixin):
590
+ _tied_weights_keys = ["lm_head.weight"]
591
+ _tp_plan = {"lm_head": "colwise_rep"}
592
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
593
+
594
+ def __init__(self, config):
595
+ super().__init__(config)
596
+ self.model = Qwen3MoeModel(config)
597
+ self.vocab_size = config.vocab_size
598
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
599
+ self.router_aux_loss_coef = config.router_aux_loss_coef
600
+ self.num_experts = config.num_experts
601
+ self.num_experts_per_tok = config.num_experts_per_tok
602
+
603
+ # Initialize weights and apply final processing
604
+ self.post_init()
605
+
606
+ def set_decoder(self, decoder):
607
+ self.model = decoder
608
+
609
+ def get_decoder(self):
610
+ return self.model
611
+
612
+ @can_return_tuple
613
+ @auto_docstring
614
+ def forward(
615
+ self,
616
+ input_ids: Optional[torch.LongTensor] = None,
617
+ attention_mask: Optional[torch.Tensor] = None,
618
+ position_ids: Optional[torch.LongTensor] = None,
619
+ past_key_values: Optional[Cache] = None,
620
+ inputs_embeds: Optional[torch.FloatTensor] = None,
621
+ labels: Optional[torch.LongTensor] = None,
622
+ use_cache: Optional[bool] = None,
623
+ output_router_logits: Optional[bool] = None,
624
+ cache_position: Optional[torch.LongTensor] = None,
625
+ logits_to_keep: Union[int, torch.Tensor] = 0,
626
+ **kwargs: Unpack[TransformersKwargs],
627
+ ) -> MoeCausalLMOutputWithPast:
628
+ r"""
629
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
630
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
631
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
632
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
633
+
634
+ Example:
635
+
636
+ ```python
637
+ >>> from transformers import AutoTokenizer, Qwen3MoeForCausalLM
638
+
639
+ >>> model = Qwen3MoeForCausalLM.from_pretrained("Qwen/Qwen3-MoE-15B-A2B")
640
+ >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-MoE-15B-A2B")
641
+
642
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
643
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
644
+
645
+ >>> # Generate
646
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
647
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
648
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
649
+ ```"""
650
+
651
+ output_router_logits = (
652
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
653
+ )
654
+
655
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
656
+ outputs: MoeModelOutputWithPast = self.model(
657
+ input_ids=input_ids,
658
+ attention_mask=attention_mask,
659
+ position_ids=position_ids,
660
+ past_key_values=past_key_values,
661
+ inputs_embeds=inputs_embeds,
662
+ use_cache=use_cache,
663
+ output_router_logits=output_router_logits,
664
+ cache_position=cache_position,
665
+ **kwargs,
666
+ )
667
+
668
+ hidden_states = outputs.last_hidden_state
669
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
670
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
671
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
672
+
673
+ loss = None
674
+ if labels is not None:
675
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
676
+
677
+ aux_loss = None
678
+ if output_router_logits:
679
+ aux_loss = load_balancing_loss_func(
680
+ outputs.router_logits,
681
+ self.num_experts,
682
+ self.num_experts_per_tok,
683
+ attention_mask,
684
+ )
685
+ if labels is not None:
686
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
687
+
688
+ return MoeCausalLMOutputWithPast(
689
+ loss=loss,
690
+ aux_loss=aux_loss,
691
+ logits=logits,
692
+ past_key_values=outputs.past_key_values,
693
+ hidden_states=outputs.hidden_states,
694
+ attentions=outputs.attentions,
695
+ router_logits=outputs.router_logits,
696
+ )
697
+
698
+
699
+ class Qwen3MoeForSequenceClassification(GenericForSequenceClassification, Qwen3MoePreTrainedModel):
700
+ pass
701
+
702
+
703
+ class Qwen3MoeForTokenClassification(GenericForTokenClassification, Qwen3MoePreTrainedModel):
704
+ pass
705
+
706
+
707
+ class Qwen3MoeForQuestionAnswering(GenericForQuestionAnswering, Qwen3MoePreTrainedModel):
708
+ base_model_prefix = "transformer" # For BC, where `transformer` was used instead of `model`
709
+
710
+
711
+ __all__ = [
712
+ "Qwen3MoeForCausalLM",
713
+ "Qwen3MoeForQuestionAnswering",
714
+ "Qwen3MoeModel",
715
+ "Qwen3MoePreTrainedModel",
716
+ "Qwen3MoeForSequenceClassification",
717
+ "Qwen3MoeForTokenClassification",
718
+ ]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/qwen3_moe/modular_qwen3_moe.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch Qwen3 model."""
16
+
17
+ from typing import Optional, Union
18
+
19
+ import torch
20
+ import torch.nn.functional as F
21
+ import torch.utils.checkpoint
22
+ from torch import nn
23
+
24
+ from ...activations import ACT2FN
25
+ from ...cache_utils import Cache
26
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
27
+ from ...modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
28
+ from ...processing_utils import Unpack
29
+ from ...utils import TransformersKwargs, logging
30
+ from ...utils.deprecation import deprecate_kwarg
31
+ from ..llama.modeling_llama import (
32
+ LlamaForQuestionAnswering,
33
+ LlamaForSequenceClassification,
34
+ LlamaForTokenClassification,
35
+ LlamaRMSNorm,
36
+ )
37
+ from ..mixtral.modeling_mixtral import MixtralForCausalLM, MixtralModel, load_balancing_loss_func
38
+ from ..qwen2_moe.modeling_qwen2_moe import Qwen2MoeDecoderLayer
39
+ from ..qwen3.modeling_qwen3 import Qwen3Attention
40
+ from .configuration_qwen3_moe import Qwen3MoeConfig
41
+
42
+
43
+ logger = logging.get_logger(__name__)
44
+
45
+
46
+ class Qwen3MoeAttention(Qwen3Attention): # This is the main diff with qwen2Moe!
47
+ def __init__(self, config: Qwen3MoeConfig, layer_idx: int):
48
+ super().__init__(config, layer_idx)
49
+ self.sliding_window = getattr(config, "sliding_window", None)
50
+
51
+
52
+ class Qwen3MoeMLP(nn.Module):
53
+ def __init__(self, config, intermediate_size=None):
54
+ super().__init__()
55
+ self.config = config
56
+ self.hidden_size = config.hidden_size
57
+ self.intermediate_size = intermediate_size if intermediate_size is not None else config.intermediate_size
58
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
59
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
60
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
61
+ self.act_fn = ACT2FN[config.hidden_act]
62
+
63
+ def forward(self, x):
64
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
65
+ return down_proj
66
+
67
+
68
+ class Qwen3MoeSparseMoeBlock(nn.Module):
69
+ def __init__(self, config):
70
+ super().__init__()
71
+ self.num_experts = config.num_experts
72
+ self.top_k = config.num_experts_per_tok
73
+ self.norm_topk_prob = config.norm_topk_prob
74
+
75
+ # gating
76
+ self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False)
77
+ self.experts = nn.ModuleList(
78
+ [Qwen3MoeMLP(config, intermediate_size=config.moe_intermediate_size) for _ in range(self.num_experts)]
79
+ )
80
+
81
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
82
+ """ """
83
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
84
+ hidden_states = hidden_states.view(-1, hidden_dim)
85
+ # router_logits: (batch * sequence_length, n_experts)
86
+ router_logits = self.gate(hidden_states)
87
+
88
+ routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
89
+ routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
90
+ if self.norm_topk_prob: # only diff with mixtral sparse moe block!
91
+ routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
92
+ # we cast back to the input dtype
93
+ routing_weights = routing_weights.to(hidden_states.dtype)
94
+
95
+ final_hidden_states = torch.zeros(
96
+ (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
97
+ )
98
+
99
+ # One hot encode the selected experts to create an expert mask
100
+ # this will be used to easily index which expert is going to be sollicitated
101
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
102
+
103
+ # Loop over all available experts in the model and perform the computation on each expert
104
+ expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
105
+ for expert_idx in expert_hit:
106
+ expert_layer = self.experts[expert_idx]
107
+ idx, top_x = torch.where(expert_mask[expert_idx].squeeze(0))
108
+
109
+ # Index the correct hidden states and compute the expert hidden state for
110
+ # the current expert. We need to make sure to multiply the output hidden
111
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
112
+ current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
113
+ current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
114
+
115
+ # However `index_add_` only support torch tensors for indexing so we'll use
116
+ # the `top_x` tensor here.
117
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
118
+ final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
119
+ return final_hidden_states, router_logits
120
+
121
+
122
+ class Qwen3MoeRMSNorm(LlamaRMSNorm):
123
+ pass
124
+
125
+
126
+ class Qwen3MoeDecoderLayer(Qwen2MoeDecoderLayer, nn.Module):
127
+ def __init__(self, config: Qwen3MoeConfig, layer_idx: int):
128
+ nn.Module().__init__()
129
+ self.hidden_size = config.hidden_size
130
+
131
+ self.self_attn = Qwen3MoeAttention(config, layer_idx)
132
+
133
+ if (layer_idx not in config.mlp_only_layers) and (
134
+ config.num_experts > 0 and (layer_idx + 1) % config.decoder_sparse_step == 0
135
+ ):
136
+ self.mlp = Qwen3MoeSparseMoeBlock(config)
137
+ else:
138
+ self.mlp = Qwen3MoeMLP(config, intermediate_size=config.intermediate_size)
139
+
140
+ self.input_layernorm = Qwen3MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
141
+ self.post_attention_layernorm = Qwen3MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
142
+
143
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
144
+ def forward(
145
+ self,
146
+ hidden_states: torch.Tensor,
147
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
148
+ attention_mask: Optional[torch.Tensor] = None,
149
+ position_ids: Optional[torch.LongTensor] = None,
150
+ past_key_values: Optional[tuple[torch.Tensor]] = None,
151
+ cache_position: Optional[torch.LongTensor] = None,
152
+ **kwargs: Unpack[FlashAttentionKwargs],
153
+ ) -> torch.FloatTensor:
154
+ residual = hidden_states
155
+
156
+ hidden_states = self.input_layernorm(hidden_states)
157
+
158
+ # Self Attention
159
+ hidden_states, _ = self.self_attn(
160
+ hidden_states=hidden_states,
161
+ position_embeddings=position_embeddings,
162
+ attention_mask=attention_mask,
163
+ position_ids=position_ids,
164
+ past_key_values=past_key_values,
165
+ cache_position=cache_position,
166
+ **kwargs,
167
+ )
168
+ hidden_states = residual + hidden_states
169
+
170
+ # Fully Connected
171
+ residual = hidden_states
172
+ hidden_states = self.post_attention_layernorm(hidden_states)
173
+ hidden_states = self.mlp(hidden_states)
174
+ # For the MoE layers, we need to unpack
175
+ if isinstance(hidden_states, tuple):
176
+ hidden_states, _ = hidden_states
177
+ hidden_states = residual + hidden_states
178
+
179
+ return hidden_states
180
+
181
+
182
+ class Qwen3MoeModel(MixtralModel):
183
+ pass
184
+
185
+
186
+ class Qwen3MoeForCausalLM(MixtralForCausalLM):
187
+ def __init__(self, config):
188
+ super().__init__(config)
189
+ self.model = Qwen3MoeModel(config)
190
+ self.num_experts = config.num_experts
191
+
192
+ def forward(
193
+ self,
194
+ input_ids: Optional[torch.LongTensor] = None,
195
+ attention_mask: Optional[torch.Tensor] = None,
196
+ position_ids: Optional[torch.LongTensor] = None,
197
+ past_key_values: Optional[Cache] = None,
198
+ inputs_embeds: Optional[torch.FloatTensor] = None,
199
+ labels: Optional[torch.LongTensor] = None,
200
+ use_cache: Optional[bool] = None,
201
+ output_router_logits: Optional[bool] = None,
202
+ cache_position: Optional[torch.LongTensor] = None,
203
+ logits_to_keep: Union[int, torch.Tensor] = 0,
204
+ **kwargs: Unpack[TransformersKwargs],
205
+ ) -> MoeCausalLMOutputWithPast:
206
+ r"""
207
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
208
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
209
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
210
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
211
+
212
+ Example:
213
+
214
+ ```python
215
+ >>> from transformers import AutoTokenizer, Qwen3MoeForCausalLM
216
+
217
+ >>> model = Qwen3MoeForCausalLM.from_pretrained("Qwen/Qwen3-MoE-15B-A2B")
218
+ >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-MoE-15B-A2B")
219
+
220
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
221
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
222
+
223
+ >>> # Generate
224
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
225
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
226
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
227
+ ```"""
228
+
229
+ output_router_logits = (
230
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
231
+ )
232
+
233
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
234
+ outputs: MoeModelOutputWithPast = self.model(
235
+ input_ids=input_ids,
236
+ attention_mask=attention_mask,
237
+ position_ids=position_ids,
238
+ past_key_values=past_key_values,
239
+ inputs_embeds=inputs_embeds,
240
+ use_cache=use_cache,
241
+ output_router_logits=output_router_logits,
242
+ cache_position=cache_position,
243
+ **kwargs,
244
+ )
245
+
246
+ hidden_states = outputs.last_hidden_state
247
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
248
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
249
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
250
+
251
+ loss = None
252
+ if labels is not None:
253
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
254
+
255
+ aux_loss = None
256
+ if output_router_logits:
257
+ aux_loss = load_balancing_loss_func(
258
+ outputs.router_logits,
259
+ self.num_experts,
260
+ self.num_experts_per_tok,
261
+ attention_mask,
262
+ )
263
+ if labels is not None:
264
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
265
+
266
+ return MoeCausalLMOutputWithPast(
267
+ loss=loss,
268
+ aux_loss=aux_loss,
269
+ logits=logits,
270
+ past_key_values=outputs.past_key_values,
271
+ hidden_states=outputs.hidden_states,
272
+ attentions=outputs.attentions,
273
+ router_logits=outputs.router_logits,
274
+ )
275
+
276
+
277
+ class Qwen3MoeForSequenceClassification(LlamaForSequenceClassification):
278
+ pass
279
+
280
+
281
+ class Qwen3MoeForTokenClassification(LlamaForTokenClassification):
282
+ pass
283
+
284
+
285
+ class Qwen3MoeForQuestionAnswering(LlamaForQuestionAnswering):
286
+ pass
287
+
288
+
289
+ __all__ = [
290
+ "Qwen3MoeForCausalLM",
291
+ "Qwen3MoeForQuestionAnswering",
292
+ "Qwen3MoeModel",
293
+ "Qwen3MoePreTrainedModel", # noqa: F822
294
+ "Qwen3MoeForSequenceClassification",
295
+ "Qwen3MoeForTokenClassification",
296
+ ]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/rag/__init__.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_rag import *
22
+ from .modeling_rag import *
23
+ from .modeling_tf_rag import *
24
+ from .retrieval_rag import *
25
+ from .tokenization_rag import *
26
+ else:
27
+ import sys
28
+
29
+ _file = globals()["__file__"]
30
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/rag/configuration_rag.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020, The RAG Authors and The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """RAG model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import add_start_docstrings
19
+
20
+
21
+ RAG_CONFIG_DOC = r"""
22
+ [`RagConfig`] stores the configuration of a *RagModel*. Configuration objects inherit from [`PretrainedConfig`] and
23
+ can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.
24
+
25
+ Args:
26
+ title_sep (`str`, *optional*, defaults to `" / "`):
27
+ Separator inserted between the title and the text of the retrieved document when calling [`RagRetriever`].
28
+ doc_sep (`str`, *optional*, defaults to `" // "`):
29
+ Separator inserted between the text of the retrieved document and the original input when calling
30
+ [`RagRetriever`].
31
+ n_docs (`int`, *optional*, defaults to 5):
32
+ Number of documents to retrieve.
33
+ max_combined_length (`int`, *optional*, defaults to 300):
34
+ Max length of contextualized input returned by [`~RagRetriever.__call__`].
35
+ retrieval_vector_size (`int`, *optional*, defaults to 768):
36
+ Dimensionality of the document embeddings indexed by [`RagRetriever`].
37
+ retrieval_batch_size (`int`, *optional*, defaults to 8):
38
+ Retrieval batch size, defined as the number of queries issues concurrently to the faiss index encapsulated
39
+ [`RagRetriever`].
40
+ dataset (`str`, *optional*, defaults to `"wiki_dpr"`):
41
+ A dataset identifier of the indexed dataset in HuggingFace Datasets (list all available datasets and ids
42
+ using `datasets.list_datasets()`).
43
+ dataset_split (`str`, *optional*, defaults to `"train"`)
44
+ Which split of the `dataset` to load.
45
+ index_name (`str`, *optional*, defaults to `"compressed"`)
46
+ The index name of the index associated with the `dataset`. One can choose between `"legacy"`, `"exact"` and
47
+ `"compressed"`.
48
+ index_path (`str`, *optional*)
49
+ The path to the serialized faiss index on disk.
50
+ passages_path (`str`, *optional*):
51
+ A path to text passages compatible with the faiss index. Required if using
52
+ [`~models.rag.retrieval_rag.LegacyIndex`]
53
+ use_dummy_dataset (`bool`, *optional*, defaults to `False`)
54
+ Whether to load a "dummy" variant of the dataset specified by `dataset`.
55
+ label_smoothing (`float`, *optional*, defaults to 0.0):
56
+ Only relevant if `return_loss` is set to `True`. Controls the `epsilon` parameter value for label smoothing
57
+ in the loss calculation. If set to 0, no label smoothing is performed.
58
+ do_marginalize (`bool`, *optional*, defaults to `False`):
59
+ If `True`, the logits are marginalized over all documents by making use of
60
+ `torch.nn.functional.log_softmax`.
61
+ reduce_loss (`bool`, *optional*, defaults to `False`):
62
+ Whether or not to reduce the NLL loss using the `torch.Tensor.sum` operation.
63
+ do_deduplication (`bool`, *optional*, defaults to `True`):
64
+ Whether or not to deduplicate the generations from different context documents for a given input. Has to be
65
+ set to `False` if used while training with distributed backend.
66
+ exclude_bos_score (`bool`, *optional*, defaults to `False`):
67
+ Whether or not to disregard the BOS token when computing the loss.
68
+ output_retrieved(`bool`, *optional*, defaults to `False`):
69
+ If set to `True`, `retrieved_doc_embeds`, `retrieved_doc_ids`, `context_input_ids` and
70
+ `context_attention_mask` are returned. See returned tensors for more detail.
71
+ use_cache (`bool`, *optional*, defaults to `True`):
72
+ Whether or not the model should return the last key/values attentions (not used by all models).
73
+ forced_eos_token_id (`int`, *optional*):
74
+ The id of the token to force as the last generated token when `max_length` is reached. Usually set to
75
+ `eos_token_id`.
76
+ """
77
+
78
+
79
+ @add_start_docstrings(RAG_CONFIG_DOC)
80
+ class RagConfig(PretrainedConfig):
81
+ model_type = "rag"
82
+ has_no_defaults_at_init = True
83
+
84
+ def __init__(
85
+ self,
86
+ vocab_size=None,
87
+ is_encoder_decoder=True,
88
+ prefix=None,
89
+ bos_token_id=None,
90
+ pad_token_id=None,
91
+ eos_token_id=None,
92
+ decoder_start_token_id=None,
93
+ title_sep=" / ",
94
+ doc_sep=" // ",
95
+ n_docs=5,
96
+ max_combined_length=300,
97
+ retrieval_vector_size=768,
98
+ retrieval_batch_size=8,
99
+ dataset="wiki_dpr",
100
+ dataset_split="train",
101
+ index_name="compressed",
102
+ index_path=None,
103
+ passages_path=None,
104
+ use_dummy_dataset=False,
105
+ reduce_loss=False,
106
+ label_smoothing=0.0,
107
+ do_deduplication=True,
108
+ exclude_bos_score=False,
109
+ do_marginalize=False,
110
+ output_retrieved=False,
111
+ use_cache=True,
112
+ forced_eos_token_id=None,
113
+ dataset_revision=None,
114
+ **kwargs,
115
+ ):
116
+ super().__init__(
117
+ bos_token_id=bos_token_id,
118
+ pad_token_id=pad_token_id,
119
+ eos_token_id=eos_token_id,
120
+ decoder_start_token_id=decoder_start_token_id,
121
+ forced_eos_token_id=forced_eos_token_id,
122
+ is_encoder_decoder=is_encoder_decoder,
123
+ prefix=prefix,
124
+ vocab_size=vocab_size,
125
+ **kwargs,
126
+ )
127
+ if "question_encoder" not in kwargs or "generator" not in kwargs:
128
+ raise ValueError(
129
+ f"A configuration of type {self.model_type} cannot be instantiated because "
130
+ f"both `question_encoder` and `generator` sub-configurations were not passed, only {kwargs}"
131
+ )
132
+ question_encoder_config = kwargs.pop("question_encoder")
133
+ question_encoder_model_type = question_encoder_config.pop("model_type")
134
+ decoder_config = kwargs.pop("generator")
135
+ decoder_model_type = decoder_config.pop("model_type")
136
+
137
+ from ..auto.configuration_auto import AutoConfig
138
+
139
+ self.question_encoder = AutoConfig.for_model(question_encoder_model_type, **question_encoder_config)
140
+ self.generator = AutoConfig.for_model(decoder_model_type, **decoder_config)
141
+
142
+ self.reduce_loss = reduce_loss
143
+ self.label_smoothing = label_smoothing
144
+ self.exclude_bos_score = exclude_bos_score
145
+ self.do_marginalize = do_marginalize
146
+
147
+ self.title_sep = title_sep
148
+ self.doc_sep = doc_sep
149
+ self.n_docs = n_docs
150
+ self.max_combined_length = max_combined_length
151
+
152
+ self.dataset = dataset
153
+ self.dataset_split = dataset_split
154
+ self.index_name = index_name
155
+
156
+ self.retrieval_vector_size = retrieval_vector_size
157
+ self.retrieval_batch_size = retrieval_batch_size
158
+ self.passages_path = passages_path
159
+ self.index_path = index_path
160
+ self.use_dummy_dataset = use_dummy_dataset
161
+ self.dataset_revision = dataset_revision
162
+
163
+ self.output_retrieved = output_retrieved
164
+
165
+ self.do_deduplication = do_deduplication
166
+
167
+ self.use_cache = use_cache
168
+
169
+ if self.forced_eos_token_id is None:
170
+ self.forced_eos_token_id = getattr(self.generator, "forced_eos_token_id", None)
171
+
172
+ @classmethod
173
+ def from_question_encoder_generator_configs(
174
+ cls, question_encoder_config: PretrainedConfig, generator_config: PretrainedConfig, **kwargs
175
+ ) -> PretrainedConfig:
176
+ r"""
177
+ Instantiate a [`EncoderDecoderConfig`] (or a derived class) from a pre-trained encoder model configuration and
178
+ decoder model configuration.
179
+
180
+ Returns:
181
+ [`EncoderDecoderConfig`]: An instance of a configuration object
182
+ """
183
+ return cls(question_encoder=question_encoder_config.to_dict(), generator=generator_config.to_dict(), **kwargs)
184
+
185
+
186
+ __all__ = ["RagConfig"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/rag/modeling_rag.py ADDED
@@ -0,0 +1,1669 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020, The RAG Authors and The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """RAG model implementation."""
16
+
17
+ import copy
18
+ from dataclasses import dataclass
19
+ from typing import Callable, Optional, Union
20
+
21
+ import torch
22
+ from torch import nn
23
+
24
+ from ...cache_utils import Cache, EncoderDecoderCache
25
+ from ...configuration_utils import PretrainedConfig
26
+ from ...generation import GenerationConfig, GenerationMixin, LogitsProcessorList, StoppingCriteriaList
27
+ from ...modeling_outputs import ModelOutput
28
+ from ...modeling_utils import PreTrainedModel
29
+ from ...utils import auto_docstring, logging
30
+ from .configuration_rag import RagConfig
31
+ from .retrieval_rag import RagRetriever
32
+
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ @dataclass
38
+ @auto_docstring(
39
+ custom_intro="""
40
+ Base class for retriever augmented marginalized models outputs.
41
+ """
42
+ )
43
+ class RetrievAugLMMarginOutput(ModelOutput):
44
+ r"""
45
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
46
+ Language modeling loss.
47
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
48
+ Prediction scores of the language modeling head. The score is possibly marginalized over all documents for
49
+ each vocabulary token.
50
+ doc_scores (`torch.FloatTensor` of shape `(batch_size, config.n_docs)`):
51
+ Score between each retrieved document embeddings (see `retrieved_doc_embeds`) and
52
+ `question_encoder_last_hidden_state`.
53
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
54
+ List of `torch.FloatTensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size,
55
+ num_heads, sequence_length, embed_size_per_head)`).
56
+
57
+ Contains precomputed hidden-states (key and values in the attention blocks) of the decoder that can be used
58
+ (see `past_key_values` input) to speed up sequential decoding.
59
+ retrieved_doc_embeds (`torch.FloatTensor` of shape `(batch_size, config.n_docs, hidden_size)`, *optional*, returned when *output_retrieved=True*):
60
+ Embedded documents retrieved by the retriever. Is used with `question_encoder_last_hidden_state` to compute
61
+ the `doc_scores`.
62
+ retrieved_doc_ids (`torch.LongTensor` of shape `(batch_size, config.n_docs)`, *optional*, returned when *output_retrieved=True*):
63
+ The indexes of the embedded documents retrieved by the retriever.
64
+ context_input_ids (`torch.LongTensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
65
+ Input ids post-processed from the retrieved documents and the question encoder input_ids by the retriever.
66
+ context_attention_mask (`torch.LongTensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
67
+ Attention mask post-processed from the retrieved documents and the question encoder `input_ids` by the
68
+ retriever.
69
+ question_encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
70
+ Sequence of hidden states at the output of the last layer of the question encoder pooled output of the
71
+ model.
72
+ question_enc_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
73
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings and one for the output of each layer) of
74
+ shape `(batch_size, sequence_length, hidden_size)`.
75
+
76
+ Hidden states of the question encoder at the output of each layer plus the initial embedding outputs.
77
+ question_enc_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
78
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
79
+ sequence_length)`.
80
+
81
+ Attentions weights of the question encoder, after the attention softmax, used to compute the weighted
82
+ average in the self-attention heads.
83
+ generator_enc_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
84
+ Sequence of hidden-states at the output of the last layer of the generator encoder of the model.
85
+ generator_enc_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
86
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings and one for the output of each layer) of
87
+ shape `(batch_size, sequence_length, hidden_size)`.
88
+
89
+ Hidden states of the generator encoder at the output of each layer plus the initial embedding outputs.
90
+ generator_enc_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
91
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
92
+ sequence_length)`.
93
+
94
+ Attentions weights of the generator encoder, after the attention softmax, used to compute the weighted
95
+ average in the self-attention heads.
96
+ generator_dec_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
97
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings and one for the output of each layer) of
98
+ shape `(batch_size, sequence_length, hidden_size)`.
99
+
100
+ Hidden states of the generator decoder at the output of each layer plus the initial embedding outputs.
101
+ generator_dec_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
102
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
103
+ sequence_length)`.
104
+
105
+ Attentions weights of the generator decoder, after the attention softmax, used to compute the weighted
106
+ average in the self-attention heads.
107
+ generator_cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
108
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
109
+ sequence_length)`.
110
+
111
+ Cross-attentions weights of the generator decoder, after the attention softmax, used to compute the
112
+ weighted average in the cross-attention heads.
113
+ """
114
+
115
+ loss: Optional[torch.FloatTensor] = None
116
+ logits: Optional[torch.FloatTensor] = None
117
+ doc_scores: Optional[torch.FloatTensor] = None
118
+ past_key_values: Optional[Cache] = None
119
+ retrieved_doc_embeds: Optional[torch.FloatTensor] = None
120
+ retrieved_doc_ids: Optional[torch.LongTensor] = None
121
+ context_input_ids: Optional[torch.LongTensor] = None
122
+ context_attention_mask: Optional[torch.LongTensor] = None
123
+ question_encoder_last_hidden_state: Optional[torch.FloatTensor] = None
124
+ question_enc_hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
125
+ question_enc_attentions: Optional[tuple[torch.FloatTensor, ...]] = None
126
+ generator_enc_last_hidden_state: Optional[torch.FloatTensor] = None
127
+ generator_enc_hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
128
+ generator_enc_attentions: Optional[tuple[torch.FloatTensor, ...]] = None
129
+ generator_dec_hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
130
+ generator_dec_attentions: Optional[tuple[torch.FloatTensor, ...]] = None
131
+ generator_cross_attentions: Optional[tuple[torch.FloatTensor, ...]] = None
132
+
133
+
134
+ @dataclass
135
+ @auto_docstring
136
+ class RetrievAugLMOutput(ModelOutput):
137
+ r"""
138
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
139
+ Prediction scores of the language modeling head. The score is possibly marginalized over all documents for
140
+ each vocabulary token.
141
+ doc_scores (`torch.FloatTensor` of shape `(batch_size, config.n_docs)`):
142
+ Score between each retrieved document embeddings (see `retrieved_doc_embeds`) and
143
+ `question_encoder_last_hidden_state`.
144
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
145
+ List of `torch.FloatTensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size,
146
+ num_heads, sequence_length, embed_size_per_head)`).
147
+
148
+ Contains precomputed hidden-states (key and values in the attention blocks) of the decoder that can be used
149
+ (see `past_key_values` input) to speed up sequential decoding.
150
+ retrieved_doc_embeds (`torch.FloatTensor` of shape `(batch_size, config.n_docs, hidden_size)`, *optional*, returned when *output_retrieved=True*):
151
+ Embedded documents retrieved by the retriever. Is used with `question_encoder_last_hidden_state` to compute
152
+ the `doc_scores`.
153
+ retrieved_doc_ids (`torch.LongTensor` of shape `(batch_size, config.n_docs)`, *optional*, returned when *output_retrieved=True*):
154
+ The indexes of the embedded documents retrieved by the retriever.
155
+ context_input_ids (`torch.LongTensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
156
+ Input ids post-processed from the retrieved documents and the question encoder input_ids by the retriever.
157
+ context_attention_mask (`torch.LongTensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
158
+ Attention mask post-processed from the retrieved documents and the question encoder `input_ids` by the
159
+ retriever.
160
+ question_encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
161
+ Sequence of hidden states at the output of the last layer of the question encoder pooled output of the
162
+ model.
163
+ question_enc_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
164
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings and one for the output of each layer) of
165
+ shape `(batch_size, sequence_length, hidden_size)`.
166
+
167
+ Hidden states of the question encoder at the output of each layer plus the initial embedding outputs.
168
+ question_enc_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
169
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
170
+ sequence_length)`.
171
+
172
+ Attentions weights of the question encoder, after the attention softmax, used to compute the weighted
173
+ average in the self-attention heads.
174
+ generator_enc_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
175
+ Sequence of hidden-states at the output of the last layer of the generator encoder of the model.
176
+ generator_enc_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
177
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings and one for the output of each layer) of
178
+ shape `(batch_size, sequence_length, hidden_size)`.
179
+
180
+ Hidden states of the generator encoder at the output of each layer plus the initial embedding outputs.
181
+ generator_enc_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
182
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
183
+ sequence_length)`.
184
+
185
+ Attentions weights of the generator encoder, after the attention softmax, used to compute the weighted
186
+ average in the self-attention heads.
187
+ generator_dec_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
188
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings and one for the output of each layer) of
189
+ shape `(batch_size, sequence_length, hidden_size)`.
190
+
191
+ Hidden states of the generator decoder at the output of each layer plus the initial embedding outputs.
192
+ generator_dec_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
193
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
194
+ sequence_length)`.
195
+
196
+ Attentions weights of the generator decoder, after the attention softmax, used to compute the weighted
197
+ average in the self-attention heads.
198
+ generator_cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
199
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
200
+ sequence_length)`.
201
+
202
+ Cross-attentions weights of the generator decoder, after the attention softmax, used to compute the
203
+ weighted average in the cross-attention heads.
204
+ """
205
+
206
+ logits: Optional[torch.FloatTensor] = None
207
+ doc_scores: Optional[torch.FloatTensor] = None
208
+ past_key_values: Optional[Cache] = None
209
+ retrieved_doc_embeds: Optional[torch.FloatTensor] = None
210
+ retrieved_doc_ids: Optional[torch.LongTensor] = None
211
+ context_input_ids: Optional[torch.LongTensor] = None
212
+ context_attention_mask: Optional[torch.LongTensor] = None
213
+ question_encoder_last_hidden_state: Optional[torch.FloatTensor] = None
214
+ question_enc_hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
215
+ question_enc_attentions: Optional[tuple[torch.FloatTensor, ...]] = None
216
+ generator_enc_last_hidden_state: Optional[torch.FloatTensor] = None
217
+ generator_enc_hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
218
+ generator_enc_attentions: Optional[tuple[torch.FloatTensor, ...]] = None
219
+ generator_dec_hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
220
+ generator_dec_attentions: Optional[tuple[torch.FloatTensor, ...]] = None
221
+ generator_cross_attentions: Optional[tuple[torch.FloatTensor, ...]] = None
222
+
223
+
224
+ @auto_docstring(
225
+ custom_intro="""
226
+ RAG models were released with the paper [Retrieval-Augmented Generation for Knowledge-Intensive NLP
227
+ Tasks](https://huggingface.co/papers/2005.11401) by Patrick Lewis, Ethan Perez, Aleksandra Piktus et al.
228
+
229
+ RAG is a retriever augmented model and encapsulate three components: a question encoder, a dataset retriever and a
230
+ generator, the encoder and generator are trainable while the retriever is just an indexed dataset.
231
+ """
232
+ )
233
+ @auto_docstring
234
+ class RagPreTrainedModel(PreTrainedModel):
235
+ config: RagConfig
236
+ base_model_prefix = "rag"
237
+ _supports_flash_attn = True
238
+ _supports_sdpa = True
239
+
240
+ @classmethod
241
+ def from_pretrained_question_encoder_generator(
242
+ cls,
243
+ question_encoder_pretrained_model_name_or_path: Optional[str] = None,
244
+ generator_pretrained_model_name_or_path: Optional[str] = None,
245
+ retriever: RagRetriever = None,
246
+ **kwargs,
247
+ ) -> PreTrainedModel:
248
+ r"""
249
+ Instantiates an question encoder and a generator from one or two base classes of the library from pretrained
250
+ model checkpoints.
251
+
252
+ The model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated). To train
253
+ the model, you need to first set it back in training mode with `model.train()`.
254
+
255
+ Params:
256
+ question_encoder_pretrained_model_name_or_path (`str`, *optional*, defaults to `None`):
257
+ Information necessary to initiate the question encoder. Can be either:
258
+
259
+ - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
260
+ - A path to a *directory* containing model weights saved using
261
+ [`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
262
+ - A path or url to a *tensorflow index checkpoint file* (e.g, `./tf_model/model.ckpt.index`). In
263
+ this case, `from_tf` should be set to `True` and a configuration object should be provided as
264
+ `config` argument. This loading path is slower than converting the TensorFlow checkpoint in a
265
+ PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
266
+
267
+ generator_pretrained_model_name_or_path (`str`, *optional*, defaults to `None`):
268
+ Information necessary to initiate the generator. Can be either:
269
+
270
+ - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
271
+ - A path to a *directory* containing model weights saved using
272
+ [`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
273
+ - A path or url to a *tensorflow index checkpoint file* (e.g, `./tf_model/model.ckpt.index`). In
274
+ this case, `from_tf` should be set to `True` and a configuration object should be provided as
275
+ `config` argument. This loading path is slower than converting the TensorFlow checkpoint in a
276
+ PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
277
+
278
+ model_args (remaining positional arguments, *optional*):
279
+ All remaining positional arguments will be passed to the underlying model's `__init__` method.
280
+ retriever ([`RagRetriever`], *optional*):
281
+ The retriever to use.
282
+ kwwargs (remaining dictionary of keyword arguments, *optional*):
283
+ Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
284
+ `output_attentions=True`).
285
+
286
+ - To update the question_encoder configuration, use the prefix *question_encoder_* for each
287
+ configuration parameter.
288
+ - To update the generator configuration, use the prefix *generator_* for each configuration parameter.
289
+ - To update the parent model configuration, do not use a prefix for each configuration parameter.
290
+
291
+ Behaves differently depending on whether a `config` is provided or automatically loaded.
292
+
293
+ Example:
294
+
295
+ ```python
296
+ >>> from transformers import RagModel
297
+
298
+ >>> # initialize a RAG from two pretrained models.
299
+ >>> model = RagModel.from_pretrained_question_encoder_generator(
300
+ ... "facebook/dpr-question_encoder-single-nq-base", "google-t5/t5-small"
301
+ ... )
302
+ >>> # saving model after fine-tuning
303
+ >>> model.save_pretrained("./rag")
304
+ >>> # load fine-tuned model
305
+ >>> model = RagModel.from_pretrained("./rag")
306
+ ```"""
307
+
308
+ kwargs_question_encoder = {
309
+ argument[len("question_encoder_") :]: value
310
+ for argument, value in kwargs.items()
311
+ if argument.startswith("question_encoder_")
312
+ }
313
+
314
+ kwargs_generator = {
315
+ argument[len("generator_") :]: value
316
+ for argument, value in kwargs.items()
317
+ if argument.startswith("generator_")
318
+ }
319
+
320
+ # remove question_encoder, generator kwargs from kwargs
321
+ for key in kwargs_question_encoder:
322
+ del kwargs["question_encoder_" + key]
323
+ for key in kwargs_generator:
324
+ del kwargs["generator_" + key]
325
+
326
+ # Load and initialize the question_encoder and generator
327
+ # The distinction between question_encoder and generator at the model level is made
328
+ # by the value of the flag `is_generator` that we need to set correctly.
329
+ question_encoder = kwargs_question_encoder.pop("model", None)
330
+ if question_encoder is None:
331
+ assert question_encoder_pretrained_model_name_or_path is not None, (
332
+ "If `model` is not defined as an argument, a `question_encoder_pretrained_model_name_or_path` has to"
333
+ " be defined"
334
+ )
335
+ from ..auto.modeling_auto import AutoModel
336
+
337
+ if "config" not in kwargs_question_encoder:
338
+ from ..auto.configuration_auto import AutoConfig
339
+
340
+ question_encoder_config, kwargs_question_encoder = AutoConfig.from_pretrained(
341
+ question_encoder_pretrained_model_name_or_path,
342
+ **kwargs_question_encoder,
343
+ return_unused_kwargs=True,
344
+ )
345
+ kwargs_question_encoder["config"] = question_encoder_config
346
+
347
+ question_encoder = AutoModel.from_pretrained(
348
+ question_encoder_pretrained_model_name_or_path, **kwargs_question_encoder
349
+ )
350
+
351
+ generator = kwargs_generator.pop("model", None)
352
+ if generator is None:
353
+ assert generator_pretrained_model_name_or_path is not None, (
354
+ "If `generator_model` is not defined as an argument, a `generator_pretrained_model_name_or_path` has"
355
+ " to be defined"
356
+ )
357
+ from ..auto.modeling_auto import AutoModelForSeq2SeqLM
358
+
359
+ if "config" not in kwargs_generator:
360
+ from ..auto.configuration_auto import AutoConfig
361
+
362
+ generator_config, kwargs_generator = AutoConfig.from_pretrained(
363
+ generator_pretrained_model_name_or_path, **kwargs_generator, return_unused_kwargs=True
364
+ )
365
+
366
+ kwargs_generator["config"] = generator_config
367
+
368
+ generator = AutoModelForSeq2SeqLM.from_pretrained(
369
+ generator_pretrained_model_name_or_path, **kwargs_generator
370
+ )
371
+
372
+ # instantiate config with corresponding kwargs
373
+ config = kwargs.get("config")
374
+ if config is None:
375
+ config = RagConfig.from_question_encoder_generator_configs(
376
+ question_encoder.config, generator.config, **kwargs
377
+ )
378
+
379
+ return cls(question_encoder=question_encoder, generator=generator, config=config, retriever=retriever)
380
+
381
+
382
+ @auto_docstring
383
+ class RagModel(RagPreTrainedModel):
384
+ def __init__(
385
+ self,
386
+ config: Optional[PretrainedConfig] = None,
387
+ question_encoder: Optional[PreTrainedModel] = None,
388
+ generator: Optional[PreTrainedModel] = None,
389
+ retriever: Optional[RagRetriever] = None, # or maybe just use a `set_retriever(...)` method
390
+ **kwargs,
391
+ ):
392
+ r"""
393
+ question_encoder (`PreTrainedModel`, *optional*):
394
+ The model responsible for encoding the question into hidden states for retrieval.
395
+ generator (`PreTrainedModel`, *optional*):
396
+ The model responsible for generating text based on retrieved documents.
397
+ retriever (`RagRetriever`, *optional*):
398
+ The component responsible for retrieving documents from a knowledge base given the encoded question.
399
+ """
400
+ assert config is not None or (question_encoder is not None and generator is not None), (
401
+ "Either a configuration or an question_encoder and a generator has to be provided."
402
+ )
403
+
404
+ if config is None:
405
+ config = RagConfig.from_question_encoder_generator_configs(
406
+ question_encoder.config, generator.config, **kwargs
407
+ )
408
+ else:
409
+ assert isinstance(config, self.config_class), f"config: {config} has to be of type {self.config_class}"
410
+ super().__init__(config)
411
+ if question_encoder is None:
412
+ from ..auto.modeling_auto import AutoModel
413
+
414
+ question_encoder = AutoModel.from_config(config.question_encoder)
415
+
416
+ if generator is None:
417
+ from ..auto.modeling_auto import AutoModelForSeq2SeqLM
418
+
419
+ generator = AutoModelForSeq2SeqLM.from_config(config.generator)
420
+
421
+ self.retriever = retriever
422
+ if self.retriever is not None:
423
+ assert isinstance(retriever, RagRetriever), (
424
+ f"`self.retriever` is of type {type(self.retriever)}, but should be of type `RagRetriever`"
425
+ )
426
+ self.retriever = retriever
427
+
428
+ self.question_encoder = question_encoder
429
+ self.generator = generator
430
+
431
+ self.ctx_encoder = None
432
+ self.context_encoder_training = False
433
+
434
+ @auto_docstring
435
+ def forward(
436
+ self,
437
+ input_ids: Optional[torch.LongTensor] = None,
438
+ attention_mask: Optional[torch.Tensor] = None,
439
+ encoder_outputs: Optional[tuple[tuple[torch.FloatTensor]]] = None,
440
+ decoder_input_ids: Optional[torch.LongTensor] = None,
441
+ decoder_attention_mask: Optional[torch.BoolTensor] = None,
442
+ past_key_values: Optional[Cache] = None,
443
+ doc_scores: Optional[torch.FloatTensor] = None,
444
+ context_input_ids: Optional[torch.LongTensor] = None,
445
+ context_attention_mask: Optional[torch.LongTensor] = None,
446
+ use_cache: Optional[bool] = None,
447
+ output_attentions: Optional[bool] = None,
448
+ output_hidden_states: Optional[bool] = None,
449
+ output_retrieved: Optional[bool] = None,
450
+ n_docs: Optional[int] = None,
451
+ ) -> Union[tuple[torch.Tensor], RetrievAugLMOutput]:
452
+ r"""
453
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
454
+ Indices of input sequence tokens in the vocabulary. [`RagConfig`], used to initialize the model, specifies
455
+ which generator to use, it also specifies a compatible generator tokenizer. Use that tokenizer class to
456
+ obtain the indices.
457
+
458
+ [What are input IDs?](../glossary#input-ids)
459
+ encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*)
460
+ Tuple consists of (`generator_enc_last_hidden_state`, *optional*: `generator_enc_hidden_states`,
461
+ *optional*: `generator_enc_attentions`). `generator_enc_last_hidden_state` of shape `(batch_size, n_docs *
462
+ sequence_length, hidden_size)` is a sequence of hidden-states at the output of the last layer of the
463
+ generator's encoder.
464
+
465
+ Used by the ([`RagModel`]) model during decoding.
466
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
467
+ Provide for generation tasks. `None` by default, construct as per instructions for the generator model
468
+ you're using with your RAG instance.
469
+ decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
470
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
471
+ be used by default.
472
+ doc_scores (`torch.FloatTensor` of shape `(batch_size, config.n_docs)`):
473
+ Score between each retrieved document embeddings (see `retrieved_doc_embeds`) and
474
+ `question_encoder_last_hidden_state`. If the model has is not initialized with a `retriever` `doc_scores`
475
+ has to be provided to the forward pass. `doc_scores` can be computed via
476
+ `question_encoder_last_hidden_state` and `retrieved_doc_embeds`, see examples for more information.
477
+ context_input_ids (`torch.LongTensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
478
+ Input IDs post-processed from the retrieved documents and the question encoder `input_ids` by the
479
+ retriever. If the model was not initialized with a `retriever` ``context_input_ids` has to be provided to
480
+ the forward pass. `context_input_ids` are returned by [`~RagRetriever.__call__`].
481
+ context_attention_mask (`torch.LongTensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`,*optional*, returned when *output_retrieved=True*):
482
+ Attention mask post-processed from the retrieved documents and the question encoder `input_ids` by the
483
+ retriever. If the model has is not initialized with a `retriever` `context_attention_mask` has to be
484
+ provided to the forward pass. `context_attention_mask` are returned by [`~RagRetriever.__call__`].
485
+ output_retrieved (`bool`, *optional*):
486
+ Whether or not to return the `retrieved_doc_embeds`, `retrieved_doc_ids`, `context_input_ids` and
487
+ `context_attention_mask`. See returned tensors for more detail.
488
+ n_docs (`int`, *optional*):
489
+ The number of documents to retrieve.
490
+
491
+ Example:
492
+
493
+ ```python
494
+ >>> from transformers import AutoTokenizer, RagRetriever, RagModel
495
+ >>> import torch
496
+
497
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/rag-token-base")
498
+ >>> retriever = RagRetriever.from_pretrained(
499
+ ... "facebook/rag-token-base", index_name="exact", use_dummy_dataset=True
500
+ ... )
501
+ >>> # initialize with RagRetriever to do everything in one forward call
502
+ >>> model = RagModel.from_pretrained("facebook/rag-token-base", retriever=retriever)
503
+
504
+ >>> inputs = tokenizer("How many people live in Paris?", return_tensors="pt")
505
+ >>> outputs = model(input_ids=inputs["input_ids"])
506
+ ```"""
507
+ n_docs = n_docs if n_docs is not None else self.config.n_docs
508
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
509
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
510
+ output_hidden_states = (
511
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
512
+ )
513
+ output_retrieved = output_retrieved if output_retrieved is not None else self.config.output_retrieved
514
+
515
+ # whether retriever has to be used
516
+ has_to_retrieve = (
517
+ self.retriever is not None
518
+ and (context_input_ids is None or context_attention_mask is None or doc_scores is None)
519
+ and encoder_outputs is None
520
+ )
521
+ # encoder_outputs are pre-computed during RAG-token generation
522
+ if encoder_outputs is None:
523
+ if has_to_retrieve:
524
+ question_enc_outputs = self.question_encoder(
525
+ input_ids, attention_mask=attention_mask, return_dict=True
526
+ )
527
+ question_encoder_last_hidden_state = question_enc_outputs[0] # hidden states of question encoder
528
+
529
+ retriever_outputs = self.retriever(
530
+ input_ids,
531
+ question_encoder_last_hidden_state.detach().to(device="cpu", dtype=torch.float32).numpy(),
532
+ prefix=self.generator.config.prefix,
533
+ n_docs=n_docs,
534
+ return_tensors="pt",
535
+ )
536
+ if self.context_encoder_training:
537
+ (
538
+ context_input_ids,
539
+ context_attention_mask,
540
+ retrieved_doc_embeds,
541
+ retrieved_doc_input_ids,
542
+ retrieved_doc_attention_mask,
543
+ retrieved_doc_ids,
544
+ ) = (
545
+ retriever_outputs["context_input_ids"],
546
+ retriever_outputs["context_attention_mask"],
547
+ retriever_outputs["retrieved_doc_embeds"],
548
+ retriever_outputs["tokenized_doc_ids"],
549
+ retriever_outputs["tokenized_doc_attention_mask"],
550
+ retriever_outputs["doc_ids"],
551
+ )
552
+
553
+ context_input_ids = context_input_ids.to(input_ids)
554
+ context_attention_mask = context_attention_mask.to(input_ids)
555
+
556
+ retrieved_doc_input_ids = retrieved_doc_input_ids.to(input_ids)
557
+ retrieved_doc_attention_mask = retrieved_doc_attention_mask.to(input_ids)
558
+ retrieved_doc_embeds = self.ctx_encoder(
559
+ retrieved_doc_input_ids, attention_mask=retrieved_doc_attention_mask, return_dict=True
560
+ ).pooler_output
561
+ retrieved_doc_embeds = retrieved_doc_embeds.view(
562
+ -1, n_docs, question_encoder_last_hidden_state.shape[1]
563
+ ) # reshaping
564
+
565
+ # compute doc_scores involving ctx_encoder
566
+ doc_scores = torch.bmm(
567
+ question_encoder_last_hidden_state.unsqueeze(1), retrieved_doc_embeds.transpose(1, 2)
568
+ ).squeeze(1)
569
+
570
+ else:
571
+ context_input_ids, context_attention_mask, retrieved_doc_embeds, retrieved_doc_ids = (
572
+ retriever_outputs["context_input_ids"],
573
+ retriever_outputs["context_attention_mask"],
574
+ retriever_outputs["retrieved_doc_embeds"],
575
+ retriever_outputs["doc_ids"],
576
+ )
577
+
578
+ # set to correct device
579
+ retrieved_doc_embeds = retrieved_doc_embeds.to(question_encoder_last_hidden_state)
580
+ context_input_ids = context_input_ids.to(input_ids)
581
+ context_attention_mask = context_attention_mask.to(input_ids)
582
+
583
+ # compute doc_scores
584
+ doc_scores = torch.bmm(
585
+ question_encoder_last_hidden_state.unsqueeze(1), retrieved_doc_embeds.transpose(1, 2)
586
+ ).squeeze(1)
587
+ else:
588
+ assert context_input_ids is not None, (
589
+ "Make sure that `context_input_ids` are passed, if no `retriever` is set. Alternatively, you can"
590
+ " set a retriever using the `set_retriever(...)` function."
591
+ )
592
+ assert context_attention_mask is not None, (
593
+ "Make sure that `context_attention_mask` are passed, if no `retriever` is set. Alternatively, you"
594
+ " can set a retriever using the `set_retriever(...)` function."
595
+ )
596
+ assert doc_scores is not None, (
597
+ "Make sure that `doc_scores` are passed, if no `retriever` is set. Alternatively, you can set a"
598
+ " retriever using the `set_retriever(...)` function."
599
+ )
600
+
601
+ assert doc_scores is not None, (
602
+ "Make sure that `doc_scores` are passed when passing `encoder_outputs` to the forward function."
603
+ )
604
+
605
+ assert (doc_scores.shape[1] % n_docs) == 0, (
606
+ f" The first dimension of `context_input_ids` should be a multiple of `n_docs`={n_docs}, but is"
607
+ f" {context_input_ids.shape[0]}."
608
+ )
609
+
610
+ # Decoder input without context documents
611
+ if decoder_input_ids is not None:
612
+ decoder_input_ids = decoder_input_ids.repeat_interleave(n_docs, dim=0)
613
+
614
+ if decoder_attention_mask is not None:
615
+ decoder_attention_mask = decoder_attention_mask.repeat_interleave(n_docs, dim=0)
616
+
617
+ gen_outputs = self.generator(
618
+ input_ids=context_input_ids,
619
+ attention_mask=context_attention_mask,
620
+ encoder_outputs=encoder_outputs,
621
+ decoder_input_ids=decoder_input_ids,
622
+ decoder_attention_mask=decoder_attention_mask,
623
+ past_key_values=past_key_values,
624
+ use_cache=use_cache,
625
+ output_attentions=output_attentions,
626
+ return_dict=True,
627
+ )
628
+
629
+ if not has_to_retrieve:
630
+ question_encoder_last_hidden_state = None
631
+ question_enc_hidden_states = None
632
+ question_enc_attentions = None
633
+ retrieved_doc_embeds = None
634
+ retrieved_doc_ids = None
635
+ else:
636
+ question_enc_hidden_states = question_enc_outputs.hidden_states
637
+ question_enc_attentions = question_enc_outputs.attentions
638
+
639
+ if not has_to_retrieve or not output_retrieved:
640
+ # don't output retrieved docs
641
+ context_input_ids = (None,)
642
+ context_attention_mask = None
643
+ retrieved_doc_embeds = None
644
+ retrieved_doc_ids = None
645
+
646
+ return RetrievAugLMOutput(
647
+ logits=gen_outputs.logits,
648
+ doc_scores=doc_scores,
649
+ past_key_values=gen_outputs.past_key_values,
650
+ context_input_ids=context_input_ids,
651
+ context_attention_mask=context_attention_mask,
652
+ retrieved_doc_embeds=retrieved_doc_embeds,
653
+ retrieved_doc_ids=retrieved_doc_ids,
654
+ question_encoder_last_hidden_state=question_encoder_last_hidden_state,
655
+ question_enc_hidden_states=question_enc_hidden_states,
656
+ question_enc_attentions=question_enc_attentions,
657
+ generator_enc_last_hidden_state=gen_outputs.encoder_last_hidden_state,
658
+ generator_enc_hidden_states=gen_outputs.encoder_hidden_states,
659
+ generator_enc_attentions=gen_outputs.encoder_attentions,
660
+ generator_dec_hidden_states=gen_outputs.decoder_hidden_states,
661
+ generator_dec_attentions=gen_outputs.decoder_attentions,
662
+ generator_cross_attentions=gen_outputs.cross_attentions,
663
+ )
664
+
665
+
666
+ @auto_docstring(
667
+ custom_intro="""
668
+ A RAG-sequence model implementation. It performs RAG-sequence specific marginalization in the forward pass.
669
+ """
670
+ )
671
+ class RagSequenceForGeneration(RagPreTrainedModel):
672
+ def __init__(
673
+ self,
674
+ config: Optional[PretrainedConfig] = None,
675
+ question_encoder: Optional[PreTrainedModel] = None,
676
+ generator: Optional[PreTrainedModel] = None,
677
+ retriever: Optional[RagRetriever] = None,
678
+ **kwargs,
679
+ ):
680
+ r"""
681
+ question_encoder (`PreTrainedModel`, *optional*):
682
+ The model responsible for encoding the question into hidden states for retrieval.
683
+ generator (`PreTrainedModel`, *optional*):
684
+ The model responsible for generating text based on retrieved documents.
685
+ retriever (`RagRetriever`, *optional*):
686
+ The component responsible for retrieving documents from a knowledge base given the encoded question.
687
+ """
688
+ assert config is not None or (question_encoder is not None and generator is not None), (
689
+ "Either a configuration or an encoder and a generator has to be provided."
690
+ )
691
+
692
+ if config is None:
693
+ config = RagConfig.from_question_encoder_generator_configs(
694
+ question_encoder.config, generator.config, **kwargs
695
+ )
696
+ super().__init__(config)
697
+
698
+ # instantiate model
699
+ self.rag = RagModel(config=config, question_encoder=question_encoder, generator=generator, retriever=retriever)
700
+
701
+ def set_retriever(self, retriever: RagRetriever):
702
+ self.rag.retriever = retriever
703
+
704
+ def set_context_encoder_for_training(self, ctx_encoder: PreTrainedModel):
705
+ self.rag.context_encoder_training = True
706
+ self.rag.ctx_encoder = ctx_encoder
707
+
708
+ @auto_docstring
709
+ def forward(
710
+ self,
711
+ input_ids: Optional[torch.LongTensor] = None,
712
+ attention_mask: Optional[torch.Tensor] = None,
713
+ encoder_outputs: Optional[tuple[tuple[torch.Tensor]]] = None,
714
+ decoder_input_ids: Optional[torch.LongTensor] = None,
715
+ decoder_attention_mask: Optional[torch.BoolTensor] = None,
716
+ past_key_values: Optional[Cache] = None,
717
+ context_input_ids: Optional[torch.LongTensor] = None,
718
+ context_attention_mask: Optional[torch.LongTensor] = None,
719
+ doc_scores: Optional[torch.FloatTensor] = None,
720
+ use_cache: Optional[bool] = None,
721
+ output_attentions: Optional[bool] = None,
722
+ output_hidden_states: Optional[bool] = None,
723
+ output_retrieved: Optional[bool] = None,
724
+ exclude_bos_score: Optional[bool] = None,
725
+ reduce_loss: Optional[bool] = None,
726
+ labels: Optional[torch.LongTensor] = None,
727
+ n_docs: Optional[int] = None,
728
+ **kwargs, # needs kwargs for generation
729
+ ) -> RetrievAugLMMarginOutput:
730
+ r"""
731
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
732
+ Indices of input sequence tokens in the vocabulary. [`RagConfig`], used to initialize the model, specifies
733
+ which generator to use, it also specifies a compatible generator tokenizer. Use that tokenizer class to
734
+ obtain the indices.
735
+
736
+ [What are input IDs?](../glossary#input-ids)
737
+ encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*)
738
+ Tuple consists of (`generator_enc_last_hidden_state`, *optional*: `generator_enc_hidden_states`,
739
+ *optional*: `generator_enc_attentions`). `generator_enc_last_hidden_state` of shape `(batch_size, n_docs *
740
+ sequence_length, hidden_size)` is a sequence of hidden-states at the output of the last layer of the
741
+ generator's encoder.
742
+
743
+ Used by the ([`RagModel`]) model during decoding.
744
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
745
+ Provide for generation tasks. `None` by default, construct as per instructions for the generator model
746
+ you're using with your RAG instance.
747
+ decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
748
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
749
+ be used by default.
750
+ context_input_ids (`torch.LongTensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
751
+ Input IDs post-processed from the retrieved documents and the question encoder `input_ids` by the
752
+ retriever. If the model was not initialized with a `retriever` ``context_input_ids` has to be provided to
753
+ the forward pass. `context_input_ids` are returned by [`~RagRetriever.__call__`].
754
+ context_attention_mask (`torch.LongTensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`,*optional*, returned when *output_retrieved=True*):
755
+ Attention mask post-processed from the retrieved documents and the question encoder `input_ids` by the
756
+ retriever. If the model has is not initialized with a `retriever` `context_attention_mask` has to be
757
+ provided to the forward pass. `context_attention_mask` are returned by [`~RagRetriever.__call__`].
758
+ doc_scores (`torch.FloatTensor` of shape `(batch_size, config.n_docs)`):
759
+ Score between each retrieved document embeddings (see `retrieved_doc_embeds`) and
760
+ `question_encoder_last_hidden_state`. If the model has is not initialized with a `retriever` `doc_scores`
761
+ has to be provided to the forward pass. `doc_scores` can be computed via
762
+ `question_encoder_last_hidden_state` and `retrieved_doc_embeds`, see examples for more information.
763
+ output_retrieved (`bool`, *optional*):
764
+ Whether or not to return the `retrieved_doc_embeds`, `retrieved_doc_ids`, `context_input_ids` and
765
+ `context_attention_mask`. See returned tensors for more detail.
766
+ exclude_bos_score (`bool`, *optional*):
767
+ Only relevant if `labels` is passed. If `True`, the score of the BOS token is disregarded when computing
768
+ the loss.
769
+ reduce_loss (`bool`, *optional*):
770
+ Only relevant if `labels` is passed. If `True`, the NLL loss is reduced using the `torch.Tensor.sum`
771
+ operation.
772
+ n_docs (`int`, *optional*):
773
+ The number of documents to retrieve.
774
+
775
+ Example:
776
+
777
+ ```python
778
+ >>> from transformers import AutoTokenizer, RagRetriever, RagSequenceForGeneration
779
+ >>> import torch
780
+
781
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/rag-sequence-nq")
782
+ >>> retriever = RagRetriever.from_pretrained(
783
+ ... "facebook/rag-sequence-nq", index_name="exact", use_dummy_dataset=True
784
+ ... )
785
+ >>> # initialize with RagRetriever to do everything in one forward call
786
+ >>> model = RagSequenceForGeneration.from_pretrained("facebook/rag-token-nq", retriever=retriever)
787
+
788
+ >>> inputs = tokenizer("How many people live in Paris?", return_tensors="pt")
789
+ >>> targets = tokenizer(text_target="In Paris, there are 10 million people.", return_tensors="pt")
790
+ >>> input_ids = inputs["input_ids"]
791
+ >>> labels = targets["input_ids"]
792
+ >>> outputs = model(input_ids=input_ids, labels=labels)
793
+
794
+ >>> # or use retriever separately
795
+ >>> model = RagSequenceForGeneration.from_pretrained("facebook/rag-sequence-nq", use_dummy_dataset=True)
796
+ >>> # 1. Encode
797
+ >>> question_hidden_states = model.question_encoder(input_ids)[0]
798
+ >>> # 2. Retrieve
799
+ >>> docs_dict = retriever(input_ids.numpy(), question_hidden_states.detach().numpy(), return_tensors="pt")
800
+ >>> doc_scores = torch.bmm(
801
+ ... question_hidden_states.unsqueeze(1), docs_dict["retrieved_doc_embeds"].float().transpose(1, 2)
802
+ ... ).squeeze(1)
803
+ >>> # 3. Forward to generator
804
+ >>> outputs = model(
805
+ ... context_input_ids=docs_dict["context_input_ids"],
806
+ ... context_attention_mask=docs_dict["context_attention_mask"],
807
+ ... doc_scores=doc_scores,
808
+ ... decoder_input_ids=labels,
809
+ ... )
810
+ ```"""
811
+ n_docs = n_docs if n_docs is not None else self.config.n_docs
812
+ exclude_bos_score = exclude_bos_score if exclude_bos_score is not None else self.config.exclude_bos_score
813
+ reduce_loss = reduce_loss if reduce_loss is not None else self.config.reduce_loss
814
+
815
+ if labels is not None:
816
+ if decoder_input_ids is None:
817
+ decoder_input_ids = labels
818
+ use_cache = False
819
+
820
+ outputs = self.rag(
821
+ input_ids=input_ids,
822
+ attention_mask=attention_mask,
823
+ encoder_outputs=encoder_outputs,
824
+ decoder_input_ids=decoder_input_ids,
825
+ decoder_attention_mask=decoder_attention_mask,
826
+ context_input_ids=context_input_ids,
827
+ context_attention_mask=context_attention_mask,
828
+ doc_scores=doc_scores,
829
+ past_key_values=past_key_values,
830
+ use_cache=use_cache,
831
+ output_attentions=output_attentions,
832
+ output_hidden_states=output_hidden_states,
833
+ output_retrieved=output_retrieved,
834
+ n_docs=n_docs,
835
+ )
836
+
837
+ loss = None
838
+ if labels is not None:
839
+ loss = self.get_nll(
840
+ outputs.logits,
841
+ outputs.doc_scores,
842
+ decoder_input_ids,
843
+ reduce_loss=reduce_loss,
844
+ epsilon=self.config.label_smoothing,
845
+ exclude_bos_score=exclude_bos_score,
846
+ n_docs=n_docs,
847
+ )
848
+
849
+ return RetrievAugLMMarginOutput(
850
+ loss=loss,
851
+ logits=outputs.logits,
852
+ doc_scores=outputs.doc_scores,
853
+ past_key_values=outputs.past_key_values,
854
+ context_input_ids=outputs.context_input_ids,
855
+ context_attention_mask=outputs.context_attention_mask,
856
+ retrieved_doc_embeds=outputs.retrieved_doc_embeds,
857
+ retrieved_doc_ids=outputs.retrieved_doc_ids,
858
+ question_encoder_last_hidden_state=outputs.question_encoder_last_hidden_state,
859
+ question_enc_hidden_states=outputs.question_enc_hidden_states,
860
+ question_enc_attentions=outputs.question_enc_attentions,
861
+ generator_enc_last_hidden_state=outputs.generator_enc_last_hidden_state,
862
+ generator_enc_hidden_states=outputs.generator_enc_hidden_states,
863
+ generator_enc_attentions=outputs.generator_enc_attentions,
864
+ generator_dec_hidden_states=outputs.generator_dec_hidden_states,
865
+ generator_dec_attentions=outputs.generator_dec_attentions,
866
+ generator_cross_attentions=outputs.generator_cross_attentions,
867
+ )
868
+
869
+ @property
870
+ def retriever(self):
871
+ return self.rag.retriever
872
+
873
+ @property
874
+ def generator(self):
875
+ return self.rag.generator
876
+
877
+ @property
878
+ def question_encoder(self):
879
+ return self.rag.question_encoder
880
+
881
+ @torch.no_grad()
882
+ def generate(
883
+ self,
884
+ input_ids: Optional[torch.LongTensor] = None,
885
+ attention_mask: Optional[torch.LongTensor] = None,
886
+ context_input_ids: Optional[torch.LongTensor] = None,
887
+ context_attention_mask: Optional[torch.LongTensor] = None,
888
+ doc_scores: Optional[torch.FloatTensor] = None,
889
+ do_deduplication: Optional[bool] = None, # defaults to True
890
+ num_return_sequences: Optional[int] = None, # defaults to 1
891
+ num_beams: Optional[int] = None, # defaults to 1
892
+ n_docs: Optional[int] = None,
893
+ **model_kwargs,
894
+ ) -> torch.LongTensor:
895
+ """
896
+ Implements RAG sequence "thorough" decoding. Read the [`~generation.GenerationMixin.generate`]` documentation
897
+ for more information on how to set other generate input parameters.
898
+
899
+ Args:
900
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
901
+ The sequence used as a prompt for the generation. If `input_ids` is not passed, then
902
+ `context_input_ids` has to be provided.
903
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
904
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
905
+
906
+ - 1 for tokens that are **not masked**,
907
+ - 0 for tokens that are **masked**.
908
+
909
+ [What are attention masks?](../glossary#attention-mask)
910
+ context_input_ids (`torch.LongTensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
911
+ Input IDs post-processed from the retrieved documents and the question encoder input_ids by the
912
+ retriever.
913
+ context_attention_mask (`torch.LongTensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
914
+ Attention mask post-processed from the retrieved documents and the question encoder `input_ids` by the
915
+ retriever.
916
+
917
+ If the model is not initialized with a `retriever` or `input_ids` is not given, `context_input_ids` and
918
+ `context_attention_mask` have to be provided to the forward pass. They are returned by
919
+ [`~RagRetriever.__call__`].
920
+ doc_scores (`torch.FloatTensor` of shape `(batch_size, config.n_docs)`):
921
+ Score between each retrieved document embeddings (see `retrieved_doc_embeds`) and
922
+ `question_encoder_last_hidden_state`.
923
+
924
+ If the model is not initialized with a `retriever` or `input_ids` is not given, `doc_scores` has to be
925
+ provided to the forward pass. `doc_scores` are returned by [`~RagRetriever.__call__`].
926
+ do_deduplication (`bool`, *optional*):
927
+ Whether or not to deduplicate the generations from different context documents for a given input. Has
928
+ to be set to `False` if used while training with distributed backend.
929
+ num_return_sequences(`int`, *optional*, defaults to 1):
930
+ The number of independently computed returned sequences for each element in the batch. Note that this
931
+ is not the value we pass to the `generator`'s `[`~generation.GenerationMixin.generate`]` function,
932
+ where we set `num_return_sequences` to `num_beams`.
933
+ num_beams (`int`, *optional*, defaults to 1):
934
+ Number of beams for beam search. 1 means no beam search.
935
+ n_docs (`int`, *optional*, defaults to `config.n_docs`)
936
+ Number of documents to retrieve and/or number of documents for which to generate an answer.
937
+ kwargs (`dict[str, Any]`, *optional*):
938
+ Additional kwargs will be passed to [`~generation.GenerationMixin.generate`].
939
+
940
+ Return:
941
+ `torch.LongTensor` of shape `(batch_size * num_return_sequences, sequence_length)`: The generated
942
+ sequences. The second dimension (sequence length) is either equal to `max_length` or shorter if all batches
943
+ finished early due to the `eos_token_id`.
944
+ """
945
+
946
+ n_docs = n_docs if n_docs is not None else self.config.n_docs
947
+ do_deduplication = do_deduplication if do_deduplication is not None else self.config.do_deduplication
948
+ num_doc_return_sequences = (
949
+ num_return_sequences if num_return_sequences is not None else self.config.num_return_sequences
950
+ )
951
+ num_beams = num_beams if num_beams is not None else self.config.num_beams
952
+
953
+ assert input_ids is not None or context_input_ids is not None, (
954
+ " At least one of input_ids or context_input_ids must be given"
955
+ )
956
+
957
+ if self.retriever is not None and context_input_ids is None:
958
+ question_hidden_states = self.question_encoder(input_ids, attention_mask=attention_mask)[0]
959
+ context_input_ids = self.retriever(
960
+ input_ids,
961
+ question_hidden_states.detach().to(device="cpu", dtype=torch.float32).numpy(),
962
+ prefix=self.generator.config.prefix,
963
+ n_docs=n_docs,
964
+ return_tensors="pt",
965
+ )["context_input_ids"]
966
+
967
+ # set to correct device
968
+ context_input_ids = context_input_ids.to(input_ids)
969
+
970
+ hypos = []
971
+ model_kwargs["num_beams"] = num_beams
972
+ model_kwargs["num_return_sequences"] = num_beams
973
+ model_kwargs["attention_mask"] = None
974
+
975
+ batch_size = input_ids.shape[0] if input_ids is not None else context_input_ids.shape[0] // n_docs
976
+
977
+ for index in range(batch_size):
978
+ # first, generate beams from documents:
979
+ generator_input_ids = context_input_ids[index * n_docs : (index + 1) * n_docs] # (n_docs, max_len)
980
+
981
+ output_sequences = self.generator.generate(
982
+ generator_input_ids,
983
+ **model_kwargs,
984
+ ) # n_docs * n_beam, tgt_len
985
+ if do_deduplication:
986
+ # do_deduplication, max_output_len
987
+ output_sequences = torch.stack(list({str(k.tolist()): k for k in output_sequences}.values()))
988
+
989
+ num_candidates = output_sequences.shape[
990
+ 0
991
+ ] # after deduplication, this number can be less than n_docs*n_beam
992
+
993
+ # then, run model forwards to get nll scores:
994
+ if input_ids is not None:
995
+ new_input_ids = input_ids[index : index + 1].repeat(num_candidates, 1)
996
+ outputs = self(new_input_ids, labels=output_sequences, exclude_bos_score=True)
997
+ else: # input_ids is None, need context_input_ids/mask and doc_scores
998
+ assert context_attention_mask is not None, (
999
+ "Make sure that `context_attention_mask` are passed, if no `input_ids` is set. Alternatively, you"
1000
+ " can set a retriever using the `set_retriever(...)` function."
1001
+ )
1002
+ assert doc_scores is not None, (
1003
+ "Make sure that `doc_scores` are passed, if no `input_ids` is set. Alternatively, you can set a"
1004
+ " retriever using the `set_retriever(...)` function."
1005
+ )
1006
+
1007
+ individual_input_ids = generator_input_ids.repeat(
1008
+ num_candidates, 1
1009
+ ) # (num_candidates*n_docs, max_len)
1010
+
1011
+ individual_attention_mask = context_attention_mask[index * n_docs : (index + 1) * n_docs]
1012
+ individual_attention_mask = individual_attention_mask.repeat(num_candidates, 1)
1013
+
1014
+ individual_doc_scores = doc_scores[index : (index + 1), :] # doc_scores.shape = [batch, n_docs]
1015
+ individual_doc_scores = individual_doc_scores.repeat(num_candidates, 1) # [num_candidates, n_docs]
1016
+
1017
+ outputs = self(
1018
+ context_input_ids=individual_input_ids,
1019
+ context_attention_mask=individual_attention_mask,
1020
+ doc_scores=individual_doc_scores,
1021
+ labels=output_sequences,
1022
+ exclude_bos_score=True,
1023
+ )
1024
+
1025
+ top_cand_inds = (-outputs["loss"]).topk(num_doc_return_sequences)[1]
1026
+
1027
+ # add hypothesis
1028
+ hypos.append(output_sequences[top_cand_inds])
1029
+
1030
+ return self._cat_and_pad(hypos, pad_token_id=self.config.generator.pad_token_id)
1031
+
1032
+ def get_nll(
1033
+ self, seq_logits, doc_scores, target, reduce_loss=False, epsilon=0.0, exclude_bos_score=False, n_docs=None
1034
+ ):
1035
+ # shift tokens left
1036
+ target = torch.cat(
1037
+ [target[:, 1:], target.new(target.shape[0], 1).fill_(self.config.generator.pad_token_id)], 1
1038
+ )
1039
+
1040
+ n_docs = n_docs if n_docs is not None else self.config.n_docs
1041
+
1042
+ # bos_token_id is None for T5
1043
+ bos_token_id = self.config.bos_token_id or self.config.generator.bos_token_id
1044
+ use_bos = bos_token_id is not None and target[:, 0].eq(bos_token_id).all()
1045
+
1046
+ def _mask_pads(ll, smooth_obj):
1047
+ pad_mask = target.eq(self.config.generator.pad_token_id)
1048
+ if pad_mask.any():
1049
+ ll.masked_fill_(pad_mask, 0.0)
1050
+ smooth_obj.masked_fill_(pad_mask, 0.0)
1051
+ return ll.squeeze(-1), smooth_obj.squeeze(-1)
1052
+
1053
+ # seq_logits dim = (batch*n_docs, tgt_len , #vocabs)
1054
+ seq_logprobs = nn.functional.log_softmax(seq_logits, dim=-1).view(
1055
+ seq_logits.shape[0] // n_docs, n_docs, -1, seq_logits.size(-1)
1056
+ ) # batch_size x n_docs x tgt_len x #vocab_size
1057
+ doc_logprobs = nn.functional.log_softmax(doc_scores, dim=1).unsqueeze(-1).unsqueeze(-1)
1058
+
1059
+ # RAG-sequence marginalization
1060
+ first_token_scores = seq_logprobs[:, :, :1, :]
1061
+ second_token_scores = seq_logprobs[:, :, 1:2, :]
1062
+ remainder = seq_logprobs[:, :, 2:, :]
1063
+ rag_logprobs = torch.cat([first_token_scores, second_token_scores + doc_logprobs, remainder], dim=2)
1064
+
1065
+ # calculate loss
1066
+ target = target.unsqueeze(1).unsqueeze(-1).repeat(1, n_docs, 1, 1)
1067
+ assert target.dim() == rag_logprobs.dim()
1068
+
1069
+ ll = rag_logprobs.gather(dim=-1, index=target)
1070
+ smooth_obj = rag_logprobs.sum(dim=-1, keepdim=True) # total sum of all (normalised) logits
1071
+
1072
+ ll, smooth_obj = _mask_pads(ll, smooth_obj)
1073
+
1074
+ # sum over tokens, exclude bos while scoring
1075
+ ll = ll[:, :, 1:].sum(2) if exclude_bos_score and use_bos else ll.sum(2)
1076
+ smooth_obj = smooth_obj.sum(2)
1077
+ ll = ll.logsumexp(1) # logsumexp over docs
1078
+ smooth_obj = smooth_obj.logsumexp(1)
1079
+
1080
+ nll_loss = -ll
1081
+ smooth_loss = -smooth_obj
1082
+
1083
+ if reduce_loss:
1084
+ nll_loss = nll_loss.sum()
1085
+ smooth_loss = smooth_loss.sum()
1086
+
1087
+ eps_i = epsilon / rag_logprobs.size(-1)
1088
+ loss = (1.0 - epsilon) * nll_loss + eps_i * smooth_loss
1089
+ return loss
1090
+
1091
+ @staticmethod
1092
+ def _cat_and_pad(tensors, pad_token_id):
1093
+ output = (
1094
+ tensors[0].new(sum([t.shape[0] for t in tensors]), max([t.shape[1] for t in tensors])).fill_(pad_token_id)
1095
+ )
1096
+ ind = 0
1097
+ for t in tensors:
1098
+ output[ind : ind + t.shape[0], : t.shape[1]] = t
1099
+ ind += t.shape[0]
1100
+ return output
1101
+
1102
+
1103
+ @auto_docstring(
1104
+ custom_intro="""
1105
+ A RAG-token model implementation. It performs RAG-token specific marginalization in the forward pass.
1106
+ """
1107
+ )
1108
+ class RagTokenForGeneration(RagPreTrainedModel, GenerationMixin):
1109
+ def __init__(
1110
+ self,
1111
+ config: Optional[PretrainedConfig] = None,
1112
+ question_encoder: Optional[PreTrainedModel] = None,
1113
+ generator: Optional[PreTrainedModel] = None,
1114
+ retriever: Optional[RagRetriever] = None,
1115
+ **kwargs,
1116
+ ):
1117
+ r"""
1118
+ question_encoder (`PreTrainedModel`, *optional*):
1119
+ The model responsible for encoding the question into hidden states for retrieval.
1120
+ generator (`PreTrainedModel`, *optional*):
1121
+ The model responsible for generating text based on retrieved documents.
1122
+ retriever (`RagRetriever`, *optional*):
1123
+ The component responsible for retrieving documents from a knowledge base given the encoded question.
1124
+ """
1125
+ assert config is not None or (question_encoder is not None and generator is not None), (
1126
+ "Either a configuration or an encoder and a generator has to be provided."
1127
+ )
1128
+
1129
+ if config is None:
1130
+ config = RagConfig.from_question_encoder_generator_configs(
1131
+ question_encoder.config, generator.config, **kwargs
1132
+ )
1133
+
1134
+ super().__init__(config)
1135
+
1136
+ # instantiate model
1137
+ self.rag = RagModel(config=config, question_encoder=question_encoder, generator=generator, retriever=retriever)
1138
+
1139
+ def set_retriever(self, retriever: RagRetriever):
1140
+ self.rag.retriever = retriever
1141
+
1142
+ def set_context_encoder_for_training(self, ctx_encoder: PreTrainedModel):
1143
+ self.rag.context_encoder_training = True
1144
+ self.rag.ctx_encoder = ctx_encoder
1145
+
1146
+ def prepare_inputs_for_generation(
1147
+ self,
1148
+ decoder_input_ids,
1149
+ past_key_values=None,
1150
+ attention_mask=None,
1151
+ use_cache=None,
1152
+ encoder_outputs=None,
1153
+ doc_scores=None,
1154
+ n_docs=None,
1155
+ **kwargs,
1156
+ ):
1157
+ # Overwritten -- `do_marginalize` is explicitly set in the output
1158
+
1159
+ if past_key_values is not None:
1160
+ # if past is defined use only last decoder_input_ids
1161
+ decoder_input_ids = decoder_input_ids[:, -1:]
1162
+
1163
+ return {
1164
+ "input_ids": None,
1165
+ "encoder_outputs": encoder_outputs,
1166
+ "doc_scores": doc_scores,
1167
+ "context_attention_mask": attention_mask,
1168
+ "decoder_input_ids": decoder_input_ids,
1169
+ "past_key_values": past_key_values,
1170
+ "use_cache": use_cache,
1171
+ "do_marginalize": True,
1172
+ "n_docs": n_docs,
1173
+ }
1174
+
1175
+ @property
1176
+ def retriever(self):
1177
+ return self.rag.retriever
1178
+
1179
+ @property
1180
+ def generator(self):
1181
+ return self.rag.generator
1182
+
1183
+ @property
1184
+ def question_encoder(self):
1185
+ return self.rag.question_encoder
1186
+
1187
+ @staticmethod
1188
+ def _reorder_cache(past_key_values, beam_idx):
1189
+ """Reorders cache for generation. BART-inspired but we need to take care of the extra dimension for docs"""
1190
+
1191
+ def _reorder_stacked(hidden_states, new_order):
1192
+ n_docs = hidden_states.shape[0] // new_order.shape[0]
1193
+ hidden_states = hidden_states.view(-1, n_docs, *hidden_states.shape[1:])
1194
+ hidden_states = hidden_states.index_select(0, new_order)
1195
+ result = hidden_states.view(-1, *hidden_states.shape[2:])
1196
+ return result
1197
+
1198
+ reordered_past = ()
1199
+ for layer_past in past_key_values:
1200
+ # get the correct batch idx from decoder layer's batch dim for cross and self-attn
1201
+ reordered_past += (
1202
+ tuple(_reorder_stacked(past_state, beam_idx.to(past_state.device)) for past_state in layer_past),
1203
+ )
1204
+ if isinstance(past_key_values, EncoderDecoderCache):
1205
+ reordered_past = EncoderDecoderCache.from_legacy_cache(reordered_past)
1206
+
1207
+ return reordered_past
1208
+
1209
+ def marginalize(self, seq_logits, doc_scores, n_docs=None):
1210
+ n_docs = n_docs if n_docs is not None else self.config.n_docs
1211
+
1212
+ # RAG-token marginalization
1213
+ seq_logprobs = nn.functional.log_softmax(seq_logits, dim=-1).view(
1214
+ seq_logits.shape[0] // n_docs, n_docs, -1, seq_logits.size(-1)
1215
+ )
1216
+ doc_logprobs = torch.log_softmax(doc_scores, dim=1)
1217
+ log_prob_sum = seq_logprobs + doc_logprobs.unsqueeze(-1).unsqueeze(-1)
1218
+ return torch.logsumexp(log_prob_sum, dim=1)
1219
+
1220
+ @auto_docstring
1221
+ def forward(
1222
+ self,
1223
+ input_ids: Optional[torch.LongTensor] = None,
1224
+ attention_mask: Optional[torch.FloatTensor] = None,
1225
+ encoder_outputs: Optional[tuple[tuple[torch.Tensor]]] = None,
1226
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1227
+ decoder_attention_mask: Optional[torch.BoolTensor] = None,
1228
+ past_key_values: Optional[Cache] = None,
1229
+ context_input_ids: Optional[torch.LongTensor] = None,
1230
+ context_attention_mask: Optional[torch.LongTensor] = None,
1231
+ doc_scores: Optional[torch.FloatTensor] = None,
1232
+ use_cache: Optional[bool] = None,
1233
+ output_attentions: Optional[bool] = None,
1234
+ output_hidden_states: Optional[bool] = None,
1235
+ output_retrieved: Optional[bool] = None,
1236
+ do_marginalize: Optional[bool] = None,
1237
+ reduce_loss: Optional[bool] = None,
1238
+ labels: Optional[torch.LongTensor] = None,
1239
+ n_docs: Optional[int] = None,
1240
+ **kwargs, # needs kwargs for generation
1241
+ ) -> RetrievAugLMMarginOutput:
1242
+ r"""
1243
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1244
+ Indices of input sequence tokens in the vocabulary. [`RagConfig`], used to initialize the model, specifies
1245
+ which generator to use, it also specifies a compatible generator tokenizer. Use that tokenizer class to
1246
+ obtain the indices.
1247
+
1248
+ [What are input IDs?](../glossary#input-ids)
1249
+ encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*)
1250
+ Tuple consists of (`generator_enc_last_hidden_state`, *optional*: `generator_enc_hidden_states`,
1251
+ *optional*: `generator_enc_attentions`). `generator_enc_last_hidden_state` of shape `(batch_size, n_docs *
1252
+ sequence_length, hidden_size)` is a sequence of hidden-states at the output of the last layer of the
1253
+ generator's encoder.
1254
+
1255
+ Used by the ([`RagModel`]) model during decoding.
1256
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1257
+ Provide for generation tasks. `None` by default, construct as per instructions for the generator model
1258
+ you're using with your RAG instance.
1259
+ decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1260
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
1261
+ be used by default.
1262
+ context_input_ids (`torch.LongTensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
1263
+ Input IDs post-processed from the retrieved documents and the question encoder `input_ids` by the
1264
+ retriever. If the model was not initialized with a `retriever` ``context_input_ids` has to be provided to
1265
+ the forward pass. `context_input_ids` are returned by [`~RagRetriever.__call__`].
1266
+ context_attention_mask (`torch.LongTensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`,*optional*, returned when *output_retrieved=True*):
1267
+ Attention mask post-processed from the retrieved documents and the question encoder `input_ids` by the
1268
+ retriever. If the model has is not initialized with a `retriever` `context_attention_mask` has to be
1269
+ provided to the forward pass. `context_attention_mask` are returned by [`~RagRetriever.__call__`].
1270
+ doc_scores (`torch.FloatTensor` of shape `(batch_size, config.n_docs)`):
1271
+ Score between each retrieved document embeddings (see `retrieved_doc_embeds`) and
1272
+ `question_encoder_last_hidden_state`. If the model has is not initialized with a `retriever` `doc_scores`
1273
+ has to be provided to the forward pass. `doc_scores` can be computed via
1274
+ `question_encoder_last_hidden_state` and `retrieved_doc_embeds`, see examples for more information.
1275
+ output_retrieved (`bool`, *optional*):
1276
+ Whether or not to return the `retrieved_doc_embeds`, `retrieved_doc_ids`, `context_input_ids` and
1277
+ `context_attention_mask`. See returned tensors for more detail.
1278
+ do_marginalize (`bool`, *optional*):
1279
+ If `True`, the logits are marginalized over all documents by making use of
1280
+ `torch.nn.functional.log_softmax`.
1281
+ reduce_loss (`bool`, *optional*):
1282
+ Only relevant if `labels` is passed. If `True`, the NLL loss is reduced using the `torch.Tensor.sum`
1283
+ operation.
1284
+ n_docs (`int`, *optional*):
1285
+ The number of documents to retrieve.
1286
+
1287
+ Example:
1288
+
1289
+ ```python
1290
+ >>> from transformers import AutoTokenizer, RagRetriever, RagTokenForGeneration
1291
+ >>> import torch
1292
+
1293
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/rag-token-nq")
1294
+ >>> retriever = RagRetriever.from_pretrained(
1295
+ ... "facebook/rag-token-nq", index_name="exact", use_dummy_dataset=True
1296
+ ... )
1297
+ >>> # initialize with RagRetriever to do everything in one forward call
1298
+ >>> model = RagTokenForGeneration.from_pretrained("facebook/rag-token-nq", retriever=retriever)
1299
+
1300
+ >>> inputs = tokenizer("How many people live in Paris?", return_tensors="pt")
1301
+ >>> targets = tokenizer(text_target="In Paris, there are 10 million people.", return_tensors="pt")
1302
+ >>> input_ids = inputs["input_ids"]
1303
+ >>> labels = targets["input_ids"]
1304
+ >>> outputs = model(input_ids=input_ids, labels=labels)
1305
+
1306
+ >>> # or use retriever separately
1307
+ >>> model = RagTokenForGeneration.from_pretrained("facebook/rag-token-nq", use_dummy_dataset=True)
1308
+ >>> # 1. Encode
1309
+ >>> question_hidden_states = model.question_encoder(input_ids)[0]
1310
+ >>> # 2. Retrieve
1311
+ >>> docs_dict = retriever(input_ids.numpy(), question_hidden_states.detach().numpy(), return_tensors="pt")
1312
+ >>> doc_scores = torch.bmm(
1313
+ ... question_hidden_states.unsqueeze(1), docs_dict["retrieved_doc_embeds"].float().transpose(1, 2)
1314
+ ... ).squeeze(1)
1315
+ >>> # 3. Forward to generator
1316
+ >>> outputs = model(
1317
+ ... context_input_ids=docs_dict["context_input_ids"],
1318
+ ... context_attention_mask=docs_dict["context_attention_mask"],
1319
+ ... doc_scores=doc_scores,
1320
+ ... decoder_input_ids=labels,
1321
+ ... )
1322
+
1323
+ >>> # or directly generate
1324
+ >>> generated = model.generate(
1325
+ ... context_input_ids=docs_dict["context_input_ids"],
1326
+ ... context_attention_mask=docs_dict["context_attention_mask"],
1327
+ ... doc_scores=doc_scores,
1328
+ ... )
1329
+ >>> generated_string = tokenizer.batch_decode(generated, skip_special_tokens=True)
1330
+ ```"""
1331
+ n_docs = n_docs if n_docs is not None else self.config.n_docs
1332
+ do_marginalize = do_marginalize if do_marginalize is not None else self.config.do_marginalize
1333
+ reduce_loss = reduce_loss if reduce_loss is not None else self.config.reduce_loss
1334
+
1335
+ if labels is not None:
1336
+ if decoder_input_ids is None:
1337
+ decoder_input_ids = labels
1338
+ use_cache = False
1339
+
1340
+ outputs = self.rag(
1341
+ input_ids=input_ids,
1342
+ attention_mask=attention_mask,
1343
+ encoder_outputs=encoder_outputs,
1344
+ decoder_input_ids=decoder_input_ids,
1345
+ decoder_attention_mask=decoder_attention_mask,
1346
+ context_input_ids=context_input_ids,
1347
+ context_attention_mask=context_attention_mask,
1348
+ doc_scores=doc_scores,
1349
+ past_key_values=past_key_values,
1350
+ use_cache=use_cache,
1351
+ output_attentions=output_attentions,
1352
+ output_hidden_states=output_hidden_states,
1353
+ output_retrieved=output_retrieved,
1354
+ n_docs=n_docs,
1355
+ )
1356
+
1357
+ loss = None
1358
+ logits = outputs.logits
1359
+ if labels is not None:
1360
+ assert decoder_input_ids is not None
1361
+ loss = self.get_nll(
1362
+ outputs.logits,
1363
+ outputs.doc_scores,
1364
+ labels,
1365
+ reduce_loss=reduce_loss,
1366
+ epsilon=self.config.label_smoothing,
1367
+ n_docs=n_docs,
1368
+ )
1369
+
1370
+ if do_marginalize:
1371
+ logits = self.marginalize(logits, outputs.doc_scores, n_docs)
1372
+
1373
+ return RetrievAugLMMarginOutput(
1374
+ loss=loss,
1375
+ logits=logits,
1376
+ doc_scores=outputs.doc_scores,
1377
+ past_key_values=outputs.past_key_values,
1378
+ context_input_ids=outputs.context_input_ids,
1379
+ context_attention_mask=outputs.context_attention_mask,
1380
+ retrieved_doc_embeds=outputs.retrieved_doc_embeds,
1381
+ retrieved_doc_ids=outputs.retrieved_doc_ids,
1382
+ question_encoder_last_hidden_state=outputs.question_encoder_last_hidden_state,
1383
+ question_enc_hidden_states=outputs.question_enc_hidden_states,
1384
+ question_enc_attentions=outputs.question_enc_attentions,
1385
+ generator_enc_last_hidden_state=outputs.generator_enc_last_hidden_state,
1386
+ generator_enc_hidden_states=outputs.generator_enc_hidden_states,
1387
+ generator_enc_attentions=outputs.generator_enc_attentions,
1388
+ generator_dec_hidden_states=outputs.generator_dec_hidden_states,
1389
+ generator_dec_attentions=outputs.generator_dec_attentions,
1390
+ generator_cross_attentions=outputs.generator_cross_attentions,
1391
+ )
1392
+
1393
+ @torch.no_grad()
1394
+ def generate(
1395
+ self,
1396
+ input_ids: Optional[torch.LongTensor] = None,
1397
+ attention_mask: Optional[torch.LongTensor] = None,
1398
+ context_input_ids: Optional[torch.LongTensor] = None,
1399
+ context_attention_mask: Optional[torch.LongTensor] = None,
1400
+ doc_scores: Optional[torch.FloatTensor] = None,
1401
+ n_docs: Optional[int] = None,
1402
+ generation_config: Optional[GenerationConfig] = None,
1403
+ prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], list[int]]] = None,
1404
+ logits_processor: Optional[LogitsProcessorList] = LogitsProcessorList(),
1405
+ stopping_criteria: Optional[StoppingCriteriaList] = StoppingCriteriaList(),
1406
+ **kwargs,
1407
+ ) -> torch.LongTensor:
1408
+ """
1409
+ Implements RAG token decoding.
1410
+
1411
+ Args:
1412
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1413
+ The sequence used as a prompt for the generation. If `input_ids` is not passed, then
1414
+ `context_input_ids` has to be provided.
1415
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1416
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1417
+
1418
+ - 1 for tokens that are **not masked**,
1419
+ - 0 for tokens that are **masked**.
1420
+
1421
+ [What are attention masks?](../glossary#attention-mask)
1422
+ context_input_ids (`torch.LongTensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
1423
+ Input IDs post-processed from the retrieved documents and the question encoder `input_ids` by the
1424
+ retriever.
1425
+
1426
+ If the model has is not initialized with a `retriever`, `context_input_ids` has to be provided to the
1427
+ forward pass. `context_input_ids` are returned by [`~RagRetriever.__call__`].
1428
+ context_attention_mask (`torch.LongTensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
1429
+ Attention mask post-processed from the retrieved documents and the question encoder `input_ids` by the
1430
+ retriever.
1431
+
1432
+ If the model has is not initialized with a `retriever`, `context_input_ids` has to be provided to the
1433
+ forward pass. `context_input_ids` are returned by [`~RagRetriever.__call__`].
1434
+ doc_scores (`torch.FloatTensor` of shape `(batch_size, config.n_docs)`):
1435
+ Score between each retrieved document embeddings (see `retrieved_doc_embeds`) and
1436
+ `question_encoder_last_hidden_state`.
1437
+
1438
+ If the model has is not initialized with a `retriever`, `context_input_ids` has to be provided to the
1439
+ forward pass. `context_input_ids` are returned by [`~RagRetriever.__call__`].
1440
+ n_docs (`int`, *optional*, defaults to `config.n_docs`)
1441
+ Number of documents to retrieve and/or number of documents for which to generate an answer.
1442
+ generation_config (`~generation.GenerationConfig`, *optional*):
1443
+ The generation configuration to be used as base parametrization for the generation call. `**kwargs`
1444
+ passed to generate matching the attributes of `generation_config` will override them. If
1445
+ `generation_config` is not provided, the default will be used, which has the following loading
1446
+ priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model
1447
+ configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s
1448
+ default values, whose documentation should be checked to parameterize generation.
1449
+ prefix_allowed_tokens_fn (`Callable[[int, torch.Tensor], list[int]]`, *optional*):
1450
+ If provided, this function constraints the beam search to allowed tokens only at each step. If not
1451
+ provided no constraint is applied. This function takes 2 arguments `inputs_ids` and the batch ID
1452
+ `batch_id`. It has to return a list with the allowed tokens for the next generation step conditioned on
1453
+ the previously generated tokens `inputs_ids` and the batch ID `batch_id`. This argument is useful for
1454
+ constrained generation conditioned on the prefix, as described in [Autoregressive Entity
1455
+ Retrieval](https://huggingface.co/papers/2010.00904).
1456
+ logits_processor (`LogitsProcessorList`, *optional*):
1457
+ Custom logits processors that complement the default logits processors built from arguments and a
1458
+ model's config. If a logit processor is passed that is already created with the arguments or a model's
1459
+ config an error is thrown.
1460
+ stopping_criteria (`StoppingCriteriaList`, *optional*):
1461
+ Custom stopping criteria that complement the default stopping criteria built from arguments and a
1462
+ model's config. If a stopping criteria is passed that is already created with the arguments or a
1463
+ model's config an error is thrown.
1464
+ kwargs (`dict[str, Any]`, *optional*):
1465
+ Ad hoc parametrization of `generate_config` and/or additional model-specific kwargs that will be
1466
+ forwarded to the `forward` function of the model.
1467
+
1468
+ Return:
1469
+ `torch.LongTensor` of shape `(batch_size * num_return_sequences, sequence_length)`: The generated
1470
+ sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter if all batches
1471
+ finished early due to the `eos_token_id`.
1472
+ """
1473
+ # Handle `generation_config` and kwargs that might update it
1474
+ if generation_config is None:
1475
+ generation_config = self.generation_config
1476
+ generation_config = copy.deepcopy(generation_config)
1477
+ model_kwargs = generation_config.update(**kwargs) # All unused kwargs must be model kwargs
1478
+
1479
+ kwargs_has_attention_mask = model_kwargs.get("attention_mask", None) is not None
1480
+ self._prepare_special_tokens(generation_config, kwargs_has_attention_mask)
1481
+
1482
+ # set default parameters
1483
+ n_docs = n_docs if n_docs is not None else self.config.n_docs
1484
+
1485
+ # retrieve docs
1486
+ if self.retriever is not None and context_input_ids is None:
1487
+ question_hidden_states = self.question_encoder(input_ids, attention_mask=attention_mask)[0]
1488
+ out = self.retriever(
1489
+ input_ids,
1490
+ question_hidden_states.detach().to(device="cpu", dtype=torch.float32).numpy(),
1491
+ prefix=self.generator.config.prefix,
1492
+ n_docs=n_docs,
1493
+ return_tensors="pt",
1494
+ )
1495
+ context_input_ids, context_attention_mask, retrieved_doc_embeds = (
1496
+ out["context_input_ids"],
1497
+ out["context_attention_mask"],
1498
+ out["retrieved_doc_embeds"],
1499
+ )
1500
+
1501
+ # set to correct device
1502
+ retrieved_doc_embeds = retrieved_doc_embeds.to(question_hidden_states)
1503
+ context_input_ids = context_input_ids.to(input_ids)
1504
+ context_attention_mask = context_attention_mask.to(input_ids)
1505
+
1506
+ # compute doc_scores
1507
+ doc_scores = torch.bmm(question_hidden_states.unsqueeze(1), retrieved_doc_embeds.transpose(1, 2)).squeeze(
1508
+ 1
1509
+ )
1510
+
1511
+ assert (context_input_ids.shape[0] % n_docs) == 0, (
1512
+ f" The first dimension of `context_input_ids` should be a multiple of `n_docs`={n_docs}, but is"
1513
+ f" {context_input_ids.shape[0]}."
1514
+ )
1515
+
1516
+ # batch_size
1517
+ batch_size = context_input_ids.shape[0] // n_docs
1518
+
1519
+ encoder = self.rag.generator.get_encoder()
1520
+ encoder_outputs = encoder(input_ids=context_input_ids, attention_mask=context_attention_mask, return_dict=True)
1521
+
1522
+ input_ids = torch.full(
1523
+ (batch_size * generation_config.num_beams, 1),
1524
+ generation_config.decoder_start_token_id,
1525
+ dtype=torch.long,
1526
+ device=next(self.parameters()).device,
1527
+ )
1528
+ input_ids_seq_length = input_ids.shape[-1]
1529
+ last_hidden_state = encoder_outputs["last_hidden_state"]
1530
+
1531
+ def extend_enc_output(tensor, num_beams=None):
1532
+ # split into `batch_size`, `num_beams`, `num_docs`
1533
+ tensor = tensor[None, None, :].reshape((batch_size, 1, n_docs) + tensor.shape[1:])
1534
+ # repeat same last hidden states over `num_beams` dimension
1535
+ tensor = tensor.expand((batch_size, num_beams, n_docs) + tensor.shape[3:])
1536
+ # merge `batch_size`, `num_beams`, `num_docs` dims again
1537
+ return tensor.reshape((batch_size * num_beams * n_docs,) + tensor.shape[3:])
1538
+
1539
+ # correctly extend last_hidden_state and attention mask
1540
+ context_attention_mask = extend_enc_output(context_attention_mask, num_beams=generation_config.num_beams)
1541
+ encoder_outputs["last_hidden_state"] = extend_enc_output(
1542
+ last_hidden_state, num_beams=generation_config.num_beams
1543
+ )
1544
+
1545
+ doc_scores = doc_scores.repeat_interleave(generation_config.num_beams, dim=0)
1546
+
1547
+ # define start_len & additional parameters
1548
+ model_kwargs["doc_scores"] = doc_scores
1549
+ model_kwargs["encoder_outputs"] = encoder_outputs
1550
+ model_kwargs["attention_mask"] = context_attention_mask
1551
+ model_kwargs["n_docs"] = n_docs
1552
+
1553
+ pre_processor = self._get_logits_processor(
1554
+ generation_config=generation_config,
1555
+ input_ids_seq_length=input_ids_seq_length,
1556
+ encoder_input_ids=context_input_ids,
1557
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
1558
+ logits_processor=logits_processor,
1559
+ device=input_ids.device,
1560
+ )
1561
+
1562
+ prepared_stopping_criteria = self._get_stopping_criteria(
1563
+ generation_config=generation_config, stopping_criteria=stopping_criteria
1564
+ )
1565
+
1566
+ self._prepare_cache_for_generation(
1567
+ generation_config,
1568
+ model_kwargs,
1569
+ assistant_model=None,
1570
+ batch_size=input_ids.shape[0],
1571
+ max_cache_length=generation_config.max_length - 1,
1572
+ )
1573
+
1574
+ if generation_config.num_beams == 1:
1575
+ if generation_config.num_return_sequences > 1:
1576
+ raise ValueError(
1577
+ f"num_return_sequences has to be 1, but is {generation_config.num_return_sequences} when doing"
1578
+ " greedy search."
1579
+ )
1580
+ return self._sample(
1581
+ input_ids,
1582
+ logits_processor=pre_processor,
1583
+ stopping_criteria=prepared_stopping_criteria,
1584
+ generation_config=generation_config,
1585
+ synced_gpus=False,
1586
+ streamer=None,
1587
+ **model_kwargs,
1588
+ )
1589
+ elif generation_config.num_beams > 1:
1590
+ if generation_config.num_return_sequences > generation_config.num_beams:
1591
+ raise ValueError("`num_return_sequences` has to be smaller or equal to `num_beams`.")
1592
+
1593
+ return self._beam_search(
1594
+ input_ids,
1595
+ logits_processor=pre_processor,
1596
+ stopping_criteria=prepared_stopping_criteria,
1597
+ generation_config=generation_config,
1598
+ synced_gpus=False,
1599
+ **model_kwargs,
1600
+ )
1601
+ else:
1602
+ raise ValueError(
1603
+ f"`num_beams` has to be an integer strictly superior to 0 (≥ 1), but is {generation_config.num_beams}"
1604
+ )
1605
+
1606
+ # Auxiliary functions for beam search
1607
+ def _temporary_reorder_cache(self, past_key_values, beam_idx):
1608
+ # RAG should always use the legacy path even though the LM backbone (T5) uses new cache format
1609
+ # because RAG expands input for doc-size internally. TODO: raushan, remove me when all models support
1610
+ # new cache format
1611
+ past_key_values = self._reorder_cache(past_key_values, beam_idx)
1612
+ return past_key_values
1613
+
1614
+ def get_input_embeddings(self):
1615
+ return self.rag.generator.get_input_embeddings()
1616
+
1617
+ def get_output_embeddings(self):
1618
+ return self.rag.generator.get_output_embeddings()
1619
+
1620
+ def set_output_embeddings(self, new_embeddings):
1621
+ return self.rag.generator.set_output_embeddings(new_embeddings)
1622
+
1623
+ def shift_tokens_right(self, input_ids, start_token_id=None):
1624
+ """Shift input ids one token to the right, and pad with start_token_id"""
1625
+ if start_token_id is None:
1626
+ start_token_id = self.config.decoder_start_token_id
1627
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
1628
+ shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
1629
+ shifted_input_ids[:, 0] = start_token_id
1630
+ return shifted_input_ids
1631
+
1632
+ def get_nll(self, seq_logits, doc_scores, target, reduce_loss=False, epsilon=0.0, n_docs=None):
1633
+ n_docs = n_docs if n_docs is not None else self.config.n_docs
1634
+ # shift tokens left
1635
+ target = torch.cat(
1636
+ [target[:, 1:], target.new(target.shape[0], 1).fill_(self.config.generator.pad_token_id)], 1
1637
+ )
1638
+
1639
+ def _mask_pads(ll, smooth_obj):
1640
+ pad_mask = target.eq(self.config.generator.pad_token_id)
1641
+ if pad_mask.any():
1642
+ ll.masked_fill_(pad_mask, 0.0)
1643
+ smooth_obj.masked_fill_(pad_mask, 0.0)
1644
+ return ll.squeeze(-1), smooth_obj.squeeze(-1)
1645
+
1646
+ rag_logprobs = self.marginalize(seq_logits, doc_scores, n_docs)
1647
+
1648
+ target = target.unsqueeze(-1)
1649
+ assert target.dim() == rag_logprobs.dim()
1650
+
1651
+ ll = rag_logprobs.gather(dim=-1, index=target)
1652
+ smooth_obj = rag_logprobs.sum(dim=-1, keepdim=True) # total sum of all (normalised) logits
1653
+ ll, smooth_obj = _mask_pads(ll, smooth_obj)
1654
+ ll = ll.sum(1) # sum over tokens
1655
+ smooth_obj = smooth_obj.sum(1)
1656
+
1657
+ nll_loss = -ll
1658
+ smooth_loss = -smooth_obj
1659
+
1660
+ if reduce_loss:
1661
+ nll_loss = nll_loss.sum()
1662
+ smooth_loss = smooth_loss.sum()
1663
+
1664
+ eps_i = epsilon / rag_logprobs.size(-1)
1665
+ loss = (1.0 - epsilon) * nll_loss + eps_i * smooth_loss
1666
+ return loss
1667
+
1668
+
1669
+ __all__ = ["RagModel", "RagPreTrainedModel", "RagSequenceForGeneration", "RagTokenForGeneration"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/rag/modeling_tf_rag.py ADDED
@@ -0,0 +1,1776 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020, The RAG Authors and The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """TFRAG model implementation."""
17
+
18
+ from __future__ import annotations
19
+
20
+ import copy
21
+ from dataclasses import dataclass
22
+
23
+ import numpy as np
24
+ import tensorflow as tf
25
+
26
+ from ...configuration_utils import PretrainedConfig
27
+ from ...generation import TFLogitsProcessorList
28
+ from ...modeling_tf_utils import (
29
+ TFCausalLanguageModelingLoss,
30
+ TFModelInputType,
31
+ TFPreTrainedModel,
32
+ keras,
33
+ shape_list,
34
+ unpack_inputs,
35
+ )
36
+ from ...utils import ModelOutput, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
37
+ from .configuration_rag import RagConfig
38
+ from .retrieval_rag import RagRetriever
39
+
40
+
41
+ logger = logging.get_logger(__name__)
42
+
43
+ _CONFIG_FOR_DOC = "RagConfig"
44
+
45
+
46
+ @dataclass
47
+ class TFRetrievAugLMMarginOutput(ModelOutput):
48
+ """
49
+ Base class for retriever augmented marginalized models outputs.
50
+
51
+ Args:
52
+ loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
53
+ Language modeling loss.
54
+ logits (`tf.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
55
+ Prediction scores of the language modeling head. The score is possibly marginalized over all documents for
56
+ each vocabulary token.
57
+ past_key_values (`list[tf.Tensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
58
+ List of `tf.Tensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size, num_heads,
59
+ sequence_length, embed_size_per_head)`).
60
+
61
+ Contains precomputed hidden-states (key and values in the attention blocks) of the decoder that can be used
62
+ (see `past_key_values` input) to speed up sequential decoding.
63
+ doc_scores (`tf.Tensor` of shape `(batch_size, config.n_docs)`):
64
+ Score between each retrieved document embeddings (see `retrieved_doc_embeds`) and
65
+ `question_encoder_last_hidden_state`.
66
+ retrieved_doc_embeds (`tf.Tensor` of shape `(batch_size, config.n_docs, hidden_size)`, *optional*, returned when *output_retrieved=True*):
67
+ Embedded documents retrieved by the retriever. Is used with `question_encoder_last_hidden_state` to compute
68
+ the `doc_scores`.
69
+ retrieved_doc_ids (`tf.Tensor` (int32) of shape `(batch_size, config.n_docs)`, *optional*, returned when *output_retrieved=True*):
70
+ The indexes of the embedded documents retrieved by the retriever.
71
+ context_input_ids (`tf.Tensor`(int32) of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
72
+ Input ids post-processed from the retrieved documents and the question encoder input_ids by the retriever.
73
+ context_attention_mask (`tf.Tensor` (int32) of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
74
+ Attention mask post-processed from the retrieved documents and the question encoder `input_ids` by the
75
+ retriever.
76
+ question_encoder_last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
77
+ Sequence of hidden states at the output of the last layer of the question encoder pooled output of the
78
+ model.
79
+ question_enc_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
80
+ Tuple of `tf.Tensor` (one for the output of the embeddings and one for the output of each layer) of shape
81
+ `(batch_size, sequence_length, hidden_size)`.
82
+
83
+ Hidden states of the question encoder at the output of each layer plus the initial embedding outputs.
84
+ question_enc_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
85
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
86
+ sequence_length)`.
87
+
88
+ Attentions weights of the question encoder, after the attention softmax, used to compute the weighted
89
+ average in the self-attention heads.
90
+ generator_enc_last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
91
+ Sequence of hidden-states at the output of the last layer of the generator encoder of the model.
92
+ generator_enc_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
93
+ Tuple of `tf.Tensor` (one for the output of the embeddings and one for the output of each layer) of shape
94
+ `(batch_size, sequence_length, hidden_size)`.
95
+
96
+ Hidden states of the generator encoder at the output of each layer plus the initial embedding outputs.
97
+ generator_enc_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
98
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
99
+ sequence_length)`.
100
+
101
+ Attentions weights of the generator encoder, after the attention softmax, used to compute the weighted
102
+ average in the self-attention heads.
103
+ generator_dec_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
104
+ Tuple of `tf.Tensor` (one for the output of the embeddings and one for the output of each layer) of shape
105
+ `(batch_size, sequence_length, hidden_size)`.
106
+
107
+ Hidden states of the generator decoder at the output of each layer plus the initial embedding outputs.
108
+ generator_dec_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
109
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
110
+ sequence_length)`.
111
+
112
+ Attentions weights of the generator decoder, after the attention softmax, used to compute the weighted
113
+ average in the self-attention heads.
114
+ """
115
+
116
+ loss: tf.Tensor | None = None
117
+ logits: tf.Tensor | None = None
118
+ past_key_values: list[tf.Tensor] | None = None
119
+ doc_scores: tf.Tensor | None = None
120
+ retrieved_doc_embeds: tf.Tensor | None = None
121
+ retrieved_doc_ids: tf.Tensor | None = None
122
+ context_input_ids: tf.Tensor | None = None
123
+ context_attention_mask: tf.Tensor | None = None
124
+ question_encoder_last_hidden_state: tf.Tensor | None = None
125
+ question_enc_hidden_states: tuple[tf.Tensor, ...] | None = None
126
+ question_enc_attentions: tuple[tf.Tensor, ...] | None = None
127
+ generator_enc_last_hidden_state: tf.Tensor | None = None
128
+ generator_enc_hidden_states: tuple[tf.Tensor, ...] | None = None
129
+ generator_enc_attentions: tuple[tf.Tensor, ...] | None = None
130
+ generator_dec_hidden_states: tuple[tf.Tensor, ...] | None = None
131
+ generator_dec_attentions: tuple[tf.Tensor, ...] | None = None
132
+
133
+
134
+ @dataclass
135
+ class TFRetrievAugLMOutput(ModelOutput):
136
+ """
137
+ Args:
138
+ logits (`tf.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
139
+ Prediction scores of the language modeling head. The score is possibly marginalized over all documents for
140
+ each vocabulary token.
141
+ past_key_values (`list[tf.Tensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
142
+ List of `tf.Tensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size, num_heads,
143
+ sequence_length, embed_size_per_head)`).
144
+
145
+ Contains precomputed hidden-states (key and values in the attention blocks) of the decoder that can be used
146
+ (see `past_key_values` input) to speed up sequential decoding.
147
+ doc_scores (`tf.Tensor` of shape `(batch_size, config.n_docs)`):
148
+ Score between each retrieved document embeddings (see `retrieved_doc_embeds`) and
149
+ `question_encoder_last_hidden_state`.
150
+ retrieved_doc_embeds (`tf.Tensor` of shape `(batch_size, config.n_docs, hidden_size)`, *optional*, returned when *output_retrieved=True*):
151
+ Embedded documents retrieved by the retriever. Is used with `question_encoder_last_hidden_state` to compute
152
+ the `doc_scores`.
153
+ retrieved_doc_ids (`tf.Tensor` of shape `(batch_size, config.n_docs)`, *optional*, returned when *output_retrieved=True*):
154
+ The indexes of the embedded documents retrieved by the retriever.
155
+ context_input_ids (`tf.Tensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
156
+ Input ids post-processed from the retrieved documents and the question encoder input_ids by the retriever.
157
+ context_attention_mask (`tf.Tensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
158
+ Attention mask post-processed from the retrieved documents and the question encoder `input_ids` by the
159
+ retriever.
160
+ question_encoder_last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
161
+ Sequence of hidden states at the output of the last layer of the question encoder pooled output of the
162
+ model.
163
+ question_enc_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
164
+ Tuple of `tf.Tensor` (one for the output of the embeddings and one for the output of each layer) of shape
165
+ `(batch_size, sequence_length, hidden_size)`.
166
+
167
+ Hidden states of the question encoder at the output of each layer plus the initial embedding outputs.
168
+ question_enc_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
169
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
170
+ sequence_length)`.
171
+
172
+ Attentions weights of the question encoder, after the attention softmax, used to compute the weighted
173
+ average in the self-attention heads.
174
+ generator_enc_last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
175
+ Sequence of hidden-states at the output of the last layer of the generator encoder of the model.
176
+ generator_enc_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
177
+ Tuple of `tf.Tensor` (one for the output of the embeddings and one for the output of each layer) of shape
178
+ `(batch_size, sequence_length, hidden_size)`.
179
+
180
+ Hidden states of the generator encoder at the output of each layer plus the initial embedding outputs.
181
+ generator_enc_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
182
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
183
+ sequence_length)`.
184
+
185
+ Attentions weights of the generator encoder, after the attention softmax, used to compute the weighted
186
+ average in the self-attention heads.
187
+ generator_dec_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
188
+ Tuple of `tf.Tensor` (one for the output of the embeddings and one for the output of each layer) of shape
189
+ `(batch_size, sequence_length, hidden_size)`.
190
+
191
+ Hidden states of the generator decoder at the output of each layer plus the initial embedding outputs.
192
+ generator_dec_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
193
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
194
+ sequence_length)`.
195
+
196
+ Attentions weights of the generator decoder, after the attention softmax, used to compute the weighted
197
+ average in the self-attention heads.
198
+ """
199
+
200
+ logits: tf.Tensor | None = None
201
+ past_key_values: list[tf.Tensor] | None = None
202
+ doc_scores: tf.Tensor | None = None
203
+ retrieved_doc_embeds: tf.Tensor | None = None
204
+ retrieved_doc_ids: tf.Tensor | None = None
205
+ context_input_ids: tf.Tensor | None = None
206
+ context_attention_mask: tf.Tensor | None = None
207
+ question_encoder_last_hidden_state: tf.Tensor | None = None
208
+ question_enc_hidden_states: tuple[tf.Tensor, ...] | None = None
209
+ question_enc_attentions: tuple[tf.Tensor, ...] | None = None
210
+ generator_enc_last_hidden_state: tf.Tensor | None = None
211
+ generator_enc_hidden_states: tuple[tf.Tensor, ...] | None = None
212
+ generator_enc_attentions: tuple[tf.Tensor, ...] | None = None
213
+ generator_dec_hidden_states: tuple[tf.Tensor, ...] | None = None
214
+ generator_dec_attentions: tuple[tf.Tensor, ...] | None = None
215
+
216
+
217
+ class TFRagPreTrainedModel(TFPreTrainedModel):
218
+ r"""
219
+ RAG models were released with the paper [Retrieval-Augmented Generation for Knowledge-Intensive NLP
220
+ Tasks](https://huggingface.co/papers/2005.11401) by Patrick Lewis, Ethan Perez, Aleksandra Piktus et al.
221
+
222
+ RAG is a retriever augmented model and encapsulate three components: a question encoder, a dataset retriever and a
223
+ generator, the encoder and generator are trainable while the retriever is just an indexed dataset.
224
+
225
+ """
226
+
227
+ config_class = RagConfig
228
+ base_model_prefix = "rag"
229
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
230
+
231
+ @classmethod
232
+ def from_pretrained_question_encoder_generator(
233
+ cls,
234
+ question_encoder_pretrained_model_name_or_path: str | None = None,
235
+ generator_pretrained_model_name_or_path: str | None = None,
236
+ retriever: RagRetriever = None,
237
+ *model_args,
238
+ **kwargs,
239
+ ) -> TFPreTrainedModel:
240
+ r"""
241
+ Instantiates an question encoder and a generator from one or two base classes of the library from pretrained
242
+ model checkpoints.
243
+
244
+ Params:
245
+ question_encoder_pretrained_model_name_or_path (`str`, *optional*):
246
+ Information necessary to initiate the question encoder. Can be either:
247
+
248
+ - A string with the *shortcut name* of a pretrained model to load from cache or download, e.g.,
249
+ `google-bert/bert-base-uncased`.
250
+ - A string with the *identifier name* of a pretrained model that was user-uploaded to our S3, e.g.,
251
+ `dbmdz/bert-base-german-cased`.
252
+ - A path to a *directory* containing model weights saved using
253
+ [`~TFPreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
254
+ - A path or url to a *pytorch index checkpoint file* (e.g, `./pt_model/`). In this case,
255
+ `question_encoder_from_pt` should be set to `True`.
256
+
257
+ generator_pretrained_model_name_or_path (`str`, *optional*, defaults to `None`):
258
+ Information necessary to initiate the generator. Can be either:
259
+
260
+ - A string with the *shortcut name* of a pretrained model to load from cache or download, e.g.,
261
+ `google-t5/t5-small`.
262
+ - A string with the *identifier name* of a pretrained model that was user-uploaded to our S3, e.g.,
263
+ `facebook/bart-base`.
264
+ - A path to a *directory* containing model weights saved using
265
+ [`~TFPreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
266
+ - A path or url to a *pytorch checkpoint file* (e.g, `./pt_model/`). In this case,
267
+ `generator_from_pt` should be set to `True`.
268
+
269
+ model_args (remaining positional arguments, *optional*):
270
+ All remaining positional arguments will be passed to the underlying model's `__init__` method.
271
+ retriever ([`RagRetriever`], *optional*):
272
+ The retriever to use.
273
+ kwargs (remaining dictionary of keyword arguments, *optional*):
274
+ Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
275
+ `output_attentions=True`).
276
+
277
+ - To update the question_encoder configuration, use the prefix *question_encoder_* for each
278
+ configuration parameter.
279
+ - To update the generator configuration, use the prefix *generator_* for each configuration parameter.
280
+ - To update the parent model configuration, do not use a prefix for each configuration parameter.
281
+
282
+ Behaves differently depending on whether a `config` is provided or automatically loaded.
283
+
284
+ Example:
285
+
286
+ ```python
287
+ >>> from transformers import RagRetriever, TFRagModel
288
+
289
+ >>> # initialize a RAG from two pretrained models.
290
+ >>> model = TFRagModel.from_pretrained_question_encoder_generator(
291
+ ... "facebook/dpr-question_encoder-single-nq-base", "google-t5/t5-small"
292
+ ... )
293
+ >>> # alternatively, initialize from pytorch pretrained models can also be done
294
+ >>> model = TFRagModel.from_pretrained_question_encoder_generator(
295
+ ... "facebook/dpr-question_encoder-single-nq-base",
296
+ ... "facebook/bart-base",
297
+ ... generator_from_pt=True,
298
+ ... question_encoder_from_pt=True,
299
+ ... )
300
+
301
+ >>> # saving model after fine-tuning
302
+ >>> model.save_pretrained("./rag")
303
+
304
+ >>> # load retriever
305
+ >>> retriever = RagRetriever.from_pretrained(
306
+ ... "facebook/rag-token-base", index_name="exact", use_dummy_dataset=True
307
+ ... )
308
+ >>> # load fine-tuned model with retriever
309
+ >>> model = TFRagModel.from_pretrained("./rag", retriever=retriever)
310
+ ```"""
311
+
312
+ kwargs_question_encoder = {
313
+ argument[len("question_encoder_") :]: value
314
+ for argument, value in kwargs.items()
315
+ if argument.startswith("question_encoder_")
316
+ }
317
+
318
+ kwargs_generator = {
319
+ argument[len("generator_") :]: value
320
+ for argument, value in kwargs.items()
321
+ if argument.startswith("generator_")
322
+ }
323
+
324
+ # remove question_encoder, generator kwargs from kwargs
325
+ for key in kwargs_question_encoder:
326
+ del kwargs["question_encoder_" + key]
327
+ for key in kwargs_generator:
328
+ del kwargs["generator_" + key]
329
+
330
+ # Load and initialize the question_encoder and generator
331
+ # The distinction between question_encoder and generator at the model level is made
332
+ # by the value of the flag `is_generator` that we need to set correctly.
333
+ question_encoder = kwargs_question_encoder.pop("model", None)
334
+ if question_encoder is None:
335
+ assert question_encoder_pretrained_model_name_or_path is not None, (
336
+ "If `model` is not defined as an argument, a `question_encoder_pretrained_model_name_or_path` has to"
337
+ " be defined"
338
+ )
339
+
340
+ from ..auto.modeling_tf_auto import TFAutoModel
341
+
342
+ if "config" not in kwargs_question_encoder:
343
+ from ..auto.configuration_auto import AutoConfig
344
+
345
+ question_encoder_config = AutoConfig.from_pretrained(question_encoder_pretrained_model_name_or_path)
346
+ kwargs_question_encoder["config"] = question_encoder_config
347
+
348
+ question_encoder = TFAutoModel.from_pretrained(
349
+ question_encoder_pretrained_model_name_or_path,
350
+ name="question_encoder",
351
+ load_weight_prefix=cls.load_weight_prefix,
352
+ *model_args,
353
+ **kwargs_question_encoder,
354
+ )
355
+
356
+ generator = kwargs_generator.pop("generator", None)
357
+ if generator is None:
358
+ assert generator_pretrained_model_name_or_path is not None, (
359
+ "If `generator_model` is not defined as an argument, a `generator_pretrained_model_name_or_path` has"
360
+ " to be defined"
361
+ )
362
+
363
+ from ..auto.modeling_tf_auto import TFAutoModelForSeq2SeqLM
364
+
365
+ if "config" not in kwargs_generator:
366
+ from ..auto.configuration_auto import AutoConfig
367
+
368
+ generator_config = AutoConfig.from_pretrained(generator_pretrained_model_name_or_path)
369
+ kwargs_generator["config"] = generator_config
370
+
371
+ generator = TFAutoModelForSeq2SeqLM.from_pretrained(
372
+ generator_pretrained_model_name_or_path,
373
+ name="generator",
374
+ load_weight_prefix=cls.load_weight_prefix,
375
+ **kwargs_generator,
376
+ )
377
+
378
+ # instantiate config with corresponding kwargs
379
+ config = kwargs.get("config")
380
+ if config is None:
381
+ config = RagConfig.from_question_encoder_generator_configs(
382
+ question_encoder.config, generator.config, **kwargs
383
+ )
384
+
385
+ return cls(question_encoder=question_encoder, generator=generator, config=config, retriever=retriever)
386
+
387
+
388
+ RAG_START_DOCSTRING = r"""
389
+
390
+ RAG is a sequence-to-sequence model which encapsulates two core components: a question encoder and a generator.
391
+ During a forward pass, we encode the input with the question encoder and pass it to the retriever to extract
392
+ relevant context documents. The documents are then prepended to the input. Such contextualized inputs is passed to
393
+ the generator.
394
+
395
+ The question encoder can be any *autoencoding* model, preferably [`TFDPRQuestionEncoder`], and the generator can be
396
+ any *seq2seq* model, preferably [`TFBartForConditionalGeneration`].
397
+
398
+ The model can be initialized with a [`RagRetriever`] for end-to-end generation or used in combination with the
399
+ outputs of a retriever in multiple steps---see examples for more details. The model is compatible any
400
+ *autoencoding* model as the `question_encoder` and any *seq2seq* model with language model head as the `generator`.
401
+ It has been tested with [`TFDPRQuestionEncoder`] as the `question_encoder` and [`TFBartForConditionalGeneration`]
402
+ as the `generator`.
403
+
404
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
405
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
406
+ etc.)
407
+
408
+ This model is also a Tensorflow [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model)
409
+ subclass. Use it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to
410
+ general usage and behavior.
411
+
412
+ The model is in a developing state as it is now fully supports in eager-mode only, and may not be exported in
413
+ SavedModel format.
414
+
415
+ Args:
416
+ config ([`RagConfig`]):
417
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
418
+ load the weights associated with the model, only the configuration. Check out the
419
+ [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
420
+ question_encoder ([`TFPreTrainedModel`]):
421
+ An encoder model compatible with the faiss index encapsulated by the `retriever`.
422
+ generator ([`TFPreTrainedModel`]):
423
+ A seq2seq model used as the generator in the RAG architecture.
424
+ retriever ([`RagRetriever`]):
425
+ A retriever class encapsulating a faiss index queried to obtain context documents for current inputs.
426
+ """
427
+
428
+
429
+ RAG_FORWARD_INPUTS_DOCSTRING = r"""
430
+ Args:
431
+ input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
432
+ Indices of input sequence tokens in the vocabulary. [`RagConfig`], used to initialize the model, specifies
433
+ which generator to use, it also specifies a compatible generator tokenizer. Use that tokenizer class to
434
+ obtain the indices.
435
+ attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
436
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
437
+
438
+ - 1 for tokens that are **not masked**,
439
+ - 0 for tokens that are **masked**.
440
+
441
+ [What are attention masks?](../glossary#attention-mask)
442
+ encoder_outputs (`tuple(tuple(tf.Tensor)`, *optional*)
443
+ Tuple consists of (`generator_enc_last_hidden_state`, *optional*: `generator_enc_hidden_states`,
444
+ *optional*: `generator_enc_attentions`). `generator_enc_last_hidden_state` of shape `(batch_size, n_docs *
445
+ sequence_length, hidden_size)` is a sequence of hidden-states at the output of the last layer of the
446
+ generator's encoder.
447
+
448
+ Used by the ([`TFRagModel`]) model during decoding.
449
+ decoder_input_ids (`tf.Tensor` of shape `(batch_size, target_sequence_length)`, *optional*):
450
+ Provide for generation tasks. `None` by default, construct as per instructions for the generator model
451
+ you're using with your RAG instance.
452
+ decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
453
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
454
+ be used by default.
455
+ past_key_values (`tuple(tuple(tf.Tensor))`):
456
+ Tuple consists of two elements: `encoder_outputs` of the RAG model (see `encoder_outputs`) and
457
+ `past_key_values` of the underlying generator. Can be used to speed up decoding. `past_key_values` are used
458
+ in the ([`RagTokenForGeneration`]) model during decoding.
459
+ doc_scores (`tf.Tensor` of shape `(batch_size, config.n_docs)`):
460
+ Score between each retrieved document embeddings (see `retrieved_doc_embeds`) and
461
+ `question_encoder_last_hidden_state`. If the model has is not initialized with a `retriever` `doc_scores`
462
+ has to be provided to the forward pass. `doc_scores` can be computed via
463
+ `question_encoder_last_hidden_state` and `retrieved_doc_embeds`, see examples for more information.
464
+ context_input_ids (`tf.Tensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
465
+ Input IDs post-processed from the retrieved documents and the question encoder `input_ids` by the
466
+ retriever.
467
+
468
+ If the model has is not initialized with a `retriever` ``context_input_ids` has to be provided to the
469
+ forward pass. `context_input_ids` are returned by [`~RagRetriever.__call__`]. context_attention_mask
470
+ (`tf.Tensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when
471
+ *output_retrieved=True*): Attention mask post-processed from the retrieved documents and the question
472
+ encoder `input_ids` by the retriever.
473
+
474
+ If the model has is not initialized with a `retriever` `context_attention_mask` has to be provided to the
475
+ forward pass. `context_attention_mask` are returned by [`~RagRetriever.__call__`].
476
+ use_cache (`bool`, *optional*, defaults to `True`):
477
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
478
+ `past_key_values`).
479
+ output_attentions (`bool`, *optional*):
480
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
481
+ tensors for more detail.
482
+ output_hidden_states (`bool`, *optional*):
483
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
484
+ more detail.
485
+ output_retrieved(`bool`, *optional*):
486
+ Whether or not to return the `retrieved_doc_embeds`, `retrieved_doc_ids`, `context_input_ids` and
487
+ `context_attention_mask`. See returned tensors for more detail.
488
+ return_dict (`bool`, *optional*):
489
+ Whether or not to return a [`TFRetrievAugLMOutput`] instead of a plain tuple.
490
+ n_docs (`int`, *optional*, defaults to `config.n_docs``)
491
+ Number of documents to retrieve and/or number of documents for which to generate an answer.
492
+ """
493
+
494
+
495
+ @add_start_docstrings_to_model_forward(RAG_START_DOCSTRING)
496
+ class TFRagModel(TFRagPreTrainedModel):
497
+ load_weight_prefix = "tf_rag_model_1"
498
+
499
+ def __init__(
500
+ self,
501
+ config: PretrainedConfig | None = None,
502
+ question_encoder: TFPreTrainedModel | None = None,
503
+ generator: TFPreTrainedModel | None = None,
504
+ retriever: RagRetriever | None = None,
505
+ load_weight_prefix: str | None = None,
506
+ **kwargs,
507
+ ):
508
+ assert config is not None or (question_encoder is not None and generator is not None), (
509
+ "Either a configuration or an question_encoder and a generator has to be provided."
510
+ )
511
+
512
+ if config is None:
513
+ config = RagConfig.from_question_encoder_generator_configs(
514
+ question_encoder.config, generator.config, **kwargs
515
+ )
516
+ else:
517
+ assert isinstance(config, self.config_class), f"config: {config} has to be of type {self.config_class}"
518
+ super().__init__(config, **kwargs)
519
+
520
+ if question_encoder is None:
521
+ from ..auto.modeling_tf_auto import TFAutoModel
522
+
523
+ question_encoder = TFAutoModel.from_config(config.question_encoder, name="question_encoder")
524
+
525
+ if generator is None:
526
+ from ..auto.modeling_tf_auto import TFAutoModelForSeq2SeqLM
527
+
528
+ load_weight_prefix = load_weight_prefix if load_weight_prefix is not None else self.load_weight_prefix
529
+ generator = TFAutoModelForSeq2SeqLM.from_config(
530
+ config.generator, name="generator", load_weight_prefix=load_weight_prefix + "/generator"
531
+ )
532
+
533
+ self.retriever = retriever
534
+ if self.retriever is not None:
535
+ assert isinstance(retriever, RagRetriever), (
536
+ f"`self.retriever` is of type {type(self.retriever)}, but should be of type `RagRetriever`"
537
+ )
538
+ self.retriever = retriever
539
+
540
+ self.question_encoder = question_encoder
541
+ self.generator = generator
542
+
543
+ def set_retriever(self, retriever: RagRetriever):
544
+ self.retriever = retriever
545
+
546
+ @unpack_inputs
547
+ @add_start_docstrings_to_model_forward(RAG_FORWARD_INPUTS_DOCSTRING)
548
+ @replace_return_docstrings(output_type=TFRetrievAugLMOutput, config_class=_CONFIG_FOR_DOC)
549
+ def call(
550
+ self,
551
+ input_ids: TFModelInputType | None = None,
552
+ attention_mask: np.ndarray | tf.Tensor | None = None,
553
+ encoder_outputs: np.ndarray | tf.Tensor | None = None,
554
+ decoder_input_ids: np.ndarray | tf.Tensor | None = None,
555
+ decoder_attention_mask: np.ndarray | tf.Tensor | None = None,
556
+ past_key_values: tuple[tuple[np.ndarray | tf.Tensor]] | None = None,
557
+ doc_scores: np.ndarray | tf.Tensor | None = None,
558
+ context_input_ids: np.ndarray | tf.Tensor | None = None,
559
+ context_attention_mask: np.ndarray | tf.Tensor | None = None,
560
+ use_cache: bool | None = None,
561
+ output_attentions: bool | None = None,
562
+ output_hidden_states: bool | None = None,
563
+ output_retrieved: bool | None = None,
564
+ n_docs: int | None = None,
565
+ return_dict: bool | None = None,
566
+ training: bool = False,
567
+ **kwargs,
568
+ ) -> TFRetrievAugLMOutput:
569
+ r"""
570
+ Returns:
571
+
572
+ Example:
573
+
574
+ ```python
575
+ >>> from transformers import AutoTokenizer, RagRetriever, TFRagModel
576
+ >>> import torch
577
+ from ...utils.deprecation import deprecate_kwarg
578
+ from ...utils.deprecation import deprecate_kwarg
579
+ from ...utils.deprecation import deprecate_kwarg
580
+ from ...utils.deprecation import deprecate_kwarg
581
+
582
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/rag-token-base")
583
+ >>> retriever = RagRetriever.from_pretrained(
584
+ ... "facebook/rag-token-base", index_name="exact", use_dummy_dataset=True
585
+ ... )
586
+ >>> # initialize with RagRetriever to do everything in one forward call
587
+ >>> model = TFRagModel.from_pretrained("facebook/rag-token-base", retriever=retriever, from_pt=True)
588
+
589
+ >>> input_dict = tokenizer.prepare_seq2seq_batch(
590
+ ... "How many people live in Paris?", "In Paris, there are 10 million people.", return_tensors="tf"
591
+ ... )
592
+ >>> input_ids = input_dict["input_ids"]
593
+ >>> outputs = model(input_ids)
594
+ ```"""
595
+ assert "decoder_cached_states" not in kwargs, (
596
+ "Please use past_key_values to cache intermediate outputs"
597
+ ) # from modeling_tf_bart.py
598
+
599
+ # aliasing to minimize code changing
600
+ n_docs = n_docs if n_docs is not None else self.config.n_docs
601
+
602
+ # whether retriever has to be used
603
+ has_to_retrieve = (
604
+ self.retriever is not None
605
+ and (context_input_ids is None or context_attention_mask is None or doc_scores is None)
606
+ and encoder_outputs is None
607
+ )
608
+
609
+ # encoder_outputs are pre-computed during RAG-token generation
610
+ if encoder_outputs is None:
611
+ if has_to_retrieve:
612
+ question_enc_outputs = self.question_encoder(
613
+ input_ids, attention_mask=attention_mask, return_dict=True, training=training
614
+ )
615
+ # see https://github.com/huggingface/transformers/blob/main/src/transformers/models/dpr/modeling_tf_dpr.py#L91
616
+ question_encoder_last_hidden_state = question_enc_outputs[
617
+ 0
618
+ ] # hidden states of question encoder => pooler_output
619
+
620
+ retriever_outputs = self.retriever(
621
+ input_ids,
622
+ question_encoder_last_hidden_state.numpy(),
623
+ prefix=self.generator.config.prefix,
624
+ n_docs=n_docs,
625
+ return_tensors="tf",
626
+ )
627
+ context_input_ids, context_attention_mask, retrieved_doc_embeds, retrieved_doc_ids = (
628
+ retriever_outputs["context_input_ids"],
629
+ retriever_outputs["context_attention_mask"],
630
+ retriever_outputs["retrieved_doc_embeds"],
631
+ retriever_outputs["doc_ids"],
632
+ )
633
+
634
+ context_input_ids = tf.cast(context_input_ids, tf.int32)
635
+ context_attention_mask = tf.cast(context_attention_mask, tf.int32)
636
+ retrieved_doc_embeds = tf.cast(retrieved_doc_embeds, tf.float32)
637
+ retrieved_doc_ids = tf.cast(retrieved_doc_ids, tf.int32)
638
+
639
+ # compute doc_scores
640
+ doc_scores = tf.squeeze(
641
+ tf.matmul(
642
+ tf.expand_dims(question_encoder_last_hidden_state, axis=1),
643
+ retrieved_doc_embeds,
644
+ transpose_b=True,
645
+ ),
646
+ axis=1,
647
+ )
648
+
649
+ else:
650
+ assert context_input_ids is not None, (
651
+ "Make sure that `context_input_ids` are passed, if no `retriever` is set. Alternatively, you can"
652
+ " set a retriever using the `set_retriever(...)` function."
653
+ )
654
+ assert context_attention_mask is not None, (
655
+ "Make sure that `context_attention_mask` are passed, if no `retriever` is set. Alternatively, you"
656
+ " can set a retriever using the `set_retriever(...)` function."
657
+ )
658
+ assert doc_scores is not None, (
659
+ "Make sure that `doc_scores` are passed, if no `retriever` is set. Alternatively, you can set a"
660
+ " retriever using the `set_retriever(...)` function."
661
+ )
662
+
663
+ assert doc_scores is not None, (
664
+ "Make sure that `doc_scores` are passed when passing `encoder_outputs` to the forward function."
665
+ )
666
+
667
+ assert (doc_scores.shape[1] % n_docs) == 0, (
668
+ f" The first dimension of `context_input_ids` should be a multiple of `n_docs`={n_docs}, but is"
669
+ f" {context_input_ids.shape[0]}."
670
+ )
671
+
672
+ # Decoder input without context documents
673
+ if decoder_input_ids is not None:
674
+ decoder_input_ids = tf.repeat(decoder_input_ids, n_docs, axis=0)
675
+
676
+ if decoder_attention_mask is not None:
677
+ decoder_attention_mask = tf.repeat(decoder_attention_mask, n_docs, axis=0)
678
+
679
+ gen_outputs = self.generator(
680
+ context_input_ids,
681
+ attention_mask=context_attention_mask,
682
+ encoder_outputs=encoder_outputs,
683
+ decoder_input_ids=decoder_input_ids,
684
+ decoder_attention_mask=decoder_attention_mask,
685
+ past_key_values=past_key_values,
686
+ use_cache=use_cache,
687
+ return_dict=True,
688
+ training=training,
689
+ )
690
+
691
+ if not has_to_retrieve:
692
+ question_encoder_last_hidden_state = None
693
+ question_enc_hidden_states = None
694
+ question_enc_attentions = None
695
+ retrieved_doc_embeds = None
696
+ retrieved_doc_ids = None
697
+ else:
698
+ question_enc_hidden_states = question_enc_outputs.hidden_states
699
+ question_enc_attentions = question_enc_outputs.attentions
700
+
701
+ if not has_to_retrieve or not output_retrieved:
702
+ # don't output retrieved docs
703
+ context_input_ids = (None,)
704
+ context_attention_mask = None
705
+ retrieved_doc_embeds = None
706
+ retrieved_doc_ids = None
707
+
708
+ return TFRetrievAugLMOutput(
709
+ logits=gen_outputs.logits,
710
+ doc_scores=doc_scores,
711
+ past_key_values=gen_outputs.past_key_values,
712
+ context_input_ids=context_input_ids,
713
+ context_attention_mask=context_attention_mask,
714
+ retrieved_doc_embeds=retrieved_doc_embeds,
715
+ retrieved_doc_ids=retrieved_doc_ids,
716
+ question_encoder_last_hidden_state=question_encoder_last_hidden_state,
717
+ question_enc_hidden_states=question_enc_hidden_states,
718
+ question_enc_attentions=question_enc_attentions,
719
+ generator_enc_last_hidden_state=gen_outputs.encoder_last_hidden_state,
720
+ generator_enc_hidden_states=gen_outputs.encoder_hidden_states,
721
+ generator_enc_attentions=gen_outputs.encoder_attentions,
722
+ generator_dec_hidden_states=gen_outputs.decoder_hidden_states,
723
+ generator_dec_attentions=gen_outputs.decoder_attentions,
724
+ )
725
+
726
+ def build(self, input_shape=None):
727
+ if self.built:
728
+ return
729
+ self.built = True
730
+ with tf.name_scope(self.generator.name):
731
+ self.generator.build(None)
732
+ with tf.name_scope(self.question_encoder.name):
733
+ self.question_encoder.build(None)
734
+
735
+
736
+ @add_start_docstrings_to_model_forward(
737
+ """
738
+ A TF RAG-token model implementation. It performs RAG-token specific marginalization in the forward pass.
739
+ """,
740
+ RAG_START_DOCSTRING,
741
+ )
742
+ class TFRagTokenForGeneration(TFRagPreTrainedModel, TFCausalLanguageModelingLoss):
743
+ load_weight_prefix = "tf_rag_token_for_generation_1/rag"
744
+
745
+ def __init__(
746
+ self,
747
+ config: PretrainedConfig | None = None,
748
+ question_encoder: TFPreTrainedModel | None = None,
749
+ generator: TFPreTrainedModel | None = None,
750
+ retriever: RagRetriever | None = None,
751
+ **kwargs,
752
+ ):
753
+ assert config is not None or (question_encoder is not None and generator is not None), (
754
+ "Either a configuration or an encoder and a generator has to be provided."
755
+ )
756
+
757
+ if config is None:
758
+ config = RagConfig.from_question_encoder_generator_configs(
759
+ question_encoder.config, generator.config, **kwargs
760
+ )
761
+
762
+ super().__init__(config)
763
+
764
+ # instantiate model
765
+ self.rag = TFRagModel(
766
+ config=config,
767
+ question_encoder=question_encoder,
768
+ generator=generator,
769
+ retriever=retriever,
770
+ load_weight_prefix=self.load_weight_prefix,
771
+ name="rag",
772
+ )
773
+
774
+ def set_retriever(self, retriever: RagRetriever):
775
+ self.rag.retriever = retriever
776
+
777
+ # Adapted from https://github.com/huggingface/transformers/blob/main/src/transformers/modeling_tf_bart.py
778
+ def prepare_inputs_for_generation(
779
+ self,
780
+ decoder_input_ids,
781
+ past_key_values=None,
782
+ attention_mask=None,
783
+ use_cache=None,
784
+ encoder_outputs=None,
785
+ doc_scores=None,
786
+ n_docs=None,
787
+ **kwargs,
788
+ ):
789
+ if past_key_values is not None:
790
+ # if past is defined use only last decoder_input_ids
791
+ decoder_input_ids = decoder_input_ids[:, -1:]
792
+
793
+ return {
794
+ "input_ids": None,
795
+ "encoder_outputs": encoder_outputs,
796
+ "doc_scores": doc_scores,
797
+ "context_attention_mask": attention_mask,
798
+ "decoder_input_ids": decoder_input_ids,
799
+ "past_key_values": past_key_values,
800
+ "use_cache": use_cache,
801
+ "do_marginalize": True,
802
+ "n_docs": n_docs,
803
+ }
804
+
805
+ @property
806
+ def retriever(self):
807
+ return self.rag.retriever
808
+
809
+ @property
810
+ def generator(self):
811
+ return self.rag.generator
812
+
813
+ @property
814
+ def question_encoder(self):
815
+ return self.rag.question_encoder
816
+
817
+ @staticmethod
818
+ def _gather_beams(nested, beam_indices, batch_axis=0):
819
+ """
820
+ RAG-specific `_gather_beams`: gathers the beam slices indexed by beam_indices into new beam array. If the
821
+ nested tensor has a shape mismatch with the beam indices, then it means it is the cache. In that case, isolates
822
+ and takes care of the extra dimension for ndocs.
823
+ """
824
+
825
+ def gather_fn(tensor):
826
+ is_rag_cache = tensor.shape[0] != beam_indices.shape[0]
827
+ if is_rag_cache:
828
+ n_docs = tensor.shape[0] // beam_indices.shape[0]
829
+ batch_size = beam_indices.shape[0]
830
+ # reshapes into (batch size, num beams, n_docs, ...), the cache format expected by RAG
831
+ tensor = tf.reshape(tensor, (batch_size, -1, n_docs, *tensor.shape[2:]))
832
+
833
+ gathered_tensor = tf.gather(params=tensor, indices=beam_indices, axis=1, batch_dims=1)
834
+
835
+ if is_rag_cache:
836
+ # reshapes back into the shape expected by beam search
837
+ gathered_tensor = tf.reshape(gathered_tensor, (batch_size * n_docs, -1, *gathered_tensor.shape[3:]))
838
+
839
+ return gathered_tensor
840
+
841
+ return tf.nest.map_structure(gather_fn, nested)
842
+
843
+ def marginalize(self, seq_logits, doc_scores, n_docs=None):
844
+ n_docs = n_docs if n_docs is not None else self.config.n_docs
845
+
846
+ # RAG-token marginalization
847
+ seq_logprobs = tf.nn.log_softmax(seq_logits, axis=-1)
848
+ seq_logprobs = tf.reshape(seq_logprobs, [seq_logits.shape[0] // n_docs, n_docs, -1, seq_logits.shape[-1]])
849
+ doc_logprobs = tf.nn.log_softmax(doc_scores, axis=1)
850
+ doc_logprobs = tf.expand_dims(doc_logprobs, axis=-1)
851
+ doc_logprobs = tf.expand_dims(doc_logprobs, axis=-1) # twice
852
+ log_prob_sum = seq_logprobs + doc_logprobs
853
+ return tf.reduce_logsumexp(log_prob_sum, axis=1)
854
+
855
+ @unpack_inputs
856
+ @add_start_docstrings_to_model_forward(RAG_FORWARD_INPUTS_DOCSTRING)
857
+ @replace_return_docstrings(output_type=TFRetrievAugLMMarginOutput, config_class=_CONFIG_FOR_DOC)
858
+ def call(
859
+ self,
860
+ input_ids: TFModelInputType | None = None,
861
+ attention_mask: np.ndarray | tf.Tensor | None = None,
862
+ decoder_input_ids: np.ndarray | tf.Tensor | None = None,
863
+ decoder_attention_mask: np.ndarray | tf.Tensor | None = None,
864
+ encoder_outputs: np.ndarray | tf.Tensor | None = None,
865
+ past_key_values: tuple[tuple[np.ndarray | tf.Tensor]] | None = None,
866
+ doc_scores: np.ndarray | tf.Tensor | None = None,
867
+ context_input_ids: np.ndarray | tf.Tensor | None = None,
868
+ context_attention_mask: np.ndarray | tf.Tensor | None = None,
869
+ use_cache: bool | None = None,
870
+ output_attentions: bool | None = None,
871
+ output_hidden_states: bool | None = None,
872
+ output_retrieved: bool | None = None,
873
+ n_docs: int | None = None,
874
+ do_marginalize: bool | None = None,
875
+ labels: np.ndarray | tf.Tensor | None = None,
876
+ reduce_loss: bool | None = None,
877
+ return_dict: bool | None = None,
878
+ training: bool = False,
879
+ **kwargs, # needs kwargs for generation
880
+ ) -> TFRetrievAugLMMarginOutput:
881
+ r"""
882
+ do_marginalize (`bool`, *optional*):
883
+ If `True`, the logits are marginalized over all documents by making use of
884
+ `torch.nn.functional.log_softmax`.
885
+ labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
886
+ Labels for computing the cross entropy classification loss according to Rag-Token model formulation See
887
+ https://huggingface.co/papers/2005.11401 Section 2.1 for details about Rag-Token formulation. Indices should be
888
+ in `[0, ..., config.vocab_size - 1]`.
889
+ reduce_loss (`bool`, *optional*):
890
+ Only relevant if `labels` is passed. If `True`, the NLL loss is reduced using the `tf.Tensor.sum`
891
+ operation.
892
+ kwargs (`dict[str, any]`, *optional*, defaults to `{}`):
893
+ Legacy dictionary, which is required so that model can use *generate()* function.
894
+
895
+ Returns:
896
+
897
+ Example:
898
+
899
+ ```python
900
+ >>> import tensorflow as tf
901
+ >>> from transformers import AutoTokenizer, RagRetriever, TFRagTokenForGeneration
902
+
903
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/rag-token-nq")
904
+ >>> retriever = RagRetriever.from_pretrained(
905
+ ... "facebook/rag-token-nq", index_name="exact", use_dummy_dataset=True
906
+ ... )
907
+ >>> # initialize with RagRetriever to do everything in one forward call
908
+ >>> model = TFRagTokenForGeneration.from_pretrained("facebook/rag-token-nq", retriever=retriever, from_pt=True)
909
+
910
+ >>> input_dict = tokenizer.prepare_seq2seq_batch(
911
+ ... "How many people live in Paris?", "In Paris, there are 10 million people.", return_tensors="tf"
912
+ ... )
913
+ >>> outputs = model(input_dict, output_retrieved=True)
914
+
915
+ >>> # or use retriever separately
916
+ >>> # 1. Encode
917
+ >>> input_ids = input_dict["input_ids"]
918
+ >>> question_hidden_states = model.question_encoder(input_ids)[0]
919
+ >>> # 2. Retrieve
920
+ >>> docs_dict = retriever(input_ids.numpy(), question_hidden_states.numpy(), return_tensors="tf")
921
+ >>> doc_scores = tf.squeeze(
922
+ ... tf.matmul(
923
+ ... tf.expand_dims(question_hidden_states, axis=1), docs_dict["retrieved_doc_embeds"], transpose_b=True
924
+ ... ),
925
+ ... axis=1,
926
+ ... )
927
+ >>> # 3. Forward to generator
928
+ >>> outputs = model(
929
+ ... inputs=None,
930
+ ... context_input_ids=docs_dict["context_input_ids"],
931
+ ... context_attention_mask=docs_dict["context_attention_mask"],
932
+ ... doc_scores=doc_scores,
933
+ ... decoder_input_ids=input_dict["labels"],
934
+ ... )
935
+
936
+ >>> # or directly generate
937
+ >>> generated = model.generate(
938
+ ... context_input_ids=docs_dict["context_input_ids"],
939
+ ... context_attention_mask=docs_dict["context_attention_mask"],
940
+ ... doc_scores=doc_scores,
941
+ ... )
942
+ >>> generated_string = tokenizer.batch_decode(generated, skip_special_tokens=True)
943
+ ```"""
944
+
945
+ assert "decoder_cached_states" not in kwargs, (
946
+ "Please use past_key_values to cache intermediate outputs"
947
+ ) # from modeling_tf_bart.py
948
+
949
+ do_marginalize = do_marginalize if do_marginalize else self.config.do_marginalize
950
+ reduce_loss = reduce_loss if reduce_loss else self.config.reduce_loss
951
+
952
+ if labels is not None:
953
+ if decoder_input_ids is None:
954
+ decoder_input_ids = labels
955
+ use_cache = False
956
+
957
+ outputs = self.rag(
958
+ input_ids,
959
+ attention_mask=attention_mask,
960
+ encoder_outputs=encoder_outputs,
961
+ decoder_input_ids=decoder_input_ids,
962
+ decoder_attention_mask=decoder_attention_mask,
963
+ context_input_ids=context_input_ids,
964
+ context_attention_mask=context_attention_mask,
965
+ doc_scores=doc_scores,
966
+ past_key_values=past_key_values,
967
+ use_cache=use_cache,
968
+ output_attentions=output_attentions,
969
+ output_hidden_states=output_hidden_states,
970
+ output_retrieved=output_retrieved,
971
+ n_docs=n_docs,
972
+ training=training,
973
+ )
974
+
975
+ loss = None
976
+ logits = outputs.logits
977
+ if labels is not None:
978
+ assert decoder_input_ids is not None
979
+ loss = self.get_nll(
980
+ outputs.logits,
981
+ outputs.doc_scores,
982
+ labels,
983
+ reduce_loss=reduce_loss,
984
+ epsilon=self.config.label_smoothing,
985
+ n_docs=n_docs,
986
+ )
987
+
988
+ if do_marginalize:
989
+ logits = self.marginalize(logits, outputs.doc_scores, n_docs)
990
+
991
+ return TFRetrievAugLMMarginOutput(
992
+ loss=loss,
993
+ logits=logits,
994
+ past_key_values=outputs.past_key_values,
995
+ doc_scores=outputs.doc_scores,
996
+ context_input_ids=outputs.context_input_ids,
997
+ context_attention_mask=outputs.context_attention_mask,
998
+ retrieved_doc_embeds=outputs.retrieved_doc_embeds,
999
+ retrieved_doc_ids=outputs.retrieved_doc_ids,
1000
+ question_encoder_last_hidden_state=outputs.question_encoder_last_hidden_state,
1001
+ question_enc_hidden_states=outputs.question_enc_hidden_states,
1002
+ question_enc_attentions=outputs.question_enc_attentions,
1003
+ generator_enc_last_hidden_state=outputs.generator_enc_last_hidden_state,
1004
+ generator_enc_hidden_states=outputs.generator_enc_hidden_states,
1005
+ generator_enc_attentions=outputs.generator_enc_attentions,
1006
+ generator_dec_hidden_states=outputs.generator_dec_hidden_states,
1007
+ generator_dec_attentions=outputs.generator_dec_attentions,
1008
+ )
1009
+
1010
+ def generate(
1011
+ self,
1012
+ input_ids: TFModelInputType | None = None,
1013
+ attention_mask: tf.Tensor | None = None,
1014
+ context_input_ids=None,
1015
+ context_attention_mask=None,
1016
+ doc_scores=None,
1017
+ n_docs=None,
1018
+ generation_config=None,
1019
+ logits_processor=TFLogitsProcessorList(),
1020
+ **kwargs,
1021
+ ):
1022
+ """
1023
+ Implements TFRAG token decoding.
1024
+
1025
+ Args:
1026
+ input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1027
+ The sequence used as a prompt for the generation. If `input_ids` is not passed, then
1028
+ `context_input_ids` has to be provided.
1029
+ attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1030
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1031
+
1032
+ - 1 for tokens that are **not masked**,
1033
+ - 0 for tokens that are **masked**.
1034
+
1035
+ [What are attention masks?](../glossary#attention-mask)
1036
+ context_input_ids (`tf.Tensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
1037
+ Input IDs post-processed from the retrieved documents and the question encoder `input_ids` by the
1038
+ retriever.
1039
+
1040
+ If the model has is not initialized with a `retriever`, `context_input_ids` has to be provided to the
1041
+ forward pass. `context_input_ids` are returned by [`~RagRetriever.__call__`].
1042
+ context_attention_mask (`tf.Tensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
1043
+ Attention mask post-processed from the retrieved documents and the question encoder `input_ids` by the
1044
+ retriever.
1045
+
1046
+ If the model has is not initialized with a `retriever`, `context_input_ids` has to be provided to the
1047
+ forward pass. `context_input_ids` are returned by [`~RagRetriever.__call__`].
1048
+ doc_scores (`tf.Tensor` of shape `(batch_size, config.n_docs)`):
1049
+ Score between each retrieved document embeddings (see `retrieved_doc_embeds`) and
1050
+ `question_encoder_last_hidden_state`.
1051
+
1052
+ If the model has is not initialized with a `retriever`, `context_input_ids` has to be provided to the
1053
+ forward pass. `context_input_ids` are returned by [`~RagRetriever.__call__`].
1054
+ n_docs (`int`, *optional*, defaults to `config.n_docs`)
1055
+ Number of documents to retrieve and/or number of documents for which to generate an answer.
1056
+ generation_config (`~generation.GenerationConfig`, *optional*):
1057
+ The generation configuration to be used as base parametrization for the generation call. `**kwargs`
1058
+ passed to generate matching the attributes of `generation_config` will override them. If
1059
+ `generation_config` is not provided, the default will be used, which had the following loading
1060
+ priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model
1061
+ configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s
1062
+ default values, whose documentation should be checked to parameterize generation.
1063
+ logits_processor (`TFLogitsProcessorList`, *optional*):
1064
+ Custom logits processors that complement the default logits processors built from arguments and a
1065
+ model's config. If a logit processor is passed that is already created with the arguments or a model's
1066
+ config an error is thrown.
1067
+ kwargs (`dict[str, Any]`, *optional*):
1068
+ Ad hoc parametrization of `generate_config` and/or additional model-specific kwargs that will be
1069
+ forwarded to the `forward` function of the model.
1070
+
1071
+ Return:
1072
+ `tf.Tensor` of shape `(batch_size * num_return_sequences, sequence_length)`: The generated sequences. The
1073
+ second dimension (sequence_length) is either equal to `max_length` or shorter if all batches finished early
1074
+ due to the `eos_token_id`.
1075
+ """
1076
+ # Handle `generation_config` and kwargs that might update it
1077
+ if generation_config is None:
1078
+ generation_config = self.generation_config
1079
+ generation_config = copy.deepcopy(generation_config)
1080
+ model_kwargs = generation_config.update(**kwargs) # All unused kwargs must be model kwargs
1081
+
1082
+ # set default parameters
1083
+ n_docs = n_docs if n_docs is not None else self.config.n_docs
1084
+
1085
+ # retrieve docs
1086
+ if self.retriever is not None and context_input_ids is None:
1087
+ question_hidden_states = self.question_encoder(input_ids, attention_mask=attention_mask)[0]
1088
+ out = self.retriever(
1089
+ input_ids,
1090
+ question_hidden_states.numpy().astype(np.float32),
1091
+ prefix=self.generator.config.prefix,
1092
+ n_docs=n_docs,
1093
+ return_tensors="tf",
1094
+ )
1095
+ context_input_ids, context_attention_mask, retrieved_doc_embeds = (
1096
+ out["context_input_ids"],
1097
+ out["context_attention_mask"],
1098
+ out["retrieved_doc_embeds"],
1099
+ )
1100
+
1101
+ context_input_ids = tf.cast(context_input_ids, tf.int32)
1102
+ context_attention_mask = tf.cast(context_attention_mask, tf.int32)
1103
+ retrieved_doc_embeds = tf.cast(retrieved_doc_embeds, tf.float32)
1104
+
1105
+ # compute doc_scores
1106
+ doc_scores = tf.matmul(
1107
+ tf.expand_dims(question_hidden_states, axis=1), retrieved_doc_embeds, transpose_b=True
1108
+ )
1109
+ doc_scores = tf.squeeze(doc_scores, axis=1)
1110
+
1111
+ assert (context_input_ids.shape[0] % n_docs) == 0, (
1112
+ f" The first dimension of `context_input_ids` should be a multiple of `n_docs`={n_docs}, but is"
1113
+ f" {context_input_ids.shape[0]}."
1114
+ )
1115
+
1116
+ batch_size = context_input_ids.shape[0] // n_docs
1117
+
1118
+ encoder = self.rag.generator.get_encoder()
1119
+ encoder_outputs = encoder(
1120
+ input_ids=context_input_ids,
1121
+ attention_mask=context_attention_mask,
1122
+ output_attentions=generation_config.output_attentions,
1123
+ output_hidden_states=generation_config.output_hidden_states,
1124
+ return_dict=True,
1125
+ )
1126
+
1127
+ decoder_input_ids = tf.fill(
1128
+ (batch_size * generation_config.num_beams, 1),
1129
+ tf.cast(generation_config.decoder_start_token_id, tf.int32),
1130
+ )
1131
+ last_hidden_state = encoder_outputs["last_hidden_state"]
1132
+
1133
+ def extend_enc_output(tensor, num_beams=None):
1134
+ """
1135
+ Broadcast tensor with `num_beams` replica, with correct order Input: tensor of shape (batch_size*n_docs ,
1136
+ d) Output: tensor of shape (batch_size*num_beams*n_docs , d)
1137
+ """
1138
+
1139
+ # expand batch_size & num_beam dimensions
1140
+ d_shape_list = tensor.shape[1:]
1141
+
1142
+ # split n_docs dimensions
1143
+ new_shape = (batch_size, 1, n_docs) + d_shape_list
1144
+ tensor = tf.reshape(tensor, new_shape)
1145
+
1146
+ # repeat same last hidden states over `num_beams` dimension
1147
+ new_shape = (batch_size, num_beams, n_docs) + d_shape_list
1148
+ tensor = tf.broadcast_to(tensor, new_shape)
1149
+
1150
+ # merge `batch_size`, `num_beams`, `num_docs` dims again
1151
+ new_shape = (batch_size * num_beams * n_docs,) + d_shape_list
1152
+ return tf.reshape(tensor, new_shape)
1153
+
1154
+ # correctly extend last_hidden_state and attention mask
1155
+ context_attention_mask = extend_enc_output(context_attention_mask, num_beams=generation_config.num_beams)
1156
+ encoder_outputs["last_hidden_state"] = extend_enc_output(
1157
+ last_hidden_state, num_beams=generation_config.num_beams
1158
+ )
1159
+
1160
+ doc_scores = tf.repeat(doc_scores, generation_config.num_beams, axis=0)
1161
+
1162
+ # define start_len & additional parameters
1163
+ model_kwargs["doc_scores"] = doc_scores
1164
+ model_kwargs["encoder_outputs"] = encoder_outputs
1165
+ model_kwargs["attention_mask"] = context_attention_mask
1166
+ model_kwargs["n_docs"] = n_docs
1167
+
1168
+ pre_processor = self._get_logits_processor(
1169
+ generation_config=generation_config,
1170
+ input_ids_seq_length=tf.shape(decoder_input_ids)[-1],
1171
+ logits_processor=logits_processor,
1172
+ )
1173
+
1174
+ if generation_config.num_beams == 1:
1175
+ return self.greedy_search(
1176
+ input_ids=decoder_input_ids,
1177
+ max_length=generation_config.max_length,
1178
+ pad_token_id=generation_config.pad_token_id,
1179
+ eos_token_id=generation_config.eos_token_id,
1180
+ logits_processor=pre_processor,
1181
+ output_attentions=generation_config.output_attentions,
1182
+ output_hidden_states=generation_config.output_hidden_states,
1183
+ output_scores=generation_config.output_scores,
1184
+ return_dict_in_generate=generation_config.return_dict_in_generate,
1185
+ **model_kwargs,
1186
+ )
1187
+ elif generation_config.num_beams > 1:
1188
+ if generation_config.num_beams < generation_config.num_return_sequences:
1189
+ raise ValueError(
1190
+ "Beam search decoding cannot return more sequences than it has beams. Please set num_beams >="
1191
+ f" num_return_sequences, got {generation_config.num_beams} and"
1192
+ f" {generation_config.num_return_sequences} (respectively)"
1193
+ )
1194
+
1195
+ def unflatten_beam_dim(tensor):
1196
+ """Unflattens the first, flat batch*beam dimension of a non-scalar array."""
1197
+ shape = shape_list(tensor)
1198
+ return tf.reshape(tensor, [-1, generation_config.num_beams] + shape[1:])
1199
+
1200
+ decoder_input_ids = unflatten_beam_dim(decoder_input_ids)
1201
+ model_kwargs["attention_mask"] = unflatten_beam_dim(model_kwargs["attention_mask"])
1202
+ model_kwargs["encoder_outputs"]["last_hidden_state"] = unflatten_beam_dim(
1203
+ model_kwargs["encoder_outputs"]["last_hidden_state"]
1204
+ )
1205
+
1206
+ return self.beam_search(
1207
+ input_ids=decoder_input_ids,
1208
+ max_length=generation_config.max_length,
1209
+ pad_token_id=generation_config.pad_token_id,
1210
+ eos_token_id=generation_config.eos_token_id,
1211
+ logits_processor=pre_processor,
1212
+ output_attentions=generation_config.output_attentions,
1213
+ output_hidden_states=generation_config.output_hidden_states,
1214
+ output_scores=generation_config.output_scores,
1215
+ return_dict_in_generate=generation_config.return_dict_in_generate,
1216
+ **model_kwargs,
1217
+ )
1218
+ else:
1219
+ raise ValueError(
1220
+ f"`num_beams` has to be an integer strictly superior to 0 (≥ 1), but is {generation_config.num_beams}"
1221
+ )
1222
+
1223
+ def get_input_embeddings(self):
1224
+ return self.rag.generator.get_input_embeddings()
1225
+
1226
+ def get_output_embeddings(self):
1227
+ return self.rag.generator.get_output_embeddings()
1228
+
1229
+ # Adapted from tf_t5's & tf_bart's _shift_right
1230
+ def shift_tokens_right(self, input_ids, start_token_id=None):
1231
+ """Shift input ids one token to the right, and pad with start_token_id"""
1232
+
1233
+ if start_token_id is None:
1234
+ start_token_id = self.generator.config.decoder_start_token_id
1235
+ assert start_token_id is not None, (
1236
+ "self.generator.config.decoder_start_token_id has to be defined. In Rag we commonly use Bart as"
1237
+ " generator, see Bart docs for more information"
1238
+ )
1239
+
1240
+ pad_token_id = self.generator.config.pad_token_id
1241
+ assert pad_token_id is not None, "self.model.config.pad_token_id has to be defined."
1242
+
1243
+ start_tokens = tf.fill((shape_list(input_ids)[0], 1), tf.cast(start_token_id, input_ids.dtype))
1244
+ shifted_input_ids = tf.concat([start_tokens, input_ids[:, :-1]], -1)
1245
+
1246
+ # replace possible -100 values in labels by `pad_token_id`
1247
+ shifted_input_ids = tf.where(
1248
+ shifted_input_ids == -100,
1249
+ tf.fill(shape_list(shifted_input_ids), tf.cast(pad_token_id, input_ids.dtype)),
1250
+ shifted_input_ids,
1251
+ )
1252
+
1253
+ # "Verify that `labels` has only positive values and -100"
1254
+ assert_gte0 = tf.debugging.assert_greater_equal(shifted_input_ids, tf.cast(0, shifted_input_ids.dtype))
1255
+
1256
+ # Make sure the assertion op is called by wrapping the result in an identity no-op
1257
+ with tf.control_dependencies([assert_gte0]):
1258
+ shifted_input_ids = tf.identity(shifted_input_ids)
1259
+
1260
+ return shifted_input_ids
1261
+
1262
+ # nll stands for 'negative log likelihood'
1263
+ def get_nll(self, seq_logits, doc_scores, target, reduce_loss=False, epsilon=0.0, n_docs=None):
1264
+ n_docs = n_docs if n_docs is not None else self.config.n_docs
1265
+ # shift tokens left (from original Pytorch's version)
1266
+
1267
+ target = tf.concat(
1268
+ [target[:, 1:], tf.fill([target.shape[0], 1], tf.cast(self.config.generator.pad_token_id, target.dtype))],
1269
+ axis=1,
1270
+ )
1271
+ rag_logprobs = self.marginalize(seq_logits, doc_scores, n_docs)
1272
+ loss = self.hf_compute_loss(target, rag_logprobs, from_logits=True, reduce_loss=reduce_loss)
1273
+
1274
+ return loss
1275
+
1276
+ # Adopted modeling_tf_bart + add smooth_loss to match with pytorch version
1277
+ def hf_compute_loss(self, labels, y_pred, smooth_epsilon=0.0, from_logits=True, reduce_loss=False):
1278
+ """CrossEntropyLoss that ignores pad tokens"""
1279
+ # Matt: As written, this loss is not XLA-compatible, but it's doing some very weird things
1280
+ # and I don't feel comfortable converting it.
1281
+ loss_fn = keras.losses.SparseCategoricalCrossentropy(
1282
+ from_logits=True,
1283
+ reduction=keras.losses.Reduction.SUM,
1284
+ )
1285
+
1286
+ if from_logits is False: # convert to logits
1287
+ eps = 1e-9
1288
+ y_pred = tf.clip_by_value(y_pred, clip_value_min=eps, clip_value_max=1 - eps)
1289
+ y_pred = tf.math.log(y_pred)
1290
+
1291
+ logits = y_pred
1292
+ melted_labels = tf.reshape(labels, (-1,))
1293
+ active_loss = tf.not_equal(melted_labels, self.config.generator.pad_token_id)
1294
+
1295
+ reduced_logits = tf.boolean_mask(tf.reshape(logits, (-1, logits.shape[2])), active_loss)
1296
+ labels = tf.boolean_mask(melted_labels, active_loss)
1297
+ nll_loss = loss_fn(labels, reduced_logits)
1298
+
1299
+ smooth_loss = -tf.reduce_sum(reduced_logits, axis=-1)
1300
+ smooth_loss = tf.reduce_sum(smooth_loss) # sum and squeeze like torch
1301
+ eps_i = smooth_epsilon / reduced_logits.shape[-1]
1302
+
1303
+ loss = (1.0 - smooth_epsilon) * nll_loss + eps_i * smooth_loss
1304
+
1305
+ return loss
1306
+
1307
+ def build(self, input_shape=None):
1308
+ if self.built:
1309
+ return
1310
+ self.built = True
1311
+ if getattr(self, "rag", None) is not None:
1312
+ with tf.name_scope(self.rag.name):
1313
+ self.rag.build(None)
1314
+
1315
+
1316
+ @add_start_docstrings_to_model_forward(
1317
+ """
1318
+ A TF RAG-sequence model implementation. It performs RAG-sequence specific marginalization in the forward pass.
1319
+ """,
1320
+ RAG_START_DOCSTRING,
1321
+ )
1322
+ class TFRagSequenceForGeneration(TFRagPreTrainedModel, TFCausalLanguageModelingLoss):
1323
+ load_weight_prefix = "tf_rag_sequence_for_generation_1/rag"
1324
+
1325
+ def __init__(
1326
+ self,
1327
+ config: PretrainedConfig | None = None,
1328
+ question_encoder: TFPreTrainedModel | None = None,
1329
+ generator: TFPreTrainedModel | None = None,
1330
+ retriever: RagRetriever | None = None,
1331
+ **kwargs,
1332
+ ):
1333
+ assert config is not None or (question_encoder is not None and generator is not None), (
1334
+ "Either a configuration or an encoder and a generator has to be provided."
1335
+ )
1336
+
1337
+ if config is None:
1338
+ config = RagConfig.from_question_encoder_generator_configs(
1339
+ question_encoder.config, generator.config, **kwargs
1340
+ )
1341
+
1342
+ super().__init__(config)
1343
+
1344
+ # instantiate model
1345
+ self.rag = TFRagModel(
1346
+ config=config,
1347
+ question_encoder=question_encoder,
1348
+ generator=generator,
1349
+ retriever=retriever,
1350
+ load_weight_prefix=self.load_weight_prefix,
1351
+ name="rag",
1352
+ )
1353
+
1354
+ def set_retriever(self, retriever: RagRetriever):
1355
+ self.rag.retriever = retriever
1356
+
1357
+ @property
1358
+ def retriever(self):
1359
+ return self.rag.retriever
1360
+
1361
+ @property
1362
+ def generator(self):
1363
+ return self.rag.generator
1364
+
1365
+ @property
1366
+ def question_encoder(self):
1367
+ return self.rag.question_encoder
1368
+
1369
+ @unpack_inputs
1370
+ @add_start_docstrings_to_model_forward(RAG_FORWARD_INPUTS_DOCSTRING)
1371
+ @replace_return_docstrings(output_type=TFRetrievAugLMMarginOutput, config_class=_CONFIG_FOR_DOC)
1372
+ def call(
1373
+ self,
1374
+ input_ids: TFModelInputType | None = None,
1375
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1376
+ decoder_input_ids: np.ndarray | tf.Tensor | None = None,
1377
+ decoder_attention_mask: np.ndarray | tf.Tensor | None = None,
1378
+ encoder_outputs: np.ndarray | tf.Tensor | None = None,
1379
+ past_key_values: tuple[tuple[np.ndarray | tf.Tensor]] | None = None,
1380
+ doc_scores: np.ndarray | tf.Tensor | None = None,
1381
+ context_input_ids: np.ndarray | tf.Tensor | None = None,
1382
+ context_attention_mask: np.ndarray | tf.Tensor | None = None,
1383
+ use_cache: bool | None = None,
1384
+ output_attentions: bool | None = None,
1385
+ output_hidden_states: bool | None = None,
1386
+ output_retrieved: bool | None = None,
1387
+ n_docs: int | None = None,
1388
+ exclude_bos_score: bool | None = None,
1389
+ labels: np.ndarray | tf.Tensor | None = None,
1390
+ reduce_loss: bool | None = None,
1391
+ return_dict: bool | None = None,
1392
+ training: bool = False,
1393
+ **kwargs, # needs kwargs for generation
1394
+ ) -> tuple[tf.Tensor] | TFRetrievAugLMMarginOutput:
1395
+ r"""
1396
+ exclude_bos_score (`bool`, *optional*):
1397
+ Only relevant if `labels` is passed. If `True`, the score of the BOS token is disregarded when computing
1398
+ the loss.
1399
+ labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
1400
+ Labels for computing the cross entropy classification loss according to Rag-Sequence model formulation See
1401
+ https://huggingface.co/papers/2005.11401 Section 2.1 for details about Rag-Sequence formulation. Indices should
1402
+ be in `[0, ..., config.vocab_size - 1]`.
1403
+ reduce_loss (`bool`, *optional*):
1404
+ Only relevant if `labels` is passed. If `True`, the NLL loss is reduced using the `tf.Tensor.sum`
1405
+ operation.
1406
+ kwargs (`dict[str, any]`, *optional*, defaults to `{}`):
1407
+ Legacy dictionary, which is required so that model can use *generate()* function.
1408
+
1409
+ Returns:
1410
+
1411
+ Example:
1412
+
1413
+ ```python
1414
+ >>> from transformers import AutoTokenizer, RagRetriever, TFRagSequenceForGeneration
1415
+
1416
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/rag-sequence-nq")
1417
+ >>> retriever = RagRetriever.from_pretrained(
1418
+ ... "facebook/rag-sequence-nq", index_name="exact", use_dummy_dataset=True
1419
+ ... )
1420
+ >>> # initialize with RagRetriever to do everything in one forward call
1421
+ >>> model = TFRagSequenceForGeneration.from_pretrained(
1422
+ ... "facebook/rag-sequence-nq", retriever=retriever, from_pt=True
1423
+ ... )
1424
+
1425
+ >>> input_dict = tokenizer.prepare_seq2seq_batch(
1426
+ ... "How many people live in Paris?", "In Paris, there are 10 million people.", return_tensors="tf"
1427
+ ... )
1428
+ >>> outputs = model(input_dict, output_retrieved=True)
1429
+
1430
+ >>> # or use retriever separately
1431
+ >>> # 1. Encode
1432
+ >>> input_ids = input_dict["input_ids"]
1433
+ >>> question_hidden_states = model.question_encoder(input_ids)[0]
1434
+ >>> # 2. Retrieve
1435
+ >>> docs_dict = retriever(input_ids.numpy(), question_hidden_states.numpy(), return_tensors="tf")
1436
+ >>> doc_scores = tf.squeeze(
1437
+ ... tf.matmul(
1438
+ ... tf.expand_dims(question_hidden_states, axis=1), docs_dict["retrieved_doc_embeds"], transpose_b=True
1439
+ ... ),
1440
+ ... axis=1,
1441
+ ... )
1442
+ >>> # 3. Forward to generator
1443
+ >>> outputs = model(
1444
+ ... inputs=None,
1445
+ ... context_input_ids=docs_dict["context_input_ids"],
1446
+ ... context_attention_mask=docs_dict["context_attention_mask"],
1447
+ ... doc_scores=doc_scores,
1448
+ ... decoder_input_ids=input_dict["labels"],
1449
+ ... )
1450
+
1451
+ >>> # or directly generate
1452
+ >>> generated = model.generate(
1453
+ ... context_input_ids=docs_dict["context_input_ids"],
1454
+ ... context_attention_mask=docs_dict["context_attention_mask"],
1455
+ ... doc_scores=doc_scores,
1456
+ ... )
1457
+ >>> generated_string = tokenizer.batch_decode(generated, skip_special_tokens=True)
1458
+ ```"""
1459
+
1460
+ assert "decoder_cached_states" not in kwargs, (
1461
+ "Please use past_key_values to cache intermediate outputs"
1462
+ ) # from modeling_tf_bart.py
1463
+
1464
+ exclude_bos_score = exclude_bos_score if exclude_bos_score else self.config.exclude_bos_score
1465
+ reduce_loss = reduce_loss if reduce_loss else self.config.reduce_loss
1466
+
1467
+ if labels is not None:
1468
+ if decoder_input_ids is None:
1469
+ decoder_input_ids = labels
1470
+ use_cache = False
1471
+
1472
+ outputs = self.rag(
1473
+ input_ids,
1474
+ attention_mask=attention_mask,
1475
+ encoder_outputs=encoder_outputs,
1476
+ decoder_input_ids=decoder_input_ids,
1477
+ decoder_attention_mask=decoder_attention_mask,
1478
+ context_input_ids=context_input_ids,
1479
+ context_attention_mask=context_attention_mask,
1480
+ doc_scores=doc_scores,
1481
+ past_key_values=past_key_values,
1482
+ use_cache=use_cache,
1483
+ output_attentions=output_attentions,
1484
+ output_hidden_states=output_hidden_states,
1485
+ output_retrieved=output_retrieved,
1486
+ n_docs=n_docs,
1487
+ training=training,
1488
+ )
1489
+
1490
+ loss = None
1491
+ if labels is not None:
1492
+ loss = self.get_nll(
1493
+ outputs.logits,
1494
+ outputs.doc_scores,
1495
+ labels,
1496
+ reduce_loss=reduce_loss,
1497
+ epsilon=self.config.label_smoothing,
1498
+ n_docs=n_docs,
1499
+ )
1500
+
1501
+ return TFRetrievAugLMMarginOutput(
1502
+ loss=loss,
1503
+ logits=outputs.logits,
1504
+ doc_scores=outputs.doc_scores,
1505
+ past_key_values=outputs.past_key_values,
1506
+ context_input_ids=outputs.context_input_ids,
1507
+ context_attention_mask=outputs.context_attention_mask,
1508
+ retrieved_doc_embeds=outputs.retrieved_doc_embeds,
1509
+ retrieved_doc_ids=outputs.retrieved_doc_ids,
1510
+ question_encoder_last_hidden_state=outputs.question_encoder_last_hidden_state,
1511
+ question_enc_hidden_states=outputs.question_enc_hidden_states,
1512
+ question_enc_attentions=outputs.question_enc_attentions,
1513
+ generator_enc_last_hidden_state=outputs.generator_enc_last_hidden_state,
1514
+ generator_enc_hidden_states=outputs.generator_enc_hidden_states,
1515
+ generator_enc_attentions=outputs.generator_enc_attentions,
1516
+ generator_dec_hidden_states=outputs.generator_dec_hidden_states,
1517
+ generator_dec_attentions=outputs.generator_dec_attentions,
1518
+ )
1519
+
1520
+ def get_nll(
1521
+ self, seq_logits, doc_scores, target, reduce_loss=False, epsilon=0.0, exclude_bos_score=False, n_docs=None
1522
+ ):
1523
+ # shift tokens left
1524
+ target = tf.concat(
1525
+ [target[:, 1:], tf.fill([target.shape[0], 1], tf.cast(self.config.generator.pad_token_id, target.dtype))],
1526
+ axis=1,
1527
+ )
1528
+
1529
+ # bos_token_id is None for T5
1530
+ bos_token_id = self.config.bos_token_id or self.config.generator.bos_token_id
1531
+ n_docs = n_docs if n_docs is not None else self.config.n_docs
1532
+ equal_bos_token_id_all = tf.reduce_all(tf.equal(target[:, 0], bos_token_id))
1533
+ use_bos = bos_token_id is not None and equal_bos_token_id_all
1534
+
1535
+ def _mask_pads(ll, smooth_obj):
1536
+ pad_mask = tf.equal(target, tf.cast(self.config.generator.pad_token_id, target.dtype))
1537
+ if tf.reduce_any(pad_mask):
1538
+ ll = tf.where(pad_mask, 0.0, ll)
1539
+ smooth_obj = tf.where(pad_mask, 0.0, smooth_obj)
1540
+ return tf.squeeze(ll, axis=-1), tf.squeeze(smooth_obj, axis=-1)
1541
+
1542
+ # seq_logits.shape = (batch*n_docs, tgt_len , vocabs)
1543
+ seq_logprobs = tf.nn.log_softmax(seq_logits, axis=-1)
1544
+ seq_logprobs = tf.reshape(
1545
+ seq_logprobs, (seq_logits.shape[0] // n_docs, n_docs, -1, seq_logits.shape[-1])
1546
+ ) # (batch_size, n_docs, tgt_len, vocabs)
1547
+ doc_logprobs = tf.nn.log_softmax(doc_scores, axis=1)
1548
+ doc_logprobs = tf.expand_dims(doc_logprobs, axis=-1)
1549
+ doc_logprobs = tf.expand_dims(doc_logprobs, axis=-1) # done twice to get 4-D
1550
+
1551
+ # RAG-sequence marginalization
1552
+ first_token_scores = seq_logprobs[:, :, :1, :]
1553
+ second_token_scores = seq_logprobs[:, :, 1:2, :]
1554
+ remainder = seq_logprobs[:, :, 2:, :]
1555
+ rag_logprobs = tf.concat([first_token_scores, second_token_scores + doc_logprobs, remainder], axis=2)
1556
+
1557
+ # calculate loss
1558
+ target = tf.expand_dims(target, axis=1) # n_docs dimension
1559
+ target = tf.expand_dims(target, axis=-1) # logits dimension
1560
+ target = tf.repeat(target, n_docs, axis=1)
1561
+ assert len(target.shape) == len(rag_logprobs.shape)
1562
+
1563
+ # last-axis gathering only - use 2D-reshape-trick for Torch's style nD gathering
1564
+ def torch_gather(param, id_tensor):
1565
+ # 2d-gather torch equivalent: https://stackoverflow.com/questions/52129909/tensorflow-equivalent-of-torch-gather
1566
+ def gather2d(target, id_tensor):
1567
+ idx = tf.stack([tf.range(tf.shape(id_tensor)[0], dtype=id_tensor.dtype), id_tensor[:, 0]], axis=-1)
1568
+ result = tf.gather_nd(target, idx)
1569
+ return tf.expand_dims(result, axis=-1)
1570
+
1571
+ target = tf.reshape(param, (-1, param.shape[-1])) # reshape 2D
1572
+ target_shape = id_tensor.shape
1573
+
1574
+ id_tensor = tf.reshape(id_tensor, (-1, 1)) # also 2D-index
1575
+ result = gather2d(target, id_tensor)
1576
+ return tf.reshape(result, target_shape)
1577
+
1578
+ ll = torch_gather(rag_logprobs, id_tensor=target)
1579
+ smooth_obj = tf.reduce_sum(rag_logprobs, axis=-1, keepdims=True) # total sum of all (normalised) logits
1580
+
1581
+ ll, smooth_obj = _mask_pads(ll, smooth_obj)
1582
+
1583
+ # sum over tokens, exclude bos while scoring
1584
+ if exclude_bos_score and use_bos:
1585
+ ll = tf.reduce_sum(ll[:, :, 1:], axis=2)
1586
+ else:
1587
+ ll = tf.reduce_sum(ll, axis=2)
1588
+
1589
+ smooth_obj = tf.reduce_sum(smooth_obj, axis=2)
1590
+ ll = tf.math.reduce_logsumexp(ll, axis=1) # logsumexp over docs
1591
+ smooth_obj = tf.math.reduce_logsumexp(smooth_obj, axis=1)
1592
+
1593
+ nll_loss = -ll
1594
+ smooth_loss = -smooth_obj
1595
+
1596
+ if reduce_loss:
1597
+ nll_loss = tf.reduce_sum(nll_loss)
1598
+ smooth_loss = tf.reduce_sum(smooth_loss)
1599
+
1600
+ eps_i = epsilon / rag_logprobs.shape[-1]
1601
+ loss = (1.0 - epsilon) * nll_loss + eps_i * smooth_loss
1602
+ return loss
1603
+
1604
+ def generate(
1605
+ self,
1606
+ input_ids: TFModelInputType | None = None,
1607
+ attention_mask: tf.Tensor | None = None,
1608
+ context_input_ids=None,
1609
+ context_attention_mask=None,
1610
+ doc_scores=None,
1611
+ do_deduplication=None, # defaults to True
1612
+ num_return_sequences=None, # defaults to 1
1613
+ num_beams=None, # defaults to 1
1614
+ n_docs=None,
1615
+ **model_kwargs,
1616
+ ):
1617
+ """
1618
+ Implements RAG sequence "thorough" decoding. Read the [`~generation.GenerationMixin.generate`]` documentation
1619
+ for more information on how to set other generate input parameters
1620
+
1621
+ Args:
1622
+ input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1623
+ The sequence used as a prompt for the generation. If `input_ids` is not passed, then
1624
+ `context_input_ids` has to be provided.
1625
+ attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1626
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for
1627
+ tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention
1628
+ masks?](../glossary#attention-mask)
1629
+ context_input_ids (`tf.Tensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
1630
+ Input IDs post-processed from the retrieved documents and the question encoder input_ids by the
1631
+ retriever.
1632
+ context_attention_mask (`tf.Tensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
1633
+ Attention mask post-processed from the retrieved documents and the question encoder `input_ids` by the
1634
+ retriever. If the model has is not initialized with a `retriever` or `input_ids` is not given,
1635
+ `context_input_ids` and `context_attention_mask` have to be provided to the forward pass. They are
1636
+ returned by [`~RagRetriever.__call__`].
1637
+ doc_scores (`tf.Tensor` of shape `(batch_size, config.n_docs)`):
1638
+ Score between each retrieved document embeddings (see `retrieved_doc_embeds`) and
1639
+ `question_encoder_last_hidden_state`. If the model has is not initialized with a `retriever` or
1640
+ `input_ids` is not given, `doc_scores` has to be provided to the forward pass. `doc_scores` are
1641
+ returned by [`~RagRetriever.__call__`].
1642
+ do_deduplication (`bool`, *optional*):
1643
+ Whether or not to deduplicate the generations from different context documents for a given input. Has
1644
+ to be set to `False` if used while training with distributed backend.
1645
+ num_return_sequences(`int`, *optional*, defaults to 1):
1646
+ The number of independently computed returned sequences for each element in the batch. Note that this
1647
+ is not the value we pass to the `generator`'s `[`~generation.GenerationMixin.generate`]` function,
1648
+ where we set `num_return_sequences` to `num_beams`.
1649
+ num_beams (`int`, *optional*, defaults to 1):
1650
+ Number of beams for beam search. 1 means no beam search.
1651
+ n_docs (`int`, *optional*, defaults to `config.n_docs`)
1652
+ Number of documents to retrieve and/or number of documents for which to generate an answer.
1653
+ kwargs (`dict[str, Any]`, *optional*):
1654
+ Additional kwargs will be passed to [`~generation.GenerationMixin.generate`]
1655
+
1656
+ Return:
1657
+ `tf.Tensor` of shape `(batch_size * num_return_sequences, sequence_length)`: The generated sequences. The
1658
+ second dimension (sequence length) is either equal to `max_length` or shorter if all batches finished early
1659
+ due to the `eos_token_id`.
1660
+ """
1661
+
1662
+ n_docs = n_docs if n_docs is not None else self.config.n_docs
1663
+ do_deduplication = do_deduplication if do_deduplication is not None else self.config.do_deduplication
1664
+ num_doc_return_sequences = (
1665
+ num_return_sequences if num_return_sequences is not None else self.config.num_return_sequences
1666
+ )
1667
+ num_beams = num_beams if num_beams is not None else self.config.num_beams
1668
+
1669
+ assert input_ids is not None or context_input_ids is not None, (
1670
+ " At least one of input_ids or context_input_ids must be given"
1671
+ )
1672
+
1673
+ if self.retriever is not None and context_input_ids is None:
1674
+ question_hidden_states = self.question_encoder(input_ids, attention_mask=attention_mask)[0]
1675
+ context_input_ids = self.retriever(
1676
+ input_ids,
1677
+ question_hidden_states.numpy(),
1678
+ prefix=self.generator.config.prefix,
1679
+ n_docs=n_docs,
1680
+ return_tensors="tf",
1681
+ )["context_input_ids"]
1682
+
1683
+ hypos = []
1684
+ model_kwargs["num_beams"] = num_beams
1685
+ model_kwargs["num_return_sequences"] = num_beams # put here so that not confused with num_doc_return_sequences
1686
+ model_kwargs["attention_mask"] = None
1687
+
1688
+ batch_size = input_ids.shape[0] if input_ids is not None else context_input_ids.shape[0] // n_docs
1689
+
1690
+ for index in range(batch_size):
1691
+ # first, generate beams from documents:
1692
+ generator_input_ids = context_input_ids[index * n_docs : (index + 1) * n_docs] # (n_docs, max_len)
1693
+
1694
+ output_sequences = self.generator.generate(
1695
+ generator_input_ids,
1696
+ **model_kwargs,
1697
+ ) # n_docs * n_beam, tgt_len
1698
+ if do_deduplication:
1699
+ # do_deduplication -- for TF, work on Eager mode only!
1700
+ output_sequences = tf.stack(list({str(k.numpy().tolist()): k for k in output_sequences}.values()))
1701
+
1702
+ num_candidates = output_sequences.shape[
1703
+ 0
1704
+ ] # after deduplication, this number can be less than n_docs*n_beam
1705
+
1706
+ # then, run model forwards to get nll scores:
1707
+ if input_ids is not None:
1708
+ new_input_ids = tf.tile(input_ids[index : index + 1], (num_candidates, 1))
1709
+ outputs = self(new_input_ids, labels=output_sequences, exclude_bos_score=True)
1710
+ else: # input_ids is None, need context_input_ids/mask and doc_scores
1711
+ assert context_attention_mask is not None, (
1712
+ "Make sure that `context_attention_mask` are passed, if no `input_ids` is set. Alternatively, you"
1713
+ " can set a retriever using the `set_retriever(...)` function."
1714
+ )
1715
+ assert doc_scores is not None, (
1716
+ "Make sure that `doc_scores` are passed, if no `input_ids` is set. Alternatively, you can set a"
1717
+ " retriever using the `set_retriever(...)` function."
1718
+ )
1719
+
1720
+ individual_input_ids = tf.tile(
1721
+ generator_input_ids, (num_candidates, 1)
1722
+ ) # (num_candidates*n_docs, max_len)
1723
+
1724
+ individual_attention_mask = context_attention_mask[index * n_docs : (index + 1) * n_docs]
1725
+ individual_attention_mask = tf.tile(individual_attention_mask, (num_candidates, 1))
1726
+
1727
+ individual_doc_scores = doc_scores[index : (index + 1), :] # doc_scores.shape = [batch, n_docs]
1728
+ individual_doc_scores = tf.tile(individual_doc_scores, (num_candidates, 1)) # [num_candidates, n_docs]
1729
+
1730
+ outputs = self(
1731
+ input_ids=None,
1732
+ context_input_ids=individual_input_ids,
1733
+ context_attention_mask=individual_attention_mask,
1734
+ doc_scores=individual_doc_scores,
1735
+ labels=output_sequences,
1736
+ exclude_bos_score=True,
1737
+ )
1738
+
1739
+ top_cand_inds = tf.math.top_k((-outputs["loss"]), k=num_doc_return_sequences)[1]
1740
+
1741
+ # add hypothesis
1742
+ hypos.append(tf.gather(output_sequences, top_cand_inds))
1743
+
1744
+ return self._cat_and_pad(hypos, pad_token_id=self.config.generator.pad_token_id)
1745
+
1746
+ @staticmethod
1747
+ def _cat_and_pad(tensors, pad_token_id):
1748
+ # used by generate(): tensors is a (batched) list of (candidates, len); len is varied across batch
1749
+
1750
+ # Initialize padded tensor with shape ( all_candidates , max_candidate_length ),
1751
+ # where all_candidates counted from all inputs
1752
+ new_shape = sum([t.shape[0] for t in tensors]), max([t.shape[1] for t in tensors])
1753
+ output = tf.fill(new_shape, pad_token_id)
1754
+
1755
+ # Normal tensor doesn't support slice assignment, so we need tf.Variable
1756
+ output = tf.Variable(output)
1757
+
1758
+ # Assign, and then convert back to tensor
1759
+ ind = 0
1760
+ for t in tensors:
1761
+ output[ind : ind + t.shape[0], : t.shape[1]].assign(t)
1762
+ ind += t.shape[0]
1763
+
1764
+ output = tf.convert_to_tensor(output)
1765
+ return tf.cast(output, tensors[0][0][0].dtype)
1766
+
1767
+ def build(self, input_shape=None):
1768
+ if self.built:
1769
+ return
1770
+ self.built = True
1771
+ if getattr(self, "rag", None) is not None:
1772
+ with tf.name_scope(self.rag.name):
1773
+ self.rag.build(None)
1774
+
1775
+
1776
+ __all__ = ["TFRagModel", "TFRagPreTrainedModel", "TFRagSequenceForGeneration", "TFRagTokenForGeneration"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/rag/retrieval_rag.py ADDED
@@ -0,0 +1,682 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020, The RAG Authors and The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """RAG Retriever model implementation."""
16
+
17
+ import os
18
+ import pickle
19
+ import time
20
+ from collections.abc import Iterable
21
+ from typing import Optional
22
+
23
+ import numpy as np
24
+
25
+ from ...tokenization_utils import PreTrainedTokenizer
26
+ from ...tokenization_utils_base import BatchEncoding
27
+ from ...utils import cached_file, is_datasets_available, is_faiss_available, logging, requires_backends, strtobool
28
+ from .configuration_rag import RagConfig
29
+ from .tokenization_rag import RagTokenizer
30
+
31
+
32
+ if is_datasets_available():
33
+ from datasets import Dataset, load_dataset, load_from_disk
34
+
35
+ if is_faiss_available():
36
+ import faiss
37
+
38
+
39
+ logger = logging.get_logger(__name__)
40
+
41
+
42
+ LEGACY_INDEX_PATH = "https://storage.googleapis.com/huggingface-nlp/datasets/wiki_dpr/"
43
+
44
+
45
+ class Index:
46
+ """
47
+ A base class for the Indices encapsulated by the [`RagRetriever`].
48
+ """
49
+
50
+ def get_doc_dicts(self, doc_ids: np.ndarray) -> list[dict]:
51
+ """
52
+ Returns a list of dictionaries, containing titles and text of the retrieved documents.
53
+
54
+ Args:
55
+ doc_ids (`np.ndarray` of shape `(batch_size, n_docs)`):
56
+ A tensor of document indices.
57
+ """
58
+ raise NotImplementedError
59
+
60
+ def get_top_docs(self, question_hidden_states: np.ndarray, n_docs=5) -> tuple[np.ndarray, np.ndarray]:
61
+ """
62
+ For each query in the batch, retrieves `n_docs` documents.
63
+
64
+ Args:
65
+ question_hidden_states (`np.ndarray` of shape `(batch_size, vector_size)`):
66
+ An array of query vectors.
67
+ n_docs (`int`):
68
+ The number of docs retrieved per query.
69
+
70
+ Returns:
71
+ `np.ndarray` of shape `(batch_size, n_docs)`: A tensor of indices of retrieved documents. `np.ndarray` of
72
+ shape `(batch_size, vector_size)`: A tensor of vector representations of retrieved documents.
73
+ """
74
+ raise NotImplementedError
75
+
76
+ def is_initialized(self):
77
+ """
78
+ Returns `True` if index is already initialized.
79
+ """
80
+ raise NotImplementedError
81
+
82
+ def init_index(self):
83
+ """
84
+ A function responsible for loading the index into memory. Should be called only once per training run of a RAG
85
+ model. E.g. if the model is trained on multiple GPUs in a distributed setup, only one of the workers will load
86
+ the index.
87
+ """
88
+ raise NotImplementedError
89
+
90
+
91
+ class LegacyIndex(Index):
92
+ """
93
+ An index which can be deserialized from the files built using https://github.com/facebookresearch/DPR. We use
94
+ default faiss index parameters as specified in that repository.
95
+
96
+ Args:
97
+ vector_size (`int`):
98
+ The dimension of indexed vectors.
99
+ index_path (`str`):
100
+ A path to a *directory* containing index files compatible with [`~models.rag.retrieval_rag.LegacyIndex`]
101
+ """
102
+
103
+ INDEX_FILENAME = "hf_bert_base.hnswSQ8_correct_phi_128.c_index"
104
+ PASSAGE_FILENAME = "psgs_w100.tsv.pkl"
105
+
106
+ def __init__(self, vector_size, index_path):
107
+ requires_backends(self, ["faiss"])
108
+ self.index_id_to_db_id = []
109
+ self.index_path = index_path
110
+ self.passages = self._load_passages()
111
+ self.vector_size = vector_size
112
+ self.index = None
113
+ self._index_initialized = False
114
+
115
+ def _resolve_path(self, index_path, filename):
116
+ is_local = os.path.isdir(index_path)
117
+ try:
118
+ # Load from URL or cache if already cached
119
+ resolved_archive_file = cached_file(index_path, filename)
120
+ except OSError:
121
+ msg = (
122
+ f"Can't load '{filename}'. Make sure that:\n\n"
123
+ f"- '{index_path}' is a correct remote path to a directory containing a file named {filename}\n\n"
124
+ f"- or '{index_path}' is the correct path to a directory containing a file named {filename}.\n\n"
125
+ )
126
+ raise OSError(msg)
127
+ if is_local:
128
+ logger.info(f"loading file {resolved_archive_file}")
129
+ else:
130
+ logger.info(f"loading file {filename} from cache at {resolved_archive_file}")
131
+ return resolved_archive_file
132
+
133
+ def _load_passages(self):
134
+ logger.info(f"Loading passages from {self.index_path}")
135
+ passages_path = self._resolve_path(self.index_path, self.PASSAGE_FILENAME)
136
+ if not strtobool(os.environ.get("TRUST_REMOTE_CODE", "False")):
137
+ raise ValueError(
138
+ "This part uses `pickle.load` which is insecure and will execute arbitrary code that is potentially "
139
+ "malicious. It's recommended to never unpickle data that could have come from an untrusted source, or "
140
+ "that could have been tampered with. If you already verified the pickle data and decided to use it, "
141
+ "you can set the environment variable `TRUST_REMOTE_CODE` to `True` to allow it."
142
+ )
143
+ with open(passages_path, "rb") as passages_file:
144
+ passages = pickle.load(passages_file)
145
+ return passages
146
+
147
+ def _deserialize_index(self):
148
+ logger.info(f"Loading index from {self.index_path}")
149
+ resolved_index_path = self._resolve_path(self.index_path, self.INDEX_FILENAME + ".index.dpr")
150
+ self.index = faiss.read_index(resolved_index_path)
151
+ resolved_meta_path = self._resolve_path(self.index_path, self.INDEX_FILENAME + ".index_meta.dpr")
152
+ if not strtobool(os.environ.get("TRUST_REMOTE_CODE", "False")):
153
+ raise ValueError(
154
+ "This part uses `pickle.load` which is insecure and will execute arbitrary code that is potentially "
155
+ "malicious. It's recommended to never unpickle data that could have come from an untrusted source, or "
156
+ "that could have been tampered with. If you already verified the pickle data and decided to use it, "
157
+ "you can set the environment variable `TRUST_REMOTE_CODE` to `True` to allow it."
158
+ )
159
+ with open(resolved_meta_path, "rb") as metadata_file:
160
+ self.index_id_to_db_id = pickle.load(metadata_file)
161
+ assert len(self.index_id_to_db_id) == self.index.ntotal, (
162
+ "Deserialized index_id_to_db_id should match faiss index size"
163
+ )
164
+
165
+ def is_initialized(self):
166
+ return self._index_initialized
167
+
168
+ def init_index(self):
169
+ index = faiss.IndexHNSWFlat(self.vector_size + 1, 512)
170
+ index.hnsw.efSearch = 128
171
+ index.hnsw.efConstruction = 200
172
+ self.index = index
173
+ self._deserialize_index()
174
+ self._index_initialized = True
175
+
176
+ def get_doc_dicts(self, doc_ids: np.array):
177
+ doc_list = []
178
+ for doc_ids_i in doc_ids:
179
+ ids = [str(int(doc_id)) for doc_id in doc_ids_i]
180
+ docs = [self.passages[doc_id] for doc_id in ids]
181
+ doc_list.append(docs)
182
+ doc_dicts = []
183
+ for docs in doc_list:
184
+ doc_dict = {}
185
+ doc_dict["title"] = [doc[1] for doc in docs]
186
+ doc_dict["text"] = [doc[0] for doc in docs]
187
+ doc_dicts.append(doc_dict)
188
+ return doc_dicts
189
+
190
+ def get_top_docs(self, question_hidden_states: np.ndarray, n_docs=5) -> tuple[np.ndarray, np.ndarray]:
191
+ aux_dim = np.zeros(len(question_hidden_states), dtype="float32").reshape(-1, 1)
192
+ query_nhsw_vectors = np.hstack((question_hidden_states, aux_dim))
193
+ _, docs_ids = self.index.search(query_nhsw_vectors, n_docs)
194
+ vectors = [[self.index.reconstruct(int(doc_id))[:-1] for doc_id in doc_ids] for doc_ids in docs_ids]
195
+ ids = [[int(self.index_id_to_db_id[doc_id]) for doc_id in doc_ids] for doc_ids in docs_ids]
196
+ return np.array(ids), np.array(vectors)
197
+
198
+
199
+ class HFIndexBase(Index):
200
+ def __init__(self, vector_size, dataset, index_initialized=False):
201
+ requires_backends(self, ["faiss"])
202
+ self.vector_size = vector_size
203
+ self.dataset = dataset
204
+ self._index_initialized = index_initialized
205
+ self._check_dataset_format(with_index=index_initialized)
206
+ dataset.set_format("numpy", columns=["embeddings"], output_all_columns=True, dtype="float32")
207
+
208
+ def _check_dataset_format(self, with_index: bool):
209
+ if not isinstance(self.dataset, Dataset):
210
+ raise TypeError(f"Dataset should be a datasets.Dataset object, but got {type(self.dataset)}")
211
+ if len({"title", "text", "embeddings"} - set(self.dataset.column_names)) > 0:
212
+ raise ValueError(
213
+ "Dataset should be a dataset with the following columns: "
214
+ "title (str), text (str) and embeddings (arrays of dimension vector_size), "
215
+ f"but got columns {self.dataset.column_names}"
216
+ )
217
+ if with_index and "embeddings" not in self.dataset.list_indexes():
218
+ raise ValueError(
219
+ "Missing faiss index in the dataset. Make sure you called `dataset.add_faiss_index` to compute it "
220
+ "or `dataset.load_faiss_index` to load one from the disk."
221
+ )
222
+
223
+ def init_index(self):
224
+ raise NotImplementedError()
225
+
226
+ def is_initialized(self):
227
+ return self._index_initialized
228
+
229
+ def get_doc_dicts(self, doc_ids: np.ndarray) -> list[dict]:
230
+ return [self.dataset[doc_ids[i].tolist()] for i in range(doc_ids.shape[0])]
231
+
232
+ def get_top_docs(self, question_hidden_states: np.ndarray, n_docs=5) -> tuple[np.ndarray, np.ndarray]:
233
+ _, ids = self.dataset.search_batch("embeddings", question_hidden_states, n_docs)
234
+ docs = [self.dataset[[i for i in indices if i >= 0]] for indices in ids]
235
+ vectors = [doc["embeddings"] for doc in docs]
236
+ for i in range(len(vectors)):
237
+ if len(vectors[i]) < n_docs:
238
+ vectors[i] = np.vstack([vectors[i], np.zeros((n_docs - len(vectors[i]), self.vector_size))])
239
+ return np.array(ids), np.array(vectors) # shapes (batch_size, n_docs) and (batch_size, n_docs, d)
240
+
241
+
242
+ class CanonicalHFIndex(HFIndexBase):
243
+ """
244
+ A wrapper around an instance of [`~datasets.Datasets`]. If `index_path` is set to `None`, we load the pre-computed
245
+ index available with the [`~datasets.arrow_dataset.Dataset`], otherwise, we load the index from the indicated path
246
+ on disk.
247
+
248
+ Args:
249
+ vector_size (`int`): the dimension of the passages embeddings used by the index
250
+ dataset_name (`str`, optional, defaults to `wiki_dpr`):
251
+ A dataset identifier of the indexed dataset on HuggingFace AWS bucket (list all available datasets and ids
252
+ with `datasets.list_datasets()`).
253
+ dataset_split (`str`, optional, defaults to `train`)
254
+ Which split of the `dataset` to load.
255
+ index_name (`str`, optional, defaults to `train`)
256
+ The index_name of the index associated with the `dataset`. The index loaded from `index_path` will be saved
257
+ under this name.
258
+ index_path (`str`, optional, defaults to `None`)
259
+ The path to the serialized faiss index on disk.
260
+ use_dummy_dataset (`bool`, optional, defaults to `False`):
261
+ If True, use the dummy configuration of the dataset for tests.
262
+ """
263
+
264
+ def __init__(
265
+ self,
266
+ vector_size: int,
267
+ dataset_name: str = "wiki_dpr",
268
+ dataset_split: str = "train",
269
+ index_name: Optional[str] = None,
270
+ index_path: Optional[str] = None,
271
+ use_dummy_dataset=False,
272
+ dataset_revision=None,
273
+ ):
274
+ requires_backends(self, ["faiss"])
275
+ if int(index_path is None) + int(index_name is None) != 1:
276
+ raise ValueError("Please provide `index_name` or `index_path`.")
277
+ self.dataset_name = dataset_name
278
+ self.dataset_split = dataset_split
279
+ self.index_name = index_name
280
+ self.index_path = index_path
281
+ self.use_dummy_dataset = use_dummy_dataset
282
+ self.dataset_revision = dataset_revision
283
+ logger.info(f"Loading passages from {self.dataset_name}")
284
+ dataset = load_dataset(
285
+ self.dataset_name,
286
+ with_index=False,
287
+ split=self.dataset_split,
288
+ dummy=self.use_dummy_dataset,
289
+ revision=dataset_revision,
290
+ )
291
+ super().__init__(vector_size, dataset, index_initialized=False)
292
+
293
+ def init_index(self):
294
+ if self.index_path is not None:
295
+ logger.info(f"Loading index from {self.index_path}")
296
+ self.dataset.load_faiss_index("embeddings", file=self.index_path)
297
+ else:
298
+ logger.info(f"Loading index from {self.dataset_name} with index name {self.index_name}")
299
+ self.dataset = load_dataset(
300
+ self.dataset_name,
301
+ with_embeddings=True,
302
+ with_index=True,
303
+ split=self.dataset_split,
304
+ index_name=self.index_name,
305
+ dummy=self.use_dummy_dataset,
306
+ revision=self.dataset_revision,
307
+ )
308
+ self.dataset.set_format("numpy", columns=["embeddings"], output_all_columns=True)
309
+ self._index_initialized = True
310
+
311
+
312
+ class CustomHFIndex(HFIndexBase):
313
+ """
314
+ A wrapper around an instance of [`~datasets.Datasets`]. The dataset and the index are both loaded from the
315
+ indicated paths on disk.
316
+
317
+ Args:
318
+ vector_size (`int`): the dimension of the passages embeddings used by the index
319
+ dataset_path (`str`):
320
+ The path to the serialized dataset on disk. The dataset should have 3 columns: title (str), text (str) and
321
+ embeddings (arrays of dimension vector_size)
322
+ index_path (`str`)
323
+ The path to the serialized faiss index on disk.
324
+ """
325
+
326
+ def __init__(self, vector_size: int, dataset, index_path=None):
327
+ requires_backends(self, ["faiss"])
328
+ super().__init__(vector_size, dataset, index_initialized=index_path is None)
329
+ self.index_path = index_path
330
+
331
+ @classmethod
332
+ def load_from_disk(cls, vector_size, dataset_path, index_path):
333
+ logger.info(f"Loading passages from {dataset_path}")
334
+ if dataset_path is None or index_path is None:
335
+ raise ValueError(
336
+ "Please provide `dataset_path` and `index_path` after calling `dataset.save_to_disk(dataset_path)` "
337
+ "and `dataset.get_index('embeddings').save(index_path)`."
338
+ )
339
+ dataset = load_from_disk(dataset_path)
340
+ return cls(vector_size=vector_size, dataset=dataset, index_path=index_path)
341
+
342
+ def init_index(self):
343
+ if not self.is_initialized():
344
+ logger.info(f"Loading index from {self.index_path}")
345
+ self.dataset.load_faiss_index("embeddings", file=self.index_path)
346
+ self._index_initialized = True
347
+
348
+
349
+ class RagRetriever:
350
+ """
351
+ Retriever used to get documents from vector queries. It retrieves the documents embeddings as well as the documents
352
+ contents, and it formats them to be used with a RagModel.
353
+
354
+ Args:
355
+ config ([`RagConfig`]):
356
+ The configuration of the RAG model this Retriever is used with. Contains parameters indicating which
357
+ `Index` to build. You can load your own custom dataset with `config.index_name="custom"` or use a canonical
358
+ one (default) from the datasets library with `config.index_name="wiki_dpr"` for example.
359
+ question_encoder_tokenizer ([`PreTrainedTokenizer`]):
360
+ The tokenizer that was used to tokenize the question. It is used to decode the question and then use the
361
+ generator_tokenizer.
362
+ generator_tokenizer ([`PreTrainedTokenizer`]):
363
+ The tokenizer used for the generator part of the RagModel.
364
+ index ([`~models.rag.retrieval_rag.Index`], optional, defaults to the one defined by the configuration):
365
+ If specified, use this index instead of the one built using the configuration
366
+
367
+ Examples:
368
+
369
+ ```python
370
+ >>> # To load the default "wiki_dpr" dataset with 21M passages from wikipedia (index name is 'compressed' or 'exact')
371
+ >>> from transformers import RagRetriever
372
+
373
+ >>> retriever = RagRetriever.from_pretrained(
374
+ ... "facebook/dpr-ctx_encoder-single-nq-base", dataset="wiki_dpr", index_name="compressed"
375
+ ... )
376
+
377
+ >>> # To load your own indexed dataset built with the datasets library. More info on how to build the indexed dataset in examples/rag/use_own_knowledge_dataset.py
378
+ >>> from transformers import RagRetriever
379
+
380
+ >>> dataset = (
381
+ ... ...
382
+ ... ) # dataset must be a datasets.Datasets object with columns "title", "text" and "embeddings", and it must have a supported index (e.g., Faiss or other index types depending on your setup)
383
+ >>> retriever = RagRetriever.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base", indexed_dataset=dataset)
384
+
385
+ >>> # To load your own indexed dataset built with the datasets library that was saved on disk. More info in examples/rag/use_own_knowledge_dataset.py
386
+ >>> from transformers import RagRetriever
387
+
388
+ >>> dataset_path = "path/to/my/dataset" # dataset saved via *dataset.save_to_disk(...)*
389
+ >>> index_path = "path/to/my/index" # index saved via *dataset.get_index("embeddings").save(...)*
390
+ >>> retriever = RagRetriever.from_pretrained(
391
+ ... "facebook/dpr-ctx_encoder-single-nq-base",
392
+ ... index_name="custom",
393
+ ... passages_path=dataset_path,
394
+ ... index_path=index_path,
395
+ ... )
396
+
397
+ >>> # To load the legacy index built originally for Rag's paper
398
+ >>> from transformers import RagRetriever
399
+
400
+ >>> retriever = RagRetriever.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base", index_name="legacy")
401
+ ```"""
402
+
403
+ def __init__(self, config, question_encoder_tokenizer, generator_tokenizer, index=None, init_retrieval=True):
404
+ self._init_retrieval = init_retrieval
405
+ requires_backends(self, ["datasets"])
406
+ super().__init__()
407
+ self.index = index or self._build_index(config)
408
+ self.generator_tokenizer = generator_tokenizer
409
+ self.question_encoder_tokenizer = question_encoder_tokenizer
410
+
411
+ self.n_docs = config.n_docs
412
+ self.batch_size = config.retrieval_batch_size
413
+
414
+ self.config = config
415
+ if self._init_retrieval:
416
+ self.init_retrieval()
417
+
418
+ self.ctx_encoder_tokenizer = None
419
+ self.return_tokenized_docs = False
420
+
421
+ @staticmethod
422
+ def _build_index(config):
423
+ if config.index_name == "legacy":
424
+ return LegacyIndex(
425
+ config.retrieval_vector_size,
426
+ config.index_path or LEGACY_INDEX_PATH,
427
+ )
428
+ elif config.index_name == "custom":
429
+ return CustomHFIndex.load_from_disk(
430
+ vector_size=config.retrieval_vector_size,
431
+ dataset_path=config.passages_path,
432
+ index_path=config.index_path,
433
+ )
434
+ else:
435
+ return CanonicalHFIndex(
436
+ vector_size=config.retrieval_vector_size,
437
+ dataset_name=config.dataset,
438
+ dataset_split=config.dataset_split,
439
+ index_name=config.index_name,
440
+ index_path=config.index_path,
441
+ use_dummy_dataset=config.use_dummy_dataset,
442
+ dataset_revision=config.dataset_revision,
443
+ )
444
+
445
+ @classmethod
446
+ def from_pretrained(cls, retriever_name_or_path, indexed_dataset=None, **kwargs):
447
+ requires_backends(cls, ["datasets"])
448
+ config = kwargs.pop("config", None) or RagConfig.from_pretrained(retriever_name_or_path, **kwargs)
449
+ rag_tokenizer = RagTokenizer.from_pretrained(retriever_name_or_path, config=config)
450
+ question_encoder_tokenizer = rag_tokenizer.question_encoder
451
+ generator_tokenizer = rag_tokenizer.generator
452
+ if indexed_dataset is not None:
453
+ config.index_name = "custom"
454
+ index = CustomHFIndex(config.retrieval_vector_size, indexed_dataset)
455
+ else:
456
+ index = cls._build_index(config)
457
+ return cls(
458
+ config,
459
+ question_encoder_tokenizer=question_encoder_tokenizer,
460
+ generator_tokenizer=generator_tokenizer,
461
+ index=index,
462
+ )
463
+
464
+ def save_pretrained(self, save_directory):
465
+ if isinstance(self.index, CustomHFIndex):
466
+ if self.config.index_path is None:
467
+ index_path = os.path.join(save_directory, "hf_dataset_index.faiss")
468
+ self.index.dataset.get_index("embeddings").save(index_path)
469
+ self.config.index_path = index_path
470
+ if self.config.passages_path is None:
471
+ passages_path = os.path.join(save_directory, "hf_dataset")
472
+ # datasets don't support save_to_disk with indexes right now
473
+ faiss_index = self.index.dataset._indexes.pop("embeddings")
474
+ self.index.dataset.save_to_disk(passages_path)
475
+ self.index.dataset._indexes["embeddings"] = faiss_index
476
+ self.config.passages_path = passages_path
477
+ self.config.save_pretrained(save_directory)
478
+ rag_tokenizer = RagTokenizer(
479
+ question_encoder=self.question_encoder_tokenizer,
480
+ generator=self.generator_tokenizer,
481
+ )
482
+ rag_tokenizer.save_pretrained(save_directory)
483
+
484
+ def init_retrieval(self):
485
+ """
486
+ Retriever initialization function. It loads the index into memory.
487
+ """
488
+
489
+ logger.info("initializing retrieval")
490
+ self.index.init_index()
491
+
492
+ def postprocess_docs(self, docs, input_strings, prefix, n_docs, return_tensors=None):
493
+ r"""
494
+ Postprocessing retrieved `docs` and combining them with `input_strings`.
495
+
496
+ Args:
497
+ docs (`dict`):
498
+ Retrieved documents.
499
+ input_strings (`str`):
500
+ Input strings decoded by `preprocess_query`.
501
+ prefix (`str`):
502
+ Prefix added at the beginning of each input, typically used with T5-based models.
503
+
504
+ Return:
505
+ `tuple(tensors)`: a tuple consisting of two elements: contextualized `input_ids` and a compatible
506
+ `attention_mask`.
507
+ """
508
+
509
+ def cat_input_and_doc(doc_title, doc_text, input_string, prefix):
510
+ # TODO(Patrick): if we train more RAG models, I want to put the input first to take advantage of effortless truncation
511
+ # TODO(piktus): better handling of truncation
512
+ if doc_title.startswith('"'):
513
+ doc_title = doc_title[1:]
514
+ if doc_title.endswith('"'):
515
+ doc_title = doc_title[:-1]
516
+ if prefix is None:
517
+ prefix = ""
518
+ out = (prefix + doc_title + self.config.title_sep + doc_text + self.config.doc_sep + input_string).replace(
519
+ " ", " "
520
+ )
521
+ return out
522
+
523
+ rag_input_strings = [
524
+ cat_input_and_doc(
525
+ docs[i]["title"][j],
526
+ docs[i]["text"][j],
527
+ input_strings[i],
528
+ prefix,
529
+ )
530
+ for i in range(len(docs))
531
+ for j in range(n_docs)
532
+ ]
533
+
534
+ contextualized_inputs = self.generator_tokenizer.batch_encode_plus(
535
+ rag_input_strings,
536
+ max_length=self.config.max_combined_length,
537
+ return_tensors=return_tensors,
538
+ padding="max_length",
539
+ truncation=True,
540
+ )
541
+
542
+ return contextualized_inputs["input_ids"], contextualized_inputs["attention_mask"]
543
+
544
+ def _chunk_tensor(self, t: Iterable, chunk_size: int) -> list[Iterable]:
545
+ return [t[i : i + chunk_size] for i in range(0, len(t), chunk_size)]
546
+
547
+ def _main_retrieve(self, question_hidden_states: np.ndarray, n_docs: int) -> tuple[np.ndarray, np.ndarray]:
548
+ question_hidden_states_batched = self._chunk_tensor(question_hidden_states, self.batch_size)
549
+ ids_batched = []
550
+ vectors_batched = []
551
+ for question_hidden_states in question_hidden_states_batched:
552
+ start_time = time.time()
553
+ ids, vectors = self.index.get_top_docs(question_hidden_states, n_docs)
554
+ logger.debug(
555
+ f"index search time: {time.time() - start_time} sec, batch size {question_hidden_states.shape}"
556
+ )
557
+ ids_batched.extend(ids)
558
+ vectors_batched.extend(vectors)
559
+ return (
560
+ np.array(ids_batched),
561
+ np.array(vectors_batched),
562
+ ) # shapes (batch_size, n_docs) and (batch_size, n_docs, d)
563
+
564
+ def retrieve(self, question_hidden_states: np.ndarray, n_docs: int) -> tuple[np.ndarray, np.ndarray, list[dict]]:
565
+ """
566
+ Retrieves documents for specified `question_hidden_states`.
567
+
568
+ Args:
569
+ question_hidden_states (`np.ndarray` of shape `(batch_size, vector_size)`):
570
+ A batch of query vectors to retrieve with.
571
+ n_docs (`int`):
572
+ The number of docs retrieved per query.
573
+
574
+ Return:
575
+ `tuple[np.ndarray, np.ndarray, list[dict]]`: A tuple with the following objects:
576
+
577
+ - **retrieved_doc_embeds** (`np.ndarray` of shape `(batch_size, n_docs, dim)`) -- The retrieval embeddings
578
+ of the retrieved docs per query.
579
+ - **doc_ids** (`np.ndarray` of shape `(batch_size, n_docs)`) -- The ids of the documents in the index
580
+ - **doc_dicts** (`list[dict]`): The `retrieved_doc_embeds` examples per query.
581
+ """
582
+
583
+ doc_ids, retrieved_doc_embeds = self._main_retrieve(question_hidden_states, n_docs)
584
+ return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(doc_ids)
585
+
586
+ def set_ctx_encoder_tokenizer(self, ctx_encoder_tokenizer: PreTrainedTokenizer):
587
+ # used in end2end retriever training
588
+ self.ctx_encoder_tokenizer = ctx_encoder_tokenizer
589
+ self.return_tokenized_docs = True
590
+
591
+ def __call__(
592
+ self,
593
+ question_input_ids: list[list[int]],
594
+ question_hidden_states: np.ndarray,
595
+ prefix=None,
596
+ n_docs=None,
597
+ return_tensors=None,
598
+ ) -> BatchEncoding:
599
+ """
600
+ Retrieves documents for specified `question_hidden_states`.
601
+
602
+ Args:
603
+ question_input_ids (`list[list[int]]`) batch of input ids
604
+ question_hidden_states (`np.ndarray` of shape `(batch_size, vector_size)`:
605
+ A batch of query vectors to retrieve with.
606
+ prefix (`str`, *optional*):
607
+ The prefix used by the generator's tokenizer.
608
+ n_docs (`int`, *optional*):
609
+ The number of docs retrieved per query.
610
+ return_tensors (`str` or [`~utils.TensorType`], *optional*, defaults to "pt"):
611
+ If set, will return tensors instead of list of python integers. Acceptable values are:
612
+
613
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
614
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
615
+ - `'np'`: Return Numpy `np.ndarray` objects.
616
+
617
+ Returns: [`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
618
+
619
+ - **context_input_ids** -- List of token ids to be fed to a model.
620
+
621
+ [What are input IDs?](../glossary#input-ids)
622
+
623
+ - **context_attention_mask** -- List of indices specifying which tokens should be attended to by the model
624
+ (when `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names`).
625
+
626
+ [What are attention masks?](../glossary#attention-mask)
627
+
628
+ - **retrieved_doc_embeds** -- List of embeddings of the retrieved documents
629
+ - **doc_ids** -- List of ids of the retrieved documents
630
+ """
631
+
632
+ n_docs = n_docs if n_docs is not None else self.n_docs
633
+ prefix = prefix if prefix is not None else self.config.generator.prefix
634
+ retrieved_doc_embeds, doc_ids, docs = self.retrieve(question_hidden_states, n_docs)
635
+
636
+ input_strings = self.question_encoder_tokenizer.batch_decode(question_input_ids, skip_special_tokens=True)
637
+ context_input_ids, context_attention_mask = self.postprocess_docs(
638
+ docs, input_strings, prefix, n_docs, return_tensors=return_tensors
639
+ )
640
+
641
+ if self.return_tokenized_docs:
642
+ retrieved_doc_text = []
643
+ retrieved_doc_title = []
644
+
645
+ for b_idx in range(len(docs)):
646
+ for doc_idx in range(n_docs):
647
+ retrieved_doc_text.append(docs[b_idx]["text"][doc_idx])
648
+ retrieved_doc_title.append(docs[b_idx]["title"][doc_idx])
649
+
650
+ tokenized_docs = self.ctx_encoder_tokenizer(
651
+ retrieved_doc_title,
652
+ retrieved_doc_text,
653
+ truncation=True,
654
+ padding="longest",
655
+ return_tensors=return_tensors,
656
+ )
657
+
658
+ return BatchEncoding(
659
+ {
660
+ "context_input_ids": context_input_ids,
661
+ "context_attention_mask": context_attention_mask,
662
+ "retrieved_doc_embeds": retrieved_doc_embeds,
663
+ "doc_ids": doc_ids,
664
+ "tokenized_doc_ids": tokenized_docs["input_ids"],
665
+ "tokenized_doc_attention_mask": tokenized_docs["attention_mask"],
666
+ },
667
+ tensor_type=return_tensors,
668
+ )
669
+
670
+ else:
671
+ return BatchEncoding(
672
+ {
673
+ "context_input_ids": context_input_ids,
674
+ "context_attention_mask": context_attention_mask,
675
+ "retrieved_doc_embeds": retrieved_doc_embeds,
676
+ "doc_ids": doc_ids,
677
+ },
678
+ tensor_type=return_tensors,
679
+ )
680
+
681
+
682
+ __all__ = ["RagRetriever"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/rag/tokenization_rag.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020, The RAG Authors and The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Tokenization classes for RAG."""
16
+
17
+ import os
18
+ import warnings
19
+ from typing import Optional
20
+
21
+ from ...tokenization_utils_base import BatchEncoding
22
+ from ...utils import logging
23
+ from .configuration_rag import RagConfig
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+
29
+ class RagTokenizer:
30
+ def __init__(self, question_encoder, generator):
31
+ self.question_encoder = question_encoder
32
+ self.generator = generator
33
+ self.current_tokenizer = self.question_encoder
34
+
35
+ def save_pretrained(self, save_directory):
36
+ if os.path.isfile(save_directory):
37
+ raise ValueError(f"Provided path ({save_directory}) should be a directory, not a file")
38
+ os.makedirs(save_directory, exist_ok=True)
39
+ question_encoder_path = os.path.join(save_directory, "question_encoder_tokenizer")
40
+ generator_path = os.path.join(save_directory, "generator_tokenizer")
41
+ self.question_encoder.save_pretrained(question_encoder_path)
42
+ self.generator.save_pretrained(generator_path)
43
+
44
+ @classmethod
45
+ def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
46
+ # dynamically import AutoTokenizer
47
+ from ..auto.tokenization_auto import AutoTokenizer
48
+
49
+ config = kwargs.pop("config", None)
50
+
51
+ if config is None:
52
+ config = RagConfig.from_pretrained(pretrained_model_name_or_path)
53
+
54
+ question_encoder = AutoTokenizer.from_pretrained(
55
+ pretrained_model_name_or_path, config=config.question_encoder, subfolder="question_encoder_tokenizer"
56
+ )
57
+ generator = AutoTokenizer.from_pretrained(
58
+ pretrained_model_name_or_path, config=config.generator, subfolder="generator_tokenizer"
59
+ )
60
+ return cls(question_encoder=question_encoder, generator=generator)
61
+
62
+ def __call__(self, *args, **kwargs):
63
+ return self.current_tokenizer(*args, **kwargs)
64
+
65
+ def batch_decode(self, *args, **kwargs):
66
+ return self.generator.batch_decode(*args, **kwargs)
67
+
68
+ def decode(self, *args, **kwargs):
69
+ return self.generator.decode(*args, **kwargs)
70
+
71
+ def _switch_to_input_mode(self):
72
+ self.current_tokenizer = self.question_encoder
73
+
74
+ def _switch_to_target_mode(self):
75
+ self.current_tokenizer = self.generator
76
+
77
+ def prepare_seq2seq_batch(
78
+ self,
79
+ src_texts: list[str],
80
+ tgt_texts: Optional[list[str]] = None,
81
+ max_length: Optional[int] = None,
82
+ max_target_length: Optional[int] = None,
83
+ padding: str = "longest",
84
+ return_tensors: Optional[str] = None,
85
+ truncation: bool = True,
86
+ **kwargs,
87
+ ) -> BatchEncoding:
88
+ warnings.warn(
89
+ "`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the "
90
+ "regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` "
91
+ "context manager to prepare your targets. See the documentation of your specific tokenizer for more "
92
+ "details",
93
+ FutureWarning,
94
+ )
95
+ if max_length is None:
96
+ max_length = self.current_tokenizer.model_max_length
97
+ model_inputs = self(
98
+ src_texts,
99
+ add_special_tokens=True,
100
+ return_tensors=return_tensors,
101
+ max_length=max_length,
102
+ padding=padding,
103
+ truncation=truncation,
104
+ **kwargs,
105
+ )
106
+ if tgt_texts is None:
107
+ return model_inputs
108
+ # Process tgt_texts
109
+ if max_target_length is None:
110
+ max_target_length = self.current_tokenizer.model_max_length
111
+ labels = self(
112
+ text_target=tgt_texts,
113
+ add_special_tokens=True,
114
+ return_tensors=return_tensors,
115
+ padding=padding,
116
+ max_length=max_target_length,
117
+ truncation=truncation,
118
+ **kwargs,
119
+ )
120
+ model_inputs["labels"] = labels["input_ids"]
121
+ return model_inputs
122
+
123
+
124
+ __all__ = ["RagTokenizer"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/recurrent_gemma/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_recurrent_gemma import *
22
+ from .modeling_recurrent_gemma import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/recurrent_gemma/configuration_recurrent_gemma.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Google Inc. HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """RecurrentGemma model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class RecurrentGemmaConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`RecurrentGemmaModel`]. It is used to instantiate a RecurrentGemma
27
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
28
+ defaults will yield a similar configuration to that of the RecurrentGemma-7B.
29
+
30
+ e.g. [google/recurrentgemma-2b](https://huggingface.co/google/recurrentgemma-2b)
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+
36
+ Args:
37
+ num_hidden_layers (`int`, *optional*, defaults to 26):
38
+ The number of hidden layers in the model.
39
+ vocab_size (`int`, *optional*, defaults to 256000):
40
+ Vocabulary size of the RecurrentGemma model. Defines the number of
41
+ different tokens that can be represented by the
42
+ `inputs_ids` passed when calling [`RecurrentGemmaModel`]
43
+ hidden_size (`int`, *optional*, defaults to 2560):
44
+ Dimension of the hidden representations.
45
+ intermediate_size (`int`, *optional*, defaults to 7680):
46
+ Dimension of the MLP representations.
47
+ num_attention_heads (`int`, *optional*, defaults to 10):
48
+ The number of heads for the attention block and the number of
49
+ heads/blocks for the block-diagonal layers used in the RG-LRU gates.
50
+ This number must divide `hidden_size` and `lru_width`.
51
+ lru_width (`int` or `None`, *optional*):
52
+ Dimension of the hidden representations of the RG-LRU. If `None`
53
+ this will be set to `hidden_size`.
54
+ Whether to scale the output of the embeddings by `sqrt(hidden_size)`.
55
+ attention_window_size (`int`, *optional*, defaults to 2048):
56
+ The size of the attention window used in the attention block.
57
+ conv1d_width (`int`, *optional*, defaults to 4):
58
+ The kernel size of conv1d layers used in the recurrent blocks.
59
+ logits_soft_cap (`float`, *optional*, defaults to 30.0):
60
+ The value at which the logits should be soft-capped to after the transformer and LM-head computation in the Causal LM architecture.
61
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
62
+ The epsilon used by the rms normalization layers.
63
+ use_cache (`bool`, *optional*, defaults to `True`):
64
+ Whether the model should return the last key/values
65
+ attentions (not used by all models). Only
66
+ relevant if `config.is_decoder=True`.
67
+ pad_token_id (`int`, *optional*, defaults to 0):
68
+ Padding token id.
69
+ eos_token_id (`int`, *optional*, defaults to 1):
70
+ End of stream token id.
71
+ bos_token_id (`int`, *optional*, defaults to 2):
72
+ Beginning of stream token id.
73
+ hidden_activation (``str` or `function``, *optional*, defaults to `"gelu_pytorch_tanh"`):
74
+ The hidden activation used in the recurrent block as well as the MLP layer of the decoder layers.
75
+ partial_rotary_factor (`float`, *optional*, defaults to 0.5):
76
+ The partial rotary factor used in the initialization of the rotary embeddings.
77
+ rope_theta (`float`, *optional*, defaults to 10000.0):
78
+ The base period of the RoPE embeddings.
79
+ block_types (`list[str]`, *optional*, defaults to `('recurrent', 'recurrent', 'attention')`):
80
+ List of aleternating blocks that will be repeated to initialize the `temporal_block` layer.
81
+ attention_dropout (`float`, *optional*, defaults to 0.0): dropout value to use after the attention softmax.
82
+ num_key_value_heads (`16`, *optional*, defaults to 16): Number of key value heads to use GQA.
83
+ attention_bias (`bool`, *optional*, defaults to `False`): whether or not the linear q,k,v of the Attention layer should have bias
84
+ w_init_variance_scale (`float`, *optional*, defaults to 0.01): weight initialization variance.
85
+ ```python
86
+ >>> from transformers import RecurrentGemmaModel, RecurrentGemmaConfig
87
+
88
+ >>> # Initializing a RecurrentGemma recurrentgemma-2b style configuration
89
+ >>> configuration = RecurrentGemmaConfig()
90
+
91
+ >>> # Initializing a model from the recurrentgemma-2b style configuration
92
+ >>> model = RecurrentGemmaModel(configuration)
93
+
94
+ >>> # Accessing the model configuration
95
+ >>> configuration = model.config
96
+ ```"""
97
+
98
+ model_type = "recurrent_gemma"
99
+
100
+ def __init__(
101
+ self,
102
+ num_hidden_layers=26,
103
+ vocab_size=256000,
104
+ hidden_size=2560,
105
+ intermediate_size=3 * 2560,
106
+ num_attention_heads=10,
107
+ lru_width=None,
108
+ attention_window_size=2048,
109
+ conv1d_width=4,
110
+ logits_soft_cap=30.0,
111
+ rms_norm_eps=1e-6,
112
+ use_cache=True,
113
+ pad_token_id=0,
114
+ eos_token_id=1,
115
+ bos_token_id=2,
116
+ hidden_activation="gelu_pytorch_tanh",
117
+ partial_rotary_factor=0.5,
118
+ rope_theta=10000.0,
119
+ block_types=("recurrent", "recurrent", "attention"),
120
+ attention_dropout=0.0,
121
+ num_key_value_heads=None,
122
+ attention_bias=False,
123
+ w_init_variance_scale=0.01,
124
+ **kwargs,
125
+ ):
126
+ self.num_hidden_layers = num_hidden_layers
127
+ self.vocab_size = vocab_size
128
+ self.hidden_size = hidden_size
129
+ self.intermediate_size = intermediate_size
130
+ self.num_attention_heads = num_attention_heads
131
+ self.lru_width = lru_width if lru_width is not None else hidden_size
132
+ self.attention_window_size = attention_window_size
133
+ self.conv1d_width = conv1d_width
134
+ self.logits_soft_cap = logits_soft_cap
135
+ self.rms_norm_eps = rms_norm_eps
136
+ self.use_cache = use_cache
137
+ self.rope_theta = rope_theta
138
+ self.partial_rotary_factor = partial_rotary_factor
139
+ self.block_types = list(block_types)
140
+ self.hidden_activation = hidden_activation
141
+ self.head_dim = self.hidden_size // self.num_attention_heads
142
+ self.num_key_value_heads = num_key_value_heads if num_key_value_heads is not None else num_attention_heads
143
+ if self.num_key_value_heads > self.num_attention_heads:
144
+ raise ValueError("The number of `num_key_value_heads` must be smaller than `num_attention_heads`")
145
+ self.attention_dropout = attention_dropout
146
+ self.attention_bias = attention_bias
147
+ self.w_init_variance_scale = w_init_variance_scale
148
+ self.final_w_init_variance_scale = 2.0 / self.num_hidden_layers
149
+ super().__init__(
150
+ pad_token_id=pad_token_id,
151
+ bos_token_id=bos_token_id,
152
+ eos_token_id=eos_token_id,
153
+ **kwargs,
154
+ )
155
+
156
+ @property
157
+ def layers_block_type(self):
158
+ return (self.block_types * 100)[: self.num_hidden_layers]
159
+
160
+
161
+ __all__ = ["RecurrentGemmaConfig"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/recurrent_gemma/convert_recurrent_gemma_to_hf.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import argparse
15
+ import os
16
+ import warnings
17
+
18
+ import torch
19
+ from accelerate import init_empty_weights
20
+
21
+ from transformers import GemmaTokenizer, RecurrentGemmaConfig, RecurrentGemmaForCausalLM
22
+
23
+
24
+ try:
25
+ from transformers import GemmaTokenizerFast
26
+ except ImportError as e:
27
+ warnings.warn(e)
28
+ warnings.warn(
29
+ "The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion"
30
+ )
31
+ GemmaTokenizerFast = None
32
+
33
+ import regex as re
34
+
35
+
36
+ """
37
+ Sample usage:
38
+
39
+ ```
40
+ python src/transformers/models/gemma/convert_gemma_weights_to_hf.py \
41
+ --input_dir /path/to/downloaded/gemma/weights --model_size 7B --output_dir /output/path
42
+ ```
43
+
44
+ Thereafter, models can be loaded via:
45
+
46
+ ```py
47
+ from transformers import GemmaForCausalLM, GemmaTokenizerFast
48
+
49
+ model = GemmaForCausalLM.from_pretrained("/output/path")
50
+ tokenizer = GemmaTokenizerFast.from_pretrained("/output/path")
51
+ ```
52
+
53
+ Important note: you need to be able to host the whole model in RAM to execute this script (even if the biggest versions
54
+ come in several checkpoints they each contain a part of each weight of the model, so we need to load them all in RAM).
55
+ """
56
+
57
+ gemma_2b_config = RecurrentGemmaConfig(
58
+ num_attention_heads=10,
59
+ num_key_value_heads=1,
60
+ hidden_size=2560,
61
+ intermediate_size=15360,
62
+ vocab_size=256000,
63
+ num_hidden_layers=26,
64
+ )
65
+
66
+ gemma_7b_config = RecurrentGemmaConfig()
67
+
68
+ CONFIG_MAPPING = {"2B": gemma_2b_config, "7B": gemma_7b_config}
69
+ LAYER_NAME_MAPPING = {"embedder.weight": "model.embed_tokens.weight"}
70
+
71
+
72
+ def write_model(save_path, input_base_path, config, safe_serialization=True, push_to_hub=False, dtype=torch.float32):
73
+ print(f"Fetching all parameters from the checkpoint at '{input_base_path}'")
74
+ model_state_dict = torch.load(input_base_path, map_location="cpu", weights_only=True)
75
+
76
+ REPLACEMENT = {
77
+ "blocks.": "layers.",
78
+ ".ffw_down.b": ".down_proj.b",
79
+ ".ffw_down.w": ".down_proj.w",
80
+ ".ffw_up.b": ".up_proj.bias",
81
+ ".ffw_up.w": ".up_proj.weight",
82
+ "recurrent_block": "temporal_block",
83
+ "attention_block": "temporal_block",
84
+ "temporal_block.proj_final": "temporal_block.out_proj",
85
+ "norm.scale": "norm.weight",
86
+ ".proj_k": ".k_proj",
87
+ ".proj_q": ".q_proj",
88
+ ".proj_v": ".v_proj",
89
+ ".proj_final": ".o_proj",
90
+ "embedder.input_embedding": "embed_tokens.weight",
91
+ "conv_1d.w": "conv_1d.weight",
92
+ "conv_1d.b": "conv_1d.bias",
93
+ "input_gate.w": "input_gate.weight",
94
+ "input_gate.b": "input_gate.bias",
95
+ "a_param": "recurrent_param",
96
+ "a_gate.b": "recurrent_gate.bias",
97
+ "a_gate.w": "recurrent_gate.weight",
98
+ }
99
+
100
+ state_dict = {}
101
+ for k, v in model_state_dict.items():
102
+ k = "model." + k
103
+ pattern = re.compile("|".join(map(re.escape, REPLACEMENT.keys())))
104
+ key = pattern.sub(lambda match: REPLACEMENT[match.group(0)], k)
105
+ if "conv_1d.weight" in key:
106
+ v = v[:, None, :].transpose(0, 2)
107
+ if "up_proj.weight" in key:
108
+ state_dict[key.replace("up_proj", "gate_proj")] = v[0].T.contiguous()
109
+ v = v[1].T.contiguous()
110
+ if "up_proj.bias" in key:
111
+ state_dict[key.replace("up_proj", "gate_proj")] = v[0, 0, 0].clone()
112
+ v = v[1, 0, 0].contiguous()
113
+ if "recurrent_gate.bias" in key:
114
+ state_dict[key.replace("gate.", "gate_")] = v.contiguous().clone()
115
+ elif "recurrent_gate.weight" in key:
116
+ state_dict[key.replace("gate.", "gate_")] = v.contiguous().clone()
117
+ elif "input_gate.b" in key:
118
+ state_dict[key.replace("gate.", "gate_")] = v.contiguous().clone()
119
+ elif "input_gate.w" in key:
120
+ state_dict[key.replace("gate.", "gate_")] = v.contiguous().clone()
121
+ elif "embed_tokens" in key:
122
+ state_dict[key] = v[: config.vocab_size, :].contiguous().clone()
123
+ state_dict["lm_head.weight"] = v[: config.vocab_size, :].contiguous().clone()
124
+ else:
125
+ state_dict[key] = v.contiguous()
126
+
127
+ torch.set_default_dtype(dtype)
128
+
129
+ print("Loading the checkpoint in a Gemma model.")
130
+ with init_empty_weights():
131
+ model = RecurrentGemmaForCausalLM(config)
132
+ model.load_state_dict(state_dict, assign=True, strict=True)
133
+
134
+ model.config.torch_dtype = torch.float32
135
+ del model.config._name_or_path
136
+ print("Saving in the Transformers format.")
137
+
138
+ if push_to_hub:
139
+ print(f"pushing the model to {save_path}")
140
+ else:
141
+ model.save_pretrained(save_path, safe_serialization=safe_serialization)
142
+
143
+
144
+ def write_tokenizer(input_tokenizer_path, save_path, push_to_hub=False):
145
+ # Initialize the tokenizer based on the `spm` model
146
+ tokenizer_class = GemmaTokenizer if GemmaTokenizerFast is None else GemmaTokenizerFast
147
+ print(f"Saving a {tokenizer_class.__name__} to {save_path}.")
148
+ tokenizer = tokenizer_class(input_tokenizer_path)
149
+ if push_to_hub:
150
+ tokenizer.push_to_hub(save_path)
151
+ else:
152
+ tokenizer.save_pretrained(save_path)
153
+
154
+
155
+ def main():
156
+ parser = argparse.ArgumentParser()
157
+ parser.add_argument(
158
+ "--input_checkpoint",
159
+ help="Absolute path to the target Gemma weights.",
160
+ default="/home/arthur/transformers_recurrentgemma/google/recurrent-gemma-2b-it/ToBeDeleted/2b-it.pt",
161
+ )
162
+ parser.add_argument(
163
+ "--tokenizer_checkpoint",
164
+ help="Location of Gemma tokenizer model",
165
+ )
166
+ parser.add_argument(
167
+ "--model_size",
168
+ default="2B",
169
+ choices=["2B", "7B", "tokenizer_only"],
170
+ help="'f' models correspond to the finetuned versions, and are specific to the Gemma2 official release. For more details on Gemma2, check out the original repo: https://huggingface.co/google/gemma-7b",
171
+ )
172
+ parser.add_argument(
173
+ "--output_dir",
174
+ default="google/recurrent-gemma-2b-it-hf",
175
+ help="Location to write HF model and tokenizer",
176
+ )
177
+ parser.add_argument(
178
+ "--pickle_serialization",
179
+ help="Whether or not to save using `safetensors`.",
180
+ action="store_true",
181
+ default=False,
182
+ )
183
+ parser.add_argument(
184
+ "--convert_tokenizer",
185
+ help="Whether or not to convert the tokenizer as well.",
186
+ action="store_true",
187
+ default=False,
188
+ )
189
+ parser.add_argument(
190
+ "--push_to_hub",
191
+ help="Whether or not to push the model to the hub at `output_dir` instead of saving it locally.",
192
+ action="store_true",
193
+ default=False,
194
+ )
195
+ parser.add_argument(
196
+ "--dtype",
197
+ default="float32",
198
+ help="Target dtype of the converted model",
199
+ )
200
+ args = parser.parse_args()
201
+
202
+ if args.convert_tokenizer:
203
+ if args.tokenizer_checkpoint is None:
204
+ raise ValueError("Path to the tokenizer is required when passing --convert_tokenizer")
205
+
206
+ spm_path = os.path.join(args.tokenizer_checkpoint)
207
+ write_tokenizer(spm_path, args.output_dir, args.push_to_hub)
208
+
209
+ config = CONFIG_MAPPING[args.model_size]
210
+ dtype = getattr(torch, args.dtype)
211
+ write_model(
212
+ config=config,
213
+ input_base_path=args.input_checkpoint,
214
+ save_path=args.output_dir,
215
+ safe_serialization=not args.pickle_serialization,
216
+ push_to_hub=args.push_to_hub,
217
+ dtype=dtype,
218
+ )
219
+
220
+
221
+ if __name__ == "__main__":
222
+ main()
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/recurrent_gemma/modeling_recurrent_gemma.py ADDED
@@ -0,0 +1,791 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Google Inc. HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """PyTorch RecurrentGemma model."""
17
+
18
+ import math
19
+ from typing import Optional, Union
20
+
21
+ import torch
22
+ import torch.utils.checkpoint
23
+ from torch import nn
24
+
25
+ from ...activations import ACT2FN
26
+ from ...generation import GenerationMixin
27
+ from ...modeling_attn_mask_utils import AttentionMaskConverter
28
+ from ...modeling_layers import GradientCheckpointingLayer
29
+ from ...modeling_outputs import BaseModelOutputWithNoAttention, CausalLMOutput
30
+ from ...modeling_utils import PreTrainedModel
31
+ from ...utils import auto_docstring, logging
32
+ from ...utils.import_utils import is_torchdynamo_compiling
33
+ from .configuration_recurrent_gemma import RecurrentGemmaConfig
34
+
35
+
36
+ logger = logging.get_logger(__name__)
37
+ _MAX_SQRT_GRADIENT = 1000.0
38
+
39
+
40
+ # Copied from transformers.models.gemma.modeling_gemma.GemmaRMSNorm with Gemma->RecurrentGemma
41
+ class RecurrentGemmaRMSNorm(nn.Module):
42
+ def __init__(self, dim: int, eps: float = 1e-6):
43
+ super().__init__()
44
+ self.eps = eps
45
+ self.weight = nn.Parameter(torch.zeros(dim))
46
+
47
+ def _norm(self, x):
48
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
49
+
50
+ def forward(self, x):
51
+ output = self._norm(x.float())
52
+ # Llama does x.to(float16) * w whilst RecurrentGemma is (x * w).to(float16)
53
+ # See https://github.com/huggingface/transformers/pull/29402
54
+ output = output * (1.0 + self.weight.float())
55
+ return output.type_as(x)
56
+
57
+ def extra_repr(self):
58
+ return f"{tuple(self.weight.shape)}, eps={self.eps}"
59
+
60
+
61
+ class RecurrentGemmaRotaryEmbedding(nn.Module):
62
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
63
+
64
+ def __init__(self, dim, base=10000, device=None):
65
+ super().__init__()
66
+ self.dim = dim
67
+ self.base = base
68
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float() / self.dim))
69
+ self.register_buffer("inv_freq", tensor=inv_freq, persistent=False)
70
+
71
+ @torch.no_grad()
72
+ def forward(self, x, position_ids, seq_len=None):
73
+ # x: [bs, num_attention_heads, seq_len, head_size]
74
+ self.inv_freq.to(x.device)
75
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
76
+ position_ids_expanded = position_ids[:, None, :].float()
77
+ # Force float32 since bfloat16 loses precision on long contexts
78
+ # See https://github.com/huggingface/transformers/pull/29285
79
+ device_type = x.device.type
80
+ device_type = device_type if device_type != "mps" else "cpu"
81
+ with torch.autocast(device_type=device_type, enabled=False):
82
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
83
+ emb = torch.cat((freqs, freqs), dim=-1)
84
+ cos = emb.cos()
85
+ sin = emb.sin()
86
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
87
+
88
+
89
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
90
+ def rotate_half(x):
91
+ """Rotates half the hidden dims of the input."""
92
+ x1 = x[..., : x.shape[-1] // 2]
93
+ x2 = x[..., x.shape[-1] // 2 :]
94
+ return torch.cat((-x2, x1), dim=-1)
95
+
96
+
97
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
98
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
99
+ """Applies Rotary Position Embedding to the query and key tensors.
100
+
101
+ Args:
102
+ q (`torch.Tensor`): The query tensor.
103
+ k (`torch.Tensor`): The key tensor.
104
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
105
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
106
+ position_ids (`torch.Tensor`, *optional*):
107
+ Deprecated and unused.
108
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
109
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
110
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
111
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
112
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
113
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
114
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
115
+ Returns:
116
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
117
+ """
118
+ cos = cos.unsqueeze(unsqueeze_dim)
119
+ sin = sin.unsqueeze(unsqueeze_dim)
120
+ q_embed = (q * cos) + (rotate_half(q) * sin)
121
+ k_embed = (k * cos) + (rotate_half(k) * sin)
122
+ return q_embed, k_embed
123
+
124
+
125
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
126
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
127
+ """
128
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
129
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
130
+ """
131
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
132
+ if n_rep == 1:
133
+ return hidden_states
134
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
135
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
136
+
137
+
138
+ class RecurrentGemmaSdpaAttention(nn.Module):
139
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
140
+
141
+ def __init__(self, config: RecurrentGemmaConfig):
142
+ super().__init__()
143
+ self.config = config
144
+ self.attention_dropout = config.attention_dropout
145
+ self.hidden_size = config.hidden_size
146
+ self.num_attention_heads = config.num_attention_heads
147
+ self.head_dim = config.head_dim
148
+ self.num_key_value_heads = config.num_key_value_heads
149
+ self.num_key_value_groups = self.num_attention_heads // self.num_key_value_heads
150
+ self.partial_rotary_factor = config.partial_rotary_factor
151
+
152
+ self.q_proj = nn.Linear(self.hidden_size, self.num_attention_heads * self.head_dim, bias=config.attention_bias)
153
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
154
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
155
+ self.o_proj = nn.Linear(self.num_attention_heads * self.head_dim, self.hidden_size, bias=True)
156
+ self.rotary_emb = RecurrentGemmaRotaryEmbedding(
157
+ int(self.partial_rotary_factor * self.head_dim),
158
+ base=config.rope_theta,
159
+ )
160
+
161
+ def forward(
162
+ self,
163
+ hidden_states: torch.Tensor,
164
+ position_ids: Optional[torch.LongTensor] = None,
165
+ attention_mask: Optional[torch.Tensor] = None,
166
+ cache_position: Optional[torch.LongTensor] = None,
167
+ use_cache: bool = False,
168
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
169
+ bsz, q_len, _ = hidden_states.size()
170
+
171
+ query_states = self.q_proj(hidden_states)
172
+ key_states = self.k_proj(hidden_states)
173
+ value_states = self.v_proj(hidden_states)
174
+
175
+ query_states = query_states.view(bsz, q_len, self.num_attention_heads, self.head_dim).transpose(1, 2)
176
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
177
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
178
+
179
+ cos, sin = self.rotary_emb(value_states, position_ids)
180
+
181
+ # Partial rotary embedding
182
+ query_rot, query_pass = torch.chunk(query_states, int(1 / self.partial_rotary_factor), dim=-1)
183
+ key_rot, key_pass = torch.chunk(key_states, int(1 / self.partial_rotary_factor), dim=-1)
184
+ query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)
185
+ query_states = torch.cat((query_rot, query_pass), dim=-1)
186
+ key_states = torch.cat((key_rot, key_pass), dim=-1)
187
+
188
+ if use_cache and hasattr(self, "key_states"):
189
+ cache_kwargs = {"cache_position": cache_position}
190
+ key_states, value_states = self._update_cache(key_states, value_states, **cache_kwargs)
191
+
192
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
193
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
194
+
195
+ causal_mask = attention_mask
196
+ if attention_mask is not None:
197
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
198
+
199
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
200
+ query_states.contiguous(),
201
+ key_states.contiguous(),
202
+ value_states.contiguous(),
203
+ attn_mask=causal_mask, # pretty much a must for sliding window backend!
204
+ dropout_p=self.attention_dropout if self.training else 0.0,
205
+ scale=self.head_dim**-0.5,
206
+ )
207
+
208
+ attn_output = attn_output.transpose(1, 2).contiguous()
209
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
210
+ attn_output = self.o_proj(attn_output)
211
+ return attn_output
212
+
213
+ def _setup_cache(self, batch_size, device, dtype=None):
214
+ if dtype is None and self.config.torch_dtype is not None:
215
+ dtype = self.config.torch_dtype
216
+ dtype = dtype if dtype is not None else torch.float32
217
+ cache_shape = (batch_size, self.num_key_value_heads, self.config.attention_window_size, self.head_dim)
218
+ self.value_states = torch.zeros(cache_shape, dtype=dtype, device=device)
219
+ self.key_states = torch.zeros(cache_shape, dtype=dtype, device=device)
220
+
221
+ @torch.no_grad()
222
+ def _update_cache(self, key_states, value_states, **cache_kwargs):
223
+ """
224
+ torch.compile compatible sliding window.
225
+ Computes the `indices` based on `cache_position >= self.config.attention_window_size - 1`.
226
+ The `to_shift` is only true once we are above attention_window_size. Thus with `attention_window_size==64`:
227
+
228
+ indices = (slicing + to_shift[-1].int()-1) % self.config.attention_window_size
229
+ tensor([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
230
+ 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
231
+ 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
232
+ 55, 56, 57, 58, 59, 60, 61, 62, 63, 0])
233
+
234
+ We overwrite the cache using these, then we always write at cache_position (clamped to `attention_window_size`)
235
+ """
236
+ cache_position = cache_kwargs.get("cache_position")
237
+ if cache_position.shape[0] > self.config.attention_window_size:
238
+ # int indexing -> device sync? in compile, use tensor
239
+ k_out = key_states[:, :, -self.config.attention_window_size :, :]
240
+ v_out = value_states[:, :, -self.config.attention_window_size :, :]
241
+ else:
242
+ slicing = torch.ones(
243
+ self.config.attention_window_size, dtype=torch.long, device=value_states.device
244
+ ).cumsum(0)
245
+ cache_position = cache_position.clamp(0, self.config.attention_window_size - 1)
246
+ to_shift = cache_position >= self.config.attention_window_size - 1
247
+ indices = (slicing + to_shift[-1].int() - 1) % self.config.attention_window_size
248
+
249
+ k_out, v_out = self.key_states.to(key_states.device), self.value_states.to(value_states.device)
250
+ k_out = k_out[:, :, indices]
251
+ v_out = v_out[:, :, indices]
252
+
253
+ k_out[:, :, cache_position] = key_states.to(k_out.dtype)
254
+ v_out[:, :, cache_position] = value_states.to(v_out.dtype)
255
+
256
+ self.key_states, self.value_states = k_out, v_out
257
+ return k_out, v_out
258
+
259
+
260
+ class SqrtBoundDerivative(torch.autograd.Function):
261
+ """Computes a square root with a gradient clipped at `_MAX_SQRT_GRADIENT`."""
262
+
263
+ @staticmethod
264
+ def forward(ctx, x: torch.Tensor) -> torch.Tensor:
265
+ """The forward pass, which is a normal `sqrt`."""
266
+ ctx.save_for_backward(x)
267
+ return torch.sqrt(x)
268
+
269
+ @staticmethod
270
+ def backward(ctx, grad_output: torch.Tensor) -> torch.Tensor:
271
+ """The backward pass, which clips the `sqrt` gradient."""
272
+ (x,) = ctx.saved_tensors
273
+ clipped_x_times_4 = torch.clip(4.0 * x, min=1 / (_MAX_SQRT_GRADIENT**2))
274
+ return grad_output / torch.sqrt(clipped_x_times_4)
275
+
276
+
277
+ class RecurrentGemmaRglru(nn.Module):
278
+ """A Real-Gated Linear Recurrent Unit (RG-LRU) layer."""
279
+
280
+ def __init__(self, config):
281
+ super().__init__()
282
+ self.num_attention_heads = config.num_attention_heads
283
+ self.block_width = config.lru_width // self.num_attention_heads
284
+
285
+ self.recurrent_param = nn.Parameter(torch.empty([config.lru_width]))
286
+ self.input_gate_weight = nn.Parameter(
287
+ torch.empty([self.num_attention_heads, self.block_width, self.block_width])
288
+ )
289
+ self.input_gate_bias = nn.Parameter(torch.empty([self.num_attention_heads, self.block_width]))
290
+
291
+ self.recurrent_gate_weight = nn.Parameter(
292
+ torch.empty([self.num_attention_heads, self.block_width, self.block_width])
293
+ )
294
+ self.recurrent_gate_bias = nn.Parameter(torch.empty([self.num_attention_heads, self.block_width]))
295
+ self.recurrent_states = None
296
+
297
+ def forward(
298
+ self,
299
+ activations: torch.Tensor,
300
+ position_ids: torch.Tensor,
301
+ ) -> tuple[torch.Tensor, torch.Tensor]:
302
+ batch_size, seq_len, lru_width = activations.shape
303
+ reset = position_ids[:, :, None] == 0
304
+
305
+ reshape_act = activations.reshape(batch_size * seq_len, self.num_attention_heads, self.block_width)
306
+ reshape_act = reshape_act.permute(1, 0, 2)
307
+
308
+ res = torch.baddbmm(self.input_gate_bias[:, None, :], reshape_act, self.input_gate_weight)
309
+ input_gate = torch.sigmoid(res.transpose(0, 1).reshape(batch_size, seq_len, lru_width))
310
+
311
+ res = torch.baddbmm(self.recurrent_gate_bias[:, None, :], reshape_act, self.recurrent_gate_weight)
312
+ recurrent_gate = torch.sigmoid(res.transpose(0, 1).reshape(batch_size, seq_len, lru_width))
313
+
314
+ # Compute the parameter `A` of the recurrence.
315
+ log_recurrent_gate = -8.0 * recurrent_gate * nn.functional.softplus(self.recurrent_param)
316
+ recurrent_gate = torch.exp(log_recurrent_gate)
317
+ a_square = torch.exp(2 * log_recurrent_gate)
318
+
319
+ # Gate the input.
320
+ gated_inputs = activations * input_gate
321
+
322
+ # Apply gamma normalization to the input. We need to clip the derivatives of
323
+ # `sqrt` in order to prevent NaNs during training in bfloat16. TODO a bit annoying
324
+ multiplier = 1
325
+ tracing = isinstance(activations, torch.fx.Proxy) or is_torchdynamo_compiling()
326
+ if not torch.jit.is_tracing() and not tracing:
327
+ multiplier = SqrtBoundDerivative.apply(1 - a_square)
328
+ multiplier = reset + ~reset * multiplier
329
+ normalized_x = gated_inputs * multiplier.type(activations.dtype)
330
+
331
+ hidden_states, recurrent_states = self._rnn_scan(
332
+ hidden_states=normalized_x,
333
+ recurrent_gate=recurrent_gate,
334
+ reset=reset,
335
+ recurrent_states=self.recurrent_states,
336
+ )
337
+ self.recurrent_states = recurrent_states
338
+ return hidden_states
339
+
340
+ # TODO refactor
341
+ def _rnn_scan(
342
+ self,
343
+ hidden_states: torch.Tensor,
344
+ recurrent_gate: torch.Tensor,
345
+ reset: torch.Tensor,
346
+ recurrent_states: Union[torch.Tensor, None],
347
+ acc_dtype: torch.dtype = torch.float32,
348
+ ) -> tuple[torch.Tensor, torch.Tensor]:
349
+ """Runs the recurrence of a linear RNN.
350
+
351
+ Args:
352
+ hidden_states: The input sequence.
353
+ recurrent_gate: The diagonal of the recurrence matrix `A`.
354
+ reset: Indicator of document boundaries, e.g. when to reset the hidden state
355
+ of the RNN.
356
+ recurrent_states: The initial hidden state.
357
+ acc_dtype: The data type for the accumulation.
358
+
359
+ Returns:
360
+ The output of the linear recurrence.
361
+ """
362
+ # Multiply `a` by the reset.
363
+ recurrent_gate = recurrent_gate * ~reset
364
+
365
+ if hidden_states.shape[1] == 1:
366
+ # Using scan in sampling mode.
367
+ if recurrent_states is None: # same here, when decoding you always have cache
368
+ return hidden_states, hidden_states[:, 0].type(acc_dtype)
369
+
370
+ else:
371
+ contextualized_states = recurrent_gate.type(acc_dtype) * recurrent_states[:, None].to(
372
+ recurrent_gate.device
373
+ )
374
+ contextualized_states += hidden_states.type(acc_dtype)
375
+ return contextualized_states.type(hidden_states.dtype), contextualized_states[:, -1]
376
+
377
+ else:
378
+ # Using scan in linear mode.
379
+ if recurrent_states is None:
380
+ recurrent_states = torch.zeros(hidden_states[:, 0].shape, dtype=acc_dtype, device=hidden_states.device)
381
+
382
+ contextualized_states = torch.zeros_like(hidden_states)
383
+ for t in range(hidden_states.shape[1]):
384
+ recurrent_states = recurrent_gate[:, t].type(acc_dtype) * recurrent_states.to(recurrent_gate.device)
385
+ recurrent_states = recurrent_states + hidden_states[:, t].type(acc_dtype)
386
+ contextualized_states[:, t] = recurrent_states.type(hidden_states.dtype)
387
+
388
+ return contextualized_states, recurrent_states
389
+
390
+
391
+ class RecurrentGemmaRecurrentBlock(nn.Module):
392
+ """Griffin and Hawk's recurrent block."""
393
+
394
+ def __init__(self, config):
395
+ super().__init__()
396
+ self.lru_width = config.lru_width
397
+ self.hidden_size = config.hidden_size
398
+ self.linear_y = nn.Linear(in_features=config.hidden_size, out_features=config.lru_width)
399
+ self.linear_x = nn.Linear(in_features=config.hidden_size, out_features=config.lru_width)
400
+ self.linear_out = nn.Linear(in_features=config.lru_width, out_features=config.hidden_size)
401
+ self.conv1d_width = config.conv1d_width
402
+ self.conv_1d = nn.Conv1d(
403
+ config.lru_width,
404
+ config.lru_width,
405
+ kernel_size=config.conv1d_width,
406
+ groups=config.lru_width,
407
+ padding=config.conv1d_width - 1,
408
+ )
409
+ self.rg_lru = RecurrentGemmaRglru(config)
410
+ self.act_fn = ACT2FN[config.hidden_activation]
411
+
412
+ self.conv1d_state = None
413
+
414
+ def forward(
415
+ self,
416
+ input_states: torch.Tensor,
417
+ position_ids: torch.Tensor,
418
+ attention_mask: torch.Tensor,
419
+ cache_position: torch.Tensor,
420
+ use_cache: bool = True,
421
+ ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
422
+ _, seq_len, _ = input_states.shape
423
+
424
+ y_branch = self.linear_y(input_states)
425
+ y_branch = self.act_fn(y_branch)
426
+
427
+ x_branch = self.linear_x(input_states)
428
+ x_branch = x_branch.transpose(1, 2)
429
+
430
+ if use_cache:
431
+ if cache_position.shape[0] != 1: # prefill
432
+ self.conv1d_state = nn.functional.pad(x_branch, (self.conv1d_width - x_branch.shape[-1] - 1, 0))
433
+ x_branch = self.conv_1d(x_branch)[..., :seq_len]
434
+ else: # decoding
435
+ conv_state = torch.cat((self.conv1d_state, x_branch), -1)
436
+ x_branch = torch.sum(conv_state * self.conv_1d.weight[:, 0, :], dim=-1) + self.conv_1d.bias
437
+ x_branch = x_branch.unsqueeze(-1)
438
+ self.conv1d_state = conv_state[:, :, 1:]
439
+ else:
440
+ x_branch = self.conv_1d(x_branch)[..., :seq_len]
441
+
442
+ x_branch = self.rg_lru(x_branch.transpose(1, 2), position_ids)
443
+
444
+ hidden_states = x_branch * y_branch
445
+ hidden_states = self.linear_out(hidden_states)
446
+ return hidden_states
447
+
448
+ def _setup_cache(self, batch, device, dtype):
449
+ # recurrent_states always computed in full precision
450
+ self.rg_lru.recurrent_states = torch.zeros((batch, self.lru_width), device=device, dtype=torch.float32)
451
+ self.conv1d_state = torch.zeros((batch, self.hidden_size, self.conv1d_width - 1), device=device, dtype=dtype)
452
+
453
+
454
+ TEMPORAL_BLOCK_CLASSES = {"recurrent": RecurrentGemmaRecurrentBlock, "attention": RecurrentGemmaSdpaAttention}
455
+
456
+
457
+ class RecurrentGemmaMlp(nn.Module):
458
+ def __init__(self, config):
459
+ super().__init__()
460
+ self.config = config
461
+ self.hidden_size = config.hidden_size
462
+ self.intermediate_size = config.intermediate_size // 2
463
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=True)
464
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=True)
465
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=True)
466
+ self.act_fn = ACT2FN[config.hidden_activation]
467
+
468
+ def forward(self, hidden_states):
469
+ gate = self.act_fn(self.gate_proj(hidden_states))
470
+ return self.down_proj(gate * self.up_proj(hidden_states))
471
+
472
+
473
+ class RecurrentGemmaDecoderLayer(GradientCheckpointingLayer):
474
+ """Griffin and Hawk's residual block."""
475
+
476
+ def __init__(self, config, layer_idx):
477
+ super().__init__()
478
+ self.temporal_pre_norm = RecurrentGemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
479
+ self.temporal_block = TEMPORAL_BLOCK_CLASSES[config.layers_block_type[layer_idx]](config)
480
+ self.channel_pre_norm = RecurrentGemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
481
+ self.mlp_block = RecurrentGemmaMlp(config)
482
+
483
+ def forward(
484
+ self,
485
+ activations: torch.Tensor,
486
+ position_ids: torch.Tensor,
487
+ attention_mask: torch.Tensor,
488
+ cache_position: Optional[torch.Tensor] = None,
489
+ use_cache: Optional[bool] = None,
490
+ ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
491
+ raw_activations = activations
492
+ inputs_normalized = self.temporal_pre_norm(raw_activations) # RMSNorm introduces slight slight differences
493
+
494
+ hidden_states = self.temporal_block(
495
+ inputs_normalized, position_ids, attention_mask, cache_position=cache_position, use_cache=use_cache
496
+ )
497
+
498
+ residual = hidden_states + raw_activations
499
+
500
+ hidden_states = self.channel_pre_norm(residual)
501
+ hidden_states = self.mlp_block(hidden_states)
502
+
503
+ hidden_states = hidden_states + residual
504
+ return hidden_states
505
+
506
+
507
+ @auto_docstring
508
+ class RecurrentGemmaPreTrainedModel(PreTrainedModel):
509
+ config: RecurrentGemmaConfig
510
+ base_model_prefix = "model"
511
+ supports_gradient_checkpointing = True
512
+ _no_split_modules = ["RecurrentGemmaDecoderLayer"]
513
+ _skip_keys_device_placement = ["cache"]
514
+ _supports_flash_attn = False
515
+ _supports_sdpa = False # we can't compare with eager for now
516
+
517
+ def _init_weights(self, module):
518
+ std = math.sqrt(self.config.w_init_variance_scale / self.config.conv1d_width)
519
+ if isinstance(module, nn.Conv1d):
520
+ torch.nn.init.normal_(module.weight, mean=0.0, std=std)
521
+ torch.nn.init.zeros_(module.bias)
522
+ elif isinstance(module, RecurrentGemmaSdpaAttention):
523
+ torch.nn.init.normal_(module.q_proj.weight, mean=0.0, std=math.sqrt(1.0 / self.config.hidden_size))
524
+ torch.nn.init.normal_(module.k_proj.weight, mean=0.0, std=math.sqrt(1.0 / self.config.hidden_size))
525
+ torch.nn.init.normal_(module.v_proj.weight, mean=0.0, std=math.sqrt(1.0 / self.config.hidden_size))
526
+
527
+ std = math.sqrt(self.config.final_w_init_variance_scale / self.config.hidden_size)
528
+ torch.nn.init.normal_(module.o_proj.weight, mean=0.0, std=std)
529
+ elif isinstance(module, RecurrentGemmaRecurrentBlock):
530
+ torch.nn.init.zeros_(module.linear_x.bias)
531
+ torch.nn.init.normal_(module.linear_x.weight, mean=0.0, std=math.sqrt(1.0 / self.config.hidden_size))
532
+
533
+ torch.nn.init.zeros_(module.linear_y.bias)
534
+ torch.nn.init.normal_(module.linear_y.weight, mean=0.0, std=math.sqrt(1.0 / self.config.hidden_size))
535
+
536
+ std = math.sqrt(self.config.final_w_init_variance_scale / self.config.lru_width)
537
+ torch.nn.init.normal_(module.linear_out.weight, mean=0.0, std=std)
538
+ torch.nn.init.zeros_(module.linear_out.bias)
539
+ elif isinstance(module, RecurrentGemmaRglru):
540
+ std = math.sqrt(
541
+ self.config.w_init_variance_scale / (self.config.lru_width // self.config.num_attention_heads)
542
+ )
543
+ torch.nn.init.normal_(module.input_gate_weight, mean=0.0, std=std)
544
+ torch.nn.init.normal_(module.recurrent_gate_weight, mean=0.0, std=std)
545
+ torch.nn.init.zeros_(module.input_gate_bias)
546
+ torch.nn.init.zeros_(module.recurrent_gate_bias)
547
+
548
+ module.recurrent_param.data.uniform_(0.9**2 + 1e-8, 0.999**2 + 1e-8)
549
+ module.recurrent_param.data.log_().mul_(0.5)
550
+ module.recurrent_param.data.neg_().exp_().sub_(1.0).log_()
551
+ elif isinstance(module, nn.Linear):
552
+ torch.nn.init.normal_(module.weight, mean=0.0, std=std)
553
+ if getattr(module, "bias", None) is not None:
554
+ torch.nn.init.zeros_(module.bias)
555
+ elif isinstance(module, nn.Embedding):
556
+ module.weight.data.normal_(mean=0.0, std=std)
557
+ if module.padding_idx is not None:
558
+ module.weight.data[module.padding_idx].zero_()
559
+
560
+ elif isinstance(module, RecurrentGemmaRMSNorm):
561
+ module.weight.data.fill_(1.0)
562
+
563
+ def _setup_cache(self, config, batch, device, dtype):
564
+ layers = getattr(self, "model", self).layers
565
+ for layer in layers:
566
+ layer.temporal_block._setup_cache(batch, device, dtype)
567
+
568
+ def reset_cache(self, batch, device, dtype):
569
+ pass
570
+
571
+
572
+ @auto_docstring
573
+ class RecurrentGemmaModel(RecurrentGemmaPreTrainedModel):
574
+ def __init__(self, config: RecurrentGemmaConfig):
575
+ super().__init__(config)
576
+ self.padding_idx = config.pad_token_id
577
+ self.vocab_size = config.vocab_size
578
+
579
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
580
+ self.layers = nn.ModuleList(
581
+ [RecurrentGemmaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
582
+ )
583
+ self.final_norm = RecurrentGemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
584
+ self.gradient_checkpointing = False
585
+
586
+ self.register_buffer(
587
+ "normalizer", torch.tensor(self.config.hidden_size**0.5, dtype=torch.bfloat16), persistent=False
588
+ )
589
+ # Initialize weights and apply final processing
590
+ self.post_init()
591
+
592
+ @auto_docstring
593
+ def forward(
594
+ self,
595
+ input_ids: Optional[torch.LongTensor] = None,
596
+ position_ids: Optional[torch.LongTensor] = None,
597
+ attention_mask: Optional[torch.Tensor] = None,
598
+ cache_position: Optional[torch.LongTensor] = None,
599
+ inputs_embeds: Optional[torch.FloatTensor] = None,
600
+ use_cache: Optional[bool] = None,
601
+ output_hidden_states: Optional[bool] = None,
602
+ return_dict: Optional[bool] = None,
603
+ ) -> Union[tuple, BaseModelOutputWithNoAttention]:
604
+ output_hidden_states = (
605
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
606
+ )
607
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
608
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
609
+
610
+ if (input_ids is None) ^ (inputs_embeds is not None):
611
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
612
+
613
+ if self.gradient_checkpointing and self.training and use_cache:
614
+ logger.warning_once(
615
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
616
+ )
617
+ use_cache = False
618
+
619
+ if inputs_embeds is None:
620
+ inputs_embeds = self.embed_tokens(input_ids)
621
+
622
+ hidden_states = inputs_embeds
623
+
624
+ if use_cache and inputs_embeds.shape[1] != 1: # TODO let's maybe only call in the `generate`?
625
+ self._setup_cache(self.config, hidden_states.shape[0], hidden_states.device, hidden_states.dtype)
626
+
627
+ if cache_position is None:
628
+ cache_position = torch.arange(hidden_states.shape[1], device=hidden_states.device)
629
+ if position_ids is None:
630
+ position_ids = cache_position.unsqueeze(0)
631
+
632
+ causal_mask = self._update_causal_mask(attention_mask, inputs_embeds, cache_position)
633
+
634
+ hidden_states = hidden_states * self.normalizer.type(hidden_states.dtype)
635
+
636
+ all_hidden_states = () if output_hidden_states else None
637
+ for i, residual_block in enumerate(self.layers):
638
+ if output_hidden_states:
639
+ all_hidden_states += (hidden_states,)
640
+ hidden_states = residual_block(hidden_states, position_ids, causal_mask, cache_position, use_cache)
641
+
642
+ hidden_states = self.final_norm(hidden_states)
643
+
644
+ # add hidden states from the last decoder layer
645
+ if output_hidden_states:
646
+ all_hidden_states += (hidden_states,)
647
+
648
+ if not return_dict:
649
+ return tuple(v for v in [hidden_states, all_hidden_states] if v is not None)
650
+
651
+ return BaseModelOutputWithNoAttention(
652
+ last_hidden_state=hidden_states,
653
+ hidden_states=all_hidden_states,
654
+ )
655
+
656
+ # Ignore copy
657
+ def _update_causal_mask(self, attention_mask, input_tensor, cache_position):
658
+ dtype, device = input_tensor.dtype, input_tensor.device
659
+ min_dtype = torch.finfo(dtype).min
660
+ sequence_length = input_tensor.shape[1]
661
+ target_length = max(self.config.attention_window_size, sequence_length)
662
+
663
+ diagonal = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
664
+ causal_mask = diagonal
665
+ if sequence_length != 1:
666
+ causal_mask = torch.triu(diagonal, diagonal=-1)
667
+
668
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
669
+ causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
670
+ if attention_mask is not None:
671
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
672
+ if attention_mask.dim() == 2:
673
+ # Crop the attention mask to the target length.
674
+ attention_mask = attention_mask[:, -target_length:]
675
+ mask_length = attention_mask.shape[-1]
676
+ padding_mask = causal_mask[..., :mask_length].eq(0.0) * attention_mask[:, None, None, :].eq(0.0)
677
+ causal_mask[..., :mask_length] = causal_mask[..., :mask_length].masked_fill(padding_mask, min_dtype)
678
+
679
+ if attention_mask is not None and attention_mask.device.type in ["cuda", "xpu", "npu"]:
680
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
681
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
682
+ # Details: https://github.com/pytorch/pytorch/issues/110213
683
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
684
+
685
+ return causal_mask
686
+
687
+
688
+ # TODO: re-enable check: Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM with LLAMA->RECURRENTGEMMA,Llama->RecurrentGemma,llama->gemma
689
+ @auto_docstring
690
+ class RecurrentGemmaForCausalLM(RecurrentGemmaPreTrainedModel, GenerationMixin):
691
+ _tied_weights_keys = ["lm_head.weight"]
692
+
693
+ def __init__(self, config):
694
+ super().__init__(config)
695
+ self.model = RecurrentGemmaModel(config)
696
+ self.vocab_size = config.vocab_size
697
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
698
+
699
+ # Initialize weights and apply final processing
700
+ self.post_init()
701
+
702
+ def set_decoder(self, decoder):
703
+ self.model = decoder
704
+
705
+ def get_decoder(self):
706
+ return self.model
707
+
708
+ @auto_docstring
709
+ # Ignore copy
710
+ def forward(
711
+ self,
712
+ input_ids: Optional[torch.LongTensor] = None,
713
+ position_ids: Optional[torch.LongTensor] = None,
714
+ cache_position: Optional[torch.LongTensor] = None,
715
+ attention_mask: Optional[torch.Tensor] = None,
716
+ inputs_embeds: Optional[torch.FloatTensor] = None,
717
+ labels: Optional[torch.LongTensor] = None,
718
+ output_hidden_states: Optional[bool] = None,
719
+ return_dict: Optional[bool] = None,
720
+ use_cache: Optional[bool] = None,
721
+ **kwargs,
722
+ ) -> Union[tuple, CausalLMOutput]:
723
+ r"""
724
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
725
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
726
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
727
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
728
+
729
+ Example:
730
+
731
+ ```python
732
+ >>> from transformers import AutoTokenizer, RecurrentGemmaForCausalLM
733
+
734
+ >>> model = RecurrentGemmaForCausalLM.from_pretrained("google/recurrentgemma-2b")
735
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/recurrentgemma-2b")
736
+
737
+ >>> prompt = "What is your favorite condiment?"
738
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
739
+
740
+ >>> # Generate
741
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
742
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
743
+ "What is your favorite condiment?"
744
+ ```"""
745
+ output_hidden_states = (
746
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
747
+ )
748
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
749
+ output_hidden_states = True
750
+ outputs = self.model(
751
+ input_ids=input_ids,
752
+ position_ids=position_ids,
753
+ cache_position=cache_position,
754
+ attention_mask=attention_mask,
755
+ inputs_embeds=inputs_embeds,
756
+ use_cache=use_cache,
757
+ output_hidden_states=output_hidden_states,
758
+ return_dict=return_dict,
759
+ )
760
+
761
+ hidden_states = outputs[0]
762
+ logits = self.lm_head(hidden_states)
763
+
764
+ # Soft-cap the logits TODO remove if always done.
765
+ # if self.config.logits_soft_cap is not None:
766
+ cap = self.config.logits_soft_cap
767
+ logits = nn.functional.tanh(logits / cap) * cap
768
+
769
+ loss = None
770
+ if labels is not None:
771
+ # Upcast to float if we need to compute the loss to avoid potential precision issues
772
+ logits = logits.float()
773
+ loss = self.loss_function(
774
+ logits,
775
+ labels,
776
+ vocab_size=self.config.vocab_size,
777
+ **kwargs,
778
+ )
779
+
780
+ if not return_dict:
781
+ output = (logits,) + outputs[1:]
782
+ return (loss,) + output if loss is not None else output
783
+
784
+ return CausalLMOutput(
785
+ loss=loss,
786
+ logits=logits,
787
+ hidden_states=outputs.hidden_states,
788
+ )
789
+
790
+
791
+ __all__ = ["RecurrentGemmaForCausalLM", "RecurrentGemmaModel", "RecurrentGemmaPreTrainedModel"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/reformer/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_reformer import *
22
+ from .modeling_reformer import *
23
+ from .tokenization_reformer import *
24
+ from .tokenization_reformer_fast 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__)
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/reformer/configuration_reformer.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The Trax Authors and The HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """Reformer model configuration"""
17
+
18
+ from ...configuration_utils import PretrainedConfig
19
+ from ...utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class ReformerConfig(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`ReformerModel`]. It is used to instantiate a
28
+ Reformer model according to the specified arguments, defining the model architecture. Instantiating a configuration
29
+ with the defaults will yield a similar configuration to that of the ReFormer
30
+ [google/reformer-crime-and-punishment](https://huggingface.co/google/reformer-crime-and-punishment) architecture.
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+ Args:
36
+ attention_head_size (`int`, *optional*, defaults to 64):
37
+ Dimensionality of the projected key, query and value vectors
38
+ attn_layers (`list[str]`, *optional*, defaults to `["local", "lsh", "local", "lsh", "local", "lsh"]`):
39
+ List of attention layer types in ascending order. It can be chosen between a LSHSelfAttention layer
40
+ (`"lsh"`) and a LocalSelfAttention layer (`"local"`).
41
+
42
+ For more information on LSHSelfAttention layer, see [LSH Self Attention](reformer#lsh-self-attention). For
43
+ more information on LocalSelfAttention layer, see [Local Self Attention](reformer#local-self-attention).
44
+ axial_pos_embds (`bool`, *optional*, defaults to `True`):
45
+ Whether or not to use axial position embeddings. For more information on how axial position embeddings
46
+ work, see [Axial Position Encodings](reformer#axial-positional-encodings).
47
+ axial_norm_std (`float`, *optional*, defaults to 1.0):
48
+ The standard deviation of the normal_initializer for initializing the weight matrices of the axial
49
+ positional encodings.
50
+ axial_pos_shape (`list[int]`, *optional*, defaults to `[64, 64]`):
51
+ The position dims of the axial position encodings. During training, the product of the position dims has to
52
+ be equal to the sequence length.
53
+
54
+ For more information on how axial position embeddings work, see [Axial Position
55
+ Encodings](reformer#axial-positional-encodings).
56
+ axial_pos_embds_dim (`list[int]`, *optional*, defaults to `[64, 192]`):
57
+ The embedding dims of the axial position encodings. The sum of the embedding dims has to be equal to the
58
+ hidden size.
59
+
60
+ For more information on how axial position embeddings work, see [Axial Position
61
+ Encodings](reformer#axial-positional-encodings).
62
+ chunk_size_lm_head (`int`, *optional*, defaults to 0):
63
+ The chunk size of the final language model feed forward head layer. A chunk size of 0 means that the feed
64
+ forward layer is not chunked. A chunk size of n means that the feed forward layer processes n <
65
+ sequence_length embeddings at a time.
66
+
67
+ For more information on feed forward chunking, see [How does Feed Forward Chunking
68
+ work?](../glossary#feed-forward-chunking).
69
+ eos_token_id (`int`, *optional*, defaults to 2):
70
+ The token id for the end-of-sentence token.
71
+ feed_forward_size (`int`, *optional*, defaults to 512):
72
+ Dimensionality of the feed_forward layer in the residual attention block.
73
+ hash_seed (`int`, *optional*):
74
+ Seed that can be used to make local sensitive hashing in `LSHSelfAttention` deterministic. This should only
75
+ be set for testing purposed. For evaluation and training purposes `hash_seed` should be left as `None` to
76
+ ensure fully random rotations in local sensitive hashing scheme.
77
+ hidden_act (`str` or `Callable`, *optional*, defaults to `"relu"`):
78
+ The non-linear activation function (function or string) in the feed forward layer in the residual attention
79
+ block. If string, `"gelu"`, `"relu"`, `"silu"` and `"gelu_new"` are supported.
80
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.05):
81
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
82
+ hidden_size (`int`, *optional*, defaults to 256):
83
+ Dimensionality of the output hidden states of the residual attention blocks.
84
+ initializer_range (`float`, *optional*, defaults to 0.02):
85
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
86
+ is_decoder (`bool`, *optional*, defaults to `False`):
87
+ Whether or not to use a causal mask in addition to the `attention_mask` passed to [`ReformerModel`]. When
88
+ using the Reformer for causal language modeling, this argument should be set to `True`.
89
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
90
+ The epsilon used by the layer normalization layers.
91
+ local_chunk_length (`int`, *optional*, defaults to 64):
92
+ Length of chunk which attends to itself in `LocalSelfAttention`. Chunking reduces memory complexity from
93
+ sequence length x sequence length (self attention) to chunk length x chunk length x sequence length / chunk
94
+ length (chunked self attention).
95
+ local_num_chunks_before (`int`, *optional*, defaults to 1):
96
+ Number of previous neighbouring chunks to attend to in `LocalSelfAttention` layer to itself.
97
+ local_num_chunks_after (`int`, *optional*, defaults to 0):
98
+ Number of following neighbouring chunks to attend to in `LocalSelfAttention` layer in addition to itself.
99
+ local_attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
100
+ The dropout ratio for the attention probabilities in `LocalSelfAttention`.
101
+ lsh_attn_chunk_length (`int`, *optional*, defaults to 64):
102
+ Length of chunk which attends to itself in `LSHSelfAttention`. Chunking reduces memory complexity from
103
+ sequence length x sequence length (self attention) to chunk length x chunk length x sequence length / chunk
104
+ length (chunked self attention).
105
+ lsh_num_chunks_before (`int`, *optional*, defaults to 1):
106
+ Number of previous neighbouring chunks to attend to in `LSHSelfAttention` layer to itself.
107
+ lsh_num_chunks_after (`int`, *optional*, defaults to 0):
108
+ Number of following neighbouring chunks to attend to in `LSHSelfAttention` layer to itself.
109
+ lsh_attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
110
+ The dropout ratio for the attention probabilities in `LSHSelfAttention`.
111
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
112
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
113
+ just in case (e.g., 512 or 1024 or 2048).
114
+ num_attention_heads (`int`, *optional*, defaults to 12):
115
+ Number of attention heads for each attention layer in the Transformer encoder.
116
+ num_buckets (`int` or `list[int]`, *optional*):
117
+ Number of buckets, the key query vectors can be "hashed into" using the locality sensitive hashing scheme.
118
+ Each query key vector is hashed into a hash in `1, ..., num_buckets`. The number of buckets can also be
119
+ factorized into a list for improved memory complexity. In this case, each query key vector is hashed into a
120
+ hash in `1-1, 1-2, ..., num_buckets[0]-1, ..., num_buckets[0]-num_buckets[1]` if `num_buckets` is
121
+ factorized into two factors. The number of buckets (or the product the factors) should approximately equal
122
+ sequence length / lsh_chunk_length. If `num_buckets` not set, a good value is calculated on the fly.
123
+ num_hashes (`int`, *optional*, defaults to 1):
124
+ Number of hashing rounds (e.g., number of random rotations) in Local Sensitive Hashing scheme. The higher
125
+ `num_hashes`, the more accurate the `LSHSelfAttention` becomes, but also the more memory and time intensive
126
+ the hashing becomes.
127
+ pad_token_id (`int`, *optional*, defaults to 0):
128
+ The token id for the padding token.
129
+ vocab_size (`int`, *optional*, defaults to 320):\
130
+ Vocabulary size of the Reformer model. Defines the number of different tokens that can be represented by
131
+ the `inputs_ids` passed when calling [`ReformerModel`].
132
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
133
+ Whether to tie input and output embeddings.
134
+ use_cache (`bool`, *optional*, defaults to `True`):
135
+ Whether or not the model should return the last key/values attentions (not used by all models).
136
+ classifier_dropout (`float`, *optional*):
137
+ The dropout ratio for the classification head.
138
+
139
+ Examples:
140
+
141
+ ```python
142
+ >>> from transformers import ReformerConfig, ReformerModel
143
+
144
+ >>> # Initializing a Reformer configuration
145
+ >>> configuration = ReformerConfig()
146
+
147
+ >>> # Initializing a Reformer model (with random weights)
148
+ >>> model = ReformerModel(configuration)
149
+
150
+ >>> # Accessing the model configuration
151
+ >>> configuration = model.config
152
+ ```
153
+ """
154
+
155
+ model_type = "reformer"
156
+ keys_to_ignore_at_inference = ["past_buckets_states"]
157
+ attribute_map = {}
158
+
159
+ def __init__(
160
+ self,
161
+ attention_head_size=64,
162
+ attn_layers=["local", "lsh", "local", "lsh", "local", "lsh"],
163
+ axial_norm_std=1.0,
164
+ axial_pos_embds=True,
165
+ axial_pos_shape=[64, 64],
166
+ axial_pos_embds_dim=[64, 192],
167
+ chunk_size_lm_head=0,
168
+ eos_token_id=2,
169
+ feed_forward_size=512,
170
+ hash_seed=None,
171
+ hidden_act="relu",
172
+ hidden_dropout_prob=0.05,
173
+ hidden_size=256,
174
+ initializer_range=0.02,
175
+ is_decoder=False,
176
+ layer_norm_eps=1e-12,
177
+ local_num_chunks_before=1,
178
+ local_num_chunks_after=0,
179
+ local_attention_probs_dropout_prob=0.05,
180
+ local_attn_chunk_length=64,
181
+ lsh_attn_chunk_length=64,
182
+ lsh_attention_probs_dropout_prob=0.0,
183
+ lsh_num_chunks_before=1,
184
+ lsh_num_chunks_after=0,
185
+ max_position_embeddings=4096,
186
+ num_attention_heads=12,
187
+ num_buckets=None,
188
+ num_hashes=1,
189
+ pad_token_id=0,
190
+ vocab_size=320,
191
+ tie_word_embeddings=False,
192
+ use_cache=True,
193
+ classifier_dropout=None,
194
+ **kwargs,
195
+ ):
196
+ self.hash_seed = hash_seed
197
+ self.vocab_size = vocab_size
198
+ self.attention_head_size = attention_head_size
199
+ self.hidden_size = hidden_size
200
+ self.num_attention_heads = num_attention_heads
201
+ self.num_hashes = num_hashes
202
+ self.num_hidden_layers = len(attn_layers)
203
+ self.num_buckets = tuple(num_buckets) if isinstance(num_buckets, list) else num_buckets
204
+ self.lsh_attn_chunk_length = lsh_attn_chunk_length
205
+ self.local_attn_chunk_length = local_attn_chunk_length
206
+ self.lsh_num_chunks_after = lsh_num_chunks_after
207
+ self.lsh_num_chunks_before = lsh_num_chunks_before
208
+ self.local_num_chunks_after = local_num_chunks_after
209
+ self.local_num_chunks_before = local_num_chunks_before
210
+ self.hidden_act = hidden_act
211
+ self.feed_forward_size = feed_forward_size
212
+ self.hidden_dropout_prob = hidden_dropout_prob
213
+ self.lsh_attention_probs_dropout_prob = lsh_attention_probs_dropout_prob
214
+ self.local_attention_probs_dropout_prob = local_attention_probs_dropout_prob
215
+ self.max_position_embeddings = max_position_embeddings
216
+ self.initializer_range = initializer_range
217
+ self.layer_norm_eps = layer_norm_eps
218
+ self.axial_pos_embds = axial_pos_embds
219
+ self.axial_pos_shape = tuple(axial_pos_shape)
220
+ self.axial_pos_embds_dim = tuple(axial_pos_embds_dim)
221
+ self.axial_norm_std = axial_norm_std
222
+ self.chunk_size_lm_head = chunk_size_lm_head
223
+ self.attn_layers = attn_layers
224
+ self.use_cache = use_cache
225
+ self.classifier_dropout = classifier_dropout
226
+ super().__init__(
227
+ pad_token_id=pad_token_id,
228
+ eos_token_id=eos_token_id,
229
+ is_decoder=is_decoder,
230
+ tie_word_embeddings=tie_word_embeddings,
231
+ **kwargs,
232
+ )
233
+
234
+
235
+ __all__ = ["ReformerConfig"]
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/reformer/convert_reformer_trax_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Convert Reformer checkpoint."""
16
+
17
+ import argparse
18
+ import pickle
19
+
20
+ import numpy as np
21
+ import torch
22
+ from torch import nn
23
+
24
+ from transformers import ReformerConfig, ReformerModelWithLMHead
25
+ from transformers.utils import logging
26
+
27
+
28
+ logging.set_verbosity_info()
29
+
30
+
31
+ def set_param(torch_layer, weight, bias=None):
32
+ # set parameter of one layer
33
+ assert torch_layer.weight.shape == weight.shape, f"{torch_layer} layer.weight does not match"
34
+ torch_layer.weight = nn.Parameter(weight)
35
+ if bias is not None:
36
+ assert torch_layer.bias.shape == bias.shape, f"{torch_layer} layer.bias does not match"
37
+ torch_layer.bias = nn.Parameter(bias)
38
+
39
+
40
+ def set_layer_weights_in_torch_lsh(weights, torch_layer, hidden_size):
41
+ # set torch weights for 1-to-1 comparison
42
+ np_query_key = np.asarray(weights[0])
43
+ np_value = np.asarray(weights[1])
44
+ np_dense = np.asarray(weights[2])
45
+
46
+ set_param(
47
+ torch_layer.self_attention.query_key,
48
+ torch.tensor(np_query_key).transpose(1, 2).contiguous().view(-1, hidden_size),
49
+ )
50
+ set_param(
51
+ torch_layer.self_attention.value,
52
+ torch.tensor(np_value).transpose(1, 2).contiguous().view(-1, hidden_size),
53
+ )
54
+ set_param(
55
+ torch_layer.output.dense,
56
+ torch.tensor(np_dense).view(-1, hidden_size).contiguous().transpose(0, 1),
57
+ )
58
+
59
+
60
+ def set_layer_weights_in_torch_local(weights, torch_layer, hidden_size):
61
+ # set torch weights for 1-to-1 comparison
62
+ np_query = np.asarray(weights[0])
63
+ np_key = np.asarray(weights[1])
64
+ np_value = np.asarray(weights[2])
65
+ np_dense = np.asarray(weights[3])
66
+
67
+ set_param(
68
+ torch_layer.self_attention.query,
69
+ torch.tensor(np_query).transpose(1, 2).contiguous().view(-1, hidden_size),
70
+ )
71
+ set_param(
72
+ torch_layer.self_attention.key,
73
+ torch.tensor(np_key).transpose(1, 2).contiguous().view(-1, hidden_size),
74
+ )
75
+ set_param(
76
+ torch_layer.self_attention.value,
77
+ torch.tensor(np_value).transpose(1, 2).contiguous().view(-1, hidden_size),
78
+ )
79
+ set_param(
80
+ torch_layer.output.dense,
81
+ torch.tensor(np_dense).view(-1, hidden_size).contiguous().transpose(0, 1),
82
+ )
83
+
84
+
85
+ def set_block_weights_in_torch(weights, torch_block, hidden_size):
86
+ # layernorm 1
87
+ layer_norm_1 = weights[0][0][0]
88
+ layer_norm_1_weight = np.asarray(layer_norm_1[0])
89
+ layer_norm_1_bias = np.asarray(layer_norm_1[1])
90
+ set_param(
91
+ torch_block.attention.layer_norm,
92
+ torch.tensor(layer_norm_1_weight),
93
+ torch.tensor(layer_norm_1_bias),
94
+ )
95
+
96
+ # lsh weights + output
97
+ attn_weights = weights[0][1]
98
+ if len(attn_weights) < 4:
99
+ set_layer_weights_in_torch_lsh(attn_weights, torch_block.attention, hidden_size)
100
+ else:
101
+ set_layer_weights_in_torch_local(attn_weights, torch_block.attention, hidden_size)
102
+
103
+ # intermediate weighs
104
+ intermediate_weights = weights[2][0][1][2]
105
+
106
+ # Chunked Feed Forward
107
+ if len(intermediate_weights) == 4:
108
+ intermediate_weights = intermediate_weights[2]
109
+
110
+ # layernorm 2
111
+ layer_norm_2_weight = np.asarray(intermediate_weights[0][0])
112
+ layer_norm_2_bias = np.asarray(intermediate_weights[0][1])
113
+ set_param(
114
+ torch_block.feed_forward.layer_norm,
115
+ torch.tensor(layer_norm_2_weight),
116
+ torch.tensor(layer_norm_2_bias),
117
+ )
118
+
119
+ # intermediate dense
120
+ inter_dense_weight = np.asarray(intermediate_weights[1][0])
121
+ inter_dense_bias = np.asarray(intermediate_weights[1][1])
122
+ set_param(
123
+ torch_block.feed_forward.dense.dense,
124
+ torch.tensor(inter_dense_weight).transpose(0, 1).contiguous(),
125
+ torch.tensor(inter_dense_bias),
126
+ )
127
+
128
+ # intermediate out
129
+ out_dense_weight = np.asarray(intermediate_weights[4][0])
130
+ out_dense_bias = np.asarray(intermediate_weights[4][1])
131
+ set_param(
132
+ torch_block.feed_forward.output.dense,
133
+ torch.tensor(out_dense_weight).transpose(0, 1).contiguous(),
134
+ torch.tensor(out_dense_bias),
135
+ )
136
+
137
+
138
+ def set_model_weights_in_torch(weights, torch_model, hidden_size):
139
+ # reformer model
140
+ torch_model_reformer = torch_model.reformer
141
+
142
+ # word embeds
143
+ word_embeddings = np.asarray(weights[1])
144
+ set_param(
145
+ torch_model_reformer.embeddings.word_embeddings,
146
+ torch.tensor(word_embeddings),
147
+ )
148
+
149
+ if isinstance(weights[3], tuple):
150
+ position_embeddings = torch_model_reformer.embeddings.position_embeddings
151
+ for emb_idx in range(len(position_embeddings.weights)):
152
+ emb_weights = np.asarray(weights[3][emb_idx][0])
153
+ assert position_embeddings.weights[emb_idx].shape == emb_weights.shape, (
154
+ f"{position_embeddings[emb_idx]} emb does not match"
155
+ )
156
+ position_embeddings.weights[emb_idx] = nn.Parameter(torch.tensor(emb_weights))
157
+
158
+ trax_layer_weights = weights[5]
159
+ assert len(torch_model_reformer.encoder.layers) * 4 == len(trax_layer_weights), (
160
+ "HF and trax model do not have the same number of layers"
161
+ )
162
+ for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers):
163
+ block_weights = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)]
164
+ set_block_weights_in_torch(block_weights, layer, hidden_size)
165
+
166
+ # output layer norm
167
+ layer_norm_out_weight = np.asarray(weights[7][0])
168
+ layer_norm_out_bias = np.asarray(weights[7][1])
169
+ set_param(
170
+ torch_model_reformer.encoder.layer_norm,
171
+ torch.tensor(layer_norm_out_weight),
172
+ torch.tensor(layer_norm_out_bias),
173
+ )
174
+
175
+ # output embeddings
176
+ output_embed_weights = np.asarray(weights[9][0])
177
+ output_embed_bias = np.asarray(weights[9][1])
178
+ set_param(
179
+ torch_model.lm_head.decoder,
180
+ torch.tensor(output_embed_weights).transpose(0, 1).contiguous(),
181
+ torch.tensor(output_embed_bias),
182
+ )
183
+
184
+
185
+ def convert_trax_checkpoint_to_pytorch(trax_model_pkl_path, config_file, pytorch_dump_path):
186
+ # Initialise PyTorch model
187
+ config = ReformerConfig.from_json_file(config_file)
188
+ print(f"Building PyTorch model from configuration: {config}")
189
+ model = ReformerModelWithLMHead(config)
190
+
191
+ with open(trax_model_pkl_path, "rb") as f:
192
+ model_weights = pickle.load(f)["weights"]
193
+
194
+ set_model_weights_in_torch(model_weights, model, config.hidden_size)
195
+
196
+ # Save pytorch-model
197
+ print(f"Save PyTorch model to {pytorch_dump_path}")
198
+ torch.save(model.state_dict(), pytorch_dump_path)
199
+
200
+
201
+ if __name__ == "__main__":
202
+ parser = argparse.ArgumentParser()
203
+ # Required parameters
204
+ parser.add_argument(
205
+ "--trax_model_pkl_path",
206
+ default=None,
207
+ type=str,
208
+ required=True,
209
+ help="Path to the TensorFlow checkpoint path.\n"
210
+ "Given the files are in the pickle format, please be wary of passing it files you trust.",
211
+ )
212
+ parser.add_argument(
213
+ "--config_file",
214
+ default=None,
215
+ type=str,
216
+ required=True,
217
+ help=(
218
+ "The config json file corresponding to the pre-trained Reformer model. \n"
219
+ "This specifies the model architecture."
220
+ ),
221
+ )
222
+ parser.add_argument(
223
+ "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
224
+ )
225
+ args = parser.parse_args()
226
+ convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/reformer/modeling_reformer.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/reformer/tokenization_reformer.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The Trax Authors and The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Tokenization class for model Reformer."""
16
+
17
+ import os
18
+ from shutil import copyfile
19
+ from typing import Any, Optional
20
+
21
+ import sentencepiece as spm
22
+
23
+ from ...tokenization_utils import PreTrainedTokenizer
24
+ from ...utils import logging
25
+ from ...utils.import_utils import requires
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+
31
+ SPIECE_UNDERLINE = "▁"
32
+
33
+ VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
34
+
35
+
36
+ @requires(backends=("sentencepiece",))
37
+ class ReformerTokenizer(PreTrainedTokenizer):
38
+ """
39
+ Construct a Reformer tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece) .
40
+
41
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
42
+ this superclass for more information regarding those methods.
43
+
44
+ Args:
45
+ vocab_file (`str`):
46
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
47
+ contains the vocabulary necessary to instantiate a tokenizer.
48
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
49
+ The end of sequence token.
50
+
51
+ <Tip>
52
+
53
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
54
+ The token used is the `sep_token`.
55
+
56
+ </Tip>
57
+
58
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
59
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
60
+ token instead.
61
+ additional_special_tokens (`list[str]`, *optional*, defaults to `[]`):
62
+ Additional special tokens used by the tokenizer.
63
+ sp_model_kwargs (`dict`, *optional*):
64
+ Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
65
+ SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
66
+ to set:
67
+
68
+ - `enable_sampling`: Enable subword regularization.
69
+ - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
70
+
71
+ - `nbest_size = {0,1}`: No sampling is performed.
72
+ - `nbest_size > 1`: samples from the nbest_size results.
73
+ - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
74
+ using forward-filtering-and-backward-sampling algorithm.
75
+
76
+ - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
77
+ BPE-dropout.
78
+ """
79
+
80
+ vocab_files_names = VOCAB_FILES_NAMES
81
+ model_input_names = ["input_ids", "attention_mask"]
82
+
83
+ def __init__(
84
+ self,
85
+ vocab_file,
86
+ eos_token="</s>",
87
+ unk_token="<unk>",
88
+ additional_special_tokens=[],
89
+ sp_model_kwargs: Optional[dict[str, Any]] = None,
90
+ **kwargs,
91
+ ) -> None:
92
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
93
+
94
+ self.vocab_file = vocab_file
95
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
96
+ self.sp_model.Load(vocab_file)
97
+
98
+ super().__init__(
99
+ eos_token=eos_token,
100
+ unk_token=unk_token,
101
+ additional_special_tokens=additional_special_tokens,
102
+ sp_model_kwargs=self.sp_model_kwargs,
103
+ **kwargs,
104
+ )
105
+
106
+ @property
107
+ def vocab_size(self):
108
+ return self.sp_model.get_piece_size()
109
+
110
+ def get_vocab(self) -> dict[str, int]:
111
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
112
+ vocab.update(self.added_tokens_encoder)
113
+ return vocab
114
+
115
+ def __getstate__(self):
116
+ state = self.__dict__.copy()
117
+ state["sp_model"] = None
118
+ return state
119
+
120
+ def __setstate__(self, d):
121
+ self.__dict__ = d
122
+
123
+ # for backward compatibility
124
+ if not hasattr(self, "sp_model_kwargs"):
125
+ self.sp_model_kwargs = {}
126
+
127
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
128
+ self.sp_model.Load(self.vocab_file)
129
+
130
+ def _tokenize(self, text: str) -> list[str]:
131
+ """Take as input a string and return a list of strings (tokens) for words/sub-words"""
132
+ return self.sp_model.encode(text, out_type=str)
133
+
134
+ def _convert_token_to_id(self, token):
135
+ """Converts a token (str) in an id using the vocab."""
136
+ return self.sp_model.piece_to_id(token)
137
+
138
+ def _convert_id_to_token(self, index):
139
+ """Converts an index (integer) in a token (str) using the vocab."""
140
+ if index < self.sp_model.get_piece_size():
141
+ token = self.sp_model.IdToPiece(index)
142
+ return token
143
+
144
+ def convert_tokens_to_string(self, tokens):
145
+ """Converts a sequence of tokens (string) in a single string."""
146
+ current_sub_tokens = []
147
+ out_string = ""
148
+ for token in tokens:
149
+ # make sure that special tokens are not decoded using sentencepiece model
150
+ if token in self.all_special_tokens:
151
+ out_string += self.sp_model.decode(current_sub_tokens) + token
152
+ current_sub_tokens = []
153
+ else:
154
+ current_sub_tokens.append(token)
155
+ out_string += self.sp_model.decode(current_sub_tokens)
156
+ return out_string.strip()
157
+
158
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
159
+ if not os.path.isdir(save_directory):
160
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
161
+ return
162
+ out_vocab_file = os.path.join(
163
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
164
+ )
165
+
166
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
167
+ copyfile(self.vocab_file, out_vocab_file)
168
+ elif not os.path.isfile(self.vocab_file):
169
+ with open(out_vocab_file, "wb") as fi:
170
+ content_spiece_model = self.sp_model.serialized_model_proto()
171
+ fi.write(content_spiece_model)
172
+
173
+ return (out_vocab_file,)
174
+
175
+
176
+ __all__ = ["ReformerTokenizer"]