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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 asgenerated_code. - Review steps get
[Review]prefix with content inlined into description and emptygenerated_code. - Only the last commit step receives
tests_passed=Trueandcanonical_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 |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Trajectory dict ready for |
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 | |
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 | |
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 | |
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 | |
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 | |
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 |
required |
compress
|
bool
|
Apply diff compression via |
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 | |
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 |
required |
mode
|
Literal['multi_turn', 'single_turn']
|
|
'multi_turn'
|
system_prompt
|
str
|
System message for every conversation. |
SYSTEM_PROMPT
|
Returns:
| Type | Description |
|---|---|
list[list[dict[str, str]]]
|
A tuple |
list[dict[str, str]]
|
|
tuple[list[list[dict[str, str]]], list[dict[str, str]]]
|
|
tuple[list[list[dict[str, str]]], list[dict[str, str]]]
|
TRL's |
tuple[list[list[dict[str, str]]], list[dict[str, str]]]
|
|
tuple[list[list[dict[str, str]]], list[dict[str, str]]]
|
str} |
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]]]
|
|
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]]]
|
|
tuple[list[list[dict[str, str]]], list[dict[str, str]]]
|
missing |
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 | |
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 | |
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::
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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. |
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 | |
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 |
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 | |
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 | |
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).
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 |
required |
return_outputs
|
bool
|
If |
False
|
num_items_in_batch
|
Any
|
Passed through to parent when falling back. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Scalar loss, or |
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 | |
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; |
required |
offset_mapping
|
list[tuple[int, int]]
|
|
required |
hunk_ranges_chars
|
list[tuple[int, int]]
|
Half-open |
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 |
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 | |
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; |
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
|
1.0
|
unchanged_weight
|
float
|
Weight assigned to non-masked tokens whose ID is
not in |
0.3
|
Returns:
| Type | Description |
|---|---|
list[float]
|
Per-token float weights of the same length as |
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 | |
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
|
|
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: |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
A configured :class: |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
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 | |
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.
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 | |
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 | |
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
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 | |
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.
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 | |
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 | |
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 | |
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).
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 |
required |
tokenizer
|
Any
|
Matching HuggingFace tokenizer. |
required |
test_rows
|
list[dict[str, Any]]
|
Augmented pair dicts (must have |
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 |
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 | |
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 |
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 |
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 | |
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).
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 |
required |
positives
|
Any
|
Positive embeddings |
required |
temperature
|
float
|
Temperature scalar tau. Lower = harder negatives. |
0.07
|
Returns:
| Type | Description |
|---|---|
Any
|
Scalar |
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 | |
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.
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
|
run_training(config: EncoderTrainingConfig) -> Path
Run the InfoNCE encoder pretraining loop.
Steps
- Load all augmented pairs from config.augmented_dir.
- Task-ID-level train/test split (via d2l_data.split_by_task_id).
- Build ContrastivePairDataset + DataLoader for the training split.
- Load base encoder (AutoModel) + tokenizer.
- Train for config.epochs with AdamW + cosine schedule + linear warmup.
- Log per-epoch train loss and retrieval eval metrics to MLflow.
- 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 | |
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 | |
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. |
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 | |
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 ( |
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 | |
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 | |
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 | |
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 | |
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 | |
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: |
step_cadence |
int
|
Evaluate Pass@1 every |
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 |
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. |
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 | |
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 | |
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 | |
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 | |
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 | |
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. |
required |
max_samples
|
int
|
Per-benchmark problem cap. |
required |
provider
|
Any
|
:class: |
required |
registry
|
Any
|
:class: |
required |
adapter_ids
|
list[str] | None
|
Ordered adapter stack; empty list = base only. |
None
|
Returns:
| Type | Description |
|---|---|
Callable[[], float]
|
A callable that returns |
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 | |
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
|
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 | |
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.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
|
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 | |
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 |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 |
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 | |
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 | |
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 | |
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. |
required |
registry
|
Any
|
An :class: |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
The adapter's |
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 | |
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 |
dict[str, int]
|
|
tuple[float, dict[str, int]]
|
original record count as the denominator). Unroutable records — |
tuple[float, dict[str, int]]
|
those raising |
tuple[float, dict[str, int]]
|
logged and skipped, but still count against the denominator. Returns |
tuple[float, dict[str, int]]
|
|
tuple[float, dict[str, int]]
|
|
tuple[float, dict[str, int]]
|
only; unroutable records are excluded, so |
tuple[float, dict[str, int]]
|
|
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 | |
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 | |
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 | |
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 | |
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.
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;
|
required |
base_model_id_override
|
str | None
|
Override for the per-adapter
|
required |
emb_model
|
Any | None
|
Pre-loaded sentence-transformer encoder, or |
required |
compute_zscore
|
bool
|
When True, compute + persist z-score stats to
|
required |
task_type
|
str | None
|
Passed through to |
None
|
min_fitness
|
float | None
|
Passed through to |
None
|
sources
|
tuple[str, ...] | None
|
Passed through to |
None
|
emb_model_name
|
str | None
|
HF repo id recorded in the manifest; defaults to
|
None
|
emb_model_dim
|
int | None
|
Embedding dim recorded in the manifest; defaults to
|
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 | |
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.
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 |
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 | |
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).
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 |
required |
target_modules
|
tuple[str, ...]
|
Module names to extract. Must appear at the module
slot of the PEFT key (e.g. |
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 | |
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 | |
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 | |
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 |
required |
task_id
|
str
|
Manifest-stable id (usually |
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 |
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 |
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 | |
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.
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 |
adapter_path |
str
|
Absolute path to the adapter directory (must contain
|
task_description |
str
|
Free-text description used to compute the task
embedding. Source is caller-supplied (see builder's
|
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
|
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 |
source_task_hash |
str | None
|
Optional dedup key ( |
fitness_score |
float | None
|
Optional evaluation fitness ( |
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 | |
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 | |
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 |
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 |
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 ( |
created_at |
str
|
ISO-8601 UTC timestamp of manifest creation. |
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 | |
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 | |
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 | |
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 | |
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 | |
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.
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 viaregistry.list_all).task_typematches iff provided.fitness_score >= min_fitnessiff provided (None-valued fitness scores are excluded whenmin_fitnessis set).sourceinsourcesiff provided.file_pathexists 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. |
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 | |
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.
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
|
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}} |
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 | |
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 |
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 | |
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 |
required |
Returns:
| Type | Description |
|---|---|
dict[str, dict[str, Any]]
|
Stats dict |
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 | |
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).
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'
|
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 | |
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 |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dict mapping task_id to a |
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 | |
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 | |
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 |
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 | |
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: |
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 ( |
oracle_fallback |
Literal['base_model', 'skip']
|
What to do when a record's bin has no registered
oracle. |
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]]
|
|
required |
Returns:
| Type | Description |
|---|---|
dict[str, object]
|
Report dict with keys |
dict[str, object]
|
( |
dict[str, object]
|
delta >= |
dict[str, object]
|
absolute regression observed, |
dict[str, object]
|
benchmarks), and |
dict[str, object]
|
failed, or empty when |
Raises:
| Type | Description |
|---|---|
ValueError
|
When any required benchmark is missing from |
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 | |
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
- Load records from
config.dataset_path. - Open the AdapterRegistry, audit oracle coverage, abort when
coverage <
config.min_oracle_coverage. - When
config.dry_run: return a report dict and exit. - Setup base model, tokenizer, hypernet, hc.
- Build :class:
OracleAdapterCacheand loopnum_stepsrecords, calling :func:_training_step_round2per step. Skip sentinels advance the step counter without an optimizer step. - Apply the same checkpoint + kill-switch cadence as round-1.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
Any
|
:class: |
required |
kill_switch_evaluate_fn
|
Any | None
|
Optional zero-arg callable returning Pass@1
for the kill-switch. When |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Report dict. Shape depends on mode. In dry_run mode the keys are |
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
|
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 | |
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: |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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
|
None
|
dataset_path
|
str | None
|
Path to a JSONL file of mined pair records (as produced
by |
None
|
encoding_mode
|
str
|
|
'multi_turn'
|
diff_aware_loss
|
bool
|
When True, wrap the SFT collator with
|
False
|
diff_changed_weight
|
float
|
Per-token weight applied to assistant tokens
absent from the masked context span. Only used when
|
1.0
|
diff_unchanged_weight
|
float
|
Per-token weight applied to assistant
tokens also present in the masked context span. Only used
when |
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 |
None
|
override_lora_dropout
|
float | None
|
Post-load override for the warm-start
adapter's LoRA dropout probability. Applied the same way as
|
None
|
warmup_ratio
|
float | None
|
Linear warmup fraction of total training steps passed
to |
None
|
neftune_noise_alpha
|
float | None
|
NEFTune noise alpha for embedding perturbation.
When set, passed to |
None
|
max_length
|
int
|
SFT tokenizer truncation length. Caps activation
memory; both the cross-entropy logits tensor and (with
|
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 | |
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'
|
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 |
1.0
|
diff_unchanged_weight
|
float
|
Weight for assistant tokens present in the
masked context span when |
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 |
None
|
neftune_noise_alpha
|
float | None
|
NEFTune noise alpha forwarded to |
None
|
max_length
|
int
|
SFT tokenizer truncation length forwarded to
|
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 | |
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 |
None
|
Returns:
| Type | Description |
|---|---|
int
|
Exit code: 0 on success. |
Raises:
| Type | Description |
|---|---|
SystemExit
|
Raised by argparse on invalid arguments or |
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 | |
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 | |
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
|
required |
Returns:
| Type | Description |
|---|---|
None
|
None. |
Raises:
| Type | Description |
|---|---|
None
|
All exceptions from |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 |
required |
messages
|
list[dict[str, str]]
|
A list of |
required |
Returns:
| Type | Description |
|---|---|
dict[str, list[int]]
|
|
dict[str, list[int]]
|
the same length. |
dict[str, list[int]]
|
any message has |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the tokenizer doesn't expose |
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 | |