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

本站现有博文339篇,共被浏览1000826次

本站已经建立2711天!

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