oneflow.nn

Operators for neural networks

Copyright 2020 The OneFlow Authors. All rights reserved.

Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

class oneflow.nn.AdaptiveAvgPool1d(output_size)

在由多个平面组成的输入信号 input 上应用 1D 自适应平均池化。

对于任何大小的输入,输出大小都是 H。

输出的数量等于输入平面的数量。

参数:
  • output_size - 目标输出大小 H(单个整数)

示例:

>>> import oneflow as flow
>>> import oneflow.nn as nn

>>> m = nn.AdaptiveAvgPool1d(5)
>>> input = flow.randn(1, 64, 8)
>>> output = m(input)
>>> output.size()
oneflow.Size([1, 64, 5])
class oneflow.nn.AdaptiveAvgPool2d(output_size)

在由多个平面组成的的信号 input 上应用 2D 自适应平均池化。

对于任何大小的输入,输出大小都是 H x W 。

输出的数量等于输入平面的数量。

参数:
  • output_size - 目标输出大小(单个整数 H 或包含两个整数的元组 (H, W) )。 H 和 W 可以是 int 也可以是 None ,如果为 None 则大小将和输入大小一致。

示例:

>>> import oneflow as flow
>>> import oneflow.nn as nn

>>> m = nn.AdaptiveAvgPool2d((5,7))
>>> input = flow.randn(1, 64, 8, 9)
>>> output = m(input)
>>> output.size()
oneflow.Size([1, 64, 5, 7])

>>> m = nn.AdaptiveAvgPool2d(7)
>>> input = flow.randn(1, 64, 10, 9)
>>> output = m(input)
>>> output.size()
oneflow.Size([1, 64, 7, 7])

>>> m = nn.AdaptiveAvgPool2d((None, 7))
>>> input = flow.randn(1, 64, 10, 9)
>>> output = m(input)
>>> output.size()
oneflow.Size([1, 64, 10, 7])
class oneflow.nn.AdaptiveAvgPool3d(output_size)

在由多个平面组成的信号 input 上应用 3D 自适应平均池化。

对于任何大小的输入,输出大小都是 D x H x W 。

输出的数量等于输入平面的数量。

参数:
  • output_size - 目标输出大小(单个整数 D 则为 D x D x D 或包含三个整数的元组 (D, H, W) )。 H 、 W 和 D 可以是 int 也可以是 None ,如果为 None 则大小将和输入大小一致。

示例:

>>> import oneflow as flow
>>> import oneflow.nn as nn

>>> m = nn.AdaptiveAvgPool3d((5,7,9))
>>> input = flow.randn(1, 64, 8, 9, 10)
>>> output = m(input)
>>> output.size()
oneflow.Size([1, 64, 5, 7, 9])

>>> m = nn.AdaptiveAvgPool3d(7)
>>> input = flow.randn(1, 64, 10, 9, 8)
>>> output = m(input)
>>> output.size()
oneflow.Size([1, 64, 7, 7, 7])

>>> m = nn.AdaptiveAvgPool3d((7, None, None))
>>> input = flow.randn(1, 64, 10, 9, 8)
>>> output = m(input)
>>> output.size()
oneflow.Size([1, 64, 7, 9, 8])
class oneflow.nn.AvgPool1d(kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True)

在由多个平面组成的信号 input 上执行 1D 平均池化。 在最简单的情况下,输出值是输入大小为 \((N, C, H, W)\) 的层。 输出 \((N, C, H_{out}, W_{out})\)kernel_size\(k\) 可以被精确地描述为:

\[out(N_i, C_j, l) = \frac{1}{k} \sum_{m=0}^{k-1} input(N_i, C_j, stride[0] \times h + m, stride*l + m)\]

如果 padding 非零,则输入在两侧隐式填充 0 以填充点数。

参数 kernel_sizestridepadding 可以为 int 或者单元素元组。

Note

ceil_mode 为 True 时,如果滑动窗口在 left padding 或输入内开始,则允许滑动窗口出界。忽略在右侧填充区域开始的滑动窗口。

参数:
  • kernel_size (Union[int, Tuple[int, int]]): 窗口的大小

  • strides (Union[int, Tuple[int, int]], 可选): 窗口的 stride 。默认值为 None

  • padding (Union[int, Tuple[int, int]]): 如果非 0 ,在两侧添加隐式填充 0 。默认为 0

  • ceil_mode (bool): 如果为 True ,将使用 ceil 而不是 floor 来计算输出形状。默认为 False

  • count_include_pad (bool): 如果为 True ,将在平均计算中填充 0 ,默认为 True

示例:

import oneflow as flow

m = flow.nn.AvgPool1d(kernel_size=3, padding=1, stride=1)
x = flow.randn(1, 4, 4)
y = m(x)
y.shape
oneflow.Size([1, 4, 4])
class oneflow.nn.AvgPool2d(kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True, divisor_override=0)

在由多个平面组成的信号 input 上执行 2D 平均池化。

在最简单的情况下,输出值是输入大小为 \((N, C, H, W)\) 的层。

输出 \((N, C, H_{out}, W_{out})\)kernel_size\((kH, kW)\) 可以被精确地描述为:

\[out(N_i, C_j, h, w) = \frac{1}{kH * kW} \sum_{m=0}^{kH-1} \sum_{n=0}^{kW-1} input(N_i, C_j, stride[0] \times h + m, stride[1] \times w + n)\]
参数:
  • kernel_size (Union[int, Tuple[int, int]]): 整数或长度为 1 或 2 的整数列表。输入张量的每个维度的窗口大小

  • strides (Union[int, Tuple[int, int]]): 整数或长度为 1 或 2 的整数列表。输入张量的每个维度的滑动窗口的 stride 。默认为 None

  • padding (Tuple[int, int]): 整数或长度为 1 或 2 的整数列表。在两侧添加隐式填充 0 。默认为 0

  • ceil_mode (bool, default to False): 如果为 True 。将使用 ceil 而不是 floor 来计算输出形状。默认为 False

示例:

import oneflow as flow

m = flow.nn.AvgPool2d(kernel_size=3, padding=1, stride=1)
x = flow.randn(1, 4, 4, 4)
y = m(x)
y.shape
oneflow.Size([1, 4, 4, 4])
class oneflow.nn.AvgPool3d(kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True, divisor_override=0)

在由多个平面组成的信号 input 上执行 3D 平均池化。在最简单的情况下,输出值是输入大小为 \((N, C, D, H, W)\) 的层。

输出 \((N, C, D_{out}, H_{out}, W_{out})\)kernel_size\((kD, kH, kW)\) 可以被精确地描述为:

\[out(N_i, C_j, d, h, w) = \frac{1}{kD * kH * kW } \sum_{k=0}^{kD-1} \sum_{m=0}^{kH-1} \sum_{n=0}^{kW-1} input(N_i, C_j, stride[0] \times d + k, stride[1] \times h + m, stride[2] \times w + n)\]

如果 padding 非零,则输入在三侧隐式填充 0 以填充点数。

Note

ceil_mode 为 True 时,如果滑动窗口在 left padding 或输入内开始,则允许滑动窗口出界。忽略在右侧填充区域开始的滑动窗口。

参数:
  • kernel_size (Union[int, Tuple[int, int, int]]): 窗口的大小

  • strides (Union[int, Tuple[int, int, int]], 可选): 窗口的 stride 。默认值为 None

  • padding (Union[int, Tuple[int, int, int]]): 如果非 0 ,在三侧添加隐式填充 0 。默认为 0

  • ceil_mode (bool): 如果为 True ,将使用 ceil 而不是 floor 来计算输出形状。默认为 False

  • count_include_pad (bool): 如果为 True ,将在平均计算中填充 0 ,默认为 True

  • divisor_override (int): 如果设定了 attr:divisor_override ,它将用作除数,否则 attr:kernel_size 将作为除数。默认为 0

形状:
  • Input: \((N, C, D_{in}, H_{in}, W_{in})\)

  • Output: \((N, C, D_{out}, H_{out}, W_{out})\)

    \[D_{out} = \left\lfloor\frac{D_{in} + 2 \times \text{padding}[0] - \text{kernel_size}[0]}{\text{stride}[0]} + 1\right\rfloor\]
    \[H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{padding}[1] - \text{kernel_size}[1]}{\text{stride}[1]} + 1\right\rfloor\]
    \[W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{padding}[2] - \text{kernel_size}[2]}{\text{stride}[2]} + 1\right\rfloor\]

示例:

import oneflow as flow

m = flow.nn.AvgPool3d(kernel_size=(2,2,2),padding=(0,0,0),stride=(1,1,1))
x = flow.randn(9, 7, 11, 32, 20)
y = m(x)
y.shape
oneflow.Size([9, 7, 10, 31, 19])
class oneflow.nn.BCELoss(weight=None, reduction='mean')Tensor

计算二值交叉熵损失 (binary cross-entropy loss)。

公式为:

如果 reduction = “none” :

\[out = -(Target_i*log(Input_i) + (1-Target_i)*log(1-Input_i))\]

如果 reduction = “mean”:

\[out = -\frac{1}{n}\sum_{i=1}^n(Target_i*log(Input_i) + (1-Target_i)*log(1-Input_i))\]

如果 reduction = “sum”:

\[out = -\sum_{i=1}^n(Target_i*log(Input_i) + (1-Target_i)*log(1-Input_i))\]
参数:
  • weight (oneflow.Tensor, 可选的): 手动重新调整损失的权重。默认为 None ,对应的权重值为 1

  • reduction (str, 可选的): 规约的方式,可以是 “none” 、 “mean” 、 “sum” 中的一种。默认为 “mean”

Attention

输入值必须在区间 (0, 1) 内。否则此损失函数可能返回 nan 值。

返回类型:

oneflow.tensor

示例:

>>> import oneflow as flow
>>> input = flow.tensor([[1.2, 0.2, -0.3], [0.7, 0.6, -2]], dtype=flow.float32)
>>> target = flow.tensor([[0, 1, 0], [1, 0, 1]], dtype=flow.float32)
>>> weight = flow.tensor([[2, 2, 2], [2, 2, 2]], dtype=flow.float32)
>>> activation = flow.nn.Sigmoid()
>>> sigmoid_input = activation(input)
>>> m = flow.nn.BCELoss(weight, reduction="none")
>>> out = m(sigmoid_input, target)
>>> out
tensor([[2.9266, 1.1963, 1.1087],
        [0.8064, 2.0750, 4.2539]], dtype=oneflow.float32)
>>> m_sum = flow.nn.BCELoss(weight, reduction="sum")
>>> out = m_sum(sigmoid_input, target)
>>> out
tensor(12.3668, dtype=oneflow.float32)
>>> m_mean = flow.nn.BCELoss(weight, reduction="mean")
>>> out = m_mean(sigmoid_input, target)
>>> out
tensor(2.0611, dtype=oneflow.float32)
>>> m_none = flow.nn.BCELoss()
>>> out = m_none(sigmoid_input, target)
>>> out
tensor(1.0306, dtype=oneflow.float32)
class oneflow.nn.BCEWithLogitsLoss(weight=None, reduction='mean', pos_weight=None)Tensor

此运算将 SigmoidBCELoss 组合在一起。为了数据的稳定性,我们用了一些数学技巧,而不是将 Sigmoid 作用于 BCELoss 层。

公式为:

如果 reduction = "none":

\[out = -weight*[Pos\_weight*y*log\sigma({x}) + (1-y)*log(1-\sigma(x))]\]

如果 reduction = "mean":

\[out = -\frac{weight}{n}\sum_{i=1}^n[Pos\_weight*y*log\sigma({x}) + (1-y)*log(1-\sigma(x))]\]

如果 reduction = "sum":

\[out = -weight*\sum_{i=1}^n[Pos\_weight*y*log\sigma({x}) + (1-y)*log(1-\sigma(x))]\]
参数:
  • weight (Tensor, 可选的): 手动重新调整损失的权重。默认为 None

  • reduction (str, 可选的): 规约的方式,可以是 "none""mean""sum" 中的一种。默认为 “mean” 。如果为 'none' 则不进行规约。如果为 'mean' ,输出的值的和除以元素数。如果为 'sum' ,输出将被求和。默认为 "mean"

  • pos_weight (Tensor, 可选的): 手动重新调整正例的权重。

形状:
  • Input : \((N,*)\) 其中 * 的意思是,可以增加任意维度

  • Target : \((N,*)\) 与输入形状一样

  • Output : 标量。如果 reduction"none" ,则 \((N,*)\) 和输入形状一样

示例:

>>> import oneflow as flow

>>> input = flow.tensor([[1.2, 0.2, -0.3], [0.7, 0.6, -2], [0.7, 0.6, -2]], dtype=flow.float32)
>>> target = flow.tensor([[0, 1, 0], [1, 0, 1], [1, 0, 1]], dtype=flow.float32)
>>> weight = flow.tensor([[2, 2, 2], [2, 2, 2], [2, 2, 2]], dtype=flow.float32)
>>> pos_weight = flow.tensor([1.2, 1.3, 1.4], dtype=flow.float32)

>>> m = flow.nn.BCEWithLogitsLoss(weight=weight, pos_weight=pos_weight, reduction="none")
>>> out = m(input, target)
>>> out
tensor([[2.9266, 1.5552, 1.1087],
        [0.9676, 2.0750, 5.9554],
        [0.9676, 2.0750, 5.9554]], dtype=oneflow.float32)

>>> m = flow.nn.BCEWithLogitsLoss(weight=weight, pos_weight=pos_weight, reduction="mean")
>>> out = m(input, target)
>>> out
tensor(2.6207, dtype=oneflow.float32)

>>> m = flow.nn.BCEWithLogitsLoss(weight=weight, pos_weight=pos_weight, reduction="sum")
>>> out = m(input, target)
>>> out
tensor(23.5865, dtype=oneflow.float32)
class oneflow.nn.BatchNorm1d(num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)

在 2D 或 3D 输入(具有可选附加通道维度的小批量 1D 输入)上应用批归一化 (Batch Normalization) 。行为与论文 Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift 一致。

\[y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta\]

按小批量逐维度求平均值和标准差, \(\gamma\)\(\beta\) 是大小为 C 的可学习参数向量( C 是输入的大小)。 默认情况下,\(\gamma\) 的元素均为 1 而 \(\beta\) 的元素均为 0 。标准差的计算等价于 torch.var(input, unbiased=False)

此外,默认情况下,在训练期间,该层不断估计计算的均值和方差,然后评估时将其归一化。运行估计默认 momentum 为 0.1 。

如果 track_running_stats 被设置为 False ,则该层不会继续进行估计,并且在评估时也使用批处理统计信息。

Note

momentum 参数不同于优化器 (optimizer) 类中使用的参数或传统的动量概念。数学上,这里的更新规则是: \(\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momentum} \times x_t\) ,其中 \(\hat{x}\) 是估计的统计量, \(x_t\) 是新的观察值。

因为批归一化 (Batch Normalization) 是在 C 维度上完成的,计算 (N, L) 切片的统计数据,所以常称其为 Temporal Batch Normalization 。

参数:
  • num_features - \(C\) 来自于大小为 \((N, C, L)\) 的预期输入或 \(L\) 来自大小为 \((N, L)\) 的输入

  • eps - 为数值稳定性而为分母加的值。默认为:1e-5

  • momentum - 用于 running_meanrunning_var 计算的值。设定为 None 则计算移动平均 (Moving average) ,默认:0.1

  • affine - 如果为 True ,该模块具有可学习的仿射参数。默认为 True

  • track_running_stats - 当设置为 True 时,该模块跟踪运行均值和方差,当设置为 False 时,此模块不会跟踪此类统计信息,并将统计缓冲区 running_meanrunning_var 初始化为 None 。当这些缓冲区为“无”时,此模块在训练和评估模式中始终使用批处理统计信息。默认值: True

形状:
  • Input : \((N, C)\)\((N, C, L)\)

  • Output : \((N, C)\)\((N, C, L)\) (与输入形状相同)

示例:

>>> import oneflow as flow

>>> x = flow.randn(20, 100)
>>> m = flow.nn.BatchNorm1d(100)
>>> y = m(x)
class oneflow.nn.BatchNorm2d(num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)

在 4D 输入(具有可选附加通道维度的小批量 2D 输入)上应用批归一化 (Batch Normalization) 。行为与论文 Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift 一致。

\[y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta\]

按小批量逐维度求平均值和标准差, \(\gamma\)\(\beta\) 是大小为 C 的可学习参数向量( C 是输入的大小)。 默认情况下,\(\gamma\) 的元素均为 1 而 \(\beta\) 的元素均为 0 。标准差的计算等价于 torch.var(input, unbiased=False)

此外,默认情况下,在训练期间,该层不断估计计算的均值和方差,然后评估时将其归一化。运行估计默认 momentum 为 0.1 。

如果 track_running_stats 被设置为 False ,则该层不会继续进行估计,并且在评估时也使用批处理统计信息。

Note

momentum 参数不同于优化器 (optimizer) 类中使用的参数或传统的动量概念。数学上,这里的更新规则是: \(\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momentum} \times x_t\) ,其中 \(\hat{x}\) 是估计的统计量, \(x_t\) 是新的观察值。

因为批归一化 (Batch Normalization) 是在 C 维度上完成的,计算 (N, H, W) 切片的统计数据,所以常称其为 Spatial Batch Normalization 。

参数:
  • num_features - \(C\) 来自于大小为 \((N, C, H, W)\) 的预期输入

  • eps - 为数值稳定性而为分母加的值。默认为:1e-5

  • momentum - 用于 running_meanrunning_var 计算的值。设定为 None 则计算移动平均 (Moving average) ,默认:0.1

  • affine - 如果为 True ,该模块具有可学习的仿射参数。默认为 True

  • track_running_stats - 当设置为 True 时,该模块跟踪运行均值和方差,当设置为 False 时,此模块不会跟踪此类统计信息,并将统计缓冲区 running_meanrunning_var 初始化为 None 。当这些缓冲区为“无”时,此模块在训练和评估模式中始终使用批处理统计信息。默认值: True

形状:
  • Input : \((N, C, H, W)\)

  • Output : \((N, C, H, W)\) (与输入形状相同)

示例:

>>> import oneflow as flow

>>> x = flow.randn(4, 2, 8, 3)
>>> m = flow.nn.BatchNorm2d(num_features=2, eps=1e-5, momentum=0.1)
>>> y = m(x)
class oneflow.nn.BatchNorm3d(num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)

在 5D 输入(具有可选附加通道维度的小批量 3D 输入)上应用批归一化 (Batch Normalization) 。行为与论文 Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift 一致。

\[y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta\]

按小批量逐维度求平均值和标准差, \(\gamma\)\(\beta\) 是大小为 C 的可学习参数向量( C 是输入的大小)。 默认情况下,\(\gamma\) 的元素均为 1 而 \(\beta\) 的元素均为 0 。标准差的计算等价于 torch.var(input, unbiased=False)

此外,默认情况下,在训练期间,该层不断估计计算的均值和方差,然后评估时将其归一化。运行估计默认 momentum 为 0.1 。

如果 track_running_stats 被设置为 False ,则该层不会继续进行估计,并且在评估时也使用批处理统计信息。

Note

momentum 参数不同于优化器 (optimizer) 类中使用的参数或传统的动量概念。数学上,这里的更新规则是: \(\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momentum} \times x_t\) ,其中 \(\hat{x}\) 是估计的统计量, \(x_t\) 是新的观察值。

因为批归一化 (Batch Normalization) 是在 C 维度上完成的,计算 (N, H, W) 切片的统计数据,所以常称其为 Spatial Batch Normalization 。

参数:
  • num_features - \(C\) 来自于大小为 \((N, C, D, H, W)\) 的预期输入

  • eps - 为数值稳定性而为分母加的值。默认为:1e-5

  • momentum - 用于 running_meanrunning_var 计算的值。设定为 None 则计算移动平均 (Moving average) ,默认:0.1

  • affine - 如果为 True ,该模块具有可学习的仿射参数。默认为 True

  • track_running_stats - 当设置为 True 时,该模块跟踪运行均值和方差,当设置为 False 时,此模块不会跟踪此类统计信息,并将统计缓冲区 running_meanrunning_var 初始化为 None 。当这些缓冲区为“无”时,此模块在训练和评估模式中始终使用批处理统计信息。默认值: True

形状:
  • Input : \((N, C, D, H, W)\)

  • Output : \((N, C, D, H, W)\) (与输入形状相同)

示例:

>>> import oneflow as flow

>>> x = flow.randn(3, 2, 5, 8, 4)
>>> m = flow.nn.BatchNorm3d(num_features=2, eps=1e-5, momentum=0.1)
>>> y = m(x)
>>> y.size()
oneflow.Size([3, 2, 5, 8, 4])
class oneflow.nn.CELU(alpha=1.0, inplace=False)

应用逐元素方程:

\[\begin{split}\text{CELU}(x, \alpha) = \begin{cases} x & \text{ if } x \ge 0 \\ \alpha*(exp(\frac{x}{\alpha})-1) & \text{ otherwise } \\ \end{cases}\end{split}\]
参数:
  • alpha (float): CELU 公式中的 \(\alpha\) 。默认值:1.0

  • inplace (bool): 是否执行 place 操作。默认: False

形状:
  • Input : \((N,*)\) 其中 * 的意思是,可以增加任意维度

  • Output : \((N, *)\), 与输入相同

示例:

>>> import oneflow as flow

