PyTorc 1.0中国語ドキュメント:拡張PyTorch
4471 ワード
訳者:PEGASUS 1993
本章では、EMCのCライブラリを使用した拡張方法
拡張torch.autograd
操作を追加 以下のコードから見ることができます
全文を読む/本文を改善する
本章では、EMCのCライブラリを使用した拡張方法
torch.nn
、torch.autograd
およびカスタム作成C
拡張ツールについて説明します.拡張torch.autograd
操作を追加
autograd
必要Function
操作ごとに新しいサブクラスを実現します.回想すると、Function
・autograd
を用いて結果と勾配を計算し、操作履歴を符号化する.各新機能には、次の2つの方法が必要です.forward()
-操作を実行するコード.デフォルト値を指定した場合は、必要に応じて任意のパラメータを使用できます.一部のパラメータはオプションです.ここでは各種Python
対象をサポートする.Variable
パラメータは呼び出し前に変換されるTensor
それらの使用状況はgraph
に登録される.なお、このロジックは、lists
/dicts
/その他のデータの構造を遍歴せず、直接呼び出されるVariables
パラメータのみを考慮する.複数の出力がある場合は、単一Tensor
またはTensor
フォーマットのメタグループを返すことができます.また、Function
文書検索forward()
でしか呼び出せない有用な方法の説明を参照してください.backward()
-勾配を計算する式.出力と同じ数のVariable
パラメータが与えられる.それぞれが勾配を計算する出力を表す.入力と同じ数のVariable
を返すべきである.それぞれの表示にはそれぞれの入力の勾配が含まれる.勾配を計算する必要がない場合(needs_input_grad
属性を参照)、または、非Variable
オブジェクトであればNone
クラスを返すことができる.また、forward()
メソッドにオプションのパラメータがあれば、入力よりも多くの勾配を返すことができ、いずれもNone
タイプであればよい.torch.nn
モジュールのLinear
関数、および注記# Inherit from Function
class Linear(Function):
# bias is an optional argument
def forward(self, input, weight, bias=None):
self.save_for_backward(input, weight, bias)
output = input.mm(weight.t())
if bias is not None:
output += bias.unsqueeze(0).expand_as(output)
return output
# This function has only a single output, so it gets only one gradient
def backward(self, grad_output):
# This is a pattern that is very convenient - at the top of backward
# unpack saved_tensors and initialize all gradients w.r.t. inputs to
# None. Thanks to the fact that additional trailing Nones are
# ignored, the return statement is simple even when the function has
# optional inputs.
input, weight, bias = self.saved_tensors
全文を読む/本文を改善する