第6章構築者のための手引き
6.7.3. Neural Networks and GPUs6.7.3 ニューラルネットワークとGPU
Similarly, a neural network model can specify devices. The following code puts the model parameters on the GPU.
英語のヒント
同様に、ニューラルネットワークのモデルもデバイスを指定できる。次のコードは、モデルのパラメータをGPU上に置く。
net = nn.Sequential(nn.LazyLinear(1))
net = net.to(device=try_gpu())We will see many more examples of how to run models on GPUs in the following chapters, simply because the models will become somewhat more computationally intensive.
英語のヒント
以降の章では、GPU上でモデルを走らせる例をもっとたくさん見ることになる。単純に、モデルがいくらか計算の負担の大きいものになるからである。
For example, when the input is a tensor on the GPU, the model will calculate the result on the same GPU.
英語のヒント
たとえば、入力がGPU上のテンソルであるとき、モデルは同じGPU上で結果を計算する。
net(X)tensor([[0.7802],
[0.7802]], device='cuda:0', grad_fn=<AddmmBackward0>)Let’s confirm that the model parameters are stored on the same GPU.
英語のヒント
モデルのパラメータが同じGPU上に保存されていることを確かめよう。
net[0].weight.data.devicedevice(type='cuda', index=0)Let the trainer support GPU.
英語のヒント
トレーナーがGPUに対応するようにしよう。
@d2l.add_to_class(d2l.Trainer) #@save
def __init__(self, max_epochs, num_gpus=0, gradient_clip_val=0):
self.save_hyperparameters()
self.gpus = [d2l.gpu(i) for i in range(min(num_gpus, d2l.num_gpus()))]
@d2l.add_to_class(d2l.Trainer) #@save
def prepare_batch(self, batch):
if self.gpus:
batch = [a.to(self.gpus[0]) for a in batch]
return batch
@d2l.add_to_class(d2l.Trainer) #@save
def prepare_model(self, model):
model.trainer = self
model.board.xlim = [0, self.max_epochs]
if self.gpus:
model.to(self.gpus[0])
self.model = modelIn short, as long as all data and parameters are on the same device, we can learn models efficiently. In the following chapters we will see several such examples.
英語のヒント
要するに、すべてのデータとパラメータが同じデバイス上にあるかぎり、モデルを効率よく学習できる。以降の章では、そうした例をいくつか見ていく。