autodiff

package
v0.28.44 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 14 Imported by: 2 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package autodiff implements reverse-mode automatic differentiation (symbolic backpropagation) for GoMLX computation graphs (graph.Graph).

Its main entry point is Gradient, which appends graph nodes computing the partial derivatives of a scalar output with respect to selected target nodes using Vector-Jacobian Products (VJP). It also honors graph.StopGradient, custom gradients via graph.IdentityWithCustomGradient, and activation checkpointing via graph.Node.Checkpoint / graph.Node.StopCheckpoint.

Index

Constants

This section is empty.

Variables

View Source
var VJPRegistration = map[graphimpl.NodeType]VJP{
	graphimpl.NodeTypeInvalid:                        vjpForSingleOutput(noOpVJP),
	graphimpl.NodeTypeConstant:                       vjpForSingleOutput(nilVJP),
	graphimpl.NodeTypeParameter:                      vjpForSingleOutput(nilVJP),
	graphimpl.NodeTypeConvertDType:                   vjpForSingleOutput(convertDTypeVJP),
	graphimpl.NodeTypeWhere:                          vjpForSingleOutput(whereVJP),
	graphimpl.NodeTypeNeg:                            vjpForSingleOutput(negVJP),
	graphimpl.NodeTypeAbs:                            vjpForSingleOutput(absVJP),
	graphimpl.NodeTypeExp:                            vjpForSingleOutput(expVJP),
	graphimpl.NodeTypeExpm1:                          vjpForSingleOutput(expm1VJP),
	graphimpl.NodeTypeLog:                            vjpForSingleOutput(logVJP),
	graphimpl.NodeTypeLog1p:                          vjpForSingleOutput(log1pVJP),
	graphimpl.NodeTypeCos:                            vjpForSingleOutput(cosVJP),
	graphimpl.NodeTypeSin:                            vjpForSingleOutput(sinVJP),
	graphimpl.NodeTypeTanh:                           vjpForSingleOutput(tanhVJP),
	graphimpl.NodeTypeAdd:                            vjpForSingleOutput(addVJP),
	graphimpl.NodeTypeSub:                            vjpForSingleOutput(subVJP),
	graphimpl.NodeTypeMul:                            vjpForSingleOutput(mulVJP),
	graphimpl.NodeTypeDiv:                            vjpForSingleOutput(divVJP),
	graphimpl.NodeTypePow:                            vjpForSingleOutput(powVJP),
	graphimpl.NodeTypeSqrt:                           vjpForSingleOutput(sqrtVJP),
	graphimpl.NodeTypeRsqrt:                          vjpForSingleOutput(rsqrtVJP),
	graphimpl.NodeTypeErf:                            vjpForSingleOutput(erfVJP),
	graphimpl.NodeTypeBatchNormForTraining:           batchNormForTrainingVJP,
	graphimpl.NodeTypeFusedDense:                     vjpForSingleOutput(fusedDenseVJP),
	graphimpl.NodeTypeFusedQuantizedDense:            vjpForSingleOutput(fusedQuantizedDenseVJP),
	graphimpl.NodeTypeFusedLayerNorm:                 vjpForSingleOutput(fusedLayerNormVJP),
	graphimpl.NodeTypeFusedRoPE:                      vjpForSingleOutput(fusedRoPEVJP),
	graphimpl.NodeTypeFusedActivation:                vjpForSingleOutput(fusedActivationVJP),
	graphimpl.NodeTypeFusedScaledDotProductAttention: fusedScaledDotProductAttentionVJP,
	graphimpl.NodeTypeFusedTopK:                      fusedTopKVJP,

	graphimpl.NodeTypeLogicalAnd: vjpForSingleOutput(zeroVJP),
	graphimpl.NodeTypeLogicalOr:  vjpForSingleOutput(zeroVJP),
	graphimpl.NodeTypeLogicalXor: vjpForSingleOutput(zeroVJP),
	graphimpl.NodeTypeLogicalNot: vjpForSingleOutput(zeroVJP),
	graphimpl.NodeTypeBitwiseAnd: vjpForSingleOutput(zeroVJP),
	graphimpl.NodeTypeBitwiseOr:  vjpForSingleOutput(zeroVJP),
	graphimpl.NodeTypeBitwiseXor: vjpForSingleOutput(zeroVJP),
	graphimpl.NodeTypeBitwiseNot: vjpForSingleOutput(zeroVJP),

	graphimpl.NodeTypeReal:    vjpForSingleOutput(realVJP),
	graphimpl.NodeTypeImag:    vjpForSingleOutput(imagVJP),
	graphimpl.NodeTypeConj:    vjpForSingleOutput(conjVJP),
	graphimpl.NodeTypeComplex: vjpForSingleOutput(complexVJP),

	graphimpl.NodeTypeMax:                   vjpForSingleOutput(minMaxVJP),
	graphimpl.NodeTypeMin:                   vjpForSingleOutput(minMaxVJP),
	graphimpl.NodeTypeReshape:               vjpForSingleOutput(reshapeVJP),
	graphimpl.NodeTypeReduceSum:             vjpForSingleOutput(reduceSumVJP),
	graphimpl.NodeTypeReduceMax:             vjpForSingleOutput(reduceMaxVJP),
	graphimpl.NodeTypeReduceMin:             vjpForSingleOutput(reduceMinVJP),
	graphimpl.NodeTypeLogistic:              vjpForSingleOutput(logisticVJP),
	graphimpl.NodeTypeDotGeneral:            vjpForSingleOutput(dotGeneralVJP),
	graphimpl.NodeTypeSlice:                 vjpForSingleOutput(sliceVJP),
	graphimpl.NodeTypeGather:                vjpForSingleOutput(gatherVJP),
	graphimpl.NodeTypeScatterSum:            vjpForSingleOutput(scatterSumVJP),
	graphimpl.NodeTypeScatterMax:            vjpForSingleOutput(scatterMaxOrMinVJP),
	graphimpl.NodeTypeScatterMin:            vjpForSingleOutput(scatterMaxOrMinVJP),
	graphimpl.NodeTypeConcatenate:           vjpForSingleOutput(concatenateVJP),
	graphimpl.NodeTypeConvGeneral:           vjpForSingleOutput(convGeneralVJP),
	graphimpl.NodeTypeReduceWindow:          vjpForSingleOutput(reduceWindowVJP),
	graphimpl.NodeTypeTranspose:             vjpForSingleOutput(transposeVJP),
	graphimpl.NodeTypeBroadcastInDim:        vjpForSingleOutput(broadcastInDimVJP),
	graphimpl.NodeTypeDynamicBroadcastInDim: vjpForSingleOutput(dynamicBroadcastInDimVJP),
	graphimpl.NodeTypeFFT:                   vjpForSingleOutput(fftVJP),
	graphimpl.NodeTypeDynamicSlice:          vjpForSingleOutput(dynamicSliceVJP),
	graphimpl.NodeTypeDynamicUpdateSlice:    vjpForSingleOutput(dynamicUpdateSliceVJP),
	graphimpl.NodeTypeDynamicDimensionSize:  vjpForSingleOutput(zeroVJP),
	graphimpl.NodeTypeDynamicReshape:        vjpForSingleOutput(dynamicReshapeVJP),
	graphimpl.NodeTypeDynamicShape:          vjpForSingleOutput(zeroVJP),
	graphimpl.NodeTypeCumMax:                vjpForSingleOutput(cumMaxVJP),
	graphimpl.NodeTypeCumSum:                vjpForSingleOutput(cumSumVJP),
	graphimpl.NodeTypePad:                   vjpForSingleOutput(padVJP),
	graphimpl.NodeTypeDynamicPad:            vjpForSingleOutput(dynamicPadVJP),
	graphimpl.NodeTypeIota:                  vjpForSingleOutput(zeroVJP),
	graphimpl.NodeTypeDynamicIota:           vjpForSingleOutput(zeroVJP),
	graphimpl.NodeTypeNonZero:               vjpForSingleOutput(zeroVJP),
	graphimpl.NodeTypeReverse:               vjpForSingleOutput(reverseVJP),
	graphimpl.NodeTypeOptimizationBarrier:   vjpOptimizationBarrier,
	graphimpl.NodeTypeSchedulingBarrier:     vjpForSingleOutput(vjpSchedulingBarrier),
}

VJPRegistration maps each node type to its implementation of VJP. If implementing a new outputOps, or for experimentation, one can dynamically change this.

Notice xla.GetTupleElementNode is specialized inside the main reverse autodiff code, and is not in the table here.

Functions

func Gradient

func Gradient(output *graph.Node, gradientNodes ...*graph.Node) []*graph.Node

Gradient builds new graph nodes representing the reverse-mode partial derivatives of scalar `output` with respect to each node in `gradientNodes`, returning one gradient node per target in the same order and with the same shape and DType as the corresponding target.

How it works:

  • Reverse-mode backpropagation (VJP): Starting from adjoint `1` at `output`, Gradient walks backwards in topological order along the subgraph connecting `gradientNodes` to `output`, accumulating Vector-Jacobian Products at each node into new nodes on the same graph.Graph.
  • Disconnected or stopped targets: If no differentiable path reaches a node in `gradientNodes` (for example because it was unused or blocked by graph.StopGradient), its returned gradient is graph.ZerosLike(node).
  • Custom gradients & checkpointing: Per-node custom gradients set with graph.IdentityWithCustomGradient take precedence over VJPRegistration. Nodes inside a checkpointed region (graph.Node.Checkpoint / graph.Node.StopCheckpoint) are lazily rematerialized on the backward pass using scheduling barriers so activations don't have to be kept alive across the forward pass.
  • Higher-order gradients: Because Gradient appends standard graph.Node operations to the graph, higher-order derivatives can be computed by calling Gradient again on a scalar derived from its outputs (provided the backward ops involved have registered VJPs).

