PyTorc 1.0中国語ドキュメント:拡張PyTorch

4471 ワード

訳者:PEGASUS 1993
本章では、EMCのCライブラリを使用した拡張方法torch.nntorch.autogradおよびカスタム作成C拡張ツールについて説明します.
拡張torch.autograd
操作を追加autograd必要Function操作ごとに新しいサブクラスを実現します.回想すると、Functionautogradを用いて結果と勾配を計算し、操作履歴を符号化する.各新機能には、次の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
    

    全文を読む/本文を改善する