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

本站现有博文338篇,共被浏览966586次

本站已经建立2679天!

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