flash_llama.py 5.63 KB
Newer Older
drbh's avatar
drbh committed
1
import os
2
3
4
5
import torch
import torch.distributed

from opentelemetry import trace
6
from transformers import AutoConfig, AutoTokenizer, GenerationConfig
drbh's avatar
drbh committed
7
from typing import Optional, Tuple, Dict, List
8
9
10
11
12
13
14
15

from text_generation_server.models import FlashCausalLM
from text_generation_server.models.custom_modeling.flash_llama_modeling import (
    FlashLlamaForCausalLM,
)
from text_generation_server.utils import (
    initialize_torch_distributed,
    weight_files,
16
    Weights,
drbh's avatar
drbh committed
17
    hub,
18
19
20
21
)

tracer = trace.get_tracer(__name__)

Nicolas Patry's avatar
Nicolas Patry committed
22
from text_generation_server.utils.import_utils import SYSTEM
23

drbh's avatar
drbh committed
24
25
26
27
28
29
30
31
32
33
34
ADAPTER_LAYERS = [
    "q_proj",
    "k_proj",
    "v_proj",
    "o_proj",
    "gate_proj",
    "up_proj",
    "down_proj",
]
ROW_PARALLEL = {"o_proj", "down_proj", "lm_head"}

Nicolas Patry's avatar
Nicolas Patry committed
35

36
37
class FlashLlama(FlashCausalLM):
    def __init__(
38
39
40
41
        self,
        model_id: str,
        revision: Optional[str] = None,
        quantize: Optional[str] = None,
Nicolas Patry's avatar
Nicolas Patry committed
42
        speculator: Optional[str] = None,
43
        dtype: Optional[torch.dtype] = None,
44
        trust_remote_code: bool = False,
drbh's avatar
drbh committed
45
        lora_adapter_ids: Optional[list] = [],
46
    ):
47
        self.process_group, rank, world_size = initialize_torch_distributed()
48
        if torch.cuda.is_available():
49
            device = torch.device(f"cuda:{rank}")
50
            dtype = torch.float16 if dtype is None else dtype
Nicolas Patry's avatar
Nicolas Patry committed
51
52
53
        elif SYSTEM == "ipex":
            if hasattr(torch, "xpu") and torch.xpu.is_available():
                device = torch.device(f"xpu:{rank}")
Wang, Yi's avatar
Wang, Yi committed
54
                dtype = torch.float16 if dtype is None else dtype
Nicolas Patry's avatar
Nicolas Patry committed
55
56
            else:
                device = torch.device("cpu")
Wang, Yi's avatar
Wang, Yi committed
57
                dtype = torch.bfloat16 if dtype is None else dtype
58
59
60
        else:
            raise NotImplementedError("FlashLlama is only available on GPU")

61
62
63
64
65
66
67
        tokenizer = AutoTokenizer.from_pretrained(
            model_id,
            revision=revision,
            padding_side="left",
            truncation_side="left",
            trust_remote_code=trust_remote_code,
        )
68
69
70
71
72
73
74
75
76
        try:
            generation_config = GenerationConfig.from_pretrained(
                model_id, revision=revision, trust_remote_code=trust_remote_code
            )
            if isinstance(generation_config.eos_token_id, (list, set)):
                # TODO Huge hack
                tokenizer._eos_token_ids = set(generation_config.eos_token_id)
        except Exception:
            pass
77

78
        config = AutoConfig.from_pretrained(
79
            model_id, revision=revision, trust_remote_code=trust_remote_code
80
        )
81
        config.quantize = quantize
Nicolas Patry's avatar
Nicolas Patry committed
82
        config.speculator = speculator
83
84

        torch.distributed.barrier(group=self.process_group)
85

86
        filenames = weight_files(model_id, revision=revision, extension=".safetensors")
87
        weights = Weights(filenames, device, dtype, process_group=self.process_group)
88
        if config.quantize in ["awq", "exl2", "gptq", "marlin"]:
OlivierDehaene's avatar
OlivierDehaene committed
89
            weights._set_gptq_params(model_id, revision)
90

91
92
        prefix = ""
        model = FlashLlamaForCausalLM(prefix, config, weights)
93
        torch.distributed.barrier(group=self.process_group)
94
        super(FlashLlama, self).__init__(
drbh's avatar
drbh committed
95
            model_id=model_id,
96
            model=model,
97
            tokenizer=tokenizer,
98
            num_layers=len(model.model.layers),
99
            num_kv_heads=model.model.num_key_value_heads,
100
            head_size=model.model.head_size,
101
            dtype=dtype,
102
            device=device,
103
104
            rank=rank,
            world_size=world_size,
105
        )
drbh's avatar
drbh committed
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171

    @property
    def supports_adapter_loading(self) -> bool:
        return True

    def adapter_target_to_layer(self) -> Dict[str, Tuple[str, torch.Tensor]]:
        layer_weights = {}

        prefix = "model.layers"

        # This accounts for VLMs (e.g. LlavaNext, Idefics2)
        # that have a language_model inside of the larger model.
        if hasattr(self.model, "language_model"):
            _model = self.model.language_model
        elif hasattr(self.model, "text_model"):
            _model = self.model.text_model
        else:
            _model = self.model

        for i, layer in enumerate(_model.model.layers):
            layer_weights[(i, "q_proj")] = (
                f"{prefix}.{i}.self_attn.q_proj",
                layer.self_attn.query_key_value,
            )
            layer_weights[(i, "k_proj")] = (
                f"{prefix}.{i}.self_attn.k_proj",
                layer.self_attn.query_key_value,
            )
            layer_weights[(i, "v_proj")] = (
                f"{prefix}.{i}.self_attn.v_proj",
                layer.self_attn.query_key_value,
            )
            layer_weights[(i, "o_proj")] = (
                f"{prefix}.{i}.self_attn.o_proj",
                layer.self_attn.o_proj,
            )

            layer_weights[(i, "gate_proj")] = (
                f"{prefix}.{i}.mlp.gate_proj",
                layer.mlp.gate_up_proj,
            )
            layer_weights[(i, "up_proj")] = (
                f"{prefix}.{i}.mlp.up_proj",
                layer.mlp.gate_up_proj,
            )
            layer_weights[(i, "down_proj")] = (
                f"{prefix}.{i}.mlp.down_proj",
                layer.mlp.down_proj,
            )

        layer_weights[(0, "lm_head")] = ("lm_head", _model.lm_head)
        return layer_weights

    @property
    def adapter_layers(self) -> List[str]:
        return ADAPTER_LAYERS

    @property
    def default_traced_adapter_layers(self) -> List[str]:
        return ["q_proj", "v_proj"]

    def get_num_layers_for_type(self, layer_type: str) -> int:
        return 1 if layer_type == "lm_head" else len(self.model.model.layers)

    def is_row_parallel(self, layer_type: str) -> bool:
        return layer_type in ROW_PARALLEL