快捷方式

模組

class torch.nn.Module(*args, **kwargs)[source][source]

所有神經網路模組的基類。

您的模型也應繼承此類別。

模組也可以包含其他模組,允許它們以樹狀結構巢狀。您可以將子模組作為常規屬性進行分配

import torch.nn as nn
import torch.nn.functional as F

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

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

以這種方式分配的子模組將被註冊,並且在呼叫 to() 等方法時,它們的引數也將被轉換。

注意

如上例所示,在子類中進行屬性分配之前,必須呼叫父類的 __init__() 方法。

變數

training (bool) – 布林值,表示此模組處於訓練模式還是評估模式。

add_module(name, module)[source][source]

向當前模組新增一個子模組。

可以使用給定的名稱作為屬性訪問該模組。

引數
  • name (str) – 子模組的名稱。可以使用給定名稱從當前模組訪問該子模組

  • module (Module) – 要新增到當前模組的子模組。

apply(fn)[source][source]

遞迴地將函式 fn 應用於每個子模組(由 .children() 返回)以及自身。

典型用法包括初始化模型的引數(另請參閱 torch.nn.init)。

引數

fn (Module -> None) – 將應用於每個子模組的函式

返回

self

返回型別

模組

示例

>>> @torch.no_grad()
>>> def init_weights(m):
>>>     print(m)
>>>     if type(m) == nn.Linear:
>>>         m.weight.fill_(1.0)
>>>         print(m.weight)
>>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))
>>> net.apply(init_weights)
Linear(in_features=2, out_features=2, bias=True)
Parameter containing:
tensor([[1., 1.],
        [1., 1.]], requires_grad=True)
Linear(in_features=2, out_features=2, bias=True)
Parameter containing:
tensor([[1., 1.],
        [1., 1.]], requires_grad=True)
Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
)
bfloat16()[source][source]

將所有浮點引數和緩衝區轉換為 bfloat16 資料型別。

注意

此方法會就地修改模組。

返回

self

返回型別

模組

buffers(recurse=True)[source][source]

返回模組緩衝區的迭代器。

引數

recurse (bool) – 如果為 True,則生成此模組和所有子模組的緩衝區。否則,僅生成作為此模組直接成員的緩衝區。

Yields

torch.Tensor – 模組緩衝區

返回型別

Iterator[Tensor]

示例

>>> for buf in model.buffers():
>>>     print(type(buf), buf.size())
<class 'torch.Tensor'> (20L,)
<class 'torch.Tensor'> (20L, 1L, 5L, 5L)
children()[source][source]

返回直接子模組的迭代器。

Yields

Module – 一個子模組

返回型別

Iterator[Module]

compile(*args, **kwargs)[source][source]

使用 torch.compile() 編譯此模組的 forward 方法。

此模組的 __call__ 方法被編譯,所有引數原樣傳遞給 torch.compile()

有關此函式引數的詳細資訊,請參閱 torch.compile()

cpu()[source][source]

將所有模型引數和緩衝區移動到 CPU。

注意

此方法會就地修改模組。

返回

self

返回型別

模組

cuda(device=None)[source][source]

將所有模型引數和緩衝區移動到 GPU。

這也會使關聯的引數和緩衝區成為不同的物件。因此,如果模組在最佳化時駐留在 GPU 上,則應在構造最佳化器之前呼叫此方法。

注意

此方法會就地修改模組。

引數

device (int, optional) – 如果指定,所有引數將被複制到該裝置

返回

self

返回型別

模組

double()[source][source]

將所有浮點引數和緩衝區轉換為 double 資料型別。

注意

此方法會就地修改模組。

返回

self

返回型別

模組

eval()[source][source]

將模組設定為評估模式。

這僅對某些模組有效。有關特定模組在訓練/評估模式下的行為詳情,即它們是否受影響,請參閱其文件,例如 DropoutBatchNorm 等。

這等同於呼叫 self.train(False)

關於 .eval() 與其他幾個可能與之混淆的機制的比較,請參閱 區域性停用梯度計算

返回

self

返回型別

模組

