Skip to content

Training Module

Model training orchestration and utilities.

Overview

The training module provides the Trainer class for training leech models.

Trainer Class

Trainer

Trainer(model: Module, model_type: str, train_loader: DataLoader, val_loader: DataLoader | None = None, device: str = 'cuda', learning_rate: float = 0.001, output_dir: Path | None = None, pos_weight: Tensor | None = None, weight_decay: float = 0.0, max_grad_norm: float = 0.0, quantile_grad_clip: bool = False, grad_accum_split: int = 1, save_optim_every: int = 1, scheduler_type: str = 'none', scheduler_patience: int = 5, scheduler_factor: float = 0.5, warmup_epochs: int = 0, loss_type: str = 'bce', focal_gamma: float = 2.0, focal_neg_gamma: float | None = None, label_smoothing: float = 0.0, use_mixed_precision: bool = False, resume_checkpoint: Path | None = None, num_out: int | None = None, epochs: int = 50, adversarial_lambda: float = 0.0, adversarial_num_classes: int = 4, adversarial_anneal_epochs: int = 0, cl_regression: bool = False, cl_lambda: float = 1.0, checkpoint_metric: str = 'auto', dist: DistContext | None = None, cfg: TrainConfig | None = None, seed: int | None = None, train_data_path: Path | None = None, val_data_path: Path | None = None)

Trainer for leech models.

Handles training loop, validation, checkpointing, and metrics logging.

Source code in src/leech/training.py
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
773
774
775
776
777
778
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
def __init__(
    self,
    model: nn.Module,
    model_type: str,
    train_loader: DataLoader,
    val_loader: DataLoader | None = None,
    device: str = "cuda",
    learning_rate: float = 0.001,
    output_dir: Path | None = None,
    pos_weight: torch.Tensor | None = None,
    weight_decay: float = 0.0,
    max_grad_norm: float = 0.0,
    quantile_grad_clip: bool = False,
    grad_accum_split: int = 1,
    save_optim_every: int = 1,
    scheduler_type: str = "none",
    scheduler_patience: int = 5,
    scheduler_factor: float = 0.5,
    warmup_epochs: int = 0,
    loss_type: str = "bce",
    focal_gamma: float = 2.0,
    focal_neg_gamma: float | None = None,
    label_smoothing: float = 0.0,
    use_mixed_precision: bool = False,
    resume_checkpoint: Path | None = None,
    num_out: int | None = None,
    epochs: int = 50,
    adversarial_lambda: float = 0.0,
    adversarial_num_classes: int = 4,
    adversarial_anneal_epochs: int = 0,
    cl_regression: bool = False,
    cl_lambda: float = 1.0,
    checkpoint_metric: str = "auto",
    dist: DistContext | None = None,
    cfg: TrainConfig | None = None,
    seed: int | None = None,
    train_data_path: Path | None = None,
    val_data_path: Path | None = None,
):
    # The recipe as one object (#270). Every caller above still passes
    # loose kwargs (43 test call sites plus train_model's own kwarg path)
    # and those keep working unchanged: when cfg is omitted, one is built
    # from exactly the arguments above, then unpacked back into the same
    # local names the rest of this method already used, so the body below
    # this block is untouched. train_model's own call site passes its
    # already-resolved cfg directly instead of re-listing ~20 of these.
    #
    # MAINTENANCE: train_model (below, search "if cfg is None") has the
    # same build-then-unpack shape for its own, larger kwarg set. Both
    # are real, load-bearing entry points (Trainer is constructed
    # directly with loose kwargs at ~60 test call sites, not only via
    # train_model), so this duplication couldn't be collapsed to one
    # copy without breaking one of the two call surfaces. A recipe field
    # added to only one of the two pairs here silently doesn't reach the
    # other constructor's cfg=None fallback -- check both when adding one.
    if cfg is None:
        cfg = TrainConfig(
            epochs=epochs,
            loss_type=loss_type,
            focal_gamma=focal_gamma,
            focal_neg_gamma=focal_neg_gamma,
            label_smoothing=label_smoothing,
            mixed_precision=use_mixed_precision,
            checkpoint_metric=checkpoint_metric,
            num_out=num_out if num_out is not None else 1,
            optim=OptimConfig(
                learning_rate=learning_rate,
                weight_decay=weight_decay,
                max_grad_norm=max_grad_norm,
                quantile_grad_clip=quantile_grad_clip,
                grad_accum_split=grad_accum_split,
                save_optim_every=save_optim_every,
            ),
            scheduler=SchedulerConfig(
                scheduler_type=scheduler_type,
                scheduler_patience=scheduler_patience,
                scheduler_factor=scheduler_factor,
                warmup_epochs=warmup_epochs,
            ),
            aux_head=AuxHeadConfig(
                adversarial_lambda=adversarial_lambda,
                adversarial_anneal_epochs=adversarial_anneal_epochs,
                cl_regression=cl_regression,
                cl_lambda=cl_lambda,
            ),
        )
    learning_rate = cfg.optim.learning_rate
    weight_decay = cfg.optim.weight_decay
    max_grad_norm = cfg.optim.max_grad_norm
    quantile_grad_clip = cfg.optim.quantile_grad_clip
    grad_accum_split = cfg.optim.grad_accum_split
    save_optim_every = cfg.optim.save_optim_every
    scheduler_type = cfg.scheduler.scheduler_type
    scheduler_patience = cfg.scheduler.scheduler_patience
    scheduler_factor = cfg.scheduler.scheduler_factor
    warmup_epochs = cfg.scheduler.warmup_epochs
    loss_type = cfg.loss_type
    focal_gamma = cfg.focal_gamma
    focal_neg_gamma = cfg.focal_neg_gamma
    label_smoothing = cfg.label_smoothing
    use_mixed_precision = cfg.mixed_precision
    epochs = cfg.epochs
    adversarial_lambda = cfg.aux_head.adversarial_lambda
    adversarial_anneal_epochs = cfg.aux_head.adversarial_anneal_epochs
    cl_regression = cfg.aux_head.cl_regression
    cl_lambda = cfg.aux_head.cl_lambda
    checkpoint_metric = cfg.checkpoint_metric
    # num_out is not unpacked from cfg: the caller-supplied value (which
    # may be the sentinel-resolved None) is what the loss-type branch
    # below already keys off, and cfg.num_out always has a concrete int
    # (defaulted to 1), so unpacking it would turn "not yet known" into
    # "1" for every caller that passes num_out=None.
    #
    # self.cfg is currently write-only: nothing in this class reads it
    # back, and it does not enter a checkpoint payload. It is also not
    # re-synced after construction, so self.cfg.pos_weight (float-typed
    # here; the Tensor actually used is a local, never assigned back),
    # self.cfg.num_out (may differ from the auto-detected value above)
    # and self.cfg.checkpoint_metric (pre-"auto"-resolution) can all
    # disagree with what the run actually used. Do not read self.cfg
    # expecting it to reflect resolved values until something here
    # actually consumes it and that gap gets closed.
    self.cfg = cfg

    # Which rank this is. SINGLE has world_size 1, so every guard below is
    # off and the path is exactly what it was before DDP existed.
    self.dist = dist if dist is not None else SINGLE
    self._is_main = self.dist.is_main
    self._ddp_modules: list[nn.Module] = []

    # Wrap model with inference wrapper for unified forward pass
    self.model_type = model_type
    self.model_wrapper = ModelInferenceWrapper(model, model_type)
    self.model = self.model_wrapper.model  # Keep reference to underlying model
    self.model.to(device)
    # The forward goes through DDP; everything else -- state_dict, the
    # repr-capture hook, the best-weights deepcopy -- stays on the unwrapped
    # module, so a checkpoint written here has the same keys as a
    # single-GPU one and needs no `module.` stripping downstream.
    self.model_wrapper.forward_module = self._wrap_ddp(self.model, device)
    self.train_loader = train_loader
    self.val_loader = val_loader
    self.device = device
    self.output_dir = output_dir
    self.max_grad_norm = max_grad_norm
    self.warmup_epochs = warmup_epochs
    self.base_lr = learning_rate
    # Provenance for the interrupt-safe resume checkpoint (issue #330):
    # the run seed (overwritten by whatever a resumed checkpoint recorded,
    # so `training_seed.txt` ends the run holding the seed it actually ran
    # under) and the corpus fingerprints the recipe guard compares against.
    self.seed = seed
    self._train_data_path = train_data_path
    self._val_data_path = val_data_path
    # Not reset on resume -- see `_resume_from_checkpoint` -- so early
    # stopping continues counting from where an interrupted run left off
    # instead of getting `early_stopping_patience` fresh epochs every retry.
    self.patience_counter = 0

    # Gradient accumulation: split each batch into N sub-batches, scale each
    # sub-loss by 1/N, and step the optimizer once per full batch.
    self.grad_accum_split = max(1, int(grad_accum_split))
    if self.grad_accum_split > 1:
        logger.info(f"Gradient accumulation: {self.grad_accum_split} sub-batches per step")

    # Adaptive (quantile) gradient clipping takes precedence over the fixed
    # --max-grad-norm threshold when enabled.
    self.clip_grad_fn: ClipGrad | None = None
    if quantile_grad_clip:
        self.clip_grad_fn = ClipGrad()
        if max_grad_norm > 0:
            logger.warning(
                f"quantile_grad_clip enabled; ignoring fixed max_grad_norm={max_grad_norm}"
            )
        logger.info("Quantile-based gradient clipping enabled")

    # Optimizer state is bulky (2x model size for AdamW); write it only every
    # N epochs while weights are written on every save. 1 = every save.
    self.save_optim_every = max(1, int(save_optim_every))
    if self.save_optim_every > 1:
        logger.info(f"Saving optimizer state every {self.save_optim_every} epochs")

    # Adversarial training (gradient reversal for confound invariance)
    self.adversarial_head: AdversarialHead | None = None
    self._adv_forward: nn.Module | None = None
    self.adversarial_criterion: nn.CrossEntropyLoss | None = None
    self.adversarial_lambda = adversarial_lambda
    self.adversarial_anneal_epochs = adversarial_anneal_epochs

    if adversarial_lambda > 0:
        repr_dim = self.model_wrapper.enable_repr_capture()
        self.adversarial_head = AdversarialHead(
            input_dim=repr_dim,
            num_classes=adversarial_num_classes,
            lambda_=0.0 if adversarial_anneal_epochs > 0 else adversarial_lambda,
        )
        self.adversarial_head.to(device)
        # The aux heads sit OUTSIDE the model but inside the optimizer, so
        # without their own wrapper their gradients are never allreduced:
        # every rank would keep a private head while the backbone stays in
        # sync. Converges, reports plausible numbers, wrong.
        self._adv_forward = self._wrap_ddp(self.adversarial_head, device)
        # ignore_index=-1 skips samples with unknown confound (e.g. uncharged)
        self.adversarial_criterion = nn.CrossEntropyLoss(ignore_index=-1)
        logger.info(
            f"Adversarial training enabled: lambda={adversarial_lambda}, "
            f"classes={adversarial_num_classes}, anneal_epochs={adversarial_anneal_epochs}, "
            f"repr_dim={repr_dim}"
        )

    # CL regression head (continuous charging-level prediction)
    self.cl_regression_head: RegressionHead | None = None
    self._cl_forward: nn.Module | None = None
    self.cl_lambda = cl_lambda

    if cl_regression:
        # Enable repr capture if not already active for adversarial
        if self.adversarial_head is None:
            repr_dim = self.model_wrapper.enable_repr_capture()
        else:
            repr_dim = self.model_wrapper.enable_repr_capture()
        self.cl_regression_head = RegressionHead(input_dim=repr_dim)
        self.cl_regression_head.to(device)
        self._cl_forward = self._wrap_ddp(self.cl_regression_head, device)
        logger.info(f"CL regression head enabled: repr_dim={repr_dim}, cl_lambda={cl_lambda}")

    # Setup optimizer (include adversarial + CL regression head params if present)
    all_params = list(model.parameters())
    if self.adversarial_head is not None:
        all_params += list(self.adversarial_head.parameters())
    if self.cl_regression_head is not None:
        all_params += list(self.cl_regression_head.parameters())
    # AdamW decouples weight_decay from the gradient (vs. Adam's L2-on-grad).
    # With Adam, adaptive per-param LRs almost cancel L2 reg for low-grad
    # params, so weight_decay loses bite as cosine LR decays toward 0. AdamW
    # applies decay directly to weights and preserves regularization through
    # the LR schedule. State dict is compatible with Adam checkpoints for
    # resume — only the step rule changes.
    # fused=True runs the optimizer step as a single fused CUDA kernel (faster);
    # it is only supported on CUDA, so fall back to the standard path on CPU.
    self.optimizer = torch.optim.AdamW(
        all_params,
        lr=learning_rate,
        weight_decay=weight_decay,
        fused=(device != "cpu"),
    )

    # Setup loss
    self.loss_type = loss_type
    self._num_out = num_out if num_out is not None else 1
    self.label_smoothing = label_smoothing
    pw = pos_weight.to(device) if pos_weight is not None else None
    if loss_type == "cross_entropy":
        # CrossEntropyLoss expects (B, num_classes) logits and (B,) integer labels
        if pw is not None and self._num_out <= 2:
            # Convert pos_weight to per-class weights for CE (binary case)
            ce_weights = torch.tensor([1.0, pw.item()], dtype=torch.float32).to(device)
            self.criterion = nn.CrossEntropyLoss(
                weight=ce_weights, label_smoothing=label_smoothing
            )
        elif pw is not None and self._num_out > 2:
            # Multiclass: pw is already a per-class weight tensor
            self.criterion = nn.CrossEntropyLoss(
                weight=pw.to(device), label_smoothing=label_smoothing
            )
            logger.info(f"Using class weights for {self._num_out}-class CE")
        else:
            self.criterion = nn.CrossEntropyLoss(label_smoothing=label_smoothing)
        logger.info(f"Using CrossEntropyLoss ({self._num_out}-class)")
    elif loss_type == "focal":
        self.criterion = FocalBCEWithLogitsLoss(
            gamma=focal_gamma, pos_weight=pw, neg_gamma=focal_neg_gamma
        )
        neg_gamma_note = f", neg_gamma={focal_neg_gamma}" if focal_neg_gamma is not None else ""
        if label_smoothing > 0:
            logger.info(
                f"Using focal loss (gamma={focal_gamma}{neg_gamma_note}) "
                f"with label smoothing={label_smoothing}"
            )
        else:
            logger.info(f"Using focal loss (gamma={focal_gamma}{neg_gamma_note})")
    elif loss_type == "noise_corrected_bce":
        self.criterion = NoiseCorrectedBCEWithLogitsLoss(pos_weight=pw)
        logger.info(
            "Using noise-corrected BCE (forward correction); per-sample rates "
            "come from each batch's 'noise_rate' field (0 where unmapped)"
        )
    else:
        if pw is not None:
            self.criterion = nn.BCEWithLogitsLoss(pos_weight=pw)
        else:
            self.criterion = nn.BCEWithLogitsLoss()
            logger.info("Training without class weighting")
    # Weighted CE normalizes by the summed weight of the samples it sees,
    # not by their count, so it is the one loss here that does not
    # decompose over shards. See _weighted_ce_global.
    self._ce_needs_global_norm = (
        self.dist.enabled
        and loss_type == "cross_entropy"
        and getattr(self.criterion, "weight", None) is not None
    )
    if label_smoothing > 0 and loss_type != "cross_entropy":
        logger.info(f"Label smoothing={label_smoothing} (applied to binary targets)")

    # Setup LR scheduler
    self.scheduler = None
    self.scheduler_type = scheduler_type
    if scheduler_type == "reduce_on_plateau":
        self.scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
            self.optimizer,
            mode="min",
            patience=scheduler_patience,
            factor=scheduler_factor,
        )
        logger.info(
            f"Using ReduceLROnPlateau scheduler (patience={scheduler_patience}, factor={scheduler_factor})"
        )
    elif scheduler_type == "cosine":
        # Unified linear-warmup + cosine-decay schedule (bonito style): one
        # LambdaLR covering both phases instead of a manual warmup bolted
        # onto CosineAnnealingLR. With warmup_epochs=0 the multiplier is
        # numerically identical to CosineAnnealingLR(T_max=epochs,
        # eta_min=1e-6); with warmup it reproduces the previous manual ramp.
        eta_min = 1e-6
        end_ratio = eta_min / learning_rate if learning_rate > 0 else 0.0
        effective_epochs = max(1, epochs - warmup_epochs)
        self.scheduler = torch.optim.lr_scheduler.LambdaLR(
            self.optimizer,
            lr_lambda=linear_warmup_cosine_decay(
                total_epochs=epochs,
                warmup_epochs=warmup_epochs,
                end_ratio=end_ratio,
            ),
        )
        logger.info(
            f"Using linear_warmup_cosine_decay scheduler "
            f"(warmup={warmup_epochs}, T_max={effective_epochs}, eta_min={eta_min})"
        )

    # Mixed precision (only on CUDA)
    self.use_mixed_precision = use_mixed_precision and device != "cpu"
    self.scaler = None
    if self.use_mixed_precision:
        self.scaler = torch.amp.GradScaler("cuda")
        logger.info("Mixed precision training enabled")

    # Track best model — checkpoint criterion is configurable.
    # "auto" maps to macro-F1 for multiclass and AUROC for binary (immune to
    # class-imbalance gaming, unlike raw accuracy on one-vs-all heads).
    self._checkpoint_metric = self._resolve_checkpoint_metric(checkpoint_metric)
    logger.info(f"Checkpoint criterion: {self._checkpoint_metric}")
    self.best_val_acc = 0.0
    self.best_val_f1 = 0.0
    self.best_val_auc = 0.0
    # Generic "best value of whatever self._checkpoint_metric names" --
    # equal to best_val_{acc,f1,auc} for the three plain metrics, and the
    # only record kept for the two parametric ones (tpr_at_fpr:<f> /
    # callable_at_precision:<p>), which have no dedicated best_val_*
    # field of their own.
    #
    # -inf, not 0.0: a strict tpr_at_fpr/callable_at_precision target can
    # legitimately score 0.0 on every epoch (e.g. tpr_at_fpr:0.0001 on a
    # model that never clears that FPR ceiling), and a 0.0 floor would
    # make every such epoch "not improved" forever -- no checkpoint ever
    # saved inside the loop, best_epoch stuck at 0, and _ensure_best_
    # checkpoint's fallback (whatever the last epoch happened to be)
    # silently standing in for "best" instead. -inf guarantees the first
    # validated epoch always registers as an improvement, whatever its
    # value. _serializable_best_val_selection is what keeps this sentinel
    # out of the JSON/checkpoint outputs if validation never runs at all.
    self.best_val_selection = float("-inf")
    self.best_epoch = 0
    self.start_epoch = 1
    self._best_model_state: dict[str, Any] | None = None
    # Raw gathered (labels, probs) from the most recent validate() call,
    # needed to compute a parametric checkpoint metric -- those can't be
    # reduced to a scalar inside validate() the way val_acc/auc/f1 are,
    # since which scalar they need depends on self._checkpoint_metric.
    # Only ever populated for binary (_resolve_checkpoint_metric refuses
    # a parametric metric on a multiclass model).
    self._last_val_labels: np.ndarray | None = None
    self._last_val_probs: np.ndarray | None = None

    # History
    self.history: dict[str, list[float]] = {
        "train_loss": [],
        "train_acc": [],
        "val_loss": [],
        "val_acc": [],
        "val_auc": [],
        "val_f1": [],
        # Whatever self._checkpoint_metric resolved to, every epoch --
        # numerically identical to the matching val_acc/val_auc/val_f1
        # entry for the three plain metrics, and the only per-epoch
        # record of the two parametric ones. run_grid_point reads this
        # (rather than history[selection_metric], which doesn't exist for
        # a parametric metric string) to find a grid point's best epoch.
        "val_selection": [],
    }
    if self.adversarial_head is not None:
        self.history["train_adv_loss"] = []
        self.history["train_adv_acc"] = []
    if self.cl_regression_head is not None:
        self.history["train_cl_loss"] = []
        self.history["val_cl_loss"] = []

    if self.output_dir and self._is_main:
        self.output_dir.mkdir(parents=True, exist_ok=True)

    # Resume from checkpoint (skip if file doesn't exist)
    if resume_checkpoint is not None:
        if resume_checkpoint.exists():
            self._resume_from_checkpoint(resume_checkpoint)
        else:
            logger.info(f"Checkpoint not found, starting fresh: {resume_checkpoint}")

