Core Guides

Evolve a model: the SDFT example

SDFT, Self-Distillation Fine-Tuning, teaches a model from demonstrations without training on the demonstrations themselves. The model answers a request on its own. The same model then reads the request with a demonstration added, and the model's own answer is trained toward what it would say with the demonstration in view.

This page shows the four classes of the SDFT recipe (recipes/sdft/). Write a recipe defines each class: its base class, what it implements, and when Reef calls it.

The ideas of SDFT at the steps of the loop. Inference: the student answers the call without the demonstration. Control: the report holds the demonstration as its teacher_context. Samples: samples.py makes the teacher's request, the student's request with the demonstration block. Control: a job holds the samples as they come. Training: slime/worker.py runs the self-teacher's pass and the KL loss. Control commits a version, and inference serves it. The ideas of SDFT at the steps of the loop. Inference: the student answers the call without the demonstration. Control: the report holds the demonstration as its teacher_context. Samples: samples.py makes the teacher's request, the student's request with the demonstration block. Control: a job holds the samples as they come. Training: slime/worker.py runs the self-teacher's pass and the KL loss. Control commits a version, and inference serves it.

The four classes of SDFT #

SDFT writes two of the four classes itself: the samples class and the algorithm. It takes the other two from Reef.

Attribute

SDFT's class

Written by

What it does in SDFT

report

TeacherContextReport

Reef

A report holds the demonstration of a good answer

samples

SDFTSamples

SDFT

A report becomes the student's call and the teacher's request: the same request with the demonstration

algorithm

SdftAlgorithm

SDFT

Every job trains. The loss moves the student's distribution toward the teacher's, at each token of the student's answer

evaluation

AlwaysActivate

Reef

Every new version serves at once

The recipe class names them (recipe.py):

Python
# control: what a report holds. The demonstration is the report's teacher_context; its references name the
# one model call that the demonstration answers.
report = TeacherContextReport
# samples: what a report becomes. SDFTSamples.make_sample keeps the student's call as the sample and adds the
# teacher's request: the student's request with the demonstration block.
samples = SDFTSamples
# training: SdftAlgorithm trains every job. At each optimizer step it sends each sample's teacher sequence to
# the GPU workers. It names their two functions: the self-teacher's pass before the step, and the KL loss.
algorithm = SdftAlgorithm
# evaluation: every new version serves at once. The deployment's activation section can name another rule.
evaluation = AlwaysActivate

1. The report (control): the demonstration #

Class: TeacherContextReport (teacher_context.py), a class that Reef has.

Implements: the fields of a report (definition).

SDFT needs one thing from the client for each answer: a demonstration of a good answer. The report type has a field for it, teacher_context:

Python
teacher_context: str = ""
score: float | None = None

The client calls the model through Reef, gets the call's receipt, and reports the receipt with the demonstration (client.py):

Python
def demonstrate(receipt: str, demonstration: str) -> None:
    """Report on the call ``receipt``: a demonstration of the answer, as the report's ``teacher_context``."""
    client.report(SCENARIO, {"metadata": {"teacher_context": demonstration}}, references=[receipt])

2. The samples (samples service): the teacher's request #

Class: SDFTSamples (samples.py), written by SDFT.

Implements: make_sample(context) (definition).

The sample of a report is the student's call, with the teacher's request beside it. make_sample does three things:

Python
# 1. The student's call is the sample: the request that the served model read, and its own reply.
#    The teacher's distribution is the training signal, so a reported score is metadata only.
sample = student_sample(self.assembly, context, 0.0 if context.score is None else context.score)
call = student_call(sample)

# 2. The teacher's request is the student's request with the demonstration block added. The block goes
#    to the end of the final user message, as the reference rewrites the question. A request that ends
#    with a tool result gets the block as a new user message, so the demonstration still comes right
#    before the reply.
demonstration = self.settings.context_template.replace(CONTEXT_PLACEHOLDER, report.teacher_context)
messages = normalize_messages_for_template(call.messages)
if messages and messages[-1].get("role") == "user":
    question = str(messages[-1].get("content") or "")
    content = f"{question}\n\n{demonstration}" if question else demonstration
    messages[-1] = {**messages[-1], "content": content}
else:
    messages.append({"role": "user", "content": demonstration})

