falcon.py 20 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

Zhuohan Li's avatar
Zhuohan Li committed
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Adapted from
# https://github.com/huggingface/transformers/blob/a5cc30d72ae2dc19af534e4b35c986cc28db1275/src/transformers/models/falcon/modeling_falcon.py
# Copyright 2023 The vLLM team.
# Copyright 2023 the Falcon authors and HuggingFace Inc. team.  All rights
# reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""PyTorch Falcon model."""

import math
24
from collections.abc import Iterable
25
from itertools import islice
26
from typing import TypeAlias
Zhuohan Li's avatar
Zhuohan Li committed
27
28
29
30
31
32

import torch
from torch import nn
from torch.nn import LayerNorm
from transformers import FalconConfig as HF_FalconConfig

33
from vllm.compilation.decorators import support_torch_compile
34
from vllm.config import CacheConfig, VllmConfig
35
36
37
38
39
40
from vllm.distributed import (
    get_pp_group,
    get_tensor_model_parallel_rank,
    get_tensor_model_parallel_world_size,
    tensor_model_parallel_all_reduce,
)
41
from vllm.model_executor.layers.activation import get_act_fn
42
from vllm.model_executor.layers.attention import Attention
43
44
45
46
47
from vllm.model_executor.layers.linear import (
    ColumnParallelLinear,
    QKVParallelLinear,
    RowParallelLinear,
)
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
53
54
    ParallelLMHead,
    VocabParallelEmbedding,
)
55
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
56
from vllm.sequence import IntermediateTensors
Zhuohan Li's avatar
Zhuohan Li committed
57
58
from vllm.transformers_utils.configs import RWConfig

59
from .interfaces import SupportsPP
60
61
62
63
64
65
66
from .utils import (
    AutoWeightsLoader,
    is_pp_missing_parameter,
    make_empty_intermediate_tensors_factory,
    make_layers,
    maybe_prefix,
)
67

68
FalconConfig: TypeAlias = HF_FalconConfig | RWConfig
Zhuohan Li's avatar
Zhuohan Li committed
69
70
71


def _get_alibi_slopes(total_num_heads: int) -> torch.Tensor:
72
73
74
75
    closest_power_of_2 = 2 ** math.floor(math.log2(total_num_heads))
    base = torch.tensor(
        2 ** (-(2 ** -(math.log2(closest_power_of_2) - 3))), dtype=torch.float32
    )
Zhuohan Li's avatar
Zhuohan Li committed
76
77
78
79
80
    powers = torch.arange(1, 1 + closest_power_of_2, dtype=torch.int32)
    slopes = torch.pow(base, powers)

    if closest_power_of_2 != total_num_heads:
        extra_base = torch.tensor(
81
82
83
84
85
86
87
88
89
            2 ** (-(2 ** -(math.log2(2 * closest_power_of_2) - 3))), dtype=torch.float32
        )
        num_remaining_heads = min(
            closest_power_of_2, total_num_heads - closest_power_of_2
        )
        extra_powers = torch.arange(
            1, 1 + 2 * num_remaining_heads, 2, dtype=torch.int32
        )
        slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0)
Zhuohan Li's avatar
Zhuohan Li committed
90
91
92
93
94

    return slopes


class FalconAttention(nn.Module):
95
96
97
    def __init__(
        self,
        config: FalconConfig,
98
99
        cache_config: CacheConfig | None = None,
        quant_config: QuantizationConfig | None = None,
100
        prefix: str = "",
101
    ):
Zhuohan Li's avatar
Zhuohan Li committed
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
        super().__init__()

        self.hidden_size = config.hidden_size
        tp_size = get_tensor_model_parallel_world_size()

        self.total_num_heads = config.num_attention_heads
        assert self.total_num_heads % tp_size == 0
        self.num_heads = self.total_num_heads // tp_size
        self.head_dim = self.hidden_size // self.total_num_heads
        assert self.head_dim * self.total_num_heads == self.hidden_size

        self.new_decoder_architecture = config.new_decoder_architecture
        self.multi_query = config.multi_query

        if self.new_decoder_architecture:
            self.total_num_kv_heads = config.num_kv_heads
        elif self.multi_query:
            self.total_num_kv_heads = 1
        else:
            self.total_num_kv_heads = self.total_num_heads
