> ## Documentation Index
> Fetch the complete documentation index at: https://wb-21fd5541-feat-cli-docs-generator.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# PyTorch

<Card title="Try in Colab" href="https://colab.research.google.com/github/wandb/examples/blob/master/colabs/intro/Intro_to_Weights_%26_Biases.ipynb" icon="python" />

PyTorch は、特に研究者の間で、Python におけるディープラーニングの最も人気のあるフレームワークの一つです。W\&B は、PyTorch に対して一流のサポートを提供し、勾配のログから CPU と GPU 上でのコードのプロファイリングまで対応しています。

Colab ノートブックで私たちのインテグレーションを試してみてください。

<Card title="Try in Colab" href="https://colab.research.google.com/github/wandb/examples/blob/master/colabs/pytorch/Simple_PyTorch_Integration.ipynb" icon="python" />

また、[example repo](https://github.com/wandb/examples) では、スクリプトや [Fashion MNIST](https://github.com/wandb/examples/tree/master/examples/pytorch/pytorch-cnn-fashion) を使用した [Hyperband](https://arxiv.org/abs/1603.06560) によるハイパーパラメータ最適化などの例を含むものがあります。それが生成する [W\&B Dashboard](https://wandb.ai/wandb/keras-fashion-mnist/runs/5z1d85qs) もご覧いただけます。

## `wandb.watch` を使った勾配のログ

勾配を自動的にログするには、[`wandb.watch`](/ja/models/ref/python/watch) を呼び出して、PyTorch モデルを渡します。

```python theme={null}
import wandb

wandb.init(config=args)

model = ...  # モデルをセットアップする

# マジック
wandb.watch(model, log_freq=100)

model.train()
for batch_idx, (data, target) in enumerate(train_loader):
    output = model(data)
    loss = F.nll_loss(output, target)
    loss.backward()
    optimizer.step()
    if batch_idx % args.log_interval == 0:
        wandb.log({"loss": loss})
```

同じスクリプト内で複数のモデルを追跡する必要がある場合は、それぞれのモデルに対して `wandb.watch` を個別に呼び出すことができます。この関数の参照ドキュメントは[こちら](/ja/models/ref/python/watch)。

<Warning>
  勾配、メトリクス、およびグラフは、フォワード *および* バックワードパスの後に `wandb.log` が呼び出されるまでログされません。
</Warning>

## 画像とメディアのログ

画像データを持つ PyTorch `Tensors` を [`wandb.Image`](/ja/models/ref/python/data-types/image) に渡すことができ、[`torchvision`](https://pytorch.org/vision/stable/index.html) のユーティリティが自動的に画像に変換します。

```python theme={null}
images_t = ...  # PyTorch Tensors として画像を生成またはロードする
wandb.log({"examples": [wandb.Image(im) for im in images_t]})
```

PyTorch や他のフレームワークにおけるリッチメディアのログについての詳細は、[メディアログガイド](/ja/models/track/log/media/)をご覧ください。

メディアと一緒にモデルの予測や派生メトリクスなどの情報も含めたい場合は、`wandb.Table` を使用します。

```python theme={null}
my_table = wandb.Table()

my_table.add_column("image", images_t)
my_table.add_column("label", labels)
my_table.add_column("class_prediction", predictions_t)

# Table を W&B にログ
wandb.log({"mnist_predictions": my_table})
```

<Frame>
  <img src="https://mintcdn.com/wb-21fd5541-feat-cli-docs-generator/-vjxKu9fYIXeDZhD/images/integrations/pytorch_example_table.png?fit=max&auto=format&n=-vjxKu9fYIXeDZhD&q=85&s=482ba9e0ae6b9a1cd468b76d0855a5e5" alt="上記のコードはこのようなテーブルを生成します。このモデルは良好に見えます！" width="1784" height="1212" data-path="images/integrations/pytorch_example_table.png" />
</Frame>

データセットやモデルのログと視覚化についての詳細は、[W\&B Tables のガイド](/ja/models/tables/)をご覧ください。

## PyTorch コードのプロファイリング

<Frame>
  <img src="https://mintcdn.com/wb-21fd5541-feat-cli-docs-generator/-vjxKu9fYIXeDZhD/images/integrations/pytorch_example_dashboard.png?fit=max&auto=format&n=-vjxKu9fYIXeDZhD&q=85&s=75ffb6d1d3c0fd5f13584b1d131a5c6c" alt="W&B ダッシュボード内で PyTorch コード実行の詳細なトレースを確認します。" width="787" height="609" data-path="images/integrations/pytorch_example_dashboard.png" />
</Frame>

W\&B は [PyTorch Kineto](https://github.com/pytorch/kineto) の [Tensorboard プラグイン](https://github.com/pytorch/kineto/blob/master/tb_plugin/README) と直接統合されており、PyTorch コードのプロファイリング、CPU と GPU の通信の詳細の検査、ボトルネックや最適化を識別するためのツールを提供します。

```python theme={null}
profile_dir = "path/to/run/tbprofile/"
profiler = torch.profiler.profile(
    schedule=schedule,  # スケジュールの詳細はプロファイラードキュメントを参照
    on_trace_ready=torch.profiler.tensorboard_trace_handler(profile_dir),
    with_stack=True,
)

with profiler:
    ...  # プロファイルしたいコードをここで実行
    # 詳細な使用情報はプロファイラードキュメントを参照

# wandb アーティファクトを作成
profile_art = wandb.Artifact("trace", type="profile")
# pt.trace.json ファイルをアーティファクトに追加
profile_art.add_file(glob.glob(profile_dir + ".pt.trace.json"))
# アーティファクトをログ
profile_art.save()
```

[こちらの Colab](http://wandb.me/trace-colab)で作業中の例コードを見て実行できます。

<Warning>
  インタラクティブなトレースビューツールは、Chrome Trace Viewer に基づいており、Chrome ブラウザで最も良好に動作します。
</Warning>
