utils.py 4.38 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
31
    # 'Qwen2VLForConditionalGeneration'
    support_nn_architectures = ['LlamaForCausalLM', 'QWenLMHeadModel', 'Qwen2ForCausalLM', 'Qwen2MoeForCausalLM', 'ChatGLMModel', 'ChatGLMForConditionalGeneration', 'BaichuanForCausalLM', 'BloomForCausalLM', 'MedusaModel', 'MixtralForCausalLM', 'MLPSpeculatorPreTrainedModel', 'FalconForCausalLM']  
32
    if any(arch in architectures for arch in support_nn_architectures): 
zhuwenwen's avatar
zhuwenwen committed
33
        if os.getenv('LLAMA_NN') != '0': 
zhuwenwen's avatar
zhuwenwen committed
34
             if (architectures == ['QWenLMHeadModel'] or architectures == ['ChatGLMModel'] ) and visions != []:
zhuwenwen's avatar
zhuwenwen committed
35
36
37
                os.environ['LLAMA_NN'] = '0'
             else:
                os.environ['LLAMA_NN'] = '1'
zhuwenwen's avatar
zhuwenwen committed
38
        if (architectures == ['BloomForCausalLM'] or architectures == ['FalconForCausalLM']) or os.getenv('LM_NN') == '0':
zhuwenwen's avatar
zhuwenwen committed
39
            os.environ['LM_NN'] = '0'
zhuwenwen's avatar
zhuwenwen committed
40
        else:
zhuwenwen's avatar
zhuwenwen committed
41
            os.environ['LM_NN'] = '1'
42
43
        if os.getenv('GEMM_PAD') != '1': 
            os.environ['GEMM_PAD'] = '0'
zhuwenwen's avatar
zhuwenwen committed
44
45
        if os.getenv('FA_PAD') != '1': 
            os.environ['FA_PAD'] = '0'
zhuwenwen's avatar
zhuwenwen committed
46
47
48
49
50
51
52
53
54
55
        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
56
57
    else:
        os.environ['LLAMA_NN'] = '0'
zhuwenwen's avatar
zhuwenwen committed
58
        os.environ['LM_NN'] = '0'
59
60
        os.environ['GEMM_PAD'] = '0'
        os.environ['FA_PAD'] = '0'
zhuwenwen's avatar
zhuwenwen committed
61
        os.environ['AWQ_PAD'] = '0'
62
        
63
64
    # Special handling for quantized Mixtral.
    # FIXME(woosuk): This is a temporary hack.
65
66
67
    mixtral_supported = [
        "fp8", "compressed-tensors", "gptq_marlin", "awq_marlin"
    ]
68

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

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

    return model_cls, arch
83
84
85
86


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


@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,
                )