Supervised Fine-Tuning (SFT)

“SFT is a post-training technique used to align LLM responses to a set of desired responses using a dataset of (prompt, response) pairs. This technique is the simplest way to shift a model’s behaviour toward a target style or task and does not utilise reinforcement learning.”

It’s similar to a continuation of the pre-training stage of an LLM, but using a curated dataset that is specific to the LLM’s application. Cross-entropy loss is computed exclusively on the response tokens, so the model is never penalised for how it encodes the prompt.

SFT is typically the first stage of a two-step alignment pipeline:

  • SFT (this class): warm-up the model to follow instructions by minimising cross-entropy on (prompt, good_response) pairs.

  • DPO: further align the SFT-initialised model using (prompt, chosen_response, rejected_response) triples.

This technique is surprisingly effective, as pre-trained LLMs have been shown to easily adapt to a relatively small amount of new data.

Example

from agilerl.algorithms.sft import SFT
from agilerl.llm_envs import DatasetEnv
from datasets import load_dataset
from peft import LoraConfig
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

# Instantiate the model and the associated tokenizer
model = AutoModelForCausalLM.from_pretrained(
    "Qwen/Qwen2.5-3B",
    torch_dtype=torch.bfloat16,
)
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-3B")

# Load the dataset into an SFT DatasetEnv
raw_dataset = load_dataset("HumanLLMs/Human-Like-DPO-Dataset", split="train").shuffle(seed=42)
train_test_split = raw_dataset.train_test_split(test_size=0.1)
train_dataset = train_test_split["train"]
test_dataset = train_test_split["test"]
env = DatasetEnv(
  train_dataset=train_dataset,
  test_dataset=test_dataset,
  tokenizer=tokenizer,
  objective="sft",
  response_column="chosen",
  data_batch_size_per_gpu=16,
)

# Configure LoRA adapters
lora_config = LoraConfig(
  r=16,
  lora_alpha=64,
  target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
  bias="none",
)

# Instantiate the agent
agent = SFT(
  actor_network=model,
  pad_token_id=tokenizer.eos_token_id,
  pad_token=tokenizer.eos_token,
  device="cuda" if torch.cuda.is_available() else "cpu",
  batch_size=32,
  lr=5e-5,
  update_epochs=1,
  lora_config=lora_config,
  seed=42,
)

Training an SFT agent

To train an SFT agent on a single dataset environment, use the train_llm_dataset function:

from agilerl.training.llm import train_llm_dataset

train_llm_dataset(
  pop=[agent],
  env=env,
  init_hp={"BATCH_SIZE": 32, "UPDATE_EPOCHS": 1},
  checkpoint_steps=250,
)

Saving and Loading Agents

To save an agent, use the save_llm_checkpoint function:

from agilerl.utils.utils import save_llm_checkpoint

save_llm_checkpoint(agent, "path/to/checkpoint")

To load a trained model, you must use the HuggingFace .from_pretrained method, AgileRL is compatible with HuggingFace and Peft models:

from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel
import torch

base_model = AutoModelForCausalLM.from_pretrained(
    "Qwen/Qwen2.5-3B",
    torch_dtype=torch.bfloat16,
    device_map="auto"
)
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-3B")
model = PeftModel.from_pretrained(base_model, "path/to/model/directory")

Parameters

class agilerl.algorithms.sft.SFT(*args: Any, **kwargs: Any)

Supervised Fine-Tuning (SFT) algorithm.

Trains an LLM via token-level cross-entropy loss computed exclusively on the response tokens of each (prompt, response) pair, or on the assistant turns of each multi-turn messages conversation. No rejected/negative responses are needed or used.

This is typically the first stage of a two-step alignment pipeline:

  1. SFT (this class) — warm-up the model to follow instructions by minimising cross-entropy on (prompt, good_response) pairs.

  2. DPO — further align the SFT-initialised model using (prompt, chosen_response, rejected_response) triples.

