# 掩码（计算）

在计算领域，掩码是一种布尔数组、张量或位模式，用于标记数据结构中哪些元素应被选中、忽略或替换。掩码与数据一同存储，或作为单独参数传入，运算会逐元素查询掩码：以某种方式标记的条目参与计算，以另一种方式标记的条目则被跳过、置零或填入替代值。这一思想在计算的各个尺度上都有体现，从整数的[位运算](https://www.edgepedia.org/zh/bitwise-operation)到大型语言模型内部的注意力掩码。

| 关键事实 | 详情 |
|---|---|
| 核心机制 | 掩码是与数据形状相同（或可广播）的布尔结构；每个元素的掩码值决定该元素是被使用、忽略还是覆盖<sup>[1](https://numpy.org/doc/stable/reference/maskedarray.generic.html)</sup> |
| NumPy 约定 | 在 `numpy.ma` 中，`True` 掩码条目将对应数据元素标记为无效，被掩码的条目不计入计算<sup>[1](https://numpy.org/doc/stable/reference/maskedarray.generic.html)</sup> |
| 选择 | `tf.boolean_mask(tensor, mask)` 返回一个 (N−K+1) 维张量，其中包含 N 维张量里 K 维掩码为 `True` 的条目；NumPy 中的等价写法是 `tensor[mask]`<sup>[2](https://www.tensorflow.org/api_docs/python/tf/boolean_mask?authuser=56)</sup> |
| 替换 | `torch.Tensor.masked_fill` 在掩码为 `True` 处用指定值填充张量元素<sup>[3](https://docs.pytorch.org/docs/stable/tensors.html?highlight=masked_fill_)</sup> |
| 注意力掩码 | Transformer 解码器施加掩码，阻止位置关注后续位置，从而使位置 \( i \) 的预测仅依赖于小于 \( i \) 的位置的输出<sup>[4](https://arxiv.org/abs/1706.03762)</sup> |
| 约定陷阱 | 在 PyTorch 中，`MultiheadAttention` 的 `key_padding_mask` 里 `True` 表示*忽略*，而 `scaled_dot_product_attention` 的 `attn_mask` 里 `True` 表示*参与*；两者之间迁移时需要反转掩码<sup>[5](https://docs.pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention)</sup> |
| 预训练用途 | BERT 从双向上下文预测被掩码的词，BEiT 则将掩码建模扩展到图像：掩蔽图像块并恢复视觉词元<sup>[6](https://arxiv.org/abs/1810.04805)</sup><sup> • </sup><sup>[7](https://arxiv.org/abs/2106.08254)</sup> |

## 选择与过滤

掩码最直接的用途是挑出元素的子集。布尔掩码数组为每个数据元素对应一个条目，用掩码索引数据只返回掩码值为 `True` 的元素。TensorFlow 的 `tf.boolean_mask` 将这一操作形式化到 N 维张量：掩码的 K 个维度必须与张量的前 K 个维度匹配，结果是一个 (N−K+1) 维张量，按行优先顺序填入对应 `True` 值的条目<sup>[2](https://www.tensorflow.org/api_docs/python/tf/boolean_mask?authuser=56)</sup>。PyTorch 提供对应操作 `masked_select`，根据布尔掩码索引输入并返回新的一维张量<sup>[8](https://docs.pytorch.org/docs/stable/torch.html?highlight=diag)</sup>。

掩码也驱动条件选择而非删除。在 `tf.where` 中，当提供值 `x` 和 `y` 时，条件张量充当掩码，决定每个输出元素来自 `x`（条件为 `True`）还是 `y`（条件为 `False`），三个输入相互广播<sup>[9](https://www.tensorflow.org/api_docs/python/tf/where?authuser=0000)</sup>。PyTorch 中的相关操作 `masked_fill` 在掩码为 `True` 的每个位置写入替代值，张量其余部分保持不变<sup>[3](https://docs.pytorch.org/docs/stable/tensors.html?highlight=masked_fill_)</sup>。

## 掩码数组与缺失数据

**掩码数组将数据与有效性配对。** NumPy 的 `numpy.ma` 模块将掩码数组实现为标准 `ndarray` 与掩码的组合，掩码要么是特殊值 `nomask`（无元素无效），要么是标记每个元素有效或无效的布尔数组。`True` 掩码条目将对应数据元素标记为无效，该包确保被掩码的条目不参与计算<sup>[1](https://numpy.org/doc/stable/reference/maskedarray.generic.html)</sup>。这一设计针对的是存在但应暂时忽略的数据，例如超出有效区域的传感器读数，与真正缺失的值有所区别<sup>[10](https://numpy.org/neps/nep-0024-missing-data-2.html)</sup>。

掩码随数据一同经历运算。有效条目可以通过反转掩码索引（`x[~x.mask]`）或使用 `compressed` 方法恢复，后者始终返回一维数组<sup>[1](https://numpy.org/doc/stable/reference/maskedarray.generic.html)</sup>。算术与比较运算会传播掩码：二元运算的结果在任何输入被掩码处均被掩码<sup>[1](https://numpy.org/doc/stable/reference/maskedarray.generic.html)</sup>。一种更廉价的近似做法是在浮点数据中用 NaN 充当“穷人版掩码”，`nansum`、`nanmean` 等函数会将 NaN 条目排除在结果之外<sup>[11](https://numpy.org/doc/stable/user/misc.html)</sup>。

PyTorch 用 `MaskedTensor` 推广了这一思想，这是一种张量子类，由数据加掩码组成，掩码指明哪些条目应包含或忽略。其诞生原因是“已指定”与“未指定”值在 PyTorch 中历史悠久却缺乏形式语义，它旨在让这类值成为一等公民，支持变长数据的掩码语义、区分零梯度与 NaN 梯度，并赋能稀疏应用。该 API 目前处于原型阶段<sup>[12](https://docs.pytorch.org/docs/stable/masked.html)</sup>。

## 神经网络中的序列掩码

循环与 [Transformer](https://www.edgepedia.org/zh/transformer) 模型处理不等长序列的批次，掩码将填充位置排除在计算之外。Keras 提供 `Masking` 层，跳过所有特征值均等于选定 `mask_value`（默认为 0.0）的时间步；掩码向下游支持掩码的层传播，不支持掩码的层若收到掩码则抛出异常<sup>[13](https://keras.io/api/layers/core_layers/masking/)</sup>。在 Keras 的约定中，被掩码的时间步记为 `False`，可用的时间步记为 `True`<sup>[13](https://keras.io/api/layers/core_layers/masking/)</sup>。

**注意力掩码控制模型能看什么。** 在原版 Transformer 中，解码器的自注意力子层经过修改，阻止位置关注后续位置；结合输出嵌入的一个位置的偏移，这一掩码确保位置 \( i \) 的预测仅依赖于位置小于 \( i \) 的已知输出<sup>[4](https://arxiv.org/abs/1706.03762)</sup>。正是这种因果（下三角）掩码使自回归生成得以成立。PyTorch 直接暴露该机制：`MultiheadAttention` 接受形状为 \( (N, S) \) 的 `key_padding_mask`，标记哪些键元素作为填充应被忽略，以及形状为 \( (L, S) \) 或 \( (N \cdot \text{num\_heads}, L, S) \) 的 `attn_mask`，阻止对某些位置的注意力，可用二值或浮点形式<sup>[14](https://docs.pytorch.org/docs/stable/generated/torch.nn.MultiheadAttention.html)</sup>。两种约定的极性相反：在 `key_padding_mask` 中，二值 `True` 表示该值被忽略；而在 `scaled_dot_product_attention` 的 `attn_mask` 中，`True` 表示该元素参与注意力，因此在两者之间迁移时必须反转掩码<sup>[5](https://docs.pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention)</sup>。

`flex_attention` API 将掩码表达为函数而非张量：可调用的 `mask_mod` 接收批次、头、查询索引和键/值索引，返回该注意力连接是否允许，`create_block_mask` 据此构建块稀疏掩码。因果掩码就是一行函数：`q_idx >= kv_idx`<sup>[15](https://docs.pytorch.org/docs/stable/nn.attention.flex_attention.html)</sup>。

研究仍在不断改进这些掩码。StableMask 针对相对位置编码下因果掩码的两个局限：即使当前嵌入已自足，所有注意力分数仍必须非零且和为 1；以及此类 Transformer 并非通用近似器。它引入伪注意力值和逐步递减的掩码比例，在 7100 万到 14 亿参数的语言模型上显示出增益<sup>[16](https://arxiv.org/abs/2402.04779)</sup>。一项 2025 年关于视觉语言模型的研究发现，在预填充阶段对视觉查询严格掩蔽未来位置过于僵化，于是提出未来感知注意力，将未来视觉上下文池化到过去的表示中，同时保持自回归结构<sup>[17](https://arxiv.org/abs/2505.18605)</sup>。

## 掩码作为训练信号

掩码不仅是排除数据的手段，它还能创造学习任务本身。BERT 用掩码语言模型预训练双向编码器，从左、右两侧上下文预测被掩码的词，突破了单向语言建模的局限<sup>[6](https://arxiv.org/abs/1810.04805)</sup>。[BEiT](https://www.edgepedia.org/zh/beit) 将这一配方迁移到视觉：每张图像被词元化为视觉词元，图像块被随机掩蔽，预训练目标是从损坏的图像块恢复原始视觉词元；基础规模的 BEiT 在 ImageNet-1K 上达到 83.2% 的 top-1 准确率<sup>[7](https://arxiv.org/abs/2106.08254)</sup>。

Dropout 对网络单元施加随机掩码：训练时单元及其连接被随机丢弃，防止单元过度共适应，近似于对指数级数量的稀疏网络取平均<sup>[18](https://www.jmlr.org/papers/v15/srivastava14a.html)</sup>。在注意力中，同样的随机掩码思想表现为缩放点积注意力中概率可配置的注意力 dropout<sup>[5](https://docs.pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention)</sup>。

## 其他用途

掩码一词还涵盖数据净化。OpenAI 于 2025 年发布的 Privacy Filter 是一个开放权重的模型，用于检测并隐去文本中的个人身份信息；它可在本地运行，使个人身份信息在不离开本机的情况下被掩码或隐去，类别涵盖账号、密码和 API 密钥<sup>[19](https://openai.com/index/introducing-openai-privacy-filter/)</sup>。

## References

1. [The numpy.ma module, NumPy v2.5 Manual](https://numpy.org/doc/stable/reference/maskedarray.generic.html)
2. [tf.boolean_mask, TensorFlow v2.16.1 API documentation](https://www.tensorflow.org/api_docs/python/tf/boolean_mask?authuser=56)
3. [torch.Tensor, PyTorch 2.7 documentation](https://docs.pytorch.org/docs/stable/tensors.html?highlight=masked_fill_)
4. [Vaswani et al. (2017). Attention Is All You Need. arXiv:1706.03762](https://arxiv.org/abs/1706.03762)
5. [torch.nn.functional.scaled_dot_product_attention, PyTorch 2.14 documentation](https://docs.pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention)
6. [Devlin et al. (2018). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. arXiv:1810.04805](https://arxiv.org/abs/1810.04805)
7. [Bao et al. (2021). BEiT: BERT Pre-Training of Image Transformers. arXiv:2106.08254](https://arxiv.org/abs/2106.08254)
8. [torch, PyTorch 2.14 documentation](https://docs.pytorch.org/docs/stable/torch.html?highlight=diag)
9. [tf.where, TensorFlow v2.16.1 API documentation](https://www.tensorflow.org/api_docs/python/tf/where?authuser=0000)
10. [NEP 24 — Missing data functionality - alternative 1 to NEP 12, NumPy Enhancement Proposals](https://numpy.org/neps/nep-0024-missing-data-2.html)
11. [Miscellaneous, NumPy v2.5 Manual](https://numpy.org/doc/stable/user/misc.html)
12. [torch.masked, PyTorch 2.14 documentation](https://docs.pytorch.org/docs/stable/masked.html)
13. [Masking layer, Keras 3 API documentation](https://keras.io/api/layers/core_layers/masking/)
14. [MultiheadAttention, PyTorch 2.14 documentation](https://docs.pytorch.org/docs/stable/generated/torch.nn.MultiheadAttention.html)
15. [torch.nn.attention.flex_attention, PyTorch 2.14 documentation](https://docs.pytorch.org/docs/stable/nn.attention.flex_attention.html)
16. [Yin et al. (2024). StableMask: Refining Causal Masking in Decoder-only Transformer. arXiv:2402.04779](https://arxiv.org/abs/2402.04779)
17. [Pei et al. (2025). Rethinking Causal Mask Attention for Vision-Language Inference. arXiv:2505.18605](https://arxiv.org/abs/2505.18605)
18. [Srivastava et al. (2014). Dropout: A Simple Way to Prevent Neural Networks from Overfitting. JMLR 15(56):1929–1958](https://www.jmlr.org/papers/v15/srivastava14a.html)
19. [Introducing OpenAI Privacy Filter, OpenAI](https://openai.com/index/introducing-openai-privacy-filter/)

---
*Initially written Sep 17, 2026 · Reviewed: Sep 30, 2026; Oct 15, 2026 · Edited: Sep 30, 2026; Oct 15, 2026 · Last review: Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 人工智能与数据 › Algorithms and computational methods › Algorithms overview

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/mask-computing

English original: https://www.edgepedia.org/mask-computing
