MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / __main__.py
| 1 | #!/usr/bin/env python3 |
| 2 | """MojoLlama unified CLI — as simple as llama.cpp. |
| 3 | |
| 4 | Usage: |
| 5 | mojollama <command> [options] |
| 6 | |
| 7 | Commands (match llama.cpp naming): |
| 8 | chat Interactive chat with a model |
| 9 | serve Start API server (OpenAI-compatible, SSE streaming) |
| 10 | bench Benchmark inference performance |
| 11 | quantize Quantize a GGUF model to a different type |
| 12 | imatrix Generate importance matrix for guided quantization |
| 13 | convert Convert HuggingFace model to GGUF |
| 14 | info Show system and model info |
| 15 | autotune Auto-tune server settings for this hardware |
| 16 | eval Run evaluations (MMLU, GSM8K, etc.) |
| 17 | train Fine-tune a model (LoRA, QLoRA, DPO, GRPO, etc.) |
| 18 | export Export GGUF to other formats (safetensors, ONNX) |
| 19 | hub HuggingFace Hub operations (login, push, whoami) |
| 20 | |
| 21 | Examples: |
| 22 | mojollama chat -m ~/models/qwen.gguf |
| 23 | mojollama serve -m ~/models/qwen.gguf -p 8080 |
| 24 | mojollama bench -m ~/models/qwen.gguf -n 128 |
| 25 | mojollama quantize model.gguf -t Q4_K_M |
| 26 | mojollama convert --hf meta-llama/Llama-3.2-1B --outtype q4_0 |
| 27 | mojollama info |
| 28 | """ |
| 29 | |
| 30 | import os |
| 31 | import sys |
| 32 | import argparse |
| 33 | |
| 34 | # Ensure we can import from the package |
| 35 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| 36 | |
| 37 | |
| 38 | VERSION = "0.5.0" |
| 39 | BANNER = f"""╔═══════════════════════════════════════════╗ |
| 40 | ║ MojoLlama v{VERSION} ║ |
| 41 | ║ Unified CLI — as simple as llama.cpp ║ |
| 42 | ╚═══════════════════════════════════════════╝""" |
| 43 | |
| 44 | |
| 45 | def print_commands(): |
| 46 | """Print available commands grouped by category.""" |
| 47 | print(BANNER) |
| 48 | print() |
| 49 | print("USAGE: mojollama <command> [options]") |
| 50 | print() |
| 51 | print("INFERENCE:") |
| 52 | print(" chat Interactive chat with a model") |
| 53 | print(" serve Start API server (OpenAI-compatible)") |
| 54 | print() |
| 55 | print("BENCHMARK & TUNE:") |
| 56 | print(" bench Benchmark inference performance (tok/s, latency)") |
| 57 | print(" autotune Auto-tune server settings for this hardware") |
| 58 | print(" eval Run evaluations (MMLU, GSM8K, CEval, etc.)") |
| 59 | print() |
| 60 | print("MODEL OPS:") |
| 61 | print(" quantize Quantize a GGUF model (supports K/IQ quants)") |
| 62 | print(" imatrix Generate importance matrix for guided quantization") |
| 63 | print(" convert Convert HuggingFace model to GGUF") |
| 64 | print(" export Export GGUF to safetensors, ONNX") |
| 65 | print() |
| 66 | print("HUB:") |
| 67 | print(" hub HuggingFace Hub: login, whoami, push") |
| 68 | print() |
| 69 | print("SYSTEM:") |
| 70 | print(" info Show system info (CPU, RAM, GPU, models)") |
| 71 | print() |
| 72 | print("DEVELOPMENT:") |
| 73 | print(" train Fine-tune a model (LoRA, QLoRA, DPO, GRPO, etc.)") |
| 74 | print() |
| 75 | print(f"Run 'mojollama <command> --help' for detailed options.") |
| 76 | print() |
| 77 | |
| 78 | |
| 79 | def cmd_chat(args): |
| 80 | """Interactive chat with a model.""" |
| 81 | from mojollama.studio import cmd_chat as _chat |
| 82 | _chat(args) |
| 83 | |
| 84 | |
| 85 | def cmd_serve(args): |
| 86 | """Start the API server.""" |
| 87 | if args.backend == "studio": |
| 88 | from mojollama.studio import cmd_serve as _serve |
| 89 | _serve(args) |
| 90 | else: |
| 91 | from mojollama.server import main as _server_main |
| 92 | sys.argv = ["server.py", |
| 93 | "--model", args.model or "", |
| 94 | "--port", str(args.port)] |
| 95 | _server_main() |
| 96 | |
| 97 | |
| 98 | def cmd_bench(args): |
| 99 | """Benchmark inference performance. Better than llama-bench — thread sweep, |
| 100 | multi-model, profile mode, A/B comparison, historical results.""" |
| 101 | if not args.model: |
| 102 | print("ERROR: --model is required for benchmarking") |
| 103 | print() |
| 104 | print("Examples:") |
| 105 | print(" mojollama bench -m model.gguf # single benchmark") |
| 106 | print(" mojollama bench -m model.gguf -t 1,2,4,8,16,32 # thread sweep") |
| 107 | print(" mojollama bench -m m1.gguf,m2.gguf # multi-model") |
| 108 | print(" mojollama bench -m model.gguf --compare # A/B vs llama.cpp") |
| 109 | print(" mojollama bench -m model.gguf --profile # component profile") |
| 110 | print(" mojollama bench -m model.gguf --json # JSON output") |
| 111 | print(" mojollama bench -m model.gguf --save results.json # save to file") |
| 112 | print(" mojollama bench --load a.json --load b.json # historical compare") |
| 113 | sys.exit(1) |
| 114 | os.environ["OMP_NUM_THREADS"] = str(args.threads) |
| 115 | # Add paths needed for engine imports |
| 116 | kernels_dir = os.path.join(os.path.dirname(__file__), 'kernels') |
| 117 | if kernels_dir not in sys.path: |
| 118 | sys.path.insert(0, kernels_dir) |
| 119 | from mojollama.benchmarks.bench_tok import main as _bench_main |
| 120 | # Forward all relevant flags |
| 121 | sys.argv = ["bench"] |
| 122 | if args.model: sys.argv.extend(["--model", args.model]) |
| 123 | sys.argv.extend(["--threads", str(args.threads)]) |
| 124 | sys.argv.extend(["--prompt-len", str(args.prompt_len)]) |
| 125 | sys.argv.extend(["--gen-len", str(args.gen_len)]) |
| 126 | sys.argv.extend(["--warmup", str(args.warmup)]) |
| 127 | sys.argv.extend(["--measured", str(args.measured)]) |
| 128 | if args.compare: sys.argv.append("--compare") |
| 129 | if args.profile: sys.argv.append("--profile") |
| 130 | if args.output_json: sys.argv.extend(["--output", "json"]) |
| 131 | if args.save: sys.argv.extend(["--save", args.save]) |
| 132 | if args.concurrent: sys.argv.extend(["--concurrent", args.concurrent]) |
| 133 | if args.concurrent_quick: sys.argv.append("--concurrent-quick") |
| 134 | if args.load_paths: |
| 135 | for path in args.load_paths: |
| 136 | sys.argv.extend(["--load", path]) |
| 137 | _bench_main() |
| 138 | |
| 139 | |
| 140 | def cmd_quantize(args): |
| 141 | """Quantize a GGUF model. Supports multi-quant cascade, target BPW, benchmark.""" |
| 142 | import time |
| 143 | |
| 144 | # --list-types |
| 145 | Q_TYPES = [ |
| 146 | ("Q2_K", 2.5, "2-bit K-quant (smallest, lowest quality)"), |
| 147 | ("Q3_K_S", 3.0, "3-bit K-quant small"), |
| 148 | ("Q3_K_M", 3.4, "3-bit K-quant medium (balanced)"), |
| 149 | ("Q3_K_L", 3.6, "3-bit K-quant large"), |
| 150 | ("Q4_0", 4.0, "4-bit (no K-quant, fast but large)"), |
| 151 | ("Q4_K_S", 4.4, "4-bit K-quant small"), |
| 152 | ("Q4_K_M", 4.5, "4-bit K-quant medium (recommended)"), |
| 153 | ("Q5_0", 5.0, "5-bit (no K-quant)"), |
| 154 | ("Q5_K_S", 5.1, "5-bit K-quant small"), |
| 155 | ("Q5_K_M", 5.5, "5-bit K-quant medium"), |
| 156 | ("Q6_K", 6.0, "6-bit K-quant (high quality)"), |
| 157 | ("Q8_0", 8.0, "8-bit (lossless-ish)"), |
| 158 | ("F16", 16.0, "16-bit float (lossless)"), |
| 159 | ] |
| 160 | if args.list_types: |
| 161 | dash = "─" * 10; dash5 = "─" * 5; dash40 = "─" * 40 |
| 162 | print(f"\n{'Type':>10s} {'BPW':>5s} Description") |
| 163 | print(f"{dash} {dash5} {dash40}") |
| 164 | for name, bpw, desc in Q_TYPES: |
| 165 | print(f"{name:>10s} {bpw:>5.1f} {desc}") |
| 166 | print(f"\n Use: mojollama quantize model.gguf -t TYPE") |
| 167 | print(f" Multi: mojollama quantize model.gguf --multi Q8_0,Q6_K,Q4_K_M") |
| 168 | print(f" Target BPW: mojollama quantize model.gguf --target-bpw 3.5") |
| 169 | return |
| 170 | |
| 171 | # --target-bpw: auto-select best type |
| 172 | if args.target_bpw: |
| 173 | best = None |
| 174 | for name, bpw, desc in Q_TYPES: |
| 175 | if bpw <= args.target_bpw + 0.1: |
| 176 | best = name |
| 177 | else: |
| 178 | break |
| 179 | if best: |
| 180 | best_bpw = next(b for n,b,d in Q_TYPES if n==best) |
| 181 | print(f"[Quantize] Target BPW={args.target_bpw}: selected {best} ({best_bpw:.1f} bpw)") |
| 182 | args.type = best |
| 183 | else: |
| 184 | print(f"[Quantize] No type fits target BPW={args.target_bpw}, using Q2_K") |
| 185 | args.type = "Q2_K" |
| 186 | |
| 187 | # --multi cascade |
| 188 | if args.multi: |
| 189 | types = [t.strip() for t in args.multi.split(",")] |
| 190 | print(f"\n[Quantize] Multi-quant cascade: {' → '.join(types)}") |
| 191 | print(f"[Quantize] Base model: {args.model}") |
| 192 | print() |
| 193 | prev_model = args.model |
| 194 | results = [] |
| 195 | for i, qt in enumerate(types): |
| 196 | outfile = args.model.replace(".gguf", f"-{qt}.gguf") |
| 197 | print(f" [{i+1}/{len(types)}] Quantizing to {qt}...") |
| 198 | print(f" Input: {prev_model}") |
| 199 | print(f" Output: {outfile}") |
| 200 | t0 = time.time() |
| 201 | _run_llama_quantize(prev_model, outfile, qt, args) |
| 202 | elapsed = time.time() - t0 |
| 203 | size_mb = os.path.getsize(outfile) / (1024*1024) |
| 204 | print(f" Done: {elapsed:.0f}s Size: {size_mb:.0f} MB") |
| 205 | results.append((qt, outfile, elapsed, size_mb)) |
| 206 | |
| 207 | # Benchmark each output if --bench |
| 208 | if args.bench and os.path.exists(outfile): |
| 209 | print(f" Benchmarking {qt}...") |
| 210 | try: |
| 211 | from mojollama.benchmarks.bench_tok import bench_native |
| 212 | pp_ms, pp_tok, tg_ms, tg_tok = bench_native(outfile) |
| 213 | print(f" tg128: {tg_tok:.1f} tok/s") |
| 214 | results[-1] = (qt, outfile, elapsed, size_mb, tg_tok) |
| 215 | except Exception as e: |
| 216 | print(f" Benchmark FAILED: {e}") |
| 217 | |
| 218 | prev_model = outfile |
| 219 | print() |
| 220 | print(f"[Quantize] Cascade complete. {' → '.join(types)}") |
| 221 | return |
| 222 | |
| 223 | # Standard single quantization |
| 224 | outfile = args.output or args.model.replace(".gguf", f"-{args.type}.gguf") |
| 225 | print(f"\n[Quantize] {args.model} → {outfile} ({args.type})") |
| 226 | print() |
| 227 | t0 = time.time() |
| 228 | _run_llama_quantize(args.model, outfile, args.type, args) |
| 229 | elapsed = time.time() - t0 |
| 230 | size_mb = os.path.getsize(outfile) / (1024*1024) |
| 231 | print(f"\nDone: {elapsed:.0f}s Size: {size_mb:.0f} MB") |
| 232 | |
| 233 | # Benchmark if --bench |
| 234 | if args.bench: |
| 235 | print(f"\n[Quantize] Benchmarking {args.type}...") |
| 236 | try: |
| 237 | from mojollama.benchmarks.bench_tok import bench_native |
| 238 | pp_ms, pp_tok, tg_ms, tg_tok = bench_native(outfile) |
| 239 | print(f" pp512: {pp_tok:.1f} tok/s tg128: {tg_tok:.1f} tok/s") |
| 240 | except Exception as e: |
| 241 | print(f" Benchmark FAILED: {e}") |
| 242 | print() |
| 243 | |
| 244 | |
| 245 | def _run_llama_quantize(inpath, outpath, qtype, args): |
| 246 | """Run llama-quantize with progress monitoring.""" |
| 247 | quantize_bin = "/tmp/llama.cpp/build/bin/llama-quantize" |
| 248 | if not os.path.exists(quantize_bin): |
| 249 | print(f" ERROR: llama-quantize not found at {quantize_bin}") |
| 250 | print(f" Build it: cd /tmp/llama.cpp && cmake -B build && cmake --build build -j32 --target llama-quantize") |
| 251 | sys.exit(1) |
| 252 | cmd = [quantize_bin, "--allow-requantize" if args.allow_requantize else None, |
| 253 | "--pure" if args.pure else None, |
| 254 | "--leave-output-tensor" if args.leave_output else None, |
| 255 | "--dry-run" if args.dry_run else None, inpath, outpath, qtype] |
| 256 | if args.threads and args.threads > 0: |
| 257 | cmd.append(str(args.threads)) |
| 258 | if args.imatrix: |
| 259 | cmd.extend(["--imatrix", args.imatrix]) |
| 260 | cmd = [c for c in cmd if c is not None] |
| 261 | # Run with progress display |
| 262 | import subprocess |
| 263 | proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) |
| 264 | for line in proc.stdout: |
| 265 | line = line.rstrip() |
| 266 | if line: |
| 267 | # Show progress lines (not debug spam) |
| 268 | if any(x in line.lower() for x in ['size', 'quantizing', 'done', 'error', 'warning', 'processing', '%']): |
| 269 | print(f" {line}", flush=True) |
| 270 | elif line.startswith('['): |
| 271 | print(f" {line}", flush=True) |
| 272 | proc.wait() |
| 273 | if proc.returncode != 0: |
| 274 | print(f" ERROR: Quantization failed (exit code {proc.returncode})") |
| 275 | sys.exit(proc.returncode) |
| 276 | |
| 277 | |
| 278 | def cmd_imatrix(args): |
| 279 | """Generate importance matrix.""" |
| 280 | from mojollama.studio import cmd_imatrix as _imatrix |
| 281 | _imatrix(args) |
| 282 | |
| 283 | |
| 284 | def cmd_convert(args): |
| 285 | """Convert HuggingFace model to GGUF.""" |
| 286 | from mojollama.studio import cmd_export as _export |
| 287 | _export(args) |
| 288 | |
| 289 | |
| 290 | def cmd_info(args): |
| 291 | """Show system and model info.""" |
| 292 | from mojollama.studio import cmd_info as _info |
| 293 | _info(args) |
| 294 | |
| 295 | |
| 296 | def cmd_autotune(args): |
| 297 | """Auto-tune server settings for this hardware.""" |
| 298 | # Default to MojoLlama native tuning if no llama-bench available |
| 299 | import shutil |
| 300 | lb = shutil.which("llama-bench") or "/tmp/llama.cpp/build/bin/llama-bench" |
| 301 | use_mojollama = args.mojollama or not os.path.exists(lb) |
| 302 | if not args.model: |
| 303 | print("ERROR: --model is required for autotune") |
| 304 | print("Usage: mojollama autotune -m model.gguf [--quick] [--llamacpp-only]") |
| 305 | sys.exit(1) |
| 306 | |
| 307 | from mojollama.autotune import autotune |
| 308 | config = autotune(args.model, quick=args.quick, mojollama=use_mojollama) |
| 309 | if config: |
| 310 | from mojollama.autotune import save_config, print_config |
| 311 | save_config(config) |
| 312 | print_config(config) |
| 313 | |
| 314 | |
| 315 | def cmd_hub(args): |
| 316 | """HuggingFace Hub operations.""" |
| 317 | if not args.hub_action: |
| 318 | print("Usage: mojollama hub <login|whoami|push> [options]") |
| 319 | print(" mojollama hub login --token <token>") |
| 320 | print(" mojollama hub whoami") |
| 321 | print(" mojollama hub push -m model.gguf --repo user/repo") |
| 322 | sys.exit(1) |
| 323 | if args.hub_action == "login": |
| 324 | from mojollama.studio import cmd_hub_login as _login |
| 325 | _login(args) |
| 326 | elif args.hub_action == "whoami": |
| 327 | from mojollama.studio import cmd_hub_whoami as _whoami |
| 328 | _whoami(args) |
| 329 | elif args.hub_action == "push": |
| 330 | from mojollama.studio import cmd_hub_push as _push |
| 331 | _push(args) |
| 332 | |
| 333 | |
| 334 | def cmd_eval(args): |
| 335 | """Run evaluations.""" |
| 336 | from mojollama.studio import cmd_evaluate as _eval |
| 337 | _eval(args) |
| 338 | |
| 339 | |
| 340 | def cmd_export(args): |
| 341 | """Export to other formats.""" |
| 342 | if not args.export_format: |
| 343 | print("Usage: mojollama export <safetensors|onnx> [options]") |
| 344 | print(" mojollama export safetensors -m model.gguf -o ./export/") |
| 345 | print(" mojollama export onnx -m model.gguf -o model.onnx") |
| 346 | sys.exit(1) |
| 347 | if args.export_format == "safetensors": |
| 348 | from mojollama.studio import cmd_export_safetensors as _st |
| 349 | _st(args) |
| 350 | elif args.export_format == "onnx": |
| 351 | from mojollama.studio import cmd_export_onnx as _onnx |
| 352 | _onnx(args) |
| 353 | |
| 354 | |
| 355 | def cmd_train(args): |
| 356 | """Fine-tune a model.""" |
| 357 | from mojollama.studio import cmd_train as _train |
| 358 | _train(args) |
| 359 | |
| 360 | |
| 361 | def build_parser(): |
| 362 | """Build the unified argument parser.""" |
| 363 | parser = argparse.ArgumentParser( |
| 364 | description="MojoLlama — unified CLI for LLM inference, serving, and model ops", |
| 365 | formatter_class=argparse.RawDescriptionHelpFormatter, |
| 366 | epilog=""" |
| 367 | Examples: |
| 368 | mojollama chat -m model.gguf |
| 369 | mojollama serve -m model.gguf -p 8080 |
| 370 | mojollama bench -m model.gguf -n 128 |
| 371 | mojollama quantize model.gguf -t Q4_K_M |
| 372 | mojollama convert --hf meta-llama/Llama-3.2-1B --outtype q4_0 |
| 373 | mojollama info |
| 374 | """) |
| 375 | parser.add_argument("--version", "-V", action="store_true", |
| 376 | help="Show version and exit") |
| 377 | |
| 378 | sub = parser.add_subparsers(dest="command", help="Command") |
| 379 | |
| 380 | # ── chat ────────────────────────────────────────────────────── |
| 381 | p_chat = sub.add_parser("chat", help="Interactive chat with a model", |
| 382 | description="Chat with an LLM interactively") |
| 383 | p_chat.add_argument("-m", "--model", help="Model path (GGUF)") |
| 384 | p_chat.add_argument("-p", "--port", type=int, default=9000, |
| 385 | help="Backend server port (default: 9000)") |
| 386 | p_chat.set_defaults(func=cmd_chat) |
| 387 | |
| 388 | # ── serve ───────────────────────────────────────────────────── |
| 389 | p_serve = sub.add_parser("serve", help="Start API server", |
| 390 | description="Start an OpenAI-compatible API server with SSE streaming") |
| 391 | p_serve.add_argument("-m", "--model", help="Model path (GGUF)") |
| 392 | p_serve.add_argument("-p", "--port", type=int, default=8080, |
| 393 | help="Server port (default: 8080)") |
| 394 | p_serve.add_argument("--host", default="127.0.0.1", |
| 395 | help="Bind address (default: 127.0.0.1)") |
| 396 | p_serve.add_argument("-t", "--threads", type=int, default=0, |
| 397 | help="CPU threads (default: auto)") |
| 398 | p_serve.add_argument("--backend", choices=["native", "studio"], default="native", |
| 399 | help="Backend: native (mojollama.server) or studio (default: native)") |
| 400 | p_serve.set_defaults(func=cmd_serve) |
| 401 | |
| 402 | # ── bench ───────────────────────────────────────────────────── |
| 403 | p_bench = sub.add_parser("bench", aliases=["benchmark"], |
| 404 | help="Benchmark inference performance (better than llama-bench)", |
| 405 | description="Comprehensive benchmark: thread sweep, multi-model, " |
| 406 | "A/B comparison, profile mode, historical results.") |
| 407 | p_bench.add_argument("-m", "--model", type=str, |
| 408 | help="Model path(s) — comma-separated for multi-model comparison") |
| 409 | p_bench.add_argument("-t", "--threads", type=str, default="32", |
| 410 | help="Thread count(s) — comma-separated for sweep (default: 32)") |
| 411 | p_bench.add_argument("--prompt-len", type=int, default=512, |
| 412 | help="Prompt length in tokens (default: 512)") |
| 413 | p_bench.add_argument("--gen-len", type=int, default=128, |
| 414 | help="Tokens to generate (default: 128)") |
| 415 | p_bench.add_argument("--warmup", type=int, default=5, |
| 416 | help="Warmup tokens (default: 5)") |
| 417 | p_bench.add_argument("--measured", type=int, default=30, |
| 418 | help="Measured tokens (default: 30)") |
| 419 | p_bench.add_argument("--compare", action="store_true", |
| 420 | help="A/B comparison with llama.cpp") |
| 421 | p_bench.add_argument("--profile", action="store_true", |
| 422 | help="Component-level profiling") |
| 423 | p_bench.add_argument("--concurrent", type=str, |
| 424 | help="Concurrency benchmark: comma-sep levels, e.g. '1,2,4,8,16'") |
| 425 | p_bench.add_argument("--concurrent-quick", action="store_true", |
| 426 | help="Quick concurrency test (levels 1,4,8)") |
| 427 | p_bench.add_argument("--json", dest="output_json", action="store_true", |
| 428 | help="Output results as JSON") |
| 429 | p_bench.add_argument("--save", type=str, |
| 430 | help="Save results to JSON file") |
| 431 | p_bench.add_argument("--load", type=str, action="append", dest="load_paths", |
| 432 | help="Load previous results for comparison (can be used multiple times)") |
| 433 | p_bench.set_defaults(func=cmd_bench) |
| 434 | |
| 435 | # ── quantize ────────────────────────────────────────────────── |
| 436 | p_quant = sub.add_parser("quantize", aliases=["q"], |
| 437 | help="Quantize a GGUF model", |
| 438 | description="Quantize a GGUF model to a different quantization type. " |
| 439 | "Supports multi-quant cascade with --multi and target-BPW selection.") |
| 440 | p_quant.add_argument("model", nargs="?", help="Path to input GGUF model (optional with --list-types)") |
| 441 | p_quant.add_argument("-t", "--type", default="Q4_K_M", dest="type", |
| 442 | help="Quantization type (default: Q4_K_M). Use --list-types to see options") |
| 443 | p_quant.add_argument("-o", "--output", help="Output path (default: auto)") |
| 444 | p_quant.add_argument("--imatrix", help="Importance matrix file for guided quantization") |
| 445 | p_quant.add_argument("--threads", type=int, default=0, help="Thread count (0=auto)") |
| 446 | p_quant.add_argument("--allow-requantize", action="store_true", |
| 447 | help="Allow requantizing already quantized tensors") |
| 448 | p_quant.add_argument("--dry-run", action="store_true", |
| 449 | help="Calculate size without quantizing") |
| 450 | p_quant.add_argument("--pure", action="store_true", |
| 451 | help="Disable K-quant mixtures, pure type") |
| 452 | p_quant.add_argument("--leave-output", action="store_true", |
| 453 | help="Leave output.weight unquantized") |
| 454 | p_quant.add_argument("--multi", type=str, |
| 455 | help="Multi-quant cascade: comma-separated types, e.g. 'Q8_0,Q6_K,Q4_K_M,Q3_K_M' " |
| 456 | "(runs sequentially, each from previous)") |
| 457 | p_quant.add_argument("--target-bpw", type=float, |
| 458 | help="Target bits-per-weight (auto-selects best type)") |
| 459 | p_quant.add_argument("--bench", action="store_true", |
| 460 | help="Benchmark each output after quantization") |
| 461 | p_quant.add_argument("--list-types", action="store_true", |
| 462 | help="List available quantization types and exit") |
| 463 | p_quant.set_defaults(func=cmd_quantize) |
| 464 | |
| 465 | # ── imatrix ────────────────────────────────────────────────── |
| 466 | p_imatrix = sub.add_parser("imatrix", |
| 467 | help="Generate importance matrix", |
| 468 | description="Generate importance matrix for guided quantization") |
| 469 | p_imatrix.add_argument("model", help="Path to GGUF model") |
| 470 | p_imatrix.add_argument("-f", "--data", help="Calibration data file (text)") |
| 471 | p_imatrix.add_argument("-o", "--output", help="Output imatrix file path") |
| 472 | p_imatrix.add_argument("-t", "--threads", type=int, default=0, |
| 473 | help="Number of threads") |
| 474 | p_imatrix.add_argument("-c", "--ctx-size", type=int, default=512, |
| 475 | help="Context size (default: 512)") |
| 476 | p_imatrix.set_defaults(func=cmd_imatrix) |
| 477 | |
| 478 | # ── convert ─────────────────────────────────────────────────── |
| 479 | p_conv = sub.add_parser("convert", aliases=["cvt"], |
| 480 | help="Convert HF model to GGUF", |
| 481 | description="Convert a HuggingFace model to GGUF format") |
| 482 | p_conv.add_argument("--hf", help="HF model ID or path") |
| 483 | p_conv.add_argument("-m", "--model", help="Alias for --hf (local path or HF ID)") |
| 484 | p_conv.add_argument("--outtype", default="q4_0", |
| 485 | help="Output quantization type (default: q4_0)") |
| 486 | p_conv.add_argument("-o", "--outfile", help="Output GGUF path") |
| 487 | p_conv.add_argument("--remote", action="store_true", |
| 488 | help="Download from HuggingFace Hub") |
| 489 | p_conv.add_argument("--vocab-only", action="store_true") |
| 490 | p_conv.set_defaults(func=cmd_convert) |
| 491 | |
| 492 | # ── info ────────────────────────────────────────────────────── |
| 493 | p_info = sub.add_parser("info", help="Show system info", |
| 494 | description="Show system information: CPU, RAM, GPU, available models") |
| 495 | p_info.set_defaults(func=cmd_info) |
| 496 | |
| 497 | # ── autotune ────────────────────────────────────────────────── |
| 498 | p_tune = sub.add_parser("autotune", |
| 499 | help="Auto-tune server settings", |
| 500 | description="Auto-tune MojoLlama native engine or llama.cpp settings for this hardware") |
| 501 | p_tune.add_argument("-m", "--model", required=True, help="Model path (GGUF) to benchmark") |
| 502 | p_tune.add_argument("-q", "--quick", action="store_true", |
| 503 | help="Faster sweep (fewer combinations)") |
| 504 | p_tune.add_argument("--mojollama", action="store_true", |
| 505 | help="Force MojoLlama native engine tuning (auto-detected by default)") |
| 506 | p_tune.add_argument("--deep", action="store_true", |
| 507 | help="Deep hardware detection (CPU features, GPU, etc.)") |
| 508 | p_tune.set_defaults(func=cmd_autotune) |
| 509 | |
| 510 | # ── hub ─────────────────────────────────────────────────────── |
| 511 | p_hub = sub.add_parser("hub", help="HuggingFace Hub operations", |
| 512 | description="Login, whoami, push models to HuggingFace Hub") |
| 513 | p_hub.add_argument("hub_action", nargs="?", choices=["login", "whoami", "push"], |
| 514 | help="Hub action") |
| 515 | p_hub.add_argument("--token", help="HF API token (for login)") |
| 516 | p_hub.add_argument("-m", "--model", help="Model path (for push)") |
| 517 | p_hub.add_argument("--repo", help="HF repo ID (for push)") |
| 518 | p_hub.add_argument("--message", help="Commit message (for push)") |
| 519 | p_hub.add_argument("--private", action="store_true", |
| 520 | help="Create private repo (for push)") |
| 521 | p_hub.add_argument("--quant", help="Quantization type metadata (for push)") |
| 522 | p_hub.add_argument("--params", help="Parameter count metadata (for push)") |
| 523 | p_hub.set_defaults(func=cmd_hub) |
| 524 | |
| 525 | # ── eval ────────────────────────────────────────────────────── |
| 526 | p_eval = sub.add_parser("eval", aliases=["evaluate"], |
| 527 | help="Run evaluations", |
| 528 | description="Run benchmark evaluations (MMLU, GSM8K, CEval, etc.)") |
| 529 | p_eval.add_argument("action", nargs="?", choices=["download", "list"], default=None, |
| 530 | help="'download' to fetch datasets, 'list' to show available") |
| 531 | p_eval.add_argument("-b", "--benchmarks", nargs="+", |
| 532 | help="Benchmarks to run: mmlu gsm8k ceval hellaswag arc bbh humaneval") |
| 533 | p_eval.add_argument("-a", "--all", action="store_true", |
| 534 | help="Run all available benchmarks") |
| 535 | p_eval.add_argument("-m", "--model", help="Model name (for display)") |
| 536 | p_eval.add_argument("--max-samples", type=int, default=0, |
| 537 | help="Max samples per category (0=all)") |
| 538 | p_eval.add_argument("--port", type=int, default=8081, |
| 539 | help="Backend port") |
| 540 | p_eval.add_argument("-o", "--output", help="Save results to JSON file") |
| 541 | p_eval.set_defaults(func=cmd_eval) |
| 542 | |
| 543 | # ── export ──────────────────────────────────────────────────── |
| 544 | p_export = sub.add_parser("export", |
| 545 | help="Export to safetensors, ONNX", |
| 546 | description="Export GGUF to safetensors or ONNX format") |
| 547 | p_export.add_argument("export_format", nargs="?", |
| 548 | choices=["safetensors", "onnx"], |
| 549 | help="Export format") |
| 550 | p_export.add_argument("-m", "--model", help="GGUF model path") |
| 551 | p_export.add_argument("-o", "--output", help="Output path or directory") |
| 552 | p_export.add_argument("--dtype", default="float16", |
| 553 | choices=["float16", "float32", "bfloat16"], |
| 554 | help="Data type (safetensors, default: float16)") |
| 555 | p_export.add_argument("--shard-size", default="2GB", |
| 556 | help="Shard size (safetensors, default: 2GB)") |
| 557 | p_export.add_argument("--opset", type=int, default=17, |
| 558 | help="ONNX opset (ONNX, default: 17)") |
| 559 | p_export.add_argument("--max-seq-len", type=int, default=2048, |
| 560 | help="Max sequence length (ONNX, default: 2048)") |
| 561 | p_export.set_defaults(func=cmd_export) |
| 562 | |
| 563 | # ── train ───────────────────────────────────────────────────── |
| 564 | p_train = sub.add_parser("train", |
| 565 | help="Fine-tune a model", |
| 566 | description="Fine-tune a model using LoRA, QLoRA, DoRA, GaLore, DPO, GRPO, etc.") |
| 567 | p_train.add_argument("--model", help="Model path (GGUF)") |
| 568 | p_train.add_argument("--data", help="Training data (JSONL, JSON, or text)") |
| 569 | p_train.add_argument("--method", choices=["lora", "qlora", "dora", "galore", |
| 570 | "dpo", "orpo", "kto", "simpo", "grpo"], |
| 571 | default="lora", help="Training method (default: lora)") |
| 572 | p_train.add_argument("--lora-out", default="adapter.gguf") |
| 573 | p_train.add_argument("--lora-rank", type=int, default=16) |
| 574 | p_train.add_argument("--lora-alpha", type=int, default=32) |
| 575 | p_train.add_argument("--lr", type=float, default=1e-4) |
| 576 | p_train.add_argument("--weight-decay", type=float, default=0.0) |
| 577 | p_train.add_argument("--epochs", type=int, default=2) |
| 578 | p_train.add_argument("--batch", type=int, default=4) |
| 579 | p_train.add_argument("--max-seq-length", type=int, default=512) |
| 580 | p_train.add_argument("--seed", type=int, default=42) |
| 581 | p_train.add_argument("--warmup-steps", type=int, default=0) |
| 582 | p_train.add_argument("--dataset-format", default="auto", |
| 583 | choices=["auto", "alpaca", "sharegpt", "jsonl", "text"]) |
| 584 | p_train.add_argument("--list-methods", action="store_true", |
| 585 | help="List available training methods") |
| 586 | p_train.add_argument("--dpo-beta", type=float, default=0.1) |
| 587 | p_train.add_argument("--orpo-lambda", type=float, default=0.5) |
| 588 | p_train.add_argument("--simpo-gamma", type=float, default=0.5) |
| 589 | p_train.add_argument("--grpo-group-size", type=int, default=8) |
| 590 | p_train.add_argument("--grpo-clip", type=float, default=0.2) |
| 591 | p_train.add_argument("--galore-rank", type=int, default=128) |
| 592 | p_train.set_defaults(func=cmd_train) |
| 593 | |
| 594 | return parser |
| 595 | |
| 596 | |
| 597 | def main(): |
| 598 | parser = build_parser() |
| 599 | |
| 600 | # If no args, show banner + command list |
| 601 | if len(sys.argv) == 1: |
| 602 | print_commands() |
| 603 | return |
| 604 | |
| 605 | args = parser.parse_args() |
| 606 | |
| 607 | if args.version: |
| 608 | print(f"MojoLlama v{VERSION}") |
| 609 | return |
| 610 | |
| 611 | if not hasattr(args, "func"): |
| 612 | print_commands() |
| 613 | return |
| 614 | |
| 615 | # Set OMP_NUM_THREADS if common threads arg exists |
| 616 | if hasattr(args, "threads") and args.threads > 0: |
| 617 | os.environ["OMP_NUM_THREADS"] = str(args.threads) |
| 618 | |
| 619 | try: |
| 620 | args.func(args) |
| 621 | except KeyboardInterrupt: |
| 622 | print("\nInterrupted.") |
| 623 | sys.exit(130) |
| 624 | except Exception as e: |
| 625 | print(f"ERROR: {e}", file=sys.stderr) |
| 626 | if os.environ.get("MOJOLLAMA_DEBUG"): |
| 627 | import traceback |
| 628 | traceback.print_exc() |
| 629 | sys.exit(1) |
| 630 | |
| 631 | |
| 632 | if __name__ == "__main__": |
| 633 | main() |