extra_repr()[source][source]

返回模組的額外表示。

要列印自定義的額外資訊,您應該在自己的模組中重新實現此方法。單行和多行字串均可接受。

返回型別

str

float()[source][source]

將所有浮點引數和緩衝區轉換為 float 資料型別。

注意

此方法會就地修改模組。

返回

self

返回型別

模組

forward(*input)[source]

定義每次呼叫時執行的計算。

應由所有子類覆蓋。

注意

儘管前向傳播的實現需要在此函式中定義,但之後應呼叫 Module 例項本身而不是此函式,因為前者會負責執行已註冊的鉤子,而後者會靜默忽略它們。

get_buffer(target)[source][source]

返回由 target 指定的緩衝區(如果存在),否則丟擲錯誤。

有關此方法功能的更詳細解釋以及如何正確指定 target,請參閱 get_submodule 的文件字串。

引數

target (str) – 要查詢的緩衝區的完全限定字串名稱。(有關如何指定完全限定字串,請參閱 get_submodule。)

返回

target 引用的緩衝區

返回型別

torch.Tensor

丟擲

AttributeError – 如果目標字串引用了無效路徑或解析到的物件不是緩衝區

get_extra_state()[source][source]

返回要包含在模組 state_dict 中的任何額外狀態。

如果需要儲存額外狀態,請為您的模組實現此方法以及相應的 set_extra_state() 方法。在構建模組的 state_dict() 時會呼叫此函式。

請注意,額外狀態應該是可 pickle 化的,以確保 state_dict 的序列化正常工作。我們僅為序列化 Tensors 提供向後相容性保證;如果其他物件的序列化 pickle 格式發生變化,可能會破壞向後相容性。

返回

要儲存在模組 state_dict 中的任何額外狀態

返回型別

object

get_parameter(target)[source][source]

返回由 target 指定的引數(如果存在),否則丟擲錯誤。

有關此方法功能的更詳細解釋以及如何正確指定 target,請參閱 get_submodule 的文件字串。

引數

target (str) – 要查詢的 Parameter 的完全限定字串名稱。(有關如何指定完全限定字串,請參閱 get_submodule。)

返回

target 引用的 Parameter

返回型別

torch.nn.Parameter

丟擲

AttributeError – 如果目標字串引用了無效路徑或解析到的物件不是 nn.Parameter

get_submodule(target)[source][source]

返回由 target 指定的子模組(如果存在),否則丟擲錯誤。

例如,假設您有一個 nn.Module A 如下所示

A(
    (net_b): Module(
        (net_c): Module(
            (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2))
        )
        (linear): Linear(in_features=100, out_features=200, bias=True)
    )
)

(圖示一個 nn.Module AA 有一個巢狀的子模組 net_b,它本身有兩個子模組 net_clinearnet_c 然後有一個子模組 conv。)

要檢查我們是否有 linear 子模組,我們將呼叫 get_submodule("net_b.linear")。要檢查我們是否有 conv 子模組,我們將呼叫 get_submodule("net_b.net_c.conv")

get_submodule 的執行時受 target 中模組巢狀深度的限制。查詢 named_modules 可以達到相同的結果,但在傳遞模組數量上是 O(N)。因此,對於檢查某個子模組是否存在,應始終使用 get_submodule

引數

target (str) – 要查詢的子模組的完全限定字串名稱。(有關如何指定完全限定字串,請參閱上例。)

返回

target 引用的子模組

返回型別

torch.nn.Module

丟擲

AttributeError – 如果目標字串產生的路徑上的任何一點(子路徑)解析到不存在的屬性名稱或不是 nn.Module 例項的物件。

half()[source][source]

將所有浮點引數和緩衝區轉換為 half 資料型別。

注意

此方法會就地修改模組。

返回

self

返回型別

模組

ipu(device=None)[source][source]

將所有模型引數和緩衝區移動到 IPU。

這也會使關聯的引數和緩衝區成為不同的物件。因此,如果模組在最佳化時駐留在 IPU 上,則應在構造最佳化器之前呼叫此方法。

注意

此方法會就地修改模組。

引數

device (int, optional) – 如果指定,所有引數將被複制到該裝置

返回

self

返回型別

模組

load_state_dict(state_dict, strict=True, assign=False)[source][source]

將引數和緩衝區從 state_dict 複製到此模組及其後代中。

如果 strictTrue,則 state_dict 中的鍵必須與此模組 state_dict() 函式返回的鍵完全匹配。

警告

如果 assignTrue,則必須在呼叫 load_state_dict 之後建立最佳化器,除非 get_swap_module_params_on_conversion()True

引數
  • state_dict (dict) – 包含引數和持久緩衝區的字典。

  • strict (bool, optional) – 是否嚴格要求 state_dict 中的鍵與此模組 state_dict() 函式返回的鍵匹配。預設值: True

  • assign (bool, optional) – 當設定為 False 時,保留當前模組中張量的屬性,而設定為 True 則保留 state_dict 中張量的屬性。唯一的例外是 requires_grad 欄位。 預設值: False

返回

  • missing_keys 是一個 str 列表,包含任何期望的鍵

    由此模組期望但提供的 state_dict 中缺失的鍵。

  • unexpected_keys 是一個 str 列表,包含未被期望的鍵

    由此模組期望但卻存在於提供的 state_dict 中的鍵。

返回型別

帶有 missing_keysunexpected_keys 欄位的 NamedTuple

注意

如果引數或 buffer 被註冊為 None 並且其對應的鍵存在於 state_dict 中,load_state_dict() 將引發 RuntimeError

modules()[source][source]

返回網路中所有模組的迭代器。

Yields

Module – 網路中的一個模組

返回型別

Iterator[Module]

注意

重複的模組只返回一次。在以下示例中,l 只返回一次。

示例

>>> l = nn.Linear(2, 2)
>>> net = nn.Sequential(l, l)
>>> for idx, m in enumerate(net.modules()):
...     print(idx, '->', m)

0 -> Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
)
1 -> Linear(in_features=2, out_features=2, bias=True)
mtia(device=None)[source][source]

將所有模型引數和 buffers 移動到 MTIA。

這也使得相關的引數和 buffers 成為不同的物件。因此,如果模組在最佳化時將在 MTIA 上執行,則應在構建最佳化器之前呼叫此方法。

注意

此方法會就地修改模組。

引數

device (int, optional) – 如果指定,所有引數將被複制到該裝置

返回

self

返回型別

模組

named_buffers(prefix='', recurse=True, remove_duplicate=True)[source][source]

返回模組 buffers 的迭代器,同時產生 buffer 的名稱及其 buffer 本身。

引數
  • prefix (str) – 新增到所有 buffer 名稱前的字串。

  • recurse (bool, optional) – 如果為 True,則產生當前模組及其所有子模組的 buffers。否則,僅產生當前模組的直接成員 buffers。預設為 True。

  • remove_duplicate (bool, optional) – 是否移除結果中的重複 buffers。預設為 True。

Yields

(str, torch.Tensor) – 包含名稱和 buffer 的元組

返回型別

Iterator[tuple[str, torch.Tensor]]

示例

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

返回直接子模組的迭代器,同時產生模組的名稱及其模組本身。

Yields

(str, Module) – 包含名稱和子模組的元組

返回型別

Iterator[tuple[str, ‘Module’]]

示例

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

返回網路中所有模組的迭代器,同時產生模組的名稱及其模組本身。

引數
  • memo (Optional[set['Module']]) – 一個備忘錄,用於儲存已新增到結果中的模組集合

  • prefix (str) – 將新增到模組名稱中的字首

  • remove_duplicate (bool) – 是否移除結果中的重複模組例項

Yields

(str, Module) – 包含名稱和模組的元組

注意

重複的模組只返回一次。在以下示例中,l 只返回一次。

示例

>>> l = nn.Linear(2, 2)
>>> net = nn.Sequential(l, l)
>>> for idx, m in enumerate(net.named_modules()):
...     print(idx, '->', m)

0 -> ('', Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
))
1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
named_parameters(prefix='', recurse=True, remove_duplicate=True)[source][source]

