MAE 代码实战详解
MAE 代码实战详解
- if__name__=="__main__"
- model.forward
- model.forward.encorder
- model.forward.decorder
- model.forward.loss
- 大小排序索引-有点神奇
- torch.gather
if__name__==“main”
- MAE 模型选择
def mae_vit_base_patch16_dec512d8b(**kwargs):model = MaskedAutoencoderViT(patch_size=16, embed_dim=768, depth=12, num_heads=12,decoder_embed_dim=512, decoder_depth=8, decoder_num_heads=16,mlp_ratio=4, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)return model
- debug 调试
if__name__=="__main__":model = mae_vit_base_patch16_dec512d8b()input = torch.rand(1,3,224,224)output = model(input) # debug
model.forward
def forward(self, imgs, mask_ratio=0.75):latent, mask, ids_restore = self.forward_encoder(imgs, mask_ratio)pred = self.forward_decoder(latent, ids_restore) # [N, L, p*p*3]loss = self.forward_loss(imgs, pred, mask)return loss, pred, mask
model.forward.encorder
latent, mask, ids_restore = self.forward_encoder(imgs, mask_ratio)
x = self.patch_embed(x)
PatchEmbed理解x.shape:
[B,C,H,W]->[B,H*W,C]
PatchEmbed((proj): Conv2d(3, 768, kernel_size=(16, 16), stride=(16, 16))(norm): Identity())
def forward(self, x):B, C, H, W = x.shape_assert(H == self.img_size[0], f"Input image height ({H}) doesn't match model ({self.img_size[0]}).")_assert(W == self.img_size[1], f"Input image width ({W}) doesn't match model ({self.img_size[1]}).")x = self.proj(x)#Conv2d(3, 768, kernel_size=(16, 16), stride=(16, 16))if self.flatten:x = x.flatten(2).transpose(1, 2) # BCHW -> B H*W Cx = self.norm(x)#self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()return x
LayerNorm与BatchNorm区别
pos_embed = get_2d_sincos_pos_embed(self.pos_embed.shape[-1], int(self.patch_embed.num_patches**.5), cls_token=True)
def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False):"""grid_size: int of the grid height and widthreturn:pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)"""grid_h = np.arange(grid_size, dtype=np.float32)grid_w = np.arange(grid_size, dtype=np.float32)grid = np.meshgrid(grid_w, grid_h) # here w goes first #X, Y = np.meshgrid(x, y) 代表的是将x中每一个数据和y中每一个数据组合生成很多点,然后将这些点的x坐标放入到X中,y坐标放入Y中,并且相应位置是对应的 x中的元素先移动,(x1,y1),(x2,y1) ... (x1,y2),(x2,y2)...grid = np.stack(grid, axis=0)grid = grid.reshape([2, 1, grid_size, grid_size])pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)if cls_token:pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0)return pos_embed
np.meshgrid
no.stack 填充
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):assert embed_dim % 2 == 0# use half of dimensions to encode grid_hemb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)return emb
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):"""embed_dim: output dimension for each positionpos: a list of positions to be encoded: size (M,)out: (M, D)"""assert embed_dim % 2 == 0omega = np.arange(embed_dim // 2, dtype=np.float)omega /= embed_dim / 2.omega = 1. / 10000**omega # (D/2,)pos = pos.reshape(-1) # (M,)out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer productemb_sin = np.sin(out) # (M, D/2)emb_cos = np.cos(out) # (M, D/2)emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)return emb
Transformer学习笔记一:Positional Encoding(位置编码)
如何理解和使用NumPy.einsum?
model.forward.decorder
model.forward.loss
大小排序索引-有点神奇
# sort noise for each sampleids_shuffle = torch.argsort(noise, dim=1) # ascend: small is keep, large is remove ’’’只在sequence length 维度进行排序,torch.argsort返回排序后的值所对应原a的下标,即torch.sort()返回的indices’’’ids_restore = torch.argsort(ids_shuffle, dim=1) # 之前从小到大的数的索引
torch.gather
torch.gather(input, dim, index, out=None) → TensorGathers values along an axis specified by dim.For a 3-D tensor the output is specified by:out[i][j][k] = input[index[i][j][k]][j][k] # dim=0out[i][j][k] = input[i][index[i][j][k]][k] # dim=1out[i][j][k] = input[i][j][index[i][j][k]] # dim=2Parameters: input (Tensor) – The source tensordim (int) – The axis along which to indexindex (LongTensor) – The indices of elements to gatherout (Tensor, optional) – Destination tensorExample:>>> t = torch.Tensor([[1,2],[3,4]])>>> torch.gather(t, 1, torch.LongTensor([[0,0],[1,0]]))1 14 3[torch.FloatTensor of size 2x2]
For a 2-D tensor the output is specified by:out[i][j] = input[ index[i][j] ][j] # dim=0out[i][j] = input[i][ index[i][j][k] ][k] # dim=1
Example:
>>> t = torch.Tensor([[1,2],[3,4]])>>> torch.gather(t, 1, torch.LongTensor([[0,0],[1,0]]))1 14 3
output[i][j] = input[i][ index[i][j] ]#行对应
>>> t = torch.Tensor([[1,2],[3,4]])>>> torch.gather(t, 0, torch.LongTensor([[0,0],[1,0]]))1 23 2output[i][j] = input[ index[i][j] ][j]#列对应
参考1
MAE 代码实战详解相关推荐
- 《Java和Android开发实战详解》——2.5节良好的Java程序代码编写风格
本节书摘来自异步社区<Java和Android开发实战详解>一书中的第2章,第2.5节良好的Java程序代码编写风格,作者 陈会安,更多章节内容可以访问云栖社区"异步社区&quo ...
- python 自动化-Python API 自动化实战详解(纯代码)
主要讲如何在公司利用Python 搞API自动化. 1.分层设计思路 dataPool :数据池层,里面有我们需要的各种数据,包括一些公共数据等 config :基础配置 tools : 工具层 co ...
- 《Unity 4 3D开发实战详解》一6.7 物理引擎综合案例
本节书摘来异步社区<Unity 4 3D开发实战详解>一书中的第6章,第6.7节,作者: 吴亚峰 , 杜化美 , 张月霞 , 索依娜 责编: 张涛,更多章节内容可以访问云栖社区" ...
- 《Java和Android开发实战详解》——1.2节Java基础知识
本节书摘来自异步社区<Java和Android开发实战详解>一书中的第1章,第1.2节Java基础知识,作者 陈会安,更多章节内容可以访问云栖社区"异步社区"公众号查看 ...
- 《Java和Android开发实战详解》——2.2节构建Java应用程序
本节书摘来自异步社区<Java和Android开发实战详解>一书中的第2章,第2.2节构建Java应用程序,作者 陈会安,更多章节内容可以访问云栖社区"异步社区"公众号 ...
- Linux shell脚本入门到实战详解(一)
Linux shell脚本入门到实战详解 一.shell 入门简介 1.1 什么是 shell # 为啥介绍shell 上次出了一篇linux 命令详解,得到了很多小伙伴的认可,有部分粉丝私信我,让我 ...
- flex+php ria应用开发实战详解光盘,《Flex+PHPRIA应用开发实战详解-梁文新版》学习日记2...
这本书真是折磨啊,今天看到了XML解析部分,文章在介绍函数及其参数时很是仔细,但是这本没有把源码最终写清楚,总是少一部分,xml和php对大小写不是很敏感,均能读出来,今天也遇到一个乱码问题,希望这方 ...
- flex+php ria应用开发实战详解,《Flex+PHP RIA应用开发实战详解-梁文新版》学习日记2...
这本书真是折磨啊,今天看到了XML解析部分,文章在介绍函数及其参数时很是仔细,但是这本没有把源码最终写清楚,总是少一部分,xml和php对大小写不是很敏感,均能读出来,今天也遇到一个乱码问题,希望这方 ...
- 《Android NFC开发实战详解》——6.4节Android NFC P2P开发进阶
本节书摘来自异步社区<Android NFC开发实战详解>一书中的第6章,第6.4节Android NFC P2P开发进阶,作者 赵波,更多章节内容可以访问云栖社区"异步社区&q ...
- 《数据修复技术与典型实例实战详解》——1.4 分区表的修复
本节书摘来自异步社区<数据修复技术与典型实例实战详解>一书中的第1章,第1.4节,作者:叶润华著,更多章节内容可以访问云栖社区"异步社区"公众号查看 1.4 分区表的修 ...
最新文章
- 百度开发者大会-《用HTML5新特性开发移动App》PPT分享
- Raspberry Pi 4B 开机自动运行Python文件
- htmlparser设置表单属性值
- 全球及中国抗甲状腺药物行业应用现状调研及未来产销需求预测报告2021-2027年
- 恒生电子发布云计算金融应用“超云计划”
- HLS中数据的合并与拆分
- 一次对路边饮用水RFID供应机的跑路玩法
- 1.9 编程基础之二分查找 12 最长平台 python
- Jshop小程序商城,小程序端。后台采用Thinkphp5.1框架开发
- 树莓派之ubuntu安装docker
- 运放的电压比较器电路
- 编程两年后,我的2018总结
- 这不是一篇技术型的文章,而是一篇能让你在IT世界中畅游的方法
- 叶酸修饰的金星形纳米颗粒,Gold star shaped nanoparticles modified with folic acid
- 人应该怎样度过自己的一生
- 【愚公系列】2022年12月 使用win11系统自带SSH,远程控制VMware中Liunx虚拟机系统
- 批量将 PDF 转为 ePub 格式文档
- nvaicat 下载加破解教程
- oracle中索引的使用
- HDCTF-2nd复盘
热门文章
- 索引的作用?和它的优点缺点是什么?
- java duplicate key_Stream 操作 Duplicate key问题
- 外国内乱时,撤侨不一定是最佳策略
- electron tray click right click
- 先森请自重,小女子只卖身不卖艺
- win10电脑显示未连接网络连接到服务器,win10系统未识别网络无法连接到internet的解决方法...
- 一个程序员失败的爱情
- mysql数据库修改初始密码
- linux认证ppt的图片,linux用户、组和身份认证-课件(PPT-精).ppt
- 中南大学保研去华科计算机,巨无霸学校保研清北比率,武大山大中大华科川大吉大大工中南。...