---
title: "grad(): function in IR, TypeShade API reference"
description: "grad, a function in IR. Differentiate a function of a module and add the derivative as a new function."
url: https://typeshade.dev/api/grad/
language: en
---

# `grad()`

Function in IR

Differentiate a function of a module 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 af54ddad5.

## Syntax

```ts
function grad(
  m: ModuleDecl,
  fn: string,
  wrt: string | readonly string[],
  opts?: GradOptions,
): GradResult
```

## Parameters

**`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.

**`wrt` `string | readonly string[]`**

in forward mode, the name of the parameter to differentiate with respect to: an `f32`, or an `f32` vector with `opts.direction`. In reverse mode, one name or a list of names of `f32`, `f32` vector or `f32` matrix parameters.

**`opts` optional `GradOptions`**

the mode, the generated name and, for a vector parameter in forward mode, the direction.

## Return value

`GradResult`

the module with the derivative added, the derivative’s name and, in reverse mode, the field of each adjoint.

## Exceptions

**[`SD0118`](https://typeshade.dev/reference/errors/sd0118/)**

[`SD0118`](https://typeshade.dev/reference/errors/sd0118/) when the function, the parameter or a construct the parameter reaches cannot be differentiated; the message names it.

## Description

In forward mode (the default) the new function takes the same parameters as `fn` and returns `d fn / d param` at them, with the type of `fn`’s result. In reverse mode (`opts.mode: 'reverse'`) `wrt` is a list of names, and the new function takes the same parameters followed by a seed `dy` of the result’s type. It returns a struct with one field for each name `x` of `wrt`, holding `dy · d fn / d x`, so one call gives the gradient with respect to every name. A loop runs under a checkpoint schedule in function memory (`opts.checkpoints`), and `tapeBytes` reports its size.

Both modes differentiate `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

```ts
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)

const r = grad(module, 'f', ['x', 'k'], { mode: 'reverse' })
compileModule(r.module).fns[r.name]!(0.5, 2, 1) // { x: …, k: … }, the gradient
```

## In the guide

- [The CPU oracle](https://typeshade.dev/guide/internals/the-cpu-oracle/)

## Source

[`src/core/passes/grad.ts`, line 102](https://github.com/typeshade/typeshade/blob/af54ddad5/src/core/passes/grad.ts#L102), at commit af54ddad5
