プリンキピア

第12章最適化アルゴリズム

12.5.1. Vectorization and Caches12.5.1 ベクトル化とキャッシュ

At the heart of the decision to use minibatches is computational efficiency. This is most easily understood when considering parallelization to multiple GPUs and multiple servers. In this case we need to send at least one image to each GPU. With 8 GPUs per server and 16 servers we already arrive at a minibatch size no smaller than 128.
英語のヒント
ミニバッチを使うという決定の核心にあるのは、計算の効率である。これは、複数のGPUと複数のサーバーへの並列化を考えると最もわかりやすい。この場合、各GPUに少なくとも1枚の画像を送る必要がある。サーバーあたり8個のGPUと16台のサーバーがあれば、すでにミニバッチの大きさは128を下回らない。
Things are a bit more subtle when it comes to single GPUs or even CPUs. These devices have multiple types of memory, often multiple types of computational units and different bandwidth constraints between them. For instance, a CPU has a small number of registers and then the L1, L2, and in some cases even L3 cache (which is shared among different processor cores). These caches are of increasing size and latency (and at the same time they are of decreasing bandwidth). Suffice to say, the processor is capable of performing many more operations than what the main memory interface is able to provide.
英語のヒント
単一のGPUや、さらにはCPUとなると、事情は少し微妙になる。これらの装置には、複数の種類のメモリ、しばしば複数の種類の計算ユニット、そしてそれらのあいだの異なる帯域の制約がある。たとえば、CPUには少数のレジスタがあり、その先にL1、L2、場合によってはL3のキャッシュ(異なるプロセッサのコアのあいだで共有される)がある。これらのキャッシュは、大きさと遅延が順に増えていく(そして同時に、帯域は順に減っていく)。要するに、プロセッサは、メインメモリのインターフェースが供給できるよりずっと多くの演算を実行できる。
First, a 2GHz CPU with 16 cores and AVX-512 vectorization can process up to 2⋅109⋅16⋅32=1012 bytes per second. The capability of GPUs easily exceeds this number by a factor of 100. On the other hand, a midrange server processor might not have much more than 100 GB/s bandwidth, i.e., less than one tenth of what would be required to keep the processor fed. To make matters worse, not all memory access is created equal: memory interfaces are typically 64 bit wide or wider (e.g., on GPUs up to 384 bit), hence reading a single byte incurs the cost of a much wider access.
英語のヒント
第一に、16コアでAVX-512のベクトル化をもつ2GHzのCPUは、毎秒最大2⋅109⋅16⋅32=1012バイトを処理できる。GPUの能力は、この数字を簡単に100倍上回る。一方、中くらいのサーバー用プロセッサの帯域は、100 GB/sをあまり超えないかもしれない。つまり、プロセッサに供給し続けるのに必要な量の10分の1にも満たない。さらに悪いことに、すべてのメモリアクセスが等しいわけではない。メモリのインターフェースはふつう64ビット幅かそれ以上(たとえばGPUでは最大384ビット)なので、1バイトを読むだけでも、もっとずっと幅の広いアクセスのコストがかかる。
Second, there is significant overhead for the first access whereas sequential access is relatively cheap (this is often called a burst read). There are many more things to keep in mind, such as caching when we have multiple sockets, chiplets, and other structures. See this Wikipedia article for a more in-depth discussion.
英語のヒント
第二に、最初のアクセスには大きなオーバーヘッドがあるのに対し、連続したアクセスは比較的安い(これはよくバースト読み出しと呼ばれる)。複数のソケット、チップレット、そのほかの構造があるときのキャッシュのように、心に留めておくべきことはもっとたくさんある。もっと掘り下げた議論は、このウィキペディアの記事を参照。
The way to alleviate these constraints is to use a hierarchy of CPU caches that are actually fast enough to supply the processor with data. This is the driving force behind batching in deep learning. To keep matters simple, consider matrix-matrix multiplication, say 𝐀=𝐁𝐂. We have a number of options for calculating 𝐀. For instance, we could try the following:
英語のヒント
これらの制約を和らげる方法は、プロセッサにデータを供給できるほど実際に速い、CPUのキャッシュの階層を使うことである。これが、深層学習でのバッチ処理の原動力である。話を簡単にするため、行列と行列の積、たとえば𝐀=𝐁𝐂を考えよう。𝐀を計算するにはいくつかの選択肢がある。たとえば、次を試せる。
  1. We could compute 𝐀ij=𝐁i,:𝐂:,j, i.e., we could compute it elementwise by means of dot products.
    英語のヒント
    𝐀ij=𝐁i,:𝐂:,jを計算できる。つまり、内積によって要素ごとに計算できる。
  2. We could compute 𝐀:,j=𝐁𝐂:,j, i.e., we could compute it one column at a time. Likewise we could compute 𝐀 one row 𝐀i,: at a time.
    英語のヒント
    𝐀:,j=𝐁𝐂:,jを計算できる。つまり、1列ずつ計算できる。同じように、𝐀を1行𝐀i,:ずつ計算することもできる。
  3. We could simply compute 𝐀=𝐁𝐂.
    英語のヒント
    単に𝐀=𝐁𝐂を計算できる。
  4. We could break 𝐁 and 𝐂 into smaller block matrices and compute 𝐀 one block at a time.
    英語のヒント
    𝐁と𝐂をもっと小さなブロック行列に分け、𝐀を1ブロックずつ計算できる。