>>> input = flow.tensor([-0.5, 0, 0.5], dtype=flow.float32)
>>> celu = flow.nn.CELU(alpha=0.5)

>>> out = celu(input)
>>> out
tensor([-0.3161,  0.0000,  0.5000], dtype=oneflow.float32)
class oneflow.nn.COCOReader(annotation_file: str, image_dir: str, batch_size: int, shuffle: bool = True, random_seed: Optional[int] = None, group_by_aspect_ratio: bool = True, remove_images_without_annotations: bool = True, stride_partition: bool = True, device: Optional[Union[oneflow._oneflow_internal.device, str]] = None, placement: Optional[oneflow._oneflow_internal.placement] = None, sbp: Optional[Union[oneflow._oneflow_internal.sbp.sbp, List[oneflow._oneflow_internal.sbp.sbp]]] = None)
class oneflow.nn.CTCLoss(blank=0, reduction='mean', zero_infinity=False)

计算 CTC(Connectionist Temporal Classification) 损失。

此接口与 PyTorch 一致,文档参考自: https://pytorch.org/docs/stable/generated/torch.nn.CTCLoss.html#torch.nn.CTCLoss

计算连续且未分段的时间序列和 target 序列之间的损失。CTCLoss 对 inputtarget 可能对齐的概率求和,产生一个相对于每个 input 节点可微的损失值。 假定 inputtarget 的对齐为“多对一”,这限制了 target 序列的长度,即 target \(\leq\) input

参数:
  • blank (int, 可选的) - 空白标签。默认值为 \(0\)

  • reduction (string, 可选的) - 指定应用于输出的 reduction:'none' | 'mean' | 'sum'. 'none' :不进行 reduction;'mean' :输出损失将除以目标长度,然后取该批次的平均值。默认值为: 'mean'

  • zero_infinity (bool, 可选的) - 是否将无限损失和相关梯度归零。默认值为:False。无限损失主要发生在 inputs 太短而无法与 target 对齐时。

形状:
  • Log_probs : 形状为 \((T, N, C)\) 的张量且 \(T = \text{input length}\)\(N = \text{batch size}\)\(C = \text{number of classes (including blank)}\)

  • Targets : 形状为 \((N, S)\)\((\operatorname{sum}(\text{target_lengths}))\) 的张量,其中 \(N = \text{batch size}\)\(S = \text{max target length, if shape is } (N, S)\)。 它代表 target 序列。 target 序列中的每个元素都是一个 class 索引。并且 target 索引不能为空(默认值为 0)。在 \((N, S)\) 形式中,target 被填充到最长序列的长度并堆叠。 在 \((\operatorname{sum}(\text{target_lengths}))\) 形式中,我们假定目标在 1 维内未填充和连接。

  • Input_lengths : 大小为 \((N)\) 的元组或张量,其中 \(N = \text{batch size}\)。它表示 inputs 的长度(每个都必须 \(\leq T\))。假定序列被填充为相等长度,为每个序列指定长度以实现掩码。

  • Target_lengths : 大小为 \((N)\) 的元组或张量,其中 \(N = \text{batch size}\)。它代表 target 的长度。若假定序列被填充为相等长度,为每个序列指定长度以实现掩码。若 target 形状是 \((N,S)\), 则 target_lengths 是每个目标序列的有效停止索引 \(s_n\) ,这样每个目标序列都满足 target_n = targets[n,0:s_n] ,长度都必须 \(\leq S\)。 若目标是作为单个目标的串联的 1d 张量给出的,则 target_lengths 必须加起来为张量的总长度。

参考文献:

A. Graves et al.: Connectionist Temporal Classification: Labelling Unsegmented Sequence Data with Recurrent Neural Networks: https://www.cs.toronto.edu/~graves/icml_2006.pdf

示例:

>>> import oneflow as flow

>>> log_probs = flow.tensor(
...    [
...        [[-1.1031, -0.7998, -1.5200], [-0.9808, -1.1363, -1.1908]],
...        [[-1.2258, -1.0665, -1.0153], [-1.1135, -1.2331, -0.9671]],
...        [[-1.3348, -0.6611, -1.5118], [-0.9823, -1.2355, -1.0941]],
...        [[-1.3850, -1.3273, -0.7247], [-0.8235, -1.4783, -1.0994]],
...        [[-0.9049, -0.8867, -1.6962], [-1.4938, -1.3630, -0.6547]],
...    ], dtype=flow.float32)
>>> targets = flow.tensor([[1, 2, 2], [1, 2, 2]], dtype=flow.int32)
>>> input_lengths = flow.tensor([5, 5], dtype=flow.int32)
>>> target_lengths = flow.tensor([3, 3], dtype=flow.int32)
>>> loss_mean = flow.nn.CTCLoss()
>>> out = loss_mean(log_probs, targets, input_lengths, target_lengths)
>>> out
tensor(1.1376, dtype=oneflow.float32)
>>> loss_sum = flow.nn.CTCLoss(blank=0, reduction="sum")
>>> out = loss_sum(log_probs, targets, input_lengths, target_lengths)
>>> out
tensor(6.8257, dtype=oneflow.float32)
class oneflow.nn.CoinFlip(batch_size: int = 1, random_seed: Optional[int] = None, probability: float = 0.5, device: Optional[Union[oneflow._oneflow_internal.device, str]] = None, placement: Optional[oneflow._oneflow_internal.placement] = None, sbp: Optional[Union[oneflow._oneflow_internal.sbp.sbp, List[oneflow._oneflow_internal.sbp.sbp]]] = None)
class oneflow.nn.CombinedMarginLoss(m1=1.0, m2=0.0, m3=0.0)

以下操作在 InsightFace 中实现了 margin_softmaxhttps://github.com/deepinsight/insightface/blob/master/recognition/arcface_mxnet/train.py InsightFace 中 margin_softmax 的实现是由多个算子组成的。 我们将它们组合在一起以加快速度。

参数:
  • input (oneflow.Tensor) - 输入张量。

  • label (oneflow.Tensor) - 数据类型为整数的标签。

  • m1 (float) - 损失参数 m1。

  • m2 (float) - 损失参数 m2。

  • m3 (float) - 损失参数 m3。

返回类型:

oneflow.tensor

示例:

>>> import oneflow as flow

>>> x = flow.tensor([[-0.7027179, 0.0230609], [-0.02721931, -0.16056311], [-0.4565852, -0.64471215]], dtype=flow.float32)
>>> label = flow.tensor([0, 1, 1], dtype=flow.int32)
>>> loss_func = flow.nn.CombinedMarginLoss(0.3, 0.5, 0.4)
>>> out = loss_func(x, label)
>>> out
tensor([[-0.0423,  0.0231],
        [-0.0272,  0.1237],
        [-0.4566, -0.0204]], dtype=oneflow.float32)
class oneflow.nn.ConstantPad1d(padding, value=0)

用常数值填充输入张量的边界。此接口与 PyTorch 一致,文档参考自: https://pytorch.org/docs/stable/generated/torch.nn.ConstantPad1d.html

torch.nn.functional.pad() 来进行 N 维填充。

参数:
  • padding (int, list, tuple) - 填充的大小。若数据类型为 int 则在两个边界中使用相同的填充。若是 2-tuple ,则 (\(\text{padding_left}\), \(\text{padding_right}\))。

  • value (int, float) - 用于填充的常量值。默认值为 0。

形状:
  • Input : \((N, C, W_{in})\)

  • Output : \((N, C, W_{out})\) ,其中

    \(W_{out} = W_{in} + \text{padding_left} + \text{padding_right}\)

示例:

>>> import oneflow as flow

>>> input = flow.arange(8, dtype=flow.float32).reshape(2,2,2)
>>> m = flow.nn.ConstantPad1d(padding=[1, 2], value=9.9999)
>>> output = m(input)
>>> output
tensor([[[9.9999, 0.0000, 1.0000, 9.9999, 9.9999],
         [9.9999, 2.0000, 3.0000, 9.9999, 9.9999]],

        [[9.9999, 4.0000, 5.0000, 9.9999, 9.9999],
         [9.9999, 6.0000, 7.0000, 9.9999, 9.9999]]], dtype=oneflow.float32)
class oneflow.nn.ConstantPad2d(padding, value=0)

此接口与 PyTorch 一致,文档参考自: https://pytorch.org/docs/stable/generated/torch.nn.ConstantPad2d.html

用 0 填充输入张量边界。用户可以通过设置参数 paddings 来设置填充量。

参数:
  • padding (int 或 tuple) - 填充的大小。若是 int,则在所有边界中使用相同的填充。若是 4-tuple ,则(\(\mathrm{padding_{left}}\), \(\mathrm{padding_{right}}\), \(\mathrm{padding_{top}}\), \(\mathrm{padding_{bottom}}\))。

形状:
  • Input : \((N, C, H_{in}, W_{in})\)

  • Output : \((N, C, H_{out}, W_{out})\) ,其中

    \(H_{out} = H_{in} + \text{padding_top} + \text{padding_bottom}\)

    \(W_{out} = W_{in} + \text{padding_left} + \text{padding_right}\)

示例:

>>> import oneflow as flow

>>> m1 = flow.nn.ZeroPad2d(2)
>>> m2 = flow.nn.ZeroPad2d((1,2,2,0))
>>> input = flow.arange(18, dtype=flow.float32).reshape((1, 2, 3, 3))
>>> output = m1(input)
>>> output.shape
oneflow.Size([1, 2, 7, 7])
>>> output
tensor([[[[ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
          [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
          [ 0.,  0.,  0.,  1.,  2.,  0.,  0.],
          [ 0.,  0.,  3.,  4.,  5.,  0.,  0.],
          [ 0.,  0.,  6.,  7.,  8.,  0.,  0.],
          [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
          [ 0.,  0.,  0.,  0.,  0.,  0.,  0.]],

         [[ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
          [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
          [ 0.,  0.,  9., 10., 11.,  0.,  0.],
          [ 0.,  0., 12., 13., 14.,  0.,  0.],
          [ 0.,  0., 15., 16., 17.,  0.,  0.],
          [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
          [ 0.,  0.,  0.,  0.,  0.,  0.,  0.]]]], dtype=oneflow.float32)
>>> output = m2(input)
>>> output
tensor([[[[ 0.,  0.,  0.,  0.,  0.,  0.],
          [ 0.,  0.,  0.,  0.,  0.,  0.],
          [ 0.,  0.,  1.,  2.,  0.,  0.],
          [ 0.,  3.,  4.,  5.,  0.,  0.],
          [ 0.,  6.,  7.,  8.,  0.,  0.]],

         [[ 0.,  0.,  0.,  0.,  0.,  0.],
          [ 0.,  0.,  0.,  0.,  0.,  0.],
          [ 0.,  9., 10., 11.,  0.,  0.],
          [ 0., 12., 13., 14.,  0.,  0.],
          [ 0., 15., 16., 17.,  0.,  0.]]]], dtype=oneflow.float32)
class oneflow.nn.ConstantPad3d(padding, value=0)

用常数填充输入张量的边界。此接口与 PyTorch 一致,文档参考自: https://pytorch.org/docs/stable/generated/torch.nn.ConstantPad3d.html

torch.nn.functional.pad() 来进行 N 维填充。

参数:
  • padding (int, list, tuple) - 填充的大小。若数据类型为 int 则在所有边界中使用相同的填充。若是 6-tuple ,则 ( \(\text{padding_left}\) , \(\text{padding_right}\) , \(\text{padding_top}\) , \(\text{padding_bottom}\) , \(\text{padding_front}\) , \(\text{padding_back}\) )。

  • value (int, float) - 用于填充的常量值。默认值为 0。

形状:
  • Input: \((N, C, D_{in}, H_{in}, W_{in})\)

  • Output: \((N, C, D_{out}, H_{out}, W_{out})\) ,其中

    \(D_{out} = D_{in} + \text{padding_front} + \text{padding_back}\)

    \(H_{out} = H_{in} + \text{padding_top} + \text{padding_bottom}\)

    \(W_{out} = W_{in} + \text{padding_left} + \text{padding_right}\)

示例:

>>> import oneflow as flow
>>> input = flow.arange(8, dtype=flow.int32).reshape(1,1,2,2,2)
>>> m = flow.nn.ConstantPad3d(padding=1, value=9)
>>> output = m(input)
>>> output
tensor([[[[[9, 9, 9, 9],
           [9, 9, 9, 9],
           [9, 9, 9, 9],
           [9, 9, 9, 9]],

          [[9, 9, 9, 9],
           [9, 0, 1, 9],
           [9, 2, 3, 9],
           [9, 9, 9, 9]],

          [[9, 9, 9, 9],
           [9, 4, 5, 9],
           [9, 6, 7, 9],
           [9, 9, 9, 9]],

          [[9, 9, 9, 9],
           [9, 9, 9, 9],
           [9, 9, 9, 9],
           [9, 9, 9, 9]]]]], dtype=oneflow.int32)
class oneflow.nn.Conv1d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros')

此接口与 PyTorch 一致,文档参考自: https://pytorch.org/docs/master/generated/torch.nn.Conv1d.html#conv1d

对由多个平面组成的输入信号应用 1D 卷积。

在最简单的情况下,大小为 \((N, C_{\text{in}}, L)\) 的输入层的输出值和输出 \((N, C_{\text{out}}, L_{\text{out}})\) 可以被准确的表述为:

\[\text{out}(N_i, C_{\text{out}_j}) = \text{bias}(C_{\text{out}_j}) + \sum_{k = 0}^{C_{in} - 1} \text{weight}(C_{\text{out}_j}, k) \star \text{input}(N_i, k)\]

其中 \(\star\) 为有效的 cross-correlation 算子, \(N\) 是批量大小, \(C\) 表示通道数, \(L\) 是信号序列的长度。

  • stride 是控制互相关 (cross-correlation) 的步幅 (stride) 的单个数字或单元素元组。

  • padding 控制应用于输入的填充量。可以是 string {{‘valid’, ‘same’}} 或一个给出在两侧的隐式填充量的整数元组。

  • dilation 控制核心点 (kernel points) 之间的间距,也称为 à trous algorithm。这个 链接 中有 dilation 的可视化展示。

Note

padding='valid' 等同于无填充。 padding='same' 填充输入,使输出具有与输入相同的形状。 但是在这种情况下,不支持除了 1 以外的任何步幅 (stride) 值。

参数:
  • in_channels (int) - 输入图像的通道数。

  • out_channels (int) - 卷积产生的通道数。

  • kernel_size (int 或者 tuple) - 卷积核的大小。

  • stride (int 或者 tuple, 可选的) - 卷积的步幅 (stride)。默认值为: 1。

  • padding (int, tuple 或者 str, 可选的) - 添加到输入两侧的填充值。默认值为: 0。

  • padding_mode (string, 可选的) - 默认值为: 'zeros'

  • dilation (int 或者 tuple, 可选的) - 核心的元素之间的间距。默认值为: 1。

  • groups (int, 可选的) - 从输入通道到输出通道的 blocked connections 数。默认值为:1。

  • bias (bool, 可选的) - 若为 True ,则向输出添加可学习的偏差。默认值为: True

形状:
  • Input : \((N, C_{in}, L_{in})\)

  • Output : \((N, C_{out}, L_{out})\) ,其中

    \[L_{out} = \left\lfloor\frac{L_{in} + 2 \times \text{padding} - \text{dilation} \times (\text{kernel_size} - 1) - 1}{\text{stride}} + 1\right\rfloor\]
weight

形状为 \((\text{out_channels}, \frac{\text{in_channels}}{\text{groups}}, \text{kernel_size})\) 的模块的可学习权重。这些权重的值是由公式 \(\mathcal{U}(-\sqrt{k}, \sqrt{k})\) 计算而来,其中 \(k = \frac{groups}{C_\text{in} * \text{kernel_size}}\)

Type

Tensor

bias

形状为 (out_channels) 的模块的可学习偏置。若 biasTrue ,则那么这些权重的值是由公式 \(\mathcal{U}(-\sqrt{k}, \sqrt{k})\) 计算而来,其中 \(k = \frac{groups}{C_\text{in} * \text{kernel_size}}\)

Type

Tensor

示例:

>>> import oneflow as flow
>>> import oneflow.nn as nn

>>> input = flow.randn(20, 16, 50)
>>> m = nn.Conv1d(16, 33, 3, stride=2)
>>> output = m(input)
class oneflow.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros')

此接口与 PyTorch 一致,文档参考自: https://pytorch.org/docs/master/generated/torch.nn.Conv2d.html#conv2d

对由多个平面组成的输入信号应用 2D 卷积。

在最简单的情况下,大小为 \((N, C_{\text{in}}, H, W)\) 的输入层的输出值和输出 \((N, C_{\text{out}}, H_{\text{out}}, W_{\text{out}})\) 可以被准确的表述为:

\[\text{out}(N_i, C_{\text{out}_j}) = \text{bias}(C_{\text{out}_j}) + \sum_{k = 0}^{C_{\text{in}} - 1} \text{weight}(C_{\text{out}_j}, k) \star \text{input}(N_i, k)\]

其中 \(\star\) 为有效的 2D cross-correlation 算子, \(N\) 是批量大小, \(C\) 表示通道数, \(H\) 是以像素为单位的输入平面的高度,和 \(W\) 是以像素为单位的宽度。

  • stride 是控制互相关 (cross-correlation) 的步幅 (stride) 的单个数字或单元素元组。

  • padding 控制在输入每个维度两侧隐式填充 padding 个点。

  • dilation 控制核心点 (kernel points) 之间的间距,也称为 à trous algorithm。这个 链接 中有 dilation 的可视化展示。

  • groups 控制输入和输出之间的连接。 in_channelsout_channels 都必须能被 groups 整除。例如:
    • 当 groups=1 时,所有输入都卷积到输出。

    • 当 groups=2 时,该操作等效于并排放置两个 conv 层,其中每个层检查一半的输入通道并产生一半的输出通道,然后将两者连接起来。

    • 当 groups= in_channels 时, 每个输入通道都与它自己的一组过滤器(大小为 \(\frac{\text{out_channels}}{\text{in_channels}}\))进行卷积。

参数 kernel_sizestridepaddingdilation 可以是:
  • 单个 int – 在这种情况下,高度和宽度使用相同的值。

  • 一个由两个 int 组成的 tuple – 在这种情况下,第一个 int 用于高度,第二个 int 用于宽度。

Note

groups == in_channels 并且 out_channels == K * in_channels 时,其中 K 是一个正整数,这个操作被称为“深度卷积”。

换句话说,对于大小为 \((N, C_{in}, L_{in})\) 的输入,可以使用参数 \((C_\text{in}=C_\text{in}, C_\text{out}=C_\text{in} \times \text{K}, ..., \text{groups}=C_\text{in})\) 执行具有深度乘数 K 的深度卷积。

参数:
  • in_channels (int) - 输入图像的通道数。

  • out_channels (int) - 卷积产生的通道数。

  • kernel_size (int 或者 tuple) - 卷积核的大小。

  • stride (int 或者 tuple, 可选的) - 卷积的步幅 (stride)。默认值为:1。

  • padding (int, tuple 或者 str, 可选的) - 添加到输入两侧的填充值。默认值为:0。

  • padding_mode (string, 可选的) - 默认值为: 'zeros'

  • dilation (int 或者 tuple, 可选的) - 核心的元素之间的间距。默认值为:1。

  • groups (int, 可选的) - 从输入通道到输出通道的 blocked connections 数。默认值为:1。

  • bias (bool, 可选的) - 若为 True ,则向输出添加可学习的偏差。默认值为:True

形状:
  • Input : \((N, C_{in}, H_{in}, W_{in})\)

  • Output : \((N, C_{out}, H_{out}, W_{out})\) ,其中

    \[H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{padding}[0] - \text{dilation}[0] \times (\text{kernel_size}[0] - 1) - 1}{\text{stride}[0]} + 1\right\rfloor\]
    \[W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{padding}[1] - \text{dilation}[1] \times (\text{kernel_size}[1] - 1) - 1}{\text{stride}[1]} + 1\right\rfloor\]
weight

形状为 \((\text{out_channels}, \frac{\text{in_channels}}{\text{groups}},\text{kernel_size[0]}, \text{kernel_size[1]})\) 的模块的可学习权重。这些权重的值是由公式 \(\mathcal{U}(-\sqrt{k}, \sqrt{k})\) 计算而来,其中 \(k = \frac{groups}{C_\text{in} * \prod_{i=0}^{1}\text{kernel_size}[i]}\)

Type

Tensor

bias

形状为 (out_channels) 的模块的可学习偏置。若 biasTrue ,则那么这些权重的值是由公式 \(\mathcal{U}(-\sqrt{k}, \sqrt{k})\) 计算而来,其中 \(k = \frac{groups}{C_\text{in} * \prod_{i=0}^{1}\text{kernel_size}[i]}\)

Type

Tensor

示例:

>>> import oneflow as flow
>>> import oneflow.nn as nn

>>> input = flow.randn(20, 16, 50, 100)
>>> m = nn.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2), dilation=(3, 1))
>>> output = m(input)
class oneflow.nn.Conv3d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros')

此接口与 PyTorch 一致,文档参考自: https://pytorch.org/docs/master/generated/torch.nn.Conv3d.html#conv3

对由多个平面组成的输入信号应用 3D 卷积。

在最简单的情况下,大小为 \((N, C_{in}, D, H, W)\) 的输入层的输出值和输出。 \((N, C_{out}, D_{out}, H_{out}, W_{out})\) 可以被准确的表述为:

\[out(N_i, C_{out_j}) = bias(C_{out_j}) + \sum_{k = 0}^{C_{in} - 1} weight(C_{out_j}, k) \star input(N_i, k)\]

其中 \(\star\) 为有效的 3D cross-correlation 算子。

  • stride 是控制互相关 (cross-correlation) 的步幅 (stride) 的单个数字或单元素元组。

  • padding 控制应用于输入的填充量。可以是 string {{‘valid’, ‘same’}} 或一个给出在两侧的隐式填充量的整数元组。

  • dilation 控制核心点 (kernel points) 之间的间距,也称为 à trous algorithm。这个 链接 中有 dilation 的可视化展示。

参数 kernel_sizestridepaddingdilation 可以是:

  • 单个 int – 在这种情况下,长度、宽度和高度使用相同的值

  • 一个由两个 int 组成的 tuple – 在这种情况下,第一个 int 用于长度,第二个 int 用于高度,第三个 int 用于宽度。

Note

padding='valid' 等同于无填充。 padding='same' 填充输入,使输出具有与输入相同的形状。 但是在这种情况下,不支持除了 1 以外的任何步幅 (stride) 值。

参数:
  • in_channels (int) - 输入图像的通道数。

  • out_channels (int) - 卷积产生的通道数。

  • kernel_size (int 或者 tuple) - 卷积核的大小。

  • stride (int 或者 tuple, 可选的) - 卷积的步幅 (stride)。默认值为:1。

  • padding (int, tuple 或者 str, 可选的) - 添加到输入两侧的填充值。默认值为:0。

  • padding_mode (string, 可选的) - 默认值为: 'zeros'

  • dilation (int 或者 tuple, 可选的) - 核心的元素之间的间距。默认值为:1。

  • groups (int, 可选的) - 从输入通道到输出通道的 blocked connections 数。默认值为:1。

  • bias (bool, 可选的) - 若为 True ,则向输出添加可学习的偏差。默认值为:True

形状:
  • Input : \((N, C_{in}, D_{in}, H_{in}, W_{in})\)

  • Output : \((N, C_{out}, D_{out}, H_{out}, W_{out})\) ,其中

    \[D_{out} = \left\lfloor\frac{D_{in} + 2 \times \text{padding}[0] - \text{dilation}[0] \times (\text{kernel_size}[0] - 1) - 1}{\text{stride}[0]} + 1\right\rfloor\]
    \[H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{padding}[1] - \text{dilation}[1] \times (\text{kernel_size}[1] - 1) - 1}{\text{stride}[1]} + 1\right\rfloor\]
    \[W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{padding}[2] - \text{dilation}[2] \times (\text{kernel_size}[2] - 1) - 1}{\text{stride}[2]} + 1\right\rfloor\]
weight

形状为 \((\text{out_channels}, \frac{\text{in_channels}}{\text{groups}},\text{kernel_size[0]}, \text{kernel_size[1]}, \text{kernel_size[2]})\) 的模块的可学习权重。这些权重的值是由公式 \(\mathcal{U}(-\sqrt{k}, \sqrt{k})\) 计算而来,其中 \(k = \frac{groups}{C_\text{in} * \prod_{i=0}^{2}\text{kernel_size}[i]}\)

Type

Tensor

bias

形状为 (out_channels) 的模块的可学习偏置。若 biasTrue ,则那么这些权重的值是由公式 \(\mathcal{U}(-\sqrt{k}, \sqrt{k})\) 计算而来,其中 \(k = \frac{groups}{C_\text{in} * \prod_{i=0}^{2}\text{kernel_size}[i]}\)

Type

Tensor

示例:

>>> import oneflow as flow
>>> import oneflow.nn as nn

>>> input = flow.randn(1, 2, 5, 5, 5)
>>> m = nn.Conv3d(2, 4, kernel_size=3, stride=1)
>>> output = m(input)
class oneflow.nn.ConvTranspose1d(in_channels: int, out_channels: int, kernel_size: Union[int, Tuple[int]], stride: Union[int, Tuple[int]] = 1, padding: Union[int, Tuple[int]] = 0, output_padding: Union[int, Tuple[int]] = 0, groups: int = 1, bias: bool = True, dilation: Union[int, Tuple[int]] = 1, padding_mode: str = 'zeros')

在由多个输入平面组成的输入图像上应用 1D 转置卷积算子。

该 module 可以看作是 Conv1d 相对于其输入的梯度。它也称为分数步幅卷积或反卷积(尽管它实际上不是反卷积操作)。此 module 支持 TensorFloat32。

其中:
  • stride 控制互相关 (cross-correlation) 的步幅 (stride)。

  • padding 控制应用于输入两侧,点的数量为 dilation * (kernel_size - 1) - padding 的隐式 0 填充。更多细节请参考 note

  • output_padding 控制添加到输出形状一侧的大小。更多信息请参考 note

  • dilation 控制核心点 (kernel points) 之间的间距,也称为 à trous algorithm。这个 链接 中有 dilation 的可视化展示。

Note

padding 参数有效地将 dilation * (kernel_size - 1) - padding 个 0 填充到输入的两侧。 设定此项的目的是当 Conv1dConvTranspose1d 用相同的参数初始化时, 它们的输入和输出的形状是互逆的。然而,当 stride > 1 时, Conv1d 将多个输入形状映射到相同的输出形状。则使用 output_padding 有效地增加一侧的输出形状来解决这种歧义。 请注意,output_padding 仅用于查找输出形状,但实际上并未填充输出。

Note

在某些情况下,将 CUDA 后端与 CuDNN 一起使用时,此算子可能会选择非确定性算法来提高性能。 若此操作有不确定性,可以尝试通过设置 torch.backends.cudnn.deterministic = True 来使操作具有确定性(可能以性能为代价)。 背景请参阅有关随机性 (randomness) 的 notes。

参数:
  • in_channels (int) - 输入图像的通道数。

  • out_channels (int) - 卷积产生的通道数。

  • kernel_size (int 或 tuple) - 卷积核的大小。

  • stride (int 或 tuple, 可选的) - 卷积的步幅 (stride)。默认值为:1。

  • padding (int 或 tuple, 可选的) - 添加到输入每侧的 dilation * (kernel_size - 1) - padding 大小的 0 填充值。默认值为:0。

  • output_padding (int 或 tuple, 可选的) - 添加到输出形状一侧的大小。默认值为:0。

  • groups (int, 可选的) - 从输入通道到输出通道的 blocked connections 数。默认值为:1。

  • bias (bool, 可选的) - 若为 True ,则向输出添加可学习的偏差。默认值为:True

  • dilation (int 或 tuple, 可选的) - 核心的元素之间的间距。默认值为:1。

形状:
  • Input : \((N, C_{in}, L_{in})\)

  • Output : \((N, C_{out}, L_{out})\) ,其中

    \[L_{out} = (L_{in} - 1) \times \text{stride} - 2 \times \text{padding} + \text{dilation} \times (\text{kernel_size} - 1) + \text{output_padding} + 1\]
weight

形状为 \((\text{in_channels}, \frac{\text{out_channels}}{\text{groups}}, \text{kernel_size})\) 的模块的可学习参数。这些参数的值从 \(\mathcal{U}(-\sqrt{k}, \sqrt{k})\) 中采样,其中 \(k = \frac{groups}{C_\text{out} * \text{kernel_size}}\)

Type

Tensor

bias

形状为 (out_channels) 的模块的可学习偏置。如果 biasTrue,那么这些值从 \(\mathcal{U}(-\sqrt{k}, \sqrt{k})\) 中取样,其中 \(k = \frac{groups}{C_\text{out} * \text{kernel_size}}\)

Type

Tensor

class oneflow.nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride=1, padding=0, output_padding=0, groups=1, bias=True, dilation=1, padding_mode='zeros')

在由多个输入平面组成的输入图像上应用 2D 转置卷积算子。

该 module 可以看作是 Conv2d 相对于其输入的梯度。它也称为分数步幅卷积或反卷积(尽管它实际上不是反卷积操作)。

参数:
  • in_channels (int) - 输入图像的通道数。

  • out_channels (int) - 卷积产生的通道数。

  • kernel_size (int 或 tuple) - 卷积核的大小。

  • stride (int 或 tuple, 可选的) - 卷积的步幅 (stride)。默认值为:1。

  • padding (int 或 tuple, 可选的) - 添加到输入每侧的 dilation * (kernel_size - 1) - padding 大小的 0 填充值。默认值为:0。

  • output_padding (int 或 tuple, 可选的) - 添加到输出形状一侧的大小。默认值为:0。

  • groups (int, 可选的) - 从输入通道到输出通道的 blocked connections 数。默认值为:1。

  • bias (bool, 可选的) - 若为 True ,则向输出添加可学习的偏差。默认值为:True

  • dilation (int 或 tuple, 可选的) - 核心的元素之间的间距。默认值为:1。

形状:
  • Input : \((N, C_{in}, H_{in}, W_{in})\)

  • Output : \((N, C_{out}, H_{out}, W_{out})\) ,其中

\[ \begin{align}\begin{aligned}H_{out} = (H_{in} - 1) \times \text{stride}[0] - 2 \times \text{padding}[0] + \text{dilation}[0]\\ \times (\text{kernel_size}[0] - 1) + \text{output_padding}[0] + 1\end{aligned}\end{align} \]
\[ \begin{align}\begin{aligned}W_{out} = (W_{in} - 1) \times \text{stride}[1] - 2 \times \text{padding}[1] + \text{dilation}[1]\\ \times (\text{kernel_size}[1] - 1) + \text{output_padding}[1] + 1\end{aligned}\end{align} \]
weight

形状为 \((\text{in_channels}, \frac{\text{out_channels}}{\text{groups}},\) \(\text{kernel_size[0]}, \text{kernel_size[1]})\) 的模块的可学习权重。这些权重的值是由公式 \(\mathcal{U}(-\sqrt{k}, \sqrt{k})\) 计算而来,其中 \(k = \frac{groups}{C_\text{out} * \prod_{i=0}^{1}\text{kernel_size}[i]}\)

Type

Tensor

bias

形状为 (out_channels) 的模块的可学习偏置。若 biasTrue ,则那么这些权重的值是由公式 \(\mathcal{U}(-\sqrt{k}, \sqrt{k})\) 计算而来,其中 \(k = \frac{groups}{C_\text{out} * \text{kernel_size}}\)

Type

Tensor

示例:

>>> import oneflow as flow
>>> import oneflow.nn as nn

>>> m = nn.ConvTranspose2d(16, 33, 3, stride=2)
>>> # non-square kernels and unequal stride and with padding
>>> m = nn.ConvTranspose2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2))
>>> m = m.to("cuda")
>>> input = flow.randn(20, 16, 50, 100, device=flow.device("cuda"))
>>> output = m(input)
>>> output.size()
oneflow.Size([20, 33, 93, 100])
class oneflow.nn.ConvTranspose3d(in_channels, out_channels, kernel_size, stride=1, padding=0, output_padding=0, groups=1, bias=True, dilation=1, padding_mode='zeros')

在由多个输入平面组成的输入图像上应用 3D 转置卷积算子。

转置卷积算子将每个输入值逐元素乘以一个可学习的内核 (kernel) ,并对所有输入特征平面的输出求和。

该 module 可以看作是 Conv3d 相对于其输入的梯度。它也称为分数步幅卷积或反卷积(尽管它实际上不是反卷积操作)。

此 module 支持 TensorFloat32。

  • stride 控制互相关 (cross-correlation) 的步幅 (stride)。

  • padding 控制应用于输入两侧,点的数量为 dilation * (kernel_size - 1) - padding 的隐式 0 填充。 更多细节请参考 note

  • output_padding 控制添加到输出形状一侧的大小。更多信息请参考 note

  • dilation 控制核心点 (kernel points) 之间的间距,也称为 à trous algorithm。这个 链接 中有 dilation 的可视化展示。

参数 kernel_sizestridepaddingoutput_padding 可以是以下形式:

  • 单个 int – 在这种情况下,长度、高度和宽度的大小使用相同的值。

  • 一个由三个 int 组成的 tuple – 在这种情况下,第一个 int 用于长度,第二个 int 表示高度,第三个 int 表示宽度。

Note

padding 参数有效地将 dilation * (kernel_size - 1) - padding 个 0 填充到输入的两侧。 设定此项的目的是当 Conv3dConvTranspose3d 用相同的参数初始化时, 它们的输入和输出的形状是互逆的。然而,当 stride > 1 时, Conv3d 将多个输入形状映射到相同的输出形状。则使用 output_padding 有效地增加一侧的输出形状来解决这种歧义。 请注意,output_padding 仅用于查找输出形状,但实际上并未填充输出。

参数:
  • in_channels (int) - 输入图像的通道数。

  • out_channels (int) - 卷积产生的通道数。

  • kernel_size (int 或 tuple) - 卷积核的大小。

  • stride (int 或 tuple, 可选的) - 卷积的步幅 (stride)。默认值为:1。

  • padding (int 或 tuple, 可选的) - 添加到输入每侧的 dilation * (kernel_size - 1) - padding 大小的 0 填充值。默认值为:0。

  • output_padding (int 或 tuple, 可选的) - 添加到输出形状一侧的大小。默认值为:0。

  • groups (int, 可选的) - 从输入通道到输出通道的 blocked connections 数。默认值为:1。

  • bias (bool, 可选的) - 若为 True ,则向输出添加可学习的偏差。默认值为:True

  • dilation (int 或 tuple, 可选的) - 核心的元素之间的间距。默认值为:1。

形状:
  • Input : \((N, C_{in}, D_{in}, H_{in}, W_{in})\)

  • Output : \((N, C_{out}, D_{out}, H_{out}, W_{out})\) ,其中

\[D_{out} = (D_{in} - 1) \times \text{stride}[0] - 2 \times \text{padding}[0] + \text{dilation}[0] \times (\text{kernel_size}[0] - 1) + \text{output_padding}[0] + 1\]
\[H_{out} = (H_{in} - 1) \times \text{stride}[1] - 2 \times \text{padding}[1] + \text{dilation}[1] \times (\text{kernel_size}[1] - 1) + \text{output_padding}[1] + 1\]
\[W_{out} = (W_{in} - 1) \times \text{stride}[2] - 2 \times \text{padding}[2] + \text{dilation}[2] \times (\text{kernel_size}[2] - 1) + \text{output_padding}[2] + 1\]
weight

形状为 \((\text{in_channels}, \frac{\text{out_channels}}{\text{groups}},\) \(\text{kernel_size[0]}, \text{kernel_size[1]}, \text{kernel_size[2]})\) 的模块的可学习权重。这些权重的值是由公式 \(\mathcal{U}(-\sqrt{k}, \sqrt{k})\) 计算而来,其中 \(k = \frac{groups}{C_\text{out} * \prod_{i=0}^{2}\text{kernel_size}[i]}\)

Type

Tensor

bias

形状为 (out_channels) 的模块的可学习偏置。若 biasTrue ,则那么这些权重的值是由公式 \(\mathcal{U}(-\sqrt{k}, \sqrt{k})\) 计算而来,其中 \(k = \frac{groups}{C_\text{out} * \text{kernel_size}}\)

Type

Tensor

示例:

>>> import oneflow as flow
>>> import oneflow.nn as nn
>>> # With square kernels and equal stride
>>> m = nn.ConvTranspose3d(16, 33, 3, stride=2)
>>> # non-square kernels and unequal stride and with padding
>>> m = nn.ConvTranspose3d(16, 33, (3, 5, 2), stride=(2, 1, 1), padding=(0, 4, 2))
>>> input = flow.randn(20, 16, 10, 50, 100)
>>> output = m(input)
class oneflow.nn.CropMirrorNormalize(color_space: str = 'BGR', output_layout: str = 'NCHW', crop_h: int = 0, crop_w: int = 0, crop_pos_y: float = 0.5, crop_pos_x: float = 0.5, mean: Sequence[float] = [0.0], std: Sequence[float] = [1.0], output_dtype: oneflow._oneflow_internal.dtype = oneflow.float32)
class oneflow.nn.CrossEntropyLoss(weight=None, ignore_index=100, reduction='mean')

将类 LogSoftmaxNLLLoss 组合在一起。

该类在使用 C 类训练分类问题时很有效。

input 应包含每个类的原始的,非标准化分数。

K 维下, input 的大小必须为 \((minibatch, C)\)\((minibatch, C, d_1, d_2, ..., d_K)\) , 其中 \(K \geq 1\) (见下文)。

在此标准中,类的索引应在 \([0, C-1]\) 范围内并引作为大小为 minibatch 的一维张量的 target

该损失可以被描述为:

\[\text{loss}(x, class) = -\log\left(\frac{\exp(x[class])}{\sum_j \exp(x[j])}\right) = -x[class] + \log\left(\sum_j \exp(x[j])\right)\]

通过提供大小为 \((minibatch, C, d_1, d_2, ..., d_K)\) 的输入和适当形状的目标(其中 \(K \geq 1\)\(K\) 是维度数), 此类也可用于更高维度的输入,例如 2D 图像(见下文)。

参数:
  • reduction (string, 可选的) - 指定应用于输出的 reduction(可以是 'none''mean''sum' ,默认值为 'mean')。其中 'none' :不进行简化;'mean' :取输出的加权平均值;'sum' :取输出的和。

示例:

>>> import oneflow as flow

>>> input = flow.tensor(
...    [[-0.1664078, -1.7256707, -0.14690138],
...        [-0.21474946, 0.53737473, 0.99684894],
...        [-1.135804, -0.50371903, 0.7645404]], dtype=flow.float32)
>>> target = flow.tensor([0, 1, 2], dtype=flow.int32)
>>> out = flow.nn.CrossEntropyLoss(reduction="none")(input, target)
>>> out
tensor([0.8020, 1.1167, 0.3583], dtype=oneflow.float32)
>>> out_sum = flow.nn.CrossEntropyLoss(reduction="sum")(input, target)
>>> out_sum
tensor(2.2769, dtype=oneflow.float32)
>>> out_mean = flow.nn.CrossEntropyLoss(reduction="mean")(input, target)
>>> out_mean
tensor(0.7590, dtype=oneflow.float32)
class oneflow.nn.Dropout(p:=0.5, inplace=False, generator=None)

在训练期间,使用来自伯努利分布 (Bernoulli distribution) 的样本,以概率 p 随机将输入张量的一些元素归零。 在每次 forward call 时,所有的通道都将独立归零。

如 “Improving neural networks by preventing co-adaptation of feature detectors” 所述,此方法已被证明可以有效用于正则化 (regularization) 和防止神经元协同适应 (co-adaptation of neurons) 。

此外,在训练期间,输出按因数 \(\frac{1}{1-p}\) 进行缩放。这意味着在评估过程中只计算一个恒等函数。

参数:
  • p (float): 元素归零的概率。默认:0.5

  • inplace (bool): 是否执行 in-place 操作。默认为: False

形状:
  • Input : \((*)\) 输入可以是任何形状

  • Output : \((*)\) 输出与输入形状相同

示例:

>>> import oneflow as flow

>>> m = flow.nn.Dropout(p=0)
>>> x = flow.tensor([[-0.7797, 0.2264, 0.2458, 0.4163], [0.4299, 0.3626, -0.4892, 0.4141], [-1.4115, 1.2183, -0.5503, 0.6520]],dtype=flow.float32)
>>> y = m(x)
>>> y 
tensor([[-0.7797,  0.2264,  0.2458,  0.4163],
        [ 0.4299,  0.3626, -0.4892,  0.4141],
        [-1.4115,  1.2183, -0.5503,  0.6520]], dtype=oneflow.float32)
inplace: bool
p: float
class oneflow.nn.ELU(alpha=1.0, inplace=False)

应用以下逐元素公式:

\[\begin{split}\text{ELU}(x) = \begin{cases} x & \text{ if } x \gt 0 \\ \alpha*(exp(x)-1) & \text{ if } x \le 0 \\ \end{cases}\end{split}\]
参数:
  • alpha : ELU 公式的 \(\alpha\) 值。默认:1.0

  • inplace : 是否执行 in-place 操作。默认: False

形状:
  • Input : \((N, *)\) 其中 * 表示任意数量的额外维度

  • Output : \((N, *)\) 形状与输入一致

示例:

>>> import oneflow as flow

>>> input = flow.tensor([-0.5, 0, 0.5], dtype=flow.float32)
>>> elu = flow.nn.ELU()

>>> out = elu(input)
>>> out
tensor([-0.3935,  0.0000,  0.5000], dtype=oneflow.float32)
class oneflow.nn.Embedding(num_embeddings, embedding_dim, padding_idx=None, max_norm=None, norm_type=None, scale_grad_by_freq=False, sparse=False, _weight=None)

一个简单的查找表,用于存储固定字典和大小的嵌入。

该模块通常用于储存词嵌入并索引它们。该模块的输入是索引列表,输出是相应的词嵌入。

参数:
  • num_embeddings (int): 嵌入字典的大小

  • embedding_dim (int): 每个嵌入向量的大小

  • padding_idx (int, 可选的): 如果设定了此参数,则 padding_idx 处的元素不会影响梯度;因此,在训练期间不会更新 padding_idx 的嵌入向量,它仍然是一个固定的 pad 。对于新构建的嵌入, padding_idx 处的嵌入向量将默认为全零,但可以更新为另一个值以用作填充向量。

示例:

>>> import oneflow as flow

