EADST

Pytorch Q4_0 Quantize and Dequantize aligning with llama.cpp

Pytorch Q4_0 Quantize and Dequantize aligning with llama.cpp

import torch

# Check if CUDA is available
use_cuda = torch.cuda.is_available()
device = torch.device("cuda" if use_cuda else "cpu")

def q4_0_quantize_and_dequantize_tensor(tensor):
    tensor = tensor.to(dtype=torch.float32, device=device)

    # Reshape tensor to process each 32-value block independently
    orig_shape = tensor.shape
    tensor = tensor.view(-1, 32)

    # Find the maximum absolute value per block
    max_vals = torch.max(torch.abs(tensor), dim=1)[0]

    # Prevent division by zero
    max_vals[max_vals == 0] = 1.0

    # Calculate d and id for each block
    d = max_vals / -8.0
    ids = 1.0 / d

    # Scale and quantize tensor elements
    scaled_tensors = tensor * ids[:, None]
    quantized_tensors = torch.clamp(scaled_tensors + 8.5, 0, 15).to(torch.uint8)

    # Dequantize the tensor
    dequantized_tensors = (quantized_tensors.float() - 8.0) * d[:, None]

    # Reshape back to the original shape
    dequantized_tensors = dequantized_tensors.view(orig_shape).to(dtype=torch.float16)

    return dequantized_tensors

# Assuming 'model_part' is already loaded and on CPU
model_part = torch.load(f"your_model_path/pytorch_model.bin", map_location="cpu")
keywords = [
    "embed_tokens.weight",
    "self_attn.q_proj.weight",
    "self_attn.k_proj.weight",
    "self_attn.v_proj.weight",
    "self_attn.o_proj.weight",
    "mlp.up_proj.weight",
    "mlp.gate_proj.weight",
    "mlp.down_proj.weight",
    "lm_head.weight"
]
for name, data in model_part.items():
    for word in keywords:
        if word in name:
            # Quantize and dequantize the entire tensor
            model_part[name] = q4_0_quantize_and_dequantize_tensor(data)

# Save the updated model parts
torch.save(model_part, "pytorch_model_quantized.bin")

Reference:

相关标签
About Me
XD
Goals determine what you are going to be.
Category
标签云
Llama News 净利润 NLP Agent Miniforge GPTQ printf Bert Food Nginx logger ModelScope 图标 v2ray 音频 HaggingFace Permission tar Freesound BF16 PDB DeepSeek Pillow Anaconda SQL Animate Interview Quantize Gemma InvalidArgumentError diffusers 域名 Numpy Cloudreve Use Plotly Tiktoken Proxy scipy CEIR Jupyter Augmentation Pickle 图形思考法 搞笑 Web TensorRT Card 阿里云 第一性原理 飞书 GoogLeNet Review 强化学习 Hotel API网关 Safetensors 报税 Jetson API FastAPI icon hf Distillation Diagram RGB Pandas 版权 CV SPIE transformers Shortcut Google Vim Disk LoRA GIT Translation VPN PDF Michelin ChatGPT 论文 Ubuntu Magnet 多线程 Logo NameSilo GPT4 Input Tensor tqdm UNIX mmap Bin Zip Bipartite Qwen2 JSON YOLO Git Data HuggingFace Plate TensorFlow 论文速读 Clash Mixtral Breakpoint 顶会 XGBoost 财报 LLAMA Crawler Paddle Search Baidu FP16 DeepStream Django Github WAN Video Knowledge Domain Rebuttal v0.dev ONNX Statistics BeautifulSoup Datetime OpenCV FP8 FP64 NLTK Attention LLM SQLite uWSGI RL Quantization Algorithm Heatmap LaTeX CSV Qwen2.5 PIP Streamlit IndexTTS2 多进程 CUDA 递归学习法 OCR CTC Transformers QWEN COCO ResNet-50 Harness Tracking VSCode PyTorch llama.cpp Random Password Bitcoin Docker C++ Claude TSV Firewall 证件照 CC Sklearn Dataset Excel Paper 继承 Base64 FlashAttention git SAM uwsgi Land Color Pytorch PyCharm FP32 OpenAI Qwen RAR VGG-16 Image2Text 关于博主 BTC Windows Linux Conda Vmess WebCrawler ms-swift Hungarian git-lfs Template EXCEL torchinfo 腾讯云 LeetCode SVR GGML 签证 CLAP XML TTS Website Ptyhon Math 云服务器 Markdown CAM MD5 公式 算法题 UI Hilton Python AI
站点统计

本站现有博文336篇,共被浏览946153

本站已经建立2656天!

热门文章
文章归档
回到顶部