Skip to content
Published on

AI開発環境完全ガイド:GPUサーバーセットアップからJupyter、VS Code、Dockerまで

Authors

概要

適切なAI開発環境のセットアップは戦いの半分です。適切な基盤なしでは、再現可能な実験、チームコラボレーション、高速なイテレーションサイクルはすべて不可能です。このガイドでは、AI/ML開発者が知っておくべきすべてを網羅します。初期のGPUサーバーセットアップから日常の開発ワークフローまで。

UbuntuへのCUDAインストール、Python環境管理、JupyterLabとVS Codeをプロとして使いこなす方法、そしてDockerコンテナで再現可能な実験環境を構築する方法を学びます。


1. AI開発環境の要件

1.1 ハードウェア推奨スペック

GPU(最優先)

AIリサーチにおいて、GPUは必須です。

  • エントリーレベル / 個人リサーチ: NVIDIA RTX 4080/4090(16-24GB VRAM)
  • 共有チームサーバー: NVIDIA A100 40GBまたは80GB
  • 大規模LLM学習: NVIDIA H100またはH200(80GB以上のVRAM)
  • クラウドオプション: AWS p3/p4d/p5、GCP A100/H100、Lambda Labs

CPU

GPU学習中、CPUは主にデータ前処理とローディングを担います。

  • 最小: 8コア16スレッド(Intel Core i9またはAMD Ryzen 9)
  • 推奨: 16コア以上(AMD Threadripper、Intel Xeon)
  • 最適なDataLoaderワーカー数 = CPUコア数の半分

RAM

  • 最小: 32GB
  • 推奨: 64GB(GPU VRAMの少なくとも4倍)
  • 大規模NLP: 128GB以上(トークン化、データローディング)

ストレージ

/home/user/          -> NVMe SSDOS、コード、環境)
/data/               -> NVMe SSDまたは高速HDD(学習データ)
/models/             -> HDDまたはNAS(モデルチェックポイント)
  • OSとパッケージ: NVMe SSD 500GB以上
  • データセット: NVMe SSD(I/O集約学習)または高性能HDD
  • チェックポイント: HDD 4TB以上(コスト効率の高い大容量ストレージ)

1.2 OSの選択

Ubuntu 22.04 LTS — 強く推奨

# Ubuntuのバージョンを確認
lsb_release -a

# 出力例:
# Ubuntu 22.04.3 LTS (Jammy Jellyfish)

Ubuntuを選ぶ理由:

  • NVIDIAの主要サポートプラットフォーム(最新ドライバー、CUDA、cuDNNがすぐに利用可能)
  • AI/MLコミュニティのドキュメントとパッケージエコシステムが最大
  • DockerとKubernetesとの最高の互換性
  • 安定したサーバー運用のための5年間のLTSサポート

macOS(M1/M2/M3)

Apple SiliconはMetal Performance Shadersを通じてGPUアクセラレーションをサポートします。

# MPSの利用可能性を確認(PyTorch)
python -c "import torch; print(torch.backends.mps.is_available())"

1.3 クラウド vs ローカル開発

観点ローカルサーバークラウド
初期コスト高い(ハードウェア)低い
継続コスト低い(電気代)高い(時間課金)
レイテンシなしインスタンス起動時間
スケーラビリティ限定的無制限
データセキュリティ高いポリシー依存
最適な用途継続的リサーチ大規模な一時実験

2. NVIDIA GPUドライバーとCUDAのインストール

2.1 nvidia-driverのインストール(Ubuntu)

# 1. 既存のNVIDIAパッケージを削除
sudo apt-get purge nvidia*
sudo apt autoremove

# 2. 利用可能なドライバーを確認
ubuntu-drivers devices

# 3. 推奨ドライバーを自動インストール
sudo ubuntu-drivers autoinstall

# または特定バージョンをインストール
sudo apt install nvidia-driver-535

# 4. 再起動
sudo reboot

# 5. インストールを確認
nvidia-smi

nvidia-smiの出力例:

+-----------------------------------------------------------------------------+
| NVIDIA-SMI 535.154.05   Driver Version: 535.154.05   CUDA Version: 12.2    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  NVIDIA A100-SXM4-40GB  Off| 00000000:00:04.0 Off |                    0 |
| N/A   34C    P0    56W / 400W |   1024MiB / 40960MiB |      0%      Default |
+-----------------------------------------------------------------------------+

2.2 CUDAツールキットのインストール

公式NVIDIAウェブサイトでプラットフォームに適したインストールコマンドを生成してください。

# CUDA 12.2のインストール(Ubuntu 22.04の例)
wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/cuda-keyring_1.1-1_all.deb
sudo dpkg -i cuda-keyring_1.1-1_all.deb
sudo apt-get update
sudo apt-get -y install cuda-toolkit-12-2

