baichuan.py 4.83 KB
Newer Older
codethazine's avatar
codethazine committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# coding=utf-8
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
#
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
# and OPT implementations in this library. It has been modified from its
# original forms to accommodate minor architectural differences compared
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
#
# 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.
Woosuk Kwon's avatar
Woosuk Kwon committed
20
"""Inference-only BaiChuan model compatible with HuggingFace weights."""
Roy's avatar
Roy committed
21
from typing import Optional
codethazine's avatar
codethazine committed
22
23

import torch
Roy's avatar
Roy committed
24
25
from transformers import PretrainedConfig
from vllm.config import LoRAConfig
codethazine's avatar
codethazine committed
26

Roy's avatar
Roy committed
27
28
from vllm.model_executor.layers.linear import LinearMethodBase
from vllm.model_executor.models.llama import LlamaForCausalLM
29
30
from vllm.model_executor.weight_utils import (default_weight_loader,
                                              hf_model_weights_iterator)
codethazine's avatar
codethazine committed
31
32


Roy's avatar
Roy committed
33
class BaiChuanBaseForCausalLM(LlamaForCausalLM):
codethazine's avatar
codethazine committed
34
35
36
37

    def load_weights(self,
                     model_name_or_path: str,
                     cache_dir: Optional[str] = None,
Jasmond L's avatar
Jasmond L committed
38
39
                     load_format: str = "auto",
                     revision: Optional[str] = None):
40
41
42
43
44
        stacked_params_mapping = [
            # (param_name, shard_name, shard_id)
            ("gate_up_proj", "gate_proj", 0),
            ("gate_up_proj", "up_proj", 1),
        ]
Roy's avatar
Roy committed
45
46
47
        param_weight_map = [
            ("qkv_proj", "W_pack"),
        ]
48
        params_dict = dict(self.named_parameters())
codethazine's avatar
codethazine committed
49
        for name, loaded_weight in hf_model_weights_iterator(
Jasmond L's avatar
Jasmond L committed
50
                model_name_or_path, cache_dir, load_format, revision):
Roy's avatar
Roy committed
51
52
53
            for (param_name, weight_name) in param_weight_map:
                name = name.replace(weight_name, param_name)

codethazine's avatar
codethazine committed
54
55
            if "rotary_emb.inv_freq" in name:
                continue
56
57
58
59
60
61
62
63
64
65
66
            if name == "lm_head.weight":
                # Unlike Baichuan, Baichuan2 normalizes the head weights. Refer to:
                # https://huggingface.co/baichuan-inc/Baichuan2-7B-Chat/blob/84603cde5ebffb6084e476cfaeceaf0b8b91fe54/modeling_baichuan.py#L508
                # Distinguish between Baichuan and Baichuan2 by checking the
                # vocab size. This is suggested by
                # https://github.com/vllm-project/vllm/pull/1022#discussion_r1325652704
                is_baichuan2 = self.config.vocab_size == 125696
                if is_baichuan2:
                    loaded_weight = torch.nn.functional.normalize(
                        loaded_weight)

67
            for (param_name, weight_name, shard_id) in stacked_params_mapping:
codethazine's avatar
codethazine committed
68
69
                if weight_name not in name:
                    continue
CHU Tianxiang's avatar
CHU Tianxiang committed
70
71
72
73
74
                name = name.replace(weight_name, param_name)
                # Skip loading extra bias for GPTQ models.
                if name.endswith(".bias") and name not in params_dict:
                    continue
                param = params_dict[name]
75
76
                weight_loader = param.weight_loader
                weight_loader(param, loaded_weight, shard_id)
codethazine's avatar
codethazine committed
77
                break
78
            else:
CHU Tianxiang's avatar
CHU Tianxiang committed
79
80
81
                # Skip loading extra bias for GPTQ models.
                if name.endswith(".bias") and name not in params_dict:
                    continue
82
83
84
85
                param = params_dict[name]
                weight_loader = getattr(param, "weight_loader",
                                        default_weight_loader)
                weight_loader(param, loaded_weight)
86
87


88
89
class BaichuanForCausalLM(BaiChuanBaseForCausalLM):
    """Baichuan 13B and Baichuan2 7B/13B."""
90

Roy's avatar
Roy committed
91
92
93
94
95
96
97
98
99
100
101
    def __init__(
        self,
        config: Optional[PretrainedConfig] = None,
        linear_method: Optional[LinearMethodBase] = None,
        lora_config: Optional[LoRAConfig] = None,
    ) -> None:
        if config.hidden_size != 4096:  # baichuan 13b, baichuan2 13b
            config.postion_embedding = "ALIBI"
        super().__init__(config=config,
                         linear_method=linear_method,
                         lora_config=lora_config)
102
103


104
105
class BaiChuanForCausalLM(BaiChuanBaseForCausalLM):
    """Baichuan 7B."""
106

Roy's avatar
Roy committed
107
108
109
110
111
112
113
114
115
    def __init__(
        self,
        config: Optional[PretrainedConfig] = None,
        linear_method: Optional[LinearMethodBase] = None,
        lora_config: Optional[LoRAConfig] = None,
    ) -> None:
        super().__init__(config=config,
                         linear_method=linear_method,
                         lora_config=lora_config)