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

本站现有博文333篇,共被浏览913615

本站已经建立2616天!

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