快捷方式

GRUCell

class torchrl.modules.GRUCell(input_size: int, hidden_size: int, bias: bool = True, device=None, dtype=None)[源]

一個門控迴圈單元 (GRU) cell,其操作與 nn.LSTMCell 相同,但完全用 Python 編寫實現。

注意

該類實現不依賴於 CuDNN,這使其與 torch.vmap()torch.compile() 相容。

示例

>>> import torch
>>> from torchrl.modules.tensordict_module.rnn import GRUCell
>>> device = torch.device("cuda") if torch.cuda.device_count() else torch.device("cpu")
>>> B = 2
>>> N_IN = 10
>>> N_OUT = 20
>>> V = 4  # vector size
>>> gru_cell = GRUCell(input_size=N_IN, hidden_size=N_OUT, device=device)

# 單次呼叫 >>> x = torch.randn(B, 10, device=device) >>> h0 = torch.zeros(B, 20, device=device) >>> with torch.no_grad(): … h1 = gru_cell(x, h0)

# 向量化呼叫 - nn.GRUCell 不支援 >>> def call_gru(x, h): … h_out = gru_cell(x, h) … return h_out >>> batched_call = torch.vmap(call_gru) >>> x = torch.randn(V, B, 10, device=device) >>> h0 = torch.zeros(V, B, 20, device=device) >>> with torch.no_grad(): … h1 = batched_call(x, h0)

一個門控迴圈單元 (GRU) cell。

\[\begin{split}\begin{array}{ll} r = \sigma(W_{ir} x + b_{ir} + W_{hr} h + b_{hr}) \\ z = \sigma(W_{iz} x + b_{iz} + W_{hz} h + b_{hz}) \\ n = \tanh(W_{in} x + b_{in} + r \odot (W_{hn} h + b_{hn})) \\ h' = (1 - z) \odot n + z \odot h \end{array}\end{split}\]

其中 \(\sigma\) 是 sigmoid 函式,\(\odot\) 是 Hadamard 積。

引數:
  • input_size – 輸入 x 中預期的特徵數量

  • hidden_size – 隱藏狀態 h 中的特徵數量

  • bias – 如果 False,則該層不使用 bias 權重 b_ihb_hh。預設值:True

輸入: input, hidden
  • input : 包含輸入特徵的 tensor

  • hidden : 包含 batch 中每個元素的初始隱藏狀態的 tensor。如果未提供,則預設為零。

輸出: h’
  • h’ : 包含 batch 中每個元素的下一個隱藏狀態的 tensor

形狀
  • input: \((N, H_{in})\)\((H_{in})\) 包含輸入特徵的 tensor,其中 \(H_{in}\) = input_size

  • hidden: \((N, H_{out})\)\((H_{out})\) 包含初始隱藏狀態的 tensor,其中 \(H_{out}\) = hidden_size。如果未提供,則預設為零。

  • output: \((N, H_{out})\)\((H_{out})\) 包含下一個隱藏狀態的 tensor。

變數:
  • weight_ih (torch.Tensor) – 可學習的輸入到隱藏層權重,形狀為 (3*hidden_size, input_size)

  • weight_hh (torch.Tensor) – 可學習的隱藏層到隱藏層權重,形狀為 (3*hidden_size, hidden_size)

  • bias_ih – 可學習的輸入到隱藏層 bias,形狀為 (3*hidden_size)

  • bias_hh – 可學習的隱藏層到隱藏層 bias,形狀為 (3*hidden_size)

注意

所有權重和 bias 都從 \(\mathcal{U}(-\sqrt{k}, \sqrt{k})\) 初始化,其中 \(k = \frac{1}{\text{hidden\_size}}\)

在某些 ROCm 裝置上,使用 float16 輸入時,該模組將使用 不同的精度 進行反向傳播。

示例

>>> rnn = nn.GRUCell(10, 20)
>>> input = torch.randn(6, 3, 10)
>>> hx = torch.randn(3, 20)
>>> output = []
>>> for i in range(6):
...     hx = rnn(input[i], hx)
...     output.append(hx)
forward(input: Tensor, hx: Optional[Tensor] = None) Tensor[源]

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

應被所有子類覆蓋。

注意

雖然正向傳播 (forward pass) 的方法需要在此函式中定義,但之後應呼叫 Module 例項而不是直接呼叫此函式,因為前者會處理已註冊的鉤子,而後者會默默忽略它們。

文件

訪問 PyTorch 的全面開發者文件

檢視文件

教程

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

檢視教程

資源

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

檢視資源