falcon.py 23.9 KB
Newer Older
Zhuohan Li's avatar
Zhuohan Li committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 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
21
from typing import Iterable, List, Optional, Set, Tuple, Union
Zhuohan Li's avatar
Zhuohan Li committed
22

zhuwenwen's avatar
zhuwenwen committed
23
24
import os
import re
Zhuohan Li's avatar
Zhuohan Li committed
25
26
27
28
29
import torch
from torch import nn
from torch.nn import LayerNorm
from transformers import FalconConfig as HF_FalconConfig

30
from vllm.attention import Attention, AttentionMetadata
31
from vllm.compilation.decorators import support_torch_compile
32
from vllm.config import CacheConfig, VllmConfig
33
from vllm.distributed import (get_pp_group, get_tensor_model_parallel_rank,
34
35
                              get_tensor_model_parallel_world_size,
                              tensor_model_parallel_all_reduce)
36
from vllm.model_executor.layers.activation import get_act_fn
37
38
39
from vllm.model_executor.layers.linear import (ColumnParallelLinear,
                                               QKVParallelLinear,
                                               RowParallelLinear)
40
from vllm.model_executor.layers.logits_processor import LogitsProcessor
41
from vllm.model_executor.layers.quantization import QuantizationConfig
42
from vllm.model_executor.layers.rotary_embedding import get_rope
Joe Runde's avatar
Joe Runde committed
43
from vllm.model_executor.layers.sampler import SamplerOutput, get_sampler
44
from vllm.model_executor.layers.vocab_parallel_embedding import (
45
    ParallelLMHead, VocabParallelEmbedding)
46
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
47
from vllm.model_executor.sampling_metadata import SamplingMetadata
48
from vllm.sequence import IntermediateTensors
Zhuohan Li's avatar
Zhuohan Li committed
49
50
from vllm.transformers_utils.configs import RWConfig

51
52
from .interfaces import SupportsPP
from .utils import (is_pp_missing_parameter,
53
54
                    make_empty_intermediate_tensors_factory, make_layers,
                    maybe_prefix)
55

zhuwenwen's avatar
zhuwenwen committed
56
57
58
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
FalconConfig = Union[HF_FalconConfig, RWConfig]


def _get_alibi_slopes(total_num_heads: int) -> torch.Tensor:
    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)
    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(
            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)

    return slopes


class FalconAttention(nn.Module):

87
88
89
    def __init__(
        self,
        config: FalconConfig,
90
        cache_config: Optional[CacheConfig] = None,
91
        quant_config: Optional[QuantizationConfig] = None,
92
        prefix: str = "",
93
    ):
Zhuohan Li's avatar
Zhuohan Li committed
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
        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
114
115
116
117
118
119
120
121
122
        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
123

124
125
126
127
128
129
130
        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,
131
            quant_config=quant_config,
132
        )
Zhuohan Li's avatar
Zhuohan Li committed
133
134
135
136
137
138
139
140
141
142
143
144
        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)
        self.reduce_row_parallel_results = not (config.new_decoder_architecture
                                                or config.parallel_attn)
        self.dense = RowParallelLinear(
            self.hidden_size,
            self.hidden_size,
            bias=config.bias,
            skip_bias_add=True,
145
            quant_config=quant_config,
Zhuohan Li's avatar
Zhuohan Li committed
146
147
148
149
150
151
152
153
            reduce_results=self.reduce_row_parallel_results)

        self.use_rotary = config.rotary
        self.use_alibi = config.alibi
        assert not (self.use_rotary and self.use_alibi), (
            "Rotary and alibi are mutually exclusive.")

        if self.use_rotary:
154
155
156
            rope_theta = getattr(config, "rope_theta", 10000)
            max_position_embeddings = getattr(config,
                                              "max_position_embeddings", 8192)
Woosuk Kwon's avatar
Woosuk Kwon committed
157
            self.rotary_emb = get_rope(
158
159
                self.head_dim,
                rotary_dim=self.head_dim,
Woosuk Kwon's avatar
Woosuk Kwon committed
160
161
162
                max_position=max_position_embeddings,
                base=rope_theta,
            )
