MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / studio.py
| 1 | #!/usr/bin/env python3 |
| 2 | """MojoLlama Studio — train, export, dataset, merge, chat, benchmark. |
| 3 | |
| 4 | Usage: |
| 5 | mojollama-studio train --model model.gguf --data dataset.jsonl |
| 6 | mojollama-studio export --hf meta-llama/Llama-3.2-1B --outtype q4_0 |
| 7 | mojollama-studio dataset create --output data.jsonl |
| 8 | mojollama-studio dataset auto-label --model model.gguf --input prompts.jsonl |
| 9 | mojollama-studio merge --base model.gguf --lora adapter.gguf --output merged.gguf |
| 10 | mojollama-studio chat --model model.gguf |
| 11 | mojollama-studio serve --model model.gguf --port 9000 |
| 12 | mojollama-studio benchmark --model model.gguf |
| 13 | """ |
| 14 | |
| 15 | import os |
| 16 | import sys |
| 17 | import json |
| 18 | import time |
| 19 | import argparse |
| 20 | import subprocess |
| 21 | import urllib.request |
| 22 | from pathlib import Path |
| 23 | |
| 24 | import numpy as np |
| 25 | |
| 26 | # Auto-tuner for server optimization |
| 27 | from mojollama.autotune import autotune, save_config, print_config, load_config |
| 28 | from mojollama.dataset import ( |
| 29 | load_dataset, StreamingDataset, get_dataset_info, find_datasets, |
| 30 | convert_dataset, compute_stats, split_dataset, write_jsonl, |
| 31 | AutoLabeler, compute_confidence, ALL_FORMATS, FORMAT_DESCRIPTIONS, |
| 32 | detect_format, |
| 33 | ) |
| 34 | |
| 35 | STUDIO_VERSION = "0.2.0" |
| 36 | BASE_DIR = Path(__file__).parent.parent.parent.resolve() |
| 37 | LLAMA_CPP = "/tmp/llama.cpp" |
| 38 | CONVERTER = f"{LLAMA_CPP}/convert_hf_to_gguf.py" |
| 39 | FINETUNE_BIN = f"{LLAMA_CPP}/build/examples/training/llama-finetune" |
| 40 | SERVER_BIN = f"{LLAMA_CPP}/build/bin/llama-server" |
| 41 | CHAT_HTML = f"{BASE_DIR}/www/chat.html" |
| 42 | INDEX_HTML = f"{BASE_DIR}/www/index.html" |
| 43 | |
| 44 | # ── Model registry ────────────────────────────────────────── |
| 45 | MODEL_REGISTRY = Path.home() / ".mojollama" / "models.json" |
| 46 | MODEL_CACHE = Path.home() / ".cache" / "mojollama" / "models" |
| 47 | os.makedirs(MODEL_CACHE, exist_ok=True) |
| 48 | os.makedirs(MODEL_REGISTRY.parent, exist_ok=True) |
| 49 | |
| 50 | |
| 51 | def _load_model_registry(): |
| 52 | """Load the model registry (connected models).""" |
| 53 | if MODEL_REGISTRY.exists(): |
| 54 | try: |
| 55 | return json.loads(MODEL_REGISTRY.read_text()) |
| 56 | except Exception: |
| 57 | return {"connected": {}} |
| 58 | return {"connected": {}} |
| 59 | |
| 60 | |
| 61 | def _save_model_registry(registry): |
| 62 | """Save the model registry.""" |
| 63 | MODEL_REGISTRY.write_text(json.dumps(registry, indent=2)) |
| 64 | |
| 65 | |
| 66 | def _resolve_model(model_spec): |
| 67 | """Resolve a model spec to a local path. |
| 68 | |
| 69 | Accepts: |
| 70 | - Local path (/path/to/model.gguf) |
| 71 | - HF repo ID (Qwen/Qwen3-30B-A3B-Instruct-GGUF) |
| 72 | - Alias name from registry (my-model) |
| 73 | |
| 74 | Returns (local_path, source) tuple. |
| 75 | """ |
| 76 | if not model_spec: |
| 77 | return None, None |
| 78 | |
| 79 | # 1) Direct local path |
| 80 | if os.path.exists(model_spec): |
| 81 | return os.path.abspath(model_spec), "local" |
| 82 | |
| 83 | # 2) Check registry aliases |
| 84 | reg = _load_model_registry() |
| 85 | if model_spec in reg.get("connected", {}): |
| 86 | entry = reg["connected"][model_spec] |
| 87 | lp = entry.get("local_path", "") |
| 88 | if os.path.exists(lp): |
| 89 | return lp, f"registry:{model_spec}" |
| 90 | print(f" ⚠ Registry entry '{model_spec}' has missing local path, re-downloading...") |
| 91 | |
| 92 | # 3) Check if it's already a downloaded file in cache |
| 93 | cached = list(MODEL_CACHE.glob(f"**/*{model_spec.split('/')[-1]}*")) |
| 94 | if cached: |
| 95 | return str(cached[0]), "cache" |
| 96 | |
| 97 | # 4) Treat as HF repo ID — auto-download |
| 98 | return _download_hf_model(model_spec), "hf" |
| 99 | |
| 100 | |
| 101 | def _download_hf_model(repo_id, filename=None): |
| 102 | """Download a model from HuggingFace Hub to local cache. |
| 103 | |
| 104 | Returns local path. Uses hf_hub_download or huggingface_hub CLI. |
| 105 | """ |
| 106 | local_name = repo_id.replace("/", "--") |
| 107 | dest_dir = MODEL_CACHE / local_name |
| 108 | dest_dir.mkdir(parents=True, exist_ok=True) |
| 109 | |
| 110 | # Check if already downloaded |
| 111 | existing = list(dest_dir.glob("*.gguf")) |
| 112 | if existing: |
| 113 | return str(existing[0]) |
| 114 | |
| 115 | print(f" 📥 Downloading {repo_id} from HuggingFace Hub...") |
| 116 | print(f" Target: {dest_dir}") |
| 117 | |
| 118 | try: |
| 119 | from huggingface_hub import hf_hub_download, list_repo_files |
| 120 | |
| 121 | # List files to find the GGUF |
| 122 | files = [f for f in list_repo_files(repo_id) if f.endswith(".gguf")] |
| 123 | if not files: |
| 124 | print(f" ❌ No GGUF files found in {repo_id}") |
| 125 | return None |
| 126 | |
| 127 | # Pick the best one (prefer Q4_K_M, then largest) |
| 128 | if filename: |
| 129 | selected = [f for f in files if filename in f] |
| 130 | if selected: |
| 131 | files = selected |
| 132 | |
| 133 | # Auto-select: prefer Q4_K_M, then largest quant |
| 134 | preferred = [f for f in files if "q4_k_m" in f.lower() or "Q4_K_M" in f] |
| 135 | if not preferred: |
| 136 | preferred = sorted(files) # sort alphabetically, gives stable selection |
| 137 | target = preferred[0] |
| 138 | |
| 139 | print(f" File: {target}") |
| 140 | local_path = hf_hub_download(repo_id=repo_id, filename=target, |
| 141 | cache_dir=str(dest_dir)) |
| 142 | print(f" ✅ Downloaded to {local_path}") |
| 143 | return local_path |
| 144 | |
| 145 | except ImportError: |
| 146 | print(f" ⚠ huggingface_hub not installed, trying HF CLI...") |
| 147 | try: |
| 148 | result = subprocess.run( |
| 149 | ["huggingface-cli", "download", repo_id, "--local-dir", str(dest_dir)], |
| 150 | capture_output=True, text=True, timeout=600 |
| 151 | ) |
| 152 | if result.returncode == 0: |
| 153 | ggufs = list(dest_dir.rglob("*.gguf")) |
| 154 | if ggufs: |
| 155 | print(f" ✅ Downloaded to {ggufs[0]}") |
| 156 | return str(ggufs[0]) |
| 157 | print(f" ❌ HF download failed: {result.stderr[:200]}") |
| 158 | return None |
| 159 | except FileNotFoundError: |
| 160 | print(f" ❌ huggingface_hub CLI not available") |
| 161 | print(f" Install: pip install huggingface_hub") |
| 162 | return None |
| 163 | except Exception as e: |
| 164 | print(f" ❌ Download failed: {e}") |
| 165 | return None |
| 166 | |
| 167 | |
| 168 | def cmd_connect(args): |
| 169 | """Connect to a model from HuggingFace Hub or local path. |
| 170 | |
| 171 | Downloads the model (if remote) and registers it in the model registry |
| 172 | with an alias name so all studio commands can use it. |
| 173 | """ |
| 174 | print_banner() |
| 175 | print("[Connect] Model Registration") |
| 176 | print() |
| 177 | |
| 178 | spec = args.spec or input("Model (HF repo ID or local path): ").strip() |
| 179 | if not spec: |
| 180 | print("❌ No model specified") |
| 181 | return |
| 182 | |
| 183 | alias = args.alias or input(f"Alias name [{Path(spec).stem}]: ").strip() or Path(spec).stem |
| 184 | |
| 185 | print(f"\n Resolving: {spec}") |
| 186 | local_path, source = _resolve_model(spec) |
| 187 | |
| 188 | if not local_path or not os.path.exists(local_path): |
| 189 | print(f"❌ Could not resolve model: {spec}") |
| 190 | return |
| 191 | |
| 192 | # Detect engine type |
| 193 | engine_type = "unknown" |
| 194 | try: |
| 195 | from mojollama.benchmarks.bench_tok import detect_engine_type |
| 196 | engine_type = detect_engine_type(local_path) |
| 197 | except Exception: |
| 198 | pass |
| 199 | |
| 200 | # Register |
| 201 | reg = _load_model_registry() |
| 202 | reg["connected"][alias] = { |
| 203 | "spec": spec, |
| 204 | "local_path": local_path, |
| 205 | "engine_type": engine_type, |
| 206 | "connected_at": time.strftime("%Y-%m-%dT%H:%M:%S"), |
| 207 | "size_gb": round(os.path.getsize(local_path) / (1024**3), 1), |
| 208 | } |
| 209 | _save_model_registry(reg) |
| 210 | |
| 211 | print(f"\n ✅ Model registered as '{alias}'") |
| 212 | print(f" Path: {local_path}") |
| 213 | print(f" Engine: {engine_type}") |
| 214 | print(f" Size: {reg['connected'][alias]['size_gb']:.1f} GB") |
| 215 | print(f"\n You can now use this model in any studio command:") |
| 216 | print(f" mojollama-studio chat --model {alias}") |
| 217 | print(f" mojollama-studio benchmark --model {alias}") |
| 218 | print(f" mojollama-studio train --model {alias} --data dataset.jsonl") |
| 219 | print(f" mojollama-studio serve --model {alias} --port 8080") |
| 220 | |
| 221 | |
| 222 | def cmd_models(args): |
| 223 | """List connected models.""" |
| 224 | reg = _load_model_registry() |
| 225 | connected = reg.get("connected", {}) |
| 226 | |
| 227 | if not connected: |
| 228 | print_banner() |
| 229 | print("[Models] No connected models") |
| 230 | print() |
| 231 | print(" Connect a model:") |
| 232 | print(" mojollama-studio connect Qwen/Qwen3-30B-A3B-Instruct-GGUF") |
| 233 | print(" mojollama-studio connect /path/to/model.gguf --alias my-model") |
| 234 | return |
| 235 | |
| 236 | print_banner() |
| 237 | print(f"[Models] {len(connected)} connected") |
| 238 | print() |
| 239 | print(f" {'Alias':<24s} {'Engine':<10s} {'Size':>6s} {'Source':<40s}") |
| 240 | print(f" {'─'*24} {'─'*10} {'─'*6} {'─'*40}") |
| 241 | for alias, entry in sorted(connected.items()): |
| 242 | etype = entry.get("engine_type", "?") |
| 243 | size = f"{entry.get('size_gb', 0):.1f}G" |
| 244 | spec = entry.get("spec", entry.get("local_path", "?"))[:40] |
| 245 | exists = "✅" if os.path.exists(entry.get("local_path", "")) else "❌" |
| 246 | print(f" {exists} {alias:<22s} {etype:<10s} {size:>6s} {spec:<40s}") |
| 247 | print(f"\n To use: mojollama-studio <command> --model <alias>") |
| 248 | |
| 249 | |
| 250 | def _get_model(spec): |
| 251 | """Resolve a model spec (path, alias, or HF repo) to local path. Handles input prompts.""" |
| 252 | if not spec: |
| 253 | return None |
| 254 | path, source = _resolve_model(spec) |
| 255 | if path and os.path.exists(path): |
| 256 | if source.startswith("registry"): |
| 257 | print(f" Model: {spec} ({path})") |
| 258 | elif source == "hf": |
| 259 | print(f" Model: {spec} → downloaded ✅") |
| 260 | return path |
| 261 | print(f" ❌ Could not resolve model: {spec}") |
| 262 | return None |
| 263 | |
| 264 | |
| 265 | def print_banner(): |
| 266 | print("╔═══════════════════════════════════════════╗") |
| 267 | print("║ MojoLlama Studio v" + STUDIO_VERSION + " ║") |
| 268 | print("║ Train · Export · Dataset · Chat ║") |
| 269 | print("╚═══════════════════════════════════════════╝") |
| 270 | print() |
| 271 | |
| 272 | |
| 273 | # ─── Train ───────────────────────────────────────────────────────────── |
| 274 | |
| 275 | TRAINING_METHODS = { |
| 276 | "lora": "Low-Rank Adaptation (standard, via llama-finetune)", |
| 277 | "qlora": "Quantized LoRA (NF4 base + LoRA adapters)", |
| 278 | "dora": "Weight-Decomposed Low-Rank Adaptation", |
| 279 | "galore": "Gradient Low-Rank Projection (memory-efficient full FT)", |
| 280 | "dpo": "Direct Preference Optimization (preference pairs)", |
| 281 | "orpo": "Odds Ratio Preference Optimization", |
| 282 | "kto": "Kahneman-Tversky Optimization (unpaired preferences)", |
| 283 | "simpo": "Simple Preference Optimization", |
| 284 | "grpo": "Group Relative Policy Optimization (RL fine-tuning)", |
| 285 | } |
| 286 | |
| 287 | def cmd_train(args): |
| 288 | """Fine-tune a model using one of the supported training methods.""" |
| 289 | from mojollama.trainer import MojoLlamaTrainer, emit_metric |
| 290 | |
| 291 | if args.list_methods: |
| 292 | print_banner() |
| 293 | print("[Train] Available training methods:\n") |
| 294 | for name, desc in TRAINING_METHODS.items(): |
| 295 | print(f" {name:8s} — {desc}") |
| 296 | return |
| 297 | |
| 298 | print_banner() |
| 299 | |
| 300 | if args.method and args.method not in TRAINING_METHODS: |
| 301 | print(f"❌ Unknown method: {args.method}") |
| 302 | print("Available methods: lora, qlora, dora, galore, dpo, orpo, kto, simpo, grpo") |
| 303 | return |
| 304 | |
| 305 | model = args.model or input("Model path (GGUF): ").strip() |
| 306 | data = args.data or input("Training data path: ").strip() |
| 307 | method = args.method or "lora" |
| 308 | lora_out = args.lora_out or "adapter.gguf" |
| 309 | |
| 310 | if not os.path.exists(data): |
| 311 | print(f"\n❌ Training data not found: {data}") |
| 312 | print("Create one with: mojollama-studio dataset create") |
| 313 | return |
| 314 | |
| 315 | # Build kwargs for method-specific params |
| 316 | kwargs = {} |
| 317 | if method == "dpo": |
| 318 | kwargs["dpo_beta"] = args.dpo_beta |
| 319 | kwargs["dpo_lr"] = args.lr |
| 320 | elif method == "orpo": |
| 321 | kwargs["orpo_lambda"] = args.orpo_lambda |
| 322 | kwargs["orpo_lr"] = args.lr |
| 323 | elif method == "simpo": |
| 324 | kwargs["simpo_gamma"] = args.simpo_gamma |
| 325 | kwargs["simpo_lr"] = args.lr |
| 326 | elif method == "grpo": |
| 327 | kwargs["grpo_group_size"] = args.grpo_group_size |
| 328 | kwargs["grpo_clip"] = args.grpo_clip |
| 329 | kwargs["grpo_lr"] = args.lr |
| 330 | elif method == "galore": |
| 331 | kwargs["galore_lr"] = args.lr |
| 332 | kwargs["galore_rank"] = args.galore_rank |
| 333 | |
| 334 | trainer = MojoLlamaTrainer( |
| 335 | model_path=model, |
| 336 | data_path=data, |
| 337 | method=method, |
| 338 | lora_rank=args.lora_rank, |
| 339 | lora_alpha=args.lora_alpha, |
| 340 | lr=args.lr, |
| 341 | weight_decay=args.weight_decay, |
| 342 | epochs=args.epochs, |
| 343 | batch_size=args.batch, |
| 344 | max_seq_length=args.max_seq_length, |
| 345 | output_path=lora_out, |
| 346 | save_steps=args.save_steps, |
| 347 | seed=args.seed, |
| 348 | warmup_steps=args.warmup_steps, |
| 349 | dataset_format=args.dataset_format or "auto", |
| 350 | max_samples=args.max_samples, |
| 351 | template=args.template or "alpaca", |
| 352 | **kwargs, |
| 353 | ) |
| 354 | |
| 355 | trainer.train() |
| 356 | |
| 357 | |
| 358 | # ─── Export ──────────────────────────────────────────────────────────── |
| 359 | |
| 360 | def cmd_export(args): |
| 361 | """Convert HF model → GGUF.""" |
| 362 | print_banner() |
| 363 | print("[Export] HuggingFace → GGUF converter") |
| 364 | print() |
| 365 | |
| 366 | model = args.hf or args.model or input("HF model ID or path: ").strip() |
| 367 | outtype = args.outtype or "q4_0" |
| 368 | outfile = args.outfile or f"{model.split('/')[-1]}-{outtype}.gguf" |
| 369 | |
| 370 | # Supported direct types vs types needing post-quantization |
| 371 | direct_types = {"f32", "f16", "bf16", "q8_0", "tq1_0", "tq2_0", "auto"} |
| 372 | post_quant_types = {"q4_0", "q4_1", "q5_0", "q5_1", "q2_k", "q3_k", "q4_k", "q5_k", "q6_k", "q8_k"} |
| 373 | |
| 374 | if outtype in direct_types: |
| 375 | intermediate = outfile |
| 376 | elif outtype in post_quant_types: |
| 377 | # Step 1: convert to f16 first |
| 378 | intermediate = outfile.replace(f"-{outtype}.gguf", "-f16.gguf") |
| 379 | if intermediate == outfile: |
| 380 | intermediate = outfile.replace(".gguf", "-f16.gguf") |
| 381 | print(f"Step 1: Converting to F16 first...") |
| 382 | else: |
| 383 | print(f"Unsupported outtype: {outtype}") |
| 384 | print(f"Supported: {', '.join(sorted(direct_types | post_quant_types))}") |
| 385 | return |
| 386 | |
| 387 | cmd = [sys.executable, CONVERTER, model, "--outtype", "f16" if outtype in post_quant_types else outtype, |
| 388 | "--outfile", intermediate] |
| 389 | if args.remote: |
| 390 | cmd.append("--remote") |
| 391 | if args.vocab_only: |
| 392 | cmd.append("--vocab-only") |
| 393 | |
| 394 | print(f"Source: {model}") |
| 395 | print(f"Intermediate: {intermediate}") |
| 396 | print(f"Final: {outfile}") |
| 397 | print() |
| 398 | |
| 399 | t0 = time.time() |
| 400 | subprocess.run(cmd, check=True) |
| 401 | elapsed = time.time() - t0 |
| 402 | |
| 403 | # Step 2: post-quantize if needed |
| 404 | if outtype in post_quant_types: |
| 405 | print(f"\nStep 2: Quantizing {intermediate} → {outtype}...") |
| 406 | from gguf import quantize as gguf_quantize |
| 407 | from gguf import GGMLQuantizationType, GGUFReader |
| 408 | |
| 409 | qt_map = { |
| 410 | "q4_0": GGMLQuantizationType.Q4_0, |
| 411 | "q4_1": GGMLQuantizationType.Q4_1, |
| 412 | "q5_0": GGMLQuantizationType.Q5_0, |
| 413 | "q5_1": GGMLQuantizationType.Q5_1, |
| 414 | "q2_k": GGMLQuantizationType.Q2_K, |
| 415 | "q3_k": GGMLQuantizationType.Q3_K, |
| 416 | "q4_k": GGMLQuantizationType.Q4_K, |
| 417 | "q5_k": GGMLQuantizationType.Q5_K, |
| 418 | "q6_k": GGMLQuantizationType.Q6_K, |
| 419 | "q8_k": GGMLQuantizationType.Q8_K, |
| 420 | } |
| 421 | target_qt = qt_map.get(outtype) |
| 422 | |
| 423 | if target_qt: |
| 424 | reader = GGUFReader(intermediate) |
| 425 | print(f" Read {len(reader.tensors)} tensors from intermediate") |
| 426 | |
| 427 | from gguf import GGUFWriter |
| 428 | writer = GGUFWriter(outfile, "llama") |
| 429 | |
| 430 | # Copy KV metadata (simplified) |
| 431 | for name, field in reader.fields.items(): |
| 432 | if name.startswith("GGUF."): |
| 433 | continue |
| 434 | # Copy known types |
| 435 | from gguf import GGUFValueType |
| 436 | if field.types[-1] == GGUFValueType.STRING: |
| 437 | val = bytes(field.parts[-1]).decode('utf-8') if hasattr(field.parts[-1], 'tobytes') else str(field.parts[-1]) |
| 438 | writer.add_string(name, val) |
| 439 | elif field.types[-1] in (GGUFValueType.UINT32, GGUFValueType.INT32, GGUFValueType.UINT64, GGUFValueType.INT64): |
| 440 | val = int(field.parts[-1].item()) if hasattr(field.parts[-1], 'item') else int(field.parts[-1]) |
| 441 | writer.add_uint32(name, val) |
| 442 | elif field.types[-1] == GGUFValueType.FLOAT32: |
| 443 | val = float(field.parts[-1].item()) if hasattr(field.parts[-1], 'item') else float(field.parts[-1]) |
| 444 | writer.add_float32(name, val) |
| 445 | |
| 446 | # Copy tensors with quantization |
| 447 | for t in reader.tensors: |
| 448 | data = np.asarray(t.data) |
| 449 | new_data = gguf_quantize(data, target_qt) if t.tensor_type != target_qt.value else data |
| 450 | writer.add_tensor(t.name, new_data, raw_dtype=target_qt) |
| 451 | |
| 452 | writer.write_header_to_file() |
| 453 | writer.write_kv_data_to_file() |
| 454 | writer.write_tensors_to_file(progress=True) |
| 455 | writer.close() |
| 456 | os.remove(intermediate) |
| 457 | print(f" Quantized to {outtype}") |
| 458 | else: |
| 459 | # Fall back to copy |
| 460 | import shutil |
| 461 | shutil.copy(intermediate, outfile) |
| 462 | |
| 463 | size_mb = os.path.getsize(outfile) / 1024**2 if os.path.exists(outfile) else 0 |
| 464 | elapsed = time.time() - t0 |
| 465 | print(f"\n✅ Exported to {outfile} ({size_mb:.0f} MB, {elapsed:.0f}s)") |
| 466 | |
| 467 | |
| 468 | # ─── Merge ────────────────────────────────────────────────────────────── |
| 469 | |
| 470 | def cmd_merge(args): |
| 471 | """Merge LoRA/QLoRA adapter into base GGUF model. |
| 472 | |
| 473 | Supports both standard LoRA and QLoRA (NF4) adapters. |
| 474 | Uses Python-based merge from gguf library for full control, |
| 475 | or falls back to llama-export-lora if available. |
| 476 | """ |
| 477 | print_banner() |
| 478 | print("[Merge] LoRA/QLoRA adapter merge") |
| 479 | print() |
| 480 | |
| 481 | from gguf import GGUFReader, GGUFWriter, GGMLQuantizationType, GGUFValueType, dequantize, quantize, Keys |
| 482 | |
| 483 | base_path = args.base |
| 484 | lora_path = args.lora |
| 485 | output_path = args.output |
| 486 | out_quant = args.type or "q4_0" |
| 487 | verbose = args.verbose |
| 488 | |
| 489 | # Read base model |
| 490 | print(f"Reading base model: {base_path}") |
| 491 | base_reader = GGUFReader(base_path) |
| 492 | print(f" {len(base_reader.tensors)} tensors") |
| 493 | print(f" Base type: {GGMLQuantizationType(base_reader.tensors[0].tensor_type).name if hasattr(base_reader.tensors[0], 'tensor_type') else '?'}") |
| 494 | |
| 495 | # Read LoRA adapter |
| 496 | print(f"Reading LoRA adapter: {lora_path}") |
| 497 | lora_reader = GGUFReader(lora_path) |
| 498 | print(f" {len(lora_reader.tensors)} tensors") |
| 499 | |
| 500 | # Get alpha from adapter metadata |
| 501 | lora_alpha = 1.0 |
| 502 | if Keys.Adapter.LORA_ALPHA in lora_reader.fields: |
| 503 | alpha_field = lora_reader.fields[Keys.Adapter.LORA_ALPHA] |
| 504 | lora_alpha = float(np.asarray(alpha_field.parts[-1]).item()) |
| 505 | print(f" LoRA alpha: {lora_alpha}") |
| 506 | |
| 507 | # Build LoRA tensor lookup: base_tensor_name -> {"a": tensor, "b": tensor} |
| 508 | lora_map = {} |
| 509 | for t in lora_reader.tensors: |
| 510 | name = t.name |
| 511 | if name.endswith(".lora_a"): |
| 512 | base_name = name[:-7] # strip ".lora_a" |
| 513 | lora_map.setdefault(base_name, {})["a"] = t |
| 514 | elif name.endswith(".lora_b"): |
| 515 | base_name = name[:-7] # strip ".lora_b" |
| 516 | lora_map.setdefault(base_name, {})["b"] = t |
| 517 | elif not name.endswith(".lora_a") and not name.endswith(".lora_b"): |
| 518 | # Non-LoRA tensors in adapter (e.g. norm layers) |
| 519 | lora_map.setdefault(name, {})["copy"] = t |
| 520 | |
| 521 | # Output quantization type map |
| 522 | qt_map = { |
| 523 | "f32": GGMLQuantizationType.F32, |
| 524 | "f16": GGMLQuantizationType.F16, |
| 525 | "q4_0": GGMLQuantizationType.Q4_0, |
| 526 | "q4_1": GGMLQuantizationType.Q4_1, |
| 527 | "q5_0": GGMLQuantizationType.Q5_0, |
| 528 | "q5_1": GGMLQuantizationType.Q5_1, |
| 529 | "q8_0": GGMLQuantizationType.Q8_0, |
| 530 | "q2_k": GGMLQuantizationType.Q2_K, |
| 531 | "q3_k": GGMLQuantizationType.Q3_K, |
| 532 | "q4_k": GGMLQuantizationType.Q4_K, |
| 533 | "q5_k": GGMLQuantizationType.Q5_K, |
| 534 | "q6_k": GGMLQuantizationType.Q6_K, |
| 535 | "q8_k": GGMLQuantizationType.Q8_K, |
| 536 | } |
| 537 | target_qt = qt_map.get(out_quant, GGMLQuantizationType.F16) |
| 538 | |
| 539 | # Get architecture from base model |
| 540 | arch = "llama" |
| 541 | if "general.architecture" in base_reader.fields: |
| 542 | arch_field = base_reader.fields["general.architecture"] |
| 543 | arch = bytes(np.asarray(arch_field.parts[-1])).decode("utf-8") |
| 544 | |
| 545 | print(f" Output: {output_path} ({out_quant})") |
| 546 | print() |
| 547 | |
| 548 | writer = GGUFWriter(output_path, arch) |
| 549 | |
| 550 | # Copy KV metadata from base model |
| 551 | n_kv = 0 |
| 552 | for name, field in base_reader.fields.items(): |
| 553 | if name.startswith("GGUF."): |
| 554 | continue |
| 555 | try: |
| 556 | if field.types[-1] == GGUFValueType.STRING: |
| 557 | val = bytes(np.asarray(field.parts[-1])).decode("utf-8") |
| 558 | writer.add_string(name, val) |
| 559 | n_kv += 1 |
| 560 | elif field.types[-1] in (GGUFValueType.UINT32, GGUFValueType.INT32, |
| 561 | GGUFValueType.UINT64, GGUFValueType.INT64): |
| 562 | val = int(np.asarray(field.parts[-1]).item()) |
| 563 | writer.add_uint32(name, val) |
| 564 | n_kv += 1 |
| 565 | elif field.types[-1] == GGUFValueType.FLOAT32: |
| 566 | val = float(np.asarray(field.parts[-1]).item()) |
| 567 | writer.add_float32(name, val) |
| 568 | n_kv += 1 |
| 569 | elif field.types[-1] == GGUFValueType.ARRAY: |
| 570 | arr_field = field |
| 571 | sub_type = arr_field.types[-1] if len(arr_field.types) > 1 else GGUFValueType.STRING |
| 572 | if sub_type == GGUFValueType.STRING: |
| 573 | vals = [bytes(np.asarray(arr_field.parts[idx])).decode("utf-8") for idx in arr_field.data] |
| 574 | writer.add_string_array(name, vals) |
| 575 | n_kv += 1 |
| 576 | elif sub_type in (GGUFValueType.UINT32, GGUFValueType.INT32): |
| 577 | vals = [int(np.asarray(arr_field.parts[idx]).item()) for idx in arr_field.data] |
| 578 | writer.add_uint32_array(name, vals) |
| 579 | n_kv += 1 |
| 580 | except (ValueError, TypeError, IndexError, KeyError): |
| 581 | pass # skip fields we can't copy |
| 582 | |
| 583 | print(f" Copied {n_kv} KV metadata entries") |
| 584 | |
| 585 | # Process tensors |
| 586 | n_merged = 0 |
| 587 | n_copied = 0 |
| 588 | |
| 589 | for t in base_reader.tensors: |
| 590 | name = t.name |
| 591 | raw_data = np.asarray(t.data) |
| 592 | |
| 593 | if name in lora_map and "a" in lora_map[name] and "b" in lora_map[name]: |
| 594 | # --- Merge LoRA --- |
| 595 | t_a = lora_map[name]["a"] |
| 596 | t_b = lora_map[name]["b"] |
| 597 | lora_a = np.asarray(t_a.data).astype(np.float32) |
| 598 | lora_b = np.asarray(t_b.data).astype(np.float32) |
| 599 | |
| 600 | # Dequantize base tensor to F32 |
| 601 | base_f32 = dequantize(raw_data, t.tensor_type).astype(np.float32) |
| 602 | |
| 603 | # Compute LoRA delta: ΔW = B @ A |
| 604 | # lora_a shape: (rank, input_dim) |
| 605 | # lora_b shape: (output_dim, rank) |
| 606 | lora_delta = lora_b @ lora_a |
| 607 | |
| 608 | rank = lora_a.shape[0] |
| 609 | scaling = lora_alpha / rank |
| 610 | merged_data = base_f32 + lora_delta * scaling |
| 611 | |
| 612 | # Quantize output |
| 613 | if target_qt != GGMLQuantizationType.F32: |
| 614 | out_data = quantize(merged_data, target_qt) |
| 615 | else: |
| 616 | out_data = merged_data |
| 617 | |
| 618 | writer.add_tensor(name, out_data, raw_dtype=target_qt) |
| 619 | n_merged += 1 |
| 620 | print(f" ✓ Merge: {name}") |
| 621 | |
| 622 | elif name in lora_map and "copy" in lora_map[name]: |
| 623 | # Copy from adapter (e.g. norm layers overwritten by adapter) |
| 624 | t_copy = lora_map[name]["copy"] |
| 625 | copy_data = np.asarray(t_copy.data) |
| 626 | writer.add_tensor(name, copy_data, raw_dtype=t_copy.tensor_type) |
| 627 | n_copied += 1 |
| 628 | print(f" ◉ Copy (adapter): {name}") |
| 629 | |
| 630 | else: |
| 631 | # Copy base tensor as-is (optionally requantize) |
| 632 | if target_qt != t.tensor_type: |
| 633 | data_f32 = dequantize(raw_data, t.tensor_type).astype(np.float32) |
| 634 | if target_qt != GGMLQuantizationType.F32: |
| 635 | out_data = quantize(data_f32, target_qt) |
| 636 | else: |
| 637 | out_data = data_f32 |
| 638 | writer.add_tensor(name, out_data, raw_dtype=target_qt) |
| 639 | else: |
| 640 | writer.add_tensor(name, raw_data, raw_dtype=t.tensor_type) |
| 641 | n_copied += 1 |
| 642 | |
| 643 | print(f"\n ─────────────────────────────") |
| 644 | print(f" Merged: {n_merged} tensors") |
| 645 | print(f" Copied: {n_copied} tensors") |
| 646 | print(f" ─────────────────────────────") |
| 647 | |
| 648 | # Write output file |
| 649 | print(" Writing merged model...") |
| 650 | writer.write_header_to_file() |
| 651 | writer.write_kv_data_to_file() |
| 652 | writer.write_tensors_to_file(progress=True) |
| 653 | writer.close() |
| 654 | |
| 655 | size_mb = os.path.getsize(output_path) / 1024**2 if os.path.exists(output_path) else 0 |
| 656 | print(f"\n✅ Merged model saved to {output_path} ({size_mb:.0f} MB)") |
| 657 | |
| 658 | |
| 659 | # ─── Dataset ─────────────────────────────────────────────────────────── |
| 660 | |
| 661 | def cmd_dataset(args): |
| 662 | """Create, view, convert, compute stats, stream, and auto-label datasets.""" |
| 663 | print_banner() |
| 664 | print("[Dataset] Training data management") |
| 665 | print() |
| 666 | |
| 667 | actions = { |
| 668 | "create": _cmd_dataset_create, |
| 669 | "view": _cmd_dataset_view, |
| 670 | "convert": _cmd_dataset_convert, |
| 671 | "info": _cmd_dataset_info, |
| 672 | "stats": _cmd_dataset_stats, |
| 673 | "stream": _cmd_dataset_stream, |
| 674 | "list": _cmd_dataset_list, |
| 675 | "split": _cmd_dataset_split, |
| 676 | "auto-label": _cmd_dataset_autolabel, |
| 677 | } |
| 678 | |
| 679 | if args.action in actions: |
| 680 | actions[args.action](args) |
| 681 | else: |
| 682 | print("Dataset commands:") |
| 683 | print(" create — Create a new dataset interactively") |
| 684 | print(" view — View sample entries from a dataset") |
| 685 | print(" convert — Convert between dataset formats") |
| 686 | print(" info — Show dataset metadata and format detection") |
| 687 | print(" stats — Compute comprehensive dataset statistics") |
| 688 | print(" stream — Stream a large dataset (memory-efficient)") |
| 689 | print(" list — List available datasets in the workspace") |
| 690 | print(" split — Split dataset into train/val/test") |
| 691 | print(" auto-label — Auto-generate completions with confidence scoring") |
| 692 | |
| 693 | |
| 694 | def _cmd_dataset_create(args): |
| 695 | """Create a new dataset interactively with format selection.""" |
| 696 | output = args.output or "dataset.jsonl" |
| 697 | fmt = args.format or "alpaca" |
| 698 | |
| 699 | print(f"Creating {fmt} dataset: {output}") |
| 700 | print("Format details:") |
| 701 | print(f" {FORMAT_DESCRIPTIONS.get(fmt, fmt)}") |
| 702 | print() |
| 703 | |
| 704 | entries = [] |
| 705 | print("Enter samples. Empty prompt to finish.\n") |
| 706 | try: |
| 707 | while True: |
| 708 | if fmt == "alpaca": |
| 709 | instruction = input("Instruction: ").strip() |
| 710 | if not instruction: |
| 711 | break |
| 712 | input_text = input("Input (optional): ").strip() |
| 713 | output_text = input("Output: ").strip() |
| 714 | from mojollama.dataset import DatasetEntry, write_jsonl |
| 715 | entries.append(DatasetEntry( |
| 716 | source_format=fmt, |
| 717 | instruction=instruction, |
| 718 | input_text=input_text, |
| 719 | output=output_text, |
| 720 | )) |
| 721 | elif fmt == "sharegpt": |
| 722 | convs = [] |
| 723 | while True: |
| 724 | role = input(" Role (human/gpt, empty to finish): ").strip() |
| 725 | if not role: |
| 726 | break |
| 727 | val = input(" Message: ").strip() |
| 728 | if val: |
| 729 | convs.append({"from": role, "value": val}) |
| 730 | if not convs: |
| 731 | break |
| 732 | from mojollama.dataset import DatasetEntry |
| 733 | entries.append(DatasetEntry( |
| 734 | source_format=fmt, |
| 735 | conversations=convs, |
| 736 | )) |
| 737 | elif fmt == "openai": |
| 738 | msgs = [] |
| 739 | while True: |
| 740 | role = input(" Role (system/user/assistant, empty to finish): ").strip() |
| 741 | if not role: |
| 742 | break |
| 743 | content = input(" Content: ").strip() |
| 744 | if content: |
| 745 | msgs.append({"role": role, "content": content}) |
| 746 | if not msgs: |
| 747 | break |
| 748 | from mojollama.dataset import DatasetEntry |
| 749 | entries.append(DatasetEntry( |
| 750 | source_format=fmt, |
| 751 | messages=msgs, |
| 752 | )) |
| 753 | else: |
| 754 | prompt = input("Prompt: ").strip() |
| 755 | if not prompt: |
| 756 | break |
| 757 | completion = input("Completion: ").strip() |
| 758 | from mojollama.dataset import DatasetEntry |
| 759 | entries.append(DatasetEntry( |
| 760 | source_format="jsonl", |
| 761 | prompt=prompt, |
| 762 | completion=completion or "(pending)", |
| 763 | )) |
| 764 | |
| 765 | print(f" → Sample {len(entries)} saved\n") |
| 766 | except (EOFError, KeyboardInterrupt): |
| 767 | print() |
| 768 | |
| 769 | if entries: |
| 770 | from mojollama.dataset import write_jsonl |
| 771 | write_jsonl(entries, output, format=fmt) |
| 772 | print(f"\n✅ Saved {len(entries)} samples to {output}") |
| 773 | else: |
| 774 | print("\n⚠️ No samples saved") |
| 775 | |
| 776 | |
| 777 | def _cmd_dataset_view(args): |
| 778 | """View samples from a dataset.""" |
| 779 | path = args.dataset or args.input or input("Dataset path: ").strip() |
| 780 | count = args.count or 10 |
| 781 | if not os.path.exists(path): |
| 782 | print(f"❌ File not found: {path}") |
| 783 | return |
| 784 | |
| 785 | from mojollama.dataset import get_dataset_info, get_reader |
| 786 | info = get_dataset_info(path) |
| 787 | print(f"Dataset: {path}") |
| 788 | print(f"Format: {info.get('format', 'unknown')}") |
| 789 | print(f"Samples: {info.get('line_count', '?')}") |
| 790 | print(f"Size: {info.get('size_display', '?')}") |
| 791 | print() |
| 792 | |
| 793 | reader = get_reader(path, format=info.get("format")) |
| 794 | entries = reader.read()[:count] |
| 795 | |
| 796 | for i, entry in enumerate(entries): |
| 797 | print(f"[{i+1}] ", end="") |
| 798 | if entry.instruction: |
| 799 | print(f"Instruction: {entry.instruction[:80]}...") |
| 800 | elif entry.prompt: |
| 801 | print(f"Prompt: {entry.prompt[:80]}...") |
| 802 | if entry.messages: |
| 803 | roles = set(m.get("role", "") for m in entry.messages) |
| 804 | print(f" Messages: {len(entry.messages)} turns ({', '.join(roles)})") |
| 805 | if entry.conversations: |
| 806 | print(f" Conversations: {len(entry.conversations)} turns") |
| 807 | if entry.chosen and entry.rejected: |
| 808 | print(f" Chosen: {len(entry.chosen)} / Rejected: {len(entry.rejected)} turns") |
| 809 | if entry.output: |
| 810 | print(f" Output: {entry.output[:80]}...") |
| 811 | elif entry.completion: |
| 812 | print(f" Completion: {entry.completion[:80]}...") |
| 813 | print() |
| 814 | |
| 815 | |
| 816 | def _cmd_dataset_convert(args): |
| 817 | """Convert between dataset formats.""" |
| 818 | src = args.input or input("Source file: ").strip() |
| 819 | dst = args.output or "converted.jsonl" |
| 820 | fmt = args.format or "openai" |
| 821 | |
| 822 | if not os.path.exists(src): |
| 823 | print(f"❌ File not found: {src}") |
| 824 | return |
| 825 | |
| 826 | if fmt not in ALL_FORMATS: |
| 827 | print(f"❌ Unknown format: {fmt}") |
| 828 | print(f"Supported: {', '.join(ALL_FORMATS)}") |
| 829 | return |
| 830 | |
| 831 | result = convert_dataset(src, dst, target_format=fmt) |
| 832 | print(f"✅ Conversion complete:") |
| 833 | print(f" Input: {result['input_path']} ({result['input_format']})") |
| 834 | print(f" Output: {result['output_path']} ({result['output_format']})") |
| 835 | print(f" Samples: {result['samples']}") |
| 836 | |
| 837 | |
| 838 | def _cmd_dataset_info(args): |
| 839 | """Show comprehensive dataset info with format detection.""" |
| 840 | path = args.dataset or args.input or input("Dataset path: ").strip() |
| 841 | if not os.path.exists(path): |
| 842 | print(f"❌ File not found: {path}") |
| 843 | return |
| 844 | |
| 845 | info = get_dataset_info(path) |
| 846 | print(f"File: {info['name']}") |
| 847 | print(f"Path: {info['path']}") |
| 848 | print(f"Size: {info['size_display']}") |
| 849 | print(f"Format: {info['format']}") |
| 850 | print(f"Lines: {info.get('line_count', 0)}") |
| 851 | print() |
| 852 | |
| 853 | # Show sample preview |
| 854 | samples = info.get("samples_preview", []) |
| 855 | if samples: |
| 856 | print("Sample data:") |
| 857 | for i, s in enumerate(samples[:3]): |
| 858 | print(f" [{i+1}] {json.dumps(s, ensure_ascii=False)[:200]}") |
| 859 | print() |
| 860 | |
| 861 | |
| 862 | def _cmd_dataset_stats(args): |
| 863 | """Compute comprehensive dataset statistics.""" |
| 864 | path = args.dataset or args.input or input("Dataset path: ").strip() |
| 865 | if not os.path.exists(path): |
| 866 | print(f"❌ File not found: {path}") |
| 867 | return |
| 868 | |
| 869 | print(f"Computing stats for: {path}") |
| 870 | print() |
| 871 | |
| 872 | from mojollama.dataset import get_reader |
| 873 | |
| 874 | fmt = detect_format(path) |
| 875 | print(f"Format: {FORMAT_DESCRIPTIONS.get(fmt, fmt)}") |
| 876 | print() |
| 877 | |
| 878 | # Read all entries (may take a moment for large datasets) |
| 879 | reader = get_reader(path, format=fmt, max_samples=args.max_samples) |
| 880 | entries = reader.read() |
| 881 | stats = compute_stats(entries) |
| 882 | |
| 883 | print(f"Total samples: {stats.total_samples}") |
| 884 | print(f"Estimated tokens: {stats.estimated_tokens:,}") |
| 885 | print(f"Vocabulary size: {stats.vocab_size:,}") |
| 886 | print() |
| 887 | print("Length distribution (chars):") |
| 888 | print(f" Mean: {stats.avg_length:.1f}") |
| 889 | print(f" Median: {stats.median_length:.1f}") |
| 890 | print(f" Std: {stats.std_length:.1f}") |
| 891 | print(f" Min: {stats.min_length}") |
| 892 | print(f" Max: {stats.max_length}") |
| 893 | print() |
| 894 | print("Prompt length (chars):") |
| 895 | print(f" Mean: {stats.to_dict()['prompt_length']['mean']}") |
| 896 | print(f" Median: {stats.to_dict()['prompt_length']['median']}") |
| 897 | print() |
| 898 | print("Completion length (chars):") |
| 899 | print(f" Mean: {stats.to_dict()['completion_length']['mean']}") |
| 900 | print(f" Median: {stats.to_dict()['completion_length']['median']}") |
| 901 | print() |
| 902 | |
| 903 | if stats.format_distribution: |
| 904 | print("Format distribution:") |
| 905 | for fmt_name, count in stats.format_distribution.items(): |
| 906 | print(f" {fmt_name}: {count}") |
| 907 | print() |
| 908 | |
| 909 | # Show histogram |
| 910 | hist = stats.length_distribution(bins=8) |
| 911 | if hist.get("counts"): |
| 912 | edges = hist["bins"] |
| 913 | counts = hist["counts"] |
| 914 | max_count = max(counts) |
| 915 | print("Length histogram:") |
| 916 | for i, (start, end) in enumerate(zip(edges[:-1], edges[1:])): |
| 917 | bar = "█" * int((counts[i] / max_count) * 30) if max_count > 0 else "" |
| 918 | print(f" {int(start):>6}–{int(end):<6} │ {bar} {counts[i]}") |
| 919 | |
| 920 | |
| 921 | def _cmd_dataset_stream(args): |
| 922 | """Stream a large dataset (memory-efficient preview).""" |
| 923 | path = args.dataset or args.input or input("Dataset path: ").strip() |
| 924 | count = args.count or 20 |
| 925 | if not os.path.exists(path): |
| 926 | print(f"❌ File not found: {path}") |
| 927 | return |
| 928 | |
| 929 | from mojollama.dataset import StreamingDataset |
| 930 | ds = StreamingDataset(path) |
| 931 | total = ds.count_lines() |
| 932 | print(f"Streaming {path}") |
| 933 | print(f"Total lines: {total:,}") |
| 934 | print(f"Previewing {min(count, total)} entries...") |
| 935 | print() |
| 936 | |
| 937 | streamed = 0 |
| 938 | for i, entry in enumerate(ds.stream_entries()): |
| 939 | if i >= count: |
| 940 | break |
| 941 | streamed += 1 |
| 942 | # Show a compact preview |
| 943 | text = entry.get_text()[:100] |
| 944 | print(f" [{i+1}] {text}...") |
| 945 | # Show format hints |
| 946 | hints = [] |
| 947 | if entry.messages: |
| 948 | hints.append(f"{len(entry.messages)} messages") |
| 949 | if entry.conversations: |
| 950 | hints.append(f"{len(entry.conversations)} convs") |
| 951 | if entry.chosen or entry.rejected: |
| 952 | hints.append(f"preference") |
| 953 | if hints: |
| 954 | print(f" ({', '.join(hints)})") |
| 955 | print() |
| 956 | |
| 957 | print(f"Previewed {streamed} entries (of {total:,} total)") |
| 958 | if total > count: |
| 959 | print(f"Use --count N to show more entries") |
| 960 | |
| 961 | |
| 962 | def _cmd_dataset_list(args): |
| 963 | """List available datasets.""" |
| 964 | directory = args.directory or os.getcwd() |
| 965 | datasets = find_datasets(directory) |
| 966 | |
| 967 | if not datasets: |
| 968 | print("No datasets found.") |
| 969 | print(f"Looked in: {directory}") |
| 970 | print("Supported: .jsonl, .jsonl.gz, .json, .json.gz") |
| 971 | return |
| 972 | |
| 973 | print(f"Found {len(datasets)} datasets in {directory}:") |
| 974 | print() |
| 975 | print(f" {'Name':<30} {'Format':<14} {'Size':<10}") |
| 976 | print(f" {'─'*30} {'─'*14} {'─'*10}") |
| 977 | for ds in datasets: |
| 978 | print(f" {ds['name']:<30} {ds['format_description']:<14} {ds['size_display']:<10}") |
| 979 | |
| 980 | |
| 981 | def _cmd_dataset_split(args): |
| 982 | """Split dataset into train/val/test sets.""" |
| 983 | path = args.dataset or args.input or input("Dataset path: ").strip() |
| 984 | if not os.path.exists(path): |
| 985 | print(f"❌ File not found: {path}") |
| 986 | return |
| 987 | |
| 988 | train_pct = args.train_ratio or 0.8 |
| 989 | val_pct = args.val_ratio or 0.1 |
| 990 | test_pct = args.test_ratio or 0.1 |
| 991 | out_prefix = args.output_prefix or os.path.splitext(path)[0] |
| 992 | shuffle = not args.no_shuffle |
| 993 | |
| 994 | from mojollama.dataset import get_reader |
| 995 | fmt = detect_format(path) |
| 996 | reader = get_reader(path, format=fmt) |
| 997 | entries = reader.read() |
| 998 | total = len(entries) |
| 999 | |
| 1000 | splits = split_dataset(entries, train_ratio=train_pct, val_ratio=val_pct, |
| 1001 | test_ratio=test_pct, shuffle=shuffle) |
| 1002 | print(f"Splitting {total} entries:") |
| 1003 | print(f" Train: {len(splits['train'])} ({train_pct*100:.0f}%)") |
| 1004 | print(f" Val: {len(splits['val'])} ({val_pct*100:.0f}%)") |
| 1005 | print(f" Test: {len(splits['test'])} ({test_pct*100:.0f}%)") |
| 1006 | print() |
| 1007 | |
| 1008 | for split_name, split_entries in splits.items(): |
| 1009 | if not split_entries: |
| 1010 | continue |
| 1011 | out_path = f"{out_prefix}-{split_name}.jsonl" |
| 1012 | write_jsonl(split_entries, out_path, format=fmt) |
| 1013 | print(f" ✅ {split_name}: {len(split_entries)} → {out_path}") |
| 1014 | |
| 1015 | |
| 1016 | def _cmd_dataset_autolabel(args): |
| 1017 | """Auto-generate completions with confidence scoring.""" |
| 1018 | input_file = args.input or input("Input dataset (JSONL): ").strip() |
| 1019 | output = args.output or input_file.replace(".jsonl", "-labeled.jsonl") |
| 1020 | api_base = args.api_base or "http://127.0.0.1:9000" |
| 1021 | model = args.model or "" |
| 1022 | max_tokens = args.max_tokens or 256 |
| 1023 | temperature = args.temperature or 0.7 |
| 1024 | batch_size = args.batch_size or 1 |
| 1025 | threshold = args.confidence_threshold or 0.0 |
| 1026 | |
| 1027 | if not os.path.exists(input_file): |
| 1028 | print(f"❌ File not found: {input_file}") |
| 1029 | return |
| 1030 | |
| 1031 | from mojollama.dataset import AutoLabeler, get_reader, compute_stats |
| 1032 | |
| 1033 | # Determine format |
| 1034 | fmt = detect_format(input_file) |
| 1035 | print(f"Input format: {FORMAT_DESCRIPTIONS.get(fmt, fmt)}") |
| 1036 | print(f"Model API: {api_base}") |
| 1037 | print(f"Max tokens: {max_tokens}, Temperature: {temperature}") |
| 1038 | print(f"Batch size: {batch_size}") |
| 1039 | print() |
| 1040 | |
| 1041 | # Read entries |
| 1042 | reader = get_reader(input_file, format=fmt) |
| 1043 | entries = reader.read() |
| 1044 | total = len(entries) |
| 1045 | print(f"Loaded {total} entries") |
| 1046 | print() |
| 1047 | |
| 1048 | # Auto-label |
| 1049 | labeler = AutoLabeler( |
| 1050 | api_base=api_base, |
| 1051 | model=model, |
| 1052 | max_tokens=max_tokens, |
| 1053 | temperature=temperature, |
| 1054 | ) |
| 1055 | |
| 1056 | def _progress(done, total): |
| 1057 | print(f" Progress: {done}/{total} ({done/total*100:.0f}%)", end="\r", flush=True) |
| 1058 | |
| 1059 | print("Auto-labeling...") |
| 1060 | labeled = labeler.label_batch(entries, batch_size=batch_size, callback=_progress) |
| 1061 | print("\n") |
| 1062 | |
| 1063 | # Compute confidence scores |
| 1064 | from mojollama.dataset import compute_confidence |
| 1065 | for entry in labeled: |
| 1066 | entry.metadata["confidence"] = compute_confidence(entry) |
| 1067 | |
| 1068 | # Filter by confidence threshold |
| 1069 | high_conf = [e for e in labeled if e.metadata.get("confidence", 0) >= threshold] |
| 1070 | low_conf = [e for e in labeled if e.metadata.get("confidence", 0) < threshold] |
| 1071 | |
| 1072 | print(f"Results:") |
| 1073 | print(f" Total entries: {len(labeled)}") |
| 1074 | print(f" High confidence: {len(high_conf)} (≥{threshold:.2f})") |
| 1075 | print(f" Low confidence: {len(low_conf)} (<{threshold:.2f})") |
| 1076 | print() |
| 1077 | |
| 1078 | avg_conf = ( |
| 1079 | sum(e.metadata.get("confidence", 0) for e in labeled) / max(len(labeled), 1) |
| 1080 | ) |
| 1081 | print(f" Average confidence: {avg_conf:.3f}") |
| 1082 | print() |
| 1083 | |
| 1084 | # Stats on the labeled data |
| 1085 | stats = compute_stats(labeled) |
| 1086 | print(f" Estimated tokens: {stats.estimated_tokens:,}") |
| 1087 | print() |
| 1088 | |
| 1089 | # Save all |
| 1090 | from mojollama.dataset import write_jsonl |
| 1091 | write_jsonl(labeled, output, format="openai") |
| 1092 | print(f"✅ Saved {len(labeled)} labeled entries to {output}") |
| 1093 | |
| 1094 | # Save high-confidence subset |
| 1095 | if len(high_conf) != len(labeled): |
| 1096 | hc_out = output.replace(".jsonl", "-highconf.jsonl") |
| 1097 | write_jsonl(high_conf, hc_out, format="openai") |
| 1098 | print(f"✅ High-confidence subset ({len(high_conf)}) → {hc_out}") |
| 1099 | |
| 1100 | |
| 1101 | # ─── Chat ────────────────────────────────────────────────────────────── |
| 1102 | |
| 1103 | def cmd_chat(args): |
| 1104 | """Interactive chat with a model.""" |
| 1105 | print_banner() |
| 1106 | model = _get_model(args.model) |
| 1107 | if not model: |
| 1108 | model = input("Model path (GGUF): ").strip() |
| 1109 | print("[Chat] Interactive model chat") |
| 1110 | print() |
| 1111 | |
| 1112 | model = args.model or input("Model path (GGUF): ").strip() |
| 1113 | port = args.port or 9000 |
| 1114 | |
| 1115 | if not os.path.exists(model): |
| 1116 | print(f"❌ Model not found: {model}") |
| 1117 | return |
| 1118 | |
| 1119 | # Check if already running |
| 1120 | try: |
| 1121 | urllib.request.urlopen(f"http://127.0.0.1:{port}/health", timeout=2) |
| 1122 | print(f"Server already running on port {port}") |
| 1123 | print(f"Open {CHAT_HTML} or use curl") |
| 1124 | return |
| 1125 | except: |
| 1126 | pass |
| 1127 | |
| 1128 | # Start server |
| 1129 | print(f"Starting llama.cpp server on port {port}...") |
| 1130 | print(f"Model: {model}") |
| 1131 | print() |
| 1132 | |
| 1133 | logfile = f"/tmp/mojollama-chat-{port}.log" |
| 1134 | with open(logfile, "w") as lf: |
| 1135 | proc = subprocess.Popen( |
| 1136 | [SERVER_BIN, "-m", model, "-c", "4096", |
| 1137 | "-t", "64", "-tb", "32", "-b", "4096", "-ub", "4096", |
| 1138 | "-np", "8", "--mlock", "--cont-batching", |
| 1139 | "--port", str(port), "--host", "0.0.0.0", "--no-webui"], |
| 1140 | stdout=lf, stderr=subprocess.STDOUT |
| 1141 | ) |
| 1142 | |
| 1143 | print("Waiting for server...") |
| 1144 | for _ in range(30): |
| 1145 | time.sleep(1) |
| 1146 | try: |
| 1147 | urllib.request.urlopen(f"http://127.0.0.1:{port}/health", timeout=2) |
| 1148 | print(f"\n✅ Server ready at http://0.0.0.0:{port}") |
| 1149 | print(f" Chat UI: {CHAT_HTML}") |
| 1150 | print(" API: curl http://127.0.0.1:{port}/v1/chat/completions") |
| 1151 | print(" -d '{\"messages\":[{\"role\":\"user\",\"content\":\"Hi\"}]}'") |
| 1152 | print("\nPress Ctrl+C to stop server") |
| 1153 | proc.wait() |
| 1154 | return |
| 1155 | except: |
| 1156 | pass |
| 1157 | |
| 1158 | with open(logfile) as lf: |
| 1159 | last_lines = lf.read().splitlines()[-5:] |
| 1160 | print(f"❌ Server failed to start (see {logfile})") |
| 1161 | for line in last_lines: |
| 1162 | print(f" {line}") |
| 1163 | proc.kill() |
| 1164 | |
| 1165 | |
| 1166 | # ─── Serve ───────────────────────────────────────────────────────────── |
| 1167 | |
| 1168 | def cmd_serve(args): |
| 1169 | """Start the full MojoLlama API server with AutoBackend.""" |
| 1170 | print_banner() |
| 1171 | print("[Serve] MojoLlama API server") |
| 1172 | print() |
| 1173 | |
| 1174 | os.environ["PORT"] = str(args.port or 9000) |
| 1175 | model = _get_model(args.model) or args.model |
| 1176 | if model: |
| 1177 | os.environ["MODEL_PATH"] = model |
| 1178 | |
| 1179 | sys.path.insert(0, f"{BASE_DIR}/src") |
| 1180 | from mojollama.server import main |
| 1181 | main() |
| 1182 | |
| 1183 | |
| 1184 | # ─── Benchmark ───────────────────────────────────────────────────────── |
| 1185 | |
| 1186 | def cmd_benchmark(args): |
| 1187 | """Benchmark model inference speed (delegates to new bench suite).""" |
| 1188 | print_banner() |
| 1189 | print("[Benchmark] MojoLlama Native Engine Benchmark") |
| 1190 | print() |
| 1191 | model = args.model or input("Model path (GGUF): ").strip() |
| 1192 | if not os.path.exists(model): |
| 1193 | print(f"❌ Model not found: {model}") |
| 1194 | return |
| 1195 | os.environ["OMP_NUM_THREADS"] = str(args.threads or 32) |
| 1196 | # Delegate to the new bench_tok |
| 1197 | sys.argv = ["bench", "--model", model] |
| 1198 | if args.threads: |
| 1199 | sys.argv.extend(["--threads", str(args.threads)]) |
| 1200 | if args.n_predict: |
| 1201 | sys.argv.extend(["--gen-len", str(args.n_predict)]) |
| 1202 | from mojollama.benchmarks.bench_tok import main as _bench_main |
| 1203 | _bench_main() |
| 1204 | |
| 1205 | |
| 1206 | # ─── Evaluate ───────────────────────────────────────────────────────── |
| 1207 | |
| 1208 | def cmd_evaluate(args): |
| 1209 | """Run benchmark evaluations (MMLU, GSM8K, CEval, etc.).""" |
| 1210 | print_banner() |
| 1211 | print("║ Evaluation Framework ║") |
| 1212 | print() |
| 1213 | |
| 1214 | if args.action == "download": |
| 1215 | return cmd_evaluate_download(args) |
| 1216 | |
| 1217 | if args.action == "list": |
| 1218 | from mojollama.eval.orchestrator import list_benchmarks |
| 1219 | print("Available benchmarks:") |
| 1220 | for b in list_benchmarks(): |
| 1221 | print(f" {b['id']:15s} — {b['description']}") |
| 1222 | print() |
| 1223 | print("Cached datasets:") |
| 1224 | from mojollama.eval.dataset import list_available_datasets |
| 1225 | cached = list_available_datasets() |
| 1226 | if cached: |
| 1227 | for name, info in cached.items(): |
| 1228 | size_mb = info.get("size", 0) / 1024**2 |
| 1229 | subjects = info.get("subjects", 0) |
| 1230 | extra = f" ({subjects} subjects)" if subjects else "" |
| 1231 | print(f" \u2705 {name:15s} {size_mb:.1f} MB{extra}") |
| 1232 | else: |
| 1233 | print(" (none cached \u2014 run `evaluate download` first)") |
| 1234 | return |
| 1235 | |
| 1236 | # Ensure we have a backend running |
| 1237 | llama_port = args.port or 8081 |
| 1238 | backend_url = f"http://127.0.0.1:{llama_port}" |
| 1239 | |
| 1240 | from mojollama.eval.base import check_backend_alive |
| 1241 | if not check_backend_alive(backend_url): |
| 1242 | print(f"\u274c Backend at {backend_url} is not responding.") |
| 1243 | print(f" Start a server first: mojollama-studio serve --model model.gguf") |
| 1244 | return |
| 1245 | |
| 1246 | # Determine which benchmarks to run |
| 1247 | benchmarks_to_run = [] |
| 1248 | if args.benchmarks: |
| 1249 | benchmarks_to_run = [b.lower() for b in args.benchmarks] |
| 1250 | elif args.all: |
| 1251 | from mojollama.eval.orchestrator import BENCHMARKS |
| 1252 | benchmarks_to_run = list(BENCHMARKS.keys()) |
| 1253 | else: |
| 1254 | print("Specify --benchmarks or --all. Use `evaluate list` to see available benchmarks.") |
| 1255 | return |
| 1256 | |
| 1257 | from mojollama.eval.orchestrator import run_benchmarks, format_results |
| 1258 | |
| 1259 | results = run_benchmarks(benchmarks_to_run, backend_url, |
| 1260 | args.model or "unknown", |
| 1261 | max_samples=args.max_samples or 0) |
| 1262 | |
| 1263 | print() |
| 1264 | print(format_results(results)) |
| 1265 | |
| 1266 | if args.output: |
| 1267 | import json |
| 1268 | with open(args.output, "w") as f: |
| 1269 | json.dump(results, f, indent=2, default=str) |
| 1270 | print(f"\\n\u2705 Results saved to {args.output}") |
| 1271 | |
| 1272 | |
| 1273 | def cmd_evaluate_download(args): |
| 1274 | """Download evaluation datasets.""" |
| 1275 | from mojollama.eval.orchestrator import download_all_datasets |
| 1276 | results = download_all_datasets() |
| 1277 | ok_count = sum(1 for v in results.values() if v) |
| 1278 | total = len(results) |
| 1279 | print(f"\\n{'─'*40}") |
| 1280 | print(f" {ok_count}/{total} datasets downloaded successfully") |
| 1281 | return results |
| 1282 | |
| 1283 | |
| 1284 | # ─── Auto-tune ───────────────────────────────────────────────────────── |
| 1285 | |
| 1286 | def cmd_autotune(args): |
| 1287 | """Auto-tune server settings for this hardware.""" |
| 1288 | print("╔══════════════════════════════════════════════╗") |
| 1289 | print("║ MojoLlama AutoTuner v0.2.0 ║") |
| 1290 | print("╚══════════════════════════════════════════════╝") |
| 1291 | print() |
| 1292 | |
| 1293 | # Deep mode: detect hardware first |
| 1294 | if args.deep: |
| 1295 | from mojollama.detect import detect_hardware, summary, recommend_llamacpp_flags, format_recommendation |
| 1296 | hw = detect_hardware() |
| 1297 | print(summary(hw)) |
| 1298 | print() |
| 1299 | flags = recommend_llamacpp_flags(hw) |
| 1300 | print("Recommended flags from hardware detection:") |
| 1301 | print(f" {format_recommendation(flags)}") |
| 1302 | print() |
| 1303 | |
| 1304 | config = autotune(args.model or |
| 1305 | "/tmp/tl-Q4_0.gguf", |
| 1306 | quick=args.quick) |
| 1307 | |
| 1308 | if config: |
| 1309 | # Merge hardware detection findings into config |
| 1310 | if args.deep: |
| 1311 | from mojollama.detect import detect_hardware, recommend_llamacpp_flags |
| 1312 | hw = detect_hardware() |
| 1313 | flags = recommend_llamacpp_flags(hw) |
| 1314 | config["hardware_detection"] = { |
| 1315 | "cpu": hw["cpu"], |
| 1316 | "gpu": hw["gpu"]["primary"], |
| 1317 | } |
| 1318 | # Apply hardware-recommended settings |
| 1319 | hs = config["llama_server"] |
| 1320 | for k in ["threads", "batch_size", "n_parallel", "mlock", "flash_attn", "cpu_mask"]: |
| 1321 | if k in flags: |
| 1322 | hs[k] = flags[k] |
| 1323 | if hw["gpu"]["primary"]: |
| 1324 | hs["gpu"] = flags.get("gpu") |
| 1325 | hs["gpu_layers"] = flags.get("gpu_layers", -1) |
| 1326 | |
| 1327 | save_config(config) |
| 1328 | print_config(config) |
| 1329 | |
| 1330 | # Show the generated server config |
| 1331 | from mojollama.backends import build_server_cmd |
| 1332 | cmd = build_server_cmd( |
| 1333 | "/tmp/llama.cpp/build/bin/llama-server", |
| 1334 | args.model or "model.gguf", |
| 1335 | 8081 |
| 1336 | ) |
| 1337 | print() |
| 1338 | print("Recommended llama-server command:") |
| 1339 | print(f" {' '.join(cmd)}") |
| 1340 | else: |
| 1341 | print("❌ Auto-tuning failed") |
| 1342 | |
| 1343 | |
| 1344 | # ─── Info ────────────────────────────────────────────────────────────── |
| 1345 | |
| 1346 | def cmd_info(args): |
| 1347 | """Show system info and available resources.""" |
| 1348 | print_banner() |
| 1349 | |
| 1350 | print("System:") |
| 1351 | import psutil |
| 1352 | print(f" RAM: {psutil.virtual_memory().total / 1024**3:.0f} GB total, " |
| 1353 | f"{psutil.virtual_memory().available / 1024**3:.0f} GB free") |
| 1354 | print(f" CPU: {psutil.cpu_count()} cores") |
| 1355 | print() |
| 1356 | |
| 1357 | print("Backends:") |
| 1358 | backends = [] |
| 1359 | if os.path.exists(SERVER_BIN): |
| 1360 | backends.append("llama.cpp ✓") |
| 1361 | try: |
| 1362 | import max |
| 1363 | backends.append("MAX ✓") |
| 1364 | except: |
| 1365 | backends.append("MAX ✗") |
| 1366 | if os.path.exists(FINETUNE_BIN): |
| 1367 | backends.append("finetune ✓") |
| 1368 | for b in backends: |
| 1369 | print(f" {b}") |
| 1370 | print() |
| 1371 | |
| 1372 | print("Models:") |
| 1373 | for f in sorted(Path(BASE_DIR).glob("*.gguf")): |
| 1374 | size = f.stat().st_size / 1024**3 |
| 1375 | print(f" {f.name} ({size:.1f} GB)") |
| 1376 | |
| 1377 | print() |
| 1378 | print("AVAILABLE COMMANDS:") |
| 1379 | print(" train Fine-tune a model with LoRA/QLoRA/DPO/GRPO") |
| 1380 | print(" export Convert HuggingFace model to GGUF") |
| 1381 | print(" dataset Create/manage training data") |
| 1382 | print(" merge Merge LoRA adapter into base model") |
| 1383 | print(" chat Interactive chat with an endpoint-connected model") |
| 1384 | print(" serve Full MojoLlama API server") |
| 1385 | print(" benchmark Benchmark model inference speed") |
| 1386 | print(" evaluate Run evaluations (MMLU, GSM8K, CEval)") |
| 1387 | print(" quantize Quantize a GGUF model") |
| 1388 | print(" imatrix Generate importance matrix") |
| 1389 | print(" autotune Auto-tune server settings") |
| 1390 | print(" connect Connect to a model (HF Hub or local)") |
| 1391 | print(" models List connected models") |
| 1392 | print(" info System info") |
| 1393 | print(" hub-login Login to HuggingFace Hub") |
| 1394 | print(" hub-whoami Show HuggingFace user info") |
| 1395 | print(" hub-push Push model to HuggingFace Hub") |
| 1396 | print() |
| 1397 | print(" Run 'mojollama-studio <command> --help' for detailed options.") |
| 1398 | # ─── Quantizer Wrappers ──────────────────────────────────────────────── |
| 1399 | |
| 1400 | def cmd_quantize(args): |
| 1401 | """Quantize GGUF → GGUF (delegates to new multi-quant engine).""" |
| 1402 | # Delegate to __main__.py's cmd_quantize which has --multi, --target-bpw, --bench, --list-types |
| 1403 | sys.argv = ["quantize"] |
| 1404 | if args.model: sys.argv.append(args.model) |
| 1405 | if args.type: sys.argv.extend(["-t", args.type]) |
| 1406 | if args.output: sys.argv.extend(["-o", args.output]) |
| 1407 | if args.imatrix: sys.argv.extend(["--imatrix", args.imatrix]) |
| 1408 | if args.threads: sys.argv.extend(["--threads", str(args.threads)]) |
| 1409 | if args.allow_requantize: sys.argv.append("--allow-requantize") |
| 1410 | if args.dry_run: sys.argv.append("--dry-run") |
| 1411 | if args.pure: sys.argv.append("--pure") |
| 1412 | if args.leave_output: sys.argv.append("--leave-output") |
| 1413 | if args.multi: sys.argv.extend(["--multi", args.multi]) |
| 1414 | if args.target_bpw: sys.argv.extend(["--target-bpw", str(args.target_bpw)]) |
| 1415 | if args.bench: sys.argv.append("--bench") |
| 1416 | if args.list_types: sys.argv.append("--list-types") |
| 1417 | from mojollama.__main__ import cmd_quantize as _quant |
| 1418 | _quant(args) |
| 1419 | |
| 1420 | |
| 1421 | def cmd_imatrix(args): |
| 1422 | """Generate importance matrix using llama-imatrix.""" |
| 1423 | imatrix_bin = "/tmp/llama.cpp/build/bin/llama-imatrix" |
| 1424 | |
| 1425 | cmd = [imatrix_bin, "-m", args.model] |
| 1426 | if args.data: |
| 1427 | cmd.extend(["-f", args.data]) |
| 1428 | if args.output: |
| 1429 | cmd.extend(["-o", args.output]) |
| 1430 | if args.threads and args.threads > 0: |
| 1431 | cmd.extend(["-t", str(args.threads)]) |
| 1432 | if args.ctx_size: |
| 1433 | cmd.extend(["-c", str(args.ctx_size)]) |
| 1434 | |
| 1435 | print_banner() |
| 1436 | print("[IMatrix] Generating importance matrix...") |
| 1437 | print() |
| 1438 | subprocess.run(cmd, check=True) |
| 1439 | |
| 1440 | |
| 1441 | def cmd_dynamic_quant(args): |
| 1442 | """Dynamic quantization: select per-tensor quant types based on importance matrix.""" |
| 1443 | import re, math, tempfile |
| 1444 | |
| 1445 | quant_types = { |
| 1446 | 'Q2_K': 2.5, 'Q3_K_S': 3.0, 'Q3_K_M': 3.4, 'Q4_0': 4.0, |
| 1447 | 'Q4_K_S': 4.4, 'Q4_K_M': 4.5, 'Q5_0': 5.0, 'Q5_K_M': 5.5, |
| 1448 | 'Q6_K': 6.0, 'Q8_0': 8.0, |
| 1449 | } |
| 1450 | refined = {'Q6_K': 6.0, 'Q5_K_M': 5.5, 'Q4_K_M': 4.5, 'Q3_K_S': 3.0, 'Q2_K': 2.5} |
| 1451 | |
| 1452 | # Parse imatrix file |
| 1453 | tensor_importance = {} |
| 1454 | with open(args.imatrix) as f: |
| 1455 | for line in f: |
| 1456 | line = line.strip() |
| 1457 | if not line or line.startswith('#') or line.startswith(';'): |
| 1458 | continue |
| 1459 | parts = line.split(None, 1) |
| 1460 | if len(parts) == 2: |
| 1461 | try: |
| 1462 | tensor_importance[parts[0]] = float(parts[1]) |
| 1463 | except ValueError: |
| 1464 | pass |
| 1465 | |
| 1466 | if not tensor_importance: |
| 1467 | print("[DynamicQuant] ERROR: No valid entries in imatrix file") |
| 1468 | return |
| 1469 | |
| 1470 | # Group tensors by type |
| 1471 | groups = {'attention': [], 'ffn': [], 'output': [], 'embedding': [], 'norm': [], 'other': []} |
| 1472 | for tname, imp in tensor_importance.items(): |
| 1473 | base = os.path.splitext(tname)[0] |
| 1474 | base_clean = re.sub(r'blk\.\d+\.', '', base) |
| 1475 | if any(x in base_clean for x in ['attn_q', 'attn_k', 'attn_v', 'attn_o', 'attention', 'self_attn']): |
| 1476 | groups['attention'].append((tname, imp)) |
| 1477 | elif any(x in base_clean for x in ['ffn_gate', 'ffn_up', 'ffn_down', 'mlp', 'feed_forward']): |
| 1478 | groups['ffn'].append((tname, imp)) |
| 1479 | elif any(x in base_clean for x in ['output', 'lm_head']): |
| 1480 | groups['output'].append((tname, imp)) |
| 1481 | elif any(x in base_clean for x in ['embed', 'tok_embeddings', 'token_embd']): |
| 1482 | groups['embedding'].append((tname, imp)) |
| 1483 | elif 'norm' in base_clean: |
| 1484 | groups['norm'].append((tname, imp)) |
| 1485 | else: |
| 1486 | groups['other'].append((tname, imp)) |
| 1487 | |
| 1488 | # Assign quant types |
| 1489 | assignments = {} |
| 1490 | if args.target_bpw: |
| 1491 | # Target BPW mode: grid search for best threshold split |
| 1492 | all_sorted = sorted(tensor_importance.items(), key=lambda x: x[1]) |
| 1493 | n = len(all_sorted) |
| 1494 | best_error = float('inf') |
| 1495 | best_thresholds = None |
| 1496 | best_assignment = {} |
| 1497 | bpw_target = float(args.target_bpw) |
| 1498 | |
| 1499 | for t1 in range(0, 101, 5): |
| 1500 | for t2 in range(t1, 101, 5): |
| 1501 | for t3 in range(t2, 101, 5): |
| 1502 | p1, p2, p3 = t1 / 100, t2 / 100, t3 / 100 |
| 1503 | total_bpw = 0 |
| 1504 | temp_assign = {} |
| 1505 | for i, (name, imp) in enumerate(all_sorted): |
| 1506 | pct = i / n |
| 1507 | if pct <= p1: |
| 1508 | qt = 'Q6_K' |
| 1509 | elif pct <= p2: |
| 1510 | qt = 'Q5_K_M' |
| 1511 | elif pct <= p3: |
| 1512 | qt = 'Q4_K_M' |
| 1513 | else: |
| 1514 | qt = 'Q3_K_S' if args.extreme else 'Q2_K' |
| 1515 | temp_assign[name] = qt |
| 1516 | total_bpw += refined[qt] |
| 1517 | avg_bpw = total_bpw / n |
| 1518 | error = abs(avg_bpw - bpw_target) |
| 1519 | if error < best_error: |
| 1520 | best_error = error |
| 1521 | best_thresholds = (p1, p2, p3) |
| 1522 | best_assignment = temp_assign |
| 1523 | assignments = best_assignment |
| 1524 | print(f"[DynamicQuant] Target BPW: {bpw_target}, achieved: {bpw_target - best_error:.2f} (error: {best_error:.2f})") |
| 1525 | p1, p2, p3 = best_thresholds |
| 1526 | print(f"[DynamicQuant] Thresholds: Q6_K<={p1*100:.0f}%, Q5_K_M<={p2*100:.0f}%, Q4_K_M<={p3*100:.0f}%, Q3_K_S>{p3*100:.0f}%") |
| 1527 | else: |
| 1528 | # Standard mode: per-group 30/40/30 split |
| 1529 | for group_name, group_tensors in groups.items(): |
| 1530 | if not group_tensors: |
| 1531 | continue |
| 1532 | sorted_tensors = sorted(group_tensors, key=lambda x: x[1]) |
| 1533 | n = len(sorted_tensors) |
| 1534 | for i, (tname, _) in enumerate(sorted_tensors): |
| 1535 | pct = i / n |
| 1536 | if pct <= 0.3: |
| 1537 | assignments[tname] = 'Q6_K' |
| 1538 | elif pct <= 0.7: |
| 1539 | assignments[tname] = 'Q4_K_M' |
| 1540 | else: |
| 1541 | assignments[tname] = 'Q3_K_S' |
| 1542 | |
| 1543 | # Count |
| 1544 | qt_counts = {} |
| 1545 | for qt in assignments.values(): |
| 1546 | qt_counts[qt] = qt_counts.get(qt, 0) + 1 |
| 1547 | print(f"[DynamicQuant] Quantization plan: {', '.join(f'{k}: {v}' for k, v in sorted(qt_counts.items()))}") |
| 1548 | |
| 1549 | if args.verbose or args.dry_run: |
| 1550 | print(f"\n Tensor assignments:") |
| 1551 | for tname, qt in sorted(assignments.items()): |
| 1552 | print(f" {tname} -> {qt}") |
| 1553 | |
| 1554 | if args.dry_run: |
| 1555 | print(f"\n[DynamicQuant] Dry-run mode. Would run:") |
| 1556 | print(f" llama-quantize --tensor-type-file <temp_file> {args.model} {args.output} COPY {args.threads or 32}") |
| 1557 | return |
| 1558 | |
| 1559 | # Write tensor-type file and run quantization |
| 1560 | with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False, prefix='dynquant_') as f: |
| 1561 | for tname, qt in sorted(assignments.items()): |
| 1562 | f.write(f"{tname} {qt}\n") |
| 1563 | ttf_path = f.name |
| 1564 | |
| 1565 | quantize_bin = "/tmp/llama.cpp/build/bin/llama-quantize" |
| 1566 | outfile = args.output or args.model.replace('.gguf', '-dynamic.gguf') |
| 1567 | cmd = [quantize_bin, "--allow-requantize", "--tensor-type-file", ttf_path, |
| 1568 | args.model, outfile, "COPY"] |
| 1569 | if args.threads and args.threads > 0: |
| 1570 | cmd.append(str(args.threads)) |
| 1571 | |
| 1572 | print(f"[DynamicQuant] Quantizing -> {outfile}") |
| 1573 | subprocess.run(cmd, check=True) |
| 1574 | os.unlink(ttf_path) |
| 1575 | print(f"[DynamicQuant] Done: {outfile}") |
| 1576 | |
| 1577 | |
| 1578 | def cmd_nf4_wrapper(args): |
| 1579 | """Convert to NF4 (wraps quantizer.py).""" |
| 1580 | from mojollama.quantizer import main as quantizer_main |
| 1581 | import sys |
| 1582 | sys.argv = ["quantizer.py", "nf4", args.model, |
| 1583 | "--output", args.output or "", |
| 1584 | "--block-size", str(args.block_size)] |
| 1585 | sys.argv = [a for a in sys.argv if a] |
| 1586 | return quantizer_main() |
| 1587 | |
| 1588 | |
| 1589 | def cmd_quant_types(args): |
| 1590 | """List supported quantization types.""" |
| 1591 | from mojollama.quantizer import main as quantizer_main |
| 1592 | import sys |
| 1593 | sys.argv = ["quantizer.py", "list-types"] |
| 1594 | return quantizer_main() |
| 1595 | |
| 1596 | |
| 1597 | # ─── Hub commands (from exporter) ─────────────────────────────────── |
| 1598 | |
| 1599 | def cmd_hub_login(args): |
| 1600 | """Login to HuggingFace Hub.""" |
| 1601 | from mojollama.exporter import hub_login |
| 1602 | print_banner() |
| 1603 | print("║ HuggingFace Hub — Login ║") |
| 1604 | print() |
| 1605 | hub_login(token=args.token or "") |
| 1606 | |
| 1607 | |
| 1608 | def cmd_hub_whoami(args): |
| 1609 | """Show HuggingFace user info.""" |
| 1610 | from mojollama.exporter import hub_whoami |
| 1611 | user = hub_whoami() |
| 1612 | if user: |
| 1613 | print(f"User: {user.get('name', 'unknown')}") |
| 1614 | print(f"Email: {user.get('email', 'unknown')}") |
| 1615 | else: |
| 1616 | print("❌ Not logged in to HuggingFace Hub") |
| 1617 | |
| 1618 | |
| 1619 | def cmd_hub_push(args): |
| 1620 | """Push model to HuggingFace Hub.""" |
| 1621 | from mojollama.exporter import hub_push_model |
| 1622 | print_banner() |
| 1623 | print("║ HuggingFace Hub — Push Model ║") |
| 1624 | print() |
| 1625 | model_path = args.model or input("Model path: ").strip() |
| 1626 | repo_id = args.repo or input("HF repo ID (e.g. username/model): ").strip() |
| 1627 | if not os.path.exists(model_path): |
| 1628 | print(f"❌ Model not found: {model_path}") |
| 1629 | return |
| 1630 | metadata = {"studio_version": STUDIO_VERSION} |
| 1631 | if args.quant: metadata["quantization"] = args.quant |
| 1632 | if args.params: metadata["parameters"] = args.params |
| 1633 | if args.description: metadata["description"] = args.description |
| 1634 | result = hub_push_model( |
| 1635 | model_path=model_path, repo_id=repo_id, |
| 1636 | private=args.private, |
| 1637 | commit_message=args.message or f"Upload via MojoLlama Studio", |
| 1638 | metadata=metadata, |
| 1639 | ) |
| 1640 | if result: |
| 1641 | print(f"\n✅ Model available at: {result}") |
| 1642 | |
| 1643 | |
| 1644 | def cmd_hub_push_adapter(args): |
| 1645 | """Push LoRA adapter to HuggingFace Hub.""" |
| 1646 | from mojollama.exporter import hub_push_adapter |
| 1647 | print_banner() |
| 1648 | print("║ HuggingFace Hub — Push Adapter ║") |
| 1649 | print() |
| 1650 | adapter_path = args.adapter or input("Adapter path: ").strip() |
| 1651 | base_model = args.base_model or input("Base model name: ").strip() |
| 1652 | repo_id = args.repo or input("HF repo ID: ").strip() |
| 1653 | if not os.path.exists(adapter_path): |
| 1654 | print(f"❌ Adapter not found: {adapter_path}") |
| 1655 | return |
| 1656 | metadata = {"base_model": base_model} |
| 1657 | if args.rank: metadata["lora_rank"] = args.rank |
| 1658 | if args.alpha: metadata["lora_alpha"] = args.alpha |
| 1659 | result = hub_push_adapter( |
| 1660 | adapter_path=adapter_path, base_model=base_model, |
| 1661 | repo_id=repo_id, private=args.private, metadata=metadata, |
| 1662 | ) |
| 1663 | if result: |
| 1664 | print(f"\n✅ Adapter available at: {result}") |
| 1665 | |
| 1666 | |
| 1667 | # ─── Export format commands ──────────────────────────────────────── |
| 1668 | |
| 1669 | def cmd_export_safetensors(args): |
| 1670 | """Convert GGUF model to safetensors format.""" |
| 1671 | from mojollama.exporter import gguf_to_safetensors |
| 1672 | print_banner() |
| 1673 | print("[Export] GGUF → Safetensors") |
| 1674 | print() |
| 1675 | gguf_path = args.model or input("GGUF model path: ").strip() |
| 1676 | output_dir = args.output or gguf_path.replace(".gguf", "-safetensors") |
| 1677 | result = gguf_to_safetensors( |
| 1678 | gguf_path=gguf_path, output_dir=output_dir, |
| 1679 | dtype=args.dtype or "float16", shard_size=args.shard_size or "2GB", |
| 1680 | ) |
| 1681 | if result: |
| 1682 | print(f"\n✅ Saved to: {result}") |
| 1683 | |
| 1684 | |
| 1685 | def cmd_export_onnx(args): |
| 1686 | """Convert GGUF model to ONNX format.""" |
| 1687 | from mojollama.exporter import gguf_to_onnx |
| 1688 | print_banner() |
| 1689 | print("[Export] GGUF → ONNX") |
| 1690 | print() |
| 1691 | gguf_path = args.model or input("GGUF model path: ").strip() |
| 1692 | output_path = args.output or gguf_path.replace(".gguf", ".onnx") |
| 1693 | result = gguf_to_onnx( |
| 1694 | gguf_path=gguf_path, output_path=output_path, |
| 1695 | opset=args.opset or 17, max_seq_len=args.max_seq_len or 2048, |
| 1696 | ) |
| 1697 | if result: |
| 1698 | print(f"\n✅ Saved to: {result}") |
| 1699 | |
| 1700 | |
| 1701 | # ─── Checkpoint commands ─────────────────────────────────────────── |
| 1702 | |
| 1703 | def cmd_checkpoint_save(args): |
| 1704 | """Save a training checkpoint.""" |
| 1705 | from mojollama.exporter import TrainingCheckpoint |
| 1706 | print_banner() |
| 1707 | print("[Checkpoint] Save") |
| 1708 | print() |
| 1709 | ckpt = TrainingCheckpoint(args.checkpoint_dir or "checkpoints") |
| 1710 | result = ckpt.save( |
| 1711 | step=args.step or 0, epoch=args.epoch or 0, loss=args.loss or 0.0, |
| 1712 | model_path=args.model or None, |
| 1713 | ) |
| 1714 | if result: |
| 1715 | print(f"\n✅ Checkpoint saved to: {result}") |
| 1716 | |
| 1717 | |
| 1718 | def cmd_checkpoint_load(args): |
| 1719 | """Load and display training checkpoint info.""" |
| 1720 | from mojollama.exporter import TrainingCheckpoint |
| 1721 | print_banner() |
| 1722 | print("[Checkpoint] Load") |
| 1723 | print() |
| 1724 | ckpt = TrainingCheckpoint(args.checkpoint_dir or "checkpoints") |
| 1725 | data = ckpt.load() |
| 1726 | if data is None: |
| 1727 | print("❌ No checkpoint found") |
| 1728 | return |
| 1729 | print(f" Step: {data.get('step', '?')}") |
| 1730 | print(f" Epoch: {data.get('epoch', '?')}") |
| 1731 | print(f" Loss: {data.get('loss', '?')}") |
| 1732 | print(f" Best Loss: {data.get('best_loss', '?')}") |
| 1733 | if data.get("config"): |
| 1734 | print(f" Config:") |
| 1735 | for k, v in data["config"].items(): |
| 1736 | print(f" {k}: {v}") |
| 1737 | |
| 1738 | |
| 1739 | def cmd_checkpoint_list(args): |
| 1740 | """List all training checkpoints.""" |
| 1741 | from mojollama.exporter import TrainingCheckpoint |
| 1742 | print_banner() |
| 1743 | print("[Checkpoint] List") |
| 1744 | print() |
| 1745 | checkpoints = TrainingCheckpoint.list_checkpoints(args.checkpoint_dir or ".") |
| 1746 | if not checkpoints: |
| 1747 | print("No checkpoints found") |
| 1748 | return |
| 1749 | print(f"Found {len(checkpoints)} checkpoint(s):") |
| 1750 | print() |
| 1751 | for ckpt in checkpoints: |
| 1752 | name = ckpt.get("name", "?") |
| 1753 | loss = ckpt.get("loss", "?") |
| 1754 | step = ckpt.get("step", "?") |
| 1755 | status = "✅" if "error" not in ckpt else "❌" |
| 1756 | print(f" {status} {name} — step {step}, loss {loss}") |
| 1757 | |
| 1758 | |
| 1759 | # ─── Main ────────────────────────────────────────────────────────────── |
| 1760 | |
| 1761 | def main(): |
| 1762 | parser = argparse.ArgumentParser(description="MojoLlama Studio") |
| 1763 | parser.add_argument("--version", action="store_true", help="Show version") |
| 1764 | |
| 1765 | sub = parser.add_subparsers(dest="command", help="Command") |
| 1766 | |
| 1767 | # train |
| 1768 | p_train = sub.add_parser("train", help="Fine-tune a model (LoRA, QLoRA, DoRA, GaLore, DPO, GRPO, etc.)") |
| 1769 | p_train.add_argument("--model", help="Model path (GGUF)") |
| 1770 | p_train.add_argument("--data", help="Training data (JSONL, JSON, or text)") |
| 1771 | p_train.add_argument("--method", choices=list(TRAINING_METHODS.keys()), |
| 1772 | default="lora", help="Training method (default: lora)") |
| 1773 | p_train.add_argument("--lora-out", default="adapter.gguf") |
| 1774 | p_train.add_argument("--lora-rank", type=int, default=16) |
| 1775 | p_train.add_argument("--lora-alpha", type=int, default=32) |
| 1776 | p_train.add_argument("--lr", type=float, default=1e-4) |
| 1777 | p_train.add_argument("--weight-decay", type=float, default=0.0) |
| 1778 | p_train.add_argument("--epochs", type=int, default=2) |
| 1779 | p_train.add_argument("--batch", type=int, default=4) |
| 1780 | p_train.add_argument("--max-seq-length", type=int, default=512, |
| 1781 | help="Maximum sequence length") |
| 1782 | p_train.add_argument("--save-steps", type=int, default=0, |
| 1783 | help="Save checkpoint every N steps") |
| 1784 | p_train.add_argument("--seed", type=int, default=42) |
| 1785 | p_train.add_argument("--warmup-steps", type=int, default=0) |
| 1786 | p_train.add_argument("--dataset-format", default="auto", |
| 1787 | choices=["auto", "alpaca", "sharegpt", "jsonl", "text"]) |
| 1788 | p_train.add_argument("--max-samples", type=int, default=0, |
| 1789 | help="Max samples to use (0 = all)") |
| 1790 | p_train.add_argument("--template", default="alpaca", |
| 1791 | choices=["alpaca", "sharegpt", "preference", "text"]) |
| 1792 | # Method-specific options |
| 1793 | p_train.add_argument("--dpo-beta", type=float, default=0.1, help="DPO KL penalty") |
| 1794 | p_train.add_argument("--orpo-lambda", type=float, default=0.1, help="ORPO lambda") |
| 1795 | p_train.add_argument("--simpo-gamma", type=float, default=0.5, help="SimPO reward margin") |
| 1796 | p_train.add_argument("--grpo-group-size", type=int, default=8, help="GRPO group size") |
| 1797 | p_train.add_argument("--grpo-clip", type=float, default=0.2, help="GRPO clip epsilon") |
| 1798 | p_train.add_argument("--galore-rank", type=int, default=128, |
| 1799 | help="GaLore projection rank") |
| 1800 | p_train.add_argument("--list-methods", action="store_true", |
| 1801 | help="List available training methods") |
| 1802 | p_train.add_argument("--resume-from", help="Resume from checkpoint directory") |
| 1803 | p_train.add_argument("--checkpoint-dir", default="checkpoints", help="Directory for saving checkpoints") |
| 1804 | p_train.add_argument("--save-every", type=int, default=10, help="Save checkpoint every N steps") |
| 1805 | |
| 1806 | # export |
| 1807 | p_export = sub.add_parser("export", help="Convert HF model to GGUF") |
| 1808 | p_export.add_argument("--hf", help="HF model ID or path") |
| 1809 | p_export.add_argument("--model", help="Alias for --hf") |
| 1810 | p_export.add_argument("--outtype", default="q4_0") |
| 1811 | p_export.add_argument("--outfile", help="Output GGUF path") |
| 1812 | p_export.add_argument("--remote", action="store_true", help="Download from HF") |
| 1813 | p_export.add_argument("--vocab-only", action="store_true") |
| 1814 | p_export.add_argument("--mojo-bin", action="store_true", help="Also generate .bin") |
| 1815 | |
| 1816 | # convert (alias for export) |
| 1817 | p_convert = sub.add_parser("convert", help="Alias for export: Convert HF model to GGUF") |
| 1818 | p_convert.add_argument("--hf", help="HF model ID or path") |
| 1819 | p_convert.add_argument("--model", help="Alias for --hf") |
| 1820 | p_convert.add_argument("--outtype", default="q4_0") |
| 1821 | p_convert.add_argument("--outfile", help="Output GGUF path") |
| 1822 | p_convert.add_argument("--remote", action="store_true", help="Download from HF") |
| 1823 | p_convert.add_argument("--vocab-only", action="store_true") |
| 1824 | p_convert.add_argument("--mojo-bin", action="store_true", help="Also generate .bin") |
| 1825 | |
| 1826 | # merge |
| 1827 | p_merge = sub.add_parser("merge", help="Merge LoRA adapter into base model") |
| 1828 | p_merge.add_argument("--base", required=True, help="Base model (GGUF)") |
| 1829 | p_merge.add_argument("--lora", required=True, help="LoRA adapter (GGUF)") |
| 1830 | p_merge.add_argument("--output", default="merged.gguf", help="Output path") |
| 1831 | p_merge.add_argument("--type", default="q4_0", help="Output quantization type") |
| 1832 | p_merge.add_argument("--verbose", action="store_true", help="Verbose output") |
| 1833 | |
| 1834 | # dataset |
| 1835 | p_data = sub.add_parser("dataset", help="Manage datasets") |
| 1836 | p_data.add_argument("action", choices=[ |
| 1837 | "create", "view", "convert", "info", "stats", |
| 1838 | "stream", "list", "split", "auto-label", |
| 1839 | ], help="Dataset action") |
| 1840 | p_data.add_argument("--output", help="Output file") |
| 1841 | p_data.add_argument("--dataset", help="Dataset path") |
| 1842 | p_data.add_argument("--input", help="Input file") |
| 1843 | p_data.add_argument("--format", help="Dataset format (alpaca/sharegpt/openai/preference/jsonl)") |
| 1844 | p_data.add_argument("--model", help="Model name for auto-label") |
| 1845 | p_data.add_argument("--port", type=int, default=9000, help="Server port for auto-label API") |
| 1846 | p_data.add_argument("--api-base", help="API base URL for auto-label (default: http://127.0.0.1:9000)") |
| 1847 | p_data.add_argument("--max-tokens", type=int, default=256, help="Max tokens for auto-label") |
| 1848 | p_data.add_argument("--temperature", type=float, default=0.7, help="Temperature for auto-label") |
| 1849 | p_data.add_argument("--count", type=int, default=10, help="Number of samples to show (view/stream)") |
| 1850 | p_data.add_argument("--max-samples", type=int, help="Max samples to read for stats") |
| 1851 | p_data.add_argument("--batch-size", type=int, default=1, help="Batch size for auto-label") |
| 1852 | p_data.add_argument("--confidence-threshold", type=float, default=0.0, |
| 1853 | help="Min confidence threshold for auto-label") |
| 1854 | p_data.add_argument("--directory", help="Directory to scan for list") |
| 1855 | p_data.add_argument("--train-ratio", type=float, default=0.8, help="Train split ratio") |
| 1856 | p_data.add_argument("--val-ratio", type=float, default=0.1, help="Validation split ratio") |
| 1857 | p_data.add_argument("--test-ratio", type=float, default=0.1, help="Test split ratio") |
| 1858 | p_data.add_argument("--output-prefix", help="Output prefix for split files") |
| 1859 | p_data.add_argument("--no-shuffle", action="store_true", help="Disable shuffle for split") |
| 1860 | |
| 1861 | # connect — endpoint-based model loading |
| 1862 | p_connect = sub.add_parser("connect", help="Connect to a model from HF Hub or local path") |
| 1863 | p_connect.add_argument("spec", nargs="?", help="HF repo ID or local path") |
| 1864 | p_connect.add_argument("--alias", help="Alias name for the model (defaults to repo name)") |
| 1865 | |
| 1866 | # models |
| 1867 | p_models = sub.add_parser("models", aliases=["list-models"], |
| 1868 | help="List connected models") |
| 1869 | |
| 1870 | # quantize (wrapper around quantizer.py) |
| 1871 | p_quant = sub.add_parser("quantize", help="Quantize a GGUF model to a different type (all K/IQ quants, imatrix, NF4)") |
| 1872 | p_quant.add_argument("model", help="Path to input GGUF model") |
| 1873 | p_quant.add_argument("--type", "-t", default="Q4_K_M", dest="type", |
| 1874 | help="Quantization type (default: Q4_K_M)") |
| 1875 | p_quant.add_argument("--output", "-o", help="Output path") |
| 1876 | p_quant.add_argument("--imatrix", help="Importance matrix file for guided quantization") |
| 1877 | p_quant.add_argument("--threads", type=int, default=0, help="Thread count (0 = auto)") |
| 1878 | p_quant.add_argument("--allow-requantize", action="store_true", |
| 1879 | help="Allow requantizing already quantized tensors") |
| 1880 | p_quant.add_argument("--pure", action="store_true", |
| 1881 | help="Disable K-quant mixtures, pure type") |
| 1882 | p_quant.add_argument("--leave-output", action="store_true", |
| 1883 | help="Leave output.weight unquantized") |
| 1884 | p_quant.add_argument("--dry-run", action="store_true", |
| 1885 | help="Calculate size without quantizing") |
| 1886 | p_quant.add_argument("--override-kv", action="append", |
| 1887 | help="Override model metadata key=type:val (can be repeated)") |
| 1888 | p_quant.add_argument("--multi", type=str, |
| 1889 | help="Multi-quant cascade: comma-separated types, e.g. 'Q8_0,Q6_K,Q4_K_M'") |
| 1890 | p_quant.add_argument("--target-bpw", type=float, |
| 1891 | help="Target bits-per-weight (auto-selects best type)") |
| 1892 | p_quant.add_argument("--bench", action="store_true", |
| 1893 | help="Benchmark each output after quantization") |
| 1894 | p_quant.add_argument("--list-types", action="store_true", |
| 1895 | help="List available quantization types and exit") |
| 1896 | p_quant.add_argument("--compare", action="store_true", |
| 1897 | help="Compare with llama.cpp baseline") |
| 1898 | |
| 1899 | # imatrix |
| 1900 | p_imatrix = sub.add_parser("imatrix", help="Generate importance matrix for better quantization") |
| 1901 | p_imatrix.add_argument("model", help="Path to GGUF model") |
| 1902 | p_imatrix.add_argument("--data", "-f", help="Calibration data file (text)") |
| 1903 | p_imatrix.add_argument("--output", "-o", help="Output imatrix file path") |
| 1904 | p_imatrix.add_argument("--threads", "-t", type=int, default=0, help="Number of threads") |
| 1905 | p_imatrix.add_argument("--ctx-size", "-c", type=int, default=512, help="Context size") |
| 1906 | |
| 1907 | p_dyn = sub.add_parser("dynamic-quantize", help="Dynamic per-tensor quantization guided by importance matrix") |
| 1908 | p_dyn.add_argument("model", help="Path to input GGUF model") |
| 1909 | p_dyn.add_argument("--imatrix", required=True, help="Importance matrix file (.dat)") |
| 1910 | p_dyn.add_argument("--output", "-o", help="Output GGUF path") |
| 1911 | p_dyn.add_argument("--target-bpw", type=float, help="Target bits-per-weight (auto thresholds)") |
| 1912 | p_dyn.add_argument("--extreme", action="store_true", help="Use Q2_K for lowest importance (instead of Q3_K_S)") |
| 1913 | p_dyn.add_argument("--dry-run", action="store_true", help="Preview assignments without quantizing") |
| 1914 | p_dyn.add_argument("--verbose", action="store_true", help="Print per-tensor assignments") |
| 1915 | p_dyn.add_argument("--threads", "-t", type=int, default=0, help="Number of threads") |
| 1916 | |
| 1917 | p_nf4 = sub.add_parser("nf4", help="Convert to NF4 (NormalFloat4) for QLoRA") |
| 1918 | p_nf4.add_argument("model", help="Path to input GGUF model") |
| 1919 | p_nf4.add_argument("--output", "-o", help="Output path") |
| 1920 | p_nf4.add_argument("--block-size", type=int, default=64, |
| 1921 | help="NF4 block size (default: 64)") |
| 1922 | |
| 1923 | # quant-types |
| 1924 | sub.add_parser("quant-types", help="List all supported quantization types") |
| 1925 | |
| 1926 | # chat |
| 1927 | p_chat = sub.add_parser("chat", help="Interactive chat") |
| 1928 | p_chat.add_argument("--model", help="Model path (GGUF)") |
| 1929 | p_chat.add_argument("--port", type=int, default=9000) |
| 1930 | |
| 1931 | # serve |
| 1932 | p_serve = sub.add_parser("serve", help="Start API server") |
| 1933 | p_serve.add_argument("--port", type=int, default=9000) |
| 1934 | p_serve.add_argument("--model", help="Model path override") |
| 1935 | |
| 1936 | # benchmark |
| 1937 | p_bench = sub.add_parser("benchmark", help="Benchmark inference speed (MojoLlama native engine)") |
| 1938 | p_bench.add_argument("--model", help="Model path (GGUF)") |
| 1939 | p_bench.add_argument("--threads", "-t", type=int, default=32, |
| 1940 | help="CPU threads (default: 32)") |
| 1941 | p_bench.add_argument("--n-predict", type=int, default=128, |
| 1942 | help="Tokens to generate (default: 128)") |
| 1943 | p_bench.add_argument("--compare", action="store_true", |
| 1944 | help="A/B comparison with llama.cpp") |
| 1945 | p_bench.add_argument("--json", dest="output_json", action="store_true", |
| 1946 | help="Output as JSON") |
| 1947 | p_bench.set_defaults(func=cmd_benchmark) |
| 1948 | |
| 1949 | # evaluate |
| 1950 | p_eval = sub.add_parser("evaluate", help="Run benchmark evaluations (MMLU, GSM8K, CEval, etc.)") |
| 1951 | p_eval.add_argument("action", nargs="?", choices=["download", "list"], default=None, |
| 1952 | help="'download' to fetch datasets, 'list' to show available") |
| 1953 | p_eval.add_argument("--benchmarks", "-b", nargs="+", |
| 1954 | help="Benchmarks to run: mmlu gsm8k ceval hellaswag arc bbh humaneval") |
| 1955 | p_eval.add_argument("--all", "-a", action="store_true", |
| 1956 | help="Run all available benchmarks") |
| 1957 | p_eval.add_argument("--model", "-m", help="Model name (for display)") |
| 1958 | p_eval.add_argument("--max-samples", type=int, default=0, |
| 1959 | help="Max samples per category (0 = all)") |
| 1960 | p_eval.add_argument("--port", type=int, default=8081, |
| 1961 | help="llama.cpp backend port") |
| 1962 | p_eval.add_argument("--output", "-o", help="Save results to JSON file") |
| 1963 | |
| 1964 | # autotune |
| 1965 | p_tune = sub.add_parser("autotune", help="Auto-tune server settings for this hardware") |
| 1966 | p_tune.add_argument("--model", "-m", help="Model to benchmark with (default: TinyLlama Q4_0)") |
| 1967 | p_tune.add_argument("--quick", "-q", action="store_true", help="Faster sweep (fewer combos)") |
| 1968 | p_tune.add_argument("--deep", "-d", action="store_true", |
| 1969 | help="Deep hardware detection (CPU features, GPU, CUDA, ROCm, etc.)") |
| 1970 | |
| 1971 | # info |
| 1972 | sub.add_parser("info", help="System info") |
| 1973 | |
| 1974 | # ── Hub commands ───────────────────────────────────────────── |
| 1975 | p_hub_login = sub.add_parser("hub-login", help="Login to HuggingFace Hub") |
| 1976 | p_hub_login.add_argument("--token", help="HF API token") |
| 1977 | |
| 1978 | sub.add_parser("hub-whoami", help="Show HuggingFace user info") |
| 1979 | |
| 1980 | p_hub_push = sub.add_parser("hub-push", help="Push model to HuggingFace Hub") |
| 1981 | p_hub_push.add_argument("--model", "-m", help="Model path") |
| 1982 | p_hub_push.add_argument("--repo", help="HF repo ID") |
| 1983 | p_hub_push.add_argument("--message", help="Commit message") |
| 1984 | p_hub_push.add_argument("--private", action="store_true", help="Create private repo") |
| 1985 | p_hub_push.add_argument("--quant", help="Quantization type (metadata)") |
| 1986 | p_hub_push.add_argument("--params", help="Parameter count (metadata)") |
| 1987 | p_hub_push.add_argument("--description", help="Model description") |
| 1988 | |
| 1989 | p_hub_adapter = sub.add_parser("hub-push-adapter", help="Push LoRA adapter to HF Hub") |
| 1990 | p_hub_adapter.add_argument("--adapter", help="Adapter GGUF path") |
| 1991 | p_hub_adapter.add_argument("--base-model", help="Base model name") |
| 1992 | p_hub_adapter.add_argument("--repo", help="HF repo ID") |
| 1993 | p_hub_adapter.add_argument("--private", action="store_true") |
| 1994 | p_hub_adapter.add_argument("--rank", type=int, help="LoRA rank") |
| 1995 | p_hub_adapter.add_argument("--alpha", type=float, help="LoRA alpha") |
| 1996 | |
| 1997 | # ── Export format commands ──────────────────────────────────── |
| 1998 | p_st = sub.add_parser("export-safetensors", help="Convert GGUF to safetensors") |
| 1999 | p_st.add_argument("--model", "-m", help="GGUF model path") |
| 2000 | p_st.add_argument("--output", "-o", help="Output directory") |
| 2001 | p_st.add_argument("--dtype", default="float16", choices=["float16", "float32", "bfloat16"]) |
| 2002 | p_st.add_argument("--shard-size", default="2GB", help="Shard size (1GB, 2GB, 5GB, NO)") |
| 2003 | |
| 2004 | p_onnx = sub.add_parser("export-onnx", help="Convert GGUF to ONNX") |
| 2005 | p_onnx.add_argument("--model", "-m", help="GGUF model path") |
| 2006 | p_onnx.add_argument("--output", "-o", help="Output path") |
| 2007 | p_onnx.add_argument("--opset", type=int, default=17, help="ONNX opset") |
| 2008 | p_onnx.add_argument("--max-seq-len", type=int, default=2048) |
| 2009 | |
| 2010 | # ── Checkpoint commands ────────────────────────────────────── |
| 2011 | p_ckpt_save = sub.add_parser("checkpoint-save", help="Save training checkpoint") |
| 2012 | p_ckpt_save.add_argument("--checkpoint-dir", default="checkpoints") |
| 2013 | p_ckpt_save.add_argument("--model", help="Model file path") |
| 2014 | p_ckpt_save.add_argument("--step", type=int, default=0) |
| 2015 | p_ckpt_save.add_argument("--epoch", type=int, default=0) |
| 2016 | p_ckpt_save.add_argument("--loss", type=float, default=0.0) |
| 2017 | |
| 2018 | p_ckpt_load = sub.add_parser("checkpoint-load", help="Load training checkpoint") |
| 2019 | p_ckpt_load.add_argument("--checkpoint-dir", default="checkpoints") |
| 2020 | |
| 2021 | p_ckpt_list = sub.add_parser("checkpoint-list", help="List training checkpoints") |
| 2022 | p_ckpt_list.add_argument("--checkpoint-dir", default=".", help="Base directory") |
| 2023 | |
| 2024 | args = parser.parse_args() |
| 2025 | |
| 2026 | if args.version: |
| 2027 | print(f"MojoLlama Studio v{STUDIO_VERSION}") |
| 2028 | return |
| 2029 | |
| 2030 | if not args.command: |
| 2031 | parser.print_help() |
| 2032 | print("\nCommands:") |
| 2033 | print(" train Fine-tune a model with LoRA") |
| 2034 | print(" export Convert HuggingFace model to GGUF") |
| 2035 | print(" convert Alias for export") |
| 2036 | print(" dataset Create, view, auto-label, and manage training datasets") |
| 2037 | print(" merge Merge LoRA adapter into base GGUF model") |
| 2038 | print(" quantize Quantize GGUF to different type (K/IQ quants, imatrix)") |
| 2039 | print(" imatrix Generate importance matrix for guided quantization") |
| 2040 | print(" nf4 Convert to NF4 (NormalFloat4) for QLoRA") |
| 2041 | print(" quant-types List supported quantization types") |
| 2042 | print(" chat Interactive chat with a model") |
| 2043 | print(" serve Start the full MojoLlama API server") |
| 2044 | print(" benchmark Benchmark model inference speed") |
| 2045 | print(" evaluate Run benchmark evaluations (MMLU, GSM8K, CEval)") |
| 2046 | print(" autotune Auto-tune server settings for this hardware") |
| 2047 | print(" info Show system info") |
| 2048 | print(" hub-login Login to HuggingFace Hub") |
| 2049 | print(" hub-whoami Show HuggingFace user info") |
| 2050 | print(" hub-push Push model to HuggingFace Hub") |
| 2051 | print(" hub-push-adapter Push LoRA adapter to HF Hub") |
| 2052 | print(" export-safetensors Convert GGUF to safetensors") |
| 2053 | print(" export-onnx Convert GGUF to ONNX") |
| 2054 | print(" checkpoint-save Save training checkpoint") |
| 2055 | print(" checkpoint-load Load training checkpoint") |
| 2056 | print(" checkpoint-list List training checkpoints") |
| 2057 | return |
| 2058 | |
| 2059 | commands = { |
| 2060 | "train": cmd_train, |
| 2061 | "export": cmd_export, |
| 2062 | "convert": cmd_export, |
| 2063 | "dataset": cmd_dataset, |
| 2064 | "merge": cmd_merge, |
| 2065 | "quantize": cmd_quantize, |
| 2066 | "dynamic-quantize": cmd_dynamic_quant, |
| 2067 | "imatrix": cmd_imatrix, |
| 2068 | "nf4": cmd_nf4_wrapper, |
| 2069 | "quant-types": cmd_quant_types, |
| 2070 | "chat": cmd_chat, |
| 2071 | "serve": cmd_serve, |
| 2072 | "benchmark": cmd_benchmark, |
| 2073 | "evaluate": cmd_evaluate, |
| 2074 | "autotune": cmd_autotune, |
| 2075 | "info": cmd_info, |
| 2076 | "hub-login": cmd_hub_login, |
| 2077 | "hub-whoami": cmd_hub_whoami, |
| 2078 | "hub-push": cmd_hub_push, |
| 2079 | "hub-push-adapter": cmd_hub_push_adapter, |
| 2080 | "connect": cmd_connect, |
| 2081 | "models": cmd_models, |
| 2082 | "list-models": cmd_models, |
| 2083 | "export-safetensors": cmd_export_safetensors, |
| 2084 | "export-onnx": cmd_export_onnx, |
| 2085 | "checkpoint-save": cmd_checkpoint_save, |
| 2086 | "checkpoint-load": cmd_checkpoint_load, |
| 2087 | "checkpoint-list": cmd_checkpoint_list, |
| 2088 | } |
| 2089 | commands[args.command](args) |
| 2090 | |
| 2091 | |
| 2092 | if __name__ == "__main__": |
| 2093 | main() |