Parameters:
  • pad_token_id (int) – Pad token id

  • pad_token (str) – Pad token string

  • model_name (str, optional) – HuggingFace model name or path, used when no actor_network is supplied

  • actor_network (PreTrainedModel | PeftModel | None, optional) – Pre-built HuggingFace causal LM

  • model_config (dict, optional) – Extra kwargs forwarded to the model constructor

  • hp_config (HyperparameterConfig, optional) – Hyperparameter mutation config for AgileRL HPO, defaults to None (mutations disabled)

  • index (int, optional) – Population index, defaults to 0

  • batch_size (int, optional) – Total training batch size (across all GPUs), defaults to 16

  • lr (float, optional) – Learning rate, defaults to 5e-5

  • max_grad_norm (float, optional) – Gradient clipping norm, defaults to 0.1

  • update_epochs (int, optional) – Number of passes over each data batch, defaults to 1

  • calc_position_embeddings (bool, optional) – Whether to recompute position ids from the attention mask (recommended for packed/padded inputs), defaults to True

  • micro_batch_size_per_gpu (int, optional) – Micro-batch size for gradient accumulation. When None the full batch is used in a single forward pass.

  • mini_batch_size (int | None, optional) – Per-rank samples covered by one optimizer step. None uses batch_size / world_size. gradient_accumulation_steps is derived as mini_batch_size / micro_batch_size_per_gpu.

  • gradient_checkpointing (bool | None, optional) – Recompute block activations in the backward pass. None lets the training-memory search pick it on CUDA for a catalog model; elsewhere it is on.

  • device (str, optional) – Device for accelerated computing, ‘cpu’ or ‘cuda’, defaults to ‘cpu’

  • lora_config (LoraConfig, optional) – LoRA config; when supplied the base model is wrapped with PEFT adapters, defaults to None

  • fsdp_config (FSDPConfig | None, optional) – FSDP2 sharding settings for distributed runs, defaults to None

  • wrap (bool, optional) – Wrap models for distributed training on construction, defaults to True

  • clone (bool, optional) – Flag that suppresses adapter initialisation when cloning an existing agent, defaults to False

  • seed (int, optional) – Random seed, defaults to 42

  • use_separate_reference_adapter (bool, optional) – Also create a reference LoRA adapter alongside actor. SFT does not itself use a reference policy, so this defaults to False; enable it when you plan to save an SFT checkpoint that will be consumed by a downstream algorithm (e.g. DPO/GRPO) which expects a reference adapter. Defaults to False.

  • quantization_config (BitsAndBytesConfig | None, optional) – Optional transformers.BitsAndBytesConfig for loading the base model in 4-/8-bit (QLoRA). lm_head is kept unquantized so the fused-linear-logprob path stays numerically exact.

  • max_model_len (int, optional) – Longest training row (prompt plus response) the training-memory search sizes for, defaults to 1024.

  • routed_expert_chunk_mib (int | None, optional) – MiB of the widest activation of one routed-expert row chunk under DDP; FSDP reads fsdp_config.routed_expert_chunk_mib. None lets the training-memory search pick it when it runs, else keeps 64.

add_scores(scores: Sequence[float | list[float]]) → None

Add scores to the metrics.

Parameters:

scores (Sequence[float | list[float]]) – List of scores (or per-agent score rows) to add.

apply_lr() → None

Set lr / lr_critic as the optimizer’s peaks at the schedule’s current step.

clean_up() → None

Clean up the algorithm.

clone(index: int | None = None, wrap: bool = True) → Self

Create a clone of the algorithm.

QLoRA clones rebuild the base via from_pretrained and transfer only adapter (+ value head) weights. FSDP2 clones copy a rank-0 CPU full state dict onto a fresh CPU actor, then shard. The dense full model is never placed on GPU.

Parameters:
  • index (int | None, optional) – The index of the clone, defaults to None

  • wrap (bool, optional) – Unused. Clones always call wrap_models(). Kept so tournament / multi-frequency can pass wrap=False.

