algorithm = "custom" for DPO, distillation, or another objective that needs
its own training loop. Your Python script runs on your machine and calls a
managed Flash GPU for sampling, scoring, backward passes, and optimizer steps.
You own data loading, prompt formatting, rewards, and logging.
Custom training supports all six catalog models with
text-only inputs on one or two Modal GPUs. Set train.max_context_tokens and
train.lora_rank to adjust sequence length and adapter rank, using the same
model context and rank limits
as SFT and GRPO. Flash selects the cheapest available GPU that fits your
model, context, and rank. Custom losses materialize full-vocabulary logits, so
a shape that fits SFT may need a larger GPU for custom training; shapes that
cannot fit the selected GPU shape are rejected. Images and the built-in thinking
switch are not supported in this mode. Custom distillation scripts supply their
own teacher access.
Start from a DPO example
Install the custom-loss extra in the Python environment running the CLI, then create an editable script and matching config:flash custom init creates algorithm.py and algorithm.toml, preserving
existing files by refusing to overwrite them. The starter demonstrates paired
chosen/rejected answers, a frozen reference distribution, a local PyTorch DPO
loss, metrics, and checkpoint state. Replace its toy pairs with your data.
algorithm.toml
[environment],
[wandb], or thinking: the local script owns those concerns. Set learning
rates in client.optim_step(...), not in [train]. See
Custom configuration for the accepted fields.
max_wall_seconds, not a prediction of your script’s runtime.
Use two GPUs for a larger model
Custom training defaults to one GPU. Set[gpu] count = 2 to allow a two-GPU
Modal worker. Flash can still select one card if it fits and costs less; count
is a ceiling, consistent with other training modes. The worker splits whole
model layers across its allocated GPUs, keeping weights and optimizer state on
GPU. This provides more model capacity, not data-parallel throughput scaling.
CPU/disk offload and more than two GPUs are not supported for custom training.
For example, configure the 35B MoE at rank 64 and 8,192 tokens:
flash train algorithm.toml --cost
to check the selected shape before launching.
Write the training loop
Defineasync def main(client) for nonblocking local control, or
def main(client) for blocking calls. For the async form, await every operation:
Construct batches with
from flash.custom import Datum. A Datum holds a list
of token IDs and optional weights. Position i scores the next token,
tokens[i + 1], so each row has len(tokens) - 1 log probabilities or weights.
A batch contains at most 16 rows. Each row has at least two tokens and must fit
train.max_context_tokens.
forward_backward requires explicit weights and computes the sum of
-weight * logprob across tokens and rows. Set prompt-target weights to zero
and apply your own averaging denominator. Gradients accumulate until
optim_step or zero_grad.
For forward_backward_custom, define loss_fn(data, logprobs) returning a
finite scalar PyTorch tensor and a dictionary of finite numeric metrics. The
provided log-probability tensors support local autograd, including losses that
compare multiple sequences. The generated DPO starter shows this pattern.
Operations within one session execute in order. Async control lets other local
work run while awaiting the GPU; it does not run simultaneous optimizer
mutations. If a request fails with an unresolved outcome, call
retry_pending() before issuing another operation. This retries the pending
operation without applying it twice.
Train with soft targets
UseDatum(..., target_tokens=...) to score several candidate tokens at each
position. This supports distillation from a teacher’s top-K distribution as well
as custom losses over selected tokens.
Without target_tokens, position i scores tokens[i + 1] as above. With it,
target_tokens[i] lists the candidate token IDs to score after the prefix ending
at tokens[i]. The matrix must have len(tokens) - 1 rows and a fixed width
of 1–64 candidates. Returned logprobs have the same matrix shape, and
forward_backward requires weights of that shape too. A request can contain
at most 100,000 target entries across its batch; split larger batches.
For a teacher and student using the same token IDs, a distillation update in an
async controller can look like this:
-sum(weights * logprobs) over all positions and candidates. Use
probabilities as weights, not log probabilities; zero prompt-only positions
and unused cells, and divide weights by your chosen averaging denominator.
Top-K probabilities may sum to less than one: decide whether to retain that
mass or renormalize it for your objective. Token IDs must use the student’s
vocabulary; do not copy IDs from a teacher with a different tokenizer.
forward_backward_custom also accepts these rows. Its loss_fn(data, logprobs)
receives a [T, K] tensor for each row with explicit targets, so you can write a
local differentiable loss over candidate probabilities. The top_k option on
forward returns model-selected alternatives; target_tokens chooses which
tokens your loss scores.
Keep the controller running
Theflash train process is your controller. Run it in a persistent terminal
such as tmux; --background is rejected for custom training. Ctrl-C cancels
the run and preserves completed checkpoints. An unhandled script exception
also cancels it. This differs from SFT and GRPO, where Ctrl-C only detaches.
Flash reserves the GPU while your script prepares data or waits for external
rewards. Charges use measured session time, capped at the accepted wall-time
quote. The session also stops at its idle or wall-time limit. See
Custom-session billing.
Use the normal run commands from another terminal:
Warm-start an adapter
Usetrain.init_from_adapter to initialize custom training from an existing
adapter, including SFT or GRPO, with fresh optimizer and algorithm state:
lora_rank and lora_alpha: Flash
inherits them from the source adapter. The source must fit the receiving
custom-training limits. Do not combine this with custom.resume_from.
Warm-starting begins a new optimization run; durable resume below continues
saved custom optimizer and algorithm state.
See the custom-client reference for operation
arguments, response fields, input limits, and recovery behavior.
Resume a checkpoint
Pass a JSON-serializablealgorithm_state object of at most 1 MiB to optim_step so periodic saves
include your data cursor, reference scores, and other algorithm state. Automatic
saves occur on the save_every cadence, at save_at_steps, and at the final
step; the final adapter is also published.
The script is responsible for restoring its own state from
client.restored_state and continuing from client.step.
To continue, submit a new run with the exact saved step:
max_steps must exceed the restored step and is the total target,
not the number of additional steps. /final is not a custom-resume selector; train.init_from_adapter starts a
new optimization run rather than restoring custom optimizer state. In-place load_checkpoint is unavailable for
managed sessions; use custom.resume_from for durable continuation.
You can resume on a different supported GPU shape if it fits. Keep the same
shape when reproducing a random sampling trajectory; changing device count
changes how CUDA random state is distributed.
Custom runs do not automatically retry a failed local controller. Restart from
a completed checkpoint. Deploy or download the saved adapter with the normal
checkpoint workflow.