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

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

本站已经建立2591天!

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