Returns:

A clone of the algorithm

Return type:

EvolvableAlgorithm

configure_batch_size_per_process(batch_size: int, micro_batch_size_per_gpu: int | None, mini_batch_size: int | None, group_size: int = 1) → None

Derive per-process batch sizes and gradient accumulation steps.

batch_size is the global collect size (prompt groups for GRPO-family). Each data-parallel replica holds (batch_size / dp_size) * group_size samples, where dp_size is the process-group world folded by tensor-parallel degree (world_size / tp). Unset mini_batch_size is that per-rank count. Unset micro_batch_size_per_gpu uses the mini-batch. gradient_accumulation_steps is mini_batch_size / micro_batch_size_per_gpu.

Parameters:
  • batch_size (int) – Global collect size across ranks.

  • micro_batch_size_per_gpu (int | None) – Samples per forward/backward pass.

  • mini_batch_size (int | None) – Per-rank samples per optimizer step.

  • group_size (int) – Completions per prompt (GRPO-family).

static copy_attributes(agent: IndividualT, clone: IndividualT, exclude: Iterable[str] = ()) → IndividualT

Copy the non-evolvable attributes of the algorithm to a clone.

Parameters:
  • agent (EvolvableAlgorithm) – The algorithm to copy attributes from.

  • clone (EvolvableAlgorithm) – The clone of the algorithm.

  • exclude (Iterable[str]) – Attribute names to leave on clone / agent.

Returns:

The clone of the algorithm.

Return type:

EvolvableAlgorithm

property current_lr: float

Actor learning rate the next learn call trains with.

property current_lr_critic: float

Critic learning rate the next learn call trains with; lr is the peak without lr_critic.

eval_policy_network_ids() → set[int]

Return the id of every evaluation network in the agent’s policy group.

Returns:

Identities of the policy’s evaluation networks.

Return type:

set[int]

evolvable_attributes(networks_only: bool = False) → dict[str, Any]

Return the attributes related to the evolvable networks in the algorithm. Includes attributes that are either EvolvableModule or ModuleDict objects, as well as the optimizers associated with the networks.

Parameters:

networks_only (bool, optional) – If True, only include evolvable networks, defaults to False

Returns:

A dictionary of network attributes.

Return type:

dict[str, Any]

finalize_training_step(num_steps: int) → None

Close the agent’s training block, storing any captured GraMa scores.

Parameters:

num_steps (int) – Number of steps taken during the training step.

Returns:

None.

Return type:

None

property fitness: list[float | ndarray[tuple[int, ...], dtype[_ScalarType_co]]]

Fitness history (scalars, or per-sub-agent rows for multi-agent).

get_action(obs: ndarray[tuple[int, ...], dtype[_ScalarType_co]] | dict[str, ndarray[tuple[int, ...], dtype[_ScalarType_co]]] | tuple[ndarray[tuple[int, ...], dtype[_ScalarType_co]], ...] | Tensor | TensorDict | tuple[Tensor, ...] | dict[str, Tensor] | Number | list[RolloutPrompt] | RolloutPrompt | dict[str, ndarray[tuple[int, ...], dtype[_ScalarType_co]] | dict[str, ndarray[tuple[int, ...], dtype[_ScalarType_co]]] | tuple[ndarray[tuple[int, ...], dtype[_ScalarType_co]], ...] | Tensor | TensorDict | tuple[Tensor, ...] | dict[str, Tensor] | Number | list[RolloutPrompt] | RolloutPrompt], *args: Any, **kwargs: Any) → NoReturn

Not implemented — SFT is an offline supervised algorithm.

Raises:

NotImplementedError – Always.

static get_action_dim(action_space: Space | list[Space] | dict[str, Space]) → int | dict[str, int] | tuple[int | dict[str, int], ...]

Return the dimension of the action space as it pertains to the underlying networks (i.e. the output size of the networks).

