第13章計算の性能
13.1.3. Hybridizing the Sequential Class13.1.3 Sequentialクラスのハイブリッド化
The easiest way to get a feel for how hybridization works is to consider deep networks with multiple layers. Conventionally the Python interpreter will need to execute the code for all layers to generate an instruction that can then be forwarded to a CPU or a GPU. For a single (fast) computing device this does not cause any major issues. On the other hand, if we use an advanced 8-GPU server such as an AWS P3dn.24xlarge instance Python will struggle to keep all GPUs busy. The single-threaded Python interpreter becomes the bottleneck here. Let’s see how we can address this for significant parts of the code by replacing
Sequential with HybridSequential. We begin by defining a simple MLP.英語のヒント
ハイブリッド化がどう働くかの感触をつかむ最も簡単な方法は、複数の層をもつ深いネットワークを考えることである。従来は、Pythonのインタープリタがすべての層のコードを実行して、CPUやGPUに送れる命令を生成する必要がある。一つの(速い)計算装置では、これは大きな問題を起こさない。一方、AWS P3dn.24xlargeインスタンスのような高度な8GPUのサーバーを使うと、PythonはすべてのGPUを忙しく保つのに苦労する。ここでは、シングルスレッドのPythonのインタープリタがボトルネックになる。
SequentialをHybridSequentialに置き換えることで、コードのかなりの部分についてこれにどう対処できるかを見よう。まず、単純なMLPを定義する。import torch
from torch import nn
from d2l import torch as d2l
# Factory for networks
def get_net():
net = nn.Sequential(nn.Linear(512, 256),
nn.ReLU(),
nn.Linear(256, 128),
nn.ReLU(),
nn.Linear(128, 2))
return net
x = torch.randn(size=(1, 512))
net = get_net()
net(x)tensor([[-0.1602, 0.0003]], grad_fn=<AddmmBackward0>)By converting the model using
torch.jit.script function, we are able to compile and optimize the computation in the MLP. The model’s computation result remains unchanged.英語のヒント
torch.jit.script関数を使ってモデルを変換することで、MLPの計算をコンパイルして最適化できる。モデルの計算結果は変わらない。net = torch.jit.script(net)
net(x)tensor([[-0.1602, 0.0003]], grad_fn=<AddmmBackward0>)This seems almost too good to be true: write the same code as before and simply convert the model using
torch.jit.script. Once this happens the network is optimized (we will benchmark the performance below).英語のヒント
これはほとんど話がうますぎるように思える。前と同じコードを書き、
torch.jit.scriptを使ってモデルを変換するだけである。これが済むと、ネットワークは最適化される(性能は下で計測する)。13.1.3.1. Acceleration by Hybridization13.1.3.1 ハイブリッド化による高速化
To demonstrate the performance improvement gained by compilation we compare the time needed to evaluate
net(x) before and after hybridization. Let’s define a class to measure this time first. It will come handy throughout the chapter as we set out to measure (and improve) performance.英語のヒント
コンパイルで得られる性能の改善を示すため、ハイブリッド化の前と後で
net(x)を評価するのにかかる時間を比べる。まず、この時間を測るクラスを定義しよう。性能を測り(そして改善し)始めるので、この章を通じて役に立つ。#@save
class Benchmark:
"""For measuring running time."""
def __init__(self, description='Done'):
self.description = description
def __enter__(self):
self.timer = d2l.Timer()
return self
def __exit__(self, *args):
print(f'{self.description}: {self.timer.stop():.4f} sec')Now we can invoke the network twice, once with and once without torchscript.
英語のヒント
では、ネットワークを2回、torchscriptありで1回、なしで1回呼び出せる。
net = get_net()
with Benchmark('Without torchscript'):
for i in range(1000): net(x)
net = torch.jit.script(net)
with Benchmark('With torchscript'):
for i in range(1000): net(x)Without torchscript: 2.1447 sec
With torchscript: 4.0545 secAs is observed in the above results, after an
nn.Sequential instance is scripted using the torch.jit.script function, computing performance is improved through the use of symbolic programming.英語のヒント
上の結果で見られるように、
torch.jit.script関数を使ってnn.Sequentialインスタンスをスクリプト化すると、記号的プログラミングを使うことで計算の性能が改善する。13.1.3.2. Serialization13.1.3.2 シリアライズ
One of the benefits of compiling the models is that we can serialize (save) the model and its parameters to disk. This allows us to store a model in a manner that is independent of the front-end language of choice. This allows us to deploy trained models to other devices and easily use other front-end programming languages. At the same time the code is often faster than what can be achieved in imperative programming. Let’s see the
save function in action.英語のヒント
モデルをコンパイルする利点の一つは、モデルとそのパラメータをディスクにシリアライズ(保存)できることである。これにより、選んだフロントエンドの言語に依存しないやり方でモデルを格納できる。これにより、訓練したモデルをほかの装置に配備し、ほかのフロントエンドのプログラミング言語を簡単に使える。同時に、そのコードは、命令型プログラミングで達成できるものより速いことが多い。
save関数が動くところを見よう。net.save('my_mlp')
!ls -lh my_mlp*-rw-r--r-- 1 ci ci 651K Aug 18 19:32 my_mlp