Constraints and panics:

  • `output` must be a non-complex scalar (`output.Rank() == 0 && !output.DType().IsComplex()`); if your loss is non-scalar, reduce it first (e.g. with graph.ReduceAllSum or graph.ReduceMean).
  • `output` and all `gradientNodes` must belong to the same graph.Graph while it is still being built (before compilation).
  • Panics if an operation on a differentiable path from `gradientNodes` to `output` has no custom gradient and no entry in VJPRegistration.

Example:

loss := graph.ReduceAllSum(graph.Add(graph.Square(x), graph.Mul(x, y)))
grads := autodiff.Gradient(loss, x, y)
gradX, gradY := grads[0], grads[1]

Types

type SingleOutputVJP

type SingleOutputVJP func(node, v *graph.Node, outputShape shapes.Shape) []*graph.Node

SingleOutputVJP for VJP of ops that have a single output (most of them).

type VJP

type VJP = graph.VJP

VJP returns the $v \dot Jacobian$ of the given `node`, with respect to each of its inputNodes (given by `node.Inputs()`).

outputShape is the shape of the value for which we are calculating the gradient for. For now this is only used for Gradient, so one can expect outputShape to be scalar, and `v.Shape()` to be the same as `output.Shape()`. But this won't be true once Jacobian functionality (like a Gradient where output is a non-scalar tensor), is defined.

Args:

node: node for which we are calculating the backward gradient. An important part of `node` are its inputNodes
   given by `node.Inputs()`. The VJP function must one gradient per input.
v: gradient (or jacobian) of what we care about with the respect to the output of `node`, also known as the
   adjoint. VJP needs to calculate the next adjoint (`v`) but with respect to the inputNodes of `node` instead.
outputShape: for now fixed as scalar, and can be ignored. When we add support for Jacobian this will hold
   the outputShape of the thing we are calculating the Jacobian for.

Returns:

The adjoint (the updated `vjps`) to each of `node` inputNodes. That is, the gradient of the loss (typically, but of
whatever we are calculating the gradient of) with respect to each of the `node` inputNodes.

VJP is an alias to graph.VJP.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL