All pages
Objective and evaluate
objective is what the optimizer minimizes. evaluate is what every evaluation
pass reports. Both receive the model's prediction and the targets prepare
returned.
(defun objective (prediction targets)
(let ((loss (cross-entropy prediction targets :reduction :sum)))
(metric "train/loss" (/ loss (numel targets))) ; what the summary shows
loss)) ; what is optimized
(defun evaluate (prediction targets)
(metric "eval/loss"
(/ (cross-entropy prediction targets :reduction :sum)
(numel targets))))objective
- Returns one float scalar; anything else is
E-OBJ-001, with the shape it did return. - Several losses are one weighted sum; report the parts with
metric. To weigh each by its own running average, see below. Named contributions can report each term's parameter-gradient RMS by optimizer group. - Its value is emitted every step as
train/objective, averaged over the step's microbatches, whatever it is called and however it reduces. - Written with three parameters, it also receives the extra keys of
prepare's plist asmetadata. - Written with four, it also receives
ctx, the builtin keys of ctx without the counters, so a loss weight can follow the run's schedule. They are bound for every microbatch; a step's:stepand:progressare those of the update being computed.evaluatereceives noctx.
(defun objective (prediction targets metadata ctx)
(let ((aux-weight (* 0.3 (- 1.0 (getf ctx :progress))))) ; annealed to 0
(metric "aux/weight" aux-weight)
(+ (fit (first prediction) targets)
(* aux-weight (aux-loss (nth 1 prediction) targets)))))On CUDA a training graph that reads ctx does not stack its microbatches;
explain --device cuda says so on its stacking line.
- In reverse mode, gradients are of the objective as written: a sum and a mean
give different gradient scales.
tap-gradientsees exactly that adjoint.
A running average of a loss
A buffer cannot follow a loss: its update reads
nothing derived from a batch. A trainable parameter can, exactly. Its gradient
level - loss under plain SGD at rate 1 - decay makes it
decay * level + (1 - decay) * loss. Here each task's loss is divided by its
own running average, so the tasks pull on the shared weights at a comparable
scale:
(require "sexpgpu/nn" cross-entropy)
(require "sexpgpu/optim" adamw sgd)
(defknobs
(microbatches 8)
(decay 0.99))
(defmodel loss-level (tasks)
(defparam value (ones [tasks]) :numerics :high)
(lambda (losses) ; [tasks], one loss each
(let ((gap (- value (stop-gradient losses))))
(+ (sum (/ losses (stop-gradient value))) ; what the shared weights see
(* 0.5 (sum (* gap gap))))))) ; what moves the level
(defvar level (loss-level 2)) ; a root of its own: level.value
(defun objective (prediction targets metadata)
(let ((words (cross-entropy (first prediction) targets))
(tags (cross-entropy (nth 1 prediction) (getf metadata :tags))))
(metric "train/words" words)
(metric "train/tags" tags)
(level (concat 0 [(reshape words [1]) (reshape tags [1])]))))
(defvar optimizer
(adamw :lr 3e-4
:weight-decay 0.1
:groups [(group (select-and (select :rank-below 2)
(select-not (select "level.*")))
:weight-decay 0.0)
(group (select "level.*")
:optimizer (sgd :lr (/ (- 1 decay) microbatches)))]))
(defrun :steps 10000 :microbatches microbatches ...)-
The two
stop-gradients keep the parts apart: the shared weights get each loss divided by its level, and the level gets onlylevel - loss. -
Gradients add up over a step's microbatches and across GPUs, so the level's is
microbatches * (level - mean),meanbeing the step's mean loss. The rate(1 - decay) / microbatchesmakes the leveldecay * level + (1 - decay) * meanon any number of GPUs;1 - decayalone decays by1 - microbatches * (1 - decay)instead, and swings once that is negative. -
(select :rank-below 2)matches the level, a vector, too: without theselect-notit is in two groups,E-OPT-002. Its ownsgdhas no weight decay and no state. -
The first step divides by the initializer. Start the level near the losses you expect, or give step zero the rate
1 / microbatches, so that the second step already divides by the first step's mean:(sgd :lr (lambda (ctx) (let ((later (cast (minimum (getf ctx :step) 1) :f32))) (/ (- 1.0 (* decay later)) microbatches)))) -
:numerics :highkeeps the levelf32under:precision :bf16; without it the objective reads the level rounded tobf16. Between nodes the defaultbf16gradient sum rounds the level's gradient too;SEXPGPU_NODE_GRADIENTS=f32keeps it exact. -
The level is a parameter: a checkpoint stores it, and a resume continues it as the uninterrupted run would.
-
train/objectiveincludes the tracking term0.5 * (level - loss)^2; read the tasks' own metrics. -
The same pattern follows any scalar of a batch: a gradient
level - xtracks the mean ofxover the step's microbatches.
Forward-query training
:gradient :forward-query in defrun trains without
differentiating the objective. For every microbatch the run draws a direction
z, one sign, +1 or -1, for each element of each trainable parameter, evaluates
the objective at parameters + radius * z and at parameters - radius * z, and
gives the optimizer (loss+ - loss-) / (2 * radius) * z where reverse mode
gives the gradient. The same defoptimizer updates the parameters, and the
microbatches of a step, on one GPU or several, add up their estimates as they
add up gradients: a step takes one direction per microbatch.
(defrun :steps 2000 :microbatches 8 :gradient :forward-query :query-radius 1e-3)- An estimate points along the gradient on average, but one is far larger and
noisier: roughly the square root of the number of parameter elements over the
number of microbatches times the gradient's size. Start from a learning rate
far below the reverse-mode recipe's, and raise
:microbatchesto average more directions. - A microbatch evaluates the model twice and runs no backward pass. On CUDA the microbatches are not stacked.
- A direction is a random draw like
uniform's, keyed by the parameter's path and:seed, and new for every step and microbatch, so a resume draws the same directions as the uninterrupted run; see determinism. A draw inside the model, a dropout mask, is the same at both points. stop-gradientholds: what it wraps is computed at the parameters themselves, so the estimate is of the gradient reverse mode would take.train/objective, everymetricand every diagnostic report the mean of their values at the two points. A guard counts at both, so a loss that stops being finite stops the run with that guard'sE-GUARD-001, as in reverse mode, its count taking in both evaluations.- A selected diagnostic that reads a
tap-gradientisE-CONTRACT-022: there is no gradient for it to read. - The radius moves every element by the same amount, so with
:precision :bf16it has to be large enough to change the weights the model computes with: the default1e-3is lost on a weight of size 0.5 or more. explainshows the run'sgradientrow in its training step.
Forward-credit training
:gradient :forward-credit trains with errors that the experiment computes in
the forward graph. A call has the form
(forward-credit parameter activation input score): score has the same shape
as activation, and the input and activation share their leading axes. A float
input gives the ordinary outer product. An integer input can index rows of a
matrix parameter, so an embedding update uses token ids and accumulates the
corresponding score rows without materializing one-hot vectors. A matrix
parameter is [input, output], so its dense update is the sum of
inputᵀ * score; a vector parameter sums input * score over the leading axes.
Every trainable parameter needs a map. The compiler emits these updates as
ordinary graph outputs and builds no backward graph.
Forward credit is a local credit rule chosen by the experiment. It can match the
objective gradient when the supplied scores do, but it can also deliberately
send a different learning signal through a residual block. It has no
:query-radius; use :gradient :forward-query when the objective itself should
be estimated by parameter perturbations.
evaluate
- Returns nothing useful; it emits metrics with
metric. - Runs on every evaluation pass, after
eval-prepareand the model, over that pass's loader. - Each metric is averaged over the batches the pass reads, tagged with the pass name, and offered to the curriculum by name.
- Required when a pass exists; an
evaluatewith no pass isE-CONTRACT-014.
Two names the runtime reads
| name | effect |
|---|---|
train/loss | when objective reports it, the summary, the status file and the progress line show it instead of the objective, so a run optimizing a sum still prints the mean per token |
eval/loss | when evaluate reports it, sweep's table shows it instead of the first metric the evaluation reported |
metric, its metadata and what it becomes in each place are in
metrics. A number about how the
model is doing rather than how well is a diagnostic instead.
Related: the run file, sexpgpu/nn (cross-entropy).