mhc_post

Applicable Products

  • Ascend 950PR&950DT products: Supported
  • Atlas A3 products: Supported
  • Atlas A2 products: Supported
  • Atlas 200I/500 A2 inference products: Not supported
  • Atlas inference products: Not supported
  • Atlas training products: Not supported

Function

  • Description:

    Implements forward computation of the MHC Post component, which is used in the post-processing phase of multi-layer residual join in the Transformer model. This operator fuses the residual matrix transformation and output state projection into a single computation, avoiding extra overhead caused by multiple independent operator calls.

  • Formula:

    • The core formula of the MHC Post operator is:

      $$x_{l+1} = (H_{l}^{res})^{T} \cdot x_{l} + h_{l}^{out} \cdot H_{t}^{post}$$

      Where:

      • $(H_{l}^{res})^{T} \cdot x_{l}$ denotes the multiplication of the input $x_{l}$ by the transpose of the residual matrix. For the $i$-th row in the output (corresponding to the $i$-th head), the computation is:

        $$x_{l+1}[i] = \sum_{j=0}^{n-1} H_{l}^{res}[j, i] \cdot x_{l}[j]$$

        That is, matrix $H_{l}^{res}$ is transposed and multiplied with $x_{l}$. $H_{l}^{res}[j, i]$ is a scalar, which multiplies row $j$ of $x_{l}$, and the result is accumulated into row $i$ of the output.

      • $h_{l}^{out} \cdot H_{t}^{post}$ represents element-wise multiplication and broadcast between output state $h_{l}^{out}$ and post-processing weight $H_{t}^{post}$. For the $i$-th head:

        $$x_{l+1}[i] += H_{t}^{post}[i] \cdot h_{l}^{out}$$

        That is, $H_{t}^{post}[i]$ is a scalar, which multiplies the entire row of $h_{l}^{out}$, and the result is added to row $i$ of the output.

    • In summary, the complete calculation process is:

      $$x_{l+1}[i, :] = H_{t}^{post}[i] \cdot h_{l}^{out}[:] + \sum_{j=0}^{n-1} H_{l}^{res}[j, i] \cdot x_{l}[j, :]$$

      where $x_{l}$ represents parameter x, $H_{l}^{res}$ represents parameter h_res, $h_{l}^{out}$ represents parameter h_out, $H_{t}^{post}$ represents parameter h_post, and $x_{l+1}$ represents the output y.

    • When h_res is None, Res Mapping is skipped, and the formula degrades to a direct residual connection:

      $$x_{l+1} = x_{l} + h_{l}^{out} \cdot H_{t}^{post}$$

    NOTE:

    The input supports two dimension formats: BSND (4-dimensional) and TND (3-dimensional), where B (Batch) indicates the batch size, S (Seq-Length) indicates the sequence length, T indicates the cumulative sum of sequence lengths of all batches ($T = B \times S$), n indicates the number of heads (head count), and D indicates the hidden dimension size (headdim) of each head.

Prototype

cann_ops_transformer.mhc_post(x, h_res, h_out, h_post) -> Tensor

where h_res is an optional input and None can be passed in (only the single-operator mode of Ascend 950PR&950DT products supports passing in None; None is not supported in graph mode).

Parameters

Parameter Parameter Type Optional/Required Description Data Type Dimension (shape)
x Tensor Required Input token features of the current layer, corresponding to xl in the formula. bfloat16, float16
  • (B, S, n, D)
  • (T, n, D)
h_res Tensor Optional Residual connection matrix, corresponding to Hlres in the formula. When h_res is None, Res Mapping is skipped and the formula degrades to direct residual connection. Only Ascend 950PR&950DT products support passing in None. Passing in None on other products raises an error. float32
  • (B, S, n, n)
  • (T, n, n)
h_out Tensor Required Output state of the previous layer, corresponding to Hlout in the formula. bfloat16, float16
  • (B, S, D)
  • (T, D)
h_post Tensor Required Post-processing weight matrix, corresponding to Htpost in the formula. float32
  • (B, S, n)
  • (T, n)

