メインコンテンツへスキップ
W&B Sandboxes は現在プライベートプレビュー中で、招待制でのみご利用いただけます。利用登録をリクエストするには、サポート または担当の AISE にお問い合わせください。
このチュートリアルでは、W&B Sandbox 環境で PyTorch モデルをトレーニングします。これを行うには、適切な環境変数を設定して サンドボックス を起動し、必要な依存関係をインストールして、UCI Zoo データセットでシンプルなニューラルネットワークをトレーニングする Python スクリプトを実行します。

前提条件

始める前に、以下がそろっていることを確認してください。

W&B Python SDK をインストール

W&B Python SDK をインストールします。pip を使用してインストールできます。
pip install wandb

W&B にログインして認証する

まだログインしていない場合は、W&B にログインしてください。wandb login CLI コマンドを実行し、表示される案内に従って W&B アカウントにログインします。
wandb login
W&B が認証情報をどのように検索するかについて詳しくは、wandb login のリファレンスドキュメントを参照してください。

トレーニング スクリプトと依存関係をコピーする

このチュートリアルに必要なコードにアクセスするには、以下のドロップダウンを展開してください。コードをコピー&ペーストして、このチュートリアルと同じディレクトリ内にある 3 つの別々のファイルに保存します。次のセクションでは、これらのファイルを読み込み、W&B Sandbox 環境内で PyTorch モデルをトレーニングするスクリプトを実行します。
以下のコードを requirements.txt という名前のファイルにコピー&ペーストしてください。このファイルには、トレーニングスクリプトに必要な依存関係が含まれています。
requirements.txt
torch
pandas
ucimlrepo
scikit-learn
pyyaml
以下のコードを hyperparameters.yaml という名前の YAML ファイルにコピー&ペーストしてください。このファイルには、トレーニングスクリプトのハイパーパラメーターが含まれています。
hyperparameters.yaml
learning_rate: 0.1
epochs: 1000
model_type: Multivariate_neural_network_classifier
以下のコードを train.py という名前のファイルにコピー&ペーストしてください。このスクリプトは、UCI Zoo データセットでシンプルな PyTorch モデルをトレーニングし、トレーニング済みのモデルを zoo_wandb.pth という名前のファイルに保存します。
train.py
import argparse
import torch
from torch import nn
import yaml
import pandas as pd
from ucimlrepo import fetch_ucirepo

from sklearn.model_selection import train_test_split