163
164
165
            self.attn = Attention(self.num_heads,
                                  self.head_dim,
                                  self.inv_norm_factor,
166
                                  num_kv_heads=self.num_kv_heads,
167
168
                                  quant_config=quant_config,
                                  prefix=f"{prefix}.attn")
Zhuohan Li's avatar
Zhuohan Li committed
169
170
171
172
173
174
175
        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
            alibi_slopes = (_get_alibi_slopes(self.total_num_heads) *
                            self.inv_norm_factor)
            alibi_slopes = alibi_slopes[head_start:head_end].tolist()
176
177
178
179
            self.attn = Attention(self.num_heads,
                                  self.head_dim,
                                  self.inv_norm_factor,
                                  num_kv_heads=self.num_kv_heads,
180
                                  alibi_slopes=alibi_slopes,
181
182
                                  quant_config=quant_config,
                                  prefix=f"{prefix}.attn")
Zhuohan Li's avatar
Zhuohan Li committed
183
        else:
184
185
186
            self.attn = Attention(self.num_heads,
                                  self.head_dim,
                                  scale=self.inv_norm_factor,
187
                                  num_kv_heads=self.num_kv_heads,
188
                                  cache_config=cache_config,
189
190
                                  quant_config=quant_config,
                                  prefix=f"{prefix}.attn")
zhuwenwen's avatar
zhuwenwen committed
191
192
193
194
195
            
        self.quant_method = None
        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
196
197
198
199
200

    def forward(
        self,
        positions: torch.Tensor,
        hidden_states: torch.Tensor,
201
202
        kv_cache: torch.Tensor,
        attn_metadata: AttentionMetadata,
Zhuohan Li's avatar
Zhuohan Li committed
203
    ) -> torch.Tensor:
204
        qkv, bias = self.query_key_value(hidden_states)
zhuwenwen's avatar
zhuwenwen committed
205
206
        # if os.environ.get('FA_PAD') == '1' and self.quant_method is None:
        #     qkv = qkv[...,:-32]
207
208
209
        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
210
        if self.use_rotary:
Woosuk Kwon's avatar
Woosuk Kwon committed
211
            q, k = self.rotary_emb(positions, q, k)
212
        attn_output = self.attn(q, k, v, kv_cache, attn_metadata)
Zhuohan Li's avatar
Zhuohan Li committed
213
214
215
216
217
218
        attn_output, bias = self.dense(attn_output)
        return attn_output, bias


class FalconMLP(nn.Module):

219
220
221
    def __init__(
        self,
        config: FalconConfig,
222
        quant_config: Optional[QuantizationConfig] = None,
223
    ):
Zhuohan Li's avatar
Zhuohan Li committed
224
225
226
227
228
229
        super().__init__()
        hidden_size = config.hidden_size

        self.dense_h_to_4h = ColumnParallelLinear(hidden_size,
                                                  4 * hidden_size,
                                                  bias=config.bias,
230
                                                  skip_bias_add=True,
231
                                                  quant_config=quant_config)
232
        self.act = get_act_fn("gelu")
Zhuohan Li's avatar
Zhuohan Li committed
233
234
235
236
237
238
239
        self.reduce_row_parallel_results = not (config.new_decoder_architecture
                                                or config.parallel_attn)
        self.dense_4h_to_h = RowParallelLinear(
            4 * hidden_size,
            hidden_size,
            bias=config.bias,
            skip_bias_add=True,
240
            reduce_results=self.reduce_row_parallel_results,
241
            quant_config=quant_config)
Zhuohan Li's avatar
Zhuohan Li committed
242
243
244
245
246
247
248
249
250
251
252
253
254

    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):

255
256
257
    def __init__(
        self,
        config: FalconConfig,
258
        cache_config: Optional[CacheConfig] = None,
259
        quant_config: Optional[QuantizationConfig] = None,
260
        prefix: str = "",
261
    ):
Zhuohan Li's avatar
Zhuohan Li committed
262
263
264
        super().__init__()
        hidden_size = config.hidden_size
        self.num_heads = config.num_attention_heads
