プリンキピア

第2章準備

2.5.2. Backward for Non-Scalar Variables2.5.2 スカラーでない変数の逆伝播

When y is a vector, the most natural representation of the derivative of y with respect to a vector x is a matrix called the Jacobian that contains the partial derivatives of each component of y with respect to each component of x. Likewise, for higher-order y and x, the result of differentiation could be an even higher-order tensor.
英語のヒント
yがベクトルのとき、ベクトルxについてのyの導関数の最も自然な表現は、ヤコビ行列と呼ばれる行列で、xの各成分についてのyの各成分の偏導関数を含む。同様に、より高い階のyとxでは、微分の結果はさらに高い階のテンソルになりうる。
While Jacobians do show up in some advanced machine learning techniques, more commonly we want to sum up the gradients of each component of y with respect to the full vector x, yielding a vector of the same shape as x. For example, we often have a vector representing the value of our loss function calculated separately for each example among a batch of training examples. Here, we just want to sum up the gradients computed individually for each example.
英語のヒント
ヤコビ行列は発展的な機械学習の技術で確かに現れるが、もっと普通は、yの各成分の勾配を、ベクトルx全体について足し合わせ、xと同じ形状のベクトルを得たい。たとえば、訓練事例のバッチのなかの各事例について別々に計算した損失関数の値を表すベクトルがあることが多い。ここでは、各事例について個別に計算した勾配を足し合わせたいだけである。
Because deep learning frameworks vary in how they interpret gradients of non-scalar tensors, PyTorch takes some steps to avoid confusion. Invoking backward on a non-scalar elicits an error unless we tell PyTorch how to reduce the object to a scalar. More formally, we need to provide some vector 𝐯 such that backward will compute 𝐯⊤∂𝐱𝐲 rather than ∂𝐱𝐲. This next part may be confusing, but for reasons that will become clear later, this argument (representing 𝐯) is named gradient. For a more detailed description, see Yang Zhang’s Medium post.
英語のヒント
深層学習フレームワークによって、スカラーでないテンソルの勾配の解釈が異なるので、PyTorchは混乱を避けるための手を打っている。スカラーでないものに対してbackwardを呼び出すと、それをスカラーにどう縮約するかをPyTorchに伝えないかぎりエラーになる。より形式的には、backwardが∂𝐱𝐲ではなく𝐯⊤∂𝐱𝐲を計算するように、何らかのベクトル𝐯を与える必要がある。次の部分は紛らわしいかもしれないが、後で明らかになる理由から、この引数(𝐯を表す)はgradientと名づけられている。より詳しい説明は、Yang ZhangのMediumの記事を見てほしい。
x.grad.zero_()
y = x * x
y.backward(gradient=torch.ones(len(y)))  # Faster: y.sum().backward()
x.grad
tensor([0., 2., 4., 6.])