>>> indices = flow.tensor([[1, 2, 4, 5], [4, 3, 2, 9]], dtype=flow.int)
>>> m = flow.nn.Embedding(10, 3)
>>> y = m(indices)
class oneflow.nn.FakeQuantization(quantization_formula='google', quantization_bit=8, quantization_scheme='symmetric')

在训练时间内模拟量化 (quantize) 和反量化 (dequantize) 操作。输出将被计算为:

若 quantization_scheme == “symmetric”:

\[ \begin{align}\begin{aligned}& quant\_max = 2^{quantization\_to\_bit - 1} - 1\\& quant\_min = -quant\_max\\& clamp(round(x / scale), quant\_min, quant\_max) * scale\end{aligned}\end{align} \]

若 quantization_scheme == “affine”:

\[ \begin{align}\begin{aligned}& quant\_max = 2^{quantization\_to\_bit} - 1\\& quant\_min = 0\\& (clamp(round(x / scale + zero\_point), quant\_min, quant\_max) - zero\_point) * scale\end{aligned}\end{align} \]
参数:
  • quantization_bit (int): 量化输入为 uintX / intX , X 可以在范围 [2, 8] 中。默认为 8

  • quantization_scheme (str): “symmetric” 或 “affine” , 量化为有符号/无符号整数。 默认为 “symmetric”

  • quantization_formula (str): 支持 “google” 或 “cambricon”

返回类型:

oneflow.Tensor: 量化和反量化操作后的输入张量

示例:

>>> import oneflow as flow

>>> input_tensor = flow.rand(2, 3, 4, 5, dtype=flow.float32) - 0.5

>>> quantization_bit = 8
>>> quantization_scheme = "symmetric"
>>> quantization_formula = "google"
>>> per_layer_quantization = True

>>> min_max_observer = flow.nn.MinMaxObserver(quantization_formula=quantization_formula, quantization_bit=quantization_bit,
... quantization_scheme=quantization_scheme, per_layer_quantization=per_layer_quantization)
>>> fake_quantization = flow.nn.FakeQuantization(quantization_formula=quantization_formula, quantization_bit=quantization_bit,
... quantization_scheme=quantization_scheme)

>>> scale, zero_point = min_max_observer(
...    input_tensor,
... )

>>> output_tensor = fake_quantization(
...    input_tensor,
...    scale,
...    zero_point,
... )
class oneflow.nn.Flatten(start_dim=1, end_dim=- 1)

将 tensor 指定连续范围的维度展平。用于:nn.Sequential 。

参数:
  • start_dim (int): 展平开始的维度(默认为 1)

  • end_dim (int): 展平结束的维度(默认为 -1)

示例:

>>> import oneflow as flow
>>> input = flow.Tensor(32, 1, 5, 5)
>>> m = flow.nn.Flatten()
>>> output = m(input)
>>> output.shape
oneflow.Size([32, 25])
class oneflow.nn.FusedBatchNorm1d(num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)

在 2D 或 3D 输入上应用 Fused Batch Normalization ,公式为:

\[out = ReLU(BatchNorm(input) + addend)\]

Batch Normalization 的公式为:

\[y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta\]

逐维度小批量计算均值和标准差,其中 \(\gamma\)\(\beta\) 是大小为 CC 是输入大小) 的可学习参数向量。默认情况下, \(\gamma\) 的元素被设置为 1 ,并且 \(\beta\) 被设置为 0 。通过有偏估计器 (biased estimator) 计算标准差,相当于 torch.var(input, unbiased=False)

默认情况下,该层在训练期间不断估计计算的均值和方差,然后在评估期间用于归一化(normalization)。 运行估计期间, momentum 为 0.1。

如果将 track_running_stats 设置为 False ,则该层不会继续进行估计, 而是在评估期间也使用批处理统计信息。

Note

参数 momentum 与优化器 (optimizer) 中使用的参数和传统的动量 (momentum) 概念都不同。 在数学上,这里运行统计的更新规则是 \(\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momentum} \times x_t\) , 其中 \(\hat{x}\) 是估计的统计量,\(x_t\) 是新的观察值。

因为 Batch Normalization 是在维度 C 上完成的,并在 (N, L) 切片上计算统计数据,所以学术上普遍称之为 Temporal Batch Normalization 。

参数:
  • num_features : 来自大小为 \((N, C, L)\) 的预期输入的 \(C\) 或者来自大小为 \((N, L)\) 的输入的 \(L\)

  • eps : 为数值稳定性而添加到分母的值。默认: 1e-5

  • momentum : 用于 running_meanrunning_var 计算的值。可以设置为 None 以计算累积移动平均。默认: 0.1

  • affine (bool, 可选): 如果为 True ,则该模块具有可学习的仿射参数。默认: True

  • track_running_stats (bool, 可选): 如果为 True ,则此模块跟踪运行均值和方差。如果为 False ,此模块不跟踪此类统计信息,同时初始化统计缓冲区 running_meanrunning_varNone 。当这些缓冲区为 None 时, 此模块在训练和评估模式中始终使用 batch statistics 。默认: True

形状:
  • Input : \((N, C)\)\((N, C, L)\)

  • Output : \((N, C)\)\((N, C, L)\) (与输入形状相同)

示例:

>>> import oneflow as flow

>>> x = flow.randn(20, 100).to("cuda") # 目前 GPU 支持 FusedBatchNorm 。
>>> m = flow.nn.FusedBatchNorm1d(num_features=100, eps=1e-5, momentum=0.1).to("cuda")
>>> y = m(x, addend=None)
class oneflow.nn.FusedBatchNorm2d(num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)

在 4D 输入上应用 Fused Batch Normalization ,公式为:

\[out = ReLU(BatchNorm(input) + addend)\]

Batch Normalization 的公式为:

\[y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta\]

逐维度小批量计算均值和标准差,其中 \(\gamma\)\(\beta\) 是大小为 CC 是输入大小) 的可学习参数向量。默认情况下, \(\gamma\) 的元素被设置为 1 ,并且 \(\beta\) 被设置为 0 。通过有偏估计器 (biased estimator) 计算标准差,相当于 torch.var(input, unbiased=False)

默认情况下,该层在训练期间不断估计计算的均值和方差,然后在评估期间用于归一化(normalization)。 运行估计期间, momentum 为 0.1 。

如果将 track_running_stats 设置为 False ,则该层不会继续进行估计, 而是在评估期间也使用批处理统计信息。

Note

参数 momentum 与优化器 (optimizer) 中使用的参数和传统的动量 (momentum) 概念都不同。 在数学上,这里运行统计的更新规则是 \(\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momentum} \times x_t\) , 其中 \(\hat{x}\) 是估计的统计量,\(x_t\) 是新的观察值。

因为 Batch Normalization 是在维度 C 上完成的,并在 (N, H, W) 切片上计算统计数据,所以学术上普遍称之为 Temporal Batch Normalization 。

参数:
  • num_features : 来自大小为 \((N, C, H, W)\) 的预期输入的 \(C\)

  • eps : 为数值稳定性而添加到分母的值。默认: 1e-5

  • momentum : 用于 running_meanrunning_var 计算的值。可以设置为 None 以计算累积移动平均。默认: 0.1

  • affine (bool, 可选): 如果为 True ,则该模块具有可学习的仿射参数。默认: True

  • track_running_stats (bool, 可选): 如果为 True ,则此模块跟踪运行均值和方差,如果为 False ,此模块不跟踪此类统计信息,同时初始化统计缓冲区 running_meanrunning_varNone 。当这些缓冲区为 None 时, 此模块在训练和评估模式中始终使用 batch statistics 。默认: True

形状:
  • Input: \((N, C, H, W)\)

  • Output: \((N, C, H, W)\) (与输入形状相同)

示例:

>>> import oneflow as flow

>>> x = flow.randn(4, 2, 8, 3).to("cuda") # 目前 GPU 支持 FusedBatchNorm 。
>>> m = flow.nn.FusedBatchNorm2d(num_features=2, eps=1e-5, momentum=0.1).to("cuda")
>>> y = m(x, addend=None)
class oneflow.nn.FusedBatchNorm3d(num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)

在 5D 输入上应用 Fused Batch Normalization ,公式为:

\[out = ReLU(BatchNorm(input) + addend)\]

Batch Normalization 的公式为:

\[y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta\]

逐维度小批量计算均值和标准差,其中 \(\gamma\)\(\beta\) 是大小为 CC 是输入大小) 的可学习参数向量。默认情况下, \(\gamma\) 的元素被设置为 1 ,并且 \(\beta\) 被设置为 0 。通过有偏估计器 (biased estimator) 计算标准差,相当于 torch.var(input, unbiased=False)

默认情况下,该层在训练期间不断估计计算的均值和方差,然后在评估期间用于归一化(normalization)。 运行估计期间, momentum 为 0.1 。

如果将 track_running_stats 设置为 False ,则该层不会继续进行估计, 而是在评估期间也使用批处理统计信息。

Note

参数 momentum 与优化器 (optimizer) 中使用的参数和传统的动量 (momentum) 概念都不同。 在数学上,这里运行统计的更新规则是 \(\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momentum} \times x_t\) , 其中 \(\hat{x}\) 是估计的统计量,\(x_t\) 是新的观察值。

因为 Batch Normalization 是在维度 C 上完成的,并在 (N, D, H, W) 切片上计算统计数据,所以学术上普遍称之为 Temporal Batch Normalization 。

参数:
  • num_features : 来自大小为 \((N, C, D, H, W)\) 的预期输入的 \(C\)

  • eps : 为数值稳定性而添加到分母的值。默认: 1e-5

  • momentum : 用于 running_meanrunning_var 计算的值。可以设置为 None 以计算累积移动平均。默认: 0.1

  • affine (bool, 可选): 如果为 True ,则该模块具有可学习的仿射参数。默认: True

  • track_running_stats (bool, 可选): 如果为 True ,则此模块跟踪运行均值和方差。如果为 False ,此模块不跟踪此类统计信息,同时初始化统计缓冲区 running_meanrunning_varNone 。当这些缓冲区为 None 时, 此模块在训练和评估模式中始终使用 batch statistics 。默认: True

形状:
  • Input: \((N, C, D, H, W)\)

  • Output: \((N, C, D, H, W)\) (与输入形状相同)

示例:

>>> import oneflow as flow

>>> x = flow.randn(3, 2, 5, 8, 4).to("cuda") # 目前 GPU 中支持 FusedBatchNorm 。
>>> m = flow.nn.FusedBatchNorm3d(num_features=2, eps=1e-5, momentum=0.1).to("cuda")
>>> y = m(x, addend=None)
class oneflow.nn.FusedMLP(in_features: int, hidden_features: Tuple[int], out_features: int, skip_final_activation=False)

对输入数据应用带有 relu 激活的线性变换:\(y = ReLU(xA^T + b)\)

参数:
  • in_features - 每一个输入样本的大小

  • hidden_features - 每一个线形层的藏层大小的元组

  • out_features - 最后一层的隐藏大小

形状:
  • Input: \((N, *, H_{in})\),其中 \(*\) 表示任意维度且 \(H_{in} = {in\_features}\)

  • Output: \((N, *, H_{out})\)

属性:
  • skip_final_activation: 是否跳过最后一个隐藏层的激活,默认为 False

示例:

>>> import numpy as np
>>> import oneflow as flow


>>> m = flow.nn.FusedMLP(128, [256, 512], 1024).to("cuda")
>>> input = flow.Tensor(np.random.randn(1, 128)).to("cuda")
>>> output = m(input)
>>> output.size()
oneflow.Size([1, 1024])
add_parameters()None

Register parameter in FusedMLP module.

bias(i)

Return the ith bias.

biases()

Returns the bias list in FusedMLP module.

weight(i)

Returns the ith weight.

weights()

Returns the weight list in FusedMLP module.

class oneflow.nn.GELU

Gelu 激活算子。

公式为:

\[out = 0.5 * x * (1 + tanh(\sqrt{\frac{2}{\pi}} * (x + 0.044715x^{3})))\]
参数:

x (oneflow.tensor): 输入张量

返回类型:

oneflow.tensor

示例:

>>> import oneflow as flow

>>> input = flow.tensor([-0.5, 0, 0.5], dtype=flow.float32)
>>> gelu = flow.nn.GELU()

>>> out = gelu(input)
>>> out
tensor([-0.1543,  0.0000,  0.3457], dtype=oneflow.float32)
class oneflow.nn.GLU(dim=- 1)

GLU 激活算子。

参数:
  • input (Tensor, float): 输入张量

  • dim (int, 可选的): 分割输入的维度。默认:-1

形状:
  • Input: \((\ast_1, N, \ast_2)\) 其中 * 表示任意数量的额外维度

  • Output: \((\ast_1, M, \ast_2)\) 其中 \(M=N/2\)

公式为:

\[GLU(input) = GLU(a, b) = a \otimes sigmoid(b)\]

Note

其中输入沿 dim 分成 a 和 b ,⊗ 是矩阵之间的元素积。

示例:

>>> import oneflow as flow
>>> import oneflow.nn as nn
>>> m = nn.GLU()
>>> x = flow.tensor([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=flow.float32)
>>> y = m(x)
>>> y
tensor([[0.9526, 1.9640],
        [4.9954, 5.9980]], dtype=oneflow.float32)
class oneflow.nn.GroupNorm(num_groups: int, num_channels: int, eps: float = 1e-05, affine: bool = True)

此接口与 PyTorch 对其,可参考以下文档: https://pytorch.org/docs/stable/generated/torch.nn.GroupNorm.html

对小批量输入应用组归一化 (Group Normalization) 的行为按 论文 中所述。

公式为:

\[y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta\]

输入通道被分成 num_groups 个组,每组包含 num_channels / num_groups 个通道。 每个组的平均值和标准差分开计算。如果 affineTrue ,则 \(\gamma\)\(\beta\) 是大小为 num_channels 的可学习逐通道仿射变换参数向量 (learnable per-channel affine transform parameter vectors)。

通过有偏估计器 (biased estimator) 计算标准差,相当于 torch.var(input, unbiased=False)

该层在训练和评估模式下都使用从输入计算的统计数据。

参数:
  • num_groups (int): 将通道分成的组数

  • num_channels (int): 输入中预期的通道数

  • eps (float, 可选): 为数值稳定性而添加到分母的值。默认:1e-5

  • affine (bool, 可选): 如果为 True ,该模块具有可学习逐通道仿射变换参数,并初始化为 1 (对于权重)和 0(对于偏差)。默认: True

形状:
  • Input: \((N, C, *)\) 其中 \(C=\text{num_channels}\)

  • Output: \((N, C, *)\) (与输入形状相同)

示例:

>>> import oneflow as flow

>>> input = flow.randn(20, 6, 10, 10)
>>> # 将 6 个通道分成 3 组
>>> m = flow.nn.GroupNorm(3, 6)
>>> # 将6个通道分成6组(相当于InstanceNorm)
>>> m = flow.nn.GroupNorm(6, 6)
>>> # 将所有 6 个通道放在一个组中(相当于 LayerNorm)
>>> m = flow.nn.GroupNorm(1, 6)
>>> # 激活模块
>>> output = m(input)
class oneflow.nn.Hardshrink(lambd: float = 0.5, inplace: bool = False)

The Hardshrink activation.

The formula is:

\[\begin{split}\text{Hardshrink}(x) = \begin{cases} x, & \text{ if } x > \lambda \\ x, & \text{ if } x < -\lambda \\ 0, & \text{ otherwise } \end{cases}\end{split}\]
Parameters
  • lambd – the \(\lambda\) value for the Hardshrink formulation. Default: 0.5

  • inplace – can optionally do the operation in-place. Default: False

Shape:
  • Input: \((N, *)\) where * means, any number of additional dimensions

  • Output: \((N, *)\), same shape as the input

For example:

>>> import numpy as np
>>> import oneflow as flow
>>> x = np.array([-1.1, 0, 0.2, 0.5]).astype(np.float32)
>>> input = flow.Tensor(x)
>>> hardshrink = flow.nn.Hardshrink(lambd=0.5)
>>> out = hardshrink(input)
>>> out
tensor([-1.1000,  0.0000,  0.0000,  0.0000], dtype=oneflow.float32)
class oneflow.nn.Hardsigmoid(inplace=False)

应用逐元素公式:

\[\begin{split}\text{Hardsigmoid}(x) = \begin{cases} 0 & \text{ if } x \le -3 \\ 1 & \text{ if } x \ge +3 \\ \frac{x}{6} + \frac{1}{2} & \text{ otherwise } \\ \end{cases}\end{split}\]
参数:
  • inplace (bool): 是否进行 in-place 操作。默认: False

形状:
  • Input : \((N, *)\) 其中 * 表示任意数量的额外维度

  • Output : \((N, *)\), 与输入相同的形状

示例:

>>> import oneflow as flow

>>> input = flow.tensor([-0.5, 0, 0.5], dtype=flow.float32)
>>> hardsigmoid = flow.nn.Hardsigmoid()

>>> out = hardsigmoid(input)
>>> out
tensor([0.4167, 0.5000, 0.5833], dtype=oneflow.float32)
class oneflow.nn.Hardswish(inplace=False)

如论文 Searching for MobileNetV3 中所述,逐元素应用 Hardswish 函数。

公式为:

\[\begin{split}\text{Hardswish}(x) = \begin{cases} 0 & \text{ if } x \le -3 \\ x & \text{ if } x \ge +3 \\ x*(x+3)/6 & \text{ otherwise } \\ \end{cases}\end{split}\]
参数:
  • inplace (bool, 可选): 是否执行 in-place 操作。默认: False

形状:
  • Input : \((N, *)\) 其中 * 表示任意数量的额外维度

  • Output : \((N, *)\) 与输入形状相同

>>> import oneflow as flow

>>> input = flow.tensor([-0.5, 0, 0.5], dtype=flow.float32)
>>> hardswish = flow.nn.Hardswish()

>>> out = hardswish(input)
>>> out
tensor([-0.2083,  0.0000,  0.2917], dtype=oneflow.float32)
class oneflow.nn.Hardtanh(min_val=- 1, max_val=1, inplace=False, min_value=None, max_value=None)

逐元素应用 HardTanh 函数。

公式为:

\[\begin{split}\text{HardTanh}(x) = \begin{cases} 1 & \text{ if } x > 1 \\ -1 & \text{ if } x < -1 \\ x & \text{ otherwise } \\ \end{cases}\end{split}\]

可以使用参数 min_valmax_val 调整线性区域的范围 \([-1, 1]\)

参数:
  • min_val (float): 线性区域范围的最小值。默认:-1

  • max_val (float): 线性区域范围的最大值。默认:1

  • inplace (bool): 是否执行 in-place 操作。默认: False

关键词参数: min_valuemax_value 已被弃用,由 min_valmax_val 替代。

形状:
  • Input : \((N, *)\) 其中 * 表示任意数量的额外维度

  • Output : \((N, *)\) 与输入形状相同

示例:

>>> import oneflow as flow

>>> m = flow.nn.Hardtanh()
>>> x = flow.tensor([0.2, 0.3, 3.0, 4.0],dtype=flow.float32)
>>> out = m(x)
>>> out
tensor([0.2000, 0.3000, 1.0000, 1.0000], dtype=oneflow.float32)
class oneflow.nn.Identity(*args, **kwargs)

对参数不敏感的占位符标识运算符。

示例:
  • args : 任何参数(未使用)

  • kwargs : 任何关键词参数(未使用)

示例:

import oneflow as flow

m = flow.nn.Identity()
input = flow.rand(2, 3, 4, 5)

output = m(input)

# output = input
class oneflow.nn.InstanceNorm1d(num_features, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)

此接口与 PyTorch 一致。可以在 https://pytorch.org/docs/stable/generated/torch.nn.InstanceNorm1d.html 参考相关文档。

将实例归一化 (Instance Normalization) 应用于 3D 输入(具有可选附加通道维度的小批量 1D 输入),行为如论文 Instance Normalization: The Missing Ingredient for Fast Stylization 所述。

公式为:

\[y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta\]

逐维度小批量单独计算均值和标准差。 如果 affineTrue\(\gamma\)\(\beta\) 是大小为 C 的可学习参数向量(其中 C 是输入大小)。 标准差是通过有偏估计器 (biased estimator) 计算的,相当于 torch.var(input, unbiased=False)

默认情况下,该层在训练和评估模式下都使用从输入数据计算的实例统计信息。

如果 track_running_statsTrue ,在训练期间,该层会不断计算均值和方差的估计值, 然后在评估期间将其用于归一化 (normalization) 。运行期间 momentum 为 0.1 。

Note

参数 momentum 与优化器 (optimizer) 中使用的参数和传统的动量 (momentum) 概念都不同。 在数学上,这里运行统计的更新规则是 \(\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momentum} \times x_t\) , 其中 \(\hat{x}\) 是估计的统计量,\(x_t\) 是新的观察值。

Note

尽管 InstanceNorm1dLayerNorm 非常相似,但有一些细微的区别。 InstanceNorm1d 应用于多维时间序列等通道数据的每个通道,但 LayerNorm 通常应用于整个样本,并且经常应用于 NLP 任务。此外, LayerNorm 应用逐元素仿射变换, 而 InstanceNorm1d 通常不应用仿射变换。

