PyTorch模型定义

简介: 好久没更新了,2022年也过去快一半了,更文量还是不如前几年。近期会尝试加快更新的进度。本篇文章的更新内容是PyTorch模型的定义。

PyTorch模型定义

1. 前言

好久没更新了,2022年也过去快一半了,更文量还是不如前几年。近期会尝试加快更新的进度。

本篇文章的更新内容是PyTorch模型的定义。

2. PyTorch模型定义的方式

PyTorch-DataWhale.png

2.1. Sequential

Sequential 类可以通过更加简单的方式定义模型。它可以接收一个子模块的有序字典(OrderedDict) 或者一系列子模块作为参数来逐一添加 Module 的实例,⽽模型的前向计算就是将这些实例按添加的顺序逐⼀计算

Sequential定义源码:

torch.nn.modules.containerPyTorch1.11.0documentationclassSequential(Module):
r"""A sequential container.    Modules will be added to it in the order they are passed in the    constructor. Alternatively, an ``OrderedDict`` of modules can be    passed in. The ``forward()`` method of ``Sequential`` accepts any    input and forwards it to the first module it contains. It then    "chains" outputs to inputs sequentially for each subsequent module,    finally returning the output of the last module.    The value a ``Sequential`` provides over manually calling a sequence    of modules is that it allows treating the whole container as a    single module, such that performing a transformation on the    ``Sequential`` applies to each of the modules it stores (which are    each a registered submodule of the ``Sequential``).    What's the difference between a ``Sequential`` and a    :class:`torch.nn.ModuleList`? A ``ModuleList`` is exactly what it    sounds like--a list for storing ``Module`` s! On the other hand,    the layers in a ``Sequential`` are connected in a cascading way.    Example::        # Using Sequential to create a small model. When `model` is run,        # input will first be passed to `Conv2d(1,20,5)`. The output of        # `Conv2d(1,20,5)` will be used as the input to the first        # `ReLU`; the output of the first `ReLU` will become the input        # for `Conv2d(20,64,5)`. Finally, the output of        # `Conv2d(20,64,5)` will be used as input to the second `ReLU`        model = nn.Sequential(                  nn.Conv2d(1,20,5),                  nn.ReLU(),                  nn.Conv2d(20,64,5),                  nn.ReLU()                )        # Using Sequential with OrderedDict. This is functionally the        # same as the above code        model = nn.Sequential(OrderedDict([                  ('conv1', nn.Conv2d(1,20,5)),                  ('relu1', nn.ReLU()),                  ('conv2', nn.Conv2d(20,64,5)),                  ('relu2', nn.ReLU())                ]))    """_modules: Dict[str, Module]  # type: ignore[assignment]@overloaddef__init__(self, *args: Module) ->None:
        ...
@overloaddef__init__(self, arg: 'OrderedDict[str, Module]') ->None:
        ...
def__init__(self, *args):
super(Sequential, self).__init__()
iflen(args) ==1andisinstance(args[0], OrderedDict):
forkey, moduleinargs[0].items():
self.add_module(key, module)
else:
foridx, moduleinenumerate(args):
self.add_module(str(idx), module)

以上是节选的源码。

重点需要看的代码区域是:

def__init__(self, *args):
super(Sequential, self).__init__()
iflen(args) ==1andisinstance(args[0], OrderedDict):
forkey, moduleinargs[0].items():
self.add_module(key, module)
else:
foridx, moduleinenumerate(args):
self.add_module(str(idx), module)


由python基础知识可以知道,*args代表输入的参数可以是列表

所以,这个构造函数中的if len(args) == 1 and isinstance(args[0], OrderedDict):用来判断输入的参数是不是一个列表:

第一个判断条件是args的长度是否为1

第二个判断条件是isinstance(args[0], OrderedDict),判断传入的是不是一个OrderedDict

再次:

如果不是以上的情况,那么传入的就是一些Module,接着继续处理。

使用Sequential来定义模型。只需要将模型的层按序排列起来即可,根据层名的不同,排列的时候有两种方式:

2.1.1 使用OrderedDict

对应源码if len(args) == 1 and isinstance(args[0], OrderedDict):判断语句为真。

importcollectionimporttorch.nnasnnnet2=nn.Sequential(collections.OrderedDict([
          ('fc1', nn.Linear(784, 256)),
          ('relu1', nn.ReLU()),
          ('fc2', nn.Linear(256, 10))
          ]))
print(net2)


使用Sequential定义模型的好处在于简单、易读,同时使用Sequential定义的模型不需要再写forward,因为顺序已经定义好了。但使用Sequential也会使得模型定义丧失灵活性,比如需要在模型中间加入一个外部输入时就不适合用Sequential的方式实现。使用时需根据实际需求加以选择。

2.1.2 直接排列

对应源码if len(args) == 1 and isinstance(args[0], OrderedDict):判断语句为假,进入else语句部分

importtorch.nnasnnnet=nn.Sequential(
nn.Linear(784, 256),
nn.ReLU(),
nn.Linear(256, 10), 
        )
