Skip to content

Serializer breaks with custom classes #1003

Closed

Description

@vadimkantorov
import torch
class A:
    pass
torch.save(A(), 'a.pth')

# File ".../python2.7/site-packages/torch/serialization.py", line 120, in save
#    return _save(obj, f, pickle_module, pickle_protocol)
#  File ".../python2.7/site-packages/torch/serialization.py", line 186, in _save
#    pickler.dump(obj)
#  File ".../python2.7/site-packages/torch/serialization.py", line 150, in persistent_id
#    elif torch.is_storage(obj):
#   File ".../python2.7/site-packages/torch/__init__.py", line 100, in is_storage
#    return obj.__class__ in _storage_classes
# AttributeError: class A has no attribute '__class__'

Is it expected behavior?

Root cause seems to be te that torch.is_tensor(obj) and torch.is_storage(obj) expect an object to have the attribute __class__. And somehow serializer calls torch.is_storage(A) which blows (torch.is_storage(A()) does not).

Activity

  1. soumith commented on Mar 15, 2017

    @soumith
    Collaborator
    class A(object):
        pass
    torch.save(A(), 'a.pth')
    

    Classes have to be derived from object in py2 afaik.
    Once you do that, it should serialize fine.

  2. vadimkantorov commented on Mar 15, 2017

    @vadimkantorov
    ContributorAuthor

    I think the ones derived from object are called new-style classes or something like that.

    I have patched is_storage and is_tensor to have:
    getattr(obj, "__class__", None) in _storage_classes. It has solved the issue.

    It may still be good to make is_tensor and is_storage to be robust to objects of old-style classes.

  3. soumith commented on Mar 15, 2017

    @soumith
    Collaborator

    can you send a PR with that patch. Yes, if it's an easy fix, probs worth supporting old-style classes.

  4. self-assigned this
    on Apr 10, 2017
  5. soumith commented on Apr 11, 2017

    @soumith
    Collaborator

    fixed in master. will be in next release.

  6. added a commit that references this issue on May 11, 2022
  7. added a commit that references this issue on Aug 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions