oneflow.nn.Module

Module class for building neural networks

class oneflow.nn.Module

Base class for all neural network modules.

This class is consistent with PyTorch. The documentation is referenced from: https://pytorch.org/docs/stable/generated/torch.nn.Module.html.

Your models should also subclass this class.

Modules can also contain other Modules, allowing to nest them in a tree structure. You can assign the submodules as regular attributes:

import oneflow.nn as nn
import oneflow.nn.functional as F

class Model(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(1, 20, 5)
        self.conv2 = nn.Conv2d(20, 20, 5)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        return F.relu(self.conv2(x))

Submodules assigned in this way will be registered, and will have their parameters converted too when you call to(), etc.

Note

As per the example above, an __init__() call to the parent class must be made before assignment on the child.

Variables

training (bool) – Boolean represents whether this module is in training or evaluation mode.

add_module(name: str, module: Optional[oneflow.nn.module.Module])None

将子模块添加到当前模块。

可以使用给定的名称作为属性来访问模块。

参数:
  • name (string) - 子模块的名称,可以使用给定的名称作为属性来访问模块。

  • module (Module) - 要添加到模块的子模块。

返回值:

Module: self

apply(fn)

Applies fn recursively to every submodule (as returned by .children()) as well as self. Typical use includes initializing the parameters of a model.

Parameters

fn (Module -> None) – function to be applied to each submodule

Returns

self

Return type

Module

Example:

>>> import oneflow as flow
>>> import oneflow.nn as nn
>>> @flow.no_grad()
... def init_weights(m):
...     print(m)
...     if type(m) == nn.Linear:
...         m.weight.fill_(1.0)
...         print(m.weight)
>>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))
>>> net.apply(init_weights)
Linear(in_features=2, out_features=2, bias=True)
tensor([[1., 1.],
        [1., 1.]], dtype=oneflow.float32, requires_grad=True)
Linear(in_features=2, out_features=2, bias=True)
tensor([[1., 1.],
        [1., 1.]], dtype=oneflow.float32, requires_grad=True)
Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
)
Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
)
buffers(recurse=True)Iterator[Tensor]

Returns an iterator over module buffers.

Parameters

recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.

Yields

oneflow.Tensor – module buffer

Example:

>>> for buf in model.buffers(): 
...     print(type(buf), buf.size()) 
<class 'oneflow.Tensor'> oneflow.Size([10])
children()Iterator[Module]

Returns an iterator over immediate children modules.

Yields

Module – a child module

Example:

>>> import oneflow.nn as nn
>>> l1 = nn.Linear(2, 2)
>>> l2 = nn.Linear(2, 2)
>>> net = nn.Sequential(l1, l2)
>>> for idx, m in enumerate(net.children()):
...     print(idx, '->', m)
0 -> Linear(in_features=2, out_features=2, bias=True)
1 -> Linear(in_features=2, out_features=2, bias=True)
cpu()T

将所有模型参数和缓存移动到 CPU。

Note

此方法会以 in-place 方式修改模块。

cuda(device: Optional[Union[int, oneflow._oneflow_internal.device]] = None)T

将所有模型参数和缓存移动到 GPU。

这也会使关联的参数和缓存成为不同的对象。因此,如果模块运行在 GPU 上且需要被优化,该函数应在构建优化器之前被调用。

Note

此方法会以 in-place 方式修改模块。

参数:
  • device (int, optional) - 如果指定了 device,所有参数将被复制到此

返回值:

Module: self

double()T

将所有浮点参数和缓存转换为 double 数据类型。

Note

此方法会以 in-place 方式修改模块。

返回值:

Module: self

eval()

Sets the module in evaluation mode.

This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g. Dropout, BatchNorm1d, etc.

This is equivalent with self.train(False).

Returns

self

Return type

Module

float()T

将所有浮点参数和缓存转换为 float 数据类型。

Note

此方法会以 in-place 方式修改模块。

返回值:

Module: self

half()

Casts all floating point parameters and buffers to half datatype.

Note

This method modifies the module in-place.

Returns

self

Return type

Module

load_state_dict(state_dict, strict=True)

Copies parameters and buffers from state_dict into this module and its descendants. If strict is True, then the keys of state_dict must exactly match the keys returned by this module’s state_dict() function.

Parameters
  • state_dict (dict) – a dict containing parameters and persistent buffers.

  • strict (bool, optional) – whether to strictly enforce that the keys in state_dict match the keys returned by this module’s state_dict() function. Default: True

Returns

  • missing_keys is a list of str containing the missing keys

  • unexpected_keys is a list of str containing the unexpected keys

Return type

NamedTuple with missing_keys and unexpected_keys fields

Note

If a parameter or buffer is registered as None and its corresponding key exists in state_dict, load_state_dict() will raise a RuntimeError.

modules()Iterator[Module]

Returns an iterator over all modules in the network.

Yields

Module – a module in the network

Note

Duplicate modules are returned only once. In the following example, l will be returned only once.

Example:

>>> import oneflow.nn as nn
>>> l = nn.Linear(2, 2)
>>> net = nn.Sequential(l, l)
>>> for idx, m in enumerate(net.modules()):
...     print(idx, '->', m)
0 -> Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
)
1 -> Linear(in_features=2, out_features=2, bias=True)
named_buffers(prefix='', recurse=True)Iterator[Tuple[str, Tensor]]

Returns an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.

Parameters
  • prefix (str) – prefix to prepend to all buffer names.

  • recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.

Yields

(string, oneflow.Tensor) – Tuple containing the name and buffer

Example:

>>> for name, buf in self.named_buffers(): 
...    if name in ['running_var']: 
...        print(buf.size()) 
named_children()Iterator[Tuple[str, Module]]

Returns an iterator over immediate children modules, yielding both the name of the module as well as the module itself.

Yields

(string, Module) – Tuple containing a name and child module

Example:

>>> for name, module in model.named_children(): 
...     if name in ['conv4', 'conv5']: 
...         print(module) 
named_modules(memo=None, prefix='')

Returns an iterator over all modules in the network, yielding both the name of the module as well as the module itself.

Parameters
  • memo – a memo to store the set of modules already added to the result

  • prefix – a prefix that will be added to the name of the module

Yields

(string, Module) – Tuple of name and module

Note

Duplicate modules are returned only once. In the following example, l will be returned only once.

Example:

>>> import oneflow.nn as nn
>>> l = nn.Linear(2, 2)
>>> net = nn.Sequential(l, l)
>>> for idx, m in enumerate(net.named_modules()):
...     print(idx, '->', m)
0 -> ('', Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
))
1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
named_parameters(prefix='', recurse=True)Iterator[Tuple[str, Tensor]]

Returns an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.

Parameters
  • prefix (str) – prefix to prepend to all parameter names.

  • recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.

Yields

(string, Parameter) – Tuple containing the name and parameter

Example:

>>> for name, param in self.named_parameters(): 
...    if name in ['bias']: 
...        print(param.size()) 
parameters(recurse=True)Iterator[Parameter]

Returns an iterator over module parameters.

This is typically passed to an optimizer.

Parameters

recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.

Yields

Parameter – module parameter

Example:

>>> for param in model.parameters(): 
...     print(type(param), param.size()) 
<class 'oneflow.Tensor'> oneflow.Size([10])
register_buffer(name, tensor, persistent=True)

Adds a buffer to the module.

This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s running_mean is not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by setting persistent to False. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’s state_dict.

Buffers can be accessed as attributes using given names.

Parameters
  • name (string) – name of the buffer. The buffer can be accessed from this module using the given name

  • tensor (Tensor or None) – buffer to be registered. If None, then operations that run on buffers, such as cuda, are ignored. If None, the buffer is not included in the module’s state_dict.

  • persistent (bool) – whether the buffer is part of this module’s state_dict.

Example:

>>> self.register_buffer('running_mean', oneflow.zeros(num_features)) 
register_forward_hook(hook)

Registers a forward hook on the module.

The hook will be called every time after forward() has computed an output. It should have the following signature:

hook(module, input, output) -> None or modified output

The input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to the forward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called after forward() is called.

register_forward_pre_hook(hook)

Registers a forward pre-hook on the module.

The hook will be called every time before forward() is invoked. It should have the following signature:

hook(module, input) -> None or modified input

The input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to the forward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned(unless that value is already a tuple).

register_parameter(name, param)

Adds a parameter to the module.

The parameter can be accessed as an attribute using given name.

Parameters
  • name (string) – name of the parameter. The parameter can be accessed from this module using the given name

  • param (Parameter or None) – parameter to be added to the module. If None, then operations that run on parameters, such as cuda, are ignored. If None, the parameter is not included in the module’s state_dict.

state_dict(destination=None, prefix='', keep_vars=False)Dict[str, Tensor]

Returns a dictionary containing a whole state of the module.

Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to None are not included.

Parameters
  • destination (dict, optional) – Deprecated. This dict is returned with the module state saved in it. It should also have an attribute _metadata: dict to save metadata of the module state. If it’s not provided, an OrderedDict is created and returned. Default: None

  • prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in dict. Default: ''

  • keep_vars (bool, optional) – by default the Tensor s returned in the state dict are detached from autograd. If it’s set to True, detaching is not performed. Default: False

Returns

a dictionary containing a whole state of the module

Return type

dict

Example:

>>> import oneflow.nn as nn
>>> l1 = nn.Linear(2, 2)
>>> l2 = nn.Linear(2, 2)
>>> net = nn.Sequential(l1, l2)
>>> net.state_dict().keys()
odict_keys(['0.weight', '0.bias', '1.weight', '1.bias'])
to(device=None)

Moves the parameters and buffers.

Its signature is similar to oneflow.Tensor.to(). The parameters and buffers will be moved device, if that is given.

See below for examples.

Note

This method modifies the module in-place.

Parameters

device (oneflow.device) – the desired device of the parameters and buffers in this module

Returns

self

Return type

Module

Examples:

>>> import oneflow as flow
>>> import oneflow.nn as nn
>>> linear = nn.Linear(2, 2)
>>> linear.weight.device
device(type='cpu', index=0)
>>> gpu1 = flow.device("cuda:1")
>>> linear.to(gpu1)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight.device
device(type='cuda', index=1)
>>> cpu = flow.device("cpu")
>>> linear.to(cpu)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight.device
device(type='cpu', index=0)
to_consistent(*args, **kwargs)

此接口已停止维护,请使用 oneflow.nn.Module.to_global()

to_global(placement=None, sbp=None)

将所有参数和缓存设置为全局的。

它对此模块中每一个参数和缓存执行相同的 oneflow.Tensor.to_global()

Note

此方法会以 in-place 方式修改模块。

如果该模块的参数和缓存是本地的,则 placement 和 sbp 都是必需的,否则至少需要其中的一个。

参数:
  • placement (flow.placement, optional) - 该模块中参数和缓存的所需位置。默认值为 None

  • sbp (flow.sbp.sbp or tuple of flow.sbp.sbp, optional) - 此模块中参数和缓存的所需 sbp。默认值为 None

示例:

>   import oneflow as flow
>   m = flow.nn.Conv2d(in_channels=3, out_channels=4, kernel_size=3)
>   m.to_global(placement=flow.placement("cpu", ranks=[0]), sbp=[flow.sbp.split(0)])
>   m.weight.is_global
True
>   m.bias.is_global
True
train(mode=True)

Sets the module in training mode.

This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g. Dropout, BatchNorm1d, etc.

Parameters

mode (bool) – whether to set training mode (True) or evaluation mode (False). Default: True.

Returns

self

Return type

Module

zero_grad(set_to_none: bool = False)None

将所有模型参数的梯度设置为零。更多细节请参考 oneflow.optim.Optimizer 中的类似功能。

参数: