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

Hello! I issued this command to install torch on a Conda environment:
pip install torch==2.5.0 torchvision==0.20.0 torchaudio==2.5.0 (I also tried the equivalent conda install pytorch... command, but got the same result). I even tried to install it in a Docker container, but I’m still encountering the same issue!

if I do:

from torch.utils.data import DataLoader
dataset = datasets.ImageFolder(root=dataset_path, transform=transform)

What I will get out is going to be: AttributeError: module 'torch' has no attribute '_six'. I really can’t figure this issue out. I tried downgrading Torch and TorchVision, but nothing seemed to work. Do you know how to fix this?

Thanks in advance :slight_smile:

The _six dependency was removed in 2023 in this PR and I cannot reproduce any issues using torch==2.5.1.

Thank you a lot for the quick reply. Can you please give me some more insights about your setup?

I tried this docker run -d --name torch -v $PWD:/workspace -it pytorch/pytorch:1.7.1-cuda11.0-cudnn8-devel, but I’m still encountering the same problem… How can I replicate your environment?

You are using an old torch==1.7.1 container so use a recent one or uninstall the older PyTorch release and install the latest one via pip install torch.

I’m running this container now docker run -d --name torch -v $PWD:/workspace -it pytorch/pytorch:2.5.1-cuda12.4-cudnn9-devel, but I’m getting the same error!

I really don’t have any idea what might be wrong about my environment. Moreover, I’m on the Docker…

Is this deprecated: from torchvision import datasets, transforms?

I noticed one thing: model = torch.hub.load('pytorch/vision:v0.10.0', 'mobilenet_v2', pretrained=True), from https://pytorch.org/hub/pytorch_vision_mobilenet_v2/. I tried to put v0.20.1, but it can’t be found. Can this be my issue? If yes, do you know which torch hub model should I use? Is there a listing somewhere?

I found https://github.com/pytorch/vision/releases/tag/v0.20.0, tried to change the line into model = torch.hub.load('pytorch/vision:v0.20.0', 'mobilenet_v2', pretrained=True), but this time I’m getting this error ImportError: cannot import name 'get_model_weights' from 'torchvision.models'. Is Mobilenet_v2 deprecated?

Doesn’t seem like it’s the case: https://github.com/pytorch/vision/blob/main/torchvision/models/mobilenetv2.py

Full code:

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

model = torch.hub.load('pytorch/vision:v0.20.0', 'mobilenet_v2', pretrained=True)
print(model.classifier)

transform = transforms.Compose([
    transforms.Resize((64, 64)),  # Resize images to 64x64
    transforms.ToTensor(),          # Convert images to PyTorch tensors
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))  # Normalize to [-1, 1]
])
dataset_path = "./dataset/train"

dataset = datasets.ImageFolder(root=dataset_path, transform=transform)
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[2], line 6
      3 import torch.nn as nn
      4 from tqdm import tqdm
----> 6 model = torch.hub.load('pytorch/vision:v0.20.0', 'mobilenet_v2', pretrained=True)
      7 print(model.classifier)

File /opt/conda/lib/python3.11/site-packages/torch/hub.py:647, in load(repo_or_dir, model, source, trust_repo, force_reload, verbose, skip_validation, *args, **kwargs)
    637 if source == "github":
    638     repo_or_dir = _get_cache_or_reload(
    639         repo_or_dir,
    640         force_reload,
   (...)
    644         skip_validation=skip_validation,
    645     )
--> 647 model = _load_local(repo_or_dir, model, *args, **kwargs)
    648 return model

File /opt/conda/lib/python3.11/site-packages/torch/hub.py:673, in _load_local(hubconf_dir, model, *args, **kwargs)
    671 with _add_to_sys_path(hubconf_dir):
    672     hubconf_path = os.path.join(hubconf_dir, MODULE_HUBCONF)
--> 673     hub_module = _import_module(MODULE_HUBCONF, hubconf_path)
    675     entry = _load_entry_from_hubconf(hub_module, model)
    676     model = entry(*args, **kwargs)