122
123
124
125
126
127
128
129
130
        if self.total_num_kv_heads >= tp_size:
            # Number of KV heads is greater than TP size, so we partition
            # the KV heads across multiple tensor parallel GPUs.
            assert self.total_num_kv_heads % tp_size == 0
        else:
            # Number of KV heads is less than TP size, so we replicate
            # the KV heads across multiple tensor parallel GPUs.
            assert tp_size % self.total_num_kv_heads == 0
        self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
Zhuohan Li's avatar
Zhuohan Li committed
131

132
133
134
135
136
137
138
        self.query_key_value = QKVParallelLinear(
            self.hidden_size,
            self.head_dim,
            self.total_num_heads,
            self.total_num_kv_heads,
            bias=config.bias,
            skip_bias_add=True,
139
            quant_config=quant_config,
140
            prefix=f"{prefix}.query_key_value",
141
        )
Zhuohan Li's avatar
Zhuohan Li committed
142
143
144
145
146
        self.q_size = self.num_heads * self.head_dim
        self.kv_size = self.num_kv_heads * self.head_dim

        # Layer-wise attention scaling
        self.inv_norm_factor = 1.0 / math.sqrt(self.head_dim)
147
148
149
        self.reduce_row_parallel_results = not (
            config.new_decoder_architecture or config.parallel_attn
        )
Zhuohan Li's avatar
Zhuohan Li committed
150
151
152
153
154
        self.dense = RowParallelLinear(
            self.hidden_size,
            self.hidden_size,
            bias=config.bias,
            skip_bias_add=True,
155
            quant_config=quant_config,
156
            reduce_results=self.reduce_row_parallel_results,
157
            prefix=f"{prefix}.dense",
158
        )
Zhuohan Li's avatar
Zhuohan Li committed
159
160
161
162

        self.use_rotary = config.rotary
        self.use_alibi = config.alibi
        assert not (self.use_rotary and self.use_alibi), (
163
164
            "Rotary and alibi are mutually exclusive."
        )
Zhuohan Li's avatar
Zhuohan Li committed
165
166

        if self.use_rotary:
167
            max_position_embeddings = getattr(config, "max_position_embeddings", 8192)
Woosuk Kwon's avatar
Woosuk Kwon committed
168
            self.rotary_emb = get_rope(
169
                self.head_dim,
Woosuk Kwon's avatar
Woosuk Kwon committed
170
                max_position=max_position_embeddings,
171
                rope_parameters=config.rope_parameters,
Woosuk Kwon's avatar
Woosuk Kwon committed
172
            )
173
174
175
176
177
178
179
180
            self.attn = Attention(
                self.num_heads,
                self.head_dim,
                self.inv_norm_factor,
                num_kv_heads=self.num_kv_heads,
                quant_config=quant_config,
                prefix=f"{prefix}.attn",
            )
Zhuohan Li's avatar
Zhuohan Li committed
181
182
183
184
        elif self.use_alibi:
            tp_rank = get_tensor_model_parallel_rank()
            head_start = tp_rank * self.num_heads
            head_end = (tp_rank + 1) * self.num_heads
185
186
187
            alibi_slopes = (
                _get_alibi_slopes(self.total_num_heads) * self.inv_norm_factor
            )
Zhuohan Li's avatar
Zhuohan Li committed
188
            alibi_slopes = alibi_slopes[head_start:head_end].tolist()
189
190
191
192
193
194
195
196
197
            self.attn = Attention(
                self.num_heads,
                self.head_dim,
                self.inv_norm_factor,
                num_kv_heads=self.num_kv_heads,
                alibi_slopes=alibi_slopes,
                quant_config=quant_config,
                prefix=f"{prefix}.attn",
            )
Zhuohan Li's avatar
Zhuohan Li committed
198
        else:
199
200
201
202
203
204
205
206
207
            self.attn = Attention(
                self.num_heads,
                self.head_dim,
                scale=self.inv_norm_factor,
                num_kv_heads=self.num_kv_heads,
                cache_config=cache_config,
                quant_config=quant_config,
                prefix=f"{prefix}.attn",
            )
Zhuohan Li's avatar
Zhuohan Li committed
208
209
210
211
212
213

    def forward(
        self,
        positions: torch.Tensor,
        hidden_states: torch.Tensor,
    ) -> torch.Tensor:
214
215
216
217
        qkv, bias = self.query_key_value(hidden_states)
        if bias is not None:
            qkv += bias
        q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
Zhuohan Li's avatar
Zhuohan Li committed
218
        if self.use_rotary:
Woosuk Kwon's avatar
Woosuk Kwon committed
219
            q, k = self.rotary_emb(positions, q, k)
220
        attn_output = self.attn(q, k, v)
Zhuohan Li's avatar
Zhuohan Li committed
221
222
223
224
225
        attn_output, bias = self.dense(attn_output)
        return attn_output, bias


class FalconMLP(nn.Module):
226
227
228
    def __init__(
        self,
        config: FalconConfig,
229
        quant_config: QuantizationConfig | None = None,
230
        prefix: str = "",
231
    ):
Zhuohan Li's avatar
Zhuohan Li committed
232
233
234
        super().__init__()
        hidden_size = config.hidden_size

235
236
237
238
239
240
        self.dense_h_to_4h = ColumnParallelLinear(
            hidden_size,
            4 * hidden_size,
            bias=config.bias,
            skip_bias_add=True,
            quant_config=quant_config,
241
            prefix=f"{prefix}.dense_h_to_4h",
242
        )
243
        self.act = get_act_fn("gelu")
244
245
246
        self.reduce_row_parallel_results = not (
            config.new_decoder_architecture or config.parallel_attn
        )
Zhuohan Li's avatar
Zhuohan Li committed
247
248
249
250
251
        self.dense_4h_to_h = RowParallelLinear(
            4 * hidden_size,
            hidden_size,
            bias=config.bias,
            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
        )
Zhuohan Li's avatar
Zhuohan Li committed
256
257
258
259
260
261
262
263
264
265
266
267

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        # NOTE(zhuohan): Following huggingface, we do not fuse bias add here.
        x, bias = self.dense_h_to_4h(x)
        if bias is not None:
            x += bias
        x = self.act(x)
        x, bias = self.dense_4h_to_h(x)
        return x, bias


class FalconDecoderLayer(nn.Module):
268
269
270
    def __init__(
        self,
        config: FalconConfig,
271
272
        cache_config: CacheConfig | None = None,
        quant_config: QuantizationConfig | None = None,
273
        prefix: str = "",
274
    ):
Zhuohan Li's avatar
Zhuohan Li committed
275
276
277
        super().__init__()
        hidden_size = config.hidden_size
        self.num_heads = config.num_attention_heads
278
        self.self_attention = FalconAttention(
279
280
            config, cache_config, quant_config, prefix=f"{prefix}.self_attention"
        )
281
        self.mlp = FalconMLP(config, quant_config, prefix=f"{prefix}.mlp")
Zhuohan Li's avatar
Zhuohan Li committed
282
283
        self.config = config

284
        if not hasattr(config, "num_ln_in_parallel_attn"):
285
286
            config.num_ln_in_parallel_attn = None

287
        if config.num_ln_in_parallel_attn is None and config.new_decoder_architecture:
288
289
290
291
            config.num_ln_in_parallel_attn = 2

        if not config.parallel_attn:
            self.post_attention_layernorm = LayerNorm(
292
293
294
                hidden_size, eps=config.layer_norm_epsilon
            )
            self.input_layernorm = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
295
296
297
        else:
            if config.num_ln_in_parallel_attn == 2:
                # 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
303
304
                self.input_layernorm = LayerNorm(
                    hidden_size, eps=config.layer_norm_epsilon
                )
Zhuohan Li's avatar
Zhuohan Li committed
305

306
307
308
        self.reduce_row_parallel_results = not (
            config.new_decoder_architecture or config.parallel_attn
        )
Zhuohan Li's avatar
Zhuohan Li committed
309
310
311
312
313

    def forward(
        self,
        positions: torch.Tensor,
        hidden_states: torch.Tensor,
314
    ) -> torch.Tensor:
Zhuohan Li's avatar
Zhuohan Li committed
315
316
        residual = hidden_states

317
        if self.config.num_ln_in_parallel_attn == 2:
Zhuohan Li's avatar
Zhuohan Li committed
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
            attention_layernorm_out = self.ln_attn(hidden_states)
            mlp_layernorm_out = self.ln_mlp(hidden_states)
        else:
            attention_layernorm_out = self.input_layernorm(hidden_states)

        # Self attention.
        attention_output, attention_bias = self.self_attention(
            positions=positions,
            hidden_states=attention_layernorm_out,
        )
        if self.reduce_row_parallel_results and attention_bias is not None:
            attention_output += attention_bias

        if not self.config.new_decoder_architecture:
            if self.config.parallel_attn:
                mlp_layernorm_out = attention_layernorm_out
            else:
                residual += attention_output
                mlp_layernorm_out = self.post_attention_layernorm(residual)

338
339
340
341
342
        if (
            self.config.new_decoder_architecture
            and self.config.parallel_attn
            and self.config.num_ln_in_parallel_attn == 1
        ):
