Model Details
This model is an FP8 model with activation per-tensor FP8 quantization of moonshotai/Kimi-K2-Instruct generated by intel/auto-round algorithm.
Please follow the license of the original model.
How To Use
Sample Code
from transformers import AutoTokenizer, AutoModelForCausalLM
import transformers
from transformers.modeling_utils import no_init_weights
from loguru import logger
import torch
from torch import nn
def float8_e4m3fn_ste(x: torch.Tensor):
fp8 = (x.to(torch.float8_e4m3fn).to(x.dtype) - x).detach() + x
return fp8
WEIGHT_SCALE_NAME = "weight_scale"
INPUT_SCALE_NAME = "act_scale"
class FP8QDQLinear(torch.nn.Linear):
dtype = torch.bfloat16
fp8_dtype = torch.float8_e4m3fn
def __init__(self, in_features: int, out_features: int, bias: bool = True, device=None):
super().__init__(in_features, out_features, bias=bias)
self.in_features = in_features
self.out_features = out_features
self.weight = nn.Parameter(
torch.empty(out_features, in_features, dtype=FP8QDQLinear.fp8_dtype), requires_grad=True
)
if bias:
self.bias = nn.Parameter(torch.empty(out_features))
else:
self.register_parameter("bias", None)
def dequant_weight_online(self):
fp8_weight = self.weight
# if str(self.scale_weight.device) == "meta":
if not hasattr(self, WEIGHT_SCALE_NAME):
print(self.name, "no scale weight")
qdq_weight = fp8_weight.to(FP8QDQLinear.dtype)
else:
qdq_weight = fp8_weight.to(FP8QDQLinear.dtype) * self.weight_scale.to(fp8_weight.device)
return qdq_weight
@classmethod
def create_from_linear(cls, linear: nn.Linear):
qdq_linear = cls(linear.in_features, linear.out_features)
qdq_linear.weight.data = linear.weight.data
if linear.bias is not None:
qdq_linear.bias = linear.bias
return qdq_linear
def forward(self, bf16_input: torch.Tensor) -> torch.Tensor:
if not hasattr(self, INPUT_SCALE_NAME):
print(self.name, "has no scale input")
qdq_input = bf16_input
else:
fp8_max = torch.finfo(torch.float8_e4m3fn).max
fp8_res = bf16_input / getattr(self, INPUT_SCALE_NAME).to(bf16_input.device)
fp8_res = torch.clip(fp8_res, -fp8_max, fp8_max)
fp8_res = float8_e4m3fn_ste(fp8_res)
qdq_input = fp8_res * getattr(self, INPUT_SCALE_NAME).to(fp8_res.device)
qdq_weight = self.dequant_weight_online()
out = torch.nn.functional.linear(qdq_input, qdq_weight, self.bias)
return out
torch.nn.Linear = FP8QDQLinear
def get_module(module, key):
"""Get module from model by key name.
Args:
module (torch.nn.Module): original model
key (str): module name to be replaced
"""
name_list = key.split(".")
for name in name_list:
module = getattr(module, name, None)
return module
def qdq_eval(qmodel_path, prompt="The future of AI is"):
import transformers
def _patch__initialize_weights(self, module):
module._is_hf_initialized = True
transformers.modeling_utils.PreTrainedModel._initialize_weights = _patch__initialize_weights
tokenizer = transformers.AutoTokenizer.from_pretrained(qmodel_path, trust_remote_code=True)
# patch_transformers()
with no_init_weights():
model = transformers.AutoModelForCausalLM.from_pretrained(
qmodel_path,
torch_dtype=torch.bfloat16,
low_cpu_mem_usage=True,
trust_remote_code=True,
device_map=None
)
import os
from safetensors.torch import safe_open
dir_ = qmodel_path
for file in os.listdir(dir_):
if file.endswith("safetensors"):
with safe_open(os.path.join(dir_, file), framework="pt", device="cpu") as f:
for weight_name in f.keys():
layer_name = ".".join(weight_name.split(".")[:-1])
module = get_module(model, layer_name)
if module is None:
continue
module.name = layer_name
if WEIGHT_SCALE_NAME in weight_name:
scale = f.get_tensor(weight_name)
setattr(module, WEIGHT_SCALE_NAME, scale.to(FP8QDQLinear.dtype))
if INPUT_SCALE_NAME in weight_name:
scale_input = f.get_tensor(weight_name)
setattr(module, INPUT_SCALE_NAME, scale_input.to(FP8QDQLinear.dtype))
for n, m in model.named_modules():
if isinstance(m, FP8QDQLinear):
m.name = n
encode = tokenizer.encode(prompt, return_tensors="pt")
model = model.to("cpu")
encode = encode.to("cpu")
with torch.no_grad():
generate_kwargs = dict(do_sample=False, temperature=0.0001, top_p=0.0001)
output_tokens = model.generate(encode, max_new_tokens=20, **generate_kwargs)
output = tokenizer.decode(output_tokens[0], skip_special_tokens=True)
logger.info(f"Output: {output}")
if __name__ == "__main__":
qmodel_path = "/data3/Kimi-K2-Instruct-BF16-W8AFP8/Kimi-K2-Instruct-BF16-w8afp8/"
qdq_eval(qmodel_path, prompt="The future of AI is")
Generate the model
pip install git+https://github.com/intel/auto-round@hengguo/export_static_fp8
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
import transformers
model_name = "Kimi-K2-Instruct-BF16"
tokenizer = AutoTokenizer.from_pretrained(model_name,trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(model_name,device_map="cpu", torch_dtype="auto",trust_remote_code=True)
block = model.model.layers
device_map = {}
for n, m in block.named_modules():
if isinstance(m, (torch.nn.Linear, transformers.modeling_utils.Conv1D)):
if "experts" in n and ("shared_experts" not in n):
if int(n.split('.')[-2]) < 96:
device = "cuda:1"
elif int(n.split('.')[-2]) >= 96 and int(n.split('.')[-2]) < 192:
device = "cuda:2"
elif int(n.split('.')[-2]) >= 192 and int(n.split('.')[-2]) < 288:
device = "cuda:3"
elif int(n.split('.')[-2]) >= 288:
device = "cuda:4"
else:
device = "cuda:0"
n = n[2:]
device_map.update({n: device})
from auto_round import AutoRound
autoround = AutoRound(
model=model, tokenizer=tokenizer, device_map=device_map, iters=0, lr=5e-3,nsamples=512,bits=8,act_bits=8,group_size=-1,
batch_size=8, low_gpu_mem_usage=True, seqlen=2048, data_type="fp8", act_data_type="fp8",act_dynamic=False,
)
autoround.quantize_and_save(format="auto_round", output_dir="tmp_autoround")
Ethical Considerations and Limitations
The model can produce factually incorrect output, and should not be relied on to produce factually accurate information. Because of the limitations of the pretrained model and the finetuning datasets, it is possible that this model could generate lewd, biased or otherwise offensive outputs.
Therefore, before deploying any applications of the model, developers should perform safety testing.
Caveats and Recommendations
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model.
Here are a couple of useful links to learn more about Intel's AI software:
- Intel Neural Compressor link
Disclaimer
The license on this model does not constitute legal advice. We are not responsible for the actions of third parties who use this model. Please consult an attorney before using this model for commercial purposes.
Cite
@article{cheng2023optimize, title={Optimize weight rounding via signed gradient descent for the quantization of llms}, author={Cheng, Wenhua and Zhang, Weiwei and Shen, Haihao and Cai, Yiyang and He, Xin and Lv, Kaokao and Liu, Yi}, journal={arXiv preprint arXiv:2309.05516}, year={2023} }
- Downloads last month
- 3
Model tree for Intel/Kimi-K2-Instruct-w8afp8-AutoRound
Base model
moonshotai/Kimi-K2-Instruct