File size: 10,600 Bytes
05c5c96 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 | #!/usr/bin/env python3
"""
Utilities for working with GGUF models (Qwen, Mistral)
Plus comparison between GGUF teacher and student model
"""
import torch
import logging
from pathlib import Path
from typing import Optional, Dict
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# ============================================================================
# GGUF Loading (for inference only)
# ============================================================================
class GGUFWrapper:
"""
Wrapper for loading and using GGUF models
GGUF models are optimized for CPU/inference via llama.cpp
They cannot be used for training (no gradient computation)
Use cases:
- Inference speed benchmarking
- Comparing outputs with student model
- Validation without loading full model into GPU
"""
def __init__(self, gguf_path: str, n_gpu_layers: int = -1):
"""
Load GGUF model
Args:
gguf_path: Path to .gguf file
n_gpu_layers: Number of layers on GPU (-1 = all)
"""
try:
from llama_cpp import Llama
except ImportError:
logger.error("llama-cpp-python not installed. Install with:")
logger.error(" pip install llama-cpp-python")
raise
logger.info(f"Loading GGUF: {gguf_path}")
self.model = Llama(
model_path=gguf_path,
n_gpu_layers=n_gpu_layers,
n_ctx=512,
verbose=False,
)
self.gguf_path = gguf_path
logger.info("✓ GGUF model loaded")
def generate(self, prompt: str, max_tokens: int = 100, temperature: float = 0.7) -> str:
"""Generate text"""
output = self.model(
prompt,
max_tokens=max_tokens,
temperature=temperature,
top_p=0.95,
stop=["<|endoftext|>", "<|end|>"],
)
return output['choices'][0]['text']
def get_embedding(self, text: str):
"""Get text embedding"""
embedding = self.model.embed(text)
return torch.tensor(embedding)
def speed_test(self, prompt: str = "The future of AI", num_runs: int = 5) -> Dict:
"""Benchmark inference speed"""
import time
logger.info(f"Speed test ({num_runs} runs)...")
times = []
for _ in range(num_runs):
start = time.time()
self.generate(prompt, max_tokens=100)
elapsed = time.time() - start
times.append(elapsed)
avg_time = sum(times) / len(times)
logger.info(f"Average time per generation: {avg_time:.2f}s")
logger.info(f"Throughput: {100/avg_time:.1f} tokens/sec")
return {
'avg_time_sec': avg_time,
'throughput_tokens_per_sec': 100 / avg_time,
}
# ============================================================================
# GGUF vs Student Comparison
# ============================================================================
class ModelComparison:
"""Compare GGUF teacher with student model"""
def __init__(self, gguf_path: str, student_checkpoint: str, device: str = "cuda"):
"""
Load both models for comparison
Args:
gguf_path: Path to GGUF teacher
student_checkpoint: Path to student checkpoint
device: Device for student model
"""
self.device = torch.device(device)
# Load GGUF teacher
try:
self.gguf_teacher = GGUFWrapper(gguf_path)
except Exception as e:
logger.warning(f"Could not load GGUF: {e}")
self.gguf_teacher = None
# Load student
from qwen_inference import StudentInference
self.student = StudentInference(student_checkpoint, device=device)
self.tokenizer = self.student.tokenizer
def compare_generations(self, prompt: str, max_length: int = 100):
"""Generate from both models and compare"""
logger.info(f"\nPrompt: '{prompt}'\n")
# Student generation
logger.info("Generating with student...")
student_text = self.student.generate(prompt, max_length=max_length)
logger.info(f"Student:\n{student_text}\n")
# GGUF generation
if self.gguf_teacher:
logger.info("Generating with GGUF teacher...")
teacher_text = self.gguf_teacher.generate(prompt, max_tokens=max_length)
logger.info(f"GGUF Teacher:\n{teacher_text}\n")
else:
logger.warning("GGUF teacher not available")
def compare_speed(self, prompt: str = "The future of AI"):
"""Compare inference speed"""
logger.info("\nSpeed Comparison\n")
# Student speed
logger.info("Student speed test...")
student_stats = self.student.inference_speed_test(prompt, num_runs=10)
# GGUF speed
if self.gguf_teacher:
logger.info("\nGGUF speed test...")
gguf_stats = self.gguf_teacher.speed_test(prompt, num_runs=5)
logger.info(f"\n{'Model':<20} {'Time (ms)':<12} {'Throughput':<20}")
logger.info("=" * 52)
logger.info(f"{'Student':<20} {student_stats['avg_time_ms']:<12.1f} "
f"{student_stats['throughput']:.1f} samples/s")
logger.info(f"{'GGUF':<20} {gguf_stats['avg_time_sec']*1000:<12.1f} "
f"{gguf_stats['throughput_tokens_per_sec']:.1f} tokens/s")
speedup = (gguf_stats['avg_time_sec'] * 1000) / student_stats['avg_time_ms']
logger.info(f"\nStudent is {speedup:.1f}x faster than GGUF")
else:
logger.warning("GGUF teacher not available for comparison")
# ============================================================================
# Model Information & Utilities
# ============================================================================
class ModelInfo:
"""Get info about models"""
@staticmethod
def print_student_info(checkpoint_path: str):
"""Print student model info"""
checkpoint = torch.load(checkpoint_path, map_location="cpu")
config = checkpoint['config']
logger.info(f"\nStudent Model Info:")
logger.info(f"{'Parameter':<30} {'Value':<20}")
logger.info("=" * 50)
logger.info(f"{'Layers':<30} {config.get('student_num_layers', 'N/A'):<20}")
logger.info(f"{'Hidden Dimension':<30} {config.get('student_hidden_dim', 'N/A'):<20}")
logger.info(f"{'Num Heads':<30} {config.get('student_num_heads', 'N/A'):<20}")
logger.info(f"{'Max Seq Length':<30} {config.get('max_seq_length', 'N/A'):<20}")
logger.info(f"{'Temperature':<30} {config.get('temperature', 'N/A'):<20}")
logger.info(f"{'Training Steps':<30} {checkpoint.get('global_step', 'N/A'):<20}")
# Count parameters
model_size = sum(p.numel() for p in checkpoint['model_state_dict'].values())
logger.info(f"{'Total Parameters':<30} {model_size/1e6:.1f}M")
logger.info(f"{'Model Size (FP32)':<30} {model_size*4/1e9:.2f}GB")
logger.info(f"{'Model Size (FP16)':<30} {model_size*2/1e9:.2f}GB")
@staticmethod
def gguf_info(gguf_path: str):
"""Print GGUF model info"""
try:
from llama_cpp import Llama
llm = Llama(model_path=gguf_path, n_gpu_layers=0)
logger.info(f"\nGGUF Model Info:")
logger.info(f"Path: {gguf_path}")
logger.info(f"Size: {Path(gguf_path).stat().st_size / 1e9:.2f}GB")
# llama.cpp doesn't expose detailed arch info easily
except Exception as e:
logger.error(f"Could not load GGUF: {e}")
# ============================================================================
# Conversion Utilities
# ============================================================================
class GGUFConverter:
"""
Convert GGUF ↔ HuggingFace formats
Note: Requires knowing the model architecture
"""
@staticmethod
def gguf_to_huggingface(gguf_path: str, output_dir: str, model_type: str = "llama"):
"""
Convert GGUF to HuggingFace format
Supported model_type: "llama", "mistral", "qwen"
WARNING: This is complex and often requires manual config adjustment
Easier alternative: Download HuggingFace model directly
"""
logger.warning("GGUF conversion is complex and model-specific")
logger.warning("Recommend: Download equivalent from HuggingFace instead")
logger.info(f"Example: huggingface-cli download Qwen/Qwen2.5-0.5B")
# ============================================================================
# Main - Usage Examples
# ============================================================================
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--gguf", help="Path to GGUF model")
parser.add_argument("--student", help="Path to student checkpoint")
parser.add_argument("--compare", action="store_true", help="Compare GGUF vs student")
parser.add_argument("--gguf-info", action="store_true", help="Print GGUF info")
parser.add_argument("--student-info", action="store_true", help="Print student info")
parser.add_argument("--prompt", default="The future of AI", help="Generation prompt")
args = parser.parse_args()
# GGUF information
if args.gguf_info and args.gguf:
ModelInfo.gguf_info(args.gguf)
# Student information
if args.student_info and args.student:
ModelInfo.print_student_info(args.student)
# Comparison
if args.compare and args.gguf and args.student:
comp = ModelComparison(args.gguf, args.student)
comp.compare_generations(args.prompt)
comp.compare_speed(args.prompt)
# Default: Simple GGUF loading and generation
if args.gguf and not (args.compare or args.gguf_info):
logger.info("Loading GGUF model (inference only)...")
gguf = GGUFWrapper(args.gguf)
logger.info(f"\nPrompt: {args.prompt}")
text = gguf.generate(args.prompt, max_tokens=100)
logger.info(f"\nGenerated:\n{text}")
logger.info("\nSpeed test...")
stats = gguf.speed_test(args.prompt, num_runs=3)
|