Metadata-Version: 2.4
Name: torchao-neuron
Version: 0.18.0+neuron.1
Summary: MXFP8 quantization for PyTorch on AWS Trainium
Home-page: https://github.com/aws-neuron/torchao-neuron
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: pytest==9.0.3; extra == "dev"
Requires-Dist: unittest-xml-reporting; extra == "dev"
Requires-Dist: parameterized; extra == "dev"
Requires-Dist: packaging; extra == "dev"
Requires-Dist: transformers; extra == "dev"
Requires-Dist: hypothesis; extra == "dev"
Requires-Dist: sentencepiece; extra == "dev"
Requires-Dist: expecttest; extra == "dev"
Requires-Dist: pyyaml; extra == "dev"
Requires-Dist: bitsandbytes; extra == "dev"
Requires-Dist: matplotlib; extra == "dev"
Requires-Dist: pandas; extra == "dev"
Requires-Dist: fire; extra == "dev"
Requires-Dist: tabulate; extra == "dev"
Requires-Dist: tiktoken; extra == "dev"
Requires-Dist: blobfile; extra == "dev"
Requires-Dist: lm_eval; extra == "dev"
Requires-Dist: diskcache; extra == "dev"
Requires-Dist: pycocotools; extra == "dev"
Requires-Dist: tqdm; extra == "dev"
Requires-Dist: importlib_metadata; extra == "dev"
Requires-Dist: ninja; extra == "dev"
Requires-Dist: cmake<4.0.0,>=3.19.0; extra == "dev"
Requires-Dist: ruff==0.11.6; extra == "dev"
Requires-Dist: pre-commit; extra == "dev"
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: license-file
Dynamic: provides-extra
Dynamic: summary

# torchao-neuron (Beta)

TorchAO is a quantization library for native PyTorch. TorchAO Neuron is the
Neuron fork of TorchAO. It adds Trainium-specific support for AO's MXFP8
quantization and matrix multiplication interfaces.
In addition, the fork adds new performance-optimized code paths which
differ from the upstream implementations by fusing quantization and matrix
multiplication. TorchTitan Neuron applies these features for MXFP8 training with
TorchNeuron, the native PyTorch backend.

