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

username: Alberto_Zurini
cooked: <p>Hello! I issued this command to install torch on a Conda environment:<br>
<code>pip install torch==2.5.0 torchvision==0.20.0 torchaudio==2.5.0</code> (I also tried the equivalent <code>conda install pytorch...</code> command, but got the same result). I even tried to install it in a Docker container, but I’m still encountering the same issue!</p>
<p>if I do:</p>
<pre><code class="lang-auto">from torch.utils.data import DataLoader
dataset = datasets.ImageFolder(root=dataset_path, transform=transform)
</code></pre>
<p>What I will get out is going to be: <code>AttributeError: module 'torch' has no attribute '_six'</code>. 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?</p>
<p>Thanks in advance <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=12" title=":slight_smile:" class="emoji" alt=":slight_smile:" loading="lazy" width="20" height="20"></p>

username: ptrblck
cooked: <p>The <code>_six</code> dependency was removed in 2023 in <a href="https://github.com/pytorch/pytorch/pull/94709">this PR</a> and I cannot reproduce any issues using <code>torch==2.5.1</code>.</p>

username: Alberto_Zurini
cooked: <p>Thank you a lot for the quick reply. Can you please give me some more insights about your setup?</p>
<p>I tried this <code>docker run -d --name torch -v $PWD:/workspace -it pytorch/pytorch:1.7.1-cuda11.0-cudnn8-devel</code>, but I’m still encountering the same problem… How can I replicate your environment?</p>

username: ptrblck
cooked: <aside class="quote no-group" data-username="Alberto_Zurini" data-post="3" data-topic="214757">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/alberto_zurini/48/74782_2.png" class="avatar"> Alberto_Zurini:</div>
<blockquote>
<p>pytorch/pytorch:1.7.1-cuda11.0-cudnn8-devel</p>
</blockquote>
</aside>
<p>You are using an old <code>torch==1.7.1</code> container so use a recent one or uninstall the older PyTorch release and install the latest one via <code>pip install torch</code>.</p>

username: Alberto_Zurini
cooked: <p>I’m running this container now <code>docker run -d --name torch -v $PWD:/workspace -it pytorch/pytorch:2.5.1-cuda12.4-cudnn9-devel</code>, but I’m getting the same error!<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/7/1/71fcec3b3cbfe8c0c7991a275d48d4c3a1fddbde.png" data-download-href="https://discuss.pytorch.org/uploads/default/71fcec3b3cbfe8c0c7991a275d48d4c3a1fddbde" title="image"><img src="https://discuss.pytorch.org/uploads/default/original/3X/7/1/71fcec3b3cbfe8c0c7991a275d48d4c3a1fddbde.png" alt="image" data-base62-sha1="ggnQ01m6fY6O3utbCF9Uoyr0ZD8" width="690" height="445" data-dominant-color="252627"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">770×497 48.6 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>
<p>I really don’t have any idea what might be wrong about my environment. Moreover, I’m on the Docker…</p>
<p>Is this deprecated: <code>from torchvision import datasets, transforms</code>?</p>

username: Alberto_Zurini
cooked: <p>I noticed one thing: <code>model = torch.hub.load('pytorch/vision:v0.10.0', 'mobilenet_v2', pretrained=True)</code>, from <a href="https://pytorch.org/hub/pytorch_vision_mobilenet_v2/" rel="noopener nofollow ugc">https://pytorch.org/hub/pytorch_vision_mobilenet_v2/</a>. I tried to put <code>v0.20.1</code>, 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?</p>
<p>I found <a href="https://github.com/pytorch/vision/releases/tag/v0.20.0" rel="noopener nofollow ugc">https://github.com/pytorch/vision/releases/tag/v0.20.0</a>, tried to change the line into <code>model = torch.hub.load('pytorch/vision:v0.20.0', 'mobilenet_v2', pretrained=True)</code>, but this time I’m getting this error <code>ImportError: cannot import name 'get_model_weights' from 'torchvision.models'</code>. Is <code>Mobilenet_v2</code> deprecated?</p>

username: Alberto_Zurini
cooked: <p>Doesn’t seem like it’s the case: <a href="https://github.com/pytorch/vision/blob/main/torchvision/models/mobilenetv2.py" rel="noopener nofollow ugc">https://github.com/pytorch/vision/blob/main/torchvision/models/mobilenetv2.py</a></p>

username: Alberto_Zurini
cooked: <p>Full code:</p>
<pre><code class="lang-auto">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)
</code></pre>

username: Alberto_Zurini
cooked: <pre><code class="lang-auto">---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[2], line 6
      3 import torch.nn as nn
      4 from tqdm import tqdm
----&gt; 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     )
--&gt; 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)
--&gt; 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)
--&gt; 115 spec.loader.exec_module(module)
    116 return module

File &lt;frozen importlib._bootstrap_external&gt;:940, in exec_module(self, module)

File &lt;frozen importlib._bootstrap&gt;: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"]
----&gt; 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
---&gt; 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))
--&gt; 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.&lt;locals&gt;.register(func)
    793 else:
    794     use_lib = lib
--&gt; 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
--&gt; 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     )
---&gt; 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
</code></pre>

username: Alberto_Zurini
cooked: <p>Turns out there’s a better way to load the model from the hub, which is <code>model = models.mobilenet_v2(pretrained=True)</code>. This fixed the last error (the nms one).</p>
<p>As far as the first error is concerned, I’m not sure of what happened! I’m now running everything in docker using the <code>pytorch/pytorch:2.5.1-cuda12.4-cudnn9-devel</code> and the error is not showing up anymore. I read that even doing a <code>pip install torch</code> can mess up with cache and other things, so I guess nothing should be issued on this container, at least as far as torch &amp; co are concerned.</p>