EADST

Pytorch Q4_1 Quantize and Dequantize aligning with llama.cpp

Pytorch Q4_1 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_1_quantize_and_dequantize_tensor(tensor):
    tensor = tensor.to(dtype=torch.float32, device=device)

    # Reshape tensor to process each 4-value block independently
    orig_shape = tensor.shape
    tensor = tensor.view(-1, 32)

    # Find the min and max values per block
    min_vals = torch.min(tensor, dim=1)[0]
    max_vals = torch.max(tensor, dim=1)[0]

    # Calculate scale d for each block
    d = (max_vals - min_vals) / (2**4 - 1)
    d[d == 0] = 1.0  # Prevent division by zero

    # Calculate inverse of d
    ids = 1.0 / d

    # Quantize tensor elements
    quantized_tensors = (tensor - min_vals[:, None]) * ids[:, None]

    # Clamp values to be between 0 and 15 (for 4 bits)
    quantized_tensors = torch.clamp(quantized_tensors + 0.5, 0, 15).to(torch.uint8)

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

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

本站已经建立2711天!

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