> This page is for version 0.5.0 · 26.06.
> For other versions, use one of these documentation indexes:
> - Nightly (default): https://docs.nvidia.com/nemo/automodel/nightly/llms.txt
> - Latest: https://docs.nvidia.com/nemo/automodel/latest/llms.txt
> - 0.7.0 · 26.10: https://docs.nvidia.com/nemo/automodel/v0.7/llms.txt
> - 0.5.0 · 26.06: https://docs.nvidia.com/nemo/automodel/v0.5/llms.txt
> - 0.4.0 · 26.04: https://docs.nvidia.com/nemo/automodel/v0.4/llms.txt

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.nvidia.com/nemo/automodel/llms.txt.

# nemo_automodel.components.optim.nvfp4_resident_adam

Adam step of resident NVFP4 expert weights in two kernels.

Transformer Engine `FusedAdam` steps an NVFP4 weight in three passes over its FP32 master weight: it casts the
BF16 gradient to FP32, runs Adam, and quantizes the master back into the weight. `enable_nvfp4_fused_adam_step`
replaces these for the `NVFP4Tensor` parameters of a model, which are the expert weights of
`GroupedExpertsTENVFP4`, with one kernel that runs Adam on the BF16 gradient
and records the largest magnitude of each updated master, and one kernel that writes the row-wise and column-wise
NVFP4 operands of every weight from its master. Master weights, moments, codes, block scales and outer scales
come out bit-identical to the `FusedAdam` step; the optimizer state stays where `FusedAdam` keeps it, so
checkpoints and schedulers are unaffected.

The kernels are built once per build directory with `torch.utils.cpp_extension.load_inline` (CUDA toolkit
required) under `$NEMO_NVFP4_ADAM_BUILD_DIR` or `~/.cache/nemo_automodel/nvfp4_adam`.

## Module Contents

### Classes

| Name                                                                                    | Description                                                                                           |
| --------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| [`_FusedAdamStep`](#nemo_automodel-components-optim-nvfp4_resident_adam-_FusedAdamStep) | Step hooks of one `FusedAdam` that run the Adam step of some of its NVFP4 weights in the two kernels. |

### Functions

| Name                                                                                                                | Description                                                                       |
| ------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| [`_build_directory`](#nemo_automodel-components-optim-nvfp4_resident_adam-_build_directory)                         | Build directory of this source text, torch version and device architecture.       |
| [`_kernels_cover`](#nemo_automodel-components-optim-nvfp4_resident_adam-_kernels_cover)                             | Whether the requantization kernel writes `weight` the way its own quantizer does. |
| [`_load_extension`](#nemo_automodel-components-optim-nvfp4_resident_adam-_load_extension)                           | Import the extension from its built library, building it on first use.            |
| [`enable_nvfp4_fused_adam_step`](#nemo_automodel-components-optim-nvfp4_resident_adam-enable_nvfp4_fused_adam_step) | Step the resident NVFP4 expert weights of every model part in the fused kernels.  |

### Data

[`_EXTENSION_NAME`](#nemo_automodel-components-optim-nvfp4_resident_adam-_EXTENSION_NAME)

[`_STALE_LOCK_SECONDS`](#nemo_automodel-components-optim-nvfp4_resident_adam-_STALE_LOCK_SECONDS)

[`_STATE_NAMES`](#nemo_automodel-components-optim-nvfp4_resident_adam-_STATE_NAMES)

[`_StepArgument`](#nemo_automodel-components-optim-nvfp4_resident_adam-_StepArgument)

[`_extension`](#nemo_automodel-components-optim-nvfp4_resident_adam-_extension)

[`_extension_lock`](#nemo_automodel-components-optim-nvfp4_resident_adam-_extension_lock)

[`logger`](#nemo_automodel-components-optim-nvfp4_resident_adam-logger)

### API

```python
class nemo_automodel.components.optim.nvfp4_resident_adam._FusedAdamStep(
    weights: list[transformer_engine.pytorch.tensor.nvfp4_tensor.NVFP4Tensor],
    extension: types.ModuleType
)
```

Step hooks of one `FusedAdam` that run the Adam step of some of its NVFP4 weights in the two kernels.

The pre-step hook takes the gradients of those weights away, so `FusedAdam.step` advances its step counter
and updates every other parameter but skips them; the post-step hook puts the gradients back and steps the
weights with the group's hyperparameters. A weight keeps the `FusedAdam` step while it has no optimizer
state yet (its first step), when its state is not FP32 tensors, or when its gradient is not BF16; so does
every weight of a step that is given a closure or a gradient scaler.

**`_held`** `list[tuple[int, NVFP4Tensor, Tensor]] = []`

---

**`_weight_ids`** `= {(id(weight)) for weight in weights}`

---

```python
nemo_automodel.components.optim.nvfp4_resident_adam._FusedAdamStep.hold_gradients(
    optimizer: torch.optim.Optimizer,
    args: tuple[nemo_automodel.components.optim.nvfp4_resident_adam._StepArgument, ...],
    kwargs: dict[str, nemo_automodel.components.optim.nvfp4_resident_adam._StepArgument]
) -> None
```

Pre-step hook: take the gradients of the weights the kernels will step.

**Parameters:**

**`optimizer`** `torch.optim.Optimizer`

The optimizer about to step.

---

**`args`** `tuple[_StepArgument, ...]`

Positional arguments of `step`, the optimizer first.

---

**`kwargs`** `dict[str, _StepArgument]`

Keyword arguments of `step`.

---

```python
nemo_automodel.components.optim.nvfp4_resident_adam._FusedAdamStep.step_held_weights(
    optimizer: transformer_engine.pytorch.optimizers.FusedAdam,
    args: tuple[nemo_automodel.components.optim.nvfp4_resident_adam._StepArgument, ...],
    kwargs: dict[str, nemo_automodel.components.optim.nvfp4_resident_adam._StepArgument]
) -> None
```

Post-step hook: return the gradients and step their weights.

**Parameters:**

**`optimizer`** `FusedAdam`

The optimizer that just stepped.

---

**`args`** `tuple[_StepArgument, ...]`

Positional arguments of `step`, the optimizer first.

---

**`kwargs`** `dict[str, _StepArgument]`

Keyword arguments of `step`.

---

```python
nemo_automodel.components.optim.nvfp4_resident_adam._build_directory() -> str
```

Build directory of this source text, torch version and device architecture.

```python
nemo_automodel.components.optim.nvfp4_resident_adam._kernels_cover(
    weight: transformer_engine.pytorch.tensor.nvfp4_tensor.NVFP4Tensor
) -> bool
```

Whether the requantization kernel writes `weight` the way its own quantizer does.

**Parameters:**

**`weight`** `NVFP4Tensor`

NVFP4 weight of logical shape \[output_features, input_features].

---

**Returns:** `bool`

True for 2D block scales, rounding to nearest, and both the row-wise and the column-wise operand.

```python
nemo_automodel.components.optim.nvfp4_resident_adam._load_extension() -> types.ModuleType
```

Import the extension from its built library, building it on first use.

`load_inline` takes a file lock in the build directory on every call, and a process killed while holding
it leaves a lock that blocks every later caller. A finished library is therefore imported directly, and a
lock older than any build is removed.

```python
nemo_automodel.components.optim.nvfp4_resident_adam.enable_nvfp4_fused_adam_step(
    model_parts: list[torch.nn.Module],
    optimizers: list[torch.optim.Optimizer]
) -> None
```

Step the resident NVFP4 expert weights of every model part in the fused kernels.

Applies to the `NVFP4Tensor` parameters of the model parts (the expert weights of
`GroupedExpertsTENVFP4`) that are 2D block-scaled, rounded to nearest and hold both operands, and to
Transformer Engine `FusedAdam` optimizers with FP32 master weights that are not
capturable. Every other weight and optimizer keeps the `FusedAdam` step, as do all weights when the kernels
cannot be built (logged as a warning).

**Parameters:**

**`model_parts`** `list[nn.Module]`

Pipeline model parts paired one-to-one with `optimizers`.

---

**`optimizers`** `list[torch.optim.Optimizer]`

Optimizers that hold the parameters of the matching model part.

---

**Raises:**

* `ValueError`: If there is not one optimizer per model part.

```python
nemo_automodel.components.optim.nvfp4_resident_adam._EXTENSION_NAME = 'nemo_nvfp4_adam'
```

```python
nemo_automodel.components.optim.nvfp4_resident_adam._STALE_LOCK_SECONDS = 600.0
```

```python
nemo_automodel.components.optim.nvfp4_resident_adam._STATE_NAMES = ('master_param', 'exp_avg', 'exp_avg_sq')
```

```python
nemo_automodel.components.optim.nvfp4_resident_adam._StepArgument: TypeAlias = torch.optim.Optimizer | Callable[[], torch.Tensor] | torch.amp.GradScaler | None
```

```python
nemo_automodel.components.optim.nvfp4_resident_adam._extension: ModuleType | None = None
```

```python
nemo_automodel.components.optim.nvfp4_resident_adam._extension_lock = threading.Lock()
```

```python
nemo_automodel.components.optim.nvfp4_resident_adam.logger = logging.getLogger(__name__)
```