MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / exporter.py
| 1 | #!/usr/bin/env python3 |
| 2 | """MojoLlama Exporter — HF Hub push, safetensors, ONNX, checkpoint management. |
| 3 | |
| 4 | Supports: |
| 5 | - Push models and LoRA adapters to HuggingFace Hub |
| 6 | - Convert GGUF → safetensors (for use with transformers) |
| 7 | - Convert GGUF → ONNX (for deployment) |
| 8 | - Save/load training checkpoints (optimizer, LR scheduler, step) |
| 9 | - Best-model tracking (save when eval improves) |
| 10 | |
| 11 | Dependencies: |
| 12 | pip install huggingface_hub safetensors transformers onnx onnxruntime |
| 13 | """ |
| 14 | |
| 15 | import os |
| 16 | import sys |
| 17 | import io |
| 18 | import json |
| 19 | import time |
| 20 | import shutil |
| 21 | import tempfile |
| 22 | import subprocess |
| 23 | from pathlib import Path |
| 24 | from typing import Optional, Dict, Any, List, Tuple |
| 25 | |
| 26 | import numpy as np |
| 27 | |
| 28 | STUDIO_VERSION = "0.1.0" |
| 29 | BASE_DIR = Path(__file__).parent.parent.parent.resolve() |
| 30 | LLAMA_CPP = "/tmp/llama.cpp" |
| 31 | CONVERTER = f"{LLAMA_CPP}/convert_hf_to_gguf.py" |
| 32 | |
| 33 | |
| 34 | # ═══════════════════════════════════════════════════════════════ |
| 35 | # HuggingFace Hub |
| 36 | # ═══════════════════════════════════════════════════════════════ |
| 37 | |
| 38 | def hub_get_token(env_only: bool = False) -> str: |
| 39 | """Resolve HF token from env vars: HF_TOKEN (highest priority), HUGGINGFACE_TOKEN. |
| 40 | |
| 41 | Args: |
| 42 | env_only: If True, skip token store lookup (only check env). Default False. |
| 43 | |
| 44 | Returns: |
| 45 | Token string, or empty string if not found. |
| 46 | """ |
| 47 | token = os.environ.get("HF_TOKEN", "") or os.environ.get("HUGGINGFACE_TOKEN", "") |
| 48 | if token: |
| 49 | return token |
| 50 | if not env_only: |
| 51 | try: |
| 52 | from huggingface_hub import HfFolder |
| 53 | stored = HfFolder.get_token() |
| 54 | if stored: |
| 55 | return stored |
| 56 | except Exception: |
| 57 | pass |
| 58 | return "" |
| 59 | |
| 60 | |
| 61 | def hub_login(token: str = "", save: bool = True) -> bool: |
| 62 | """Login to HuggingFace Hub with a token or check existing login. |
| 63 | |
| 64 | Auto-detects HF_TOKEN / HUGGINGFACE_TOKEN env vars if no token is passed. |
| 65 | """ |
| 66 | try: |
| 67 | from huggingface_hub import login, whoami, HfFolder |
| 68 | except ImportError: |
| 69 | print("❌ huggingface_hub not installed. Run: pip install huggingface_hub") |
| 70 | return False |
| 71 | |
| 72 | # Resolve token: explicit arg > env var |
| 73 | if not token: |
| 74 | token = hub_get_token(env_only=True) |
| 75 | |
| 76 | if token: |
| 77 | login(token=token, add_to_git_credential=save) |
| 78 | print("✅ Logged in to HuggingFace Hub") |
| 79 | return True |
| 80 | else: |
| 81 | try: |
| 82 | user = whoami() |
| 83 | print(f"✅ Already logged in as: {user.get('name', 'unknown')}") |
| 84 | return True |
| 85 | except Exception: |
| 86 | print("❌ Not logged in to HuggingFace Hub.") |
| 87 | print(" Set HF_TOKEN env var or use --token or run: huggingface-cli login") |
| 88 | return False |
| 89 | |
| 90 | |
| 91 | def hub_whoami() -> Optional[Dict[str, Any]]: |
| 92 | """Get current HuggingFace user info.""" |
| 93 | try: |
| 94 | from huggingface_hub import whoami |
| 95 | return whoami() |
| 96 | except ImportError: |
| 97 | return None |
| 98 | except Exception: |
| 99 | return None |
| 100 | |
| 101 | |
| 102 | def hub_push_model( |
| 103 | model_path: str, |
| 104 | repo_id: str, |
| 105 | *, |
| 106 | commit_message: str = "Upload MojoLlama GGUF model", |
| 107 | private: bool = False, |
| 108 | exist_ok: bool = True, |
| 109 | metadata: Optional[Dict[str, Any]] = None, |
| 110 | ) -> Optional[str]: |
| 111 | """Upload a GGUF model (or safetensors) to HuggingFace Hub. |
| 112 | |
| 113 | Args: |
| 114 | model_path: Path to local model file (GGUF, safetensors, etc.) |
| 115 | repo_id: HuggingFace repo ID (e.g. 'username/model-name') |
| 116 | commit_message: Commit message for the upload |
| 117 | private: Whether to create a private repo |
| 118 | exist_ok: If False, fails if repo already exists |
| 119 | metadata: Optional metadata dict to save as model card or README |
| 120 | |
| 121 | Returns: |
| 122 | URL to the uploaded model on HF Hub, or None on failure. |
| 123 | """ |
| 124 | try: |
| 125 | from huggingface_hub import ( |
| 126 | HfApi, create_repo, upload_file, upload_folder, |
| 127 | Repository, CommitOperationAdd, |
| 128 | ) |
| 129 | except ImportError: |
| 130 | print("❌ huggingface_hub not installed. Run: pip install huggingface_hub") |
| 131 | return None |
| 132 | |
| 133 | if not os.path.exists(model_path): |
| 134 | print(f"❌ Model not found: {model_path}") |
| 135 | return None |
| 136 | |
| 137 | api = HfApi() |
| 138 | |
| 139 | # Create or get repo |
| 140 | try: |
| 141 | create_repo( |
| 142 | repo_id=repo_id, |
| 143 | private=private, |
| 144 | exist_ok=exist_ok, |
| 145 | ) |
| 146 | print(f" Repo: {repo_id}") |
| 147 | except Exception as e: |
| 148 | print(f"❌ Failed to create repo: {e}") |
| 149 | return None |
| 150 | |
| 151 | model_size = os.path.getsize(model_path) |
| 152 | model_name = os.path.basename(model_path) |
| 153 | |
| 154 | print(f" File: {model_name} ({model_size / 1024**3:.2f} GB)") |
| 155 | print(f" Uploading...") |
| 156 | |
| 157 | # Upload the model file |
| 158 | try: |
| 159 | upload_url = api.upload_file( |
| 160 | path_or_fileobj=model_path, |
| 161 | path_in_repo=model_name, |
| 162 | repo_id=repo_id, |
| 163 | commit_message=commit_message, |
| 164 | ) |
| 165 | except Exception as e: |
| 166 | print(f"❌ Upload failed: {e}") |
| 167 | return None |
| 168 | |
| 169 | # Upload metadata as README.md if provided |
| 170 | if metadata: |
| 171 | readme_parts = ["---"] |
| 172 | for k, v in metadata.items(): |
| 173 | if isinstance(v, str): |
| 174 | readme_parts.append(f"{k}: '{v}'") |
| 175 | elif isinstance(v, (int, float)): |
| 176 | readme_parts.append(f"{k}: {v}") |
| 177 | elif isinstance(v, bool): |
| 178 | readme_parts.append(f"{k}: {'true' if v else 'false'}") |
| 179 | if metadata.get("tags"): |
| 180 | tags = metadata["tags"] |
| 181 | if isinstance(tags, list): |
| 182 | readme_parts.append(f"tags: [{', '.join(tags)}]") |
| 183 | readme_parts.append("---") |
| 184 | readme_parts.append("") |
| 185 | readme_parts.append(f"# {repo_id}") |
| 186 | readme_parts.append("") |
| 187 | readme_parts.append(f"MojoLlama Studio generated model ({model_name}).") |
| 188 | readme_parts.append("") |
| 189 | readme_parts.append("## Metadata") |
| 190 | for k, v in metadata.items(): |
| 191 | if k == "tags": |
| 192 | continue |
| 193 | readme_parts.append(f"- **{k}**: {v}") |
| 194 | readme_parts.append("") |
| 195 | |
| 196 | readme_content = "\n".join(readme_parts) |
| 197 | |
| 198 | # Upload README as a separate commit |
| 199 | try: |
| 200 | api.upload_file( |
| 201 | path_or_fileobj=io.BytesIO(readme_content.encode()), |
| 202 | path_in_repo="README.md", |
| 203 | repo_id=repo_id, |
| 204 | commit_message="Add model metadata and README", |
| 205 | ) |
| 206 | except Exception as e: |
| 207 | print(f" ⚠️ README upload failed: {e}") |
| 208 | |
| 209 | model_url = f"https://huggingface.co/{repo_id}" |
| 210 | print(f"✅ Uploaded to {model_url}") |
| 211 | return model_url |
| 212 | |
| 213 | |
| 214 | def hub_push_adapter( |
| 215 | adapter_path: str, |
| 216 | base_model: str, |
| 217 | repo_id: str, |
| 218 | *, |
| 219 | commit_message: str = "Upload MojoLlama LoRA adapter", |
| 220 | private: bool = False, |
| 221 | metadata: Optional[Dict[str, Any]] = None, |
| 222 | ) -> Optional[str]: |
| 223 | """Upload a LoRA adapter to HuggingFace Hub, with adapter config.""" |
| 224 | try: |
| 225 | from huggingface_hub import HfApi, create_repo, upload_file |
| 226 | except ImportError: |
| 227 | print("❌ huggingface_hub not installed") |
| 228 | return None |
| 229 | |
| 230 | if not os.path.exists(adapter_path): |
| 231 | print(f"❌ Adapter not found: {adapter_path}") |
| 232 | return None |
| 233 | |
| 234 | api = HfApi() |
| 235 | |
| 236 | try: |
| 237 | create_repo(repo_id=repo_id, private=private, exist_ok=True) |
| 238 | except Exception as e: |
| 239 | print(f"❌ Failed to create repo: {e}") |
| 240 | return None |
| 241 | |
| 242 | # Upload adapter GGUF |
| 243 | adapter_name = os.path.basename(adapter_path) |
| 244 | print(f" Uploading adapter: {adapter_name}") |
| 245 | try: |
| 246 | api.upload_file( |
| 247 | path_or_fileobj=adapter_path, |
| 248 | path_in_repo=adapter_name, |
| 249 | repo_id=repo_id, |
| 250 | commit_message=commit_message, |
| 251 | ) |
| 252 | except Exception as e: |
| 253 | print(f"❌ Upload failed: {e}") |
| 254 | return None |
| 255 | |
| 256 | # Create adapter_config.json metadata |
| 257 | adapter_config = { |
| 258 | "adapter_type": "LoRA", |
| 259 | "base_model": base_model, |
| 260 | "studio_version": STUDIO_VERSION, |
| 261 | } |
| 262 | if metadata: |
| 263 | adapter_config.update(metadata) |
| 264 | |
| 265 | try: |
| 266 | config_json = json.dumps(adapter_config, indent=2) |
| 267 | api.upload_file( |
| 268 | path_or_fileobj=io.BytesIO(config_json.encode()), |
| 269 | path_in_repo="adapter_config.json", |
| 270 | repo_id=repo_id, |
| 271 | commit_message="Add adapter configuration", |
| 272 | ) |
| 273 | except Exception as e: |
| 274 | print(f" ⚠️ Config upload failed: {e}") |
| 275 | |
| 276 | url = f"https://huggingface.co/{repo_id}" |
| 277 | print(f"✅ Adapter uploaded to {url}") |
| 278 | return url |
| 279 | |
| 280 | |
| 281 | def hub_list_models(pattern: str = "") -> List[Dict[str, Any]]: |
| 282 | """List models on the HuggingFace Hub matching a pattern.""" |
| 283 | try: |
| 284 | from huggingface_hub import HfApi |
| 285 | except ImportError: |
| 286 | return [] |
| 287 | api = HfApi() |
| 288 | try: |
| 289 | models = api.list_models(search=pattern, task="text-generation") |
| 290 | return [ |
| 291 | { |
| 292 | "id": m.modelId, |
| 293 | "downloads": m.downloads or 0, |
| 294 | "likes": m.likes or 0, |
| 295 | "pipeline_tag": m.pipeline_tag or "", |
| 296 | "modified": str(m.lastModified) if m.lastModified else "", |
| 297 | } |
| 298 | for m in models[:20] |
| 299 | ] |
| 300 | except Exception: |
| 301 | return [] |
| 302 | |
| 303 | |
| 304 | # ═══════════════════════════════════════════════════════════════ |
| 305 | # GGUF → Safetensors Conversion |
| 306 | # ═══════════════════════════════════════════════════════════════ |
| 307 | |
| 308 | def gguf_to_safetensors( |
| 309 | gguf_path: str, |
| 310 | output_dir: str, |
| 311 | *, |
| 312 | dtype: str = "float16", |
| 313 | shard_size: str = "2GB", |
| 314 | ) -> Optional[str]: |
| 315 | """Convert a GGUF model to safetensors format. |
| 316 | |
| 317 | Args: |
| 318 | gguf_path: Path to input GGUF file |
| 319 | output_dir: Output directory for safetensors files |
| 320 | dtype: Output dtype ('float16', 'float32', 'bfloat16') |
| 321 | shard_size: Max shard size ('2GB', '5GB', '10GB', or 'NO' for no sharding) |
| 322 | |
| 323 | Returns: |
| 324 | Path to the output directory, or None on failure. |
| 325 | """ |
| 326 | print(f"GGUF → Safetensors conversion") |
| 327 | print(f" Input: {gguf_path}") |
| 328 | print(f" Output: {output_dir}") |
| 329 | print(f" Dtype: {dtype}") |
| 330 | print(f" Shard size: {shard_size}") |
| 331 | print() |
| 332 | |
| 333 | try: |
| 334 | from safetensors import safe_open |
| 335 | from safetensors.torch import save_file as st_save_file |
| 336 | except ImportError: |
| 337 | print("❌ safetensors not installed. Run: pip install safetensors") |
| 338 | return None |
| 339 | |
| 340 | try: |
| 341 | from gguf import GGUFReader, GGMLQuantizationType, dequantize |
| 342 | except ImportError: |
| 343 | print("❌ gguf package not installed") |
| 344 | return None |
| 345 | |
| 346 | import torch |
| 347 | |
| 348 | os.makedirs(output_dir, exist_ok=True) |
| 349 | |
| 350 | dtype_map = { |
| 351 | "float16": torch.float16, |
| 352 | "float32": torch.float32, |
| 353 | "bfloat16": torch.bfloat16, |
| 354 | } |
| 355 | target_dtype = dtype_map.get(dtype, torch.float16) |
| 356 | |
| 357 | max_shard_bytes = { |
| 358 | "NO": float("inf"), |
| 359 | "1GB": 1 * 1024**3, |
| 360 | "2GB": 2 * 1024**3, |
| 361 | "5GB": 5 * 1024**3, |
| 362 | "10GB": 10 * 1024**3, |
| 363 | }.get(shard_size, 2 * 1024**3) |
| 364 | |
| 365 | print("Reading GGUF model...") |
| 366 | reader = GGUFReader(gguf_path) |
| 367 | print(f" {len(reader.tensors)} tensors found") |
| 368 | |
| 369 | # Extract metadata for model index |
| 370 | metadata = {} |
| 371 | arch = "llama" |
| 372 | for name, field in reader.fields.items(): |
| 373 | if name == "general.architecture": |
| 374 | try: |
| 375 | arch = bytes(np.asarray(field.parts[-1])).decode("utf-8") |
| 376 | except Exception: |
| 377 | pass |
| 378 | if name.startswith("GGUF."): |
| 379 | continue |
| 380 | metadata[name] = str(field.parts[-1]) if field.parts else "" |
| 381 | |
| 382 | # Convert tensors |
| 383 | tensors = {} |
| 384 | current_shard = 1 |
| 385 | current_shard_size = 0 |
| 386 | shard_files = [] |
| 387 | |
| 388 | print(f"Converting to {dtype}...") |
| 389 | |
| 390 | for t in reader.tensors: |
| 391 | name = t.name |
| 392 | raw_data = np.asarray(t.data) |
| 393 | |
| 394 | # Dequantize to float32 first |
| 395 | try: |
| 396 | data_f32 = dequantize(raw_data, t.tensor_type).astype(np.float32) |
| 397 | except Exception: |
| 398 | # If dequantize fails, try reading as-is |
| 399 | data_f32 = raw_data.astype(np.float32) |
| 400 | |
| 401 | # Convert to target dtype |
| 402 | tensor_torch = torch.from_numpy(data_f32).to(target_dtype) |
| 403 | tensors[name] = tensor_torch |
| 404 | |
| 405 | tensor_bytes = tensor_torch.numel() * tensor_torch.element_size() |
| 406 | current_shard_size += tensor_bytes |
| 407 | |
| 408 | # Write shard if we've crossed the threshold |
| 409 | if current_shard_size >= max_shard_bytes: |
| 410 | if shard_size == "NO": |
| 411 | continue |
| 412 | shard_file = os.path.join(output_dir, f"model-{current_shard_size // (1024**3):03d}-of-{100:03d}.safetensors") |
| 413 | shard_file = os.path.join(output_dir, f"model-{current_shard:05d}-of-{100:05d}.safetensors") |
| 414 | shard_path = _write_safetensors_shard(tensors, shard_file) |
| 415 | if shard_path: |
| 416 | shard_files.append(shard_path) |
| 417 | print(f" Shard {current_shard}: {shard_path} ({current_shard_size / 1024**3:.2f} GB)") |
| 418 | tensors = {} |
| 419 | current_shard += 1 |
| 420 | current_shard_size = 0 |
| 421 | |
| 422 | # Write final shard |
| 423 | if tensors: |
| 424 | total_shards = current_shard |
| 425 | shard_file = os.path.join(output_dir, f"model-{current_shard:05d}-of-{total_shards:05d}.safetensors") |
| 426 | shard_path = _write_safetensors_shard(tensors, shard_file) |
| 427 | if shard_path: |
| 428 | shard_files.append(shard_path) |
| 429 | print(f" Final shard {current_shard}: {shard_path}") |
| 430 | |
| 431 | # Rename shard files with correct total count |
| 432 | total_shards = len(shard_files) |
| 433 | renamed_files = [] |
| 434 | for i, old_path in enumerate(shard_files): |
| 435 | new_path = os.path.join(output_dir, f"model-{i+1:05d}-of-{total_shards:05d}.safetensors") |
| 436 | if old_path != new_path: |
| 437 | os.rename(old_path, new_path) |
| 438 | renamed_files.append(os.path.basename(new_path)) |
| 439 | |
| 440 | # Write model index JSON |
| 441 | index_data = { |
| 442 | "metadata": { |
| 443 | "total_size": sum( |
| 444 | os.path.getsize(os.path.join(output_dir, f)) |
| 445 | for f in renamed_files |
| 446 | ), |
| 447 | }, |
| 448 | "weight_map": _build_weight_map(reader.tensors, renamed_files, max_shard_bytes), |
| 449 | } |
| 450 | |
| 451 | index_path = os.path.join(output_dir, "model.safetensors.index.json") |
| 452 | with open(index_path, "w") as f: |
| 453 | json.dump(index_data, f, indent=2) |
| 454 | print(f" Index: {index_path}") |
| 455 | |
| 456 | # Write config.json with architecture info |
| 457 | config = { |
| 458 | "architectures": ["LlamaForCausalLM"], |
| 459 | "model_type": arch, |
| 460 | "torch_dtype": dtype, |
| 461 | "transformers_version": "4.40.0", |
| 462 | } |
| 463 | # Try to extract n_embd, n_head, n_layer from metadata |
| 464 | n_embd = _get_metadata_int(reader, "llama.embedding_length") |
| 465 | if n_embd: |
| 466 | config["hidden_size"] = n_embd |
| 467 | n_head = _get_metadata_int(reader, "llama.head_count") |
| 468 | if n_head: |
| 469 | config["num_attention_heads"] = n_head |
| 470 | n_layer = _get_metadata_int(reader, "llama.block_count") |
| 471 | if n_layer: |
| 472 | config["num_hidden_layers"] = n_layer |
| 473 | |
| 474 | config_path = os.path.join(output_dir, "config.json") |
| 475 | with open(config_path, "w") as f: |
| 476 | json.dump(config, f, indent=2) |
| 477 | print(f" Config: {config_path}") |
| 478 | |
| 479 | print(f"\n✅ Safetensors model saved to {output_dir}") |
| 480 | print(f" {len(renamed_files)} shard(s), {len(reader.tensors)} tensors") |
| 481 | return output_dir |
| 482 | |
| 483 | |
| 484 | def _write_safetensors_shard(tensors: Dict, path: str) -> Optional[str]: |
| 485 | """Write a dict of torch tensors to a safetensors file.""" |
| 486 | try: |
| 487 | from safetensors.torch import save_file as st_save_file |
| 488 | st_save_file(tensors, path, metadata={"format": "pt"}) |
| 489 | return path |
| 490 | except Exception as e: |
| 491 | print(f" ⚠️ Failed to write shard {path}: {e}") |
| 492 | return None |
| 493 | |
| 494 | |
| 495 | def _build_weight_map(tensors, shard_files, max_shard_bytes): |
| 496 | """Build weight_map dict for safetensors index.""" |
| 497 | import itertools |
| 498 | |
| 499 | weight_map = {} |
| 500 | shard_idx = 0 |
| 501 | current_shard = os.path.join(os.path.dirname(shard_files[0]) if shard_files else ".", shard_files[0]) if shard_files else "" |
| 502 | current_size = 0 |
| 503 | |
| 504 | for t in tensors: |
| 505 | tensor_size = np.asarray(t.data).nbytes |
| 506 | if current_size + tensor_size > max_shard_bytes and shard_idx < len(shard_files) - 1: |
| 507 | shard_idx += 1 |
| 508 | current_size = 0 |
| 509 | current_shard = os.path.join(os.path.dirname(shard_files[0]) if shard_files else ".", shard_files[shard_idx]) if shard_files else "" |
| 510 | weight_map[t.name] = current_shard |
| 511 | current_size += tensor_size |
| 512 | |
| 513 | return weight_map |
| 514 | |
| 515 | |
| 516 | def _get_metadata_int(reader, key): |
| 517 | """Try to read an integer metadata value from a GGUF reader.""" |
| 518 | try: |
| 519 | from gguf import GGUFValueType |
| 520 | if key in reader.fields: |
| 521 | field = reader.fields[key] |
| 522 | if field.types[-1] in (GGUFValueType.UINT32, GGUFValueType.INT32, |
| 523 | GGUFValueType.UINT64, GGUFValueType.INT64): |
| 524 | return int(np.asarray(field.parts[-1]).item()) |
| 525 | except Exception: |
| 526 | pass |
| 527 | return None |
| 528 | |
| 529 | |
| 530 | # ═══════════════════════════════════════════════════════════════ |
| 531 | # GGUF → ONNX Export |
| 532 | # ═══════════════════════════════════════════════════════════════ |
| 533 | |
| 534 | def gguf_to_onnx( |
| 535 | gguf_path: str, |
| 536 | output_path: str, |
| 537 | *, |
| 538 | opset: int = 17, |
| 539 | optimize: bool = True, |
| 540 | max_seq_len: int = 2048, |
| 541 | ) -> Optional[str]: |
| 542 | """Convert a GGUF model to ONNX format. |
| 543 | |
| 544 | This is a best-effort conversion — GGUF models are quantized weight formats |
| 545 | meant for llama.cpp, not for ONNX. We convert weights and create a minimal |
| 546 | ONNX export. |
| 547 | |
| 548 | Args: |
| 549 | gguf_path: Path to input GGUF file |
| 550 | output_path: Output ONNX file path |
| 551 | opset: ONNX opset version (default: 17) |
| 552 | optimize: Whether to run ONNX optimization passes |
| 553 | max_seq_len: Maximum sequence length for the model |
| 554 | |
| 555 | Returns: |
| 556 | Path to output ONNX file, or None on failure. |
| 557 | """ |
| 558 | print(f"GGUF → ONNX Export") |
| 559 | print(f" Input: {gguf_path}") |
| 560 | print(f" Output: {output_path}") |
| 561 | print(f" Opset: {opset}") |
| 562 | print(f" Max seq len: {max_seq_len}") |
| 563 | print() |
| 564 | |
| 565 | try: |
| 566 | import onnx |
| 567 | from onnx import helper, TensorProto, numpy_helper |
| 568 | except ImportError: |
| 569 | print("❌ onnx not installed. Run: pip install onnx onnxruntime") |
| 570 | return None |
| 571 | |
| 572 | try: |
| 573 | from gguf import GGUFReader, GGMLQuantizationType, dequantize |
| 574 | except ImportError: |
| 575 | print("❌ gguf package not installed") |
| 576 | return None |
| 577 | |
| 578 | import torch |
| 579 | import torch.nn as nn |
| 580 | |
| 581 | # Read GGUF model |
| 582 | print("Reading GGUF model...") |
| 583 | reader = GGUFReader(gguf_path) |
| 584 | print(f" {len(reader.tensors)} tensors found") |
| 585 | |
| 586 | # Extract model dimensions from metadata |
| 587 | n_layer = _get_metadata_int(reader, "llama.block_count") or 24 |
| 588 | n_embd = _get_metadata_int(reader, "llama.embedding_length") or 2048 |
| 589 | n_head = _get_metadata_int(reader, "llama.head_count") or 16 |
| 590 | n_head_kv = _get_metadata_int(reader, "llama.head_count_kv") or n_head |
| 591 | n_ff = _get_metadata_int(reader, "llama.feed_forward_length") or n_embd * 4 |
| 592 | |
| 593 | print(f" Architecture: {n_layer} layers, {n_embd} hidden, {n_head} heads") |
| 594 | |
| 595 | # Dequantize all tensors to float32 |
| 596 | print("Dequantizing tensors...") |
| 597 | state_dict = {} |
| 598 | for t in reader.tensors: |
| 599 | name = t.name |
| 600 | raw_data = np.asarray(t.data) |
| 601 | try: |
| 602 | data_f32 = dequantize(raw_data, t.tensor_type).astype(np.float32) |
| 603 | except Exception: |
| 604 | data_f32 = raw_data.astype(np.float32) |
| 605 | state_dict[name] = torch.from_numpy(data_f32) |
| 606 | |
| 607 | # Build a simple transformer model and trace it |
| 608 | print("Building ONNX model...") |
| 609 | |
| 610 | class LlamaLikeModel(nn.Module): |
| 611 | """Simplified Llama-like model for ONNX export.""" |
| 612 | def __init__(self, state_dict, n_embd, n_head, n_layer, n_ff, max_seq_len): |
| 613 | super().__init__() |
| 614 | self.n_embd = n_embd |
| 615 | self.max_seq_len = max_seq_len |
| 616 | self.n_head = n_head |
| 617 | self.n_layer = n_layer |
| 618 | |
| 619 | # Embedding |
| 620 | self.embed = nn.Embedding(max_seq_len, n_embd) |
| 621 | self.lm_head = nn.Linear(n_embd, max_seq_len, bias=False) |
| 622 | |
| 623 | # Load weights from state_dict |
| 624 | self._load_weights(state_dict) |
| 625 | |
| 626 | def _load_weights(self, sd): |
| 627 | # Map GGUF tensor names to our model |
| 628 | weight_map = { |
| 629 | "token_embd.weight": "embed.weight", |
| 630 | "output.weight": "lm_head.weight", |
| 631 | } |
| 632 | for gguf_name, our_name in weight_map.items(): |
| 633 | if gguf_name in sd: |
| 634 | self.state_dict()[our_name].copy_(sd[gguf_name]) |
| 635 | |
| 636 | def forward(self, input_ids): |
| 637 | x = self.embed(input_ids) |
| 638 | x = self.lm_head(x) |
| 639 | return x |
| 640 | |
| 641 | model = LlamaLikeModel(state_dict, n_embd, n_head, n_layer, n_ff, max_seq_len) |
| 642 | model.eval() |
| 643 | |
| 644 | # Export to ONNX |
| 645 | dummy_input = torch.randint(0, max_seq_len, (1, 1)) |
| 646 | torch.onnx.export( |
| 647 | model, |
| 648 | dummy_input, |
| 649 | output_path, |
| 650 | export_params=True, |
| 651 | opset_version=opset, |
| 652 | do_constant_folding=True, |
| 653 | input_names=["input_ids"], |
| 654 | output_names=["logits"], |
| 655 | dynamic_axes={ |
| 656 | "input_ids": {0: "batch_size", 1: "sequence_length"}, |
| 657 | "logits": {0: "batch_size", 1: "sequence_length"}, |
| 658 | }, |
| 659 | ) |
| 660 | |
| 661 | # Run optimization passes |
| 662 | if optimize: |
| 663 | print("Running ONNX optimization...") |
| 664 | try: |
| 665 | import onnxoptimizer |
| 666 | onnx_model = onnx.load(output_path) |
| 667 | passes = ["fuse_consecutive_transposes", "eliminate_deadend", "eliminate_duplicate_initializer"] |
| 668 | optimized = onnxoptimizer.optimize(onnx_model, passes) |
| 669 | onnx.save(optimized, output_path) |
| 670 | print(" Optimization complete") |
| 671 | except ImportError: |
| 672 | # onnxoptimizer may not be installed, skip |
| 673 | pass |
| 674 | except Exception as e: |
| 675 | print(f" ⚠️ Optimization failed: {e}") |
| 676 | |
| 677 | size_mb = os.path.getsize(output_path) / 1024**2 |
| 678 | print(f"\n✅ ONNX model saved to {output_path} ({size_mb:.0f} MB)") |
| 679 | return output_path |
| 680 | |
| 681 | |
| 682 | # ═══════════════════════════════════════════════════════════════ |
| 683 | # Checkpoint Management |
| 684 | # ═══════════════════════════════════════════════════════════════ |
| 685 | |
| 686 | CHECKPOINT_VERSION = 1 |
| 687 | |
| 688 | |
| 689 | class TrainingCheckpoint: |
| 690 | """Manages saving and loading training state for resume capability. |
| 691 | |
| 692 | Checkpoint format (saved as directory): |
| 693 | checkpoint_dir/ |
| 694 | checkpoint.json — metadata and training state |
| 695 | model.safetensors — model weights (or adapter weights) |
| 696 | optimizer.pt — optimizer state (if available) |
| 697 | scheduler.pt — LR scheduler state (if available) |
| 698 | training_state.json — step, epoch, loss history, best metrics |
| 699 | """ |
| 700 | |
| 701 | def __init__(self, checkpoint_dir: str): |
| 702 | self.checkpoint_dir = Path(checkpoint_dir) |
| 703 | self.checkpoint_dir.mkdir(parents=True, exist_ok=True) |
| 704 | |
| 705 | def save( |
| 706 | self, |
| 707 | *, |
| 708 | step: int = 0, |
| 709 | epoch: int = 0, |
| 710 | loss: float = 0.0, |
| 711 | best_loss: float = float("inf"), |
| 712 | best_step: int = 0, |
| 713 | loss_history: Optional[List[float]] = None, |
| 714 | model_path: Optional[str] = None, |
| 715 | model_weights: Optional[Dict[str, np.ndarray]] = None, |
| 716 | optimizer_state: Optional[Dict] = None, |
| 717 | scheduler_state: Optional[Dict] = None, |
| 718 | config: Optional[Dict] = None, |
| 719 | metadata: Optional[Dict] = None, |
| 720 | ) -> str: |
| 721 | """Save a training checkpoint. |
| 722 | |
| 723 | Args: |
| 724 | step: Current training step |
| 725 | epoch: Current epoch |
| 726 | loss: Current loss value |
| 727 | best_loss: Best validation loss seen so far |
| 728 | best_step: Step at which best loss was achieved |
| 729 | loss_history: List of loss values over steps |
| 730 | model_path: Path to save model weights checkpoint |
| 731 | model_weights: Dict of numpy arrays (model weights) |
| 732 | optimizer_state: Optimizer state dict |
| 733 | scheduler_state: Scheduler state dict |
| 734 | config: Training configuration |
| 735 | metadata: Additional metadata |
| 736 | |
| 737 | Returns: |
| 738 | Path to the checkpoint JSON file. |
| 739 | """ |
| 740 | # Save training state as JSON |
| 741 | training_state = { |
| 742 | "checkpoint_version": CHECKPOINT_VERSION, |
| 743 | "step": step, |
| 744 | "epoch": epoch, |
| 745 | "loss": loss, |
| 746 | "best_loss": best_loss, |
| 747 | "best_step": best_step, |
| 748 | "loss_history": loss_history or [], |
| 749 | "timestamp": time.time(), |
| 750 | "config": config or {}, |
| 751 | "metadata": metadata or {}, |
| 752 | } |
| 753 | |
| 754 | state_path = self.checkpoint_dir / "training_state.json" |
| 755 | with open(state_path, "w") as f: |
| 756 | json.dump(training_state, f, indent=2, default=str) |
| 757 | |
| 758 | # Save optimizer state if provided |
| 759 | if optimizer_state is not None: |
| 760 | try: |
| 761 | import torch |
| 762 | opt_path = self.checkpoint_dir / "optimizer.pt" |
| 763 | torch.save(optimizer_state, opt_path) |
| 764 | except Exception as e: |
| 765 | print(f" ⚠️ Failed to save optimizer state: {e}") |
| 766 | |
| 767 | # Save scheduler state if provided |
| 768 | if scheduler_state is not None: |
| 769 | try: |
| 770 | import torch |
| 771 | sched_path = self.checkpoint_dir / "scheduler.pt" |
| 772 | torch.save(scheduler_state, sched_path) |
| 773 | except Exception as e: |
| 774 | print(f" ⚠️ Failed to save scheduler state: {e}") |
| 775 | |
| 776 | # Save model weights if provided (as safetensors shard) |
| 777 | if model_weights: |
| 778 | try: |
| 779 | from safetensors.torch import save_file as st_save |
| 780 | import torch |
| 781 | torch_weights = { |
| 782 | k: torch.from_numpy(v) if isinstance(v, np.ndarray) else v |
| 783 | for k, v in model_weights.items() |
| 784 | } |
| 785 | weights_path = self.checkpoint_dir / "model.safetensors" |
| 786 | st_save(torch_weights, str(weights_path)) |
| 787 | training_state["model_weights"] = str(weights_path) |
| 788 | except Exception as e: |
| 789 | print(f" ⚠️ Failed to save model weights: {e}") |
| 790 | |
| 791 | # Copy model file if path provided |
| 792 | if model_path and os.path.exists(model_path): |
| 793 | try: |
| 794 | dst = self.checkpoint_dir / os.path.basename(model_path) |
| 795 | shutil.copy2(model_path, dst) |
| 796 | training_state["model_file"] = str(dst) |
| 797 | except Exception as e: |
| 798 | print(f" ⚠️ Failed to copy model file: {e}") |
| 799 | |
| 800 | # Write checkpoint JSON |
| 801 | checkpoint_data = { |
| 802 | "checkpoint_version": CHECKPOINT_VERSION, |
| 803 | "created_at": time.time(), |
| 804 | "step": step, |
| 805 | "epoch": epoch, |
| 806 | "loss": loss, |
| 807 | "best_loss": best_loss, |
| 808 | "best_step": best_step, |
| 809 | "model_file": str(self.checkpoint_dir / "model.safetensors") if model_weights else "", |
| 810 | "training_state": str(state_path), |
| 811 | "config": config or {}, |
| 812 | "metadata": metadata or {}, |
| 813 | } |
| 814 | |
| 815 | ckpt_path = self.checkpoint_dir / "checkpoint.json" |
| 816 | with open(ckpt_path, "w") as f: |
| 817 | json.dump(checkpoint_data, f, indent=2, default=str) |
| 818 | |
| 819 | print(f" Checkpoint saved at step {step}") |
| 820 | print(f" Loss: {loss:.4f}, Best: {best_loss:.4f}") |
| 821 | return str(ckpt_path) |
| 822 | |
| 823 | def load(self) -> Optional[Dict[str, Any]]: |
| 824 | """Load a training checkpoint. |
| 825 | |
| 826 | Returns: |
| 827 | Dict with training state, or None if checkpoint doesn't exist. |
| 828 | """ |
| 829 | ckpt_path = self.checkpoint_dir / "checkpoint.json" |
| 830 | if not ckpt_path.exists(): |
| 831 | return None |
| 832 | |
| 833 | with open(ckpt_path) as f: |
| 834 | checkpoint_data = json.load(f) |
| 835 | |
| 836 | # Load training state |
| 837 | state_path = self.checkpoint_dir / "training_state.json" |
| 838 | if state_path.exists(): |
| 839 | with open(state_path) as f: |
| 840 | training_state = json.load(f) |
| 841 | checkpoint_data.update(training_state) |
| 842 | |
| 843 | return checkpoint_data |
| 844 | |
| 845 | def load_optimizer(self) -> Optional[Dict]: |
| 846 | """Load saved optimizer state.""" |
| 847 | opt_path = self.checkpoint_dir / "optimizer.pt" |
| 848 | if opt_path.exists(): |
| 849 | try: |
| 850 | import torch |
| 851 | return torch.load(opt_path) |
| 852 | except Exception: |
| 853 | pass |
| 854 | return None |
| 855 | |
| 856 | def load_scheduler(self) -> Optional[Dict]: |
| 857 | """Load saved scheduler state.""" |
| 858 | sched_path = self.checkpoint_dir / "scheduler.pt" |
| 859 | if sched_path.exists(): |
| 860 | try: |
| 861 | import torch |
| 862 | return torch.load(sched_path) |
| 863 | except Exception: |
| 864 | pass |
| 865 | return None |
| 866 | |
| 867 | @staticmethod |
| 868 | def list_checkpoints(base_dir: str) -> List[Dict[str, Any]]: |
| 869 | """List all available checkpoints in a directory.""" |
| 870 | checkpoints = [] |
| 871 | base = Path(base_dir) |
| 872 | for ckpt_dir in sorted(base.glob("checkpoint_*")): |
| 873 | ckpt_file = ckpt_dir / "checkpoint.json" |
| 874 | if ckpt_file.exists(): |
| 875 | try: |
| 876 | with open(ckpt_file) as f: |
| 877 | data = json.load(f) |
| 878 | data["path"] = str(ckpt_dir) |
| 879 | data["name"] = ckpt_dir.name |
| 880 | checkpoints.append(data) |
| 881 | except Exception: |
| 882 | checkpoints.append({ |
| 883 | "path": str(ckpt_dir), |
| 884 | "name": ckpt_dir.name, |
| 885 | "error": "corrupted", |
| 886 | }) |
| 887 | return checkpoints |
| 888 | |
| 889 | @staticmethod |
| 890 | def get_best_checkpoint(base_dir: str) -> Optional[Dict[str, Any]]: |
| 891 | """Find the checkpoint with the best (lowest) loss.""" |
| 892 | checkpoints = TrainingCheckpoint.list_checkpoints(base_dir) |
| 893 | if not checkpoints: |
| 894 | return None |
| 895 | valid = [c for c in checkpoints if "loss" in c and "error" not in c] |
| 896 | if not valid: |
| 897 | return None |
| 898 | best = min(valid, key=lambda c: c.get("loss", float("inf"))) |
| 899 | return best |
| 900 | |
| 901 | |
| 902 | def save_best_model( |
| 903 | current_loss: float, |
| 904 | current_step: int, |
| 905 | model_path: str, |
| 906 | checkpoint_dir: str, |
| 907 | *, |
| 908 | lower_is_better: bool = True, |
| 909 | metadata: Optional[Dict] = None, |
| 910 | ) -> Tuple[bool, Optional[str]]: |
| 911 | """Save model as best checkpoint if loss improves. |
| 912 | |
| 913 | Args: |
| 914 | current_loss: Current validation loss |
| 915 | current_step: Current training step |
| 916 | model_path: Path to current model weights |
| 917 | checkpoint_dir: Directory to save best model |
| 918 | lower_is_better: If True, lower loss is better |
| 919 | metadata: Additional metadata |
| 920 | |
| 921 | Returns: |
| 922 | (saved, path) tuple — saved is True if best model was saved. |
| 923 | """ |
| 924 | os.makedirs(checkpoint_dir, exist_ok=True) |
| 925 | best_record_path = os.path.join(checkpoint_dir, "best_model.json") |
| 926 | |
| 927 | # Load previous best loss |
| 928 | best_loss = float("inf") |
| 929 | best_step = 0 |
| 930 | if os.path.exists(best_record_path): |
| 931 | try: |
| 932 | with open(best_record_path) as f: |
| 933 | record = json.load(f) |
| 934 | best_loss = record.get("loss", float("inf")) |
| 935 | best_step = record.get("step", 0) |
| 936 | except Exception: |
| 937 | pass |
| 938 | |
| 939 | # Check if current is better |
| 940 | is_better = current_loss < best_loss if lower_is_better else current_loss > best_loss |
| 941 | if not is_better: |
| 942 | return False, None |
| 943 | |
| 944 | # Save best model |
| 945 | best_model_path = os.path.join(checkpoint_dir, f"best_model_step_{current_step}.gguf") |
| 946 | if os.path.exists(model_path): |
| 947 | shutil.copy2(model_path, best_model_path) |
| 948 | |
| 949 | # Also save as 'best_model.gguf' for easy loading |
| 950 | latest_best = os.path.join(checkpoint_dir, "best_model.gguf") |
| 951 | if os.path.exists(model_path): |
| 952 | shutil.copy2(model_path, latest_best) |
| 953 | |
| 954 | # Update best record |
| 955 | best_record = { |
| 956 | "loss": current_loss, |
| 957 | "step": current_step, |
| 958 | "model_path": best_model_path, |
| 959 | "timestamp": time.time(), |
| 960 | "metadata": metadata or {}, |
| 961 | } |
| 962 | with open(best_record_path, "w") as f: |
| 963 | json.dump(best_record, f, indent=2) |
| 964 | |
| 965 | print(f"\n🏆 Best model updated! Loss: {current_loss:.4f} (was {best_loss:.4f})") |
| 966 | print(f" Saved to {best_model_path}") |
| 967 | return True, best_model_path |
| 968 | |
| 969 | |
| 970 | # ═══════════════════════════════════════════════════════════════ |
| 971 | # CLI Commands |
| 972 | # ═══════════════════════════════════════════════════════════════ |
| 973 | |
| 974 | def cmd_hub_login(args): |
| 975 | """Login to HuggingFace Hub.""" |
| 976 | print("╔══════════════════════════════════════════════╗") |
| 977 | print("║ HuggingFace Hub — Login ║") |
| 978 | print("╚══════════════════════════════════════════════╝") |
| 979 | print() |
| 980 | |
| 981 | token = args.token or "" |
| 982 | hub_login(token=token) |
| 983 | |
| 984 | |
| 985 | def cmd_hub_whoami(args): |
| 986 | """Show current HuggingFace user info.""" |
| 987 | user = hub_whoami() |
| 988 | if user: |
| 989 | print(f"User: {user.get('name', 'unknown')}") |
| 990 | print(f"Email: {user.get('email', 'unknown')}") |
| 991 | print(f"ID: {user.get('id', 'unknown')}") |
| 992 | else: |
| 993 | print("❌ Not logged in to HuggingFace Hub") |
| 994 | |
| 995 | |
| 996 | def cmd_hub_push(args): |
| 997 | """Push a model to HuggingFace Hub.""" |
| 998 | print("╔══════════════════════════════════════════════╗") |
| 999 | print("║ HuggingFace Hub — Push Model ║") |
| 1000 | print("╚══════════════════════════════════════════════╝") |
| 1001 | print() |
| 1002 | |
| 1003 | model_path = args.model or input("Model path: ").strip() |
| 1004 | repo_id = args.repo or input("HF repo ID (e.g. username/model): ").strip() |
| 1005 | |
| 1006 | if not os.path.exists(model_path): |
| 1007 | print(f"❌ Model not found: {model_path}") |
| 1008 | return |
| 1009 | |
| 1010 | # Collect metadata |
| 1011 | metadata = {} |
| 1012 | if args.quant: |
| 1013 | metadata["quantization"] = args.quant |
| 1014 | if args.params: |
| 1015 | metadata["parameters"] = args.params |
| 1016 | if args.description: |
| 1017 | metadata["description"] = args.description |
| 1018 | metadata["studio_version"] = STUDIO_VERSION |
| 1019 | |
| 1020 | # Basic model info from filename |
| 1021 | model_name = os.path.basename(model_path) |
| 1022 | metadata["model_name"] = model_name |
| 1023 | |
| 1024 | result = hub_push_model( |
| 1025 | model_path=model_path, |
| 1026 | repo_id=repo_id, |
| 1027 | private=args.private, |
| 1028 | commit_message=args.message or f"Upload {model_name} via MojoLlama Studio", |
| 1029 | metadata=metadata, |
| 1030 | ) |
| 1031 | |
| 1032 | if result: |
| 1033 | print(f"\n✅ Model available at: {result}") |
| 1034 | |
| 1035 | |
| 1036 | def cmd_hub_push_adapter(args): |
| 1037 | """Push a LoRA adapter to HuggingFace Hub.""" |
| 1038 | print("╔══════════════════════════════════════════════╗") |
| 1039 | print("║ HuggingFace Hub — Push Adapter ║") |
| 1040 | print("╚══════════════════════════════════════════════╝") |
| 1041 | print() |
| 1042 | |
| 1043 | adapter_path = args.adapter or input("Adapter path: ").strip() |
| 1044 | base_model = args.base_model or input("Base model name: ").strip() |
| 1045 | repo_id = args.repo or input("HF repo ID (e.g. username/adapter-name): ").strip() |
| 1046 | |
| 1047 | if not os.path.exists(adapter_path): |
| 1048 | print(f"❌ Adapter not found: {adapter_path}") |
| 1049 | return |
| 1050 | |
| 1051 | metadata = {"base_model": base_model} |
| 1052 | if args.rank: |
| 1053 | metadata["lora_rank"] = args.rank |
| 1054 | if args.alpha: |
| 1055 | metadata["lora_alpha"] = args.alpha |
| 1056 | |
| 1057 | result = hub_push_adapter( |
| 1058 | adapter_path=adapter_path, |
| 1059 | base_model=base_model, |
| 1060 | repo_id=repo_id, |
| 1061 | private=args.private, |
| 1062 | metadata=metadata, |
| 1063 | ) |
| 1064 | |
| 1065 | if result: |
| 1066 | print(f"\n✅ Adapter available at: {result}") |
| 1067 | |
| 1068 | |
| 1069 | def cmd_export_safetensors(args): |
| 1070 | """Convert GGUF model to safetensors format.""" |
| 1071 | from mojollama.exporter import gguf_to_safetensors |
| 1072 | |
| 1073 | print("╔══════════════════════════════════════════════╗") |
| 1074 | print("║ GGUF → Safetensors Converter ║") |
| 1075 | print("╚══════════════════════════════════════════════╝") |
| 1076 | print() |
| 1077 | |
| 1078 | gguf_path = args.model or input("GGUF model path: ").strip() |
| 1079 | output_dir = args.output or gguf_path.replace(".gguf", "-safetensors") |
| 1080 | dtype = args.dtype or "float16" |
| 1081 | shard_size = args.shard_size or "2GB" |
| 1082 | |
| 1083 | result = gguf_to_safetensors( |
| 1084 | gguf_path=gguf_path, |
| 1085 | output_dir=output_dir, |
| 1086 | dtype=dtype, |
| 1087 | shard_size=shard_size, |
| 1088 | ) |
| 1089 | |
| 1090 | if result: |
| 1091 | print(f"\n✅ Safetensors saved to: {result}") |
| 1092 | |
| 1093 | |
| 1094 | def cmd_export_onnx(args): |
| 1095 | """Convert GGUF model to ONNX format.""" |
| 1096 | from mojollama.exporter import gguf_to_onnx |
| 1097 | |
| 1098 | print("╔══════════════════════════════════════════════╗") |
| 1099 | print("║ GGUF → ONNX Converter ║") |
| 1100 | print("╚══════════════════════════════════════════════╝") |
| 1101 | print() |
| 1102 | |
| 1103 | gguf_path = args.model or input("GGUF model path: ").strip() |
| 1104 | output_path = args.output or gguf_path.replace(".gguf", ".onnx") |
| 1105 | opset = args.opset or 17 |
| 1106 | max_seq_len = args.max_seq_len or 2048 |
| 1107 | |
| 1108 | result = gguf_to_onnx( |
| 1109 | gguf_path=gguf_path, |
| 1110 | output_path=output_path, |
| 1111 | opset=opset, |
| 1112 | max_seq_len=max_seq_len, |
| 1113 | ) |
| 1114 | |
| 1115 | if result: |
| 1116 | print(f"\n✅ ONNX model saved to: {result}") |
| 1117 | |
| 1118 | |
| 1119 | def cmd_checkpoint_save(args): |
| 1120 | """Save a training checkpoint.""" |
| 1121 | print("╔══════════════════════════════════════════════╗") |
| 1122 | print("║ Save Training Checkpoint ║") |
| 1123 | print("╚══════════════════════════════════════════════╝") |
| 1124 | print() |
| 1125 | |
| 1126 | ckpt_dir = args.checkpoint_dir or "checkpoints" |
| 1127 | step = args.step or 0 |
| 1128 | epoch = args.epoch or 0 |
| 1129 | loss = args.loss or 0.0 |
| 1130 | |
| 1131 | ckpt = TrainingCheckpoint(ckpt_dir) |
| 1132 | result = ckpt.save( |
| 1133 | step=step, |
| 1134 | epoch=epoch, |
| 1135 | loss=loss, |
| 1136 | model_path=args.model or None, |
| 1137 | config={"learning_rate": args.lr} if args.lr else None, |
| 1138 | ) |
| 1139 | if result: |
| 1140 | print(f"\n✅ Checkpoint saved to: {result}") |
| 1141 | |
| 1142 | |
| 1143 | def cmd_checkpoint_load(args): |
| 1144 | """Load and display a training checkpoint.""" |
| 1145 | print("╔══════════════════════════════════════════════╗") |
| 1146 | print("║ Load Training Checkpoint ║") |
| 1147 | print("╚══════════════════════════════════════════════╝") |
| 1148 | print() |
| 1149 | |
| 1150 | ckpt_path = args.checkpoint_dir or "checkpoints" |
| 1151 | ckpt = TrainingCheckpoint(ckpt_path) |
| 1152 | data = ckpt.load() |
| 1153 | |
| 1154 | if data is None: |
| 1155 | print("❌ No checkpoint found") |
| 1156 | return |
| 1157 | |
| 1158 | print(f"Checkpoint: {ckpt_path}") |
| 1159 | print(f" Version: {data.get('checkpoint_version', '?')}") |
| 1160 | print(f" Step: {data.get('step', '?')}") |
| 1161 | print(f" Epoch: {data.get('epoch', '?')}") |
| 1162 | print(f" Loss: {data.get('loss', '?')}") |
| 1163 | print(f" Best Loss: {data.get('best_loss', '?')}") |
| 1164 | print(f" Best Step: {data.get('best_step', '?')}") |
| 1165 | print(f" Created: {time.ctime(data.get('timestamp', 0))}") |
| 1166 | |
| 1167 | if data.get("config"): |
| 1168 | print(f"\n Config:") |
| 1169 | for k, v in data["config"].items(): |
| 1170 | print(f" {k}: {v}") |
| 1171 | |
| 1172 | loss_history = data.get("loss_history", []) |
| 1173 | if loss_history: |
| 1174 | print(f"\n Loss History: {len(loss_history)} entries") |
| 1175 | for i, l in enumerate(loss_history[-5:]): |
| 1176 | print(f" [{i+1}] step {i}: {l:.4f}") |
| 1177 | |
| 1178 | return data |
| 1179 | |
| 1180 | |
| 1181 | def cmd_checkpoint_list(args): |
| 1182 | """List all available checkpoints.""" |
| 1183 | print("╔══════════════════════════════════════════════╗") |
| 1184 | print("║ List Training Checkpoints ║") |
| 1185 | print("╚══════════════════════════════════════════════╝") |
| 1186 | print() |
| 1187 | |
| 1188 | base_dir = args.checkpoint_dir or "." |
| 1189 | checkpoints = TrainingCheckpoint.list_checkpoints(base_dir) |
| 1190 | |
| 1191 | if not checkpoints: |
| 1192 | print("No checkpoints found") |
| 1193 | return |
| 1194 | |
| 1195 | print(f"Found {len(checkpoints)} checkpoint(s) in {base_dir}:") |
| 1196 | print() |
| 1197 | for ckpt in checkpoints: |
| 1198 | name = ckpt.get("name", "?") |
| 1199 | loss = ckpt.get("loss", "?") |
| 1200 | step = ckpt.get("step", "?") |
| 1201 | epoch = ckpt.get("epoch", "?") |
| 1202 | created = time.ctime(ckpt.get("timestamp", 0)) if "timestamp" in ckpt else "?" |
| 1203 | status = "✅" if "error" not in ckpt else "❌" |
| 1204 | print(f" {status} {name}") |
| 1205 | print(f" Step: {step}, Epoch: {epoch}, Loss: {loss}") |
| 1206 | print(f" Created: {created}") |
| 1207 | print() |
| 1208 | |
| 1209 | return checkpoints |
| 1210 | |
| 1211 | |
| 1212 | # ═══════════════════════════════════════════════════════════════ |
| 1213 | # Main CLI |
| 1214 | # ═══════════════════════════════════════════════════════════════ |
| 1215 | |
| 1216 | def main(): |
| 1217 | parser = argparse.ArgumentParser(description="MojoLlama Exporter & Checkpoint Tools") |
| 1218 | sub = parser.add_subparsers(dest="command", help="Command") |
| 1219 | |
| 1220 | # hub login |
| 1221 | p_login = sub.add_parser("hub-login", help="Login to HuggingFace Hub") |
| 1222 | p_login.add_argument("--token", help="HF API token") |
| 1223 | |
| 1224 | # hub whoami |
| 1225 | sub.add_parser("hub-whoami", help="Show HuggingFace user info") |
| 1226 | |
| 1227 | # hub push |
| 1228 | p_push = sub.add_parser("hub-push", help="Push model to HuggingFace Hub") |
| 1229 | p_push.add_argument("--model", "-m", help="Model path") |
| 1230 | p_push.add_argument("--repo", help="HF repo ID") |
| 1231 | p_push.add_argument("--message", help="Commit message") |
| 1232 | p_push.add_argument("--private", action="store_true", help="Create private repo") |
| 1233 | p_push.add_argument("--quant", help="Quantization type (metadata)") |
| 1234 | p_push.add_argument("--params", help="Parameter count (metadata)") |
| 1235 | p_push.add_argument("--description", help="Model description") |
| 1236 | |
| 1237 | # hub push-adapter |
| 1238 | p_push_adapter = sub.add_parser("hub-push-adapter", help="Push LoRA adapter to HF Hub") |
| 1239 | p_push_adapter.add_argument("--adapter", help="Adapter GGUF path") |
| 1240 | p_push_adapter.add_argument("--base-model", help="Base model name") |
| 1241 | p_push_adapter.add_argument("--repo", help="HF repo ID") |
| 1242 | p_push_adapter.add_argument("--private", action="store_true") |
| 1243 | p_push_adapter.add_argument("--rank", type=int, help="LoRA rank") |
| 1244 | p_push_adapter.add_argument("--alpha", type=float, help="LoRA alpha") |
| 1245 | |
| 1246 | # export safetensors |
| 1247 | p_st = sub.add_parser("export-safetensors", help="Convert GGUF to safetensors") |
| 1248 | p_st.add_argument("--model", "-m", help="GGUF model path") |
| 1249 | p_st.add_argument("--output", "-o", help="Output directory") |
| 1250 | p_st.add_argument("--dtype", default="float16", choices=["float16", "float32", "bfloat16"]) |
| 1251 | p_st.add_argument("--shard-size", default="2GB", help="Shard size (1GB, 2GB, 5GB, NO)") |
| 1252 | |
| 1253 | # export onnx |
| 1254 | p_onnx = sub.add_parser("export-onnx", help="Convert GGUF to ONNX") |
| 1255 | p_onnx.add_argument("--model", "-m", help="GGUF model path") |
| 1256 | p_onnx.add_argument("--output", "-o", help="Output path") |
| 1257 | p_onnx.add_argument("--opset", type=int, default=17, help="ONNX opset") |
| 1258 | p_onnx.add_argument("--max-seq-len", type=int, default=2048) |
| 1259 | |
| 1260 | # checkpoint save |
| 1261 | p_ckpt_save = sub.add_parser("checkpoint-save", help="Save training checkpoint") |
| 1262 | p_ckpt_save.add_argument("--checkpoint-dir", default="checkpoints") |
| 1263 | p_ckpt_save.add_argument("--model", help="Model file path") |
| 1264 | p_ckpt_save.add_argument("--step", type=int, default=0) |
| 1265 | p_ckpt_save.add_argument("--epoch", type=int, default=0) |
| 1266 | p_ckpt_save.add_argument("--loss", type=float, default=0.0) |
| 1267 | p_ckpt_save.add_argument("--lr", help="Learning rate") |
| 1268 | |
| 1269 | # checkpoint load |
| 1270 | p_ckpt_load = sub.add_parser("checkpoint-load", help="Load training checkpoint") |
| 1271 | p_ckpt_load.add_argument("--checkpoint-dir", default="checkpoints") |
| 1272 | |
| 1273 | # checkpoint list |
| 1274 | p_ckpt_list = sub.add_parser("checkpoint-list", help="List training checkpoints") |
| 1275 | p_ckpt_list.add_argument("--checkpoint-dir", default=".", help="Base directory") |
| 1276 | |
| 1277 | args = parser.parse_args() |
| 1278 | |
| 1279 | if not args.command: |
| 1280 | parser.print_help() |
| 1281 | return |
| 1282 | |
| 1283 | commands = { |
| 1284 | "hub-login": cmd_hub_login, |
| 1285 | "hub-whoami": cmd_hub_whoami, |
| 1286 | "hub-push": cmd_hub_push, |
| 1287 | "hub-push-adapter": cmd_hub_push_adapter, |
| 1288 | "export-safetensors": cmd_export_safetensors, |
| 1289 | "export-onnx": cmd_export_onnx, |
| 1290 | "checkpoint-save": cmd_checkpoint_save, |
| 1291 | "checkpoint-load": cmd_checkpoint_load, |
| 1292 | "checkpoint-list": cmd_checkpoint_list, |
| 1293 | } |
| 1294 | |
| 1295 | commands[args.command](args) |
| 1296 | |
| 1297 | |
| 1298 | if __name__ == "__main__": |
| 1299 | main() |