DGL 0.5ユーザガイド : 1 章 グラフ : 1.6 GPU で DGLGraph を使用する (翻訳/解説)
翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 09/16/2020 (0.5.1)
* 本ページは、DGL の以下のドキュメントを翻訳した上で適宜、補足説明したものです:
* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。
ユーザガイド : 1 章 グラフ : 1.6 GPU で DGLGraph を使用する
構築の間に 2 つの GPU tensor を渡すことにより GPU 上 で DGLGraph を作成できます。もう一つのアプローチは DGLGraph を GPU にコピーするために to() API を使用することです、これはグラフ構造と特徴データを与えられたデバイスにコピーします。
>>> import dgl >>> import torch as th >>> u, v = th.tensor([0, 1, 2]), th.tensor([2, 3, 4]) >>> g = dgl.graph((u, v)) >>> g.ndata['x'] = th.randn(5, 3) # original feature is on CPU >>> g.device device(type='cpu') >>> cuda_g = g.to('cuda:0') # accepts any device objects from backend framework >>> cuda_g.device device(type='cuda', index=0) >>> cuda_g.ndata['x'].device # feature data is copied to GPU too device(type='cuda', index=0) >>> # A graph constructed from GPU tensors is also on GPU >>> u, v = u.to('cuda:0'), v.to('cuda:0') >>> g = dgl.graph((u, v)) >>> g.device device(type='cuda', index=0)
GPU を伴う任意の演算は GPU 上で遂行されます。そして、それらは総ての tensor 引数が既に GPU 上に置かれていることを要求して結果 (グラフ or tenor) も GPU 上になります。更に、GPU グラフは GPU 上の特徴データだけを受け取ります。
>>> cuda_g.in_degrees() tensor([0, 0, 1, 1, 1], device='cuda:0') >>> cuda_g.in_edges([2, 3, 4]) # ok for non-tensor type arguments (tensor([0, 1, 2], device='cuda:0'), tensor([2, 3, 4], device='cuda:0')) >>> cuda_g.in_edges(th.tensor([2, 3, 4]).to('cuda:0')) # tensor type must be on GPU (tensor([0, 1, 2], device='cuda:0'), tensor([2, 3, 4], device='cuda:0')) >>> cuda_g.ndata['h'] = th.randn(5, 4) # ERROR! feature must be on GPU too! DGLError: Cannot assign node feature "h" on device cpu to a graph on device cuda:0. Call DGLGraph.to() to copy the graph to the same device.
以上