Write a recipe
A recipe says how Reef learns from an agent's runs. Reef runs the same loop for every recipe, and at four steps of the loop it calls a class of the recipe. So a recipe is four classes, one for each of these steps. Each class has a base class, and the base class says what you implement:
|
Attribute |
The question that the class answers |
Base class |
You implement |
|---|---|---|---|
|
report |
What does a report hold? |
Report |
The fields of the dataclass |
|
samples |
What does a report become for the training? |
ReportSamples |
make_sample(context) |
|
algorithm |
How does a job train? |
WeightAlgorithm |
prepare_job(data, state) and the loss |
|
evaluation |
Does Reef accept the new version? |
Evaluation |
accepts(scores) |
The recipe itself is a subclass of WeightTrainingRecipe, and reef.recipe exports it with the four base classes. For each class you either write a subclass of the base class, or name a class that Reef has. This page defines the four classes one by one. Each section has the same parts: the definition of the class, the example, and the classes that Reef has. The example is the recipe with the name minimal (recipes/minimal/): it fine-tunes the model on the agent runs that pass a check. The page shows the core code, and each section names the file that holds the complete code. Use Reef runs this recipe.
The recipe class #
The recipe class names the four classes. This is the whole minimal recipe (recipe.py):
name: str = "minimal"
# control: what a report holds. Control refuses a report that this type does not parse.
report = RunReport
# samples: what a report becomes. The samples service calls PassedRuns.make_sample once for each report.
samples = PassedRuns
# training: the built-in sft algorithm. Every job trains, with cross-entropy on each reply of the model.
algorithm = "sft"
# evaluation: every new version serves at once. The deployment's activation section can name another rule.
evaluation = AlwaysActivateminimal writes two of the four classes itself, RunReport and PassedRuns. The other two are classes that Reef has.
The loop calls the classes in this order. The names are short for the real ones:
# inference, for each model call
record = store(call) # the response carries the record's ID: the receipt
# control, for each report (POST /reef/report)
report = recipe.report.from_dict(body) # 1. report
store(report)
# samples service, for each stored report
sample = recipe.samples.make_sample(context) # 2. samples
store(sample)
# control, when enough samples wait
data = JobData(samples) # the data of a job: the samples as they come
submit(data)
# training service, for each job
signal = recipe.algorithm.prepare_job(data, state) # 3. algorithm: train or skip, the advantages
checkpoint = backend.train(data, signal) # and the algorithm's loss at each optimizer step
# control, for each checkpoint
version = commit(checkpoint)
# evaluation service, for a recipe whose evaluation reads scores
scores = run(tasks, version) # the score of each evaluation task with the new version
# control
if recipe.evaluation.accepts(scores): # 4. evaluation
serve(version) # inference loads it1. The report (control) #
A report is the client's feedback on model calls. Inference stores each call and returns its receipt, and a report names the receipts of the calls that it is about in references. The report type says which other fields a client sends with each report.
|
Part |
Definition |
|---|---|
|
Base class |
Report (base.py) |
|
Reef calls it |
In the control service, for each POST /reef/report, before it stores the report |
|
You implement |
A frozen dataclass. Each field is one field of the report |
|
Input |
The body of the report. The field score is the report's score, and every other field is metadata.<field>. Reef itself reads references: the receipts of the model calls |
|
Output |
The parsed report, which the samples class reads as context.parsed_report |
|
Rules |
A field has the type float, int, str, bool or Mapping[str, str], optionally | None. A field without a default is required. For a rule between fields, override validate() and raise ReportValidationError |
The example (report.py). A report of minimal must hold a score:
@dataclass(frozen=True)
class RunReport(Report):
"""The report of one agent run.
Values: ``score`` is the report's top-level ``score``, a finite number that the client's check gave the run.
Purpose: control parses each report with it and refuses a report without a score; ``PassedRuns`` reads it.
"""
score: floatA report that does not parse gets 400, and the message names the field: score is required.
Classes that Reef has. ScoredRolloutReport holds a required score, as RunReport does. For a recipe that names no report, control checks only what it checks for every report: a score is a finite number, and the references name stored calls.
2. The samples (samples service) #
The samples class turns one report, with the model calls of its runs, into one training sample.
|
Part |
Definition |
|---|---|
|
Base class |
ReportSamples (reports.py) |
|
Reef calls it |
In the samples service, once for each report, when the report and its calls are stored |
|
You implement |
make_sample(context) |
|
Input |
context, a ReportContext. context.parsed_report is the report, context.score its score, and context.inferences the model calls of the report's runs, oldest first. Each call holds the request in payload["messages"] and the model's answer in payload["response"] |
|
Output |
A Sample, or SkippedReport(reason) for a report that trains nothing |
|
Rules |
The method makes no network call and no model call. It raises ValueError for a report that breaks the recipe's contract |
The example (samples.py). minimal skips a run whose score is below min_score. For every other run it returns the sample of the base class: the calls of the run as one trajectory, in which each reply of the model is a step that trains.
class PassedRuns(ReportSamples):
"""Each run whose score is at least ``min_score`` becomes one trajectory sample: every reply of the served model
in the run. A run with a lower score trains nothing."""
settings_type = PassedRunsSettings
settings: PassedRunsSettings
def make_sample(self, context: ReportContext) -> Sample | SkippedReport:
if context.score is None or context.score < self.settings.min_score:
return SkippedReport(f"the score {context.score} is below min_score {self.settings.min_score}")
# The default sample: the run's calls as one trajectory, in which each reply of the model is a trained step.
return super().make_sample(context)min_score is a setting of the class. The dataclass PassedRunsSettings in the same file declares it, and a deployment sets it as recipe.samples.min-score.
Classes that Reef has. ReportSamples itself makes one trajectory sample of each report. A recipe that names no samples makes no sample of a report. The base class of every samples class is Samples; a class that makes samples without reports subclasses it (Less common parts).
The data of a job #
The samples wait until a job starts. A job starts when enough samples wait, and the deployment sets that number, recipe.jobs.job-samples. By default a job holds its samples as they come, and a recipe writes nothing for this step (distill.py):
def make_job_data(self, samples: tuple[Sample, ...], data_id: str) -> JobData:
return JobData(data_id, samples)A recipe that arranges the samples of a job names a class in the attribute jobs. For example, TTT-Discover lays one step out as groups of rollouts (jobs.py), and GEPA makes each job one minibatch (jobs.py).
|
Part |
Definition |
|---|---|
|
Base class |
Jobs (base.py) |
|
Reef calls it |
In the control service, when job-samples samples wait, and for the samples that a training request names |
|
You implement |
make_job_data(samples, data_id) |
|
Input |
samples: the samples of the job, oldest first. data_id: the ID that the result must have |
|
Output |
A JobData: the samples that the job trains, in the order in which it trains them |
|
Rules |
The result has the ID data_id. The job uses up every sample of samples, also one that the result leaves out |
3. The algorithm (training) #
The algorithm says how one job trains. It is one class with a name and two parts:
-
prepare_job runs once for each job, before the training. It reads all the samples of the job and decides three things: whether the job trains, the advantage of each sample when the loss reads one, and the state that the next job gets.
-
The loss runs at each optimizer step, in the training backend, where the model is.
|
Part |
Definition |
|---|---|
|
Base class |
WeightAlgorithm (objectives.py). Your class subclasses SlimeAlgorithm to train on Slime, on your GPUs, or TinkerAlgorithm to train on Tinker |
|
Reef calls it |
In the training service: prepare_job once for each job, then the loss at each optimizer step |
|
You implement |
name, prepare_job(data, state) and the loss. The default prepare_job trains every job without advantages |
|
Input |
data: the JobData of the job, with its samples. state: the state that the prepare_job of the job before returned, empty for the first job |
|
Output |
A TrainingSignal: the action train or skip, the next state, metrics, and optionally one advantage for each trajectory, in the order of the job's data |
|
Rules |
prepare_job changes neither argument, and reads no model and no GPU. Two classes of one algorithm, one for each backend, have the same name |
WeightAlgorithm defines the name and prepare_job, which are the same on every backend. The loss has another form on each backend, because each backend computes it in another place. So WeightAlgorithm has one subclass for each backend, which says how a class gives its loss:
|
Backend |
Subclass of WeightAlgorithm |
Where the loss runs |
How the class gives the loss |
|---|---|---|---|
|
Slime |
SlimeAlgorithm |
On your GPUs, in the worker processes of Slime |
loss_type names a loss of Slime, or loss names your own loss function, which the GPU workers import (slime/worker.py) |
|
Tinker |
TinkerAlgorithm |
On Tinker's side |
loss_fn names a loss of Tinker, and inputs(rows, ...) gives the values of each token that the loss reads |
A recipe names its algorithm in one of three ways:
|
The recipe writes |
Meaning |
Example |
|---|---|---|
|
A name |
An algorithm that Reef has |
algorithm = "sft" in minimal |
|
One class |
Your algorithm, for the one backend that the recipe supports |
algorithm = SdftAlgorithm in SDFT |
|
One class for each backend |
Your algorithm, for both backends. The deployment's training.backend selects the class that runs |
algorithm = (TttdAlgorithm, TttdTinkerAlgorithm) in TTT-Discover |
The example. minimal names the algorithm sft, supervised fine-tuning, which Reef has: every job trains, and the loss is the cross-entropy on each reply of the model in the sample. What minimal adds to plain fine-tuning is its samples class: only the runs that passed train.
The class of sft on Tinker shows the whole form of an algorithm: the name, the loss of Tinker, and the values that the loss reads (losses.py). It keeps the default prepare_job:
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
]The class of sft on Slime has the same name and names Slime's loss: loss_type = "sft_loss" (sft.py).
A prepare_job of your own. This algorithm trains each run with its score as the advantage. It keeps the loss of a class that Reef has, and writes only prepare_job (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)A loss of your own on Slime is a function in slime/worker.py, which runs on the GPU workers. The class names it in loss, as a reference package.module:function. SDFT's class names two functions: the loss, and the function that the workers call before they train the samples of a job (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"Evolve a model writes both functions in full, and Write an algorithm lists every member of both base classes.
Classes that Reef has. sft on both backends, and slime_dataset on Slime: Slime's own rollouts and loss on a prompt dataset or on tasks. A deployment sets the options of an algorithm under recipe.algorithm.
4. The evaluation (evaluation) #
The evaluation class decides whether Reef accepts a version that training made. It reads the scores of the version on the evaluation tasks.
|
Part |
Definition |
|---|---|
|
Base class |
Evaluation (evaluation.py) |
|
Reef calls it |
After training made a version. For a class that reads scores, Reef first runs the evaluation tasks with the new version |
|
You implement |
accepts(scores), and the attribute sides: the versions whose scores the method reads |
|
Input |
scores, a VersionScores. scores.candidate holds the score of each evaluation run of the new version, and scores.mean_score is their mean. With the side current, scores.current holds the scores of the version that the new one would replace, on the same tasks |
|
Output |
True: Reef accepts the version |
|
Rules |
The method decides from scores alone. Reef builds the class without arguments |
sides says what Reef runs before it asks:
|
sides |
What Reef runs |
What accepts gets |
|---|---|---|
|
() |
No task |
No scores |
|
("candidate",), the default |
The evaluation tasks, with the new version |
scores.candidate |
|
("candidate", "current") |
The evaluation tasks, with the new version and with the version that it would replace |
scores.candidate and scores.current. Only a harness recipe has this side |
One base class serves both kinds of recipe. What an accepted version is, and where the tasks come from, differ:
|
Kind of recipe |
An accepted version |
A version that is not accepted |
The evaluation tasks |
|---|---|---|---|
|
Weights |
Serves |
Is stored, and does not serve |
The setting artifact_evaluation of the scenario (scenario settings). The evaluation service runs them |
|
Harness |
Is kept as a new version of the tree |
Is dropped |
evolution.evaluation of the deployment. The job runs them, after the method |
The example. minimal names AlwaysActivate, a class that Reef has: it has no sides, and it accepts every version. So every version serves at once, and no task runs.
An evaluation class of your own. This class accepts a version when its mean score on the evaluation tasks is at least a half (test_recipe_declaration.py):
class PassingVersions(Evaluation):
"""Accept a new version when its mean score on the evaluation tasks is at least a half."""
# The decision reads the scores of the new version. Reef runs the evaluation tasks with it first.
sides = ("candidate",)
def accepts(self, scores: VersionScores) -> bool:
return scores.mean_score is not None and scores.mean_score >= 0.5Classes that Reef has. Each one is an Evaluation:
|
Class |
Kind of recipe |
Sides |
Accepts |
|---|---|---|---|
|
AlwaysActivate |
Weights |
None |
Every version. The default of a weight recipe |
|
NeverActivate |
Weights |
None |
No version. A person selects what serves (Use Reef, step 5) |
|
EvaluatedActivation |
Weights |
The candidate |
A version whose mean score is at least min_mean_score |
|
NoEvaluationPolicy |
Harness |
None |
Every tree |
|
FloorPolicy |
Harness |
The candidate |
A tree whose every task reaches floor_score |
|
ComparePolicy |
Harness |
The candidate and the current tree |
A tree that scores better than the current tree |
A deployment can name another class in place of the recipe's: for a weight recipe in its activation section (the activation section), and for a harness recipe in evolution.evaluation.policy. A class with settings, such as EvaluatedActivation, gets them there.
5. Run the recipe #
A deployment file selects the recipe by its class: recipe.implementation is <package>.<module>:<Class>. No other registration exists. The sections beside it set the settings of the classes (serve.yaml):
recipe:
implementation: recipes.minimal.recipe:MinimalRecipe
samples:
# A run trains when its check scores it 1 or more.
min-score: 1.0
jobs:
# A job starts when four runs that passed wait: one optimizer step.
job-samples: ${training.config.global_batch_size}|
Section of the deployment file |
Sets the settings of |
|---|---|
|
recipe.samples |
The class samples |
|
recipe.jobs |
The size of a job, job-samples, and the settings of a jobs class |
|
recipe.algorithm |
The class algorithm |
|
activation |
Another rule in place of the class evaluation, with the settings of that rule |
Test the recipe first. The test of minimal runs the recipe's classes in memory, with no server, no model and no GPU (test_minimal_recipe.py):
python -m pytest tests/recipes/minimal -qThen check the deployment file, and run it as Use Reef does from step 1. The first command prints each setting with its source, and starts no process:
reef serve -c serve.yaml --print-configThe deployment file also holds where the recipe runs: the training backend, the engine that serves the model and the stores (Run Reef in production).
To start a recipe of your own, copy recipes/minimal/ to recipes/<name>/ and change one class at a time.
A recipe that evolves a harness #
A harness recipe has the same four classes, and it subclasses HarnessEvolutionRecipe. A version is a tree of text files, not weights. So one of the four classes has another base class: the algorithm is a HarnessAlgorithm, which edits the tree. The evaluation is an Evaluation, as for weights: it decides whether the edited tree is kept. The training service runs both in one job: first the method, then the evaluation of the method's tree.
|
Attribute |
Base class |
The class that the base recipe names |
|---|---|---|
|
report |
Report |
ScoredRolloutReport: a report holds a score |
|
samples |
ReportSamples |
TraceSamples: one reported run is one trace. By default one trace starts one job |
|
algorithm |
HarnessAlgorithm |
None: the recipe names it |
|
evaluation |
Evaluation |
The class that the deployment's evolution.evaluation.policy names: compare, floor or none |
The algorithm of a harness recipe is a HarnessAlgorithm:
|
Part |
Definition |
|---|---|
|
Base class |
HarnessAlgorithm (contract.py) |
|
Reef calls it |
In the training service: run(job) once for each job, in a new workspace |
|
You implement |
run(job) |
|
Input |
job.workspace, the directories of the job: harness/ is a copy of the tree that serves, material/ holds the traces and the tasks of the job, and state/ holds the method's files from the job before. job.services is what Reef runs for the method: the models, the tree check, the evaluation and the coding agent |
|
Output |
The tree that the method leaves in harness/: the candidate. Its files in state/ for the next job, and a summary in output/ |
|
Rules |
Write only files that a part of the adapter takes: workspace.host()["parts"] lists them. An unchanged tree skips the job. An exception fails the job, and Reef keeps none of its changes. Take the models and the agent from job.services. Wrap trace text in untrusted_text, and keep credentials out of the tree |
The evaluation of a harness recipe has the definition of section 4. The job scores the sides that the class names on the tasks of evolution.evaluation, and asks accepts with those scores. Reef has three classes for a harness recipe: ComparePolicy, FloorPolicy and NoEvaluationPolicy. A subclass of one sets the recipe's defaults of the evolution.evaluation settings in setting_defaults (policy.py).
A tree that the job keeps is a new version. The deployment's activation section then decides whether the version serves, as for weights. A tree that changes a part that the adapter marks for review waits for a person.
Evolve a harness writes a harness recipe in full, GEPA, and its memory example writes ReasoningBank. To test a method, call run on a Workspace.create workspace with a canned model, as ACE's tests do.
Less common parts of a recipe #
-
Other shapes of sample. Reports that train together, such as the rollouts of one prompt: override make_grouping of the samples class (reports.py). A class that asks a model judge: subclass JudgedSamples (judging.py). Samples without a report, such as one sample for each run that ends: subclass InferenceSamples (traces.py), as ReasoningBank does.
-
Components. A recipe whose versions hold more than weights or a harness tree overrides Recipe.build_components(scenario). It returns a ComponentSpec for each named part of a version (components.py).
-
A task generator. The recipe reef.recipe.generated_tasks:GeneratedTaskRecipe trains on tasks that a TaskGenerator makes (generator.py; Generated tasks). SPADE is an example.
-
A method without a recipe class. A deployment selects reef.recipe.harness:HarnessEvolutionRecipe and names the method in recipe.config.evolution.method. A method that is only prompts uses AgentMethod and its agent protocol.
-
A task scorer and a task collector of a harness recipe. TaskScorer.score(task, result) scores each evaluation run (scoring.py), and TaskCollector.collect(samples) chooses the trace prompts that become evaluation tasks (tasks.py). A deployment selects them under recipe.config.evolution.evaluation.
Package the recipe #
A recipe is a package with this layout. Only README.md, __init__.py and recipe.py are required:
recipes/<name>/
README.md what the recipe trains and how to run it (template: recipes/AGENTS.md)
__init__.py exports the recipe class
recipe.py the recipe class: the four classes
report.py control: the report type
samples.py samples: the samples class and its settings
jobs.py samples: a jobs class, for a recipe that arranges the samples of a job
slime/algorithm.py training on Slime: the algorithm class and its settings
slime/worker.py training on Slime: the loss on the GPU workers
tinker.py training on Tinker: the algorithm class
evaluation.py evaluation: the evaluation class
examples/<example>/
serve.yaml a deployment of the recipe
tests/recipes/<name>/ the recipe's testsA file exists only when the recipe writes that class itself. A beta recipe is under recipes/beta/<name>/. The Reef wheel does not include recipes/. test_sao_configs.py checks each deployment file under recipes/; add a new deployment file to its list of examples.
Next steps #
-
Three complete recipes, each with its four classes: SDFT trains weights, GEPA evolves the rules and skills of a harness, and ReasoningBank builds a memory.
-
Write an algorithm: every member of the two algorithm base classes.
-
Production interfaces: the contract of the training backend, the serving runtime, the sandbox, the stores and the harness adapter.
-
Recipe configuration: the keys of the recipe section.
-
The recipes that ship: what each one trains.