falcon.py 22.3 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

zhuwenwen's avatar
zhuwenwen committed
28
29
import os
import re
Zhuohan Li's avatar
Zhuohan Li committed
30
31
32
33
34
import torch
from torch import nn
from torch.nn import LayerNorm
from transformers import FalconConfig as HF_FalconConfig

35
import vllm.envs as envs
36
from vllm.attention.layer import Attention
37
from vllm.compilation.decorators import support_torch_compile
38
from vllm.config import CacheConfig, VllmConfig
39
40
41
42
43
44
from vllm.distributed import (
    get_pp_group,
    get_tensor_model_parallel_rank,
    get_tensor_model_parallel_world_size,
    tensor_model_parallel_all_reduce,
)
45
from vllm.model_executor.layers.activation import get_act_fn
46
47
48
49
50
from vllm.model_executor.layers.linear import (
    ColumnParallelLinear,
    QKVParallelLinear,
    RowParallelLinear,
)
51
from vllm.model_executor.layers.logits_processor import LogitsProcessor
52
from vllm.model_executor.layers.quantization import QuantizationConfig
53
from vllm.model_executor.layers.rotary_embedding import get_rope
54
from vllm.model_executor.layers.vocab_parallel_embedding import (
55
56
57
    ParallelLMHead,
    VocabParallelEmbedding,
)
58
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
59
from vllm.sequence import IntermediateTensors
Zhuohan Li's avatar
Zhuohan Li committed
60
61
from vllm.transformers_utils.configs import RWConfig

62
from .interfaces import SupportsPP
63
64
65
66
67
68
69
from .utils import (
    AutoWeightsLoader,
    is_pp_missing_parameter,
    make_empty_intermediate_tensors_factory,
    make_layers,
    maybe_prefix,
)
70

71
FalconConfig: TypeAlias = HF_FalconConfig | RWConfig
zhuwenwen's avatar
zhuwenwen committed
72
73
74
from vllm import _custom_ops as ops
from vllm.model_executor.utils import pad_weight, gemm_bank_conf

Zhuohan Li's avatar
Zhuohan Li committed
75
76

def _get_alibi_slopes(total_num_heads: int) -> torch.Tensor:
77
78
79
80
    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
81
82
83
84
85
    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(
86
87
88
89
90
91
92
93
94
            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
95
96
97
98
99

    return slopes


class FalconAttention(nn.Module):
100
101
102
    def __init__(
        self,
        config: FalconConfig,
103
104
        cache_config: CacheConfig | None = None,
        quant_config: QuantizationConfig | None = None,
105
        prefix: str = "",
106
    ):
Zhuohan Li's avatar
Zhuohan Li committed
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
        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
127
128
129
130
131
132
133
134
135
        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
136

137
138
139
140
141
142
143
        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,
144
            quant_config=quant_config,
145
            prefix=f"{prefix}.query_key_value",
146
        )
Zhuohan Li's avatar
Zhuohan Li committed
147
148
149
150
151
        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)
152
153
154
        self.reduce_row_parallel_results = not (
            config.new_decoder_architecture or config.parallel_attn
        )
Zhuohan Li's avatar
Zhuohan Li committed
155
156
157
158
159
        self.dense = RowParallelLinear(
            self.hidden_size,
            self.hidden_size,
            bias=config.bias,
            skip_bias_add=True,
160
            quant_config=quant_config,
161
            reduce_results=self.reduce_row_parallel_results,
162
            prefix=f"{prefix}.dense",
163
        )
Zhuohan Li's avatar
Zhuohan Li committed
164
165
166
167

        self.use_rotary = config.rotary
        self.use_alibi = config.alibi
        assert not (self.use_rotary and self.use_alibi), (
168
169
            "Rotary and alibi are mutually exclusive."
        )
Zhuohan Li's avatar
Zhuohan Li committed
170
171

        if self.use_rotary:
172
            max_position_embeddings = getattr(config, "max_position_embeddings", 8192)
Woosuk Kwon's avatar
Woosuk Kwon committed
173
            self.rotary_emb = get_rope(
174
                self.head_dim,
Woosuk Kwon's avatar
Woosuk Kwon committed
175
                max_position=max_position_embeddings,
176
                rope_parameters=config.rope_parameters,
Woosuk Kwon's avatar
Woosuk Kwon committed
177
            )
178
179
180
181
182
183
184
            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",
Woosuk Kwon's avatar
Woosuk Kwon committed
185
            )
Zhuohan Li's avatar
Zhuohan Li committed
186
187
188
189
        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
190
191
192
            alibi_slopes = (
                _get_alibi_slopes(self.total_num_heads) * self.inv_norm_factor
            )
Zhuohan Li's avatar
Zhuohan Li committed
193
            alibi_slopes = alibi_slopes[head_start:head_end].tolist()
194
195
196
197
198
199
200
201
202
            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
203
        else:
204
205
206
207
208
209
210
211
212
            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",
            )
213
            self.quant_method = None
zhuwenwen's avatar
zhuwenwen committed
214
215
216
        if quant_config is not None:
            self.quant_method=quant_config.get_name()
            self.quant_config=quant_config
Zhuohan Li's avatar
Zhuohan Li committed
217
218
219
220
221
222

    def forward(
        self,
        positions: torch.Tensor,
        hidden_states: torch.Tensor,
    ) -> torch.Tensor:
223
        qkv, bias = self.query_key_value(hidden_states)
zhuwenwen's avatar
zhuwenwen committed
224
225
        # if os.environ.get('FA_PAD') == '1' and self.quant_method is None:
        #     qkv = qkv[...,:-32]
226
227
228
        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
229
        if self.use_rotary:
Woosuk Kwon's avatar
Woosuk Kwon committed
230
            q, k = self.rotary_emb(positions, q, k)
231
        attn_output = self.attn(q, k, v)
Zhuohan Li's avatar
Zhuohan Li committed
232
233
234
235
236
        attn_output, bias = self.dense(attn_output)
        return attn_output, bias


class FalconMLP(nn.Module):
237
238
239
    def __init__(
        self,
        config: FalconConfig,
240
        quant_config: QuantizationConfig | None = None,
241
        prefix: str = "",
242
    ):
Zhuohan Li's avatar
Zhuohan Li committed
243
244
245
        super().__init__()
        hidden_size = config.hidden_size

246
247
248
249
250
251
        self.dense_h_to_4h = ColumnParallelLinear(
            hidden_size,
            4 * hidden_size,
            bias=config.bias,
            skip_bias_add=True,
            quant_config=quant_config,
252
            prefix=f"{prefix}.dense_h_to_4h",
253
        )
254
        self.act = get_act_fn("gelu")
255
256
257
        self.reduce_row_parallel_results = not (
            config.new_decoder_architecture or config.parallel_attn
        )
Zhuohan Li's avatar
Zhuohan Li committed
258
259
260
261
262
        self.dense_4h_to_h = RowParallelLinear(
            4 * hidden_size,
            hidden_size,
            bias=config.bias,
            skip_bias_add=True,
263
            reduce_results=self.reduce_row_parallel_results,
264
            quant_config=quant_config,
265
            prefix=f"{prefix}.dense_4h_to_h",
266
        )
Zhuohan Li's avatar
Zhuohan Li committed
267
268
269
270
271
272
273
274
275
276
277
278

    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):
279
280
281
    def __init__(
        self,
        config: FalconConfig,
282
283
        cache_config: CacheConfig | None = None,
        quant_config: QuantizationConfig | None = None,
284
        prefix: str = "",
285
    ):
Zhuohan Li's avatar
Zhuohan Li committed
286
287
288
        super().__init__()
        hidden_size = config.hidden_size
        self.num_heads = config.num_attention_heads
289
        self.self_attention = FalconAttention(
290
291
            config, cache_config, quant_config, prefix=f"{prefix}.self_attention"
        )
292
        self.mlp = FalconMLP(config, quant_config, prefix=f"{prefix}.mlp")
Zhuohan Li's avatar
Zhuohan Li committed
293
294
        self.config = config

295
        if not hasattr(config, "num_ln_in_parallel_attn"):
zhuwenwen's avatar
zhuwenwen committed
296
            config.num_ln_in_parallel_attn = None
297

298
        if config.num_ln_in_parallel_attn is None and config.new_decoder_architecture:
299
300
301
302
            config.num_ln_in_parallel_attn = 2

        if not config.parallel_attn:
            self.post_attention_layernorm = LayerNorm(
303
304
305
                hidden_size, eps=config.layer_norm_epsilon
            )
            self.input_layernorm = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
306
307
308
        else:
            if config.num_ln_in_parallel_attn == 2:
                # The layer norm before self-attention
309
                self.ln_attn = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
310
                # The layer norm before the MLP
311
                self.ln_mlp = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
312
            else:
313
314
315
                self.input_layernorm = LayerNorm(
                    hidden_size, eps=config.layer_norm_epsilon
                )
Zhuohan Li's avatar
Zhuohan Li committed
316

317
318
319
        self.reduce_row_parallel_results = not (
            config.new_decoder_architecture or config.parallel_attn
        )
Zhuohan Li's avatar
Zhuohan Li committed
320
321
322
323
324

    def forward(
        self,
        positions: torch.Tensor,
        hidden_states: torch.Tensor,
325
    ) -> torch.Tensor:
Zhuohan Li's avatar
Zhuohan Li committed
326
327
        residual = hidden_states

328
        if self.config.num_ln_in_parallel_attn == 2:
Zhuohan Li's avatar
Zhuohan Li committed
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
            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)

349
350
351
352
353
        if (
            self.config.new_decoder_architecture
            and self.config.parallel_attn
            and self.config.num_ln_in_parallel_attn == 1
        ):
354
355
            mlp_layernorm_out = attention_layernorm_out

Zhuohan Li's avatar
Zhuohan Li committed
356
357
358
359
360
361
362
363
364
365
        # 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
366
            mlp_output = tensor_model_parallel_all_reduce(mlp_output)
Zhuohan Li's avatar
Zhuohan Li committed
367
368
369
370
371
372
373
374
375
            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


376
@support_torch_compile
Zhuohan Li's avatar
Zhuohan Li committed
377
class FalconModel(nn.Module):
378
    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
Zhuohan Li's avatar
Zhuohan Li committed
379
        super().__init__()
380
381
382
383
384

        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
385
386
387
388
389
390
391
        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(
392
393
394
            config.vocab_size,
            self.embed_dim,
        )
Zhuohan Li's avatar
Zhuohan Li committed
395
396

        # Transformer blocks
397
398
        self.start_layer, self.end_layer, self.h = make_layers(
            config.num_hidden_layers,
399
            lambda prefix: FalconDecoderLayer(
400
401
402
403
                config, cache_config, quant_config, prefix=prefix
            ),
            prefix=f"{prefix}.h",
        )
Zhuohan Li's avatar
Zhuohan Li committed
404
405
406

        # Final Layer Norm
        self.ln_f = LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
407
408
409
        self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory(
            ["hidden_states"], config.hidden_size
        )
zhuwenwen's avatar
zhuwenwen committed
410
411
412
413
414
415
416
417
418
        self.quant_method = None
        if quant_config is not None:
            self.quant_method=quant_config.get_name()
            self.quant_config=quant_config
        
        self.use_llama_nn = os.environ.get('LLAMA_NN') == '1'
        self.use_gemm_pad = os.environ.get('GEMM_PAD') == '1'
        self.use_fa_pad = os.environ.get('FA_PAD') == '1'
        self.use_awq_pad = os.environ.get('AWQ_PAD') == '1'
419
        self.w8a8_strategy = envs.VLLM_W8A8_BACKEND
Zhuohan Li's avatar
Zhuohan Li committed
420

421
    def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
422
        return self.word_embeddings(input_ids)
Zhuohan Li's avatar
Zhuohan Li committed
423
424
425

    def forward(
        self,
426
        input_ids: torch.Tensor,
Zhuohan Li's avatar
Zhuohan Li committed
427
        positions: torch.Tensor,
428
429
430
        intermediate_tensors: IntermediateTensors | None,
        inputs_embeds: torch.Tensor | None = None,
    ) -> torch.Tensor | IntermediateTensors:
