hzy00 commited on
Commit
77496dd
·
verified ·
1 Parent(s): b421815

Delete modular_qwen2.py

Browse files
Files changed (1) hide show
  1. modular_qwen2.py +0 -249
modular_qwen2.py DELETED
@@ -1,249 +0,0 @@
1
- from typing import Callable, Optional
2
-
3
- import torch
4
- import torch.utils.checkpoint
5
- from torch import nn
6
-
7
- from transformers.cache_utils import Cache, DynamicCache
8
- from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
9
- from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
10
- from transformers.modeling_outputs import (
11
- BaseModelOutputWithPast,
12
- )
13
- from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS
14
- from transformers.processing_utils import Unpack
15
- from transformers.utils import auto_docstring, can_return_tuple, logging
16
- from transformers.models.llama.modeling_llama import (
17
- LlamaAttention,
18
- LlamaDecoderLayer,
19
- LlamaForCausalLM,
20
- LlamaForQuestionAnswering,
21
- LlamaForSequenceClassification,
22
- LlamaForTokenClassification,
23
- LlamaMLP,
24
- LlamaPreTrainedModel,
25
- apply_rotary_pos_emb,
26
- eager_attention_forward,
27
- )
28
- from transformers.models.mistral.modeling_mistral import MistralModel
29
- from transformers.models.qwen2.configuration_qwen2 import Qwen2Config
30
-
31
-
32
- logger = logging.get_logger(__name__)
33
-
34
-
35
- class Qwen2MLP(LlamaMLP):
36
- def __init__(self, config):
37
- super().__init__(config)
38
- self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
39
- self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
40
- self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
41
-
42
-
43
- class Qwen2Attention(LlamaAttention):
44
- def __init__(self, config: Qwen2Config, layer_idx: int):
45
- super().__init__(config, layer_idx)
46
- self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=True)
47
- self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
48
- self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
49
-
50
- # [MODIFIED]
51
- self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=True)
52
- self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None
53
-
54
- def forward(
55
- self,
56
- hidden_states: torch.Tensor,
57
- position_embeddings: tuple[torch.Tensor, torch.Tensor],
58
- attention_mask: Optional[torch.Tensor],
59
- past_key_value: Optional[Cache] = None,
60
- cache_position: Optional[torch.LongTensor] = None,
61
- **kwargs: Unpack[FlashAttentionKwargs],
62
- ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
63
- input_shape = hidden_states.shape[:-1]
64
- hidden_shape = (*input_shape, -1, self.head_dim)
65
-
66
- query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
67
- key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
68
- value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
69
-
70
- cos, sin = position_embeddings
71
- query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
72
-
73
- if past_key_value is not None:
74
- # sin and cos are specific to RoPE models; cache_position needed for the static cache
75
- cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
76
- key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
77
-
78
- attention_interface: Callable = eager_attention_forward
79
- if self.config._attn_implementation != "eager":
80
- attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
81
-
82
- attn_output, attn_weights = attention_interface(
83
- self,
84
- query_states,
85
- key_states,
86
- value_states,
87
- attention_mask,
88
- dropout=0.0 if not self.training else self.attention_dropout,
89
- scaling=self.scaling,
90
- sliding_window=self.sliding_window, # main diff with Llama
91
- **kwargs,
92
- )
93
-
94
- attn_output = attn_output.reshape(*input_shape, -1).contiguous()
95
- attn_output = self.o_proj(attn_output)
96
- return attn_output, attn_weights
97
-
98
-
99
- class Qwen2DecoderLayer(LlamaDecoderLayer):
100
- def __init__(self, config: Qwen2Config, layer_idx: int):
101
- super().__init__()
102
- self.attention_type = config.layer_types[layer_idx]
103
-
104
-
105
- class Qwen2PreTrainedModel(LlamaPreTrainedModel):
106
- pass
107
-
108
-
109
- class Qwen2Model(MistralModel):
110
- def __init__(self, config: Qwen2Config):
111
- super().__init__(config)
112
- self.has_sliding_layers = "sliding_attention" in self.config.layer_types
113
-
114
- @can_return_tuple
115
- @auto_docstring
116
- def forward(
117
- self,
118
- input_ids: Optional[torch.LongTensor] = None,
119
- attention_mask: Optional[torch.Tensor] = None,
120
- position_ids: Optional[torch.LongTensor] = None,
121
- past_key_values: Optional[Cache] = None,
122
- inputs_embeds: Optional[torch.FloatTensor] = None,
123
- use_cache: Optional[bool] = None,
124
- output_attentions: Optional[bool] = None,
125
- output_hidden_states: Optional[bool] = None,
126
- cache_position: Optional[torch.LongTensor] = None,
127
- **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
128
- ) -> BaseModelOutputWithPast:
129
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
130
- output_hidden_states = (
131
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
132
- )
133
- use_cache = use_cache if use_cache is not None else self.config.use_cache
134
-
135
- if (input_ids is None) ^ (inputs_embeds is not None):
136
- raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
137
-
138
- if self.gradient_checkpointing and self.training and use_cache:
139
- logger.warning_once(
140
- "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
141
- )
142
- use_cache = False
143
-
144
- # TODO (joao): remove this exception in v4.56 -- it exists for users that try to pass a legacy cache
145
- if not isinstance(past_key_values, (type(None), Cache)):
146
- raise ValueError("The `past_key_values` should be either a `Cache` object or `None`.")
147
-
148
- if inputs_embeds is None:
149
- inputs_embeds = self.embed_tokens(input_ids)
150
-
151
- if use_cache and past_key_values is None:
152
- past_key_values = DynamicCache()
153
-
154
- if cache_position is None:
155
- past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
156
- cache_position = torch.arange(
157
- past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
158
- )
159
-
160
- if position_ids is None:
161
- position_ids = cache_position.unsqueeze(0)
162
-
163
- # It may already have been prepared by e.g. `generate`
164
- if not isinstance(causal_mask_mapping := attention_mask, dict):
165
- # Prepare mask arguments
166
- mask_kwargs = {
167
- "config": self.config,
168
- "input_embeds": inputs_embeds,
169
- "attention_mask": attention_mask,
170
- "cache_position": cache_position,
171
- "past_key_values": past_key_values,
172
- "position_ids": position_ids,
173
- }
174
- # Create the masks
175
- causal_mask_mapping = {
176
- "full_attention": create_causal_mask(**mask_kwargs),
177
- }
178
- # The sliding window alternating layers are not always activated depending on the config
179
- if self.has_sliding_layers:
180
- causal_mask_mapping["sliding_attention"] = create_sliding_window_causal_mask(**mask_kwargs)
181
-
182
- hidden_states = inputs_embeds
183
-
184
- # create position embeddings to be shared across the decoder layers
185
- position_embeddings = self.rotary_emb(hidden_states, position_ids)
186
-
187
- # decoder layers
188
- all_hidden_states = () if output_hidden_states else None
189
- all_self_attns = () if output_attentions else None
190
-
191
- for decoder_layer in self.layers[: self.config.num_hidden_layers]:
192
- if output_hidden_states:
193
- all_hidden_states += (hidden_states,)
194
-
195
- layer_outputs = decoder_layer(
196
- hidden_states,
197
- attention_mask=causal_mask_mapping[decoder_layer.attention_type],
198
- position_ids=position_ids,
199
- past_key_value=past_key_values,
200
- output_attentions=output_attentions,
201
- use_cache=use_cache,
202
- cache_position=cache_position,
203
- position_embeddings=position_embeddings,
204
- **flash_attn_kwargs,
205
- )
206
-
207
- hidden_states = layer_outputs[0]
208
-
209
- if output_attentions:
210
- all_self_attns += (layer_outputs[1],)
211
-
212
- hidden_states = self.norm(hidden_states)
213
-
214
- # add hidden states from the last decoder layer
215
- if output_hidden_states:
216
- all_hidden_states += (hidden_states,)
217
-
218
- return BaseModelOutputWithPast(
219
- last_hidden_state=hidden_states,
220
- past_key_values=past_key_values if use_cache else None,
221
- hidden_states=all_hidden_states,
222
- attentions=all_self_attns,
223
- )
224
-
225
-
226
- class Qwen2ForCausalLM(LlamaForCausalLM):
227
- pass
228
-
229
-
230
- class Qwen2ForSequenceClassification(LlamaForSequenceClassification):
231
- pass
232
-
233
-
234
- class Qwen2ForTokenClassification(LlamaForTokenClassification):
235
- pass
236
-
237
-
238
- class Qwen2ForQuestionAnswering(LlamaForQuestionAnswering):
239
- pass
240
-
241
-
242
- __all__ = [
243
- "Qwen2PreTrainedModel",
244
- "Qwen2Model",
245
- "Qwen2ForCausalLM",
246
- "Qwen2ForSequenceClassification",
247
- "Qwen2ForTokenClassification",
248
- "Qwen2ForQuestionAnswering",
249
- ]