print(net)


2.2. ModuleList

对应模块为nn.ModuleList()

部分源码:

classModuleList(Module):
r"""Holds submodules in a list.    :class:`~torch.nn.ModuleList` can be indexed like a regular Python list, but    modules it contains are properly registered, and will be visible by all    :class:`~torch.nn.Module` methods.    Args:        modules (iterable, optional): an iterable of modules to add    Example::        class MyModule(nn.Module):            def __init__(self):                super(MyModule, self).__init__()                self.linears = nn.ModuleList([nn.Linear(10, 10) for i in range(10)])            def forward(self, x):                # ModuleList can act as an iterable, or be indexed using ints                for i, l in enumerate(self.linears):                    x = self.linears[i // 2](x) + l(x)                return x    """_modules: Dict[str, Module]  # type: ignore[assignment]def__init__(self, modules: Optional[Iterable[Module]] =None) ->None:
super(ModuleList, self).__init__()
ifmodulesisnotNone:
self+=modules


可以看到,ModuleList这个类实际上功能实现的比较简单。

ModuleList 接收一个子模块(或层,需属于nn.Module类)的列表作为输入,然后也可以类似List那样进行appendextend操作。同时,子模块或层的权重也会自动添加到网络中来。

net=nn.ModuleList([nn.Linear(784, 256), nn.ReLU()])
net.append(nn.Linear(256, 10)) # # 类似List的append操作print(net[-1])  # 类似List的索引访问print(net)


nn.ModuleList 并没有定义一个网络,它只是将不同的模块储存在一起。ModuleList中元素的先后顺序并不代表其在网络中的真实位置顺序,需要经过forward函数指定各个层的先后顺序后才算完成了模型的定义。具体实现时用for循环即可完成.

classmodel(nn.Module):
def__init__(self, ...):
super().__init__()
self.modulelist= ...
    ...
defforward(self, x):
forlayerinself.modulelist:
x=layer(x)
returnx

2.3. ModuleDict

对应模块为nn.ModuleDict()

ModuleDictModuleList的作用类似,只是ModuleDict能够更方便地为神经网络的层添加名称。

部分源码:

classModuleDict(Module):
r"""Holds submodules in a dictionary.    :class:`~torch.nn.ModuleDict` can be indexed like a regular Python dictionary,    but modules it contains are properly registered, and will be visible by all    :class:`~torch.nn.Module` methods.    :class:`~torch.nn.ModuleDict` is an **ordered** dictionary that respects    * the order of insertion, and    * in :meth:`~torch.nn.ModuleDict.update`, the order of the merged      ``OrderedDict``, ``dict`` (started from Python 3.6) or another      :class:`~torch.nn.ModuleDict` (the argument to      :meth:`~torch.nn.ModuleDict.update`).    Note that :meth:`~torch.nn.ModuleDict.update` with other unordered mapping    types (e.g., Python's plain ``dict`` before Python version 3.6) does not    preserve the order of the merged mapping.    Args:        modules (iterable, optional): a mapping (dictionary) of (string: module)            or an iterable of key-value pairs of type (string, module)    Example::        class MyModule(nn.Module):            def __init__(self):                super(MyModule, self).__init__()                self.choices = nn.ModuleDict({                        'conv': nn.Conv2d(10, 10, 3),                        'pool': nn.MaxPool2d(3)                })                self.activations = nn.ModuleDict([                        ['lrelu', nn.LeakyReLU()],                        ['prelu', nn.PReLU()]                ])            def forward(self, x, choice, act):                x = self.choices[choice](x)                x = self.activations[act](x)                return x    """_modules: Dict[str, Module]  # type: ignore[assignment]def__init__(self, modules: Optional[Mapping[str, Module]] =None) ->None:
super(ModuleDict, self).__init__()
ifmodulesisnotNone:
self.update(modules)

实例:

net=nn.ModuleDict({
'linear': nn.Linear(784, 256),
'act': nn.ReLU(),
})
net['output'] =nn.Linear(256, 10) # 添加print(net['linear']) # 访问print(net.output)
print(net)

3. 方式的区别

Sequential适用于快速验证结果,因为已经明确了要用哪些层,直接写一下就好了,不需要同时写__init__forward

ModuleListModuleDict在某个完全相同的层需要重复出现多次时,非常方便实现,可以”一行顶多行“;

当我们需要之前层的信息的时候,比如 ResNets 中的残差计算,当前层的结果需要和之前层中的结果进行融合,一般使用 ModuleList/ModuleDict 比较方便。

参考资料

5.1 PyTorch模型定义的方式 — 深入浅出PyTorch (datawhalechina.github.io)

Sequential — PyTorch 1.11.0 documentation

torch.nn.modules.container — PyTorch 1.11.0 documentation

ModuleList — PyTorch 1.11.0 documentation

torch.nn.modules.container — PyTorch 1.11.0 documentation

ModuleDict — PyTorch 1.11.0 documentation

torch.nn.modules.container — PyTorch 1.11.0 documentation


目录
相关文章
|
5月前
|
机器学习/深度学习 存储 PyTorch
Neural ODE原理与PyTorch实现:深度学习模型的自适应深度调节
Neural ODE将神经网络与微分方程结合,用连续思维建模数据演化,突破传统离散层的限制,实现自适应深度与高效连续学习。
402 3
Neural ODE原理与PyTorch实现:深度学习模型的自适应深度调节
|
4月前
|
边缘计算 人工智能 PyTorch
130_知识蒸馏技术:温度参数与损失函数设计 - 教师-学生模型的优化策略与PyTorch实现
随着大型语言模型(LLM)的规模不断增长,部署这些模型面临着巨大的计算和资源挑战。以DeepSeek-R1为例,其671B参数的规模即使经过INT4量化后,仍需要至少6张高端GPU才能运行,这对于大多数中小型企业和研究机构来说成本过高。知识蒸馏作为一种有效的模型压缩技术,通过将大型教师模型的知识迁移到小型学生模型中,在显著降低模型复杂度的同时保留核心性能,成为解决这一问题的关键技术之一。
|
6月前
|
PyTorch 算法框架/工具 异构计算
PyTorch 2.0性能优化实战:4种常见代码错误严重拖慢模型
我们将深入探讨图中断(graph breaks)和多图问题对性能的负面影响,并分析PyTorch模型开发中应当避免的常见错误模式。
392 9
|
8月前
|
机器学习/深度学习 存储 PyTorch
PyTorch + MLFlow 实战:从零构建可追踪的深度学习模型训练系统
本文通过使用 Kaggle 数据集训练情感分析模型的实例,详细演示了如何将 PyTorch 与 MLFlow 进行深度集成,实现完整的实验跟踪、模型记录和结果可复现性管理。文章将系统性地介绍训练代码的核心组件,展示指标和工件的记录方法,并提供 MLFlow UI 的详细界面截图。
359 2
PyTorch + MLFlow 实战:从零构建可追踪的深度学习模型训练系统
|
8月前
|
机器学习/深度学习 PyTorch 算法框架/工具
提升模型泛化能力:PyTorch的L1、L2、ElasticNet正则化技术深度解析与代码实现
本文将深入探讨L1、L2和ElasticNet正则化技术,重点关注其在PyTorch框架中的具体实现。关于这些技术的理论基础,建议读者参考相关理论文献以获得更深入的理解。
257 4
提升模型泛化能力:PyTorch的L1、L2、ElasticNet正则化技术深度解析与代码实现
|
9月前
|
机器学习/深度学习 PyTorch 编译器
深入解析torch.compile:提升PyTorch模型性能、高效解决常见问题
PyTorch 2.0推出的`torch.compile`功能为深度学习模型带来了显著的性能优化能力。本文从实用角度出发,详细介绍了`torch.compile`的核心技巧与应用场景,涵盖模型复杂度评估、可编译组件分析、系统化调试策略及性能优化高级技巧等内容。通过解决图断裂、重编译频繁等问题,并结合分布式训练和NCCL通信优化,开发者可以有效提升日常开发效率与模型性能。文章为PyTorch用户提供了全面的指导,助力充分挖掘`torch.compile`的潜力。
1047 17
|
10月前
|
存储 自然语言处理 PyTorch
从零开始用Pytorch实现LLaMA 4的混合专家(MoE)模型
近期发布的LLaMA 4模型引入混合专家(MoE)架构,以提升效率与性能。尽管社区对其实际表现存在讨论,但MoE作为重要设计范式再次受到关注。本文通过Pytorch从零实现简化版LLaMA 4 MoE模型,涵盖数据准备、分词、模型构建(含词元嵌入、RoPE、RMSNorm、多头注意力及MoE层)到训练与文本生成全流程。关键点包括MoE层实现(路由器、专家与共享专家)、RoPE处理位置信息及RMSNorm归一化。虽规模小于实际LLaMA 4,但清晰展示MoE核心机制:动态路由与稀疏激活专家,在控制计算成本的同时提升性能。完整代码见链接,基于FareedKhan-dev的Github代码修改而成。
454 9
从零开始用Pytorch实现LLaMA 4的混合专家(MoE)模型
|
9月前
|
机器学习/深度学习 搜索推荐 PyTorch
基于昇腾用PyTorch实现CTR模型DIN(Deep interest Netwok)网络
本文详细讲解了如何在昇腾平台上使用PyTorch训练推荐系统中的经典模型DIN(Deep Interest Network)。主要内容包括:DIN网络的创新点与架构剖析、Activation Unit和Attention模块的实现、Amazon-book数据集的介绍与预处理、模型训练过程定义及性能评估。通过实战演示,利用Amazon-book数据集训练DIN模型,最终评估其点击率预测性能。文中还提供了代码示例,帮助读者更好地理解每个步骤的实现细节。

推荐镜像

更多