返回模組引數的迭代器,同時產生引數的名稱及其引數本身。

引數
  • prefix (str) – 新增到所有引數名稱前的字串。

  • recurse (bool) – 如果為 True,則產生當前模組及其所有子模組的引數。否則,僅產生當前模組的直接成員引數。

  • remove_duplicate (bool, optional) – 是否移除結果中的重複引數。預設為 True。

Yields

(str, Parameter) – 包含名稱和引數的元組

返回型別

Iterator[tuple[str, torch.nn.parameter.Parameter]]

示例

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

返回模組引數的迭代器。

這通常會傳遞給最佳化器。

引數

recurse (bool) – 如果為 True,則產生當前模組及其所有子模組的引數。否則,僅產生當前模組的直接成員引數。

Yields

Parameter – 模組引數

返回型別

Iterator[Parameter]

示例

>>> for param in model.parameters():
>>>     print(type(param), param.size())
<class 'torch.Tensor'> (20L,)
<class 'torch.Tensor'> (20L, 1L, 5L, 5L)
register_backward_hook(hook)[source][source]

在模組上註冊一個 backward 鉤子。

此函式已棄用,推薦使用 register_full_backward_hook()。此函式的行為將在未來版本中更改。

返回

一個控制代碼,可透過呼叫 handle.remove() 來移除新增的鉤子。

返回型別

torch.utils.hooks.RemovableHandle

register_buffer(name, tensor, persistent=True)[source][source]

向模組新增一個 buffer。

這通常用於註冊不應被視為模型引數的 buffer。例如,BatchNorm 的 running_mean 不是引數,而是模組狀態的一部分。預設情況下,buffers 是持久的,並將與引數一起儲存。可以透過將 persistent 設定為 False 來更改此行為。持久 buffer 和非持久 buffer 之間的唯一區別是,後者不會成為此模組的 state_dict 的一部分。

Buffers 可以透過給定的名稱作為屬性訪問。

引數
  • name (str) – buffer 的名稱。可以透過給定的名稱從此模組訪問該 buffer。

  • tensor (Tensor or None) – 要註冊的 buffer。如果為 None,則忽略在 buffers 上執行的操作(例如 cuda)。如果為 None,則該 buffer 包含在模組的 state_dict 中。

  • persistent (bool) – buffer 是否是此模組 state_dict 的一部分。

示例

>>> self.register_buffer('running_mean', torch.zeros(num_features))
register_forward_hook(hook, *, prepend=False, with_kwargs=False, always_call=False)[source][source]

在模組上註冊一個 forward 鉤子。

每次 forward() 計算出輸出後,將呼叫此鉤子。

如果 with_kwargsFalse 或未指定,則輸入僅包含傳遞給模組的位置引數。關鍵字引數不會傳遞給鉤子,僅傳遞給 forward。鉤子可以修改輸出。它可以就地修改輸入,但由於此鉤子是在呼叫 forward() 之後呼叫的,因此對 forward 沒有影響。鉤子應具有以下簽名:

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

如果 with_kwargsTrue,則 forward 鉤子將接收傳遞給 forward 函式的 kwargs,並且應返回可能已修改的輸出。鉤子應具有以下簽名:

hook(module, args, kwargs, output) -> None or modified output
引數
  • hook (Callable) – 要註冊的使用者定義鉤子。

  • prepend (bool) – 如果為 True,則提供的 hook 將在此 torch.nn.Module 上所有現有 forward 鉤子之前觸發。否則,提供的 hook 將在此 torch.nn.Module 上所有現有 forward 鉤子之後觸發。請注意,透過 register_module_forward_hook() 註冊的全域性 forward 鉤子將在透過此方法註冊的所有鉤子之前觸發。預設為 False

  • with_kwargs (bool) – 如果為 True,則 hook 將接收傳遞給 forward 函式的 kwargs。預設為 False

  • always_call (bool) – 如果為 True,則無論在呼叫 Module 時是否引發異常,都將執行 hook。預設為 False

返回

一個控制代碼,可透過呼叫 handle.remove() 來移除新增的鉤子。

返回型別

torch.utils.hooks.RemovableHandle

register_forward_pre_hook(hook, *, prepend=False, with_kwargs=False)[source][source]

在模組上註冊一個 forward pre-hook。

每次 forward() 被呼叫之前,將呼叫此鉤子。

如果 with_kwargs 為 false 或未指定,則輸入僅包含傳遞給模組的位置引數。關鍵字引數不會傳遞給鉤子,僅傳遞給 forward。鉤子可以修改輸入。使用者可以在鉤子中返回一個元組或單個修改後的值。如果返回單個值(除非該值本身已經是元組),我們會將其包裝成一個元組。鉤子應具有以下簽名:

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

如果 with_kwargs 為 true,則 forward pre-hook 將接收傳遞給 forward 函式的 kwargs。如果鉤子修改了輸入,則應返回 args 和 kwargs。鉤子應具有以下簽名:

hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
引數
  • hook (Callable) – 要註冊的使用者定義鉤子。

  • prepend (bool) – 如果為 true,則提供的 hook 將在此 torch.nn.Module 上所有現有 forward_pre 鉤子之前觸發。否則,提供的 hook 將在此 torch.nn.Module 上所有現有 forward_pre 鉤子之後觸發。請注意,透過 register_module_forward_pre_hook() 註冊的全域性 forward_pre 鉤子將在透過此方法註冊的所有鉤子之前觸發。預設為 False

  • with_kwargs (bool) – 如果為 true,則 hook 將接收傳遞給 forward 函式的 kwargs。預設為 False

返回

一個控制代碼,可透過呼叫 handle.remove() 來移除新增的鉤子。

返回型別

torch.utils.hooks.RemovableHandle

register_full_backward_hook(hook, prepend=False)[source][source]

在模組上註冊一個 backward 鉤子。

每次計算模組梯度時,都將呼叫此鉤子,即,僅當計算模組輸出的梯度時,鉤子才會執行。鉤子應具有以下簽名:

hook(module, grad_input, grad_output) -> tuple(Tensor) or None

grad_inputgrad_output 是元組,分別包含關於輸入和輸出的梯度。鉤子不應修改其引數,但可以選擇返回關於輸入的新梯度,該梯度將在後續計算中替代 grad_inputgrad_input 僅對應作為位置引數給出的輸入,所有關鍵字引數都將被忽略。對於所有非張量引數,grad_inputgrad_output 中的條目將為 None

出於技術原因,當此鉤子應用於 Module 時,其 forward 函式將接收傳遞給 Module 的每個張量的一個檢視。類似地,呼叫者將接收 Module 的 forward 函式返回的每個張量的一個檢視。

警告

使用 backward 鉤子時,不允許就地修改輸入或輸出,否則將引發錯誤。

引數
  • hook (Callable) – 要註冊的使用者定義鉤子。

  • prepend (bool) – 如果為 true,則提供的 hook 將在此 torch.nn.Module 上所有現有 backward 鉤子之前觸發。否則,提供的 hook 將在此 torch.nn.Module 上所有現有 backward 鉤子之後觸發。請注意,透過 register_module_full_backward_hook() 註冊的全域性 backward 鉤子將在透過此方法註冊的所有鉤子之前觸發。

返回

一個控制代碼,可透過呼叫 handle.remove() 來移除新增的鉤子。

返回型別

torch.utils.hooks.RemovableHandle

register_full_backward_pre_hook(hook, prepend=False)[source][source]

在模組上註冊一個 backward pre-hook。

每次計算模組梯度時,都將呼叫此鉤子。鉤子應具有以下簽名:

hook(module, grad_output) -> tuple[Tensor] or None

grad_output 是一個元組。鉤子不應修改其引數,但可以選擇返回關於輸出的新梯度,該梯度將在後續計算中替代 grad_output。 對於所有非張量引數,grad_output 中的條目將為 None

出於技術原因,當此鉤子應用於 Module 時,其 forward 函式將接收傳遞給 Module 的每個張量的一個檢視。類似地,呼叫者將接收 Module 的 forward 函式返回的每個張量的一個檢視。