343
344
            mlp_layernorm_out = attention_layernorm_out

Zhuohan Li's avatar
Zhuohan Li committed
345
346
347
348
349
350
351
352
353
354
        # MLP.
        mlp_output, mlp_bias = self.mlp(mlp_layernorm_out)
        if self.reduce_row_parallel_results and mlp_bias is not None:
            mlp_output += mlp_bias

        if not self.reduce_row_parallel_results:
            # When MLP and Attention layers are parallel, we can use
            # only one all-reduce operator to reduce the results from
            # both MLP and Attention layers.
            mlp_output += attention_output
355
            mlp_output = tensor_model_parallel_all_reduce(mlp_output)
Zhuohan Li's avatar
Zhuohan Li committed
356
357
358
359
360
361
362
363
364
            if attention_bias is not None:
                mlp_output += attention_bias
            if mlp_bias is not None:
                mlp_output += mlp_bias

        output = mlp_output + residual
        return output


365
@support_torch_compile
Zhuohan Li's avatar
Zhuohan Li committed
366
class FalconModel(nn.Module):
367
    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
Zhuohan Li's avatar
Zhuohan Li committed
368
        super().__init__()
369
370
371
372
373

        config = vllm_config.model_config.hf_config
        cache_config = vllm_config.cache_config
        quant_config = vllm_config.quant_config

Zhuohan Li's avatar
Zhuohan Li committed
374
375
376
377
378
379
380
        self.config = config
        self.embed_dim = config.hidden_size
        self.num_heads = config.num_attention_heads
        self.use_alibi = config.alibi

        # Embedding + LN Embedding
        self.word_embeddings = VocabParallelEmbedding(
381
382
383
            config.vocab_size,
            self.embed_dim,
        )
Zhuohan Li's avatar
Zhuohan Li committed
384
385

        # Transformer blocks
386
387
        self.start_layer, self.end_layer, self.h = make_layers(
            config.num_hidden_layers,
388
            lambda prefix: FalconDecoderLayer(
389
390
391
392
                config, cache_config, quant_config, prefix=prefix
            ),
            prefix=f"{prefix}.h",
        )
Zhuohan Li's avatar
Zhuohan Li committed
393
394
395

        # Final Layer Norm
        self.ln_f = LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
396
397
398
        self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory(
            ["hidden_states"], config.hidden_size
        )
Zhuohan Li's avatar
Zhuohan Li committed
399

400
    def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
401
402
        return self.word_embeddings(input_ids)

Zhuohan Li's avatar
Zhuohan Li committed
403
404
    def forward(
        self,
zhuwenwen's avatar
zhuwenwen committed
405
        input_ids: torch.Tensor | None,
Zhuohan Li's avatar
Zhuohan Li committed
406
        positions: torch.Tensor,
407
408
409
        intermediate_tensors: IntermediateTensors | None,
        inputs_embeds: torch.Tensor | None = None,
    ) -> torch.Tensor | IntermediateTensors:
410
        if get_pp_group().is_first_rank:
411
412
413
            if inputs_embeds is not None:
                hidden_states = inputs_embeds
            else:
414
                hidden_states = self.embed_input_ids(input_ids)
415
416
        else:
            hidden_states = intermediate_tensors["hidden_states"]
417
        for layer in islice(self.h, self.start_layer, self.end_layer):
418
            hidden_states = layer(positions, hidden_states)
419
420
        if not get_pp_group().is_last_rank:
            return IntermediateTensors({"hidden_states": hidden_states})
Zhuohan Li's avatar
Zhuohan Li committed
421
422
423
        hidden_states = self.ln_f(hidden_states)
        return hidden_states

424
    def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
425
426
427
428
429
430
431
432
433
        total_num_heads = self.config.num_attention_heads
        if self.config.new_decoder_architecture:
            total_num_kv_heads = self.config.num_kv_heads
        elif self.config.multi_query:
            total_num_kv_heads = 1
        else:
            total_num_kv_heads = total_num_heads
        num_query_heads_per_kv_head = total_num_heads // total_num_kv_heads
        params_dict = dict(self.named_parameters(remove_duplicate=False))
434
        loaded_params: set[str] = set()
