# qkv为什么要乘上不同的参数矩阵

Self-Attention的核心是用文本中的其它词来增强目标词的语义表示, 从而更好的利用上下文的信息.

在self-attention中, sequence中的每个token都会和sequence中的每个token做点积去计算相似度, 也包括这个词本身. 而对于self-attention, 它的q, k, v来自同一向量, 如果不乘各自的参数, 即使用各自的`Dense`作用, 则q, k, v是完全一样的.

在这种情况下, 如果每个token对应的向量, 如果模长相近, $$q\_i$$与$$k\_i$$两个向量的点积, 即同一个token之间的点积, 得到的值是最大的, 因为两个向量的方向一致, 没有夹角.

然后对得到的点积矩阵求softmax, 相同位置的最终得到的值会是很大的(可以看到attention矩阵对角线的值很大), 然后使用这个值对所有token的向量进行加权平均, 那么这个token本身占的比重将会是最大的, 而且往往远超其他位置的token. 这就使得其他token的比重很小, 无法有效利用上下文信息来增强当前词的语义表示.

而乘上各自不同的矩阵之后, 同一个token对应q, k, v将会不一样, 在很大程度上能够**缓解**上面的影响(不是完全解决, 一般情况下在经过attention转换后, 还是同一个token成分最大).

## 参考资料

* [超细节的BERT/Transformer知识点](https://zhuanlan.zhihu.com/p/132554155)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://kerasnoone.gitbook.io/garnet/shen-jing-wang-luo/cnnrnntf-san-zhong-te-zheng-chou-qu-qi-de-bi-jiao/transformer/multi-head-attention/multiheadattention-zhong-de-qkv-wei-shi-mo-yao-cheng-shang-bu-tong-de-can-shu-ju-zhen.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
