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

本站现有博文332篇,共被浏览875352

本站已经建立2583天!

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