431
        if get_pp_group().is_first_rank:
432
433
434
            if inputs_embeds is not None:
                hidden_states = inputs_embeds
            else:
435
                hidden_states = self.embed_input_ids(input_ids)
436
437
        else:
            hidden_states = intermediate_tensors["hidden_states"]
438
        for layer in islice(self.h, self.start_layer, self.end_layer):
439
            hidden_states = layer(positions, hidden_states)
440
441
        if not get_pp_group().is_last_rank:
            return IntermediateTensors({"hidden_states": hidden_states})
Zhuohan Li's avatar
Zhuohan Li committed
442
443
444
        hidden_states = self.ln_f(hidden_states)
        return hidden_states

445
    def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
Zhuohan Li's avatar
Zhuohan Li committed
446
447
448
449
450
451
452
453
        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
454
        params_dict = dict(self.named_parameters(remove_duplicate=False))
455
        loaded_params: set[str] = set()
456
        for name, loaded_weight in weights:
CHU Tianxiang's avatar
CHU Tianxiang committed
457
458
459
            # Skip loading extra bias for GPTQ models.
            if name.endswith(".bias") and name not in params_dict:
                continue
460
461
            if is_pp_missing_parameter(name, self):
                continue
462
            param = params_dict[name]
Zhuohan Li's avatar
Zhuohan Li committed
463
            if "query_key_value" in name:
464
465
                output_dim = getattr(param, "output_dim", None)
                loaded_weight_shape = loaded_weight.shape
CHU Tianxiang's avatar
CHU Tianxiang committed
466
467
                if output_dim is not None:
                    loaded_weight = loaded_weight.view(
468
469
470
471
                        loaded_weight_shape[:output_dim]
                        + (total_num_kv_heads, num_query_heads_per_kv_head + 2, -1)
                        + loaded_weight_shape[output_dim + 1 :]
                    )
CHU Tianxiang's avatar
CHU Tianxiang committed
472
                    wq = loaded_weight.narrow(
473
474
475
476
477
478
                        output_dim + 1, 0, num_query_heads_per_kv_head
                    ).reshape(
                        *loaded_weight_shape[:output_dim],
                        -1,
                        *loaded_weight_shape[output_dim + 1 :],
                    )
CHU Tianxiang's avatar
CHU Tianxiang committed
479
                    wk = loaded_weight.narrow(
480
481
482
483
484
485
                        output_dim + 1, num_query_heads_per_kv_head, 1
                    ).reshape(
                        *loaded_weight_shape[:output_dim],
                        -1,
                        *loaded_weight_shape[output_dim + 1 :],
                    )
CHU Tianxiang's avatar
CHU Tianxiang committed
486
                    wv = loaded_weight.narrow(
487
488
489
490
491
492
                        output_dim + 1, num_query_heads_per_kv_head + 1, 1
                    ).reshape(
                        *loaded_weight_shape[:output_dim],
                        -1,
                        *loaded_weight_shape[output_dim + 1 :],
                    )
CHU Tianxiang's avatar
CHU Tianxiang committed
493
                    loaded_weight = torch.cat([wq, wk, wv], dim=output_dim)
494

495
            weight_loader = getattr(param, "weight_loader", default_weight_loader)
496
            weight_loader(param, loaded_weight)
497
            loaded_params.add(name)
zhuwenwen's avatar
zhuwenwen committed
498
            
zhuwenwen's avatar
zhuwenwen committed
499
500
501
502
503
504
505
506
507
        if self.use_llama_nn and self.quant_method is None :
            lay_key_words = [
                "self_attention.query_key_value.weight",
                "self_attention.dense.weight",
                "mlp.dense_h_to_4h.weight",
                "mlp.dense_4h_to_h.weight",
            ]
            combined_words = "|".join(lay_key_words)
            
zhuwenwen's avatar
zhuwenwen committed
508
509
            # lay_qkv_words = ["self_attention.query_key_value.weight"]   
            # qkv_words = "|".join(lay_qkv_words)          
