【问题标题】:Simple example of CuDnnGRU based RNN implementation in TensorflowTensorflow 中基于 CuDnnGRU 的 RNN 实现的简单示例
【发布时间】:2023-07-09 08:07:01
【问题描述】:

我将以下代码用于标准 GRU 实现:

def BiRNN_deep_dynamic_FAST_FULL_autolength(x,batch_size,dropout,hidden_dim):

seq_len=length_rnn(x)

with tf.variable_scope('forward'):
    lstm_cell_fwd =tf.contrib.rnn.GRUCell(hidden_dim,kernel_initializer=tf.contrib.layers.xavier_initializer(),bias_initializer=tf.contrib.layers.xavier_initializer())
    lstm_cell_fwd = tf.contrib.rnn.DropoutWrapper(lstm_cell_fwd, output_keep_prob=dropout)
with tf.variable_scope('backward'):
    lstm_cell_back =tf.contrib.rnn.GRUCell(hidden_dim,kernel_initializer=tf.contrib.layers.xavier_initializer(),bias_initializer=tf.contrib.layers.xavier_initializer())
    lstm_cell_back = tf.contrib.rnn.DropoutWrapper(lstm_cell_back, output_keep_prob=dropout)

outputs,_= tf.nn.bidirectional_dynamic_rnn(cell_fw=lstm_cell_fwd,cell_bw= lstm_cell_back,inputs=x,sequence_length=seq_len,dtype=tf.float32,time_major=False)
outputs_fwd,outputs_bck=outputs

### fwd matrix is the matrix that keeps all the last [-1] vectors
fwd_matrix=tf.gather_nd(outputs_fwd, tf.stack([tf.range(batch_size), seq_len-1], axis=1))       ###  99,64

outputs_fwd=tf.transpose(outputs_fwd,[1,0,2])
outputs_bck=tf.transpose(outputs_bck,[1,0,2])

return outputs_fwd,outputs_bck,fwd_matrix

谁能提供一个简单的例子来说明如何以类似的方式使用 tf.contrib.cudnn_rnn.CudnnGRU Cell?只换掉单元格是行不通的。

第一个问题是 CuDnnGRU 单元没有 dropout 包装器,这很好。其次,它似乎不适用于 tf.nn.bidirectional_dynamic_rnn。任何帮助表示赞赏。

【问题讨论】:

    标签: tensorflow rnn


    【解决方案1】:

    CudnnGRU 不是RNNCell 实例。它更类似于dynamic_rnn

    下面的张量操作是等价的,其中input_tensor 是时间主要张量,即形状为[max_sequence_length, batch_size, embedding_size]。 CudnnGRU 期望输入张量是时间主要的(与更标准的批处理主要格式相反,即形状 [batch_size, max_sequence_length, embedding_size]),无论如何将时间主要张量与 RNN 操作一起使用是一个好习惯,因为它们有点快.

    CudnnGRU:

    rnn = tf.contrib.cudnn_rnn.CudnnGRU(
      num_rnn_layers, hidden_size, direction='bidirectional')
    
    rnn_output = rnn(input_tensor)
    

    CudnnCompatibleGRUCell:

    rnn_output = input_tensor
    sequence_length = tf.reduce_sum(
      tf.sign(inputs),
      reduction_indices=0)  # 1 if `input_tensor` is batch-major.
    
      for _ in range(num_rnn_layers):
        fw_cell = tf.contrib.cudnn_rnn.CudnnCompatibleGRUCell(hidden_size)
        bw_cell = tf.contrib.cudnn_rnn.CudnnCompatibleGRUCell(hidden_size)
        rnn_output = tf.nn.bidirectional_dynamic_rnn(
          fw_cell, bw_cell, rnn_output, sequence_length=sequence_length,
          dtype=tf.float32, time_major=True)[1]  # Set `time_major` accordingly
    

    注意以下几点:

    1. 如果您使用的是 LSTM,则无需使用CudnnCompatibleLSTMCell;你可以使用标准的LSTMCell。但是对于 GRU,Cudnn 实现在本质上具有不同的数学运算,尤其是更多的权重 (see the documentation)。
    2. dynamic_rnn 不同,CudnnGRU 不允许您指定序列长度。尽管如此,它还是快了一个数量级,但是您必须小心提取输出的方式(例如,如果您对填充且长度不同的每个序列的最终隐藏状态感兴趣,则需要每个序列的长度)。
    3. rnn_output 可能是一个在这两种情况下都有很多(不同)东西的元组。请参阅文档或将其打印出来,以检查您需要输出的哪些部分。

    【讨论】:

      最近更新 更多