プリンキピア

第2章準備

2.5.3. Detaching Computation2.5.3 計算の切り離し

Sometimes, we wish to move some calculations outside of the recorded computational graph. For example, say that we use the input to create some auxiliary intermediate terms for which we do not want to compute a gradient. In this case, we need to detach the respective computational graph from the final result. The following toy example makes this clearer: suppose we have z = x * y and y = x * x but we want to focus on the direct influence of x on z rather than the influence conveyed via y. In this case, we can create a new variable u that takes the same value as y but whose provenance (how it was created) has been wiped out. Thus u has no ancestors in the graph and gradients do not flow through u to x. For example, taking the gradient of z = x * u will yield the result u, (not 3 * x * x as you might have expected since z = x * x * x).
英語のヒント
記録された計算グラフの外に、一部の計算を移したいことがある。たとえば、入力を使って、勾配を計算したくない補助的な中間項を作るとしよう。この場合、それぞれの計算グラフを最終結果から切り離す必要がある。次の簡単な例でこれがはっきりする。z = x * yとy = x * xがあるが、yを経由して伝わる影響ではなく、xがzに与える直接の影響に注目したいとしよう。この場合、yと同じ値をとるが、その由来(どう作られたか)が消された新しい変数uを作れる。したがってuはグラフのなかに祖先をもたず、勾配はuを通ってxへは流れない。たとえば、z = x * uの勾配をとると、結果はuになる(z = x * x * xなので期待したかもしれない3 * x * xではない)。
x.grad.zero_()
y = x * x
u = y.detach()
z = u * x

z.sum().backward()
x.grad == u
tensor([True, True, True, True])
Note that while this procedure detaches y’s ancestors from the graph leading to z, the computational graph leading to y persists and thus we can calculate the gradient of y with respect to x.
英語のヒント
この手続きは、zに至るグラフからyの祖先を切り離すが、yに至る計算グラフは残っているので、xについてのyの勾配は計算できることに注意してほしい。
x.grad.zero_()
y.sum().backward()
x.grad == 2 * x
tensor([True, True, True, True])