Okay, here is a Python script designed to benchmark different GGUF quantization levels (Q2_K to Q8_0) of the Qwen2-0.5B-Instruct model using llama-cpp-python.
Clarifications:
- Model: The common small Qwen model is Qwen2 0.5B, not Qwen3 0.6B. This script uses
Qwen/Qwen2-0.5B-Instruct-GGUF.
- Quantization:
llama-cpp-python uses GGUF files which are pre-quantized. "Unsloth dynamic quantized" usually refers to techniques applied during training or runtime with libraries like Unsloth specifically for PyTorch models, not directly applicable to loading pre-quantized GGUF files via llama-cpp-python. This script uses standard GGUF files.
- CPU/Memory Measurement: The script measures:
- Time Taken: Wall-clock time for the generation call.
- Approx. Memory Usage: The increase in the Python process's Resident Set Size (RSS) memory after loading the model. This is a practical measure of the model's RAM footprint within this process. It doesn't capture complex shared memory or exact peak usage during computation but serves well for comparison.
- CPU Usage: Directly measuring CPU load specifically for the generation task within a Python script is complex. Generation time on a consistent machine serves as a good proxy for CPU intensity – faster times generally mean less CPU time consumed for the same task. We will focus on Time and Memory.
Prerequisites:
- Python: Ensure you have Python 3.8+ installed.
- llama-cpp-python: Install with CPU support. If you have a C compiler setup (like GCC/Clang or MSVC build tools):
pip install llama-cpp-python
Or, refer to the llama-cpp-python documentation for detailed installation instructions specific to your OS.
- Other Libraries:
pip install huggingface_hub psutil tabulate
Python Script (benchmark_qwen2_gguf.py):
import os
import time
import psutil # For memory usage
import gc # For garbage collection
from huggingface_hub import hf_hub_download
from llama_cpp import Llama
from tabulate import tabulate
# --- Configuration ---
MODEL_REPO = "Qwen/Qwen2-0.5B-Instruct-GGUF"
# Select quantization levels between Q2 and Q8
# Common available quants for Qwen2-0.5B:
# ['Q2_K', 'Q3_K_M', 'Q4_0', 'Q4_K_M', 'Q5_K_M', 'Q6_K', 'Q8_0']
# Adjust this list based on available files in the repo if needed
QUANTS_TO_TEST = ["Q2_K", "Q3_K_M", "Q4_K_M", "Q5_K_M", "Q6_K", "Q8_0"]
# Ensure filenames match the Hugging Face repo structure (lowercase usually)
# Example: qwen2-0_5b-instruct-q2_k.gguf
MODEL_FILENAMES = {
q: f"qwen2-0_5b-instruct-{q.lower()}.gguf" for q in QUANTS_TO_TEST
}
DOWNLOAD_DIR = "./gguf_models" # Directory to save models
PROMPT = "Write a short story about a curious robot exploring an ancient library."
MAX_TOKENS_GENERATION = 150 # Number of tokens to generate for benchmark
N_CTX = 2048 # Context window size
# --- Benchmarking Setup ---
results = []
process = psutil.Process() # Get current process for memory measurement
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
print("Starting GGUF Model Benchmark...")
print(f"Models will be downloaded to: {DOWNLOAD_DIR}")
print(f"Testing Prompt: '{PROMPT}' (generating max {MAX_TOKENS_GENERATION} tokens)")
print("-" * 60)
# --- Main Loop ---
for quant in QUANTS_TO_TEST:
filename = MODEL_FILENAMES.get(quant)
if not filename:
print(f"Skipping {quant}: Filename not defined.")
continue
model_path = os.path.join(DOWNLOAD_DIR, filename)
llm = None # Ensure llm is None at the start of the loop
print(f"\n--- Testing Quantization: {quant} ({filename}) ---")
# --- 1. Download Model ---
if not os.path.exists(model_path):
print(f"Downloading {filename} from {MODEL_REPO}...")
try:
hf_hub_download(
repo_id=MODEL_REPO,
filename=filename,
local_dir=DOWNLOAD_DIR,
local_dir_use_symlinks=False # Recommended for Windows / cleaner storage
)
print("Download complete.")
except Exception as e:
print(f"ERROR: Failed to download {filename}. Skipping. Error: {e}")
continue
else:
print("Model found locally.")
# --- 2. Benchmark ---
try:
# Measure memory before loading
gc.collect() # Run GC before measurement for consistency
mem_before_load = process.memory_info().rss
# print(f"Memory before load: {mem_before_load / (1024**2):.2f} MiB") # Debug print
# Load model - CPU only
print("Loading model...")
load_start_time = time.perf_counter()
llm = Llama(
model_path=model_path,
n_ctx=N_CTX,
n_gpu_layers=0, # Ensure CPU execution
verbose=False # Set to True for detailed llama.cpp output
)
load_end_time = time.perf_counter()
load_time = load_end_time - load_start_time
print(f"Model loaded in {load_time:.2f} seconds.")
# Measure memory after loading
gc.collect()
mem_after_load = process.memory_info().rss
memory_used_mib = (mem_after_load - mem_before_load) / (1024 * 1024) # In MiB
print(f"Approx. Memory Increase (RSS): {memory_used_mib:.2f} MiB")
# Optional Warmup (run a very small generation to initialize internal states)
_ = llm(PROMPT[:10], max_tokens=2, temperature=0.1)
# Generate Text & Time it
print(f"Generating response (max {MAX_TOKENS_GENERATION} tokens)...")
gen_start_time = time.perf_counter()
response = llm(
PROMPT,
max_tokens=MAX_TOKENS_GENERATION,
temperature=0.7, # Typical generation temperature
stop=["<|im_end|>", "\n"] # Use appropriate stop tokens if needed
)
gen_end_time = time.perf_counter()
generation_time = gen_end_time - gen_start_time
generated_text = response['choices'][0]['text'].strip()
print(f"Generation finished in {generation_time:.2f} seconds.")
# print(f"Generated Text Snippet: {generated_text[:100]}...") # Optional: print output
# Store results
results.append({
"Quant": quant,
"Load Time (s)": f"{load_time:.2f}",
"Memory Usage (MiB)": f"{memory_used_mib:.2f}",
"Generation Time (s)": f"{generation_time:.2f}",
"Output Snippet": generated_text[:60].replace('\n', ' ') + "..."
})
except Exception as e:
print(f"ERROR: Failed during processing {quant}. Skipping. Error: {e}")
finally:
# --- 3. Cleanup ---
if llm is not None:
# Explicitly delete the Llama object to trigger __del__ and release C++ resources
del llm
llm = None
# Force garbage collection to release Python-level memory
gc.collect()
print("Model unloaded, attempting memory release.")
# Optional: Check memory after cleanup
# mem_after_cleanup = process.memory_info().rss
# print(f"Memory after cleanup: {mem_after_cleanup / (1024**2):.2f} MiB")
# --- 4. Display Results ---
print("\n" + "=" * 60)
print(" Benchmark Summary")
print("=" * 60)
if results:
# Sort results by Quant name for consistent order (optional)
results.sort(key=lambda x: QUANTS_TO_TEST.index(x['Quant']))
print(tabulate(results, headers="keys", tablefmt="grid"))
else:
print("No results were generated due to errors or configuration.")
print("\nBenchmark finished.")
How to Run:
- Save the code above as a Python file (e.g.,
benchmark_qwen2_gguf.py).
- Open your terminal or command prompt.
- Navigate to the directory where you saved the file.
- Run the script using Python:
python benchmark_qwen2_gguf.py
Explanation:
- Configuration: Sets up the model repository, quantization levels to test, filenames, download directory, prompt, and generation parameters.
- Setup: Creates the download directory if it doesn't exist and initializes an empty list
results to store benchmark data. It also gets the current process handle using psutil to measure its memory.
- Looping through Quants: The script iterates through each quantization level specified in
QUANTS_TO_TEST.
- Download: It checks if the model file exists locally. If not, it downloads it from the Hugging Face Hub using
hf_hub_download.
- Measure & Load: It records the process memory before loading the model. Then, it instantiates the
Llama object with n_gpu_layers=0 for CPU execution and measures the time taken. After loading, it measures the process memory again and calculates the increase in MiB.
- Generate & Time: It runs a generation task using the defined prompt and
max_tokens. The time taken for just the generation call (llm(...)) is measured.
- Store Results: Key metrics (Quantization Type, Load Time, Memory Increase, Generation Time, Output Snippet) are stored in the
results list.
- Cleanup: This is crucial.
del llm explicitly removes the reference to the Llama object, allowing its internal C++ resources to be potentially freed. gc.collect() encourages Python's garbage collector to reclaim memory. This helps provide a cleaner memory baseline before loading the next model in the loop.
- Display Results: Finally, after testing all models, the script uses the
tabulate library to print the collected results in a nicely formatted table.
This script provides a standardized way to compare the performance and resource usage of different GGUF quantization levels for the specified Qwen2 model on your CPU.