Why can the attribute "device" not be resolved within the namespace of torch?

Hello,

I want to follow along the introductory tutorial Build the Neural Network — PyTorch Tutorials 2.6.0+cu124 documentation and copied the source code. It raises the error:

AttributeError: module 'torch' has no attribute 'accelerator'

and I do not understand why this supposedly compiles without error for the tutorial but does not on my machine (M2 macbook air).

import os
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets, transforms


class NeuralNetwork(nn.Module):
    def __init__(self):
        super().__init__()
        self.flatten = nn.Flatten()
        self.linear_relu_stack = nn.Sequential(
            nn.Linear(28*28, 512),
            nn.ReLU(),
            nn.Linear(512, 512),
            nn.ReLU(),
            nn.Linear(512, 10),
        )

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

device = torch.accelerator.current_accelerator().type if torch.accelerator.is_available() else "cpu"
print(f"Using {device} device")

model = NeuralNetwork()
print(model)

The code works for me using torch==2.6.0+cu124:

python -c "import torch; print(torch.__version__); print(torch.accelerator.current_accelerator().type)"
2.6.0+cu124
cuda

an update did the trick, thanks a lot!

I tried upgrading torch and torchvision together and separately also, but the error was not resolved in both cases.

> pip install --upgrade torch torchvision

btw I am running it on Google Colab

My code shows that the function exists and works in 2.6.0 so double check which version you are on.