This repository ([aws-neuron/torchao-neuron](https://github.com/aws-neuron/torchao-neuron))
is a fork of the upstream [pytorch/ao](https://github.com/pytorch/ao) project. It is licensed under the BSD 3-Clause license; see [LICENSE](LICENSE).

## Requirements

| Component | Required version |
|---|---|
| Instance types | Trn3 |
| Neuron SDK | 2.34 |
| PyTorch | 2.14.0 |
| `torch-neuronx` | 2.14.3.1 |
| `torchtitan-neuron` | 0.2.2+neuron.2, for the MXFP8 training recipes |

## Installation

TorchAO Neuron ships as the `torchao-neuron` wheel on the Neuron pip
repository, the same repository that serves `torch-neuronx`. It is a pure
Python wheel with no compiled extensions. Install it into the environment where
`torch-neuronx` is installed:

```bash
python -m pip install torchao-neuron \
  --extra-index-url https://pip.repos.neuron.amazonaws.com
```

To install from a source checkout instead, use an editable install:

```bash
USE_CPP=0 pip install -e . --no-build-isolation
```

The wheel installs the `torchao` Python package. Do not install the upstream
`torchao` wheel into the same environment, because both provide the same
package name.

TorchAO Neuron installs on any Neuron instance, but its MXFP8 ops register only
on Trn3.

## Verify the installation

First confirm the package imports and that the Neuron MXFP8 ops registered. On
Trn3 the fused op is present; on any other instance the import still succeeds
but the op is absent.

```bash
python -c "import torch, torchao; import torchao.prototype.mx_formats.kernels; \
print(torchao.__version__, hasattr(torch.ops.neuron, 'fused_quantize_mx_scaled_mm_nki'))"
```

Then run `MXFP8Linear` once against a bf16 reference:

```python
import torch
import torch.nn.functional as F
from torchao.prototype.moe_training.mxfp8_linear import MXFP8Linear

torch.manual_seed(0)
x_cpu = torch.randn(128, 256, dtype=torch.bfloat16)

linear = MXFP8Linear(256, 512, bias=False).to("neuron", torch.bfloat16)
w_cpu = linear.weight.detach().cpu()

x = x_cpu.to("neuron").requires_grad_(True)
out = linear(x)
out.sum().backward()

ref = F.linear(x_cpu.float(), w_cpu.float())
rel = (torch.linalg.norm(out.cpu().float() - ref) / torch.linalg.norm(ref)).item()
print(f"shape={tuple(out.shape)} finite={torch.isfinite(out.cpu()).all().item()} rel_error={rel:.4f}")
```

Expected output:

```
shape=(128, 512) finite=True rel_error=0.0353
```

The fused MXFP8 linear runs quantization and the scaled matmul as a single
Neuron operation and accepts kernel configuration arguments:

```python
import torch
import torch.nn.functional as F
from torchao.prototype.mx_formats.neuron_mxfp8 import (
    NeuronLowering,
    NeuronMXFP8BackendOptions,
    NkiKernelOptions,
    QuantScheme,
    neuron_fused_mx_linear,
)

torch.manual_seed(0)
x_cpu = torch.randn(128, 256, dtype=torch.bfloat16)
w_cpu = torch.randn(512, 256, dtype=torch.bfloat16)

# Optional. Omit for the defaults: NKI lowering, 1x32, fused backward=False
opts = NeuronMXFP8BackendOptions(
    lowering=NeuronLowering.NKI,
    nki=NkiKernelOptions(quant_scheme=QuantScheme.ONE_X32, fused_backward=True),
)

x = x_cpu.to("neuron").requires_grad_(True)
w = w_cpu.to("neuron").requires_grad_(True)
out = neuron_fused_mx_linear(x, w, None, opts)
out.sum().backward()

ref = F.linear(x_cpu.float(), w_cpu.float())
rel = (torch.linalg.norm(out.cpu().float() - ref) / torch.linalg.norm(ref)).item()
print(f"shape={tuple(out.shape)} finite={torch.isfinite(out.cpu()).all().item()} rel_error={rel:.4f}")
```

A `rel_error` well under `0.10` confirms the install. MXFP8 is supported on Trn3.

## Supported configurations

TorchAO Neuron supports the following MXFP8 configurations on dense
`nn.Linear` layers, in eager mode and under `torch.compile` with
`backend="neuron"`. Quantizing MoE expert weights is available through
TorchTitan Neuron.

- **`MXFP8Linear`** — TorchAO's MXFP8 linear, running on Neuron through the
  `quantize_mx` custom operator and `aten::_scaled_mm` pytorch core operator.
  Quantization and the matmul stay separate operations, so the layer keeps
  upstream TorchAO semantics.

- **Fused MXFP8 linear** (`neuron_fused_mx_linear`) — an autograd function
  that runs quantization and the scaled matmul as one Neuron custom operation.
  Its kernel configuration arguments select:

  - **NKI kernel lowering** (default) — forward and backward run the
    `matmul_mxfp8` NKI kernels, which also accept a quantization layout and a
    tuned-config file.
  - **MLIR custom operator lowering** — the forward lowers to a neuronx-cc
    custom op instead, and takes none of the NKI configuration arguments.
  - **Fused backward matmuls** — computes both the weight and
    activation gradients in one backward kernel, rather than two calls to
    the matmul kernel.

- **Pre-quantized weights** — a separate workflow, not part of the fused
  autograd function. Quantize a weight once and reuse the encoding across
  matmuls, so a distributed gather moves FP8 instead of bf16. It is exposed as
  the `neuron::quantize_mx_nki` and `neuron::prequantized_mx_scaled_mm_nki`
  custom operators, for callers that supply their own autograd function.

## How TorchAO Neuron works

TorchAO Neuron provides a PyTorch interface for the MXFP8 features supported on
Neuron devices. The core features are delivered as kernels in the NKI Library,
custom ops defined in the Neuron Graph Compiler, and aten ops in TorchNeuron.
TorchAO makes these features accessible to PyTorch users by providing the wrapper
code necessary to insert these operations into their models. TorchTitan Neuron
provides the examples for integrating TorchAO into PyTorch training.

## Quantization layouts

MXFP8 groups elements along the contraction dimension and stores one scale per
group. The NKI lowering supports two layouts, `1x32` (the default) and
`wrapX`. They differ in how a group is formed and in which NeuronCore engine
rearranges the operand into the layout the matmul expects. `1x32` is the only
layout the pre-quantized weight path supports.

For how the layout choice interacts with kernel selection and performance, and
how to tune it, check the MXFP8 autotuning tutorial in the [TorchTitan Neuron
documentation](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/training/torchtitan/tutorials/index.html).

## Related repositories

- TorchTitan Neuron: https://github.com/aws-neuron/torchtitan-neuron
- TorchNeuron: https://github.com/aws-neuron/torch-neuronx
