utils.py 4.44 KB
Newer Older
1
2
"""Utilities for selecting and loading models."""
import contextlib
3
4
from dataclasses import dataclass, field
from typing import Dict, List, Tuple, Type
5

zhuwenwen's avatar
zhuwenwen committed
6
import os
7
8
9
10
11
import torch
from torch import nn

from vllm.config import ModelConfig
from vllm.model_executor.models import ModelRegistry
12
13
14
from vllm.model_executor.models.adapters import (as_classification_model,
                                                 as_embedding_model,
                                                 as_reward_model)
15
16
17
18
19
20
21
22
23
24
25
26
27
28


@contextlib.contextmanager
def set_default_torch_dtype(dtype: torch.dtype):
    """Sets the default torch dtype to the given dtype."""
    old_dtype = torch.get_default_dtype()
    torch.set_default_dtype(dtype)
    yield
    torch.set_default_dtype(old_dtype)


def get_model_architecture(
        model_config: ModelConfig) -> Tuple[Type[nn.Module], str]:
    architectures = getattr(model_config.hf_config, "architectures", [])
zhuwenwen's avatar
zhuwenwen committed
29
    visions = getattr(model_config.hf_config, "visual", []) or getattr(model_config.hf_config, "vision_config", [])
zhuwenwen's avatar
zhuwenwen committed
30
    # 'Qwen2VLForConditionalGeneration'
zhuwenwen's avatar
zhuwenwen committed
31
32
    support_nn_architectures = ['LlamaForCausalLM', 'QWenLMHeadModel', 'Qwen2ForCausalLM', 'Qwen2MoeForCausalLM', 'ChatGLMModel', 'ChatGLMForConditionalGeneration', 
                                'BaichuanForCausalLM', 'BloomForCausalLM', 'MedusaModel', 'MixtralForCausalLM', 'MLPSpeculatorPreTrainedModel', 'FalconForCausalLM', 'DeepseekV3ForCausalLM']  
33
    if any(arch in architectures for arch in support_nn_architectures): 
zhuwenwen's avatar
zhuwenwen committed
34
        if os.getenv('LLAMA_NN') != '0': 
zhuwenwen's avatar
zhuwenwen committed
35
             if (architectures == ['QWenLMHeadModel'] or architectures == ['ChatGLMModel'] ) and visions != []:
zhuwenwen's avatar
zhuwenwen committed
36
37
38
                os.environ['LLAMA_NN'] = '0'
             else:
                os.environ['LLAMA_NN'] = '1'
zhuwenwen's avatar
zhuwenwen committed
39
        if (architectures == ['BloomForCausalLM'] or architectures == ['FalconForCausalLM']) or os.getenv('LM_NN') == '0':
zhuwenwen's avatar
zhuwenwen committed
40
            os.environ['LM_NN'] = '0'
zhuwenwen's avatar
zhuwenwen committed
41
        else:
zhuwenwen's avatar
zhuwenwen committed
42
            os.environ['LM_NN'] = '1'
43
44
        if os.getenv('GEMM_PAD') != '1': 
            os.environ['GEMM_PAD'] = '0'
zhuwenwen's avatar
zhuwenwen committed
45
46
        if os.getenv('FA_PAD') != '1': 
            os.environ['FA_PAD'] = '0'
zhuwenwen's avatar
zhuwenwen committed
47
48
49
50
51
52
53
54
55
56
        try:
            if os.getenv('AWQ_PAD') == '0' or ((torch.cuda.isCurrentDeviceEco(torch.cuda.current_device())) and os.getenv('AWQ_PAD') == None):
                os.environ['AWQ_PAD'] = '0'
            else:
                os.environ['AWQ_PAD'] = '1'
        except Exception as e:
            if os.getenv('AWQ_PAD') != '0': 
                os.environ['AWQ_PAD'] = '1'
            else:
                os.environ['AWQ_PAD'] = '0'
zhuwenwen's avatar
zhuwenwen committed
57
58
    else:
        os.environ['LLAMA_NN'] = '0'
zhuwenwen's avatar
zhuwenwen committed
59
        os.environ['LM_NN'] = '0'
60
61
        os.environ['GEMM_PAD'] = '0'
        os.environ['FA_PAD'] = '0'
zhuwenwen's avatar
zhuwenwen committed
62
        os.environ['AWQ_PAD'] = '0'
63
        
64
65
    # Special handling for quantized Mixtral.
    # FIXME(woosuk): This is a temporary hack.
66
67
68
    mixtral_supported = [
        "fp8", "compressed-tensors", "gptq_marlin", "awq_marlin"
    ]
69

70
    if (model_config.quantization is not None
71
            and model_config.quantization not in mixtral_supported
72
73
            and "MixtralForCausalLM" in architectures):
        architectures = ["QuantMixtralForCausalLM"]
74

75
    model_cls, arch = ModelRegistry.resolve_model_cls(architectures)
76
    if model_config.task == "embed":
77
        model_cls = as_embedding_model(model_cls)
78
79
80
81
    elif model_config.task == "classify":
        model_cls = as_classification_model(model_cls)
    elif model_config.task == "reward":
        model_cls = as_reward_model(model_cls)
82
83

    return model_cls, arch
84
85
86
87


def get_architecture_class_name(model_config: ModelConfig) -> str:
    return get_model_architecture(model_config)[1]
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110


@dataclass
class ParamMapping:
    """
    A class to handle parameter mapping for model weight loading.
    It creates a bidirectional mapping between packed parameters and their 
    constituent parts.
    """
    packed_mapping: Dict[str, List[str]]
    inverse_packed_mapping: Dict[str, Tuple[str,
                                            int]] = field(default_factory=dict)

    def __post_init__(self):
        for packed_name, sub_params in self.packed_mapping.items():
            # Skip self-contained cases (e.g., {"W_pack": ["W_pack"]})
            if len(sub_params) == 1 and sub_params[0] == packed_name:
                continue
            for index, param_name in enumerate(sub_params):
                self.inverse_packed_mapping[param_name] = (
                    packed_name,
                    index,
                )