当前位置:网站首页>rearrange 和 einsum 真的优雅吗
rearrange 和 einsum 真的优雅吗
2022-04-23 06:12:00 【wujpbb7】
结论是,还好吧。
从代码量看,差不多:
# -*- coding:utf-8 -*-
import torch
from torch import nn
from torch import einsum
from einops import rearrange
class SimpleQKV(nn.Module):
def __init__(self, dim, use_ein):
super().__init__()
self.proj = nn.Linear(dim, dim*3, bias=False)
self.dim = dim
self.scale = self.dim ** -0.5
self.use_ein = use_ein
torch.manual_seed(777) # 为了使权重相同,便于比较输出
nn.init.xavier_uniform_(self.proj.weight)
def forward(self, x):
n,c,h,w = x.shape
#assert c==self.dim
if (self.use_ein):
x = rearrange(x, 'n c h w -> n (h w) c')
else:
x = x.permute(0,2,3,1).view(n, -1, c)
qkv = self.proj(x)
q,k,v = qkv.chunk(chunks=3,dim=-1)
if (self.use_ein):
attn = (einsum('n i c, n j c -> n i j', q, k) * self.scale).softmax(dim=-1)
v = einsum('n i j, n j c -> n i c', attn, v)
output = rearrange(v, 'n (h w) c -> n c h w', h=h)
else:
attn = (torch.matmul(q, k.transpose(1,2)) * self.scale).softmax(dim=-1)
v = torch.matmul(attn, v)
output = v.permute(0,2,1).view(n,c,h,w)
return output
batch, chan, height, width = 1, 20, 7, 7
simple_qkv_ein = SimpleQKV(chan, True)
simple_qkv_noein = SimpleQKV(chan, False)
x = torch.randn(batch, chan, height, width, device='cpu')
out1 = simple_qkv_ein(x)
out2 = simple_qkv_noein(x)
assert(out1.equal(out2))
# 保存onnx
simple_qkv_ein.eval()
onnx_filename = './simple_qkv_ein.onnx'
torch.onnx.export(simple_qkv_ein, x, onnx_filename,
input_names=['input'], output_names=['ouput'],
export_params=True, verbose=False, opset_version=12)
simple_qkv_noein.eval()
onnx_filename = './simple_qkv_noein.onnx'
torch.onnx.export(simple_qkv_noein, x, onnx_filename,
input_names=['input'], output_names=['ouput'],
export_params=True, verbose=False, opset_version=12)
print('save onnx succ.')
从保存的onnx看(经过 onnxsim 优化),也差不多:

版权声明
本文为[wujpbb7]所创,转载请带上原文链接,感谢
https://blog.csdn.net/blueblood7/article/details/121223135
边栏推荐
- Chapter 5 fundamentals of machine learning
- 面试总结之特征工程
- .net加载字体时遇到 Failed to decode downloaded font:
- 电脑关机程序
- C# EF mysql更新datetime字段报错Modifying a column with the ‘Identity‘ pattern is not supported
- unhandled system error, NCCL version 2.7.8
- 第4章 Pytorch数据处理工具箱
- PyTorch 13. 嵌套函数和闭包(狗头)
- Android exposed components - ignored component security
- [2021 book recommendation] kubernetes in production best practices
猜你喜欢

第1章 NumPy基础
![[recommendation of new books in 2021] practical IOT hacking](/img/9a/13ea1e7df14a53088d4777d21ab1f6.png)
[recommendation of new books in 2021] practical IOT hacking

【点云系列】Unsupervised Multi-Task Feature Learning on Point Clouds
![[2021 book recommendation] Red Hat Certified Engineer (RHCE) Study Guide](/img/36/1c484aec5efbac8ae49851844b7946.png)
[2021 book recommendation] Red Hat Certified Engineer (RHCE) Study Guide

ArcGIS License Server Administrator 无法启动解决方法

【点云系列】DeepMapping: Unsupervised Map Estimation From Multiple Point Clouds
![[2021 book recommendation] artistic intelligence for IOT Cookbook](/img/8a/3ff45a911becb895e6dd9e061ac252.png)
[2021 book recommendation] artistic intelligence for IOT Cookbook

第5 章 机器学习基础
![Android interview Online Economic encyclopedia [constantly updating...]](/img/48/dd1abec83ec0db7d68812f5fa9dcfc.png)
Android interview Online Economic encyclopedia [constantly updating...]

【点云系列】Relationship-based Point Cloud Completion
随机推荐
Solution to slow compilation speed of Xcode
Chapter 1 numpy Foundation
Paddleocr image text extraction
Visual Studio 2019安装与使用
Component based learning (3) path and group annotations in arouter
【动态规划】不同路径2
torch_geometric学习一,MessagePassing
PyTorch 18. torch.backends.cudnn
[2021 book recommendation] artistic intelligence for IOT Cookbook
Machine learning II: logistic regression classification based on Iris data set
Face_ Recognition face detection
机器学习笔记 一:学习思路
面试总结之特征工程
【點雲系列】SG-GAN: Adversarial Self-Attention GCN for Point Cloud Topological Parts Generation
Mysql database installation and configuration details
Data class of kotlin journey
Chapter 8 generative deep learning
【3D形状重建系列】Implicit Functions in Feature Space for 3D Shape Reconstruction and Completion
Summary of image classification white box anti attack technology
[2021 book recommendation] red hat rhcsa 8 cert Guide: ex200