参数:
  • num_features (int): 来自大小为 \((N, C, L)\) 的预期输入的 \(C\) 或者来自大小为 \((N, L)\) 的预期输入的 \(L\)

  • eps (float): 为数值稳定性而添加到分母的值。默认:1e-5

  • momentum (float): 用于计算 running_mean 和 running_var 。默认:0.1

  • affine (bool): 如果为 True ,该模块具有可学习的仿射参数 (learnable affine parameters) ,初始化方式与批量标准化 (batch normalization) 相同。默认: False

  • track_running_stats (bool): 如果为 True ,该模块记录运行均值和方差,如果为 True ,该模块不记录运行均值和方差,并且始终在训练和评估模式下都使用批处理该类统计信息。默认: False

形状:
  • Input : \((N, C, L)\)

  • Output : \((N, C, L)\) (与输入相同)

示例:

>>> import oneflow as flow

>>> # 没有可学习的参数
>>> m = flow.nn.InstanceNorm1d(100)
>>> # 有可学习的参数
>>> m = flow.nn.InstanceNorm1d(100, affine=True)
>>> x = flow.randn(20, 100, 40)
>>> output = m(x)
class oneflow.nn.InstanceNorm2d(num_features, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)

此接口与 PyTorch 一致。可以在 https://pytorch.org/docs/stable/generated/torch.nn.InstanceNorm1d.html 参考相关文档。

将实例归一化 (Instance Normalization) 应用于 4D 输入(具有可选附加通道维度的小批量 2D 输入),行为如论文 Instance Normalization: The Missing Ingredient for Fast Stylization 所述。

公式为:

\[y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta\]

逐维度小批量单独计算均值和标准差。 如果 affineTrue\(\gamma\)\(\beta\) 是大小为 C 的可学习参数向量(其中 C 是输入大小)。 标准差是通过有偏估计器 (biased estimator) 计算的,相当于 torch.var(input, unbiased=False)

默认情况下,该层在训练和评估模式下都使用从输入数据计算的实例统计信息。

如果 track_running_statsTrue ,在训练期间,该层会不断计算均值和方差的估计值, 然后在评估期间将其用于归一化 (normalization) 。运行期间 momentum 为 0.1 。

Note

参数 momentum 与优化器 (optimizer) 中使用的参数和传统的动量 (momentum) 概念都不同。 在数学上,这里运行统计的更新规则是 \(\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momentum} \times x_t\) , 其中 \(\hat{x}\) 是估计的统计量,\(x_t\) 是新的观察值。

Note

尽管 InstanceNorm2dLayerNorm 非常相似,但有一些细微的区别。 InstanceNorm2d 应用RGB图像等通道数据的每个通道,但 LayerNorm 通常应用于整个样本,并且经常应用于 NLP 任务。此外, LayerNorm 应用逐元素仿射变换, 而 InstanceNorm2d 通常不应用仿射变换。

参数:
  • num_features (int): 来自大小为 \((N, C, H, W)\) 的预期输入的 \(C\)

  • eps (float): 为数值稳定性而添加到分母的值。默认:1e-5

  • momentum (float): 用于计算 running_mean 和 running_var 。默认:0.1

  • affine (bool): 如果为 True ,该模块具有可学习的仿射参数 (learnable affine parameters) ,初始化方式与批量标准化 (batch normalization) 相同。默认: False

  • track_running_stats (bool): 如果为 True ,该模块记录运行均值和方差,如果为 True ,该模块不记录运行均值和方差,并且始终在训练和评估模式下都使用批处理该类统计信息。默认: False

形状:
  • Input : \((N, C, H, W)\)

  • Output : \((N, C, H, W)\) (与输入相同)

示例:

>>> import oneflow as flow

>>> # 没有可学习的参数
>>> m = flow.nn.InstanceNorm1d(100)
>>> # 有可学习的参数
>>> m = flow.nn.InstanceNorm1d(100, affine=True)
>>> x = flow.randn(20, 100, 40)
>>> output = m(x)
class oneflow.nn.InstanceNorm3d(num_features, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)

此接口与 PyTorch 一致。可以在 https://pytorch.org/docs/stable/generated/torch.nn.InstanceNorm1d.html 参考相关文档。

将实例归一化 (Instance Normalization) 应用于 5D 输入(具有可选附加通道维度的小批量 3D 输入),行为如论文 Instance Normalization: The Missing Ingredient for Fast Stylization 所述。

公式为:

\[y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta\]

逐维度小批量单独计算均值和标准差。 如果 affineTrue\(\gamma\)\(\beta\) 是大小为 C 的可学习参数向量(其中 C 是输入大小)。 标准差是通过有偏估计器 (biased estimator) 计算的,相当于 torch.var(input, unbiased=False)

默认情况下,该层在训练和评估模式下都使用从输入数据计算的实例统计信息。

如果 track_running_statsTrue ,在训练期间,该层会不断计算均值和方差的估计值, 然后在评估期间将其用于归一化 (normalization) 。运行期间 momentum 为 0.1 。

Note

参数 momentum 与优化器 (optimizer) 中使用的参数和传统的动量 (momentum) 概念都不同。 在数学上,这里运行统计的更新规则是 \(\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momentum} \times x_t\) , 其中 \(\hat{x}\) 是估计的统计量,\(x_t\) 是新的观察值。

Note

尽管 InstanceNorm3dLayerNorm 非常相似,但有一些细微的区别。 InstanceNorm3d 应用于具有RGB颜色的3D模型等通道数据的每个通道,但 LayerNorm 通常应用于整个样本,并且经常应用于 NLP 任务。此外, LayerNorm 应用逐元素仿射变换, 而 InstanceNorm3d 通常不应用仿射变换。

参数:
  • num_features (int): 来自大小为 \((N, C, D, H, W)\) 的预期输入的 \(C\)

  • eps (float): 为数值稳定性而添加到分母的值。默认:1e-5

  • momentum (float): 用于计算 running_mean 和 running_var 。默认:0.1

  • affine (bool): 如果为 True ,该模块具有可学习的仿射参数 (learnable affine parameters) ,初始化方式与批量标准化 (batch normalization) 相同。默认: False

  • track_running_stats (bool): 如果为 True ,该模块记录运行均值和方差,如果为 True ,该模块不记录运行均值和方差,并且始终在训练和评估模式下都使用批处理该类统计信息。默认: False

形状:
  • Input : \((N, C, D, H, W)\)

  • Output : \((N, C, D, H, W)\) (与输入相同)

示例:

>>> import oneflow as flow

>>> # 没有可学习的参数
>>> m = flow.nn.InstanceNorm3d(100)
>>> # 有可学习的参数
>>> m = flow.nn.InstanceNorm3d(100, affine=True)
>>> x = flow.randn(20, 100, 35, 45, 10)
>>> output = m(x)
class oneflow.nn.KLDivLoss(reduction='mean', log_target=False)

此接口与 PyTorch 一致。文档参考自: https://pytorch.org/docs/stable/generated/torch.nn.KLDivLoss.html?highlight=kldivloss#torch.nn.KLDivLoss

此算子测量 KL 散度。 Kullback-Leibler divergence 可用于连续分布中的距离测量,并且在对连续输出分布的空间(离散采样)执行直接回归时通常很有效。与 NLLLoss 一样, input 应包含 log-probabilities 并且不限于 2D tensor。默认情况下,目标被解释为 probabilities ,但可以将其视为将 log_target 设置为 Truelog-probabilities

此 criterion 要求 targetTensor 的形状与 inputTensor 一致。未简化 (即 reduction 设置为 'none' ) 的损失可以描述为:

\[l(x,y) = L = \{ l_1,\dots,l_N \}, \quad l_n = y_n \cdot \left( \log y_n - x_n \right)\]

其中索引 \(N\) span input 的所有维度,并且 \(L\) 具有与 input 相同的形状。 如果 reduction 不为 'none' (默认 'mean' ),则:

\[\begin{split}\ell(x, y) = \begin{cases} \operatorname{mean}(L), & \text{if reduction} = \text{`mean';} \\ \operatorname{sum}(L), & \text{if reduction} = \text{`sum'.} \end{cases}\end{split}\]

如果 reduction 为默认值 'mean' ,每个 minibatch 的损失在 observations 和维度上取平均值。 如果 reduction'batchmean' ,可以得到正确的 KL 散度,其中损失仅在批次维度上进行平均。 'mean' 模式的行为将在下一个主要版本中更改为与 'batchmean' 相同。

参数:
  • reduction (string, 可选的): 指定应用于输出的简化(可以为 'none''batchmean''sum''mean' ,默认: 'mean' ):
    • 'none' :不会进行简化

    • 'batchmean' :输出的总和将除以 batchsize 。

    • 'sum' :将输出求和。

    • 'mean' :输出和将除以输出中的元素数。

  • log_target (bool, 可选的): 指定是否在 log space 中传递 target。默认: False

Note

reduction = 'mean' 时不会返回真正的 KL 散度值,请使用符合 KL 数学定义的 reduction = 'batchmean' 。 在下一个主要版本中,'mean' 将更改为与 'batchmean' 相同。

形状:
  • Input : \((N, *)\) 其中 \(*\) 表示任意数量的额外维度

  • Target : \((N, *)\),与输入的形状相同

  • Output : 默认为标量。如果 :attr:reduction'none' ,则为 \((N, *)\),形状与输入相同

示例:

>>> import oneflow as flow
>>> input = flow.tensor([-0.9021705, 0.08798598, 1.04686249], dtype=flow.float32)
>>> target = flow.tensor([1.22386942, -0.89729659, 0.01615712], dtype=flow.float32)
>>> m = flow.nn.KLDivLoss(reduction="none", log_target=False)
>>> out = m(input, target)
>>> out
tensor([ 1.3514,  0.0000, -0.0836], dtype=oneflow.float32)
>>> m = flow.nn.KLDivLoss(reduction="mean", log_target=False)
>>> out = m(input, target)
>>> out
tensor(0.4226, dtype=oneflow.float32)
>>> m = flow.nn.KLDivLoss(reduction="sum", log_target=True)
>>> out = m(input, target)
>>> out
tensor(5.7801, dtype=oneflow.float32)
class oneflow.nn.L1Loss(reduction='mean')

此运算符计算 inputtarget 中每个元素之间的 L1 Loss 。

公式为:

如果 reduction = “none”:

\[output = |Target - Input|\]

如果 reduction = “mean”:

\[output = \frac{1}{n}\sum_{i=1}^n|Target_i - Input_i|\]

如果 reduction = “sum”:

\[output = \sum_{i=1}^n|Target_i - Input_i|\]
参数:
  • input (Tensor): 输入张量。

  • target (Tensor): 目标张量。

  • reduction (str): 简化类型,可以为 "none""mean""sum" 。默认为 “mean” 。

返回类型:

oneflow.tensor

示例:

>>> import oneflow as flow
>>> input = flow.tensor([[1, 1, 1], [2, 2, 2], [7, 7, 7]], dtype = flow.float32)
>>> target = flow.tensor([[4, 4, 4], [4, 4, 4], [4, 4, 4]], dtype = flow.float32)
>>> m = flow.nn.L1Loss(reduction="none")
>>> out = m(input, target)
>>> out
tensor([[3., 3., 3.],
        [2., 2., 2.],
        [3., 3., 3.]], dtype=oneflow.float32)
>>> m_mean = flow.nn.L1Loss(reduction="mean")
>>> out = m_mean(input, target)
>>> out
tensor(2.6667, dtype=oneflow.float32)
>>> m_mean = flow.nn.L1Loss(reduction="sum")
>>> out = m_mean(input, target)
>>> out
tensor(24., dtype=oneflow.float32)
class oneflow.nn.LayerNorm(normalized_shape, eps=1e-05, elementwise_affine=True)

对小批量输入应用层归一化 (Layer Normalization) ,行为如论文 Layer Normalization 所述。

\[y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta\]

在特定数字维度上分别计算均值和标准差,这些维度的形状必须由:attr:normalized_shape 指定。 如果 elementwise_affineTrue ,则 \(\gamma\)\(\beta\) 是 参数 normalized_shape 的可学习仿射变换参数。标准差是通过有偏估计器 (biased estimator) 计算的。

Note

与批量归一化 (Batch Normalization) 和实例归一化 (Instance Normalization) 使用 affine 选项为每个完整通道/平面应用标量 scale 和偏差不同,层归一化 (Layer Normalization) 使用 elementwise_affine 处理每个元素的 scale 和偏差。

该层在训练和评估模式下都使用从输入数据计算的统计信息。

参数:
  • normalized_shape (int 或 list 或 oneflow.Size): 来自预期大小输入的输入形状,如果使用单个整数,则将其视为单例列表,并且此模块将对最后一个维度进行标准化,该维度预计具有该特定大小。

    \[[* \times \text{normalized_shape}[0] \times \text{normalized_shape}[1] \times \ldots \times \text{normalized_shape}[-1]]\]
  • eps (float, 可选的): 为数值稳定性而添加到分母的值。默认:1e-5

  • elementwise_affine (bool, 可选的): 如果为 True ,该模块具有可学习的逐元素仿射参数,

    并且将他们初始化为 1 (对于权重)和 0(对于偏差)。默认值: True

形状:
  • Input : \((N, *)\)

  • Output : \((N, *)\) (形状与输入相同)

示例:

>>> import oneflow as flow

>>> x = flow.tensor([[[[-0.16046895, -1.03667831], [-0.34974465, 0.26505867]],[[-1.24111986, -0.53806001], [1.72426331, 0.43572459]],],[[[-0.77390957, -0.42610624], [0.16398858, -1.35760343]],[[1.07541728, 0.11008703], [0.26361224, -0.48663723]]]], dtype=flow.float32)
>>> m = flow.nn.LayerNorm(2)
>>> m(x) 
tensor([[[[ 1.0000, -1.0000],
          [-0.9999,  0.9999]],

         [[-1.0000,  1.0000],
          [ 1.0000, -1.0000]]],


        [[[-0.9998,  0.9998],
          [ 1.0000, -1.0000]],

         [[ 1.0000, -1.0000],
          [ 1.0000, -1.0000]]]], dtype=oneflow.float32,
       grad_fn=<broadcast_add_backward>)
elementwise_affine: bool
eps: float
normalized_shape: Tuple[int, ]
class oneflow.nn.LeakyReLU(negative_slope: float = 0.01, inplace: bool = False)

逐元素地应用如下公式:

\[\begin{split}\text{LeakyRELU}(x) = \begin{cases} x, & \text{ if } x \geq 0 \\ \text{negative_slope} \times x, & \text{ otherwise } \end{cases}\end{split}\]
参数:
  • negative_slope - 控制负斜率的角度。默认值为 1e-2。

  • inplace - 可以选择以 in-place 的方式执行操作。默认值为 False

形状:
  • Input - \((N, *)\) ,其中 * 表示任意数量的附加维度。

  • Output - \((N, *)\) ,与输入的形状相同。

示例:

>>> import numpy as np
>>> import oneflow as flow

>>> m = flow.nn.LeakyReLU(0.1)
>>> arr = np.array([0.2, 0.3, 3.0, 4.0])
>>> x = flow.Tensor(arr)
>>> out = m(x)
>>> out
tensor([0.2000, 0.3000, 3.0000, 4.0000], dtype=oneflow.float32)
class oneflow.nn.Linear(in_features: int, out_features: int, bias: bool = True)

对输入数据应用线性变换: \(y = xA^T + b\)

参数:
  • in_features - 每一个输入样本的大小。

  • out_features - 每一个输出样本的大小。

  • bias - 若设置为 False ,则该层不会学习附加偏差。默认值为 True

形状:
  • Input: \((N, *, H_{in})\) ,其中 * 表示任意数量的附加维度,且 \(H_{in} = {in\_features}\)

  • Output: \((N, *, H_{out})\) ,其中除了最后一个维度之外的所有维度都与输入的形状相同,且 \(H_{out} = {out\_features}\)

属性:
  • weight: 形状为 \(({out\_features}, {in\_features})\) 的模块的可学习参数。这些值通过 \(\mathcal{U}(-\sqrt{k}, \sqrt{k})\) 初始化,其中 \(k = 1 / {in\_features}\)

  • bias: 形状为 \(({out\_features})\) 的模块的可学习参数。若 bias = True ,则这些值通过 \(\mathcal{U}(-\sqrt{k}, \sqrt{k})\) 初始化,其中 \(k = 1 / {in\_features}\)

示例:

>>> import numpy as np
>>> import oneflow as flow


>>> m = flow.nn.Linear(20, 30, False)
>>> input = flow.Tensor(np.random.randn(128, 20))
>>> output = m(input)
>>> output.size()
oneflow.Size([128, 30])
class oneflow.nn.LogSigmoid

逐元素地应用如下公式:

\[\text{LogSigmoid}(x) = \log\left(\frac{ 1 }{ 1 + \exp(-x)}\right)\]
形状:
  • Input: \((N, *)\) ,其中 * 表示任意数量的附加维度。

  • Output: \((N, *)\) ,与输入的形状相同。

示例:

>>> import numpy as np
>>> import oneflow as flow

>>> x = np.array([-0.5, 0, 0.5]).astype(np.float32)
>>> input = flow.Tensor(x)
>>> logsigmoid = flow.nn.LogSigmoid()

>>> out = logsigmoid(input)
>>> out
tensor([-0.9741, -0.6931, -0.4741], dtype=oneflow.float32)
class oneflow.nn.LogSoftmax(dim: Optional[int] = None)

对一个 n 维输入张量应用 LogSoftmax 公式,它可以被简化为:

\[\text{LogSoftmax}(x_{i}) = \log\left(\frac{\exp(x_i) }{ \sum_j \exp(x_j)} \right) = x_i - \log({ \sum_j \exp(x_j)})\]
参数:
  • dim (int) - LogSoftmax 计算的维度。

形状:
  • Input: \((N, *)\) ,其中 * 表示任意数量的附加维度。

  • Output: \((N, *)\) ,与输入的形状相同。

示例:

>>> import numpy as np
>>> import oneflow as flow

>>> m = flow.nn.LogSoftmax(dim=1)
>>> x = flow.Tensor(
...    np.array(
...        [[ 0.4296, -1.1957,  2.5463],
...        [ 1.2552, -1.5747,  0.6923]]
...    )
... )
>>> out = m(x)
>>> out
tensor([[-2.2513, -3.8766, -0.1346],
        [-0.4877, -3.3176, -1.0506]], dtype=oneflow.float32)
class oneflow.nn.MSELoss(reduction: str = 'mean')

此接口与 PyTorch 一致,文档参考自: https://pytorch.org/docs/stable/generated/torch.nn.MSELoss.html?highlight=mseloss#torch.nn.MSELoss

创建一个指标来测量输入 \(x\) 和目标 \(y\) 中每个元素之间的均方误差(平方 L2 范数)。

未规约的损失(如将 reduction 设置为 'none')可被描述为:

\[\ell(x, y) = L = \{l_1,\dots,l_N\}^\top, \quad l_n = \left( x_n - y_n \right)^2,\]

其中 \(N\) 是每个批量的大小。如果 reduction 不是 'none' (默认值为 'mean'),则有

\[\begin{split}\ell(x, y) = \begin{cases} \operatorname{mean}(L), & \text{if reduction} = \text{`mean';}\\ \operatorname{sum}(L), & \text{if reduction} = \text{`sum'.} \end{cases}\end{split}\]

\(x\)\(y\) 是任意形状的张量,每个都有 \(n\) 个元素。平均运算对所有元素进行操作,除以 \(n\) 。如果设置 reduction = 'sum',则可以避免除以 \(n\) 的行为。

参数:
  • reduction (string, optional) - 指定应用于输出的规约操作: 'none' | 'mean' | 'sum' 。若为 'none' :不进行规约;'mean' :输出的和将会除以输出中的元素数量; 'sum' :输出将被求和。默认为 'mean'

形状:
  • Input: \((N, *)\) ,其中 * 表示任意数量的附加维度。

  • Output: \((N, *)\) ,与输入的形状相同。

示例:

>>> import oneflow as flow
>>> import numpy as np
>>> input = flow.tensor(
... [[-0.02557137, 0.03101675, 1.37493674],
... [0.25599439, -1.08372561, -0.21006816]], dtype=flow.float32)
>>> target = flow.tensor(
... [[-1.53105064, -0.68137555, 0.5931354],
... [-0.49158347, 0.93673637, 0.1324141]], dtype=flow.float32)
>>> m = flow.nn.MSELoss(reduction="none")
>>> out = m(input, target)
>>> out
tensor([[2.2665, 0.5075, 0.6112],
        [0.5589, 4.0823, 0.1173]], dtype=oneflow.float32)
>>> m = flow.nn.MSELoss(reduction="mean")
>>> out = m(input, target)
>>> out
tensor(1.3573, dtype=oneflow.float32)
>>> m = flow.nn.MSELoss(reduction="sum")
>>> out = m(input, target)
>>> out
tensor(8.1436, dtype=oneflow.float32)
class oneflow.nn.MarginRankingLoss(margin: float = 0.0, reduction: str = 'mean')

根据给定的输入 \(x1\), \(x2\) ,两个一维小批量 Tensors ,以及一个带标签的一维小批量张量 \(y\) (包含 1 或 -1),创建一个指标来测量损失。

\(y = 1\) 则假定第一个输入的 rank 比第二个输入更高, \(y = -1\) 反之亦然。

小批量中每个样本的损失函数为:

\[\text{loss}(x1, x2, y) = \max(0, -y * (x1 - x2) + \text{margin})\]
参数:
  • margin (float, optional) - 默认为 \(0\)

  • reduction (string, optional) - 指定应用于输出的规约操作: 'none' | 'mean' | 'sum' 。若为 'none' :不进行规约;'mean' :输出的和将会除以输出中的元素数量; 'sum' :输出将被求和。默认为 'mean'

形状:
  • x1 : \((N, D)\) ,其中 N 是批量大小, D 是样本大小。

  • x2 : \((N, D)\) ,其中 N 是批量大小, D 是样本大小。

  • Target : \((N)\)

  • Output : 若 reduction = 'none' ,那么输出为 \((N)\) ,否则为标量。

示例:

>>> import oneflow as flow
>>> import numpy as np
>>> x1 = flow.tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), dtype=flow.float32)
>>> x2 = flow.tensor(np.array([[2, 2, 2], [2, 2, 2], [2, 2, 2]]), dtype=flow.float32)
>>> target = flow.tensor(np.array([[1, -1, 1],[-1, 1, -1], [1, 1, 1]]), dtype=flow.float32)
>>> m = flow.nn.MarginRankingLoss(margin =1.0, reduction="none")
>>> out = m(x1, x2, target)
>>> out
tensor([[2., 1., 0.],
        [3., 0., 5.],
        [0., 0., 0.]], dtype=oneflow.float32)

>>> m = flow.nn.MarginRankingLoss(margin = 0.3, reduction="sum")
>>> out = m(x1, x2, target)
>>> out
tensor(8.2000, dtype=oneflow.float32)

>>> m = flow.nn.MarginRankingLoss(margin = 10, reduction="mean")
>>> out = m(x1, x2, target)
>>> out
tensor(8.3333, dtype=oneflow.float32)
class oneflow.nn.MaxPool1d(kernel_size: Union[int, Tuple[int]], stride: Optional[Union[int, Tuple[int]]] = None, padding: Union[int, Tuple[int]] = 0, dilation: Union[int, Tuple[int]] = 1, return_indices: bool = False, ceil_mode: bool = False)

此接口与 PyTorch 一致,文档参考自: https://pytorch.org/docs/stable/generated/torch.nn.MaxPool1d.html#torch.nn.MaxPool1d

在一个由多个输入平面组成的输入信号上应用 1D max pooling

在最简单的情况下,若输入大小为 \((N, C, L)\) 和输出大小为 \((N, C, L_{out})\) ,则该层的输出值可以被准确描述为:

\[out(N_i, C_j, k) = \max_{m=0, \ldots, \text{kernel_size} - 1} input(N_i, C_j, stride \times k + m)\]

padding 不为零,则在输入的两侧用最小值隐式地填充 padding 个点。 dilation 是滑动窗口中元素之间的跨步。这个 链接 中有 dilation 的可视化展示。

Note

若 ceil_mode = True 且滑动窗口从左侧填充区域或输入中开始,则允许其越界。从右侧填充区域开始的滑动窗口将被忽略。

参数:
  • kernel_size - 滑动窗口的大小,必须为正。

  • stride - 滑动窗口的步长,必须为正。默认值为 kernel_size

  • padding - 填充在输入张量两侧的隐式负无穷,该值必须非负且不大于 kernel_size / 2。

  • dilation - 滑动窗口中元素之间的步幅,必须为正。

  • return_indices - 若设置为 True 则返回 argmax 以及最大值。

  • ceil_mode - 若设置为 True 则使用 ceil 而非 floor 来计算输出形状,这确保了输入张量中的每个元素都被滑动窗口覆盖。

形状:
  • Input: \((N, C, L_{in})\)

  • Output: \((N, C, L_{out})\) ,其中

    \[L_{out} = \left\lfloor \frac{L_{in} + 2 \times \text{padding} - \text{dilation} \times (\text{kernel_size} - 1) - 1}{\text{stride}} + 1\right\rfloor\]

示例:

import oneflow as flow
import numpy as np

of_maxpool1d = flow.nn.MaxPool1d(kernel_size=3, padding=1, stride=1)
x = flow.Tensor(np.random.randn(1, 4, 4))
y = of_maxpool1d(x)
y.shape
oneflow.Size([1, 4, 4])
class oneflow.nn.MaxPool2d(kernel_size: Union[int, Tuple[int, int]], stride: Optional[Union[int, Tuple[int, int]]] = None, padding: Union[int, Tuple[int, int]] = 0, dilation: Union[int, Tuple[int, int]] = 1, return_indices: bool = False, ceil_mode: bool = False)

此接口与 PyTorch 一致,文档参考自: https://pytorch.org/docs/stable/generated/torch.nn.MaxPool2d.html#torch.nn.MaxPool2d

在一个由多个输入平面组成的输入信号上应用 2D max pooling

在最简单的情况下,若输入大小为 \((N, C, H, W)\) ,输出大小为 \((N, C, H_{out}, W_{out})\)kernel_size\((kH, kW)\) ,则该层的输出值可以被准确描述为:

\[\begin{split}\begin{aligned} out(N_i, C_j, h, w) ={} & \max_{m=0, \ldots, kH-1} \max_{n=0, \ldots, kW-1} \\ & \text{input}(N_i, C_j, \text{stride[0]} \times h + m, \text{stride[1]} \times w + n) \end{aligned}\end{split}\]

padding 不为零,则在输入的两侧用最小值隐式地填充 padding 个点。 dilation 控制了核点之间的空间。这个 链接 中有 dilation 的可视化展示。

Note

若 ceil_mode = True 且滑动窗口从左侧填充区域或输入中开始,则允许其越界。从右侧填充区域开始的滑动窗口将被忽略。

参数 kernel_size, stride, padding, dilation 可以是:
  • 一个单独的 int – 在这种情况下,高度和宽度维度使用相同的值。

  • 一个由两个 int 组成的 tuple – 在这种情况下,第一个整数用于高度维度,第二个整数用于宽度维度。

参数:
  • kernel_size - 窗口的最大尺寸。

  • stride - 滑动窗口的步长,必须为正。默认值为 kernel_size

  • padding - 要添加在两侧的隐式最小填充。

  • dilation - 滑动窗口中元素之间的步幅,必须为正。

  • return_indices - 若设置为 True ,则返回最大索引和输出,在后续的 torch.nn.MaxUnpool2d 中使用。

  • ceil_mode - 若设置为 True 则使用 ceil 而非 floor 来计算输出形状。

形状:
  • Input: \((N, C, H_{in}, W_{in})\)

  • Output: \((N, C, H_{out}, W_{out})\) ,其中

    \[H_{out} = \left\lfloor\frac{H_{in} + 2 * \text{padding[0]} - \text{dilation[0]} \times (\text{kernel_size[0]} - 1) - 1}{\text{stride[0]}} + 1\right\rfloor\]
    \[W_{out} = \left\lfloor\frac{W_{in} + 2 * \text{padding[1]} - \text{dilation[1]} \times (\text{kernel_size[1]} - 1) - 1}{\text{stride[1]}} + 1\right\rfloor\]

示例:

import oneflow as flow
import numpy as np

m = flow.nn.MaxPool2d(kernel_size=3, padding=1, stride=1)
x = flow.Tensor(np.random.randn(1, 4, 4, 4))
y = m(x)
y.shape
oneflow.Size([1, 4, 4, 4])
class oneflow.nn.MaxPool3d(kernel_size: Union[int, Tuple[int, int, int]], stride: Optional[Union[int, Tuple[int, int, int]]] = None, padding: Union[int, Tuple[int, int, int]] = 0, dilation: Union[int, Tuple[int, int, int]] = 1, return_indices: bool = False, ceil_mode: bool = False)

此接口与 PyTorch 一致,文档参考自: https://pytorch.org/docs/stable/generated/torch.nn.MaxPool3d.html#torch.nn.MaxPool3d

在一个由多个输入平面组成的输入信号上应用 3D max pooling

在最简单的情况下,若输入大小为 \((N, C, D, H, W)\) ,输出大小为 \((N, C, D_{out}, H_{out}, W_{out})\)kernel_size\((kD, kH, kW)\) ,则该层的输出值可以被准确描述为:

\[\begin{split}\begin{aligned} \text{out}(N_i, C_j, d, h, w) ={} & \max_{k=0, \ldots, kD-1} \max_{m=0, \ldots, kH-1} \max_{n=0, \ldots, kW-1} \\ & \text{input}(N_i, C_j, \text{stride[0]} \times d + k, \text{stride[1]} \times h + m, \text{stride[2]} \times w + n) \end{aligned}\end{split}\]

padding 不为零,则在输入的两侧用最小值隐式地填充 padding 个点。 dilation 控制了核点之间的空间。这个 链接 中有 dilation 的可视化展示。

Note

若 ceil_mode = True 且滑动窗口从左侧填充区域或输入中开始,则允许其越界。从右侧填充区域开始的滑动窗口将被忽略。

参数 kernel_size, stride, padding, dilation 可以是:
  • 一个单独的 int – 在这种情况下,深度、高度和宽度维度使用相同的值。

  • 一个由三个 int 组成的 tuple – 在这种情况下,第一个整数用于深度维度,第二个整数用于高度维度,第三个整数用于宽度维度。

参数:
  • kernel_size - 窗口的最大尺寸。

  • stride - 滑动窗口的步长,必须为正。默认值为 kernel_size

  • padding - 要添加在三个边上的的隐式最小填充。

  • dilation - 滑动窗口中元素之间的步幅,必须为正。

  • return_indices - 若设置为 True ,则返回最大索引和输出,在后续的 torch.nn.MaxUnpool3d 中使用。

  • ceil_mode - 若设置为 True 则使用 ceil 而非 floor 来计算输出形状。

形状:
  • Input: \((N, C, D_{in}, H_{in}, W_{in})\)

  • Output: \((N, C, D_{out}, H_{out}, W_{out})\) ,其中

    \[D_{out} = \left\lfloor\frac{D_{in} + 2 \times \text{padding}[0] - \text{dilation}[0] \times (\text{kernel_size}[0] - 1) - 1}{\text{stride}[0]} + 1\right\rfloor\]
    \[H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{padding}[1] - \text{dilation}[1] \times (\text{kernel_size}[1] - 1) - 1}{\text{stride}[1]} + 1\right\rfloor\]
    \[W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{padding}[2] - \text{dilation}[2] \times (\text{kernel_size}[2] - 1) - 1}{\text{stride}[2]} + 1\right\rfloor\]

