API Reference for model-training

model_training

Training pipelines for LoRA fine-tuning and trajectory management.

Classes

D2LTrainConfig

Bases: BaseModel

Pydantic model for D2L training hyperparameters.

Enables validation, JSON serialization (for checkpoint storage), and .model_dump() for MLflow experiment logging.

Attributes:

Name Type Description
model_config_name str

Registry lookup key (e.g. "qwen3.5-9b"). Used to resolve base_model_name from the model registry when not set.

base_model_name str

HuggingFace model name for the student/teacher base.

sakana_checkpoint_path str

Path to the Sakana hypernet checkpoint.

num_steps int

Total training steps.

lr float

Learning rate for AdamW optimizer.

alpha float

Blending weight for KL vs CE loss (1.0 = pure KL, 0.0 = pure CE).

temperature float

Softmax temperature for KL divergence computation.

checkpoint_every int

Steps between lightweight checkpoint saves.

full_checkpoint_every int

Steps between full checkpoint saves (incl. optimizer).

checkpoint_dir str

Directory for checkpoint output.

experiment_name str

MLflow experiment name.

dry_run bool

If True, validate tensor shapes then exit.

smoke_test bool

If True, run 5 steps and verify loss trend.

dataset_path str | None

Path to training JSONL file (required for full training).

grad_clip float

Gradient clipping max norm.

warmup_steps int

Number of linear LR warmup steps.

lora_r int

LoRA rank.

max_length int

Maximum tokenizer sequence length.

Functions
model_post_init
model_post_init(__context: Any) -> None

Resolve base_model_name from registry when not explicitly set.

Source code in libs/model-training/src/model_training/d2l_train.py
117
118
119
120
121
122
123
def model_post_init(self, __context: Any) -> None:
    """Resolve base_model_name from registry when not explicitly set."""
    if not self.base_model_name:
        from model_training.model_configs import ModelRegistry

        mc = ModelRegistry.default().get(self.model_config_name)
        object.__setattr__(self, "base_model_name", mc.model_id)

ModelConfig

Bases: BaseModel

Immutable configuration for a base model + training defaults.

Attributes:

Name Type Description
canonical_name str

Short lookup key (e.g. "qwen3.5-9b").

model_id str

HuggingFace repository ID.

warm_start_adapter_id str | None

Pre-trained PEFT adapter to continue from.

default_lora_rank int

LoRA rank for fresh initialization.

default_lora_alpha int

LoRA alpha scaling factor.

attn_implementation str | None

Attention implementation override (e.g. "eager").

expected_num_layers int

Expected total layer count for probe validation.

expected_hidden_size int

Expected hidden dimension for probe validation.

gradient_accumulation_steps int

Training gradient accumulation default.

lr_scheduler_type str

Learning rate scheduler type.

epochs int

Number of training epochs.

quirks dict[str, Any]

Model-specific overrides and notes.

ModelRegistry

ModelRegistry()

Registry of named ModelConfig presets.

Usage

registry = ModelRegistry.default() config = registry.get("qwen3.5-9b")

Initialize an empty model registry.

Source code in libs/model-training/src/model_training/model_configs.py
65
66
67
def __init__(self) -> None:
    """Initialize an empty model registry."""
    self._presets: dict[str, ModelConfig] = {}
Functions
register
register(config: ModelConfig) -> None

Register a model configuration preset.

Parameters:

Name Type Description Default
config ModelConfig

ModelConfig to register under its canonical_name.

required
Source code in libs/model-training/src/model_training/model_configs.py
69
70
71
72
73
74
75
def register(self, config: ModelConfig) -> None:
    """Register a model configuration preset.

    Args:
        config: ModelConfig to register under its canonical_name.
    """
    self._presets[config.canonical_name] = config
get
get(name: str) -> ModelConfig

Look up a model configuration by canonical name.

Parameters:

Name Type Description Default
name str

Canonical model name (e.g. "qwen3.5-9b").

required

Returns:

Type Description
ModelConfig

The registered ModelConfig.

Raises:

Type Description
KeyError

If no preset exists for the given name.

Source code in libs/model-training/src/model_training/model_configs.py
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
def get(self, name: str) -> ModelConfig:
    """Look up a model configuration by canonical name.

    Args:
        name: Canonical model name (e.g. "qwen3.5-9b").

    Returns:
        The registered ModelConfig.

    Raises:
        KeyError: If no preset exists for the given name.
    """
    if name not in self._presets:
        available = ", ".join(sorted(self._presets.keys()))
        raise KeyError(
            f"No model config registered for {name!r}. Available: {available}"
        )
    return self._presets[name]
list_names
list_names() -> list[str]

Return sorted list of registered model names.

Source code in libs/model-training/src/model_training/model_configs.py
96
97
98
def list_names(self) -> list[str]:
    """Return sorted list of registered model names."""
    return sorted(self._presets.keys())
default classmethod
default() -> ModelRegistry

Return singleton registry with built-in presets.

Presets
  • qwen3.5-9b: Qwen3.5-9B with DeltaCoder warm-start
  • qwen3-coder-next: Qwen3-Coder-Next (hybrid attention)
Source code in libs/model-training/src/model_training/model_configs.py
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
@classmethod
def default(cls) -> ModelRegistry:
    """Return singleton registry with built-in presets.

    Presets:
        - qwen3.5-9b: Qwen3.5-9B with DeltaCoder warm-start
        - qwen3-coder-next: Qwen3-Coder-Next (hybrid attention)
    """
    if cls._default_instance is not None:
        return cls._default_instance

    registry = cls()

    registry.register(
        ModelConfig(
            canonical_name="qwen3.5-9b",
            model_id="Qwen/Qwen3.5-9B",
            warm_start_adapter_id=("danielcherubini/Qwen3.5-DeltaCoder-9B"),
            default_lora_rank=64,
            default_lora_alpha=32,
            attn_implementation="eager",
            expected_num_layers=32,
            expected_hidden_size=4096,
            gradient_accumulation_steps=16,
            lr_scheduler_type="constant",
            epochs=3,
            quirks={
                "flash_attention_warning": (
                    "Flash + sample packing causes loss collapse"
                ),
            },
        )
    )

    registry.register(
        ModelConfig(
            canonical_name="qwen3-coder-next",
            model_id="Qwen/Qwen3-Coder-Next",
            warm_start_adapter_id=None,
            default_lora_rank=8,
            default_lora_alpha=16,
            attn_implementation=None,
            expected_num_layers=48,
            expected_hidden_size=2048,
            gradient_accumulation_steps=4,
            lr_scheduler_type="cosine",
            epochs=3,
        )
    )

    cls._default_instance = registry
    return registry

Functions

train_d2l_qwen3

train_d2l_qwen3(
    config: D2LTrainConfig,
    *,
    kill_switch_evaluate_fn: Any = None,
) -> dict[str, Any]

Run KL-divergence context distillation training.

Three execution modes controlled by config flags: - dry_run=True: Validate shapes with single forward pass, no optimizer step. - smoke_test=True: Run min(num_steps, 5) steps, assert finite decreasing loss. - default: Full training from dataset with checkpointing and MLflow tracking.

Parameters:

Name Type Description Default
config D2LTrainConfig

Training configuration.

required
kill_switch_evaluate_fn Any

Zero-arg callable returning the current Pass@1 as a float. Required when config.kill_switch_enabled is True; ignored otherwise. Inject a closure built via :func:model_training.kill_switch.build_benchmark_evaluate_fn for production runs, or a mock for tests.

None

Returns:

Type Description
dict[str, Any]

Dictionary with training results: - final_loss: Loss at the last step. - best_loss: Lowest loss seen during training. - num_steps_completed: Number of training steps completed. - checkpoint_dir: Path to checkpoint directory. - shape_summary (dry_run only): Tensor shape validation results. - kill_switch_triggered: True when training halted early due to Pass@1 regression (only present when the kill-switch is enabled).

Source code in libs/model-training/src/model_training/d2l_train.py
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
def train_d2l_qwen3(  # noqa: C901
    config: D2LTrainConfig,
    *,
    kill_switch_evaluate_fn: Any = None,
) -> dict[str, Any]:
    """Run KL-divergence context distillation training.

    Three execution modes controlled by config flags:
    - dry_run=True: Validate shapes with single forward pass, no optimizer step.
    - smoke_test=True: Run min(num_steps, 5) steps, assert finite decreasing loss.
    - default: Full training from dataset with checkpointing and MLflow tracking.

    Args:
        config: Training configuration.
        kill_switch_evaluate_fn: Zero-arg callable returning the current Pass@1
            as a float. Required when ``config.kill_switch_enabled`` is True;
            ignored otherwise. Inject a closure built via
            :func:`model_training.kill_switch.build_benchmark_evaluate_fn` for
            production runs, or a mock for tests.

    Returns:
        Dictionary with training results:
            - final_loss: Loss at the last step.
            - best_loss: Lowest loss seen during training.
            - num_steps_completed: Number of training steps completed.
            - checkpoint_dir: Path to checkpoint directory.
            - shape_summary (dry_run only): Tensor shape validation results.
            - kill_switch_triggered: True when training halted early due to
              Pass@1 regression (only present when the kill-switch is enabled).
    """
    import mlflow  # noqa: PLC0415
    import torch  # noqa: PLC0415
    from ctx_to_lora.modeling.hypernet import HyperLoRA  # noqa: PLC0415
    from torch.nn.utils import clip_grad_norm_  # noqa: PLC0415
    from torch.optim import AdamW  # noqa: PLC0415
    from torch.optim.lr_scheduler import (  # noqa: PLC0415
        CosineAnnealingLR,
        LinearLR,
        SequentialLR,
    )
    from transformers import AutoModelForCausalLM, AutoTokenizer  # noqa: PLC0415

    from model_training.d2l_config import build_hypernet_config  # noqa: PLC0415
    from model_training.d2l_data import (  # noqa: PLC0415
        generate_needle_dataset,
        load_jsonl,
        split_by_task_id,
    )
    from model_training.sakana_d2l import (  # noqa: PLC0415
        get_aggregator_config,
        transfer_aggregator_weights,
    )

    # Mode dispatch: dry_run exits after shape validation
    if config.dry_run:
        shape_summary = _dry_run_validate_shapes(config)
        return {"shape_summary": shape_summary, "status": "dry_run_complete"}

    # Smoke test caps steps at 5
    if config.smoke_test:
        config = config.model_copy(update={"num_steps": min(config.num_steps, 5)})

    # Guard: require probe cache when not in smoke_test mode.
    # smoke_test uses generate_needle_dataset and may not have a real probe cache.
    if not config.smoke_test:
        _require_probe_cache(config.model_config_name)

    num_steps = config.num_steps
    warmup_steps = config.warmup_steps

    # Load tokenizer and base model
    logger.info("Loading tokenizer: %s", config.base_model_name)
    tokenizer = AutoTokenizer.from_pretrained(config.base_model_name)

    logger.info("Loading base model: %s", config.base_model_name)
    base_model = AutoModelForCausalLM.from_pretrained(
        config.base_model_name,
        output_hidden_states=True,
    ).eval()

    # Build hypernet config with aggregator config from checkpoint
    logger.info(
        "Building hypernet config from checkpoint: %s",
        config.sakana_checkpoint_path,
    )
    hc = build_hypernet_config(
        config.model_config_name,
        aggregator_config=get_aggregator_config(config.sakana_checkpoint_path),
        lora_r=config.lora_r,
    )

    # Create hypernet and transfer aggregator weights (freezes aggregator)
    hypernet = HyperLoRA(hc).to(torch.float32)
    hypernet = transfer_aggregator_weights(hypernet, config.sakana_checkpoint_path)
    hypernet.train()

    # Device selection: cuda > mps > cpu
    from shared.hardware import get_best_device  # noqa: PLC0415

    device = torch.device(get_best_device())
    logger.info("Using device: %s", device)
    base_model = base_model.to(device)
    hypernet = hypernet.to(device)

    # Optimizer: only trainable params (head + projections, not frozen aggregator)
    trainable_params = [p for p in hypernet.parameters() if p.requires_grad]
    logger.info("Trainable params: %d", sum(p.numel() for p in trainable_params))
    optimizer = AdamW(trainable_params, lr=config.lr)

    # Scheduler: linear warmup → cosine annealing
    scheduler = SequentialLR(
        optimizer,
        schedulers=[
            LinearLR(optimizer, start_factor=0.01, total_iters=warmup_steps),
            CosineAnnealingLR(
                optimizer,
                T_max=max(1, num_steps - warmup_steps),
                eta_min=1e-6,
            ),
        ],
        milestones=[warmup_steps],
    )

    # Data loading
    if config.smoke_test or config.dataset_path is None:
        records = generate_needle_dataset(n=20)
        logger.info("Using needle dataset (%d records)", len(records))
    else:
        all_records = load_jsonl(config.dataset_path)
        records, _ = split_by_task_id(all_records)
        logger.info(
            "Loaded %d training records from %s",
            len(records),
            config.dataset_path,
        )

    if not records:
        raise ValueError("No training records loaded; cannot train on empty dataset.")

    # MLflow setup and training loop
    _setup_mlflow(config)

    best_loss = float("inf")
    final_loss = float("inf")
    step_losses: list[float] = []

    # Kill-switch setup (Plan A follow-up). Disabled by default.
    from model_training.kill_switch import (  # noqa: PLC0415
        KillSwitchConfig,
        KillSwitchState,
        maybe_run_kill_switch,
    )

    ks_config = KillSwitchConfig(
        enabled=config.kill_switch_enabled,
        step_cadence=config.kill_switch_step_cadence,
        benchmark_id=config.kill_switch_benchmark_id,
        max_samples=config.kill_switch_max_samples,
        delta=config.kill_switch_delta,
    )
    ks_state = KillSwitchState()
    if ks_config.enabled and kill_switch_evaluate_fn is None:
        raise ValueError(
            "kill_switch_enabled=True requires kill_switch_evaluate_fn; "
            "build one via model_training.kill_switch.build_benchmark_evaluate_fn."
        )
    kill_switch_halted = False

    with mlflow.start_run(run_name=f"{config.experiment_name}-step{num_steps}"):
        mlflow.log_params(config.model_dump())

        for step in range(1, num_steps + 1):
            record = records[(step - 1) % len(records)]

            loss, metrics = _training_step(
                record=record,
                base_model=base_model,
                tokenizer=tokenizer,
                hypernet=hypernet,
                hc=hc,
                config=config,
            )

            loss.backward()
            clip_grad_norm_(trainable_params, config.grad_clip)
            optimizer.step()
            scheduler.step()
            optimizer.zero_grad()

            step_loss = metrics["total_loss"]
            step_losses.append(step_loss)
            final_loss = step_loss
            if step_loss < best_loss:
                best_loss = step_loss

            mlflow.log_metrics(metrics, step=step)
            logger.info(
                "Step %d/%d — loss=%.4f (kl=%.4f, ce=%.4f)",
                step,
                num_steps,
                metrics["total_loss"],
                metrics["kl_loss"],
                metrics["ce_loss"],
            )

            # Tiered checkpointing
            if step % config.full_checkpoint_every == 0:
                ckpt_path = _save_checkpoint(
                    step=step,
                    hypernet=hypernet,
                    optimizer=optimizer,
                    scheduler=scheduler,
                    config=config,
                    hc=hc,
                    best_loss=best_loss,
                    full=True,
                )
                mlflow.log_artifact(str(ckpt_path))
            elif step % config.checkpoint_every == 0:
                ckpt_path = _save_checkpoint(
                    step=step,
                    hypernet=hypernet,
                    optimizer=optimizer,
                    scheduler=scheduler,
                    config=config,
                    hc=hc,
                    best_loss=best_loss,
                    full=False,
                )
                mlflow.log_artifact(str(ckpt_path))

            # Kill-switch: evaluate Pass@1 at cadence and halt on regression.
            if maybe_run_kill_switch(
                step=step,
                config=ks_config,
                state=ks_state,
                evaluate_fn=kill_switch_evaluate_fn,
            ):
                kill_switch_halted = True
                _nan = float("nan")
                _last = (
                    ks_state.last_pass_at_1
                    if ks_state.last_pass_at_1 is not None
                    else _nan
                )
                _base = ks_state.baseline if ks_state.baseline is not None else _nan
                logger.error(
                    "Kill-switch halted training at step %d: "
                    "pass_at_1=%.3f baseline=%.3f delta=%.3f",
                    step,
                    _last,
                    _base,
                    ks_config.delta,
                )
                break

    # Smoke test assertions
    if config.smoke_test:
        for i, sl in enumerate(step_losses):
            assert torch.isfinite(torch.tensor(sl)), (  # noqa: S101
                f"Smoke test: loss at step {i + 1} is not finite: {sl}"
            )
        assert step_losses[-1] < step_losses[0], (  # noqa: S101
            f"Smoke test: final loss {step_losses[-1]:.4f} not less than "
            f"initial loss {step_losses[0]:.4f}"
        )
        assert any(p.grad is not None for p in trainable_params), (  # noqa: S101
            "Smoke test: no trainable param has non-None gradient after training"
        )

    result: dict[str, Any] = {
        "final_loss": final_loss,
        "best_loss": best_loss,
        "num_steps_completed": num_steps,
        "checkpoint_dir": config.checkpoint_dir,
    }
    if ks_config.enabled:
        result["kill_switch_triggered"] = kill_switch_halted
        result["kill_switch_baseline"] = ks_state.baseline
        result["kill_switch_last_pass_at_1"] = ks_state.last_pass_at_1
    return result

format_for_sft

format_for_sft(
    trajectory: dict[str, Any],
) -> list[dict[str, str]]

Convert a trajectory into SFT-compatible chat format.

Only successful trajectories (outcome == 'success') produce output. Extracts the final step where tests_passed is True as the assistant message.

Parameters:

Name Type Description Default
trajectory dict[str, Any]

A trajectory dict as returned by load_trajectory.

required

Returns:

Type Description
list[dict[str, str]]

A list of 3 message dicts ([system, user, assistant]) for successful

list[dict[str, str]]

trajectories, or an empty list if the trajectory did not succeed.

Source code in libs/model-training/src/model_training/trajectory.py
 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
def format_for_sft(trajectory: dict[str, Any]) -> list[dict[str, str]]:
    """Convert a trajectory into SFT-compatible chat format.

    Only successful trajectories (outcome == 'success') produce output.
    Extracts the final step where tests_passed is True as the assistant message.

    Args:
        trajectory: A trajectory dict as returned by load_trajectory.

    Returns:
        A list of 3 message dicts ([system, user, assistant]) for successful
        trajectories, or an empty list if the trajectory did not succeed.
    """
    if trajectory.get("outcome") != "success":
        return []

    steps: list[dict[str, Any]] = trajectory.get("steps", [])
    successful_step = next(
        (s for s in reversed(steps) if s.get("tests_passed")),
        None,
    )

    if successful_step is None:
        return []

    task_description: str = trajectory.get("task_description", "")
    generated_code: str = successful_step.get("generated_code", "")

    return [
        {"role": "system", "content": SYSTEM_PROMPT},
        {"role": "user", "content": task_description},
        {"role": "assistant", "content": generated_code},
    ]

load_trajectory

load_trajectory(trajectory_id: str) -> dict[str, Any]

Load a stored trajectory by session ID.

Parameters:

Name Type Description Default
trajectory_id str

The session ID used as the filename (without .json).

required

Returns:

Type Description
dict[str, Any]

A dict containing the full trajectory data including steps and metadata.

Raises:

Type Description
FileNotFoundError

If no trajectory file exists for the given ID.

Source code in libs/model-training/src/model_training/trajectory.py
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def load_trajectory(trajectory_id: str) -> dict[str, Any]:
    """Load a stored trajectory by session ID.

    Args:
        trajectory_id: The session ID used as the filename (without .json).

    Returns:
        A dict containing the full trajectory data including steps and metadata.

    Raises:
        FileNotFoundError: If no trajectory file exists for the given ID.
    """
    trajectory_dir = _get_trajectory_dir()
    file_path = trajectory_dir / f"{trajectory_id}.json"
    # Let FileNotFoundError propagate naturally if file does not exist
    return json.loads(file_path.read_text())  # type: ignore[no-any-return]

record_trajectory

record_trajectory(
    session_id: str,
    steps: list[dict[str, Any]],
    outcome: Optional[str] = None,
    *,
    task_description: str = "",
    task_type: str = "",
    adapter_ids: list[str] | None = None,
) -> dict[str, Any]

Persist a coding session trajectory to disk for future distillation.

Parameters:

Name Type Description Default
session_id str

Unique identifier for the coding session.

required
steps list[dict[str, Any]]

List of step dicts, each containing attempt results.

required
outcome Optional[str]

Final session result ('success', 'exhausted', or None).

None
task_description str

Natural language description of the coding task.

''
task_type str

Category of task (e.g. 'function', 'class', 'refactor').

''
adapter_ids list[str] | None

LoRA adapter IDs used during the session.

None

Returns:

Type Description
dict[str, Any]

A dict with 'session_id' and 'file_path' keys.

Source code in libs/model-training/src/model_training/trajectory.py
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
def record_trajectory(
    session_id: str,
    steps: list[dict[str, Any]],
    outcome: Optional[str] = None,
    *,
    task_description: str = "",
    task_type: str = "",
    adapter_ids: list[str] | None = None,
) -> dict[str, Any]:
    """Persist a coding session trajectory to disk for future distillation.

    Args:
        session_id: Unique identifier for the coding session.
        steps: List of step dicts, each containing attempt results.
        outcome: Final session result ('success', 'exhausted', or None).
        task_description: Natural language description of the coding task.
        task_type: Category of task (e.g. 'function', 'class', 'refactor').
        adapter_ids: LoRA adapter IDs used during the session.

    Returns:
        A dict with 'session_id' and 'file_path' keys.
    """
    trajectory_dir = _get_trajectory_dir()
    trajectory_dir.mkdir(parents=True, exist_ok=True)

    file_path = trajectory_dir / f"{session_id}.json"
    timestamp = datetime.now(tz=timezone.utc).isoformat()

    trajectory: dict[str, Any] = {
        "session_id": session_id,
        "task_description": task_description,
        "task_type": task_type,
        "adapter_ids": adapter_ids if adapter_ids is not None else [],
        "outcome": outcome,
        "timestamp": timestamp,
        "steps": steps,
    }

    file_path.write_text(json.dumps(trajectory, indent=2))

    return {"session_id": session_id, "file_path": str(file_path)}

Modules

config

Training configuration for LoRA fine-tuning.

No GPU imports required — this module is pure dict construction and validation.

Functions
get_training_config
get_training_config(
    task_type: str,
    rank: int = 64,
    epochs: int = 3,
    learning_rate: float = 0.0002,
) -> dict[str, Any]

Return a training configuration dict with hyperparameters.

Generates a configuration appropriate for the given task type, with sensible defaults for QLoRA fine-tuning.

Parameters:

Name Type Description Default
task_type str

Task category (e.g. 'bug-fix', 'feature-impl').

required
rank int

LoRA rank for the adapter.

64
epochs int

Number of training epochs.

3
learning_rate float

Learning rate for the optimizer.

0.0002

Returns:

Type Description
dict[str, Any]

A dict containing all training hyperparameters.

Example

config = get_training_config("bug-fix", rank=64, epochs=3) config["task_type"] 'bug-fix'

Source code in libs/model-training/src/model_training/config.py
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
def get_training_config(
    task_type: str,
    rank: int = 64,
    epochs: int = 3,
    learning_rate: float = 2e-4,
) -> dict[str, Any]:
    """Return a training configuration dict with hyperparameters.

    Generates a configuration appropriate for the given task type,
    with sensible defaults for QLoRA fine-tuning.

    Args:
        task_type: Task category (e.g. 'bug-fix', 'feature-impl').
        rank: LoRA rank for the adapter.
        epochs: Number of training epochs.
        learning_rate: Learning rate for the optimizer.

    Returns:
        A dict containing all training hyperparameters.

    Example:
        >>> config = get_training_config("bug-fix", rank=64, epochs=3)
        >>> config["task_type"]
        'bug-fix'
    """
    return {
        "task_type": task_type,
        "rank": rank,
        "alpha": 2 * rank,
        "epochs": epochs,
        "learning_rate": learning_rate,
        "warmup_ratio": 0.03,
        "lr_scheduler_type": "cosine",
        "bf16": True,
        "per_device_train_batch_size": 1,
        "gradient_accumulation_steps": 4,
        "save_strategy": "no",
        "logging_steps": 1,
        "report_to": "none",
        "eval_strategy": "no",
        "target_modules": ["q_proj", "v_proj"],
        "dropout": 0.1,
    }
validate_config
validate_config(config: dict[str, Any]) -> bool

Validate training configuration fields and value ranges.

Checks that all required fields are present and their values fall within acceptable ranges.

Parameters:

Name Type Description Default
config dict[str, Any]

A training configuration dict to validate.

required

Returns:

Type Description
bool

True if the configuration is valid.

Raises:

Type Description
ValueError

If required keys are missing or values are out of range.

Example

valid = validate_config({"task_type": "bug-fix", "rank": 64, ... "epochs": 3, "learning_rate": 2e-4}) valid True

Source code in libs/model-training/src/model_training/config.py
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
def validate_config(config: dict[str, Any]) -> bool:
    """Validate training configuration fields and value ranges.

    Checks that all required fields are present and their values
    fall within acceptable ranges.

    Args:
        config: A training configuration dict to validate.

    Returns:
        True if the configuration is valid.

    Raises:
        ValueError: If required keys are missing or values are out of range.

    Example:
        >>> valid = validate_config({"task_type": "bug-fix", "rank": 64,
        ...                         "epochs": 3, "learning_rate": 2e-4})
        >>> valid
        True
    """
    missing = _REQUIRED_KEYS - set(config.keys())
    if missing:
        raise ValueError(f"Missing required config keys: {sorted(missing)}")

    rank = config["rank"]
    if not (isinstance(rank, int) and rank > 0 and rank <= 256):
        raise ValueError(f"rank must be an integer in range (0, 256], got {rank!r}")

    epochs = config["epochs"]
    if not (isinstance(epochs, int) and epochs > 0 and epochs <= 100):
        raise ValueError(f"epochs must be an integer in range (0, 100], got {epochs!r}")

    lr = config["learning_rate"]
    if not (isinstance(lr, float) and lr > 0.0 and lr < 1.0):
        raise ValueError(f"learning_rate must be a float in range (0, 1), got {lr!r}")

    return True

d2l_config

Config helpers for hypernetwork training across model architectures.

Provides both model-specific (Qwen3-Coder-Next) and model-agnostic config builders. The model-agnostic build_hypernet_config() uses the model registry and probe cache to support any registered model.

All heavy imports (transformers, ctx_to_lora, peft) are deferred to function bodies per project convention (INFRA-05) to avoid GPU imports at module level.

Functions
get_d2l_qwen3_config
get_d2l_qwen3_config() -> dict[str, Any]

Return Qwen3-Coder-Next architecture dimensions without loading model weights.

Uses Qwen3NextConfig defaults which exactly match Qwen3-Coder-Next specs: - hidden_size: 2048 - num_hidden_layers: 48 (12 full_attention + 36 linear_attention) - num_attention_heads: 16 (Q heads), num_key_value_heads: 2 (GQA KV) - head_dim: 256 - full_attention layer indices: [3, 7, 11, 15, 19, 23, 27, 31, 35, 39, 43, 47] - vocab_size: 151936 - model_type: "qwen3_next"

Returns:

Type Description
dict[str, Any]

Dict with keys: hidden_size, num_hidden_layers, num_attention_heads,

dict[str, Any]

num_key_value_heads, head_dim, attention_layer_indices, vocab_size,

dict[str, Any]

model_type.

Source code in libs/model-training/src/model_training/d2l_config.py
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
def get_d2l_qwen3_config() -> dict[str, Any]:
    """Return Qwen3-Coder-Next architecture dimensions without loading model weights.

    Uses Qwen3NextConfig defaults which exactly match Qwen3-Coder-Next specs:
    - hidden_size: 2048
    - num_hidden_layers: 48 (12 full_attention + 36 linear_attention)
    - num_attention_heads: 16 (Q heads), num_key_value_heads: 2 (GQA KV)
    - head_dim: 256
    - full_attention layer indices: [3, 7, 11, 15, 19, 23, 27, 31, 35, 39, 43, 47]
    - vocab_size: 151936
    - model_type: "qwen3_next"

    Returns:
        Dict with keys: hidden_size, num_hidden_layers, num_attention_heads,
        num_key_value_heads, head_dim, attention_layer_indices, vocab_size,
        model_type.
    """
    from transformers import Qwen3NextConfig  # noqa: PLC0415

    cfg = Qwen3NextConfig()
    layer_types: list[str] = cfg.layer_types or []
    attention_layer_indices = [
        i for i, t in enumerate(layer_types) if t == "full_attention"
    ]
    return {
        "hidden_size": cfg.hidden_size,
        "num_hidden_layers": cfg.num_hidden_layers,
        "num_attention_heads": cfg.num_attention_heads,
        "num_key_value_heads": cfg.num_key_value_heads,
        "head_dim": cfg.head_dim,
        "attention_layer_indices": attention_layer_indices,
        "vocab_size": cfg.vocab_size,
        "model_type": cfg.model_type,
    }
build_qwen3_hypernet_config
build_qwen3_hypernet_config(
    lora_r: int = 8,
    target_modules: list[str] | None = None,
    aggregator_config: Any = None,
) -> Any

Construct HypernetConfig targeting Qwen3-Coder-Next attention layers.

Discovers full_attention layer indices dynamically from Qwen3NextConfig.layer_types. Result has exactly 12 layer indices matching the Qwen3-Coder-Next architecture.

Phase 26 probe cache integration: if a probe cache exists for QWEN3_NEXT_CANONICAL_NAME, uses real per-projection in/out dimensions for feature_sizes. Falls back to hidden_size placeholder when no cache is found (e.g., in CI where the model has not been probed).

Parameters:

Name Type Description Default
lora_r int

LoRA rank for the adapter. Defaults to 8.

8
target_modules list[str] | None

LoRA target module names. Defaults to ["q_proj", "v_proj"].

None
aggregator_config Any

Perceiver aggregator config from a Sakana checkpoint. If None (default / Phase 25 CI), HypernetConfig is built with aggregator_config=None as placeholder. Phase 29 populates this via get_aggregator_config() with a loaded model.

None

Returns:

Type Description
Any

HypernetConfig with layer_indices set to the 12 full_attention indices

Any

and base_hidden_size=2048.

Source code in libs/model-training/src/model_training/d2l_config.py
 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
def build_qwen3_hypernet_config(
    lora_r: int = 8,
    target_modules: list[str] | None = None,
    aggregator_config: Any = None,
) -> Any:
    """Construct HypernetConfig targeting Qwen3-Coder-Next attention layers.

    Discovers full_attention layer indices dynamically from Qwen3NextConfig.layer_types.
    Result has exactly 12 layer indices matching the Qwen3-Coder-Next architecture.

    Phase 26 probe cache integration: if a probe cache exists for
    QWEN3_NEXT_CANONICAL_NAME, uses real per-projection in/out dimensions for
    feature_sizes. Falls back to hidden_size placeholder when no cache is found
    (e.g., in CI where the model has not been probed).

    Args:
        lora_r: LoRA rank for the adapter. Defaults to 8.
        target_modules: LoRA target module names. Defaults to ["q_proj", "v_proj"].
        aggregator_config: Perceiver aggregator config from a Sakana checkpoint.
            If None (default / Phase 25 CI), HypernetConfig is built with
            aggregator_config=None as placeholder. Phase 29 populates this via
            get_aggregator_config() with a loaded model.

    Returns:
        HypernetConfig with layer_indices set to the 12 full_attention indices
        and base_hidden_size=2048.
    """
    from ctx_to_lora.modeling.hypernet import HypernetConfig  # noqa: PLC0415
    from peft import LoraConfig  # noqa: PLC0415
    from transformers import Qwen3NextConfig  # noqa: PLC0415

    if target_modules is None:
        target_modules = ["q_proj", "v_proj"]

    cfg = Qwen3NextConfig()
    layer_types: list[str] = cfg.layer_types or []
    layer_indices = [
        i for i, t in enumerate(layer_types) if t == "full_attention"
    ]  # Always [3, 7, 11, 15, 19, 23, 27, 31, 35, 39, 43, 47]

    lora_config = LoraConfig(
        r=lora_r,
        lora_alpha=lora_r * 2,
        target_modules=target_modules,
        lora_dropout=0.0,
        bias="none",
        task_type="CAUSAL_LM",
    )

    from model_training.d2l_probe import (  # noqa: PLC0415
        QWEN3_NEXT_CANONICAL_NAME,
        load_probe_cache,
    )

    cache = load_probe_cache(QWEN3_NEXT_CANONICAL_NAME)
    if cache is not None:
        in_sizes = {mod: cache["feature_sizes"][mod]["in"] for mod in target_modules}
        out_sizes = {mod: cache["feature_sizes"][mod]["out"] for mod in target_modules}
        feature_sizes: tuple[dict[str, int], dict[str, int]] = (in_sizes, out_sizes)
        logger.info("Using probe cache feature_sizes for %s", QWEN3_NEXT_CANONICAL_NAME)
    else:
        hidden: int = cfg.hidden_size or 2048
        _placeholder: dict[str, int] = dict.fromkeys(target_modules, hidden)
        feature_sizes = (_placeholder, dict.fromkeys(target_modules, hidden))
        logger.warning(
            "No probe cache for '%s' — using hidden_size=%d as placeholder. "
            "Run probe_model() and save_probe_cache() to set real dimensions.",
            QWEN3_NEXT_CANONICAL_NAME,
            cfg.hidden_size,
        )

    return HypernetConfig(
        latent_size=512,
        use_light_weight_lora=False,
        light_weight_latent_size=128,
        per_rank_gen=False,
        use_per_rank_bias=False,
        use_bias=True,
        per_layer_processing=False,
        use_token_mixing=False,
        num_pre_head_layers=1,
        dropout_rate=0.0,
        lora_config=lora_config,
        extra_modules=None,
        base_hidden_size=cfg.hidden_size,
        layer_indices=layer_indices,
        feature_sizes=feature_sizes,
        aggregator_config=aggregator_config,
    )
build_hypernet_config
build_hypernet_config(
    model_name: str,
    lora_r: int | None = None,
    target_modules: list[str] | None = None,
    aggregator_config: Any = None,
) -> Any

Construct HypernetConfig for any registered model.

Uses the model registry for architecture expectations and the probe cache for actual layer indices and feature dimensions. For Qwen3-Coder-Next, delegates to the specialized builder. For other models, builds config from probe cache data.

Parameters:

Name Type Description Default
model_name str

Canonical model name from the registry (e.g. "qwen3.5-9b").

required
lora_r int | None

LoRA rank. Defaults to the registry's default_lora_rank.

None
target_modules list[str] | None

LoRA target module names. Defaults to probe cache's target_modules or ["q_proj", "v_proj"].

None
aggregator_config Any

Perceiver aggregator config from a Sakana checkpoint.

None

Returns:

Type Description
Any

HypernetConfig configured for the specified model.

Raises:

Type Description
KeyError

If model_name is not in the registry.

RuntimeError

If no probe cache exists for a non-Qwen3-Coder-Next model.

Source code in libs/model-training/src/model_training/d2l_config.py
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
def build_hypernet_config(
    model_name: str,
    lora_r: int | None = None,
    target_modules: list[str] | None = None,
    aggregator_config: Any = None,
) -> Any:
    """Construct HypernetConfig for any registered model.

    Uses the model registry for architecture expectations and the probe cache
    for actual layer indices and feature dimensions. For Qwen3-Coder-Next,
    delegates to the specialized builder. For other models, builds config
    from probe cache data.

    Args:
        model_name: Canonical model name from the registry (e.g. "qwen3.5-9b").
        lora_r: LoRA rank. Defaults to the registry's default_lora_rank.
        target_modules: LoRA target module names. Defaults to probe cache's
            target_modules or ["q_proj", "v_proj"].
        aggregator_config: Perceiver aggregator config from a Sakana checkpoint.

    Returns:
        HypernetConfig configured for the specified model.

    Raises:
        KeyError: If model_name is not in the registry.
        RuntimeError: If no probe cache exists for a non-Qwen3-Coder-Next model.
    """
    from ctx_to_lora.modeling.hypernet import HypernetConfig  # noqa: PLC0415
    from peft import LoraConfig  # noqa: PLC0415

    from model_training.d2l_probe import load_probe_cache  # noqa: PLC0415
    from model_training.model_configs import (  # noqa: PLC0415
        ModelRegistry,
        validate_against_probe,
    )

    mc = ModelRegistry.default().get(model_name)

    # Qwen3-Coder-Next has specialized logic for hybrid attention discovery
    if model_name == "qwen3-coder-next":
        rank = lora_r if lora_r is not None else mc.default_lora_rank
        return build_qwen3_hypernet_config(
            lora_r=rank,
            target_modules=target_modules,
            aggregator_config=aggregator_config,
        )

    # Generic path: requires probe cache for layer indices and dimensions
    cache = load_probe_cache(model_name)
    if cache is None:
        msg = (
            f"No probe cache found for {model_name!r}. "
            "Run probe_model() and save_probe_cache() before building "
            "hypernet config for this model."
        )
        raise RuntimeError(msg)

    validate_against_probe(mc, cache)

    rank = lora_r if lora_r is not None else mc.default_lora_rank
    layer_indices = cache["attention_layer_indices"]

    # Resolve target modules from probe cache or fallback
    if target_modules is None:
        target_modules = cache.get("target_modules", ["q_proj", "v_proj"])

    lora_config = LoraConfig(
        r=rank,
        lora_alpha=mc.default_lora_alpha,
        target_modules=target_modules,
        lora_dropout=0.0,
        bias="none",
        task_type="CAUSAL_LM",
    )

    # Build feature_sizes from probe cache
    feature_sizes_raw = cache.get("feature_sizes", {})
    in_sizes: dict[str, int] = {}
    out_sizes: dict[str, int] = {}
    for mod in target_modules:
        if mod in feature_sizes_raw:
            in_sizes[mod] = feature_sizes_raw[mod]["in"]
            out_sizes[mod] = feature_sizes_raw[mod]["out"]
        else:
            in_sizes[mod] = mc.expected_hidden_size
            out_sizes[mod] = mc.expected_hidden_size

    feature_sizes: tuple[dict[str, int], dict[str, int]] = (
        in_sizes,
        out_sizes,
    )

    return HypernetConfig(
        latent_size=512,
        use_light_weight_lora=False,
        light_weight_latent_size=128,
        per_rank_gen=False,
        use_per_rank_bias=False,
        use_bias=True,
        per_layer_processing=False,
        use_token_mixing=False,
        num_pre_head_layers=1,
        dropout_rate=0.0,
        lora_config=lora_config,
        extra_modules=None,
        base_hidden_size=mc.expected_hidden_size,
        layer_indices=layer_indices,
        feature_sizes=feature_sizes,
        aggregator_config=aggregator_config,
    )

d2l_data

Data pipeline for KL-divergence context distillation training.

Provides functions for: - Converting trajectories to distillation records (activation/teacher split) - Generating needle-in-haystack synthetic datasets for CI smoke testing - JSONL persistence (save/load round-trip) - Task-ID-level train/test splitting

Functions
save_jsonl
save_jsonl(
    records: list[dict[str, Any]], path: str | Path
) -> None

Persist a list of dicts to a JSONL file.

Parameters:

Name Type Description Default
records list[dict[str, Any]]

List of JSON-serializable dicts to save.

required
path str | Path

File path for output. Parent directories are created if needed.

required
Source code in libs/model-training/src/model_training/d2l_data.py
259
260
261
262
263
264
265
266
267
268
269
270
def save_jsonl(records: list[dict[str, Any]], path: str | Path) -> None:
    """Persist a list of dicts to a JSONL file.

    Args:
        records: List of JSON-serializable dicts to save.
        path: File path for output. Parent directories are created if needed.
    """
    out = Path(path)
    out.parent.mkdir(parents=True, exist_ok=True)
    with out.open("w", encoding="utf-8") as f:
        for record in records:
            f.write(json.dumps(record, ensure_ascii=False) + "\n")
load_jsonl
load_jsonl(path: str | Path) -> list[dict[str, Any]]

Load records from a JSONL file.

Parameters:

Name Type Description Default
path str | Path

Path to the JSONL file.

required

Returns:

Type Description
list[dict[str, Any]]

List of dicts, one per non-empty line.

Source code in libs/model-training/src/model_training/d2l_data.py
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
def load_jsonl(path: str | Path) -> list[dict[str, Any]]:
    """Load records from a JSONL file.

    Args:
        path: Path to the JSONL file.

    Returns:
        List of dicts, one per non-empty line.
    """
    src = Path(path)
    return [
        json.loads(line)
        for line in src.read_text(encoding="utf-8").splitlines()
        if line.strip()
    ]
format_for_distillation
format_for_distillation(
    trajectory: dict[str, Any],
) -> list[dict[str, str]]

Convert a trajectory to distillation records with activation/teacher split.

Each record has: - activation_text: trajectory context + task description (NO answer tokens) - teacher_text: trajectory context + task description + answer - task_id: identifier for train/test splitting

Only successful trajectories (outcome == 'success') produce records.

Parameters:

Name Type Description Default
trajectory dict[str, Any]

Trajectory dict with task_id/session_id, task_description, steps, and outcome fields.

required

Returns:

Type Description
list[dict[str, str]]

List of distillation record dicts, or empty list if no successful outcome.

Source code in libs/model-training/src/model_training/d2l_data.py
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
def format_for_distillation(trajectory: dict[str, Any]) -> list[dict[str, str]]:
    """Convert a trajectory to distillation records with activation/teacher split.

    Each record has:
    - activation_text: trajectory context + task description (NO answer tokens)
    - teacher_text: trajectory context + task description + answer
    - task_id: identifier for train/test splitting

    Only successful trajectories (outcome == 'success') produce records.

    Args:
        trajectory: Trajectory dict with task_id/session_id, task_description,
            steps, and outcome fields.

    Returns:
        List of distillation record dicts, or empty list if no successful outcome.
    """
    if trajectory.get("outcome") != "success":
        return []

    steps: list[dict[str, Any]] = trajectory.get("steps", [])
    task_description: str = trajectory.get("task_description", "")
    task_id: str = trajectory.get("task_id") or trajectory.get("session_id", "")

    # Build trajectory context from step descriptions (no answer tokens)
    trajectory_parts: list[str] = []
    for step in steps:
        desc = step.get("description", "")
        if desc:
            trajectory_parts.append(desc)

    trajectory_text = "\n".join(trajectory_parts)

    # Build activation_text (context only, no answer)
    activation_base = f"{trajectory_text}\n{task_description}".strip()

    records: list[dict[str, str]] = []
    for step in steps:
        if not step.get("tests_passed"):
            continue

        # Extract answer from canonical_solution or generated_code
        answer: str = step.get("canonical_solution") or step.get("generated_code", "")
        if not answer:
            continue

        records.append(
            {
                "task_id": task_id,
                "activation_text": activation_base,
                "teacher_text": f"{activation_base}\n{answer}",
            }
        )

    return records
normalize_mined_trajectory
normalize_mined_trajectory(
    mined: dict[str, Any],
) -> dict[str, Any]

Convert a GitHub-mined trajectory dict into distillation-ready format.

Maps the mining pipeline's output (PR/issue metadata with commit and review steps) into the schema expected by format_for_distillation.

Outcome mapping
  • pr_* task_ids: "merged" -> "success", else "failure"
  • issue_* task_ids: "closed" -> "success", else "failure"
  • Fallback: "merged" or "closed" -> "success", else "failure"
Step mapping
  • Commit steps get [Commit] prefix in description and their content as generated_code.
  • Review steps get [Review] prefix with content inlined into description and empty generated_code.
  • Only the last commit step receives tests_passed=True and canonical_solution (and only when the overall outcome is success).

Parameters:

Name Type Description Default
mined dict[str, Any]

Dict from the GitHub mining pipeline with keys task_id, task_description, outcome, and steps (list of dicts with type, description, and content fields).

required

Returns:

Type Description
dict[str, Any]

Trajectory dict ready for format_for_distillation.

Source code in libs/model-training/src/model_training/d2l_data.py
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
def normalize_mined_trajectory(mined: dict[str, Any]) -> dict[str, Any]:
    """Convert a GitHub-mined trajectory dict into distillation-ready format.

    Maps the mining pipeline's output (PR/issue metadata with commit and review
    steps) into the schema expected by ``format_for_distillation``.

    Outcome mapping:
        - ``pr_*`` task_ids: ``"merged"`` -> ``"success"``, else ``"failure"``
        - ``issue_*`` task_ids: ``"closed"`` -> ``"success"``, else ``"failure"``
        - Fallback: ``"merged"`` or ``"closed"`` -> ``"success"``, else ``"failure"``

    Step mapping:
        - Commit steps get ``[Commit]`` prefix in description and their content
          as ``generated_code``.
        - Review steps get ``[Review]`` prefix with content inlined into
          description and empty ``generated_code``.
        - Only the **last** commit step receives ``tests_passed=True`` and
          ``canonical_solution`` (and only when the overall outcome is success).

    Args:
        mined: Dict from the GitHub mining pipeline with keys ``task_id``,
            ``task_description``, ``outcome``, and ``steps`` (list of dicts
            with ``type``, ``description``, and ``content`` fields).

    Returns:
        Trajectory dict ready for ``format_for_distillation``.
    """
    task_id: str = mined.get("task_id", "")
    raw_outcome: str = mined.get("outcome", "")
    raw_steps: list[dict[str, Any]] = mined.get("steps", [])

    # --- Determine normalized outcome ---
    if task_id.startswith("pr_"):
        normalized_outcome = "success" if raw_outcome == "merged" else "failure"
    elif task_id.startswith("issue_"):
        normalized_outcome = "success" if raw_outcome == "closed" else "failure"
    else:
        normalized_outcome = (
            "success" if raw_outcome in ("merged", "closed") else "failure"
        )

    # --- Identify commit steps to find the last one ---
    commit_steps = [s for s in raw_steps if s.get("type") == "commit"]

    # --- Normalize steps ---
    normalized_steps: list[dict[str, Any]] = []
    for step in raw_steps:
        step_type = step.get("type", "")
        step_description = step.get("description", "")
        step_content = step.get("content", "")

        if step_type == "commit":
            is_last_commit = commit_steps and step is commit_steps[-1]
            tests_passed = is_last_commit and normalized_outcome == "success"
            entry: dict[str, Any] = {
                "description": f"[Commit] {step_description}",
                "generated_code": step_content,
                "tests_passed": tests_passed,
            }
            if is_last_commit and normalized_outcome == "success":
                entry["canonical_solution"] = step_content
            normalized_steps.append(entry)
        elif step_type == "review":
            normalized_steps.append(
                {
                    "description": f"[Review] {step_content}",
                    "generated_code": "",
                    "tests_passed": False,
                }
            )

    return {
        "task_id": task_id,
        "session_id": task_id,
        "task_description": mined.get("task_description", ""),
        "steps": normalized_steps,
        "outcome": normalized_outcome,
    }
generate_needle_dataset
generate_needle_dataset(
    n: int = 20,
) -> list[dict[str, str]]

Generate needle-in-haystack records for CI smoke testing.

Records are deterministic (no randomness, no LLM). Each record contains a code fact embedded in a function/class context with a query and answer.

Parameters:

Name Type Description Default
n int

Number of records to generate. Cycles through templates if n exceeds the number of available templates.

20

Returns:

Type Description
list[dict[str, str]]

List of n record dicts with activation_text, teacher_text, and task_id.

Source code in libs/model-training/src/model_training/d2l_data.py
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
def generate_needle_dataset(n: int = 20) -> list[dict[str, str]]:
    """Generate needle-in-haystack records for CI smoke testing.

    Records are deterministic (no randomness, no LLM). Each record contains
    a code fact embedded in a function/class context with a query and answer.

    Args:
        n: Number of records to generate. Cycles through templates if n
            exceeds the number of available templates.

    Returns:
        List of n record dicts with activation_text, teacher_text, and task_id.
    """
    records: list[dict[str, str]] = []
    n_templates = len(_NEEDLE_TEMPLATES)
    n_slots = len(_SLOT_VALUES)

    for i in range(n):
        template = _NEEDLE_TEMPLATES[i % n_templates]
        slots = _SLOT_VALUES[i % n_slots]

        try:
            trajectory = template["trajectory_template"].format(**slots)
            query = template["query_template"].format(**slots)
            answer = template["answer_template"].format(**slots)
        except KeyError:
            # If template has a slot not in _SLOT_VALUES, use a safe fallback
            trajectory = (
                f"# code fact {i}\ndef func_{i}(x: int) -> int:\n    return {i}"
            )
            query = f"What does func_{i} return?"
            answer = str(i)

        activation_text = f"{trajectory}\n\nQ: {query}"
        teacher_text = f"{trajectory}\n\nQ: {query}\nA: {answer}"

        records.append(
            {
                "task_id": f"needle_{i}",
                "activation_text": activation_text,
                "teacher_text": teacher_text,
            }
        )

    return records
generate_trajectory_dataset
generate_trajectory_dataset(
    source: str = "humaneval", max_tasks: int | None = None
) -> list[dict[str, str]]

Generate trajectory records from a coding task dataset.

Each record has activation_text (prompt only, no solution) and teacher_text (prompt + canonical solution), making it ready for KL-divergence distillation.

Parameters:

Name Type Description Default
source str

Dataset source identifier. Currently only "humaneval" is supported.

'humaneval'
max_tasks int | None

Maximum number of tasks to process. If None, all tasks are used.

None

Returns:

Type Description
list[dict[str, str]]

List of trajectory record dicts with task_id, activation_text, and

list[dict[str, str]]

teacher_text fields.

Raises:

Type Description
ValueError

If an unsupported source is specified.

Source code in libs/model-training/src/model_training/d2l_data.py
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
519
520
521
522
523
524
def generate_trajectory_dataset(
    source: str = "humaneval",
    max_tasks: int | None = None,
) -> list[dict[str, str]]:
    """Generate trajectory records from a coding task dataset.

    Each record has activation_text (prompt only, no solution) and teacher_text
    (prompt + canonical solution), making it ready for KL-divergence distillation.

    Args:
        source: Dataset source identifier. Currently only "humaneval" is supported.
        max_tasks: Maximum number of tasks to process. If None, all tasks are used.

    Returns:
        List of trajectory record dicts with task_id, activation_text, and
        teacher_text fields.

    Raises:
        ValueError: If an unsupported source is specified.
    """
    from datasets import load_dataset  # noqa: PLC0415

    if source == "humaneval":
        dataset = load_dataset("openai_humaneval", split="test", trust_remote_code=True)
    else:
        raise ValueError(
            f"Unsupported source: {source!r}. Only 'humaneval' is supported."
        )

    records: list[dict[str, str]] = []
    tasks = list(dataset) if max_tasks is None else list(dataset)[:max_tasks]
    for task in tasks:
        task_id: str = task["task_id"]
        prompt: str = task["prompt"]
        canonical_solution: str = task["canonical_solution"]

        # activation_text: the function signature + docstring (no solution)
        activation_text = prompt.rstrip()
        # teacher_text: prompt + solution (the full implementation)
        teacher_text = prompt.rstrip() + canonical_solution

        records.append(
            {
                "task_id": task_id,
                "activation_text": activation_text,
                "teacher_text": teacher_text,
            }
        )

    logger.info("Generated %d trajectory records from %r", len(records), source)
    return records
augment_trajectories
augment_trajectories(
    trajectories: list[dict[str, Any]],
    n_variants: int = 3,
    model: str = "Qwen/Qwen3.5-9B",
    ollama_base_url: str | None = None,
) -> list[dict[str, Any]]

Produce LLM-augmented variants of trajectory records.

For each input trajectory, generates up to n_variants augmented records using an Ollama LLM. Augmented records always inherit the source task_id to preserve split integrity when mixed with originals.

Augmentation strategies (up to n_variants selected in order): 1. Paraphrase the task description 2. Reorder/drop steps in the trajectory 3. Rename variables throughout the trajectory

Parameters:

Name Type Description Default
trajectories list[dict[str, Any]]

List of trajectory record dicts with task_id, activation_text, and teacher_text fields.

required
n_variants int

Number of augmented variants to produce per trajectory. Maximum 3 (one per augmentation strategy).

3
model str

Ollama model identifier to use for augmentation.

'Qwen/Qwen3.5-9B'
ollama_base_url str | None

Ollama base URL. Defaults to "http://localhost:11434".

None

Returns:

Type Description
list[dict[str, Any]]

List of augmented trajectory dicts. Each record has the same task_id

list[dict[str, Any]]

as its source trajectory, with LLM-generated activation_text and

list[dict[str, Any]]

teacher_text.

Source code in libs/model-training/src/model_training/d2l_data.py
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
def augment_trajectories(
    trajectories: list[dict[str, Any]],
    n_variants: int = 3,
    model: str = "Qwen/Qwen3.5-9B",
    ollama_base_url: str | None = None,
) -> list[dict[str, Any]]:
    """Produce LLM-augmented variants of trajectory records.

    For each input trajectory, generates up to n_variants augmented records
    using an Ollama LLM. Augmented records always inherit the source task_id
    to preserve split integrity when mixed with originals.

    Augmentation strategies (up to n_variants selected in order):
    1. Paraphrase the task description
    2. Reorder/drop steps in the trajectory
    3. Rename variables throughout the trajectory

    Args:
        trajectories: List of trajectory record dicts with task_id,
            activation_text, and teacher_text fields.
        n_variants: Number of augmented variants to produce per trajectory.
            Maximum 3 (one per augmentation strategy).
        model: Ollama model identifier to use for augmentation.
        ollama_base_url: Ollama base URL. Defaults to "http://localhost:11434".

    Returns:
        List of augmented trajectory dicts. Each record has the same task_id
        as its source trajectory, with LLM-generated activation_text and
        teacher_text.
    """
    import asyncio  # noqa: PLC0415

    from inference.ollama_provider import OllamaProvider  # noqa: PLC0415

    base_url = ollama_base_url or "http://localhost:11434"
    provider = OllamaProvider(base_url=base_url)

    augmentation_prompts = [
        (
            "Paraphrase the following coding task description and trajectory, "
            "keeping the same logic but using different wording:\n\n{text}"
        ),
        (
            "Rewrite the following coding trajectory by reordering and slightly "
            "dropping some intermediate steps, while preserving the overall "
            "outcome:\n\n{text}"
        ),
        (
            "Rewrite the following code trajectory by renaming variables and "
            "function parameters to different names, keeping the same logic:"
            "\n\n{text}"
        ),
    ]

    async def _augment_one(
        trajectory: dict[str, Any],
        prov: Any,
        n: int,
        mdl: str,
    ) -> list[dict[str, Any]]:
        task_id: str = trajectory["task_id"]
        activation_text: str = trajectory.get("activation_text", "")
        teacher_text: str = trajectory.get("teacher_text", "")

        results: list[dict[str, Any]] = []
        strategies = augmentation_prompts[:n]
        for strategy_prompt in strategies:
            augment_prompt = strategy_prompt.format(text=teacher_text)
            result = await prov.generate(augment_prompt, mdl)
            augmented_teacher = result.text

            # Build augmented activation by stripping the solution portion
            # Use teacher text length ratio to approximate activation
            activation_prompt = strategy_prompt.format(text=activation_text)
            act_result = await prov.generate(activation_prompt, mdl)
            augmented_activation = act_result.text

            results.append(
                {
                    "task_id": task_id,  # CRITICAL: inherit source task_id
                    "activation_text": augmented_activation,
                    "teacher_text": augmented_teacher,
                }
            )
        return results

    async def _augment_all(
        trajs: list[dict[str, Any]],
        n: int,
        mdl: str,
    ) -> list[dict[str, Any]]:
        all_tasks = [_augment_one(t, provider, n, mdl) for t in trajs]
        nested = await asyncio.gather(*all_tasks)
        return [record for group in nested for record in group]

    augmented = asyncio.run(_augment_all(trajectories, n_variants, model))
    logger.info(
        "Augmented %d trajectories into %d records (n_variants=%d)",
        len(trajectories),
        len(augmented),
        n_variants,
    )
    return augmented
split_by_task_id
split_by_task_id(
    records: list[dict[str, Any]],
    test_fraction: float = 0.2,
    seed: int = 42,
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]

Split records at task-ID boundary with no task_id crossing train/test.

Augmented records that share a task_id are always assigned to the same partition, preventing task-family leakage.

Parameters:

Name Type Description Default
records list[dict[str, Any]]

List of record dicts, each with a 'task_id' field.

required
test_fraction float

Fraction of unique task_ids to assign to test set. Minimum 1 task_id goes to test even if fraction rounds to 0.

0.2
seed int

Random seed for reproducible splits.

42

Returns:

Type Description
tuple[list[dict[str, Any]], list[dict[str, Any]]]

Tuple of (train_records, test_records) where task_ids never overlap.

Source code in libs/model-training/src/model_training/d2l_data.py
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
def split_by_task_id(
    records: list[dict[str, Any]],
    test_fraction: float = 0.2,
    seed: int = 42,
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
    """Split records at task-ID boundary with no task_id crossing train/test.

    Augmented records that share a task_id are always assigned to the same
    partition, preventing task-family leakage.

    Args:
        records: List of record dicts, each with a 'task_id' field.
        test_fraction: Fraction of unique task_ids to assign to test set.
            Minimum 1 task_id goes to test even if fraction rounds to 0.
        seed: Random seed for reproducible splits.

    Returns:
        Tuple of (train_records, test_records) where task_ids never overlap.
    """
    task_ids = sorted({r["task_id"] for r in records})
    rng = random.Random(seed)
    rng.shuffle(task_ids)
    n_test = max(1, int(len(task_ids) * test_fraction))
    test_ids = set(task_ids[:n_test])
    train = [r for r in records if r["task_id"] not in test_ids]
    test = [r for r in records if r["task_id"] in test_ids]
    return train, test
normalize_mined_pairs
normalize_mined_pairs(
    trajectory: dict[str, Any],
    compress: bool = True,
    max_diff_lines: int = 500,
    language: str | None = None,
) -> list[dict[str, Any]]

Convert a mined PR trajectory into per-step training pairs.

Each review-to-revision cycle becomes one training record with activation_text (task + current code + review feedback) and teacher_text (activation + revision diff). Compatible with augment_trajectories, split_by_task_id, and save_jsonl.

The algorithm groups contiguous commits and reviews into blocks, then pairs each reviews-block with the following commits-block. Multiple commits in a block: the last commit is used (the state the reviewer actually saw). Multiple reviews: concatenated.

Parameters:

Name Type Description Default
trajectory dict[str, Any]

Raw mined trajectory from mine_pr_diff_chains.

required
compress bool

Apply diff compression via compress_diff.

True
max_diff_lines int

Max lines per compressed diff.

500
language str | None

Language tag for metadata (from repos config).

None

Returns:

Type Description
list[dict[str, Any]]

List of training pair records with task_id, activation_text,

list[dict[str, Any]]

teacher_text, and metadata fields.

Source code in libs/model-training/src/model_training/d2l_data.py
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
def normalize_mined_pairs(
    trajectory: dict[str, Any],
    compress: bool = True,
    max_diff_lines: int = 500,
    language: str | None = None,
) -> list[dict[str, Any]]:
    """Convert a mined PR trajectory into per-step training pairs.

    Each review-to-revision cycle becomes one training record with
    activation_text (task + current code + review feedback) and
    teacher_text (activation + revision diff). Compatible with
    ``augment_trajectories``, ``split_by_task_id``, and ``save_jsonl``.

    The algorithm groups contiguous commits and reviews into blocks,
    then pairs each reviews-block with the following commits-block.
    Multiple commits in a block: the last commit is used (the state
    the reviewer actually saw). Multiple reviews: concatenated.

    Args:
        trajectory: Raw mined trajectory from ``mine_pr_diff_chains``.
        compress: Apply diff compression via ``compress_diff``.
        max_diff_lines: Max lines per compressed diff.
        language: Language tag for metadata (from repos config).

    Returns:
        List of training pair records with task_id, activation_text,
        teacher_text, and metadata fields.
    """
    task_id: str = trajectory.get("task_id", "")
    task_desc: str = trajectory.get("task_description", "")
    raw_steps: list[dict[str, Any]] = trajectory.get("steps", [])
    outcome: str = trajectory.get("outcome", "")

    if not raw_steps:
        return []

    blocks = _group_steps_into_blocks(raw_steps)

    def _diff(step: dict[str, Any]) -> str:
        raw = step.get("content", "")
        return compress_diff(raw, max_lines=max_diff_lines) if compress else raw

    def _record(idx: int, activation: str, teacher: str) -> dict[str, Any]:
        return _make_pair_record(
            task_id,
            outcome,
            language,
            idx,
            activation,
            teacher,
            task_description=task_desc,
        )

    records: list[dict[str, Any]] = []
    step_idx = 0
    prev_diff = ""
    bi = 0  # block index

    # --- Step 0: initial commits block ---
    if blocks[0][0] == "commit":
        last_commit = blocks[0][1][-1]
        diff = _diff(last_commit)
        activation = f"## Task\n{task_desc}"
        teacher = f"{activation}\n\n## Implementation\n{diff}"
        records.append(_record(step_idx, activation, teacher))
        prev_diff = diff
        step_idx += 1
        bi = 1

    # --- Subsequent (reviews, commits) pairs ---
    while bi < len(blocks) - 1:
        if blocks[bi][0] == "review" and blocks[bi + 1][0] == "commit":
            review_text = "\n\n".join(r.get("content", "") for r in blocks[bi][1])
            revision = _diff(blocks[bi + 1][1][-1])
            activation = f"## Task\n{task_desc}"
            if prev_diff:
                activation += f"\n\n## Current Code\n{prev_diff}"
            activation += f"\n\n## Review Feedback\n{review_text}"
            teacher = f"{activation}\n\n## Revision\n{revision}"
            records.append(_record(step_idx, activation, teacher))
            prev_diff = revision
            step_idx += 1
            bi += 2
        else:
            bi += 1

    return records
pairs_to_chat_messages
pairs_to_chat_messages(
    pairs: list[dict[str, Any]],
    *,
    mode: Literal[
        "multi_turn", "single_turn"
    ] = "multi_turn",
    system_prompt: str = SYSTEM_PROMPT,
) -> tuple[
    list[list[dict[str, str]]], list[dict[str, str]]
]

Convert mined pair records into SFT chat conversations.

multi_turn (preferred when pairs share a source_task_id): emits one conversation per task grouping — [system, user_1, assistant_1, user_2, assistant_2, ...] — where each (user, assistant) pair is one review→revision cycle. This preserves the attempt-error-correction structure so the adapter can encode the trajectory rather than only the final code.

single_turn: emits one conversation per pair (no clustering). Useful when metadata.source_task_id is missing or the caller prefers flat examples. Each conversation is [system, user, assistant].

Pairs are grouped in the order they appear in the input; within a group, pairs are sorted by metadata.step_index to preserve chronological order of review cycles. Empty input returns ([], []).

Parameters:

Name Type Description Default
pairs list[dict[str, Any]]

List of pair records as emitted by normalize_mined_pairs. Each record must have activation_text and teacher_text. metadata.source_task_id and metadata.step_index are used for grouping/ordering when present; fall back to task_id.

required
mode Literal['multi_turn', 'single_turn']

"multi_turn" clusters pairs by task_id; "single_turn" emits one conversation per pair.

'multi_turn'
system_prompt str

System message for every conversation.

SYSTEM_PROMPT

Returns:

Type Description
list[list[dict[str, str]]]

A tuple (conversations, pre_post_records).

list[dict[str, str]]

conversations is a list of chat-message lists suitable for

tuple[list[list[dict[str, str]]], list[dict[str, str]]]

datasets.Dataset.from_list([{"messages": m} for m in convs]) and

tuple[list[list[dict[str, str]]], list[dict[str, str]]]

TRL's SFTTrainer with assistant_only_loss=True.

tuple[list[list[dict[str, str]]], list[dict[str, str]]]

pre_post_records is a list of ``{"pre_code": str, "post_code":

tuple[list[list[dict[str, str]]], list[dict[str, str]]]

str}dicts aligned 1:1 withconversations``. For multi-turn

tuple[list[list[dict[str, str]]], list[dict[str, str]]]

conversations the pre/post codes are the concatenation (joined by

tuple[list[list[dict[str, str]]], list[dict[str, str]]]

"\\n\\n") of each individual turn's pre/post code.

tuple[list[list[dict[str, str]]], list[dict[str, str]]]

Invalid or missing fields are handled gracefully: missing

tuple[list[list[dict[str, str]]], list[dict[str, str]]]

activation_text / teacher_text produce empty strings, and

tuple[list[list[dict[str, str]]], list[dict[str, str]]]

missing metadata keys fall back to empty string / 0 defaults.

Raises:

Type Description
None

No exceptions are raised — invalid input fields fall back to empty-string / zero defaults.

Source code in libs/model-training/src/model_training/d2l_data.py
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
def pairs_to_chat_messages(
    pairs: list[dict[str, Any]],
    *,
    mode: Literal["multi_turn", "single_turn"] = "multi_turn",
    system_prompt: str = SYSTEM_PROMPT,
) -> tuple[list[list[dict[str, str]]], list[dict[str, str]]]:
    r"""Convert mined pair records into SFT chat conversations.

    ``multi_turn`` (preferred when pairs share a ``source_task_id``): emits
    one conversation per task grouping — ``[system, user_1, assistant_1,
    user_2, assistant_2, ...]`` — where each (user, assistant) pair is one
    review→revision cycle. This preserves the attempt-error-correction
    structure so the adapter can encode the trajectory rather than only the
    final code.

    ``single_turn``: emits one conversation per pair (no clustering). Useful
    when ``metadata.source_task_id`` is missing or the caller prefers flat
    examples. Each conversation is ``[system, user, assistant]``.

    Pairs are grouped in the order they appear in the input; within a group,
    pairs are sorted by ``metadata.step_index`` to preserve chronological
    order of review cycles. Empty input returns ``([], [])``.

    Args:
        pairs: List of pair records as emitted by ``normalize_mined_pairs``.
            Each record must have ``activation_text`` and ``teacher_text``.
            ``metadata.source_task_id`` and ``metadata.step_index`` are used
            for grouping/ordering when present; fall back to ``task_id``.
        mode: ``"multi_turn"`` clusters pairs by task_id; ``"single_turn"``
            emits one conversation per pair.
        system_prompt: System message for every conversation.

    Returns:
        A tuple ``(conversations, pre_post_records)``.

        ``conversations`` is a list of chat-message lists suitable for
        ``datasets.Dataset.from_list([{"messages": m} for m in convs])`` and
        TRL's ``SFTTrainer`` with ``assistant_only_loss=True``.

        ``pre_post_records`` is a list of ``{"pre_code": str, "post_code":
        str}`` dicts aligned 1:1 with ``conversations``. For multi-turn
        conversations the pre/post codes are the concatenation (joined by
        ``"\\n\\n"``) of each individual turn's pre/post code.

        Invalid or missing fields are handled gracefully: missing
        ``activation_text`` / ``teacher_text`` produce empty strings, and
        missing ``metadata`` keys fall back to empty string / 0 defaults.

    Raises:
        None: No exceptions are raised — invalid input fields fall back
            to empty-string / zero defaults.
    """
    if not pairs:
        return [], []

    if mode == "single_turn":
        return _pairs_to_single_turn(pairs, system_prompt)

    # multi_turn: cluster by source_task_id (or task_id), sort by step_index.
    groups, group_order = _group_pairs_by_task(pairs)
    conversations: list[list[dict[str, str]]] = []
    pre_post_records: list[dict[str, str]] = []
    for key in group_order:
        group = sorted(
            groups[key],
            key=lambda p: (p.get("metadata") or {}).get("step_index", 0),
        )
        messages: list[dict[str, str]] = [{"role": "system", "content": system_prompt}]
        turn_pre_codes: list[str] = []
        turn_post_codes: list[str] = []
        for pair in group:
            user = pair.get("activation_text", "")
            teacher = pair.get("teacher_text", "")
            assistant = _extract_revision(user, teacher)
            if not assistant:
                continue
            messages.append({"role": "user", "content": user})
            messages.append({"role": "assistant", "content": assistant})
            turn_pre_codes.append(_extract_pre_revision(user))
            turn_post_codes.append(_extract_post_revision(user, teacher))
        # A valid SFT conversation needs at least one user/assistant turn.
        if len(messages) >= 3:
            conversations.append(messages)
            pre_post_records.append(
                {
                    "pre_code": "\n\n".join(turn_pre_codes),
                    "post_code": "\n\n".join(turn_post_codes),
                }
            )
    return conversations, pre_post_records

d2l_diff

RTK-style diff compression for training data preparation.

Filters irrelevant files (lockfiles, generated code, binary assets, build artifacts) and truncates large diffs to minimize token overhead in hypernetwork training pairs.

Operates on the concatenated diff format produced by mine_pr_diff_chains

--- src/main.py --- +real code --- package-lock.json --- +lockfile noise

Functions
compress_diff
compress_diff(content: str, max_lines: int = 500) -> str

Filter irrelevant files and truncate large diffs.

Parses the --- filename --- section format produced by mine_pr_diff_chains and removes lockfiles, generated code, binary files, and build artifacts.

Parameters:

Name Type Description Default
content str

Concatenated diff content with section headers.

required
max_lines int

Maximum total output lines.

500

Returns:

Type Description
str

Filtered and truncated diff string.

Source code in libs/model-training/src/model_training/d2l_diff.py
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
def compress_diff(content: str, max_lines: int = 500) -> str:
    """Filter irrelevant files and truncate large diffs.

    Parses the ``--- filename ---`` section format produced by
    ``mine_pr_diff_chains`` and removes lockfiles, generated code,
    binary files, and build artifacts.

    Args:
        content: Concatenated diff content with section headers.
        max_lines: Maximum total output lines.

    Returns:
        Filtered and truncated diff string.
    """
    if not content:
        return content

    parts = _SECTION_RE.split(content)

    # No section headers found -- fall through to truncation only
    if len(parts) == 1:
        return _truncate(content, max_lines)

    # parts = [preamble, header1, body1, header2, body2, ...]
    kept: list[str] = []
    idx = 1  # skip preamble (parts[0])
    while idx < len(parts):
        header = parts[idx]
        body = parts[idx + 1] if idx + 1 < len(parts) else ""
        filename = header[4:-4]  # strip "--- " and " ---"
        if not _should_skip(filename):
            kept.append(header + body)
        idx += 2

    result = "".join(kept).strip()

    if not result:
        return ""

    return _truncate(result, max_lines)

d2l_lora

Functional LoRA injection via context manager for hypernetwork training.

Patches transformer attention projection modules with F.linear forward functions that carry live hypernetwork tensor graph nodes, preserving autograd continuity through A and B matrices back to the hypernetwork head.

Unlike PEFT's get_peft_model (which severs the autograd graph by copying tensors into new nn.Parameter objects), this approach uses closures over the original A/B tensors so that loss.backward() propagates gradients through the LoRA path all the way to the hypernetwork parameters.

All heavy GPU imports (torch, transformers) are deferred to function bodies per INFRA-05 project convention.

Functions
apply_functional_lora
apply_functional_lora(
    model: Any, lora_dict: dict[str, Any], hc: Any
) -> _FunctionalLoRAContext

Create a context manager that patches model with functional LoRA.

Usage

with apply_functional_lora(base_model, lora_dict, hc): output = base_model(input_ids) loss = criterion(output, target) loss.backward() # gradients flow through A/B to hypernetwork

Parameters:

Name Type Description Default
model Any

Base transformer model (nn.Module).

required
lora_dict dict[str, Any]

Dict from HyperLoRA.generate_weights(). Structure::

lora_dict[proj_name]["A"] shape: (batch=1, n_layers, r, d_in)
lora_dict[proj_name]["B"] shape: (batch=1, n_layers, r, d_out)

Keys match hc.lora_config.target_modules. Batch dimension is always 1 (squeezed at index 0).

required
hc Any

HypernetConfig with attributes: hc.lora_config.target_modules: list of projection names hc.lora_config.r: LoRA rank hc.lora_config.lora_alpha: scaling numerator hc.layer_indices: list of absolute layer indices

required

Returns:

Type Description
_FunctionalLoRAContext

_FunctionalLoRAContext to use as context manager.

Source code in libs/model-training/src/model_training/d2l_lora.py
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
def apply_functional_lora(
    model: Any, lora_dict: dict[str, Any], hc: Any
) -> _FunctionalLoRAContext:
    """Create a context manager that patches model with functional LoRA.

    Usage:
        with apply_functional_lora(base_model, lora_dict, hc):
            output = base_model(input_ids)
            loss = criterion(output, target)
        loss.backward()  # gradients flow through A/B to hypernetwork

    Args:
        model: Base transformer model (nn.Module).
        lora_dict: Dict from HyperLoRA.generate_weights(). Structure::

                lora_dict[proj_name]["A"] shape: (batch=1, n_layers, r, d_in)
                lora_dict[proj_name]["B"] shape: (batch=1, n_layers, r, d_out)

            Keys match hc.lora_config.target_modules.
            Batch dimension is always 1 (squeezed at index 0).
        hc: HypernetConfig with attributes:
            hc.lora_config.target_modules: list of projection names
            hc.lora_config.r: LoRA rank
            hc.lora_config.lora_alpha: scaling numerator
            hc.layer_indices: list of absolute layer indices

    Returns:
        _FunctionalLoRAContext to use as context manager.
    """
    return _FunctionalLoRAContext(model, lora_dict, hc)

d2l_mining

GitHub trajectory mining for coding session distillation.

Mines PR diff chains and issue-commit chains from GitHub repositories, producing trajectory dicts suitable for normalization and distillation. Designed to run on an L4 VM with network access and a GITHUB_TOKEN.

Classes
Functions
search_quality_prs
search_quality_prs(
    repo: str,
    max_results: int = 100,
    github_token: str | None = None,
    min_review_comments: int = 1,
    min_commits: int = 2,
    exclude_labels: list[str] | None = None,
) -> list[int]

Search for high-quality merged PRs using the GitHub Search API.

Pre-filters PRs by review approval, comment count, label exclusion, and minimum commit count to identify PRs with meaningful review trajectories suitable for distillation.

Parameters:

Name Type Description Default
repo str

GitHub repository in "owner/repo" format.

required
max_results int

Maximum number of qualifying PR numbers to return.

100
github_token str | None

Personal access token for GitHub API authentication.

None
min_review_comments int

Minimum number of comments for search query.

1
min_commits int

Minimum number of commits a PR must have.

2
exclude_labels list[str] | None

Labels to exclude. Defaults to common non-code labels.

None

Returns:

Type Description
list[int]

List of qualifying PR numbers.

Source code in libs/model-training/src/model_training/d2l_mining.py
 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
def search_quality_prs(
    repo: str,
    max_results: int = 100,
    github_token: str | None = None,
    min_review_comments: int = 1,
    min_commits: int = 2,
    exclude_labels: list[str] | None = None,
) -> list[int]:
    """Search for high-quality merged PRs using the GitHub Search API.

    Pre-filters PRs by review approval, comment count, label exclusion,
    and minimum commit count to identify PRs with meaningful review
    trajectories suitable for distillation.

    Args:
        repo: GitHub repository in "owner/repo" format.
        max_results: Maximum number of qualifying PR numbers to return.
        github_token: Personal access token for GitHub API authentication.
        min_review_comments: Minimum number of comments for search query.
        min_commits: Minimum number of commits a PR must have.
        exclude_labels: Labels to exclude. Defaults to common non-code labels.

    Returns:
        List of qualifying PR numbers.
    """
    client = GitHubClient(token=github_token)
    labels_to_exclude = (
        frozenset(exclude_labels)
        if exclude_labels is not None
        else _DEFAULT_EXCLUDE_LABELS
    )

    query = (
        f"repo:{repo} is:pr is:merged review:approved comments:>{min_review_comments}"
    )
    per_page = min(max_results, 100)
    pages_needed = math.ceil(max_results / 100)

    all_items: list[dict[str, Any]] = []
    for page in range(1, pages_needed + 1):
        data = client.get(
            "/search/issues",
            params={
                "q": query,
                "sort": "updated",
                "order": "desc",
                "per_page": per_page,
                "page": page,
            },
        )
        items = data.get("items", [])
        all_items.extend(items)
        if len(items) < per_page:
            break

    total = len(all_items)

    # Label filter
    after_label: list[dict[str, Any]] = []
    for item in all_items:
        item_labels = {lbl["name"] for lbl in item.get("labels", [])}
        if not item_labels & labels_to_exclude:
            after_label.append(item)

    # Commit count filter
    result: list[int] = []
    for item in after_label:
        pr_number = item["number"]
        detail = client.get(f"/repos/{repo}/pulls/{pr_number}")
        if detail.get("commits", 0) >= min_commits:
            result.append(pr_number)
        if len(result) >= max_results:
            break

    logger.info(
        "Search found %d candidates, %d after label filter, %d after commit filter",
        total,
        len(after_label),
        len(result),
    )
    return result
mine_pr_diff_chains
mine_pr_diff_chains(
    repo: str,
    max_prs: int = 100,
    github_token: str | None = None,
    pr_numbers: list[int] | None = None,
) -> list[dict[str, Any]]

Extract PR diff chains from a GitHub repository.

Each chain represents an iterative coding session: initial commit -> review comments -> revision commits. The resulting trajectory records capture the back-and-forth of code review as a multi-step improvement process, suitable for distillation.

Returns trajectory dicts with the following fields: - task_id: f"pr_{repo}_{pr_number}" - task_description: PR title concatenated with body text - steps: list of commit diffs and review comments in chronological order - outcome: "merged" or "closed" depending on PR final state

Parameters:

Name Type Description Default
repo str

GitHub repository in "owner/repo" format.

required
max_prs int

Maximum number of PRs to process. Defaults to 100.

100
github_token str | None

Personal access token for GitHub API authentication.

None
pr_numbers list[int] | None

Optional list of specific PR numbers to mine. When provided, skips the paginated PR list fetch and fetches each PR individually.

None

Returns:

Type Description
list[dict[str, Any]]

List of trajectory dicts representing PR diff chains.

Source code in libs/model-training/src/model_training/d2l_mining.py
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
def mine_pr_diff_chains(
    repo: str,
    max_prs: int = 100,
    github_token: str | None = None,
    pr_numbers: list[int] | None = None,
) -> list[dict[str, Any]]:
    """Extract PR diff chains from a GitHub repository.

    Each chain represents an iterative coding session: initial commit ->
    review comments -> revision commits. The resulting trajectory records
    capture the back-and-forth of code review as a multi-step improvement
    process, suitable for distillation.

    Returns trajectory dicts with the following fields:
    - task_id: f"pr_{repo}_{pr_number}"
    - task_description: PR title concatenated with body text
    - steps: list of commit diffs and review comments in chronological order
    - outcome: "merged" or "closed" depending on PR final state

    Args:
        repo: GitHub repository in "owner/repo" format.
        max_prs: Maximum number of PRs to process. Defaults to 100.
        github_token: Personal access token for GitHub API authentication.
        pr_numbers: Optional list of specific PR numbers to mine. When
            provided, skips the paginated PR list fetch and fetches each
            PR individually.

    Returns:
        List of trajectory dicts representing PR diff chains.
    """
    client = GitHubClient(token=github_token)

    if pr_numbers is not None:
        prs = [client.get(f"/repos/{repo}/pulls/{n}") for n in pr_numbers[:max_prs]]
    else:
        prs = client.get_paginated(
            f"/repos/{repo}/pulls",
            params={"state": "closed", "sort": "updated", "direction": "desc"},
            max_pages=math.ceil(max_prs / 100),
        )
        prs = prs[:max_prs]

    if not prs:
        return []

    trajectories: list[dict[str, Any]] = []

    for pr in prs:
        pr_number = pr["number"]
        title = pr.get("title", "")
        body = pr.get("body", "") or ""

        commits = client.get_paginated(
            f"/repos/{repo}/pulls/{pr_number}/commits",
            max_pages=5,
        )
        reviews = client.get_paginated(
            f"/repos/{repo}/pulls/{pr_number}/comments",
            max_pages=3,
        )

        # Build timestamped steps for chronological interleaving
        timed_steps: list[tuple[str, dict[str, str]]] = []

        for commit in commits:
            sha = commit["sha"]
            msg = commit["commit"]["message"]
            ts = commit["commit"].get("committer", {}).get("date", "")
            detail = client.get(f"/repos/{repo}/commits/{sha}")
            files = detail.get("files", [])
            patches = []
            for f in files:
                patch = f.get("patch", "")
                if patch:
                    patches.append(f"--- {f['filename']} ---\n{patch}")
            timed_steps.append(
                (
                    ts,
                    {
                        "type": "commit",
                        "description": msg,
                        "content": "\n".join(patches),
                    },
                )
            )

        for comment in reviews:
            ts = comment.get("created_at", "")
            timed_steps.append(
                (
                    ts,
                    {
                        "type": "review",
                        "description": "Review comment",
                        "content": comment.get("body", ""),
                    },
                )
            )

        # Sort by timestamp so commits and reviews interleave chronologically
        timed_steps.sort(key=lambda x: x[0])
        steps = [step for _, step in timed_steps]

        outcome = "merged" if pr.get("merged_at") is not None else "closed"

        trajectories.append(
            {
                "task_id": f"pr_{repo}_{pr_number}",
                "task_description": f"{title}\n\n{body}".strip(),
                "steps": steps,
                "outcome": outcome,
            }
        )

    return trajectories
mine_issue_commit_chains
mine_issue_commit_chains(
    repo: str,
    max_issues: int = 100,
    github_token: str | None = None,
) -> list[dict[str, Any]]

Link GitHub issues to their fixing commits via commit message references.

Scans commit messages for "fixes #N", "closes #N", or "resolves #N" patterns to identify which commits address which issues. Groups linked commits as trajectory steps for distillation.

Returns trajectory dicts with the following fields: - task_id: f"issue_{repo}_{issue_number}" - task_description: issue title concatenated with body text - steps: list of commits referencing this issue in chronological order - outcome: "closed" or "open" from the issue state

Parameters:

Name Type Description Default
repo str

GitHub repository in "owner/repo" format.

required
max_issues int

Maximum number of issues to process. Defaults to 100.

100
github_token str | None

Personal access token for GitHub API authentication.

None

Returns:

Type Description
list[dict[str, Any]]

List of trajectory dicts representing issue-commit chains.

Source code in libs/model-training/src/model_training/d2l_mining.py
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
def mine_issue_commit_chains(
    repo: str,
    max_issues: int = 100,
    github_token: str | None = None,
) -> list[dict[str, Any]]:
    """Link GitHub issues to their fixing commits via commit message references.

    Scans commit messages for "fixes #N", "closes #N", or "resolves #N"
    patterns to identify which commits address which issues. Groups linked
    commits as trajectory steps for distillation.

    Returns trajectory dicts with the following fields:
    - task_id: f"issue_{repo}_{issue_number}"
    - task_description: issue title concatenated with body text
    - steps: list of commits referencing this issue in chronological order
    - outcome: "closed" or "open" from the issue state

    Args:
        repo: GitHub repository in "owner/repo" format.
        max_issues: Maximum number of issues to process. Defaults to 100.
        github_token: Personal access token for GitHub API authentication.

    Returns:
        List of trajectory dicts representing issue-commit chains.
    """
    client = GitHubClient(token=github_token)

    raw_issues = client.get_paginated(
        f"/repos/{repo}/issues",
        params={"state": "all", "sort": "updated", "direction": "desc"},
        max_pages=math.ceil(max_issues / 100),
    )

    # Filter out pull requests (GitHub issues API includes PRs)
    issues = [i for i in raw_issues if not i.get("pull_request")]
    issues = issues[:max_issues]

    issue_numbers = {i["number"] for i in issues}
    issue_map = {i["number"]: i for i in issues}

    repo_commits = client.get_paginated(
        f"/repos/{repo}/commits",
        max_pages=10,
    )

    # Group commits by referenced issue number
    linked: dict[int, list[dict[str, Any]]] = {}
    for commit in repo_commits:
        msg = commit["commit"]["message"]
        refs = _FIXES_RE.findall(msg)
        for ref in refs:
            issue_num = int(ref)
            if issue_num in issue_numbers:
                linked.setdefault(issue_num, []).append(commit)

    trajectories: list[dict[str, Any]] = []

    for issue_num, commits in linked.items():
        issue = issue_map[issue_num]
        title = issue.get("title", "")
        body = issue.get("body", "") or ""

        steps: list[dict[str, str]] = []
        for commit in commits:
            sha = commit["sha"]
            msg = commit["commit"]["message"]
            detail = client.get(f"/repos/{repo}/commits/{sha}")
            files = detail.get("files", [])
            patches = []
            for f in files:
                patch = f.get("patch", "")
                if patch:
                    patches.append(f"--- {f['filename']} ---\n{patch}")
            steps.append(
                {
                    "type": "commit",
                    "description": msg,
                    "content": "\n".join(patches),
                }
            )

        trajectories.append(
            {
                "task_id": f"issue_{repo}_{issue_num}",
                "task_description": f"{title}\n\n{body}".strip(),
                "steps": steps,
                "outcome": issue.get("state", "open"),
            }
        )

    return trajectories

d2l_prep

Data preparation pipeline for context distillation training.

Converts raw trajectory JSON files into a training JSONL by calling format_for_distillation on each trajectory and persisting the resulting records via save_jsonl.

Usage (CLI): uv run python -m model_training.d2l_prep traj1.json traj2.json -o train.jsonl

Functions
prepare_training_jsonl
prepare_training_jsonl(
    input_paths: list[Path], output_path: Path
) -> int

Convert trajectory JSON files to a training JSONL.

Reads each input file, calls format_for_distillation on every trajectory, collects all returned records, and writes them to output_path via save_jsonl.

Failed trajectories (outcome != 'success') are filtered by format_for_distillation and produce zero records — they do not raise.

Parameters:

Name Type Description Default
input_paths list[Path]

Trajectory JSON files, each containing a single trajectory dict or a JSON array of trajectory dicts.

required
output_path Path

Destination JSONL file. Parent directories are created automatically. File is always written (may be empty).

required

Returns:

Type Description
int

Number of records written.

Source code in libs/model-training/src/model_training/d2l_prep.py
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
def prepare_training_jsonl(
    input_paths: list[Path],
    output_path: Path,
) -> int:
    """Convert trajectory JSON files to a training JSONL.

    Reads each input file, calls format_for_distillation on every trajectory,
    collects all returned records, and writes them to output_path via save_jsonl.

    Failed trajectories (outcome != 'success') are filtered by
    format_for_distillation and produce zero records — they do not raise.

    Args:
        input_paths: Trajectory JSON files, each containing a single trajectory
            dict or a JSON array of trajectory dicts.
        output_path: Destination JSONL file. Parent directories are created
            automatically. File is always written (may be empty).

    Returns:
        Number of records written.
    """
    all_records: list[dict[str, Any]] = []

    for path in input_paths:
        trajectories = _load_trajectories(path)
        logger.info("Processing %s (%d trajectories)", path, len(trajectories))
        for traj in trajectories:
            records = format_for_distillation(traj)
            all_records.extend(records)
            logger.debug(
                "  trajectory %s → %d records",
                traj.get("task_id", "<no-id>"),
                len(records),
            )

    save_jsonl(all_records, output_path)
    logger.info("Wrote %d records to %s", len(all_records), output_path)
    return len(all_records)

d2l_probe

Architecture probe and activation extraction for hypernetwork training.

Discovers standard attention layers (those with q_proj/k_proj/v_proj/o_proj children) via model.named_modules(), caches results to JSON, and provides extract_activations_with_model() that accepts a pre-loaded model and tokenizer.

Phase 26 purpose: eliminate hidden_size placeholders and per-call model loading. The probe becomes the single source of truth for layer indices and projection dimensions across the v7.0 pipeline.

All heavy GPU imports (torch, transformers) are deferred to function bodies per INFRA-05 project convention.

Functions
discover_target_modules
discover_target_modules(model: Any) -> list[str]

Discover all LoRA-targetable projection modules in a model.

Single-pass iteration over model.named_modules() collecting the short names of any Linear modules whose names match known projection patterns (attention, GDN, or MLP). Returns a sorted, deduplicated list.

Parameters:

Name Type Description Default
model Any

Any nn.Module (typically a transformer model).

required

Returns:

Type Description
list[str]

Sorted list of unique projection names found (e.g.

list[str]

["down_proj", "gate_proj", "k_proj", "o_proj", "q_proj", ...]).

Source code in libs/model-training/src/model_training/d2l_probe.py
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
def discover_target_modules(model: Any) -> list[str]:
    """Discover all LoRA-targetable projection modules in a model.

    Single-pass iteration over model.named_modules() collecting the short
    names of any Linear modules whose names match known projection patterns
    (attention, GDN, or MLP). Returns a sorted, deduplicated list.

    Args:
        model: Any nn.Module (typically a transformer model).

    Returns:
        Sorted list of unique projection names found (e.g.
        ["down_proj", "gate_proj", "k_proj", "o_proj", "q_proj", ...]).
    """
    import torch.nn as nn  # noqa: PLC0415

    found: set[str] = set()
    for name, module in model.named_modules():
        short = name.split(".")[-1]
        if short in ALL_KNOWN_PROJECTIONS and isinstance(module, nn.Linear):
            found.add(short)
    return sorted(found)
probe_model
probe_model(model: Any) -> dict[str, Any]

Probe a model's architecture to discover attention layers and modules.

Iterates model.named_modules() to find layers that have all four attention projection children (q_proj, k_proj, v_proj, o_proj). DeltaNet and other linear-attention layers that lack these projections are skipped.

For each discovered attention layer, captures the in/out dimensions of q_proj, k_proj, v_proj, and o_proj weights.

Also discovers all LoRA-targetable projection modules (attention, GDN, MLP) via discover_target_modules().

Parameters:

Name Type Description Default
model Any

Any nn.Module (typically a transformer model).

required

Returns:

Type Description
dict[str, Any]

Dict with keys: - attention_layer_indices: sorted list of int layer indices - feature_sizes: dict mapping projection name to {"in": int, "out": int} - target_modules: sorted list of discovered projection names

Source code in libs/model-training/src/model_training/d2l_probe.py
 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
def probe_model(model: Any) -> dict[str, Any]:
    """Probe a model's architecture to discover attention layers and modules.

    Iterates model.named_modules() to find layers that have all four attention
    projection children (q_proj, k_proj, v_proj, o_proj). DeltaNet and other
    linear-attention layers that lack these projections are skipped.

    For each discovered attention layer, captures the in/out dimensions of
    q_proj, k_proj, v_proj, and o_proj weights.

    Also discovers all LoRA-targetable projection modules (attention, GDN,
    MLP) via discover_target_modules().

    Args:
        model: Any nn.Module (typically a transformer model).

    Returns:
        Dict with keys:
            - attention_layer_indices: sorted list of int layer indices
            - feature_sizes: dict mapping projection name to {"in": int, "out": int}
            - target_modules: sorted list of discovered projection names
    """
    attention_layer_indices: list[int] = []
    feature_sizes: dict[str, dict[str, int]] = {}

    for name, module in model.named_modules():
        # Get immediate children names
        child_names = {n.split(".")[-1] for n, _ in module.named_children()}
        if not ATTN_PROJECTIONS.issubset(child_names):
            continue

        # Extract layer index from the last numeric segment in dotted name
        parts = name.split(".")
        layer_idx: int | None = None
        for part in reversed(parts):
            if part.isdigit():
                layer_idx = int(part)
                break
        if layer_idx is None:
            continue

        attention_layer_indices.append(layer_idx)

        # Capture projection dimensions (out_f, in_f = weight.shape)
        for proj_name in ("q_proj", "k_proj", "v_proj", "o_proj"):
            proj = getattr(module, proj_name, None)
            if proj is None or not hasattr(proj, "weight"):
                continue
            out_f, in_f = proj.weight.shape
            if proj_name not in feature_sizes:
                feature_sizes[proj_name] = {"in": in_f, "out": out_f}

    return {
        "attention_layer_indices": sorted(attention_layer_indices),
        "feature_sizes": feature_sizes,
        "target_modules": discover_target_modules(model),
    }
save_probe_cache
save_probe_cache(
    model_name: str, probe_result: dict[str, Any]
) -> Path

Persist probe results to JSON cache.

Adds metadata fields (model_name, model_name_hash, probed_at) to a copy of probe_result. Creates PROBE_CACHE_DIR if it does not exist.

Parameters:

Name Type Description Default
model_name str

Canonical model identifier (used for cache lookup key).

required
probe_result dict[str, Any]

Output from probe_model().

required

Returns:

Type Description
Path

Path to the written JSON file.

Source code in libs/model-training/src/model_training/d2l_probe.py
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
def save_probe_cache(model_name: str, probe_result: dict[str, Any]) -> Path:
    """Persist probe results to JSON cache.

    Adds metadata fields (model_name, model_name_hash, probed_at) to a copy
    of probe_result. Creates PROBE_CACHE_DIR if it does not exist.

    Args:
        model_name: Canonical model identifier (used for cache lookup key).
        probe_result: Output from probe_model().

    Returns:
        Path to the written JSON file.
    """
    cache_path = _model_name_to_cache_path(model_name)
    PROBE_CACHE_DIR.mkdir(parents=True, exist_ok=True)

    data = dict(probe_result)
    data["model_name"] = model_name
    data["model_name_hash"] = hashlib.sha256(model_name.encode()).hexdigest()[:16]
    data["probed_at"] = datetime.now(timezone.utc).isoformat()

    cache_path.write_text(json.dumps(data, indent=2))
    logger.info("Probe cache saved: %s → %s", model_name, cache_path)
    return cache_path
load_probe_cache
load_probe_cache(model_name: str) -> dict[str, Any] | None

Load probe results from JSON cache.

Parameters:

Name Type Description Default
model_name str

Canonical model identifier.

required

Returns:

Type Description
dict[str, Any] | None

Probe result dict (including metadata fields) if cached, else None.

dict[str, Any] | None

Never raises — returns None on any miss.

Source code in libs/model-training/src/model_training/d2l_probe.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
def load_probe_cache(model_name: str) -> dict[str, Any] | None:
    """Load probe results from JSON cache.

    Args:
        model_name: Canonical model identifier.

    Returns:
        Probe result dict (including metadata fields) if cached, else None.
        Never raises — returns None on any miss.
    """
    cache_path = _model_name_to_cache_path(model_name)
    if not cache_path.exists():
        logger.debug("Probe cache miss for '%s' (path: %s)", model_name, cache_path)
        return None

    data: dict[str, Any] = json.loads(cache_path.read_text())
    logger.debug("Probe cache hit for '%s'", model_name)
    return data
extract_activations_with_model
extract_activations_with_model(
    text: str,
    model: Any,
    tokenizer: Any,
    layer_indices: list[int] | None = None,
    model_name: str | None = None,
    max_length: int = 512,
) -> tuple[Any, Any]

Extract per-layer hidden state activations from a pre-loaded model.

Runs text through the model with output_hidden_states=True and stacks activations from the specified layer indices. Uses hidden_states[i] directly (no +1 offset) — consistent with existing sakana_d2l.py convention.

Parameters:

Name Type Description Default
text str

Input text to tokenize and process.

required
model Any

Pre-loaded nn.Module in eval mode.

required
tokenizer Any

Pre-loaded tokenizer.

required
layer_indices list[int] | None

Which hidden state indices to extract. If None, loads from probe cache via model_name.

None
model_name str | None

Canonical model name for cache lookup (required when layer_indices is None).

None
max_length int

Max token sequence length.

512

Returns:

Type Description
tuple[Any, Any]

Tuple of (features, attention_mask): features shape: (1, num_layers, seq_len, hidden_dim) attention_mask shape: (1, seq_len)

Raises:

Type Description
RuntimeError

If layer_indices is None and no probe cache exists for model_name.

Source code in libs/model-training/src/model_training/d2l_probe.py
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
def extract_activations_with_model(
    text: str,
    model: Any,
    tokenizer: Any,
    layer_indices: list[int] | None = None,
    model_name: str | None = None,
    max_length: int = 512,
) -> tuple[Any, Any]:
    """Extract per-layer hidden state activations from a pre-loaded model.

    Runs text through the model with output_hidden_states=True and stacks
    activations from the specified layer indices. Uses hidden_states[i] directly
    (no +1 offset) — consistent with existing sakana_d2l.py convention.

    Args:
        text: Input text to tokenize and process.
        model: Pre-loaded nn.Module in eval mode.
        tokenizer: Pre-loaded tokenizer.
        layer_indices: Which hidden state indices to extract. If None, loads
            from probe cache via model_name.
        model_name: Canonical model name for cache lookup (required when
            layer_indices is None).
        max_length: Max token sequence length.

    Returns:
        Tuple of (features, attention_mask):
            features shape: (1, num_layers, seq_len, hidden_dim)
            attention_mask shape: (1, seq_len)

    Raises:
        RuntimeError: If layer_indices is None and no probe cache exists for model_name.
    """
    import torch  # noqa: PLC0415

    if layer_indices is None:
        if model_name is None:
            msg = (
                "layer_indices is None and model_name is None — "
                "cannot load from probe cache without a model name."
            )
            raise RuntimeError(msg)
        cache = load_probe_cache(model_name)
        if cache is None:
            msg = (
                f"layer_indices is None but no probe cache found for '{model_name}'. "
                "Run probe_model() and save_probe_cache() first."
            )
            raise RuntimeError(msg)
        layer_indices = cache["attention_layer_indices"]

    # Determine device from model
    try:
        device = next(model.parameters()).device
    except StopIteration:
        device = torch.device("cpu")

    inputs = tokenizer(
        text, return_tensors="pt", truncation=True, max_length=max_length
    )
    inputs = {k: v.to(device) for k, v in inputs.items()}

    with torch.no_grad():
        outputs = model(**inputs, output_hidden_states=True)

    hidden_states = outputs.hidden_states
    # Stack selected layers: (batch, num_layers, seq_len, hidden_dim)
    selected = torch.stack([hidden_states[i] for i in layer_indices], dim=1)
    attention_mask = inputs["attention_mask"]

    logger.info(
        "Extracted activations: %s from %d layers", selected.shape, len(layer_indices)
    )
    return selected, attention_mask

d2l_train

KL-divergence context distillation training loop for Qwen3-Coder-Next.

Assembles all Phase 25-28 components (config, data pipeline, activation extraction, weight transfer, functional LoRA injection) into a complete distillation training script.

Three execution modes: - dry-run: loads real base model + hypernet, validates tensor shapes, exits - smoke-test: 5 training steps, verifies finite loss and decreasing trend - full: trains from JSONL dataset with tiered checkpointing and MLflow tracking

All heavy GPU imports (torch, transformers, peft) are deferred to function bodies per INFRA-05 project convention.

Usage

uv run python -m model_training.d2l_train --dry-run uv run python -m model_training.d2l_train --smoke-test uv run python -m model_training.d2l_train --dataset path/to/train.jsonl

Classes
D2LTrainConfig

Bases: BaseModel

Pydantic model for D2L training hyperparameters.

Enables validation, JSON serialization (for checkpoint storage), and .model_dump() for MLflow experiment logging.

Attributes:

Name Type Description
model_config_name str

Registry lookup key (e.g. "qwen3.5-9b"). Used to resolve base_model_name from the model registry when not set.

base_model_name str

HuggingFace model name for the student/teacher base.

sakana_checkpoint_path str

Path to the Sakana hypernet checkpoint.

num_steps int

Total training steps.

lr float

Learning rate for AdamW optimizer.

alpha float

Blending weight for KL vs CE loss (1.0 = pure KL, 0.0 = pure CE).

temperature float

Softmax temperature for KL divergence computation.

checkpoint_every int

Steps between lightweight checkpoint saves.

full_checkpoint_every int

Steps between full checkpoint saves (incl. optimizer).

checkpoint_dir str

Directory for checkpoint output.

experiment_name str

MLflow experiment name.

dry_run bool

If True, validate tensor shapes then exit.

smoke_test bool

If True, run 5 steps and verify loss trend.

dataset_path str | None

Path to training JSONL file (required for full training).

grad_clip float

Gradient clipping max norm.

warmup_steps int

Number of linear LR warmup steps.

lora_r int

LoRA rank.

max_length int

Maximum tokenizer sequence length.

Functions
model_post_init
model_post_init(__context: Any) -> None

Resolve base_model_name from registry when not explicitly set.

Source code in libs/model-training/src/model_training/d2l_train.py
117
118
119
120
121
122
123
def model_post_init(self, __context: Any) -> None:
    """Resolve base_model_name from registry when not explicitly set."""
    if not self.base_model_name:
        from model_training.model_configs import ModelRegistry

        mc = ModelRegistry.default().get(self.model_config_name)
        object.__setattr__(self, "base_model_name", mc.model_id)
Functions
train_d2l_qwen3
train_d2l_qwen3(
    config: D2LTrainConfig,
    *,
    kill_switch_evaluate_fn: Any = None,
) -> dict[str, Any]

Run KL-divergence context distillation training.

Three execution modes controlled by config flags: - dry_run=True: Validate shapes with single forward pass, no optimizer step. - smoke_test=True: Run min(num_steps, 5) steps, assert finite decreasing loss. - default: Full training from dataset with checkpointing and MLflow tracking.

Parameters:

Name Type Description Default
config D2LTrainConfig

Training configuration.

required
kill_switch_evaluate_fn Any

Zero-arg callable returning the current Pass@1 as a float. Required when config.kill_switch_enabled is True; ignored otherwise. Inject a closure built via :func:model_training.kill_switch.build_benchmark_evaluate_fn for production runs, or a mock for tests.

None

Returns:

Type Description
dict[str, Any]

Dictionary with training results: - final_loss: Loss at the last step. - best_loss: Lowest loss seen during training. - num_steps_completed: Number of training steps completed. - checkpoint_dir: Path to checkpoint directory. - shape_summary (dry_run only): Tensor shape validation results. - kill_switch_triggered: True when training halted early due to Pass@1 regression (only present when the kill-switch is enabled).

Source code in libs/model-training/src/model_training/d2l_train.py
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
def train_d2l_qwen3(  # noqa: C901
    config: D2LTrainConfig,
    *,
    kill_switch_evaluate_fn: Any = None,
) -> dict[str, Any]:
    """Run KL-divergence context distillation training.

    Three execution modes controlled by config flags:
    - dry_run=True: Validate shapes with single forward pass, no optimizer step.
    - smoke_test=True: Run min(num_steps, 5) steps, assert finite decreasing loss.
    - default: Full training from dataset with checkpointing and MLflow tracking.

    Args:
        config: Training configuration.
        kill_switch_evaluate_fn: Zero-arg callable returning the current Pass@1
            as a float. Required when ``config.kill_switch_enabled`` is True;
            ignored otherwise. Inject a closure built via
            :func:`model_training.kill_switch.build_benchmark_evaluate_fn` for
            production runs, or a mock for tests.

    Returns:
        Dictionary with training results:
            - final_loss: Loss at the last step.
            - best_loss: Lowest loss seen during training.
            - num_steps_completed: Number of training steps completed.
            - checkpoint_dir: Path to checkpoint directory.
            - shape_summary (dry_run only): Tensor shape validation results.
            - kill_switch_triggered: True when training halted early due to
              Pass@1 regression (only present when the kill-switch is enabled).
    """
    import mlflow  # noqa: PLC0415
    import torch  # noqa: PLC0415
    from ctx_to_lora.modeling.hypernet import HyperLoRA  # noqa: PLC0415
    from torch.nn.utils import clip_grad_norm_  # noqa: PLC0415
    from torch.optim import AdamW  # noqa: PLC0415
    from torch.optim.lr_scheduler import (  # noqa: PLC0415
        CosineAnnealingLR,
        LinearLR,
        SequentialLR,
    )
    from transformers import AutoModelForCausalLM, AutoTokenizer  # noqa: PLC0415

    from model_training.d2l_config import build_hypernet_config  # noqa: PLC0415
    from model_training.d2l_data import (  # noqa: PLC0415
        generate_needle_dataset,
        load_jsonl,
        split_by_task_id,
    )
    from model_training.sakana_d2l import (  # noqa: PLC0415
        get_aggregator_config,
        transfer_aggregator_weights,
    )

    # Mode dispatch: dry_run exits after shape validation
    if config.dry_run:
        shape_summary = _dry_run_validate_shapes(config)
        return {"shape_summary": shape_summary, "status": "dry_run_complete"}

    # Smoke test caps steps at 5
    if config.smoke_test:
        config = config.model_copy(update={"num_steps": min(config.num_steps, 5)})

    # Guard: require probe cache when not in smoke_test mode.
    # smoke_test uses generate_needle_dataset and may not have a real probe cache.
    if not config.smoke_test:
        _require_probe_cache(config.model_config_name)

    num_steps = config.num_steps
    warmup_steps = config.warmup_steps

    # Load tokenizer and base model
    logger.info("Loading tokenizer: %s", config.base_model_name)
    tokenizer = AutoTokenizer.from_pretrained(config.base_model_name)

    logger.info("Loading base model: %s", config.base_model_name)
    base_model = AutoModelForCausalLM.from_pretrained(
        config.base_model_name,
        output_hidden_states=True,
    ).eval()

    # Build hypernet config with aggregator config from checkpoint
    logger.info(
        "Building hypernet config from checkpoint: %s",
        config.sakana_checkpoint_path,
    )
    hc = build_hypernet_config(
        config.model_config_name,
        aggregator_config=get_aggregator_config(config.sakana_checkpoint_path),
        lora_r=config.lora_r,
    )

    # Create hypernet and transfer aggregator weights (freezes aggregator)
    hypernet = HyperLoRA(hc).to(torch.float32)
    hypernet = transfer_aggregator_weights(hypernet, config.sakana_checkpoint_path)
    hypernet.train()

    # Device selection: cuda > mps > cpu
    from shared.hardware import get_best_device  # noqa: PLC0415

    device = torch.device(get_best_device())
    logger.info("Using device: %s", device)
    base_model = base_model.to(device)
    hypernet = hypernet.to(device)

    # Optimizer: only trainable params (head + projections, not frozen aggregator)
    trainable_params = [p for p in hypernet.parameters() if p.requires_grad]
    logger.info("Trainable params: %d", sum(p.numel() for p in trainable_params))
    optimizer = AdamW(trainable_params, lr=config.lr)

    # Scheduler: linear warmup → cosine annealing
    scheduler = SequentialLR(
        optimizer,
        schedulers=[
            LinearLR(optimizer, start_factor=0.01, total_iters=warmup_steps),
            CosineAnnealingLR(
                optimizer,
                T_max=max(1, num_steps - warmup_steps),
                eta_min=1e-6,
            ),
        ],
        milestones=[warmup_steps],
    )

    # Data loading
    if config.smoke_test or config.dataset_path is None:
        records = generate_needle_dataset(n=20)
        logger.info("Using needle dataset (%d records)", len(records))
    else:
        all_records = load_jsonl(config.dataset_path)
        records, _ = split_by_task_id(all_records)
        logger.info(
            "Loaded %d training records from %s",
            len(records),
            config.dataset_path,
        )

    if not records:
        raise ValueError("No training records loaded; cannot train on empty dataset.")

    # MLflow setup and training loop
    _setup_mlflow(config)

    best_loss = float("inf")
    final_loss = float("inf")
    step_losses: list[float] = []

    # Kill-switch setup (Plan A follow-up). Disabled by default.
    from model_training.kill_switch import (  # noqa: PLC0415
        KillSwitchConfig,
        KillSwitchState,
        maybe_run_kill_switch,
    )

    ks_config = KillSwitchConfig(
        enabled=config.kill_switch_enabled,
        step_cadence=config.kill_switch_step_cadence,
        benchmark_id=config.kill_switch_benchmark_id,
        max_samples=config.kill_switch_max_samples,
        delta=config.kill_switch_delta,
    )
    ks_state = KillSwitchState()
    if ks_config.enabled and kill_switch_evaluate_fn is None:
        raise ValueError(
            "kill_switch_enabled=True requires kill_switch_evaluate_fn; "
            "build one via model_training.kill_switch.build_benchmark_evaluate_fn."
        )
    kill_switch_halted = False

    with mlflow.start_run(run_name=f"{config.experiment_name}-step{num_steps}"):
        mlflow.log_params(config.model_dump())

        for step in range(1, num_steps + 1):
            record = records[(step - 1) % len(records)]

            loss, metrics = _training_step(
                record=record,
                base_model=base_model,
                tokenizer=tokenizer,
                hypernet=hypernet,
                hc=hc,
                config=config,
            )

            loss.backward()
            clip_grad_norm_(trainable_params, config.grad_clip)
            optimizer.step()
            scheduler.step()
            optimizer.zero_grad()

            step_loss = metrics["total_loss"]
            step_losses.append(step_loss)
            final_loss = step_loss
            if step_loss < best_loss:
                best_loss = step_loss

            mlflow.log_metrics(metrics, step=step)
            logger.info(
                "Step %d/%d — loss=%.4f (kl=%.4f, ce=%.4f)",
                step,
                num_steps,
                metrics["total_loss"],
                metrics["kl_loss"],
                metrics["ce_loss"],
            )

            # Tiered checkpointing
            if step % config.full_checkpoint_every == 0:
                ckpt_path = _save_checkpoint(
                    step=step,
                    hypernet=hypernet,
                    optimizer=optimizer,
                    scheduler=scheduler,
                    config=config,
                    hc=hc,
                    best_loss=best_loss,
                    full=True,
                )
                mlflow.log_artifact(str(ckpt_path))
            elif step % config.checkpoint_every == 0:
                ckpt_path = _save_checkpoint(
                    step=step,
                    hypernet=hypernet,
                    optimizer=optimizer,
                    scheduler=scheduler,
                    config=config,
                    hc=hc,
                    best_loss=best_loss,
                    full=False,
                )
                mlflow.log_artifact(str(ckpt_path))

            # Kill-switch: evaluate Pass@1 at cadence and halt on regression.
            if maybe_run_kill_switch(
                step=step,
                config=ks_config,
                state=ks_state,
                evaluate_fn=kill_switch_evaluate_fn,
            ):
                kill_switch_halted = True
                _nan = float("nan")
                _last = (
                    ks_state.last_pass_at_1
                    if ks_state.last_pass_at_1 is not None
                    else _nan
                )
                _base = ks_state.baseline if ks_state.baseline is not None else _nan
                logger.error(
                    "Kill-switch halted training at step %d: "
                    "pass_at_1=%.3f baseline=%.3f delta=%.3f",
                    step,
                    _last,
                    _base,
                    ks_config.delta,
                )
                break

    # Smoke test assertions
    if config.smoke_test:
        for i, sl in enumerate(step_losses):
            assert torch.isfinite(torch.tensor(sl)), (  # noqa: S101
                f"Smoke test: loss at step {i + 1} is not finite: {sl}"
            )
        assert step_losses[-1] < step_losses[0], (  # noqa: S101
            f"Smoke test: final loss {step_losses[-1]:.4f} not less than "
            f"initial loss {step_losses[0]:.4f}"
        )
        assert any(p.grad is not None for p in trainable_params), (  # noqa: S101
            "Smoke test: no trainable param has non-None gradient after training"
        )

    result: dict[str, Any] = {
        "final_loss": final_loss,
        "best_loss": best_loss,
        "num_steps_completed": num_steps,
        "checkpoint_dir": config.checkpoint_dir,
    }
    if ks_config.enabled:
        result["kill_switch_triggered"] = kill_switch_halted
        result["kill_switch_baseline"] = ks_state.baseline
        result["kill_switch_last_pass_at_1"] = ks_state.last_pass_at_1
    return result

diff_loss

Line-level diff-aware loss weighting for SFT training.

GPU-heavy imports (torch, transformers) are deferred inside function bodies to ensure CPU-only importability (INFRA-05).

trl.SFTTrainer is imported at module top-level with a try/except guard so that DiffAwareSFTTrainer is importable on CPU-only machines (it falls back to subclassing object when trl is absent).

Classes
DiffWeightedDataCollator
DiffWeightedDataCollator(
    inner_collator: Any,
    *,
    changed_weight: float = 1.0,
    unchanged_weight: float = 0.3,
    tokenizer: Any | None = None,
)

Data collator that applies diff-aware loss weights to SFT batches.

Wraps an inner collator (e.g. trl.DataCollatorForCompletionOnlyLM). On each __call__, the inner collator runs first to produce batch["input_ids"] and batch["labels"]. Diff weights are then computed and stored as batch["loss_weights"].

Hunk path (preferred): When all features carry pre_code / post_code side-channel columns AND a tokenizer is provided, weights are computed via :func:_compute_hunk_ranges + :func:compute_hunk_loss_weights. The tokenizer is used to re-tokenize post_code with return_offsets_mapping=True to obtain char-to-token alignment.

Fallback path

When any feature is missing pre_code / post_code or no tokenizer was supplied, the legacy set-based :func:compute_diff_loss_weights is used and a one-time logger.warning is emitted.

Parameters:

Name Type Description Default
inner_collator Any

The underlying data collator.

required
changed_weight float

Weight for changed / inserted tokens.

1.0
unchanged_weight float

Weight for equal (context) tokens.

0.3
tokenizer Any | None

Optional tokenizer. Required to use the hunk path.

None

Initialise the collator.

Parameters:

Name Type Description Default
inner_collator Any

The underlying data collator.

required
changed_weight float

Weight for changed / inserted tokens.

1.0
unchanged_weight float

Weight for unchanged (context) tokens.

0.3
tokenizer Any | None

Optional tokenizer; enables the hunk path when set.

None
Source code in libs/model-training/src/model_training/diff_loss.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
def __init__(
    self,
    inner_collator: Any,
    *,
    changed_weight: float = 1.0,
    unchanged_weight: float = 0.3,
    tokenizer: Any | None = None,
) -> None:
    """Initialise the collator.

    Args:
        inner_collator: The underlying data collator.
        changed_weight: Weight for changed / inserted tokens.
        unchanged_weight: Weight for unchanged (context) tokens.
        tokenizer: Optional tokenizer; enables the hunk path when set.
    """
    self.inner_collator = inner_collator
    self.changed_weight = changed_weight
    self.unchanged_weight = unchanged_weight
    self.tokenizer = tokenizer
DiffAwareSFTTrainer

Bases: SFTTrainer

SFTTrainer that applies per-token loss weights from the batch.

Expects the data collator (e.g. DiffWeightedDataCollator) to populate batch["loss_weights"] as a Tensor[batch, seq_len] float32 aligned with labels. The weighted loss is:

L = sum(per_token_CE * loss_weights * label_mask) /
    sum(loss_weights * label_mask)

where label_mask = (labels != IGNORE_INDEX). This reduces to the standard CE loss when all loss_weights == 1.0, so the identity-under-uniform-weights invariant holds.

When loss_weights is absent from the batch, falls back to standard SFTTrainer loss (no KeyError).

Functions
compute_loss
compute_loss(
    model: Any,
    inputs: dict[str, Any],
    return_outputs: bool = False,
    num_items_in_batch: Any = None,
) -> Any

Compute weighted cross-entropy loss.

Pops loss_weights from inputs before the forward pass so the model never receives an unexpected keyword argument. When loss_weights is absent, delegates to the parent implementation.

Parameters:

Name Type Description Default
model Any

The language model.

required
inputs dict[str, Any]

Batch dict (possibly containing "loss_weights").

required
return_outputs bool

If True, return (loss, outputs) tuple.

False
num_items_in_batch Any

Passed through to parent when falling back.

None

Returns:

Type Description
Any

Scalar loss, or (loss, outputs) when return_outputs=True.

Source code in libs/model-training/src/model_training/diff_loss.py
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
def compute_loss(
    self,
    model: Any,
    inputs: dict[str, Any],
    return_outputs: bool = False,
    num_items_in_batch: Any = None,
) -> Any:
    """Compute weighted cross-entropy loss.

    Pops ``loss_weights`` from ``inputs`` before the forward pass so the
    model never receives an unexpected keyword argument.  When
    ``loss_weights`` is absent, delegates to the parent implementation.

    Args:
        model: The language model.
        inputs: Batch dict (possibly containing ``"loss_weights"``).
        return_outputs: If ``True``, return ``(loss, outputs)`` tuple.
        num_items_in_batch: Passed through to parent when falling back.

    Returns:
        Scalar loss, or ``(loss, outputs)`` when ``return_outputs=True``.
    """
    loss_weights = inputs.pop("loss_weights", None)

    if loss_weights is None:
        # No weights provided — fall back to the model's own CE loss.
        # HuggingFace causal-LM heads honor -100 label masking internally,
        # so outputs.loss is standard CE on the labeled tokens. Avoids
        # super().compute_loss() which depends on full Trainer init state
        # (self.model, self.processing_class, …) and can't be exercised
        # from a minimal subclass used in unit tests.
        outputs = model(**inputs)
        return (outputs.loss, outputs) if return_outputs else outputs.loss

    outputs = model(**inputs)
    logits = outputs.logits
    labels = inputs["labels"]

    # Move loss_weights to the same device as logits.
    loss_weights = loss_weights.to(logits.device)

    loss = _compute_weighted_loss(logits, labels, loss_weights)
    return (loss, outputs) if return_outputs else loss
Functions
compute_hunk_loss_weights
compute_hunk_loss_weights(
    input_ids: list[int],
    labels: list[int],
    offset_mapping: list[tuple[int, int]],
    hunk_ranges_chars: list[tuple[int, int]],
    *,
    changed_weight: float = 1.0,
    unchanged_weight: float = 0.3,
) -> list[float]

Map hunk char ranges to tokens via offset_mapping; produce per-token weights.

Weight assignment rules:

  • Masked positions (labels[i] == IGNORE_INDEX) → 0.0.
  • Special tokens where offset_mapping[i] == (0, 0) → 0.0 (BOS, padding, etc.).
  • Assistant-turn tokens whose offset intersects any hunk range → changed_weight.
  • Assistant-turn tokens outside all hunk ranges → unchanged_weight.

Token i intersects hunk [s, e) iff offset_mapping[i] == (a, b) satisfies a < e and b > s.

Identity invariant: when changed_weight == unchanged_weight, every non-masked, non-special assistant token gets that single weight.

Parameters:

Name Type Description Default
input_ids list[int]

Token IDs for the full sequence.

required
labels list[int]

Label IDs; IGNORE_INDEX marks non-assistant positions.

required
offset_mapping list[tuple[int, int]]

(start, end) char offsets for each token in the source text. (0, 0) indicates a special/padding token.

required
hunk_ranges_chars list[tuple[int, int]]

Half-open (start, end) char ranges from _compute_hunk_ranges.

required
changed_weight float

Weight for tokens inside a hunk range.

1.0
unchanged_weight float

Weight for assistant tokens outside any hunk range.

0.3

Returns:

Type Description
list[float]

Per-token float weights of the same length as input_ids.

Source code in libs/model-training/src/model_training/diff_loss.py
 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
def compute_hunk_loss_weights(
    input_ids: list[int],
    labels: list[int],
    offset_mapping: list[tuple[int, int]],
    hunk_ranges_chars: list[tuple[int, int]],
    *,
    changed_weight: float = 1.0,
    unchanged_weight: float = 0.3,
) -> list[float]:
    """Map hunk char ranges to tokens via offset_mapping; produce per-token weights.

    Weight assignment rules:

    - Masked positions (``labels[i] == IGNORE_INDEX``) → ``0.0``.
    - Special tokens where ``offset_mapping[i] == (0, 0)`` → ``0.0`` (BOS,
      padding, etc.).
    - Assistant-turn tokens whose offset intersects any hunk range
      → ``changed_weight``.
    - Assistant-turn tokens outside all hunk ranges → ``unchanged_weight``.

    Token *i* intersects hunk ``[s, e)`` iff ``offset_mapping[i] == (a, b)``
    satisfies ``a < e and b > s``.

    Identity invariant: when ``changed_weight == unchanged_weight``, every
    non-masked, non-special assistant token gets that single weight.

    Args:
        input_ids: Token IDs for the full sequence.
        labels: Label IDs; ``IGNORE_INDEX`` marks non-assistant positions.
        offset_mapping: ``(start, end)`` char offsets for each token in the
            source text.  ``(0, 0)`` indicates a special/padding token.
        hunk_ranges_chars: Half-open ``(start, end)`` char ranges from
            ``_compute_hunk_ranges``.
        changed_weight: Weight for tokens inside a hunk range.
        unchanged_weight: Weight for assistant tokens outside any hunk range.

    Returns:
        Per-token float weights of the same length as ``input_ids``.
    """
    n = len(input_ids)
    weights: list[float] = []

    for i in range(n):
        label = labels[i] if i < len(labels) else IGNORE_INDEX
        if label == IGNORE_INDEX:
            weights.append(0.0)
            continue

        om = offset_mapping[i] if i < len(offset_mapping) else (0, 0)
        tok_start, tok_end = om

        # Special / padding tokens emitted as (0, 0) by the tokenizer.
        if tok_start == 0 and tok_end == 0:
            weights.append(0.0)
            continue

        # Check intersection with any hunk range.
        in_hunk = any(
            tok_start < h_end and tok_end > h_start
            for h_start, h_end in hunk_ranges_chars
        )
        weights.append(changed_weight if in_hunk else unchanged_weight)

    return weights
compute_diff_loss_weights
compute_diff_loss_weights(
    input_ids: list[int],
    labels: list[int],
    changed_ids: set[int],
    *,
    changed_weight: float = 1.0,
    unchanged_weight: float = 0.3,
) -> list[float]

Compute per-token loss weights based on a set of changed token IDs.

.. deprecated:: Prefer :func:compute_hunk_loss_weights with pre_code/post_code side-channels. This set-based fallback cannot distinguish where a token appears, only whether its ID was seen in the diff.

Parameters:

Name Type Description Default
input_ids list[int]

Token IDs for the full sequence.

required
labels list[int]

Label IDs; IGNORE_INDEX marks non-assistant positions.

required
changed_ids set[int]

Set of token IDs considered "changed" by the diff.

required
changed_weight float

Weight assigned to tokens whose ID is in changed_ids.

1.0
unchanged_weight float

Weight assigned to non-masked tokens whose ID is not in changed_ids.

0.3

Returns:

Type Description
list[float]

Per-token float weights of the same length as input_ids.

Source code in libs/model-training/src/model_training/diff_loss.py
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
def compute_diff_loss_weights(
    input_ids: list[int],
    labels: list[int],
    changed_ids: set[int],
    *,
    changed_weight: float = 1.0,
    unchanged_weight: float = 0.3,
) -> list[float]:
    """Compute per-token loss weights based on a set of changed token IDs.

    .. deprecated::
        Prefer :func:`compute_hunk_loss_weights` with ``pre_code``/``post_code``
        side-channels.  This set-based fallback cannot distinguish *where* a
        token appears, only *whether* its ID was seen in the diff.

    Args:
        input_ids: Token IDs for the full sequence.
        labels: Label IDs; ``IGNORE_INDEX`` marks non-assistant positions.
        changed_ids: Set of token IDs considered "changed" by the diff.
        changed_weight: Weight assigned to tokens whose ID is in
            ``changed_ids``.
        unchanged_weight: Weight assigned to non-masked tokens whose ID is
            not in ``changed_ids``.

    Returns:
        Per-token float weights of the same length as ``input_ids``.
    """
    weights: list[float] = []
    for token_id, label in zip(input_ids, labels):
        if label == IGNORE_INDEX:
            weights.append(0.0)
        elif token_id in changed_ids:
            weights.append(changed_weight)
        else:
            weights.append(unchanged_weight)
    return weights
build_diff_aware_sft_trainer
build_diff_aware_sft_trainer(
    model: Any,
    args: Any,
    train_dataset: Any,
    *,
    peft_config: Any | None = None,
    processing_class: Any | None = None,
    changed_weight: float = 1.0,
    unchanged_weight: float = 0.3,
    tokenizer: Any | None = None,
) -> Any

Build an SFTTrainer that uses diff-aware loss weighting.

Constructs a :class:DiffWeightedDataCollator wrapping trl's DataCollatorForLanguageModeling (completion-only masking via completion_mask/assistant_masks set upstream by SFTTrainer's chat-template preprocessing), then instantiates :class:DiffAwareSFTTrainer with it.

The tokenizer kwarg enables the hunk (line-level diff) path in the collator. When None (default), the collator falls back to the legacy set-based path. Task 5 threads the tokenizer through trainer.py::_construct_sft_trainer; until then, callers may pass it explicitly here.

All GPU imports are deferred to this function body (INFRA-05).

Parameters:

Name Type Description Default
model Any

The language model (or PEFT-wrapped model).

required
args Any

trl.SFTConfig training arguments.

required
train_dataset Any

HuggingFace dataset with SFT examples.

required
peft_config Any | None

Optional PEFT config for fresh LoRA init.

None
processing_class Any | None

Tokenizer / processor for the SFTTrainer.

None
changed_weight float

Weight for changed / inserted tokens.

1.0
unchanged_weight float

Weight for unchanged (context) tokens.

0.3
tokenizer Any | None

Optional tokenizer passed to :class:DiffWeightedDataCollator to enable the hunk path. Falls back to processing_class if tokenizer is None and processing_class is provided.

None

Returns:

Type Description
Any

A configured :class:DiffAwareSFTTrainer instance.

Raises:

Type Description
RuntimeError

If resolved_tokenizer.pad_token_id is None. trl's DataCollatorForLanguageModeling requires an explicit pad id.

Source code in libs/model-training/src/model_training/diff_loss.py
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
def build_diff_aware_sft_trainer(
    model: Any,
    args: Any,
    train_dataset: Any,
    *,
    peft_config: Any | None = None,
    processing_class: Any | None = None,
    changed_weight: float = 1.0,
    unchanged_weight: float = 0.3,
    tokenizer: Any | None = None,
) -> Any:
    """Build an SFTTrainer that uses diff-aware loss weighting.

    Constructs a :class:`DiffWeightedDataCollator` wrapping trl's
    ``DataCollatorForLanguageModeling`` (completion-only masking via
    ``completion_mask``/``assistant_masks`` set upstream by SFTTrainer's
    chat-template preprocessing), then instantiates
    :class:`DiffAwareSFTTrainer` with it.

    The ``tokenizer`` kwarg enables the hunk (line-level diff) path in the
    collator.  When ``None`` (default), the collator falls back to the legacy
    set-based path.  Task 5 threads the tokenizer through
    ``trainer.py::_construct_sft_trainer``; until then, callers may pass it
    explicitly here.

    All GPU imports are deferred to this function body (INFRA-05).

    Args:
        model: The language model (or PEFT-wrapped model).
        args: ``trl.SFTConfig`` training arguments.
        train_dataset: HuggingFace dataset with SFT examples.
        peft_config: Optional PEFT config for fresh LoRA init.
        processing_class: Tokenizer / processor for the SFTTrainer.
        changed_weight: Weight for changed / inserted tokens.
        unchanged_weight: Weight for unchanged (context) tokens.
        tokenizer: Optional tokenizer passed to :class:`DiffWeightedDataCollator`
            to enable the hunk path.  Falls back to ``processing_class`` if
            ``tokenizer`` is ``None`` and ``processing_class`` is provided.

    Returns:
        A configured :class:`DiffAwareSFTTrainer` instance.

    Raises:
        RuntimeError: If ``resolved_tokenizer.pad_token_id`` is ``None``.
            trl's DataCollatorForLanguageModeling requires an explicit pad id.
    """
    # trl 0.19+ relocated DataCollatorForLanguageModeling (with completion-only
    # masking) into trl.trainer.sft_trainer; the legacy top-level
    # DataCollatorForCompletionOnlyLM was removed.
    from trl.trainer.sft_trainer import (  # type: ignore[attr-defined]
        DataCollatorForLanguageModeling,
    )

    resolved_tokenizer = tokenizer if tokenizer is not None else processing_class

    pad_token_id = getattr(resolved_tokenizer, "pad_token_id", None)
    if pad_token_id is None:
        pad_token_id = getattr(resolved_tokenizer, "eos_token_id", None)
    if pad_token_id is None:
        raise RuntimeError(
            "build_diff_aware_sft_trainer requires a tokenizer with "
            "pad_token_id or eos_token_id set."
        )

    # Forward args.max_length / args.truncation_mode so the diff-aware path
    # respects the SFTConfig sequence cap. The standard SFTTrainer path threads
    # these into the collator at sft_trainer.py:893; bypassing that path (as we
    # do here) without forwarding the cap means every sequence reaches the GPU
    # uncapped — at Qwen3.5-9B vocab=152k, the cross-entropy logits tensor
    # alone OOMs an L4 at seq_len ~8k.
    inner_collator = DataCollatorForLanguageModeling(
        pad_token_id=pad_token_id,
        completion_only_loss=True,
        max_length=getattr(args, "max_length", None),
        truncation_mode=getattr(args, "truncation_mode", "keep_start"),
    )
    collator = DiffWeightedDataCollator(
        inner_collator,
        changed_weight=changed_weight,
        unchanged_weight=unchanged_weight,
        tokenizer=resolved_tokenizer,
    )

    return DiffAwareSFTTrainer(
        model=model,
        args=args,
        train_dataset=train_dataset,
        peft_config=peft_config,
        processing_class=processing_class,
        data_collator=collator,
    )

encoder_pretrain

Trajectory encoder pretraining subpackage.

Pretrains a coding-aware sentence encoder (option a: InfoNCE fine-tuning of all-mpnet-base-v2) on augmented mined coding pairs from data/pairs/.

Strict: task_description field required; pairs without it are dropped.

Public API

from model_training.encoder_pretrain.augment import augment_corpus from model_training.encoder_pretrain.train_encoder import run_training from model_training.encoder_pretrain.eval_encoder import run_retrieval_eval

Modules
augment

Pair augmentation: associate task descriptions with mined coding pairs.

Loads normalized mined pairs (data/pairs/*.jsonl), extracts pre_code / post_code from the activation_text / teacher_text fields, and associates a task_description via strict field access only:

strict: ``task_description`` field required; pairs without it are dropped.

Each output row records task_desc_source (always "explicit_field") so downstream consumers can audit which source was used.

All GPU imports are omitted (INFRA-05); this module is CPU-safe.

Functions
augment_pairs_with_task_desc
augment_pairs_with_task_desc(
    pairs: list[dict[str, Any]],
) -> list[dict[str, Any]]

Augment a list of mined pairs with task descriptions.

For each pair, reads the explicit task_description field. Pairs where task_description is missing, None, or empty-after-strip are dropped with a WARNING log. Kept pairs are returned as augmented row dicts with task_desc_source set to "explicit_field".

Parameters:

Name Type Description Default
pairs list[dict[str, Any]]

List of mined pair dicts from normalize_mined_pairs.

required

Returns:

Type Description
list[dict[str, Any]]

List of augmented row dicts with fields: task_id, pre_code,

list[dict[str, Any]]

post_code, task_desc, task_desc_source, encoder_input, metadata.

Source code in libs/model-training/src/model_training/encoder_pretrain/augment.py
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
def augment_pairs_with_task_desc(
    pairs: list[dict[str, Any]],
) -> list[dict[str, Any]]:
    """Augment a list of mined pairs with task descriptions.

    For each pair, reads the explicit ``task_description`` field. Pairs
    where ``task_description`` is missing, None, or empty-after-strip are
    dropped with a WARNING log. Kept pairs are returned as augmented row
    dicts with ``task_desc_source`` set to ``"explicit_field"``.

    Args:
        pairs: List of mined pair dicts from normalize_mined_pairs.

    Returns:
        List of augmented row dicts with fields: task_id, pre_code,
        post_code, task_desc, task_desc_source, encoder_input, metadata.
    """
    if not pairs:
        return []

    dropped = 0
    kept: list[dict[str, Any]] = []
    for pair in pairs:
        desc = _select_task_desc(pair)
        if desc is None:
            dropped += 1
            continue
        kept.append(_build_row(pair, desc))

    if dropped:
        logger.warning(
            "augment: dropped %d/%d pairs with missing task_description",
            dropped,
            len(pairs),
        )
    logger.info("augment: kept %d augmented pairs", len(kept))
    return kept
augment_corpus
augment_corpus(
    pairs_dir: Path, output_dir: Path, glob: str = "*.jsonl"
) -> None

Augment all mined-pair JSONL files in pairs_dir and write to output_dir.

Reads each <repo>.jsonl from pairs_dir, calls augment_pairs_with_task_desc, and writes the resulting rows to output_dir/<repo>.jsonl. Existing output files are overwritten.

Enforces a minimum retention ratio: if fewer than MIN_RETENTION_RATIO (0.80) of all input pairs survive augmentation, raises RuntimeError directing the operator to re-run the mining pipeline with issue/PR task_description population.

Parameters:

Name Type Description Default
pairs_dir Path

Directory containing mined pair JSONL files (e.g. data/pairs/).

required
output_dir Path

Destination directory for augmented JSONL (e.g. data/pairs_augmented/).

required
glob str

Glob pattern for JSONL files within pairs_dir.

'*.jsonl'

Raises:

Type Description
FileNotFoundError

If pairs_dir does not exist.

RuntimeError

If retention ratio < MIN_RETENTION_RATIO.

Source code in libs/model-training/src/model_training/encoder_pretrain/augment.py
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
def augment_corpus(
    pairs_dir: Path,
    output_dir: Path,
    glob: str = "*.jsonl",
) -> None:
    """Augment all mined-pair JSONL files in pairs_dir and write to output_dir.

    Reads each ``<repo>.jsonl`` from ``pairs_dir``, calls
    ``augment_pairs_with_task_desc``, and writes the resulting rows to
    ``output_dir/<repo>.jsonl``. Existing output files are overwritten.

    Enforces a minimum retention ratio: if fewer than
    ``MIN_RETENTION_RATIO`` (0.80) of all input pairs survive augmentation,
    raises RuntimeError directing the operator to re-run the mining pipeline
    with issue/PR task_description population.

    Args:
        pairs_dir: Directory containing mined pair JSONL files (e.g. data/pairs/).
        output_dir: Destination directory for augmented JSONL (e.g.
            data/pairs_augmented/).
        glob: Glob pattern for JSONL files within pairs_dir.

    Raises:
        FileNotFoundError: If pairs_dir does not exist.
        RuntimeError: If retention ratio < MIN_RETENTION_RATIO.
    """
    if not pairs_dir.exists():
        raise FileNotFoundError(
            f"pairs_dir does not exist: {pairs_dir}. "
            "Run scripts/mine_github.py first to populate data/pairs/."
        )

    output_dir.mkdir(parents=True, exist_ok=True)
    jsonl_files = sorted(pairs_dir.glob(glob))

    if not jsonl_files:
        logger.warning(
            "augment_corpus: no JSONL files found in %s matching %s",
            pairs_dir,
            glob,
        )
        return

    # First pass: count totals for retention gate
    total = 0
    kept_total = 0
    per_file: list[tuple[Path, list[dict[str, Any]]]] = []

    for src_path in jsonl_files:
        logger.info("Augmenting %s ...", src_path.name)
        pairs = load_jsonl(src_path)
        rows = augment_pairs_with_task_desc(pairs)
        total += len(pairs)
        kept_total += len(rows)
        per_file.append((src_path, rows))

    if total > 0 and (kept_total / total) < MIN_RETENTION_RATIO:
        raise RuntimeError(
            f"augment_corpus: only {kept_total}/{total} "
            f"({100 * kept_total / total:.1f}%) mined pairs have a "
            f"task_description. Re-run the mining pipeline with "
            f"issue/PR task_description population before continuing."
        )

    for src_path, rows in per_file:
        dest = output_dir / src_path.name
        save_jsonl(rows, dest)
        logger.info("  -> wrote %d rows to %s", len(rows), dest)

    logger.info(
        "augment_corpus complete: %d total rows across %d files",
        kept_total,
        len(jsonl_files),
    )
cli

Command-line entrypoint for encoder pretraining.

Accepts all flags that map 1:1 to EncoderTrainingConfig fields and exposes a --dry-run mode that resolves arguments and prints them as JSON without loading any GPU libraries, to support CI validation.

All heavy imports (torch, transformers, sentence_transformers) are deferred to the call site inside run_training — this CLI itself is CPU-safe.

Usage::

uv run python -m model_training.encoder_pretrain.cli \
    --augmented-dir data/pairs_augmented \
    --output-dir data/encoder_checkpoint \
    --epochs 5 \
    --batch-size 64 \
    --dry-run
Functions
main
main(argv: list[str] | None = None) -> int

Parse argv, dispatch to run_training (or dry-run and exit).

Parameters:

Name Type Description Default
argv list[str] | None

Command-line arguments (defaults to sys.argv[1:]).

None

Returns:

Type Description
int

Exit code (0 = success, non-zero = error).

Source code in libs/model-training/src/model_training/encoder_pretrain/cli.py
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
def main(argv: list[str] | None = None) -> int:
    """Parse argv, dispatch to run_training (or dry-run and exit).

    Args:
        argv: Command-line arguments (defaults to sys.argv[1:]).

    Returns:
        Exit code (0 = success, non-zero = error).
    """
    logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s %(message)s")
    parser = _build_parser()
    args = parser.parse_args(argv)
    config_dict = _resolve_config(args)

    if args.dry_run:
        print(json.dumps(config_dict, indent=2, sort_keys=True))
        return 0

    # Deferred to keep --dry-run CPU-only (INFRA-05).
    from pathlib import Path  # noqa: PLC0415

    from model_training.encoder_pretrain.train_encoder import (  # noqa: PLC0415
        EncoderTrainingConfig,
        run_training,
    )

    config = EncoderTrainingConfig(
        augmented_dir=Path(args.augmented_dir),
        output_dir=Path(args.output_dir),
        base_encoder=args.base_encoder,
        temperature=args.temperature,
        batch_size=args.batch_size,
        learning_rate=args.learning_rate,
        epochs=args.epochs,
        max_length=args.max_length,
        warmup_steps=args.warmup_steps,
        test_fraction=args.test_fraction,
        seed=args.seed,
        mlflow_experiment=args.mlflow_experiment,
        mlflow_tracking_uri=args.mlflow_tracking_uri,
    )
    run_training(config)
    return 0
dataset

Contrastive pair dataset and tokenizing collator for encoder pretraining.

Loads augmented JSONL files from an output directory (produced by augment.py) and exposes them as a PyTorch Dataset of (anchor, positive) string pairs.

ContrastiveCollator tokenizes both sides symmetrically and returns batched input_ids / attention_mask tensors prefixed anchor_ and positive_.

All GPU-dependent imports (torch, transformers) are deferred inside class bodies / method bodies per INFRA-05.

Classes
ContrastivePairDataset
ContrastivePairDataset(rows: list[dict[str, Any]])

PyTorch-compatible dataset of (encoder_input, post_code) pairs.

Loads all *.jsonl files from a directory of augmented pairs. Rows where post_code is empty are skipped so the collator always receives a valid positive target.

Parameters:

Name Type Description Default
rows list[dict[str, Any]]

List of augmented pair dicts as produced by augment_corpus.

required

Initialise dataset from a list of augmented pair dicts.

Parameters:

Name Type Description Default
rows list[dict[str, Any]]

Augmented pair dicts; rows with empty post_code are skipped.

required
Source code in libs/model-training/src/model_training/encoder_pretrain/dataset.py
34
35
36
37
38
39
40
41
42
43
44
45
46
def __init__(self, rows: list[dict[str, Any]]) -> None:
    """Initialise dataset from a list of augmented pair dicts.

    Args:
        rows: Augmented pair dicts; rows with empty post_code are skipped.
    """
    self._rows = [r for r in rows if r.get("post_code", "").strip()]
    skipped = len(rows) - len(self._rows)
    if skipped > 0:
        logger.warning(
            "ContrastivePairDataset: skipped %d rows with empty post_code",
            skipped,
        )
Functions
from_dir classmethod
from_dir(
    augmented_dir: Path, glob: str = "*.jsonl"
) -> "ContrastivePairDataset"

Load all augmented JSONL files from augmented_dir.

Parameters:

Name Type Description Default
augmented_dir Path

Directory containing augmented pair JSONL files.

required
glob str

Glob pattern to match files.

'*.jsonl'

Returns:

Type Description
'ContrastivePairDataset'

ContrastivePairDataset with all rows combined.

Raises:

Type Description
FileNotFoundError

If augmented_dir does not exist.

Source code in libs/model-training/src/model_training/encoder_pretrain/dataset.py
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
@classmethod
def from_dir(
    cls, augmented_dir: Path, glob: str = "*.jsonl"
) -> "ContrastivePairDataset":
    """Load all augmented JSONL files from augmented_dir.

    Args:
        augmented_dir: Directory containing augmented pair JSONL files.
        glob: Glob pattern to match files.

    Returns:
        ContrastivePairDataset with all rows combined.

    Raises:
        FileNotFoundError: If augmented_dir does not exist.
    """
    if not augmented_dir.exists():
        raise FileNotFoundError(
            f"augmented_dir does not exist: {augmented_dir}. "
            "Run augment_corpus first."
        )
    all_rows: list[dict[str, Any]] = []
    for path in sorted(augmented_dir.glob(glob)):
        with path.open(encoding="utf-8") as fh:
            for line in fh:
                line = line.strip()
                if line:
                    all_rows.append(json.loads(line))
    logger.info(
        "ContrastivePairDataset.from_dir: loaded %d rows from %s",
        len(all_rows),
        augmented_dir,
    )
    return cls(all_rows)
ContrastiveCollator
ContrastiveCollator(tokenizer: Any, max_length: int = 512)

Tokenize (anchor, positive) string pairs into padded batch tensors.

Returns a dict with keys anchor_input_ids, anchor_attention_mask, positive_input_ids, positive_attention_mask — all LongTensor[batch, max_length].

Parameters:

Name Type Description Default
tokenizer Any

A HuggingFace tokenizer (e.g. from AutoTokenizer).

required
max_length int

Maximum sequence length; sequences are truncated and padded to exactly this length.

512
Source code in libs/model-training/src/model_training/encoder_pretrain/dataset.py
107
108
109
def __init__(self, tokenizer: Any, max_length: int = 512) -> None:  # noqa: D107
    self._tokenizer = tokenizer
    self._max_length = max_length
eval_encoder

Retrieval eval and downstream cluster probe for encoder pretraining.

Retrieval eval: given the held-out test split, embed each anchor (encoder_input) and each positive (post_code), then rank positives by cosine similarity to each anchor. Reports MRR@10 and Recall@1.

Cluster probe: embed a sample of HumanEval + MBPP problem descriptions (loaded via HuggingFace datasets), compute intra-cluster vs inter-cluster mean cosine similarity as a simple cohesion score. Used as a sanity check that the encoder groups semantically similar problems; does NOT require the full benchmark harness.

All GPU-dependent imports are deferred (INFRA-05).

Functions
run_retrieval_eval
run_retrieval_eval(
    *,
    model: Any,
    tokenizer: Any,
    test_rows: list[dict[str, Any]],
    max_length: int,
    batch_size: int,
    device: str,
) -> dict[str, float]

Compute MRR@10 and Recall@1 on a held-out test split.

For each anchor embedding, rank all positive embeddings by cosine similarity and check the rank of the true positive (diagonal entry).

Parameters:

Name Type Description Default
model Any

HuggingFace AutoModel; already on device.

required
tokenizer Any

Matching HuggingFace tokenizer.

required
test_rows list[dict[str, Any]]

Augmented pair dicts (must have encoder_input and post_code keys).

required
max_length int

Truncation length.

required
batch_size int

Inference batch size.

required
device str

Device string.

required

Returns:

Type Description
dict[str, float]

Dict with "mrr_at_10" and "recall_at_1" float metrics.

Source code in libs/model-training/src/model_training/encoder_pretrain/eval_encoder.py
 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
def run_retrieval_eval(
    *,
    model: Any,
    tokenizer: Any,
    test_rows: list[dict[str, Any]],
    max_length: int,
    batch_size: int,
    device: str,
) -> dict[str, float]:
    """Compute MRR@10 and Recall@1 on a held-out test split.

    For each anchor embedding, rank all positive embeddings by cosine
    similarity and check the rank of the true positive (diagonal entry).

    Args:
        model: HuggingFace AutoModel; already on ``device``.
        tokenizer: Matching HuggingFace tokenizer.
        test_rows: Augmented pair dicts (must have ``encoder_input`` and
            ``post_code`` keys).
        max_length: Truncation length.
        batch_size: Inference batch size.
        device: Device string.

    Returns:
        Dict with ``"mrr_at_10"`` and ``"recall_at_1"`` float metrics.
    """
    import torch  # noqa: PLC0415

    if not test_rows:
        return {"mrr_at_10": 0.0, "recall_at_1": 0.0}

    anchors_text = [r["encoder_input"] for r in test_rows]
    positives_text = [r["post_code"] for r in test_rows]

    model.eval()
    anchor_embs = _embed_texts(
        model, tokenizer, anchors_text, max_length, batch_size, device
    )
    positive_embs = _embed_texts(
        model, tokenizer, positives_text, max_length, batch_size, device
    )

    # (N, N) similarity matrix
    sim_matrix = torch.matmul(anchor_embs, positive_embs.T)
    n = sim_matrix.shape[0]

    mrr_sum = 0.0
    recall_at_1_sum = 0.0

    for i in range(n):
        scores = sim_matrix[i]  # (N,)
        # Rank is 1-indexed; higher score = rank 1
        rank = int((scores > scores[i]).sum().item()) + 1
        if rank <= 10:
            mrr_sum += 1.0 / rank
        if rank == 1:
            recall_at_1_sum += 1.0

    mrr_at_10 = mrr_sum / n
    recall_at_1 = recall_at_1_sum / n

    logger.info(
        "retrieval_eval: n=%d MRR@10=%.4f Recall@1=%.4f",
        n,
        mrr_at_10,
        recall_at_1,
    )
    return {"mrr_at_10": mrr_at_10, "recall_at_1": recall_at_1}
run_cluster_probe
run_cluster_probe(
    *,
    model: Any,
    tokenizer: Any,
    max_length: int,
    batch_size: int,
    device: str,
    n_humaneval: int = 50,
    n_mbpp: int = 50,
) -> dict[str, float]

Cohesion probe: do HumanEval and MBPP cluster separately?

Loads n_humaneval problems from HumanEval (via datasets) and n_mbpp from MBPP, embeds their prompts, and computes mean intra-cluster cosine similarity vs mean inter-cluster cosine similarity. A positive cohesion_delta indicates the encoder groups similar problems together.

Does NOT require the full benchmark harness — uses datasets directly.

Parameters:

Name Type Description Default
model Any

HuggingFace AutoModel; already on device.

required
tokenizer Any

Matching HuggingFace tokenizer.

required
max_length int

Truncation length.

required
batch_size int

Inference batch size.

required
device str

Device string.

required
n_humaneval int

Number of HumanEval problems to sample.

50
n_mbpp int

Number of MBPP problems to sample.

50

Returns:

Type Description
dict[str, float]

Dict with "intra_sim", "inter_sim", and "cohesion_delta"

dict[str, float]

float metrics.

Source code in libs/model-training/src/model_training/encoder_pretrain/eval_encoder.py
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
def run_cluster_probe(
    *,
    model: Any,
    tokenizer: Any,
    max_length: int,
    batch_size: int,
    device: str,
    n_humaneval: int = 50,
    n_mbpp: int = 50,
) -> dict[str, float]:
    """Cohesion probe: do HumanEval and MBPP cluster separately?

    Loads ``n_humaneval`` problems from HumanEval (via ``datasets``) and
    ``n_mbpp`` from MBPP, embeds their prompts, and computes mean intra-cluster
    cosine similarity vs mean inter-cluster cosine similarity. A positive
    ``cohesion_delta`` indicates the encoder groups similar problems together.

    Does NOT require the full benchmark harness — uses ``datasets`` directly.

    Args:
        model: HuggingFace AutoModel; already on ``device``.
        tokenizer: Matching HuggingFace tokenizer.
        max_length: Truncation length.
        batch_size: Inference batch size.
        device: Device string.
        n_humaneval: Number of HumanEval problems to sample.
        n_mbpp: Number of MBPP problems to sample.

    Returns:
        Dict with ``"intra_sim"``, ``"inter_sim"``, and ``"cohesion_delta"``
        float metrics.
    """
    import torch  # noqa: PLC0415
    from datasets import load_dataset  # noqa: PLC0415

    he_ds = load_dataset("openai_humaneval", split="test", trust_remote_code=True)
    mbpp_ds = load_dataset("mbpp", split="train", trust_remote_code=True)

    he_texts = [
        str(ex["prompt"]) for ex in he_ds.select(range(min(n_humaneval, len(he_ds))))
    ]
    mbpp_texts = [
        str(ex["text"]) for ex in mbpp_ds.select(range(min(n_mbpp, len(mbpp_ds))))
    ]

    model.eval()
    he_embs = _embed_texts(model, tokenizer, he_texts, max_length, batch_size, device)
    mbpp_embs = _embed_texts(
        model, tokenizer, mbpp_texts, max_length, batch_size, device
    )

    def _mean_off_diagonal(sim: Any) -> float:
        n = sim.shape[0]
        if n <= 1:
            return 0.0
        mask = 1 - torch.eye(n)
        return float((sim * mask).sum() / mask.sum())

    he_sim = torch.matmul(he_embs, he_embs.T)
    mbpp_sim = torch.matmul(mbpp_embs, mbpp_embs.T)
    inter_sim = torch.matmul(he_embs, mbpp_embs.T)

    intra = (_mean_off_diagonal(he_sim) + _mean_off_diagonal(mbpp_sim)) / 2.0
    inter = float(inter_sim.mean().item())
    delta = intra - inter

    logger.info(
        "cluster_probe: intra_sim=%.4f inter_sim=%.4f cohesion_delta=%.4f",
        intra,
        inter,
        delta,
    )
    return {"intra_sim": intra, "inter_sim": inter, "cohesion_delta": delta}
loss

InfoNCE contrastive loss for encoder pretraining.

Uses in-batch negatives: for a batch of size N, the positive pair for anchor i is positive i; all other j != i are treated as negatives.

All imports are deferred inside function bodies (INFRA-05).

Functions
infonce_loss
infonce_loss(
    anchors: Any, positives: Any, temperature: float = 0.07
) -> Any

Compute InfoNCE (NT-Xent) loss with in-batch negatives.

Both tensors must be embeddings of shape (batch_size, embedding_dim). The loss is symmetric: mean of (anchor->positive CE) and (positive->anchor CE). Embeddings are L2-normalised internally before computing similarities.

Parameters:

Name Type Description Default
anchors Any

Anchor embeddings (B, D) — a torch.Tensor.

required
positives Any

Positive embeddings (B, D). Must be same shape as anchors.

required
temperature float

Temperature scalar tau. Lower = harder negatives.

0.07

Returns:

Type Description
Any

Scalar torch.Tensor loss with gradient enabled.

Raises:

Type Description
ValueError

If anchors and positives have different shapes.

Source code in libs/model-training/src/model_training/encoder_pretrain/loss.py
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
def infonce_loss(
    anchors: Any,
    positives: Any,
    temperature: float = 0.07,
) -> Any:
    """Compute InfoNCE (NT-Xent) loss with in-batch negatives.

    Both tensors must be embeddings of shape ``(batch_size, embedding_dim)``.
    The loss is symmetric: mean of (anchor->positive CE) and (positive->anchor CE).
    Embeddings are L2-normalised internally before computing similarities.

    Args:
        anchors: Anchor embeddings ``(B, D)`` — a ``torch.Tensor``.
        positives: Positive embeddings ``(B, D)``. Must be same shape as anchors.
        temperature: Temperature scalar tau. Lower = harder negatives.

    Returns:
        Scalar ``torch.Tensor`` loss with gradient enabled.

    Raises:
        ValueError: If anchors and positives have different shapes.
    """
    import torch  # noqa: PLC0415
    import torch.nn.functional as F  # noqa: PLC0415, N812

    if anchors.shape != positives.shape:
        raise ValueError(
            f"anchors shape {anchors.shape} != positives shape {positives.shape}"
        )

    batch_size = anchors.shape[0]

    # L2-normalise both sides
    anchors_norm = F.normalize(anchors, dim=-1)
    positives_norm = F.normalize(positives, dim=-1)

    # Similarity matrix: (B, B), scaled by temperature
    logits = torch.matmul(anchors_norm, positives_norm.T) / temperature

    # Diagonal entries are the positive pairs
    labels = torch.arange(batch_size, device=anchors.device)

    # Symmetric loss: anchor -> positive and positive -> anchor
    loss_a = F.cross_entropy(logits, labels)
    loss_b = F.cross_entropy(logits.T, labels)

    return (loss_a + loss_b) / 2.0
train_encoder

Encoder pretraining loop: InfoNCE fine-tuning of all-mpnet-base-v2.

Single-GPU only. Multi-GPU support (DistributedDataParallel / Accelerate multi-process) is intentionally out of scope for this plan; add a --multi-gpu flag in a follow-on plan.

All GPU-dependent imports (torch, sentence_transformers, transformers, accelerate) are deferred inside run_training (INFRA-05). The module is CPU-safe to import.

MLflow integration follows the pattern in training_common.mlflow_run.

Classes
EncoderTrainingConfig dataclass
EncoderTrainingConfig(
    augmented_dir: Path,
    output_dir: Path,
    base_encoder: str = "sentence-transformers/all-mpnet-base-v2",
    temperature: float = 0.07,
    batch_size: int = 64,
    learning_rate: float = 2e-05,
    epochs: int = 5,
    max_length: int = 512,
    warmup_steps: int = 100,
    test_fraction: float = 0.2,
    seed: int = 42,
    mlflow_experiment: str = "rune-encoder-pretrain",
    mlflow_tracking_uri: str | None = None,
)

Resolved training configuration for the encoder pretraining loop.

Parameters:

Name Type Description Default
augmented_dir Path

Directory of augmented JSONL files (from augment_corpus).

required
output_dir Path

Where to save the final HF-loadable checkpoint.

required
base_encoder str

HF model id for the starting encoder.

'sentence-transformers/all-mpnet-base-v2'
temperature float

InfoNCE temperature tau.

0.07
batch_size int

Training batch size (in-batch negatives count = batch_size - 1).

64
learning_rate float

AdamW learning rate.

2e-05
epochs int

Number of training epochs.

5
max_length int

Tokenizer max sequence length (tokens).

512
warmup_steps int

Linear warmup steps at the start of training.

100
test_fraction float

Fraction of task_ids reserved for retrieval eval.

0.2
seed int

Random seed for train/test split.

42
mlflow_experiment str

MLflow experiment name.

'rune-encoder-pretrain'
mlflow_tracking_uri str | None

Override for MLFLOW_TRACKING_URI env var.

None
Functions
run_training
run_training(config: EncoderTrainingConfig) -> Path

Run the InfoNCE encoder pretraining loop.

Steps
  1. Load all augmented pairs from config.augmented_dir.
  2. Task-ID-level train/test split (via d2l_data.split_by_task_id).
  3. Build ContrastivePairDataset + DataLoader for the training split.
  4. Load base encoder (AutoModel) + tokenizer.
  5. Train for config.epochs with AdamW + cosine schedule + linear warmup.
  6. Log per-epoch train loss and retrieval eval metrics to MLflow.
  7. Save the final encoder in HF-loadable format to config.output_dir.

The saved checkpoint is loadable via SentenceTransformer(config.output_dir).

Single-GPU only; place model on cuda:0 when available, else cpu.

Parameters:

Name Type Description Default
config EncoderTrainingConfig

EncoderTrainingConfig with all resolved hyperparameters.

required

Returns:

Type Description
Path

Path to the saved checkpoint directory (== config.output_dir).

Source code in libs/model-training/src/model_training/encoder_pretrain/train_encoder.py
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
def run_training(config: EncoderTrainingConfig) -> Path:
    """Run the InfoNCE encoder pretraining loop.

    Steps:
        1. Load all augmented pairs from config.augmented_dir.
        2. Task-ID-level train/test split (via d2l_data.split_by_task_id).
        3. Build ContrastivePairDataset + DataLoader for the training split.
        4. Load base encoder (AutoModel) + tokenizer.
        5. Train for config.epochs with AdamW + cosine schedule + linear warmup.
        6. Log per-epoch train loss and retrieval eval metrics to MLflow.
        7. Save the final encoder in HF-loadable format to config.output_dir.

    The saved checkpoint is loadable via ``SentenceTransformer(config.output_dir)``.

    Single-GPU only; place model on ``cuda:0`` when available, else ``cpu``.

    Args:
        config: EncoderTrainingConfig with all resolved hyperparameters.

    Returns:
        Path to the saved checkpoint directory (== config.output_dir).
    """
    import torch  # noqa: PLC0415
    from torch.optim import AdamW  # noqa: PLC0415
    from torch.utils.data import DataLoader  # noqa: PLC0415
    from transformers import (  # noqa: PLC0415
        AutoModel,
        AutoTokenizer,
        get_cosine_schedule_with_warmup,
    )

    from model_training.d2l_data import load_jsonl, split_by_task_id  # noqa: PLC0415
    from model_training.encoder_pretrain.dataset import (  # noqa: PLC0415
        ContrastiveCollator,
        ContrastivePairDataset,
    )
    from model_training.encoder_pretrain.eval_encoder import (  # noqa: PLC0415
        run_retrieval_eval,
    )
    from model_training.encoder_pretrain.loss import infonce_loss  # noqa: PLC0415

    # ---- device ----
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    logger.info("run_training: device=%s", device)

    # ---- load all augmented pairs ----
    all_rows: list[dict[str, Any]] = []
    for path in sorted(config.augmented_dir.glob("*.jsonl")):
        all_rows.extend(load_jsonl(path))
    logger.info("Loaded %d augmented rows from %s", len(all_rows), config.augmented_dir)

    if not all_rows:
        raise ValueError(
            f"No augmented pairs found in {config.augmented_dir}. "
            "Run augment_corpus first."
        )

    # ---- task-ID-level train/test split ----
    train_rows, test_rows = split_by_task_id(
        all_rows, test_fraction=config.test_fraction, seed=config.seed
    )
    logger.info(
        "Split: %d train rows, %d test rows (task-ID level)",
        len(train_rows),
        len(test_rows),
    )

    # ---- dataset + dataloader ----
    tokenizer = AutoTokenizer.from_pretrained(config.base_encoder)
    collator = ContrastiveCollator(tokenizer=tokenizer, max_length=config.max_length)
    train_ds = ContrastivePairDataset(train_rows)
    train_loader: DataLoader[dict[str, Any]] = DataLoader(
        train_ds,  # type: ignore[arg-type]
        batch_size=config.batch_size,
        shuffle=True,
        collate_fn=collator,
        drop_last=True,  # ensure every batch has exactly batch_size pairs
    )

    # ---- model ----
    model = AutoModel.from_pretrained(config.base_encoder)
    model = model.to(device)
    model.train()

    # ---- optimizer + scheduler ----
    optimizer = AdamW(model.parameters(), lr=config.learning_rate)
    total_steps = len(train_loader) * config.epochs
    scheduler = get_cosine_schedule_with_warmup(
        optimizer,
        num_warmup_steps=config.warmup_steps,
        num_training_steps=max(total_steps, 1),
    )

    # ---- MLflow setup ----
    mlflow_enabled = setup_mlflow(config.mlflow_experiment, config.mlflow_tracking_uri)
    mlflow_params = {
        "base_encoder": config.base_encoder,
        "temperature": config.temperature,
        "batch_size": config.batch_size,
        "learning_rate": config.learning_rate,
        "epochs": config.epochs,
        "max_length": config.max_length,
        "warmup_steps": config.warmup_steps,
        "train_rows": len(train_rows),
        "test_rows": len(test_rows),
    }

    with mlflow_run(
        enabled=mlflow_enabled,
        run_name="encoder-pretrain",
        params=mlflow_params,
    ):
        # ---- training loop ----
        for epoch in range(1, config.epochs + 1):
            epoch_loss = 0.0
            n_batches = 0
            model.train()
            for batch in train_loader:
                anchor_ids = batch["anchor_input_ids"].to(device)
                anchor_mask = batch["anchor_attention_mask"].to(device)
                pos_ids = batch["positive_input_ids"].to(device)
                pos_mask = batch["positive_attention_mask"].to(device)

                anchor_emb = _encode_batch(model, anchor_ids, anchor_mask)
                positive_emb = _encode_batch(model, pos_ids, pos_mask)

                loss = infonce_loss(
                    anchor_emb, positive_emb, temperature=config.temperature
                )

                optimizer.zero_grad()
                loss.backward()
                optimizer.step()
                scheduler.step()

                epoch_loss += loss.item()
                n_batches += 1

            avg_loss = epoch_loss / max(n_batches, 1)
            logger.info(
                "Epoch %d/%d: avg_train_loss=%.4f", epoch, config.epochs, avg_loss
            )

            # ---- per-epoch retrieval eval ----
            eval_metrics = run_retrieval_eval(
                model=model,
                tokenizer=tokenizer,
                test_rows=test_rows,
                max_length=config.max_length,
                batch_size=config.batch_size,
                device=str(device),
            )
            logger.info(
                "Epoch %d/%d eval: MRR@10=%.4f Recall@1=%.4f",
                epoch,
                config.epochs,
                eval_metrics["mrr_at_10"],
                eval_metrics["recall_at_1"],
            )

            # Log to MLflow
            if mlflow_enabled:
                try:
                    import mlflow  # noqa: PLC0415

                    mlflow.log_metrics(
                        {
                            "train_loss": avg_loss,
                            "mrr_at_10": eval_metrics["mrr_at_10"],
                            "recall_at_1": eval_metrics["recall_at_1"],
                        },
                        step=epoch,
                    )
                except Exception:  # noqa: BLE001
                    logger.debug("mlflow.log_metrics failed", exc_info=True)

        # ---- save checkpoint ----
        _save_sentence_transformer_checkpoint(
            model=model,
            tokenizer=tokenizer,
            output_dir=config.output_dir,
            max_length=config.max_length,
        )
        logger.info("Checkpoint saved to %s", config.output_dir)

    return config.output_dir

github_client

Thin GitHub REST API client with auth, pagination, and rate-limit retry.

Designed for batch data mining on a training VM (sync httpx is fine).

Classes
GitHubClient
GitHubClient(
    token: str | None = None,
    base_url: str = "https://api.github.com",
)

Minimal GitHub REST API client.

Handles authentication, paginated list endpoints, and automatic retry on rate-limit 403 responses.

Parameters:

Name Type Description Default
token str | None

GitHub personal access token. Optional for public endpoints but required for private repos and higher rate limits.

None
base_url str

API base URL. Override for GitHub Enterprise.

'https://api.github.com'

Initialize the client with optional auth token.

Parameters:

Name Type Description Default
token str | None

GitHub personal access token.

None
base_url str

API base URL.

'https://api.github.com'
Source code in libs/model-training/src/model_training/github_client.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def __init__(
    self,
    token: str | None = None,
    base_url: str = "https://api.github.com",
) -> None:
    """Initialize the client with optional auth token.

    Args:
        token: GitHub personal access token.
        base_url: API base URL.
    """
    self._base_url = base_url.rstrip("/")
    self._headers: dict[str, str] = {
        "Accept": "application/vnd.github+json",
        "X-GitHub-Api-Version": "2022-11-28",
    }
    if token is not None:
        self._headers["Authorization"] = f"Bearer {token}"
Functions
get
get(
    path: str,
    params: dict[str, Any] | None = None,
    max_retries: int = 3,
) -> Any

GET a single API endpoint with rate-limit retry.

Parameters:

Name Type Description Default
path str

API path relative to base_url (e.g. /repos/owner/repo).

required
params dict[str, Any] | None

Optional query parameters.

None
max_retries int

Maximum number of retries on rate-limit 403.

3

Returns:

Type Description
Any

Parsed JSON response body.

Raises:

Type Description
HTTPStatusError

On non-rate-limit error responses.

Source code in libs/model-training/src/model_training/github_client.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
def get(
    self,
    path: str,
    params: dict[str, Any] | None = None,
    max_retries: int = 3,
) -> Any:
    """GET a single API endpoint with rate-limit retry.

    Args:
        path: API path relative to base_url (e.g. ``/repos/owner/repo``).
        params: Optional query parameters.
        max_retries: Maximum number of retries on rate-limit 403.

    Returns:
        Parsed JSON response body.

    Raises:
        httpx.HTTPStatusError: On non-rate-limit error responses.
    """
    url = f"{self._base_url}{path}"
    return self._get_response(url, params=params, max_retries=max_retries).json()
get_paginated
get_paginated(
    path: str,
    params: dict[str, Any] | None = None,
    max_pages: int = 10,
    per_page: int = 100,
) -> list[Any]

GET a paginated list endpoint, following Link rel=next headers.

Parameters:

Name Type Description Default
path str

API path relative to base_url.

required
params dict[str, Any] | None

Optional query parameters (per_page is injected).

None
max_pages int

Maximum number of pages to fetch.

10
per_page int

Items per page (max 100 for most GitHub endpoints).

100

Returns:

Type Description
list[Any]

Flat list of all items across all fetched pages.

Source code in libs/model-training/src/model_training/github_client.py
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
def get_paginated(
    self,
    path: str,
    params: dict[str, Any] | None = None,
    max_pages: int = 10,
    per_page: int = 100,
) -> list[Any]:
    """GET a paginated list endpoint, following Link rel=next headers.

    Args:
        path: API path relative to base_url.
        params: Optional query parameters (``per_page`` is injected).
        max_pages: Maximum number of pages to fetch.
        per_page: Items per page (max 100 for most GitHub endpoints).

    Returns:
        Flat list of all items across all fetched pages.
    """
    merged_params: dict[str, Any] = dict(params or {})
    merged_params["per_page"] = per_page

    items: list[Any] = []
    url: str | None = f"{self._base_url}{path}"

    for _ in range(max_pages):
        if url is None:
            break
        resp = self._get_response(url, params=merged_params)
        items.extend(resp.json())

        # After the first request, params are baked into the Link URL.
        merged_params = {}

        link = resp.headers.get("Link", "")
        match = _LINK_NEXT_RE.search(link)
        url = match.group(1) if match else None

    return items

hypernetwork

DocToLoraHypernetwork: Perceiver-based instant LoRA adapter generation.

Generates rank-8 LoRA adapter weights from token IDs in a single forward pass. Distinct from the QLoRA gradient-descent path (Phase 21) — this produces adapters in <1s by cross-attending over token embeddings with learned latents.

IMPORTANT: All GPU imports (torch, safetensors) are deferred inside function/method bodies per INFRA-05 pattern — this module is importable in CPU-only CI.

Usage

from model_training.hypernetwork import ( DocToLoraHypernetwork, save_hypernetwork_adapter, )

model = DocToLoraHypernetwork(input_dim=DEFAULT_VOCAB_SIZE) weights = model(token_ids) save_hypernetwork_adapter(weights, "/tmp/adapter", "Qwen/Qwen3.5-9B")

Functions
load_pretrained
load_pretrained(
    checkpoint_path: str, device: str = "cpu", **kwargs: Any
) -> Any

Load a pretrained DocToLoraHypernetwork from a checkpoint.

Parameters:

Name Type Description Default
checkpoint_path str

Path to the .pt checkpoint file.

required
device str

Device to load onto ('cpu', 'cuda', 'mps'). Default: 'cpu'.

'cpu'
**kwargs Any

Override constructor args (input_dim, num_latents, etc.).

{}

Returns:

Type Description
Any

DocToLoraHypernetwork nn.Module loaded with pretrained weights.

Source code in libs/model-training/src/model_training/hypernetwork.py
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
def load_pretrained(
    checkpoint_path: str,
    device: str = "cpu",
    **kwargs: Any,
) -> Any:
    """Load a pretrained DocToLoraHypernetwork from a checkpoint.

    Args:
        checkpoint_path: Path to the .pt checkpoint file.
        device: Device to load onto ('cpu', 'cuda', 'mps'). Default: 'cpu'.
        **kwargs: Override constructor args (input_dim, num_latents, etc.).

    Returns:
        DocToLoraHypernetwork nn.Module loaded with pretrained weights.
    """
    import torch  # noqa: PLC0415

    checkpoint = torch.load(checkpoint_path, map_location=device, weights_only=True)

    # Extract constructor args from checkpoint or use defaults/overrides
    ctor_args = checkpoint.get("hypernetwork_config", {})
    ctor_args.update(kwargs)
    if "input_dim" not in ctor_args:
        ctor_args["input_dim"] = DEFAULT_VOCAB_SIZE

    model = DocToLoraHypernetwork(**ctor_args)
    model.load_state_dict(checkpoint["model_state_dict"])
    model = model.to(device)
    model.eval()
    return model
trajectory_to_tokens
trajectory_to_tokens(
    trajectory_text: str,
    vocab_size: int = DEFAULT_VOCAB_SIZE,
    max_length: int = 2048,
) -> "torch.Tensor"

Encode trajectory text as token IDs for the hypernetwork.

Uses a simple hash-based tokenization (character trigrams mapped to vocab indices). This is intentionally simple — the hypernetwork learns its own embedding, so exact tokenization doesn't matter as long as it's consistent.

Parameters:

Name Type Description Default
trajectory_text str

Text to encode (plan, code diffs, test results, etc.).

required
vocab_size int

Size of the hypernetwork's embedding vocabulary.

DEFAULT_VOCAB_SIZE
max_length int

Maximum sequence length (truncates or pads).

2048

Returns:

Type Description
'torch.Tensor'

Token ID tensor of shape (1, max_length) ready for hypernetwork forward().

Source code in libs/model-training/src/model_training/hypernetwork.py
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
def trajectory_to_tokens(
    trajectory_text: str,
    vocab_size: int = DEFAULT_VOCAB_SIZE,
    max_length: int = 2048,
) -> "torch.Tensor":
    """Encode trajectory text as token IDs for the hypernetwork.

    Uses a simple hash-based tokenization (character trigrams mapped to
    vocab indices). This is intentionally simple — the hypernetwork learns
    its own embedding, so exact tokenization doesn't matter as long as
    it's consistent.

    Args:
        trajectory_text: Text to encode (plan, code diffs, test results, etc.).
        vocab_size: Size of the hypernetwork's embedding vocabulary.
        max_length: Maximum sequence length (truncates or pads).

    Returns:
        Token ID tensor of shape (1, max_length) ready for hypernetwork forward().
    """
    import logging as _logging  # noqa: PLC0415
    import zlib  # noqa: PLC0415

    import torch  # noqa: PLC0415

    min_trajectory_chars = 10
    if len(trajectory_text) < min_trajectory_chars:
        _logging.getLogger(__name__).warning(
            "Trajectory text is very short (%d chars < %d minimum). "
            "Generated adapter may be meaningless.",
            len(trajectory_text),
            min_trajectory_chars,
        )

    tokens: list[int] = []
    for i in range(0, len(trajectory_text) - 2):
        trigram = trajectory_text[i : i + 3]
        token_id = zlib.crc32(trigram.encode()) % vocab_size
        tokens.append(token_id)

    # Pad or truncate to max_length
    if len(tokens) < max_length:
        tokens.extend([0] * (max_length - len(tokens)))
    else:
        tokens = tokens[:max_length]

    return torch.tensor([tokens], dtype=torch.long)
generate_adapter
generate_adapter(
    hypernetwork: Any,
    trajectory_text: str,
    output_dir: str,
    base_model_id: str,
    vocab_size: int = DEFAULT_VOCAB_SIZE,
    max_length: int = 2048,
    device: str = "cpu",
) -> str

End-to-end: encode trajectory, run hypernetwork, save adapter.

Parameters:

Name Type Description Default
hypernetwork Any

A DocToLoraHypernetwork instance.

required
trajectory_text str

Text to encode into the adapter.

required
output_dir str

Directory to save the adapter files.

required
base_model_id str

HuggingFace model ID of the base model.

required
vocab_size int

Vocabulary size for tokenization.

DEFAULT_VOCAB_SIZE
max_length int

Max token sequence length.

2048
device str

Device for tensor operations.

'cpu'

Returns:

Type Description
str

Path to the saved adapter directory.

Source code in libs/model-training/src/model_training/hypernetwork.py
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
def generate_adapter(
    hypernetwork: Any,
    trajectory_text: str,
    output_dir: str,
    base_model_id: str,
    vocab_size: int = DEFAULT_VOCAB_SIZE,
    max_length: int = 2048,
    device: str = "cpu",
) -> str:
    """End-to-end: encode trajectory, run hypernetwork, save adapter.

    Args:
        hypernetwork: A DocToLoraHypernetwork instance.
        trajectory_text: Text to encode into the adapter.
        output_dir: Directory to save the adapter files.
        base_model_id: HuggingFace model ID of the base model.
        vocab_size: Vocabulary size for tokenization.
        max_length: Max token sequence length.
        device: Device for tensor operations.

    Returns:
        Path to the saved adapter directory.
    """
    import torch  # noqa: PLC0415

    # Infer vocab size from hypernetwork's embedding if available
    h_vocab = getattr(
        getattr(hypernetwork, "token_embedding", None), "num_embeddings", None
    )
    effective_vocab = h_vocab if h_vocab is not None else vocab_size
    tokens = trajectory_to_tokens(trajectory_text, effective_vocab, max_length)
    tokens = tokens.to(device)

    with torch.no_grad():
        weights = hypernetwork(tokens)

    rank = getattr(hypernetwork, "rank", 8)
    target_mods = getattr(hypernetwork, "target_modules", ["q_proj", "v_proj"])
    save_hypernetwork_adapter(
        weights,
        output_dir,
        base_model_id,
        rank=rank,
        target_modules=target_mods,
    )
    return output_dir
save_hypernetwork_adapter
save_hypernetwork_adapter(
    weights: dict[str, "torch.Tensor"],
    output_dir: str,
    base_model_id: str,
    rank: int = 8,
    target_modules: list[str] | None = None,
) -> None

Serialize hypernetwork-generated LoRA weights in PEFT adapter format.

Writes: - adapter_model.safetensors: the LoRA weight tensors - adapter_config.json: PEFT-compatible configuration

Parameters:

Name Type Description Default
weights dict[str, 'torch.Tensor']

PEFT state_dict from DocToLoraHypernetwork.forward().

required
output_dir str

Directory to write adapter files to (created if needed).

required
base_model_id str

HuggingFace model ID of the base model.

required
rank int

LoRA rank. Default: 8.

8
target_modules list[str] | None

List of module names. Default: ["q_proj", "v_proj"].

None
Note

Does NOT include embed_tokens or lm_head — vLLM rejects these in adapters (per Phase 21-01 decision: no modules_to_save in LoraConfig).

Source code in libs/model-training/src/model_training/hypernetwork.py
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
def save_hypernetwork_adapter(
    weights: dict[str, "torch.Tensor"],
    output_dir: str,
    base_model_id: str,
    rank: int = 8,
    target_modules: list[str] | None = None,
) -> None:
    """Serialize hypernetwork-generated LoRA weights in PEFT adapter format.

    Writes:
    - adapter_model.safetensors: the LoRA weight tensors
    - adapter_config.json: PEFT-compatible configuration

    Args:
        weights: PEFT state_dict from DocToLoraHypernetwork.forward().
        output_dir: Directory to write adapter files to (created if needed).
        base_model_id: HuggingFace model ID of the base model.
        rank: LoRA rank. Default: 8.
        target_modules: List of module names. Default: ["q_proj", "v_proj"].

    Note:
        Does NOT include embed_tokens or lm_head — vLLM rejects these in adapters
        (per Phase 21-01 decision: no modules_to_save in LoraConfig).
    """
    from safetensors.torch import save_file  # noqa: PLC0415

    if target_modules is None:
        target_modules = ["q_proj", "v_proj"]

    output_path = Path(output_dir)
    output_path.mkdir(parents=True, exist_ok=True)

    # Write adapter weights as safetensors
    safetensors_path = output_path / "adapter_model.safetensors"
    save_file(weights, str(safetensors_path))

    # Write PEFT-compatible adapter_config.json
    adapter_config: dict[str, object] = {
        "peft_type": "LORA",
        "r": rank,
        "lora_alpha": rank * 2,
        "target_modules": target_modules,
        "lora_dropout": 0.0,
        "bias": "none",
        "task_type": "CAUSAL_LM",
        "base_model_name_or_path": base_model_id,
        "inference_mode": True,
        "modules_to_save": None,
        "fan_in_fan_out": False,
    }

    config_path = output_path / "adapter_config.json"
    config_path.write_text(json.dumps(adapter_config, indent=2))

kill_switch

Training kill-switch: halt hypernetwork training on Pass@1 regression.

At a configurable step cadence, the training loop re-runs a small benchmark (default: HumanEval @ 10 problems) and compares the current Pass@1 to a baseline captured on the first evaluation (step 0 semantic). When current < baseline - delta (default delta = 0.05 = 5 pts absolute), the kill-switch fires and the loop halts.

All heavy imports (evaluation.benchmarks) are deferred into the closure returned by :func:build_benchmark_evaluate_fn so this module stays importable without the evaluation package on the path.

Usage (in a training loop):

from model_training.kill_switch import (
    KillSwitchConfig,
    KillSwitchState,
    maybe_run_kill_switch,
)

ks_config = KillSwitchConfig(enabled=True, step_cadence=100)
ks_state = KillSwitchState()
for step in range(1, num_steps + 1):
    ...  # optimizer step, etc.
    if maybe_run_kill_switch(
        step=step,
        config=ks_config,
        state=ks_state,
        evaluate_fn=my_eval_fn,
    ):
        logger.error("Kill-switch triggered; halting training")
        break
Classes
KillSwitchConfig dataclass
KillSwitchConfig(
    enabled: bool = False,
    step_cadence: int = 100,
    benchmark_id: str = "humaneval",
    max_samples: int = 10,
    delta: float = 0.05,
)

Kill-switch configuration.

Attributes:

Name Type Description
enabled bool

Master toggle. When False, :func:maybe_run_kill_switch is a no-op regardless of other fields.

step_cadence int

Evaluate Pass@1 every step_cadence training steps.

benchmark_id str

Benchmark to evaluate against (default: HumanEval).

max_samples int

Cap on problems evaluated per call (kept small to amortise the per-step cost).

delta float

Absolute Pass@1 regression threshold. When current pass_at_1 is strictly less than baseline - delta the switch fires.

KillSwitchState dataclass
KillSwitchState(
    baseline: float | None = None,
    triggered: bool = False,
    last_pass_at_1: float | None = None,
    evaluations: int = 0,
)

Per-run kill-switch state, mutated in place by :func:update_and_check.

Attributes:

Name Type Description
baseline float | None

Pass@1 captured on the first evaluation. None until then.

triggered bool

True once a regression has fired the switch.

last_pass_at_1 float | None

Pass@1 from the most recent evaluation.

evaluations int

Count of evaluations performed so far.

Functions
should_evaluate
should_evaluate(step: int, cadence: int) -> bool

Return True when step is a positive multiple of cadence.

Parameters:

Name Type Description Default
step int

Current training step (1-based).

required
cadence int

Evaluation cadence. Non-positive values disable evaluation.

required
Source code in libs/model-training/src/model_training/kill_switch.py
 94
 95
 96
 97
 98
 99
100
101
102
103
def should_evaluate(step: int, cadence: int) -> bool:
    """Return True when ``step`` is a positive multiple of ``cadence``.

    Args:
        step: Current training step (1-based).
        cadence: Evaluation cadence. Non-positive values disable evaluation.
    """
    if cadence <= 0 or step <= 0:
        return False
    return step % cadence == 0
regression_detected
regression_detected(
    current: float, baseline: float, delta: float
) -> bool

Return True when current < baseline - delta (strict).

Boundary current == baseline - delta is NOT treated as a regression.

Source code in libs/model-training/src/model_training/kill_switch.py
106
107
108
109
110
111
def regression_detected(current: float, baseline: float, delta: float) -> bool:
    """Return True when ``current < baseline - delta`` (strict).

    Boundary ``current == baseline - delta`` is NOT treated as a regression.
    """
    return current < baseline - delta
update_and_check
update_and_check(
    state: KillSwitchState, current: float, delta: float
) -> bool

Update state with a new Pass@1 reading; return True to halt.

The first call captures current as the baseline and never halts. Subsequent calls compare to the baseline via :func:regression_detected.

Parameters:

Name Type Description Default
state KillSwitchState

Mutable kill-switch state.

required
current float

Pass@1 from the latest evaluation.

required
delta float

Absolute regression threshold.

required

Returns:

Type Description
bool

True when training should halt; False otherwise.

Source code in libs/model-training/src/model_training/kill_switch.py
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
def update_and_check(state: KillSwitchState, current: float, delta: float) -> bool:
    """Update ``state`` with a new Pass@1 reading; return True to halt.

    The first call captures ``current`` as the baseline and never halts.
    Subsequent calls compare to the baseline via :func:`regression_detected`.

    Args:
        state: Mutable kill-switch state.
        current: Pass@1 from the latest evaluation.
        delta: Absolute regression threshold.

    Returns:
        True when training should halt; False otherwise.
    """
    state.last_pass_at_1 = current
    state.evaluations += 1
    if state.baseline is None:
        state.baseline = current
        logger.info("Kill-switch baseline captured: pass_at_1=%.3f", current)
        return False
    if regression_detected(current, state.baseline, delta):
        state.triggered = True
        logger.error(
            "Kill-switch TRIGGERED: pass_at_1=%.3f < baseline=%.3f - delta=%.3f",
            current,
            state.baseline,
            delta,
        )
        return True
    return False
evaluate_and_check
evaluate_and_check(
    evaluate_fn: Callable[[], float],
    state: KillSwitchState,
    delta: float,
) -> tuple[float, bool]

Run evaluate_fn, update state, return (pass_at_1, should_halt).

Source code in libs/model-training/src/model_training/kill_switch.py
146
147
148
149
150
151
152
153
def evaluate_and_check(
    evaluate_fn: Callable[[], float],
    state: KillSwitchState,
    delta: float,
) -> tuple[float, bool]:
    """Run ``evaluate_fn``, update state, return (pass_at_1, should_halt)."""
    current = evaluate_fn()
    return current, update_and_check(state, current, delta)
maybe_run_kill_switch
maybe_run_kill_switch(
    *,
    step: int,
    config: KillSwitchConfig,
    state: KillSwitchState,
    evaluate_fn: Callable[[], float],
) -> bool

Step-level hook for a training loop.

When the kill-switch is disabled or step is not a cadence multiple, evaluate_fn is NOT invoked and the function returns False. Otherwise it runs the evaluator and updates state.

Parameters:

Name Type Description Default
step int

Current (1-based) training step.

required
config KillSwitchConfig

Kill-switch configuration.

required
state KillSwitchState

Mutable kill-switch state.

required
evaluate_fn Callable[[], float]

Zero-arg callable returning the current Pass@1.

required

Returns:

Type Description
bool

True when training should halt.

Source code in libs/model-training/src/model_training/kill_switch.py
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
def maybe_run_kill_switch(
    *,
    step: int,
    config: KillSwitchConfig,
    state: KillSwitchState,
    evaluate_fn: Callable[[], float],
) -> bool:
    """Step-level hook for a training loop.

    When the kill-switch is disabled or ``step`` is not a cadence multiple,
    ``evaluate_fn`` is NOT invoked and the function returns False. Otherwise
    it runs the evaluator and updates state.

    Args:
        step: Current (1-based) training step.
        config: Kill-switch configuration.
        state: Mutable kill-switch state.
        evaluate_fn: Zero-arg callable returning the current Pass@1.

    Returns:
        True when training should halt.
    """
    if not config.enabled:
        return False
    if not should_evaluate(step, config.step_cadence):
        return False
    _, halt = evaluate_and_check(evaluate_fn, state, config.delta)
    return halt
build_benchmark_evaluate_fn
build_benchmark_evaluate_fn(
    *,
    base_model: str,
    benchmark_id: str,
    max_samples: int,
    provider: Any,
    registry: Any,
    adapter_ids: list[str] | None = None,
) -> Callable[[], float]

Return a zero-arg closure that calls run_benchmark once.

The evaluation import is deferred into the closure body, so calling :func:build_benchmark_evaluate_fn does not load the evaluation package.

Parameters:

Name Type Description Default
base_model str

HF repo id or local path of the base model.

required
benchmark_id str

Benchmark registry key (e.g. "humaneval").

required
max_samples int

Per-benchmark problem cap.

required
provider Any

:class:inference.provider.InferenceProvider instance.

required
registry Any

:class:adapter_registry.registry.AdapterRegistry (or compatible duck-type with retrieve_by_id).

required
adapter_ids list[str] | None

Ordered adapter stack; empty list = base only.

None

Returns:

Type Description
Callable[[], float]

A callable that returns BenchmarkResult.pass_at_1 when invoked.

Source code in libs/model-training/src/model_training/kill_switch.py
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
def build_benchmark_evaluate_fn(
    *,
    base_model: str,
    benchmark_id: str,
    max_samples: int,
    provider: Any,
    registry: Any,
    adapter_ids: list[str] | None = None,
) -> Callable[[], float]:
    """Return a zero-arg closure that calls ``run_benchmark`` once.

    The evaluation import is deferred into the closure body, so calling
    :func:`build_benchmark_evaluate_fn` does not load the evaluation package.

    Args:
        base_model: HF repo id or local path of the base model.
        benchmark_id: Benchmark registry key (e.g. ``"humaneval"``).
        max_samples: Per-benchmark problem cap.
        provider: :class:`inference.provider.InferenceProvider` instance.
        registry: :class:`adapter_registry.registry.AdapterRegistry` (or
            compatible duck-type with ``retrieve_by_id``).
        adapter_ids: Ordered adapter stack; empty list = base only.

    Returns:
        A callable that returns ``BenchmarkResult.pass_at_1`` when invoked.
    """
    ids = list(adapter_ids) if adapter_ids else []

    def _evaluate() -> float:
        # evaluation.benchmarks.run_benchmark is lazily exposed via
        # module __getattr__, which mypy sees as "object" — cast to Any
        # so the call is typed correctly without a heavy import.
        from typing import Any as _Any  # noqa: PLC0415

        from evaluation.benchmarks import run_benchmark as _rb  # noqa: PLC0415
        from evaluation.benchmarks.adapter_stack import (  # noqa: PLC0415
            load_adapter_stack,
        )

        run_benchmark: _Any = _rb
        stack = load_adapter_stack(
            base_model=base_model,
            adapter_ids=ids,
            provider=provider,
            registry=registry,
        )
        result = run_benchmark(
            adapter_stack=stack,
            benchmark_id=benchmark_id,
            max_samples=max_samples,
        )
        return float(result.pass_at_1)

    return _evaluate

merging

Adapter merging strategies for evolutionary combination.

Implements TIES-Merging and DARE-Merging for combining multiple LoRA adapter state dicts into a single merged adapter. All GPU imports are deferred inside function bodies (INFRA-05 pattern).

Functions
ties_merge
ties_merge(
    state_dicts: list[dict[str, Any]], density: float = 0.5
) -> dict[str, Any]

Merge adapter state dicts using TIES-Merging.

Trim-Elect-Sign-Disjoint merge: for each parameter, trims values below density threshold, elects the majority sign (ignoring trimmed values), then averages only the values matching the elected sign.

Parameters:

Name Type Description Default
state_dicts list[dict[str, Any]]

List of state dicts (tensors) to merge.

required
density float

Fraction of values to keep per parameter (0.0 to 1.0).

0.5

Returns:

Type Description
dict[str, Any]

Merged state dict with same keys and shapes as inputs.

Raises:

Type Description
ValueError

If state_dicts is empty or density is outside [0.0, 1.0].

Source code in libs/model-training/src/model_training/merging.py
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
def ties_merge(
    state_dicts: list[dict[str, Any]],
    density: float = 0.5,
) -> dict[str, Any]:
    """Merge adapter state dicts using TIES-Merging.

    Trim-Elect-Sign-Disjoint merge: for each parameter, trims values
    below density threshold, elects the majority sign (ignoring trimmed
    values), then averages only the values matching the elected sign.

    Args:
        state_dicts: List of state dicts (tensors) to merge.
        density: Fraction of values to keep per parameter (0.0 to 1.0).

    Returns:
        Merged state dict with same keys and shapes as inputs.

    Raises:
        ValueError: If *state_dicts* is empty or *density* is outside
            ``[0.0, 1.0]``.
    """
    if not state_dicts:
        raise ValueError(
            "state_dicts must not be empty; TIES-merge of zero inputs is undefined."
        )
    if not (0.0 <= density <= 1.0):
        raise ValueError(f"density must be between 0.0 and 1.0, got {density}")

    import torch

    merged: dict[str, Any] = {}
    keys = state_dicts[0].keys()

    for key in keys:
        original_dtype = state_dicts[0][key].dtype
        tensors = [sd[key].float() for sd in state_dicts]
        stacked = torch.stack(tensors)

        # Track which values survived trimming (True = kept)
        keep_mask = torch.ones_like(stacked, dtype=torch.bool)

        # Trim: zero out values below density threshold per tensor
        for i in range(len(tensors)):
            flat = stacked[i].abs().flatten()
            if flat.numel() == 0:
                continue
            k_keep = max(1, int(flat.numel() * density))
            threshold = torch.topk(flat, k_keep).values[-1]
            mask = stacked[i].abs() >= threshold
            keep_mask[i] = mask
            stacked[i] = stacked[i] * mask.float()

        # Elect sign: majority vote using only surviving (non-trimmed) values
        signs = torch.sign(stacked)
        signs_masked = signs * keep_mask.float()
        sign_sum = signs_masked.sum(dim=0)
        elected_sign = torch.sign(sign_sum)

        # Where elected_sign == 0 (true tie), average all surviving values
        tie_mask = elected_sign == 0

        # Disjoint merge: average only values matching elected sign
        matching = (signs == elected_sign.unsqueeze(0)).float()
        # For tied positions, include all values that survived trimming
        matching = torch.where(
            tie_mask.unsqueeze(0),
            keep_mask.float(),
            matching,
        )
        matching_vals = stacked * matching
        count = matching.sum(dim=0).clamp(min=1)
        merged[key] = (matching_vals.sum(dim=0) / count).to(original_dtype)

    return merged
dare_merge
dare_merge(
    state_dicts: list[dict[str, Any]],
    drop_rate: float = 0.1,
    seed: int | None = None,
) -> dict[str, Any]

Merge adapter state dicts using DARE-Merging.

Drop-And-REscale merge: randomly drops a fraction of values from each state dict, then averages the remaining values with rescaling.

Parameters:

Name Type Description Default
state_dicts list[dict[str, Any]]

List of state dicts to merge.

required
drop_rate float

Fraction of values to drop per parameter. Must be in [0.0, 1.0).

0.1
seed int | None

Optional RNG seed for reproducible merges.

None

Returns:

Type Description
dict[str, Any]

Merged state dict with same keys and shapes as inputs.

Raises:

Type Description
ValueError

If state_dicts is empty or drop_rate is outside [0.0, 1.0).

Source code in libs/model-training/src/model_training/merging.py
 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
def dare_merge(
    state_dicts: list[dict[str, Any]],
    drop_rate: float = 0.1,
    seed: int | None = None,
) -> dict[str, Any]:
    """Merge adapter state dicts using DARE-Merging.

    Drop-And-REscale merge: randomly drops a fraction of values from
    each state dict, then averages the remaining values with rescaling.

    Args:
        state_dicts: List of state dicts to merge.
        drop_rate: Fraction of values to drop per parameter. Must be in
            ``[0.0, 1.0)``.
        seed: Optional RNG seed for reproducible merges.

    Returns:
        Merged state dict with same keys and shapes as inputs.

    Raises:
        ValueError: If *state_dicts* is empty or *drop_rate* is outside
            ``[0.0, 1.0)``.
    """
    if not state_dicts:
        raise ValueError(
            "state_dicts must not be empty; DARE-merge of zero inputs is undefined."
        )
    if not (0.0 <= drop_rate < 1.0):
        raise ValueError(f"drop_rate must be in [0.0, 1.0), got {drop_rate}")

    import torch

    if seed is not None:
        torch.manual_seed(seed)

    merged: dict[str, Any] = {}
    keys = state_dicts[0].keys()
    scale = 1.0 / (1.0 - drop_rate)

    for key in keys:
        original_dtype = state_dicts[0][key].dtype
        tensors = [sd[key].float() for sd in state_dicts]
        stacked = torch.stack(tensors)

        # Drop and rescale each tensor
        for i in range(len(tensors)):
            if drop_rate > 0:
                mask = (torch.rand_like(stacked[i]) >= drop_rate).float()
                stacked[i] = stacked[i] * mask * scale

        # Average across state dicts
        merged[key] = stacked.mean(dim=0).to(original_dtype)

    return merged
load_adapter_state_dict
load_adapter_state_dict(
    adapter_path: str | Path,
) -> dict[str, Any]

Load a LoRA adapter state dict from a safetensors file or directory.

Accepts either a direct .safetensors file path or a PEFT adapter directory containing adapter_model.safetensors.

Parameters:

Name Type Description Default
adapter_path str | Path

Path to a .safetensors file or a directory containing adapter_model.safetensors.

required

Returns:

Type Description
dict[str, Any]

State dict mapping parameter names to tensors.

Source code in libs/model-training/src/model_training/merging.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
def load_adapter_state_dict(adapter_path: str | Path) -> dict[str, Any]:
    """Load a LoRA adapter state dict from a safetensors file or directory.

    Accepts either a direct ``.safetensors`` file path or a PEFT adapter
    directory containing ``adapter_model.safetensors``.

    Args:
        adapter_path: Path to a ``.safetensors`` file or a directory
            containing ``adapter_model.safetensors``.

    Returns:
        State dict mapping parameter names to tensors.
    """
    from safetensors.torch import load_file

    path = Path(adapter_path)
    if path.is_dir():
        path = path / "adapter_model.safetensors"
    return load_file(str(path), device="cpu")

model_configs

Model registry for configurable LoRA fine-tuning targets.

Provides ModelConfig (frozen Pydantic model) and ModelRegistry with named presets for each supported base model. No GPU imports — safe to import anywhere.

Classes
ModelConfig

Bases: BaseModel

Immutable configuration for a base model + training defaults.

Attributes:

Name Type Description
canonical_name str

Short lookup key (e.g. "qwen3.5-9b").

model_id str

HuggingFace repository ID.

warm_start_adapter_id str | None

Pre-trained PEFT adapter to continue from.

default_lora_rank int

LoRA rank for fresh initialization.

default_lora_alpha int

LoRA alpha scaling factor.

attn_implementation str | None

Attention implementation override (e.g. "eager").

expected_num_layers int

Expected total layer count for probe validation.

expected_hidden_size int

Expected hidden dimension for probe validation.

gradient_accumulation_steps int

Training gradient accumulation default.

lr_scheduler_type str

Learning rate scheduler type.

epochs int

Number of training epochs.

quirks dict[str, Any]

Model-specific overrides and notes.

ModelRegistry
ModelRegistry()

Registry of named ModelConfig presets.

Usage

registry = ModelRegistry.default() config = registry.get("qwen3.5-9b")

Initialize an empty model registry.

Source code in libs/model-training/src/model_training/model_configs.py
65
66
67
def __init__(self) -> None:
    """Initialize an empty model registry."""
    self._presets: dict[str, ModelConfig] = {}
Functions
register
register(config: ModelConfig) -> None

Register a model configuration preset.

Parameters:

Name Type Description Default
config ModelConfig

ModelConfig to register under its canonical_name.

required
Source code in libs/model-training/src/model_training/model_configs.py
69
70
71
72
73
74
75
def register(self, config: ModelConfig) -> None:
    """Register a model configuration preset.

    Args:
        config: ModelConfig to register under its canonical_name.
    """
    self._presets[config.canonical_name] = config
get
get(name: str) -> ModelConfig

Look up a model configuration by canonical name.

Parameters:

Name Type Description Default
name str

Canonical model name (e.g. "qwen3.5-9b").

required

Returns:

Type Description
ModelConfig

The registered ModelConfig.

Raises:

Type Description
KeyError

If no preset exists for the given name.

Source code in libs/model-training/src/model_training/model_configs.py
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
def get(self, name: str) -> ModelConfig:
    """Look up a model configuration by canonical name.

    Args:
        name: Canonical model name (e.g. "qwen3.5-9b").

    Returns:
        The registered ModelConfig.

    Raises:
        KeyError: If no preset exists for the given name.
    """
    if name not in self._presets:
        available = ", ".join(sorted(self._presets.keys()))
        raise KeyError(
            f"No model config registered for {name!r}. Available: {available}"
        )
    return self._presets[name]
list_names
list_names() -> list[str]

Return sorted list of registered model names.

Source code in libs/model-training/src/model_training/model_configs.py
96
97
98
def list_names(self) -> list[str]:
    """Return sorted list of registered model names."""
    return sorted(self._presets.keys())
default classmethod
default() -> ModelRegistry

Return singleton registry with built-in presets.

Presets
  • qwen3.5-9b: Qwen3.5-9B with DeltaCoder warm-start
  • qwen3-coder-next: Qwen3-Coder-Next (hybrid attention)
Source code in libs/model-training/src/model_training/model_configs.py
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
@classmethod
def default(cls) -> ModelRegistry:
    """Return singleton registry with built-in presets.

    Presets:
        - qwen3.5-9b: Qwen3.5-9B with DeltaCoder warm-start
        - qwen3-coder-next: Qwen3-Coder-Next (hybrid attention)
    """
    if cls._default_instance is not None:
        return cls._default_instance

    registry = cls()

    registry.register(
        ModelConfig(
            canonical_name="qwen3.5-9b",
            model_id="Qwen/Qwen3.5-9B",
            warm_start_adapter_id=("danielcherubini/Qwen3.5-DeltaCoder-9B"),
            default_lora_rank=64,
            default_lora_alpha=32,
            attn_implementation="eager",
            expected_num_layers=32,
            expected_hidden_size=4096,
            gradient_accumulation_steps=16,
            lr_scheduler_type="constant",
            epochs=3,
            quirks={
                "flash_attention_warning": (
                    "Flash + sample packing causes loss collapse"
                ),
            },
        )
    )

    registry.register(
        ModelConfig(
            canonical_name="qwen3-coder-next",
            model_id="Qwen/Qwen3-Coder-Next",
            warm_start_adapter_id=None,
            default_lora_rank=8,
            default_lora_alpha=16,
            attn_implementation=None,
            expected_num_layers=48,
            expected_hidden_size=2048,
            gradient_accumulation_steps=4,
            lr_scheduler_type="cosine",
            epochs=3,
        )
    )

    cls._default_instance = registry
    return registry
Functions
validate_against_probe
validate_against_probe(
    config: ModelConfig, probe_result: dict[str, Any]
) -> list[str]

Validate a ModelConfig against probe results.

Checks expected_num_layers against discovered attention layer count and expected_hidden_size against probed feature dimensions.

Parameters:

Name Type Description Default
config ModelConfig

ModelConfig with expected architecture dimensions.

required
probe_result dict[str, Any]

Output from probe_model() or loaded probe cache.

required

Returns:

Type Description
list[str]

List of warning messages (empty if all checks pass).

Source code in libs/model-training/src/model_training/model_configs.py
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
def validate_against_probe(
    config: ModelConfig, probe_result: dict[str, Any]
) -> list[str]:
    """Validate a ModelConfig against probe results.

    Checks expected_num_layers against discovered attention layer count and
    expected_hidden_size against probed feature dimensions.

    Args:
        config: ModelConfig with expected architecture dimensions.
        probe_result: Output from probe_model() or loaded probe cache.

    Returns:
        List of warning messages (empty if all checks pass).
    """
    warnings: list[str] = []

    layer_indices = probe_result.get("attention_layer_indices", [])
    if layer_indices:
        max_layer = max(layer_indices)
        if max_layer >= config.expected_num_layers:
            msg = (
                f"Probe found layer index {max_layer} but "
                f"{config.canonical_name} expects {config.expected_num_layers} "
                f"total layers"
            )
            warnings.append(msg)
            logger.warning(msg)

    feature_sizes = probe_result.get("feature_sizes", {})
    for proj_name, dims in feature_sizes.items():
        in_dim = dims.get("in", 0)
        if in_dim and in_dim != config.expected_hidden_size:
            # Only warn for input projections (q/k/v) where in == hidden_size
            if proj_name in ("q_proj", "k_proj", "v_proj"):
                msg = (
                    f"{proj_name} input dim {in_dim} != expected "
                    f"hidden_size {config.expected_hidden_size} for "
                    f"{config.canonical_name}"
                )
                warnings.append(msg)
                logger.warning(msg)

    if not warnings:
        logger.info("Probe validation passed for %s", config.canonical_name)

    return warnings

oracle_cache

Oracle adapter cache and lookup helpers for round-2 training.

This module is intentionally CPU-safe: torch and peft are imported inside function bodies per INFRA-05 so the module stays importable in CPU-only CI.

Classes
OracleAdapterCache
OracleAdapterCache(
    *, registry: Any, hc: Any, max_loaded: int
)

LRU cache of oracle LoRA dicts keyed by bin_key.

Entries are lightweight LoraDict tensors — NOT PeftModel wrappers. The teacher pass applies them to the base model via :func:model_training.d2l_lora.apply_functional_lora, the same mechanism the student pass uses for hypernet output. The base model is therefore never structurally mutated (no LoraLayer wrappers), so there is no possibility of hook leakage across passes.

Missing bins (no registered oracle) return None so callers can skip the record or fall back to the bare base model.

Not thread-safe; assumes the training loop is single-threaded per GPU.

Example

cache = OracleAdapterCache(registry=reg, hc=hc, max_loaded=4) lora = cache.get("decompose_humaneval") if lora is not None: ... with apply_functional_lora(base_model, lora, hc): ... with torch.no_grad(): ... teacher_logits = base_model(**inputs).logits

Initialise the cache.

Parameters:

Name Type Description Default
registry Any

AdapterRegistry instance (or compatible mock).

required
hc Any

HypernetConfig passed through to _load_oracle_as_lora_dict.

required
max_loaded int

Maximum number of LoRA dicts to hold in memory.

required
Source code in libs/model-training/src/model_training/oracle_cache.py
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
def __init__(self, *, registry: Any, hc: Any, max_loaded: int) -> None:
    """Initialise the cache.

    Args:
        registry: AdapterRegistry instance (or compatible mock).
        hc: HypernetConfig passed through to ``_load_oracle_as_lora_dict``.
        max_loaded: Maximum number of LoRA dicts to hold in memory.
    """
    if max_loaded < 1:
        raise ValueError(f"max_loaded must be >= 1, got {max_loaded}")
    self._registry = registry
    self._hc = hc
    self._max_loaded = max_loaded
    self._cache: OrderedDict[str, LoraDict] = OrderedDict()
    self._missing: set[str] = set()
Functions
get
get(bin_key: str) -> LoraDict | None

Return the oracle LoRA dict for bin_key (loading if needed).

Returns None when no registered oracle exists. Moves the entry to the MRU position on hit.

Source code in libs/model-training/src/model_training/oracle_cache.py
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
def get(self, bin_key: str) -> LoraDict | None:
    """Return the oracle LoRA dict for ``bin_key`` (loading if needed).

    Returns ``None`` when no registered oracle exists. Moves the entry
    to the MRU position on hit.
    """
    if bin_key in self._missing:
        return None
    if bin_key in self._cache:
        self._cache.move_to_end(bin_key)
        return self._cache[bin_key]

    path = lookup_oracle_path(bin_key, self._registry)
    if path is None:
        self._missing.add(bin_key)
        return None

    logger.info("Loading oracle LoRA dict for %r from %s", bin_key, path)
    lora_dict = _load_oracle_as_lora_dict(path, self._hc)
    self._cache[bin_key] = lora_dict
    self._evict_if_full()
    return lora_dict
clear
clear() -> None

Drop all cached oracles; next .get will reload from disk.

Source code in libs/model-training/src/model_training/oracle_cache.py
289
290
291
292
def clear(self) -> None:
    """Drop all cached oracles; next ``.get`` will reload from disk."""
    self._cache.clear()
    self._missing.clear()
Functions
lookup_oracle_path
lookup_oracle_path(
    bin_key: str, registry: Any
) -> str | None

Resolve a bin key to the on-disk path of its registered oracle adapter.

The adapter_id scheme follows :mod:corpus_producer.trainer_bridge: oracle_<bin_key>. Returns None when the adapter is missing or archived so callers can decide whether to fall back to the base model or skip the record.

Parameters:

Name Type Description Default
bin_key str

Oracle bin key (e.g. "decompose_humaneval", "diagnose_pooled").

required
registry Any

An :class:adapter_registry.registry.AdapterRegistry instance (or a mock with a compatible retrieve_by_id).

required

Returns:

Type Description
str | None

The adapter's file_path string, or None when missing / archived.

Source code in libs/model-training/src/model_training/oracle_cache.py
 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
def lookup_oracle_path(bin_key: str, registry: Any) -> str | None:
    """Resolve a bin key to the on-disk path of its registered oracle adapter.

    The adapter_id scheme follows :mod:`corpus_producer.trainer_bridge`:
    ``oracle_<bin_key>``. Returns ``None`` when the adapter is missing or
    archived so callers can decide whether to fall back to the base model
    or skip the record.

    Args:
        bin_key: Oracle bin key (e.g. ``"decompose_humaneval"``,
            ``"diagnose_pooled"``).
        registry: An :class:`adapter_registry.registry.AdapterRegistry`
            instance (or a mock with a compatible ``retrieve_by_id``).

    Returns:
        The adapter's ``file_path`` string, or ``None`` when missing / archived.
    """
    from adapter_registry.exceptions import AdapterNotFoundError  # noqa: PLC0415

    adapter_id = f"{ORACLE_ID_PREFIX}{bin_key}"
    try:
        record = registry.retrieve_by_id(adapter_id)
    except AdapterNotFoundError:
        logger.warning("Oracle adapter %r not found in registry", adapter_id)
        return None
    if record.is_archived:
        logger.warning("Oracle adapter %r is archived; ignoring", adapter_id)
        return None
    return str(record.file_path)
audit_oracle_coverage
audit_oracle_coverage(
    records: list[dict[str, Any]], registry: Any
) -> tuple[float, dict[str, int]]

Compute oracle-coverage ratio and per-bin record counts.

Iterates the records, derives each bin_key, and checks whether a registered (non-archived) oracle exists for it. Caches lookup results per bin_key to avoid repeated registry queries.

Parameters:

Name Type Description Default
records list[dict[str, Any]]

List of JSONL manifest records.

required
registry Any

AdapterRegistry instance.

required

Returns:

Type Description
float

Tuple (coverage_ratio, bin_counts).

dict[str, int]

coverage_ratio is covered / len(records) (using the

tuple[float, dict[str, int]]

original record count as the denominator). Unroutable records —

tuple[float, dict[str, int]]

those raising ValueError from :func:_bin_key_for_record — are

tuple[float, dict[str, int]]

logged and skipped, but still count against the denominator. Returns

tuple[float, dict[str, int]]

0.0 when records is empty.

tuple[float, dict[str, int]]

bin_counts maps bin_key → record count for routable records

tuple[float, dict[str, int]]

only; unroutable records are excluded, so

tuple[float, dict[str, int]]

sum(bin_counts.values()) may be less than len(records).

Source code in libs/model-training/src/model_training/oracle_cache.py
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
def audit_oracle_coverage(
    records: list[dict[str, Any]],
    registry: Any,
) -> tuple[float, dict[str, int]]:
    """Compute oracle-coverage ratio and per-bin record counts.

    Iterates the records, derives each bin_key, and checks whether a
    registered (non-archived) oracle exists for it. Caches lookup results
    per bin_key to avoid repeated registry queries.

    Args:
        records: List of JSONL manifest records.
        registry: AdapterRegistry instance.

    Returns:
        Tuple ``(coverage_ratio, bin_counts)``.

        ``coverage_ratio`` is ``covered / len(records)`` (using the
        **original** record count as the denominator). Unroutable records —
        those raising ``ValueError`` from :func:`_bin_key_for_record` — are
        logged and skipped, but still count against the denominator. Returns
        ``0.0`` when ``records`` is empty.

        ``bin_counts`` maps bin_key → record count for *routable* records
        only; unroutable records are excluded, so
        ``sum(bin_counts.values())`` may be less than ``len(records)``.
    """
    if not records:
        return 0.0, {}

    bin_counts: dict[str, int] = {}
    lookup_cache: dict[str, bool] = {}
    covered = 0

    for record in records:
        try:
            bin_key = _bin_key_for_record(record)
        except ValueError as exc:
            logger.warning("Skipping unroutable record: %s", exc)
            continue
        bin_counts[bin_key] = bin_counts.get(bin_key, 0) + 1

        if bin_key not in lookup_cache:
            lookup_cache[bin_key] = lookup_oracle_path(bin_key, registry) is not None
        if lookup_cache[bin_key]:
            covered += 1

    return covered / len(records), bin_counts

peft_utils

QLoRA PEFT configuration and adapter management.

All GPU library imports (peft, transformers, torch) are deferred inside function bodies to ensure CPU-only importability (INFRA-05).

Functions
build_qlora_config
build_qlora_config(
    rank: int,
    alpha: int,
    target_modules: list[str],
    dropout: float = 0.1,
) -> Any

Build a QLoRA configuration for PEFT fine-tuning.

Parameters:

Name Type Description Default
rank int

LoRA rank (dimensionality of low-rank matrices).

required
alpha int

LoRA alpha scaling factor.

required
target_modules list[str]

List of module names to apply LoRA to.

required
dropout float

Dropout probability for LoRA layers.

0.1

Returns:

Type Description
Any

A peft LoraConfig instance configured for QLoRA.

Example

config = build_qlora_config(rank=64, alpha=128, target_modules=["q_proj"])

Source code in libs/model-training/src/model_training/peft_utils.py
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
def build_qlora_config(
    rank: int,
    alpha: int,
    target_modules: list[str],
    dropout: float = 0.1,
) -> Any:
    """Build a QLoRA configuration for PEFT fine-tuning.

    Args:
        rank: LoRA rank (dimensionality of low-rank matrices).
        alpha: LoRA alpha scaling factor.
        target_modules: List of module names to apply LoRA to.
        dropout: Dropout probability for LoRA layers.

    Returns:
        A peft LoraConfig instance configured for QLoRA.

    Example:
        >>> config = build_qlora_config(rank=64, alpha=128, target_modules=["q_proj"])
    """
    from peft import LoraConfig  # deferred — GPU/peft not available in CPU CI

    return LoraConfig(
        r=rank,
        lora_alpha=alpha,
        target_modules=target_modules,
        lora_dropout=dropout,
        bias="none",
        task_type="CAUSAL_LM",
    )
apply_lora_adapter
apply_lora_adapter(model: Any, config: Any) -> Any

Apply a LoRA adapter to a base model.

Parameters:

Name Type Description Default
model Any

The base model to wrap with LoRA.

required
config Any

The LoRA configuration (from build_qlora_config).

required

Returns:

Type Description
Any

The model wrapped with a LoRA adapter via peft.get_peft_model.

Example

adapted_model = apply_lora_adapter(base_model, lora_config)

Source code in libs/model-training/src/model_training/peft_utils.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def apply_lora_adapter(model: Any, config: Any) -> Any:
    """Apply a LoRA adapter to a base model.

    Args:
        model: The base model to wrap with LoRA.
        config: The LoRA configuration (from build_qlora_config).

    Returns:
        The model wrapped with a LoRA adapter via peft.get_peft_model.

    Example:
        >>> adapted_model = apply_lora_adapter(base_model, lora_config)
    """
    from peft import get_peft_model  # deferred — GPU/peft not available in CPU CI

    return get_peft_model(model, config)
merge_adapter
merge_adapter(model: Any) -> Any

Merge LoRA weights into the base model.

Parameters:

Name Type Description Default
model Any

A PEFT model with LoRA adapter applied.

required

Returns:

Type Description
Any

The base model with LoRA weights merged in.

Raises:

Type Description
NotImplementedError

Adapter merging is out of scope for Phase 21.

Example

merged = merge_adapter(peft_model)

Source code in libs/model-training/src/model_training/peft_utils.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
def merge_adapter(model: Any) -> Any:
    """Merge LoRA weights into the base model.

    Args:
        model: A PEFT model with LoRA adapter applied.

    Returns:
        The base model with LoRA weights merged in.

    Raises:
        NotImplementedError: Adapter merging is out of scope for Phase 21.

    Example:
        >>> merged = merge_adapter(peft_model)
    """
    raise NotImplementedError(
        "merge_adapter is not yet implemented. "
        "It will merge LoRA weights into the base model and return the merged model."
    )

reconstruction

Reconstruction-mode training dataset tooling for T2L-style hypernetworks.

Consumers import specific submodules directly:

from model_training.reconstruction.builder import build_reconstruction_dataset
from model_training.reconstruction.manifest import ReconstructionManifest
Modules
builder

Reconstruction dataset orchestrator.

Given an AdapterRegistry and a description callback, produce a manifest + task_embeddings.pt (+ optional zscore_stats.pt) in out_dir. Raises before any file is written when the adapter corpus is heterogeneous in base_model_id, warm_start_adapter, target_modules, rank, or layer_indices.

Classes Functions
build_reconstruction_dataset
build_reconstruction_dataset(
    *,
    registry: AdapterRegistry,
    out_dir: Path,
    task_description_fn: Callable[[AdapterRecord], str],
    warm_start_adapter: str | None,
    base_model_id_override: str | None,
    emb_model: Any | None,
    compute_zscore: bool,
    task_type: str | None = None,
    min_fitness: float | None = None,
    sources: tuple[str, ...] | None = None,
    emb_model_name: str | None = None,
    emb_model_dim: int | None = None,
) -> Path

Build a reconstruction dataset from a registry into out_dir.

Parameters:

Name Type Description Default
registry AdapterRegistry

Open AdapterRegistry.

required
out_dir Path

Destination directory (created if missing).

required
task_description_fn Callable[[AdapterRecord], str]

Callable returning free-text task description for an AdapterRecord. The result feeds the task embedder.

required
warm_start_adapter str | None

Warm-start adapter id stored on every record; None when no warm-start was used.

required
base_model_id_override str | None

Override for the per-adapter base_model_name_or_path read from adapter_config.json. Rune's trainer stores the warm-start adapter there, so the true base (e.g. Qwen/Qwen3.5-9B) must be supplied explicitly.

required
emb_model Any | None

Pre-loaded sentence-transformer encoder, or None to use the one-hot fallback.

required
compute_zscore bool

When True, compute + persist z-score stats to zscore_stats.pt and record the path in the manifest.

required
task_type str | None

Passed through to iter_reconstruction_candidates.

None
min_fitness float | None

Passed through to iter_reconstruction_candidates.

None
sources tuple[str, ...] | None

Passed through to iter_reconstruction_candidates.

None
emb_model_name str | None

HF repo id recorded in the manifest; defaults to DEFAULT_EMBEDDING_MODEL when an emb_model is supplied.

None
emb_model_dim int | None

Embedding dim recorded in the manifest; defaults to DEFAULT_EMBEDDING_DIM when an emb_model is supplied.

None

Returns:

Type Description
Path

Path to the written manifest.

Raises:

Type Description
ValueError

On empty candidate set or heterogeneous corpus.

Source code in libs/model-training/src/model_training/reconstruction/builder.py
 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
def build_reconstruction_dataset(
    *,
    registry: AdapterRegistry,
    out_dir: Path,
    task_description_fn: Callable[[AdapterRecord], str],
    warm_start_adapter: str | None,
    base_model_id_override: str | None,
    emb_model: Any | None,
    compute_zscore: bool,
    task_type: str | None = None,
    min_fitness: float | None = None,
    sources: tuple[str, ...] | None = None,
    emb_model_name: str | None = None,
    emb_model_dim: int | None = None,
) -> Path:
    """Build a reconstruction dataset from a registry into ``out_dir``.

    Args:
        registry: Open AdapterRegistry.
        out_dir: Destination directory (created if missing).
        task_description_fn: Callable returning free-text task description
            for an AdapterRecord. The result feeds the task embedder.
        warm_start_adapter: Warm-start adapter id stored on every record;
            ``None`` when no warm-start was used.
        base_model_id_override: Override for the per-adapter
            ``base_model_name_or_path`` read from ``adapter_config.json``.
            Rune's trainer stores the warm-start adapter there, so the true
            base (e.g. ``Qwen/Qwen3.5-9B``) must be supplied explicitly.
        emb_model: Pre-loaded sentence-transformer encoder, or ``None`` to
            use the one-hot fallback.
        compute_zscore: When True, compute + persist z-score stats to
            ``zscore_stats.pt`` and record the path in the manifest.
        task_type: Passed through to ``iter_reconstruction_candidates``.
        min_fitness: Passed through to ``iter_reconstruction_candidates``.
        sources: Passed through to ``iter_reconstruction_candidates``.
        emb_model_name: HF repo id recorded in the manifest; defaults to
            ``DEFAULT_EMBEDDING_MODEL`` when an emb_model is supplied.
        emb_model_dim: Embedding dim recorded in the manifest; defaults to
            ``DEFAULT_EMBEDDING_DIM`` when an emb_model is supplied.

    Returns:
        Path to the written manifest.

    Raises:
        ValueError: On empty candidate set or heterogeneous corpus.
    """
    candidates = iter_reconstruction_candidates(
        registry, task_type=task_type, min_fitness=min_fitness, sources=sources
    )
    if not candidates:
        raise ValueError(
            "no candidates found in registry"
            " (check task_type/min_fitness/sources filters)"
        )

    logger.info("build_reconstruction_dataset: %d candidate(s)", len(candidates))

    now = datetime.now(timezone.utc).isoformat()
    records: list[ReconstructionRecord] = []
    tensors_per_record: list[dict[str, dict[str, Any]]] = []
    descriptions: dict[str, str] = {}

    for rec in candidates:
        adapter_dir = Path(rec.file_path)
        description = task_description_fn(rec)
        record_kwargs = load_adapter_as_record(
            adapter_dir,
            task_id=rec.id,
            task_description=description,
            warm_start_adapter=warm_start_adapter,
            base_model_id_override=base_model_id_override,
            created_at=rec.created_at,
            source_task_hash=rec.training_task_hash,
            fitness_score=rec.fitness_score,
        )
        records.append(ReconstructionRecord(**record_kwargs))
        descriptions[rec.id] = description

        # Re-load state_dict for tensor stats (cheap: already on disk).
        if compute_zscore:
            sd = load_adapter_state_dict(adapter_dir)
            tensors_per_record.append(
                extract_lora_ab_from_state_dict(
                    sd, target_modules=record_kwargs["target_modules"]
                )
            )

    first = records[0]
    validate_homogeneity(
        records,
        base_model_id=first.base_model_id,
        warm_start_adapter=first.warm_start_adapter,
        target_modules=first.target_modules,
        rank=first.rank,
        layer_indices=first.layer_indices,
    )

    # Only now do we touch disk.
    out_dir.mkdir(parents=True, exist_ok=True)

    embeddings = compute_task_embeddings(descriptions, model=emb_model)
    save_task_embeddings(embeddings, out_dir / "task_embeddings.pt")

    stats_path: Path | None = None
    if compute_zscore:
        stats = compute_zscore_stats(tensors_per_record)
        stats_path = out_dir / "zscore_stats.pt"
        save_zscore_stats(stats, stats_path)

    # Determine declared emb dim.
    if emb_model is None:
        declared_model_name = None
        declared_dim = len(descriptions)
    else:
        declared_model_name = emb_model_name or DEFAULT_EMBEDDING_MODEL
        declared_dim = emb_model_dim or DEFAULT_EMBEDDING_DIM

    manifest = ReconstructionManifest(
        schema_version=SCHEMA_VERSION,
        base_model_id=first.base_model_id,
        warm_start_adapter=first.warm_start_adapter,
        target_modules=first.target_modules,
        rank=first.rank,
        layer_indices=first.layer_indices,
        task_embedding_model=declared_model_name,
        task_embedding_dim=declared_dim,
        records=records,
        zscore_stats_path=str(stats_path.resolve()) if stats_path else None,
        created_at=now,
    )
    manifest_path = out_dir / "manifest.json"
    manifest.save(manifest_path)
    logger.info("wrote manifest: %s", manifest_path)
    return manifest_path
cli

CLI for building a reconstruction dataset.

Usage

uv run python -m model_training.reconstruction.cli \ --database-url sqlite:///$HOME/.rune/rune.db \ --out-dir data/recon_v1 \ --warm-start deltacoder \ --base-model qwen3.5-9b \ --emb-model sentence-transformers/all-mpnet-base-v2

Mirrors trainer_cli.py conventions: --dry-run resolves args to JSON and exits without importing torch; heavy imports are deferred.

Functions
main
main(argv: list[str] | None = None) -> int

Entry point for the reconstruction dataset CLI.

Parameters:

Name Type Description Default
argv list[str] | None

Argument list (defaults to sys.argv[1:]).

None

Returns:

Type Description
int

Exit code (0 on success).

Source code in libs/model-training/src/model_training/reconstruction/cli.py
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
def main(argv: list[str] | None = None) -> int:
    """Entry point for the reconstruction dataset CLI.

    Args:
        argv: Argument list (defaults to ``sys.argv[1:]``).

    Returns:
        Exit code (0 on success).
    """
    parser = _build_parser()
    args = parser.parse_args(argv)
    kwargs = _resolve_kwargs(args)
    if args.dry_run:
        print(json.dumps(kwargs, indent=2, sort_keys=True))
        return 0
    _run(kwargs)
    return 0
extract

Extract per-module LoRA A/B matrices from PEFT state_dicts + adapter dirs.

Mirrors the key-parse logic in T2L's hyper_llm_modulator/data.py::get_recon_train_data. PEFT stores A as (rank, in_features) and B as (out_features, rank) per layer; we stack along a new layer axis (dim 0) without transposing.

Torch is imported inside function bodies (INFRA-05).

Functions
extract_lora_ab_from_state_dict
extract_lora_ab_from_state_dict(
    state_dict: dict[str, Any],
    *,
    target_modules: tuple[str, ...],
) -> dict[str, dict[str, Any]]

Return per-module stacked A/B tensors and sorted layer indices.

Shape: {module: {"A": Tensor[L, r, in], "B": Tensor[L, out, r], "layer_indices": LongTensor[L]}}.

Parameters:

Name Type Description Default
state_dict dict[str, Any]

Dict mapping PEFT key → tensor. Both torch.Tensor and safetensors-loaded tensors work.

required
target_modules tuple[str, ...]

Module names to extract. Must appear at the module slot of the PEFT key (e.g. "q_proj", "gate_proj").

required

Raises:

Type Description
ValueError

If any requested module has zero matching keys, or if the A and B layer sets disagree for a module.

Source code in libs/model-training/src/model_training/reconstruction/extract.py
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
def extract_lora_ab_from_state_dict(
    state_dict: dict[str, Any],
    *,
    target_modules: tuple[str, ...],
) -> dict[str, dict[str, Any]]:
    """Return per-module stacked A/B tensors and sorted layer indices.

    Shape: ``{module: {"A": Tensor[L, r, in], "B": Tensor[L, out, r],
    "layer_indices": LongTensor[L]}}``.

    Args:
        state_dict: Dict mapping PEFT key → tensor. Both ``torch.Tensor``
            and safetensors-loaded tensors work.
        target_modules: Module names to extract. Must appear at the module
            slot of the PEFT key (e.g. ``"q_proj"``, ``"gate_proj"``).

    Raises:
        ValueError: If any requested module has zero matching keys, or if
            the A and B layer sets disagree for a module.
    """
    import torch  # noqa: PLC0415

    # Collect A/B per (module, layer) first, then assemble stacks.
    a_by_mod_layer: dict[str, dict[int, torch.Tensor]] = {m: {} for m in target_modules}
    b_by_mod_layer: dict[str, dict[int, torch.Tensor]] = {m: {} for m in target_modules}

    for key, tensor in state_dict.items():
        match = _KEY_RE.match(key)
        if match is None:
            continue
        module = match.group("module")
        if module not in a_by_mod_layer:
            continue
        layer = int(match.group("layer"))
        if match.group("ab") == "A":
            a_by_mod_layer[module][layer] = tensor
        else:
            b_by_mod_layer[module][layer] = tensor

    out: dict[str, dict[str, Any]] = {}
    for module in target_modules:
        a_layers = a_by_mod_layer[module]
        b_layers = b_by_mod_layer[module]
        if not a_layers and not b_layers:
            raise ValueError(
                f"no lora_A/lora_B keys for module '{module}' in state_dict"
            )
        if set(a_layers) != set(b_layers):
            only_a = sorted(set(a_layers) - set(b_layers))
            only_b = sorted(set(b_layers) - set(a_layers))
            raise ValueError(
                f"lora_A and lora_B layer sets mismatch for '{module}': "
                f"only_A={only_a}, only_B={only_b}"
            )
        sorted_layers = sorted(a_layers.keys())
        a_stack = torch.stack([a_layers[i] for i in sorted_layers], dim=0)
        b_stack = torch.stack([b_layers[i] for i in sorted_layers], dim=0)
        out[module] = {
            "A": a_stack,
            "B": b_stack,
            "layer_indices": torch.tensor(sorted_layers, dtype=torch.long),
        }
    return out
load_adapter_state_dict
load_adapter_state_dict(
    adapter_dir: Path,
) -> dict[str, Any]

Load adapter_model.safetensors from a PEFT adapter directory.

Source code in libs/model-training/src/model_training/reconstruction/extract.py
 98
 99
100
101
102
103
104
105
def load_adapter_state_dict(adapter_dir: Path) -> dict[str, Any]:
    """Load ``adapter_model.safetensors`` from a PEFT adapter directory."""
    from safetensors.torch import load_file  # noqa: PLC0415

    st_path = adapter_dir / "adapter_model.safetensors"
    if not st_path.is_file():
        raise FileNotFoundError(f"missing adapter_model.safetensors: {st_path}")
    return load_file(str(st_path))
load_adapter_config
load_adapter_config(adapter_dir: Path) -> dict[str, Any]

Load adapter_config.json from a PEFT adapter directory.

Source code in libs/model-training/src/model_training/reconstruction/extract.py
108
109
110
111
112
113
def load_adapter_config(adapter_dir: Path) -> dict[str, Any]:
    """Load ``adapter_config.json`` from a PEFT adapter directory."""
    cfg_path = adapter_dir / "adapter_config.json"
    if not cfg_path.is_file():
        raise FileNotFoundError(f"missing adapter_config.json: {cfg_path}")
    return json.loads(cfg_path.read_text(encoding="utf-8"))
load_adapter_as_record
load_adapter_as_record(
    adapter_dir: Path,
    *,
    task_id: str,
    task_description: str,
    warm_start_adapter: str | None,
    base_model_id_override: str | None,
    created_at: str,
    source_task_hash: str | None = None,
    fitness_score: float | None = None,
) -> dict[str, Any]

Read an adapter dir and return kwargs for ReconstructionRecord(**kwargs).

The A/B tensors themselves are NOT returned — they live on disk where the trainer can stream them. Only shape / identity metadata flows through.

Parameters:

Name Type Description Default
adapter_dir Path

Directory containing adapter_model.safetensors and adapter_config.json.

required
task_id str

Manifest-stable id (usually AdapterRecord.id).

required
task_description str

Text used to compute the task embedding.

required
warm_start_adapter str | None

Warm-start adapter path/repo, or None. Stored verbatim on the record — downstream consumers must honor this.

required
base_model_id_override str | None

If set, overrides the base_model_name_or_path from adapter_config.json (e.g., when the config records the warm-start adapter instead of the true base).

required
created_at str

ISO-8601 UTC timestamp.

required
source_task_hash str | None

Optional dedup key.

None
fitness_score float | None

Optional evaluation score.

None

Returns:

Type Description
dict[str, Any]

Dict suitable for ReconstructionRecord(**returned_dict).

Source code in libs/model-training/src/model_training/reconstruction/extract.py
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
def load_adapter_as_record(
    adapter_dir: Path,
    *,
    task_id: str,
    task_description: str,
    warm_start_adapter: str | None,
    base_model_id_override: str | None,
    created_at: str,
    source_task_hash: str | None = None,
    fitness_score: float | None = None,
) -> dict[str, Any]:
    """Read an adapter dir and return kwargs for ``ReconstructionRecord(**kwargs)``.

    The A/B tensors themselves are NOT returned — they live on disk where the
    trainer can stream them. Only shape / identity metadata flows through.

    Args:
        adapter_dir: Directory containing ``adapter_model.safetensors`` and
            ``adapter_config.json``.
        task_id: Manifest-stable id (usually ``AdapterRecord.id``).
        task_description: Text used to compute the task embedding.
        warm_start_adapter: Warm-start adapter path/repo, or None. Stored
            verbatim on the record — downstream consumers must honor this.
        base_model_id_override: If set, overrides the ``base_model_name_or_path``
            from ``adapter_config.json`` (e.g., when the config records the
            warm-start adapter instead of the true base).
        created_at: ISO-8601 UTC timestamp.
        source_task_hash: Optional dedup key.
        fitness_score: Optional evaluation score.

    Returns:
        Dict suitable for ``ReconstructionRecord(**returned_dict)``.
    """
    cfg = load_adapter_config(adapter_dir)
    target_modules: tuple[str, ...] = tuple(cfg["target_modules"])
    rank = int(cfg["r"])

    state_dict = load_adapter_state_dict(adapter_dir)
    per_mod = extract_lora_ab_from_state_dict(state_dict, target_modules=target_modules)

    # All modules share the same layer set by construction (validate_homogeneity).
    first_mod = target_modules[0]
    layer_indices = tuple(int(i) for i in per_mod[first_mod]["layer_indices"].tolist())

    base_from_cfg = str(cfg.get("base_model_name_or_path", ""))
    base_model_id = base_model_id_override or base_from_cfg
    if not base_model_id:
        raise ValueError(
            f"adapter {adapter_dir} has no base_model_name_or_path and no override"
        )

    return {
        "task_id": task_id,
        "adapter_path": str(adapter_dir.resolve()),
        "task_description": task_description,
        "base_model_id": base_model_id,
        "warm_start_adapter": warm_start_adapter,
        "rank": rank,
        "target_modules": target_modules,
        "layer_indices": layer_indices,
        "created_at": created_at,
        "source_task_hash": source_task_hash,
        "fitness_score": fitness_score,
    }
manifest

Dataclasses and JSON serialization for the reconstruction training manifest.

This module is CPU-only: no torch / safetensors imports. Downstream consumers (extract.py, builder.py) depend on these types but this file has no external deps beyond the standard library.

Classes
ReconstructionRecord dataclass
ReconstructionRecord(
    task_id: str,
    adapter_path: str,
    task_description: str,
    base_model_id: str,
    warm_start_adapter: str | None,
    rank: int,
    target_modules: tuple[str, ...],
    layer_indices: tuple[int, ...],
    created_at: str,
    source_task_hash: str | None = None,
    fitness_score: float | None = None,
)

One oracle adapter's index entry in the reconstruction dataset.

Attributes:

Name Type Description
task_id str

Stable identifier — reuses AdapterRecord.id.

adapter_path str

Absolute path to the adapter directory (must contain adapter_model.safetensors and adapter_config.json).

task_description str

Free-text description used to compute the task embedding. Source is caller-supplied (see builder's task_description_fn).

base_model_id str

HF repo id of the base the adapter was trained on. Must match across all records in a manifest.

warm_start_adapter str | None

HF repo id or path of the warm-start adapter, or None if trained from scratch. Critical for DeltaCoder-relative delta semantics — see plan §"DeltaCoder-Relative Semantics".

rank int

LoRA rank. Must match across all records.

target_modules tuple[str, ...]

Names of modules the LoRA adapter targets. Must match across all records in a manifest.

layer_indices tuple[int, ...]

Transformer layer indices present in the adapter (derived from safetensor key parse). Must match across all records.

created_at str

ISO-8601 UTC timestamp (from AdapterRecord.created_at).

source_task_hash str | None

Optional dedup key (AdapterRecord.training_task_hash).

fitness_score float | None

Optional evaluation fitness (AdapterRecord.fitness_score).

Functions
to_dict
to_dict() -> dict[str, Any]

Return a plain-dict representation suitable for JSON.

Source code in libs/model-training/src/model_training/reconstruction/manifest.py
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
def to_dict(self) -> dict[str, Any]:
    """Return a plain-dict representation suitable for JSON."""
    return {
        "task_id": self.task_id,
        "adapter_path": self.adapter_path,
        "task_description": self.task_description,
        "base_model_id": self.base_model_id,
        "warm_start_adapter": self.warm_start_adapter,
        "rank": self.rank,
        "target_modules": list(self.target_modules),
        "layer_indices": list(self.layer_indices),
        "created_at": self.created_at,
        "source_task_hash": self.source_task_hash,
        "fitness_score": self.fitness_score,
    }
from_dict classmethod
from_dict(payload: dict[str, Any]) -> ReconstructionRecord

Inverse of to_dict.

Source code in libs/model-training/src/model_training/reconstruction/manifest.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
@classmethod
def from_dict(cls, payload: dict[str, Any]) -> ReconstructionRecord:
    """Inverse of ``to_dict``."""
    return cls(
        task_id=payload["task_id"],
        adapter_path=payload["adapter_path"],
        task_description=payload["task_description"],
        base_model_id=payload["base_model_id"],
        warm_start_adapter=payload["warm_start_adapter"],
        rank=int(payload["rank"]),
        target_modules=tuple(payload["target_modules"]),
        layer_indices=tuple(int(i) for i in payload["layer_indices"]),
        created_at=payload["created_at"],
        source_task_hash=payload.get("source_task_hash"),
        fitness_score=payload.get("fitness_score"),
    )
ReconstructionManifest dataclass
ReconstructionManifest(
    schema_version: int,
    base_model_id: str,
    warm_start_adapter: str | None,
    target_modules: tuple[str, ...],
    rank: int,
    layer_indices: tuple[int, ...],
    task_embedding_model: str | None,
    task_embedding_dim: int,
    records: list[ReconstructionRecord] = list(),
    zscore_stats_path: str | None = None,
    created_at: str = "",
)

Top-level index for a reconstruction training dataset.

Attributes:

Name Type Description
schema_version int

Bump on any backward-incompatible change.

base_model_id str

Homogeneous across all records.

warm_start_adapter str | None

Homogeneous across all records (or None if no warm-start was used for any oracle).

target_modules tuple[str, ...]

Homogeneous across all records.

rank int

Homogeneous across all records.

layer_indices tuple[int, ...]

Homogeneous across all records.

task_embedding_model str | None

HF repo id of the sentence-transformer used to compute embeddings, or None for the one-hot fallback.

task_embedding_dim int

Dimensionality of the task embedding vectors.

records list[ReconstructionRecord]

One record per oracle adapter.

zscore_stats_path str | None

Path to optional z-score stats file (.pt), or None if stats were not computed.

created_at str

ISO-8601 UTC timestamp of manifest creation.

Functions
to_dict
to_dict() -> dict[str, Any]

Return a plain-dict representation suitable for JSON.

Source code in libs/model-training/src/model_training/reconstruction/manifest.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def to_dict(self) -> dict[str, Any]:
    """Return a plain-dict representation suitable for JSON."""
    return {
        "schema_version": self.schema_version,
        "base_model_id": self.base_model_id,
        "warm_start_adapter": self.warm_start_adapter,
        "target_modules": list(self.target_modules),
        "rank": self.rank,
        "layer_indices": list(self.layer_indices),
        "task_embedding_model": self.task_embedding_model,
        "task_embedding_dim": self.task_embedding_dim,
        "records": [r.to_dict() for r in self.records],
        "zscore_stats_path": self.zscore_stats_path,
        "created_at": self.created_at,
    }
from_dict classmethod
from_dict(
    payload: dict[str, Any],
) -> ReconstructionManifest

Inverse of to_dict.

Source code in libs/model-training/src/model_training/reconstruction/manifest.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
@classmethod
def from_dict(cls, payload: dict[str, Any]) -> ReconstructionManifest:
    """Inverse of ``to_dict``."""
    return cls(
        schema_version=int(payload["schema_version"]),
        base_model_id=payload["base_model_id"],
        warm_start_adapter=payload["warm_start_adapter"],
        target_modules=tuple(payload["target_modules"]),
        rank=int(payload["rank"]),
        layer_indices=tuple(int(i) for i in payload["layer_indices"]),
        task_embedding_model=payload["task_embedding_model"],
        task_embedding_dim=int(payload["task_embedding_dim"]),
        records=[ReconstructionRecord.from_dict(r) for r in payload["records"]],
        zscore_stats_path=payload.get("zscore_stats_path"),
        created_at=payload.get("created_at", ""),
    )
save
save(path: Path) -> None

Write manifest as pretty-printed JSON.

Source code in libs/model-training/src/model_training/reconstruction/manifest.py
156
157
158
159
160
161
162
def save(self, path: Path) -> None:
    """Write manifest as pretty-printed JSON."""
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(
        json.dumps(self.to_dict(), indent=2, sort_keys=False),
        encoding="utf-8",
    )
load classmethod
load(path: Path) -> ReconstructionManifest

Read manifest from a JSON file.

Source code in libs/model-training/src/model_training/reconstruction/manifest.py
164
165
166
167
168
@classmethod
def load(cls, path: Path) -> ReconstructionManifest:
    """Read manifest from a JSON file."""
    payload = json.loads(path.read_text(encoding="utf-8"))
    return cls.from_dict(payload)
Functions
validate_homogeneity
validate_homogeneity(
    records: list[ReconstructionRecord],
    *,
    base_model_id: str,
    warm_start_adapter: str | None,
    target_modules: tuple[str, ...],
    rank: int,
    layer_indices: tuple[int, ...],
) -> None

Assert every record matches the given homogeneous fields.

Raises:

Type Description
ValueError

With a message naming the first mismatched field + record.

Source code in libs/model-training/src/model_training/reconstruction/manifest.py
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
def validate_homogeneity(
    records: list[ReconstructionRecord],
    *,
    base_model_id: str,
    warm_start_adapter: str | None,
    target_modules: tuple[str, ...],
    rank: int,
    layer_indices: tuple[int, ...],
) -> None:
    """Assert every record matches the given homogeneous fields.

    Raises:
        ValueError: With a message naming the first mismatched field + record.
    """
    for rec in records:
        if rec.base_model_id != base_model_id:
            raise ValueError(
                f"base_model_id mismatch on record {rec.task_id!r}: "
                f"expected {base_model_id!r}, got {rec.base_model_id!r}"
            )
        if rec.warm_start_adapter != warm_start_adapter:
            raise ValueError(
                f"warm_start_adapter mismatch on record {rec.task_id!r}: "
                f"expected {warm_start_adapter!r}, got {rec.warm_start_adapter!r}"
            )
        if rec.target_modules != target_modules:
            raise ValueError(
                f"target_modules mismatch on record {rec.task_id!r}: "
                f"expected {target_modules!r}, got {rec.target_modules!r}"
            )
        if rec.rank != rank:
            raise ValueError(
                f"rank mismatch on record {rec.task_id!r}: "
                f"expected {rank}, got {rec.rank}"
            )
        if rec.layer_indices != layer_indices:
            raise ValueError(
                f"layer_indices mismatch on record {rec.task_id!r}: "
                f"expected {layer_indices!r}, got {rec.layer_indices!r}"
            )
registry_source

Query the AdapterRegistry for reconstruction candidates.

Pure read-only wrapper. Filters out archived adapters and any record whose file_path does not point to a readable directory. Does not touch the adapter weights themselves — that's extract.load_adapter_as_record.

Classes Functions
iter_reconstruction_candidates
iter_reconstruction_candidates(
    registry: AdapterRegistry,
    *,
    task_type: str | None = None,
    min_fitness: float | None = None,
    sources: tuple[str, ...] | None = None,
) -> list[AdapterRecord]

Return AdapterRecords eligible for reconstruction-dataset inclusion.

Filters
  • is_archived=False (always enforced via registry.list_all).
  • task_type matches iff provided.
  • fitness_score >= min_fitness iff provided (None-valued fitness scores are excluded when min_fitness is set).
  • source in sources iff provided.
  • file_path exists on disk (warn-and-skip otherwise).

Parameters:

Name Type Description Default
registry AdapterRegistry

Open AdapterRegistry.

required
task_type str | None

Optional task_type filter.

None
min_fitness float | None

Optional minimum fitness_score.

None
sources tuple[str, ...] | None

Optional whitelist of source strings (e.g. ("distillation",)).

None

Returns:

Type Description
list[AdapterRecord]

List of AdapterRecord instances, insertion-order preserved.

Source code in libs/model-training/src/model_training/reconstruction/registry_source.py
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
def iter_reconstruction_candidates(
    registry: AdapterRegistry,
    *,
    task_type: str | None = None,
    min_fitness: float | None = None,
    sources: tuple[str, ...] | None = None,
) -> list[AdapterRecord]:
    """Return AdapterRecords eligible for reconstruction-dataset inclusion.

    Filters:
        - ``is_archived=False`` (always enforced via ``registry.list_all``).
        - ``task_type`` matches iff provided.
        - ``fitness_score >= min_fitness`` iff provided (None-valued fitness
          scores are **excluded** when ``min_fitness`` is set).
        - ``source`` in ``sources`` iff provided.
        - ``file_path`` exists on disk (warn-and-skip otherwise).

    Args:
        registry: Open AdapterRegistry.
        task_type: Optional task_type filter.
        min_fitness: Optional minimum fitness_score.
        sources: Optional whitelist of source strings (e.g. ``("distillation",)``).

    Returns:
        List of AdapterRecord instances, insertion-order preserved.
    """
    records = registry.list_all()  # filters is_archived

    if task_type is not None:
        records = [r for r in records if r.task_type == task_type]
    if sources is not None:
        allowed = set(sources)
        records = [r for r in records if r.source in allowed]
    if min_fitness is not None:
        records = [
            r
            for r in records
            if r.fitness_score is not None and r.fitness_score >= min_fitness
        ]

    kept: list[AdapterRecord] = []
    for rec in records:
        if not Path(rec.file_path).is_dir():
            logger.warning(
                "dropping adapter %s: file_path %r is not a directory",
                rec.id,
                rec.file_path,
            )
            continue
        kept.append(rec)
    return kept
stats

Across-corpus z-score statistics for reconstruction targets.

Mirrors T2L's std_recon_target + 1e-10 normalization (see hyper_llm_modulator/recon_trainer.py). Stats are computed element-wise across the task dimension so a downstream hypernetwork with pred_z_score can normalize oracle targets before the L1 loss.

Inputs are dicts of {module: {"A": Tensor[n_layers, r, in], "B": Tensor[n_layers, out, r]}} as produced by extract.extract_lora_ab_from_state_dict. All records must share the same module set and per-module tensor shapes.

Functions
compute_zscore_stats
compute_zscore_stats(
    per_record_tensors: Iterable[dict[str, dict[str, Any]]],
) -> dict[str, dict[str, Any]]

Compute element-wise {avg_A, std_A, avg_B, std_B} per module.

Parameters:

Name Type Description Default
per_record_tensors Iterable[dict[str, dict[str, Any]]]

Iterable of per-record dicts {module: {"A": Tensor, "B": Tensor}}. At least one record required; all records must share the same module keys and per-module tensor shapes.

required

Returns:

Type Description
dict[str, dict[str, Any]]

``{module: {"avg_A": Tensor, "std_A": Tensor, "avg_B": Tensor,

dict[str, dict[str, Any]]

"std_B": Tensor}}.stdtensors are floored toSTD_FLOOR``

dict[str, dict[str, Any]]

for numerical safety.

Raises:

Type Description
ValueError

On empty iterable or inconsistent module sets across records.

Source code in libs/model-training/src/model_training/reconstruction/stats.py
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
def compute_zscore_stats(
    per_record_tensors: Iterable[dict[str, dict[str, Any]]],
) -> dict[str, dict[str, Any]]:
    """Compute element-wise ``{avg_A, std_A, avg_B, std_B}`` per module.

    Args:
        per_record_tensors: Iterable of per-record dicts
            ``{module: {"A": Tensor, "B": Tensor}}``. At least one record
            required; all records must share the same module keys and
            per-module tensor shapes.

    Returns:
        ``{module: {"avg_A": Tensor, "std_A": Tensor, "avg_B": Tensor,
        "std_B": Tensor}}``. ``std`` tensors are floored to ``STD_FLOOR``
        for numerical safety.

    Raises:
        ValueError: On empty iterable or inconsistent module sets across records.
    """
    import torch  # noqa: PLC0415

    records = list(per_record_tensors)
    if not records:
        raise ValueError("compute_zscore_stats requires at least one record")

    reference_modules = set(records[0].keys())
    for i, rec in enumerate(records[1:], start=1):
        if set(rec.keys()) != reference_modules:
            raise ValueError(
                f"inconsistent modules at record {i}: "
                f"expected {sorted(reference_modules)}, got {sorted(rec.keys())}"
            )

    stats: dict[str, dict[str, torch.Tensor]] = {}
    for module in reference_modules:
        a_stack = torch.stack([rec[module]["A"] for rec in records], dim=0).float()
        b_stack = torch.stack([rec[module]["B"] for rec in records], dim=0).float()
        # n_records > 1 → use population std (unbiased=False) so the stat is
        # finite even with 2 samples. Downstream z-score normalization is
        # what matters; tiny-N variance is bounded by STD_FLOOR anyway.
        avg_a = a_stack.mean(dim=0)
        avg_b = b_stack.mean(dim=0)
        std_a = a_stack.std(dim=0, unbiased=False).clamp_min(STD_FLOOR)
        std_b = b_stack.std(dim=0, unbiased=False).clamp_min(STD_FLOOR)
        stats[module] = {
            "avg_A": avg_a,
            "std_A": std_a,
            "avg_B": avg_b,
            "std_B": std_b,
        }
    return stats
save_zscore_stats
save_zscore_stats(
    stats: dict[str, dict[str, Any]], path: Path
) -> None

Persist the stats dict via torch.save.

Parameters:

Name Type Description Default
stats dict[str, dict[str, Any]]

Stats dict as returned by compute_zscore_stats.

required
path Path

Destination file path (parent dirs created if absent).

required
Source code in libs/model-training/src/model_training/reconstruction/stats.py
78
79
80
81
82
83
84
85
86
87
88
def save_zscore_stats(stats: dict[str, dict[str, Any]], path: Path) -> None:
    """Persist the stats dict via ``torch.save``.

    Args:
        stats: Stats dict as returned by ``compute_zscore_stats``.
        path: Destination file path (parent dirs created if absent).
    """
    import torch  # noqa: PLC0415

    path.parent.mkdir(parents=True, exist_ok=True)
    torch.save(stats, str(path))
load_zscore_stats
load_zscore_stats(path: Path) -> dict[str, dict[str, Any]]

Inverse of save_zscore_stats.

Parameters:

Name Type Description Default
path Path

Path to a .pt file written by save_zscore_stats.

required

Returns:

Type Description
dict[str, dict[str, Any]]

Stats dict {module: {"avg_A", "std_A", "avg_B", "std_B"}}.

Raises:

Type Description
ValueError

If the loaded object is not a dict.

Source code in libs/model-training/src/model_training/reconstruction/stats.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
def load_zscore_stats(path: Path) -> dict[str, dict[str, Any]]:
    """Inverse of ``save_zscore_stats``.

    Args:
        path: Path to a ``.pt`` file written by ``save_zscore_stats``.

    Returns:
        Stats dict ``{module: {"avg_A", "std_A", "avg_B", "std_B"}}``.

    Raises:
        ValueError: If the loaded object is not a dict.
    """
    import torch  # noqa: PLC0415

    loaded = torch.load(str(path), weights_only=False)
    if not isinstance(loaded, dict):
        raise ValueError(f"expected dict in {path}, got {type(loaded)!r}")
    return loaded
task_embeddings

Task embedding computation + persistence for reconstruction datasets.

Mirrors T2L's get_task_embs (see hyper_llm_modulator/data.py). Default encoder is sentence-transformers/all-mpnet-base-v2 (768-d). A None model falls back to one-hot orthogonal vectors.

sentence-transformers is imported inside load_default_encoder (INFRA-05).

Functions
load_default_encoder
load_default_encoder(
    model_id: str = DEFAULT_EMBEDDING_MODEL,
    device: str = "cpu",
) -> _Encoder

Instantiate a sentence-transformers SentenceTransformer encoder.

Parameters:

Name Type Description Default
model_id str

HF repo id.

DEFAULT_EMBEDDING_MODEL
device str

"cpu" or "cuda".

'cpu'
Source code in libs/model-training/src/model_training/reconstruction/task_embeddings.py
26
27
28
29
30
31
32
33
34
35
36
37
def load_default_encoder(
    model_id: str = DEFAULT_EMBEDDING_MODEL, device: str = "cpu"
) -> _Encoder:
    """Instantiate a sentence-transformers SentenceTransformer encoder.

    Args:
        model_id: HF repo id.
        device: ``"cpu"`` or ``"cuda"``.
    """
    from sentence_transformers import SentenceTransformer  # type: ignore[import-not-found]  # noqa: PLC0415, I001

    return SentenceTransformer(model_id, device=device)
compute_task_embeddings
compute_task_embeddings(
    descriptions: dict[str, str], *, model: _Encoder | None
) -> dict[str, Any]

Compute per-task embeddings, returning {task_id: Tensor[1, dim]}.

When model is None, emits orthogonal one-hot vectors of dim len(descriptions). This matches T2L's fallback in get_task_embs and guarantees the hypernetwork can still discriminate tasks even when no encoder is available.

Parameters:

Name Type Description Default
descriptions dict[str, str]

Mapping of task_id to natural-language description.

required
model _Encoder | None

Encoder with an encode method, or None for one-hot.

required

Returns:

Type Description
dict[str, Any]

Dict mapping task_id to a Tensor[1, dim].

Source code in libs/model-training/src/model_training/reconstruction/task_embeddings.py
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
def compute_task_embeddings(
    descriptions: dict[str, str],
    *,
    model: _Encoder | None,
) -> dict[str, Any]:
    """Compute per-task embeddings, returning ``{task_id: Tensor[1, dim]}``.

    When ``model`` is None, emits orthogonal one-hot vectors of dim
    ``len(descriptions)``. This matches T2L's fallback in ``get_task_embs``
    and guarantees the hypernetwork can still discriminate tasks even when
    no encoder is available.

    Args:
        descriptions: Mapping of task_id to natural-language description.
        model: Encoder with an ``encode`` method, or ``None`` for one-hot.

    Returns:
        Dict mapping task_id to a ``Tensor[1, dim]``.
    """
    import torch  # noqa: PLC0415

    task_ids = list(descriptions.keys())
    n = len(task_ids)

    if model is None:
        logger.info(
            "compute_task_embeddings: no encoder → one-hot fallback (dim=%d)", n
        )
        eye = torch.eye(n, dtype=torch.float32)
        return {tid: eye[i].unsqueeze(0) for i, tid in enumerate(task_ids)}

    texts = [descriptions[tid] for tid in task_ids]
    encoded = model.encode(texts, convert_to_tensor=True)
    if not isinstance(encoded, torch.Tensor):
        encoded = torch.as_tensor(encoded)
    encoded = encoded.float().cpu()
    if encoded.ndim != 2 or encoded.shape[0] != n:
        raise ValueError(
            f"encoder returned shape {tuple(encoded.shape)}, expected ({n}, dim)"
        )
    return {tid: encoded[i].unsqueeze(0).contiguous() for i, tid in enumerate(task_ids)}
save_task_embeddings
save_task_embeddings(
    embeddings: dict[str, Any], path: Path
) -> None

Persist {task_id: Tensor} as a torch.save file.

Parameters:

Name Type Description Default
embeddings dict[str, Any]

Dict mapping task_id to embedding tensor.

required
path Path

Destination file path (parent dirs created if needed).

required
Source code in libs/model-training/src/model_training/reconstruction/task_embeddings.py
83
84
85
86
87
88
89
90
91
92
93
def save_task_embeddings(embeddings: dict[str, Any], path: Path) -> None:
    """Persist ``{task_id: Tensor}`` as a ``torch.save`` file.

    Args:
        embeddings: Dict mapping task_id to embedding tensor.
        path: Destination file path (parent dirs created if needed).
    """
    import torch  # noqa: PLC0415

    path.parent.mkdir(parents=True, exist_ok=True)
    torch.save(embeddings, str(path))
load_task_embeddings
load_task_embeddings(path: Path) -> dict[str, Any]

Inverse of save_task_embeddings.

Parameters:

Name Type Description Default
path Path

Path to a file saved by save_task_embeddings.

required

Returns:

Type Description
dict[str, Any]

Dict mapping task_id to embedding tensor.

Raises:

Type Description
ValueError

If the loaded object is not a dict.

Source code in libs/model-training/src/model_training/reconstruction/task_embeddings.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
def load_task_embeddings(path: Path) -> dict[str, Any]:
    """Inverse of ``save_task_embeddings``.

    Args:
        path: Path to a file saved by ``save_task_embeddings``.

    Returns:
        Dict mapping task_id to embedding tensor.

    Raises:
        ValueError: If the loaded object is not a dict.
    """
    import torch  # noqa: PLC0415

    loaded = torch.load(str(path), weights_only=False)
    if not isinstance(loaded, dict):
        raise ValueError(f"expected dict in {path}, got {type(loaded)!r}")
    return loaded

round2_config

Pydantic config for round-2 hypernetwork distillation training.

Inherits every round-1 field from :class:model_training.d2l_train.D2LTrainConfig and adds oracle-adapter routing fields. Defaults keep behaviour as close as possible to round-1 so operators can diff-review a round-1 vs round-2 run.

Classes
Round2TrainConfig

Bases: D2LTrainConfig

Configuration for round-2 (oracle-teacher) hypernetwork training.

Attributes:

Name Type Description
oracle_registry_url str

SQLAlchemy URL for the AdapterRegistry SQLite DB that holds the 25 per-bin oracle adapter records.

max_loaded_oracles int

LRU cache cap for simultaneously cached oracle LoRA dicts (functional-LoRA format: {module: {A, B}}). Each entry is lightweight (tensors only, no model wrappers); this bound mostly limits the rate of disk reads.

min_oracle_coverage float

Minimum fraction of training records that must route to a registered oracle. When the startup audit reports less than this, training aborts. Effectively mandatory because the default fallback ("skip") means below-coverage runs make no training progress.

oracle_fallback Literal['base_model', 'skip']

What to do when a record's bin has no registered oracle. "skip" (default) drops the record from the epoch — preserves the premise that the hypernet should only learn from oracle signal. "base_model" uses the bare base model (round-1 behaviour); kept available for ablations.

checkpoint_dir str

Overrides parent default so round-2 does not clobber round-1 checkpoints.

experiment_name str

Overrides parent default so MLflow separates the runs.

round2_gate

Strict success gate for round-2 vs round-1 benchmark deltas.

Gate (strict): - round-2 Pass@1 >= round-1 Pass@1 + 2.0% on at least 4 of 6 benchmarks, AND - no single benchmark regresses by more than 1.0%.

Functions
evaluate_round2_gate
evaluate_round2_gate(
    scores: dict[str, dict[str, float]],
) -> dict[str, object]

Apply the strict pass bar to round-1 vs round-2 Pass@1 deltas.

Parameters:

Name Type Description Default
scores dict[str, dict[str, float]]

{benchmark_id: {"baseline": <r1>, "round2": <r2>}} for every benchmark in :data:REQUIRED_BENCHMARKS.

required

Returns:

Type Description
dict[str, object]

Report dict with keys passed (bool, gate verdict), deltas

dict[str, object]

({bench: r2 - r1}), improved_count (count of benchmarks with

dict[str, object]

delta >= STRICT_IMPROVEMENT_MIN), max_regression (largest

dict[str, object]

absolute regression observed, max(0, -delta) across all

dict[str, object]

benchmarks), and reasons (list[str] describing why the gate

dict[str, object]

failed, or empty when passed).

Raises:

Type Description
ValueError

When any required benchmark is missing from scores.

Source code in libs/model-training/src/model_training/round2_gate.py
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
def evaluate_round2_gate(
    scores: dict[str, dict[str, float]],
) -> dict[str, object]:
    """Apply the strict pass bar to round-1 vs round-2 Pass@1 deltas.

    Args:
        scores: ``{benchmark_id: {"baseline": <r1>, "round2": <r2>}}`` for
            every benchmark in :data:`REQUIRED_BENCHMARKS`.

    Returns:
        Report dict with keys ``passed`` (bool, gate verdict), ``deltas``
        (``{bench: r2 - r1}``), ``improved_count`` (count of benchmarks with
        delta >= ``STRICT_IMPROVEMENT_MIN``), ``max_regression`` (largest
        absolute regression observed, ``max(0, -delta)`` across all
        benchmarks), and ``reasons`` (list[str] describing why the gate
        failed, or empty when ``passed``).

    Raises:
        ValueError: When any required benchmark is missing from ``scores``.
    """
    missing = [b for b in REQUIRED_BENCHMARKS if b not in scores]
    if missing:
        raise ValueError(f"missing required benchmarks: {missing}")

    deltas: dict[str, float] = {}
    for bench in REQUIRED_BENCHMARKS:
        r1 = float(scores[bench]["baseline"])
        r2 = float(scores[bench]["round2"])
        deltas[bench] = r2 - r1

    improved_count = sum(1 for d in deltas.values() if d >= STRICT_IMPROVEMENT_MIN)
    max_regression = max((-d for d in deltas.values() if d < 0), default=0.0)

    reasons: list[str] = []
    if improved_count < STRICT_MIN_IMPROVED:
        reasons.append(
            f"improved {improved_count} benchmark(s) by >= "
            f"{STRICT_IMPROVEMENT_MIN:+.1%}; need {STRICT_MIN_IMPROVED}"
        )
    if max_regression > STRICT_MAX_REGRESSION:
        reasons.append(
            f"max regression {max_regression:.2%} exceeds allowed "
            f"{STRICT_MAX_REGRESSION:.2%}"
        )

    passed = not reasons
    logger.info(
        "Round-2 gate: %s (improved=%d, max_regression=%.2f%%)",
        "PASS" if passed else "FAIL",
        improved_count,
        max_regression * 100,
    )
    return {
        "passed": passed,
        "deltas": deltas,
        "improved_count": improved_count,
        "max_regression": max_regression,
        "reasons": reasons,
    }

round2_train

Round-2 hypernetwork training: per-bin oracle teacher distillation.

This module mirrors :mod:model_training.d2l_train's two-pass teacher/student step but replaces the bare-base-model teacher forward with a per-record oracle-LoRA teacher forward. The oracle is applied via the SAME apply_functional_lora context manager used for the student pass, which monkey-patches the base model's weight tensors in place and restores on exit. The base model is never structurally mutated (no PeftModel wrappers, no LoraLayer replacements), so there is no possibility of hook leakage between teacher and student passes.

When a record's bin has no registered oracle and oracle_fallback='skip' (the default), the record is dropped upstream in _training_step_round2 and the teacher-forward helper is not invoked. When oracle_fallback='base_model' (ablation only), the helper is invoked with oracle_lora_dict=None and falls through to the bare base model.

GPU imports are deferred inside function bodies per INFRA-05 so this module stays importable in CPU-only CI.

Functions
train_d2l_qwen3_round2
train_d2l_qwen3_round2(
    config: Any,
    *,
    kill_switch_evaluate_fn: Any | None = None,
) -> dict[str, Any]

Round-2 hypernetwork training loop with per-bin oracle teachers.

Flow
  1. Load records from config.dataset_path.
  2. Open the AdapterRegistry, audit oracle coverage, abort when coverage < config.min_oracle_coverage.
  3. When config.dry_run: return a report dict and exit.
  4. Setup base model, tokenizer, hypernet, hc.
  5. Build :class:OracleAdapterCache and loop num_steps records, calling :func:_training_step_round2 per step. Skip sentinels advance the step counter without an optimizer step.
  6. Apply the same checkpoint + kill-switch cadence as round-1.

Parameters:

Name Type Description Default
config Any

:class:Round2TrainConfig instance.

required
kill_switch_evaluate_fn Any | None

Optional zero-arg callable returning Pass@1 for the kill-switch. When None and config.kill_switch_enabled is True, the default benchmark evaluator is constructed.

None

Returns:

Type Description
dict[str, Any]

Report dict. Shape depends on mode. In dry_run mode the keys are

dict[str, Any]

dry_run (True), coverage_ratio, bin_counts, and

dict[str, Any]

num_records. In full mode the keys are dry_run (False),

dict[str, Any]

coverage_ratio, bin_counts, num_records, final_loss,

dict[str, Any]

best_loss, steps_completed, and kill_switch_triggered.

Source code in libs/model-training/src/model_training/round2_train.py
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
def train_d2l_qwen3_round2(
    config: Any,
    *,
    kill_switch_evaluate_fn: Any | None = None,
) -> dict[str, Any]:
    """Round-2 hypernetwork training loop with per-bin oracle teachers.

    Flow:
      1. Load records from ``config.dataset_path``.
      2. Open the AdapterRegistry, audit oracle coverage, abort when
         coverage < ``config.min_oracle_coverage``.
      3. When ``config.dry_run``: return a report dict and exit.
      4. Setup base model, tokenizer, hypernet, hc.
      5. Build :class:`OracleAdapterCache` and loop ``num_steps`` records,
         calling :func:`_training_step_round2` per step. Skip sentinels
         advance the step counter without an optimizer step.
      6. Apply the same checkpoint + kill-switch cadence as round-1.

    Args:
        config: :class:`Round2TrainConfig` instance.
        kill_switch_evaluate_fn: Optional zero-arg callable returning Pass@1
            for the kill-switch. When ``None`` and ``config.kill_switch_enabled``
            is True, the default benchmark evaluator is constructed.

    Returns:
        Report dict. Shape depends on mode. In dry_run mode the keys are
        ``dry_run`` (``True``), ``coverage_ratio``, ``bin_counts``, and
        ``num_records``. In full mode the keys are ``dry_run`` (``False``),
        ``coverage_ratio``, ``bin_counts``, ``num_records``, ``final_loss``,
        ``best_loss``, ``steps_completed``, and ``kill_switch_triggered``.
    """
    from model_training.oracle_cache import (  # noqa: PLC0415
        OracleAdapterCache,
        audit_oracle_coverage,
    )

    if not config.dataset_path:
        raise ValueError("config.dataset_path is required for round-2 training")

    records = _load_records(config.dataset_path)
    registry = _open_registry(config.oracle_registry_url)
    coverage_ratio, bin_counts = audit_oracle_coverage(records, registry)

    logger.info(
        "Round-2 oracle coverage: %.3f (min=%.3f); per-bin counts: %s",
        coverage_ratio,
        config.min_oracle_coverage,
        bin_counts,
    )

    if coverage_ratio < config.min_oracle_coverage:
        raise RuntimeError(
            f"Round-2 oracle coverage {coverage_ratio:.3f} < "
            f"min_oracle_coverage {config.min_oracle_coverage:.3f}; aborting. "
            f"Per-bin counts: {bin_counts}"
        )

    if config.dry_run:
        return {
            "dry_run": True,
            "coverage_ratio": coverage_ratio,
            "bin_counts": bin_counts,
            "num_records": len(records),
        }

    handles = _setup_training(config)
    base_model = handles["base_model"]
    tokenizer = handles["tokenizer"]
    hypernet = handles["hypernet"]
    hc = handles["hc"]

    oracle_cache = OracleAdapterCache(
        registry=registry,
        hc=hc,
        max_loaded=config.max_loaded_oracles,
    )

    return _run_training_loop(
        config=config,
        records=records,
        base_model=base_model,
        tokenizer=tokenizer,
        hypernet=hypernet,
        hc=hc,
        oracle_cache=oracle_cache,
        kill_switch_evaluate_fn=kill_switch_evaluate_fn,
        coverage_ratio=coverage_ratio,
        bin_counts=bin_counts,
    )
register_round2_adapter
register_round2_adapter(
    *,
    registry: Any,
    bin_counts: dict[str, int],
    adapter_file_path: str,
    base_model_id: str,
    rank: int,
) -> str

Register the round-2 adapter output in AdapterRegistry.

The adapter_id is deterministic-per-run: round2_<uuid4[:8]>. Lineage is captured as parent_ids = json.dumps(sorted(oracle_ids)) where oracle_ids covers every bin that contributed at least one training record. generation is set to 2 so lineage queries can distinguish round-2 output from round-1 oracles (generation 0).

Parameters:

Name Type Description Default
registry Any

:class:AdapterRegistry instance.

required
bin_counts dict[str, int]

Per-bin record counts from the audit report.

required
adapter_file_path str

On-disk path to the saved round-2 adapter.

required
base_model_id str

Base model this adapter was trained against.

required
rank int

LoRA rank used during training.

required

Returns:

Type Description
str

The registered adapter_id.

Source code in libs/model-training/src/model_training/round2_train.py
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
def register_round2_adapter(
    *,
    registry: Any,
    bin_counts: dict[str, int],
    adapter_file_path: str,
    base_model_id: str,
    rank: int,
) -> str:
    """Register the round-2 adapter output in AdapterRegistry.

    The adapter_id is deterministic-per-run: ``round2_<uuid4[:8]>``. Lineage
    is captured as ``parent_ids = json.dumps(sorted(oracle_ids))`` where
    ``oracle_ids`` covers every bin that contributed at least one training
    record. ``generation`` is set to 2 so lineage queries can distinguish
    round-2 output from round-1 oracles (generation 0).

    Args:
        registry: :class:`AdapterRegistry` instance.
        bin_counts: Per-bin record counts from the audit report.
        adapter_file_path: On-disk path to the saved round-2 adapter.
        base_model_id: Base model this adapter was trained against.
        rank: LoRA rank used during training.

    Returns:
        The registered adapter_id.
    """
    from adapter_registry.models import AdapterRecord  # noqa: PLC0415

    adapter_id = f"round2_{uuid4().hex[:8]}"
    parent_ids = sorted(f"oracle_{bk}" for bk in bin_counts)

    file_path = Path(adapter_file_path)
    if file_path.exists() and file_path.is_file():
        file_bytes = file_path.read_bytes()
        file_hash = hashlib.sha256(file_bytes).hexdigest()
        file_size = len(file_bytes)
    else:
        file_hash = ""
        file_size = 0

    record = AdapterRecord(
        id=adapter_id,
        version=1,
        task_type="round2_hypernet",
        base_model_id=base_model_id,
        rank=rank,
        created_at=datetime.now(tz=timezone.utc).isoformat(),
        file_path=str(file_path),
        file_hash=file_hash,
        file_size_bytes=file_size,
        source=ROUND2_SOURCE,
        session_id="",
        parent_ids=json.dumps(parent_ids),
        generation=ROUND2_GENERATION,
    )
    registry.store(record)
    logger.info(
        "Registered round-2 adapter %s with %d parent oracles",
        adapter_id,
        len(parent_ids),
    )
    return adapter_id

sakana_d2l

SakanaAI Doc-to-LoRA integration.

Wraps Sakana's pretrained HyperLoRA perceiver so it can be used through our hypernetwork interface (load_pretrained → generate_adapter).

The Sakana hypernetwork takes per-layer activations from a base model as input and produces LoRA adapter weights. This module handles: - Downloading the checkpoint from HuggingFace - Patching flash-attention assertions for CPU/MPS/non-flash environments - Extracting per-layer activations from the base model - Saving the generated LoRA weights in PEFT format

GPU imports are deferred inside function bodies per INFRA-05 pattern.

Functions
download_checkpoint
download_checkpoint(variant: str = DEFAULT_VARIANT) -> Path

Download Sakana's pretrained checkpoint from HuggingFace.

Parameters:

Name Type Description Default
variant str

Which checkpoint variant to download. Options: 'gemma_demo', 'gemma_2b_d2l', 'mistral_7b_d2l', 'qwen_4b_d2l'.

DEFAULT_VARIANT

Returns:

Type Description
Path

Path to the downloaded checkpoint file.

Source code in libs/model-training/src/model_training/sakana_d2l.py
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
def download_checkpoint(
    variant: str = DEFAULT_VARIANT,
) -> Path:
    """Download Sakana's pretrained checkpoint from HuggingFace.

    Args:
        variant: Which checkpoint variant to download.
            Options: 'gemma_demo', 'gemma_2b_d2l', 'mistral_7b_d2l', 'qwen_4b_d2l'.

    Returns:
        Path to the downloaded checkpoint file.
    """
    # Determine filename based on variant
    if variant == "gemma_demo":
        hf_filename = "gemma_demo/checkpoint-80000/pytorch_model.bin"
    elif variant in ("gemma_2b_d2l", "mistral_7b_d2l", "qwen_4b_d2l"):
        hf_filename = f"{variant}/checkpoint-20000/pytorch_model.bin"
    else:
        msg = f"Unknown variant: {variant}"
        raise ValueError(msg)

    cached = LOCAL_CACHE_DIR / variant / "pytorch_model.bin"
    if cached.exists():
        logger.info("Using cached Sakana checkpoint: %s", cached)
        return cached

    from huggingface_hub import hf_hub_download  # noqa: PLC0415

    logger.info("Downloading Sakana checkpoint %s from %s...", variant, HF_REPO_ID)
    downloaded = Path(hf_hub_download(repo_id=HF_REPO_ID, filename=hf_filename))

    cached.parent.mkdir(parents=True, exist_ok=True)
    import shutil  # noqa: PLC0415

    shutil.copy2(downloaded, cached)
    logger.info("Cached to: %s", cached)
    return cached
load_sakana_checkpoint
load_sakana_checkpoint(
    checkpoint_path: str | Path | None = None,
    variant: str = DEFAULT_VARIANT,
    device: str = "cpu",
) -> tuple[Any, Any]

Load Sakana's HyperLoRA perceiver from checkpoint.

Downloads from HuggingFace if no local path is provided. Patches flash attention for CPU/MPS compatibility.

Parameters:

Name Type Description Default
checkpoint_path str | Path | None

Path to local checkpoint. If None, downloads from HF.

None
variant str

HF checkpoint variant (only used if checkpoint_path is None).

DEFAULT_VARIANT
device str

Device to load onto.

'cpu'

Returns:

Type Description
tuple[Any, Any]

Tuple of (hypernet, hypernet_config).

Source code in libs/model-training/src/model_training/sakana_d2l.py
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
def load_sakana_checkpoint(
    checkpoint_path: str | Path | None = None,
    variant: str = DEFAULT_VARIANT,
    device: str = "cpu",
) -> tuple[Any, Any]:
    """Load Sakana's HyperLoRA perceiver from checkpoint.

    Downloads from HuggingFace if no local path is provided.
    Patches flash attention for CPU/MPS compatibility.

    Args:
        checkpoint_path: Path to local checkpoint. If None, downloads from HF.
        variant: HF checkpoint variant (only used if checkpoint_path is None).
        device: Device to load onto.

    Returns:
        Tuple of (hypernet, hypernet_config).
    """
    import torch  # noqa: PLC0415

    _patch_flash_attention()

    # Pre-import flash_attn before torch.load — the unpickler triggers
    # ctx_to_lora module imports in a context that breaks flash_attn
    # resolution if it hasn't been imported yet.
    try:
        import flash_attn.flash_attn_interface  # noqa: F401,PLC0415
    except ImportError:
        pass

    if checkpoint_path is None:
        checkpoint_path = download_checkpoint(variant)

    logger.info("Loading Sakana checkpoint: %s", checkpoint_path)
    sd = torch.load(str(checkpoint_path), map_location="cpu", weights_only=False)

    hc = sd["hypernet_config"]
    logger.info(
        "HypernetConfig: latent_size=%d, lora_r=%d, base_model=%s",
        hc.latent_size,
        hc.lora_config.r,
        sd["base_model_name_or_path"],
    )

    from ctx_to_lora.modeling.hypernet import HyperLoRA  # noqa: PLC0415
    from shared.hardware import resolve_model_dtype  # noqa: PLC0415

    hypernet_param_count = sum(
        v.numel() for v in sd.values() if isinstance(v, torch.Tensor)
    )
    hypernet_dtype = resolve_model_dtype(
        param_count=hypernet_param_count,
        device=device,
    )
    logger.info("HyperLoRA dtype resolved to %s", hypernet_dtype)
    # Suppress "Flash Attention 2 without specifying a torch dtype" warning
    # by setting the dtype on the config before HyperLoRA instantiation.
    if hasattr(hc, "aggregator_config"):
        ac = hc.aggregator_config
        if hasattr(ac, "torch_dtype"):
            ac.torch_dtype = hypernet_dtype
    hypernet = HyperLoRA(hc).to(hypernet_dtype)

    # Load ALL hypernet weights from checkpoint (not just a prefix subset).
    # The checkpoint contains aggregator.*, head.*, scaler_{A,B}.*,
    # bias_{A,B}.*, and layers.0.* — all are required for correct
    # adapter generation.  scaler_B in particular defaults to zeros,
    # so skipping it zeroes out every lora_B matrix.
    model_keys = set(hypernet.state_dict().keys())
    hypernet_sd = {k: v for k, v in sd.items() if k in model_keys}

    loaded = hypernet.load_state_dict(hypernet_sd, strict=False)
    logger.info(
        "Loaded %d/%d hypernet weight tensors",
        len(hypernet_sd),
        len(model_keys),
    )
    if loaded.missing_keys:
        logger.warning(
            "Missing keys (%d, will use defaults): %s",
            len(loaded.missing_keys),
            loaded.missing_keys,
        )
    if loaded.unexpected_keys:
        logger.info("Unexpected keys: %d", len(loaded.unexpected_keys))

    hypernet = hypernet.to(device)
    hypernet.eval()

    param_count = sum(p.numel() for p in hypernet.parameters())
    logger.info("HyperLoRA params: %d", param_count)

    return hypernet, hc
transfer_aggregator_weights
transfer_aggregator_weights(
    hypernet: Any, checkpoint_path: str | Path
) -> Any

Load aggregator weights from a Sakana checkpoint into a HyperLoRA instance.

Loads only aggregator. weights from the checkpoint (not head.), freezes all aggregator parameters (requires_grad=False), and leaves head.* at PyTorch default initialization for Phase 29 training against the new target model.

This enables reuse of the pretrained Perceiver aggregator across different target model architectures. The aggregator maps document embeddings to LoRA weight space and is model-agnostic; only the head needs retraining per target model.

Parameters:

Name Type Description Default
hypernet Any

The HyperLoRA model to load weights into (mutated in-place).

required
checkpoint_path str | Path

Path to the Sakana checkpoint (.bin file).

required

Returns:

Type Description
Any

The mutated hypernet (returned for chaining convenience).

Source code in libs/model-training/src/model_training/sakana_d2l.py
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
def transfer_aggregator_weights(hypernet: Any, checkpoint_path: str | Path) -> Any:
    """Load aggregator weights from a Sakana checkpoint into a HyperLoRA instance.

    Loads only aggregator.* weights from the checkpoint (not head.*), freezes all
    aggregator parameters (requires_grad=False), and leaves head.* at PyTorch default
    initialization for Phase 29 training against the new target model.

    This enables reuse of the pretrained Perceiver aggregator across different target
    model architectures. The aggregator maps document embeddings to LoRA weight space
    and is model-agnostic; only the head needs retraining per target model.

    Args:
        hypernet: The HyperLoRA model to load weights into (mutated in-place).
        checkpoint_path: Path to the Sakana checkpoint (.bin file).

    Returns:
        The mutated hypernet (returned for chaining convenience).
    """
    import torch  # noqa: PLC0415

    sd = torch.load(str(checkpoint_path), map_location="cpu", weights_only=False)

    # Filter to only aggregator.* tensors that exist in the target model
    model_sd = hypernet.state_dict()
    aggregator_sd = {
        k: v
        for k, v in sd.items()
        if k.startswith("aggregator.") and isinstance(v, torch.Tensor) and k in model_sd
    }

    logger.info(
        "Loading %d aggregator weights from checkpoint: %s",
        len(aggregator_sd),
        checkpoint_path,
    )

    loaded = hypernet.load_state_dict(aggregator_sd, strict=False)
    _assert_transfer_integrity(hypernet, loaded)

    # Freeze all aggregator parameters — only head will be trained
    frozen_count = 0
    trainable_count = 0
    for name, param in hypernet.named_parameters():
        if name.startswith("aggregator."):
            param.requires_grad_(False)
            frozen_count += 1
        else:
            trainable_count += 1

    logger.info(
        "Froze %d aggregator params; %d params (head.*) remain trainable",
        frozen_count,
        trainable_count,
    )

    return hypernet
get_aggregator_config
get_aggregator_config(checkpoint_path: str | Path) -> Any

Extract the Perceiver aggregator structural config from a Sakana checkpoint.

Reads the aggregator_config from the checkpoint's HypernetConfig so that d2l_config.py can populate the aggregator_config=None placeholder set in Phase 25.

Parameters:

Name Type Description Default
checkpoint_path str | Path

Path to the Sakana checkpoint (.bin file).

required

Returns:

Type Description
Any

The aggregator_config object from the checkpoint's HypernetConfig.

Raises:

Type Description
ValueError

If the checkpoint's aggregator_config is None (predates this field).

Source code in libs/model-training/src/model_training/sakana_d2l.py
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
def get_aggregator_config(checkpoint_path: str | Path) -> Any:
    """Extract the Perceiver aggregator structural config from a Sakana checkpoint.

    Reads the aggregator_config from the checkpoint's HypernetConfig so that
    d2l_config.py can populate the aggregator_config=None placeholder set in Phase 25.

    Args:
        checkpoint_path: Path to the Sakana checkpoint (.bin file).

    Returns:
        The aggregator_config object from the checkpoint's HypernetConfig.

    Raises:
        ValueError: If the checkpoint's aggregator_config is None (predates this field).
    """
    import torch  # noqa: PLC0415

    sd = torch.load(str(checkpoint_path), map_location="cpu", weights_only=False)
    hc = sd["hypernet_config"]

    if hc.aggregator_config is None:
        msg = (
            "aggregator_config is None in checkpoint — "
            "checkpoint may predate this field"
        )
        raise ValueError(msg)

    return hc.aggregator_config
extract_activations
extract_activations(
    text: str,
    base_model_name: str,
    layer_indices: list[int],
    device: str = "cpu",
    max_length: int = 512,
) -> tuple[Any, Any]

Extract per-layer hidden state activations from the base model.

Backward-compatible wrapper around extract_activations_with_model(). Loads model and tokenizer, delegates extraction, then cleans up.

Parameters:

Name Type Description Default
text str

Input text to process.

required
base_model_name str

HuggingFace model ID for the base model.

required
layer_indices list[int]

Which layers to extract activations from.

required
device str

Device for computation.

'cpu'
max_length int

Max token sequence length.

512

Returns:

Type Description
Any

Tuple of (features, attention_mask) ready for HyperLoRA.

Any

features shape: (1, num_layers, seq_len, hidden_dim)

tuple[Any, Any]

attention_mask shape: (1, seq_len)

Source code in libs/model-training/src/model_training/sakana_d2l.py
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
def extract_activations(
    text: str,
    base_model_name: str,
    layer_indices: list[int],
    device: str = "cpu",
    max_length: int = 512,
) -> tuple[Any, Any]:
    """Extract per-layer hidden state activations from the base model.

    Backward-compatible wrapper around extract_activations_with_model().
    Loads model and tokenizer, delegates extraction, then cleans up.

    Args:
        text: Input text to process.
        base_model_name: HuggingFace model ID for the base model.
        layer_indices: Which layers to extract activations from.
        device: Device for computation.
        max_length: Max token sequence length.

    Returns:
        Tuple of (features, attention_mask) ready for HyperLoRA.
        features shape: (1, num_layers, seq_len, hidden_dim)
        attention_mask shape: (1, seq_len)
    """
    if not text or not text.strip():
        raise ValueError(
            "extract_activations called with empty text; adapter would be meaningless."
        )

    import torch  # noqa: PLC0415
    from shared.hardware import resolve_model_dtype  # noqa: PLC0415
    from transformers import AutoModelForCausalLM, AutoTokenizer  # noqa: PLC0415

    from model_training.d2l_probe import extract_activations_with_model  # noqa: PLC0415

    logger.info("Loading base model %s for activation extraction...", base_model_name)
    tokenizer = AutoTokenizer.from_pretrained(base_model_name)

    # Estimate param count from model config to resolve dtype
    from transformers import AutoConfig  # noqa: PLC0415

    config = AutoConfig.from_pretrained(base_model_name)
    estimated_params = getattr(config, "num_parameters", None)
    if estimated_params is None:
        # Rough estimate: vocab_size * hidden + num_layers * 4 * hidden^2
        vocab = getattr(config, "vocab_size", 256000)
        hidden = getattr(config, "hidden_size", 2304)
        n_layers = getattr(config, "num_hidden_layers", 26)
        estimated_params = vocab * hidden + n_layers * 4 * hidden * hidden

    # Account for inference model already on GPU as overhead
    overhead = 0
    if device != "cpu" and torch.cuda.is_available():
        overhead = torch.cuda.memory_allocated(0)

    activation_dtype = resolve_model_dtype(
        param_count=estimated_params,
        device=device,
        overhead_bytes=overhead,
    )
    logger.info("Activation extraction dtype resolved to %s", activation_dtype)

    model: Any = AutoModelForCausalLM.from_pretrained(
        base_model_name,
        dtype=activation_dtype,
    )
    model = model.to(device)  # type: ignore[assignment]
    model.eval()

    result = extract_activations_with_model(
        text=text,
        model=model,
        tokenizer=tokenizer,
        layer_indices=layer_indices,
        max_length=max_length,
    )

    del model
    if device != "cpu":
        torch.cuda.empty_cache()
    return result
generate_adapter_from_sakana
generate_adapter_from_sakana(
    text: str,
    output_dir: str,
    checkpoint_path: str | Path | None = None,
    variant: str = DEFAULT_VARIANT,
    base_model_name: str | None = None,
    device: str = "cpu",
    max_length: int = 512,
    scaling_factor: float = 0.16,
) -> str

End-to-end: text → base model activations → HyperLoRA → PEFT adapter.

This is the main entry point. It: 1. Loads the Sakana pretrained perceiver (downloading if needed) 2. Runs text through the base model to get per-layer activations 3. Feeds activations through the perceiver to generate LoRA weights 4. Saves weights in PEFT-compatible format

Parameters:

Name Type Description Default
text str

Input text (trajectory, document, context) to encode.

required
output_dir str

Directory to save the PEFT adapter files.

required
checkpoint_path str | Path | None

Path to local checkpoint, or None to download.

None
variant str

HF checkpoint variant if downloading.

DEFAULT_VARIANT
base_model_name str | None

Override base model. If None, uses the one from checkpoint.

None
device str

Device for computation.

'cpu'
max_length int

Maximum token sequence length for activation extraction.

512
scaling_factor float

Adapter scaling multiplier (0-1, default from config).

0.16

Returns:

Type Description
str

Path to the saved adapter directory.

Source code in libs/model-training/src/model_training/sakana_d2l.py
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
def generate_adapter_from_sakana(
    text: str,
    output_dir: str,
    checkpoint_path: str | Path | None = None,
    variant: str = DEFAULT_VARIANT,
    base_model_name: str | None = None,
    device: str = "cpu",
    max_length: int = 512,
    scaling_factor: float = 0.16,
) -> str:
    """End-to-end: text → base model activations → HyperLoRA → PEFT adapter.

    This is the main entry point. It:
      1. Loads the Sakana pretrained perceiver (downloading if needed)
      2. Runs text through the base model to get per-layer activations
      3. Feeds activations through the perceiver to generate LoRA weights
      4. Saves weights in PEFT-compatible format

    Args:
        text: Input text (trajectory, document, context) to encode.
        output_dir: Directory to save the PEFT adapter files.
        checkpoint_path: Path to local checkpoint, or None to download.
        variant: HF checkpoint variant if downloading.
        base_model_name: Override base model. If None, uses the one from checkpoint.
        device: Device for computation.
        max_length: Maximum token sequence length for activation extraction.
        scaling_factor: Adapter scaling multiplier (0-1, default from config).

    Returns:
        Path to the saved adapter directory.
    """
    import torch  # noqa: PLC0415

    hypernet, hc = load_sakana_checkpoint(checkpoint_path, variant, device)

    # Determine base model from checkpoint config
    if base_model_name is None:
        # Load checkpoint just to read base_model_name_or_path
        if checkpoint_path is None:
            checkpoint_path = download_checkpoint(variant)
        sd = torch.load(str(checkpoint_path), map_location="cpu", weights_only=False)
        base_model_name = sd["base_model_name_or_path"]
        del sd

    logger.info("Base model: %s", base_model_name)

    # Extract activations from base model
    layer_indices = list(hc.layer_indices)
    features, attn_mask = extract_activations(
        text=text,
        base_model_name=base_model_name,
        layer_indices=layer_indices,
        device=device,
        max_length=max_length,
    )

    # Generate LoRA weights via perceiver
    logger.info("Generating LoRA weights via HyperLoRA perceiver...")
    with torch.no_grad():
        lora_dict, layernorm_dict = hypernet.generate_weights(features, attn_mask, None)

    # Combine generated weights with bias — Sakana concatenates bias as extra
    # rank dimensions (rank 8 → 16 for single chunk). This is how the
    # checkpoint was trained and evaluated.
    from ctx_to_lora.modeling.lora_merger import combine_lora as _combine_lora

    n_chunks = torch.ones(1, dtype=torch.int32)
    lora_bias = hypernet.get_head_bias() if hypernet.config.use_bias else None
    lora_dict = _combine_lora(lora_dict, n_chunks, lora_bias=lora_bias)

    # Save as PEFT adapter
    _save_sakana_adapter(
        lora_dict=lora_dict,
        output_dir=output_dir,
        base_model_name=base_model_name,
        hc=hc,
        scaling_factor=scaling_factor,
    )

    # Free hypernet VRAM — it's not needed after adapter weights are saved
    del hypernet, lora_dict, layernorm_dict, features, attn_mask
    if device != "cpu":
        torch.cuda.empty_cache()

    return output_dir

trainer

QLoRA training orchestrator.

All GPU-dependent imports (datasets, transformers, trl, torch) are deferred inside function bodies to ensure CPU-only importability (INFRA-05).

Module-level imports: stdlib only.

Functions
train_qlora
train_qlora(
    session_id: str | None,
    adapter_id: str,
    output_dir: str,
    *,
    base_model_id: str | None = None,
    task_type: str = "code-gen",
    rank: int | None = None,
    alpha: int | None = None,
    epochs: int | None = None,
    learning_rate: float = 0.0002,
    model_config_name: str | None = None,
    warm_start_adapter_id: str | None = None,
    gradient_accumulation_steps: int | None = None,
    lr_scheduler_type: str | None = None,
    mlflow_experiment: str = "rune-qlora",
    mlflow_tracking_uri: str | None = None,
    dataset_path: str | None = None,
    encoding_mode: str = "multi_turn",
    diff_aware_loss: bool = False,
    diff_changed_weight: float = 1.0,
    diff_unchanged_weight: float = 0.3,
    override_lora_alpha: int | None = None,
    override_lora_dropout: float | None = None,
    warmup_ratio: float | None = None,
    neftune_noise_alpha: float | None = None,
    max_length: int = 2048,
) -> str

Train a QLoRA adapter from a recorded coding trajectory.

Orchestrates the full training pipeline: load trajectory, format as SFT messages, build dataset, load model with NF4 quantization, train with SFT, and save the adapter to output_dir.

When model_config_name is provided, training defaults (rank, alpha, LR schedule, gradient accumulation, attention implementation) are loaded from the model registry. When the registry config specifies a warm_start_adapter_id, the pre-trained adapter is loaded via PeftModel.from_pretrained and training continues from those weights instead of initializing fresh LoRA matrices.

All GPU imports are deferred to this function body; the module is safe to import in CPU-only environments.

Parameters:

Name Type Description Default
session_id str | None

Trajectory session ID to train from. Mutually exclusive with dataset_path.

required
adapter_id str

Unique identifier for the resulting adapter.

required
output_dir str

Directory to save the trained adapter weights.

required
base_model_id str | None

HuggingFace model ID. Overrides registry default.

None
task_type str

Task category (e.g. 'code-gen', 'bug-fix').

'code-gen'
rank int | None

LoRA rank. Defaults to registry value or 64.

None
alpha int | None

LoRA alpha scaling factor. Defaults to registry value or 128.

None
epochs int | None

Number of training epochs. Defaults to registry value or 3.

None
learning_rate float

Optimizer learning rate.

0.0002
model_config_name str | None

Registry lookup key (e.g. "qwen3.5-9b"). When set, populates defaults from the model registry.

None
warm_start_adapter_id str | None

Pre-trained PEFT adapter to continue from. Overrides the registry's warm_start_adapter_id.

None
gradient_accumulation_steps int | None

Gradient accumulation steps. Defaults to registry value or 16.

None
lr_scheduler_type str | None

LR scheduler type. Defaults to registry value or "constant".

None
mlflow_experiment str

MLflow experiment name. Set RUNE_DISABLE_MLFLOW=1 in the env to disable MLflow tracking entirely.

'rune-qlora'
mlflow_tracking_uri str | None

Optional MLflow tracking URI override. Falls back to the MLFLOW_TRACKING_URI env var, then to "sqlite:///./mlflow.db".

None
dataset_path str | None

Path to a JSONL file of mined pair records (as produced by scripts/mine_github.py --batch). Mutually exclusive with session_id; when set, the training dataset is built by pairs_to_chat_messages instead of format_for_sft.

None
encoding_mode str

"multi_turn" clusters pairs by source task and emits one conversation per task; "single_turn" emits one conversation per pair. Only used when dataset_path is set.

'multi_turn'
diff_aware_loss bool

When True, wrap the SFT collator with DiffWeightedDataCollator and swap in DiffAwareSFTTrainer so per-token loss is scaled by the diff between assistant output and the masked user/context span. Disables assistant_only_loss on SFTConfig since the custom collator provides equivalent (stricter) masking.

False
diff_changed_weight float

Per-token weight applied to assistant tokens absent from the masked context span. Only used when diff_aware_loss=True. Defaults to 1.0.

1.0
diff_unchanged_weight float

Per-token weight applied to assistant tokens also present in the masked context span. Only used when diff_aware_loss=True. Defaults to 0.3.

0.3
override_lora_alpha int | None

Post-load override for the warm-start adapter's effective alpha. Applied via a module-tree walk after PeftModel.from_pretrained since PEFT caches scaling = alpha / r per layer. Has no effect when no warm-start is in use.

None
override_lora_dropout float | None

Post-load override for the warm-start adapter's LoRA dropout probability. Applied the same way as override_lora_alpha — by walking the module tree and mutating each layer's lora_dropout[adapter_name].p.

None
warmup_ratio float | None

Linear warmup fraction of total training steps passed to SFTConfig. Defaults to 0.03 when None.

None
neftune_noise_alpha float | None

NEFTune noise alpha for embedding perturbation. When set, passed to SFTConfig(neftune_noise_alpha=...). When None (default), the kwarg is omitted so SFTConfig's own default (feature disabled) applies.

None
max_length int

SFT tokenizer truncation length. Caps activation memory; both the cross-entropy logits tensor and (with attn_implementation="eager") the materialised attention matrix scale with this value. Defaults to 2048.

2048

Returns:

Type Description
str

output_dir path where the adapter was saved.

Raises:

Type Description
FileNotFoundError

If the trajectory file does not exist.

ValueError

If the trajectory is not successful or has no SFT messages.

Source code in libs/model-training/src/model_training/trainer.py
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
def train_qlora(
    session_id: str | None,
    adapter_id: str,
    output_dir: str,
    *,
    base_model_id: str | None = None,
    task_type: str = "code-gen",
    rank: int | None = None,
    alpha: int | None = None,
    epochs: int | None = None,
    learning_rate: float = 2e-4,
    model_config_name: str | None = None,
    warm_start_adapter_id: str | None = None,
    gradient_accumulation_steps: int | None = None,
    lr_scheduler_type: str | None = None,
    mlflow_experiment: str = "rune-qlora",
    mlflow_tracking_uri: str | None = None,
    dataset_path: str | None = None,
    encoding_mode: str = "multi_turn",
    diff_aware_loss: bool = False,
    diff_changed_weight: float = 1.0,
    diff_unchanged_weight: float = 0.3,
    override_lora_alpha: int | None = None,
    override_lora_dropout: float | None = None,
    warmup_ratio: float | None = None,
    neftune_noise_alpha: float | None = None,
    max_length: int = 2048,
) -> str:
    """Train a QLoRA adapter from a recorded coding trajectory.

    Orchestrates the full training pipeline: load trajectory, format as SFT
    messages, build dataset, load model with NF4 quantization, train with SFT,
    and save the adapter to output_dir.

    When model_config_name is provided, training defaults (rank, alpha, LR
    schedule, gradient accumulation, attention implementation) are loaded from
    the model registry. When the registry config specifies a warm_start_adapter_id,
    the pre-trained adapter is loaded via PeftModel.from_pretrained and training
    continues from those weights instead of initializing fresh LoRA matrices.

    All GPU imports are deferred to this function body; the module is safe to
    import in CPU-only environments.

    Args:
        session_id: Trajectory session ID to train from. Mutually exclusive
            with dataset_path.
        adapter_id: Unique identifier for the resulting adapter.
        output_dir: Directory to save the trained adapter weights.
        base_model_id: HuggingFace model ID. Overrides registry default.
        task_type: Task category (e.g. 'code-gen', 'bug-fix').
        rank: LoRA rank. Defaults to registry value or 64.
        alpha: LoRA alpha scaling factor. Defaults to registry value or 128.
        epochs: Number of training epochs. Defaults to registry value or 3.
        learning_rate: Optimizer learning rate.
        model_config_name: Registry lookup key (e.g. "qwen3.5-9b"). When set,
            populates defaults from the model registry.
        warm_start_adapter_id: Pre-trained PEFT adapter to continue from.
            Overrides the registry's warm_start_adapter_id.
        gradient_accumulation_steps: Gradient accumulation steps. Defaults to
            registry value or 16.
        lr_scheduler_type: LR scheduler type. Defaults to registry value or
            "constant".
        mlflow_experiment: MLflow experiment name. Set RUNE_DISABLE_MLFLOW=1
            in the env to disable MLflow tracking entirely.
        mlflow_tracking_uri: Optional MLflow tracking URI override. Falls back
            to the MLFLOW_TRACKING_URI env var, then to
            ``"sqlite:///./mlflow.db"``.
        dataset_path: Path to a JSONL file of mined pair records (as produced
            by ``scripts/mine_github.py --batch``). Mutually exclusive with
            session_id; when set, the training dataset is built by
            ``pairs_to_chat_messages`` instead of ``format_for_sft``.
        encoding_mode: ``"multi_turn"`` clusters pairs by source task and
            emits one conversation per task; ``"single_turn"`` emits one
            conversation per pair. Only used when ``dataset_path`` is set.
        diff_aware_loss: When True, wrap the SFT collator with
            ``DiffWeightedDataCollator`` and swap in ``DiffAwareSFTTrainer``
            so per-token loss is scaled by the diff between assistant
            output and the masked user/context span. Disables
            ``assistant_only_loss`` on SFTConfig since the custom collator
            provides equivalent (stricter) masking.
        diff_changed_weight: Per-token weight applied to assistant tokens
            absent from the masked context span. Only used when
            ``diff_aware_loss=True``. Defaults to ``1.0``.
        diff_unchanged_weight: Per-token weight applied to assistant
            tokens also present in the masked context span. Only used
            when ``diff_aware_loss=True``. Defaults to ``0.3``.
        override_lora_alpha: Post-load override for the warm-start
            adapter's effective alpha. Applied via a module-tree walk
            after ``PeftModel.from_pretrained`` since PEFT caches
            ``scaling = alpha / r`` per layer. Has no effect when no
            warm-start is in use.
        override_lora_dropout: Post-load override for the warm-start
            adapter's LoRA dropout probability. Applied the same way as
            ``override_lora_alpha`` — by walking the module tree and
            mutating each layer's ``lora_dropout[adapter_name].p``.
        warmup_ratio: Linear warmup fraction of total training steps passed
            to ``SFTConfig``. Defaults to ``0.03`` when ``None``.
        neftune_noise_alpha: NEFTune noise alpha for embedding perturbation.
            When set, passed to ``SFTConfig(neftune_noise_alpha=...)``.
            When ``None`` (default), the kwarg is omitted so SFTConfig's
            own default (feature disabled) applies.
        max_length: SFT tokenizer truncation length. Caps activation
            memory; both the cross-entropy logits tensor and (with
            ``attn_implementation="eager"``) the materialised attention
            matrix scale with this value. Defaults to ``2048``.

    Returns:
        output_dir path where the adapter was saved.

    Raises:
        FileNotFoundError: If the trajectory file does not exist.
        ValueError: If the trajectory is not successful or has no SFT messages.
    """
    # Validate mutually-exclusive data sources up front (no GPU imports yet).
    _validate_data_source(session_id, dataset_path, encoding_mode)

    # Cosmetic third-party warnings that don't affect correctness.
    _silence_known_warnings()

    # Reduce CUDA fragmentation overhead on the L4 (22 GB) — set BEFORE the
    # first torch import so the allocator picks it up. Only sets the var when
    # the user hasn't already configured PYTORCH_CUDA_ALLOC_CONF themselves.
    os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")

    # Deferred GPU imports — all in function body for CPU-only importability
    import torch  # noqa: F401 — needed for _build_bnb_config's bfloat16 dtype
    from datasets import Dataset
    from transformers import AutoModelForCausalLM, AutoTokenizer
    from trl import SFTConfig, SFTTrainer

    # Resolve defaults from model registry and explicit overrides
    params = _resolve_training_params(
        model_config_name=model_config_name,
        base_model_id=base_model_id,
        warm_start_adapter_id=warm_start_adapter_id,
        rank=rank,
        alpha=alpha,
        epochs=epochs,
        gradient_accumulation_steps=gradient_accumulation_steps,
        lr_scheduler_type=lr_scheduler_type,
    )
    warm_start = params["warm_start"]
    resolved_rank = params["rank"]
    resolved_alpha = params["alpha"]
    resolved_epochs = params["epochs"]
    resolved_grad_accum = params["grad_accum"]
    resolved_lr_sched = params["lr_sched"]
    attn_impl = params["attn_impl"]

    # Resolve model ID — read env var inside function body for monkeypatch testability
    resolved_model_id = params["base_model_id"]
    model_id: str = resolved_model_id or os.environ.get(
        "RUNE_BASE_MODEL", "Qwen/Qwen3.5-9B"
    )  # type: ignore[assignment]

    # Build dataset from either a mined-pairs JSONL or a recorded trajectory.
    dataset = _build_training_dataset(
        dataset_cls=Dataset,
        session_id=session_id,
        dataset_path=dataset_path,
        encoding_mode=encoding_mode,
        diff_aware_loss=diff_aware_loss,
    )

    # NF4 quantization config (bfloat16 compute dtype prevents silent NaN loss).
    # _build_bnb_config also enables llm_int8_enable_fp32_cpu_offload so
    # accelerate degrades gracefully when VRAM is tight (RCA-4 (b)).
    bnb_config = _build_bnb_config()

    # Load model and tokenizer (or reuse the cached base when
    # RUNE_PERSIST_BASE_MODEL=1; see _get_or_load_base).
    model, tokenizer = _get_or_load_base(
        model_id,
        bnb_config=bnb_config,
        attn_impl=attn_impl,
        auto_model_cls=AutoModelForCausalLM,
        auto_tokenizer_cls=AutoTokenizer,
    )

    if diff_aware_loss:
        # The diff path needs assistant_masks (for label masking via the
        # inner DataCollatorForLanguageModeling) AND pre_code/post_code
        # (for DiffWeightedDataCollator.hunk_path). Preserve the latter
        # so we do not regress to RCA-5 H2 (zero gradient) or to identity
        # weights (loss collapses to mean CE on assistant tokens only,
        # ignoring hunks — still functional but defeats the purpose).
        dataset = _attach_assistant_masks(
            dataset, tokenizer, preserve_columns=["pre_code", "post_code"]
        )
    else:
        dataset = _attach_assistant_masks(dataset, tokenizer)

    model, lora_config = _setup_lora_adapter(
        model=model,
        warm_start=warm_start,
        model_config_name=model_config_name,
        resolved_rank=resolved_rank,
        resolved_alpha=resolved_alpha,
        override_lora_alpha=override_lora_alpha,
        override_lora_dropout=override_lora_dropout,
    )

    # Configure MLflow (silent no-op when disabled via env or mlflow missing)
    mlflow_enabled = setup_mlflow(
        experiment_name=mlflow_experiment, tracking_uri=mlflow_tracking_uri
    )
    report_to = "mlflow" if mlflow_enabled else "none"

    # Training arguments. When diff_aware_loss is on, our custom collator
    # subsumes the assistant-only masking, so we disable SFTConfig's
    # own flag to avoid double-masking.
    training_args = _build_sft_config(
        sft_config_cls=SFTConfig,
        output_dir=output_dir,
        resolved_epochs=resolved_epochs,
        learning_rate=learning_rate,
        warmup_ratio=warmup_ratio,
        resolved_lr_sched=resolved_lr_sched,
        resolved_grad_accum=resolved_grad_accum,
        report_to=report_to,
        diff_aware_loss=diff_aware_loss,
        neftune_noise_alpha=neftune_noise_alpha,
        max_length=max_length,
        dataset_size=len(dataset),
    )

    trainer = _construct_sft_trainer(
        sft_trainer_cls=SFTTrainer,
        model=model,
        args=training_args,
        dataset=dataset,
        tokenizer=tokenizer,
        lora_config=lora_config,
        diff_aware_loss=diff_aware_loss,
        diff_changed_weight=diff_changed_weight,
        diff_unchanged_weight=diff_unchanged_weight,
    )

    # Log training-run metadata (params streamed as per-step metrics by TRL's
    # MLflow reporter via training_args.report_to="mlflow"). When disabled,
    # contextlib.nullcontext is a zero-cost placeholder.
    # Mirrors the schedule math in _build_sft_config. Kept inline rather than
    # refactoring _build_sft_config to return a tuple (that would silently
    # break train_qlora if the call site forgot to unpack — CPU-only tests
    # don't exercise that call path).
    _ds_size = len(dataset)
    _steps_per_epoch = max(1, math.ceil(_ds_size / max(1, resolved_grad_accum)))
    _total_steps_for_log: int | None = (
        max(1, resolved_epochs * _steps_per_epoch) if _ds_size > 0 else None
    )
    run_params = _build_run_params(
        model_id=model_id,
        warm_start=warm_start,
        resolved_rank=resolved_rank,
        resolved_alpha=resolved_alpha,
        resolved_epochs=resolved_epochs,
        learning_rate=learning_rate,
        resolved_grad_accum=resolved_grad_accum,
        resolved_lr_sched=resolved_lr_sched,
        attn_impl=attn_impl,
        dataset_size=len(dataset),
        diff_aware_loss=diff_aware_loss,
        task_type=task_type,
        adapter_id=adapter_id,
        session_id=session_id,
        dataset_path=dataset_path,
        encoding_mode=encoding_mode,
        diff_changed_weight=diff_changed_weight,
        diff_unchanged_weight=diff_unchanged_weight,
        override_lora_alpha=override_lora_alpha,
        override_lora_dropout=override_lora_dropout,
        neftune_noise_alpha=neftune_noise_alpha,
        total_steps=_total_steps_for_log,
    )
    with mlflow_run(
        enabled=mlflow_enabled,
        run_name=f"{adapter_id}-r{resolved_rank}-lr{learning_rate:.1e}",
        params=run_params,
    ):
        trainer.train()

        # Save adapter weights ONCE with save_embedding_layers=False so PEFT
        # skips its hub-probe (which returns None under HF_HUB_OFFLINE=1 and
        # emits the cosmetic "Could not find a config file" warning — RCA-1).
        # Our LoRA never resizes embeddings, so the assumption is correct.
        # We bypass trainer.save_model (which would call save_pretrained with
        # default kwargs) and call save_pretrained directly to avoid the
        # double-write race the reviewer flagged.
        try:
            from peft import PeftModel  # noqa: PLC0415

            inner = getattr(trainer, "model", None)
            if isinstance(inner, PeftModel):
                inner.save_pretrained(output_dir, save_embedding_layers=False)
            else:
                # Non-PEFT path (shouldn't fire in QLoRA but stays correct).
                trainer.save_model(output_dir)
        except Exception:  # noqa: BLE001 — fall back to default save path
            logger.exception(
                "PeftModel.save_pretrained failed; falling back to "
                "trainer.save_model (Qwen config warning may resurface)"
            )
            trainer.save_model(output_dir)

        if mlflow_enabled:
            mlflow_log_output_artifacts(output_dir)

    # Release VRAM before any subsequent allocation in the caller (e.g. the
    # HPO heldout-eval at run_training_hpo.py:_evaluate_adapter_on_heldout
    # will load adapter weights and run forward passes; without this drop
    # the trainer's optimizer + dataset cache co-resides with the eval
    # state and pushes the L4 close to OOM). Persistent-base mode keeps the
    # cached base model resident — only the trial-scoped objects are freed.
    _release_trial_state(trainer, model, dataset, persist_base=_persist_base_enabled())

    return output_dir
train_and_register
train_and_register(
    session_id: str | None,
    adapter_id: str,
    *,
    base_model_id: str | None = None,
    task_type: str = "code-gen",
    rank: int | None = None,
    alpha: int | None = None,
    epochs: int | None = None,
    learning_rate: float = 0.0002,
    model_config_name: str | None = None,
    warm_start_adapter_id: str | None = None,
    gradient_accumulation_steps: int | None = None,
    lr_scheduler_type: str | None = None,
    database_url: str | None = None,
    mlflow_experiment: str = "rune-qlora",
    mlflow_tracking_uri: str | None = None,
    dataset_path: str | None = None,
    encoding_mode: str = "multi_turn",
    diff_aware_loss: bool = False,
    diff_changed_weight: float = 1.0,
    diff_unchanged_weight: float = 0.3,
    override_lora_alpha: int | None = None,
    override_lora_dropout: float | None = None,
    warmup_ratio: float | None = None,
    neftune_noise_alpha: float | None = None,
    max_length: int = 2048,
) -> str

Train a QLoRA adapter and register it in the AdapterRegistry.

Combines train_qlora() with AdapterRegistry.store() to produce a fully registered adapter ready for vLLM serving.

Parameters:

Name Type Description Default
session_id str | None

Trajectory session ID to train from.

required
adapter_id str

Unique identifier for the resulting adapter.

required
base_model_id str | None

HuggingFace model ID. Defaults to RUNE_BASE_MODEL env var.

None
task_type str

Task category (e.g. 'code-gen', 'bug-fix').

'code-gen'
rank int | None

LoRA rank. Defaults to registry value or 64.

None
alpha int | None

LoRA alpha scaling factor. Defaults to registry value or 128.

None
epochs int | None

Number of training epochs. Defaults to registry value or 3.

None
learning_rate float

Optimizer learning rate.

0.0002
model_config_name str | None

Registry lookup key (e.g. "qwen3.5-9b").

None
warm_start_adapter_id str | None

Pre-trained PEFT adapter to continue from.

None
gradient_accumulation_steps int | None

Gradient accumulation steps.

None
lr_scheduler_type str | None

LR scheduler type.

None
database_url str | None

SQLAlchemy database URL. Defaults to RUNE_DATABASE_URL env var or "sqlite:///{home}/.rune/rune.db".

None
mlflow_experiment str

MLflow experiment name. Set RUNE_DISABLE_MLFLOW=1 to skip MLflow tracking.

'rune-qlora'
mlflow_tracking_uri str | None

Optional MLflow tracking URI override.

None
dataset_path str | None

JSONL of mined pair records; mutually exclusive with session_id.

None
encoding_mode str

"multi_turn" or "single_turn" for pair→chat conversion.

'multi_turn'
diff_aware_loss bool

Enable diff-aware per-token loss weighting.

False
diff_changed_weight float

Weight for assistant tokens not in the masked context span when diff_aware_loss=True.

1.0
diff_unchanged_weight float

Weight for assistant tokens present in the masked context span when diff_aware_loss=True.

0.3
override_lora_alpha int | None

Post-load override for the warm-start adapter's effective alpha (module-tree walk).

None
override_lora_dropout float | None

Post-load override for the warm-start adapter's LoRA dropout probability.

None
warmup_ratio float | None

Linear warmup fraction forwarded to train_qlora. Defaults to 0.03 when None.

None
neftune_noise_alpha float | None

NEFTune noise alpha forwarded to train_qlora. When None (default), NEFTune is disabled.

None
max_length int

SFT tokenizer truncation length forwarded to train_qlora. Defaults to 2048.

2048

Returns:

Type Description
str

adapter_id of the registered adapter.

Raises:

Type Description
FileNotFoundError

If the trajectory file does not exist.

ValueError

If the trajectory is not successful or has no SFT messages.

Source code in libs/model-training/src/model_training/trainer.py
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
def train_and_register(
    session_id: str | None,
    adapter_id: str,
    *,
    base_model_id: str | None = None,
    task_type: str = "code-gen",
    rank: int | None = None,
    alpha: int | None = None,
    epochs: int | None = None,
    learning_rate: float = 2e-4,
    model_config_name: str | None = None,
    warm_start_adapter_id: str | None = None,
    gradient_accumulation_steps: int | None = None,
    lr_scheduler_type: str | None = None,
    database_url: str | None = None,
    mlflow_experiment: str = "rune-qlora",
    mlflow_tracking_uri: str | None = None,
    dataset_path: str | None = None,
    encoding_mode: str = "multi_turn",
    diff_aware_loss: bool = False,
    diff_changed_weight: float = 1.0,
    diff_unchanged_weight: float = 0.3,
    override_lora_alpha: int | None = None,
    override_lora_dropout: float | None = None,
    warmup_ratio: float | None = None,
    neftune_noise_alpha: float | None = None,
    max_length: int = 2048,
) -> str:
    """Train a QLoRA adapter and register it in the AdapterRegistry.

    Combines train_qlora() with AdapterRegistry.store() to produce a fully
    registered adapter ready for vLLM serving.

    Args:
        session_id: Trajectory session ID to train from.
        adapter_id: Unique identifier for the resulting adapter.
        base_model_id: HuggingFace model ID. Defaults to RUNE_BASE_MODEL env var.
        task_type: Task category (e.g. 'code-gen', 'bug-fix').
        rank: LoRA rank. Defaults to registry value or 64.
        alpha: LoRA alpha scaling factor. Defaults to registry value or 128.
        epochs: Number of training epochs. Defaults to registry value or 3.
        learning_rate: Optimizer learning rate.
        model_config_name: Registry lookup key (e.g. "qwen3.5-9b").
        warm_start_adapter_id: Pre-trained PEFT adapter to continue from.
        gradient_accumulation_steps: Gradient accumulation steps.
        lr_scheduler_type: LR scheduler type.
        database_url: SQLAlchemy database URL. Defaults to RUNE_DATABASE_URL env var
            or "sqlite:///{home}/.rune/rune.db".
        mlflow_experiment: MLflow experiment name. Set RUNE_DISABLE_MLFLOW=1 to
            skip MLflow tracking.
        mlflow_tracking_uri: Optional MLflow tracking URI override.
        dataset_path: JSONL of mined pair records; mutually exclusive with
            session_id.
        encoding_mode: ``"multi_turn"`` or ``"single_turn"`` for pair→chat
            conversion.
        diff_aware_loss: Enable diff-aware per-token loss weighting.
        diff_changed_weight: Weight for assistant tokens not in the masked
            context span when ``diff_aware_loss=True``.
        diff_unchanged_weight: Weight for assistant tokens present in the
            masked context span when ``diff_aware_loss=True``.
        override_lora_alpha: Post-load override for the warm-start
            adapter's effective alpha (module-tree walk).
        override_lora_dropout: Post-load override for the warm-start
            adapter's LoRA dropout probability.
        warmup_ratio: Linear warmup fraction forwarded to ``train_qlora``.
            Defaults to ``0.03`` when ``None``.
        neftune_noise_alpha: NEFTune noise alpha forwarded to ``train_qlora``.
            When ``None`` (default), NEFTune is disabled.
        max_length: SFT tokenizer truncation length forwarded to
            ``train_qlora``. Defaults to ``2048``.

    Returns:
        adapter_id of the registered adapter.

    Raises:
        FileNotFoundError: If the trajectory file does not exist.
        ValueError: If the trajectory is not successful or has no SFT messages.
    """
    from adapter_registry.models import AdapterRecord
    from adapter_registry.registry import AdapterRegistry
    from sqlalchemy import create_engine

    # Resolve adapter output dir — read env var inside function body
    adapter_base = os.environ.get("RUNE_ADAPTER_DIR")
    if adapter_base:
        adapter_dir = Path(adapter_base) / adapter_id
    else:
        adapter_dir = Path.home() / ".rune" / "adapters" / adapter_id
    adapter_dir.mkdir(parents=True, exist_ok=True)

    # Resolve model ID inside function body for testability
    model_id = base_model_id
    if model_id is None and model_config_name:
        from model_training.model_configs import ModelRegistry

        model_id = ModelRegistry.default().get(model_config_name).model_id
    if model_id is None:
        model_id = os.environ.get("RUNE_BASE_MODEL", "Qwen/Qwen3.5-9B")

    # Resolve training params to get the actual rank used for training
    resolved = _resolve_training_params(
        model_config_name=model_config_name,
        base_model_id=base_model_id,
        warm_start_adapter_id=warm_start_adapter_id,
        rank=rank,
        alpha=alpha,
        epochs=epochs,
        gradient_accumulation_steps=gradient_accumulation_steps,
        lr_scheduler_type=lr_scheduler_type,
    )

    output_dir = str(adapter_dir)
    train_qlora(
        session_id=session_id,
        adapter_id=adapter_id,
        output_dir=output_dir,
        base_model_id=model_id,
        task_type=task_type,
        rank=rank,
        alpha=alpha,
        epochs=epochs,
        learning_rate=learning_rate,
        model_config_name=model_config_name,
        warm_start_adapter_id=warm_start_adapter_id,
        gradient_accumulation_steps=gradient_accumulation_steps,
        lr_scheduler_type=lr_scheduler_type,
        mlflow_experiment=mlflow_experiment,
        mlflow_tracking_uri=mlflow_tracking_uri,
        dataset_path=dataset_path,
        encoding_mode=encoding_mode,
        diff_aware_loss=diff_aware_loss,
        diff_changed_weight=diff_changed_weight,
        diff_unchanged_weight=diff_unchanged_weight,
        override_lora_alpha=override_lora_alpha,
        override_lora_dropout=override_lora_dropout,
        warmup_ratio=warmup_ratio,
        neftune_noise_alpha=neftune_noise_alpha,
        max_length=max_length,
    )

    # Compute file hash and size from the saved safetensors file
    adapter_file = adapter_dir / "adapter_model.safetensors"
    file_hash = hashlib.sha256(adapter_file.read_bytes()).hexdigest()
    file_size_bytes = adapter_file.stat().st_size

    # Build the adapter record with the registry-resolved rank
    record = AdapterRecord(
        id=adapter_id,
        version=1,
        task_type=task_type,
        base_model_id=model_id,
        rank=resolved["rank"],
        created_at=datetime.now(tz=timezone.utc).isoformat(),
        file_path=output_dir,
        file_hash=file_hash,
        file_size_bytes=file_size_bytes,
        source="qlora",
        session_id=session_id,
    )

    # Resolve DB URL inside function body for testability
    db_url = database_url or os.environ.get(
        "RUNE_DATABASE_URL",
        f"sqlite:///{Path.home() / '.rune' / 'rune.db'}",
    )
    engine = create_engine(db_url)
    registry = AdapterRegistry(engine=engine)
    registry.store(record)

    return adapter_id

trainer_cli

Command-line entrypoint for QLoRA fine-tuning.

Invoked by scripts/train.sh so the shell wrapper stays thin. Accepts all flags that map 1:1 to train_and_register kwargs and exposes a --dry-run mode that resolves arguments and prints them as JSON without loading any GPU libraries, to support CI validation.

All heavy imports (torch, transformers, peft, trl) are deferred to the call site inside train_and_register — this CLI itself is CPU-safe.

Usage

uv run python -m model_training.trainer_cli \ --dataset data/pairs/repo.jsonl \ --adapter-id my-adapter \ --model qwen3.5-9b \ --warm-start deltacoder \ --dry-run

Functions
main
main(argv: list[str] | None = None) -> int

Parse argv, dispatch to train_and_register (or dry-run and exit).

Parameters:

Name Type Description Default
argv list[str] | None

Argument list to parse. Defaults to sys.argv[1:] when None.

None

Returns:

Type Description
int

Exit code: 0 on success.

Raises:

Type Description
SystemExit

Raised by argparse on invalid arguments or --help.

Source code in libs/model-training/src/model_training/trainer_cli.py
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
def main(argv: list[str] | None = None) -> int:
    """Parse argv, dispatch to train_and_register (or dry-run and exit).

    Args:
        argv: Argument list to parse. Defaults to ``sys.argv[1:]`` when
            ``None``.

    Returns:
        Exit code: 0 on success.

    Raises:
        SystemExit: Raised by argparse on invalid arguments or ``--help``.
    """
    parser = _build_parser()
    args = parser.parse_args(argv)
    kwargs = _resolve_kwargs(args)

    if args.dry_run:
        print(json.dumps(kwargs, indent=2, sort_keys=True))
        return 0

    # Deferred to keep --dry-run CPU-only.
    from model_training.trainer import train_and_register  # noqa: PLC0415

    train_and_register(**kwargs)
    return 0

training_common

Shared MLflow helpers for model-training modules.

All MLflow imports are deferred inside function bodies to ensure CPU-only importability (INFRA-05). Module-level imports: stdlib only.

Functions
setup_mlflow
setup_mlflow(
    experiment_name: str, tracking_uri: str | None
) -> bool

Configure MLflow for training runs.

Returns True when MLflow is usable and configured; False when tracking should be skipped. Skipping happens when RUNE_DISABLE_MLFLOW=1 is set in the environment, or when mlflow itself is not importable.

Tracking URI precedence: explicit tracking_uri arg, then the MLFLOW_TRACKING_URI env var, then http://localhost:5000 (the in-pod MLflow server started by infra/docker-compose.yml). The sqlite/filesystem backends were dropped from the default path because they cannot be replicated to S3 by Litestream when multiple processes open the file concurrently.

Parameters:

Name Type Description Default
experiment_name str

MLflow experiment name to activate.

required
tracking_uri str | None

Optional explicit tracking URI override.

required

Returns:

Type Description
bool

True if MLflow is active and configured, False otherwise.

Source code in libs/model-training/src/model_training/training_common.py
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
def setup_mlflow(experiment_name: str, tracking_uri: str | None) -> bool:
    """Configure MLflow for training runs.

    Returns True when MLflow is usable and configured; False when tracking
    should be skipped. Skipping happens when RUNE_DISABLE_MLFLOW=1 is set
    in the environment, or when mlflow itself is not importable.

    Tracking URI precedence: explicit ``tracking_uri`` arg, then the
    ``MLFLOW_TRACKING_URI`` env var, then ``http://localhost:5000`` (the
    in-pod MLflow server started by ``infra/docker-compose.yml``). The
    sqlite/filesystem backends were dropped from the default path because
    they cannot be replicated to S3 by Litestream when multiple processes
    open the file concurrently.

    Args:
        experiment_name: MLflow experiment name to activate.
        tracking_uri: Optional explicit tracking URI override.

    Returns:
        True if MLflow is active and configured, False otherwise.
    """
    if os.environ.get("RUNE_DISABLE_MLFLOW") == "1":
        return False
    try:
        import mlflow  # noqa: PLC0415
    except ImportError:
        return False

    # If a parent harness (e.g. the HPO wrapper at run_training_hpo.py:701)
    # already started a run, respect the URI it was started against.
    # Re-setting the tracking URI here would orphan that run because MLflow
    # binds run-ids to a backend at start time — the run would still be
    # 'active' in the client but the backend lookup would fail with
    # 'Run with id=... not found'.
    active = mlflow.active_run()
    if active is not None:
        logger.info(
            "MLflow already active under run_id=%s uri=%s; reusing",
            active.info.run_id,
            mlflow.get_tracking_uri(),
        )
        return True

    uri = tracking_uri or os.environ.get("MLFLOW_TRACKING_URI", "http://localhost:5000")
    mlflow.set_tracking_uri(uri)
    mlflow.set_experiment(experiment_name)
    logger.info("MLflow enabled: tracking_uri=%s experiment=%s", uri, experiment_name)
    return True
mlflow_log_params
mlflow_log_params(params: dict[str, Any]) -> None

Log a dict of params to the active MLflow run. Silent no-op on failure.

All exceptions are caught and logged at DEBUG level so that MLflow unavailability never interrupts training.

Parameters:

Name Type Description Default
params dict[str, Any]

Mapping of parameter names to values forwarded verbatim to mlflow.log_params.

required

Returns:

Type Description
None

None.

Raises:

Type Description
None

All exceptions from mlflow.log_params are caught and logged at DEBUG level; MLflow unavailability never interrupts training.

Source code in libs/model-training/src/model_training/training_common.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
def mlflow_log_params(params: dict[str, Any]) -> None:
    """Log a dict of params to the active MLflow run. Silent no-op on failure.

    All exceptions are caught and logged at DEBUG level so that MLflow
    unavailability never interrupts training.

    Args:
        params: Mapping of parameter names to values forwarded verbatim to
            ``mlflow.log_params``.

    Returns:
        None.

    Raises:
        None: All exceptions from ``mlflow.log_params`` are caught and
            logged at DEBUG level; MLflow unavailability never interrupts
            training.
    """
    try:
        import mlflow  # noqa: PLC0415

        mlflow.log_params(params)
    except Exception:  # noqa: BLE001 — logging must never break training
        logger.debug("mlflow.log_params skipped", exc_info=True)
mlflow_log_artifact
mlflow_log_artifact(path: str) -> None

Log a file artifact to the active MLflow run. Silent no-op on failure.

Source code in libs/model-training/src/model_training/training_common.py
 95
 96
 97
 98
 99
100
101
102
def mlflow_log_artifact(path: str) -> None:
    """Log a file artifact to the active MLflow run. Silent no-op on failure."""
    try:
        import mlflow  # noqa: PLC0415

        mlflow.log_artifact(path)
    except Exception:  # noqa: BLE001
        logger.debug("mlflow.log_artifact skipped for %s", path, exc_info=True)
mlflow_log_output_artifacts
mlflow_log_output_artifacts(output_dir: str) -> None

Log the saved adapter's safetensors + config.json to MLflow, if present.

Source code in libs/model-training/src/model_training/training_common.py
105
106
107
108
109
110
111
112
def mlflow_log_output_artifacts(output_dir: str) -> None:
    """Log the saved adapter's safetensors + config.json to MLflow, if present."""
    adapter_safetensors = Path(output_dir) / "adapter_model.safetensors"
    adapter_config = Path(output_dir) / "adapter_config.json"
    if adapter_safetensors.exists():
        mlflow_log_artifact(str(adapter_safetensors))
    if adapter_config.exists():
        mlflow_log_artifact(str(adapter_config))
mlflow_run
mlflow_run(
    *, enabled: bool, run_name: str, params: dict[str, Any]
) -> Iterator[None]

Context manager that starts an MLflow run when enabled, else no-ops.

When enabled, logs params at entry and ensures mlflow.end_run() on exit even if training raises. When disabled, the body runs unchanged.

If an MLflow run is already active in the current thread (e.g. the HPO harness opened one to attach study-level tags), attach params to it instead of starting a new run — MLflow permits only one top-level run per thread, and forcing a nested run here would hide trainer metrics inside an extra layer the caller didn't ask for.

Parameters:

Name Type Description Default
enabled bool

Whether MLflow tracking is active for this run.

required
run_name str

Display name for the MLflow run.

required
params dict[str, Any]

Parameter dict to log at run start.

required
Source code in libs/model-training/src/model_training/training_common.py
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
@contextmanager
def mlflow_run(
    *, enabled: bool, run_name: str, params: dict[str, Any]
) -> Iterator[None]:
    """Context manager that starts an MLflow run when enabled, else no-ops.

    When enabled, logs ``params`` at entry and ensures ``mlflow.end_run()`` on
    exit even if training raises. When disabled, the body runs unchanged.

    If an MLflow run is already active in the current thread (e.g. the HPO
    harness opened one to attach study-level tags), attach params to it
    instead of starting a new run — MLflow permits only one top-level run
    per thread, and forcing a nested run here would hide trainer metrics
    inside an extra layer the caller didn't ask for.

    Args:
        enabled: Whether MLflow tracking is active for this run.
        run_name: Display name for the MLflow run.
        params: Parameter dict to log at run start.
    """
    if not enabled:
        yield
        return
    import mlflow  # noqa: PLC0415

    # Respect an already-active run: the caller owns it and is responsible
    # for closing it. We just decorate it with params.
    if mlflow.active_run() is not None:
        mlflow_log_params(params)
        yield
        return

    mlflow.start_run(run_name=run_name)
    try:
        mlflow_log_params(params)
        yield
    finally:
        mlflow.end_run()

trajectory

Trajectory recording and formatting for coding session distillation.

Provides functions to persist, load, and convert coding session trajectories into SFT-compatible chat format for LoRA fine-tuning pipelines.

Functions
record_trajectory
record_trajectory(
    session_id: str,
    steps: list[dict[str, Any]],
    outcome: Optional[str] = None,
    *,
    task_description: str = "",
    task_type: str = "",
    adapter_ids: list[str] | None = None,
) -> dict[str, Any]

Persist a coding session trajectory to disk for future distillation.

Parameters:

Name Type Description Default
session_id str

Unique identifier for the coding session.

required
steps list[dict[str, Any]]

List of step dicts, each containing attempt results.

required
outcome Optional[str]

Final session result ('success', 'exhausted', or None).

None
task_description str

Natural language description of the coding task.

''
task_type str

Category of task (e.g. 'function', 'class', 'refactor').

''
adapter_ids list[str] | None

LoRA adapter IDs used during the session.

None

Returns:

Type Description
dict[str, Any]

A dict with 'session_id' and 'file_path' keys.

Source code in libs/model-training/src/model_training/trajectory.py
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
def record_trajectory(
    session_id: str,
    steps: list[dict[str, Any]],
    outcome: Optional[str] = None,
    *,
    task_description: str = "",
    task_type: str = "",
    adapter_ids: list[str] | None = None,
) -> dict[str, Any]:
    """Persist a coding session trajectory to disk for future distillation.

    Args:
        session_id: Unique identifier for the coding session.
        steps: List of step dicts, each containing attempt results.
        outcome: Final session result ('success', 'exhausted', or None).
        task_description: Natural language description of the coding task.
        task_type: Category of task (e.g. 'function', 'class', 'refactor').
        adapter_ids: LoRA adapter IDs used during the session.

    Returns:
        A dict with 'session_id' and 'file_path' keys.
    """
    trajectory_dir = _get_trajectory_dir()
    trajectory_dir.mkdir(parents=True, exist_ok=True)

    file_path = trajectory_dir / f"{session_id}.json"
    timestamp = datetime.now(tz=timezone.utc).isoformat()

    trajectory: dict[str, Any] = {
        "session_id": session_id,
        "task_description": task_description,
        "task_type": task_type,
        "adapter_ids": adapter_ids if adapter_ids is not None else [],
        "outcome": outcome,
        "timestamp": timestamp,
        "steps": steps,
    }

    file_path.write_text(json.dumps(trajectory, indent=2))

    return {"session_id": session_id, "file_path": str(file_path)}
load_trajectory
load_trajectory(trajectory_id: str) -> dict[str, Any]

Load a stored trajectory by session ID.

Parameters:

Name Type Description Default
trajectory_id str

The session ID used as the filename (without .json).

required

Returns:

Type Description
dict[str, Any]

A dict containing the full trajectory data including steps and metadata.

Raises:

Type Description
FileNotFoundError

If no trajectory file exists for the given ID.

Source code in libs/model-training/src/model_training/trajectory.py
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def load_trajectory(trajectory_id: str) -> dict[str, Any]:
    """Load a stored trajectory by session ID.

    Args:
        trajectory_id: The session ID used as the filename (without .json).

    Returns:
        A dict containing the full trajectory data including steps and metadata.

    Raises:
        FileNotFoundError: If no trajectory file exists for the given ID.
    """
    trajectory_dir = _get_trajectory_dir()
    file_path = trajectory_dir / f"{trajectory_id}.json"
    # Let FileNotFoundError propagate naturally if file does not exist
    return json.loads(file_path.read_text())  # type: ignore[no-any-return]
format_for_sft
format_for_sft(
    trajectory: dict[str, Any],
) -> list[dict[str, str]]

Convert a trajectory into SFT-compatible chat format.

Only successful trajectories (outcome == 'success') produce output. Extracts the final step where tests_passed is True as the assistant message.

Parameters:

Name Type Description Default
trajectory dict[str, Any]

A trajectory dict as returned by load_trajectory.

required

Returns:

Type Description
list[dict[str, str]]

A list of 3 message dicts ([system, user, assistant]) for successful

list[dict[str, str]]

trajectories, or an empty list if the trajectory did not succeed.

Source code in libs/model-training/src/model_training/trajectory.py
 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
def format_for_sft(trajectory: dict[str, Any]) -> list[dict[str, str]]:
    """Convert a trajectory into SFT-compatible chat format.

    Only successful trajectories (outcome == 'success') produce output.
    Extracts the final step where tests_passed is True as the assistant message.

    Args:
        trajectory: A trajectory dict as returned by load_trajectory.

    Returns:
        A list of 3 message dicts ([system, user, assistant]) for successful
        trajectories, or an empty list if the trajectory did not succeed.
    """
    if trajectory.get("outcome") != "success":
        return []

    steps: list[dict[str, Any]] = trajectory.get("steps", [])
    successful_step = next(
        (s for s in reversed(steps) if s.get("tests_passed")),
        None,
    )

    if successful_step is None:
        return []

    task_description: str = trajectory.get("task_description", "")
    generated_code: str = successful_step.get("generated_code", "")

    return [
        {"role": "system", "content": SYSTEM_PROMPT},
        {"role": "user", "content": task_description},
        {"role": "assistant", "content": generated_code},
    ]
compute_assistant_masks
compute_assistant_masks(
    tokenizer: Any, messages: list[dict[str, str]]
) -> dict[str, list[int]]

Tokenize a chat conversation and emit a 0/1 mask over assistant tokens.

Used when the tokenizer's chat template lacks {% generation %} markers (Qwen3.5-9B as of TRL 1.3.0), so TRL's return_assistant_tokens_mask=True path raises ValueError from get_training_chat_template. We bypass that path by pre-tokenizing here and providing input_ids + assistant_masks directly to SFTTrainer; _prepare_dataset short- circuits all preprocessing when input_ids is already present (sft_trainer.py:1067) and DataCollatorForLanguageModeling.torch_call consumes assistant_masks from the batch (sft_trainer.py:179-180).

Approach (Qwen-family marker scan): tokenize once and walk the token stream looking for <|im_start|>{assistant_role_token} boundaries that close at <|im_end|>. Marks the whole assistant turn — role+wrapper+content+thinking-blocks, since training the model to reproduce its own thinking is desirable. This avoids the prefix-of- full invariant failure that bites stateful templates: Qwen3.5 injects <think> markers only on the trailing assistant turn, so incremental prefix tokenization breaks. Marker scan reads only the final, ground-truth tokenization and is therefore stable.

Parameters:

Name Type Description Default
tokenizer Any

A HuggingFace tokenizer that uses <|im_start|> / <|im_end|> role markers (Qwen and ChatML-family).

required
messages list[dict[str, str]]

A list of {"role", "content"} dicts.

required

Returns:

Type Description
dict[str, list[int]]

{"input_ids": [...], "assistant_masks": [...]} with both lists

dict[str, list[int]]

the same length. assistant_masks has at least one 1 when

dict[str, list[int]]

any message has role == "assistant".

Raises:

Type Description
ValueError

If the tokenizer doesn't expose <|im_start|> / <|im_end|> token IDs — the marker-scan algorithm depends on them.

Source code in libs/model-training/src/model_training/trajectory.py
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
def compute_assistant_masks(
    tokenizer: Any, messages: list[dict[str, str]]
) -> dict[str, list[int]]:
    r"""Tokenize a chat conversation and emit a 0/1 mask over assistant tokens.

    Used when the tokenizer's chat template lacks ``{% generation %}`` markers
    (Qwen3.5-9B as of TRL 1.3.0), so TRL's ``return_assistant_tokens_mask=True``
    path raises ``ValueError`` from ``get_training_chat_template``. We bypass
    that path by pre-tokenizing here and providing ``input_ids`` +
    ``assistant_masks`` directly to SFTTrainer; ``_prepare_dataset`` short-
    circuits all preprocessing when ``input_ids`` is already present
    (sft_trainer.py:1067) and ``DataCollatorForLanguageModeling.torch_call``
    consumes ``assistant_masks`` from the batch (sft_trainer.py:179-180).

    Approach (Qwen-family marker scan): tokenize once and walk the token
    stream looking for ``<|im_start|>{assistant_role_token}`` boundaries
    that close at ``<|im_end|>``. Marks the whole assistant turn —
    role+wrapper+content+thinking-blocks, since training the model to
    reproduce its own thinking is desirable. This avoids the prefix-of-
    full invariant failure that bites stateful templates: Qwen3.5 injects
    ``<think>`` markers only on the *trailing* assistant turn, so
    incremental prefix tokenization breaks. Marker scan reads only the
    final, ground-truth tokenization and is therefore stable.

    Args:
        tokenizer: A HuggingFace tokenizer that uses ``<|im_start|>`` /
            ``<|im_end|>`` role markers (Qwen and ChatML-family).
        messages: A list of ``{"role", "content"}`` dicts.

    Returns:
        ``{"input_ids": [...], "assistant_masks": [...]}`` with both lists
        the same length. ``assistant_masks`` has at least one ``1`` when
        any message has ``role == "assistant"``.

    Raises:
        ValueError: If the tokenizer doesn't expose ``<|im_start|>`` /
            ``<|im_end|>`` token IDs — the marker-scan algorithm depends
            on them.
    """
    # ``return_dict=False`` is critical: with ``return_dict=True`` (the
    # default in newer transformers) the call returns a BatchEncoding whose
    # ``list(...)`` yields the *keys* (``["input_ids", "attention_mask"]``),
    # not the token IDs — which silently corrupts the dataset.
    full_ids: list[int] = list(
        tokenizer.apply_chat_template(
            messages,
            tokenize=True,
            add_generation_prompt=False,
            return_dict=False,
        )
    )
    mask: list[int] = [0] * len(full_ids)

    im_start_id = tokenizer.convert_tokens_to_ids("<|im_start|>")
    im_end_id = tokenizer.convert_tokens_to_ids("<|im_end|>")
    # ``convert_tokens_to_ids`` returns the unk-id for unknown markers on
    # most tokenizers; treat any non-distinct or None result as "missing".
    unk_id = getattr(tokenizer, "unk_token_id", None)
    if (
        im_start_id is None
        or im_end_id is None
        or im_start_id == unk_id
        or im_end_id == unk_id
    ):
        raise ValueError(
            "compute_assistant_masks: tokenizer lacks <|im_start|> / "
            "<|im_end|> markers; the marker-scan path requires a Qwen- or "
            "ChatML-family tokenizer."
        )

    # The role token sequence that follows <|im_start|>. For Qwen3.5,
    # tokenizer.encode("assistant") → [74455] (single-token role). We
    # encode at runtime so non-Qwen ChatML tokenizers with multi-token
    # role names still work.
    assistant_role_ids: list[int] = list(
        tokenizer.encode("assistant", add_special_tokens=False)
    )
    if not assistant_role_ids:
        return {"input_ids": full_ids, "assistant_masks": mask}

    n = len(full_ids)
    role_len = len(assistant_role_ids)
    i = 0
    while i < n:
        if full_ids[i] != im_start_id:
            i += 1
            continue
        # Match <|im_start|> + assistant role tokens.
        head_end = i + 1 + role_len
        if head_end > n or full_ids[i + 1 : head_end] != assistant_role_ids:
            i += 1
            continue
        # Walk to the closing <|im_end|>; if missing (truncated tail),
        # extend to end-of-sequence.
        j = head_end
        while j < n and full_ids[j] != im_end_id:
            j += 1
        end = j if j < n else n - 1
        for k in range(i, end + 1):
            mask[k] = 1
        i = end + 1

    return {"input_ids": full_ids, "assistant_masks": mask}