torch.autograd.grad grad_outputs使用示例,batch批量求导
# %%
import torch
from torch import autograd
import torchvision
resnet = torchvision.models.resnet.resnet18()
convs = torch.nn.Sequential(*(list(resnet.children())[:-1]))
x1 = torch.randn(64, 3, 100, 200).requires_grad_()
y1 = convs(x1)
x2 = torch.randn(64, 3, 100, 200).requires_grad_()
y2 = convs(x2)
y = torch.cat([y1,y2],dim = 0)
x = torch.cat([x1,x2],dim = 0)
print(y.shape)
print(x.shape)
grad = torch.autograd.grad(inputs= x,outputs= y, grad_outputs=torch.ones_like(y),allow_unused=True)
grad
"""
torch.Size([128, 512, 1, 1])
torch.Size([128, 3, 100, 200])
(None,)
"""
x1 = torch.randn(64, 3, 100, 200).requires_grad_()
y1 = convs(x1)
x2 = torch.randn(64, 3, 100, 200).requires_grad_()
y2 = convs(x2)
# 一个标量能对一个向量求导数吗
# outputs (sequence of Tensor) – outputs of the differentiated function.
# inputs (sequence of Tensor) – Inputs w.r.t. which the gradient will be returned (and not accumulated into .grad).
grad = torch.autograd.grad(inputs= (x1,x2),outputs= (y1,y2), grad_outputs=[torch.ones_like(y1),torch.ones_like(y2)])
print(len(grad[0]))
# 输出也是一个sequence
print(grad[0].shape)
print(grad[1].shape)
"""
64
torch.Size([64, 3, 100, 200])
torch.Size([64, 3, 100, 200])
"""
作者:JoyFrank
出处:https://www.cnblogs.com/zxyfrank/p/17043098.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
世界上只有一种英雄主义,就是看到生活本来的样子,并且热爱它
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具