') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); GitHub - VikhrModels/quantization-utils · GitHub
Skip to content

Repository files navigation

Quantization Utils - Bare Metal Setup

A comprehensive toolkit for quantizing large language models to GGUF format with support for multiple acceleration backends (CUDA, Metal, CPU).

🚀 Features

FeatureStatusDescription
🖥️ Bare MetalNative installation without Docker
🔧 Auto SetupAutomatic environment detection and configuration
🎯 Multi-BackendCUDA, Metal (Apple Silicon), and CPU support
📦 Conda ReadyComplete conda environment with all dependencies
Quick ScriptsConvenient scripts for common tasks
📊 PerplexityAutomated quality testing of quantized models
🔍 ValidationEnvironment health checks and troubleshooting

📋 Prerequisites

RequirementMinimum VersionNotes
CondaLatestMiniconda or Anaconda
Python3.11+Installed via conda
Git2.0+For repository operations
CMake3.14+For building llama.cpp

GPU Support (Optional)

PlatformRequirementsAcceleration
NVIDIACUDA 11.8+✅ CUDA acceleration
Apple SiliconmacOS + M1/M2/M3✅ Metal acceleration
OthersAny CPU✅ Optimized CPU processing

🛠️ Quick Setup

Option 1: Automated Setup (Recommended)

# Clone the repository
git clone https://github.com/Vikhrmodels/quantization-utils.git
cd quantization-utils
# Run the automated setup script
chmod +x scripts/setup.sh
./scripts/setup.sh

Option 2: Manual Setup

# Create conda environment (OS-specific)# For Linux:
conda env create -f environment-linux.yml
# For macOS:
conda env create -f environment-macos.yml
# Generic (fallback):
conda env create -f environment.yml
# Activate environment
conda activate quantization-utils
# Run setup to install llama.cpp and prepare directories
python setup.py
# Add to PATH (if needed)export PATH="$HOME/.local/bin:$PATH"

🔍 Validation

Verify your installation:

# Check environment health
./scripts/validate.sh
# Quick test
conda activate quantization-utils
cd GGUF
python -c "from shared import validate_environment; validate_environment()"

📊 Usage Examples

Basic Model Quantization

# Activate environment
conda activate quantization-utils
# Quantize a model with default settings
./scripts/quantize.sh microsoft/DialoGPT-medium
# Custom quantization levels
./scripts/quantize.sh Vikhrmodels/Vikhr-Gemma-2B-instruct -q Q4_K_M,Q5_K_M,Q8_0
# Force re-quantization
./scripts/quantize.sh microsoft/DialoGPT-medium --force

Advanced Pipeline Usage

cd GGUF
# Full pipeline with all quantization levels
python pipeline.py --model_id microsoft/DialoGPT-medium
# Specific quantization levels only
python pipeline.py --model_id microsoft/DialoGPT-medium -q Q4_K_M -q Q8_0
# With perplexity testing
python pipeline.py --model_id microsoft/DialoGPT-medium --perplexity
# For gated models (requires HF token)
python pipeline.py --model_id meta-llama/Llama-2-7b-hf --hf_token $HF_TOKEN

Perplexity Testing

# Test all quantized versions
./scripts/perplexity.sh microsoft/DialoGPT-medium
# Force recalculation
./scripts/perplexity.sh microsoft/DialoGPT-medium --force

📁 Directory Structure

quantization-utils/
├── 📄 environment.yml # Conda environment definition
├── 🐍 setup.py # Environment setup script
├── 📖 README.md # This file
│
├── 🔧 scripts/ # Convenience scripts
│ ├── setup.sh # Automated setup
│ ├── validate.sh # Environment validation
│ ├── quantize.sh # Quick quantization
│ └── perplexity.sh # Perplexity testing
│
└── 📦 GGUF/ # Main processing directory
├── 🐍 pipeline.py # Main pipeline script
├── 🐍 shared.py # Shared utilities
├── 📁 models/ # Downloaded models
├── 📁 imatrix/ # Importance matrices
├── 📁 output/ # Final quantized models
├── 📁 resources/ # Calibration data
│ └── standard_cal_data/
└── 📁 modules/ # Processing modules
├── convert.py
├── quantize.py
├── imatrix.py
└── perplexity.py

⚙️ Configuration Options

Environment Variables

VariableDescriptionExample
HF_TOKENHuggingFace API tokenhf_...
CUDA_VISIBLE_DEVICESGPU selection0,1
OMP_NUM_THREADSCPU threads8

Pipeline Parameters

ParameterDescriptionDefault
--model_idHuggingFace model IDRequired
--quantsQuantization levelsAll levels
--forceForce reprocessingFalse
--perplexityRun quality testsFalse
--threadsProcessing threadsCPU count

Quantization Levels

LevelDescriptionSizeQuality
Q2_K2-bit quantizationSmallestGood
Q4_K_M4-bit mixedBalancedVery Good
Q5_K_M5-bit mixedLargerExcellent
Q6_K6-bitLargeNear Original
Q8_08-bitLargestOriginal

🐛 Troubleshooting

Common Issues

IssueSolution
conda: command not foundInstall Miniconda/Anaconda
llama-quantize: not foundRun python setup.py
CUDA out of memoryReduce batch size or use CPU
Permission deniedCheck file permissions with chmod +x
PackagesNotFoundErrorUse OS-specific environment file

Environment Problems

# Reset environment
conda env remove -n quantization-utils
# Recreate with OS-specific file# Linux:
conda env create -f environment-linux.yml
# macOS:
conda env create -f environment-macos.yml
# Reinstall llama.cpp
rm -rf ~/.local/bin/llama-*
python setup.py
# Check installation
./scripts/validate.sh

Binary Issues

# Manual llama.cpp installationcd /tmp
git clone https://github.com/ggerganov/llama.cpp.git
cd llama.cpp
mkdir build &&cd build
cmake .. -DCMAKE_INSTALL_PREFIX=$HOME/.local
make -j$(nproc)
make install

🔧 Development

Adding New Quantization Methods

  1. Update shared.py with new Quant enum values
  2. Modify modules/quantize.py to handle new methods
  3. Update pipeline default quantization list
  4. Test with validation scripts

Custom Calibration Data

# Add to GGUF/resources/standard_cal_data/# Files should be UTF-8 text with one sample per line

📈 Performance Tips

TipDescription
🚀 GPU UsageUse CUDA/Metal for 5-10x speedup
💾 MemoryMonitor RAM usage with large models
🔄 Batch SizeAdjust based on available memory
📊 ThreadsSet to CPU core count for optimal CPU performance

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Test with ./scripts/validate.sh
  4. Submit a pull request

📄 License

This project is licensed under the terms specified in the LICENSE file.

🔗 Links


Ready to quantize? Start with ./scripts/setup.sh 🚀

About

No description, website, or topics provided.

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages