type
status
date
slug
summary
tags
category
icon
password
PyTorch提供了封装好的Transformer模块,在使用时可以直接声明对象。这种使用起来非常方便,但是封装的方法缺少了很多自主模块,特别是我们想要指定输出模型的一些隐藏层的时候。
因此,本文在此介绍Hook方法。
Hook 方法命中的是类的self属性,比如对self.subNetworkName注册Hook。可以获得对subNetworkName这个层的输入inputs与outputs.
在当前的版本,或者说较新的PyTorch版本中,nn.TransformerEncoder对self attention 的调用如下:
这里的need_weight=False,所以返回值有两个,这里源代码直接取了[0]。
为了获得权重,我们做如下调整:
此时,可能使用hook仍然无法获得自注意力的权重,是因为torch目前会默认调用一个C++ Fast-Path的方法略过self_attn子成员,而使用另一个函数完成自注意力。
所以我们可以设置屏蔽该通道:
此时使用的nn.TransformerEncoderLayer才会调用self.self_attn.
- Author:Kecilimu
- URL:https://kecilimu-notion.vercel.app//article/20250613180213
- Copyright:All articles in this blog, except for special statements, adopt BY-NC-SA agreement. Please indicate the source!