265
266
267
268
269
        self.self_attention = FalconAttention(
            config,
            cache_config,
            quant_config,
            prefix=f"{prefix}.self_attention")
270
        self.mlp = FalconMLP(config, quant_config)
Zhuohan Li's avatar
Zhuohan Li committed
271
272
        self.config = config

zhuwenwen's avatar
zhuwenwen committed
273
274
        if (not hasattr(config, "num_ln_in_parallel_attn")):
            config.num_ln_in_parallel_attn = None
275

276
277
278
279
280
281
282
        if (config.num_ln_in_parallel_attn is None
                and config.new_decoder_architecture):
            config.num_ln_in_parallel_attn = 2

        if not config.parallel_attn:
            self.post_attention_layernorm = LayerNorm(
                hidden_size, eps=config.layer_norm_epsilon)
Zhuohan Li's avatar
Zhuohan Li committed
283
284
            self.input_layernorm = LayerNorm(hidden_size,
                                             eps=config.layer_norm_epsilon)
285
286
287
288
289
290
291
292
293
294
295
        else:
            if config.num_ln_in_parallel_attn == 2:
                # The layer norm before self-attention
                self.ln_attn = LayerNorm(hidden_size,
                                         eps=config.layer_norm_epsilon)
                # The layer norm before the MLP
                self.ln_mlp = LayerNorm(hidden_size,
                                        eps=config.layer_norm_epsilon)
            else:
                self.input_layernorm = LayerNorm(hidden_size,
                                                 eps=config.layer_norm_epsilon)
Zhuohan Li's avatar
Zhuohan Li committed
296
297
298
299
300
301
302
303

        self.reduce_row_parallel_results = not (config.new_decoder_architecture
                                                or config.parallel_attn)

    def forward(
        self,
        positions: torch.Tensor,
        hidden_states: torch.Tensor,
304
305
        kv_cache: torch.Tensor,
        attn_metadata: AttentionMetadata,
306
    ) -> torch.Tensor:
Zhuohan Li's avatar
Zhuohan Li committed
307
308
        residual = hidden_states

309
        if self.config.num_ln_in_parallel_attn == 2:
Zhuohan Li's avatar
Zhuohan Li committed
310
311
312
313
314
315
316
317
318
319
            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,
            kv_cache=kv_cache,
320
            attn_metadata=attn_metadata,
Zhuohan Li's avatar
Zhuohan Li committed
321
322
323
324
325
326
327
328
329
330
331
        )
        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)

332
333
334
335
        if (self.config.new_decoder_architecture and self.config.parallel_attn
                and self.config.num_ln_in_parallel_attn == 1):
            mlp_layernorm_out = attention_layernorm_out

Zhuohan Li's avatar
Zhuohan Li committed
336
337
338
339
340
341
342
343
344
345
        # 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
346
            mlp_output = tensor_model_parallel_all_reduce(mlp_output)
Zhuohan Li's avatar
Zhuohan Li committed
347
348
349
350
351
352
353
354
355
            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


356
@support_torch_compile
Zhuohan Li's avatar
Zhuohan Li committed
357
358
class FalconModel(nn.Module):

359
    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
Zhuohan Li's avatar
Zhuohan Li committed
360
        super().__init__()
361
362
363
364
365

        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
366
367
368
369
370
371
372
        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(
373
374
375
            config.vocab_size,
            self.embed_dim,
        )
Zhuohan Li's avatar
Zhuohan Li committed
376
377

        # Transformer blocks
378
379
        self.start_layer, self.end_layer, self.h = make_layers(
            config.num_hidden_layers,
380
381
            lambda prefix: FalconDecoderLayer(
                config, cache_config, quant_config, prefix=prefix),
382
            prefix=f"{prefix}.h")
Zhuohan Li's avatar
Zhuohan Li committed
383
384
385

        # Final Layer Norm
        self.ln_f = LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
386
387
388
        self.make_empty_intermediate_tensors = (
            make_empty_intermediate_tensors_factory(["hidden_states"],
                                                    config.hidden_size))
