pytorch - Pytorch 为 nn.Module 函数添加自定义反向传递
问题描述
我正在重新实现可逆残差网络架构。
class iResNetBlock(nn.Module):
def __init__(self, input_size, hidden_size):
self.bottleneck = nn.Sequential(
LinearContraction(input_size, hidden_size),
LinearContraction(hidden_size, input_size),
nn.ReLU(),
)
def forward(self, x):
return x + self.bottleneck(x)
def inverse(self, y):
x = y.clone()
while not converged:
# fixed point iteration
x = y - self.bottleneck(x)
return x
我想为inverse
函数添加一个自定义的反向传递。由于它是定点迭代,因此可以利用隐函数定理来避免循环展开,而是通过求解线性系统来计算梯度。例如,这是在深度平衡模型架构中完成的。
def inverse(self, y):
with torch.no_grad():
x = y.clone()
while not converged:
# fixed point iteration
x = y - self.bottleneck(x)
return x
def custom_backward_inverse(self, grad_output):
pass
如何为此功能注册我的自定义反向通行证?我希望,当我稍后定义一些损失时 r = loss(y, model.inverse(other_model(model(x))))
,r.backwards()
正确地使用我的自定义渐变进行反向调用。
理想情况下,解决方案应该是torchscript
兼容的。
解决方案
推荐阅读
- python - 用于 Internet Explorer 的 driver.find_element_by_name() 的 Selenium
- r - 我可以在 R 中改变(划分)具有不同长度的列吗?
- python - 如何在 C++ 中使用命名参数
- python - 使用任何 OCR 从图像中仅提取粗体文本
- snowflake-sql - Call 表和 Order 表的 First Call 时间和 First Order 时间之间的时间差
- python - 为什么在使用“nltk.ne_chunk”分块后我没有得到“PERSON”和“GPE”作为标签?
- css - EJS 没有加载 CSS 文件
- paraview - [帕拉维尤];如何在 Paraview 中缩放部分数据
- python-3.x - 如何使用 python 解析 PDF 格式的网页并以漂亮的格式打印它的内容?
- javascript - 达到 maxlength 后自动聚焦到下一个输入