"vscode:/vscode.git/clone" did not exist on "652c83b697ac64923fac9b253a3e09a2b653eb46"
Commit a8134c13 authored by zhuwenwen's avatar zhuwenwen
Browse files

Merge branch 'v0.8.5.post-dev-w8a8' into 'v0.8.5.post1-dev'

V0.8.5.post dev w8a8

See merge request dcutoolkit/deeplearing/vllm!131
parents a68aef25 53250530
...@@ -23,6 +23,10 @@ from vllm.model_executor.layers.quantization.base_config import ( ...@@ -23,6 +23,10 @@ from vllm.model_executor.layers.quantization.base_config import (
from vllm.model_executor.layers.quantization.utils.int8_utils import ( from vllm.model_executor.layers.quantization.utils.int8_utils import (
apply_w8a8_block_int8_linear) apply_w8a8_block_int8_linear)
from vllm.model_executor.utils import set_weight_attrs from vllm.model_executor.utils import set_weight_attrs
from vllm.utils import W8a8GetCacheJSON
import os
from vllm import _custom_ops as ops
ACTIVATION_SCHEMES = ["static", "dynamic"] ACTIVATION_SCHEMES = ["static", "dynamic"]
...@@ -128,6 +132,7 @@ class BlockInt8LinearMethod(LinearMethodBase): ...@@ -128,6 +132,7 @@ class BlockInt8LinearMethod(LinearMethodBase):
def __init__(self, quant_config: BlockInt8Config): def __init__(self, quant_config: BlockInt8Config):
self.quant_config = quant_config self.quant_config = quant_config
self.tritonsingleton= W8a8GetCacheJSON()
assert self.quant_config.weight_block_size is not None assert self.quant_config.weight_block_size is not None
assert self.quant_config.is_checkpoint_int8_serialized assert self.quant_config.is_checkpoint_int8_serialized
...@@ -219,6 +224,27 @@ class BlockInt8LinearMethod(LinearMethodBase): ...@@ -219,6 +224,27 @@ class BlockInt8LinearMethod(LinearMethodBase):
def process_weights_after_loading(self, layer: Module) -> None: def process_weights_after_loading(self, layer: Module) -> None:
# Block quant doesn't need to process weights after loading # Block quant doesn't need to process weights after loading
# Use torch Parameter to avoid cuda graph capturing issue # Use torch Parameter to avoid cuda graph capturing issue
n=layer.weight.shape[0]
k=layer.weight.shape[1]
block_n=self.quant_config.weight_block_size[0]
block_k=self.quant_config.weight_block_size[1]
block_size=[block_n,block_k]
#print("layer.weight.device:",layer.weight.device)
if {n,k} not in self.tritonsingleton.weight_shapes:
self.tritonsingleton.weight_shapes.append({n,k})
json_file=self.tritonsingleton.get_blockint8json_name(n,k,block_n,block_k)
configs_dict=self.tritonsingleton.get_blockint8_triton_cache(json_file,n,k,block_n,block_k)
if configs_dict:
self.tritonsingleton.triton_json_dict.update(configs_dict)
for key, value in configs_dict.items():
m=int(key.split('_')[0])
#ops.triton_blockint8_gemm_helper(m=m,n=n,k=k,block_size=block_size,use_bias=False,out_dtype=torch.bfloat16,device=layer.weight.device,best_config=value)
layer.weight = torch.nn.Parameter(layer.weight.data, requires_grad=False) layer.weight = torch.nn.Parameter(layer.weight.data, requires_grad=False)
layer.weight_scale_inv = torch.nn.Parameter( layer.weight_scale_inv = torch.nn.Parameter(
layer.weight_scale_inv.data, requires_grad=False layer.weight_scale_inv.data, requires_grad=False
......
from typing import Any, Callable, Dict, List, Optional from typing import Any, Callable, Dict, List, Optional
import torch import torch
from vllm.model_executor.utils import set_weight_attrs from vllm.model_executor.utils import set_weight_attrs
from vllm.distributed import get_tensor_model_parallel_world_size from vllm.distributed import get_tensor_model_parallel_world_size
from torch.nn.parameter import Parameter from torch.nn.parameter import Parameter
from vllm.model_executor.layers.linear import (LinearBase,LinearMethodBase) from vllm.model_executor.layers.linear import (LinearBase,LinearMethodBase)
from vllm.model_executor.layers.quantization.base_config import ( from vllm.model_executor.layers.quantization.base_config import (
QuantizationConfig, QuantizeMethodBase) QuantizationConfig, QuantizeMethodBase)
from vllm.model_executor.layers.fused_moe import (FusedMoE, FusedMoEMethodBase, from vllm.model_executor.layers.fused_moe import (FusedMoE, FusedMoEMethodBase,
FusedMoeWeightScaleSupported) FusedMoeWeightScaleSupported)
from vllm.model_executor.parameter import (BasevLLMParameter, from vllm.model_executor.parameter import (BasevLLMParameter,
ChannelQuantScaleParameter, ChannelQuantScaleParameter,
ModelWeightParameter, ModelWeightParameter,
PerTensorScaleParameter) PerTensorScaleParameter)
from vllm.model_executor.layers.quantization.utils.int8_utils import ( from vllm.model_executor.layers.quantization.utils.int8_utils import (
per_token_group_quant_int8, per_token_group_quant_int8,
per_token_quant_int8) per_token_quant_int8)
from vllm import _custom_ops as ops from vllm import _custom_ops as ops
from vllm.utils import W8a8GetCacheJSON
def baseline_scaled_mm(a: torch.Tensor,
b: torch.Tensor, import os
scale_a: torch.Tensor, from vllm import _custom_ops as ops
scale_b: torch.Tensor,
out_dtype: torch.dtype, W8A8_TRITONJSON=W8a8GetCacheJSON()
bias: Optional[torch.Tensor] = None) -> torch.Tensor:
def baseline_scaled_mm(a: torch.Tensor,
scales= scale_a* scale_b.T b: torch.Tensor,
gemmout= torch.mm( scale_a: torch.Tensor,
a.to(dtype=torch.float32), b.to(dtype=torch.float32)) scale_b: torch.Tensor,
output = (scales *gemmout).to(out_dtype) out_dtype: torch.dtype,
if bias is not None: bias: Optional[torch.Tensor] = None) -> torch.Tensor:
output = output + bias
return output.to(out_dtype) scales= scale_a* scale_b.T
gemmout= torch.mm(
a.to(dtype=torch.float32), b.to(dtype=torch.float32))
class W8A8Int8Config(QuantizationConfig): output = (scales *gemmout).to(out_dtype)
"""Config class for W8A8 Int8 Quantization. if bias is not None:
output = output + bias
- Weight: static, per-channel, symmetric return output.to(out_dtype)
- Activation: dynamic, per-token, symmetric
"""
class W8A8Int8Config(QuantizationConfig):
def __init__(self): """Config class for W8A8 Int8 Quantization.
pass
- Weight: static, per-channel, symmetric
@classmethod - Activation: dynamic, per-token, symmetric
def get_supported_act_dtypes(cls) -> List[torch.dtype]: """
return [torch.float16, torch.bfloat16]
def __init__(self):
@classmethod pass
def get_min_capability(cls) -> int:
return 75 @classmethod
def get_supported_act_dtypes(cls) -> List[torch.dtype]:
@classmethod return [torch.float16, torch.bfloat16]
def get_name(self) -> str:
return "w8a8_int8" @classmethod
def get_min_capability(cls) -> int:
@classmethod return 75
def get_config_filenames(cls) -> List[str]:
return [] @classmethod
def get_name(self) -> str:
@classmethod return "w8a8_int8"
def from_config(cls, config: Dict[str, Any]) -> "W8A8Int8Config":
return cls() @classmethod
def get_config_filenames(cls) -> List[str]:
def get_quant_method( return []
self,
layer: torch.nn.Module, @classmethod
prefix: str, def from_config(cls, config: Dict[str, Any]) -> "W8A8Int8Config":
) -> Optional["QuantizeMethodBase"]: return cls()
if isinstance(layer, LinearBase): def get_quant_method(
return W8A8Int8LinearMethod(self) self,
elif isinstance(layer, FusedMoE): layer: torch.nn.Module,
return W8A8Int8MoEMethod(self) prefix: str,
return None ) -> Optional["QuantizeMethodBase"]:
def get_scaled_act_names(self) -> List[str]: if isinstance(layer, LinearBase):
return [] return W8A8Int8LinearMethod(self)
elif isinstance(layer, FusedMoE):
return W8A8Int8MoEMethod(self)
class W8A8Int8LinearMethod(LinearMethodBase): return None
def __init__(self, quantization_config: W8A8Int8Config): def get_scaled_act_names(self) -> List[str]:
self.quantization_config = quantization_config return []
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
layer.weight = Parameter(layer.weight.t(), requires_grad=False) class W8A8Int8LinearMethod(LinearMethodBase):
layer.weight_scale = Parameter(layer.weight_scale.data, requires_grad=False)
def __init__(self, quantization_config: W8A8Int8Config):
def create_weights( self.quantization_config = quantization_config
self, self.tritonsingleton= W8a8GetCacheJSON()
layer: torch.nn.Module, self.w8a8_strategy=int(os.getenv('W8A8_SUPPORT_METHODS', '1'))
input_size_per_partition: int,
output_partition_sizes: List[int], def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
input_size: int, n=layer.weight.shape[0]
output_size: int, k=layer.weight.shape[1]
params_dtype: torch.dtype,
**extra_weight_attrs, if self.w8a8_strategy==1:
): if {n,k} not in self.tritonsingleton.weight_shapes:
self.tritonsingleton.weight_shapes.append({n,k})
weight_loader = extra_weight_attrs.get("weight_loader") json_file=self.tritonsingleton.get_w8a8json_name(n,k)
self.logical_widths = output_partition_sizes configs_dict=self.tritonsingleton.get_triton_cache(json_file,n,k)
weight = ModelWeightParameter( if configs_dict:
data=torch.empty( self.tritonsingleton.triton_json_dict.update(configs_dict)
sum(output_partition_sizes), input_size_per_partition, dtype=torch.int8
), for key, value in configs_dict.items():
input_dim=1, m=int(key.split('_')[0])
output_dim=0, ops.triton_int8_gemm_helper(m=m,n=n,k=k,per_token_act_quant=True,per_out_channel_weight_quant=True,use_bias=False,device=layer.weight.device,best_config=value)
weight_loader=weight_loader, else:
) weight_data=layer.weight.data
layer.register_parameter("weight", weight) _weight=weight_data.T.contiguous().reshape(n,-1)
layer.weight.data=_weight
weight_scale = ChannelQuantScaleParameter(
data=torch.empty((sum(output_partition_sizes), 1), dtype=torch.float32), layer.weight = Parameter(layer.weight.t(), requires_grad=False)
output_dim=0, layer.weight_scale = Parameter(layer.weight_scale.data, requires_grad=False)
weight_loader=weight_loader,
) def create_weights(
layer.register_parameter("weight_scale", weight_scale) self,
layer: torch.nn.Module,
def apply( input_size_per_partition: int,
self, output_partition_sizes: List[int],
layer: torch.nn.Module, input_size: int,
x: torch.Tensor, output_size: int,
bias: Optional[torch.Tensor] = None, params_dtype: torch.dtype,
): **extra_weight_attrs,
x_q, x_scale = per_token_quant_int8(x) ):
# return int8_scaled_mm( weight_loader = extra_weight_attrs.get("weight_loader")
# x_q, layer.weight, x_scale, layer.weight_scale, out_dtype=x.dtype, bias=bias self.logical_widths = output_partition_sizes
# )
#return baseline_scaled_mm(x_q, layer.weight, x_scale, layer.weight_scale, x.dtype, bias) weight = ModelWeightParameter(
data=torch.empty(
best_config=None sum(output_partition_sizes), input_size_per_partition, dtype=torch.int8
return ops.triton_scaled_mm(x_q, ),
layer.weight, input_dim=1,
scale_a=x_scale, output_dim=0,
scale_b=layer.weight_scale, weight_loader=weight_loader,
out_dtype=x.dtype, )
bias=bias,best_config=best_config) layer.register_parameter("weight", weight)
class W8A8Int8MoEMethod: weight_scale = ChannelQuantScaleParameter(
"""MoE method for INT8. data=torch.empty((sum(output_partition_sizes), 1), dtype=torch.float32),
Supports loading INT8 checkpoints with static weight scale and output_dim=0,
dynamic/static activation scale. weight_loader=weight_loader,
Also supports loading quantized FP16/BF16 model checkpoints with dynamic )
activation scaling. The weight scaling factor will be initialized after layer.register_parameter("weight_scale", weight_scale)
the model weights are loaded.
Args: def apply(
quant_config: The quantization config. self,
""" layer: torch.nn.Module,
x: torch.Tensor,
def __new__(cls, *args, **kwargs): bias: Optional[torch.Tensor] = None,
):
if not hasattr(cls, "_initialized"): x_q, x_scale = per_token_quant_int8(x)
original_init = cls.__init__
new_cls = type( if self.w8a8_strategy==1:
cls.__name__, m=x_q.shape[0]
(FusedMoEMethodBase,), k=x_q.shape[1]
{ n=layer.weight.shape[1]
"__init__": original_init,
**{k: v for k, v in cls.__dict__.items() if k != "__dict__"}, if len(W8A8_TRITONJSON.triton_json_dict)==0:
}, best_config=None
)
obj = super(new_cls, new_cls).__new__(new_cls) elif f"1_{n}_{k}" in W8A8_TRITONJSON.triton_json_dict:
obj.__init__(*args, **kwargs) if m<=16:
return obj m_=m
return super().__new__(cls) elif m<=64:
m_= (m + 3) & -4 #取值到最近的4的倍数
def __init__(self, quant_config): elif m<=160:
self.quant_config = quant_config m_=(m + 7) & -8
def create_weights( elif m<200: #256
self, m_=160
layer: torch.nn.Module, elif m<480: #512
num_experts: int, m_=256
hidden_size: int, elif m<960: #1024
intermediate_size: int, m_=512
params_dtype: torch.dtype, elif m<2048:
**extra_weight_attrs, m_=1024
): elif m<4096:
tp_size = get_tensor_model_parallel_world_size() m_=2048
elif m<6000:
# WEIGHTS m_=4096
w13_weight = torch.nn.Parameter( else:
torch.empty( m_=8192
num_experts, 2 * intermediate_size, hidden_size, dtype=torch.int8
), best_config=W8A8_TRITONJSON.triton_json_dict[f"{m_}_{n}_{k}"]
requires_grad=False,
) else:
layer.register_parameter("w13_weight", w13_weight) best_config=None
set_weight_attrs(w13_weight, extra_weight_attrs)
#if best_config==None:
w2_weight = torch.nn.Parameter( # print("m:{},n:{},k:{}".format(m,n,k))
torch.empty(num_experts, hidden_size, intermediate_size, dtype=torch.int8), # print("config not found!")
requires_grad=False,
) return ops.triton_scaled_mm(x_q,
layer.register_parameter("w2_weight", w2_weight) layer.weight,
set_weight_attrs(w2_weight, extra_weight_attrs) scale_a=x_scale,
scale_b=layer.weight_scale,
w13_weight_scale = torch.nn.Parameter( out_dtype=x.dtype,
torch.ones(num_experts, 2 * intermediate_size, 1, dtype=torch.float32), bias=bias,best_config=best_config)
requires_grad=False, elif self.w8a8_strategy==2:
) return ops.cutlass_scaled_mm(x_q,
w2_weight_scale = torch.nn.Parameter( layer.weight,
torch.ones(num_experts, hidden_size, 1, dtype=torch.float32), scale_a=x_scale,
requires_grad=False, scale_b=layer.weight_scale,
) out_dtype=x.dtype,
layer.register_parameter("w13_weight_scale", w13_weight_scale) bias=bias)
layer.register_parameter("w2_weight_scale", w2_weight_scale) else:
return ops.rocblas_scaled_mm(x_q,
extra_weight_attrs.update( layer.weight,
{"quant_method": FusedMoeWeightScaleSupported.CHANNEL.value} scale_a=x_scale,
) scale_b=layer.weight_scale,
out_dtype=x.dtype,
set_weight_attrs(w13_weight_scale, extra_weight_attrs) bias=bias)
set_weight_attrs(w2_weight_scale, extra_weight_attrs)
w13_input_scale = None class W8A8Int8MoEMethod:
layer.register_parameter("w13_input_scale", w13_input_scale) """MoE method for INT8.
Supports loading INT8 checkpoints with static weight scale and
w2_input_scale = None dynamic/static activation scale.
layer.register_parameter("w2_input_scale", w2_input_scale) Also supports loading quantized FP16/BF16 model checkpoints with dynamic
activation scaling. The weight scaling factor will be initialized after
def process_weights_after_loading(self, layer: torch.nn.Module) -> None: the model weights are loaded.
layer.w13_weight = Parameter(layer.w13_weight, requires_grad=False) Args:
layer.w2_weight = Parameter(layer.w2_weight, requires_grad=False) quant_config: The quantization config.
layer.w13_weight_scale = Parameter( """
layer.w13_weight_scale.data, requires_grad=False
) def __new__(cls, *args, **kwargs):
layer.w2_weight_scale = Parameter(
layer.w2_weight_scale.data, requires_grad=False if not hasattr(cls, "_initialized"):
) original_init = cls.__init__
new_cls = type(
def apply( cls.__name__,
self, (FusedMoEMethodBase,),
layer: torch.nn.Module, {
x: torch.Tensor, "__init__": original_init,
router_logits: torch.Tensor, **{k: v for k, v in cls.__dict__.items() if k != "__dict__"},
top_k: int, },
renormalize: bool, )
use_grouped_topk: bool = False, obj = super(new_cls, new_cls).__new__(new_cls)
topk_group: Optional[int] = None, obj.__init__(*args, **kwargs)
num_expert_group: Optional[int] = None, return obj
global_num_experts: int = -1, return super().__new__(cls)
expert_map: Optional[torch.Tensor] = None,
custom_routing_function: Optional[Callable] = None, def __init__(self, quant_config):
scoring_func: str = "softmax", self.quant_config = quant_config
e_score_correction_bias: Optional[torch.Tensor] = None,
apply_router_weight_on_input: bool = False, def create_weights(
activation: str = "silu", self,
use_nn_moe: Optional[bool] = False, layer: torch.nn.Module,
routed_scaling_factor: Optional[float] = None, num_experts: int,
use_fused_gate: Optional[bool] = False, hidden_size: int,
) -> torch.Tensor: intermediate_size: int,
from vllm.model_executor.layers.fused_moe import fused_experts params_dtype: torch.dtype,
**extra_weight_attrs,
# Expert selection ):
topk_weights, topk_ids = FusedMoE.select_experts( tp_size = get_tensor_model_parallel_world_size()
hidden_states=x,
router_logits=router_logits, # WEIGHTS
use_grouped_topk=use_grouped_topk, w13_weight = torch.nn.Parameter(
top_k=top_k, torch.empty(
renormalize=renormalize, num_experts, 2 * intermediate_size, hidden_size, dtype=torch.int8
topk_group=topk_group, ),
num_expert_group=num_expert_group, requires_grad=False,
custom_routing_function=custom_routing_function, )
scoring_func=scoring_func, layer.register_parameter("w13_weight", w13_weight)
e_score_correction_bias=e_score_correction_bias, set_weight_attrs(w13_weight, extra_weight_attrs)
routed_scaling_factor=routed_scaling_factor,
use_fused_gate=use_fused_gate w2_weight = torch.nn.Parameter(
) torch.empty(num_experts, hidden_size, intermediate_size, dtype=torch.int8),
requires_grad=False,
return fused_experts( )
x, layer.register_parameter("w2_weight", w2_weight)
layer.w13_weight, set_weight_attrs(w2_weight, extra_weight_attrs)
layer.w2_weight,
topk_weights=topk_weights, w13_weight_scale = torch.nn.Parameter(
topk_ids=topk_ids, torch.ones(num_experts, 2 * intermediate_size, 1, dtype=torch.float32),
inplace=True, requires_grad=False,
use_int8_w8a8=True, )
per_channel_quant=True, w2_weight_scale = torch.nn.Parameter(
activation=activation, torch.ones(num_experts, hidden_size, 1, dtype=torch.float32),
expert_map=expert_map, requires_grad=False,
apply_router_weight_on_input=apply_router_weight_on_input, )
global_num_experts=global_num_experts, layer.register_parameter("w13_weight_scale", w13_weight_scale)
w1_scale=(layer.w13_weight_scale), layer.register_parameter("w2_weight_scale", w2_weight_scale)
w2_scale=(layer.w2_weight_scale),
a1_scale=layer.w13_input_scale, extra_weight_attrs.update(
a2_scale=layer.w2_input_scale, {"quant_method": FusedMoeWeightScaleSupported.CHANNEL.value}
use_nn_moe=use_nn_moe, )
)
set_weight_attrs(w13_weight_scale, extra_weight_attrs)
set_weight_attrs(w2_weight_scale, extra_weight_attrs)
w13_input_scale = None
layer.register_parameter("w13_input_scale", w13_input_scale)
w2_input_scale = None
layer.register_parameter("w2_input_scale", w2_input_scale)
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
layer.w13_weight = Parameter(layer.w13_weight, requires_grad=False)
layer.w2_weight = Parameter(layer.w2_weight, requires_grad=False)
layer.w13_weight_scale = Parameter(
layer.w13_weight_scale.data, requires_grad=False
)
layer.w2_weight_scale = Parameter(
layer.w2_weight_scale.data, requires_grad=False
)
def apply(
self,
layer: torch.nn.Module,
x: torch.Tensor,
router_logits: torch.Tensor,
top_k: int,
renormalize: bool,
use_grouped_topk: bool = False,
topk_group: Optional[int] = None,
num_expert_group: Optional[int] = None,
global_num_experts: int = -1,
expert_map: Optional[torch.Tensor] = None,
custom_routing_function: Optional[Callable] = None,
scoring_func: str = "softmax",
e_score_correction_bias: Optional[torch.Tensor] = None,
apply_router_weight_on_input: bool = False,
activation: str = "silu",
use_nn_moe: Optional[bool] = False,
routed_scaling_factor: Optional[float] = None,
use_fused_gate: Optional[bool] = False,
) -> torch.Tensor:
from vllm.model_executor.layers.fused_moe import fused_experts
# Expert selection
topk_weights, topk_ids = FusedMoE.select_experts(
hidden_states=x,
router_logits=router_logits,
use_grouped_topk=use_grouped_topk,
top_k=top_k,
renormalize=renormalize,
topk_group=topk_group,
num_expert_group=num_expert_group,
custom_routing_function=custom_routing_function,
scoring_func=scoring_func,
e_score_correction_bias=e_score_correction_bias,
routed_scaling_factor=routed_scaling_factor,
use_fused_gate=use_fused_gate
)
return fused_experts(
x,
layer.w13_weight,
layer.w2_weight,
topk_weights=topk_weights,
topk_ids=topk_ids,
inplace=True,
use_int8_w8a8=True,
per_channel_quant=True,
activation=activation,
expert_map=expert_map,
apply_router_weight_on_input=apply_router_weight_on_input,
global_num_experts=global_num_experts,
w1_scale=(layer.w13_weight_scale),
w2_scale=(layer.w2_weight_scale),
a1_scale=layer.w13_input_scale,
a2_scale=layer.w2_input_scale,
use_nn_moe=use_nn_moe,
)
...@@ -53,7 +53,6 @@ from vllm.model_executor.model_loader.weight_utils import ( ...@@ -53,7 +53,6 @@ from vllm.model_executor.model_loader.weight_utils import (
default_weight_loader, maybe_remap_kv_scale_name) default_weight_loader, maybe_remap_kv_scale_name)
from vllm.model_executor.sampling_metadata import SamplingMetadata from vllm.model_executor.sampling_metadata import SamplingMetadata
from vllm.sequence import IntermediateTensors from vllm.sequence import IntermediateTensors
from vllm.utils import W8a8GetCacheJSON
from .interfaces import SupportsPP from .interfaces import SupportsPP
from .utils import (PPMissingLayer, is_pp_missing_parameter, from .utils import (PPMissingLayer, is_pp_missing_parameter,
...@@ -704,7 +703,6 @@ class DeepseekV2ForCausalLM(nn.Module, SupportsPP): ...@@ -704,7 +703,6 @@ class DeepseekV2ForCausalLM(nn.Module, SupportsPP):
os.environ['LM_NN'] = '0' os.environ['LM_NN'] = '0'
self.use_w4a16_moe_sz = os.environ.get('AWQ_MOE_SZ') == '1' self.use_w4a16_moe_sz = os.environ.get('AWQ_MOE_SZ') == '1'
self.tritonsingleton= W8a8GetCacheJSON()
self.config = config self.config = config
self.quant_config = quant_config self.quant_config = quant_config
...@@ -928,48 +926,6 @@ class DeepseekV2ForCausalLM(nn.Module, SupportsPP): ...@@ -928,48 +926,6 @@ class DeepseekV2ForCausalLM(nn.Module, SupportsPP):
sz_tensor = self.restore_qzeros_tensor(qzeros, scales) sz_tensor = self.restore_qzeros_tensor(qzeros, scales)
scales.data = sz_tensor scales.data = sz_tensor
if hasattr(self.config, "quantization_config") and self.config.quantization_config["quant_method"] == "blockwise_int8":
lay_key_words = [
"self_attn.q_a_proj.weight",
"self_attn.q_b_proj.weight",
"self_attn.kv_b_proj.weight",
"self_attn.kv_a_proj_with_mqa.weight",
"self_attn.o_proj.weight",
"mlp.gate_up_proj.weight",
"mlp.down_proj.weight",
"mlp.shared_experts.gate_up_proj.weight",
"mlp.shared_experts.down_proj.weight"
]
combined_words = "|".join(lay_key_words)
weight_shapes=[]
all_json={}
matched_key_words=set()
for layername, weight in params_dict.items():
matches = re.findall(combined_words, layername)
if matches and "scale" not in layername:
weight_data =params_dict[layername]
n=weight_data.shape[0]
if len(matched_key_words) < 9 and matches[0] not in matched_key_words:
matched_key_words.add(matches[0])
k=weight_data.shape[1]
weight_shapes.append({n,k})
#print("n:{},k:{}".format(n,k))
json_file=self.tritonsingleton.get_blockint8json_name(n,k,128,128)
configs_dict=self.tritonsingleton.get_blockint8_triton_cache(json_file,n,k,128,128)
if configs_dict:
all_json.update(configs_dict)
self.tritonsingleton.triton_json_list.append(all_json)
#print("self.tritonsingleton.triton_json_dict[0].shape:",len(self.tritonsingleton.triton_json_dict[0]))
for key, value in all_json.items():
m=int(key.split('_')[0])
n=int(key.split('_')[1])
k=int(key.split('_')[2])
# ops.triton_int8_gemm_helper(m=m,n=n,k=k,per_token_act_quant=True,per_out_channel_weight_quant=True,use_bias=False,best_config=value)
return loaded_params return loaded_params
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment