快捷方式

GRUCell

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

一個門控迴圈單元 (GRU) 單元,它執行的操作與 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) 單元。

\[\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,則該層不使用偏置權重 b_ihb_hh。預設值:True

輸入:input, hidden
  • input : tensor containing input features

  • hidden : tensor containing the initial hidden state for each element in the batch. Defaults to zero if not provided.

輸出:h’
  • h’ : tensor containing the next hidden state for each element in the batch

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

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

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

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

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

  • bias_ih – the learnable input-hidden bias, of shape (3*hidden_size)

  • bias_hh – the learnable hidden-hidden bias, of shape (3*hidden_size)

注意

所有權重和偏置都從 \(\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: Tensor | None = None) Tensor[原始碼]

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

所有子類都應重寫此方法。

注意

儘管前向傳播的實現需要在此函式中定義,但您應該在之後呼叫 Module 例項而不是此函式,因為前者會處理註冊的鉤子,而後者則會靜默忽略它們。

文件

訪問全面的 PyTorch 開發者文件

檢視文件

教程

為初學者和高階開發者提供深入的教程

檢視教程

資源

查詢開發資源並讓您的問題得到解答

檢視資源