リモートサーバーでのVS Code開発環境構築
ローカルマシンからリモートサーバーにVS Codeで接続する手順を解説します。まず、ローカル側に「Remote - SSH」拡張機能をインストールします。次に、ローカルとリモートのVS Codeバージョンを整合させる必要があります。
バージョン確認とサーバー準備
ローカルVS Codeでバージョン情報を取得します:
Ctrl+Shift+P → "About: About Visual Studio Code" を実行
表示される情報から以下をメモします:
- バージョン番号:1.107.1(例)
- コミットハッシュ:994fd12f8d3a5aa16f17d42c041e5809167e845a(リモートディレクトリ名として使用)
リモートサーバーでのセットアップ
SSHでリモートサーバーに接続し、以下のコマンドを実行します:
# サーバーディレクトリ作成
mkdir -p ~/.vscode-server/bin/994fd12f8d3a5aa16f17d42c041e5809167e845a
# ダウンロードディレクトリに移動
cd ~/.vscode-server/bin/994fd12f8d3a5aa16f17d42c041e5809167e845a
# サーバーパッケージ取得
curl -O https://update.code.visualstudio.com/commit:994fd12f8d3a5aa16f17d42c041e5809167e845a/server-linux-x64/stable
# 展開
tar -xzf stable
# 必要に応じてシンボリックリンク作成
ln -sf ./server-linux-x64/bin/code-remote ./code
SSH接続設定
VS Codeの「リモートエクスプローラー」からSSHホストを追加します。接続文字列の形式:
# 基本形:ssh ユーザー名@サーバーIP -p ポート番号
ssh develop@192.168.1.100 -p 2222
深層学習フレームワーク互換性表
| PyTorch | TorchVision | CUDA対応バージョン | Python互換範囲 |
|---|---|---|---|
| 0.4.0 | 0.2.2 | 8.0, 9.0, 9.1 | 3.5 - 3.7 |
| 1.0.0 | 0.2.1 | 8.0, 9.0, 10.0 | 3.5 - 3.7 |
| 1.4.0 | 0.5.0 | 9.2, 10.1 | 3.5 - 3.8 |
| 1.7.0 | 0.8.1 | 10.1, 10.2, 11.0 | 3.6 - 3.8 |
| 1.10.0 | 0.11.1 | 10.2, 11.1, 11.3 | 3.6 - 3.9 |
| 1.13.0 | 0.14.0 | 11.6, 11.7 | 3.7 - 3.11 |
| 2.0.0 | 0.15.0 | 11.7, 11.8 | 3.8 - 3.11 |
| 2.1.0 | 0.16.0 | 11.8, 12.1 | 3.8 - 3.11 |
Weights & Biases 実験管理基礎
コア関数の実装パターン
認証処理
import wandb
# APIキーによる認証
auth_result = wandb.login(
api_key="your_api_key_here", # 文字列: APIキーを直接指定
force_relogin=True, # ブール値: 既存認証情報を上書き
host_url="https://api.wandb.ai", # 文字列: カスタムサーバーURL
anonymous_mode="never" # 文字列: "never"/"allow"/"must"
)
実験実行初期化
experiment = wandb.init(
# 識別情報
project_name="cv-experiments", # 文字列: プロジェクト名(必須)
team_name="research-lab", # 文字列: チーム/ユーザー名
experiment_name="resnet50-exp1", # 文字列: 実験名
unique_id="run_20240115_001", # 文字列: カスタムID(再開用)
group_name="ablation-study", # 文字列: 実験グループ
task_category="train", # 文字列: タスク種別
tag_list=["baseline", "resnet"], # リスト: タグ
description="ResNet50ベースライン実験" # 文字列: 詳細説明
# 設定と再開
hyperparams={"lr": 0.001, "bs": 64}, # 辞書: ハイパーパラメータ
resume_option="allow", # ブール値/文字列: 再開設定
allow_config_edit=True, # ブール値: 設定値の変更許可
reinit_strategy="finish_previous" # 文字列: 再初期化戦略
)
メトリクス記録
# スカラー値の記録
experiment.log({
"train_loss": 0.45,
"val_accuracy": 0.892,
"current_epoch": 10
})
# 画像データのバッチ記録
experiment.log({
"predictions": [
wandb.Image(pred_img1, caption="予測1"),
wandb.Image(pred_img2, caption="予測2")
]
})
# 遅延コミットによる効率化
experiment.log({"loss": 0.38}, commit=False)
experiment.log({"metric": 0.91}, commit=True) # ここで一括送信
モデル監視
# 勾配とパラメータの分布監視
experiment.watch(
target_model, # torch.nn.Module/tf.keras.Model
criterion_func=None, # 損失関数(オプション)
log_type="all", # 文字列: "gradients"/"parameters"/"all"
frequency=50, # 整数: 記録頻度(ステップ単位)
include_graph=True, # ブール値: 計算グラフ記録
log_all_layers=False # ブール値: 全レイヤー記録
)
ファイル管理
# モデルファイルのアップロード
experiment.save(
file_path="checkpoints/model_best.pth", # 文字列: ファイルパス(ワイルドカード可)
base_directory="./", # 文字列: 基準ディレクトリ
upload_policy="end" # 文字列: "live"/"now"/"end"
)
# クラウドファイルの復元
restored_path = experiment.restore(
cloud_path="model_final.pth", # 文字列: クラウド上のパス
source_run="team/project/run_20240115_001", # 文字列: ソース実行ID
local_root="./restored", # 文字列: ローカル保存先
overwrite_existing=True # ブール値: 上書き許可
)
実験終了処理
experiment.terminate(
exit_status=0, # 整数: 終了コード
silent_mode=True # ブール値: ログ出力抑制
)
Runオブジェクトの主要メソッド
# 設定値の動的操作
run.config.learning_rate = 0.0005
batch_size = run.config["batch_size"]
# 要約指標の設定
run.summary["最高精度"] = 0.956
# Artifactの作成と登録
dataset_artifact = wandb.Artifact(
name="cifar10-preprocessed",
artifact_type="dataset",
description="前処理済みCIFAR10データセット",
metadata={"samples": 50000, "classes": 10}
)
dataset_artifact.add_file("data/processed/train.pt")
dataset_artifact.add_directory("data/processed/annotations/")
run.log_artifact(dataset_artifact)
# Artifactの利用
pretrained_model = run.use_artifact(
artifact_path="research-lab/cv-experiments/resnet50-v3:latest",
artifact_type="model"
)
model_path = pretrained_model.download()
# モデルレジストリへのリンク
run.register_model(
model_path="checkpoints/final_model.pth",
registry_name="image-classifier-prod",
version_tag="v2.1",
aliases=["staging", "candidate"]
)
# メトリクス可視化設定
run.configure_plot(
metric="validation_loss",
step_reference="epoch",
aggregation="min",
optimization_target="minimize"
)
可視化データクラス
# 画像可視化
annotated_img = wandb.Image(
image_array, # np.ndarray/PIL.Image/Tensor
caption="セグメンテーション結果",
class_labels={0: "背景", 1: "物体"},
bounding_boxes={"pred": {"box_data": [...]}},
segmentation_mask=mask_array
)
# テーブル作成
results_table = wandb.Table(
column_names=["入力画像", "推論結果", "信頼度スコア"],
table_data=[
[wandb.Image(img1), "猫", 0.95],
[wandb.Image(img2), "犬", 0.87]
]
)
run.log({"推論サンプル": results_table})
# 動画/音声
video_clip = wandb.Video(video_tensor, fps=24, caption="推論過程")
audio_sample = wandb.Audio(waveform, sample_rate=22050, caption="生成音声")
# カスタムプロット
import numpy as np
true_labels = np.array([0, 1, 1, 0])
pred_scores = np.array([0.2, 0.8, 0.7, 0.3])
roc_plot = wandb.plot.roc_curve(true_labels, pred_scores, title="ROC曲線")
run.log({"性能評価": roc_plot})
ハイパーパラメータ探索
# 探索設定
sweep_configuration = {
"strategy": "bayesian", # 探索方法: "grid"/"random"/"bayesian"
"objective": {
"metric_name": "val_accuracy",
"optimization": "maximize"
},
"parameter_space": {
"dropout_rate": {"min": 0.1, "max": 0.5},
"hidden_units": {"values": [128, 256, 512]},
"optimizer": {"values": ["adam", "sgd"]}
}
}
sweep_identifier = wandb.sweep(
sweep_configuration,
project_name="hpo-experiments",
team_name="research-lab"
)
# エージェント実行
def training_routine():
trial = wandb.init()
# wandb.configからパラメータ取得
model = build_model(trial.config.hidden_units, trial.config.dropout_rate)
accuracy = train_and_evaluate(model, trial.config.optimizer)
trial.log({"val_accuracy": accuracy})
wandb.agent(
sweep_id=sweep_identifier,
target_function=training_routine,
max_runs=30
)
APIによるデータ管理
api_client = wandb.Api()
# プロジェクト情報取得
target_project = api_client.project("hpo-experiments", entity="research-lab")
# 条件付きRun検索
filtered_runs = api_client.runs(
"research-lab/hpo-experiments",
filters={"config.dropout_rate": {"$gt": 0.3}}
)
for run_item in filtered_runs:
print(f"{run_item.name}: {run_item.summary.get('val_accuracy')}")
# Artifact操作
dataset_version = api_client.artifact(
"research-lab/hpo-experiments/dataset-v2:latest"
)
local_path = dataset_version.download()
# カスタムダッシュボード作成
api_client.create_custom_chart(
entity_name="research-lab",
chart_name="hpo-analysis",
display_label="ハイパーパラメータ分析",
specification_type="vega3",
chart_spec={"$schema": "https://vega.github.io/schema/vega-lite/v3.json", ...}
)
Weights & Biases CLI操作
基本コマンド
# 認証
wandb login --api-key="your_key" --relogin --host="https://api.wandb.ai"
# 設定初期化
wandb init --project="new-project" --entity="research-lab" --reset
# オフラインログの同期
wandb sync ./wandb/offline-run-20240115_001 --clean --append
# 動作モード切替
wandb offline # ローカルのみ記録
wandb online # クラウド同期再開
# 強制終了
wandb finish run_20240115_001
Sweep操作
# Sweep作成
wandb sweep sweep_config.yaml --project="hpo-experiments" --name="sweep-001"
# エージェント起動
wandb agent research-lab/hpo-experiments/sweep_abc123 --count 50
Artifact管理
# アップロード
wandb artifact put ./data/processed --type=dataset --name="cifar10-v2"
# ダウンロード
wandb artifact get research-lab/hpo-experiments/model-best:v3
プロジェクト管理
wandb project list --entity="research-lab"
wandb runs list --project="hpo-experiments" --state="finished"
実験再開設定
環境変数による再開動作の制御:
# mustモード(厳格な再開)
export WANDB_RUN_ID="run_20240115_001"
export WANDB_RESUME="must"
# allowモード(柔軟な再開)
export WANDB_RESUME="allow"
# neverモード(新規強制)
export WANDB_RESUME="never"
# autoモード(自動検出)
export WANDB_RESUME="auto"
各シェルでの実行例:
# Bash/Zsh
WANDB_RUN_ID="run_20240115_001" WANDB_RESUME="must" python train.py
# Fish
env WANDB_RUN_ID="run_20240115_001" WANDB_RESUME="must" python train.py
# PowerShell
$env:WANDB_RUN_ID="run_20240115_001"; $env:WANDB_RESUME="must"; python train.py
システム監視ツール
GPU監視
# 1秒間隔でのステータス確認
watch -n 1 nvidia-smi
# インタラクティブなGPUモニタ
nvtop
# CPU/RAM詳細モニタ
htop
タスクキューイング
task-spoolerによるジョブ連続実行:
# インストール
sudo apt-get update && sudo apt-get install -y task-spooler
# キュー状態確認
tsp
# ジョブ追加
tsp python train_model_a.py
tsp python train_model_b.py
tsp python evaluate_models.py