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

[Refactor] TensorClass drop _tensordict argument in constructor #175

Merged
merged 5 commits into from
Jan 23, 2023
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
120 changes: 54 additions & 66 deletions tensordict/prototype/tensorclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,8 @@ def __torch_function__(
f"Attribute name {attr} can't be used with @tensorclass"
)

cls.__init__ = _init_wrapper(cls.__init__, expected_keys)
cls._build_from_tensordict = classmethod(_build_from_tensordict)
cls.__init__ = _init_wrapper(cls.__init__)
cls.from_tensordict = classmethod(_from_tensordict_wrapper(expected_keys))
cls.__torch_function__ = classmethod(__torch_function__)
cls.__getstate__ = _getstate
cls.__setstate__ = _setstate
Expand Down Expand Up @@ -158,72 +158,60 @@ def __torch_function__(
return cls


def _init_wrapper(init, expected_keys):
def _init_wrapper(init):
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
required_params = [p.name for p in params[1:] if p.default is inspect._empty]

@functools.wraps(init)
def wrapper(self, *args, batch_size=None, device=None, _tensordict=None, **kwargs):
if (args or kwargs) and _tensordict is not None:
raise ValueError("Cannot pass both args/kwargs and _tensordict.")

if _tensordict is not None:
if not all(key in expected_keys for key in _tensordict.keys()):
raise ValueError(
f"Keys from the tensordict ({set(_tensordict.keys())}) must "
f"correspond to the class attributes ({expected_keys})."
)
input_dict = {key: None for key in _tensordict.keys()}
init(self, **input_dict)
self.tensordict = _tensordict
else:
for value, key in zip(args, self.__dataclass_fields__):
if key in kwargs:
raise ValueError(f"The key {key} is already set in kwargs")
kwargs[key] = value

for key, field in self.__dataclass_fields__.items():
if field.default_factory is not dataclasses.MISSING:
default = field.default_factory()
else:
default = field.default
if default not in (None, dataclasses.MISSING):
kwargs.setdefault(key, default)

missing_params = [p for p in required_params if p not in kwargs]
if missing_params:
n_missing = len(missing_params)
raise TypeError(
f"{self.__class__.__name__}.__init__() missing {n_missing} "
f"required positional argument{'' if n_missing == 1 else 's'}: "
f"""{", ".join(f"'{name}'" for name in missing_params)}"""
)
def wrapper(self, *args, batch_size, device=None, **kwargs):
for value, key in zip(args, self.__dataclass_fields__):
if key in kwargs:
raise ValueError(f"The key {key} is already set in kwargs")
kwargs[key] = value

for key, field in self.__dataclass_fields__.items():
if field.default_factory is not dataclasses.MISSING:
default = field.default_factory()
else:
default = field.default
if default not in (None, dataclasses.MISSING):
kwargs.setdefault(key, default)

self.tensordict = TensorDict({}, batch_size=batch_size, device=device)
init(
self, **{key: _get_typed_value(value) for key, value in kwargs.items()}
missing_params = [p for p in required_params if p not in kwargs]
if missing_params:
n_missing = len(missing_params)
raise TypeError(
f"{self.__class__.__name__}.__init__() missing {n_missing} "
f"required positional argument{'' if n_missing == 1 else 's'}: "
f"""{", ".join(f"'{name}'" for name in missing_params)}"""
)

self.tensordict = TensorDict({}, batch_size=batch_size, device=device)
init(self, **{key: _get_typed_value(value) for key, value in kwargs.items()})

new_params = [
inspect.Parameter(
"batch_size", inspect.Parameter.POSITIONAL_OR_KEYWORD, default=None
),
inspect.Parameter(
"device", inspect.Parameter.POSITIONAL_OR_KEYWORD, default=None
),
inspect.Parameter(
"_tensordict", inspect.Parameter.POSITIONAL_OR_KEYWORD, default=None
),
inspect.Parameter("batch_size", inspect.Parameter.KEYWORD_ONLY),
inspect.Parameter("device", inspect.Parameter.KEYWORD_ONLY, default=None),
]
wrapper.__signature__ = init_sig.replace(parameters=params + new_params)

return wrapper


def _build_from_tensordict(cls, tensordict):
return cls(_tensordict=tensordict)
def _from_tensordict_wrapper(expected_keys):
def wrapper(cls, tensordict):
if not all(key in expected_keys for key in tensordict.keys()):
raise ValueError(
f"Keys from the tensordict ({set(tensordict.keys())}) must "
f"correspond to the class attributes ({expected_keys})."
)
tc = cls(**tensordict, batch_size=tensordict.batch_size)
Copy link
Contributor

Choose a reason for hiding this comment

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

isn't this a bit overkilling it?
IIUC we deconstruct the tensordict, reconstruct another one, then replace it with the old one. Since the construction is quite time consuming, do you think we can find another solution?

Copy link
Contributor

Choose a reason for hiding this comment

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

my very same objection, but @tcbegley measured the overhead and seems negligible. Do you have a specific test case in mind that we could try to double check the benchmark?

Copy link
Contributor

Choose a reason for hiding this comment

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

The overhead is mainly due to the checks, so if we could do the checks only once it'd be cool (TensorDIct(dictionary, batch_size, device, _run_checks=False)).
Given that the tensordict that is provided is presumably already checked we should be good no?

Copy link
Contributor

Choose a reason for hiding this comment

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

off-topic: why the _ in a parameter name? It should be used only for protected methods/variables

Copy link
Contributor

Choose a reason for hiding this comment

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

Exactly for that: we don't want users to call that. We may refactor this in the future to hide it a bit more.
You should use that only if you build a tensordict out of another tensordict and the checks have been done, which will only occur in with dedicated methods.
I'm open to suggestions to make it cleaner :)

Copy link
Contributor

@vmoens vmoens Jan 23, 2023

Choose a reason for hiding this comment

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

See this example:

td = TensorDict({"a": torch.randn(3), "b": torch.randn(2)}, [3], _run_checks=False) # passes 
td[2]  # breaks

the code breaks where it should not (it should break earlier).
If we make that arg public, we're telling the users that this would be ok-ish to construct the TD like this, which isn't.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Since we initialise an empty tensordict in the constructor, and then populate it via __setattr__ from inside the dataclass' constructor, I think we will also need to set _run_checks=False inside there to really reduce overhead. Is it ok to always have that turned off though? Presumably we still want checks when running something like

tc.X = torch.rand(100, 10)

Copy link
Contributor

Choose a reason for hiding this comment

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

Since we initialise an empty tensordict in the constructor, and then populate it via __setattr__ from inside the dataclass' constructor, I think we will also need to set _run_checks=False inside there to really reduce overhead. Is it ok to always have that turned off though? Presumably we still want checks when running something like

tc.X = torch.rand(100, 10)

yep in that case we need to run it

Copy link
Contributor

Choose a reason for hiding this comment

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

Exactly for that: we don't want users to call that. We may refactor this in the future to hide it a bit more. You should use that only if you build a tensordict out of another tensordict and the checks have been done, which will only occur in with dedicated methods. I'm open to suggestions to make it cleaner :)

couldn't we simply store a self._checked boolean attribute that gets set to true the first time, and get rid of that argument constructor?

Copy link
Contributor

Choose a reason for hiding this comment

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

That could be an option, I should go through the tensordict.py file and check if that would work in all cases

tc.__dict__["tensordict"] = tensordict
return tc

return wrapper


def _getstate(self):
Expand Down Expand Up @@ -274,7 +262,7 @@ def _getattr(self, attr):
def wrapped_func(*args, **kwargs):
res = func(*args, **kwargs)
if isinstance(res, TensorDictBase):
new = self.__class__(_tensordict=res)
new = self.from_tensordict(res)
return new
else:
return res
Expand All @@ -288,7 +276,7 @@ def _getitem(self, item):
):
raise ValueError("Invalid indexing arguments.")
res = self.tensordict[item]
return self.__class__(_tensordict=res) # device=res.device)
return self.from_tensordict(res) # device=res.device)