Return Values

Parameter Type Optional/Required Description Data Type Dimension (shape)
y Tensor Required Output of MHC Post, corresponding to xl+1 in the corresponding formula. The data type is kept consistent with input `x`, and the shape is kept consistent with input `x`. bfloat16, float16
  • (B, S, n, D)
  • (T, n, D)

Constraints

  • This API supports both training and inference use cases.

  • This API supports calls in single-operator mode and graph mode.

  • Data type constraints:

    • The data types of x and h_out must be the same.
    • The data type of output y is kept consistent with x.
  • h_res optional constraints:

    • When h_res is None, Res Mapping is skipped; this is supported only by Ascend 950PR&950DT products. For Atlas A2/A3 products, h_res is a required parameter, and passing in None causes an error.
    • Passing in None for h_res is supported only in single-operator mode. In graph mode (torch.compile), h_res must be passed in; passing in None causes an error in the GE compilation phase.
  • Dimension Constraints:

    • The dimension of h_res must be consistent with the dimension format of x: (B, S, n, n) for 4 dimensions, and (T, n, n) for 3 dimensions.
  • Shape consistency constraints:

    • 4D (BSND) format:
      • The (B, S) dimensions of h_res must be consistent with the (B, S) dimensions of x, and the last two dimensions of h_res are (n, n), where n is consistent with the third dimension of x.
      • The (B, S) dimensions of h_out must be consistent with the (B, S) dimensions of x, and the D dimension of h_out must be consistent with the D dimension of x.
      • The (B, S) dimensions of h_post must be consistent with the (B, S) dimensions of x, and the n dimension of h_post must be consistent with the n dimension of x.
    • 3D (TND) format:
      • The T dimension of h_res must be consistent with the T dimension of x, and the last two dimensions are (n, n).
      • The T dimension of h_out must be consistent with the T dimension of x, and the D dimension of h_out must be consistent with the D dimension of x.
      • The T dimension of h_post must be consistent with the T dimension of x, and the n dimension of h_post must be consistent with the n dimension of x.
  • The value of each dimension in the shape of all input tensors must be a positive number (greater than 0).

Deterministic Computation

Defaults to a deterministic implementation.

Calling Instructions

  • Single-operator mode call:

    import torch
    import torch_npu
    from cann_ops_transformer.ops import mhc_post
    
    B = 2
    S = 8
    n = 4
    D = 128
    
    x = torch.randn(B, S, n, D, dtype=torch.bfloat16).npu()
    h_res = torch.randn(B, S, n, n, dtype=torch.float32).npu()
    h_out = torch.randn(B, S, D, dtype=torch.bfloat16).npu()
    h_post = torch.randn(B, S, n, dtype=torch.float32).npu()
    
    y = mhc_post(x, h_res, h_out, h_post)
    print(f"output shape: {y.shape}")
    
    # When h_res is omitted (supported only on Ascend 950PR&950DT products, and only in single-operator mode)
    y = mhc_post(x, None, h_out, h_post)
    print(f"output shape: {y.shape}")
  • Graph mode call:

    import torch
    import torch_npu
    import torchair
    from cann_ops_transformer.ops import mhc_post
    
    torch_npu.npu.set_device(0)
    
    B = 2
    S = 8
    n = 4
    D = 128
    
    class MhcPostModel(torch.nn.Module):
        def forward(self, x, h_res, h_out, h_post):
            return mhc_post(x, h_res, h_out, h_post)
    
    model = MhcPostModel().npu()
    npu_backend = torchair.get_npu_backend()
    model = torch.compile(model, backend=npu_backend, dynamic=False)
    
    x = torch.randn(B, S, n, D, dtype=torch.bfloat16, device="npu")
    h_res = torch.randn(B, S, n, n, dtype=torch.float32, device="npu")
    h_out = torch.randn(B, S, D, dtype=torch.bfloat16, device="npu")
    h_post = torch.randn(B, S, n, dtype=torch.float32, device="npu")
    
    y = model(x, h_res, h_out, h_post)