class NeuralNetwork(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear_stack = nn.Sequential(
            nn.Linear(in_features=16 , out_features=16),
            nn.Sigmoid(),
            nn.Linear(in_features=16, out_features=7)
        )

    def forward(self, x):
        logits = self.linear_stack(x)
        return logits

def main(args):
    # 指定された設定ファイルからハイパーパラメーターを読み込む
    with open(args.config, 'r') as f:
        hyperparameter_config = yaml.safe_load(f)

    # データセットを取得
    zoo = fetch_ucirepo(id=111)

    # データ(pandas dataframe として)
    X = zoo.data.features
    y = zoo.data.targets

    print("features: ", X.shape, "type: ", type(X))
    print("labels: ", y.shape, "type: ", type(y))

    ## データを処理
    # データの型はモデルのデータ型と一致している必要があります。nn.Linear のデフォルトの dtype は torch.float32 です
    dataset = torch.tensor(X.values).type(torch.float32)

    # tensor に変換し、インデックスで扱えるようにラベルを 0~6 に変換する
    labels = torch.tensor(y.values)  - 1

    print("dataset: ", dataset.shape, "dtype: ",dataset.dtype)
    print("labels: ", labels.shape, "dtype: ",labels.dtype)

    torch.save(dataset, "zoo_dataset.pt")
    torch.save(labels, "zoo_labels.pt")

    # 後で参照できるようにし、再現性を確保するために、トレーニング用データセットの分割方法を記述する
    config = {
        "random_state" : 42,
        "test_size" : 0.25,
        "shuffle" : True
    }

    # データセットをトレーニング用とテスト用に分割
    X_train, X_test, y_train, y_test = train_test_split(
        dataset,labels,
        random_state=config["random_state"],
        test_size=config["test_size"],
        shuffle=config["shuffle"]
    )

    # ファイルをローカルに保存
    torch.save(X_train, "zoo_dataset_X_train.pt")
    torch.save(y_train, "zoo_labels_y_train.pt")

    torch.save(X_test, "zoo_dataset_X_test.pt")
    torch.save(y_test, "zoo_labels_y_test.pt")


    ## モデルを定義
    model = NeuralNetwork()
    loss_fn = nn.CrossEntropyLoss()
    optimizer = torch.optim.SGD(model.parameters(), lr=hyperparameter_config["learning_rate"])
    print(model)

    # トレーニングループ内で比較するため、初期のダミー損失値を設定
    prev_best_loss = 1e10

    # トレーニングループ
    for e in range(hyperparameter_config["epochs"] + 1):
        pred = model(X_train)
        loss = loss_fn(pred, y_train.squeeze(1))

        loss.backward()
        optimizer.step()
        optimizer.zero_grad()

        # 損失が改善した場合はモデルをチェックポイントとして保存
        if (e % 100 == 0) and (loss <= prev_best_loss):
            print("epoch: ", e, "loss:", loss.item())

            # 新しい最良の損失を保存
            prev_best_loss = loss

    print("Saving model...")
    PATH = 'zoo_wandb.pth'
    torch.save(model.state_dict(), PATH)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Train a simple neural network on the zoo dataset.")
    parser.add_argument("--config", type=str, required=True, help="Path to the hyperparameter configuration file.")
    args = parser.parse_args()
    main(args)

サンドボックスを作成してトレーニングスクリプトを実行する

次のコードスニペットでは、サンドボックスを作成し、その中にトレーニングスクリプトと依存関係をコピーし、トレーニングスクリプトを実行して、生成されたモデルファイルをダウンロードする方法を示します。次のセクションでは、このコードを1行ずつ説明します。 次のコードを Python ファイルにコピー&ペーストして実行してください。前の手順で作成した train.pyrequirements.txthyperparameters.yaml と同じディレクトリに保存してください。
train_in_sandbox.py
from pathlib import Path
from wandb.sandbox import Sandbox, NetworkOptions

# サンドボックスにマウントするファイル。サンドボックス内のパスと
# 各ファイルの内容をバイト列として辞書形式で指定する
mounted_files = [
    {"mount_path": "train.py", "file_content": Path("train.py").read_bytes()},
    {"mount_path": "requirements.txt", "file_content": Path("requirements.txt").read_bytes()},
        ]

print("Starting sandbox...")
with Sandbox.run(
    mounted_files=mounted_files,
    container_image="python:3.13",
    network=NetworkOptions(egress_mode="internet"),
    max_lifetime_seconds=3600
) as sandbox:
    sandbox.write_file("hyperparameters.yaml", Path("hyperparameters.yaml").read_bytes()).result()

    # 依存関係をインストールする
    print("Installing dependencies...")
    sandbox.exec(["pip", "install", "-r", "requirements.txt"], check=True).result()

    # スクリプトを実行する
    print("Running script...")
    result = sandbox.exec(["python", "train.py", "--config", "hyperparameters.yaml"]).result()
    print(result.stdout)
    print(result.stderr)
    print(f"Exit code: {result.returncode}")

    # 生成されたモデルファイルをローカルに保存する
    print("Downloading zoo_wandb.pth...")
    model_data = sandbox.read_file("zoo_wandb.pth").result()
    Path("zoo_wandb.pth").write_bytes(model_data)
    print("Saved zoo_wandb.pth")
前のコードスニペットでは、次の処理を行います。
  1. (6〜9行目) サンドボックスにマウントするファイル (train.pyrequirements.txt) を指定します。
  2. (12行目) サンドボックスを起動します。サンドボックスは、python:3.13 コンテナーイメージを使用し、インターネットアクセスを有効にし、最大有効期間を 3600 秒 (1 時間) に設定しています。
  3. (18行目) hyperparameters.yaml ファイルをサンドボックスに書き込みます。これにより、トレーニングスクリプト (train.py) の実行時にハイパーパラメーターへアクセスできるようになります。
  4. (22行目) 依存関係をインストールします。サンドボックス内で pip install -r requirements.txt コマンドを実行し、トレーニングスクリプトに必要な依存関係をインストールします。
  5. (26行目) トレーニングスクリプトを実行します。サンドボックス内で python train.py --config hyperparameters.yaml コマンドを実行して、トレーニングを開始します。このスクリプトは UCI Zoo データセットで PyTorch モデルをトレーニングし、トレーニング済みのモデルを zoo_wandb.pth という名前のファイルに保存します。
  6. (27〜29行目) 出力と終了コードを表示します。トレーニングスクリプトの実行完了後、デバッグと検証のために、標準出力、標準エラー出力、終了コードをコンソールに表示します。
  7. (33〜34行目) 生成されたモデルファイルをダウンロードします。read_file() メソッドを使用してサンドボックスから zoo_wandb.pth ファイルを読み取り、ローカルに保存します。