# 3. The sample holds the teacher's request in its metadata. The training service renders it and puts the
#    student's reply tokens after it: the teacher scores the student's own tokens. A teacher sequence
#    longer than ``max_teacher_tokens`` does not train.
teacher = TeacherRequest(messages, call.tools, max_tokens=self.settings.max_teacher_tokens)
return sample.with_metadata(teacher=teacher.as_json())

The training service later renders both requests with the model's chat template. The student's sequence is the request and then the reply. The teacher's sequence is the teacher's request and then the same reply tokens.

The data of a job. SDFT keeps the default (definition): a job holds its samples as they come. The deployment sets the size of a job to the batch of one optimizer step, so each job is one step (serve.yaml):

YAML
jobs:
  # A job starts when four reports wait: one optimizer step.
  job-samples: ${training.config.global_batch_size}

3. The algorithm (training): the self-teacher and the KL loss #

Class: SdftAlgorithm (slime/algorithm.py), written by SDFT. Its loss is in slime/worker.py.

Implements: name and the loss. It keeps the default prepare_job (definition).

SDFT trains on Slime, so the class is a SlimeAlgorithm. It has two parts.

The class gives the name of the algorithm and names the two functions of the loss:

Python
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 class writes no prepare_job. The default trains every job without advantages: the signal of a sample is its teacher's distribution, which the loss computes. settings_type holds the options of the loss, such as divergence, which a deployment sets under recipe.algorithm.

before_train and loss each name a function as package.module:function. The training service never imports the module, which imports torch: it reads the module's source file and checks that it defines both functions, so a misspelt name fails when Reef starts. Each GPU worker imports the two functions when it starts.

The loss is those two functions in slime/worker.py, which run on the GPU workers. before_train names sdft_actor_pre_train. Before a worker trains the samples of a job, the self-teacher scores the student's reply of each sample:

Python
# 1. The self-teacher is a copy of the model's weights. Before each pass it moves toward the trained weights
#    by ``teacher_update_rate``: 0 keeps the weights of the start, and 1 is the trained model itself.
self_teacher = process_teacher_weights(settings)

# 2. One forward pass on the teacher's weights over each teacher sequence keeps the teacher's distribution
#    at each token of the student's reply. After the pass the model holds the trained weights again.
with timer("distill_teacher"):
    compute_teacher_rows(actor, rollout_data, self_teacher, settings)

loss names sdft_loss. At each optimizer step, the loss is the divergence between the two distributions at each token of the reply:

Python
# 1. The student's logits at each token of its reply.
student_rows = student_response_rows(args, batch, logits)

# 2. The divergence between the teacher's distribution and the student's over the whole vocabulary, at each
#    token. The ``divergence`` setting names it: ``forward``, SDFT's default, is KL(teacher || student).
divergences = full_vocabulary_divergences(
    args, batch, student_rows, divergence=settings.divergence, jsd_beta=settings.jsd_beta
)

# 3. The first ``skip_response_tokens`` tokens of each reply are left out of the loss.
loss_masks, sum_of_sample_mean = leave_out_first_response_tokens(
    args, batch, settings.skip_response_tokens, sum_of_sample_mean
)

# 4. Truncated importance weights: min(p / q, ``importance_sampling_cap``) for each sampled token, where p is
#    its probability under the trained weights and q under the weights that the job started with. At the
#    default ``sequence`` level a sample's weight is the mean over its tokens. A cap of 0 gives no weights.
importance_weights, metrics = truncated_importance_weights(
    args,
    batch,
    logits,
    loss_masks,
    sum_of_sample_mean,
    cap=settings.importance_sampling_cap,
    level=settings.importance_sampling_level,
)

# 5. The loss: for each sample, its weight times the mean of the divergence over its tokens; then the sum
#    over the samples. The sample weight of the wire row is 1 for every SDFT sample.
sample_weights = batch_sample_weights(batch)
loss = sum_of_weighted_sample_means(divergences, importance_weights, sample_weights, sum_of_sample_mean, logits)
metrics.update(loss_metrics(loss, divergences, sample_weights, sum_of_sample_mean))
return loss, metrics

Each numbered step is a function of the distillation library that SDFT shares with the other distillation recipes (reef/train/slime_backend/distill/).

4. The evaluation (evaluation): every version serves #

Class: AlwaysActivate (activation.py), a class that Reef has.

Implements: accepts(scores), with no sides (definition).

The class accepts every version without scores. So every version that a job trains serves at once, and no evaluation task runs. To serve a version only after it passes tasks, name the rule evaluated in the deployment's activation section, or write an Evaluation that reads the scores of the new version.