Zhuohan Li's avatar
Zhuohan Li committed
389

390
391
    def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
        return self.word_embeddings(input_ids)
Zhuohan Li's avatar
Zhuohan Li committed
392
393
394

    def forward(
        self,
395
        input_ids: torch.Tensor,
Zhuohan Li's avatar
Zhuohan Li committed
396
        positions: torch.Tensor,
397
398
        kv_caches: List[torch.Tensor],
        attn_metadata: AttentionMetadata,
399
        intermediate_tensors: Optional[IntermediateTensors],
400
        inputs_embeds: Optional[torch.Tensor] = None,
401
402
    ) -> Union[torch.Tensor, IntermediateTensors]:
        if get_pp_group().is_first_rank:
403
404
405
406
            if inputs_embeds is not None:
                hidden_states = inputs_embeds
            else:
                hidden_states = self.get_input_embeddings(input_ids)
407
408
409
        else:
            hidden_states = intermediate_tensors["hidden_states"]
        for i in range(self.start_layer, self.end_layer):
Zhuohan Li's avatar
Zhuohan Li committed
410
411
412
413
            layer = self.h[i]
            hidden_states = layer(
                positions,
                hidden_states,
414
                kv_caches[i - self.start_layer],
415
                attn_metadata,
Zhuohan Li's avatar
Zhuohan Li committed
416
            )
417
418
        if not get_pp_group().is_last_rank:
            return IntermediateTensors({"hidden_states": hidden_states})
Zhuohan Li's avatar
Zhuohan Li committed
419
420
421
422
        hidden_states = self.ln_f(hidden_states)
        return hidden_states


423
class FalconForCausalLM(nn.Module, SupportsPP):
Zhuohan Li's avatar
Zhuohan Li committed
424

425
426
427
    # BitandBytes specific attributes
    bitsandbytes_stacked_params_mapping = {}

428
    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
Zhuohan Li's avatar
Zhuohan Li committed
429
        super().__init__()
430
431
        config = vllm_config.model_config.hf_config
        quant_config = vllm_config.quant_config
Zhuohan Li's avatar
Zhuohan Li committed
432
        self.config = config
433
        self.quant_config = quant_config
434
435
436
        self.transformer = FalconModel(vllm_config=vllm_config,
                                       prefix=maybe_prefix(
                                           prefix, "transformer"))
437
438
439
440
441
442
443
        # 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
        self.tie_word_embeddings = (config.tie_word_embeddings
                                    if config.tie_word_embeddings is not None
                                    else True)
        if self.tie_word_embeddings:
444
            self.lm_head = self.transformer.word_embeddings
445
446
447
448
        else:
            self.lm_head = ParallelLMHead(
                config.vocab_size,
                config.hidden_size,
449
                quant_config=quant_config,
450
            )
451
        self.logits_processor = LogitsProcessor(config.vocab_size)
Joe Runde's avatar
Joe Runde committed
452
        self.sampler = get_sampler()
453
454
        self.make_empty_intermediate_tensors = (
            self.transformer.make_empty_intermediate_tensors)
zhuwenwen's avatar
zhuwenwen committed
455
456
457
458
459
460
461
462
463
464
        
        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'
zhuwenwen's avatar
zhuwenwen committed
465
        self.w8a8_strategy=int(os.getenv('W8A8_SUPPORT_METHODS', '1'))
Zhuohan Li's avatar
Zhuohan Li committed
466

467
468
469
    def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
        return self.transformer.get_input_embeddings(input_ids)

Zhuohan Li's avatar
Zhuohan Li committed
470
471
472
473
    def forward(
        self,
        input_ids: torch.LongTensor,
        positions: torch.Tensor,
474
475
        kv_caches: List[torch.Tensor],
        attn_metadata: AttentionMetadata,
476
        intermediate_tensors: Optional[IntermediateTensors] = None,
477
        inputs_embeds: Optional[torch.Tensor] = None,
478
    ) -> torch.Tensor:
479
        hidden_states = self.transformer(input_ids, positions, kv_caches,
480
481
                                         attn_metadata, intermediate_tensors,
                                         inputs_embeds)
482
        return hidden_states
Zhuohan Li's avatar
Zhuohan Li committed
483

484
485
486
487
488
    def compute_logits(
        self,
        hidden_states: torch.Tensor,
        sampling_metadata: SamplingMetadata,
    ) -> Optional[torch.Tensor]:
489
        logits = self.logits_processor(self.lm_head, hidden_states,
490
491
492
                                       sampling_metadata)
        return logits

493
494
    def sample(
        self,
495
        logits: torch.Tensor,
496
        sampling_metadata: SamplingMetadata,
497
    ) -> Optional[SamplerOutput]:
498
        next_tokens = self.sampler(logits, sampling_metadata)
Zhuohan Li's avatar
Zhuohan Li committed
499
500
        return next_tokens

501
502
    def load_weights(self, weights: Iterable[Tuple[str,
                                                   torch.Tensor]]) -> Set[str]:
Zhuohan Li's avatar
Zhuohan Li committed
503
504
505
506
507
508
509
510
        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
511
        params_dict = dict(self.named_parameters(remove_duplicate=False))
512
        loaded_params: Set[str] = set()
513
        for name, loaded_weight in weights:
514
515
            if name == "lm_head.weight" and self.tie_word_embeddings:
                # Falcon uses tied embeddings except Falcon-11b.
516
                continue
CHU Tianxiang's avatar
CHU Tianxiang committed
517
518
519
            # Skip loading extra bias for GPTQ models.
            if name.endswith(".bias") and name not in params_dict:
                continue
520
521
            if is_pp_missing_parameter(name, self):
                continue
522
            param = params_dict[name]
Zhuohan Li's avatar
Zhuohan Li committed
523
            if "query_key_value" in name:
524
525
                output_dim = getattr(param, "output_dim", None)
                loaded_weight_shape = loaded_weight.shape
CHU Tianxiang's avatar
CHU Tianxiang committed
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
                if output_dim is not None:
                    loaded_weight = loaded_weight.view(
                        loaded_weight_shape[:output_dim] +
                        (total_num_kv_heads, num_query_heads_per_kv_head + 2,
                         -1) + loaded_weight_shape[output_dim + 1:])
                    wq = loaded_weight.narrow(
                        output_dim + 1, 0,
                        num_query_heads_per_kv_head).reshape(
                            *loaded_weight_shape[:output_dim], -1,
                            *loaded_weight_shape[output_dim + 1:])
                    wk = loaded_weight.narrow(
                        output_dim + 1, num_query_heads_per_kv_head,
                        1).reshape(*loaded_weight_shape[:output_dim], -1,
                                   *loaded_weight_shape[output_dim + 1:])
                    wv = loaded_weight.narrow(
                        output_dim + 1, num_query_heads_per_kv_head + 1,
                        1).reshape(*loaded_weight_shape[:output_dim], -1,
                                   *loaded_weight_shape[output_dim + 1:])
                    loaded_weight = torch.cat([wq, wk, wv], dim=output_dim)
545
546
547
548

            weight_loader = getattr(param, "weight_loader",
                                    default_weight_loader)
            weight_loader(param, loaded_weight)
549
            loaded_params.add(name)
zhuwenwen's avatar
zhuwenwen committed
550
            
zhuwenwen's avatar
zhuwenwen committed
551
552
553
554
555
556
557
558
559
        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
560
561
            # lay_qkv_words = ["self_attention.query_key_value.weight"]   
            # qkv_words = "|".join(lay_qkv_words)          
zhuwenwen's avatar
zhuwenwen committed
562
563
564
565
            
            for layername, weight in params_dict.items():
                matches = re.findall(combined_words, layername)
                if matches:         
zhuwenwen's avatar
zhuwenwen committed
566
567
                    # 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
568
                        
zhuwenwen's avatar
zhuwenwen committed
569
570
571
                    # 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
572
573
574
575
576
577
578
                                 
                    _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
579
580
                    weight.data=weight.data.reshape(ori_shape[1], -1)
                    
581
        return loaded_params
zhuwenwen's avatar
zhuwenwen committed
582
583
584