---
title: UnpadOperation
description: "| 硬件型号 | 是否支持 |"
url: https://www.hiascend.com/document/detail/zh/canncommercial/latest/API/ascendtb/ascendtb_01_0085.html
sourcePath: /source/zh/canncommercial/900/API/ascendtb/ascendtb_01_0085.html
indexId: da0d51f8576f3efd34943915484c135a70ec8a72ede93fcc3a02396356a1733d64
---
# UnpadOperation

#### 产品支持情况

| 硬件型号 | 是否支持 |
| --- | --- |
| Atlas 350 加速卡 | x |
| Atlas A3 推理系列产品 / Atlas A3 训练系列产品 | √ |
| Atlas A2 训练系列产品 / Atlas A2 推理系列产品 | √ |
| Atlas 训练系列产品 | x |
| Atlas 推理系列产品 | √ |
| Atlas 200I/500 A2 推理产品 | x |


#### 功能说明

对于输入input_ids，把所有有效的token拼接在一起，并在最后补0。


#### 使用场景

为了保证[batch,max_seq_len]的二维shape,某些batch的真实句子长度会被扩展成max_seq_len的长度，此算子目的为去除这些padding的部分。

使用示例：

假设有以下输入：

- input_ids：[[1, 2, 3, 0, 0], [4, 5, 0, 0, 0]]
- cum_offsets_now：[[2], [5]]
- seq_len：[[3], [2]]

在这个例子中：

- 第一个 batch 有 2 个填充 0，因此 cum_offsets_now 的第一个值是 2。
- 第二个 batch 有 5 个填充 0（包括第一个 batch 的 2 个填充 0），因此 cum_offsets_now 的第二个值是 5。

通过 unpad 算子处理后：

1. 计算 cum_offsets_out：
  去除最后一个 batch 的数值：[[2]]

  整体后移一个 batch：[[0], [2]]

  第一个 batch 的值置为 0：[[0], [2]]（cum_offsets_out的值）

2. 移除填充 0：

  - 对于第一个 batch：

    - cum_offsets_out[0] 是 0，表示从位置 0 开始。
    - seq_len[0] 是 3，表示有 3 个有效 token。
    - 将 input_ids[0] 中的前 3 个有效 token 复制到 x_remove_padding 的前 3 个位置。
  - 对于第二个 batch：

    - cum_offsets_out[1] 是 2，表示从位置 2 开始。
    - seq_len[1] 是 2，表示有 2 个有效 token。
    - 将 input_ids[1] 中的前 2 个有效 token 复制到 x_remove_padding 的第 3 和第 4 个位置。
    - 根据 cum_offsets_out 和 seq_len，重新排列有效 token，得到 x_remove_padding：[1, 2, 3, 4, 5, 0, 0, 0, 0, 0]。

应用场景：

在自然语言处理（NLP）中，输入的句子长度通常不同。为了让它们在一个 batch 中处理，我们需要将它们填充（pad）到相同的长度。填充的方式通常是在句子的末尾添加零（0），直到所有句子长度相同。Unpad 用于在处理完这些填充的序列后，去除填充的 0，提取有效的 token 序列。


#### 定义

```
struct UnpadParam {
    uint8_t rsv[8] = {0};
};
```


#### 参数列表

| 成员名称 | 类型 | 默认值 | 描述 |
| --- | --- | --- | --- |
| rsv[8] | uint8\_t | {0} | 预留参数。 |


#### 输入

| 参数 | 维度 | 数据类型 | 格式 | 描述 |
| --- | --- | --- | --- | --- |
| input\_ids | [batch, max\_seq\_len] | int64 | ND | 输入tensor：经过pad（末尾填充0）之后，batch个token id序列。 |
| cum\_offsets\_now | [batch, 1] | int32 | ND | 输入tensor：每个batch末尾填充0的数量组成的序列的前缀和。 |
| token\_num | [batch, 1] | int64 | ND | 输入tensor：有效token数量总和。 |
| seq\_len | [batch, 1] | int32 | ND | 输入tensor：每个batch中的有效token数量。 |


#### 输出

| 参数 | 维度 | 数据类型 | 格式 | 描述 |
| --- | --- | --- | --- | --- |
| x\_remove\_padding | [1, batch \* max\_seq\_len] | int64 | ND | 输出tensor：从input\_ids中去除填充的0后得到的有效token序列（为了保持shape，在末尾填充0）。 |
| cum\_offsets\_out | [batch, 1] | int32 | ND | 输出tensor：去除cum\_offsets\_now最后一个batch的数值，再将其整体后移一个batch，并将第一个batch的值置为0。 |
| padding\_offset | [1, batch \* max\_seq\_len] | int32 | ND | 输出tensor：由seq\_len和cum\_offsets\_out组合计算得到。 |


#### 约束说明

1<=batch<=64