435
436
437
438
439
440
441
442
443
444
445
446
        for name, loaded_weight in weights:
            # Skip loading extra bias for GPTQ models.
            if name.endswith(".bias") and name not in params_dict:
                continue
            if is_pp_missing_parameter(name, self):
                continue
            param = params_dict[name]
            if "query_key_value" in name:
                output_dim = getattr(param, "output_dim", None)
                loaded_weight_shape = loaded_weight.shape
                if output_dim is not None:
                    loaded_weight = loaded_weight.view(
447
448
449
450
                        loaded_weight_shape[:output_dim]
                        + (total_num_kv_heads, num_query_heads_per_kv_head + 2, -1)
                        + loaded_weight_shape[output_dim + 1 :]
                    )
451
                    wq = loaded_weight.narrow(
452
453
454
455
456
457
                        output_dim + 1, 0, num_query_heads_per_kv_head
                    ).reshape(
                        *loaded_weight_shape[:output_dim],
                        -1,
                        *loaded_weight_shape[output_dim + 1 :],
                    )
458
                    wk = loaded_weight.narrow(
459
460
461
462
463
464
                        output_dim + 1, num_query_heads_per_kv_head, 1
                    ).reshape(
                        *loaded_weight_shape[:output_dim],
                        -1,
                        *loaded_weight_shape[output_dim + 1 :],
                    )
465
                    wv = loaded_weight.narrow(
466
467
468
469
470
471
                        output_dim + 1, num_query_heads_per_kv_head + 1, 1
                    ).reshape(
                        *loaded_weight_shape[:output_dim],
                        -1,
                        *loaded_weight_shape[output_dim + 1 :],
                    )
472
473
                    loaded_weight = torch.cat([wq, wk, wv], dim=output_dim)

474
            weight_loader = getattr(param, "weight_loader", default_weight_loader)
475
476
477
478
            weight_loader(param, loaded_weight)
            loaded_params.add(name)
        return loaded_params

Zhuohan Li's avatar
Zhuohan Li committed
479

480
class FalconForCausalLM(nn.Module, SupportsPP):
481
482
483
    packed_modules_mapping = {
        "query_key_value": ["query_key_value"],
    }
484

485
    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
Zhuohan Li's avatar
Zhuohan Li committed
486
        super().__init__()
487
488
        config = vllm_config.model_config.hf_config
        quant_config = vllm_config.quant_config
Zhuohan Li's avatar
Zhuohan Li committed
489
        self.config = config
490
        self.quant_config = quant_config
491
492
493
        self.transformer = FalconModel(
            vllm_config=vllm_config, prefix=maybe_prefix(prefix, "transformer")
        )
494
495
496
        # only Falcon-11B doesn't share lm_head weight with word embeddings
        # and previous Falcon model doesn't have tie_word_embeddings config
        # so we set tie_word_embeddings to True by default
497
498
499
500
501
        self.tie_word_embeddings = (
            config.tie_word_embeddings
            if config.tie_word_embeddings is not None
            else True
        )
502
        if self.tie_word_embeddings:
503
            self.lm_head = self.transformer.word_embeddings
504
505
506
507
        else:
            self.lm_head = ParallelLMHead(
                config.vocab_size,
                config.hidden_size,
508
                quant_config=quant_config,
509
                prefix=maybe_prefix(prefix, "lm_head"),
510
            )
511
        self.logits_processor = LogitsProcessor(config.vocab_size)
512
        self.make_empty_intermediate_tensors = (
513
514
            self.transformer.make_empty_intermediate_tensors
        )
Zhuohan Li's avatar
Zhuohan Li committed
515

516
517
    def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
        return self.transformer.embed_input_ids(input_ids)
518

Zhuohan Li's avatar
Zhuohan Li committed
519
520
521
522
    def forward(
        self,
        input_ids: torch.LongTensor,
        positions: torch.Tensor,
523
524
        intermediate_tensors: IntermediateTensors | None = None,
        inputs_embeds: torch.Tensor | None = None,
525
    ) -> torch.Tensor:
526
527
528
        hidden_states = self.transformer(
            input_ids, positions, intermediate_tensors, inputs_embeds
        )
529
        return hidden_states
Zhuohan Li's avatar
Zhuohan Li committed
530

531
532
533
    def compute_logits(
        self,
        hidden_states: torch.Tensor,
534
    ) -> torch.Tensor | None:
535
        logits = self.logits_processor(self.lm_head, hidden_states)
536
537
        return logits

538
    def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
539
540
        loader = AutoWeightsLoader(
            self,
541
            skip_prefixes=(["lm_head."] if self.config.tie_word_embeddings else None),
542
        )
zhuwenwen's avatar
zhuwenwen committed
543
        return loader.load_weights(weights)