第2章準備
2.1.5. Saving Memory2.1.5 メモリの節約
Running operations can cause new memory to be allocated to host results. For example, if we write
Y = X + Y, we dereference the tensor that Y used to point to and instead point Y at the newly allocated memory. We can demonstrate this issue with Python’s id() function, which gives us the exact address of the referenced object in memory. Note that after we run Y = Y + X, id(Y) points to a different location. That is because Python first evaluates Y + X, allocating new memory for the result and then points Y to this new location in memory.英語のヒント
演算を実行すると、結果を置くために新しいメモリが割り当てられることがある。たとえば
Y = X + Yと書くと、Yが指していたテンソルへの参照を外し、代わりにYを新しく割り当てられたメモリに向ける。この問題は、Pythonのid()関数を使って示せる。この関数は、参照されているオブジェクトのメモリ上の正確なアドレスを返す。Y = Y + Xを実行した後、id(Y)が別の場所を指していることに注意してほしい。それは、PythonがまずY + Xを評価し、結果のために新しいメモリを割り当て、それからYをメモリ上のこの新しい場所に向けるからである。before = id(Y)
Y = Y + X
id(Y) == beforeFalseThis might be undesirable for two reasons. First, we do not want to run around allocating memory unnecessarily all the time. In machine learning, we often have hundreds of megabytes of parameters and update all of them multiple times per second. Whenever possible, we want to perform these updates in place. Second, we might point at the same parameters from multiple variables. If we do not update in place, we must be careful to update all of these references, lest we spring a memory leak or inadvertently refer to stale parameters.
英語のヒント
これは二つの理由で望ましくないかもしれない。第一に、いつも不必要にメモリを割り当てて回りたくはない。機械学習では、数百メガバイトのパラメータをもつことがよくあり、そのすべてを1秒に何度も更新する。できるかぎり、これらの更新はその場で行いたい。第二に、複数の変数から同じパラメータを指していることがある。その場で更新しないと、メモリリークを起こしたり、うっかり古くなったパラメータを参照したりしないよう、これらの参照をすべて更新するよう気をつけなければならない。
Fortunately, performing in-place operations is easy. We can assign the result of an operation to a previously allocated array
Y by using slice notation: Y[:] = <expression>. To illustrate this concept, we overwrite the values of tensor Z, after initializing it, using zeros_like, to have the same shape as Y.英語のヒント
幸い、その場での演算を行うのは簡単である。スライス記法
Y[:] = <expression>を使えば、演算の結果を、前もって割り当てた配列Yに代入できる。この考え方を示すために、テンソルZをzeros_likeでYと同じ形状に初期化した後、その値を上書きする。Z = torch.zeros_like(Y)
print('id(Z):', id(Z))
Z[:] = X + Y
print('id(Z):', id(Z))id(Z): 140381179266448
id(Z): 140381179266448If the value of
X is not reused in subsequent computations, we can also use X[:] = X + Y or X += Y to reduce the memory overhead of the operation.英語のヒント
Xの値をその後の計算で使い回さないなら、X[:] = X + YやX += Yを使って、演算のメモリのオーバーヘッドを減らすこともできる。before = id(X)
X += Y
id(X) == beforeTrue