示例:

import oneflow as flow
import numpy as np

of_maxpool3d = flow.nn.MaxPool3d(kernel_size=3, padding=1, stride=1)
x = flow.Tensor(np.random.randn(1, 4, 4, 4, 4))
y = of_maxpool3d(x)
y.shape
oneflow.Size([1, 4, 4, 4, 4])
class oneflow.nn.MinMaxObserver(quantization_formula: str = 'google', quantization_bit: int = 8, quantization_scheme: str = 'symmetric', per_layer_quantization: bool = True)

计算输入张量的量化参数。

首先计算输入张量的最大值和最小值:

\[ \begin{align}\begin{aligned}& max\_value = max(input)\\& min\_value = min(input)\end{aligned}\end{align} \]

然后用以下等式计算 scale 和 zero_point :

若 quantization_scheme 为 “symmetric”:

\[ \begin{align}\begin{aligned}& denom = 2^{quantization\_to\_bit - 1} - 1\\& scale = max(|max\_value|,|min\_value|) / denom\\& zero\_point = 0\end{aligned}\end{align} \]

若 quantization_scheme 为 “affine”:

\[ \begin{align}\begin{aligned}& denom = 2^{quantization\_to\_bit} - 1\\& scale = (max\_value - min\_value) / denom\\& zero\_point = -min\_value / scale\end{aligned}\end{align} \]

若 per_layer_quantization 为 False,则 scale 和 zero_point 的形状将为 (input.shape[0],)

参数:
  • quantization_bit (int) - 量化输入为 uintX / intX,X 的值在 [2, 8] 中,默认值为 8。

  • quantization_scheme (str) - “symmetric” 或 “affine”,量化为有符号/无符号整数。默认值为 “symmetric”。

  • quantization_formula (str) - “google” 或 “cambricon”。

  • per_layer_quantization (bool) - 若设置为 True,则表示 per-layer,否则为 per-channel。默认值为 True。

返回值:

Tuple[oneflow.Tensor, oneflow.Tensor]: 输入张量的 scale 和 zero_point。

示例:

>>> import numpy as np
>>> import oneflow as flow

>>> weight = (np.random.random((2, 3, 4, 5)) - 0.5).astype(np.float32)

>>> input_tensor = flow.tensor(
...    weight, dtype=flow.float32
... )

>>> quantization_bit = 8
>>> quantization_scheme = "symmetric"
>>> quantization_formula = "google"
>>> per_layer_quantization = True

>>> min_max_observer = flow.nn.MinMaxObserver(quantization_formula=quantization_formula, quantization_bit=quantization_bit,
... quantization_scheme=quantization_scheme, per_layer_quantization=per_layer_quantization)

>>> scale, zero_point = min_max_observer(
...    input_tensor, )
class oneflow.nn.Mish(inplace: bool = False)

逐元素地应用如下公式:

\[\text{Mish}(x) = x * \text{Tanh}(\text{Softplus}(x))\]
形状:
  • Input: \((N, *)\) ,其中 * 表示任意数量的附加维度。

  • Output: \((N, *)\) ,与输入的形状相同。

示例:

>>> import numpy as np
>>> import oneflow as flow

>>> x = np.array([1, 2, 3]).astype(np.float32)
>>> input = flow.Tensor(x)
>>> mish = flow.nn.Mish()

>>> out = mish(input)
>>> out
tensor([0.8651, 1.9440, 2.9865], dtype=oneflow.float32)
class oneflow.nn.ModuleDict(modules: Optional[Mapping[str, oneflow.nn.module.Module]] = None)
class oneflow.nn.ModuleList(modules: Optional[Iterable[oneflow.nn.module.Module]] = None)
class oneflow.nn.MovingAverageMinMaxObserver(training: bool = False, quantization_formula: str = 'google', stop_update_after_iters: int = 0, quantization_bit: int = 8, quantization_scheme: str = 'symmetric', momentum: float = 0)

根据输入张量的最小值和最大值的移动平均计算量化参数。

首先计算输入张量的 moving_max 和 moving_min:

若 quantization_scheme 为 “symmetric”:

\[ \begin{align}\begin{aligned}& moving\_max = moving\_max * momentum + |max(input)| * (1 - momentum)\\& moving\_min = moving\_max\end{aligned}\end{align} \]

若 quantization_scheme 为 “affine”:

\[ \begin{align}\begin{aligned}& moving\_max = moving\_max * momentum + max(input) * (1 - momentum)\\& moving\_min = moving\_min * momentum + min(input) * (1 - momentum)\end{aligned}\end{align} \]

最小值和最大值的移动平均值被初始化为第一批输入 Blob 的最小值和最大值。

然后用以下等式计算 scale 和 zero_point:

若 quantization_scheme 为 “symmetric”:

\[ \begin{align}\begin{aligned}& denom = 2^{quantization\_to\_bit - 1} - 1\\& scale = moving\_max / denom\\& zero\_point = 0\end{aligned}\end{align} \]

若 quantization_scheme 为 “affine”:

\[ \begin{align}\begin{aligned}& denom = 2^{quantization\_to\_bit} - 1\\& scale = (moving\_max - moving\_min) / denom\\& zero\_point = -moving\_min / scale\end{aligned}\end{align} \]

Note

current_train_step 可以直接被赋值给一个优化器(例如 SGD)。

参数:
  • training (bool) - 模式是否处于训练状态,默认值为 False。

  • quantization_bit (int) - 量化输入为 uintX / intX,X 的值在 [2, 8] 中,默认值为 8。

  • quantization_scheme (str) - “symmetric” 或 “affine”,量化为有符号/无符号整数。默认值为 “symmetric”。

  • quantization_formula (str) - “google” 或 “cambricon”。

  • momentum (float) - 指数移动平均运算的平滑参数,默认值为 0.95。

返回值:

Tuple[oneflow.Tensor, oneflow.Tensor]: 输入张量的 scale 和 zero_point。

示例:

>>> import numpy as np
>>> import oneflow as flow

>>> weight = (np.random.random((2, 3, 4, 5)) - 0.5).astype(np.float32)

>>> input_tensor = flow.tensor(
...    weight, dtype=flow.float32
... )

>>> current_train_step_tensor = flow.tensor(
...   np.zeros((1,)).astype(np.float32),
...    dtype=flow.int64,
... )

>>> momentum = 0.95
>>> quantization_bit = 8
>>> quantization_scheme = "symmetric"
>>> quantization_formula = "google"

>>> moving_average_min_max_observer = flow.nn.MovingAverageMinMaxObserver(training=True, quantization_formula=quantization_formula,
...                                                                       stop_update_after_iters=1, quantization_bit=quantization_bit,
...                                                                       quantization_scheme=quantization_scheme, momentum=momentum,
...                                                                       )

>>> (scale, zero_point) = moving_average_min_max_observer(
...    input_tensor,
...    current_train_step_tensor,
... )
reset_running_stats()None
class oneflow.nn.NLLLoss(weight: Optional[oneflow.Tensor] = None, ignore_index: int = - 100, reduction: str = 'mean')

负对数似然损失,在 C 类训练分类问题中很有效。

通过前向调用给出的输入将包含每个类的对数概率。在 K 维情况下,输入必须是大小为 \((minibatch, C)\)\((minibatch, C, d_1, d_2, ..., d_K)\) 的张量且 \(K \geq 1\)

通过在网络的最后一层添加 LogSoftmax 层,可以直接得到神经网络中的对数概率。如果不想添加额外的层,可以改用 CrossEntropyLoss

该函数期望的 target 应为 \([0, C-1]\) 范围内的索引,其中 C = number of classes

未规约的损失(如将 reduction 设置为 'none')可被描述为:

\[\ell(x, y) = L = \{l_1,\dots,l_N\}^\top, \quad l_n = - w_{y_n} x_{n,y_n}, \quad w_{c} = \mathbb{1},\]

其中 \(x\) 是输入,\(y\) 是输出,\(w\) 是权重且 \(N\) 是批的大小。如果 reduction 不是 'none' (默认值为 'mean'),则有

\[\begin{split}\ell(x, y) = \begin{cases} \sum_{n=1}^N \frac{1}{N} l_n, & \text{if reduction} = \text{`mean';}\\ \sum_{n=1}^N l_n, & \text{if reduction} = \text{`sum'.} \end{cases}\end{split}\]

该函数也可用于更高维度的输入,例如 2D 图像,通过提供 大小为 \((minibatch, C, d_1, d_2, ..., d_K)\)\(K \geq 1\) 的输 入和一个形状合适的目标,其中 \(K\) 是维度数。在图像的情况下,它计 算每个像素的 NLL 损失。

参数:
  • reduction (string, optional) - 指定应用于输出的 reduction:'none' | 'mean' | 'sum'. 'none' :不进行 reduction;'mean' :取输出的加权平均值;'sum' :输出将被求和。默认值为 'mean'

示例:

>>> import oneflow as flow
>>> import numpy as np

>>> input = flow.tensor(
... [[-0.1664078, -1.7256707, -0.14690138],
... [-0.21474946, 0.53737473, 0.99684894],
... [-1.135804, -0.50371903, 0.7645404]], dtype=flow.float32)
>>> target = flow.tensor(np.array([0, 1, 2]), dtype=flow.int32)
>>> m = flow.nn.NLLLoss(reduction="none")
>>> out = m(input, target)
>>> out
tensor([ 0.1664, -0.5374, -0.7645], dtype=oneflow.float32)

>>> m = flow.nn.NLLLoss(reduction="sum")
>>> out = m(input, target)
>>> out
tensor(-1.1355, dtype=oneflow.float32)

>>> m = flow.nn.NLLLoss(reduction="mean")
>>> out = m(input, target)
>>> out
tensor(-0.3785, dtype=oneflow.float32)
class oneflow.nn.OFRecordBytesDecoder(blob_name: str, name: Optional[str] = None)

此算子将张量读取为字节,输出取决于下游任务,可能需要进一步的解码过程,比如 cv2.imdecode() 用于图像和解码,以及 decode(“utf-8”) 用于字符。

参数:
  • blob_name - OFRecord 目标特征的名称。

  • name - 图中此分量的名称。

  • input - 可能由 OFRecordReader 提供的张量。

返回值:

按字节编码后的张量。

示例:

>>> import numpy as np
>>> import oneflow as flow

>>> def example():
...      batch_size = 16
...      record_reader = flow.nn.OFRecordReader(
...         "dataset/",
...         batch_size=batch_size,
...         part_name_suffix_length=5,
...      )
...      val_record = record_reader()

...      bytesdecoder_img = flow.nn.OFRecordBytesDecoder("encoded")

...      image_bytes_batch = bytesdecoder_img(val_record)

...      image_bytes = image_bytes_batch.numpy()[0]
...      return image_bytes
... example()  
array([255 216 255 ...  79 255 217], dtype=uint8)
class oneflow.nn.OFRecordImageDecoder(blob_name: str, color_space: str = 'BGR')
class oneflow.nn.OFRecordImageDecoderRandomCrop(blob_name: str, color_space: str = 'BGR', num_attempts: int = 10, random_seed: Optional[int] = None, random_area: Sequence[float] = [0.08, 1.0], random_aspect_ratio: Sequence[float] = [0.75, 1.333333])
class oneflow.nn.OFRecordRawDecoder(blob_name: str, shape: Sequence[int], dtype: oneflow._oneflow_internal.dtype, dim1_varying_length: bool = False, truncate: bool = False, auto_zero_padding: bool = False, name: Optional[str] = None)
class oneflow.nn.OFRecordReader(ofrecord_dir: str, batch_size: int = 1, data_part_num: int = 1, part_name_prefix: str = 'part-', part_name_suffix_length: int = - 1, random_shuffle: bool = False, shuffle_buffer_size: int = 1024, shuffle_after_epoch: bool = False, random_seed: int = - 1, device: Optional[Union[oneflow._oneflow_internal.device, str]] = None, placement: Optional[oneflow._oneflow_internal.placement] = None, sbp: Optional[Union[oneflow._oneflow_internal.sbp.sbp, List[oneflow._oneflow_internal.sbp.sbp]]] = None, name: Optional[str] = None)
class oneflow.nn.PReLU(num_parameters: int = 1, init: float = 0.25, device=None, dtype=None)

逐元素地应用如下公式:

\[PReLU(x) = \max(0,x) + a * \min(0,x)\]

这里 \(a\) 是一个可学习的参数。当不带参数调用时, nn.PReLU() 在所有输入通道中使用单个参数 \(a\)。 若调用 nn.PReLU(nChannels) ,为每个通道使用单独的 \(a\)

Note

为了获得良好的性能,在学习 \(a\) 时不应使用权重衰减。

Note

通道维度是输入的第二维度。当输入维度不足 2 时,就不存在通道维度且通道数为 1。

参数:
  • num_parameters (int) - 需要学习的 \(a\) 的数量尽管它将一个 int 数值作为输入,但只有两类值是合法的: 1 或输入的通道数。默认值为 1。

  • init (float) - \(a\) 的初始值。默认值为 0.25。

形状:
  • Input: \((N, *)\) ,其中 * 表示任意数量的附加维度。

  • Output: \((N, *)\) ,与输入的形状相同。

属性:
  • weight (Tensor) - 形状为 (num_parameters) 的可学习权重。

>>> import numpy as np
>>> import oneflow as flow

>>> m = flow.nn.PReLU()
>>> input = flow.tensor(np.asarray([[[[1, -2], [3, 4]]]]), dtype=flow.float32)
>>> print(m(input).numpy())
[[[[ 1.  -0.5]
   [ 3.   4. ]]]]
class oneflow.nn.Parameter
class oneflow.nn.ParameterDict(parameters=None)
class oneflow.nn.ParameterList(parameters=None)
oneflow.nn.PixelShuffle

alias of oneflow.nn.modules.pixelshuffle.PixelShufflev2

class oneflow.nn.Quantization(quantization_formula: str = 'google', quantization_bit: int = 8, quantization_scheme: str = 'symmetric')

在推理时模拟量化操作。

输出将被计算为:

若 quantization_scheme == “symmetric”:

\[ \begin{align}\begin{aligned}& quant\_max = 2^{quantization\_to\_bit - 1} - 1\\& quant\_min = -quant\_max\\& clamp(round(x / scale), quant\_min, quant\_max)\end{aligned}\end{align} \]

若 quantization_scheme == “affine”:

\[ \begin{align}\begin{aligned}& quant\_max = 2^{quantization\_to\_bit} - 1\\& quant\_min = 0\\& (clamp(round(x / scale + zero\_point), quant\_min, quant\_max) - zero\_point)\end{aligned}\end{align} \]
参数:
  • quantization_bit (int) - 量化输入为 uintX / intX , X 的值在 [2, 8] 中,默认值为 8。

  • quantization_scheme (str) - “symmetric” 或 “affine” , 量化为有符号/无符号整数。 默认值为 “symmetric”。

  • quantization_formula (str) - “google” or “cambricon”。

返回值:

oneflow.Tensor: 经过量化操作后的输入张量。

示例:

>>> import numpy as np
>>> import oneflow as flow

>>> weight = (np.random.random((2, 3, 4, 5)) - 0.5).astype(np.float32)

>>> input_tensor = flow.tensor(
...    weight, dtype=flow.float32
... )

>>> quantization_bit = 8
>>> quantization_scheme = "symmetric"
>>> quantization_formula = "google"
>>> per_layer_quantization = True

>>> min_max_observer = flow.nn.MinMaxObserver(quantization_formula=quantization_formula, quantization_bit=quantization_bit,
... quantization_scheme=quantization_scheme, per_layer_quantization=per_layer_quantization)
>>> quantization = flow.nn.Quantization(quantization_formula=quantization_formula, quantization_bit=quantization_bit,
... quantization_scheme=quantization_scheme)

>>> scale, zero_point = min_max_observer(
...    input_tensor,
... )

>>> output_tensor = quantization(
...    input_tensor,
...    scale,
...    zero_point,
... )
class oneflow.nn.ReLU(inplace=False)

ReLU 激活函数,对张量中的每一个元素做 element-wise 运算,公式如下:

\(\text{ReLU}(x) = (x)^+ = \max(0, x)\)

参数:

inplace: 是否做 in-place 操作。 默认为 False

形状:
  • Input: \((N, *)\) 其中 * 的意思是,可以指定任意维度

  • Output: \((N, *)\) 输入形状与输出形状一致

示例:

>>> import oneflow as flow
>>> relu = flow.nn.ReLU()
>>> x = flow.tensor([1, -2, 3], dtype=flow.float32)
>>> relu(x)
tensor([1., 0., 3.], dtype=oneflow.float32)
class oneflow.nn.ReLU6(inplace: bool = False)

逐元素地应用如下公式:

\[\begin{split}\text{Relu6}(x) = \begin{cases} 6 & \text{ if } x > 6 \\ 0 & \text{ if } x < 0 \\ x & \text{ otherwise } \\ \end{cases}\end{split}\]
参数:
  • inplace - 可以选择以 in-place 的方式执行操作。默认值为 False

形状:
  • Input: \((N, *)\) ,其中 * 表示任意数量的附加维度。

  • Output: \((N, *)\) ,与输入的形状相同。

示例:

>>> import numpy as np
>>> import oneflow as flow

>>> x = np.array([-0.5, 0, 0.5]).astype(np.float32)
>>> input = flow.Tensor(x)
>>> relu6 = flow.nn.ReLU6()

>>> out = relu6(input)
>>> out
tensor([0.0000, 0.0000, 0.5000], dtype=oneflow.float32)
class oneflow.nn.ReflectionPad2d(padding: Union[int, Tuple[int, int, int, int]])

此接口与 PyTorch 一致,文档参考自: https://pytorch.org/docs/stable/generated/torch.nn.ReflectionPad2d.html

使用输入边界的反射来填充输入张量。

参数:
  • padding (Union[int,tuple]) - 填充范围的大小或边界。若输入是一个 int,那各个维度上都会填充同样大小的数据。若输入是一个四个元素的元组,那么使用 \((\text{padding}_{\text{left}}, \text{padding}_{\text{right}}, \text{padding}_{\text{top}}, \text{padding}_{\text{bottom}} )\)

返回值:

Tensor: 返回一个新的张量,这是输入张量的反射填充的结果。

形状:
  • Input: \((N, C, H_{\text{in}}, W_{\text{in}})\)

  • Output: \((N, C, H_{\text{out}}, W_{\text{out}})\) ,其中

    \(H_{\text{out}} = H_{\text{in}} + \text{padding}_{\text{top}} + \text{padding}_{\text{bottom}}\)

    \(W_{\text{out}} = W_{\text{in}} + \text{padding}_{\text{left}} + \text{padding}_{\text{right}}\)

示例:

>>> import oneflow as flow
>>> import numpy as np
>>> input = flow.tensor(np.arange(18).reshape((1, 2, 3, 3)).astype(np.float32))
>>> m = flow.nn.ReflectionPad2d((2, 2, 1, 1))
>>> out = m(input)
>>> out
tensor([[[[ 5.,  4.,  3.,  4.,  5.,  4.,  3.],
          [ 2.,  1.,  0.,  1.,  2.,  1.,  0.],
          [ 5.,  4.,  3.,  4.,  5.,  4.,  3.],
          [ 8.,  7.,  6.,  7.,  8.,  7.,  6.],
          [ 5.,  4.,  3.,  4.,  5.,  4.,  3.]],

         [[14., 13., 12., 13., 14., 13., 12.],
          [11., 10.,  9., 10., 11., 10.,  9.],
          [14., 13., 12., 13., 14., 13., 12.],
          [17., 16., 15., 16., 17., 16., 15.],
          [14., 13., 12., 13., 14., 13., 12.]]]], dtype=oneflow.float32)
class oneflow.nn.ReplicationPad2d(padding: Union[int, Tuple[int, int, int, int]])

此接口与 PyTorch 一致,文档参考自: https://pytorch.org/docs/stable/generated/torch.nn.ReplicationPad2d.html#replicationpad2d

通过复制输入张量边界元素对输入张量进行填充操作。

参数:
  • padding (Union[int, tuple, list]) - 填充范围的大小。若输入是一个 int,那各个边界上都会填充上同样大小的数据。若输入是一个四个元素的元组,那么使用 (\(\mathrm{padding_{left}}\), \(\mathrm{padding_{right}}\), \(\mathrm{padding_{top}}\), \(\mathrm{padding_{bottom}}\))。

形状:
  • Input: \((N, C, H_{in}, W_{in})\)

  • Output: \((N, C, H_{out}, W_{out})\) ,其中

    \(H_{out} = H_{in} + \mathrm{padding_{top}} + \mathrm{padding_{bottom}}\)

    \(W_{out} = W_{in} + \mathrm{padding_{left}} + \mathrm{padding_{right}}\)

示例:

>>> import oneflow as flow
>>> import numpy as np
>>> m = flow.nn.ReplicationPad2d((2, 2, 1, 1))
>>> input = flow.tensor(np.arange(18).reshape((1, 2, 3, 3)).astype(np.float32))
>>> input_int = flow.tensor(np.arange(18).reshape((1, 2, 3, 3)).astype(np.int32))
>>> output = m(input)
>>> output.shape
oneflow.Size([1, 2, 5, 7])
>>> output
tensor([[[[ 0.,  0.,  0.,  1.,  2.,  2.,  2.],
          [ 0.,  0.,  0.,  1.,  2.,  2.,  2.],
          [ 3.,  3.,  3.,  4.,  5.,  5.,  5.],
          [ 6.,  6.,  6.,  7.,  8.,  8.,  8.],
          [ 6.,  6.,  6.,  7.,  8.,  8.,  8.]],

         [[ 9.,  9.,  9., 10., 11., 11., 11.],
          [ 9.,  9.,  9., 10., 11., 11., 11.],
          [12., 12., 12., 13., 14., 14., 14.],
          [15., 15., 15., 16., 17., 17., 17.],
          [15., 15., 15., 16., 17., 17., 17.]]]], dtype=oneflow.float32)
class oneflow.nn.SELU(inplace: bool = False)

逐元素地应用 SELU 函数,其等式为:

\[\text{SELU}(x) = \text{scale} * (\max(0,x) + \min(0, \alpha * (\exp(x) - 1)))\]

其中有 \(\alpha = 1.6732632423543772848170429916717\)

\(\text{scale} = 1.0507009873554804934193349852946\)

Warning

当使用 kaiming_normalkaiming_normal_ 进行初始化时,应当设置 nonlinearity='linear' 而非 nonlinearity='selu',这是为了得到 Self-Normalizing Neural Networks 。 查看 torch.nn.init.calculate_gain() 获得更多信息。

获得更多细节请参考文献 Self-Normalizing Neural Networks

形状:
  • Input - \((N, *)\) ,其中 * 表示任意数量的附加维度。

  • Output - \((N, *)\) ,与输入形状相同。

示例:

>>> import numpy as np
>>> import oneflow as flow
>>> x = np.array([1, 2, 3]).astype(np.float32)
>>> input = flow.Tensor(x)
>>> selu = flow.nn.SELU()
>>> out = selu(input)
>>> out
tensor([1.0507, 2.1014, 3.1521], dtype=oneflow.float32)
class oneflow.nn.Sequential(*args: Any)

一个序列容器。按照 Module 在构造函数中被传递的顺序将其添加到容器中。或者,也可以向构造函数传递 Module 的有序字典。

为了便于理解,这里有一个示例:

>>> import oneflow.nn as nn
>>> from collections import OrderedDict
>>> nn.Sequential(nn.Conv2d(1,20,5), nn.ReLU(), nn.Conv2d(20,64,5), nn.ReLU()) 
Sequential(
  (0): Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1))
  (1): ReLU()
  (2): Conv2d(20, 64, kernel_size=(5, 5), stride=(1, 1))
  (3): ReLU()
)
>>> nn.Sequential(OrderedDict([
...    ('conv1', nn.Conv2d(1,20,5)),
...    ('relu1', nn.ReLU()),
...    ('conv2', nn.Conv2d(20,64,5)),
...    ('relu2', nn.ReLU())
... ])) 
Sequential(
  (conv1): Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1))
  (relu1): ReLU()
  (conv2): Conv2d(20, 64, kernel_size=(5, 5), stride=(1, 1))
  (relu2): ReLU()
)
class oneflow.nn.SiLU(inplace: bool = False)

Swish 激活函数

\[\text{SiLU}(x) = x * sigmoid(x)\]

Note

SiLU(Sigmoid Linear Unit)在 Gaussian Error Linear Units (GELUs) 中被提出在`Sigmoid-Weighted Linear Units for Neural Network Function Approximation in Reinforcement Learning <https://arxiv.org/abs/1702.03118>`_ 和 Swish: a Self-Gated Activation Function 中被试验。

形状:
  • Input: \((N, *)\) ,其中 * 表示任意数量的附加维度。

  • Output: \((N, *)\) ,与输入的形状相同。

示例:

>>> import numpy as np
>>> import oneflow as flow


>>> x = np.array([1, 2, 3]).astype(np.float32)
>>> input = flow.Tensor(x)
>>> silu = flow.nn.SiLU()
>>> out = silu(input)
>>> out
tensor([0.7311, 1.7616, 2.8577], dtype=oneflow.float32)
class oneflow.nn.Sigmoid

应用逐元素函数:

\[\text{Sigmoid}(x) = \sigma(x) = \frac{1}{1 + \exp(-x)}\]
形状:
  • Input: \((N, *)\) 其中 * 表示任意数量的附加维度

  • Output: \((N, *)\) 与输入相同的形状

示例:

>>> import oneflow as flow
>>> x = flow.tensor([0.81733328, 0.43621480, 0.10351428], dtype=flow.float32)
>>> m = flow.nn.Sigmoid()
>>> out = m(x)
>>> out
tensor([0.6937, 0.6074, 0.5259], dtype=oneflow.float32)
class oneflow.nn.SmoothL1Loss(reduction: str = 'mean', beta: float = 1.0)

若逐元素的绝对误差低于 beta ,则创建一个使用平方项的指标,否则创建一个使用 L1 项的指标。

此接口与 PyTorch 一致,文档参考自: https://pytorch.org/docs/stable/generated/torch.nn.SmoothL1Loss.html

torch.nn.MSELoss 相比,它对异常值不太敏感,并在某些场景下可以防止梯度爆炸。比如 Ross Girshick 的论文 Fast R-CNN

对于大小为 \(N\) 的批次,未减少的损失可以描述为:

\[\ell(x, y) = L = \{l_1, ..., l_N\}^T\]

其中:

\[\begin{split}l_n = \begin{cases} 0.5 (x_n - y_n)^2 / beta, & \text{if } |x_n - y_n| < beta \\ |x_n - y_n| - 0.5 * beta, & \text{otherwise } \end{cases}\end{split}\]

reduction == none ,那么:

