Write an algorithm
An algorithm is the class of a recipe that the training service runs. Once for each job it says what the job trains, and at each optimizer step it gives the loss. A recipe names it in its attribute algorithm (Write a recipe).
The base class is WeightAlgorithm (objectives.py): it defines the name and prepare_job. The loss runs in the training backend, so WeightAlgorithm has one subclass for each backend, which says how a class gives its loss: TinkerAlgorithm for Tinker and Spindle, and SlimeAlgorithm for Slime. An algorithm is one class for each backend that the method supports. This page gives every member of the three classes.
What the training service calls #
# training service, once for each job
signal = algorithm.prepare_job(data, state) # train or skip, the advantages, the next state
if signal.action == "skip":
return # the job trains nothing and saves no checkpoint
# Tinker: for each optimizer step of the job
inputs = algorithm.inputs(rows, base_logprobs, kl_coef=...)
tinker.forward_backward(algorithm.loss_fn, inputs)
# Slime: once for each job, then for each optimizer step of the job
rows = [algorithm.shape_sample_row(sample) for sample in data] # in the training service
batch = algorithm.build_rollout_data(payload, rows) # in the training service
before_train(actor, batch) # on the GPU workers: algorithm.before_train
for step in steps:
loss, metrics = loss(args, micro_batch, logits, ...) # on the GPU workers: algorithm.lossThe base class: WeightAlgorithm #
|
Member |
Required |
What it is |
|---|---|---|
|
name |
Yes |
The algorithm's name. The parameter objective of each job holds it. On Slime it is also the prefix of the algorithm's flags. |
|
prepare_job(data, state) |
No |
Called once for each job, with all the samples of the job and the state that the job before returned. Returns a TrainingSignal: train or skip, the next state, metrics, and optionally one advantage for each trajectory. It changes neither argument, and it runs without a GPU. The default trains every job without advantages. |
|
supports_multiple_epochs |
No |
Whether a job may train its data more than once. The default is False: Reef refuses a job with epochs above 1. |
|
rollout_unit |
No |
The rows that one optimizer step keeps together: "sample", the default, or "comparison_set". |
prepare_job gets the complete data of the job. A statistic over a group of samples, such as an advantage relative to the group's mean, is computed there, so that it does not depend on how the backend cuts the job into steps. This class gives each run its score as the advantage (test_offline_pipeline.py):
class ScoredRuns(ImportanceSamplingLoss):
"""Train each run with its score as the advantage, on Tinker's importance-sampling loss."""
name = "scored"
def prepare_job(self, data: JobData, state: Mapping[str, Any]) -> TrainingSignal:
# The state is what the job before returned: here the count of the jobs.
jobs = int(state.get("jobs", 0)) + 1
# One advantage for each trajectory of the job, in the order of the job's data.
advantages = tuple(trajectory_reward(sample) for sample in trajectories(data))
return TrainingSignal("train", {"jobs": jobs}, {"jobs": jobs}, advantages)On Tinker and Spindle: TinkerAlgorithm #
Tinker computes the loss on its side. The class names a loss of Tinker and shapes the values that the loss reads (losses.py).
|
Member |
Required |
What it is |
|---|---|---|
|
loss_fn |
Yes |
The name of a built-in loss of Tinker, such as cross_entropy or importance_sampling. |
|
inputs(rows, base_logprobs, kl_coef) |
Yes |
The loss_fn_inputs of each row: one dictionary for each row of rows, in their order. |
|
uses_rollout_log_probs, uses_advantages |
No |
Whether inputs reads each row's rollout log probabilities and its advantage. Both default to True. |
|
needs_base_logprobs, check_kl_coef |
No |
For a loss with a KL penalty to the base model. |
The built-in sft algorithm on Tinker is the whole contract in one class:
class CrossEntropyLoss(TinkerAlgorithm):
"""Supervised fine-tuning: Tinker's ``cross_entropy`` on every response token the loss mask selects."""
name = "sft"
loss_fn = "cross_entropy"
uses_rollout_log_probs = False
uses_advantages = False
# The target is fixed and the loss reads no old-policy log probs. Thus each pass trains the same loss.
supports_multiple_epochs = True
def check_kl_coef(self, kl_coef: float) -> None:
if kl_coef:
raise ValueError("sft trains no KL penalty; set kl-coef to 0")
def inputs(
self, rows: Sequence[TokenRow], base_logprobs: Sequence[Sequence[float]], *, kl_coef: float
) -> list[dict[str, list[Any] | MatrixInput]]:
# Position i predicts token i+1; prompt positions weigh 0.
return [
{
"target_tokens": list(row.tokens[1:]),
"weights": [0.0] * (len(row.tokens) - len(row.mask) - 1) + [float(mask) for mask in row.mask],
}
for row in rows
]recipes/tttd/tinker.py is an algorithm with its own prepare_job and inputs.
On Slime: SlimeAlgorithm #
On Slime the loss runs in the GPU workers of Megatron, in another process than the training service. So a Slime algorithm has two files, and the class names each function of the second one:
recipes/<name>/slime/ algorithm.py the algorithm class and its settings; runs in the training service; imports no torch worker.py the functions that the GPU workers call; imports torch
The class (algorithm.py is the base class). Its members are in three layers. Most algorithms write only the first:
|
Layer |
Member |
What it is |
|---|---|---|
|
The contract |
name, prepare_job |
As on every backend (see above). |
|
The contract |
loss_type |
The --loss-type of Slime: custom_loss for a loss of your own, policy_loss or sft_loss for one of Slime's. Reef sets the option for the deployment. Required. |
|
The contract |
loss, token_loss, token_advantages, before_train, at_worker_start |
The worker functions. Each attribute names one function as a reference package.module:function, such as recipes.sdft.slime.worker:sdft_loss. loss is required for custom_loss. |
|
The contract |
settings_type |
The algorithm's options: a frozen dataclass. Each field name is the flag --<algorithm>-<name>, which a deployment sets under recipe.algorithm: a bool field is a switch, another field takes one value of its type. The base class parses the flags, checks the type of bind's config, and writes each value on Slime's arguments as <algorithm>_<name>, where the worker functions read it. |
|
The contract |
validate_specific_args(args, source) |
Checks the backend's arguments for this algorithm, and raises for a deployment that the loss cannot train. Required. |
|
Data shaping |
advantages, shape_sample_row, build_rollout_data, rollout_data_keys, rollout_tensor_dtypes, external_batch_keys |
Whether prepare_job gives advantages ("required", "forbidden" or "optional"); the row of one sample and the batch of one step, for an algorithm whose loss reads more than the tokens, the loss mask, the rollout log-probabilities and the reward. |
|
Backend plumbing |
train, bind, prepare_rollout, configure_backend_args, configure_critic_args, rollout_metrics and the critic_* attributes |
For an algorithm with a second model, such as a critic (SAO), or a teacher engine (the distillation base): how one job runs on the worker groups. |
SDFT's class sets only the names, because its base class DistillAlgorithm holds the rest (recipes/sdft/slime/algorithm.py):
name = "sdft"
settings_type = SdftSettings
# GPU workers, before they train the job's samples: the self-teacher scores the student's reply of each sample.
before_train = "recipes.sdft.slime.worker:sdft_actor_pre_train"
# GPU workers, at each optimizer step: the divergence between the self-teacher and the student.
loss = "recipes.sdft.slime.worker:sdft_loss"The worker functions. Each attribute names the function that the workers call at one point of the training. The training service sends a job to the workers in one call for each checkpoint that the job saves. So a job that saves only its last checkpoint is one call, and a call holds one or more optimizer steps.
|
Attribute |
The worker calls the function |
Signature |
|---|---|---|
|
loss |
For each micro-batch, for the loss. The algorithm's loss_type is custom_loss. |
loss(args, batch, logits, sum_of_sample_mean) returns the loss and its metrics. |
|
token_loss |
For each micro-batch, for the per-token term of Slime's policy_loss, which Reef keeps for an algorithm that names token_loss. |
token_loss(args, ppo_kl, log_probs, advantages) returns the loss of each token and the clipped fraction. |
|
token_advantages |
Once in each call, before the first optimizer step, for advantages that need the model, such as a critic's values. The class sets allows_slime_advantage_computation. |
token_advantages(args, rollout_data) sets advantages and returns in rollout_data. |
|
before_train |
Once at the start of each call, with the samples of the call: before the first optimizer step of the call, not before each step. |
before_train(actor, rollout_data) adds to rollout_data what the loss reads. |
|
at_worker_start |
Once when the worker starts. |
at_worker_start(actor) |
The training service never imports the module of the functions, which imports torch. When it resolves the algorithm, it reads the module's source file and checks that the file defines each function, and that the class names each function that the algorithm needs: loss for loss_type = "custom_loss", token_loss for uses_pg_loss_primitive, and the attributes of required_worker_functions. A misspelt reference thus fails when Reef starts, with an error that names the class, the attribute and the reference. Each worker imports the functions when it starts.
SDFT's loss function (recipes/sdft/slime/worker.py):
def sdft_loss(
args: Namespace,
batch: dict[str, Any],
logits: torch.Tensor,
sum_of_sample_mean: Callable[[torch.Tensor], torch.Tensor],
) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:Example: SDFT goes through both files.
An older form named a module in worker_module, whose functions had the decorator @worker_hook. It is removed: a class that sets worker_module, required_objective_hooks or before_step is refused when Python defines it, with the attribute to set instead.
An algorithm with a second model #
-
A critic. SAO trains a value model beside the policy. The deployment turns the critic on with Slime's option training.options.use-critic, and SaoAlgorithm refuses a deployment without it. The class's train method runs the critic's updates and then the policy's update (recipes/sao/slime/algorithm.py).
-
A teacher. A distillation algorithm reads a teacher's distribution. The teacher is the model itself (SDFT), a checkpoint that the workers load, or a teacher engine that the deployment starts with its teacher section (recipes/opd/slime/algorithm.py).
The GPUs and the engine of a second model are settings of the deployment. The algorithm says what it needs, and checks that the deployment gives it.
Rules #
-
The module of the class imports no torch, Ray, Slime or Tinker at module scope: a process without the GPU stack imports it, to read the algorithm's name and to check a job.
-
The class has a constructor without arguments: each process that needs it builds it from its reference.
-
On Slime, name the algorithm's own flags --<name>-<option>. A deployment sets a flag in one section only, recipe.algorithm or training.options.
-
A loss-type that a deployment sets must agree with the algorithm's loss_type, or the training service does not start.
-
The jobs of one deployment can name different algorithms. Reef refuses a second distillation algorithm in one run, and an algorithm that gives a data column of another algorithm another type.
-
An algorithm supports score centering only when it declares policy_gradient_weight.
Test it #
-
prepare_job without a GPU: OfflinePipeline.prepare(job, backend) (Write a recipe).
-
The loss on small tensors on a CPU, as test_sdft_worker.py does.
-
The conventions of a Slime algorithm: add its name to test_slime_algorithm_contract.py.
-
One job on the GPU stack.