zhuwenwen's avatar
zhuwenwen committed
510
            
zhuwenwen's avatar
zhuwenwen committed
511
512
            for layername in loaded_params:
                weight = params_dict[layername]
zhuwenwen's avatar
zhuwenwen committed
513
514
                matches = re.findall(combined_words, layername)
                if matches:         
zhuwenwen's avatar
zhuwenwen committed
515
516
                    # if self.use_gemm_pad and gemm_bank_conf(weight.data.shape[0]):
                    #     weight.data = pad_weight(weight.data, 32)  
zhuwenwen's avatar
zhuwenwen committed
517
                        
zhuwenwen's avatar
zhuwenwen committed
518
519
520
                    # if self.use_fa_pad and (re.findall(qkv_words, layername)):
                    #     if not gemm_bank_conf(weight.data.shape[0]):
                    #         weight.data = pad_weight(weight.data, 32)
zhuwenwen's avatar
zhuwenwen committed
521
522
523
524
525
526
527
                                 
                    _weight = torch.zeros_like(weight.data)
                    ori_shape =_weight.shape
                    
                    ops.trans_w16_gemm(_weight, weight.data, _weight.shape[0], _weight.shape[1])
                    weight.data.copy_(_weight)
                    
zhuwenwen's avatar
zhuwenwen committed
528
                    weight.data=weight.data.reshape(ori_shape[1], -1)
529
        return loaded_params
zhuwenwen's avatar
zhuwenwen committed
530

Zhuohan Li's avatar
Zhuohan Li committed
531

532
class FalconForCausalLM(nn.Module, SupportsPP):
533
534
535
    packed_modules_mapping = {
        "query_key_value": ["query_key_value"],
    }
536

537
    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
Zhuohan Li's avatar
Zhuohan Li committed
538
        super().__init__()
539
540
        config = vllm_config.model_config.hf_config
        quant_config = vllm_config.quant_config
Zhuohan Li's avatar
Zhuohan Li committed
541
        self.config = config
542
        self.quant_config = quant_config
543
544
545
        self.transformer = FalconModel(
            vllm_config=vllm_config, prefix=maybe_prefix(prefix, "transformer")
        )
546
547
548
        # 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
549
550
551
552
553
        self.tie_word_embeddings = (
            config.tie_word_embeddings
            if config.tie_word_embeddings is not None
            else True
        )
554
        if self.tie_word_embeddings:
555
            self.lm_head = self.transformer.word_embeddings
556
557
558
559
        else:
            self.lm_head = ParallelLMHead(
                config.vocab_size,
                config.hidden_size,
560
                quant_config=quant_config,
561
                prefix=maybe_prefix(prefix, "lm_head"),
562
            )
563
        self.logits_processor = LogitsProcessor(config.vocab_size)
564
        self.make_empty_intermediate_tensors = (
565
566
            self.transformer.make_empty_intermediate_tensors
        )
Zhuohan Li's avatar
Zhuohan Li committed
567

568
569
    def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
        return self.transformer.embed_input_ids(input_ids)
570

Zhuohan Li's avatar
Zhuohan Li committed
571
572
573
574
    def forward(
        self,
        input_ids: torch.LongTensor,
        positions: torch.Tensor,
575
576
        intermediate_tensors: IntermediateTensors | None = None,
        inputs_embeds: torch.Tensor | None = None,
577
    ) -> torch.Tensor:
578
579
580
        hidden_states = self.transformer(
            input_ids, positions, intermediate_tensors, inputs_embeds
        )
581
        return hidden_states
Zhuohan Li's avatar
Zhuohan Li committed
582

583
584
585
    def compute_logits(
        self,
        hidden_states: torch.Tensor,
586
    ) -> torch.Tensor | None:
587
        logits = self.logits_processor(self.lm_head, hidden_states)
588
589
        return logits

590
    def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
591
592
        loader = AutoWeightsLoader(
            self,
593
            skip_prefixes=(["lm_head."] if self.config.tie_word_embeddings else None),
594
595
        )
        return loader.load_weights(weights)