"""GRPO training pipeline for guac-coder. Integrates npcpy's GRPO utilities with guac-coder's 13-rule reward function (the legacy 12-rule path is still available). Designed for the MLX backend (Apple Silicon) with a torch fallback. """ import importlib.util import json import logging import os import pickle import time from typing import Callable, Dict, List, Optional, Tuple from guac_coder.config import GRPOConfig, RewardConfig from guac_coder.data import load_data, load_research_tasks, prepare_training_examples from guac_coder.grpo_rewards import combined_grpo_reward, compute_grpo_rewards from guac_coder.rewards import compute_total_reward logger = logging.getLogger(__name__) # --------------------------------------------------------------------------- # Backend detection / imports # --------------------------------------------------------------------------- # The mlx / torch modules themselves are imported lazily inside the update # functions; here we only need to know whether each backend is importable. HAS_MLX = importlib.util.find_spec("mlx") is not None HAS_TORCH = importlib.util.find_spec("torch") is not None if not HAS_MLX: logger.info("MLX not available; falling back to torch.") # --------------------------------------------------------------------------- # Model utilities # --------------------------------------------------------------------------- def load_model_and_tokenizer(model_name: str, backend: str = "auto"): """Load a causal LM and tokenizer. ``backend`` is one of ``auto``, ``mlx`` or ``torch``. ``auto`` prefers mlx-lm when importable (Apple Silicon) and falls back to transformers. """ if backend not in ("auto", "mlx", "torch"): raise ValueError(f"unknown backend: {backend}") if backend in ("auto", "mlx") and HAS_MLX: try: from mlx_lm import load model, tokenizer = load(model_name) return model, tokenizer, "mlx" except Exception as exc: logger.warning("mlx-lm load failed: %s", exc) if backend == "mlx": raise RuntimeError(f"Failed to load {model_name} with mlx-lm: {exc}") if backend == "mlx": raise RuntimeError( "backend='mlx' requested but mlx-lm is not available. " "Install with: pip install -e '.[mlx]'" ) try: from transformers import AutoModelForCausalLM, AutoTokenizer tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True) model = AutoModelForCausalLM.from_pretrained( model_name, trust_remote_code=True, torch_dtype="auto", device_map="auto", ) return model, tokenizer, "torch" except Exception as exc: raise RuntimeError(f"Failed to load model {model_name}: {exc}") def generate_group( model, tokenizer, prompt: str, group_size: int, temperature: float, max_new_tokens: int, backend: str, ) -> List[str]: """Generate a group of candidate completions.""" completions: List[str] = [] if backend == "mlx": try: from mlx_lm import generate for _ in range(group_size): text = generate( model, tokenizer, prompt=prompt, temp=temperature, max_tokens=max_new_tokens, verbose=False, ) completions.append(text) except Exception as exc: logger.warning("MLX generation failed: %s", exc) else: device = next(model.parameters()).device inputs = tokenizer(prompt, return_tensors="pt").to(device) for _ in range(group_size): outputs = model.generate( **inputs, max_new_tokens=max_new_tokens, temperature=temperature, do_sample=True, ) text = tokenizer.decode(outputs[0], skip_special_tokens=True) completions.append(text) return completions # --------------------------------------------------------------------------- # Checkpointing # --------------------------------------------------------------------------- def save_checkpoint( path: str, iteration: int, model_state, optimizer_state=None, metrics: Optional[Dict] = None, ) -> None: """Save a resumable checkpoint.""" ckpt = { "iteration": iteration, "model_state": model_state, "optimizer_state": optimizer_state, "metrics": metrics or {}, "timestamp": time.time(), } os.makedirs(os.path.dirname(path) or ".", exist_ok=True) with open(path, "wb") as fh: pickle.dump(ckpt, fh) logger.info("Checkpoint saved: %s", path) def load_checkpoint(path: str) -> Dict: """Load checkpoint dict.""" with open(path, "rb") as fh: ckpt = pickle.load(fh) logger.info("Checkpoint loaded: %s (iteration %d)", path, ckpt.get("iteration", 0)) return ckpt # --------------------------------------------------------------------------- # GRPO update (re-adapted from npcpy/ft/rl.py) # --------------------------------------------------------------------------- def grpo_update_mlx( model, tokenizer, prompt: str, completions: List[str], rewards: List[float], epsilon: float = 0.2, beta: float = 0.01, learning_rate: float = 1e-5, ) -> float: """Perform one GRPO update on MLX. Returns the loss value. """ import mlx.core as mx import mlx.nn as nn # Compute advantages per completion rewards_arr = mx.array(rewards) mean_reward = mx.mean(rewards_arr) std_reward = mx.std(rewards_arr) + 1e-8 advantages = (rewards_arr - mean_reward) / std_reward # Tokenize prompt once prompt_ids = mx.array(tokenizer.encode(prompt)) prompt_len = prompt_ids.shape[0] losses = [] for comp, adv in zip(completions, advantages): full_text = prompt + comp token_ids = tokenizer.encode(full_text) input_ids = mx.array(token_ids) # Forward pass logits = model(input_ids[None, :]) log_probs = nn.log_softmax(logits, axis=-1) # Extract log probs for generated tokens only gen_slice = slice(prompt_len, None) gen_log_probs = log_probs[0, gen_slice, :] gen_tokens = input_ids[gen_slice] # Token-level log probs token_log_probs = gen_log_probs[mx.arange(gen_tokens.shape[0]), gen_tokens] policy_log_prob = mx.sum(token_log_probs) # Simple surrogate loss: maximize policy_log_prob weighted by advantage # For a full implementation we'd keep old policy log probs for ratio clipping. # Here we approximate with a single-sample estimate. loss = -policy_log_prob * adv losses.append(loss) total_loss = mx.stack(losses) avg_loss = mx.mean(total_loss) # Compute gradients and update # In MLX we can use value_and_grad # For brevity, we use a simple SGD-style update via the model's parameters def loss_fn(params): model.update(params) return avg_loss # NOTE: In production, use proper MLX optimizer (e.g. nn.optim.Adam) # This is a simplified placeholder showing the structure. lvalue = float(avg_loss.item()) return lvalue def grpo_update_torch( model, tokenizer, prompt: str, completions: List[str], rewards: List[float], epsilon: float = 0.2, beta: float = 0.01, learning_rate: float = 1e-5, ) -> float: """Perform one GRPO update on torch.""" import torch import torch.nn.functional as F optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) device = next(model.parameters()).device rewards_t = torch.tensor(rewards, dtype=torch.float32, device=device) mean_r = rewards_t.mean() std_r = rewards_t.std() + 1e-8 advantages = (rewards_t - mean_r) / std_r prompt_ids = tokenizer.encode(prompt, return_tensors="pt").to(device) prompt_len = prompt_ids.shape[1] total_loss = 0.0 for comp, adv in zip(completions, advantages): full_text = prompt + comp inputs = tokenizer(full_text, return_tensors="pt").to(device) input_ids = inputs["input_ids"] outputs = model(input_ids, labels=input_ids) shift_logits = outputs.logits[:, prompt_len:-1, :].contiguous() shift_labels = input_ids[:, prompt_len + 1 :].contiguous() log_probs = F.log_softmax(shift_logits, dim=-1) token_log_probs = log_probs.gather(2, shift_labels.unsqueeze(-1)).squeeze(-1) seq_log_prob = token_log_probs.mean() loss = -seq_log_prob * adv total_loss += loss avg_loss = total_loss / len(completions) optimizer.zero_grad() avg_loss.backward() optimizer.step() return float(avg_loss.item()) # --------------------------------------------------------------------------- # Reward scoring # --------------------------------------------------------------------------- def score_completion( code: str, get_llm_response_fn: Callable, reward_cfg: RewardConfig, use_grpo_rewards: bool = True, rater: Optional[str] = None, ) -> Tuple[float, Dict]: """Score a single completion, returning (scalar_reward, details). The rater is chosen by ``rater`` (falling back to ``reward_cfg.rater``): * ``"static"`` - the 13 regex/AST rules in :mod:`guac_coder.grpo_rewards`. * ``"decision"`` - the same 13 rules, but judged by a decision model (Ollama ``/v1/systemone``, e.g. ``clef``) via :mod:`guac_coder.decision_judge`. One request, calibrated probabilities. * ``"llm"`` - the legacy generative LLM-as-judge in :mod:`guac_coder.rewards` (static + LLM blend). Details always expose ``total``, ``static`` and ``llm`` keys so metric logging stays identical across all three paths, plus ``rater`` so a metrics file records which one produced the numbers. """ effective = (rater or getattr(reward_cfg, "rater", "static") or "static").lower() if effective not in ("static", "decision", "llm"): raise ValueError( f"unknown rater {effective!r}; expected 'static', 'decision' or 'llm'" ) if effective == "decision": from guac_coder.decision_judge import ( combined_decision_reward, compute_decision_rewards, ) judge_cfg = reward_cfg.decision_judge_config() rules = compute_decision_rewards(code, cfg=judge_cfg) total = combined_decision_reward(code, cfg=judge_cfg) return total, { "total": total, "static": 0.0, "llm": 0.0, "rater": "decision", "rules": rules, } if effective == "static" and use_grpo_rewards: rules = compute_grpo_rewards(code) total = combined_grpo_reward(code) return total, { "total": total, "static": total, "llm": 0.0, "rater": "static", "rules": rules, } result = compute_total_reward(code, get_llm_response_fn, reward_cfg) result.setdefault("rater", "llm") return float(result["total"]), result # --------------------------------------------------------------------------- # Main training loop # --------------------------------------------------------------------------- def train_grpo( cfg: GRPOConfig, reward_cfg: RewardConfig, get_llm_response_fn: Callable, data_path: Optional[str] = None, use_grpo_rewards: bool = True, rater: Optional[str] = None, ) -> None: """Run GRPO training loop for guac-coder. Parameters ---------- cfg : GRPOConfig Training configuration. reward_cfg : RewardConfig Reward function configuration. get_llm_response_fn : callable Function matching get_llm_response signature for LLM judge. data_path : str, optional Path to JSONL training data. If None, uses built-in tasks. use_grpo_rewards : bool If True (default), score with the 13 per-rule rewards in guac_coder.grpo_rewards. If False, use the legacy rewards.py path (static analysis + optional LLM judge via get_llm_response_fn). rater : str, optional Scoring backend: ``"static"``, ``"decision"`` (Ollama decision model such as ``clef``) or ``"llm"``. Defaults to ``reward_cfg.rater``. """ os.makedirs(cfg.output_dir, exist_ok=True) # Setup logging log_path = os.path.join(cfg.output_dir, "training.log") logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", handlers=[ logging.FileHandler(log_path), logging.StreamHandler(), ], ) # Load data if data_path and os.path.isfile(data_path): examples = load_data(data_path) logger.info("Loaded %d examples from %s", len(examples), data_path) else: tasks = load_research_tasks() examples = list(prepare_training_examples(tasks)) logger.info("Using %d built-in research tasks", len(examples)) # Load model logger.info("Loading model: %s", cfg.model_name) model, tokenizer, backend = load_model_and_tokenizer( cfg.model_name, getattr(cfg, "backend", "auto") ) logger.info("Backend: %s", backend) iteration = 0 if cfg.resume_from_checkpoint and os.path.isfile(cfg.resume_from_checkpoint): ckpt = load_checkpoint(cfg.resume_from_checkpoint) iteration = ckpt.get("iteration", 0) # Model state restoration would happen here (backend-specific) logger.info("Resumed from iteration %d", iteration) # Metrics log metrics_path = os.path.join(cfg.output_dir, "metrics.jsonl") for it in range(iteration, cfg.num_iterations): example = examples[it % len(examples)] prompt = example["prompt"] # Generate group of completions logger.debug("Iteration %d: generating group of %d", it, cfg.group_size) completions = generate_group( model, tokenizer, prompt, cfg.group_size, cfg.temperature, cfg.max_new_tokens, backend, ) # Compute rewards rewards = [] reward_details = [] for comp in completions: # Strip prompt prefix if model echoes it code = comp if code.startswith(prompt): code = code[len(prompt) :].strip() total, result = score_completion( code, get_llm_response_fn, reward_cfg, use_grpo_rewards, rater=rater, ) rewards.append(total) reward_details.append(result) # Log reward stats mean_reward = sum(rewards) / len(rewards) max_reward = max(rewards) min_reward = min(rewards) logger.info( "Iter %d | mean_reward=%.3f max=%.3f min=%.3f", it, mean_reward, max_reward, min_reward, ) # GRPO update if backend == "mlx": loss = grpo_update_mlx( model, tokenizer, prompt, completions, rewards, cfg.epsilon, cfg.beta, cfg.learning_rate, ) else: loss = grpo_update_torch( model, tokenizer, prompt, completions, rewards, cfg.epsilon, cfg.beta, cfg.learning_rate, ) logger.info("Iter %d | loss=%.4f", it, loss) # Write metrics incrementally metric_entry = { "iteration": it, "loss": loss, "mean_reward": mean_reward, "max_reward": max_reward, "min_reward": min_reward, "rewards": rewards, "use_grpo_rewards": use_grpo_rewards, "rater": (rater or getattr(reward_cfg, "rater", "static")), "reward_details": [ { "total": rd["total"], "static": rd["static"], "llm": rd["llm"], } for rd in reward_details ], } with open(metrics_path, "a", encoding="utf-8") as fh: fh.write(json.dumps(metric_entry) + "\n") # Checkpoint if (it + 1) % cfg.checkpoint_interval == 0: ckpt_path = os.path.join(cfg.output_dir, f"checkpoint_{it:05d}.pkl") # Serialize model state in backend-appropriate way model_state = ( model.state_dict() if hasattr(model, "state_dict") else getattr(model, "parameters", lambda: {})() ) save_checkpoint(ckpt_path, it, model_state, metrics=metric_entry) logger.info("Training complete. Output in %s", cfg.output_dir)