LoginSignup
87
109

More than 3 years have passed since last update.

自分の好きな環境で無料GPUを使う

Posted at

GPU使いたいけど高くて買えない…

機械学習を勉強していて、GPUがあった方が学習が高速に回せて、効率よく勉強できる。しかし、高くて買えない…

Google Colaboratoryという手もあるが、どうしてもJupyterNotebookになれないし、自分のいつもの環境で作業したい(ちょっとわがまま)。

そんなとき、こんな記事を見つけた!

ColabにsshでアクセスしてGPUを使う

ngrokからauthtokenを取得する

ngrokにアクセスし、LOGIN->Authentication->Your Authtokenを開く。
そうすると以下のような画面にauthtokenが表示されているのでコピーしておく。

Google Colaboratryでngrokを実行する

Google Colabを開きランタイム->ランタイムのタイプの設定を開き、ハードウェアアクセラレータをGPUにする。

以下のコードをコードブロックに貼り付けて実行する。
このとき先ほどコピーしたauthtokenを13行目のYOUR AUTHTOKENのところに貼り付ける。

# Install useful stuff
! apt install --yes ssh screen nano htop ranger git > /dev/null
# SSH setting
! echo "root:password" | chpasswd
! echo "PasswordAuthentication yes" > /etc/ssh/sshd_config
! echo "PermitUserEnvironment yes" >> /etc/ssh/sshd_config
! echo "PermitRootLogin yes" >> /etc/ssh/sshd_config
! service ssh restart > /dev/null
# Download ngrok
! wget -q -c -nc https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip
! unzip -qq -n ngrok-stable-linux-amd64.zip
# Run ngrok
authtoken = "YOUR AUTHTOKEN"
get_ipython().system_raw('./ngrok authtoken $authtoken && ./ngrok tcp 22 &')
! sleep 3
# Get the address for SSH
import requests
from re import sub
r = requests.get('http://localhost:4040/api/tunnels')
str_ssh = r.json()['tunnels'][0]['public_url']
str_ssh = sub("tcp://", "", str_ssh)
str_ssh = sub(":", " -p ", str_ssh)
str_ssh = "ssh root@" + str_ssh
print(str_ssh)

実行がうまくいくと以下のように表示される。

WARNING: apt does not have a stable CLI interface. Use with caution in scripts.

ssh root@0.tcp.ngrok.io -p XXXXX

VSCodeで開いて、使ってみる

VSCodeのRemote-SSHの機能を使ってssh root@0.tcp.ngrok.io -p XXXXXにssh接続してみる。パスワードを求められるが、! echo "root:password" | chpasswdで指定していたpasswordと打てばよい。

適当にmain.pyなどを作り、以下のコードでGPUが使えることを確認

import torch

print(torch.cuda.is_available())
# True

使えた!

検証

CIFAR10学習させるというタスクで検証を行いました。
実際に使ったコードはこちら

比較に使ったのは以下の環境で、エポック数5で実施しました

GPUあり GPUなし
OS Ubuntu 18.04.3 LTS macOS Catalina v.10.15.5
torch 1.4.0 1.5.1

torchのバージョンを合わせられなかったのは怠惰。

結果(1回ずつしか実行していないので決して正しくない)

速度
GPUあり 256.162
GPUなし 320.412

速度が20%くらい速くなった!

最後に

ColabではPytorch, Kerasなどの環境構築が予めされているので、それもまた便利!

87
109
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
87
109