警告

使用 backward 鉤子時,不允許就地修改輸入,否則將引發錯誤。

引數
  • hook (Callable) – 要註冊的使用者定義鉤子。

  • prepend (bool) – 如果為 true,則提供的 hook 將在此 torch.nn.Module 上所有現有 backward_pre 鉤子之前觸發。否則,提供的 hook 將在此 torch.nn.Module 上所有現有 backward_pre 鉤子之後觸發。請注意,透過 register_module_full_backward_pre_hook() 註冊的全域性 backward_pre 鉤子將在透過此方法註冊的所有鉤子之前觸發。

返回

一個控制代碼,可透過呼叫 handle.remove() 來移除新增的鉤子。

返回型別

torch.utils.hooks.RemovableHandle

register_load_state_dict_post_hook(hook)[source][source]

註冊一個 post-hook,在模組的 load_state_dict() 呼叫後執行。

它應具有以下簽名:

hook(module, incompatible_keys) -> None

module 引數是註冊此鉤子的當前模組,而 incompatible_keys 引數是一個 NamedTuple,包含屬性 missing_keysunexpected_keysmissing_keys 是一個包含缺失鍵的 list(元素為 str),unexpected_keys 是一個包含意外部索引鍵的 list(元素為 str)。

如有需要,可以就地修改給定的 incompatible_keys。

請注意,在呼叫 load_state_dict() 並設定 strict=True 時執行的檢查會受到鉤子對 missing_keysunexpected_keys 所做修改的影響,這是預期行為。向任一鍵集合新增內容將導致在 strict=True 時丟擲錯誤,而清除缺失鍵和意外部索引鍵則可以避免錯誤。

返回

一個控制代碼,可透過呼叫 handle.remove() 來移除新增的鉤子。

返回型別

torch.utils.hooks.RemovableHandle

register_load_state_dict_pre_hook(hook)[source][source]

註冊一個 pre-hook,在模組的 load_state_dict() 呼叫前執行。

它應具有以下簽名:

hook(module, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs) -> None # noqa: B950

引數

hook (Callable) – 在載入 state dict 之前將被呼叫的可呼叫鉤子。

register_module(name, module)[source][source]

add_module() 的別名。

register_parameter(name, param)[source][source]

向模組新增一個引數。

該引數可以透過給定的名稱作為屬性訪問。

引數
  • name (str) – 引數的名稱。可以使用給定的名稱從此模組訪問該引數。

  • param (ParameterNone) – 要新增到模組的引數。如果為 None,則對引數執行的操作(例如 cuda)將被忽略。如果為 None,則引數不會包含在模組的 state_dict 中。

register_state_dict_post_hook(hook)[source][source]

state_dict() 方法註冊一個後置鉤子 (post-hook)。

它應具有以下簽名:

hook(module, state_dict, prefix, local_metadata) -> None

註冊的鉤子可以就地修改 state_dict

register_state_dict_pre_hook(hook)[source][source]

state_dict() 方法註冊一個前置鉤子 (pre-hook)。

它應具有以下簽名:

hook(module, prefix, keep_vars) -> None

註冊的鉤子可用於在呼叫 state_dict 之前執行預處理。

requires_grad_(requires_grad=True)[source][source]

更改 autograd 是否應在此模組的引數上記錄操作。

此方法就地設定引數的 requires_grad 屬性。

此方法有助於凍結模組的一部分用於微調或單獨訓練模型的某些部分(例如,GAN 訓練)。

有關 .requires_grad_() 與可能與其混淆的幾種類似機制之間的比較,請參閱本地停用梯度計算

引數

requires_grad (bool) – autograd 是否應在此模組的引數上記錄操作。預設值:True

返回

self

返回型別

模組

set_extra_state(state)[source][source]

設定載入的 state_dict 中包含的額外狀態。

此函式由 load_state_dict() 呼叫,用於處理 state_dict 中找到的任何額外狀態。如果您需要在模組的 state_dict 中儲存額外狀態,請為您自己的模組實現此函式和相應的 get_extra_state()

