当前位置:网站首页>Some thoughts on super in pytorch, combined with code
Some thoughts on super in pytorch, combined with code
2022-04-23 20:47:00 【NuerNuer】
class ResidualAdd(nn.Module):
def __init__(self, fn):
super().__init__()#inherit fa class's init method
self.fn = fn
def forward(self, x, **kwargs):
res = x
x = self.fn(x, **kwargs)
x += res
return x
# This class must define member functions , Otherwise, in the TransformerEncoderBlock Calling the forward Method will report an error .
class FeedForwardBlock(nn.Sequential):
def __init__(self, emb_size: int, expansion: int = 4, drop_p: float = 0.):
super().__init__(
nn.Linear(emb_size, expansion * emb_size),
nn.GELU(),
nn.Dropout(drop_p),
nn.Linear(expansion * emb_size, emb_size),
)
# here FeedForwardBlock The parent of a class is nn.Sequential, And through super().__init__() Displays the initial class that called the parent class
# The initial method , Therefore, it inherits the attributes and methods of classification , So when you use it , Even if FeedForwardBlock The definition method function is not displayed
# Count , You can also call the... Of the parent class forward Method .
class TransformerEncoderBlock(nn.Sequential):
def __init__(self,
emb_size: int = 768,
drop_p: float = 0.,
forward_expansion: int = 4,
forward_drop_p: float = 0.,
** kwargs):
super().__init__(
ResidualAdd(nn.Sequential(
nn.LayerNorm(emb_size),
MultiHeadAttention(emb_size, **kwargs),
nn.Dropout(drop_p)
)),
ResidualAdd(nn.Sequential(
nn.LayerNorm(emb_size),
FeedForwardBlock(emb_size, expansion=forward_expansion, drop_p=forward_drop_p),
nn.Dropout(drop_p)
)
))
# It's a little complicated here , Mainly ResidualAdd Inside nn.Sequential It's confusing , there nn.Sequential And
#TransformerEncorderBlock The parent class of doesn't have much relevance meaning , When used here , Initialize one first ResidualAdd object ,
# then , Because here TransformerEncorderBlock It still shows that the initialization method of the parent class is called , therefore , Inherits the properties of the parent class
# And methods , When in use, it will call nn.Squential Inside forward Method .
class Sequential(Module):
def __init__(self, *args: Any):
super(Sequential, self).__init__()
if len(args) == 1 and isinstance(args[0], OrderedDict):
for key, module in args[0].items():
self.add_module(key, module)
else:
for idx, module in enumerate(args):
self.add_module(str(idx), module)
def forward(self, input):
for module in self:
input = module(input)
return input
# About parent classes nn.Sequential The main part of the code , We can see that , Its initialization parameters are instantiated objects , So every instantiated object
# All classes must have forward function , Otherwise, in the input = module(input) It's a mistake , That's why ResidualAdd have to
# Must have forward Why
Reference resources :https://blog.csdn.net/ZEdwin/article/details/117296675
Give Way python Class is called directly _csldh The blog of -CSDN Blog _python Call the class directly
https://blog.csdn.net/a__int__/article/details/104600972
版权声明
本文为[NuerNuer]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210545522862.html
边栏推荐
- Install MySQL 5.0 under Linux 64bit 6 - the root password cannot be modified
- Leetcode 709, convert to lowercase
- Syntaxerror: unexpected token r in JSON at position 0
- On the three paradigms of database design
- Case of the third day of go language development fresh every day project - news release system II
- Prim、Kruskal
- 常用60类图表使用场景、制作工具推荐
- Sequential state
- Some grounded words
- 3-5通过XSS获取cookie以及XSS后台管理系统的使用
猜你喜欢
100天拿下11K,转岗测试的超全学习指南
On IRP from the perspective of source code
On the three paradigms of database design
Leetcode 542, 01 matrix
Prim、Kruskal
Express③(使用Express编写接口、跨域有关问题)
Minecraft 1.12.2模组开发(四十三) 自定义盾牌(Shield)
go interface
"Meta function" of tidb 6.0: what is placement rules in SQL?
Recommended usage scenarios and production tools for common 60 types of charts
随机推荐
An error occurs when the addressable assets system project is packaged. Runtimedata is null
SQL: query duplicate data and delete duplicate data
Leetcode 1346. Check whether integers and their multiples exist
Addition, deletion, modification and query of MySQL advanced table
Graph traversal - BFS, DFS
LeetCode 1351、统计有序矩阵中的负数
Bash script learning -- for loop traversal
Install MySQL 5.0 under Linux 64bit 6 - the root password cannot be modified
Pikachuxss how to get cookie shooting range, always fail to return to the home page
UKFslam
What about laptop Caton? Teach you to reinstall the system with one click to "revive" the computer
Prim、Kruskal
Parsing methods of JSON data in C - jar and jobobject: error reading jar from jsonreader Current JsonReader item
PHP的Laravel与Composer部署项目时常见问题
Selenium 显示等待WebDriverWait
Gsi-ecm digital platform for engineering construction management
Leetcode 74. Search two-dimensional matrix
Unity Odin ProgressBar add value column
How to configure SSH public key in code cloud
Go zero framework database avoidance Guide