"docs/vscode:/vscode.git/clone" did not exist on "a776a48b1c753645c547b735ab647867c98a9b0c"
dbrx.py 17 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

4
from collections.abc import Iterable
5
from itertools import islice
6
7
8

import torch
import torch.nn as nn
9
from transformers import DbrxConfig
10

11
from vllm.config import CacheConfig, VllmConfig
12
13
14
15
16
from vllm.distributed import (
    get_pp_group,
    get_tensor_model_parallel_rank,
    get_tensor_model_parallel_world_size,
)
17
from vllm.model_executor.layers.attention import Attention
18
from vllm.model_executor.layers.fused_moe import FusedMoE
19
20
21
22
23
from vllm.model_executor.layers.linear import (
    QKVParallelLinear,
    ReplicatedLinear,
    RowParallelLinear,
)
24
from vllm.model_executor.layers.logits_processor import LogitsProcessor
25
from vllm.model_executor.layers.quantization import QuantizationConfig
26
27
from vllm.model_executor.layers.rotary_embedding import get_rope
from vllm.model_executor.layers.vocab_parallel_embedding import (
28
29
30
    ParallelLMHead,
    VocabParallelEmbedding,
)
31
from vllm.model_executor.model_loader.weight_utils import (
32
33
34
    default_weight_loader,
    maybe_remap_kv_scale_name,
)
35
from vllm.sequence import IntermediateTensors
36

37
from .interfaces import SupportsPP
38
39
40
41
42
43
44
from .utils import (
    AutoWeightsLoader,
    is_pp_missing_parameter,
    make_empty_intermediate_tensors_factory,
    make_layers,
    maybe_prefix,
)
45

46
47
48
49
50
51
52
53

class DbrxRouter(nn.Module):
    """A Router implementation for DBRX that returns logits for each expert
    per token.
    """

    def __init__(
        self,
54
        config: DbrxConfig,
55
        params_dtype: torch.dtype | None = None,
56
57
58
59
60
61
62
63
64
65
    ):
        super().__init__()
        self.tp_size = get_tensor_model_parallel_world_size()
        self.num_total_experts = config.ffn_config.moe_num_experts
        self.d_model = config.d_model
        self.layer = ReplicatedLinear(
            self.d_model,
            self.num_total_experts,
            bias=False,
            params_dtype=params_dtype,
66
            quant_config=None,
67
68
69
70
71
72
73
        )

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        router_logits, _ = self.layer(hidden_states)
        return router_logits


74
class DbrxExperts(FusedMoE):
75
76
    def __init__(
        self,
77
        config: DbrxConfig,
78
79
        quant_config: QuantizationConfig | None = None,
        params_dtype: torch.dtype | None = None,
80
        prefix: str = "",
81
    ):
82
83
84
85
86
87
88
89
90
91
        super().__init__(
            num_experts=config.ffn_config.moe_num_experts,
            top_k=config.ffn_config.moe_top_k,
            hidden_size=config.d_model,
            intermediate_size=config.ffn_config.ffn_hidden_size,
            params_dtype=params_dtype,
            reduce_results=True,
            renormalize=True,
            quant_config=quant_config,
            tp_size=get_tensor_model_parallel_world_size(),
92
            prefix=prefix,
93
94
        )
        self.config = config
95
        self.d_model = config.d_model
96
        self.intermediate_size = self.config.ffn_config.ffn_hidden_size // self.tp_size
97

98
    # Define custom weight loader for dbrx model
99
100
101
102
103
104
105
    def weight_loader(
        self,
        param: nn.Parameter,
        loaded_weight: torch.Tensor,
        weight_name: str,
        param_name: str,
    ):
106
107
108
109
110
111
112
        tp_rank = get_tensor_model_parallel_rank()
        param_data = param.data
        shard_size = self.intermediate_size
        shard = slice(tp_rank * shard_size, (tp_rank + 1) * shard_size)
        # DBRX uses GLU for each experts.
        # GLU has 3 linear layers: w1, v1 and w2.
        if weight_name.endswith("w1"):
113
114
115
116
117
118
119
120
121
122
            if param_name.endswith("weight"):
                loaded_weight = torch.reshape(
                    loaded_weight,
                    [-1, self.intermediate_size * self.tp_size, self.d_model],
                )
                param_data[:, 0:shard_size, :] = loaded_weight[:, shard, :]
            elif param_name.endswith("weight_scale"):
                param_data[:, 0] = loaded_weight
            else:
                param_data = loaded_weight
123
        if weight_name.endswith("v1"):
124
125
126
127
128
            if param_name.endswith("weight"):
                loaded_weight = torch.reshape(
                    loaded_weight,
                    [-1, self.intermediate_size * self.tp_size, self.d_model],
                )
129
130
131
                param_data[:, shard_size : 2 * shard_size, :] = loaded_weight[
                    :, shard, :
                ]
132
133
134
135
            elif param_name.endswith("weight_scale"):
                param_data[:, 1] = loaded_weight
            else:
                param_data[:] = loaded_weight
136
        if weight_name.endswith("w2"):
137
138
139
140
141
142
143
144
            if param_name.endswith("weight"):
                loaded_weight = torch.reshape(
                    loaded_weight,
                    [-1, self.intermediate_size * self.tp_size, self.d_model],
                ).transpose(1, 2)
                param_data[:] = loaded_weight[:, :, shard]
            else:
                param_data[:] = loaded_weight
145

146
147
148
149
150
151
152
153
154
155
156

class DbrxMoE(nn.Module):
    """A tensor-parallel MoE implementation for DBRX.

    Each expert's weights are sharded across all ranks and a fused MoE
    kernel is used for the forward pass, and finally we reduce the outputs
    across ranks.
    """

    def __init__(
        self,
157
        config: DbrxConfig,
158
159
        quant_config: QuantizationConfig | None = None,
        params_dtype: torch.dtype | None = None,
160
        prefix: str = "",
161
162
163
164
165
166
167
168
169
    ):
        super().__init__()
        self.d_model = config.d_model
        if params_dtype is None:
            params_dtype = torch.get_default_dtype()
        self.params_dtype = params_dtype

        self.router = DbrxRouter(config, self.params_dtype)

170
171
172
173
174
175
        self.experts = DbrxExperts(
            config=config,
            quant_config=quant_config,
            params_dtype=self.params_dtype,
            prefix=f"{prefix}.experts",
        )
176

177
    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
178
        orig_shape = hidden_states.shape
179
180
181
        hidden_states = hidden_states.view(-1, self.d_model)
        # router_logits: (num_tokens, n_experts)
        router_logits = self.router(hidden_states)
182
183
        final_hidden_states = self.experts(hidden_states, router_logits)
        return final_hidden_states.view(orig_shape)
184
185
186
187
188


class DbrxAttention(nn.Module):
    def __init__(
        self,
189
        config: DbrxConfig,
190
191
        cache_config: CacheConfig | None = None,
        quant_config: QuantizationConfig | None = None,
192
        prefix: str = "",
193
194
195
196
197
198
199
    ):
        super().__init__()
        self.d_model = config.d_model
        self.total_num_heads = config.n_heads
        self.head_dim = self.d_model // self.total_num_heads
        self.total_num_kv_heads = config.attn_config.kv_n_heads
        self.clip_qkv = config.attn_config.clip_qkv
200
201
202
203
        rope_parameters = {
            "rope_type": "default",
            "rope_theta": int(config.attn_config.rope_theta),
        }