引數

state (dict) – 來自 state_dict 的額外狀態

set_submodule(target, module, strict=False)[source][source]

設定由 target 給定的子模組(如果存在),否則丟擲錯誤。

注意

如果 strict 設定為 False(預設值),該方法將替換現有子模組,或者在父模組存在的情況下建立新的子模組。如果 strict 設定為 True,該方法將僅嘗試替換現有子模組,並且如果子模組不存在,則丟擲錯誤。

例如,假設您有一個 nn.Module A 如下所示

A(
    (net_b): Module(
        (net_c): Module(
            (conv): Conv2d(3, 3, 3)
        )
        (linear): Linear(3, 3)
    )
)

(該圖顯示了一個 nn.Module AA 有一個巢狀的子模組 net_b,它本身有兩個子模組 net_clinearnet_c 然後有一個子模組 conv。)

要用新的子模組 Linear 覆蓋 Conv2d,您可以呼叫 set_submodule("net_b.net_c.conv", nn.Linear(1, 1)),其中 strict 可以是 TrueFalse

要向現有 net_b 模組新增新的子模組 Conv2d,您將呼叫 set_submodule("net_b.conv", nn.Conv2d(1, 1, 1))

在上述情況下,如果您設定 strict=True 並呼叫 set_submodule("net_b.conv", nn.Conv2d(1, 1, 1), strict=True),則會引發 AttributeError,因為 net_b 沒有名為 conv 的子模組。

引數
  • target (str) – 要查詢的子模組的完全限定字串名稱。(有關如何指定完全限定字串,請參閱上例。)

  • module (Module) – 要設定子模組的模組。

  • strict (bool) – 如果為 False,該方法將替換現有子模組,或者在父模組存在的情況下建立新的子模組。如果為 True,該方法將僅嘗試替換現有子模組,並且如果子模組尚不存在,則丟擲錯誤。

丟擲
  • ValueError – 如果 target 字串為空,或者 module 不是 nn.Module 的例項。

  • AttributeError – 如果在由 target 字串產生的路徑中的任何一點,(子)路徑解析為不存在的屬性名,或不是 nn.Module 的例項物件。

share_memory()[source][source]

請參閱 torch.Tensor.share_memory_()

返回型別

T

state_dict(*, destination: T_destination, prefix: str = '', keep_vars: bool = False) T_destination[source][source]
state_dict(*, prefix: str = '', keep_vars: bool = False) dict[str, Any]

返回一個字典,其中包含對模組整個狀態的引用。

包含引數和持久緩衝區(例如,執行平均值)。鍵是相應的引數和緩衝區名稱。設定為 None 的引數和緩衝區不包含在內。

注意

返回的物件是淺複製。它包含對模組引數和緩衝區的引用。

警告

目前 state_dict() 也按順序接受用於 destinationprefixkeep_vars 的位置引數。但是,此用法正在被棄用,未來版本將強制使用關鍵字引數。

警告

請避免使用引數 destination,因為它不是為終端使用者設計的。

引數
  • destination (dict, optional) – 如果提供,模組的狀態將更新到字典中,並返回同一個物件。否則,將建立並返回一個 OrderedDict。預設值:None

  • prefix (str, optional) – 新增到引數和緩衝區名稱的字首,用於構成 state_dict 中的鍵。預設值:''

  • keep_vars (bool, optional) – 預設情況下,在狀態字典中返回的 Tensor 與 autograd 分離。如果將其設定為 True,則不會執行分離。預設值:False

返回

包含模組整個狀態的字典

返回型別

dict

示例

>>> module.state_dict().keys()
['bias', 'weight']
to(device: Optional[Union[str, device, int]] = ..., dtype: Optional[dtype] = ..., non_blocking: bool = ...) Self[source][source]
to(dtype: dtype, non_blocking: bool = ...) Self
to(tensor: Tensor, non_blocking: bool = ...) Self

移動和/或轉換引數和緩衝區的資料型別。

可以如下呼叫:

