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

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

本站已经建立2639天!

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