\[\begin{split}\ell(x, y) = \begin{cases} \operatorname{mean}(L), & \text{if reduction} = \text{`mean';}\\ \operatorname{sum}(L), & \text{if reduction} = \text{`sum'.} \end{cases}\end{split}\]

Note

平滑 L1 损失可以看作是 L1Loss ,但 \(|x - y| < beta\) 部分被替换为二次函数,使得它的斜率在 \(|x - y| = beta\) 处为 1。二次函数的部分平滑了 \(|x - y| = 0\) 处的 L1 损失。

Note

平滑 L1 损失与 HuberLoss 密切相关,相当于 \(huber(x, y) / beta\) (注意 Smooth L1 的 beta 超参数相当于 Huber 的 delta)。这导致了以下差异: * 当 beta 趋向 0,平滑 L1 损失收敛到 L1Loss ,而 HuberLoss 收敛到常数 0 损失。 * 当 beta 趋向 \(+\infty\) ,平滑 L1 损失收敛到常数 0 损失,而 HuberLoss 收敛到 MSELoss。 * 对于平滑 L1 损失,随着 beta 的变化,损失的 L1 段的斜率恒为 1。而对于 HuberLoss ,斜率是 beta。

参数:
  • size_average (bool, optional) - 已弃用(参考 reduction)。默认情况下,损失是批次中每个损失元素的平均值。请注意,对于某些损失,每个样本有多个元素。若 size_average == False,则将每个小批量的损失相加。当 reduce == False 时忽略。默认值为 True

  • reduce (bool, optional) - 已弃用(参考 reduction)。根据 size_average 对每个小批量的损失进行平均或汇总。若 reduce == False,则返回每个批元素的损失,并忽略 size_average。默认值为 True

  • reduction (string, optional) - 指定应用于输出的 reduction:'none' | 'mean' | 'sum'. 'none' :不进行 reduction;'mean' :输出的和将会除以输出中的元素数量;'sum' :输出将被求和。注意: size_averagereduce 正逐渐被弃用,指定这二者的任何一个都将覆盖 reduction。默认值为 'mean'

  • beta (float, optional) - 指定在 L1 和 L2 损失之间更改的阈值。该值必须为非负。默认值为 1.0。

形状:
  • Input: \((N, *)\) ,其中 * 表示任意数量的附加维度。

  • Target: \((N, *)\) ,与输入的形状相同。

  • Output: 若 reduction == 'none' 则输出为形状为 \((N)\) 的张量,否则是一个标量。

示例:

>>> import oneflow as flow
>>> import numpy as np

>>> x = flow.tensor(np.array([0.1, 0.4, 0.3, 0.5, 0.9]).astype(np.float32), dtype=flow.float32)
>>> y = flow.tensor(np.array([0.3, 0.9, 2.5, 0.4, 0.3]).astype(np.float32), dtype=flow.float32)
>>> m = flow.nn.SmoothL1Loss(reduction="none")
>>> out = m(x, y)
>>> out
tensor([0.0200, 0.1250, 1.7000, 0.0050, 0.1800], dtype=oneflow.float32)

>>> m = flow.nn.SmoothL1Loss(reduction="mean")
>>> out = m(x, y)
>>> out
tensor(0.4060, dtype=oneflow.float32)

>>> m = flow.nn.SmoothL1Loss(reduction="sum")
>>> out = m(x, y)
>>> out
tensor(2.0300, dtype=oneflow.float32)
class oneflow.nn.Softmax(dim=None)Tensor

将 Softmax 函数应用于 n 维输入 tensor 并重新缩放 tensor,以便 n 维输出 tensor 的元素位于 [0,1] 范围内并且和为 1。

Softmax 的公式为:

\[\text{Softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}\]

当输入张量是稀疏张量时,则未被指定的值将被视为 -inf

形状:
  • Input : \((*)\) 其中 * 表示任意数量的附加维度

  • Output : \((*)\) ,与输入的形状相同

返回类型:

oneflow.tensor: 与输入具有相同维度和形状的张量,其值在 [0, 1] 范围内

参数:

dim (int): 要进行 Softmax 计算的维度(因此沿 dim 的每个切片总和为 1)。

示例:

>>> import oneflow as flow
>>> m = flow.nn.Softmax(dim = 2)
>>> x = flow.tensor([[[-0.46716809,  0.40112534,  0.61984003], [-1.31244969, -0.42528763,  1.47953856]]], dtype=flow.float32)
>>> out = m(x)
>>> out
tensor([[[0.1575, 0.3754, 0.4671],
         [0.0507, 0.1230, 0.8263]]], dtype=oneflow.float32)
class oneflow.nn.Softplus(beta: int = 1, threshold: int = 20)

逐元素地应用公式:

\[\text{Softplus}(x) = \frac{1}{\beta} * \log(1 + \exp(\beta * x))\]

SoftPlus 是 ReLU 函数的平滑近似,可用于将输出约束为始终为正。

为了数值稳定性,当 \(input \times \beta > threshold\) 时,该函数的实现恢复为线性函数。

参数:
  • beta - 公式中 \(\beta\) 的值,默认为 1

  • threshold - 高于此值的函数将恢复为线性函数,默认为 20

形状:
  • Input: \((N, *)\) ,其中 * 表示任意数量的附加维度。

  • Output: \((N, *)\) ,与输入的形状相同。

示例:

>>> import numpy as np
>>> import oneflow as flow

>>> x = np.array([-0.5, 0, 0.5]).astype(np.float32)
>>> input = flow.Tensor(x)
>>> softplus = flow.nn.Softplus()

>>> out = softplus(input)
>>> out
tensor([0.4741, 0.6931, 0.9741], dtype=oneflow.float32)
class oneflow.nn.Softshrink(lambd: float = 0.5, inplace: bool = False)

该接口与 PyTorch 一致。 文档参考自: https://pytorch.org/docs/1.10/generated/torch.nn.Softshrink.html.

Softshrink 激活函数。

公式为:

\[\begin{split}\text{Softshrink}(x) = \begin{cases} x - \lambda, & \text{ if } x > \lambda \\ x + \lambda, & \text{ if } x < -\lambda \\ 0, & \text{ otherwise } \end{cases}\end{split}\]
参数:
  • lambd - Softshrink 公式的 \(\lambda\) 值,默认值为 0.5。

  • inplace - can optionally do the operation in-place. Default: False

形状:
  • Input - \((N, *)\) 中的 * 表示额外维度的数量。

  • Output - \((N, *)\) 与 input 的形状相同。

示例:

>>> import numpy as np
>>> import oneflow as flow
>>> x = np.array([-1, 0, 0.2, 0.5]).astype(np.float32)
>>> input = flow.Tensor(x)
>>> softshrink = flow.nn.Softshrink(lambd=0.5)
>>> out = softshrink(input)
>>> out
tensor([-0.5000,  0.0000,  0.0000,  0.0000], dtype=oneflow.float32)
class oneflow.nn.Softsign(inplace: bool = False)

SoftSign 激活函数

公式为:

\[SoftSign(x) = \frac{x}{1 + |x|}\]
形状:
  • Input: \((N, *)\) ,其中 * 表示任意数量的附加维度。

  • Output: \((N, *)\) ,与输入的形状相同。

示例:

>>> import numpy as np
>>> import oneflow as flow
>>> x = np.array([1, 2, 3]).astype(np.float32)
>>> input = flow.Tensor(x)
>>> softsign = flow.nn.Softsign()
>>> out = softsign(input)
>>> out
tensor([0.5000, 0.6667, 0.7500], dtype=oneflow.float32)
class oneflow.nn.Tanh

此算子计算张量的双曲正切值。

等式为:

\[out = \frac{e^x-e^{-x}}{e^x+e^{-x}}\]
参数:
  • input (oneflow.Tensor) - 张量。

返回值:

oneflow.Tensor: 运算结果。

示例:

>>> import numpy as np
>>> import oneflow as flow

>>> x = np.array([-1, 0, 1]).astype(np.float32)
>>> input = flow.Tensor(x)
>>> tanh = flow.nn.Tanh()
>>> out = tanh(input)
>>> out
tensor([-0.7616,  0.0000,  0.7616], dtype=oneflow.float32)
class oneflow.nn.Threshold(threshold: float, value: float)

Threshold 激活函数。 如果 xthreshold 大,返回 x,否则返回 value

该接口与 PyTorch 一致。 文档参考自:https://pytorch.org/docs/1.10/generated/torch.nn.Threshold.html.

公式是:

\[\begin{split}\text{Threshold}(x) = \begin{cases} x, & \text{ if } x > \text{ threshold } \\ \text{value }, & \text{ otherwise } \end{cases}\end{split}\]
参数:
  • threshold (float) - Threshold 公式的 threshold 值。

  • value (float) - Threshold 公式的 value 值。

形状:
  • Input - \((N, *)\) 中的 * 代表任意数目附加维度。

  • Output - \((N, *)\) 与 input 的形状相同。

返回:

Oneflow.Tensor:结果向量。

示例:

>>> import oneflow as flow
>>> import numpy as np
>>> x = np.array([-1, 0, 0.5, 1]).astype(np.float32)
>>> input = flow.Tensor(x)
>>> th = flow.nn.Threshold(threshold=0.5, value=0.2)
>>> out = th(input)
>>> out
tensor([0.2000, 0.2000, 0.2000, 1.0000], dtype=oneflow.float32)
class oneflow.nn.TripletMarginLoss(margin: float = 1.0, p: float = 2.0, eps: float = 1e-06, swap: bool = False, size_average=None, reduce=None, reduction: str = 'mean')

根据给定的输入张量 \(x1\), \(x2\), \(x3\) 以及大于 \(0\) 的边界值,创建一个测量三元组损失的指标来测量样本之间的相对相似性。三元组由 a, pn 组成(即分别为 锚点正例负例)。所有输入张量的形状应为 \((N, D)\)

在 V. Balntas, E. Riba 等人的 Learning local feature descriptors with triplets and shallow convolutional neural networks 中详细描述了距离交换。

小批量中每个样本的损失函数是:

\[L(a, p, n) = \max \{d(a_i, p_i) - d(a_i, n_i) + {\rm margin}, 0\}\]

其中

\[d(x_i, y_i) = \left\lVert {\bf x}_i - {\bf y}_i \right\rVert_p\]
参数:
  • margin (float, optional) - 默认值为 \(1\)

  • p (float, optional) - 成对距离的范数,默认值为 \(2.0\)

  • swap (bool, optional) - 默认值为 False.

  • reduction (string, optional) - 指定对输出应用的 reduction,可以为:'none' | 'mean' | 'sum'。其中 'none' :不进行 reduction;'mean' :输出的和将会除以输出中的元素数量;'sum' :输出将被求和。默认值为 'mean'。注意: size_averagereduce 正逐渐被弃用,指定这二者的任何一个都将覆盖 reduction。默认值为 'mean'

形状:
  • Input: \((N, D)\) ,其中 \(D\) 是向量维度。

  • Output: 若 reduction == 'none' 则输出为形状为 \((N)\) 的张量,否则是一个标量。

示例:

>>> import oneflow as flow
>>> import numpy as np
>>> triplet_loss = flow.nn.TripletMarginLoss(margin=1.0, p=2)
>>> anchor = np.array([[1, -1, 1],[-1, 1, -1], [1, 1, 1]])
>>> positive = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> negative = np.array([[2, 2, 2], [2, 2, 2], [2, 2, 2]])
>>> output = triplet_loss(flow.Tensor(anchor), flow.Tensor(positive), flow.Tensor(negative))
>>> output
tensor(6.2971, dtype=oneflow.float32)
class oneflow.nn.Upsample(size: Optional[Union[int, Tuple[int, ]]] = None, scale_factor: Optional[Union[float, Tuple[float, ]]] = None, mode: str = 'nearest', align_corners: Optional[bool] = None)

此接口与 PyTorch 一致,文档参考自: https://pytorch.org/docs/1.9.0/_modules/torch/nn/modules/upsampling.html#Upsample

对给定的多通道 1D(时间)、2D(空间)或 3D(体积)数据进行上采样。

假定输入数据的形式为 批量大小 x 通道 x [可选深度] x [可选高度] x 宽度。 因此,对于空间输入,我们期待一个 4D 张量;对于体积输入,我们期待一个 5D 张量。

可用于上采样的算法分别是 3D、4D 和 5D 输入张量的 nearestlinearbilinearbicubictrilinear 算法。

可以用 scale_factor 或目标输出大小来计算输出大小(由于其不确定性,不能同时给出)。

参数:
  • size (int or Tuple[int] or Tuple[int, int] or Tuple[int, int, int], optional) - 输出空间大小。

  • scale_factor (float or Tuple[float] or Tuple[float, float] or Tuple[float, float, float], optional) - 空间大小的乘数。若是 tuple 则需要匹配输入大小。

  • mode (str, optional) - 上采样算法: 'nearest''linear''bilinear''bicubic''trilinear'。默认值为:'nearest'

  • align_corners (bool, optional) - 若设置为 True ,则若为 True,则输入和输出张量的角像素对齐,从而保留这些像素的值。这仅在模式为 'linear''bilinear''trilinear' 时有效。默认值为 False。

形状:
  • Input: \((N, C, W_{in})\), \((N, C, H_{in}, W_{in})\)\((N, C, D_{in}, H_{in}, W_{in})\)

  • Output: \((N, C, W_{out})\), \((N, C, H_{out}, W_{out})\) or \((N, C, D_{out}, H_{out}, W_{out})\) ,其中

\[D_{out} = \left\lfloor D_{in} \times \text{scale_factor} \right\rfloor\]
\[H_{out} = \left\lfloor H_{in} \times \text{scale_factor} \right\rfloor\]
\[W_{out} = \left\lfloor W_{in} \times \text{scale_factor} \right\rfloor\]

Warning

align_corners = True ,线性插值模式(linearbilinearbicubictrilinear)不会按比例对齐输出和输入像素,因此输出值可能取决于输入大小。这是 0.3.1 版本之前这些模式的默认行为。 0.3.1 版本之后的默认值行为是 align_corners = False。有关其如何影响输出的具体示例,请参见下文。

Note

若需要下采样或者一般性的调整大小,应该使用 interpolate()

示例:

>>> import numpy as np
>>> import oneflow as flow

>>> input = flow.tensor(np.arange(1, 5).reshape((1, 1, 2, 2)), dtype=flow.float32)
>>> input = input.to("cuda")
>>> m = flow.nn.Upsample(scale_factor=2.0, mode="nearest")
>>> output = m(input)
>>> output 
tensor([[[[1., 1., 2., 2.],
          ...
          [3., 3., 4., 4.]]]], device='cuda:0', dtype=oneflow.float32)
class oneflow.nn.UpsamplingBilinear2d(size: Optional[Tuple[int, int]] = None, scale_factor: Optional[Tuple[float, float]] = None)

对由多个输入通道组成的输入信号应用 2D bilinear upsampling。

若要指定比例,需要 sizescale_factor 作为它的构造函数参数。

若给定 size ,则它也是图像 (h, w) 的大小。

参数:
  • size (int or Tuple[int, int], optional) - 输出空间大小。

  • scale_factor (float or Tuple[float, float], optional) - 空间大小的乘数。

Warning

对这个类的维护已经停止,请使用 interpolate()。它等同于 nn.functional.interpolate(..., mode='bilinear', align_corners=True)

形状:
  • Input: \((N, C, H_{in}, W_{in})\)

  • Output: \((N, C, H_{out}, W_{out})\) ,其中

\[H_{out} = \left\lfloor H_{in} \times \text{scale_factor} \right\rfloor\]
\[W_{out} = \left\lfloor W_{in} \times \text{scale_factor} \right\rfloor\]

示例:

> import numpy as np
> import oneflow as flow

> input = flow.tensor(np.arange(1, 5).reshape((1, 1, 2, 2)), dtype=flow.float32)
> input = input.to("cuda")
> m = flow.nn.UpsamplingBilinear2d(scale_factor=2.0)
> output = m(input)
> output #doctest: +ELLIPSIS
tensor([[[[1.0000, 1.3333, 1.6667, 2.0000],
          ...
          [3.0000, 3.3333, 3.6667, 4.0000]]]], device='cuda:0', dtype=oneflow.float32)
class oneflow.nn.UpsamplingNearest2d(size: Optional[Tuple[int, int]] = None, scale_factor: Optional[Tuple[float, float]] = None)

对由多个输入通道组成的输入信号应用 2D nearest neighbor upsampling。

若要指定比例,需要 sizescale_factor 作为它的构造函数参数。

若给定 size ,则它也是图像 (h, w) 的大小。

参数:
  • size (int or Tuple[int, int], optional) - 输出空间大小。

  • scale_factor (float or Tuple[float, float], optional) - 空间大小的乘数。

Warning

对这个类的维护已经停止,请使用 interpolate()

形状:
  • Input: \((N, C, H_{in}, W_{in})\)

  • Output: \((N, C, H_{out}, W_{out})\) ,其中

\[H_{out} = \left\lfloor H_{in} \times \text{scale_factor} \right\rfloor W_{out} = \left\lfloor W_{in} \times \text{scale_factor} \right\rfloor\]

示例:

>>> import numpy as np
>>> import oneflow as flow

>>> input = flow.tensor(np.arange(1, 5).reshape((1, 1, 2, 2)), dtype=flow.float32)
>>> input = input.to("cuda")
>>> m = flow.nn.UpsamplingNearest2d(scale_factor=2.0)
>>> output = m(input)
>>> output 
tensor([[[[1., 1., 2., 2.],
          ...
          [3., 3., 4., 4.]]]], device='cuda:0', dtype=oneflow.float32)
class oneflow.nn.ZeroPad2d(padding: Union[int, tuple, list])

此接口与 PyTorch 一致,文档参考自: https://pytorch.org/docs/stable/generated/torch.nn.ZeroPad2d.html

用零填充输入张量边界。用户可以通过设置参数 paddings 来设置填充量。

参数:
  • padding (Union[int, tuple]) - 填充量的大小。若是 int 类型,则在所有边界中使用相同的填充。若是 4-tuple 则使用 (\(\mathrm{padding_{left}}\), \(\mathrm{padding_{right}}\), \(\mathrm{padding_{top}}\), \(\mathrm{padding_{bottom}}\))

形状:
  • Input: \((N, C, H_{in}, W_{in})\)

  • Output: \((N, C, H_{out}, W_{out})\) ,其中

    \(H_{out} = H_{in} + \mathrm{padding_{top}} + \mathrm{padding_{bottom}}\)

    \(W_{out} = W_{in} + \mathrm{padding_{left}} + \mathrm{padding_{right}}\)

示例:

>>> import oneflow as flow
>>> import numpy as np
>>> m1 = flow.nn.ZeroPad2d(2)
>>> m2 = flow.nn.ZeroPad2d((1,2,2,0))
>>> input = flow.tensor(np.arange(18).reshape((1, 2, 3, 3)).astype(np.float32))
>>> output = m1(input)
>>> output.shape
oneflow.Size([1, 2, 7, 7])
>>> output
tensor([[[[ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
          [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
          [ 0.,  0.,  0.,  1.,  2.,  0.,  0.],
          [ 0.,  0.,  3.,  4.,  5.,  0.,  0.],
          [ 0.,  0.,  6.,  7.,  8.,  0.,  0.],
          [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
          [ 0.,  0.,  0.,  0.,  0.,  0.,  0.]],

         [[ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
          [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
          [ 0.,  0.,  9., 10., 11.,  0.,  0.],
          [ 0.,  0., 12., 13., 14.,  0.,  0.],
          [ 0.,  0., 15., 16., 17.,  0.,  0.],
          [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
          [ 0.,  0.,  0.,  0.,  0.,  0.,  0.]]]], dtype=oneflow.float32)
>>> output = m2(input)
>>> output
tensor([[[[ 0.,  0.,  0.,  0.,  0.,  0.],
          [ 0.,  0.,  0.,  0.,  0.,  0.],
          [ 0.,  0.,  1.,  2.,  0.,  0.],
          [ 0.,  3.,  4.,  5.,  0.,  0.],
          [ 0.,  6.,  7.,  8.,  0.,  0.]],

         [[ 0.,  0.,  0.,  0.,  0.,  0.],
          [ 0.,  0.,  0.,  0.,  0.,  0.],
          [ 0.,  9., 10., 11.,  0.,  0.],
          [ 0., 12., 13., 14.,  0.,  0.],
          [ 0., 15., 16., 17.,  0.,  0.]]]], dtype=oneflow.float32)
oneflow.nn.modules.pixelshuffle.PixelShufflev2(upscale_factor: Optional[int] = None, h_upscale_factor: Optional[int] = None, w_upscale_factor: Optional[int] = None)None

部分文档参考自: https://pytorch.org/docs/stable/generated/torch.nn.PixelShuffle.html#torch.nn.PixelShuffle

将形状为 \((*, C \times r_h \times r_w, H, W)\) 的张量中的元素重新排列为形状为 \((*, C, H \times r_h, W \times r_w)\) 的张量,其中 r_h 和 r_w 是放大因子。

这对于实现步幅为 \(1/r\) 的高效亚像素卷积很有效。

更多细节请参考这篇论文: Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional Neural Network

参数:
  • upscale_factor (int, optional) - 增加空间分辨率的因子,仅在空间高度和宽度因子相同时使用。

  • h_upscale_factor (int, optional) - 增加高度空间分辨率的因子,只能使用 h_upscale_factor 和 upscale_factor 的其中一个。

  • w_upscale_factor (int, optional) - 增加宽度空间分辨率的因子,只能使用 w_upscale_factor 和 upscale_factor 的其中一个。

形状:
  • Input: \((*, C_{in}, H_{in}, W_{in})\),其中 * 是零个或多个批次维度

  • Output: \((*, C_{out}, H_{out}, W_{out})\),其中

如果使用 upscale_factor:

\[ \begin{align}\begin{aligned}C_{out} = C_{in} \div \text{h_upscale_factor}^2\\H_{out} = H_{in} \times \text{upscale_factor}\\W_{out} = W_{in} \times \text{upscale_factor}\end{aligned}\end{align} \]

如果使用 h_upscale_factor 和 w_upscale_factor:

\[ \begin{align}\begin{aligned}C_{out} = C_{in} \div \text{h_upscale_factor} \div \text{w_upscale_factor}\\H_{out} = H_{in} \times \text{h_upscale_factor}\\W_{out} = W_{in} \times \text{w_upscale_factor}\end{aligned}\end{align} \]

示例:

>>> import oneflow as flow
>>> import numpy as np
>>> m = flow.nn.PixelShuffle(upscale_factor=2)
>>> x = flow.Tensor(np.random.randn(3, 4, 5, 5))
>>> y = m(x)
>>> y.shape
oneflow.Size([3, 1, 10, 10])

>>> m = flow.nn.PixelShuffle(h_upscale_factor=3, w_upscale_factor=4)
>>> x = flow.Tensor(np.random.randn(1, 24, 2, 2))
>>> y = m(x)
>>> y.shape
oneflow.Size([1, 2, 6, 8])
oneflow.nn.parallel.DistributedDataParallel(module: oneflow.nn.module.Module, *, broadcast_buffers: bool = True, bucket_size: int = 10)
oneflow.nn.utils.clip_grad_norm_(parameters: Union[oneflow.Tensor, Iterable[oneflow.Tensor]], max_norm: float, norm_type: float = 2.0, error_if_nonfinite: bool = False)oneflow.Tensor

裁剪可迭代参数的梯度范数。范数是在所有梯度上一起计算的,就像它们被连接成一个向量一样。

参数:
  • parameters (Iterable[Tensor] 或 Tensor) - 一个可迭代的张量或一个将梯度归一化的单个张量。

  • max_norm (float 或 int) - 梯度的最大范数。

  • norm_type (float 或 int) - 使用的 p-norm 的类型。对于无穷范数,可以是 'inf'

  • error_if_nonfinite (bool) - 当为 True 时,如果来自 :attr:parameters 的梯度的总范数为 naninf-inf 会出现 error 。默认:True。

返回类型:

裁剪梯度范数后的参数。参数的总范数(视为单个向量)。

示例:

>>> import oneflow as flow

>>> x1 = flow.tensor([[2, 3, 4], [1.5, 2.6, 3.7]], dtype=flow.float32, requires_grad=True)
>>> m1 = flow.nn.ReLU()
>>> out1 = m1(x1)
>>> out1 = out1.sum()
>>> out1.backward()
>>> norm1 = flow.nn.utils.clip_grad_norm_(x1, 0.6, 1.0)
>>> norm1
tensor(6., dtype=oneflow.float32)
>>> x1.grad
tensor([[0.1000, 0.1000, 0.1000],
        [0.1000, 0.1000, 0.1000]], dtype=oneflow.float32)
>>> x2 = flow.tensor([[-2, -3, -4], [2.5, 0, 3.2]], dtype=flow.float32, requires_grad=True)
>>> out2 = flow.atan(x2)
>>> out2 = out2.sum()
>>> out2.backward()
>>> norm2 = flow.nn.utils.clip_grad_norm_(x2, 0.5)
>>> norm2
tensor(1.0394, dtype=oneflow.float32)
>>> x2.grad
tensor([[0.0962, 0.0481, 0.0283],
        [0.0663, 0.4810, 0.0428]], dtype=oneflow.float32)
oneflow.nn.utils.weight_norm(module: T_module, name: str = 'weight', dim: int = 0)T_module

对给定模块中的参数应用权重归一化 (Weight Normalization)。

\[\mathbf{w}=g \frac{\mathbf{v}}{\|\mathbf{v}\|}\]

权重归一化 (Weight Normalization) 是一种重新参数化 (Reparameterization), 它将权重张量的大小从其方向解耦。此操作将用两个参数替换由 name 指定的参数: 一个指定大小(例如 'weight'),另一个指定方向(例如 'weight_v')。 权重归一化 (Weight Normalization) 是通过一个 hook 实现的,该 hook 在每个 forward() 调用之前从大小和方向重新计算权重张量。

默认情况下,当 dim=0 时,每个输出通道/平面独立计算范数。 要计算整个权重张量的范数,请使用 dim=None

参见 https://arxiv.org/abs/1602.07868 。本文档说明参考 Pytorch 文档:https://pytorch.org/docs/stable/generated/torch.nn.utils.weight_norm.html

参数:
  • module (Module): 包含模块

  • name (str, 可选的): 权重参数名称

  • dim (int, 可选的): 计算范数的维度

返回类型:

带有权重范数 hook 的原始模块

示例:

>>> import oneflow as flow
>>> m = flow.nn.utils.weight_norm(flow.nn.Linear(20, 40), name='weight')
>>> m
Linear(in_features=20, out_features=40, bias=True)
>>> m.weight_g.size()
oneflow.Size([40, 1])
>>> m.weight_v.size()
oneflow.Size([40, 20])
oneflow.nn.utils.remove_weight_norm(module, name='weight')T_module

从模块中删除 Weight Normalization Reparameterization。

参数:
  • module (Module): 包含模块

  • name (str, 可选的): 权重参数名称

示例:

>>> import oneflow as flow
>>> m = flow.nn.utils.weight_norm(flow.nn.Linear(20, 40))
>>> flow.nn.utils.remove_weight_norm(m)
Linear(in_features=20, out_features=40, bias=True)