train_epoch

train_epoch(progress: Progress | None = None, task_id: TaskID | None = None) -> tuple[float, float]

Train for one epoch.

Parameters:

Name Type Description Default
progress Progress | None

Rich Progress instance (optional)

None
task_id TaskID | None

Progress task ID (optional)

None

Returns:

Type Description
tuple[float, float]

Tuple of (average_loss, accuracy)

Source code in src/leech/training.py
def train_epoch(
    self, progress: Progress | None = None, task_id: TaskID | None = None
) -> tuple[float, float]:
    """
    Train for one epoch.

    Args:
        progress: Rich Progress instance (optional)
        task_id: Progress task ID (optional)

    Returns:
        Tuple of (average_loss, accuracy)
    """
    self.model.train()
    if self.adversarial_head is not None:
        self.adversarial_head.train()
    if self.cl_regression_head is not None:
        self.cl_regression_head.train()

    # Training metrics reduce to a mean loss and an accuracy, so nothing
    # here needs the predictions themselves -- a running correct-count is
    # enough and keeps the per-epoch prediction arrays (one boxed
    # np.float32 per prediction) from ever existing. Totals stay on the
    # device until the epoch ends; see _DeviceTally.
    tally = _DeviceTally()
    seen = 0

    for batch in self.train_loader:
        self.optimizer.zero_grad()

        # Gradient accumulation: N sub-batches, each scaled by 1/N, one
        # optimizer step per full batch. N=1 leaves the graph untouched.
        sub_batches = split_batch(batch, self.grad_accum_split)
        num_splits = len(sub_batches)

        for micro_step, sub_batch in enumerate(sub_batches):
            # no_sync on every micro-step but the last: N sub-batches
            # otherwise pay N allreduces for one step's arithmetic.
            with self._accumulating(micro_step == num_splits - 1):
                if self.use_mixed_precision:
                    with torch.amp.autocast("cuda"):
                        logits, labels, main_loss, loss, adv, cl_loss = (
                            self._compute_batch_loss(sub_batch)
                        )
                    if num_splits > 1:
                        loss = loss / num_splits
                    self.scaler.scale(loss).backward()
                else:
                    logits, labels, main_loss, loss, adv, cl_loss = self._compute_batch_loss(
                        sub_batch
                    )
                    if num_splits > 1:
                        loss = loss / num_splits
                    loss.backward()

                # Track metrics (sub-batch losses are averaged back to a
                # per-batch mean so history is comparable across split settings)
                tally.add("loss", main_loss, num_splits)
                if adv is not None:
                    adv_loss, adv_preds, adv_labels = adv
                    tally.add("adv_loss", adv_loss, num_splits)
                    # `mask.any()` would sync; the masked matches and the
                    # masked count are all the accuracy needs, and both are
                    # correct when the mask is empty.
                    mask = adv_labels != -1
                    tally.add("adv_correct", ((adv_preds == adv_labels) & mask).sum())
                    tally.add("adv_seen", mask.sum())
                if cl_loss is not None:
                    tally.add("cl_loss", cl_loss, num_splits)

                labels_flat = labels.detach().flatten()
                if self.loss_type == "cross_entropy":
                    # argmax(logits) is exactly the softmax > 0.5 threshold
                    # (softmax is monotonic per-row in the logits), for
                    # both binary and multi-class CE -- so this reads the
                    # predicted class straight off the logits and never
                    # computes the fp16 softmax value autocast would
                    # otherwise hand back for a probability nothing here
                    # needs (#264).
                    preds = torch.argmax(logits, dim=-1).detach().flatten()
                else:
                    # sigmoid(logits) > 0.5 is exactly logits > 0; comparing
                    # the raw logit sidesteps autocast's fp16 sigmoid
                    # output entirely instead of quantizing a probability
                    # this branch only ever thresholds (#264).
                    preds = logits.detach().flatten() > 0
                matches = preds.to(torch.float64) == labels_flat.to(torch.float64)
                tally.add("correct", matches.sum())
                seen += labels_flat.numel()

        # Gradient clipping + optimizer step (once per full batch)
        needs_clip = self.clip_grad_fn is not None or self.max_grad_norm > 0
        if needs_clip:
            if self.use_mixed_precision:
                self.scaler.unscale_(self.optimizer)
            if self.clip_grad_fn is not None:
                self.clip_grad_fn(self.model.parameters())
            else:
                torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.max_grad_norm)

        if self.use_mixed_precision:
            self.scaler.step(self.optimizer)
            self.scaler.update()
        else:
            self.optimizer.step()

        # Update progress if provided
        if progress is not None and task_id is not None:
            progress.update(task_id, advance=1)

    # Compute metrics. accuracy_score normalizes to matches / samples, so
    # the running counts reproduce it exactly for both the multi-class
    # (argmax) and the binary (threshold at 0.5) case.
    #
    # Under DDP each rank has tallied only its own shard, so the sums are
    # reduced BEFORE they are divided -- and the divisor grows with the
    # world, since every rank ran the same number of batches. Averaging the
    # per-rank means instead would be the same number here and a different
    # one the moment the shards stop being equal.
    totals = {
        "loss": tally.value("loss"),
        "correct": tally.value("correct"),
        "seen": float(seen),
    }
    if self.adversarial_head is not None:
        totals["adv_loss"] = tally.value("adv_loss")
        totals["adv_correct"] = tally.value("adv_correct")
        totals["adv_seen"] = tally.value("adv_seen")
    if self.cl_regression_head is not None:
        totals["cl_loss"] = tally.value("cl_loss")
    totals = all_reduce_sum(totals, self.dist, self.device)
    num_batches = len(self.train_loader) * self.dist.world_size

    avg_loss = totals["loss"] / num_batches
    accuracy = totals["correct"] / totals["seen"] if totals["seen"] else 0.0

    # Adversarial metrics
    if self.adversarial_head is not None:
        avg_adv_loss = totals["adv_loss"] / max(1, num_batches)
        adv_seen = totals["adv_seen"]
        adv_acc = totals["adv_correct"] / adv_seen if adv_seen else 0.0
        self.history["train_adv_loss"].append(avg_adv_loss)
        self.history["train_adv_acc"].append(adv_acc)

    # CL regression metrics
    if self.cl_regression_head is not None:
        avg_cl_loss = totals["cl_loss"] / max(1, num_batches)
        self.history["train_cl_loss"].append(avg_cl_loss)

    return avg_loss, accuracy

validate

validate(progress: Progress | None = None, task_id: TaskID | None = None) -> tuple[float, float, float, float]

Validate model.

Parameters:

Name Type Description Default
progress Progress | None

Rich Progress instance (optional)

None
task_id TaskID | None

Progress task ID (optional)

None

Returns:

Type Description
tuple[float, float, float, float]

Tuple of (average_loss, accuracy, roc_auc, f1)

Source code in src/leech/training.py
def validate(
    self, progress: Progress | None = None, task_id: TaskID | None = None
) -> tuple[float, float, float, float]:
    """
    Validate model.

    Args:
        progress: Rich Progress instance (optional)
        task_id: Progress task ID (optional)

    Returns:
        Tuple of (average_loss, accuracy, roc_auc, f1)
    """
    if self.val_loader is None:
        return 0.0, 0.0, 0.0, 0.0

    self.model.eval()
    if self.cl_regression_head is not None:
        self.cl_regression_head.eval()
    # AUROC needs the probabilities themselves, so validation keeps them --
    # but as one array per batch, never as a list of boxed numpy scalars
    # (~40 bytes each while alive, and unboxed one at a time at the end).
    tally = _DeviceTally()
    all_preds: list[np.ndarray] = []
    all_labels: list[np.ndarray] = []
    # For multiclass: keep full softmax probabilities so we can compute
    # macro one-vs-rest AUROC (argmax-only preds lose that information).
    all_probs_mc: list[np.ndarray] = []
    val_seen = 0

    with torch.inference_mode():
        for batch in self.val_loader:
            # Move labels to device
            labels = batch["label"].to(self.device, non_blocking=True)

            # Adapt labels for CrossEntropyLoss
            if self.loss_type == "cross_entropy":
                ce_labels = labels.squeeze(-1).long()
            else:
                ce_labels = None

            # Forward pass (wrapper handles moving tensors and calling model correctly)
            if self.use_mixed_precision:
                with torch.amp.autocast("cuda"):
                    logits = self.model_wrapper.forward_batch(batch, self.device)
                    if ce_labels is not None:
                        loss = self.criterion(logits, ce_labels)
                    elif self.loss_type == "noise_corrected_bce":
                        loss = self.criterion(
                            logits, labels, noise_rate=self._batch_noise_rate(batch)
                        )
                    else:
                        loss = self.criterion(logits, labels)
            else:
                logits = self.model_wrapper.forward_batch(batch, self.device)
                if ce_labels is not None:
                    loss = self.criterion(logits, ce_labels)
                elif self.loss_type == "noise_corrected_bce":
                    loss = self.criterion(
                        logits, labels, noise_rate=self._batch_noise_rate(batch)
                    )
                else:
                    loss = self.criterion(logits, labels)

            # The metrics below need real probability resolution: under
            # autocast the final Linear emits fp16, and unlike softmax
            # (which autocast promotes to fp32 on its own), torch.sigmoid
            # is not on that list -- computing it on the raw logits would
            # quantize the AUROC ranking and val_auc, the checkpoint
            # -selection criterion (#264). The loss above is deliberately
            # computed on the pre-cast logits -- BCE/CE are already
            # autocast's fp32-safe, so this cast must not move earlier.
            logits = logits.float()

            # CL regression validation loss
            if (
                self.cl_regression_head is not None
                and "cl_target" in batch
                and self.model_wrapper.captured_repr is not None
            ):
                cl_targets = batch["cl_target"].to(self.device, non_blocking=True)
                cl_mask = cl_targets >= 0
                if cl_mask.any():
                    cl_preds = self.cl_regression_head(
                        self.model_wrapper.captured_repr[cl_mask]
                    )
                    tally.add(
                        "cl_loss",
                        nn.functional.mse_loss(cl_preds, cl_targets[cl_mask]),
                    )

            # Track metrics. The sample-weighted sum is what the
            # distributed reduction divides; the unweighted per-batch mean
            # below is kept for the single-GPU number, which must not move.
            tally.add("loss", loss)
            tally.add("loss_sum", loss * labels.shape[0])
            val_seen += int(labels.shape[0])
            if self.loss_type == "cross_entropy" and self._num_out > 2:
                probs_mc = torch.softmax(logits, dim=-1).cpu().numpy()
                all_probs_mc.append(probs_mc)
                all_preds.append(probs_mc.argmax(axis=-1).ravel())
            elif self.loss_type == "cross_entropy":
                all_preds.append(torch.softmax(logits, dim=-1)[:, 1].cpu().numpy().ravel())
            else:
                all_preds.append(torch.sigmoid(logits).cpu().numpy().ravel())
            all_labels.append(labels.cpu().numpy().ravel())

            # Update progress if provided
            if progress is not None and task_id is not None:
                progress.update(task_id, advance=1)

    # Compute metrics
    avg_loss = tally.value("loss") / len(self.val_loader)
    preds_arr = np.concatenate(all_preds) if all_preds else np.zeros(0, dtype=np.float32)
    labels_arr = np.concatenate(all_labels) if all_labels else np.zeros(0, dtype=np.float32)

    if self.dist.enabled:
        # Every rank scored a different slice, and AUROC does not decompose
        # over slices -- so the predictions themselves are gathered and the
        # metrics computed once, globally. That makes the 2-GPU numbers
        # equal to the 1-GPU ones rather than merely close.
        preds_arr = np.concatenate(gather_arrays(preds_arr, self.dist))
        labels_arr = np.concatenate(gather_arrays(labels_arr, self.dist))
        if all_probs_mc:
            all_probs_mc = [
                np.concatenate(
                    gather_arrays(np.concatenate(all_probs_mc, axis=0), self.dist), axis=0
                )
            ]
        # The loss is the one metric that cannot be recovered exactly: a
        # per-batch mean depends on where the batch boundaries fell, and
        # sharding moves them. The sample-weighted mean is reported
        # instead, which differs from the single-GPU number only by the
        # weight of the tail batch.
        reduced = all_reduce_sum(
            {
                "loss_sum": tally.value("loss_sum"),
                "n": float(val_seen),
                "cl_loss": tally.value("cl_loss"),
                "batches": float(len(self.val_loader)),
            },
            self.dist,
            self.device,
        )
        avg_loss = reduced["loss_sum"] / reduced["n"] if reduced["n"] else 0.0
    if self._num_out > 2:
        # Multi-class: preds are class indices; probs are needed for AUROC.
        accuracy = accuracy_score(labels_arr, preds_arr)
        f1 = f1_score(labels_arr, preds_arr, average="macro", zero_division=0.0)
        present = np.unique(labels_arr)
        # Macro one-vs-rest AUROC computed per-class. We avoid passing the
        # sliced probs to roc_auc_score(multi_class="ovr") because sklearn
        # rejects scores that don't sum to 1.0 across columns — which fires
        # whenever the val set is missing any of the model's output classes
        # (silent ValueError → AUC reported as 0.0). Manual OvR sidesteps
        # the check and lets us skip classes that are degenerate (zero
        # positives or zero negatives) in this validation set.
        if len(present) > 1 and all_probs_mc:
            probs_all = np.concatenate(all_probs_mc, axis=0)
            per_class_aucs: list[float] = []
            for c in present:
                c_int = int(c)
                if c_int >= probs_all.shape[1]:
                    continue
                y_bin = (labels_arr == c).astype(int)
                pos = int(y_bin.sum())
                if pos == 0 or pos == len(y_bin):
                    continue
                try:
                    per_class_aucs.append(float(roc_auc_score(y_bin, probs_all[:, c_int])))
                except ValueError as e:
                    logger.warning(f"AUROC failed for class {c_int}: {e}")
            auc = float(np.mean(per_class_aucs)) if per_class_aucs else 0.0
        else:
            auc = 0.0
    else:
        all_preds_binary = (preds_arr > 0.5).astype(int)
        accuracy = accuracy_score(labels_arr, all_preds_binary)
        auc = roc_auc_score(labels_arr, preds_arr) if len(np.unique(labels_arr)) > 1 else 0.0
        f1 = f1_score(labels_arr, all_preds_binary, zero_division=0.0)
        # Stashed for _current_selection_value: the parametric metrics
        # need the raw gathered (labels, probs), not a scalar already
        # reduced here. Post-gather under DDP -- the same population
        # val_acc/val_auc/val_f1 above were computed from -- so a
        # parametric metric is "computed once on the gathered
        # predictions" exactly like the others (see CLAUDE.md).
        self._last_val_labels = labels_arr
        self._last_val_probs = preds_arr

    # CL regression validation metrics
    if self.cl_regression_head is not None:
        if self.dist.enabled:
            avg_cl_loss = reduced["cl_loss"] / max(1.0, reduced["batches"])
        else:
            avg_cl_loss = tally.value("cl_loss") / max(1, len(self.val_loader))
        self.history["val_cl_loss"].append(avg_cl_loss)

    return avg_loss, accuracy, auc, f1

train

train(epochs: int, early_stopping_patience: int = 10) -> dict[str, Any]

Train model for multiple epochs.

Parameters:

Name Type Description Default
epochs int

Number of epochs to train

required
early_stopping_patience int

Stop if validation accuracy doesn't improve for N epochs (0 to disable)

10

Returns:

Type Description
dict[str, Any]

Training history dictionary

Source code in src/leech/training.py
def train(self, epochs: int, early_stopping_patience: int = 10) -> dict[str, Any]:
    """
    Train model for multiple epochs.

    Args:
        epochs: Number of epochs to train
        early_stopping_patience: Stop if validation accuracy doesn't improve for N epochs (0 to disable)

    Returns:
        Training history dictionary
    """
    # NOT reset here -- self.patience_counter carries over from a resumed
    # checkpoint (or starts at 0 from __init__ on a fresh Trainer), so
    # early stopping continues counting rather than getting a fresh
    # `early_stopping_patience` epochs on every retry of an interrupted run.
    total_epochs = max(0, epochs - self.start_epoch + 1)
    last_epoch = self.start_epoch - 1

    # If training already completed (resume past final epoch), save best and exit
    if self.start_epoch > epochs:
        logger.info(
            f"Training already complete (resumed at epoch {self.start_epoch - 1}, "
            f"requested {epochs}). Saving checkpoints and exiting."
        )
        self._finalize(last_epoch=self.start_epoch - 1)
        barrier(self.dist)
        return self.history

    # Create progress bars
    with Progress(
        SpinnerColumn(),
        TextColumn("[progress.description]{task.description}"),
        BarColumn(),
        TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
        TimeRemainingColumn(),
        console=console,
        disable=not self._is_main,
    ) as progress:
        epoch_task = progress.add_task("[cyan]Training epochs...", total=total_epochs)

        for epoch in range(self.start_epoch, epochs + 1):
            last_epoch = epoch
            # Re-seed the shared draw. Skipping this trains every epoch on
            # the same shard -- which converges, and reports metrics from a
            # world_size-th of the corpus.
            if self.dist.enabled:
                epoch_sampler = getattr(self.train_loader, "sampler", None)
                if hasattr(epoch_sampler, "set_epoch"):
                    epoch_sampler.set_epoch(epoch)
            # LR warmup. The cosine schedule folds warmup into its own
            # LambdaLR multiplier, so only the plateau/none paths need the
            # manual ramp here.
            if (
                self.scheduler_type != "cosine"
                and self.warmup_epochs > 0
                and epoch <= self.warmup_epochs
            ):
                warmup_lr = self.base_lr * (epoch / self.warmup_epochs)
                for param_group in self.optimizer.param_groups:
                    param_group["lr"] = warmup_lr

            # Adversarial lambda annealing (linear ramp)
            if self.adversarial_head is not None and self.adversarial_anneal_epochs > 0:
                progress_frac = min(1.0, epoch / self.adversarial_anneal_epochs)
                current_lambda = self.adversarial_lambda * progress_frac
                self.adversarial_head.set_lambda(current_lambda)

            # Create tasks for this epoch
            train_task = progress.add_task(
                f"[green]Epoch {epoch}/{epochs} - Training", total=len(self.train_loader)
            )

            # Train
            train_loss, train_acc = self.train_epoch(progress, train_task)
            self.history["train_loss"].append(train_loss)
            self.history["train_acc"].append(train_acc)

            progress.remove_task(train_task)

            # Validate
            if self.val_loader is not None:
                val_task = progress.add_task(
                    f"[yellow]Epoch {epoch}/{epochs} - Validation", total=len(self.val_loader)
                )
                val_loss, val_acc, val_auc, val_f1 = self.validate(progress, val_task)
                self.history["val_loss"].append(val_loss)
                self.history["val_acc"].append(val_acc)
                self.history["val_auc"].append(val_auc)
                self.history["val_f1"].append(val_f1)
                current_value = self._current_selection_value(val_acc, val_auc, val_f1)
                self.history["val_selection"].append(current_value)
                is_parametric_metric = self._checkpoint_metric not in (
                    "val_acc",
                    "val_f1",
                    "val_auc",
                )

                progress.remove_task(val_task)

                # LR scheduler step (only after warmup). For reduce_on_plateau
                # we step on the *selection metric*, not val_loss, so the
                # plateau detection matches what early-stopping and best-
                # model checkpointing react to. If val_loss were used while
                # selection runs off F1/AUC, LR can drop because loss
                # plateaued on easy examples even though the ranking metric
                # is still improving — burning the schedule prematurely.
                # The cosine LambdaLR owns warmup itself, so it steps every
                # epoch; plateau keeps the original post-warmup guard.
                if self.scheduler is not None and (
                    self.scheduler_type == "cosine" or epoch > self.warmup_epochs
                ):
                    old_lr = self.optimizer.param_groups[0]["lr"]
                    if self.scheduler_type == "reduce_on_plateau":
                        self.scheduler.step(-current_value)
                    else:
                        # Epoch-based schedulers (cosine, etc.)
                        self.scheduler.step()
                    new_lr = self.optimizer.param_groups[0]["lr"]
                    if new_lr != old_lr:
                        logger.info(f"LR reduced: {old_lr:.6f} -> {new_lr:.6f}")

                # Display metrics — [*] marks the checkpoint criterion
                lr_str = ""
                current_lr = self.optimizer.param_groups[0]["lr"]
                if current_lr != self.base_lr:
                    lr_str = f" LR: {current_lr:.6f}"
                acc_label = "Acc[*]" if self._checkpoint_metric == "val_acc" else "Acc"
                f1_label = "F1[*]" if self._checkpoint_metric == "val_f1" else "F1"
                auc_label = "AUC[*]" if self._checkpoint_metric == "val_auc" else "AUC"
                sel_str = (
                    f" | {self._checkpoint_metric}[*]: {current_value:.4f}"
                    if is_parametric_metric
                    else ""
                )
                adv_str = ""
                if self.adversarial_head is not None and self.history["train_adv_loss"]:
                    _adv_l = self.history["train_adv_loss"][-1]
                    _adv_a = self.history["train_adv_acc"][-1]
                    _lam = self.adversarial_head.grl.lambda_
                    adv_str = f" | Adv: L={_adv_l:.3f} Acc={_adv_a:.3f} λ={_lam:.3f}"
                cl_str = ""
                if self.cl_regression_head is not None and self.history["train_cl_loss"]:
                    _tcl = self.history["train_cl_loss"][-1]
                    _vcl = (
                        self.history["val_cl_loss"][-1] if self.history["val_cl_loss"] else 0.0
                    )
                    cl_str = f" | CL: train={_tcl:.4f} val={_vcl:.4f}"
                self._print(
                    f"[cyan]Epoch {epoch}/{epochs}[/cyan] | "
                    f"Train Loss: {train_loss:.4f} Acc: {train_acc:.4f} | "
                    f"Val Loss: {val_loss:.4f} {acc_label}: {val_acc:.4f} "
                    f"{f1_label}: {val_f1:.4f} {auc_label}: {val_auc:.4f}"
                    f"{sel_str}{lr_str}{adv_str}{cl_str}"
                )

                # Save best model per configured checkpoint metric
                improved = current_value > self.best_val_selection
                if improved:
                    self.best_val_acc = val_acc
                    self.best_val_f1 = val_f1
                    self.best_val_auc = val_auc
                    self.best_val_selection = current_value
                    self.best_epoch = epoch
                    self._best_model_state = copy.deepcopy(self.model.state_dict())
                    self.patience_counter = 0

                    if self.output_dir:
                        self.save_checkpoint("model_best.pt", epoch=epoch)
                        sel_note = (
                            f", {self._checkpoint_metric}: {current_value:.4f}"
                            if is_parametric_metric
                            else ""
                        )
                        self._print(
                            f"[bold green]✓ Saved best model "
                            f"(val_acc: {val_acc:.4f}, val_f1: {val_f1:.4f}, "
                            f"val_auc: {val_auc:.4f}{sel_note})[/bold green]"
                        )
                else:
                    self.patience_counter += 1

                # Early stopping (disabled if patience is 0)
                if (
                    early_stopping_patience > 0
                    and self.patience_counter >= early_stopping_patience
                ):
                    self._print(f"[yellow]Early stopping at epoch {epoch}[/yellow]")
                    break
            else:
                self._print(
                    f"[cyan]Epoch {epoch}/{epochs}[/cyan] | "
                    f"Train Loss: {train_loss:.4f} Acc: {train_acc:.4f}"
                )

            # Rolling resume checkpoint (issue #330): written every epoch,
            # after everything above (validation, best-model tracking, the
            # scheduler step) has updated for it, so it always reflects the
            # state the *next* epoch should start from. Deliberately not a
            # declared Snakemake output -- see `_finalize` -- so a rule
            # retry after a walltime kill still finds it on disk.
            if self.output_dir:
                self.save_checkpoint("model_resume.pt", epoch=epoch)

            progress.update(epoch_task, advance=1)

    # Save final model. The writers are no-ops off rank 0; the barrier is
    # what keeps a rank from tearing down its process group while rank 0 is
    # still inside a collective-free write the others would outlive.
    self._finalize(last_epoch=last_epoch)
    barrier(self.dist)

    return self.history

save_checkpoint

save_checkpoint(filename: str, epoch: int = 0) -> None

Save model checkpoint.

self.model is the unwrapped module even under DDP, so the keys are the single-GPU keys -- no module. prefix for a consumer to strip.

RNG/loader-generator state is per rank and gathered here, ahead of the _is_main early return below: gather_objects is a collective, and skipping it on the ranks that are about to return would hang the rank that does call it, waiting on peers that never arrive.

Source code in src/leech/training.py
def save_checkpoint(self, filename: str, epoch: int = 0) -> None:
    """Save model checkpoint.

    ``self.model`` is the unwrapped module even under DDP, so the keys are
    the single-GPU keys -- no ``module.`` prefix for a consumer to strip.

    RNG/loader-generator state is per rank and gathered here, ahead of the
    ``_is_main`` early return below: ``gather_objects`` is a collective,
    and skipping it on the ranks that are about to return would hang the
    rank that does call it, waiting on peers that never arrive.
    """
    rng_states = gather_objects(_capture_rng_state(), self.dist)
    loader_generator_state = (
        self.train_loader.generator.get_state()
        if self.train_loader.generator is not None
        else None
    )
    loader_generator_states = gather_objects(loader_generator_state, self.dist)

    if self.output_dir is None or not self._is_main:
        return

    checkpoint_path = self.output_dir / filename
    checkpoint: dict[str, Any] = {
        "model_state_dict": self.model.state_dict(),
        "best_val_acc": self.best_val_acc,
        "best_val_f1": self.best_val_f1,
        "best_val_auc": self.best_val_auc,
        "best_val_selection": self.best_val_selection,
        "checkpoint_metric": self._checkpoint_metric,
        "best_epoch": self.best_epoch,
        "epoch": epoch,
        "scheduler_state_dict": self.scheduler.state_dict() if self.scheduler else None,
        "scaler_state_dict": self.scaler.state_dict() if self.scaler else None,
        "best_model_state_dict": self._best_model_state,
        # Everything below is what makes this a valid --resume target
        # rather than just a snapshot of the weights (issue #330): enough
        # state that a resumed run is a continuation, not a warm start.
        "seed": self.seed,
        "patience_counter": self.patience_counter,
        "history": self.history,
        "recipe": _recipe_snapshot(self.cfg, self.model_type),
        "corpus": {
            "train": _corpus_fingerprint(self._train_data_path),
            "val": _corpus_fingerprint(self._val_data_path),
        },
        "rng_states": rng_states,
        "loader_generator_states": loader_generator_states,
    }
    if self._should_save_optimizer(epoch):
        checkpoint["optimizer_state_dict"] = self.optimizer.state_dict()
    if self.cl_regression_head is not None:
        checkpoint["cl_regression_head_state_dict"] = self.cl_regression_head.state_dict()
    if self.adversarial_head is not None:
        checkpoint["adversarial_head_state_dict"] = self.adversarial_head.state_dict()
    if self.clip_grad_fn is not None:
        checkpoint["clip_grad_buffer"] = self.clip_grad_fn.buffer
        checkpoint["clip_grad_index"] = self.clip_grad_fn.i
    _atomic_torch_save(checkpoint, checkpoint_path)

save_history

save_history() -> None

Save training history to JSON.

Source code in src/leech/training.py
def save_history(self) -> None:
    """Save training history to JSON."""
    if self.output_dir is None or not self._is_main:
        return

    history_path = self.output_dir / "metrics.json"
    with open(history_path, "w") as f:
        json.dump(self.history, f, indent=2)

    # Save summary (only if training occurred)
    if len(self.history["train_loss"]) == 0:
        return

    summary = {
        "best_val_acc": self.best_val_acc,
        "best_val_f1": self.best_val_f1,
        "best_val_auc": self.best_val_auc,
        "best_val_selection": self._serializable_best_val_selection(),
        "best_epoch": self.best_epoch,
        "checkpoint_metric": self._checkpoint_metric,
        "final_train_loss": self.history["train_loss"][-1],
        "final_train_acc": self.history["train_acc"][-1],
    }

    if self.val_loader is not None and len(self.history["val_loss"]) > 0:
        summary.update(
            {
                "final_val_loss": self.history["val_loss"][-1],
                "final_val_acc": self.history["val_acc"][-1],
                "final_val_auc": self.history["val_auc"][-1],
                "final_val_f1": self.history["val_f1"][-1],
            }
        )
        # Full binary metrics (accuracy/precision/recall/f1/auroc/auprc,
        # the threshold sweep, and -- whenever checkpoint_metric names one
        # -- the parametric low-FPR metric) for the LAST epoch's
        # validation set, the same "final" population the four fields
        # above already summarize. This is "val_metrics.json" (issue
        # #280): the validation half of "reports them ... so runs can be
        # compared after the fact" -- kept here in summary.json rather
        # than a new file, since it already plays that role for training.
        # Multiclass has no single positive-class score, so this is
        # binary-only, same as the parametric metrics themselves.
        if (
            self._num_out <= 2
            and self._last_val_labels is not None
            and self._last_val_probs is not None
        ):
            from leech.metrics import compute_metrics as _compute_binary_metrics

            summary["val_metrics"] = _compute_binary_metrics(
                self._last_val_labels,
                (self._last_val_probs > 0.5).astype(int),
                self._last_val_probs,
                checkpoint_metric=self._checkpoint_metric,
            )

    summary_path = self.output_dir / "summary.json"
    with open(summary_path, "w") as f:
        json.dump(summary, f, indent=2)

Training Functions

train_model

train_model(train_data_path: Path, val_data_path: Path | None, model_name: str, output_dir: Path, signal_len: int = 400, kmer_len: int = 11, epochs: int = 50, batch_size: int = 128, learning_rate: float = 0.001, device: str = 'cuda', seed: int | None = None, early_stopping_patience: int = 10, use_class_weights: bool = True, pos_weight: float | None = None, train_chunks: list[dict] | None = None, val_chunks: list[dict] | None = None, weight_decay: float = 0.0, max_grad_norm: float = 0.0, quantile_grad_clip: bool = False, grad_accum_split: int = 1, save_optim_every: int = 1, scheduler: str = 'none', scheduler_patience: int = 5, scheduler_factor: float = 0.5, warmup_epochs: int = 0, loss_type: str = 'bce', focal_gamma: float = 2.0, focal_neg_gamma: float | None = None, mixed_precision: bool = False, label_smoothing: float = 0.0, augment_jitter: float = 0.0, augment_scale_min: float = 1.0, augment_scale_max: float = 1.0, augment_time_mask_bases: int = 0, augment_time_mask_count: int = 1, augment_shift_max_bases: float = 0.0, augment_feature_noise_scale: float = 0.0, augment_time_stretch: tuple[float, float] = (1.0, 1.0), resume_from: Path | None = None, num_workers: int = 0, motif: str | None = None, motif_offset: int = 0, base_justify: str = 'center', seq_encoding: str = 'signal_kmer', signal_kmer_context: tuple[int, int] = (4, 4), allow_encoding_fallback: bool = True, left_context: int | None = None, right_context: int | None = None, strict_window: bool = False, balance_groups: bool = False, oversample_minority: bool = False, sample_weight_field: str | None = None, label_map: dict[str, int] | None = None, num_out: int = 1, adversarial_lambda: float = 0.0, adversarial_anneal_epochs: int = 0, confound: str | None = None, label_noise_rates: dict[str, float] | None = None, cl_regression: bool = False, cl_lambda: float = 1.0, signal_mode: str = 'both', checkpoint_metric: str = 'auto', standardize_features: bool = False, feature_channels: list[str] | None = None, gpus: int = 1, _dist: DistContext | None = None, cfg: TrainConfig | None = None, **model_kwargs: Any) -> dict[str, Any]

High-level training function.

Parameters:

Name Type Description Default
train_data_path Path

Path to training chunks (.npz)

required
val_data_path Path | None

Path to validation chunks (.npz)

required
model_name str

Model architecture name

required
output_dir Path

Output directory for models and logs

required
signal_len int

Signal length for model input

400
kmer_len int

K-mer length for model input

11
epochs int

Number of training epochs

50
batch_size int

Batch size

128
learning_rate float

Learning rate

0.001
device str

Device for training

'cuda'
seed int | None

Random seed (None = generate random seed)

None
early_stopping_patience int

Stop training if validation loss doesn't improve for N epochs

10
use_class_weights bool

Auto-compute class weights from training data (default: True)

True
pos_weight float | None

Manual positive class weight (overrides use_class_weights if provided)

None
train_chunks list[dict] | None

Pre-loaded training chunks (skips loading from train_data_path)

None
val_chunks list[dict] | None

Pre-loaded validation chunks (skips loading from val_data_path)

None
weight_decay float

L2 regularization weight (0 = disabled)

0.0
max_grad_norm float

Max gradient norm for clipping (0 = disabled)

0.0
quantile_grad_clip bool

Clip gradients at a quantile of recent norms (bonito ClipGrad)

False
grad_accum_split int

Sub-batches per optimizer step (1 = no accumulation)

1
save_optim_every int

Write optimizer state every N epochs (1 = every save)

1
scheduler str

LR scheduler type ("none" or "reduce_on_plateau")

'none'
scheduler_patience int

Epochs to wait before reducing LR

5
scheduler_factor float

Factor to reduce LR by

0.5
warmup_epochs int

Number of LR warmup epochs (0 = disabled)

0
loss_type str

Loss function type ("bce" or "focal")

'bce'
focal_gamma float

Focal loss gamma parameter

2.0
mixed_precision bool

Enable mixed precision training (CUDA only)

False
augment_jitter float

Signal jitter noise std dev (0 = disabled)

0.0
augment_scale_min float

Min random scale factor for signal augmentation

1.0
augment_scale_max float

Max random scale factor for signal augmentation

1.0
augment_time_stretch tuple[float, float]

(min, max) per-sample time-stretch factor range for the training dataset ((1.0, 1.0) = disabled). See LeechDataset's time_stretch_range for the exact per-channel rule; never applied to validation.

(1.0, 1.0)
resume_from Path | None

Path to checkpoint to resume training from

None
motif str | None

Motif used for chunk extraction (recorded in config for provenance)

None
motif_offset int

Offset within motif for focus base (recorded in config)

0
base_justify str

Signal justification within focus base (recorded in config)

'center'
seq_encoding str

Sequence encoding requested ("signal_kmer" or "base_onehot")

'signal_kmer'
gpus int

Data-parallel ranks for this run (1 = single device). --batch-size stays the GLOBAL batch and is split across them, so the recipe -- step count, LR schedule, accumulation arithmetic -- is unchanged.

1
_dist DistContext | None

Set by the spawned worker; callers pass gpus, never this.

None
allow_encoding_fallback bool

Permit a "signal_kmer" request to degrade to "base_onehot" when the corpus carries no base-to-signal maps. False raises instead; a corpus that carries them for only some chunks raises either way. However it resolves, the config records what was used, not what was asked for.

True
standardize_features bool

Compute per-channel feature mean/std once over the training corpus and freeze them into the feature branch's first layer as an affine transform (off by default). Only models that declare feature_mean/feature_std params accept this; requesting it for one that doesn't raises from get_model().

False
strict_window bool

Raise instead of zero-padding when left_context/ right_context reach outside the stored chunk (a corpus prepared with a narrower signal_context than this crop). Default False logs one warning for the whole dataset the first time it happens.

False
feature_channels list[str] | None

Channel ablation (issue #358 follow-up) -- select and order a SUBSET of the training corpus's recorded feature_channels list (prepare_config.json, falling back to the historical twelve when absent). Every requested name must be in the corpus's recorded list, checked here before any dataset is built; LeechDataset re-validates against the corpus's actual stored row count, which can be narrower than the recorded list (a kmer_* name recorded but never computed because no k-mer table was configured -- the same silent drop merge_feature_channels applies at prepare time). Applied identically to the validation corpus. None (default) uses every row the corpus has, exactly as before this existed. The checkpoint's config.json records this SELECTED list as feature_channels (what leech predict extracts) and the corpus's full recorded list separately as corpus_feature_channels, for provenance.

None
**model_kwargs Any

Additional model parameters (passed to model constructor)

{}

Returns:

Type Description
dict[str, Any]

Training history dictionary with metrics

Source code in src/leech/training.py
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
def train_model(
    train_data_path: Path,
    val_data_path: Path | None,
    model_name: str,
    output_dir: Path,
    signal_len: int = 400,
    kmer_len: int = 11,
    epochs: int = 50,
    batch_size: int = 128,
    learning_rate: float = 0.001,
    device: str = "cuda",
    seed: int | None = None,
    early_stopping_patience: int = 10,
    use_class_weights: bool = True,
    pos_weight: float | None = None,
    train_chunks: list[dict] | None = None,
    val_chunks: list[dict] | None = None,
    weight_decay: float = 0.0,
    max_grad_norm: float = 0.0,
    quantile_grad_clip: bool = False,
    grad_accum_split: int = 1,
    save_optim_every: int = 1,
    scheduler: str = "none",
    scheduler_patience: int = 5,
    scheduler_factor: float = 0.5,
    warmup_epochs: int = 0,
    loss_type: str = "bce",
    focal_gamma: float = 2.0,
    focal_neg_gamma: float | None = None,
    mixed_precision: bool = False,
    label_smoothing: float = 0.0,
    augment_jitter: float = 0.0,
    augment_scale_min: float = 1.0,
    augment_scale_max: float = 1.0,
    augment_time_mask_bases: int = 0,
    augment_time_mask_count: int = 1,
    augment_shift_max_bases: float = 0.0,
    augment_feature_noise_scale: float = 0.0,
    augment_time_stretch: tuple[float, float] = (1.0, 1.0),
    resume_from: Path | None = None,
    num_workers: int = 0,
    motif: str | None = None,
    motif_offset: int = 0,
    base_justify: str = "center",
    seq_encoding: str = "signal_kmer",
    signal_kmer_context: tuple[int, int] = (4, 4),
    allow_encoding_fallback: bool = True,
    left_context: int | None = None,
    right_context: int | None = None,
    strict_window: bool = False,
    balance_groups: bool = False,
    oversample_minority: bool = False,
    sample_weight_field: str | None = None,
    label_map: dict[str, int] | None = None,
    num_out: int = 1,
    adversarial_lambda: float = 0.0,
    adversarial_anneal_epochs: int = 0,
    confound: str | None = None,
    label_noise_rates: dict[str, float] | None = None,
    cl_regression: bool = False,
    cl_lambda: float = 1.0,
    signal_mode: str = "both",
    checkpoint_metric: str = "auto",
    standardize_features: bool = False,
    feature_channels: list[str] | None = None,
    gpus: int = 1,
    _dist: DistContext | None = None,
    cfg: TrainConfig | None = None,
    **model_kwargs: Any,
) -> dict[str, Any]:
    """
    High-level training function.

    Args:
        train_data_path: Path to training chunks (.npz)
        val_data_path: Path to validation chunks (.npz)
        model_name: Model architecture name
        output_dir: Output directory for models and logs
        signal_len: Signal length for model input
        kmer_len: K-mer length for model input
        epochs: Number of training epochs
        batch_size: Batch size
        learning_rate: Learning rate
        device: Device for training
        seed: Random seed (None = generate random seed)
        early_stopping_patience: Stop training if validation loss doesn't improve for N epochs
        use_class_weights: Auto-compute class weights from training data (default: True)
        pos_weight: Manual positive class weight (overrides use_class_weights if provided)
        train_chunks: Pre-loaded training chunks (skips loading from train_data_path)
        val_chunks: Pre-loaded validation chunks (skips loading from val_data_path)
        weight_decay: L2 regularization weight (0 = disabled)
        max_grad_norm: Max gradient norm for clipping (0 = disabled)
        quantile_grad_clip: Clip gradients at a quantile of recent norms (bonito ClipGrad)
        grad_accum_split: Sub-batches per optimizer step (1 = no accumulation)
        save_optim_every: Write optimizer state every N epochs (1 = every save)
        scheduler: LR scheduler type ("none" or "reduce_on_plateau")
        scheduler_patience: Epochs to wait before reducing LR
        scheduler_factor: Factor to reduce LR by
        warmup_epochs: Number of LR warmup epochs (0 = disabled)
        loss_type: Loss function type ("bce" or "focal")
        focal_gamma: Focal loss gamma parameter
        mixed_precision: Enable mixed precision training (CUDA only)
        augment_jitter: Signal jitter noise std dev (0 = disabled)
        augment_scale_min: Min random scale factor for signal augmentation
        augment_scale_max: Max random scale factor for signal augmentation
        augment_time_stretch: (min, max) per-sample time-stretch factor range
            for the training dataset ((1.0, 1.0) = disabled). See
            ``LeechDataset``'s ``time_stretch_range`` for the exact per-channel
            rule; never applied to validation.
        resume_from: Path to checkpoint to resume training from
        motif: Motif used for chunk extraction (recorded in config for provenance)
        motif_offset: Offset within motif for focus base (recorded in config)
        base_justify: Signal justification within focus base (recorded in config)
        seq_encoding: Sequence encoding requested ("signal_kmer" or "base_onehot")
        gpus: Data-parallel ranks for this run (1 = single device). --batch-size
            stays the GLOBAL batch and is split across them, so the recipe --
            step count, LR schedule, accumulation arithmetic -- is unchanged.
        _dist: Set by the spawned worker; callers pass gpus, never this.
        allow_encoding_fallback: Permit a "signal_kmer" request to degrade to
            "base_onehot" when the corpus carries no base-to-signal maps. False
            raises instead; a corpus that carries them for only some chunks
            raises either way. However it resolves, the config records what was
            used, not what was asked for.
        standardize_features: Compute per-channel feature mean/std once over
            the training corpus and freeze them into the feature branch's
            first layer as an affine transform (off by default). Only models
            that declare ``feature_mean``/``feature_std`` params accept this;
            requesting it for one that doesn't raises from ``get_model()``.
        strict_window: Raise instead of zero-padding when left_context/
            right_context reach outside the stored chunk (a corpus prepared
            with a narrower signal_context than this crop). Default False
            logs one warning for the whole dataset the first time it happens.
        feature_channels: Channel ablation (issue #358 follow-up) -- select
            and order a SUBSET of the training corpus's recorded
            ``feature_channels`` list (``prepare_config.json``, falling back
            to the historical twelve when absent). Every requested name must
            be in the corpus's recorded list, checked here before any
            dataset is built; ``LeechDataset`` re-validates against the
            corpus's actual stored row count, which can be narrower than the
            recorded list (a ``kmer_*`` name recorded but never computed
            because no k-mer table was configured -- the same silent drop
            ``merge_feature_channels`` applies at prepare time). Applied
            identically to the validation corpus. ``None`` (default) uses
            every row the corpus has, exactly as before this existed. The
            checkpoint's ``config.json`` records this SELECTED list as
            ``feature_channels`` (what ``leech predict`` extracts) and the
            corpus's full recorded list separately as
            ``corpus_feature_channels``, for provenance.
        **model_kwargs: Additional model parameters (passed to model constructor)

    Returns:
        Training history dictionary with metrics
    """
    # Captured before any other local binds, because under --gpus these exact
    # arguments are replayed in every spawned rank: the capture has to be the
    # call itself, not a reconstruction of it. cfg (None or a TrainConfig) is
    # captured as-is here and re-resolved identically in every rank below.
    _call_kwargs = dict(locals())
    _call_kwargs.pop("_dist", None)
    _call_kwargs.update(_call_kwargs.pop("model_kwargs", {}))

    # The recipe as one object (#270), same hybrid as Trainer.__init__: every
    # existing caller (43 test call sites, gridsearch.run_grid_point) passes
    # loose kwargs and keeps working unchanged -- a cfg is built from exactly
    # those kwargs and unpacked back into the same local names the rest of
    # this function already uses, so nothing below this block changes.
    # handle_train passes cfg directly and skips rebuilding it.
    #
    # MAINTENANCE: Trainer.__init__ (above, search "if cfg is None") has the
    # same build-then-unpack shape for a subset of these fields. A recipe
    # field added here should also be added there if Trainer needs it too --
    # see the note at that call site for why the two aren't one copy.
    if cfg is None:
        cfg = TrainConfig(
            epochs=epochs,
            batch_size=batch_size,
            early_stopping_patience=early_stopping_patience,
            use_class_weights=use_class_weights,
            pos_weight=pos_weight,
            loss_type=loss_type,
            focal_gamma=focal_gamma,
            focal_neg_gamma=focal_neg_gamma,
            label_smoothing=label_smoothing,
            mixed_precision=mixed_precision,
            checkpoint_metric=checkpoint_metric,
            num_out=num_out,
            signal_mode=signal_mode,
            standardize_features=standardize_features,
            feature_channels=feature_channels,
            motif=motif,
            motif_offset=motif_offset,
            base_justify=base_justify,
            seq_encoding=seq_encoding,
            signal_kmer_context=signal_kmer_context,
            allow_encoding_fallback=allow_encoding_fallback,
            left_context=left_context,
            right_context=right_context,
            strict_window=strict_window,
            balance_groups=balance_groups,
            oversample_minority=oversample_minority,
            sample_weight_field=sample_weight_field,
            label_map=label_map,
            confound=confound,
            label_noise_rates=label_noise_rates,
            optim=OptimConfig(
                learning_rate=learning_rate,
                weight_decay=weight_decay,
                max_grad_norm=max_grad_norm,
                quantile_grad_clip=quantile_grad_clip,
                grad_accum_split=grad_accum_split,
                save_optim_every=save_optim_every,
            ),
            scheduler=SchedulerConfig(
                scheduler_type=scheduler,
                scheduler_patience=scheduler_patience,
                scheduler_factor=scheduler_factor,
                warmup_epochs=warmup_epochs,
            ),
            augment=AugmentConfig(
                jitter=augment_jitter,
                scale_min=augment_scale_min,
                scale_max=augment_scale_max,
                time_mask_bases=augment_time_mask_bases,
                time_mask_count=augment_time_mask_count,
                shift_max_bases=augment_shift_max_bases,
                feature_noise_scale=augment_feature_noise_scale,
                time_stretch=augment_time_stretch,
            ),
            aux_head=AuxHeadConfig(
                adversarial_lambda=adversarial_lambda,
                adversarial_anneal_epochs=adversarial_anneal_epochs,
                cl_regression=cl_regression,
                cl_lambda=cl_lambda,
            ),
        )
    epochs = cfg.epochs
    batch_size = cfg.batch_size
    early_stopping_patience = cfg.early_stopping_patience
    use_class_weights = cfg.use_class_weights
    pos_weight = cfg.pos_weight
    loss_type = cfg.loss_type
    focal_gamma = cfg.focal_gamma
    focal_neg_gamma = cfg.focal_neg_gamma
    label_smoothing = cfg.label_smoothing
    mixed_precision = cfg.mixed_precision
    checkpoint_metric = cfg.checkpoint_metric
    num_out = cfg.num_out
    signal_mode = cfg.signal_mode
    standardize_features = cfg.standardize_features
    feature_channels = cfg.feature_channels
    motif = cfg.motif
    motif_offset = cfg.motif_offset
    base_justify = cfg.base_justify
    seq_encoding = cfg.seq_encoding
    signal_kmer_context = cfg.signal_kmer_context
    allow_encoding_fallback = cfg.allow_encoding_fallback
    left_context = cfg.left_context
    right_context = cfg.right_context
    strict_window = cfg.strict_window
    balance_groups = cfg.balance_groups
    oversample_minority = cfg.oversample_minority
    sample_weight_field = cfg.sample_weight_field
    label_map = cfg.label_map
    confound = cfg.confound
    label_noise_rates = cfg.label_noise_rates
    learning_rate = cfg.optim.learning_rate
    weight_decay = cfg.optim.weight_decay
    max_grad_norm = cfg.optim.max_grad_norm
    quantile_grad_clip = cfg.optim.quantile_grad_clip
    grad_accum_split = cfg.optim.grad_accum_split
    save_optim_every = cfg.optim.save_optim_every
    scheduler = cfg.scheduler.scheduler_type
    scheduler_patience = cfg.scheduler.scheduler_patience
    scheduler_factor = cfg.scheduler.scheduler_factor
    warmup_epochs = cfg.scheduler.warmup_epochs
    augment_jitter = cfg.augment.jitter
    augment_scale_min = cfg.augment.scale_min
    augment_scale_max = cfg.augment.scale_max
    augment_time_mask_bases = cfg.augment.time_mask_bases
    augment_time_mask_count = cfg.augment.time_mask_count
    augment_shift_max_bases = cfg.augment.shift_max_bases
    augment_feature_noise_scale = cfg.augment.feature_noise_scale
    augment_time_stretch = cfg.augment.time_stretch
    adversarial_lambda = cfg.aux_head.adversarial_lambda
    adversarial_anneal_epochs = cfg.aux_head.adversarial_anneal_epochs
    cl_regression = cfg.aux_head.cl_regression
    cl_lambda = cfg.aux_head.cl_lambda

    from leech.constants import generate_random_seed

    # Validate required provenance fields
    if motif is None:
        raise ValueError(
            "motif must not be None. Pass --motif on the CLI or motif= in code. "
            "A null motif causes inference to predict at every position, producing noise."
        )

    dist_ctx = _dist if _dist is not None else (context_from_env() or SINGLE)

    # Generate random seed if not provided
    if seed is None:
        seed = generate_random_seed()
        logger.info(f"Generated random seed: {seed}")
    else:
        logger.info(f"Using provided seed: {seed}")

    if gpus > 1 and not dist_ctx.enabled:
        # Parent process. The seed is resolved HERE and passed down: ranks that
        # each generated their own would disagree about the sampler draw and
        # record different provenance for what is one run.
        validate_request(
            gpus, device, has_inline_chunks=train_chunks is not None or val_chunks is not None
        )
        _call_kwargs["seed"] = seed
        return _spawn_train(gpus, device, _call_kwargs, output_dir)

    # Every rank is handed "cuda" and has to become "cuda:<local_rank>", or all
    # of them land on device 0 -- which fits, runs, and parallelises nothing.
    requested_device = device
    device = device_for(device, dist_ctx)

    # Save seed to output directory
    if dist_ctx.is_main:
        output_dir.mkdir(parents=True, exist_ok=True)
        seed_file = output_dir / "training_seed.txt"
        with open(seed_file, "w") as f:
            f.write(f"{seed}\n")
        logger.info(f"Saved seed to {seed_file}")

    # Set random seed
    torch.manual_seed(seed)
    np.random.seed(seed)

    # Override signal_len from asymmetric context if both provided
    if left_context is not None and right_context is not None:
        signal_len = left_context + right_context

    # Extract dwell_offset from model_kwargs (grid search param, not model init param)
    dwell_offset = model_kwargs.pop("dwell_offset", 0)
    dwell_template_table = model_kwargs.pop("dwell_template_table", None)

    # The dwell-template TSV is an input the checkpoint depends on at eval/
    # calibrate/predict time, but until now `config.json` recorded whatever
    # string the CLI got -- usually a repo-relative path -- and every loader
    # opened it relative to its OWN current working directory, not wherever
    # training happened to run. Copying it into the model directory (rank 0
    # only -- `output_dir` already exists from the seed-save above) makes the
    # checkpoint self-contained; `dwell_template_table_source`/`_sha256` keep
    # the original absolute path and a content fingerprint for provenance
    # even after the copy (issue #369). `LeechDataset` below still reads from
    # the CLI-given `dwell_template_table` (guaranteed to exist -- the CLI's
    # `click.Path(exists=True)` already checked it), not the copy; only what
    # `config.json` records changes.
    dwell_template_table_source: str | None = None
    dwell_template_table_sha256: str | None = None
    if dwell_template_table is not None and dist_ctx.is_main:
        _dwell_table_src = Path(dwell_template_table)
        dwell_template_table_source = str(_dwell_table_src.resolve())
        dwell_template_table_sha256 = hashlib.sha256(_dwell_table_src.read_bytes()).hexdigest()
        _dwell_table_dest = output_dir / "dwell_template_table.tsv"
        if _dwell_table_src.resolve() != _dwell_table_dest.resolve():
            shutil.copy2(_dwell_table_src, _dwell_table_dest)

    # Build augmentation config for training dataset.
    # Per-channel dicts (e.g. {"signal": 0.02, "signal_residual": 0.001})
    # can be provided via --model-config JSON; CLI flags give uniform scalars.
    augmentation = None
    jitter_cfg = model_kwargs.pop("augment_jitter", augment_jitter)
    scale_cfg = model_kwargs.pop("augment_scale_range", (augment_scale_min, augment_scale_max))

    has_jitter = (isinstance(jitter_cfg, dict) and any(v > 0 for v in jitter_cfg.values())) or (
        isinstance(jitter_cfg, (int, float)) and jitter_cfg > 0
    )
    has_scale = isinstance(scale_cfg, dict) or (
        isinstance(scale_cfg, (list, tuple)) and tuple(scale_cfg) != (1.0, 1.0)
    )

    if has_jitter or has_scale:
        augmentation = {
            "jitter_std": jitter_cfg,
            "scale_range": scale_cfg,
        }
        logger.info(f"Signal augmentation enabled: {augmentation}")

    # Build the confound encoder for adversarial training. The confound is
    # described declaratively (built-in alias or 'source:mapping[:table]' spec);
    # the encoder maps each chunk to an integer class for gradient reversal.
    confound_encoder = None
    adversarial_num_classes = 4  # default class count when adversarial is off

    if adversarial_lambda > 0 and confound:
        from leech.confounds import (
            build_confound_encoder,
            parse_confound_token,
        )

        spec = parse_confound_token(confound)

        # Collect this chunk field's values (needed for identity mappings).
        source_values: list | None = None
        if train_chunks is not None:
            source_values = [c.get(spec.source) for c in train_chunks]
        elif train_data_path is not None:
            # `with`: an unclosed np.load holds the zip handle for the whole
            # run, and the column it reads is only needed until the encoder
            # exists (see the `del` below).
            with np.load(train_data_path, allow_pickle=True) as _npz:
                # npz arrays are stored under the pluralized field name.
                for _key in (spec.source, f"{spec.source}s"):
                    if _key in _npz:
                        # The column, not `.tolist()`: boxing one Python string
                        # per chunk costs ~400 MB on a 6.7M-chunk corpus, and
                        # the encoder only needs the distinct values.
                        source_values = _npz[_key]
                        break

        # Resolve label_map for label-keyed confounds (e.g. disc_base).
        _lm = label_map
        if _lm is None and train_data_path is not None:
            _lm_path = train_data_path.parent / "label_map.json"
            if not _lm_path.exists():
                _lm_path = train_data_path.parent.parent / "label_map.json"
            if _lm_path.exists():
                with open(_lm_path) as f:
                    _lm = json.load(f)

        _data_dir = train_data_path.parent if train_data_path is not None else None
        confound_encoder = build_confound_encoder(
            spec,
            source_values=source_values,
            label_map=_lm,
            data_dir=_data_dir,
        )
        # The encoder keeps only the value -> class map, so the per-chunk
        # column is dead here. Dropping it matters: it is one Python string
        # per chunk (~400 MB on a 6.7M-chunk corpus) and both datasets are
        # built below.
        del source_values
        if confound_encoder is not None:
            adversarial_num_classes = confound_encoder.num_classes
        else:
            logger.warning(
                "Confound '%s' could not be built; adversarial training disabled", confound
            )
            adversarial_lambda = 0.0

    # Read the feature-channel list off the prepare sidecar now, before
    # constructing the datasets below that need it to key time-stretch's
    # dwell/dwell_log/dwell_mean rule by name (issue #358). A small, separate
    # read from the full `prepare_metadata` block further down (which needs
    # decisions this function makes in between) -- duplicating one dict
    # lookup is cheaper and lower-risk than reordering a multi-hundred-line
    # function.
    # The corpus's OWN motif_offset (not the possibly-unrelated --motif-offset
    # CLI value) is what a --dwell-template-table's `position` column has to
    # agree with (issue #364); falls back to the CLI value for a corpus
    # prepared before prepare_config.json existed.
    _train_feature_channels: list[str] | None = None
    _corpus_motif_offset = motif_offset
    if train_data_path is not None:
        _fc_sidecar_path = train_data_path.parent / "prepare_config.json"
        if _fc_sidecar_path.exists():
            with open(_fc_sidecar_path) as f:
                _prepare_sidecar = json.load(f)
            _train_feature_channels = _prepare_sidecar.get("feature_channels")
            _corpus_motif_offset = _prepare_sidecar.get("motif_offset", motif_offset)

    # Channel ablation (issue #358 follow-up): validate a requested
    # `--feature-channels` subset against the corpus's *recorded* list right
    # away, before either dataset is built -- a cheap, immediate failure for
    # a typo or a channel this corpus never recorded at all. `LeechDataset`
    # re-checks against the corpus's actual stored row count below (the
    # kmer_* carry-over), which this check cannot see since it never opens
    # the npz.
    _corpus_feature_channels = (
        list(_train_feature_channels)
        if _train_feature_channels is not None
        else list(DEFAULT_FEATURE_CHANNELS)
    )
    if feature_channels is not None:
        select_feature_channels(_corpus_feature_channels, feature_channels)
        logger.info(
            "Selecting %d of %d corpus feature channels: %s",
            len(feature_channels),
            len(_corpus_feature_channels),
            feature_channels,
        )

    # Create datasets (use pre-loaded chunks if provided)
    train_dataset = LeechDataset(
        chunk_path=train_data_path,
        signal_len=signal_len,
        kmer_len=kmer_len,
        model_type=model_name,
        dwell_offset=dwell_offset,
        chunks=train_chunks,
        augmentation=augmentation,
        seq_encoding=seq_encoding,
        signal_kmer_context=signal_kmer_context,
        allow_encoding_fallback=allow_encoding_fallback,
        left_context=left_context,
        right_context=right_context,
        strict_window=strict_window,
        confound_encoder=confound_encoder,
        label_noise_rates=label_noise_rates,
        cl_regression=cl_regression,
        signal_mode=signal_mode,
        time_mask_bases=augment_time_mask_bases,
        time_mask_count=augment_time_mask_count,
        shift_max_bases=augment_shift_max_bases,
        feature_noise_scale=augment_feature_noise_scale,
        time_stretch_range=augment_time_stretch,
        dwell_template_table=dwell_template_table,
        motif_offset=_corpus_motif_offset,
        standardize_features=standardize_features,
        feature_channel_names=_train_feature_channels,
        selected_feature_channels=feature_channels,
    )

    val_dataset = None
    if val_chunks is not None or val_data_path is not None:
        val_dataset = LeechDataset(
            chunk_path=val_data_path,
            signal_len=signal_len,
            kmer_len=kmer_len,
            model_type=model_name,
            dwell_offset=dwell_offset,
            chunks=val_chunks,
            seq_encoding=seq_encoding,
            signal_kmer_context=signal_kmer_context,
            allow_encoding_fallback=allow_encoding_fallback,
            left_context=left_context,
            right_context=right_context,
            strict_window=strict_window,
            confound_encoder=confound_encoder,
            label_noise_rates=label_noise_rates,
            cl_regression=cl_regression,
            signal_mode=signal_mode,
            dwell_template_table=dwell_template_table,
            motif_offset=_corpus_motif_offset,
            feature_channel_names=_train_feature_channels,
            selected_feature_channels=feature_channels,
        )

    # What the datasets actually yield, which is not always what was asked for:
    # a signal_kmer request over a corpus with no base-to-signal maps degrades
    # to base_onehot. That is a different model input, so the model has to be
    # built from it and the saved config has to record it — otherwise the
    # checkpoint claims an input it does not have, and #217's ONNX contract,
    # derived from the same config, inherits the lie (#230).
    effective_seq_encoding = train_dataset.effective_seq_encoding
    if effective_seq_encoding != seq_encoding:
        logger.warning(
            "Training with seq_encoding=%r, not the requested %r; "
            "the saved config records the effective value",
            effective_seq_encoding,
            seq_encoding,
        )
    if val_dataset is not None and val_dataset.effective_seq_encoding != effective_seq_encoding:
        raise ValueError(
            f"Train and validation data disagree on sequence encoding: "
            f"{effective_seq_encoding!r} vs {val_dataset.effective_seq_encoding!r}. "
            "One corpus carries base-to-signal maps and the other does not."
        )

    # One read of the label column, shared by the sampler, the num_out probe
    # and the class weights below.
    train_labels = _label_column(train_dataset.chunks)

    # Create data loaders
    effective_workers = resolve_dataloader_workers(num_workers, device, dist_ctx.world_size)

    # Seed the DataLoader generator from the run seed so shuffle order and each
    # worker's base seed are reproducible regardless of prior global-RNG use.
    loader_generator = torch.Generator()
    # Offset by rank so two ranks do not draw identical augmentation noise for
    # different data. At world 1 this is the seed itself.
    loader_generator.manual_seed(seed + dist_ctx.rank)

    loader_kwargs: dict = {
        "collate_fn": collate_fn,
        "num_workers": effective_workers,
        "generator": loader_generator,
    }
    if device != "cpu":
        loader_kwargs["pin_memory"] = True
    if effective_workers > 0:
        loader_kwargs["persistent_workers"] = True
        loader_kwargs["prefetch_factor"] = 4
        loader_kwargs["worker_init_fn"] = _seed_worker

    # Cap batch_size so drop_last doesn't discard all data
    effective_batch_size = min(batch_size, len(train_dataset))
    if effective_batch_size < batch_size:
        logger.warning(
            f"Batch size {batch_size} > dataset size {len(train_dataset)}, "
            f"reducing to {effective_batch_size}"
        )

    # --batch-size is the GLOBAL batch and is split across ranks. The PyTorch
    # convention is the opposite -- per-rank, effective batch grows with the
    # GPU count -- and it is wrong for a run that has to stay comparable with
    # the arms already measured: splitting leaves the optimizer-step count, the
    # epoch-indexed LR schedule and the accumulation arithmetic exactly where
    # they are, so the same command line means the same recipe at any --gpus.
    per_rank_batch_size = effective_batch_size // dist_ctx.world_size
    if per_rank_batch_size < 1:
        raise ValueError(
            f"--batch-size {effective_batch_size} cannot be split across {dist_ctx.world_size} "
            "ranks; it is the global batch, not the per-rank one."
        )
    if dist_ctx.enabled:
        logger.info(
            f"Global batch {per_rank_batch_size * dist_ctx.world_size} = "
            f"{per_rank_batch_size} per rank x {dist_ctx.world_size} ranks"
        )

    # Validate mutually exclusive sampling strategies
    _n_sampling_strategies = sum(
        [balance_groups, oversample_minority, sample_weight_field is not None]
    )
    if _n_sampling_strategies > 1:
        raise ValueError(
            "--balance-groups, --oversample-minority and --sample-weight-field "
            "are mutually exclusive. Use --balance-groups to equalize source "
            "groups, --oversample-minority to equalize class labels, or "
            "--sample-weight-field FIELD to equalize any other chunk metadata "
            "field (e.g. 'junction_indel')."
        )

    # Build balanced sampler if requested
    # Both sampler strategies want the same two things -- a count per category
    # and a weight per chunk -- and np.unique returns both from one pass over
    # the column. The four passes this replaces each built a row view per
    # chunk, before a single batch had been loaded.
    sample_weights: np.ndarray | None = None
    if balance_groups:
        # Compute per-chunk weights so each source group is equally represented
        codes, group_names, group_counts = _source_group_counts(train_dataset.chunks)

        if len(group_names) > 1:
            sample_weights = (1.0 / group_counts)[codes]
            logger.info(f"Balanced sampling enabled across {len(group_names)} source groups:")
            for rank in np.argsort(-group_counts, kind="stable"):
                count = int(group_counts[rank])
                logger.info(f"  {group_names[rank]}: {count} chunks, weight={1.0 / count:.6f}")
        else:
            logger.warning(
                f"balance_groups enabled but only 1 source group found "
                f"({group_names}). Falling back to shuffle."
            )
    elif oversample_minority:
        # Compute per-sample weights inversely proportional to class frequency
        codes, class_labels, label_counts = _categorical_codes(train_labels)

        if len(class_labels) > 1:
            sample_weights = (1.0 / label_counts)[codes]
            logger.info(f"Minority oversampling enabled across {len(class_labels)} classes:")
            for lbl, count in sorted(
                zip(class_labels.tolist(), label_counts.tolist(), strict=True)
            ):
                logger.info(f"  class {lbl}: {count} chunks, weight={1.0 / count:.6f}")
        else:
            logger.warning(
                "oversample_minority enabled but only 1 class found. Falling back to shuffle."
            )
    elif sample_weight_field is not None:
        # Generic inverse-frequency weighting by any chunk metadata field --
        # the mechanism --balance-groups is a fixed instance of. Introduced
        # for issue #282's junction_indel: grouping by the field's exact
        # values upweights every disrupted indel relative to the dominant
        # exact-match ("0") group.
        codes, group_names, group_counts = _field_group_counts(
            train_dataset.chunks, sample_weight_field
        )

        if len(group_names) > 1:
            sample_weights = (1.0 / group_counts)[codes]
            logger.info(
                f"Sample weighting enabled across {len(group_names)} values of "
                f"'{sample_weight_field}':"
            )
            for rank in np.argsort(-group_counts, kind="stable"):
                count = int(group_counts[rank])
                logger.info(f"  {group_names[rank]}: {count} chunks, weight={1.0 / count:.6f}")
        else:
            logger.warning(
                f"--sample-weight-field {sample_weight_field!r} enabled but only "
                f"1 distinct value found ({group_names}). Falling back to shuffle."
            )

    # One place decides the training sampler, because the distributed case has
    # to be a SHARD of the same draw rather than a second draw of its own.
    # Handing WeightedRandomSampler to N ranks gives every rank the same
    # oversampled indices: the run converges, reports plausible metrics, and has
    # trained on world_size copies of one shard, with nothing raised.
    train_sampler: Sampler | None = None
    if sample_weights is not None:
        if dist_ctx.enabled:
            train_sampler = DistributedWeightedSampler(
                sample_weights,
                num_samples=len(train_dataset),
                num_replicas=dist_ctx.world_size,
                rank=dist_ctx.rank,
                seed=seed,
            )
        else:
            train_sampler = WeightedRandomSampler(
                sample_weights, num_samples=len(train_dataset), replacement=True
            )
    elif dist_ctx.enabled:
        train_sampler = DistributedSampler(
            train_dataset,
            num_replicas=dist_ctx.world_size,
            rank=dist_ctx.rank,
            shuffle=True,
            seed=seed,
            drop_last=True,
        )

    # Use drop_last=True for training to avoid BatchNorm issues with batch_size=1
    train_loader = DataLoader(
        train_dataset,
        batch_size=per_rank_batch_size,
        shuffle=(train_sampler is None),
        sampler=train_sampler,
        drop_last=True,
        **loader_kwargs,
    )

    val_loader = None
    if val_dataset is not None:
        # Validation goes through `resolve_dataloader_workers` like training and
        # test, EXCEPT when the dataset fell back to per-chunk lists.
        #
        # The old comment here said workers "add memory overhead without
        # benefit" because validation `__getitem__` is trivially fast. The first
        # half is conditional and the second half is wrong. `__getitem__` being
        # cheap does not mean one process can saturate a GPU: collate, pin,
        # host-to-device and the forward pass all serialize onto that core. On a
        # 1,176,763-chunk binary val set that cost ~5 minutes of near-idle GPU
        # at every epoch boundary -- ~75 min per 15-epoch run -- which is the
        # same failure as `eval test` in #205, and #206 fixed only that one.
        #
        # The memory half is real but narrower than a blanket 0. `LeechDataset`
        # stacks into contiguous tensors precisely so a fork COW-shares the
        # buffers; it is only the `_try_stack` list fallback (inconsistent
        # per-chunk shapes) where each worker faults N PyObject headers into
        # private copies and multiplies peak RSS. So keep 0 exactly there, and
        # let every other case use workers.
        val_loader_kwargs: dict = {
            "collate_fn": collate_fn,
            "num_workers": resolve_val_dataloader_workers(
                val_dataset, num_workers, device, dist_ctx.world_size
            ),
        }
        if device != "cpu":
            val_loader_kwargs["pin_memory"] = True
        if dist_ctx.enabled:
            # Unpadded, unlike DistributedSampler: its repeated samples would be
            # counted twice in every validation metric.
            val_loader_kwargs["sampler"] = DistributedEvalSampler(
                len(val_dataset), num_replicas=dist_ctx.world_size, rank=dist_ctx.rank
            )
        val_loader = DataLoader(
            val_dataset,
            batch_size=batch_size,
            shuffle=False,
            **val_loader_kwargs,
        )

    # num_features and signal_channels come straight from the dataset's own
    # state -- it already computed both while pre-tensorizing (#272 item 4).
    # Drawing a batch to learn a shape spawns persistent DataLoader workers
    # and, under a weighted sampler, one draw from the multinomial (a
    # 6.7M-way draw on the production corpus) purely to inspect .shape.
    if train_dataset._needs_features:
        if train_dataset._features_tensor is not None:
            num_features = train_dataset._features_tensor.shape[1]
        elif train_dataset._features:
            # Degraded to per-chunk list storage (_TensorFill falls back here
            # when a chunk's feature shape disagrees with the first one) --
            # the tensor branch above is empty in this state even though the
            # corpus genuinely has features, so this is not the "no features"
            # case. Each item is (num_features, feat_width).
            num_features = train_dataset._features[0].shape[0]
        else:
            num_features = 1
    else:
        num_features = 1
    signal_in_channels = train_dataset.signal_channels

    # Per-channel feature standardization (#283): the dataset already
    # computed the corpus-wide mean/std (or disabled itself and warned if it
    # couldn't); read the result back rather than recomputing it. Lists, not
    # tensors, since these flow into get_model() kwargs and config.json --
    # both need JSON-serializable values.
    feature_mean_list: list[float] | None = None
    feature_std_list: list[float] | None = None
    if standardize_features and train_dataset.feature_mean is not None:
        feature_mean_list = train_dataset.feature_mean.tolist()
        feature_std_list = train_dataset.feature_std.tolist()
    elif standardize_features and train_dataset._needs_features:
        # The dataset already logged why (a shape mismatch across chunks) and
        # disabled itself; this just makes sure the run-level log says so too,
        # since config.json below will now (correctly) record False instead
        # of the request.
        logger.warning(
            "standardize_features was requested but the dataset could not compute "
            "feature_mean/feature_std (see its own warning above for why); "
            "config.json will record standardize_features=False, matching what "
            "actually happened rather than what was asked for."
        )
    # What actually got applied, not what was requested -- same reasoning as
    # effective_seq_encoding: a config.json that claims standardization was
    # used while feature_mean/feature_std are null is a checkpoint nobody can
    # audit afterwards (#283).
    effective_standardize_features = feature_mean_list is not None

    # Auto-detect num_out from training data when not explicitly set
    if num_out <= 1:
        max_label = int(train_labels.max())
        if max_label > 1:
            num_out = max_label + 1
            logger.info(f"Auto-detected multi-class: num_out={num_out}")
            # Load label_map from sidecar if available
            if label_map is None:
                label_map_path = train_data_path.parent / "label_map.json"
                if not label_map_path.exists():
                    # k-fold: data is in fold_N/ subdir, label_map is one level up
                    label_map_path = train_data_path.parent.parent / "label_map.json"
                if label_map_path.exists():
                    with open(label_map_path) as f:
                        label_map = json.load(f)
                    logger.info(f"Loaded label_map from {label_map_path}: {label_map}")

    # Compute class weights if requested
    pos_weight_tensor = None
    if pos_weight is not None:
        # Manual pos_weight provided
        pos_weight_tensor = torch.tensor([pos_weight], dtype=torch.float32)
        logger.info(f"Using manual pos_weight={pos_weight:.4f}")
    elif use_class_weights:
        # Auto-compute from training data
        pos_weight_tensor = compute_class_weights(train_labels)

    # Create model
    # Only pass num_features to models that need it
    model_init_kwargs = {
        "signal_len": signal_len,
        "kmer_len": kmer_len,
        "seq_encoding": effective_seq_encoding,
        "signal_kmer_context": signal_kmer_context,
        **model_kwargs,
    }
    model_init_kwargs["num_features"] = num_features

    # All models accept signal_in_channels for multi-channel signal input
    model_init_kwargs["signal_in_channels"] = signal_in_channels

    model_init_kwargs["num_out"] = num_out

    # Only added when requested: a model that hasn't declared feature_mean/
    # feature_std params raises from get_model() below, same as any other
    # unsupported --model-config override -- fail loud rather than silently
    # training unstandardized.
    if feature_mean_list is not None:
        model_init_kwargs["feature_mean"] = feature_mean_list
        model_init_kwargs["feature_std"] = feature_std_list

    model = get_model(model_name, **model_init_kwargs)

    # Enable cuDNN autotuner for fixed-size inputs (finds fastest conv algorithms)
    # plus TF32 matmuls (faster LSTM/attention/linear on Ampere+), matching the
    # eval/inference paths.
    if device != "cpu":
        torch.backends.cudnn.benchmark = True
        torch.set_float32_matmul_precision("high")
        logger.info("cuDNN benchmark + TF32 matmul enabled")

    # Compile model with torch.compile for graph-level optimizations (PyTorch 2+).
    # dynamic=False (#272 item 2): the default dynamic=None auto-detects a
    # dynamic batch dimension the first time it sees two different shapes,
    # and val_loader has no drop_last (a smaller last batch is correct there
    # -- dropping validation rows would corrupt every metric), so epoch 1's
    # validation pass marks the batch dim dynamic and the *training* forward
    # from epoch 2 on runs the slower dynamic-shape graph, even though
    # training's own batches are all one size (drop_last=True). dynamic=False
    # keeps every shape it sees compiled statically -- val's tail batch just
    # costs one extra compile for its own shape, once, rather than
    # de-optimizing every training step after it. Verify with
    # TORCH_LOGS=recompiles.
    if device != "cpu" and hasattr(torch, "compile"):
        try:
            model = torch.compile(model, dynamic=False)
            logger.info("torch.compile enabled")
        except Exception as e:
            logger.warning(f"torch.compile failed, falling back to eager mode: {e}")

    # Auto-detect cross-entropy models (num_out > 1)
    if num_out > 1 and loss_type != "cross_entropy":
        loss_type = "cross_entropy"
        logger.info(f"Model {model_name} has num_out={num_out}, switching to cross_entropy loss")

    # Introspect feature_start/feature_end from the training corpus.
    #
    # Resolved from the whole corpus (`train_dataset.chunks`, a ChunkTable
    # when one is in use), not chunk 0 -- reading a single row and trusting it
    # for the run is exactly the failure mode issue #230 fixed for
    # seq_encoding, generalized here to the feature window (issue #269).
    # `feature_window_from_metadata` raises if the corpus disagrees with
    # itself; when `train_dataset.chunks` is a plain list (legacy in-memory
    # path) it falls back to chunk 0, same as before.
    _kmer_context = kmer_len // 2
    _window_source = (
        train_dataset.chunks
        if isinstance(train_dataset.chunks, ChunkTable)
        else train_dataset.chunks[0]
    )
    # For a mapping source (the legacy row-only path), the resolver already
    # derives `feature_end` from the chunk's own feature array when only
    # `dwell_margin_right` is stored; a ChunkTable has no single feature array
    # to take a width from, so that one fallback is table-only unavailable and
    # `feature_end` comes back None in that corner case.
    _feature_start, _feature_end = feature_window_from_metadata(_window_source, _kmer_context)
    if _feature_start is None:
        _feature_start = -_kmer_context
    if _feature_end is None:
        _feature_end = _kmer_context

    # Read preparation config sidecar if available (for provenance in config.json)
    prepare_metadata: dict[str, Any] = {}
    _sidecar_path = train_data_path.parent / "prepare_config.json"
    if _sidecar_path.exists():
        with open(_sidecar_path) as f:
            prepare_metadata = json.load(f)
        logger.info(f"Read preparation metadata from {_sidecar_path}")
    else:
        # Use correct defaults for old data without sidecar
        prepare_metadata = {
            "anchor": "reference",
            "signal_norm": "median_mad",
            "reverse_signal": True,
            "refine_signal_map": True,
            "motif_reference": "fasta",
        }
        logger.info("No prepare_config.json found, using correct defaults for preparation metadata")

    # Save config
    if dist_ctx.is_main:
        output_dir.mkdir(parents=True, exist_ok=True)
    config = {
        "model_name": model_name,
        "signal_len": signal_len,
        "kmer_len": kmer_len,
        "num_features": num_features,
        "signal_in_channels": signal_in_channels,
        "dwell_offset": dwell_offset,
        "feature_start": _feature_start,
        "feature_end": _feature_end,
        "motif": motif,
        "motif_offset": motif_offset,
        "base_justify": base_justify,
        "left_context": left_context,
        "right_context": right_context,
        # Whether this run was guarded against silently zero-padding a crop
        # that overran the stored corpus (#255) -- without this, two
        # checkpoints with identical left_context/right_context but different
        # strict_window are indistinguishable in config.json, so nothing
        # downstream can tell whether a run was actually protected or merely
        # happened not to trigger the mismatch.
        "strict_window": strict_window,
        # The effective encoding, not the requested one: a checkpoint that does
        # not record what it trained on cannot be audited after the fact (#230).
        "seq_encoding": effective_seq_encoding,
        "signal_kmer_context": list(signal_kmer_context),
        "epochs": epochs,
        "batch_size": batch_size,
        "learning_rate": learning_rate,
        "device": requested_device,
        "gpus": dist_ctx.world_size,
        "seed": seed,
        "use_class_weights": use_class_weights,
        "pos_weight": pos_weight
        if pos_weight is not None
        else (pos_weight_tensor.tolist() if pos_weight_tensor is not None else None),
        "weight_decay": weight_decay,
        "max_grad_norm": max_grad_norm,
        "quantile_grad_clip": quantile_grad_clip,
        "grad_accum_split": grad_accum_split,
        "save_optim_every": save_optim_every,
        "scheduler": scheduler,
        "scheduler_patience": scheduler_patience,
        "scheduler_factor": scheduler_factor,
        "warmup_epochs": warmup_epochs,
        "loss_type": loss_type,
        "num_out": num_out,
        "focal_gamma": focal_gamma,
        "focal_neg_gamma": focal_neg_gamma,
        "mixed_precision": mixed_precision,
        "label_smoothing": label_smoothing,
        "augment_jitter": jitter_cfg,
        "augment_scale_min": augment_scale_min,
        "augment_scale_max": augment_scale_max,
        "augment_scale_range": scale_cfg if isinstance(scale_cfg, dict) else None,
        "augment_time_mask_bases": augment_time_mask_bases,
        "augment_time_mask_count": augment_time_mask_count,
        "augment_shift_max_bases": augment_shift_max_bases,
        "augment_feature_noise_scale": augment_feature_noise_scale,
        "augment_time_stretch_min": augment_time_stretch[0],
        "augment_time_stretch_max": augment_time_stretch[1],
        "balance_groups": balance_groups,
        "sample_weight_field": sample_weight_field,
        "label_map": label_map,
        "adversarial_lambda": adversarial_lambda,
        "adversarial_anneal_epochs": adversarial_anneal_epochs,
        "confound": confound,
        # Recorded verbatim (not resolved against the corpus) -- predict never
        # reads this back; it is provenance for what the training run applied.
        "label_noise_rates": label_noise_rates,
        "cl_regression": cl_regression,
        "cl_lambda": cl_lambda,
        "signal_mode": signal_mode,
        "checkpoint_metric": checkpoint_metric,
        "standardize_features": effective_standardize_features,
        # Only present when standardize_features actually computed them --
        # _instantiate_model (predict/eval/bundle/onnx_export) reconstructs
        # the model from these two fields with no extra code: any TOML
        # config that declares feature_mean/feature_std params picks them
        # straight up from config.json (see model_loading._instantiate_model
        # and config_loader.resolve_params).
        "feature_mean": feature_mean_list,
        "feature_std": feature_std_list,
        # The bare filename inside output_dir (issue #369), not the CLI's
        # original path -- every loader resolves this against the checkpoint
        # directory via `model_loading.resolve_dwell_template_path`.
        "dwell_template_table": "dwell_template_table.tsv" if dwell_template_table else None,
        "dwell_template_table_source": dwell_template_table_source,
        "dwell_template_table_sha256": dwell_template_table_sha256,
        # The table's OWN recorded build provenance (issue #364), not this
        # run's motif/motif_offset above -- None when the table predates that
        # convention. `check_dwell_template_motif_offset` already refused a
        # recorded mismatch before training started; recording it here lets
        # predict re-check it against a table that may have changed on disk
        # since, and lets an old checkpoint be audited without the TSV at hand.
        "dwell_template_motif_offset": train_dataset.dwell_template_motif_offset,
        "dwell_template_motif": train_dataset.dwell_template_motif,
        # The table's own covered [min_pos, max_pos] range, how many of this
        # run's feature-window columns fall outside it (constant ratio 1.0),
        # and every "# key: value" header line the table carried, verbatim --
        # issue #367. All None/{} when no template is configured.
        "dwell_template_positions": (
            list(train_dataset.dwell_template_positions)
            if train_dataset.dwell_template_positions is not None
            else None
        ),
        "dwell_template_uncovered_columns": train_dataset.dwell_template_uncovered_columns,
        "dwell_template_header": train_dataset.dwell_template_header or None,
        # Preparation metadata (from prepare_config.json sidecar)
        "reference_fasta": prepare_metadata.get("reference_fasta"),
        "anchor": prepare_metadata.get("anchor", "reference"),
        "signal_norm": prepare_metadata.get("signal_norm", "median_mad"),
        "reverse_signal": prepare_metadata.get("reverse_signal", True),
        "refine_signal_map": prepare_metadata.get("refine_signal_map", True),
        "refine_scale_iters": prepare_metadata.get("refine_scale_iters", 2),
        "motif_reference": prepare_metadata.get("motif_reference", "fasta"),
        "pa_mean": prepare_metadata.get("pa_mean"),
        "pa_stdev": prepare_metadata.get("pa_stdev"),
        "skip_motif_indels": prepare_metadata.get("skip_motif_indels", False),
        # Which reads the corpus was built from. `predict` must apply the same
        # rule or it scores a different population than the model was trained
        # on -- on aminoacyl-tRNA the adduct mis-calls the CCA junction, and
        # requiring a clean query mapping drops 28% of charged reads against
        # 6% of uncharged. See ReferenceMotifSearcher.
        "require_query_mapping": prepare_metadata.get("require_query_mapping", True),
        "refine_half_bandwidth": prepare_metadata.get(
            "refine_half_bandwidth", DEFAULT_REFINE_HALF_BANDWIDTH
        ),
        "refine_kmer_center_idx": prepare_metadata.get("refine_kmer_center_idx", -1),
        "recover_softclip_signal": prepare_metadata.get("recover_softclip_signal", False),
        # Focus-relative sequence masking (leech#256), auto-carried from the
        # prepare sidecar -- predict must apply the same mask a live chunk
        # was extracted with, or it feeds the model real tRNA-identity bases
        # it never saw in training. No `model train` CLI flag: it is baked
        # into the corpus at `data prepare` time, not chosen at train time.
        "mask_seq_side": prepare_metadata.get("mask_seq_side"),
        # The recorded feature-channel list (issue #358), auto-carried from
        # the prepare sidecar so `leech predict` extracts exactly the rows
        # this checkpoint was trained on. A config lacking the key (a
        # sidecar older than #358, or no sidecar at all) means the historical
        # twelve -- the same fallback pattern as `DEFAULT_SEQ_ENCODING_FALLBACK`.
        #
        # Channel ablation (issue #358 follow-up): when `--feature-channels`
        # selected a SUBSET, that selection -- not the corpus's full list --
        # is what gets recorded here, since this is exactly the list
        # `leech predict` extracts. The corpus's full recorded list is kept
        # alongside it, unconditionally, as `corpus_feature_channels` (never
        # read back by predict) purely for provenance -- "what could this
        # checkpoint have used" if a later run wants to try a different
        # subset without re-preparing.
        "feature_channels": (
            list(feature_channels)
            if feature_channels is not None
            else prepare_metadata.get("feature_channels", list(DEFAULT_FEATURE_CHANNELS))
        ),
        "corpus_feature_channels": prepare_metadata.get(
            "feature_channels", list(DEFAULT_FEATURE_CHANNELS)
        ),
        "kmer_table_sha256": prepare_metadata.get("kmer_table_sha256"),
        # Base-defined signal window (issue #278), carried through so
        # `predict` re-derives the same window `data prepare` cut; `None`
        # for a sample-context corpus. `signal_len` above already reflects
        # the corpus's actual stored width (introspected, not read from this
        # sidecar), which is the fixed emitted width in either mode.
        "signal_context_bases": prepare_metadata.get("signal_context_bases"),
        # Provenance
        "leech_version": leech.__version__,
        "git_commit": leech._get_git_revision(),
        **model_kwargs,
    }

    if dist_ctx.is_main:
        with open(output_dir / "config.json", "w") as f:
            json.dump(config, f, indent=2)

    # Create trainer. cfg carries the recipe (learning_rate, scheduler,
    # augmentation, aux-head lambdas, ...); the rest are runtime objects cfg
    # doesn't describe, plus num_out, which may have been auto-detected from
    # the data above and so can differ from cfg.num_out.
    trainer = Trainer(
        model=model,
        model_type=model_name,
        train_loader=train_loader,
        val_loader=val_loader,
        device=device,
        output_dir=output_dir,
        pos_weight=pos_weight_tensor,
        resume_checkpoint=resume_from,
        num_out=num_out,
        adversarial_num_classes=adversarial_num_classes,
        dist=dist_ctx,
        cfg=cfg,
        seed=seed,
        train_data_path=train_data_path,
        val_data_path=val_data_path,
    )

    # A resumed checkpoint may carry a different seed than the one generated
    # or passed above (training_seed.txt and config.json were already written
    # from `seed`, before the checkpoint -- and its RNG states -- were
    # loaded). Rewrite both so they report the seed this run actually ran
    # under, not a value that was immediately superseded.
    if dist_ctx.is_main and trainer.seed is not None and trainer.seed != seed:
        seed_file = output_dir / "training_seed.txt"
        with open(seed_file, "w") as f:
            f.write(f"{trainer.seed}\n")
        config["seed"] = trainer.seed
        with open(output_dir / "config.json", "w") as f:
            json.dump(config, f, indent=2)
        logger.info(f"Resumed under seed={trainer.seed}; updated {seed_file} and config.json")

    # Train
    history = trainer.train(epochs=epochs, early_stopping_patience=early_stopping_patience)

    return history

Example Usage

Python
from leech.training import Trainer
from leech.models import get_model
from leech.dataset import LeechDataset
from torch.utils.data import DataLoader

# Prepare data
train_dataset = LeechDataset("train_chunks.json")
val_dataset = LeechDataset("val_chunks.json")

train_loader = DataLoader(train_dataset, batch_size=128, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=128)

# Get model
model = get_model("ConvLSTMDwell")

# Create trainer
trainer = Trainer(
    model=model,
    train_loader=train_loader,
    val_loader=val_loader,
    learning_rate=0.001,
    weight_decay=0.0001,
    device="cuda",
    output_dir="models/"
)

# Train
history = trainer.train(
    epochs=50,
    early_stopping_patience=5
)

# Access training history
print(f"Best validation loss: {min(history['val_loss'])}")

Multi-GPU training

leech model train --gpus N runs N data-parallel ranks on one node. It is opt-in and single-node; --gpus 1 (the default) is the single-device path unchanged.

Shell
# 4 A30s of one node; --gres=gpu:4 and ~4x the memory of a single-GPU run
uv run leech model train --train-data chunks/train.npz --val-data chunks/val.npz \
  --model TCNDwellResidualLN --output-dir models/ \
  --batch-size 1024 --gpus 4

Two things to know before using it:

  • --batch-size is the global batch and is split across ranks. With --batch-size 1024 --gpus 4 each rank sees 256. The optimizer-step count, the LR schedule and the gradient-accumulation arithmetic are therefore identical at any --gpus, so a multi-GPU run stays comparable with arms already measured. (This is the opposite of the usual PyTorch convention, where the flag is per-rank and the effective batch grows with the GPU count.)
  • Memory scales with the rank count. Each rank loads its own copy of the corpus, so a run whose single-GPU peak is ~40 GiB needs ~160 GiB at --gpus 4. Size the job's --mem accordingly; the second rank is OOM-killed during its load otherwise.

The checkpoint a multi-GPU run writes is byte-compatible with a single-GPU one (same keys, no module. prefix), so leech model export, bundling and inference are unaffected.

Label-noise-aware loss

--loss noise_corrected_bce is for labels that are enrichments with a known, measured impurity rather than per-read ground truth -- e.g. a positive block that is only ~90% pure because the enrichment chemistry (or an upstream barcode/demux step) mislabels a known fraction of reads. It applies a forward correction (Patrini et al. 2017) so the model is fit against the corrected probability of the observed label rather than the raw noisy target, using a per-sample flip rate looked up from each chunk's source_group via --label-noise-rate group=rate[,group=rate,...] (e.g. --label-noise-rate gold=0.09,enzymatic=0.17); groups not named get rate 0 (plain BCE). Reach for it when a purity estimate exists for some or all of the training data and soft targets have already been tried and measured worse -- soft-labeling the noisy fraction is not equivalent to this correction and underperforms it. Because the correction trades bias for variance in the noisy regime, judge it by callable yield at a fixed precision floor (e.g. AUROC-adjacent metrics can look flat or even move against it while the fraction of confidently-called reads at 99% precision improves) rather than by AUROC alone.