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

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

本站已经建立2628天!

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