to(device=None, dtype=None, non_blocking=False)[source][source]
to(dtype, non_blocking=False)[source][source]
to(tensor, non_blocking=False)[source][source]
to(memory_format=torch.channels_last)[source][source]

其簽名類似於 torch.Tensor.to(),但只接受浮點或複數 dtype。此外,此方法只會將浮點或複數引數和緩衝區轉換為 dtype(如果給出)。整數引數和緩衝區將被移動到 device(如果給出),但資料型別保持不變。當設定 non_blocking 時,如果可能,它會嘗試相對於主機非同步轉換/移動,例如,將帶有固定記憶體的 CPU Tensor 移動到 CUDA 裝置。

請參見下面的示例。

注意

此方法會就地修改模組。

引數
  • device (torch.device) – 此模組中引數和緩衝區的期望裝置。

  • dtype (torch.dtype) – 此模組中引數和緩衝區的期望浮點或複數資料型別。

  • tensor (torch.Tensor) – 其資料型別和裝置為此模組中所有引數和緩衝區的期望資料型別和裝置的 Tensor。

  • memory_format (torch.memory_format) – 此模組中 4D 引數和緩衝區的期望記憶體格式(僅限關鍵字引數)。

返回

self

返回型別

模組

示例

>>> linear = nn.Linear(2, 2)
>>> linear.weight
Parameter containing:
tensor([[ 0.1913, -0.3420],
        [-0.5113, -0.2325]])
>>> linear.to(torch.double)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1913, -0.3420],
        [-0.5113, -0.2325]], dtype=torch.float64)
>>> gpu1 = torch.device("cuda:1")
>>> linear.to(gpu1, dtype=torch.half, non_blocking=True)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1914, -0.3420],
        [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1')
>>> cpu = torch.device("cpu")
>>> linear.to(cpu)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1914, -0.3420],
        [-0.5112, -0.2324]], dtype=torch.float16)

>>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble)
>>> linear.weight
Parameter containing:
tensor([[ 0.3741+0.j,  0.2382+0.j],
        [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128)
>>> linear(torch.ones(3, 2, dtype=torch.cdouble))
tensor([[0.6122+0.j, 0.1150+0.j],
        [0.6122+0.j, 0.1150+0.j],
        [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
to_empty(*, device, recurse=True)[source][source]

將引數和緩衝區移動到指定的裝置,而不復制儲存。

引數
  • device (torch.device) – 此模組中引數和緩衝區的期望裝置。

  • recurse (bool) – 子模組的引數和緩衝區是否應遞迴移動到指定的裝置。

返回

self

返回型別

模組

train(mode=True)[source][source]

將模組設定為訓練模式。

這僅對某些模組有效。有關它們在訓練/評估模式下的行為細節,即它們是否受到影響(例如 DropoutBatchNorm 等),請參閱特定模組的文件。

引數

mode (bool) – 是否設定為訓練模式(True)或評估模式(False)。預設值:True

返回

self

返回型別

模組

type(dst_type)[source][source]

將所有引數和緩衝區轉換為 dst_type

注意

此方法會就地修改模組。

引數

dst_type (typestring) – 期望的型別

返回

self

返回型別

模組

xpu(device=None)[source][source]

將所有模型引數和緩衝區移動到 XPU。

這也使得相關的引數和緩衝區成為不同的物件。因此,如果模組將在 XPU 上進行最佳化,則應在構造最佳化器之前呼叫此方法。

注意

此方法會就地修改模組。

引數

device (int, optional) – 如果指定,所有引數將被複制到該裝置

返回

self

返回型別

模組

zero_grad(set_to_none=True)[source][source]

重置所有模型引數的梯度。

更多背景資訊請參見 torch.optim.Optimizer 下的類似函式。

引數

set_to_none (bool) – 不設定為零,而是將梯度設定為 None。有關詳細資訊,請參閱 torch.optim.Optimizer.zero_grad()

文件

訪問 PyTorch 的全面開發者文件

檢視文件

教程

獲取面向初學者和高階開發者的深入教程

檢視教程

資源

查詢開發資源並獲得問題解答

檢視資源