main
py 540 lines 19.9 KB
Raw
1 # SPDX-License-Identifier: Apache-2.0
2 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
4 # Adapted from
5 # https://github.com/huggingface/transformers/blob/a5cc30d72ae2dc19af534e4b35c986cc28db1275/src/transformers/models/falcon/modeling_falcon.py
6 # Copyright 2023 The vLLM team.
7 # Copyright 2023 the Falcon authors and HuggingFace Inc. team. All rights
8 # 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 """PyTorch Falcon model."""
22
23 import math
24 from collections.abc import Iterable
25 from itertools import islice
26 from typing import TypeAlias
27
28 import torch
29 from torch import nn
30 from torch.nn import LayerNorm
31 from transformers import FalconConfig as HF_FalconConfig
32
33 from vllm.compilation.decorators import support_torch_compile
34 from vllm.config import CacheConfig, VllmConfig
35 from vllm.distributed import (
36 get_pp_group,
37 get_tensor_model_parallel_rank,
38 get_tensor_model_parallel_world_size,
39 tensor_model_parallel_all_reduce,
40 )
41 from vllm.model_executor.layers.activation import get_act_fn
42 from vllm.model_executor.layers.attention import Attention
43 from vllm.model_executor.layers.linear import (
44 ColumnParallelLinear,
45 QKVParallelLinear,
46 RowParallelLinear,
47 )
48 from vllm.model_executor.layers.logits_processor import LogitsProcessor
49 from vllm.model_executor.layers.quantization import QuantizationConfig
50 from vllm.model_executor.layers.rotary_embedding import get_rope
51 from vllm.model_executor.layers.vocab_parallel_embedding import (
52 ParallelLMHead,
53 VocabParallelEmbedding,
54 )
55 from vllm.model_executor.model_loader.weight_utils import default_weight_loader
56 from vllm.sequence import IntermediateTensors
57 from vllm.transformers_utils.configs.falcon import RWConfig
58
59 from .interfaces import SupportsPP
60 from .utils import (
61 AutoWeightsLoader,
62 is_pp_missing_parameter,
63 make_empty_intermediate_tensors_factory,
64 make_layers,
65 maybe_prefix,
66 )
67
68 FalconConfig: TypeAlias = HF_FalconConfig | RWConfig
69
70
71 def _get_alibi_slopes(total_num_heads: int) -> torch.Tensor:
72 closest_power_of_2 = 2 ** math.floor(math.log2(total_num_heads))
73 base = torch.tensor(
74 2 ** (-(2 ** -(math.log2(closest_power_of_2) - 3))), dtype=torch.float32
75 )
76 powers = torch.arange(1, 1 + closest_power_of_2, dtype=torch.int32)
77 slopes = torch.pow(base, powers)
78
79 if closest_power_of_2 != total_num_heads:
80 extra_base = torch.tensor(
81 2 ** (-(2 ** -(math.log2(2 * closest_power_of_2) - 3))), dtype=torch.float32
82 )
83 num_remaining_heads = min(
84 closest_power_of_2, total_num_heads - closest_power_of_2
85 )
86 extra_powers = torch.arange(
87 1, 1 + 2 * num_remaining_heads, 2, dtype=torch.int32
88 )
89 slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0)
90
91 return slopes
92
93
94 class FalconAttention(nn.Module):
95 def __init__(
96 self,
97 config: FalconConfig,
98 cache_config: CacheConfig | None = None,
99 quant_config: QuantizationConfig | None = None,
100 prefix: str = "",
101 ):
102 super().__init__()
103
104 self.hidden_size = config.hidden_size
105 tp_size = get_tensor_model_parallel_world_size()
106
107 self.total_num_heads = config.num_attention_heads
108 assert self.total_num_heads % tp_size == 0
109 self.num_heads = self.total_num_heads // tp_size
110 self.head_dim = self.hidden_size // self.total_num_heads
111 assert self.head_dim * self.total_num_heads == self.hidden_size
112
113 self.new_decoder_architecture = config.new_decoder_architecture
114 self.multi_query = config.multi_query
115
116 if self.new_decoder_architecture:
117 self.total_num_kv_heads = config.num_kv_heads
118 elif self.multi_query:
119 self.total_num_kv_heads = 1
120 else:
121 self.total_num_kv_heads = self.total_num_heads
122 if self.total_num_kv_heads >= tp_size:
123 # Number of KV heads is greater than TP size, so we partition
124 # the KV heads across multiple tensor parallel GPUs.
125 assert self.total_num_kv_heads % tp_size == 0
126 else:
127 # Number of KV heads is less than TP size, so we replicate
128 # the KV heads across multiple tensor parallel GPUs.
129 assert tp_size % self.total_num_kv_heads == 0
130 self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
131
132 self.query_key_value = QKVParallelLinear(
133 self.hidden_size,
134 self.head_dim,
135 self.total_num_heads,
136 self.total_num_kv_heads,
137 bias=config.bias,
138 skip_bias_add=True,
139 quant_config=quant_config,
140 prefix=f"{prefix}.query_key_value",
141 )
142 self.q_size = self.num_heads * self.head_dim
143 self.kv_size = self.num_kv_heads * self.head_dim
144
145 # Layer-wise attention scaling
146 self.inv_norm_factor = 1.0 / math.sqrt(self.head_dim)
147 self.reduce_row_parallel_results = not (
148 config.new_decoder_architecture or config.parallel_attn
149 )
150 self.dense = RowParallelLinear(
151 self.hidden_size,
152 self.hidden_size,
153 bias=config.bias,
154 skip_bias_add=True,
155 quant_config=quant_config,
156 reduce_results=self.reduce_row_parallel_results,
157 prefix=f"{prefix}.dense",
158 )
159
160 self.use_rotary = config.rotary
161 self.use_alibi = config.alibi
162 assert not (self.use_rotary and self.use_alibi), (
163 "Rotary and alibi are mutually exclusive."
164 )
165
166 if self.use_rotary:
167 max_position_embeddings = getattr(config, "max_position_embeddings", 8192)
168 self.rotary_emb = get_rope(
169 self.head_dim,
170 max_position=max_position_embeddings,
171 rope_parameters=config.rope_parameters,
172 )
173 self.attn = Attention(
174 self.num_heads,
175 self.head_dim,
176 self.inv_norm_factor,
177 num_kv_heads=self.num_kv_heads,
178 quant_config=quant_config,
179 prefix=f"{prefix}.attn",
180 )
181 elif self.use_alibi:
182 tp_rank = get_tensor_model_parallel_rank()
183 head_start = tp_rank * self.num_heads
184 head_end = (tp_rank + 1) * self.num_heads
185 alibi_slopes = (
186 _get_alibi_slopes(self.total_num_heads) * self.inv_norm_factor
187 )
188 alibi_slopes = alibi_slopes[head_start:head_end].tolist()
189 self.attn = Attention(
190 self.num_heads,
191 self.head_dim,
192 self.inv_norm_factor,
193 num_kv_heads=self.num_kv_heads,
194 alibi_slopes=alibi_slopes,
195 quant_config=quant_config,
196 prefix=f"{prefix}.attn",
197 )
198 else:
199 self.attn = Attention(
200 self.num_heads,
201 self.head_dim,
202 scale=self.inv_norm_factor,
203 num_kv_heads=self.num_kv_heads,
204 cache_config=cache_config,
205 quant_config=quant_config,
206 prefix=f"{prefix}.attn",
207 )
208
209 def forward(
210 self,
211 positions: torch.Tensor,
212 hidden_states: torch.Tensor,
213 ) -> torch.Tensor:
214 qkv, bias = self.query_key_value(hidden_states)
215 if bias is not None:
216 qkv += bias
217 q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
218 if self.use_rotary:
219 q, k = self.rotary_emb(positions, q, k)
220 attn_output = self.attn(q, k, v)
221 attn_output, bias = self.dense(attn_output)
222 return attn_output, bias
223
224
225 class FalconMLP(nn.Module):
226 def __init__(
227 self,
228 config: FalconConfig,
229 quant_config: QuantizationConfig | None = None,
230 prefix: str = "",
231 ):
232 super().__init__()
233 hidden_size = config.hidden_size
234
235 self.dense_h_to_4h = ColumnParallelLinear(
236 hidden_size,
237 4 * hidden_size,
238 bias=config.bias,
239 skip_bias_add=True,
240 quant_config=quant_config,
241 prefix=f"{prefix}.dense_h_to_4h",
242 )
243 self.act = get_act_fn("gelu")
244 self.reduce_row_parallel_results = not (
245 config.new_decoder_architecture or config.parallel_attn
246 )
247 self.dense_4h_to_h = RowParallelLinear(
248 4 * hidden_size,
249 hidden_size,
250 bias=config.bias,
251 skip_bias_add=True,
252 reduce_results=self.reduce_row_parallel_results,
253 quant_config=quant_config,
254 prefix=f"{prefix}.dense_4h_to_h",
255 )
256
257 def forward(self, x: torch.Tensor) -> torch.Tensor:
258 # NOTE(zhuohan): Following huggingface, we do not fuse bias add here.
259 x, bias = self.dense_h_to_4h(x)
260 if bias is not None:
261 x += bias
262 x = self.act(x)
263 x, bias = self.dense_4h_to_h(x)
264 return x, bias
265
266
267 class FalconDecoderLayer(nn.Module):
268 def __init__(
269 self,
270 config: FalconConfig,
271 cache_config: CacheConfig | None = None,
272 quant_config: QuantizationConfig | None = None,
273 prefix: str = "",
274 ):
275 super().__init__()
276 hidden_size = config.hidden_size
277 self.num_heads = config.num_attention_heads
278 self.self_attention = FalconAttention(
279 config, cache_config, quant_config, prefix=f"{prefix}.self_attention"
280 )
281 self.mlp = FalconMLP(config, quant_config, prefix=f"{prefix}.mlp")
282 self.config = config
283
284 if not hasattr(config, "num_ln_in_parallel_attn"):
285 config.num_ln_in_parallel_attn = None
286
287 if config.num_ln_in_parallel_attn is None and config.new_decoder_architecture:
288 config.num_ln_in_parallel_attn = 2
289
290 if not config.parallel_attn:
291 self.post_attention_layernorm = LayerNorm(
292 hidden_size, eps=config.layer_norm_epsilon
293 )
294 self.input_layernorm = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
295 else:
296 if config.num_ln_in_parallel_attn == 2:
297 # The layer norm before self-attention
298 self.ln_attn = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
299 # The layer norm before the MLP
300 self.ln_mlp = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
301 else:
302 self.input_layernorm = LayerNorm(
303 hidden_size, eps=config.layer_norm_epsilon
304 )
305
306 self.reduce_row_parallel_results = not (
307 config.new_decoder_architecture or config.parallel_attn
308 )
309
310 def forward(
311 self,
312 positions: torch.Tensor,
313 hidden_states: torch.Tensor,
314 ) -> torch.Tensor:
315 residual = hidden_states
316
317 if self.config.num_ln_in_parallel_attn == 2:
318 attention_layernorm_out = self.ln_attn(hidden_states)
319 mlp_layernorm_out = self.ln_mlp(hidden_states)
320 else:
321 attention_layernorm_out = self.input_layernorm(hidden_states)
322
323 # Self attention.
324 attention_output, attention_bias = self.self_attention(
325 positions=positions,
326 hidden_states=attention_layernorm_out,
327 )
328 if self.reduce_row_parallel_results and attention_bias is not None:
329 attention_output += attention_bias
330
331 if not self.config.new_decoder_architecture:
332 if self.config.parallel_attn:
333 mlp_layernorm_out = attention_layernorm_out
334 else:
335 residual += attention_output
336 mlp_layernorm_out = self.post_attention_layernorm(residual)
337
338 if (
339 self.config.new_decoder_architecture
340 and self.config.parallel_attn
341 and self.config.num_ln_in_parallel_attn == 1
342 ):
343 mlp_layernorm_out = attention_layernorm_out
344
345 # MLP.
346 mlp_output, mlp_bias = self.mlp(mlp_layernorm_out)
347 if self.reduce_row_parallel_results and mlp_bias is not None:
348 mlp_output += mlp_bias
349
350 if not self.reduce_row_parallel_results:
351 # When MLP and Attention layers are parallel, we can use
352 # only one all-reduce operator to reduce the results from
353 # both MLP and Attention layers.
354 mlp_output += attention_output
355 mlp_output = tensor_model_parallel_all_reduce(mlp_output)
356 if attention_bias is not None:
357 mlp_output += attention_bias
358 if mlp_bias is not None:
359 mlp_output += mlp_bias
360
361 output = mlp_output + residual
362 return output
363
364
365 @support_torch_compile
366 class FalconModel(nn.Module):
367 def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
368 super().__init__()
369
370 config = vllm_config.model_config.hf_config
371 cache_config = vllm_config.cache_config
372 quant_config = vllm_config.quant_config
373
374 self.config = config
375 self.embed_dim = config.hidden_size
376 self.num_heads = config.num_attention_heads
377 self.use_alibi = config.alibi
378
379 # Embedding + LN Embedding
380 self.word_embeddings = VocabParallelEmbedding(
381 config.vocab_size,
382 self.embed_dim,
383 )
384
385 # Transformer blocks
386 self.start_layer, self.end_layer, self.h = make_layers(
387 config.num_hidden_layers,
388 lambda prefix: FalconDecoderLayer(
389 config, cache_config, quant_config, prefix=prefix
390 ),
391 prefix=f"{prefix}.h",
392 )
393
394 # Final Layer Norm
395 self.ln_f = LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
396 self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory(
397 ["hidden_states"], config.hidden_size
398 )
399
400 def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
401 return self.word_embeddings(input_ids)
402
403 def forward(
404 self,
405 input_ids: torch.Tensor | None,
406 positions: torch.Tensor,
407 intermediate_tensors: IntermediateTensors | None,
408 inputs_embeds: torch.Tensor | None = None,
409 ) -> torch.Tensor | IntermediateTensors:
410 if get_pp_group().is_first_rank:
411 if inputs_embeds is not None:
412 hidden_states = inputs_embeds
413 else:
414 hidden_states = self.embed_input_ids(input_ids)
415 else:
416 assert intermediate_tensors is not None
417 hidden_states = intermediate_tensors["hidden_states"]
418 for layer in islice(self.h, self.start_layer, self.end_layer):
419 hidden_states = layer(positions, hidden_states)
420 if not get_pp_group().is_last_rank:
421 return IntermediateTensors({"hidden_states": hidden_states})
422 hidden_states = self.ln_f(hidden_states)
423 return hidden_states
424
425 def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
426 total_num_heads = self.config.num_attention_heads
427 if self.config.new_decoder_architecture:
428 total_num_kv_heads = self.config.num_kv_heads
429 elif self.config.multi_query:
430 total_num_kv_heads = 1
431 else:
432 total_num_kv_heads = total_num_heads
433 num_query_heads_per_kv_head = total_num_heads // total_num_kv_heads
434 params_dict = dict(self.named_parameters(remove_duplicate=False))
435 loaded_params: set[str] = set()
436 for name, loaded_weight in weights:
437 # Skip loading extra bias for GPTQ models.
438 if name.endswith(".bias") and name not in params_dict:
439 continue
440 if is_pp_missing_parameter(name, self):
441 continue
442 param = params_dict[name]
443 if "query_key_value" in name:
444 output_dim = getattr(param, "output_dim", None)
445 loaded_weight_shape = loaded_weight.shape
446 if output_dim is not None:
447 loaded_weight = loaded_weight.view(
448 loaded_weight_shape[:output_dim]
449 + (total_num_kv_heads, num_query_heads_per_kv_head + 2, -1)
450 + loaded_weight_shape[output_dim + 1 :]
451 )
452 wq = loaded_weight.narrow(
453 output_dim + 1, 0, num_query_heads_per_kv_head
454 ).reshape(
455 *loaded_weight_shape[:output_dim],
456 -1,
457 *loaded_weight_shape[output_dim + 1 :],
458 )
459 wk = loaded_weight.narrow(
460 output_dim + 1, num_query_heads_per_kv_head, 1
461 ).reshape(
462 *loaded_weight_shape[:output_dim],
463 -1,
464 *loaded_weight_shape[output_dim + 1 :],
465 )
466 wv = loaded_weight.narrow(
467 output_dim + 1, num_query_heads_per_kv_head + 1, 1
468 ).reshape(
469 *loaded_weight_shape[:output_dim],
470 -1,
471 *loaded_weight_shape[output_dim + 1 :],
472 )
473 loaded_weight = torch.cat([wq, wk, wv], dim=output_dim)
474
475 weight_loader = getattr(param, "weight_loader", default_weight_loader)
476 weight_loader(param, loaded_weight)
477 loaded_params.add(name)
478 return loaded_params
479
480
481 class FalconForCausalLM(nn.Module, SupportsPP):
482 packed_modules_mapping = {
483 "query_key_value": ["query_key_value"],
484 }
485
486 def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
487 super().__init__()
488 config = vllm_config.model_config.hf_config
489 quant_config = vllm_config.quant_config
490 self.config = config
491 self.quant_config = quant_config
492 self.transformer = FalconModel(
493 vllm_config=vllm_config, prefix=maybe_prefix(prefix, "transformer")
494 )
495 # only Falcon-11B doesn't share lm_head weight with word embeddings
496 # and previous Falcon model doesn't have tie_word_embeddings config
497 # so we set tie_word_embeddings to True by default
498 self.tie_word_embeddings = (
499 config.tie_word_embeddings
500 if config.tie_word_embeddings is not None
501 else True
502 )
503 self.lm_head = ParallelLMHead(
504 config.vocab_size,
505 config.hidden_size,
506 quant_config=quant_config,
507 prefix=maybe_prefix(prefix, "lm_head"),
508 )
509 if self.tie_word_embeddings:
510 self.lm_head = self.lm_head.tie_weights(self.transformer.word_embeddings)
511 self.logits_processor = LogitsProcessor(config.vocab_size)
512 self.make_empty_intermediate_tensors = (
513 self.transformer.make_empty_intermediate_tensors
514 )
515
516 def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
517 return self.transformer.embed_input_ids(input_ids)
518
519 def forward(
520 self,
521 input_ids: torch.LongTensor,
522 positions: torch.Tensor,
523 intermediate_tensors: IntermediateTensors | None = None,
524 inputs_embeds: torch.Tensor | None = None,
525 ) -> torch.Tensor:
526 hidden_states = self.transformer(
527 input_ids, positions, intermediate_tensors, inputs_embeds
528 )
529 return hidden_states
530
531 def compute_logits(
532 self,
533 hidden_states: torch.Tensor,
534 ) -> torch.Tensor | None:
535 logits = self.logits_processor(self.lm_head, hidden_states)
536 return logits
537
538 def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
539 loader = AutoWeightsLoader(self)
540 return loader.load_weights(weights)