File /opt/conda/lib/python3.11/site-packages/torch/hub.py:115, in _import_module(name, path)
    113 module = importlib.util.module_from_spec(spec)
    114 assert isinstance(spec.loader, Loader)
--> 115 spec.loader.exec_module(module)
    116 return module

File <frozen importlib._bootstrap_external>:940, in exec_module(self, module)

File <frozen importlib._bootstrap>:241, in _call_with_frames_removed(f, *args, **kwds)

File ~/.cache/torch/hub/pytorch_vision_v0.20.0/hubconf.py:4
      1 # Optional list of dependencies required by the package
      2 dependencies = ["torch"]
----> 4 from torchvision.models import get_model_weights, get_weight
      5 from torchvision.models.alexnet import alexnet
      6 from torchvision.models.convnext import convnext_base, convnext_large, convnext_small, convnext_tiny

File ~/.cache/torch/hub/pytorch_vision_v0.20.0/torchvision/__init__.py:10
      7 # Don't re-order these, we need to load the _C extension (done when importing
      8 # .extensions) before entering _meta_registrations.
      9 from .extension import _HAS_OPS  # usort:skip
---> 10 from torchvision import _meta_registrations, datasets, io, models, ops, transforms, utils  # usort:skip
     12 try:
     13     from .version import __version__  # noqa: F401

File ~/.cache/torch/hub/pytorch_vision_v0.20.0/torchvision/_meta_registrations.py:163
    153     torch._check(
    154         grad.dtype == rois.dtype,
    155         lambda: (
   (...)
    158         ),
    159     )
    160     return grad.new_empty((batch_size, channels, height, width))
--> 163 @torch.library.register_fake("torchvision::nms")
    164 def meta_nms(dets, scores, iou_threshold):
    165     torch._check(dets.dim() == 2, lambda: f"boxes should be a 2d tensor, got {dets.dim()}D")
    166     torch._check(dets.size(1) == 4, lambda: f"boxes should have 4 elements in dimension 1, got {dets.size(1)}")

File /opt/conda/lib/python3.11/site-packages/torch/library.py:795, in register_fake.<locals>.register(func)
    793 else:
    794     use_lib = lib
--> 795 use_lib._register_fake(op_name, func, _stacklevel=stacklevel + 1)
    796 return func

File /opt/conda/lib/python3.11/site-packages/torch/library.py:184, in Library._register_fake(self, op_name, fn, _stacklevel)
    181 else:
    182     func_to_register = fn
--> 184 handle = entry.fake_impl.register(func_to_register, source)
    185 self._registration_handles.append(handle)

File /opt/conda/lib/python3.11/site-packages/torch/_library/fake_impl.py:31, in FakeImplHolder.register(self, func, source)
     25 if self.kernel is not None:
     26     raise RuntimeError(
     27         f"register_fake(...): the operator {self.qualname} "
     28         f"already has an fake impl registered at "
     29         f"{self.kernel.source}."
     30     )
---> 31 if torch._C._dispatch_has_kernel_for_dispatch_key(self.qualname, "Meta"):
     32     raise RuntimeError(
     33         f"register_fake(...): the operator {self.qualname} "
     34         f"already has an DispatchKey::Meta implementation via a "
   (...)
     37         f"register_fake."
     38     )
     40 if torch._C._dispatch_has_kernel_for_dispatch_key(
     41     self.qualname, "CompositeImplicitAutograd"
     42 ):

RuntimeError: operator torchvision::nms does not exist

Turns out there’s a better way to load the model from the hub, which is model = models.mobilenet_v2(pretrained=True). This fixed the last error (the nms one).

As far as the first error is concerned, I’m not sure of what happened! I’m now running everything in docker using the pytorch/pytorch:2.5.1-cuda12.4-cudnn9-devel and the error is not showing up anymore. I read that even doing a pip install torch can mess up with cache and other things, so I guess nothing should be issued on this container, at least as far as torch & co are concerned.