Parameters:

action_space (spaces.Space or list[spaces.Space].) – The action space of the environment.

Returns:

The dimension of the action space.

Return type:

int | dict[str, int] | tuple[int | dict[str, int], …]

get_eval_modules(cloning: bool = True) → tuple[dict[str, EvolvableModule], dict[str, EvolvableModule]]

Get the offsprings of all of the evaluation modules in the individual.

Parameters:

cloning (bool, optional) – Whether to clone each evaluation module before returning it, defaults to True.

Returns:

Tuple of offspring policy and the rest of the evaluation modules

Return type:

tuple[dict[str, EvolvableModule], dict[str, EvolvableModule]]

get_lr_names() → list[str | tuple[str, str]]

Return the learning-rate attribute name(s) of each optimizer.

get_policy() → EvolvableModuleProtocol

Return the policy network of the algorithm.

static get_state_dim(observation_space: Space | list[Space] | dict[str, Space]) → tuple[int, ...] | dict[str, tuple[int, ...]] | tuple[tuple[int, ...] | dict[str, tuple[int, ...]], ...]

Return the dimension of the state space as it pertains to the underlying networks (i.e. the input size of the networks).

Parameters:

observation_space (spaces.Space or list[spaces.Space].) – The observation space of the environment.

Returns:

The dimension of the state space.

Return type:

tuple[int, …] | dict[str, tuple[int, …]]

property hp_config: HyperparameterConfig

Return the hyperparameter configuration for Evo-HPO mutations.

property index: int

Return the index of the algorithm.

init_training_step(capture_grama: bool = False) → None

Open the agent’s training block: metrics tracking, and GraMa capture.

Hooks are registered afresh each cycle, so they follow the agent through architecture mutations, checkpoint reloads and accelerator re-wrapping. Opening a block implicitly closes one that an earlier call left open.

Parameters:

capture_grama (bool) – Whether to register GraMa capture hooks for this training step. Defaults to False since the LLM finetuners never run ReGraMa.

Returns:

None.

Return type:

None

static inspect_attributes(agent: EvolvableAlgorithmProtocol | AgentWrapperProtocol[Any], input_args_only: bool = False, exclude: Iterable[str] = ()) → dict[str, Any]

Inspect and retrieve the attributes of the current object, excluding attributes related to the underlying evolvable networks (i.e. EvolvableModule, torch.optim.Optimizer) and with an option to include only the attributes that are input arguments to the constructor.

Parameters:
  • input_args_only (bool) – If True, only include attributes that are input arguments to the constructor. Defaults to False.

  • exclude (Iterable[str], optional) – Extra attribute names to drop from the result, on top of the standard exclusions below. For a caller-specific reason to leave an attribute out of its own view.

Returns:

A dictionary of attribute names and their values.

Return type:

dict[str, Any]

learn(experiences: SFTPrompts, training: bool = True) → dict[str, float]

Update model parameters using cross-entropy loss on the masked tokens.

The loss is computed only where loss_mask is set (response or assistant tokens); every other token is masked out via ignore_index=-100.

Parameters:
  • experiences (SFTPrompts) – Dict with keys input_ids, attention_mask and loss_mask ([B, L], true at trained tokens) as produced by a objective="sft" DatasetEnv.

  • training (bool) – When False the backward pass is skipped (eval mode).

Returns:

loss and perplexity averaged over all samples in the batch, and learn_phase_<phase>_s wall seconds.

Return type:

dict[str, float]

classmethod load(path: str, device: str | device = 'cpu', accelerator: Accelerator | None = None) → Self

Load an algorithm from a checkpoint.

Parameters:
  • path (string) – Location to load checkpoint from.

  • device (str, optional) – Device to load the algorithm on, defaults to ‘cpu’

  • accelerator (Accelerator | None, optional) – Accelerator object for distributed computing, defaults to None

Returns:

An instance of the algorithm

Return type:

SingleAgentAlgorithm