If we follow the first option, we will need to copy one row and one column vector into the CPU each time we want to compute an element 𝐀ij. Even worse, due to the fact that matrix elements are aligned sequentially we are thus required to access many disjoint locations for one of the two vectors as we read them from memory. The second option is much more favorable. In it, we are able to keep the column vector 𝐂:,j in the CPU cache while we keep on traversing through 𝐁. This halves the memory bandwidth requirement with correspondingly faster access. Of course, option 3 is most desirable. Unfortunately, most matrices might not entirely fit into cache (this is what we are discussing after all). However, option 4 offers a practically useful alternative: we can move blocks of the matrix into cache and multiply them locally. Optimized libraries take care of this for us. Let’s have a look at how efficient these operations are in practice.
英語のヒント
一つ目の選択肢に従うと、要素𝐀ijを計算するたびに、行ベクトル一つと列ベクトル一つをCPUにコピーする必要がある。さらに悪いことに、行列の要素は順に並んでいるので、メモリから二つのベクトルを読むとき、そのうち一方については多くの離れた場所にアクセスしなければならない。二つ目の選択肢はずっと有利である。そこでは、𝐁をたどり続けるあいだ、列ベクトル𝐂:,jをCPUのキャッシュに置いておける。これにより、メモリの帯域の要求が半分になり、それに応じてアクセスが速くなる。もちろん、選択肢3が最も望ましい。残念ながら、ほとんどの行列はキャッシュに丸ごとは収まらないかもしれない(結局のところ、それがいま論じていることである)。しかし、選択肢4は実用上役に立つ代わりのやり方を与える。行列のブロックをキャッシュに移し、そこで局所的に掛け合わせられる。最適化されたライブラリがこれを引き受けてくれる。これらの演算が実際にどれくらい効率的かを見てみよう。
Beyond computational efficiency, the overhead introduced by Python and by the deep learning framework itself is considerable. Recall that each time we execute a command the Python interpreter sends a command to the MXNet engine which needs to insert it into the computational graph and deal with it during scheduling. Such overhead can be quite detrimental. In short, it is highly advisable to use vectorization (and matrices) whenever possible.
英語のヒント
計算の効率を超えて、Pythonと深層学習のフレームワーク自体がもたらすオーバーヘッドもかなりのものである。コマンドを実行するたびに、PythonのインタープリタがMXNetのエンジンにコマンドを送り、エンジンはそれを計算グラフに挿入し、スケジューリングのあいだにそれを処理しなければならないことを思い出そう。そうしたオーバーヘッドはかなり有害になりうる。手短に言えば、可能なときはいつでもベクトル化(と行列)を使うことを強く勧める。
%matplotlib inline
import time
import numpy as np
import torch
from torch import nn
from d2l import torch as d2l

A = torch.zeros(256, 256)
B = torch.randn(256, 256)
C = torch.randn(256, 256)
Since we will benchmark the running time frequently in the rest of the book, let’s define a timer.
英語のヒント
この本の残りでは実行時間を頻繁に計測するので、タイマーを定義しよう。
class Timer:  #@save
    """Record multiple running times."""
    def __init__(self):
        self.times = []
        self.start()

    def start(self):
        """Start the timer."""
        self.tik = time.time()

    def stop(self):
        """Stop the timer and record the time in a list."""
        self.times.append(time.time() - self.tik)
        return self.times[-1]

    def avg(self):
        """Return the average time."""
        return sum(self.times) / len(self.times)

    def sum(self):
        """Return the sum of time."""
        return sum(self.times)

    def cumsum(self):
        """Return the accumulated time."""
        return np.array(self.times).cumsum().tolist()

timer = Timer()
Element-wise assignment simply iterates over all rows and columns of 𝐁 and 𝐂 respectively to assign the value to 𝐀.
英語のヒント
要素ごとの代入では、単に𝐁と𝐂のすべての行と列をそれぞれ反復して、𝐀に値を代入する。
# Compute A = BC one element at a time
timer.start()
for i in range(256):
    for j in range(256):
        A[i, j] = torch.dot(B[i, :], C[:, j])
timer.stop()
1.7845737934112549
A faster strategy is to perform column-wise assignment.
英語のヒント
もっと速い戦略は、列ごとの代入を行うことである。
# Compute A = BC one column at a time
timer.start()
for j in range(256):
    A[:, j] = torch.mv(B, C[:, j])
timer.stop()
0.06541275978088379
Last, the most effective manner is to perform the entire operation in one block. Note that multiplying any two matrices 𝐁∈ℝm×n and 𝐂∈ℝn×p takes approximately 2mnp floating point operations, when scalar multiplication and addition are counted as separate operations (fused in practice). Thus, multiplying two 256×256 matrices takes 0.03 billion floating point operations. Let’s see what the respective speed of the operations is.
英語のヒント
最後に、最も効果的なやり方は、演算全体を一つのブロックで行うことである。スカラーの乗算と加算を別々の演算として数えると(実際には融合されている)、任意の二つの行列𝐁∈ℝm×nと𝐂∈ℝn×pを掛けるには、およそ2mnp回の浮動小数点演算がかかることに注意してほしい。したがって、二つの256×256行列を掛けるには、0.03ギガ回の浮動小数点演算がかかる。それぞれの演算の速さがどうなるかを見よう。
# Compute A = BC in one go
timer.start()
A = torch.mm(B, C)
timer.stop()

gigaflops = [0.03 / i for i in timer.times]
print(f'performance in Gigaflops: element {gigaflops[0]:.3f}, '
      f'column {gigaflops[1]:.3f}, full {gigaflops[2]:.3f}')
performance in Gigaflops: element 0.017, column 0.459, full 51.633