# 環境変数の設定(~/.bashrcまたは~/.zshrcに追加)
echo 'export PATH=/usr/local/cuda/bin:$PATH' >> ~/.bashrc
echo 'export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH' >> ~/.bashrc
source ~/.bashrc

# CUDAバージョンを確認
nvcc --version

2.3 cuDNNのインストール

# NVIDIA Developerアカウントが必要
# cuDNNをダウンロード後:

# Ubuntu 22.04 + CUDA 12.x向け
sudo dpkg -i cudnn-local-repo-ubuntu2204-8.9.7.29_1.0-1_amd64.deb
sudo cp /var/cudnn-local-repo-ubuntu2204-8.9.7.29/cudnn-local-*-keyring.gpg /usr/share/keyrings/
sudo apt-get update
sudo apt-get install libcudnn8 libcudnn8-dev libcudnn8-samples

# cuDNNバージョンを確認
cat /usr/include/cudnn_version.h | grep CUDNN_MAJOR -A 2

2.4 インストールの確認

# verify_gpu.py
import subprocess
import sys

def check_nvidia_smi():
    result = subprocess.run(['nvidia-smi'], capture_output=True, text=True)
    if result.returncode == 0:
        print("nvidia-smiは正常に動作しています")
        lines = result.stdout.split('\n')
        for line in lines:
            if 'NVIDIA' in line and 'Driver' in line:
                print(f"  {line.strip()}")
    else:
        print("nvidia-smiエラー:", result.stderr)

def check_pytorch_cuda():
    try:
        import torch
        print(f"\nPyTorchバージョン: {torch.__version__}")
        print(f"CUDA利用可能: {torch.cuda.is_available()}")
        if torch.cuda.is_available():
            print(f"CUDAバージョン: {torch.version.cuda}")
            print(f"cuDNNバージョン: {torch.backends.cudnn.version()}")
            print(f"GPU数: {torch.cuda.device_count()}")
            for i in range(torch.cuda.device_count()):
                props = torch.cuda.get_device_properties(i)
                print(f"  GPU {i}: {props.name} ({props.total_memory / 1024**3:.1f}GB)")

            # クイックテンソル演算テスト
            x = torch.randn(1000, 1000).cuda()
            y = torch.randn(1000, 1000).cuda()
            z = x @ y
            print(f"GPUテンソル演算テスト: 合格(形状: {z.shape})")
    except ImportError:
        print("PyTorchがインストールされていません")

def check_tensorflow_gpu():
    try:
        import tensorflow as tf
        print(f"\nTensorFlowバージョン: {tf.__version__}")
        gpus = tf.config.list_physical_devices('GPU')
        print(f"検出されたGPU: {len(gpus)}")
        for gpu in gpus:
            print(f"  {gpu}")
    except ImportError:
        print("TensorFlowがインストールされていません")

if __name__ == "__main__":
    check_nvidia_smi()
    check_pytorch_cuda()
    check_tensorflow_gpu()
python verify_gpu.py

3. Python環境管理

3.1 pyenvによるPythonバージョン管理

# pyenvのインストール
curl https://pyenv.run | bash

# ~/.bashrcまたは~/.zshrcに追加
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(pyenv init -)"' >> ~/.bashrc
source ~/.bashrc

# 利用可能なPythonバージョンを確認
pyenv install --list | grep -E "^\s+3\.(10|11|12)"

# Pythonをインストール
pyenv install 3.11.7
pyenv install 3.10.13

# グローバルバージョンを設定
pyenv global 3.11.7

# プロジェクト固有のバージョンを設定(そのディレクトリ内で)
cd my-project
pyenv local 3.10.13

# 現在のPythonバージョンを確認
python --version
pyenv versions

3.2 conda環境(GPUライブラリ向け)

condaはRAPIDSやcuMLなどのGPUアクセラレーションライブラリのインストールに特に便利です。

# Minicondaのインストール
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh -b
eval "$($HOME/miniconda3/bin/conda shell.bash hook)"
conda init

# チャンネルの設定
conda config --add channels conda-forge
conda config --add channels nvidia
conda config --set channel_priority strict

# AI/ML環境の作成
conda create -n aiml python=3.11 -y
conda activate aiml

# CUDA付きPyTorch
conda install pytorch torchvision torchaudio pytorch-cuda=12.1 -c pytorch -c nvidia

# RAPIDS(GPUアクセラレーションデータサイエンス)
conda install -c rapidsai -c conda-forge -c nvidia rapids=23.10 cuda-version=12.0

# 環境のエクスポートとインポート
conda env export > environment.yml
conda env create -f environment.yml

# 環境の一覧表示
conda env list

environment.ymlの例:

name: aiml
channels:
  - pytorch
  - nvidia
  - conda-forge
  - defaults
dependencies:
  - python=3.11
  - pytorch>=2.1
  - torchvision
  - cudatoolkit=12.1
  - numpy>=1.24
  - pandas>=2.0
  - scikit-learn>=1.3
  - pip:
      - transformers>=4.35
      - wandb>=0.16
      - pydantic>=2.0

3.3 poetryによる依存関係管理

# poetryのインストール
curl -sSL https://install.python-poetry.org | python3 -

# プロジェクトの作成
poetry new ml-research
cd ml-research

# 依存関係を追加
poetry add torch torchvision numpy pandas transformers
poetry add --group dev pytest black ruff mypy jupyter

# エクストラ付きでインストール
poetry add "torch[cuda]>=2.1"
poetry add "transformers[torch]>=4.35"

# すべての依存関係をインストール
poetry install

# 仮想環境の情報を確認
poetry env info
poetry env list

3.4 uv(超高速パッケージマネージャー)

# uvのインストール
curl -LsSf https://astral.sh/uv/install.sh | sh

# パッケージをインストール(pipより10〜100倍速い)
uv pip install torch torchvision numpy pandas

# 仮想環境を作成
uv venv .venv --python 3.11
source .venv/bin/activate

# requirements.txtからインストール(非常に速い)
uv pip install -r requirements.txt

# Pythonバージョンの管理
uv python install 3.11 3.12
uv python list

4. 高度なJupyterLabセットアップ

4.1 JupyterLabのインストールと拡張機能

# JupyterLabのインストール
pip install jupyterlab

# 便利な拡張機能のインストール
pip install jupyterlab-git           # Git統合
pip install jupyterlab-lsp           # 言語サーバープロトコル(オートコンプリート)
pip install python-lsp-server        # Python LSP
pip install jupyterlab-code-formatter  # コードフォーマッター
pip install black isort              # フォーマッター
pip install jupyterlab-vim           # Vimキーバインディング
pip install ipywidgets               # インタラクティブウィジェット

# インストール済み拡張機能を一覧表示
jupyter labextension list

# JupyterLabを起動
jupyter lab --ip=0.0.0.0 --port=8888 --no-browser

4.2 カーネル管理

# 利用可能なカーネルを一覧表示
jupyter kernelspec list

# 現在のconda/venv環境をカーネルとして登録
pip install ipykernel
python -m ipykernel install --user --name myenv --display-name "Python (myenv)"

# 特定のconda環境をカーネルとして登録
conda activate aiml
conda install ipykernel
python -m ipykernel install --user --name aiml --display-name "Python (aiml GPU)"

# カーネルを削除
jupyter kernelspec remove old-kernel

カスタムkernel.jsonの例:

{
  "argv": [
    "/home/user/miniconda3/envs/aiml/bin/python",
    "-m",
    "ipykernel_launcher",
    "-f",
    "{connection_file}"
  ],
  "display_name": "Python (aiml GPU)",
  "language": "python",
  "env": {
    "CUDA_VISIBLE_DEVICES": "0",
    "PYTHONPATH": "/home/user/projects"
  }
}

4.3 SSHトンネリングによるリモートJupyter

# サーバーでJupyterを起動(トークンなし)
jupyter lab --no-browser --port=8888 --ip=127.0.0.1

# ローカルマシンからSSHトンネルを作成
ssh -N -L 8888:localhost:8888 user@your-server.com

# ブラウザでアクセス
# http://localhost:8888

# セキュリティのためパスワードを設定
jupyter lab password

自動起動のためのsystemdサービス:

cat > /tmp/jupyter.service << 'EOF'
[Unit]
Description=Jupyter Lab
After=network.target

[Service]
Type=simple
User=your-username
WorkingDirectory=/home/your-username
ExecStart=/home/your-username/miniconda3/envs/aiml/bin/jupyter lab --no-browser --port=8888
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

sudo mv /tmp/jupyter.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable jupyter
sudo systemctl start jupyter

4.4 JupyterマジックコマンD

# タイミング
%time result = expensive_function()
%timeit -n 100 result = fast_function()  # 100回繰り返し

# 行ごとのプロファイリング
%load_ext line_profiler
%lprun -f my_function my_function(data)

# メモリプロファイリング
%load_ext memory_profiler
%memit result = memory_heavy_function()

# セルの内容をファイルに書き込む
%%writefile my_script.py
import numpy as np
# ...

# ファイルをセルに読み込む
%load my_script.py

# シェルコマンドを実行
!nvidia-smi
!pip list | grep torch
files = !ls -la *.py

# 環境変数を設定
%env CUDA_VISIBLE_DEVICES=0

# 自動リロード(コード変更を即座に反映)
%load_ext autoreload
%autoreload 2

# インラインmatplotlibプロット
%matplotlib inline

# 現在の変数を一覧表示
%who
%whos

# 以前の出力にアクセス
print(_)   # 最後の結果
print(__)  # 2つ前の結果

4.5 nbconvert(ノートブック変換)

# ノートブックをスクリプトに変換
jupyter nbconvert --to script notebook.ipynb

# HTMLに変換(共有用)
jupyter nbconvert --to html notebook.ipynb