load_checkpoint(path: str, load_optimizer: bool = False, overwrite_reference_adapter: bool | None = None, overwrite_critic_adapter: bool = False, restore_config: bool = True, restore_hyperparameters: bool = True) → None

Load adapter weights and algorithm state from a checkpoint directory.

Adapter roles restored on load:

  • actor — the trained policy. Always loaded.

  • reference — loaded from the checkpoint’s reference/ adapter when it has one; otherwise the checkpoint’s actor is copied onto reference so SFT -> DPO -> GRPO chains work out of the box.

  • critic — loaded from the checkpoint’s critic/ adapter when it has one, otherwise left at its fresh LoRA init. Set overwrite_critic_adapter to seed it from the actor.

The checkpoint’s LoRA config must match the live algorithm’s config; a mismatch raises ValueError (re-create the agent with the checkpoint’s LoRA config to load it).

The same flow applies to plain, DDP and FSDP2 runs:

lora_only=T -> PEFT adapter dirs are loaded into the live

adapters.

lora_only=F -> the full actor state_dict is restored from

attributes.pt.

When load_optimizer=True the optimizer state is restored from attributes.pt; if the checkpoint contains no optimizer state (saved with save_optimizer=False), a UserWarning is emitted and a freshly-initialised optimizer is used. The LR schedule always resumes at the checkpoint’s learn step, with this instance’s lr / lr_critic (after any hyperparameter restore) as its peaks.

Parameters:
  • path (str) – Directory containing a checkpoint written by save_checkpoint().

  • load_optimizer (bool) – If True also load the optimizer state so training can resume.

  • overwrite_reference_adapter (bool | None) – Copy the checkpoint’s actor onto reference even when it has a reference/ adapter. None copies only when the checkpoint has no reference adapter.

  • overwrite_critic_adapter (bool) – Seed critic from the checkpoint’s actor.

  • restore_config (bool) – If False, keep this instance’s algorithm settings and restore only training state: step count, scores, fitness, reference_update_tracker, optimizer_steps, rng and, with restore_hyperparameters, the registry’s mutable hyperparameters.

  • restore_hyperparameters (bool) – If False, keep this instance’s values for the registry’s mutable hyperparameters (e.g. lr). Only a run that mutates them needs the checkpoint’s values.

load_weights(path: str, overwrite_reference_adapter: bool | None = None, overwrite_critic_adapter: bool = False) → None

Load only the LoRA adapters (and value head) from a checkpoint directory.

Parameters:
property lr_schedule_step: int

Learn steps the LR schedule has taken; 0 without a schedule.

property mut: str | None

Return the mutation object of the algorithm.

mutation_hook() → None

Execute the hooks registered with the algorithm.

packed_warmup_lengths() → list[int]

Packed lengths that reach every length-specialized kernel a learn can hit.

Returns:

packed_length_classes() of the actor at the micro-batch token budget, nearest first to the planner’s expected micro-batch: ROW_FILL of a mini-batch of full rows, split evenly over the micro-batches the budget needs. Empty off CUDA, without packing, or without recurrent mixers or flex attention.

Return type:

list[int]

classmethod population(size: int, device: str | device = 'cpu', resume_from_checkpoint: str | None = None, **kwargs: Any) → list[Self]

Create a population of LLM algorithms.

Builds agent 0 fully (loading the model from disk), then clones for agents 1..N. Under FSDP2 / QLoRA this uses adapter-only clone(); otherwise the actor is copied via clone_llm().

Parameters:
  • size (int) – The size of the population.

  • device (DeviceType) – Torch device. Defaults to "cpu".

  • resume_from_checkpoint (str | None) – Path to checkpoint to resume from.

  • kwargs (Any) – Additional keyword arguments to pass to the algorithm constructor.

Returns:

A list of LLM algorithms.

Return type:

list[LLMAlgorithm]

preprocess_observation(observation: Tensor | TensorDict | tuple[Tensor, ...] | dict[str, Tensor]) → Tensor | TensorDict | tuple[Tensor, ...] | dict[str, Tensor]

Preprocess observations (dummy) for forward pass through neural network.

Parameters:

observation (torch.Tensor[float] or dict[str, torch.Tensor[float]]) – Observations of environment

Returns:

Preprocessed observations

Return type:

torch.Tensor[float] or dict[str, torch.Tensor[float]] or tuple[torch.Tensor[float], …]

recompile() → None

Recompiles the evolvable modules in the algorithm with the specified torch compiler.

register_mutation_hook(hook: LambdaType | MethodType) → None

Register a hook to be executed after a mutation is performed on the algorithm.

Parameters:

hook (MutationHook) – The hook to be executed after mutation.

register_network_group(group: NetworkGroup) → None

Set the evaluation network for the algorithm.

Parameters:

name (str) – The name of the evaluation network.

reinit_optimizers(optimizer: OptimizerConfig | None = None) → None

Reinitialize the optimizers of an algorithm. If no optimizer is passed, all optimizers are reinitialized.

Parameters:

optimizer (OptimizerConfig | None, optional) – The optimizer to reinitialize, defaults to None, in which case all optimizers are reinitialized.

save_checkpoint(path: str, lora_only: bool = True, save_optimizer: bool = True) → None

Save adapter weights and algorithm state to a directory.

AgileRL never persists base-model weights when lora_only=True for LLM algorithms: a checkpoint is a directory containing

  • <adapter>/adapter_model.safetensors + adapter_config.json — one subdirectory per adapter in selected_adapters (always actor, plus reference / critic when those adapters are configured). Written only when lora_only=True.

  • attributes.pt — algorithm hyperparameters, plus (optionally) the actor state dict and/or optimizer state dict. Always present.

The same format is written for plain, DDP and FSDP2 runs:

lora_only=T, save_optimizer=T -> PEFT adapter dirs on disk +

optimizer state in attributes.pt

lora_only=T, save_optimizer=F -> PEFT adapter dirs only lora_only=F, save_optimizer=T -> full actor state_dict +

optimizer state in attributes.pt

lora_only=F, save_optimizer=F -> full actor state_dict in attributes.pt

FSDP2-sharded parameters and optimizer state are gathered to full tensors before saving, so checkpoints are rank-count independent.

Parameters:
  • path (str) – Directory to write the checkpoint into.

  • lora_only (bool) – If True (default) only adapter weights are written to disk via save_pretrained; the base model is shared across checkpoints and not serialised. If False, the full actor state dict is persisted into attributes.pt.

  • save_optimizer (bool) – If True (default) also persist the optimizer and LR scheduler state in attributes.pt so training can resume.

property scores: list[float | list[float]]

Per-episode scores (per-group score rows for multi-agent metrics).

select_adapter(adapter_name: str) → Generator[None, None, None]

Temporarily switch adapter; restores the actor adapter on exit.

Parameters:

adapter_name (str) – Name of the adapter to activate (“actor”, “critic”, “reference”).

set_reference_policy() → None

Copy the actor adapter onto reference every reference_update_interval optimizer steps.

Does nothing when reference_update_interval is None.

Base weights are immutable in AgileRL’s LoRA-only training: with use_separate_reference_adapter=True the actor adapter is copied onto the reference adapter; without one the implicit reference (the base model with adapters disabled) cannot move, so the update request is acknowledged with a one-time warning and the KL anchor stays the initial policy.

set_training_mode(training: bool) → None

Set the training mode of the algorithm.

Parameters:

training (bool) – If True, set the algorithm to training mode.

snapshot_checkpoint(lora_only: bool = True, save_optimizer: bool = True) → LLMCheckpointSnapshot

Copy the checkpoint of save_checkpoint() into host memory.

All ranks must call this together (FSDP2 gathers are collective). The snapshot holds the weights and optimizer state of this step: later training does not change it, so LLMCheckpointSnapshot.write() may run on another thread while training continues.

