当使用OpenNMT-py训练模型时,我们会得到一个字典作为输出,其中包含网络的权重和偏置。然而,这些张量的requires_grad属性被设置为False,因此没有梯度。例如,在一个层中,我们可能会有以下张量,表示编码器和解码器中的嵌入、权重和偏置。它们都没有梯度属性。
encoder.embeddings.emb_luts.0.weight
decoder.embeddings.emb_luts.0.weight
encoder.rnn.weight_ih_l0
encoder.rnn.weight_hh_l0
encoder.rnn.bias_ih_l0
encoder.rnn.bias_hh_l0
decoder.rnn.layers.0.weight_ih
decoder.rnn.layers.0.weight_hh
decoder.rnn.layers.0.bias_ih
decoder.rnn.layers.0.bias_hh
OpenNMT-py是否有某个选项可以将requires_gradient设置为True,或者是否有其他方法可以获取这些张量的梯度?
回答:
梯度只能在训练循环内访问,即在调用optim.step()
时。如果你想将梯度(或梯度的范数或其他信息)记录到TensorBoard中,最好在优化器步骤调用之前获取它们。这在Trainer
对象的_gradient_accumulation
方法中进行。
请注意,optim.step()
的调用有两个地方。具体使用哪一个取决于你是每次批次后进行更新,还是累积多个批次的梯度后进行更新。