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

本站现有博文332篇,共被浏览875506

本站已经建立2583天!

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