204
205
206
207
208
209
210
211
212
        self.max_position = config.max_seq_len

        # pylint: disable=invalid-name
        self.Wqkv = QKVParallelLinear(
            self.d_model,
            self.head_dim,
            self.total_num_heads,
            self.total_num_kv_heads,
            bias=False,
213
            quant_config=quant_config,
214
            prefix=f"{prefix}.Wqkv",
215
216
217
218
219
        )
        self.out_proj = RowParallelLinear(
            self.d_model,
            self.d_model,
            bias=False,
220
            quant_config=quant_config,
221
            prefix=f"{prefix}.out_proj",
222
223
224
225
        )
        self.rotary_emb = get_rope(
            self.head_dim,
            max_position=self.max_position,
226
            rope_parameters=rope_parameters,
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
            is_neox_style=True,
        )

        tp_world_size = get_tensor_model_parallel_world_size()
        self.tp_size = tp_world_size
        assert self.total_num_heads % tp_world_size == 0
        self.num_heads = self.total_num_heads // tp_world_size
        if self.total_num_kv_heads >= tp_world_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_world_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_world_size % self.total_num_kv_heads == 0
        self.num_kv_heads = max(1, self.total_num_kv_heads // tp_world_size)
        self.q_size = self.num_heads * self.head_dim
        self.kv_size = self.num_kv_heads * self.head_dim
        self.scaling = self.head_dim**-0.5
246
247
248
249
250
251
252
253
254
        self.attn = Attention(
            self.num_heads,
            self.head_dim,
            self.scaling,
            num_kv_heads=self.num_kv_heads,
            cache_config=cache_config,
            quant_config=quant_config,
            prefix=f"{prefix}.attn",
        )
255
256
257
258
259
260
261
262
263
264
265

    def forward(
        self,
        position_ids: torch.Tensor,
        hidden_states: torch.Tensor,
    ) -> torch.Tensor:
        qkv, _ = self.Wqkv(hidden_states)
        if self.clip_qkv is not None:
            qkv.clamp_(min=-self.clip_qkv, max=self.clip_qkv)
        q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
        q, k = self.rotary_emb(position_ids, q, k)
266
        attn_output = self.attn(q, k, v)
267
268
269
270
271
272
273
        hidden_states, _ = self.out_proj(attn_output)
        return hidden_states


class DbrxFusedNormAttention(nn.Module):
    def __init__(
        self,
274
        config: DbrxConfig,
275
276
        cache_config: CacheConfig | None = None,
        quant_config: QuantizationConfig | None = None,
277
        prefix: str = "",
278
279
280
    ):
        super().__init__()
        self.d_model = config.d_model
281
282
283
        self.attn = DbrxAttention(
            config, cache_config, quant_config, prefix=f"{prefix}.attn"
        )
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
        self.norm_1 = nn.LayerNorm(self.d_model)
        self.norm_2 = nn.LayerNorm(self.d_model)

    def forward(
        self,
        position_ids: torch.Tensor,
        hidden_states: torch.Tensor,
    ) -> torch.Tensor:
        residual = hidden_states
        hidden_states = self.norm_1(hidden_states)
        x = self.attn(
            position_ids=position_ids,
            hidden_states=hidden_states,
        )
        hidden_states = residual + x
        residual = hidden_states
        hidden_states = self.norm_2(hidden_states)
        return hidden_states, residual


class DbrxBlock(nn.Module):
    def __init__(
        self,
307
        config: DbrxConfig,
308
309
        cache_config: CacheConfig | None = None,
        quant_config: QuantizationConfig | None = None,
310
        prefix: str = "",
311
312
    ):
        super().__init__()
313
        self.norm_attn_norm = DbrxFusedNormAttention(
314
315
            config, cache_config, quant_config, prefix=f"{prefix}.norm_attn_norm"
        )
316
        self.ffn = DbrxMoE(config, quant_config, prefix=f"{prefix}.ffn")
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332

    def forward(
        self,
        position_ids: torch.Tensor,
        hidden_states: torch.Tensor,
    ) -> torch.Tensor:
        hidden_states, residual = self.norm_attn_norm(
            position_ids=position_ids,
            hidden_states=hidden_states,
        )
        hidden_states = self.ffn(hidden_states)
        hidden_states = hidden_states + residual
        return hidden_states


class DbrxModel(nn.Module):
333
    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
334
        super().__init__()
335
336
337
338
339

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

340
        self.quant_config = quant_config
341
342
343
344
        self.wte = VocabParallelEmbedding(
            config.vocab_size,
            config.d_model,
        )
345
346
        self.start_layer, self.end_layer, self.blocks = make_layers(
            config.n_layers,
347
            lambda prefix: DbrxBlock(config, cache_config, quant_config, prefix=prefix),
348
349
            prefix=f"{prefix}.blocks",
        )
350
351
        self.norm_f = nn.LayerNorm(config.d_model, eps=1e-5)
        for module in self.modules():
352
            if hasattr(module, "bias") and isinstance(module.bias, nn.Parameter):
353
354
                # Remove the bias term in Linear and LayerNorm.
                module.register_parameter("bias", None)
355
356
357
        self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory(
            ["hidden_states"], config.d_model
        )
358

359
    def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
360
361
        return self.wte(input_ids)

362
363
    def forward(
        self,
zhuwenwen's avatar
zhuwenwen committed
364
        input_ids: torch.Tensor | None,
365
        position_ids: torch.Tensor,
366
367
368
        intermediate_tensors: IntermediateTensors | None,
        inputs_embeds: torch.Tensor | None = None,
    ) -> torch.Tensor | IntermediateTensors:
369
        if get_pp_group().is_first_rank:
370
371
372
            if inputs_embeds is not None:
                hidden_states = inputs_embeds
            else:
373
                hidden_states = self.embed_input_ids(input_ids)
374
375
376
        else:
            assert intermediate_tensors
            hidden_states = intermediate_tensors["hidden_states"]
377
        for block in islice(self.blocks, self.start_layer, self.end_layer):
378
            hidden_states = block(position_ids, hidden_states)
379
380
        if not get_pp_group().is_last_rank:
            return IntermediateTensors({"hidden_states": hidden_states})
381
382
383
        hidden_states = self.norm_f(hidden_states)
        return hidden_states

384
385
386
387
388
389
390
391
    def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
        expert_params_mapping = [
            (
                "w13" if weight_name in ["w1", "v1"] else "w2",
                f"mlp.{weight_name}",
            )
            for weight_name in ["w1", "v1", "w2"]
        ]
392
393
394
395
        params_dict = dict(self.named_parameters(remove_duplicate=False))
        loaded_params: set[str] = set()

        for name, loaded_weight in weights:
396
397
398
            if self.quant_config is not None and (
                scale_name := self.quant_config.get_cache_scale(name)
            ):
399
400
                # Loading kv cache quantization scales
                param = params_dict[scale_name]
401
402
403
404
                weight_loader = getattr(param, "weight_loader", default_weight_loader)
                loaded_weight = (
                    loaded_weight if loaded_weight.dim() == 0 else loaded_weight[0]
                )
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
                weight_loader(param, loaded_weight)
                loaded_params.add(scale_name)
                continue

            if name.endswith(("w1", "w2", "v1")):
                name = name + "_weight"
            for param_name, weight_name in expert_params_mapping:
                if weight_name not in name:
                    continue
                name = name.replace(weight_name, param_name)
                if is_pp_missing_parameter(name, self):
                    continue
                param = params_dict[name]
                weight_loader = param.weight_loader
                weight_loader(param, loaded_weight, weight_name, name)
                break

            else:
                if is_pp_missing_parameter(name, self):
                    continue
                # Remapping the name of FP8 kv-scale.
                name = maybe_remap_kv_scale_name(name, params_dict)
                if name is None:
                    continue
                param = params_dict[name]
430
                weight_loader = getattr(param, "weight_loader", default_weight_loader)
431
432
433
434
                weight_loader(param, loaded_weight)
            loaded_params.add(name)
        return loaded_params

435

436
class DbrxForCausalLM(nn.Module, SupportsPP):
437
    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
438
        super().__init__()
439
440
        config = vllm_config.model_config.hf_config
        quant_config = vllm_config.quant_config
441
        self.config = config
442
        if config.tie_word_embeddings:
443
            raise ValueError("tie_word_embeddings is not supported for Dbrx models.")
444
        self.quant_config = quant_config
445

446
447
448
        self.transformer = DbrxModel(
            vllm_config=vllm_config, prefix=maybe_prefix(prefix, "transformer")
        )
449
450
451
        self.lm_head = ParallelLMHead(
            config.vocab_size,
            config.d_model,
452
            quant_config=quant_config,
453
            prefix=maybe_prefix(prefix, "lm_head"),
454
        )
455
        self.logits_processor = LogitsProcessor(config.vocab_size)
456
        self.make_empty_intermediate_tensors = (
457
458
            self.transformer.make_empty_intermediate_tensors
        )
459

460
461
    def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
        return self.transformer.embed_input_ids(input_ids)
462

463
464
    def forward(
        self,
zhuwenwen's avatar
zhuwenwen committed
465
        input_ids: torch.Tensor | None,
466
        positions: torch.Tensor,
467
468
469
        intermediate_tensors: IntermediateTensors | None = None,
        inputs_embeds: torch.Tensor | None = None,
    ) -> torch.Tensor | IntermediateTensors:
470
471
472
        hidden_states = self.transformer(
            input_ids, positions, intermediate_tensors, inputs_embeds
        )
473
474
        return hidden_states

475
476
477
    def compute_logits(
        self,
        hidden_states: torch.Tensor,
478
    ) -> torch.Tensor | None:
479
        logits = self.logits_processor(self.lm_head, hidden_states)
480
481
        return logits

482
    def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
483
        loader = AutoWeightsLoader(self)
zhuwenwen's avatar
zhuwenwen committed
484
        return loader.load_weights(weights)