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

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

本站已经建立2616天!

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