Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature] Frozen tensorclass #984

Merged
merged 4 commits into from
Sep 10, 2024
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
36 changes: 27 additions & 9 deletions tensordict/tensorclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,26 +349,31 @@ def is_non_tensor(obj):


class _tensorclass_dec:
def __new__(cls, autocast: bool = False):
def __new__(cls, autocast: bool = False, frozen: bool = False):
if not isinstance(autocast, bool):
clz = autocast
self = super().__new__(cls)
self.__init__(autocast=False)
self.__init__(autocast=False, frozen=False)
return self.__call__(clz)
return super().__new__(cls)

def __init__(self, autocast: bool):
def __init__(self, autocast: bool = False, frozen: bool = False):
self.autocast = autocast
self.frozen = frozen

@dataclass_transform()
def __call__(self, cls):
clz = _tensorclass(cls)
clz = _tensorclass(cls, frozen=self.frozen)
clz.autocast = self.autocast
return clz


@overload
def tensorclass(autocast: bool = False) -> _tensorclass_dec: ...
def tensorclass(autocast: bool = False, frozen: bool = False) -> _tensorclass_dec: ...


@overload
def tensorclass(cls: T) -> T: ...


@overload
Expand All @@ -387,6 +392,9 @@ def tensorclass(*args, **kwargs):
Args:
autocast (bool, optional): if ``True``, the types indicated will be enforced when an argument is set.
Defaults to ``False``.
frozen (bool, optional): if ``True``, the content of the tensorclass cannot be modified. This argument is
provided to dataclass-compatibility, a similar behavior can be obtained through the `lock` argument in
the class constructor. Defaults to ``False``.

tensorclass can be used with or without arguments:
Examples:
Expand Down Expand Up @@ -458,7 +466,7 @@ def tensorclass(*args, **kwargs):


@dataclass_transform()
def _tensorclass(cls: T) -> T:
def _tensorclass(cls: T, *, frozen) -> T:
def __torch_function__(
cls,
func: Callable,
Expand Down Expand Up @@ -494,7 +502,7 @@ def __torch_function__(

_is_non_tensor = getattr(cls, "_is_non_tensor", False)

cls = dataclass(cls)
cls = dataclass(cls, frozen=frozen)
expected_keys = cls.__expected_keys__ = set(cls.__dataclass_fields__)

for attr in expected_keys:
Expand All @@ -509,7 +517,7 @@ def __torch_function__(
delattr(cls, field.name)

_get_type_hints(cls)
cls.__init__ = _init_wrapper(cls.__init__)
cls.__init__ = _init_wrapper(cls.__init__, frozen)
cls._from_tensordict = classmethod(_from_tensordict)
cls.from_tensordict = cls._from_tensordict
if not hasattr(cls, "__torch_function__"):
Expand Down Expand Up @@ -672,7 +680,7 @@ def _from_tensordict_with_none(tc, tensordict):
)


def _init_wrapper(__init__: Callable) -> Callable:
def _init_wrapper(__init__: Callable, frozen) -> Callable:
init_sig = inspect.signature(__init__)
params = list(init_sig.parameters.values())
# drop first entry of params which corresponds to self and isn't passed by the user
Expand All @@ -685,8 +693,11 @@ def wrapper(
batch_size: Sequence[int] | torch.Size | int = None,
device: DeviceType | None = None,
names: List[str] | None = None,
lock: bool | None = None,
**kwargs,
):
if lock is None:
lock = frozen

if not is_dynamo_compiling():
# zip not supported by dynamo
Expand Down Expand Up @@ -741,6 +752,13 @@ def wrapper(
for key, value in kwargs.items()
}
__init__(self, **kwargs)
if frozen:
local_setattr = _setattr_wrapper(self.__setattr__, self.__expected_keys__)
for key, val in kwargs.items():
local_setattr(self, key, val)
del self.__dict__[key]
if lock:
self._tensordict.lock_()

new_params = [
inspect.Parameter("batch_size", inspect.Parameter.KEYWORD_ONLY),
Expand Down
46 changes: 46 additions & 0 deletions test/test_tensorclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -559,6 +559,52 @@ class MyDataNested:
assert (full_like_tc.y.X == 9).all()
assert full_like_tc.z == data.z == z

def test_frozen(self):

@tensorclass(frozen=True, autocast=True)
class X:
y: torch.Tensor

x = X(y=1)
assert isinstance(x.y, torch.Tensor)
_ = {x: 0}
assert x.is_locked
with pytest.raises(RuntimeError, match="locked"):
x.y = 0

@tensorclass(frozen=False, autocast=True)
class X:
y: torch.Tensor

x = X(y=1)
assert isinstance(x.y, torch.Tensor)
with pytest.raises(TypeError, match="unhashable"):
_ = {x: 0}
assert not x.is_locked
x.y = 0

@tensorclass(frozen=True, autocast=False)
class X:
y: torch.Tensor

x = X(y="a string!")
assert isinstance(x.y, str)
_ = {x: 0}
assert x.is_locked
with pytest.raises(RuntimeError, match="locked"):
x.y = 0

@tensorclass(frozen=False, autocast=False)
class X:
y: torch.Tensor

x = X(y="a string!")
assert isinstance(x.y, str)
with pytest.raises(TypeError, match="unhashable"):
_ = {x: 0}
assert not x.is_locked
x.y = 0

@pytest.mark.parametrize("from_torch", [True, False])
def test_gather(self, from_torch):
@tensorclass
Expand Down
Loading