Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/diffusers/utils/outputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"""

from collections import OrderedDict
from dataclasses import fields
from dataclasses import fields, is_dataclass
from typing import Any, Tuple

import numpy as np
Expand Down Expand Up @@ -101,6 +101,13 @@ def __setitem__(self, key, value):
# Don't call self.__setattr__ to avoid recursion errors
super().__setattr__(key, value)

def __reduce__(self):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That works! In Python, the __reduce__ function is more or less exclusively reserved for pickle no? So there should be no other side-effects that could be trigger here?

if not is_dataclass(self):
return super().__reduce__()
callable, _args, *remaining = super().__reduce__()
args = tuple(getattr(self, field.name) for field in fields(self))
return callable, args, *remaining

def to_tuple(self) -> Tuple[Any]:
"""
Convert self to a tuple containing all the attributes/keys that are not `None`.
Expand Down
11 changes: 11 additions & 0 deletions tests/others/test_outputs.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import pickle as pkl
import unittest
from dataclasses import dataclass
from typing import List, Union
Expand Down Expand Up @@ -58,3 +59,13 @@ def test_outputs_dict_init(self):
assert isinstance(outputs["images"][0], PIL.Image.Image)
assert isinstance(outputs[0], list)
assert isinstance(outputs[0][0], PIL.Image.Image)

def test_outputs_serialization(self):
outputs_orig = CustomOutput(images=[PIL.Image.new("RGB", (4, 4))])
serialized = pkl.dumps(outputs_orig)
outputs_copy = pkl.loads(serialized)

# Check original and copy are equal
assert dir(outputs_orig) == dir(outputs_copy)
assert dict(outputs_orig) == dict(outputs_copy)
assert vars(outputs_orig) == vars(outputs_copy)