Parameters:
Returns:

Host copy of the checkpoint; empty off the main process.

Return type:

LLMCheckpointSnapshot

property steps: int

Cumulative global step count.

test(env: DatasetEnv, loop: int = 1, *args: Any, **kwargs: Any) → npt.NDArray

Return the negative mean loss as a fitness score (higher is better).

Parameters:
  • env (DatasetEnv) – SFT environment providing evaluation batches (objective="sft")

  • loop (int, optional) – Number of evaluation batches, defaults to 1

Returns:

Mean negative loss (scalar numpy array)

Return type:

npt.NDArray

to_device(*experiences: Tensor | TensorDict | tuple[Tensor, ...] | dict[str, Tensor]) → tuple[Tensor | TensorDict | tuple[Tensor, ...] | dict[str, Tensor], ...]

Move experiences to the device.

Parameters:

experiences (tuple[torch.Tensor[float], ...]) – Experiences to move to device

Returns:

Experiences on the device

Return type:

tuple[torch.Tensor[float], …]

trainer_offload_context() → AbstractContextManager[None]

Context manager that holds the trainer on GPU only for the training step.

unrolled_eval_networks() → list[tuple[str | None, Module]]

Return the agent’s evaluation networks as (network_id, network) pairs.

Returns:

One (network_id, network) pair per measured network.

Return type:

list[tuple[str | None, torch.nn.Module]]

unwrap_models() → None

Unwraps the models in the algorithm from the accelerator.

update_existing_adapter(checkpoint_dir: str, adapter_name: str) → None

Overwrite weights of an existing adapter in-place without creating new parameters.

Parameters:
  • checkpoint_dir (str) – Checkpoint directory

  • adapter_name (str.) – Adapter name

Returns:

None

Return type:

None

static update_lr(optimizer: OptimizerWrapper, lr: float | tuple[float, float | None], scheduler_config: CosineLRScheduleConfig | None = None, schedule_step: int = 0) → LambdaLR | None

Set the peak learning rate of each param group and rebuild the schedule.

Parameters:
  • optimizer (OptimizerWrapper) – LLM optimizer.

  • lr (float | tuple[float, float | None]) – Learning rate value, or actor/critic pair; a None critic uses the actor rate.

  • scheduler_config (CosineLRScheduleConfig | None) – Scheduler configuration; None holds lr constant.

  • schedule_step (int) – Learn steps the schedule has already taken.

Returns:

Scheduler at schedule_step when scheduler_config is set.

Return type:

LambdaLR | None

use_adapter(adapter_name: str) → None

Switch the active PEFT adapter, handling all side-effects.

For “reference”: switches adapter and freezes reference params (never trained). For all others: switches adapter and restores requires_grad=True on all training adapter LoRA params so distributed gradient hooks keep firing.

Parameters:

adapter_name (str) – Name of the adapter to activate (“actor”, “critic”, “reference”).

warm_packed_kernels(lengths: list[int], stop: Callable[[], bool] | None = None) → int

Compile the learn kernels at each packed length in order, leaving no trace.

Before each length rank 0 evaluates stop and broadcasts the answer, so every rank runs the same forwards and collectives line up. A learn compiles the lengths left on first use.

Parameters:
  • lengths (list[int]) – packed_warmup_lengths() or a slice of them.

  • stop (Callable[[], bool] | None) – Ends the warmup early when it returns True; None warms every length.

Returns:

Lengths warmed.

Return type:

int

wrap_models() → None

Prepare the actor for training.

Places the actor (dense .to(device) or FSDP2 shard) then builds the optimizer and LR scheduler on those parameters. FSDP2 wraps each transformer block with activation checkpointing before fully_shard when gradient_checkpointing is on. Data-parallel prepare_actor uses HuggingFace gradient_checkpointing_enable, and the routed experts run at routed_expert_chunk_mib when it is set.