Run it #

The example runs five steps of SDFT on sums, with Answer: <number> as the demonstration. It needs two GPUs, one to serve the model and one to train it, inside the Reef GPU image, with Qwen/Qwen2.5-1.5B-Instruct in ~/models/.

The deployment file selects the recipe and sets the settings of its classes:

YAML
recipe:
  implementation: recipes.sdft.recipe:SDFTRecipe
  samples:
    # A teacher sequence (the request, the demonstration and the response) longer than the trainer's window
    # does not train.
    max-teacher-tokens: 2048
  jobs:
    # A job starts when four reports wait: one optimizer step.
    job-samples: ${training.config.global_batch_size}
  algorithm:
    # SDFT's own loss: KL(teacher || student) over the whole vocabulary.
    divergence: forward

Start Reef, and run the client in a second terminal:

Shell
export REEF_TOKEN=reef-local
reef serve -c recipes/sdft/examples/quickstart/serve.yaml
Shell
export REEF_TOKEN=reef-local
python recipes/sdft/examples/quickstart/client.py

For each step, the client asks four questions, reports each answer with its demonstration, and waits for the new version:

Python
for index in range(REPORTS_PER_STEP):
    left, right = 10 + step, 30 + 7 * index
    # 1. The served model answers on its own. The receipt names this call.
    _, receipt = ask(f"What is {left} + {right}?", temperature=1.0)
    # 2. The report gives the demonstration for that call.
    demonstrate(receipt, f"Answer: {left + right}")
# 3. Reef trains one step on the four reports and serves the new version.
while (commit := new_version(commit_number)) is None:
    time.sleep(10)

The client prints the loss of each step, and the model's answer to one question before and after. On two H100 GPUs a step takes about three and a half minutes:

Text
before: 'What is 3 + 9?' -> '3 + 9 equals 12.'
step 1: commit 2, loss 1.2190157175064087
step 2: commit 5, loss 0.31696051359176636
step 3: commit 8, loss 0.1347462236881256
step 4: commit 11, loss 0.11605717986822128
step 5: commit 14, loss 0.1879480481147766
after 5 steps: 'What is 3 + 9?' -> "Sure, let's break down the problem step by step:\n\n1. First, I need to ..."

The loss is the divergence between the teacher and the student. The answer moves toward what the teacher says with the demonstration block in view, and the default block asks for "a response of your own, including the thinking process". The example shows the loop of the method. Five steps of four reports do not teach the model the format of the demonstration; the skill stream has the measured results of SDFT on Reef.

Each step saves a checkpoint of about 13 GB under work/checkpoints.

Test it without a GPU #

The tests of the recipe run its classes in memory, with no server and no model. One test sends a report with a demonstration and checks the student's call and the teacher's request of the sample (test_sdft_quickstart.py). Another runs the loss on small tensors on a CPU (test_sdft_worker.py):

Shell
python -m pytest tests/recipes/sdft -q

Use your own model and workload #

Choose a recipe and start from its configuration; keep its GPU layout, loss flags and batch sizes.

  • Set inference.model-path and persistent checkpoint paths.

  • Set recipe.jobs.job-samples, the stored samples per job.

  • Use one chat template for training and serving: a sample that does not render does not train.

  • Set the checkpoint cadence.

Slime trains one scenario per stack. Each job continues from the latest saved checkpoint, served or not; to train from another artifact, use train-from. See Slime training options and the recipe's README.

Train a LoRA adapter #

Start from the TTT-Discover example. Reef's SGLang integration serves adapters; its vLLM integration serves full weights only. Each adapter load pauses generation, and inference.max-loaded-adapters (default 1) sets how many stay loaded. An imported adapter must declare peft_type, contain weights and match the base model (artifact imports). To check it, poll inference/status until the new artifact is ready.

Limits #

  • Slime only. The loss reads the teacher's whole distribution at each token, which Tinker's built-in losses do not take.

  • The teacher of a one-step job is the model as the step starts. Each job starts its own training workers, and the self-teacher is a copy of the weights that the job starts with. teacher-update-rate moves the copy between the steps of one job, so it has an effect only when a job holds several steps.

  • Options outside the method. A separate teacher (teacher: separate), the teacher's values at K tokens (top-k above 0) and score centering are options of the shared distillation library. With one of them, the two functions call the library's own.

Next steps #