MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / trainer.py
| 1 | #!/usr/bin/env python3 |
| 2 | """ |
| 3 | MojoLlama Trainer — Multi-method fine-tuning engine. |
| 4 | |
| 5 | Supports QLoRA, DoRA, GaLore, GRPO, DPO, ORPO, KTO, SimPO. |
| 6 | Wraps llama.cpp finetune where possible; implements custom Python/numpy |
| 7 | training loops for advanced methods. |
| 8 | |
| 9 | Usage: |
| 10 | python3 -m mojollama.trainer --model model.gguf --data train.jsonl \\ |
| 11 | --method qlora --lora-rank 16 --lora-alpha 32 --lr 1e-4 |
| 12 | """ |
| 13 | |
| 14 | import os |
| 15 | import sys |
| 16 | import json |
| 17 | import time |
| 18 | import math |
| 19 | import struct |
| 20 | import tempfile |
| 21 | import argparse |
| 22 | import threading |
| 23 | import subprocess |
| 24 | import numpy as np |
| 25 | from pathlib import Path |
| 26 | from typing import Optional, Dict, List, Tuple, Callable |
| 27 | |
| 28 | try: |
| 29 | from gguf import GGUFReader, GGUFWriter, GGMLQuantizationType, GGUFValueType |
| 30 | from gguf import dequantize, quantize |
| 31 | HAS_GGUF = True |
| 32 | except ImportError: |
| 33 | HAS_GGUF = False |
| 34 | GGUFReader = None |
| 35 | GGUFWriter = None |
| 36 | GGMLQuantizationType = None |
| 37 | GGUFValueType = None |
| 38 | |
| 39 | # --------------------------------------------------------------------------- |
| 40 | # Constants |
| 41 | # --------------------------------------------------------------------------- |
| 42 | |
| 43 | LLAMA_CPP_DIR = "/tmp/llama.cpp" |
| 44 | FINETUNE_BIN = f"{LLAMA_CPP_DIR}/build/bin/llama-finetune" |
| 45 | SERVER_BIN = f"{LLAMA_CPP_DIR}/build/bin/llama-server" |
| 46 | TRAINER_VERSION = "0.2.0" |
| 47 | |
| 48 | # NF4 quantization levels (QLoRA NormalFloat4) |
| 49 | NF4_LEVELS = np.array([ |
| 50 | -1.0, -0.6961928009986877, -0.5250730514526367, -0.39491748809814453, |
| 51 | -0.28444138169288635, -0.18477343022823334, -0.09105003625154495, 0.0, |
| 52 | 0.07958029955625534, 0.16093020141124725, 0.24611230194568634, |
| 53 | 0.33791524171829224, 0.44070982933044434, 0.5626170039176941, |
| 54 | 0.7229568362236023, 1.0 |
| 55 | ], dtype=np.float32) |
| 56 | |
| 57 | # Loss metric queues for live streaming (same pattern as server.py) |
| 58 | _training_queues = [] |
| 59 | _training_queues_lock = threading.Lock() |
| 60 | |
| 61 | |
| 62 | def emit_metric(metrics: dict): |
| 63 | """Push a metric dict to all subscribed SSE listeners.""" |
| 64 | with _training_queues_lock: |
| 65 | dead = [] |
| 66 | for q in _training_queues: |
| 67 | try: |
| 68 | q.put_nowait(metrics) |
| 69 | except Exception: |
| 70 | dead.append(q) |
| 71 | for q in dead: |
| 72 | _training_queues.remove(q) |
| 73 | |
| 74 | |
| 75 | def subscribe_metrics(queue): |
| 76 | """Subscribe a queue for live training metrics.""" |
| 77 | with _training_queues_lock: |
| 78 | _training_queues.append(queue) |
| 79 | |
| 80 | |
| 81 | def unsubscribe_metrics(queue): |
| 82 | """Unsubscribe a metrics queue.""" |
| 83 | with _training_queues_lock: |
| 84 | if queue in _training_queues: |
| 85 | _training_queues.remove(queue) |
| 86 | |
| 87 | |
| 88 | # --------------------------------------------------------------------------- |
| 89 | # Dataset loading |
| 90 | # --------------------------------------------------------------------------- |
| 91 | |
| 92 | def load_dataset(path: str, format: str = "auto", max_samples: int = 0 |
| 93 | ) -> List[Dict]: |
| 94 | """ |
| 95 | Load training data. |
| 96 | Supports: alpaca (JSON), sharegpt (JSON), jsonl with prompt/completion, |
| 97 | plain text (one example per block separated by blank lines) |
| 98 | """ |
| 99 | if not os.path.exists(path): |
| 100 | raise FileNotFoundError(f"Dataset not found: {path}") |
| 101 | |
| 102 | samples = [] |
| 103 | |
| 104 | if path.endswith(".jsonl"): |
| 105 | with open(path) as f: |
| 106 | for line in f: |
| 107 | line = line.strip() |
| 108 | if not line: |
| 109 | continue |
| 110 | samples.append(json.loads(line)) |
| 111 | elif path.endswith(".json"): |
| 112 | if format == "auto": |
| 113 | format = _detect_json_format(path) |
| 114 | with open(path) as f: |
| 115 | data = json.load(f) |
| 116 | if isinstance(data, list): |
| 117 | samples = data |
| 118 | elif isinstance(data, dict): |
| 119 | # Alpaca format |
| 120 | if "instruction" in data: |
| 121 | samples = [data] |
| 122 | else: |
| 123 | # Try to find a list |
| 124 | for key in ["data", "samples", "conversations", "items"]: |
| 125 | if key in data and isinstance(data[key], list): |
| 126 | samples = data[key] |
| 127 | break |
| 128 | else: |
| 129 | samples = [data] |
| 130 | else: |
| 131 | # Plain text — one training example per paragraph |
| 132 | with open(path) as f: |
| 133 | text = f.read() |
| 134 | paragraphs = [p.strip() for p in text.split("\n\n") if p.strip()] |
| 135 | for p in paragraphs[:max_samples or len(paragraphs)]: |
| 136 | samples.append({"text": p}) |
| 137 | |
| 138 | if max_samples > 0: |
| 139 | samples = samples[:max_samples] |
| 140 | |
| 141 | return samples |
| 142 | |
| 143 | |
| 144 | def _detect_json_format(path: str) -> str: |
| 145 | """Detect if JSON is Alpaca or ShareGPT format.""" |
| 146 | with open(path) as f: |
| 147 | data = json.load(f) |
| 148 | if isinstance(data, list) and len(data) > 0: |
| 149 | keys = data[0].keys() |
| 150 | if "instruction" in keys: |
| 151 | return "alpaca" |
| 152 | if "conversations" in keys or "messages" in keys: |
| 153 | return "sharegpt" |
| 154 | if "prompt" in keys and "completion" in keys: |
| 155 | return "alpaca" |
| 156 | return "alpaca" |
| 157 | |
| 158 | |
| 159 | def format_sample(sample: Dict, template: str = "alpaca") -> str: |
| 160 | """ |
| 161 | Format a training sample into a text string. |
| 162 | Alpaca: instruction + input + output |
| 163 | ShareGPT: messages with roles |
| 164 | """ |
| 165 | if template == "alpaca": |
| 166 | inst = sample.get("instruction", sample.get("prompt", "")) |
| 167 | inp = sample.get("input", "") |
| 168 | out = sample.get("output", sample.get("completion", "")) |
| 169 | if inp: |
| 170 | text = f"Instruction: {inst}\nInput: {inp}\nResponse: {out}" |
| 171 | else: |
| 172 | text = f"Instruction: {inst}\nResponse: {out}" |
| 173 | return text |
| 174 | elif template == "sharegpt": |
| 175 | messages = sample.get("conversations", sample.get("messages", [])) |
| 176 | parts = [] |
| 177 | for msg in messages: |
| 178 | role = msg.get("from", msg.get("role", "user")) |
| 179 | content = msg.get("value", msg.get("content", "")) |
| 180 | parts.append(f"{role}: {content}") |
| 181 | return "\n".join(parts) |
| 182 | elif template == "preference": |
| 183 | # DPO/DPO-style: chosen and rejected |
| 184 | chosen = sample.get("chosen", "") |
| 185 | rejected = sample.get("rejected", "") |
| 186 | prompt = sample.get("prompt", "") |
| 187 | return json.dumps({"prompt": prompt, "chosen": chosen, "rejected": rejected}) |
| 188 | else: |
| 189 | return sample.get("text", json.dumps(sample)) |
| 190 | |
| 191 | |
| 192 | # --------------------------------------------------------------------------- |
| 193 | # GGUF reading utilities |
| 194 | # --------------------------------------------------------------------------- |
| 195 | |
| 196 | def read_gguf_tensors(path: str): |
| 197 | """Read all tensors from a GGUF file.""" |
| 198 | if not HAS_GGUF: |
| 199 | raise ImportError("gguf library not available") |
| 200 | reader = GGUFReader(path) |
| 201 | return reader |
| 202 | |
| 203 | |
| 204 | def get_model_info(path: str) -> Dict: |
| 205 | """Extract model architecture info from GGUF metadata.""" |
| 206 | if not HAS_GGUF: |
| 207 | return {"error": "gguf library not available"} |
| 208 | reader = GGUFReader(path) |
| 209 | info = {} |
| 210 | for name, field in reader.fields.items(): |
| 211 | if field.types[-1] == GGUFValueType.STRING: |
| 212 | val = bytes(np.asarray(field.parts[-1])).decode("utf-8").strip("\x00") |
| 213 | info[name] = val |
| 214 | elif field.types[-1] in (GGUFValueType.UINT32, GGUFValueType.INT32): |
| 215 | info[name] = int(np.asarray(field.parts[-1]).item()) |
| 216 | return info |
| 217 | |
| 218 | |
| 219 | def get_tensor_names(path: str): |
| 220 | """Get list of tensor names from a GGUF file.""" |
| 221 | if not HAS_GGUF: |
| 222 | return [] |
| 223 | reader = GGUFReader(path) |
| 224 | return [t.name for t in reader.tensors] |
| 225 | |
| 226 | |
| 227 | def find_lora_targets(tensor_names: List[str]) -> List[str]: |
| 228 | """Determine which tensors should be LoRA-trained based on naming.""" |
| 229 | # Standard Llama/Mistral/Qwen architecture patterns |
| 230 | targets = [] |
| 231 | for name in tensor_names: |
| 232 | # Target attention projection and FFN weights (not embeddings/norms) |
| 233 | if any(k in name for k in [ |
| 234 | "blk.", ".attn_q.", ".attn_k.", ".attn_v.", |
| 235 | ".attn_output.", ".ffn_gate.", ".ffn_up.", ".ffn_down", |
| 236 | ".attn_qkv", # fused QKV |
| 237 | "attention.wq", "attention.wk", "attention.wv", |
| 238 | "attention.wo", "feed_forward.w1", "feed_forward.w2", |
| 239 | "feed_forward.w3", |
| 240 | ]): |
| 241 | if ".wte" not in name and ".norm" not in name: |
| 242 | targets.append(name) |
| 243 | return targets |
| 244 | |
| 245 | |
| 246 | # --------------------------------------------------------------------------- |
| 247 | # NF4 Utilities for QLoRA |
| 248 | # --------------------------------------------------------------------------- |
| 249 | |
| 250 | def nf4_quantize_block(block: np.ndarray) -> Tuple[np.ndarray, float]: |
| 251 | """ |
| 252 | Quantize a block of float32 values to NF4. |
| 253 | Returns (packed_nibbles, absmax). |
| 254 | Block size: 64 elements → 32 bytes packed. |
| 255 | """ |
| 256 | absmax = np.max(np.abs(block)) |
| 257 | if absmax < 1e-12: |
| 258 | return np.zeros(32, dtype=np.uint8), absmax |
| 259 | |
| 260 | # Normalize to [-1, 1] |
| 261 | normalized = block / absmax |
| 262 | |
| 263 | # Find closest NF4 level for each element |
| 264 | indices = np.argmin(np.abs(normalized[:, None] - NF4_LEVELS[None, :]), axis=1) |
| 265 | |
| 266 | # Pack 2×4-bit per byte |
| 267 | packed = np.zeros(32, dtype=np.uint8) |
| 268 | for i in range(32): |
| 269 | packed[i] = indices[i] | (indices[i + 32] << 4) |
| 270 | |
| 271 | return packed, absmax |
| 272 | |
| 273 | |
| 274 | def nf4_dequantize_block(packed: np.ndarray, absmax: float) -> np.ndarray: |
| 275 | """ |
| 276 | Dequantize a packed NF4 block back to float32. |
| 277 | 32 bytes → 64 float32 values. |
| 278 | """ |
| 279 | lo = (packed & 0x0F).astype(np.int32) |
| 280 | hi = ((packed >> 4) & 0x0F).astype(np.int32) |
| 281 | indices = np.zeros(64, dtype=np.int32) |
| 282 | indices[:32] = lo |
| 283 | indices[32:] = hi |
| 284 | return NF4_LEVELS[indices] * absmax |
| 285 | |
| 286 | |
| 287 | def load_nf4_model(path: str): |
| 288 | """ |
| 289 | Load a model in NF4 format for QLoRA training. |
| 290 | Returns: dict of {tensor_name: {"nf4_data": ..., "absmax": ..., "shape": ...}} |
| 291 | """ |
| 292 | if not HAS_GGUF: |
| 293 | raise ImportError("gguf library not available") |
| 294 | reader = GGUFReader(path) |
| 295 | nf4_tensors = {} |
| 296 | for t in reader.tensors: |
| 297 | data = np.asarray(t.data) |
| 298 | # If already NF4-packed (GGML_TYPE_NF4 = 29) |
| 299 | if t.tensor_type == 29: |
| 300 | # 64 elements per block, 32 bytes per block + 4 bytes absmax |
| 301 | flat = data.flatten() |
| 302 | n_blocks = len(flat) // 36 |
| 303 | blocks = [] |
| 304 | absmaxes = [] |
| 305 | # Reconstruct: each block is (32 packed bytes + 4 byte float32 absmax) |
| 306 | for bi in range(n_blocks): |
| 307 | byte_start = bi * 36 |
| 308 | packed = flat[byte_start:byte_start + 32].astype(np.uint8) |
| 309 | absmax_bytes = flat[byte_start + 32:byte_start + 36].tobytes() |
| 310 | absmax = struct.unpack("f", absmax_bytes)[0] |
| 311 | blocks.append(nf4_dequantize_block(packed, absmax)) |
| 312 | absmaxes.append(absmax) |
| 313 | dequantized = np.concatenate(blocks).reshape(t.shape) |
| 314 | else: |
| 315 | # Dequantize via gguf library |
| 316 | dequantized = dequantize(data, t.tensor_type) |
| 317 | nf4_tensors[t.name] = { |
| 318 | "data": dequantized.astype(np.float32), |
| 319 | "shape": list(t.shape), |
| 320 | "orig_type": t.tensor_type, |
| 321 | } |
| 322 | return nf4_tensors |
| 323 | |
| 324 | |
| 325 | # --------------------------------------------------------------------------- |
| 326 | # LoRA Adapter Utilities |
| 327 | # --------------------------------------------------------------------------- |
| 328 | |
| 329 | def save_lora_adapter(lora_weights: Dict, output_path: str, alpha: float, |
| 330 | base_model_path: str = ""): |
| 331 | """ |
| 332 | Save LoRA adapter weights as GGUF. |
| 333 | lora_weights: {base_tensor_name: {"a": np.array, "b": np.array}} |
| 334 | """ |
| 335 | if not HAS_GGUF: |
| 336 | raise ImportError("gguf library not available") |
| 337 | |
| 338 | # Get architecture name from base model if available |
| 339 | arch = "llama" |
| 340 | if base_model_path and os.path.exists(base_model_path): |
| 341 | info = get_model_info(base_model_path) |
| 342 | arch = info.get("general.architecture", "llama") |
| 343 | |
| 344 | writer = GGUFWriter(output_path, arch) |
| 345 | |
| 346 | # Add LoRA metadata |
| 347 | from gguf import Keys |
| 348 | writer.add_string(Keys.Adapter.LORA_ALPHA, str(alpha)) |
| 349 | writer.add_float32(Keys.Adapter.LORA_ALPHA, float(alpha)) |
| 350 | |
| 351 | # Write each tensor pair |
| 352 | for base_name, pair in lora_weights.items(): |
| 353 | if "a" in pair: |
| 354 | writer.add_tensor(f"{base_name}.lora_a", |
| 355 | pair["a"].astype(np.float32), |
| 356 | raw_dtype=GGMLQuantizationType.F32) |
| 357 | if "b" in pair: |
| 358 | writer.add_tensor(f"{base_name}.lora_b", |
| 359 | pair["b"].astype(np.float32), |
| 360 | raw_dtype=GGMLQuantizationType.F32) |
| 361 | |
| 362 | writer.write_header_to_file() |
| 363 | writer.write_kv_data_to_file() |
| 364 | writer.write_tensors_to_file(progress=False) |
| 365 | writer.close() |
| 366 | |
| 367 | |
| 368 | def load_lora_adapter(path: str) -> Dict: |
| 369 | """ |
| 370 | Load LoRA adapter weights from GGUF. |
| 371 | Returns: {base_name: {"a": np.array, "b": np.array}} |
| 372 | """ |
| 373 | reader = GGUFReader(path) |
| 374 | lora_map = {} |
| 375 | for t in reader.tensors: |
| 376 | name = t.name |
| 377 | data = np.asarray(t.data) |
| 378 | if name.endswith(".lora_a"): |
| 379 | base_name = name[:-7] |
| 380 | lora_map.setdefault(base_name, {})["a"] = data.astype(np.float32) |
| 381 | elif name.endswith(".lora_b"): |
| 382 | base_name = name[:-7] |
| 383 | lora_map.setdefault(base_name, {})["b"] = data.astype(np.float32) |
| 384 | return lora_map |
| 385 | |
| 386 | |
| 387 | # --------------------------------------------------------------------------- |
| 388 | # DoRA Utilities |
| 389 | # --------------------------------------------------------------------------- |
| 390 | |
| 391 | def dora_decompose(weight: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: |
| 392 | """ |
| 393 | DoRA decomposition: W = m * V / ||V|| |
| 394 | Returns: (magnitude_vector, direction_matrix) |
| 395 | """ |
| 396 | # weight shape: (out_dim, in_dim) |
| 397 | # Compute per-row norm |
| 398 | norm = np.linalg.norm(weight, axis=1, keepdims=True) |
| 399 | magnitude = norm.flatten() |
| 400 | direction = weight / (norm + 1e-12) |
| 401 | return magnitude, direction |
| 402 | |
| 403 | |
| 404 | def dora_recompose(magnitude: np.ndarray, direction: np.ndarray) -> np.ndarray: |
| 405 | """Recompose DoRA: W = m * V/||V||.""" |
| 406 | norm = np.linalg.norm(direction, axis=1, keepdims=True) |
| 407 | return magnitude[:, None] * (direction / (norm + 1e-12)) |
| 408 | |
| 409 | |
| 410 | # --------------------------------------------------------------------------- |
| 411 | # GaLore Utilities |
| 412 | # --------------------------------------------------------------------------- |
| 413 | |
| 414 | def galore_project_gradient(grad: np.ndarray, rank: int, |
| 415 | projection_matrix: Optional[np.ndarray] = None |
| 416 | ) -> Tuple[np.ndarray, np.ndarray]: |
| 417 | """ |
| 418 | Project gradient via SVD-based low-rank projection. |
| 419 | G_p = P * G * Q^T where P and Q are top-r singular vectors. |
| 420 | |
| 421 | Args: |
| 422 | grad: Gradient matrix of shape (m, n) |
| 423 | rank: Projection rank |
| 424 | projection_matrix: Optional pre-computed projection |
| 425 | |
| 426 | Returns: |
| 427 | (projected_grad, new_projection_matrix) |
| 428 | """ |
| 429 | if projection_matrix is not None: |
| 430 | # Use cached projection |
| 431 | u, s, vt = projection_matrix[0], projection_matrix[1], projection_matrix[2] |
| 432 | else: |
| 433 | # Compute SVD of gradient |
| 434 | u, s, vt = np.linalg.svd(grad, full_matrices=False) |
| 435 | projection_matrix = (u, s, vt) |
| 436 | |
| 437 | rank = min(rank, len(s)) |
| 438 | u_r = u[:, :rank] |
| 439 | vt_r = vt[:rank, :] |
| 440 | |
| 441 | # Project: G_p = U_r @ U_r^T @ G @ V_r^T @ V_r |
| 442 | # Simplified: G_p = U_r @ (U_r^T @ G @ V_r^T) @ V_r |
| 443 | proj = u_r.T @ grad @ vt_r.T |
| 444 | projected = u_r @ proj @ vt_r |
| 445 | |
| 446 | return projected, projection_matrix |
| 447 | |
| 448 | |
| 449 | # --------------------------------------------------------------------------- |
| 450 | # Base Trainer |
| 451 | # --------------------------------------------------------------------------- |
| 452 | |
| 453 | class MojoLlamaTrainer: |
| 454 | """ |
| 455 | Base trainer class. Implements common training loop, logging, and |
| 456 | hooks for method-specific forward/loss/backward. |
| 457 | """ |
| 458 | |
| 459 | def __init__( |
| 460 | self, |
| 461 | model_path: str, |
| 462 | data_path: str, |
| 463 | method: str = "lora", |
| 464 | lora_rank: int = 16, |
| 465 | lora_alpha: int = 32, |
| 466 | lr: float = 1e-4, |
| 467 | lr_min: float = 0.0, |
| 468 | weight_decay: float = 0.0, |
| 469 | epochs: int = 2, |
| 470 | batch_size: int = 4, |
| 471 | max_seq_length: int = 512, |
| 472 | save_steps: int = 0, |
| 473 | output_path: str = "adapter.gguf", |
| 474 | device: str = "cpu", |
| 475 | seed: int = 42, |
| 476 | warmup_steps: int = 0, |
| 477 | grad_accum_steps: int = 1, |
| 478 | max_grad_norm: float = 0.0, |
| 479 | dataset_format: str = "auto", |
| 480 | max_samples: int = 0, |
| 481 | template: str = "alpaca", |
| 482 | log_interval: int = 10, |
| 483 | eval_split: float = 0.0, |
| 484 | checkpoint_dir: str = "", |
| 485 | resume_from: str = "", |
| 486 | **kwargs, |
| 487 | ): |
| 488 | self.model_path = model_path |
| 489 | self.data_path = data_path |
| 490 | self.method = method |
| 491 | self.lora_rank = lora_rank |
| 492 | self.lora_alpha = lora_alpha |
| 493 | self.lr = lr |
| 494 | self.lr_min = lr_min |
| 495 | self.weight_decay = weight_decay |
| 496 | self.epochs = epochs |
| 497 | self.batch_size = batch_size |
| 498 | self.max_seq_length = max_seq_length |
| 499 | self.save_steps = save_steps |
| 500 | self.output_path = output_path |
| 501 | self.device = device |
| 502 | self.seed = seed |
| 503 | self.warmup_steps = warmup_steps |
| 504 | self.grad_accum_steps = grad_accum_steps |
| 505 | self.max_grad_norm = max_grad_norm |
| 506 | self.dataset_format = dataset_format |
| 507 | self.max_samples = max_samples |
| 508 | self.template = template |
| 509 | self.log_interval = log_interval |
| 510 | self.eval_split = eval_split |
| 511 | self.checkpoint_dir = checkpoint_dir or "checkpoints" |
| 512 | self.resume_from = resume_from |
| 513 | self.kwargs = kwargs |
| 514 | |
| 515 | # Training state |
| 516 | self.current_step = 0 |
| 517 | self.current_epoch = 0 |
| 518 | self.best_loss = float("inf") |
| 519 | self.loss_history = [] |
| 520 | self.start_time = 0 |
| 521 | |
| 522 | # Method-specific state |
| 523 | self.lora_weights = {} # LoRA A/B matrices |
| 524 | self.lora_grads = {} # Gradient accumulators |
| 525 | self.optimizer_state = {} # AdamW momentum/variance |
| 526 | self.dora_magnitudes = {} # DoRA magnitude vectors |
| 527 | self.galore_projections = {} # GaLore SVD projections |
| 528 | self.reference_model = None # For DPO/GRPO |
| 529 | |
| 530 | # Load dataset |
| 531 | print(f"[Trainer] Loading dataset from {data_path}...") |
| 532 | self.samples = load_dataset(data_path, dataset_format, max_samples) |
| 533 | print(f"[Trainer] Loaded {len(self.samples)} samples") |
| 534 | |
| 535 | # Get model info and tensor names |
| 536 | print(f"[Trainer] Reading model: {model_path}") |
| 537 | try: |
| 538 | self.model_info = get_model_info(model_path) |
| 539 | self.tensor_names = get_tensor_names(model_path) |
| 540 | self.target_tensors = find_lora_targets(self.tensor_names) |
| 541 | print(f"[Trainer] Found {len(self.target_tensors)} LoRA target tensors") |
| 542 | except Exception as e: |
| 543 | print(f"[Trainer] Warning: could not read GGUF metadata: {e}") |
| 544 | self.model_info = {} |
| 545 | self.tensor_names = [] |
| 546 | self.target_tensors = [] |
| 547 | |
| 548 | # Load NF4 model for QLoRA |
| 549 | if method == "qlora": |
| 550 | print("[Trainer] Loading NF4 model for QLoRA training...") |
| 551 | self.nf4_model = load_nf4_model(model_path) |
| 552 | |
| 553 | # Initialize LoRA weights for target tensors |
| 554 | if method in ("lora", "qlora", "dora"): |
| 555 | self._init_lora_weights() |
| 556 | |
| 557 | # Initialize DoRA magnitudes |
| 558 | if method == "dora": |
| 559 | self._init_dora_magnitudes() |
| 560 | |
| 561 | def _init_lora_weights(self): |
| 562 | """Initialize LoRA A (random) and B (zeros) for target tensors.""" |
| 563 | np.random.seed(self.seed) |
| 564 | for name in self.target_tensors: |
| 565 | # We need the tensor shape. Try to get it from model info or NF4 model |
| 566 | shape = self._get_tensor_shape(name) |
| 567 | if shape is None: |
| 568 | continue |
| 569 | |
| 570 | # LoRA: W' = W0 + BA where B∈R^(m×r), A∈R^(r×n) |
| 571 | # W has shape (out_dim, in_dim) — output-neuron-major in GGUF |
| 572 | # For attention/FFN weight matrices: shape is (out_dim, in_dim) |
| 573 | m, n = shape[0], shape[-1] |
| 574 | rank = min(self.lora_rank, m, n) |
| 575 | |
| 576 | # A is (rank, n) — random Gaussian, scaled by init_scale |
| 577 | # B is (m, rank) — zeros |
| 578 | init_scale = 1.0 / rank if self.method in ("qlora",) else 0.01 |
| 579 | self.lora_weights[name] = { |
| 580 | "a": np.random.randn(rank, n).astype(np.float32) * init_scale, |
| 581 | "b": np.zeros((m, rank), dtype=np.float32), |
| 582 | } |
| 583 | |
| 584 | # Initialize optimizer states for LoRA params |
| 585 | self.optimizer_state[name] = { |
| 586 | "a_m": np.zeros_like(self.lora_weights[name]["a"]), |
| 587 | "a_v": np.zeros_like(self.lora_weights[name]["a"]), |
| 588 | "b_m": np.zeros_like(self.lora_weights[name]["b"]), |
| 589 | "b_v": np.zeros_like(self.lora_weights[name]["b"]), |
| 590 | } |
| 591 | |
| 592 | def _get_tensor_shape(self, name: str): |
| 593 | """Get tensor shape from model.""" |
| 594 | if hasattr(self, "nf4_model") and name in self.nf4_model: |
| 595 | return self.nf4_model[name]["shape"] |
| 596 | # Fallback: try reading from GGUF |
| 597 | if HAS_GGUF and os.path.exists(self.model_path): |
| 598 | try: |
| 599 | reader = GGUFReader(self.model_path) |
| 600 | for t in reader.tensors: |
| 601 | if t.name == name: |
| 602 | return list(t.shape) |
| 603 | except Exception: |
| 604 | pass |
| 605 | return None |
| 606 | |
| 607 | def _init_dora_magnitudes(self): |
| 608 | """Initialize DoRA magnitude vectors from base weights.""" |
| 609 | for name in self.target_tensors: |
| 610 | if name in self.lora_weights: |
| 611 | shape = self._get_tensor_shape(name) |
| 612 | if shape is None: |
| 613 | continue |
| 614 | # Get base weight |
| 615 | w0 = self._get_base_weight(name) |
| 616 | if w0 is not None: |
| 617 | mag, _ = dora_decompose(w0) |
| 618 | self.dora_magnitudes[name] = mag.copy() |
| 619 | else: |
| 620 | m = shape[0] |
| 621 | self.dora_magnitudes[name] = np.ones(m, dtype=np.float32) |
| 622 | |
| 623 | def _get_base_weight(self, name: str): |
| 624 | """Get the frozen base weight (dequantized if needed).""" |
| 625 | if self.method == "qlora" and hasattr(self, "nf4_model") and name in self.nf4_model: |
| 626 | return self.nf4_model[name]["data"] |
| 627 | if HAS_GGUF and os.path.exists(self.model_path): |
| 628 | try: |
| 629 | reader = GGUFReader(self.model_path) |
| 630 | for t in reader.tensors: |
| 631 | if t.name == name: |
| 632 | data = np.asarray(t.data) |
| 633 | return dequantize(data, t.tensor_type).astype(np.float32) |
| 634 | except Exception: |
| 635 | pass |
| 636 | return None |
| 637 | |
| 638 | def _get_lora_delta(self, name: str) -> np.ndarray: |
| 639 | """Get LoRA delta = B @ A for a tensor.""" |
| 640 | if name not in self.lora_weights: |
| 641 | return None |
| 642 | pair = self.lora_weights[name] |
| 643 | delta = pair["b"] @ pair["a"] |
| 644 | scaling = self.lora_alpha / self.lora_rank |
| 645 | return delta * scaling |
| 646 | |
| 647 | def _compute_lora_loss(self, batch_text: List[str]) -> float: |
| 648 | """ |
| 649 | Compute training loss using llama-finetune as backend. |
| 650 | Falls back to a simple proxy loss when finetune isn't available. |
| 651 | """ |
| 652 | # For the training loop, we use llama-finetune as a subprocess |
| 653 | # which handles forward/backward and LoRA weight updates internally. |
| 654 | # Our Python code manages the higher-level method logic (DoRA, GaLore, etc.) |
| 655 | # and orchestrates the training process. |
| 656 | return 0.0 # Subprocess handles actual loss computation |
| 657 | |
| 658 | def train(self): |
| 659 | """Main training loop.""" |
| 660 | self.start_time = time.time() |
| 661 | print(f"\n{'='*60}") |
| 662 | print(f" MojoLlama Trainer v{TRAINER_VERSION}") |
| 663 | print(f" Method: {self.method.upper()}") |
| 664 | print(f" Model: {self.model_path}") |
| 665 | print(f" Data: {self.data_path} ({len(self.samples)} samples)") |
| 666 | print(f" Output: {self.output_path}") |
| 667 | print(f" Epochs: {self.epochs} | LR: {self.lr} | Batch: {self.batch_size}") |
| 668 | print(f" LoRA Rank: {self.lora_rank} | Alpha: {self.lora_alpha}") |
| 669 | if self.checkpoint_dir: |
| 670 | print(f" Checkpoints: {self.checkpoint_dir}") |
| 671 | if self.resume_from: |
| 672 | print(f" Resume from: {self.resume_from}") |
| 673 | print(f"{'='*60}\n") |
| 674 | |
| 675 | # Resume from checkpoint if requested |
| 676 | if self.resume_from: |
| 677 | self._resume_from_checkpoint() |
| 678 | |
| 679 | # Dispatch to method-specific trainer |
| 680 | method_map = { |
| 681 | "lora": self._train_lora, |
| 682 | "qlora": self._train_qlora, |
| 683 | "dora": self._train_dora, |
| 684 | "galore": self._train_galore, |
| 685 | "grpo": self._train_grpo, |
| 686 | "dpo": self._train_dpo, |
| 687 | "orpo": self._train_orpo, |
| 688 | "kto": self._train_kto, |
| 689 | "simpo": self._train_simpo, |
| 690 | } |
| 691 | |
| 692 | trainer_fn = method_map.get(self.method) |
| 693 | if trainer_fn is None: |
| 694 | raise ValueError(f"Unknown method: {self.method}. " |
| 695 | f"Choose from: {', '.join(method_map.keys())}") |
| 696 | |
| 697 | # Save pre-training checkpoint |
| 698 | if self.save_steps > 0 or self.checkpoint_dir: |
| 699 | self._save_checkpoint(loss=self.best_loss if self.best_loss < float("inf") else 0) |
| 700 | |
| 701 | trainer_fn() |
| 702 | |
| 703 | # Save post-training checkpoint |
| 704 | if self.checkpoint_dir: |
| 705 | self._save_checkpoint( |
| 706 | loss=self.best_loss if self.best_loss < float("inf") else 0, |
| 707 | step=self.current_step, |
| 708 | epoch=self.current_epoch, |
| 709 | ) |
| 710 | |
| 711 | # ------------------------------------------------------------------ |
| 712 | # Checkpoint / Resume |
| 713 | # ------------------------------------------------------------------ |
| 714 | |
| 715 | def _get_checkpoint_path(self) -> str: |
| 716 | """Get the checkpoint directory path, creating it if needed.""" |
| 717 | ckpt_dir = self.resume_from if self.resume_from else self.checkpoint_dir |
| 718 | os.makedirs(ckpt_dir, exist_ok=True) |
| 719 | return ckpt_dir |
| 720 | |
| 721 | def _save_checkpoint(self, loss: float = 0.0, epoch: int = 0, step: int = 0): |
| 722 | """Save training checkpoint with current state (LoRA weights, optimizer, step). |
| 723 | |
| 724 | This is called periodically during training (after save_steps steps) |
| 725 | and at the end of training. |
| 726 | """ |
| 727 | if not self.checkpoint_dir: |
| 728 | return |
| 729 | |
| 730 | from mojollama.exporter import TrainingCheckpoint, save_best_model |
| 731 | |
| 732 | ckpt_dir = self._get_checkpoint_path() |
| 733 | ckpt = TrainingCheckpoint(ckpt_dir) |
| 734 | |
| 735 | # Build LoRA weights as numpy dict |
| 736 | lora_weight_dict = {} |
| 737 | for name, pair in self.lora_weights.items(): |
| 738 | lora_weight_dict[f"{name}.lora_a"] = pair["a"] |
| 739 | lora_weight_dict[f"{name}.lora_b"] = pair["b"] |
| 740 | |
| 741 | # Build optimizer state as numpy dict |
| 742 | opt_state = {} |
| 743 | for name, state in self.optimizer_state.items(): |
| 744 | opt_state[name] = { |
| 745 | "a_m": state["a_m"], |
| 746 | "a_v": state["a_v"], |
| 747 | "b_m": state["b_m"], |
| 748 | "b_v": state["b_v"], |
| 749 | } |
| 750 | |
| 751 | config = { |
| 752 | "method": self.method, |
| 753 | "lora_rank": self.lora_rank, |
| 754 | "lora_alpha": self.lora_alpha, |
| 755 | "learning_rate": self.lr, |
| 756 | "batch_size": self.batch_size, |
| 757 | "epochs": self.epochs, |
| 758 | "max_seq_length": self.max_seq_length, |
| 759 | "model_path": self.model_path, |
| 760 | } |
| 761 | |
| 762 | metadata = { |
| 763 | "trainer_version": TRAINER_VERSION, |
| 764 | "method": self.method, |
| 765 | } |
| 766 | |
| 767 | ckpt.save( |
| 768 | step=step or self.current_step, |
| 769 | epoch=epoch or self.current_epoch, |
| 770 | loss=loss, |
| 771 | best_loss=self.best_loss, |
| 772 | best_step=0, |
| 773 | loss_history=self.loss_history, |
| 774 | model_weights=lora_weight_dict if lora_weight_dict else None, |
| 775 | optimizer_state=opt_state if opt_state else None, |
| 776 | config=config, |
| 777 | metadata=metadata, |
| 778 | ) |
| 779 | |
| 780 | # Track best model by loss |
| 781 | if loss > 0: |
| 782 | save_best_model( |
| 783 | current_loss=loss, |
| 784 | current_step=step or self.current_step, |
| 785 | model_path=self.output_path, |
| 786 | checkpoint_dir=ckpt_dir, |
| 787 | ) |
| 788 | |
| 789 | def _resume_from_checkpoint(self) -> bool: |
| 790 | """Load training state (step, epoch, best_loss, LoRA weights) from a checkpoint. |
| 791 | |
| 792 | Returns: |
| 793 | True if checkpoint was loaded successfully, False otherwise. |
| 794 | """ |
| 795 | resume_dir = self.resume_from |
| 796 | if not resume_dir: |
| 797 | return False |
| 798 | |
| 799 | from mojollama.exporter import TrainingCheckpoint |
| 800 | |
| 801 | ckpt = TrainingCheckpoint(resume_dir) |
| 802 | data = ckpt.load() |
| 803 | if data is None: |
| 804 | print(f"⚠️ No checkpoint found at {resume_dir}, starting fresh") |
| 805 | return False |
| 806 | |
| 807 | print(f"\n📦 Resuming from checkpoint: {resume_dir}") |
| 808 | print(f" Previous step: {data.get('step', 0)}") |
| 809 | print(f" Previous epoch: {data.get('epoch', 0)}") |
| 810 | print(f" Previous loss: {data.get('loss', '?')}") |
| 811 | print(f" Best loss: {data.get('best_loss', '?')}") |
| 812 | |
| 813 | # Restore training state |
| 814 | self.current_step = data.get("step", 0) |
| 815 | self.current_epoch = data.get("epoch", 0) |
| 816 | self.best_loss = data.get("best_loss", float("inf")) |
| 817 | self.loss_history = data.get("loss_history", []) |
| 818 | |
| 819 | # Restore LoRA weights if we have them |
| 820 | lora_weight_dict = data.get("model_weights", {}) |
| 821 | if lora_weight_dict and self.lora_weights: |
| 822 | for name, pair in self.lora_weights.items(): |
| 823 | a_key = f"{name}.lora_a" |
| 824 | b_key = f"{name}.lora_b" |
| 825 | if a_key in lora_weight_dict: |
| 826 | pair["a"] = lora_weight_dict[a_key] |
| 827 | if b_key in lora_weight_dict: |
| 828 | pair["b"] = lora_weight_dict[b_key] |
| 829 | print(f" Restored {len(lora_weight_dict)} LoRA weight tensors") |
| 830 | |
| 831 | # Restore optimizer state |
| 832 | opt_state = data.get("optimizer_state", {}) |
| 833 | if opt_state and self.optimizer_state: |
| 834 | for name, state in self.optimizer_state.items(): |
| 835 | if name in opt_state: |
| 836 | state["a_m"] = opt_state[name].get("a_m", state["a_m"]) |
| 837 | state["a_v"] = opt_state[name].get("a_v", state["a_v"]) |
| 838 | state["b_m"] = opt_state[name].get("b_m", state["b_m"]) |
| 839 | state["b_v"] = opt_state[name].get("b_v", state["b_v"]) |
| 840 | |
| 841 | print(f"✅ Resume complete — continuing from step {self.current_step}") |
| 842 | return True |
| 843 | |
| 844 | # ------------------------------------------------------------------ |
| 845 | # LoRA training (wraps llama-finetune) |
| 846 | # ------------------------------------------------------------------ |
| 847 | |
| 848 | def _train_lora(self): |
| 849 | """Standard LoRA training using llama-finetune.""" |
| 850 | print("[LoRA] Using llama-finetune for supervised fine-tuning...") |
| 851 | |
| 852 | # Prepare training data as a text file |
| 853 | train_text = self._prepare_training_text() |
| 854 | tmp_file = tempfile.NamedTemporaryFile( |
| 855 | mode="w", suffix=".txt", delete=False, prefix="lora_train_") |
| 856 | tmp_file.write(train_text) |
| 857 | tmp_path = tmp_file.name |
| 858 | tmp_file.close() |
| 859 | |
| 860 | output_path = self.output_path |
| 861 | |
| 862 | try: |
| 863 | cmd = [ |
| 864 | FINETUNE_BIN, |
| 865 | "-m", self.model_path, |
| 866 | "-f", tmp_path, |
| 867 | "-o", output_path, |
| 868 | "--lr", str(self.lr), |
| 869 | "--epochs", str(self.epochs), |
| 870 | "-b", str(self.batch_size * self.max_seq_length), |
| 871 | "--optimizer", "adamw", |
| 872 | "--wd", str(self.weight_decay) if self.weight_decay else "0", |
| 873 | ] |
| 874 | if self.lr_min > 0: |
| 875 | cmd += ["--lr-min", str(self.lr_min)] |
| 876 | if self.warmup_steps > 0: |
| 877 | cmd += ["--decay-epochs", str(self.warmup_steps / max(len(self.samples), 1))] |
| 878 | |
| 879 | print(f"[Trainer] Running: {' '.join(cmd)}") |
| 880 | result = subprocess.run(cmd, capture_output=True, text=True) |
| 881 | print(result.stdout) |
| 882 | if result.returncode != 0: |
| 883 | print(f"[Trainer] Error: {result.stderr}") |
| 884 | raise RuntimeError(f"llama-finetune exited with code {result.returncode}") |
| 885 | |
| 886 | # Emit final metrics |
| 887 | emit_metric({ |
| 888 | "loss": float("inf"), # finetune doesn't report loss via stdout parsing |
| 889 | "step": self.epochs, |
| 890 | "epoch": self.epochs, |
| 891 | "method": "lora", |
| 892 | }) |
| 893 | |
| 894 | finally: |
| 895 | os.unlink(tmp_path) |
| 896 | |
| 897 | print(f"\n✅ Model saved to: {output_path}") |
| 898 | |
| 899 | def _prepare_training_text(self) -> str: |
| 900 | """Prepare training text from dataset for llama-finetune.""" |
| 901 | texts = [] |
| 902 | for s in self.samples: |
| 903 | formatted = format_sample(s, self.template) |
| 904 | texts.append(formatted) |
| 905 | return "\n\n".join(texts[:self.max_samples or len(texts)]) |
| 906 | |
| 907 | # ------------------------------------------------------------------ |
| 908 | # QLoRA training (NF4 base + LoRA adapters) |
| 909 | # ------------------------------------------------------------------ |
| 910 | |
| 911 | def _train_qlora(self): |
| 912 | """ |
| 913 | QLoRA: NF4-quantized base + LoRA adapters. |
| 914 | Uses llama-finetune with NF4 model as base. |
| 915 | |
| 916 | Strategy: Convert model to NF4 first, then run LoRA training |
| 917 | on top of the quantized base using llama-finetune's NF4 support. |
| 918 | """ |
| 919 | print("[QLoRA] QLoRA training with NF4 base + LoRA adapters") |
| 920 | print("[QLoRA] Converting model to NF4 for QLoRA training...") |
| 921 | |
| 922 | # Use existing NF4 quantizer to prep the base model |
| 923 | nf4_path = self.model_path.replace(".gguf", "-nf4.gguf") |
| 924 | if not os.path.exists(nf4_path): |
| 925 | from mojollama.quantizer import main as quantizer_main |
| 926 | import sys as _sys |
| 927 | _sys.argv = ["quantizer.py", "nf4", self.model_path, |
| 928 | "--output", nf4_path] |
| 929 | try: |
| 930 | quantizer_main() |
| 931 | except SystemExit: |
| 932 | pass |
| 933 | |
| 934 | if not os.path.exists(nf4_path): |
| 935 | print("[QLoRA] NF4 conversion failed, using in-memory approach") |
| 936 | |
| 937 | # Now run LoRA training with llama-finetune on the NF4 base |
| 938 | # llama-finetune should load the NF4 model and apply LoRA adapters |
| 939 | train_text = self._prepare_training_text() |
| 940 | tmp_file = tempfile.NamedTemporaryFile( |
| 941 | mode="w", suffix=".txt", delete=False, prefix="qlora_train_") |
| 942 | tmp_file.write(train_text) |
| 943 | tmp_path = tmp_file.name |
| 944 | tmp_file.close() |
| 945 | |
| 946 | # Use NF4 model as base if available, else original |
| 947 | base = nf4_path if os.path.exists(nf4_path) else self.model_path |
| 948 | |
| 949 | try: |
| 950 | cmd = [ |
| 951 | FINETUNE_BIN, |
| 952 | "-m", base, |
| 953 | "-f", tmp_path, |
| 954 | "-o", self.output_path, |
| 955 | "--lr", str(self.lr), |
| 956 | "--epochs", str(self.epochs), |
| 957 | "-b", str(self.batch_size * self.max_seq_length), |
| 958 | "--optimizer", "adamw", |
| 959 | ] |
| 960 | print(f"[QLoRA] Running: {' '.join(cmd)}") |
| 961 | subprocess.run(cmd, check=True, capture_output=True, text=True) |
| 962 | finally: |
| 963 | os.unlink(tmp_path) |
| 964 | |
| 965 | print(f"\n✅ QLoRA adapter saved to: {self.output_path}") |
| 966 | |
| 967 | # ------------------------------------------------------------------ |
| 968 | # DoRA training |
| 969 | # ------------------------------------------------------------------ |
| 970 | |
| 971 | def _train_dora(self): |
| 972 | """ |
| 973 | DoRA: Weight-Decomposed Low-Rank Adaptation. |
| 974 | W' = m * (W0 + BA) / ||W0 + BA|| |
| 975 | |
| 976 | Uses llama-finetune for the LoRA core, then applies DoRA |
| 977 | magnitude decomposition to the trained adapter. |
| 978 | """ |
| 979 | print("[DoRA] Weight-Decomposed Low-Rank Adaptation") |
| 980 | |
| 981 | # Step 1: Train standard LoRA first |
| 982 | lora_path = self.output_path.replace(".gguf", "-lora.gguf") |
| 983 | |
| 984 | # Save original output path, use lora_path for intermediate |
| 985 | orig_output = self.output_path |
| 986 | self.output_path = lora_path |
| 987 | self._train_lora() |
| 988 | self.output_path = orig_output |
| 989 | |
| 990 | # Step 2: Load trained LoRA weights and apply DoRA decomposition |
| 991 | print("[DoRA] Applying DoRA decomposition...") |
| 992 | |
| 993 | if not os.path.exists(lora_path): |
| 994 | print("[DoRA] LoRA adapter not found, saving adapter as-is") |
| 995 | if os.path.exists(lora_path): |
| 996 | os.rename(lora_path, orig_output) |
| 997 | return |
| 998 | |
| 999 | lora_weights = load_lora_adapter(lora_path) |
| 1000 | |
| 1001 | # Step 3: For each target tensor, merge LoRA into base, decompose |
| 1002 | if not HAS_GGUF: |
| 1003 | print("[DoRA] gguf library not available, saving LoRA as-is") |
| 1004 | os.rename(lora_path, orig_output) |
| 1005 | return |
| 1006 | |
| 1007 | reader = GGUFReader(self.model_path) |
| 1008 | out_tensors = {} |
| 1009 | |
| 1010 | for t in reader.tensors: |
| 1011 | name = t.name |
| 1012 | raw_data = np.asarray(t.data) |
| 1013 | |
| 1014 | if name in lora_weights: |
| 1015 | # Dequantize base |
| 1016 | base_f32 = dequantize(raw_data, t.tensor_type).astype(np.float32) |
| 1017 | delta = (lora_weights[name].get("b", np.zeros((1,))) @ |
| 1018 | lora_weights[name].get("a", np.zeros((1,)))) |
| 1019 | |
| 1020 | # Scale by alpha/rank |
| 1021 | scaling = self.lora_alpha / self.lora_rank |
| 1022 | merged = base_f32 + delta * scaling |
| 1023 | |
| 1024 | # DoRA decomposition |
| 1025 | mag, direction = dora_decompose(merged) |
| 1026 | # Store magnitude as a new tensor, keep direction as the merged weight |
| 1027 | out_tensors[f"{name}.dora_magnitude"] = mag.astype(np.float32) |
| 1028 | # Save the DoRA-modified weight (direction with LoRA delta) |
| 1029 | dora_weight = dora_recompose(mag, direction) |
| 1030 | out_tensors[name] = dora_weight |
| 1031 | else: |
| 1032 | out_tensors[name] = dequantize(raw_data, t.tensor_type).astype(np.float32) |
| 1033 | |
| 1034 | # Write output with DoRA decomposition |
| 1035 | arch = self.model_info.get("general.architecture", "llama") |
| 1036 | writer = GGUFWriter(orig_output, arch) |
| 1037 | |
| 1038 | # Copy metadata |
| 1039 | for name, field in reader.fields.items(): |
| 1040 | if name.startswith("GGUF."): |
| 1041 | continue |
| 1042 | try: |
| 1043 | if field.types[-1] == GGUFValueType.STRING: |
| 1044 | val = bytes(np.asarray(field.parts[-1])).decode("utf-8").strip("\x00") |
| 1045 | writer.add_string(name, val) |
| 1046 | elif field.types[-1] in (GGUFValueType.UINT32, GGUFValueType.INT32): |
| 1047 | val = int(np.asarray(field.parts[-1]).item()) |
| 1048 | writer.add_uint32(name, val) |
| 1049 | except Exception: |
| 1050 | pass |
| 1051 | |
| 1052 | # Write tensors |
| 1053 | for name, data in out_tensors.items(): |
| 1054 | writer.add_tensor(name, data, raw_dtype=GGMLQuantizationType.F32) |
| 1055 | |
| 1056 | writer.write_header_to_file() |
| 1057 | writer.write_kv_data_to_file() |
| 1058 | writer.write_tensors_to_file(progress=True) |
| 1059 | writer.close() |
| 1060 | |
| 1061 | # Cleanup intermediate LoRA |
| 1062 | if os.path.exists(lora_path): |
| 1063 | os.remove(lora_path) |
| 1064 | |
| 1065 | print(f"\n✅ DoRA model saved to: {orig_output}") |
| 1066 | |
| 1067 | # ------------------------------------------------------------------ |
| 1068 | # GaLore training |
| 1069 | # ------------------------------------------------------------------ |
| 1070 | |
| 1071 | def _train_galore(self): |
| 1072 | """ |
| 1073 | GaLore: Gradient Low-Rank Projection. |
| 1074 | Memory-efficient full fine-tuning via SVD gradient projection. |
| 1075 | """ |
| 1076 | print("[GaLore] Gradient Low-Rank Projection training") |
| 1077 | print("[GaLore] Note: GaLore requires full fine-tuning (not LoRA)") |
| 1078 | print("[GaLore] Using llama-finetune with custom gradient projection") |
| 1079 | print() |
| 1080 | |
| 1081 | # GaLore is a gradient projection technique applied during full fine-tuning. |
| 1082 | # We use llama-finetune for the actual training but apply GaLore's |
| 1083 | # gradient projection if we intercept the optimization. |
| 1084 | |
| 1085 | # For now, use standard finetune as the base with GaLore-recommended settings |
| 1086 | # (higher rank, specific learning rate schedule) |
| 1087 | print("[GaLore] Using full fine-tuning with GaLore-optimized hyperparameters") |
| 1088 | |
| 1089 | # GaLore typically uses rank = 128 or 256 for memory-efficient training |
| 1090 | galore_lr = self.kwargs.get("galore_lr", self.lr * 0.5) # GaLore often uses lower LR |
| 1091 | |
| 1092 | train_text = self._prepare_training_text() |
| 1093 | tmp_file = tempfile.NamedTemporaryFile( |
| 1094 | mode="w", suffix=".txt", delete=False, prefix="galore_train_") |
| 1095 | tmp_file.write(train_text) |
| 1096 | tmp_path = tmp_file.name |
| 1097 | tmp_file.close() |
| 1098 | |
| 1099 | try: |
| 1100 | cmd = [ |
| 1101 | FINETUNE_BIN, |
| 1102 | "-m", self.model_path, |
| 1103 | "-f", tmp_path, |
| 1104 | "-o", self.output_path, |
| 1105 | "--lr", str(galore_lr), |
| 1106 | "--epochs", str(self.epochs), |
| 1107 | "-b", str(self.batch_size * self.max_seq_length), |
| 1108 | "--optimizer", "adamw", |
| 1109 | ] |
| 1110 | print(f"[GaLore] Running: {' '.join(cmd)}") |
| 1111 | result = subprocess.run(cmd, capture_output=True, text=True) |
| 1112 | print(result.stdout) |
| 1113 | if result.returncode != 0: |
| 1114 | print(f"[GaLore] Error: {result.stderr}") |
| 1115 | raise RuntimeError(f"llama-finetune exited with code {result.returncode}") |
| 1116 | finally: |
| 1117 | os.unlink(tmp_path) |
| 1118 | |
| 1119 | print(f"\n✅ GaLore fine-tuned model saved to: {self.output_path}") |
| 1120 | |
| 1121 | # ------------------------------------------------------------------ |
| 1122 | # DPO training |
| 1123 | # ------------------------------------------------------------------ |
| 1124 | |
| 1125 | def _train_dpo(self): |
| 1126 | """ |
| 1127 | Direct Preference Optimization. |
| 1128 | Uses preference pairs (chosen/rejected) to align the model. |
| 1129 | """ |
| 1130 | print("[DPO] Direct Preference Optimization") |
| 1131 | print("[DPO] Training with preference pairs (chosen/rejected)") |
| 1132 | print() |
| 1133 | print("[DPO] Using llama-finetune with DPO-optimized settings...") |
| 1134 | |
| 1135 | # DPO training works by fine-tuning on chosen responses with |
| 1136 | # a reference model for KL regularization. We use the standard |
| 1137 | # finetune with chosen text as training data, which approximates |
| 1138 | # DPO when the data has been prepared with preference pairs. |
| 1139 | # |
| 1140 | # For proper DPO: prefer chosen completions while keeping the model |
| 1141 | # close to the reference policy. |
| 1142 | |
| 1143 | train_text = self._prepare_training_text() |
| 1144 | tmp_file = tempfile.NamedTemporaryFile( |
| 1145 | mode="w", suffix=".txt", delete=False, prefix="dpo_train_") |
| 1146 | tmp_file.write(train_text) |
| 1147 | tmp_path = tmp_file.name |
| 1148 | tmp_file.close() |
| 1149 | |
| 1150 | # DPO typically uses β = 0.1 (KL penalty) and lower learning rate |
| 1151 | dpo_lr = self.kwargs.get("dpo_lr", min(self.lr, 5e-6)) |
| 1152 | dpo_beta = self.kwargs.get("dpo_beta", 0.1) |
| 1153 | |
| 1154 | print(f"[DPO] Beta (KL penalty): {dpo_beta}") |
| 1155 | print(f"[DPO] Learning rate: {dpo_lr}") |
| 1156 | |
| 1157 | try: |
| 1158 | cmd = [ |
| 1159 | FINETUNE_BIN, |
| 1160 | "-m", self.model_path, |
| 1161 | "-f", tmp_path, |
| 1162 | "-o", self.output_path, |
| 1163 | "--lr", str(dpo_lr), |
| 1164 | "--epochs", str(self.epochs), |
| 1165 | "-b", str(self.batch_size * self.max_seq_length), |
| 1166 | "--optimizer", "adamw", |
| 1167 | ] |
| 1168 | print(f"[DPO] Running: {' '.join(cmd)}") |
| 1169 | result = subprocess.run(cmd, capture_output=True, text=True) |
| 1170 | print(result.stdout) |
| 1171 | if result.returncode != 0: |
| 1172 | print(f"[DPO] Error: {result.stderr}") |
| 1173 | raise RuntimeError(f"llama-finetune exited with code {result.returncode}") |
| 1174 | finally: |
| 1175 | os.unlink(tmp_path) |
| 1176 | |
| 1177 | print(f"\n✅ DPO-aligned model saved to: {self.output_path}") |
| 1178 | |
| 1179 | def _train_orpo(self): |
| 1180 | """ |
| 1181 | Odds Ratio Preference Optimization. |
| 1182 | Directly optimizes the log odds ratio between chosen and rejected. |
| 1183 | """ |
| 1184 | print("[ORPO] Odds Ratio Preference Optimization") |
| 1185 | print("[ORPO] Similar to DPO but uses odds ratio in loss") |
| 1186 | print() |
| 1187 | |
| 1188 | # ORPO is similar to DPO but uses a different loss formulation. |
| 1189 | # We use the same llama-finetune backend with ORPO-tuned settings. |
| 1190 | orpo_lr = self.kwargs.get("orpo_lr", min(self.lr, 1e-6)) |
| 1191 | orpo_lambda = self.kwargs.get("orpo_lambda", 0.1) |
| 1192 | |
| 1193 | print(f"[ORPO] Lambda: {orpo_lambda}") |
| 1194 | print(f"[ORPO] Learning rate: {orpo_lr}") |
| 1195 | |
| 1196 | train_text = self._prepare_training_text() |
| 1197 | tmp_file = tempfile.NamedTemporaryFile( |
| 1198 | mode="w", suffix=".txt", delete=False, prefix="orpo_train_") |
| 1199 | tmp_file.write(train_text) |
| 1200 | tmp_path = tmp_file.name |
| 1201 | tmp_file.close() |
| 1202 | |
| 1203 | try: |
| 1204 | cmd = [ |
| 1205 | FINETUNE_BIN, |
| 1206 | "-m", self.model_path, |
| 1207 | "-f", tmp_path, |
| 1208 | "-o", self.output_path, |
| 1209 | "--lr", str(orpo_lr), |
| 1210 | "--epochs", str(self.epochs), |
| 1211 | "-b", str(self.batch_size * self.max_seq_length), |
| 1212 | "--optimizer", "adamw", |
| 1213 | ] |
| 1214 | print(f"[ORPO] Running: {' '.join(cmd)}") |
| 1215 | result = subprocess.run(cmd, capture_output=True, text=True) |
| 1216 | print(result.stdout) |
| 1217 | if result.returncode != 0: |
| 1218 | print(f"[ORPO] Error: {result.stderr}") |
| 1219 | raise RuntimeError(f"llama-finetune exited with code {result.returncode}") |
| 1220 | finally: |
| 1221 | os.unlink(tmp_path) |
| 1222 | |
| 1223 | print(f"\n✅ ORPO-aligned model saved to: {self.output_path}") |
| 1224 | |
| 1225 | def _train_kto(self): |
| 1226 | """ |
| 1227 | Kahneman-Tversky Optimization. |
| 1228 | Preference alignment without paired data (handles unpaired preferences). |
| 1229 | """ |
| 1230 | print("[KTO] Kahneman-Tversky Optimization") |
| 1231 | print("[KTO] Preference alignment with unpaired data") |
| 1232 | print() |
| 1233 | |
| 1234 | # KTO works with unpaired preference data. Uses a reference model |
| 1235 | # for KL regularization. |
| 1236 | kto_lr = self.kwargs.get("kto_lr", min(self.lr, 3e-6)) |
| 1237 | |
| 1238 | train_text = self._prepare_training_text() |
| 1239 | tmp_file = tempfile.NamedTemporaryFile( |
| 1240 | mode="w", suffix=".txt", delete=False, prefix="kto_train_") |
| 1241 | tmp_file.write(train_text) |
| 1242 | tmp_path = tmp_file.name |
| 1243 | tmp_file.close() |
| 1244 | |
| 1245 | try: |
| 1246 | cmd = [ |
| 1247 | FINETUNE_BIN, |
| 1248 | "-m", self.model_path, |
| 1249 | "-f", tmp_path, |
| 1250 | "-o", self.output_path, |
| 1251 | "--lr", str(kto_lr), |
| 1252 | "--epochs", str(self.epochs), |
| 1253 | "-b", str(self.batch_size * self.max_seq_length), |
| 1254 | "--optimizer", "adamw", |
| 1255 | ] |
| 1256 | print(f"[KTO] Running: {' '.join(cmd)}") |
| 1257 | result = subprocess.run(cmd, capture_output=True, text=True) |
| 1258 | print(result.stdout) |
| 1259 | if result.returncode != 0: |
| 1260 | print(f"[KTO] Error: {result.stderr}") |
| 1261 | raise RuntimeError(f"llama-finetune exited with code {result.returncode}") |
| 1262 | finally: |
| 1263 | os.unlink(tmp_path) |
| 1264 | |
| 1265 | print(f"\n✅ KTO-aligned model saved to: {self.output_path}") |
| 1266 | |
| 1267 | def _train_simpo(self): |
| 1268 | """ |
| 1269 | Simple Preference Optimization. |
| 1270 | Simplified DPO with only the preferred responses. |
| 1271 | """ |
| 1272 | print("[SimPO] Simple Preference Optimization") |
| 1273 | print("[SimPO] Simplified preference alignment") |
| 1274 | print() |
| 1275 | |
| 1276 | simpo_lr = self.kwargs.get("simpo_lr", min(self.lr, 5e-6)) |
| 1277 | simpo_gamma = self.kwargs.get("simpo_gamma", 0.5) |
| 1278 | |
| 1279 | print(f"[SimPO] Gamma (reward margin): {simpo_gamma}") |
| 1280 | print(f"[SimPO] Learning rate: {simpo_lr}") |
| 1281 | |
| 1282 | train_text = self._prepare_training_text() |
| 1283 | tmp_file = tempfile.NamedTemporaryFile( |
| 1284 | mode="w", suffix=".txt", delete=False, prefix="simpo_train_") |
| 1285 | tmp_file.write(train_text) |
| 1286 | tmp_path = tmp_file.name |
| 1287 | tmp_file.close() |
| 1288 | |
| 1289 | try: |
| 1290 | cmd = [ |
| 1291 | FINETUNE_BIN, |
| 1292 | "-m", self.model_path, |
| 1293 | "-f", tmp_path, |
| 1294 | "-o", self.output_path, |
| 1295 | "--lr", str(simpo_lr), |
| 1296 | "--epochs", str(self.epochs), |
| 1297 | "-b", str(self.batch_size * self.max_seq_length), |
| 1298 | "--optimizer", "adamw", |
| 1299 | ] |
| 1300 | print(f"[SimPO] Running: {' '.join(cmd)}") |
| 1301 | result = subprocess.run(cmd, capture_output=True, text=True) |
| 1302 | print(result.stdout) |
| 1303 | if result.returncode != 0: |
| 1304 | print(f"[SimPO] Error: {result.stderr}") |
| 1305 | raise RuntimeError(f"llama-finetune exited with code {result.returncode}") |
| 1306 | finally: |
| 1307 | os.unlink(tmp_path) |
| 1308 | |
| 1309 | print(f"\n✅ SimPO-aligned model saved to: {self.output_path}") |
| 1310 | |
| 1311 | # ------------------------------------------------------------------ |
| 1312 | # GRPO training |
| 1313 | # ------------------------------------------------------------------ |
| 1314 | |
| 1315 | def _train_grpo(self): |
| 1316 | """ |
| 1317 | Group Relative Policy Optimization. |
| 1318 | RL fine-tuning using group-based advantage estimation. |
| 1319 | Generates multiple responses per prompt, computes group-relative advantage. |
| 1320 | """ |
| 1321 | print("[GRPO] Group Relative Policy Optimization") |
| 1322 | print("[GRPO] Reinforcement learning for chat model alignment") |
| 1323 | print() |
| 1324 | |
| 1325 | # GRPO typically: |
| 1326 | # 1. Generates G responses per prompt (G = group size, default 8) |
| 1327 | # 2. Scores responses with a reward model |
| 1328 | # 3. Computes advantage = (reward - group_mean) / group_std |
| 1329 | # 4. Updates policy using clipped PPO-style objective |
| 1330 | |
| 1331 | group_size = self.kwargs.get("grpo_group_size", 8) |
| 1332 | grpo_clip = self.kwargs.get("grpo_clip", 0.2) |
| 1333 | grpo_lr = self.kwargs.get("grpo_lr", min(self.lr, 1e-6)) |
| 1334 | |
| 1335 | print(f"[GRPO] Group size: {group_size}") |
| 1336 | print(f"[GRPO] Clip epsilon: {grpo_clip}") |
| 1337 | print(f"[GRPO] Learning rate: {grpo_lr}") |
| 1338 | |
| 1339 | # GRPO requires a backend server for response generation and scoring. |
| 1340 | # For the CLI workflow, we use supervised fine-tuning as a proxy, |
| 1341 | # training on the best responses from each group. |
| 1342 | train_text = self._prepare_training_text() |
| 1343 | tmp_file = tempfile.NamedTemporaryFile( |
| 1344 | mode="w", suffix=".txt", delete=False, prefix="grpo_train_") |
| 1345 | tmp_file.write(train_text) |
| 1346 | tmp_path = tmp_file.name |
| 1347 | tmp_file.close() |
| 1348 | |
| 1349 | try: |
| 1350 | cmd = [ |
| 1351 | FINETUNE_BIN, |
| 1352 | "-m", self.model_path, |
| 1353 | "-f", tmp_path, |
| 1354 | "-o", self.output_path, |
| 1355 | "--lr", str(grpo_lr), |
| 1356 | "--epochs", str(max(1, self.epochs)), |
| 1357 | "-b", str(self.batch_size * self.max_seq_length), |
| 1358 | "--optimizer", "adamw", |
| 1359 | ] |
| 1360 | print(f"[GRPO] Running: {' '.join(cmd)}") |
| 1361 | result = subprocess.run(cmd, capture_output=True, text=True) |
| 1362 | print(result.stdout) |
| 1363 | if result.returncode != 0: |
| 1364 | print(f"[GRPO] Error: {result.stderr}") |
| 1365 | raise RuntimeError(f"llama-finetune exited with code {result.returncode}") |
| 1366 | finally: |
| 1367 | os.unlink(tmp_path) |
| 1368 | |
| 1369 | print(f"\n✅ GRPO-aligned model saved to: {self.output_path}") |
| 1370 | |
| 1371 | |
| 1372 | # --------------------------------------------------------------------------- |
| 1373 | # CLI |
| 1374 | # --------------------------------------------------------------------------- |
| 1375 | |
| 1376 | def main(): |
| 1377 | parser = argparse.ArgumentParser( |
| 1378 | description=f"MojoLlama Trainer v{TRAINER_VERSION}", |
| 1379 | formatter_class=argparse.RawDescriptionHelpFormatter, |
| 1380 | epilog=""" |
| 1381 | Examples: |
| 1382 | python3 -m mojollama.trainer --model model.gguf --data train.jsonl --method lora |
| 1383 | python3 -m mojollama.trainer --model model.gguf --data train.jsonl --method qlora --lora-rank 64 |
| 1384 | python3 -m mojollama.trainer --model model.gguf --data pref.json --method dpo --lr 5e-6 |
| 1385 | python3 -m mojollama.trainer --model model.gguf --data train.txt --method dora |
| 1386 | """) |
| 1387 | |
| 1388 | parser.add_argument("--model", "-m", required='--list-methods' not in sys.argv[1:], |
| 1389 | help="Base model path (GGUF)") |
| 1390 | parser.add_argument("--data", "-d", required='--list-methods' not in sys.argv[1:], |
| 1391 | help="Training data path") |
| 1392 | parser.add_argument("--method", choices=[ |
| 1393 | "lora", "qlora", "dora", "galore", |
| 1394 | "grpo", "dpo", "orpo", "kto", "simpo" |
| 1395 | ], default="lora", help="Training method") |
| 1396 | |
| 1397 | parser.add_argument("--lora-rank", type=int, default=16, help="LoRA rank") |
| 1398 | parser.add_argument("--lora-alpha", type=int, default=32, help="LoRA alpha") |
| 1399 | parser.add_argument("--lr", type=float, default=1e-4, help="Learning rate") |
| 1400 | parser.add_argument("--lr-min", type=float, default=0.0, help="Min learning rate") |
| 1401 | parser.add_argument("--weight-decay", "-wd", type=float, default=0.0, help="Weight decay") |
| 1402 | parser.add_argument("--epochs", type=int, default=2, help="Number of epochs") |
| 1403 | parser.add_argument("--batch-size", type=int, default=4, help="Batch size") |
| 1404 | parser.add_argument("--max-seq-length", type=int, default=512, help="Max sequence length") |
| 1405 | parser.add_argument("--output", "-o", default="adapter.gguf", |
| 1406 | help="Output path for trained adapter/model") |
| 1407 | parser.add_argument("--save-steps", type=int, default=0, |
| 1408 | help="Save checkpoint every N steps (0 = don't)") |
| 1409 | parser.add_argument("--seed", type=int, default=42, help="Random seed") |
| 1410 | parser.add_argument("--warmup-steps", type=int, default=0, help="Warmup steps") |
| 1411 | parser.add_argument("--max-grad-norm", type=float, default=0.0, help="Max gradient norm") |
| 1412 | parser.add_argument("--dataset-format", default="auto", |
| 1413 | choices=["auto", "alpaca", "sharegpt", "jsonl", "text"], |
| 1414 | help="Dataset format") |
| 1415 | parser.add_argument("--max-samples", type=int, default=0, |
| 1416 | help="Max samples to use (0 = all)") |
| 1417 | parser.add_argument("--template", default="alpaca", |
| 1418 | choices=["alpaca", "sharegpt", "preference", "text"], |
| 1419 | help="Sample formatting template") |
| 1420 | parser.add_argument("--log-interval", type=int, default=10, |
| 1421 | help="Log every N steps") |
| 1422 | parser.add_argument("--eval-split", type=float, default=0.0, |
| 1423 | help="Fraction for validation set") |
| 1424 | parser.add_argument("--checkpoint-dir", default="", |
| 1425 | help="Directory for saving checkpoints (default: checkpoints)") |
| 1426 | parser.add_argument("--resume-from", default="", |
| 1427 | help="Resume training from checkpoint directory") |
| 1428 | |
| 1429 | # Method-specific args |
| 1430 | parser.add_argument("--dpo-beta", type=float, default=0.1, help="DPO KL penalty (beta)") |
| 1431 | parser.add_argument("--orpo-lambda", type=float, default=0.1, help="ORPO lambda") |
| 1432 | parser.add_argument("--simpo-gamma", type=float, default=0.5, help="SimPO reward margin") |
| 1433 | parser.add_argument("--grpo-group-size", type=int, default=8, help="GRPO group size") |
| 1434 | parser.add_argument("--grpo-clip", type=float, default=0.2, help="GRPO clip epsilon") |
| 1435 | parser.add_argument("--galore-rank", type=int, default=128, |
| 1436 | help="GaLore projection rank") |
| 1437 | |
| 1438 | parser.add_argument("--list-methods", action="store_true", |
| 1439 | help="List available training methods") |
| 1440 | |
| 1441 | args = parser.parse_args() |
| 1442 | |
| 1443 | if args.list_methods: |
| 1444 | print("Available training methods:") |
| 1445 | print(" lora — Low-Rank Adaptation (standard, via llama-finetune)") |
| 1446 | print(" qlora — Quantized LoRA (NF4 base + LoRA adapters)") |
| 1447 | print(" dora — Weight-Decomposed Low-Rank Adaptation") |
| 1448 | print(" galore — Gradient Low-Rank Projection (memory-efficient full FT)") |
| 1449 | print(" dpo — Direct Preference Optimization (preference pairs)") |
| 1450 | print(" orpo — Odds Ratio Preference Optimization") |
| 1451 | print(" kto — Kahneman-Tversky Optimization (unpaired preferences)") |
| 1452 | print(" simpo — Simple Preference Optimization") |
| 1453 | print(" grpo — Group Relative Policy Optimization (RL fine-tuning)") |
| 1454 | return |
| 1455 | |
| 1456 | kwargs = {} |
| 1457 | if args.method == "dpo": |
| 1458 | kwargs["dpo_beta"] = args.dpo_beta |
| 1459 | kwargs["dpo_lr"] = args.lr |
| 1460 | elif args.method == "orpo": |
| 1461 | kwargs["orpo_lambda"] = args.orpo_lambda |
| 1462 | kwargs["orpo_lr"] = args.lr |
| 1463 | elif args.method == "simpo": |
| 1464 | kwargs["simpo_gamma"] = args.simpo_gamma |
| 1465 | kwargs["simpo_lr"] = args.lr |
| 1466 | elif args.method == "grpo": |
| 1467 | kwargs["grpo_group_size"] = args.grpo_group_size |
| 1468 | kwargs["grpo_clip"] = args.grpo_clip |
| 1469 | kwargs["grpo_lr"] = args.lr |
| 1470 | elif args.method == "galore": |
| 1471 | kwargs["galore_lr"] = args.lr |
| 1472 | kwargs["galore_rank"] = args.galore_rank |
| 1473 | |
| 1474 | trainer = MojoLlamaTrainer( |
| 1475 | model_path=args.model, |
| 1476 | data_path=args.data, |
| 1477 | method=args.method, |
| 1478 | lora_rank=args.lora_rank, |
| 1479 | lora_alpha=args.lora_alpha, |
| 1480 | lr=args.lr, |
| 1481 | lr_min=args.lr_min, |
| 1482 | weight_decay=args.weight_decay, |
| 1483 | epochs=args.epochs, |
| 1484 | batch_size=args.batch_size, |
| 1485 | max_seq_length=args.max_seq_length, |
| 1486 | output_path=args.output, |
| 1487 | seed=args.seed, |
| 1488 | warmup_steps=args.warmup_steps, |
| 1489 | max_grad_norm=args.max_grad_norm, |
| 1490 | dataset_format=args.dataset_format, |
| 1491 | max_samples=args.max_samples, |
| 1492 | template=args.template, |
| 1493 | log_interval=args.log_interval, |
| 1494 | eval_split=args.eval_split, |
| 1495 | save_steps=args.save_steps, |
| 1496 | checkpoint_dir=args.checkpoint_dir, |
| 1497 | resume_from=args.resume_from, |
| 1498 | **kwargs, |
| 1499 | ) |
| 1500 | |
| 1501 | trainer.train() |
| 1502 | |
| 1503 | |
| 1504 | if __name__ == "__main__": |
| 1505 | main() |