attention-model - 来自 Trax 的 AttentionQKV
问题描述
Trax 实现的 AttentionQKV 层如下:AttentionQKV
def AttentionQKV(d_feature, n_heads=1, dropout=0.0, mode='train'):
"""Returns a layer that maps (q, k, v, mask) to (activations, mask).
See `Attention` above for further context/details.
Args:
d_feature: Depth/dimensionality of feature embedding.
n_heads: Number of attention heads.
dropout: Probababilistic rate for internal dropout applied to attention
activations (based on query-key pairs) before dotting them with values.
mode: One of `'train'`, `'eval'`, or `'predict'`.
"""
return cb.Serial(
cb.Parallel(
core.Dense(d_feature),
core.Dense(d_feature),
core.Dense(d_feature),
),
PureAttention( # pylint: disable=no-value-for-parameter
n_heads=n_heads, dropout=dropout, mode=mode),
core.Dense(d_feature),
)
特别是三个平行的密集层的目的是什么?该层的输入是 q, k, v, mask。为什么 q, k, v 要通过一个密集层?
解决方案
此代码片段是 2017 年介绍 Transformer 模型的Attention is all you need论文第 5 页顶部的方程式的实现。计算如图 2 所示:
隐藏状态投射到h个注意力头中,这些注意力头并行地进行缩放的点积注意力。投影可以解释为提取与头部相关的信息。然后每个头根据不同的(学习的)标准进行概率检索。
推荐阅读
- java - 每次来自 AddSingleValueEventListner 的 onDataChange 时,如何更新来自 firebase 子节点的子节点总数?
- android - 如何用样式替换 setSupportActionBar?
- javascript - 如何使用 jquery ajax 将多个 HTML 页面下载到带有 apify 的 Dropbox
- excel - 匹配后定义新特征
- python-3.x - 一种矢量化方法,用于在 pandas 数据框中创建一个新列,其值来自另一列但不是同一行
- tensorflow2.0 - 从检查点加载模型失败?
- docker - 为什么使用自定义用户创建 docker 容器会重新发布派生图像?
- jquery - 如何访问从 AJAX 查询返回的 JSON 元素
- bootstrap-4 - flex-direction 的全高:column
- python - Pandas:从一个数据框列中过滤数据并更新另一个 df 列