S-exp GPU
All pages
Docs · The run fileMarkdown

Generation inside the step

defgenerate makes records on the device, inside each training step, before the step's training graph reads them: a student sampling its own rows, a frozen teacher labelling them, a pool scored and cut down to the rows worth a gradient. It is a loop of ordinary graphs, and nothing is differentiated through it.

(defgenerate :trips 6
             :init (lambda (batch ctx) (list :row ... :stride ...))
             :step (lambda (state trip ctx) (list :row ... :stride ...))
             :finish (lambda (state ctx) (list :sample ... :label ...)))
keywordmeaning
:passesoptional: the evaluation passes it runs for, and never in training. See generators for passes
:tripshow many times :step runs, 1 or more
:initthe batch, as prepare receives it, and the step's context, to the state: a plist of tensors, a keyword before each
:stepthe state, the trip as an i64 scalar and the context, to the next state, with the keys, shapes and dtypes :init made
:finishoptional: the last state and the context, once, to any plist of tensors
:untiloptional: the state a trip returned and the context, to one bool scalar; true ends the trips. See until

Each training microbatch runs :init on its batch, :step :trips times and :finish once, the state staying on the device. What :finish returned, or the last state without one, joins the batch: prepare reads each entry with (field batch :name) as it reads a loader field, so a generated name may not be a field of the training loader or of any pass's loader. An evaluation pass whose loader has the training loader's fields and batch size runs the generator on its batches too; a pass whose loader differs does not, and its prepare reading a generated name is E-CONTRACT-005. With several training loaders :init receives one batch of each, and no pass runs the generator. A generator only some passes need is declared for them with :passes.

The state has static shapes. A sequence written one position per trip is a fixed-size tensor written with where at the trip's column; a cache is the same. Here the student writes each row greedily, one position per trip, and :finish labels every position by the rule it is learning:

:step (lambda (state trip ctx)
        (let* ((row (getf state :row))
               (at (+ (cast trip :i32) 2))
               (column (iota [1 seq] :axis 1))
               (guess (sum (where (= column (- at 1)) (argmax (model row)) 0)
                           :axes [1]
                           :keepdims true)))
          (list :row (where (= column at) guess row)
                :stride (getf state :stride))))

Until

:until ends the trips early. It runs after every trip on the state that trip returned, and when it returns true no further trip runs: :finish gets that state, or it joins the batch. It never runs on the state :init made, so at least one trip runs, and at most :trips. One that never returns true gives the run without it.

:until (lambda (state ctx)
         (let ((done (getf state :done)))
           (> (min done) 0.5)))
  • One flag for the batch. :until returns one bool scalar; anything else is E-GEN-006. A state with a flag per row stops when every row has, so reduce over the rows, as (min done) does here, and count padding rows as done.
  • Exact. The state at the exit is the state the same trips give without :until in that execution. A state column a later trip would have written keeps what :init put there, and every shape stays as declared, so per-trip records past the exit read :init's values.
  • Checked every trip. The device waits for each trip to read the flag, so an :until that would stop near the end costs a little more than none; one that stops early saves the trips it skips. runtime/generate_trips reports the mean trips a generation ran; see metrics.
  • A batch stops as a whole. Its rows run until the last of them is done; a smaller batch stops closer to each row's own end. Batches do not refill finished rows.
  • Not stacked. A run whose generator has :until runs every microbatch in a call of its own, since each batch stops at its own trip; the lowering report's stacking line says so. Data-parallel ranks each stop on their own batches.
  • Reports nothing. :until is part of the generator: a metric inside it is E-GEN-004.

Persistent training slots

:persistent (lambda (state ctx) reset-mask) carries a training generator's state across optimizer steps. The function runs on the state :step returned and returns a bool vector, one flag per loader row. A true flag replaces that slot's example before the next step. The terminal state still trains once.

(defgenerate :trips 1
             :persistent (lambda (state ctx) (>= (getf state :age) 32))
             :init (lambda (batch ctx)
                     (list :example (field batch :input)
                           :age (zeros [batch-size] :dtype :i64)))
             :step (lambda (state trip ctx)
                     (list :example (getf state :example)
                           :age (+ (getf state :age) 1))))
  • One GPU or CPU device, :trips 1, and no :until. Other configurations fail with E-GEN-008. A trip may compute several model rounds with ordinary tensor operations.
  • A slot owns its example, targets and augmentation until reset. Put every value that must survive in the state, including stopping counters and the recurrent state. Slot identity is its position in the pool, rather than a dataset key. The runtime applies no task-specific stopping rule.
  • Initially every slot resets. Replacements consume the next source records in slot order, keeping unused prefetched records for later resets. Slots without a reset keep their state exactly. Initialization receives every slot's example fields when any slot resets; only reset rows of its returned state replace old state. Initialization that mixes rows should account for this full-pool context. With no resets, initialization and loading are skipped.

Several loaders and microbatches

With several training loaders, each loader's rows are its own slots. :persistent returns a list with one mask per loader, in the loaders' order. A nil mask means every row of that loader is fresh each step, as an ordinary loader's rows are:

(defgenerate :trips 1
             :persistent (lambda (state ctx)
                           (list (>= (getf state :maze-age) 128) nil))
             :init (lambda (batch ctx)
                     (list :maze-cells (field batch :maze)
                           :maze-core (zeros [maze-batch width])
                           :maze-age (zeros [maze-batch] :dtype :i64)
                           :board-cells (field batch :board)))
             :step (lambda (state trip ctx) ...))
  • Every state tensor belongs to one loader, and its first axis is that loader's batch size. A tensor computed in :init from one loader's fields belongs to that loader. A tensor computed from no field belongs to the loader whose mask reads it, or else to the only loader with that batch size. sexpgpu explain lists each loader's state. A tensor computed from two loaders' fields, or one whose owner the run cannot tell, is E-GEN-008.
  • A reset of a loader's slot replaces that row of its own loader's state only. Another loader's state in the same row index is kept. A reset takes the replacement from the slot's own loader. Above, each maze keeps its core for up to 128 steps while every board is fresh each step.
  • With :microbatches above 1, each microbatch has its own slots for every loader, so the pool holds microbatches times each loader's batch. A microbatch always reads its own slots. Replacements take a loader's records in microbatch order, then slot order. Microbatches carrying slots run one call each rather than stacked.

Steps, checkpoints and costs

  • Each step advances one trip using the trained weights at that step's start, then trains from its output. The carried value is that generator output, before :finish, rather than the graded model call's final state. No gradient crosses steps. The trip argument is zero on every step; use ctx :step or a counter in state for draws that must change between steps.
  • State and source consumption commit with a completed optimizer step. Checkpoints keep the pool, reset flags and each loader's unused source records. Resume requires the same slot shapes, loaders and microbatches. An interrupted generation replays from the last completed step. To add or remove persistence, start a fresh run, optionally loading the model weights, instead of resuming a checkpoint with another state schema.
  • A curriculum-stage change resets the whole pool and drops unused records of the old stage. Loader exhaustion follows the loader's ordinary behavior. records counts newly consumed examples; an example used on several steps counts once. Declare a separate counter to count training visits.
  • Evaluation uses fresh, ephemeral state for each batch and never advances the training pool. :persistent is not accepted on a generator with :passes. Inference and exported model weights contain no training slots.
  • The pool stays on the device between steps. Retaining both committed and proposed state increases memory, by each microbatch's slots. Reset masks require a device wait each step, and replacement initialization and loading have their ordinary costs. Reset decisions and resume follow the numerical contract in determinism; rounding on another device can change a reset.

Generators for passes

A generator with :passes runs for the passes it names and nowhere else: not in the training step, and not in any other pass. Each named pass runs it on every batch of its own loader, whatever that loader's fields and batch size, and its prepare reads what it makes. Closed-loop play is the usual case: the pass reads levels, the generator plays them, and the pass's evaluate scores the play, while the training step pays nothing for it.

(defeval hard
  :loader hard-levels
  :every 2000
  :prepare play-prepare
  :evaluate play-evaluate)
(defeval medium
  :loader medium-levels
  :every 2000
  :prepare play-prepare
  :evaluate play-evaluate)

