aclnnSwigluGroupQuantWithDualAxis

📄 View Source Code

Applicable Products

  • Ascend 950PR&950DT products: Supported
  • Atlas A3 products: Does not support
  • Atlas A2 products: Does not support
  • Atlas 200I/500 A2 inference products: Does not support
  • Atlas inference products: Does not support
  • Atlas training products: Does not support

Function

Description

Fuses Clipped-SwiGLU, optional row-wise weight multiplication, and MX FP8 quantization in two directions, and outputs five results in a single call:

  • y1Out, y1ScaleOut: Quantized along the last dimension (-1 axis). Every 32 elements within each token row share one scale.
  • y2Out and y2ScaleOut: quantized along the row direction (-2 axis); when groupIndexOptional is provided, scales are shared at group boundaries, with one scale per 32 rows within a group and per column; when it is not provided, blocks are formed over all rows.
  • yOriginOut: optional activation result before weight multiplication.

groupIndexOptional uses the cumsum (cumulative group end index) semantics; weightOptional is only allowed in the group use case. The quantized values of the first output are byte-for-byte consistent with those of the single-axis operator aclnnSwigluGroupQuant (quantMode=5).

Formula

The Clipped-SwiGLU activation can be written in a unified form:

A′={min⁡(A,L),L>0A,L=−1,B′={min⁡(max⁡(B,−L),L),L>0B,L=−1A' = \begin{cases} \min(A, L), & L > 0 \\ A, & L = -1 \end{cases}, \qquad B' = \begin{cases} \min(\max(B, -L), L), & L > 0 \\ B, & L = -1 \end{cases} F=A′⋅σ(α⋅A′)⋅(B′+β)F = A' \cdot \sigma(\alpha \cdot A') \cdot (B' + \beta)

where A=x[:,:H]A = x[:, :H], B=x[:,H:]B = x[:, H:], H=D/2H = D/2, LL is clampLimit, α\alpha is alpha, β\beta is bias; L=−1L=-1 means Clamp is disabled.

Phase 1: Clipped-SwiGLU activation
  1. Split (split into front and back parts only along the last dimension, -1 axis): A=x[:, :H]A = x[:,\ :H], B=x[:, H:]B = x[:,\ H:]
  2. Clamp (takes effect before SiLU when clampLimit > 0): A′=min⁡(A,L)A' = \min(A, L), i.e., only the gate branch is clamped to the upper bound; B′=min⁡(max⁡(B,−L),L)B' = \min(\max(B, -L), L), i.e., the linear branch is clamped symmetrically. When clampLimit = -1.0, A′=AA'=A and B′=BB'=B.
  3. Variant SwiGLU: F=A′⋅σ(α⋅A′)⋅(B′+β)F = A' \cdot \sigma(\alpha \cdot A') \cdot (B' + \beta). When alpha=1.0, bias=0.0, and clampLimit=-1.0, it degrades to standard SwiGLU.
  4. Per-token weighting (when weightOptional is not empty): u=RT(RT(F)⋅w[t])u = R_T(R_T(F) \cdot w[t]); When weight is not specified, u=RT(F)u = R_T(F). RT(⋅)R_T(\cdot) denotes rounding to the input dtype, and uu is the quantization input.
Stage 2: dual-path MX FP8 quantization (CuBALS, block size 32)

Both paths use the CuBALS (scaleAlg=1) scaling algorithm, and the block size is fixed at 32. The maximum absolute value amaxamax in a block is mapped to the representable range of the target data type sraw=amax/Amax(DType)s^{raw} = amax / Amax(DType) (448 for E4M3FN and 57344 for E5M2).

For a finite, non-zero sraws^{raw}, interpret it in the FP32 bit pattern. Let EbE_b be the 8-bit biased exponent field of FP32, and m∈[0,1)m \in [0,1) be the fractional part of the mantissa field. The CuBALS exponent rounding rule is:

Eb∗={Eb+1,0<Eb<254 and m>0Eb+1,Eb=0 and m>0.5Eb, otherwiseE_b^{*} = \begin{cases} E_b + 1, & 0 < E_b < 254 \text{ and } m > 0 \\ E_b + 1, & E_b = 0 \text{ and } m > 0.5 \\ E_b, & \text{ otherwise} \end{cases}

E8M0 directly stores the biased exponent encoding:

mxScale=Eb∗,s=2Eb∗−127mxScale = E_b^{*}, \qquad s = 2^{E_b^{*}-127}

In-block data d=Q8(u/s)d = Q8(u / s). FP32→FP8 uses RINT (round to nearest); mxScale = 0 for all-zero blocks. Unused scale padding/reserved positions are not part of valid results, and the caller should not depend on its value.

  • First output (-1 axis): Each row in [T, H] is independent, and every 32 elements within a row form a block.
  • Second output (-2 axis): In the group use case, rows are grouped by the cumulative group end index in groupIndexOptional, and every 32 rows within a group form a block, each column has an independent scale, and blocks do not cross groups; when a group ends with fewer than 32 rows, zeros are padded only in temporary blocks for scale calculation. In the non-group use case, blocks are formed over all rows.

Function Prototype

Each operator uses a two-phase API. You must first call the "aclnnSwigluGroupQuantWithDualAxisGetWorkspaceSize" API to obtain the workspace size required for the calculation and the executor that contains the calculation process of the operator, and then call the "aclnnSwigluGroupQuantWithDualAxis" API to execute the calculation.

aclnnStatus aclnnSwigluGroupQuantWithDualAxisGetWorkspaceSize(
  const aclTensor *x,
  const aclTensor *weightOptional,
  const aclTensor *groupIndexOptional,
  int64_t          dstType,
  int64_t          quantMode,
  double           clampLimit,
  bool             outputOrigin,
  double           alpha,
  double           bias,
  const aclTensor *y1Out,
  const aclTensor *y1ScaleOut,
  const aclTensor *y2Out,
  const aclTensor *y2ScaleOut,
  const aclTensor *yOriginOut,
  uint64_t        *workspaceSize,
  aclOpExecutor  **executor)
aclnnStatus aclnnSwigluGroupQuantWithDualAxis(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnSwigluGroupQuantWithDualAxis

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x (aclTensor*) Input SwiGLU input.
    • The shape is [T, D] (D = 2H).
    • D must be an even number, 64-element aligned, and H ≥ 32 (that is, D ≥ 64).
    • Does not support empty tensors.
    FLOAT16, BFLOAT16 ND 2 √
    weightOptional (aclTensor*) Input (optional) Per-token weight, used for the weighted calculation of the Clipped-SwiGLU output.
    • Optional parameter. Does not support empty tensor.
    • Allowed only when groupIndexOptional is provided. In the non-group use case, non-empty tensors are rejected.
    • The number of elements must equal T, the number of rows after axis merging.
    FLOAT16, BFLOAT16, FLOAT ND 1-8 √
    groupIndexOptional (aclTensor*) Input (optional) Cumulative group end indices (cumsum semantics; each element value is itself the group end row index), used only for grouped quantization on the second path.
    • Optional parameter. Does not support empty tensors.
    • NULL (default) = degrades to non-group; the second path forms blocks over all rows.
    • If not empty, the tensor must be INT64, 1-dimensional [G], with each element ≥ 0 and non-decreasing, and the last element equal to T.
    • Equal adjacent elements indicate an empty group; no block is generated.
    • Not responsible for output truncation: the activation and the first path always process all T rows.
    • Element values are validated on the device side. For details, see "Constraints".
    INT64 ND 1 √
    dstType (int64_t) Input Target quantization type.
    • Supports 36 (FLOAT8_E4M3FN, default) and 35 (FLOAT8_E5M2).
    - - - -
    quantMode (int64_t) Input Quantization mode.
    • Only 1 is supported (dual-axis MX FP8).
    - - - -
    clampLimit (double) Input Clamp threshold of Clipped-SwiGLU (L in the formula).
    • -1.0 indicates that clamp is disabled.
    • If enabled, the value must be a finite positive number.
    - - - -
    outputOrigin (bool) Input Whether to additionally output activation y_origin before multiplying by weight.
    • If true, yOriginOut is the activation before quantization with shape [T, H] (intermediate result cached for training backward propagation).
    • If false, yOriginOut is a [0] placeholder with invalid content.
    - - - -
    alpha (double) Input silu scaling factor of the SwiGLU variant.
    • Must be a finite positive number.
    - - - -
    bias (double) Input Bias of the linear branch of the SwiGLU variant.
    • Must be a finite number.
    - - - -
    y1Out (aclTensor*) Output Quantization output of the first path (axis -1).
    • The shape is [T, H].
    • The data type must be consistent with dstType.
    FLOAT8_E4M3FN, FLOAT8_E5M2 ND 2 √
    y1ScaleOut (aclTensor*) Output First quantization scale.
    • Shape is [T, ceil(ceil(H/32)/2), 2].
    • The last dimension stores at most 2 adjacent 32-element block scales; unused padding positions are not guaranteed to have valid values, and the caller should not depend on its content.
    FLOAT8_E8M0 ND 3 √
    y2Out (aclTensor*) Output Second (-2 axis) quantization output.
    • The shape is [T, H].
    • The data type must be consistent with dstType.
    FLOAT8_E4M3FN, FLOAT8_E5M2 ND 2 √
    y2ScaleOut (aclTensor*) Output Second quantization scale.
    • The shape is [floor(T/64) + G, H, 2] (group) or [ceil(T/64), H, 2] (non-group). G is the number of elements in groupIndexOptional.
    • The last dimension slot0/slot1 corresponds to at most two adjacent 32-row block scales. The group use case may contain physical positions reserved for group boundaries. Unused reserved slots are not guaranteed to contain valid values, and the caller should not depend on their content.
    FLOAT8_E8M0 ND 3 √
    yOriginOut (aclTensor*) Output Activation result before weight multiplication (including clamp/alpha/bias effects).
    • If outputOrigin is true, the shape is [T, H] and the data type is consistent with x. If false, [0] is used as a placeholder.
    • Does not support empty pointers.
    FLOAT16, BFLOAT16 ND 2 (outputOrigin=true) / 1 (outputOrigin=false) √
    workspaceSize (uint64_t*) Output Returns the size of the workspace to be side-applied on the Device. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator calculation flow. - - - - -
  • Return value

    aclnnStatus: return status code. For details, see aclnn Error Codes.

    The first-phase API performs input parameter validation and returns an error in the following scenarios:

    Error Code Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 x, y1Out, y1ScaleOut, y2Out, y2ScaleOut, yOriginOut, workspaceSize, or executor is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of the input or output is not within the supported range.
    The shape of the input or output does not meet the constraints (for example, x is not two-dimensional, or D is not 64-aligned).
    dstType or quantMode is not a supported value.
    The value of clampLimit, alpha, or bias is invalid (non-finite, non-positive alpha, etc.).
    The combination of weightOptional and groupIndexOptional is invalid (weight is passed for non-group).
    ACLNN_ERR_INNER_TILING_ERROR 561002 The tiling phase fails. For example, the number of weight elements does not match T, or the dimension or element count of groupIndexOptional is invalid.

aclnnSwigluGroupQuantWithDualAxis

  • Parameters:

    Parameter Input/Output Description
    workspace Input Device-side-applied workspace memory address.
    workspaceSize Input Device-side-applied workspace size, obtained by calling the first-phase API aclnnSwigluGroupQuantWithDualAxisGetWorkspaceSize.
    executor Input Op executor that contains the calculation flow of the operator.
    stream Input Stream for executing tasks.
  • Return value

    aclnnStatus: return status code. For details, see aclnn Error Codes.

Constraints

  • x only supports the 2D shape [T, 2H] and data type FLOAT16 or BFLOAT16. It must be non-empty. 2H >= 64 is required, and 2H must be divisible by 64.
  • quantMode only supports 1; dstType only supports FLOAT8_E4M3FN (default) and FLOAT8_E5M2.
  • weightOptional is allowed only when groupIndexOptional is provided, and the number of elements must be equal to T. Passing weight in non-group use cases is rejected.
  • The element values of groupIndexOptional are validated during device execution: invalid values (negative values, decreasing values, out-of-range values, or a last element not equal to T) trigger a device execution exception; for asynchronous calls, the failure may be reported only during subsequent stream synchronization. After the failure, all outputs are unusable. The GetWorkspaceSize phase validates only metadata (dtype, number of dimensions, and non-zero element count) and does not guarantee valid element values.
  • outputOrigin supports both true and false: when it is true, yOriginOut is [T, H]; when it is false, it is a [0] placeholder.
  • The quantization values of the first output are consistent with those of the single-axis operator aclnnSwigluGroupQuant (quantMode=5) byte by byte.
  • Supports deterministic computation by default; only supports forward.
  • x, weightOptional, and groupIndexOptional all support non-contiguous tensors.

Example

The sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.

#include <cstdint>
#include <cstring>
#include <iostream>
#include <limits>
#include <memory>
#include <stdexcept>
#include <vector>
#include "acl/acl.h"
#include "aclnn/acl_meta.h"
#include "aclnnop/aclnn_swiglu_group_quant_with_dual_axis.h"

namespace SwigluExample {
inline int64_t Numel(const std::vector<int64_t>& shape)
{
    int64_t size = 1;
    for (int64_t dim : shape) {
        if (dim <= 0 || size > std::numeric_limits<int64_t>::max() / dim) {
            throw std::invalid_argument("tensor shape must be positive and fit int64");
        }
        size *= dim;
    }
    return size;
}

// The MX V2 path and the dual-axis operator only ship an Ascend950 kernel, so
// running their aclnn calls on another SOC fails inside tiling. Report a skip
// instead of a false failure. An unavailable SOC name keeps the legacy
// behaviour of running the example.
inline bool CheckHardwareSupport(const char* operatorName)
{
    const char* socName = aclrtGetSocName();
    if (socName == nullptr) {
        std::cout << "Warning: cannot get SOC name, skip hardware check" << std::endl;
        return true;
    }
    std::cout << "Current SOC: " << socName << std::endl;
    if (strstr(socName, "Ascend950") != nullptr || strstr(socName, "ascend950") != nullptr) {
        return true;
    }
    std::cout << "Warning: " << operatorName << " only supports Ascend950, current SOC '" << socName
              << "' is not supported. Skip test." << std::endl;
    return false;
}

// Owns every acquired resource until stream work has finished. API void pointers
// stay inside this wrapper; callers receive only borrowed tensor descriptors.
class Session {
public:
    explicit Session(int& status) : status_(status) {}
    Session(const Session&) = delete;
    Session& operator=(const Session&) = delete;
    ~Session()
    {
        if (pending_) {
            Record(aclrtSynchronizeStream(stream_), "aclrtSynchronizeStream");
        }
        if (executor_ != nullptr) {
            Record(aclDestroyAclOpExecutor(executor_), "aclDestroyAclOpExecutor");
        }
        if (workspace_ != nullptr) {
            Record(aclrtFree(workspace_), "aclrtFree(workspace)");
        }
        for (auto& tensor : tensors_) {
            if (tensor->descriptor != nullptr) {
                Record(aclDestroyTensor(tensor->descriptor), "aclDestroyTensor");
            }
            if (tensor->device != nullptr) {
                Record(aclrtFree(tensor->device), "aclrtFree(tensor)");
            }
        }
        if (stream_ != nullptr) {
            Record(aclrtDestroyStream(stream_), "aclrtDestroyStream");
        }
        if (deviceSet_) {
            Record(aclrtResetDevice(deviceId_), "aclrtResetDevice");
        }
        if (initialized_) {
            Record(aclFinalize(), "aclFinalize");
        }
    }

    void Check(int result, const char* operation)
    {
        if (result != ACL_SUCCESS) {
            Record(result, operation);
            throw std::runtime_error(operation);
        }
    }

    void Init(int32_t deviceId)
    {
        deviceId_ = deviceId;
        Check(aclInit(nullptr), "aclInit");
        initialized_ = true;
        Check(aclrtSetDevice(deviceId_), "aclrtSetDevice");
        deviceSet_ = true;
        Check(aclrtCreateStream(&stream_), "aclrtCreateStream");
    }

    template <typename T>
    aclTensor* CreateTensor(const std::vector<T>& host, const std::vector<int64_t>& shape, aclDataType dtype)
    {
        const int64_t elements = Numel(shape);
        if (static_cast<uint64_t>(elements) != host.size() ||
            host.size() > std::numeric_limits<size_t>::max() / sizeof(T) || aclDataTypeSize(dtype) != sizeof(T)) {
            throw std::invalid_argument("tensor shape, storage or dtype size mismatch");
        }
        const size_t bytes = host.size() * sizeof(T);
        std::vector<int64_t> strides(shape.size(), 1);
        // Numel validated every positive dimension and the total product above.
        for (size_t i = shape.size(); i > 1; --i) {
            strides[i - 2] = strides[i - 1] * shape[i - 1];
        }
        tensors_.push_back(std::make_unique<TensorResource>());
        auto& tensor = *tensors_.back();
        Check(aclrtMalloc(&tensor.device, bytes, ACL_MEM_MALLOC_HUGE_FIRST), "aclrtMalloc(tensor)");
        Check(aclrtMemcpy(tensor.device, bytes, host.data(), bytes, ACL_MEMCPY_HOST_TO_DEVICE), "aclrtMemcpy");
        tensor.descriptor = aclCreateTensor(shape.data(), shape.size(), dtype, strides.data(), 0, ACL_FORMAT_ND,
                                            shape.data(), shape.size(), tensor.device);
        Check(tensor.descriptor == nullptr ? ACL_ERROR_INVALID_PARAM : ACL_SUCCESS, "aclCreateTensor");
        return tensor.descriptor;
    }

    aclOpExecutor** ExecutorAddress() { return &executor_; }

    aclOpExecutor* PrepareExecutor()
    {
        // Keep ownership explicit; a repeatable executor is destroyed by Session.
        Check(aclSetAclOpExecutorRepeatable(executor_), "aclSetAclOpExecutorRepeatable");
        return executor_;
    }

    void* AllocateWorkspace(uint64_t bytes)
    {
        if (bytes > 0) {
            Check(aclrtMalloc(&workspace_, bytes, ACL_MEM_MALLOC_HUGE_FIRST), "aclrtMalloc(workspace)");
        }
        return workspace_;
    }

    aclrtStream StreamForLaunch()
    {
        // Even a failed launch may have submitted work; synchronize before freeing.
        pending_ = true;
        return stream_;
    }

    void Synchronize()
    {
        Check(aclrtSynchronizeStream(stream_), "aclrtSynchronizeStream");
        pending_ = false;
    }

private:
    struct TensorResource {
        void* device = nullptr;
        aclTensor* descriptor = nullptr;
    };
    void Record(int result, const char* operation)
    {
        if (result != ACL_SUCCESS) {
            std::cerr << operation << " failed: " << result << std::endl;
            if (status_ == ACL_SUCCESS) {
                status_ = result;
            }
        }
    }
    int& status_;
    int32_t deviceId_ = 0;
    bool initialized_ = false;
    bool deviceSet_ = false;
    bool pending_ = false;
    aclrtStream stream_ = nullptr;
    aclOpExecutor* executor_ = nullptr;
    void* workspace_ = nullptr;
    std::vector<std::unique_ptr<TensorResource>> tensors_;
};
} // namespace SwigluExample

using SwigluExample::CheckHardwareSupport;
using SwigluExample::Numel;

int main()
{
    int status = ACL_SUCCESS;
    {
        SwigluExample::Session session(status);
        try {
            session.Init(0);
            if (!CheckHardwareSupport("SwigluGroupQuantWithDualAxis")) {
                std::cout << "\n=== Test SKIPPED (hardware not supported) ===" << std::endl;
                return ACL_SUCCESS;
            }
            const std::vector<int64_t> xShape{64, 128};
            const std::vector<int64_t> yShape{64, 64};
            const std::vector<int64_t> scale1Shape{64, 1, 2};
            const std::vector<int64_t> scale2Shape{1, 64, 2};
            std::vector<uint16_t> xHost(Numel(xShape), 0x3C00);
            std::vector<uint8_t> yHost(Numel(yShape), 0);
            std::vector<uint8_t> scale1Host(Numel(scale1Shape), 0);
            std::vector<uint8_t> scale2Host(Numel(scale2Shape), 0);
            std::vector<uint16_t> originHost(Numel(yShape), 0);

            aclTensor* x = session.CreateTensor(xHost, xShape, ACL_FLOAT16);
            aclTensor* y1 = session.CreateTensor(yHost, yShape, ACL_FLOAT8_E4M3FN);
            aclTensor* s1 = session.CreateTensor(scale1Host, scale1Shape, ACL_FLOAT8_E8M0);
            aclTensor* y2 = session.CreateTensor(yHost, yShape, ACL_FLOAT8_E4M3FN);
            aclTensor* s2 = session.CreateTensor(scale2Host, scale2Shape, ACL_FLOAT8_E8M0);
            aclTensor* origin = session.CreateTensor(originHost, yShape, ACL_FLOAT16);

            uint64_t workspaceSize = 0;
            auto ret = aclnnSwigluGroupQuantWithDualAxisGetWorkspaceSize(x, nullptr, nullptr, ACL_FLOAT8_E4M3FN, 1, 7.0,
                                                                         true, 1.702, 1.0, y1, s1, y2, s2, origin,
                                                                         &workspaceSize, session.ExecutorAddress());
            session.Check(ret, "aclnnSwigluGroupQuantWithDualAxis");
            aclOpExecutor* executor = session.PrepareExecutor();
            void* workspace = session.AllocateWorkspace(workspaceSize);
            ret = aclnnSwigluGroupQuantWithDualAxis(workspace, workspaceSize, executor, session.StreamForLaunch());
            session.Check(ret, "aclnnSwigluGroupQuantWithDualAxis");
            session.Synchronize();

        } catch (const std::exception& error) {
            std::cerr << error.what() << std::endl;
            if (status == ACL_SUCCESS) {
                status = ACL_ERROR_INVALID_PARAM;
            }
        }
    }
    if (status != ACL_SUCCESS) {
        return 1;
    }
    std::cout << "aclnnSwigluGroupQuantWithDualAxis example succeeded" << std::endl;
    return 0;
}