# PDFに変換(LaTeXが必要)
jupyter nbconvert --to pdf notebook.ipynb

# 実行してHTMLに変換
jupyter nbconvert --to html --execute notebook.ipynb

# CLIからノートブックを実行してin-placeで変換
jupyter nbconvert --to notebook --execute --inplace notebook.ipynb

# パラメータ化実行(papermill)
pip install papermill
papermill input.ipynb output.ipynb -p lr 0.001 -p epochs 100

5. AI向けVS Code

5.1 必須拡張機能のインストール

# コマンドラインから拡張機能をインストール
code --install-extension ms-python.python           # Python
code --install-extension ms-toolsai.jupyter         # Jupyter
code --install-extension ms-python.pylance          # Pylance(LSP)
code --install-extension charliermarsh.ruff         # Ruffリンター
code --install-extension github.copilot             # GitHub Copilot
code --install-extension github.copilot-chat        # Copilot Chat
code --install-extension ms-vscode-remote.remote-ssh  # Remote SSH
code --install-extension ms-vscode-remote.remote-containers  # Dev Containers
code --install-extension eamodio.gitlens            # GitLens
code --install-extension njpwerner.autodocstring     # 自動docstring

5.2 VS Code設定(settings.json)

{
  "python.defaultInterpreterPath": "${workspaceFolder}/.venv/bin/python",
  "python.formatting.provider": "none",
  "[python]": {
    "editor.defaultFormatter": "charliermarsh.ruff",
    "editor.formatOnSave": true,
    "editor.codeActionsOnSave": {
      "source.fixAll.ruff": true,
      "source.organizeImports.ruff": true
    }
  },
  "pylance.typeCheckingMode": "basic",
  "python.analysis.autoImportCompletions": true,
  "python.analysis.indexing": true,
  "python.analysis.packageIndexDepths": [
    { "name": "torch", "depth": 5 },
    { "name": "transformers", "depth": 5 }
  ],
  "jupyter.askForKernelRestart": false,
  "jupyter.interactiveWindow.creationMode": "perFile",
  "editor.inlineSuggest.enabled": true,
  "github.copilot.enable": {
    "*": true,
    "yaml": true,
    "plaintext": false
  },
  "files.exclude": {
    "**/__pycache__": true,
    "**/*.pyc": true,
    ".mypy_cache": true,
    ".ruff_cache": true
  },
  "terminal.integrated.env.linux": {
    "CUDA_VISIBLE_DEVICES": "0"
  }
}

5.3 Remote SSHのセットアップ

# ローカルの~/.ssh/config
Host ml-server
    HostName 192.168.1.100
    User your-username
    IdentityFile ~/.ssh/id_rsa
    ForwardAgent yes
    ServerAliveInterval 60
    ServerAliveCountMax 3

Host gpu-cloud
    HostName gpu-server.example.com
    User ubuntu
    IdentityFile ~/.ssh/cloud-key.pem
    Port 22

VS CodeでのRemote SSHの使い方:

  1. Ctrl+Shift+P(MacではCmd+Shift+P)を押す
  2. "Remote-SSH: Connect to Host"を選択
  3. 設定済みのホストを選択

リモートサーバーへの拡張機能自動インストール:

{
  "remote.SSH.defaultExtensions": ["ms-python.python", "ms-toolsai.jupyter", "charliermarsh.ruff"]
}

5.4 Dev Containers

.devcontainer/devcontainer.jsonの例:

{
  "name": "AI Development",
  "build": {
    "dockerfile": "Dockerfile",
    "args": {
      "CUDA_VERSION": "12.1.1",
      "PYTHON_VERSION": "3.11"
    }
  },
  "runArgs": ["--gpus", "all", "--shm-size", "8g"],
  "mounts": [
    "source=/data,target=/data,type=bind",
    "source=${localEnv:HOME}/.cache,target=/root/.cache,type=bind"
  ],
  "customizations": {
    "vscode": {
      "extensions": [
        "ms-python.python",
        "ms-toolsai.jupyter",
        "charliermarsh.ruff",
        "github.copilot"
      ],
      "settings": {
        "python.defaultInterpreterPath": "/usr/local/bin/python"
      }
    }
  },
  "postCreateCommand": "pip install -e '.[dev]'",
  "remoteUser": "root"
}

6. GPU Dockerコンテナ

6.1 NVIDIA Container Toolkitのインストール

# NVIDIA Container Toolkitのインストール
distribution=$(. /etc/os-release;echo $ID$VERSION_ID)
curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey \
    | sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg

curl -s -L https://nvidia.github.io/libnvidia-container/$distribution/libnvidia-container.list \
    | sed 's#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g' \
    | sudo tee /etc/apt/sources.list.d/nvidia-container-toolkit.list

sudo apt-get update
sudo apt-get install -y nvidia-container-toolkit
sudo nvidia-ctk runtime configure --runtime=docker
sudo systemctl restart docker

# GPUアクセスのテスト
docker run --rm --gpus all nvidia/cuda:12.2.0-base-ubuntu22.04 nvidia-smi

6.2 AIプロジェクト用のDockerfile

# Dockerfile
FROM nvidia/cuda:12.1.1-cudnn8-devel-ubuntu22.04

# 環境変数
ENV DEBIAN_FRONTEND=noninteractive
ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1
ENV PIP_NO_CACHE_DIR=1

# システムパッケージ
RUN apt-get update && apt-get install -y \
    python3.11 \
    python3.11-dev \
    python3.11-venv \
    python3-pip \
    git \
    wget \
    curl \
    vim \
    htop \
    tmux \
    && rm -rf /var/lib/apt/lists/*

# Pythonのデフォルトを設定
RUN update-alternatives --install /usr/bin/python python /usr/bin/python3.11 1
RUN update-alternatives --install /usr/bin/pip pip /usr/bin/pip3 1

# pipをアップグレード
RUN pip install --upgrade pip setuptools wheel

# 作業ディレクトリ
WORKDIR /workspace

# Python依存関係(レイヤーキャッシュを最適化)
COPY requirements.txt .
RUN pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
RUN pip install -r requirements.txt

# ソースコードをコピー
COPY . .

# 編集可能パッケージとしてインストール
RUN pip install -e ".[dev]"

# rootではないユーザーを作成(セキュリティのベストプラクティス)
RUN useradd -m -u 1000 researcher
RUN chown -R researcher:researcher /workspace
USER researcher

# ポートを公開
EXPOSE 8888 6006

CMD ["jupyter", "lab", "--ip=0.0.0.0", "--port=8888", "--no-browser"]

6.3 サービススタック用のDocker Compose

# docker-compose.yml
version: '3.8'

services:
  # 学習コンテナ
  trainer:
    build:
      context: .
      dockerfile: Dockerfile
    runtime: nvidia
    environment:
      - NVIDIA_VISIBLE_DEVICES=0
      - CUDA_VISIBLE_DEVICES=0
      - WANDB_API_KEY=${WANDB_API_KEY}
    volumes:
      - ./src:/workspace/src
      - ./configs:/workspace/configs
      - /data:/data:ro
      - model-checkpoints:/workspace/checkpoints
      - ~/.cache/huggingface:/root/.cache/huggingface
    shm_size: '8g'
    command: python train.py

  # Jupyterノートブックサーバー
  notebook:
    build:
      context: .
      dockerfile: Dockerfile
    runtime: nvidia
    environment:
      - NVIDIA_VISIBLE_DEVICES=1
    ports:
      - '8888:8888'
    volumes:
      - ./notebooks:/workspace/notebooks
      - ./src:/workspace/src
      - /data:/data:ro
    command: jupyter lab --ip=0.0.0.0 --no-browser --allow-root

  # TensorBoard
  tensorboard:
    image: tensorflow/tensorflow:latest
    ports:
      - '6006:6006'
    volumes:
      - model-checkpoints:/workspace/checkpoints:ro
    command: tensorboard --logdir=/workspace/checkpoints --host=0.0.0.0

  # MLflow追跡サーバー
  mlflow:
    image: ghcr.io/mlflow/mlflow:v2.8.0
    ports:
      - '5000:5000'
    volumes:
      - mlflow-data:/mlflow
    command: mlflow server --host=0.0.0.0 --port=5000 --default-artifact-root=/mlflow/artifacts

volumes:
  model-checkpoints:
  mlflow-data:
# フルスタックを起動
docker-compose up -d

# ログを追跡
docker-compose logs -f trainer

# 特定のサービスを再起動
docker-compose restart notebook

# コンテナ内でGPU使用率を確認
docker-compose exec trainer nvidia-smi

# 停止してボリュームを削除
docker-compose down --volumes

6.4 GPU共有戦略

# 特定のGPUを割り当て
docker run --gpus '"device=0,1"' myimage  # GPU 0と1を使用
docker run --gpus '"device=2"' myimage     # GPU 2のみ使用

# MIG(Multi-Instance GPU)A100/H100向け
sudo nvidia-smi mig -i 0 --create-gpu-instance 3g.20gb
sudo nvidia-smi mig -i 0 --create-compute-instance 3g.20gb

# MIGインスタンスをコンテナに割り当て
docker run --gpus '"MIG-GPU-xxxxxxxx-xx-xx-xxxx-xxxxxxxxxxxx/x/x"' myimage

7. リモート開発環境

7.1 SSHベースのリモート開発

# SSHキーの生成(ローカルマシン)
ssh-keygen -t ed25519 -C "your-email@example.com"

# 公開キーをサーバーにコピー
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server.com

# または手動で
cat ~/.ssh/id_ed25519.pub | ssh user@server.com "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

# 最適化されたSSH設定(~/.ssh/config)
Host ml-server
    HostName server.example.com
    User researcher
    IdentityFile ~/.ssh/id_ed25519
    ControlMaster auto
    ControlPath ~/.ssh/cm_%r@%h:%p
    ControlPersist 10m
    ServerAliveInterval 30
    Compression yes

7.2 tmux(セッション持続性)

# tmuxのインストール
sudo apt install tmux

# 新しいセッションを開始
tmux new-session -s training

# セッションに再接続
tmux attach-session -t training

# セッションを一覧表示
tmux list-sessions

# キーショートカット(プレフィックス: Ctrl+B)
# Ctrl+B d    : セッションをデタッチ(SSH切断後も実行を継続)
# Ctrl+B c    : 新しいウィンドウを作成
# Ctrl+B n/p  : 次/前のウィンドウ
# Ctrl+B %    : 縦分割
# Ctrl+B "    : 横分割
# Ctrl+B z    : ペインのズームを切り替え

~/.tmux.confの設定:

# ~/.tmux.conf

# マウスサポートを有効化
set -g mouse on

# スクロールバッファを増加
set -g history-limit 50000

# ウィンドウ番号を1から始める
set -g base-index 1
setw -g pane-base-index 1

# カラーサポート
set -g default-terminal "screen-256color"
set -ga terminal-overrides ",xterm-256color:Tc"

# ステータスバーをカスタマイズ
set -g status-bg colour235
set -g status-fg colour136
set -g status-right '#[fg=colour166]%d %b #[fg=colour136]%H:%M '

# プレフィックスをCtrl+Aに変更(screenスタイル)
set -g prefix C-a
unbind C-b
bind C-a send-prefix

# 高速ペインナビゲーション
bind -n M-Left select-pane -L
bind -n M-Right select-pane -R
bind -n M-Up select-pane -U
bind -n M-Down select-pane -D

7.3 ファイル同期(rsync、sshfs)

# コードをローカルからサーバーに同期
rsync -avz --exclude '__pycache__' --exclude '.git' \
    ./my-project/ user@server:/home/user/my-project/

# 結果をサーバーからローカルに同期
rsync -avz user@server:/home/user/my-project/outputs/ ./outputs/

# 自動同期スクリプト
cat > sync.sh << 'EOF'
#!/bin/bash
rsync -avz \
    --exclude '__pycache__' \
    --exclude '.git' \
    --exclude '.venv' \
    --exclude '*.pyc' \
    --delete \
    ./ user@ml-server:/home/user/project/
echo "同期完了: $(date)"
EOF
chmod +x sync.sh

# sshfsでリモートファイルシステムをマウント
sudo apt install sshfs
mkdir -p ~/remote-server
sshfs user@server:/home/user ~/remote-server -o reconnect,ServerAliveInterval=15

# アンマウント
fusermount -u ~/remote-server

8. モニタリングツール

8.1 nvidia-smiウォッチ

# GPUステータスを1秒毎に更新
watch -n 1 nvidia-smi

# GPUメモリ使用量のみを表示
nvidia-smi --query-gpu=index,name,memory.used,memory.total,utilization.gpu \
    --format=csv -l 1

# CSVログに記録
nvidia-smi --query-gpu=timestamp,index,utilization.gpu,memory.used,temperature.gpu \
    --format=csv -l 1 > gpu_log.csv

8.2 nvtop

# nvtopのインストール(GPU向けhtop)
sudo apt install nvtop

# 実行
nvtop

8.3 PythonからのGPUモニタリング

# gpu_monitor.py
import subprocess
import time
from dataclasses import dataclass
from typing import List

@dataclass
class GPUStats:
    index: int
    name: str
    temperature: float
    utilization: float
    memory_used: int
    memory_total: int
    power_draw: float

def get_gpu_stats() -> List[GPUStats]:
    """nvidia-smiを通じてGPU統計を照会"""
    cmd = [
        'nvidia-smi',
        '--query-gpu=index,name,temperature.gpu,utilization.gpu,memory.used,memory.total,power.draw',
        '--format=csv,noheader,nounits'
    ]
    result = subprocess.run(cmd, capture_output=True, text=True)

    gpus = []
    for line in result.stdout.strip().split('\n'):
        parts = [p.strip() for p in line.split(',')]
        gpus.append(GPUStats(
            index=int(parts[0]),
            name=parts[1],
            temperature=float(parts[2]),
            utilization=float(parts[3]),
            memory_used=int(parts[4]),
            memory_total=int(parts[5]),
            power_draw=float(parts[6]) if parts[6] != 'N/A' else 0.0
        ))
    return gpus

def monitor_training(interval: int = 10, duration: int = 3600):
    """学習中のGPUをモニタリング"""
    print(f"GPUモニタリング開始(間隔: {interval}秒)")
    history = []

    start_time = time.time()
    while time.time() - start_time < duration:
        stats = get_gpu_stats()
        timestamp = time.time() - start_time

        for gpu in stats:
            mem_pct = gpu.memory_used / gpu.memory_total * 100
            print(
                f"[{timestamp:.0f}秒] GPU {gpu.index}: "
                f"util={gpu.utilization:.0f}% "
                f"mem={gpu.memory_used}/{gpu.memory_total}MB ({mem_pct:.0f}%) "
                f"temp={gpu.temperature:.0f}C "
                f"power={gpu.power_draw:.0f}W"
            )
            history.append({
                'timestamp': timestamp,
                'gpu_index': gpu.index,
                'utilization': gpu.utilization,
                'memory_used': gpu.memory_used,
                'temperature': gpu.temperature
            })

        time.sleep(interval)

    return history

if __name__ == "__main__":
    history = monitor_training(interval=5, duration=60)
    print(f"\n{len(history)}件の測定値を収集しました")

8.4 システムモニタリング

# htopのインストールと使用
sudo apt install htop
htop

# iotopでI/Oをモニタリング
sudo apt install iotop
sudo iotop -o  # アクティブなI/Oのあるプロセスのみを表示

# ディスクI/Oの統計
iostat -x 1 5

# メモリ使用量
free -h
vmstat 1 10

# ネットワークモニタリング
sudo apt install nethogs
sudo nethogs

# 総合モニタリングダッシュボード(glances)
pip install glances
glances

9. コード品質ツール

9.1 black + ruffの設定

# インストール
pip install black ruff pre-commit

# blackを実行
black .
black --line-length 88 src/

# ruffを実行
ruff check .
ruff check --fix .  # 自動修正
ruff format .       # フォーマット(blackの代替可能)

pyproject.tomlの設定:

[tool.black]
line-length = 88
target-version = ['py310', 'py311']
include = '\.pyi?$'

[tool.ruff]
line-length = 88
target-version = "py310"

[tool.ruff.lint]
select = [
    "E",   # pycodestyleエラー
    "W",   # pycodestyle警告
    "F",   # pyflakes
    "I",   # isort
    "N",   # pep8-naming
    "UP",  # pyupgrade
    "B",   # flake8-bugbear
]
ignore = ["E501", "B008"]

[tool.ruff.lint.isort]
known-first-party = ["my_package"]

9.2 pre-commitフック

# .pre-commit-config.yaml
repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.5.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-yaml
      - id: check-json
      - id: check-merge-conflict
      - id: detect-private-key
      - id: check-added-large-files
        args: ['--maxkb=10000']

  - repo: https://github.com/psf/black
    rev: 23.11.0
    hooks:
      - id: black

  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.1.6
    hooks:
      - id: ruff
        args: [--fix]

  - repo: https://github.com/pre-commit/mirrors-mypy
    rev: v1.7.1
    hooks:
      - id: mypy
        additional_dependencies:
          - types-requests
          - pydantic
# pre-commitのインストールと有効化
pre-commit install

# すべてのファイルで実行
pre-commit run --all-files

# 特定のフックを実行
pre-commit run black --all-files

9.3 pytestとカバレッジ

# インストール
pip install pytest pytest-cov pytest-xdist

# 基本的な実行
pytest tests/ -v

# カバレッジ付き
pytest tests/ --cov=src --cov-report=html --cov-report=term-missing

# 並列実行
pytest tests/ -n auto  # CPUコア数分のワーカー

# 最も遅いテストを表示
pytest tests/ --durations=10

# 速いテストのみ実行
pytest tests/ -m "not slow"

pyproject.tomlでのpytest設定:

[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = ["test_*.py", "*_test.py"]
python_classes = ["Test*"]
python_functions = ["test_*"]
markers = [
    "slow: テストが遅いことを示す",
    "gpu: GPUを必要とするテストを示す",
    "integration: 統合テスト"
]
addopts = [
    "-v",
    "--tb=short",
    "--cov=src",
    "--cov-report=html",
    "--cov-fail-under=80"
]

10. Weights & Biasesのセットアップ

10.1 インストールと初期化

# インストール
pip install wandb

# ログイン(APIキーを設定)
wandb login
# または環境変数で設定
export WANDB_API_KEY=your-api-key-here

10.2 W&Bの基本的な使い方

import wandb
import numpy as np

# 実験を初期化
run = wandb.init(
    project="bert-sentiment-analysis",
    name="run-001-baseline",
    config={
        "learning_rate": 2e-5,
        "batch_size": 32,
        "epochs": 10,
        "model": "bert-base-uncased",
        "optimizer": "adamw"
    },
    tags=["baseline", "bert", "nlp"],
    notes="ベースラインBERTファインチューニング実験"
)

config = wandb.config
print(f"学習率: {config.learning_rate}")

# メトリクスをログ
for epoch in range(config.epochs):
    train_loss = 2.0 - epoch * 0.15 + np.random.randn() * 0.1
    val_loss = 2.2 - epoch * 0.12 + np.random.randn() * 0.1
    val_acc = 0.5 + epoch * 0.04 + np.random.randn() * 0.01

    wandb.log({
        "epoch": epoch,
        "train/loss": train_loss,
        "val/loss": val_loss,
        "val/accuracy": val_acc,
        "learning_rate": config.learning_rate * (0.95 ** epoch)
    })

# 可視化をログ
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
x = np.linspace(0, 10, 100)
ax.plot(x, np.sin(x), label='予測')
ax.plot(x, np.cos(x), label='実際')
ax.legend()
wandb.log({"prediction_plot": wandb.Image(fig)})
plt.close()

wandb.finish()

10.3 アーティファクト管理

import wandb
import os

def save_model_artifact(model_path: str, run, metadata: dict = None):
    """モデルチェックポイントをW&Bアーティファクトとして保存"""
    artifact = wandb.Artifact(
        name="model-checkpoint",
        type="model",
        metadata=metadata or {}
    )
    artifact.add_file(model_path)
    run.log_artifact(artifact)
    print(f"モデルアーティファクトを保存しました: {model_path}")

def save_dataset_artifact(data_dir: str, run):
    """データセットをW&Bアーティファクトとして保存"""
    artifact = wandb.Artifact(
        name="training-dataset",
        type="dataset",
        description="前処理済み学習データセット"
    )
    artifact.add_dir(data_dir)
    run.log_artifact(artifact)

def load_model_artifact(artifact_name: str, version: str = "latest"):
    """モデルアーティファクトをダウンロード"""
    run = wandb.init(project="my-project", job_type="inference")
    artifact = run.use_artifact(f"{artifact_name}:{version}")
    artifact_dir = artifact.download()
    print(f"アーティファクトをダウンロードしました: {artifact_dir}")
    return artifact_dir

# 使用例
run = wandb.init(project="bert-training")

with open("/tmp/model.pt", "w") as f:
    f.write("model_weights")

save_model_artifact(
    "/tmp/model.pt",
    run,
    metadata={"accuracy": 0.94, "epoch": 10, "val_loss": 0.28}
)

wandb.finish()

10.4 ハイパーパラメータ最適化スイープ

import wandb
import numpy as np

# スイープ設定
sweep_config = {
    "method": "bayes",  # random、grid、またはbayes
    "metric": {
        "name": "val/accuracy",
        "goal": "maximize"
    },
    "parameters": {
        "learning_rate": {
            "distribution": "log_uniform_values",
            "min": 1e-5,
            "max": 1e-3
        },
        "batch_size": {
            "values": [16, 32, 64, 128]
        },
        "hidden_size": {
            "values": [256, 512, 768, 1024]
        },
        "dropout": {
            "distribution": "uniform",
            "min": 0.1,
            "max": 0.5
        },
        "num_layers": {
            "values": [2, 4, 6, 8]
        }
    },
    "early_terminate": {
        "type": "hyperband",
        "min_iter": 3
    }
}

def train_sweep():
    """各スイープ実行で呼ばれる学習関数"""
    run = wandb.init()
    config = wandb.config

    best_val_acc = 0.0

    for epoch in range(10):
        train_loss = 1.0 / (config.learning_rate * 1000) * np.random.uniform(0.8, 1.2)
        val_acc = min(0.99, config.hidden_size / 2000 + np.random.uniform(0, 0.1))

        if val_acc > best_val_acc:
            best_val_acc = val_acc

        wandb.log({
            "epoch": epoch,
            "train/loss": train_loss,
            "val/accuracy": val_acc
        })

    wandb.finish()

# スイープを作成して起動
sweep_id = wandb.sweep(sweep_config, project="hyperparameter-search")
print(f"スイープID: {sweep_id}")

# N回のトライアルでエージェントを実行
wandb.agent(sweep_id, function=train_sweep, count=20)

複数のサーバーで並列スイープを実行するには:

# サーバー1
wandb agent username/project/sweep-id

# サーバー2(同時に)
wandb agent username/project/sweep-id

まとめ

AI開発環境のセットアップに時間を投資することは、プロジェクトの全期間にわたってリターンをもたらします。このガイドで取り上げた主要な優先事項のまとめです。

必須の優先事項:

  1. CUDA環境:正しいGPUドライバーとCUDAツールキットのインストールがすべての基盤です。
  2. Python環境の分離:pyenv + conda/poetryを使用してプロジェクト毎に別々の環境を作成する。
  3. JupyterLab + VS Code:探索的分析にはJupyterを、本番開発にはVS Codeを使用する。
  4. Dockerコンテナ化:再現可能な実験環境を保証してチームコラボレーションを簡単にする。
  5. W&B実験追跡:すべての実験を追跡することで再現性とインサイトが得られる。

長期的に投資する価値のある分野:

  • pre-commitフックとCI/CDでコード品質を自動化する。
  • リモート開発(Remote SSH + tmux)をマスターして、どこからでも生産的に作業する。
  • GPUモニタリングを活用して学習の問題を早期に発見する。

参考文献