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

# PyTorch

export const ColabLink = ({url}) => <a href={url} target="_blank" rel="noopener noreferrer" className="colab-link">
    <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
      <path d="M14.25.18l.9.2.73.26.59.3.45.32.34.34.25.34.16.33.1.3.04.26.02.2-.01.13V8.5l-.05.63-.13.55-.21.46-.26.38-.3.31-.33.25-.35.19-.35.14-.33.1-.3.07-.26.04-.21.02H8.77l-.69.05-.59.14-.5.22-.41.27-.33.32-.27.35-.2.36-.15.37-.1.35-.07.32-.04.27-.02.21v3.06H3.17l-.21-.03-.28-.07-.32-.12-.35-.18-.36-.26-.36-.36-.35-.46-.32-.59-.28-.73-.21-.88-.14-1.05-.05-1.23.06-1.22.16-1.04.24-.87.32-.71.36-.57.4-.44.42-.33.42-.24.4-.16.36-.1.32-.05.24-.01h.16l.06.01h8.16v-.83H6.18l-.01-2.75-.02-.37.05-.34.11-.31.17-.28.25-.26.31-.23.38-.2.44-.18.51-.15.58-.12.64-.1.71-.06.77-.04.84-.02 1.27.05zm-6.3 1.98l-.23.33-.08.41.08.41.23.34.33.22.41.09.41-.09.33-.22.23-.34.08-.41-.08-.41-.23-.33-.33-.22-.41-.09-.41.09zm13.09 3.95l.28.06.32.12.35.18.36.27.36.35.35.47.32.59.28.73.21.88.14 1.04.05 1.23-.06 1.23-.16 1.04-.24.86-.32.71-.36.57-.4.45-.42.33-.42.24-.4.16-.36.09-.32.05-.24.02-.16-.01h-8.22v.82h5.84l.01 2.76.02.36-.05.34-.11.31-.17.29-.25.25-.31.24-.38.2-.44.17-.51.15-.58.13-.64.09-.71.07-.77.04-.84.01-1.27-.04-1.07-.14-.9-.2-.73-.25-.59-.3-.45-.33-.34-.34-.25-.34-.16-.33-.1-.3-.04-.25-.02-.2.01-.13v-5.34l.05-.64.13-.54.21-.46.26-.38.3-.32.33-.24.35-.2.35-.14.33-.1.3-.06.26-.04.21-.02.13-.01h5.84l.69-.05.59-.14.5-.21.41-.28.33-.32.27-.35.2-.36.15-.36.1-.35.07-.32.04-.28.02-.21V6.07h2.09l.14.01.21.03zm-6.47 14.25l-.23.33-.08.41.08.41.23.33.33.23.41.08.41-.08.33-.23.23-.33.08-.41-.08-.41-.23-.33-.33-.23-.41-.08-.41.08z" />
    </svg>
    Try in Colab
  </a>;

<ColabLink url="https://colab.research.google.com/github/wandb/examples/blob/master/colabs/pytorch/Simple_PyTorch_Integration.ipynb" />

PyTorch is one of the most popular frameworks for deep learning in Python, especially among researchers. W\&B provides first class support for PyTorch, from logging gradients to profiling your code on the CPU and GPU.

You can also see our [example repo](https://github.com/wandb/examples) for scripts, including one on hyperparameter optimization using [Hyperband](https://arxiv.org/abs/1603.06560) on [Fashion MNIST](https://github.com/wandb/examples/tree/master/examples/pytorch/pytorch-cnn-fashion), plus the [W\&B Dashboard](https://wandb.ai/wandb/keras-fashion-mnist/runs/5z1d85qs) it generates.

## Log gradients with `run.watch`

To automatically log gradients, you can call [`wandb.Run.watch()`](/models/ref/python/experiments/run.md/#method-runwatch) and pass in your PyTorch model.

```python theme={null}
import wandb

with wandb.init(config=args) as run:

    model = ...  # set up your model

    # Magic
    run.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:
            run.log({"loss": loss})
```

If you need to track multiple models in the same script, you can call [`wandb.Run.watch()`](/models/ref/python/experiments/run/#method-runwatch) on each model separately.

<Warning>
  Gradients, metrics, and the graph won't be logged until `wandb.Run.log()` is called after a forward *and* backward pass.
</Warning>

## Log images and media

You can pass PyTorch `Tensors` with image data into [`wandb.Image`](/models/ref/python/data-types/image) and utilities from [`torchvision`](https://pytorch.org/vision/stable/index.html) will be used to convert them to images automatically:

```python theme={null}
with wandb.init(project="my_project", entity="my_entity") as run:
    images_t = ...  # generate or load images as PyTorch Tensors
    run.log({"examples": [wandb.Image(im) for im in images_t]})
```

For more on logging rich media to W\&B in PyTorch and other frameworks, check out our [media logging guide](/models/track/log/media/).

If you also want to include information alongside media, like your model's predictions or derived metrics, use a `wandb.Table`.

```python theme={null}
with wandb.init() as run:
    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)

    # Log your Table to W&B
    run.log({"mnist_predictions": my_table})
```

<Frame>
  <img src="https://mintcdn.com/wb-21fd5541-docs-1778-mysql-updates/hQX5DkvXcaXFdfod/images/integrations/pytorch_example_table.png?fit=max&auto=format&n=hQX5DkvXcaXFdfod&q=85&s=2a315b04ba307912fe6c59386b96b3ab" alt="PyTorch model results" width="1784" height="1212" data-path="images/integrations/pytorch_example_table.png" />
</Frame>

For more on logging and visualizing datasets and models, check out our [guide to W\&B Tables](/models/tables/).

## Profile PyTorch code

<Frame>
  <img src="https://mintcdn.com/wb-21fd5541-docs-1778-mysql-updates/hQX5DkvXcaXFdfod/images/integrations/pytorch_example_dashboard.png?fit=max&auto=format&n=hQX5DkvXcaXFdfod&q=85&s=1f7b3959f48997d301d0b920baf70258" alt="PyTorch execution traces" width="787" height="609" data-path="images/integrations/pytorch_example_dashboard.png" />
</Frame>

W\&B integrates directly with [PyTorch Kineto](https://github.com/pytorch/kineto)'s [Tensorboard plugin](https://github.com/pytorch/kineto/blob/master/tb_plugin/README) to provide tools for profiling PyTorch code, inspecting the details of CPU and GPU communication, and identifying bottlenecks and optimizations.

```python theme={null}
profile_dir = "path/to/run/tbprofile/"
profiler = torch.profiler.profile(
    schedule=schedule,  # see the profiler docs for details on scheduling
    on_trace_ready=torch.profiler.tensorboard_trace_handler(profile_dir),
    with_stack=True,
)

with profiler:
    ...  # run the code you want to profile here
    # see the profiler docs for detailed usage information

# create a wandb Artifact
profile_art = wandb.Artifact("trace", type="profile")
# add the pt.trace.json files to the Artifact
profile_art.add_file(glob.glob(profile_dir + ".pt.trace.json"))
# log the artifact
profile_art.save()
```

See and run working example code in [this Colab](https://wandb.me/trace-colab).

<Warning>
  The interactive trace viewing tool is based on the Chrome Trace Viewer, which works best with the Chrome browser.
</Warning>
