grad
이 페이지에서

grad()

함수, 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'

시그니처, 설명, 예제는 커밋 c66579bf의 컴파일러 소스에서 그대로 가져온 영어 원문입니다.

구문

function grad(m: ModuleDecl, fn: string, param: string, opts?: GradOptions): GradResult

매개변수

m ModuleDecl

the module holding fn.

fn string

the name of the function to differentiate. It must return f32, an f32 vector or an f32 matrix.

param string

the name of the parameter to differentiate with respect to: an f32, or an f32 vector with opts.direction.

opts선택 사항 GradOptions

the generated name and, for a vector parameter, the direction.

반환값

GradResult

the module with the derivative added, and the derivative’s name.

예외

SD0118

SD0118 when the function, the parameter or a construct the parameter reaches cannot be differentiated; the message names it.

설명

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.

예제

예제

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)

관련 가이드

소스

src/core/passes/grad.ts, 94행, 커밋 c66579bf 기준

이 페이지 편집 문제 보고