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

本站现有博文334篇,共被浏览930523

本站已经建立2639天!

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