# Automatic Differentiation

Vex currently exposes forward-mode automatic differentiation through an autograd block and four intrinsic helpers:

- `@param(expr)` seeds a value with gradient `1`
- `@val(dual)` reads the primal value
- `@grad(dual)` reads the tangent
- `@detach(dual)` clears gradient tracking

The `@{ ... }` block is still part of the language surface. It evaluates the block and returns the final autograd value.

## Core Example

```vex [autograd-polynomial.vx]
fn main(): i32 {
    let result = @{
        let x = @param(3.0)
        x * x + 2.0 * x + 1.0
    }

    $println("value = ", @val(result))
    $println("grad = ", @grad(result))
    return 0
}
```

Save as `autograd-polynomial.vx` and run `vex run autograd-polynomial.vx`.
The primal value is `16` and the derivative is `8` (printed with floating-point
formatting). This is a scalar forward-mode example, not a backward tensor
training graph.

## Direct Intrinsic Use

You can also use the intrinsics directly without wrapping everything in a larger block:

```vex
fn main(): i32 {
    let x = @param(2.0)
    let y = Math.sin(x)

    $println("sin(2.0) = ", @val(y))
    $println("d/dx sin(2.0) = ", @grad(y))
    return 0
}
```

Current examples and compiler paths use the `Math.*` namespace for trig and transcendental functions rather than `$sin`, `$cos`, `$exp`, or `$log`.

## Supported Pattern Today

The implementation is forward-mode dual-number AD.

```vex
let x = @param(2.0)
let y = @param(3.0)
let z = x * y

$println("value = ", @val(z))
$println("grad = ", @grad(z))
```

When more than one input is seeded with `@param`, the current surface returns the directional derivative along the seeded tangent vector. In the example above, `@grad(z)` is `5`, not a pair of separate partial derivatives.

If you need separate partials, run separate passes and seed one input at a time.

## Sensitivity of a calibration loss

Suppose a sensor model predicts `gain * input + bias`. With input `3`, target
`10`, gain `2`, and bias `1`, its prediction is `7` and squared error is `9`.
Two forward passes isolate the effect of changing gain and bias:

```vex [autograd-sensitivity.vx]
fn main(): i32 {
    let gainPass = @{
        let gain = @param(2.0);
        let bias = 1.0;
        let prediction = gain * 3.0 + bias;
        let error = prediction - 10.0;
        error * error
    };
    let biasPass = @{
        let gain = 2.0;
        let bias = @param(1.0);
        let prediction = gain * 3.0 + bias;
        let error = prediction - 10.0;
        error * error
    };
    $println(@val(gainPass)); $println(@grad(gainPass)); $println(@grad(biasPass));
    if @val(gainPass) != 9.0 || @grad(gainPass) != -18.0 || @grad(biasPass) != -6.0 { return 1; }
    return 0;
}
```

Run `vex run autograd-sensitivity.vx`. Expected output:

```text
9.000000
-18.000000
-6.000000
```

For `loss = (gain * input + bias - target)^2`, the gain derivative is
`2 * error * input = -18`; the bias derivative is `2 * error = -6`.
Only one parameter is seeded in each pass. Seeding both together would measure
the directional derivative for changing both by the same amount, rather than
returning these two partial derivatives separately.

The program calculates local sensitivities. A training loop must separately
choose an update rule, step size, stopping condition, and handling of
nondifferentiable points; forward-mode differentiation does not choose those
for the application.

## Detaching Values

`@detach` preserves the value and clears the gradient component.

```vex
fn main(): i32 {
    let x = @param(3.0)
    let frozen = @detach(x)

    $println("value = ", @val(frozen))
    $println("grad = ", @grad(frozen))
    return 0
}
```

## Math Functions

The current examples and compiler support autograd through ordinary arithmetic plus the math namespace.

```vex
fn main(): i32 {
    let result = @{
        let x = @param(4.0)
        Math.sqrt(x) + Math.log(x) + Math.exp(x)
    }

    $println("value = ", @val(result))
    $println("grad = ", @grad(result))
    return 0
}
```

Common working paths in the current tree include:

- `Math.sin`
- `Math.cos`
- `Math.exp`
- `Math.log`
- `Math.sqrt`

## What To Rely On

Use this page as the current contract for non-stdlib autograd syntax:

- Prefer `@param`, `@val`, `@grad`, and `@detach`
- Do not use legacy `$` spellings; autograd transforms use the `@` phase
- Use `Math.*` calls for differentiable math operations
- Keep autograd scopes small and explicit so the seeded derivative path is obvious

## Related

- [SIMD](../simd/index.md)
- [GPU Programming](../gpu/index.md)
- [Builtins](builtins.md)
