Quick Start
Overview
This document provides a simple example to help developers who are new to MindSpeed Ops quickly verify an operator library installation and invoke an operator for their first computation. The main steps are:
- Environment setup: Set up the environment and verify the installation according to the installation guide.
- Run a Triton fused operator: Invoke the
FusedCrossEntropyLossoperator to compute the forward and backward cross-entropy loss, and compare the result with the native PyTorch implementation. - Run an ACLNN fused operator: Invoke the
AddRmsNormBiasoperator to perform fused residual addition and RMS normalization. - Run unit tests: Run the operator accuracy unit tests provided in the repository.
Note
MindSpeed Ops supports Ascend products such as Ascend 950PR&950DT products and Atlas A3 training products. For details, see Supported Operators.
Prerequisites:
- Basic experience with PyTorch
- Basic Python development experience
Environment Setup
See Installation Guide to install the driver and firmware, CANN, PyTorch, TorchNPU, and Triton-Ascend, and then install MindSpeed Ops from source.
Before running an operator, make sure the CANN environment variables are active:
source /usr/local/Ascend/ascend-toolkit/latest/set_env.sh
The preceding command uses the default installation path for the root user. Replace it with the actual path to set_env.sh.
Verifying the Installation
-
Check that the NPU is available:
npu-smi info -
Check that MindSpeed Ops can be imported:
python -c "import mindspeed_ops; print('MindSpeed Ops loaded successfully')"The output should be as follows:
MindSpeed Ops loaded successfully
Running Your First Triton Operator
In this step, you will write a simple script that invokes the FusedCrossEntropyLoss operator to compute the cross-entropy loss and compares its accuracy with the native PyTorch implementation. For details about this operator, see fused_cross_entropy_loss.
-
Write an example script.
Create
quick_start_example.pyin the MindSpeed Ops root directory:import torch import torch.nn.functional as F from mindspeed_ops.api.triton.fused_cross_entropy_loss import FusedCrossEntropyLossFunction from mindspeed_ops.api.triton.utils import get_available_device # Get the available device. "npu" is returned in an NPU environment device = get_available_device() torch.manual_seed(42) dtype = torch.float16 N, vocab_size = 1024, 16384 # Create input tensors. The shape of logits is [bs * seq_len, vocab_size] logits = torch.randn(N, vocab_size, dtype=dtype, device=device, requires_grad=True) loss_weight = torch.randn(N, dtype=dtype, device=device, requires_grad=True) labels = torch.randint(0, vocab_size, (N,), dtype=torch.int32, device=device) # Compute loss = (cross_entropy(logits, labels) * loss_weight).sum() using the MindSpeed Ops fused operator loss = FusedCrossEntropyLossFunction.apply(logits, loss_weight, labels) print("fused loss:", loss.item()) # Run backward propagation loss.backward() print("grad norm of logits:", logits.grad.float().norm().item()) # PyTorch reference implementation for accuracy comparison ce = F.cross_entropy(logits.float().detach(), labels, reduction="none") ref = (ce * loss_weight.float().detach()).sum() print("reference loss:", ref.item()) print("fused_cross_entropy_loss operation exec successfully!") -
Run the script.
python quick_start_example.pyThe output should be similar to the following. The values are examples based on random data; actual results depend on the run. The fused operator result should be approximately equal to the reference result.
fused loss: 12.65625 grad norm of logits: 127.521484375 reference loss: 12.656312942504883 fused_cross_entropy_loss operation exec successfully!
Table 1 Key APIs in the example script
| API | Description |
|---|---|
get_available_device() |
Automatically detects the available compute device and returns "npu" in an NPU environment, allowing the script to fall back to CPU debugging when no NPU is available. |
FusedCrossEntropyLossFunction.apply(logits, loss_weight, labels) |
Entry point of the fused cross-entropy loss operator. It is provided as a torch.autograd.Function and supports automatic differentiation. |
Running an ACLNN Fused Operator
In this step, you will invoke the AddRmsNormBias operator to fuse residual addition (Add) and RMS normalization (RMSNorm), which are common in Transformers, into a single kernel. For details about this operator, see AddRmsNormBias.
Note
ACLNN operators depend on a C++ extension and a custom operator package. ACLNN compilation must be completed when MindSpeed Ops is installed. During a source installation, this occurs when an NPU is detected or the SOC_VERSION environment variable is set. For details, see Installation Guide.
import torch
import torch_npu # noqa: F401. Import to register the NPU backend.
from mindspeed_ops.api.aclnn.npu_add_rms_norm_bias import npu_add_rms_norm_bias
device = "npu"
x1 = torch.randn(4, 256, dtype=torch.float16, device=device)
x2 = torch.randn(4, 256, dtype=torch.float16, device=device)
gamma = torch.randn(256, dtype=torch.float16, device=device)
# Fused computation: x = x1 + x2; rstd = 1/sqrt(mean(x^2) + eps); y = (x * rstd) * gamma
y, rstd, x = npu_add_rms_norm_bias(x1, x2, gamma)
# Verify the result
expected_x = x1 + x2
assert torch.allclose(x.float(), expected_x.float(), rtol=1e-3)
print(f"y shape: {y.shape}, dtype: {y.dtype}")
print("AddRmsNormBias operation completed successfully!")
Running Unit Tests
MindSpeed Ops provides accuracy unit tests for each operator. You can use them to verify operator correctness in the current environment.
cd MindSpeed-Ops
pytest tests/unit_tests
Note
- To run tests for a single operator, use
pytest tests/unit_tests/triton/test_fused_cross_entropy_loss.py. - The unit tests use a high-precision CPU implementation and the corresponding PyTorch small-operator implementation as dual references.
- The unit tests for CATLASS operators depend on the optional CATLASS component. Set
MINDSPEED_BUILD_CATLASS=1during installation. For details, see Building and Running CATLASS Operators. If compilation is not enabled, the related test cases are skipped automatically. - The unit tests for TileLang operators depend on the optional TileLang-Ascend component. For details, see Installation Guide. If the component is not installed, the related test cases are skipped automatically.
More Operators
For all operators currently provided by MindSpeed Ops and their detailed documentation, see Supported Operators. If you encounter a problem, see FAQs.