def _setitem(self, item, value):
Expand Down Expand Up @@ -351,13 +339,13 @@ def _batch_size_setter(self, new_size: torch.Size) -> None:

def _unbind(tdc, dim):
tensordicts = torch.unbind(tdc.tensordict, dim)
out = [tdc.__class__(_tensordict=td) for td in tensordicts]
out = [tdc.from_tensordict(td) for td in tensordicts]
return out


def _full_like(tdc, fill_value):
tensordict = torch.full_like(tdc.tensordict, fill_value)
out = tdc.__class__(_tensordict=tensordict)
out = tdc.from_tensordict(tensordict)
return out


Expand All @@ -371,43 +359,43 @@ def _ones_like(tdc):

def _clone(tdc):
tensordict = torch.clone(tdc.tensordict)
out = tdc.__class__(_tensordict=tensordict)
out = tdc.from_tensordict(tensordict)
return out


def _squeeze(tdc):
tensordict = torch.squeeze(tdc.tensordict)
out = tdc.__class__(_tensordict=tensordict)
out = tdc.from_tensordict(tensordict)
return out


def _unsqueeze(tdc, dim=0):
tensordict = torch.unsqueeze(tdc.tensordict, dim)
out = tdc.__class__(_tensordict=tensordict)
out = tdc.from_tensordict(tensordict)
return out


def _permute(tdc, dims):
tensordict = torch.permute(tdc.tensordict, dims)
out = tdc.__class__(_tensordict=tensordict)
out = tdc.from_tensordict(tensordict)
return out


def _split(tdc, split_size_or_sections, dim=0):
tensordicts = torch.split(tdc.tensordict, split_size_or_sections, dim)
out = [tdc.__class__(_tensordict=td) for td in tensordicts]
out = [tdc.from_tensordict(td) for td in tensordicts]
return out


def _stack(list_of_tdc, dim):
tensordict = torch.stack([tdc.tensordict for tdc in list_of_tdc], dim)
out = list_of_tdc[0].__class__(_tensordict=tensordict)
out = list_of_tdc[0].from_tensordict(tensordict)
return out


def _cat(list_of_tdc, dim):
tensordict = torch.cat([tdc.tensordict for tdc in list_of_tdc], dim)
out = list_of_tdc[0].__class__(_tensordict=tensordict)
out = list_of_tdc[0].from_tensordict(tensordict)
return out


Expand All @@ -425,18 +413,18 @@ def _get_typed_output(out, expected_type):
# Otherwise, if the output is some TensorDictBase subclass, we check the type and if it
# does not match, we map it. In all other cases, just return what has been gathered.
if isinstance(expected_type, str) and expected_type in CLASSES_DICT:
out = CLASSES_DICT[expected_type](_tensordict=out)
out = CLASSES_DICT[expected_type].from_tensordict(out)
elif (
isinstance(expected_type, type)
and not isinstance(out, expected_type)
and isinstance(out, TensorDictBase)
):
out = expected_type(_tensordict=out)
out = expected_type.from_tensordict(out)
elif isinstance(out, TensorDictBase):
dest_dtype = _check_td_out_type(expected_type)
if dest_dtype is not None:
print(dest_dtype)
out = dest_dtype(_tensordict=out)
out = dest_dtype.from_tensordict(out)

return out

Expand Down
23 changes: 9 additions & 14 deletions test/test_tensorclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,28 +70,23 @@ def test_type():

def test_signature():
sig = inspect.signature(MyData)
assert list(sig.parameters) == ["X", "y", "batch_size", "device", "_tensordict"]
assert list(sig.parameters) == ["X", "y", "batch_size", "device"]

with pytest.raises(TypeError, match="missing 2 required positional arguments"):
MyData()
MyData(batch_size=[10])

with pytest.raises(TypeError, match="missing 1 required positional argument"):
MyData(X=torch.rand(10))
MyData(X=torch.rand(10), batch_size=[10])

with pytest.raises(TypeError, match="missing 1 required positional argument"):
MyData(X=torch.rand(10), batch_size=[10], device="cpu")

# if all positional arguments are specified, ommitting batch_size gives error
with pytest.raises(ValueError, match="batch size was not specified"):
with pytest.raises(
TypeError, match="missing 1 required keyword-only argument: 'batch_size'"
):
MyData(X=torch.rand(10), y=torch.rand(10))

# instantiation via _tensordict ignores argument checks, no TypeError
MyData(
_tensordict=TensorDict(
{"X": torch.rand(10), "y": torch.rand(10)}, batch_size=[10]
)
)

# all positional arguments + batch_size is fine
MyData(X=torch.rand(10), y=torch.rand(10), batch_size=[10])

Expand Down Expand Up @@ -158,7 +153,7 @@ class MyUnionClass:
subclass: Union[MyOptionalClass, TensorDict] = None

data = MyUnionClass(
subclass=MyUnionClass(_tensordict=TensorDict({}, [3])), batch_size=[3]
subclass=MyUnionClass.from_tensordict(TensorDict({}, [3])), batch_size=[3]
)
with pytest.raises(TypeError, match="can't be deterministically cast."):
assert data.subclass is not None
Expand Down Expand Up @@ -551,15 +546,15 @@ def __post_init__(self):
assert (data.y == y.abs()).all()

# initialising from tensordict is fine
data = MyDataPostInit._build_from_tensordict(
data = MyDataPostInit.from_tensordict(
TensorDict({"X": torch.rand(3, 4), "y": y}, batch_size=[3, 4])
)

with pytest.raises(AssertionError):
MyDataPostInit(X=-torch.ones(2), y=torch.rand(2), batch_size=[2])

with pytest.raises(AssertionError):
MyDataPostInit._build_from_tensordict(
MyDataPostInit.from_tensordict(
TensorDict({"X": -torch.ones(2), "y": torch.rand(2)}, batch_size=[2])
)

Expand Down
23 changes: 9 additions & 14 deletions test/test_tensorclass_nofuture.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,28 +68,23 @@ def test_type():

def test_signature():
sig = inspect.signature(MyData)
assert list(sig.parameters) == ["X", "y", "batch_size", "device", "_tensordict"]
assert list(sig.parameters) == ["X", "y", "batch_size", "device"]

with pytest.raises(TypeError, match="missing 2 required positional arguments"):
MyData()
MyData(batch_size=[10])

with pytest.raises(TypeError, match="missing 1 required positional argument"):
MyData(X=torch.rand(10))
MyData(X=torch.rand(10), batch_size=[10])

with pytest.raises(TypeError, match="missing 1 required positional argument"):
MyData(X=torch.rand(10), batch_size=[10], device="cpu")

# if all positional arguments are specified, ommitting batch_size gives error
with pytest.raises(ValueError, match="batch size was not specified"):
with pytest.raises(
TypeError, match="missing 1 required keyword-only argument: 'batch_size'"
):
MyData(X=torch.rand(10), y=torch.rand(10))

# instantiation via _tensordict ignores argument checks, no TypeError
MyData(
_tensordict=TensorDict(
{"X": torch.rand(10), "y": torch.rand(10)}, batch_size=[10]
)
)

# all positional arguments + batch_size is fine
MyData(X=torch.rand(10), y=torch.rand(10), batch_size=[10])

Expand Down Expand Up @@ -156,7 +151,7 @@ class MyUnionClass:
subclass: Union[MyOptionalClass, TensorDict] = None

data = MyUnionClass(
subclass=MyUnionClass(_tensordict=TensorDict({}, [3])), batch_size=[3]
subclass=MyUnionClass.from_tensordict(TensorDict({}, [3])), batch_size=[3]
)
with pytest.raises(TypeError, match="can't be deterministically cast."):
assert data.subclass is not None
Expand Down Expand Up @@ -549,15 +544,15 @@ def __post_init__(self):
assert (data.y == y.abs()).all()

# initialising from tensordict is fine
data = MyDataPostInit._build_from_tensordict(
data = MyDataPostInit.from_tensordict(
TensorDict({"X": torch.rand(3, 4), "y": y}, batch_size=[3, 4])
)

with pytest.raises(AssertionError):
MyDataPostInit(X=-torch.ones(2), y=torch.rand(2), batch_size=[2])

with pytest.raises(AssertionError):
MyDataPostInit._build_from_tensordict(
MyDataPostInit.from_tensordict(
TensorDict({"X": -torch.ones(2), "y": torch.rand(2)}, batch_size=[2])
)

Expand Down