(defgenerate :passes [hard medium]
             :trips 120
             :init (lambda (batch ctx) (list :board (field batch :cells) ...))
             :step (lambda (state trip ctx) ...)
             :until (lambda (state ctx) (> (min (getf state :done)) 0.5)))
  • Names, as defeval writes them. :passes is a vector of pass names, not evaluated. A name no defeval declares is E-GEN-007, with the nearest, so a pass declared under a when takes its generator under the same when.
  • One generator a pass. A pass runs the generator whose :passes names it, else the training generator when its loader fits that one, else none. Two :passes naming one pass, or two generators without :passes, is E-GEN-007. A file can hold one training generator and any number for passes.
  • Its own state. Each generator has its own trips, state and :until; the names it makes may not be fields of its passes' loaders (E-GEN-003). The passes it names may read different fields, or batches of different sizes, and each such loader traces the generator's graphs once.
  • Rows out. Its :finish may record the state its trips left, a table of rows the pass writes out: the boards each level ended on, say, or the first one off the plan.
  • Everything else as in training. It reads the weights its pass reads, under defrun :ema too; runtime/generate_trips is reported for each pass that ran it; and sexpgpu evaluate builds it for the passes it runs. sexpgpu explain lists its graphs as generate.<pass>.init and so on, once for each batch its passes read, <pass> the first pass the file declares that reads that batch.

What a generator may read

  • The batch's fields in :init, the state in :step and :finish, and every parameter, frozen or not: the model model binds, or any model reachable from it, runs inside a generator as it does in objective, at the parameters the step started from. Before an evaluation pass it reads the weights that pass reads: under defrun :ema the averages, unless the pass says :ema false, inline and in sexpgpu evaluate alike.
  • The context: the builtin keys of ctx only, and the trip as :step's second argument. Counters are declared in prepare, which runs after the generator, so (getf ctx :tokens) is nil there. A generator that reads :microbatch, :records or :stage-records keeps the run unstacked, since those move between the microbatches one stacked call holds.
  • A draw is a pure function of the seed, its place and its salt; see random draws. An unsalted draw is the same at every step and microbatch. Salted with (+ (* (getf ctx :step) 65536) (getf ctx :microbatch)) it is new for every microbatch, and the :microbatch keeps the run unstacked; a salt of :step alone is new every step and stacks.

What a generator may not do

  • Report: a metric inside it is E-GEN-004; return the value in the state and report it from objective. A diagnostic inside it, which a model it runs may well call, is never selected and is dropped, as an unselected diagnostic is anywhere.
  • Declare a counter: counter belongs to prepare (E-CONTRACT-010).
  • Change the state's keys, shapes or dtypes from trip to trip (E-GEN-002), or return anything but a plist of tensors (E-GEN-001). Under :bf16 a state entry keeps the dtype it was made with, so a cache can be bf16 from trip to trip.

A phase of the step

  • Stacking. A run that stacks microbatches stacks the generator to the same degree, each copy with its own batch and state. Stacking can change rounding; it does not promise the bits of microbatches run one at a time. A generator with :until keeps the run unstacked.
  • Memory. Each generator graph is a phase of the memory plan, holding the batch :init read and the state the trips carry; what it made lives until the training call that reads it. The report's memory line shows the largest, generation 0.4 GiB; see devices.
  • Signals. The loop looks for a signal before every trip; a stop abandons the step in flight, and the resume takes it again. See checkpoints.
  • Reports. sexpgpu explain lists generate.init, generate.step, generate.finish and generate.until with the graphs and the trips under the training step; the lowering report has a generate row, generate stacked when the run stacks, and a generation line. Each step and each pass that ran the generator reports runtime/generate_trips.
  • Determinism. A generator adds nothing to a checkpoint's identity, and the trip is an input like the step. Where :until stops depends on the state, so a device that rounds differently can stop a batch at another trip; see determinism.

Related: the run file, diagnostic codes.

A generator value for a pass

(generator :trips n :init start :step next [:finish finish] [:until done] [:persistent state]) returns a generator value without declaring it. Attach it to an eval-pass with :generator; selection attaches it only to that pass. It takes no :passes option. defgenerate remains the declaration for training or legacy named passes.