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 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
"""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)