grad()
Function in IR
Differentiate a function of a module with respect to one of its parameters, in forward mode, and add the derivative as a new function.
import { grad } from 'typeshade'
The signature, the description and the examples come from the compiler's own source at commit 26de7be8.
Syntax
function grad(m: ModuleDecl, fn: string, param: string, opts?: GradOptions): GradResultParameters
mModuleDeclthe module holding
fn.fnstringthe name of the function to differentiate. It must return
f32, anf32vector or anf32matrix.paramstringthe name of the parameter to differentiate with respect to: an
f32, or anf32vector withopts.direction.optsoptionalGradOptionsthe generated name and, for a vector parameter, the direction.
Return value
the module with the derivative added, and the derivative’s name.
Exceptions
Description
The new function takes the same parameters as fn and returns d fn / d param at them,
with the type of fn’s result. It differentiates f32, float-vector and float-matrix
arithmetic, the component-wise builtins (sin, exp, pow, mix, smoothstep, dot,
length, normalize and the rest), if, switch and for, and calls to other functions
of the module. floor, ceil, round, trunc, sign and step have a zero derivative.
A construct with no derivative rule, a texture sample or a derivative builtin among them, is
refused by name when the parameter reaches it, never given a zero derivative.
Examples
Example
import { compile, compileModule, grad } from 'typeshade'
const { module } = compile(`"use typeshade"export function f(x: f32, k: f32): f32 { return sin(k * x) * k}`)const d = grad(module, 'f', 'k')compileModule(d.module).fns[d.name]!(0.5, 2) // cos(1) * 0.5 * 2 + sin(1)In the guide
Source
src/core/passes/grad.ts, line 93, at commit 26de7be8