__init__.py 8.18 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

4
5
import os
import json
Zhuohan Li's avatar
Zhuohan Li committed
6
import uuid
7

Zhuohan Li's avatar
Zhuohan Li committed
8
import torch
9

10
from vllm.utils.torch_utils import direct_register_custom_op
11
MASK_64_BITS = (1 << 64) - 1
12

13

Cyrus Leung's avatar
Cyrus Leung committed
14
def random_uuid() -> str:
15
    return f"{uuid.uuid4().int & MASK_64_BITS:016x}"  # 16 hex chars
16
17
18


def length_from_prompt_token_ids_or_embeds(
19
    prompt_token_ids: list[int] | torch.Tensor | None,
20
    prompt_embeds: torch.Tensor | None,
21
) -> int:
22
    """Calculate the request length (in number of tokens) give either
23
24
    prompt_token_ids or prompt_embeds.
    """
25
26
    prompt_token_len = None if prompt_token_ids is None else len(prompt_token_ids)
    prompt_embeds_len = None if prompt_embeds is None else len(prompt_embeds)
27
28
29

    if prompt_token_len is None:
        if prompt_embeds_len is None:
30
            raise ValueError("Neither prompt_token_ids nor prompt_embeds were defined.")
31
32
        return prompt_embeds_len
    else:
33
        if prompt_embeds_len is not None and prompt_embeds_len != prompt_token_len:
34
35
36
            raise ValueError(
                "Prompt token ids and prompt embeds had different lengths"
                f" prompt_token_ids={prompt_token_len}"
37
38
                f" prompt_embeds={prompt_embeds_len}"
            )
39
        return prompt_token_len
40
41
42
43
44
45
46
47
48
49
    

class W8a8GetCacheJSON:
    _instance = None
    
    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super(W8a8GetCacheJSON, cls).__new__(cls, *args, **kwargs)
            cls._instance._initialize()
        return cls._instance
50

51
52
53
54
55
56
57
58
59
60
61
62
63
    def _initialize(self):
        from vllm.platforms import current_platform
        current_folder_path = os.path.dirname(os.path.abspath(__file__))
        json_folder_path = current_folder_path+'/../../lmslim/configs/w8a8'
    
        self.triton_json_dir=(os.getenv('TRITON_JSON_DIR', json_folder_path))
        self.triton_json_dict={}
        self.triton_moejson_dict={}
        self.triton_json_list=[]
        self.weight_shapes=[]
        self.moe_weight_shapes=[]
        arch_name = torch.cuda.get_device_properties("cuda").gcnArchName.split(':')[0]
        arch_cu = torch.cuda.get_device_properties(torch.cuda.current_device()).multi_processor_count
64
        self.cache_json_data = {}
65
66
67
68
        device_name =arch_name+'_'+str(arch_cu)+'cu'
        self.device_name=device_name
        self.topk=1
        self.quant_method=None
69

70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
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
    #析构函数,最后会生成model.json的配置文件
    def gen_model_json(self, E: int | None =0, block_size: list | None = None):
        json_dir = os.getenv('LMSLIM_TUNING_JSON', "None")
        if json_dir != "None" and os.path.exists(json_dir):
            #生成模型配置文件
            # logger.info("model_tuning.json is at LMSLIM_TUNING_JSON:%s", json_dir)
            config = {
                "layers": {
                    "linear": {
                        "shapes": [],
                        "m_range":"None",
                    },
                    "moe": {
                        "shapes": [],
                        "m_range": "None",
                        "topk": self.topk
                    }
                },
                "quantization_config": {
                    "quant_method": self.quant_method,
                    "weight_block_size": "None"
                }
            }
            
            # 处理 MoE shapes
            for shape in self.moe_weight_shapes:
                if len(shape) == 4:  # 假设 MoE shape 是 [N1, N2,K] 格式
                    moe_config = {
                        "E": shape[0],
                        "N1": shape[1],
                        "N2": shape[2],
                        "K": shape[3],      # 默认值
                    }
                    config["layers"]["moe"]["shapes"].append(moe_config)
                    
            for shape in self.weight_shapes:
                config["layers"]["linear"]["shapes"].append(shape)
            
            if block_size is not None:
                config["quantization_config"]["weight_block_size"]=block_size
                                    
            with open(json_dir+"/model.json", 'w') as f:
                json.dump(config, f, indent=4)
        # else:
        #     logger.info("LMSLIM_TUNING_JSON is not set")
                   
    def getspec_config(self,configs_dict,M,N,K):
        if f"{M}_{N}_{K}" in configs_dict:
            return configs_dict[f"{M}_{N}_{K}"]
        else:
            return None  
        
    def get_triton_cache(self,file_path,n,k):
        #在非tuning的时候使用,当文件不存在则直接返回none
        cache_json_file=file_path
        
        if os.path.exists(file_path):
        #try:
            with open(cache_json_file, 'r') as file:
                cachedata = json.load(file)
        else:
            return None 
                    
        #把所有的cache解析成key:config的形式:[M_N_K]:[config]
        configs_dict={}
        for key, value in cachedata.items():
            for sub_key, sub_value in value.items():
                configs_key= f"{sub_key}_{key}"
                configs_dict[configs_key]=sub_value
        return configs_dict
  
    def get_w8a8json_name(self,n,k):
        return self.triton_json_dir+f"/W8A8_{n}_{k}_{self.device_name}.json"
    
    def get_blockint8_triton_cache(self,file_path,n,k,block_n,block_k):
        cache_json_file=file_path
        
        if os.path.exists(file_path):
        #try:
            with open(cache_json_file, 'r') as file:
                cachedata = json.load(file)
151
        else:
152
153
154
155
156
157
158
159
160
            return None  
                    
        #把所有的cache解析成key:config的形式:[M_N_K]:[config]
        configs_dict={}
        for key, value in cachedata.items():
            for sub_key, sub_value in value.items():
                configs_key= f"{sub_key}_{key}"
                configs_dict[configs_key]=sub_value
        return configs_dict
161

162
163
    def get_blockint8json_name(self,n,k,block_n,block_k):
        return self.triton_json_dir+f"/linear_{n}_{k}_block[{block_n},{block_k}]_{self.device_name}.json"
164

165
166
167
    def get_moeint8json_name(self, E, N1, N2, K, TOPK,
                             block_size: list | None = None, use_int4_w4a8: bool | None = False,
                             use_int8_w8a8: bool | None = False):
168
169
        if use_int4_w4a8:
            if block_size is not None:
170
171
172
173
174
175
                return self.triton_json_dir + f"/MOE_W4A8INT8[{block_size[0]},{block_size[1]}]_E={E}_N1={N1}_N2={N2}_K={K}_TOPK{TOPK}_{self.device_name}.json"
            else:
                return self.triton_json_dir + f"/MOE_W4A8INT8_E={E}_N1={N1}_N2={N2}_K={K}_TOPK{TOPK}_{self.device_name}.json"
        elif use_int8_w8a8:
            if block_size is not None:
                return self.triton_json_dir + f"/MOE_BLOCKINT8[{block_size[0]},{block_size[1]}]_E={E}_N1={N1}_N2={N2}_K={K}_TOPK{TOPK}_{self.device_name}.json"
176
            else:
177
                return self.triton_json_dir + f"/MOE_W8A8INT8_E={E}_N1={N1}_N2={N2}_K={K}_TOPK{TOPK}_{self.device_name}.json"
178
179
        else:
            if block_size is not None:
180
                return self.triton_json_dir + f"/MOE_BLOCKFP8[{block_size[0]},{block_size[1]}]_E={E}_N1={N1}_N2={N2}_K={K}_TOPK{TOPK}_{self.device_name}.json"
181
            else:
182
                return self.triton_json_dir + f"/MOE_W8A8FP8_E={E}_N1={N1}_N2={N2}_K={K}_TOPK{TOPK}_{self.device_name}.json"
183
184


185
    def get_moeint8_triton_cache(self,file_path,E,N1,N2,K,TOPK):
186
187
188
        if file_path in self.cache_json_data:
            # 直接返回缓存数据,避免重复读取
            return self.cache_json_data[file_path]
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
        cache_json_file=file_path
        
        if os.path.exists(file_path):
        #try:
            with open(cache_json_file, 'r') as file:
                cachedata = json.load(file)
        else:
            return None  
                    
        #把所有的cache解析成key:config的形式:[M_N_K]:[config1,config2]
        configs_dict={}
        for key, value in cachedata.items():
            for sub_key, sub_value in value.items():
                configs_key= f"{sub_key}_{key}"   
                configs_dict[configs_key]=sub_value
204
        self.cache_json_data[file_path] = configs_dict
205
206
207
        return configs_dict