Skip to content

Feature: Create MemmapTensors with shape, device and dtype #219

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

Merged
merged 2 commits into from
Jun 22, 2022
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
69 changes: 64 additions & 5 deletions torchrl/data/tensordict/memmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import functools
import tempfile
from math import prod
from typing import Any, Callable, List, Optional, Tuple, Union

import numpy as np
Expand Down Expand Up @@ -97,7 +98,65 @@ class MemmapTensor(object):
def __init__(
self,
elem: Union[torch.Tensor, MemmapTensor],
*size: int,
device: DEVICE_TYPING = None,
dtype: torch.dtype = None,
transfer_ownership: bool = False,
):
self.idx = None
self._memmap_array = None
self.file = tempfile.NamedTemporaryFile()
self.filename = self.file.name

if isinstance(elem, (torch.Tensor, MemmapTensor, np.ndarray)):
if device is not None:
raise TypeError(
"device cannot be passed when creating a MemmapTensor from a tensor"
)
if dtype is not None:
raise TypeError(
"dtype cannot be passed when creating a MemmapTensor from a tensor"
)
return self._init_tensor(elem, transfer_ownership)
else:
if not isinstance(elem, int) and size:
raise TypeError(
"Valid init methods for MemmapTensor are: "
"\n- MemmapTensor(tensor, ...)"
"\n- MemmapTensor(size, ...)"
"\n- MemmapTensor(*size, ...)"
)
shape = (
torch.Size([elem] + list(size))
if isinstance(elem, int)
else torch.Size(elem)
)
device = device if device is not None else torch.device("cpu")
dtype = dtype if dtype is not None else torch.get_default_dtype()
return self._init_shape(shape, device, dtype, transfer_ownership)

def _init_shape(
self,
shape: torch.Size,
device: DEVICE_TYPING,
dtype: torch.dtype,
transfer_ownership: bool,
):
self._device = device
self._shape = shape
self.transfer_ownership = transfer_ownership
self.np_shape = tuple(self._shape)
self._dtype = dtype
self._ndim = len(shape)
self._numel = prod(shape)
self.mode = "r+"
self._has_ownership = True

self._tensor_dir = torch.zeros(1, device=device, dtype=dtype).__dir__()
self._save_item(shape)

def _init_tensor(
self, elem: Union[torch.Tensor, MemmapTensor], transfer_ownership: bool
):
if not isinstance(elem, (torch.Tensor, MemmapTensor)):
raise TypeError(
Expand All @@ -110,10 +169,6 @@ def __init__(
"Consider calling tensor.detach() first."
)

self.idx = None
self._memmap_array = None
self.file = tempfile.NamedTemporaryFile()
self.filename = self.file.name
self._device = elem.device
self._shape = elem.shape
self.transfer_ownership = transfer_ownership
Expand Down Expand Up @@ -153,11 +208,15 @@ def _set_memmap_array(self, value: np.memmap) -> None:

def _save_item(
self,
value: Union[torch.Tensor, MemmapTensor, np.ndarray],
value: Union[torch.Tensor, torch.Size, MemmapTensor, np.ndarray],
idx: Optional[int] = None,
):
if isinstance(value, (torch.Tensor,)):
np_array = value.cpu().numpy()
elif isinstance(value, torch.Size):
# create the memmap array on disk
_ = self.memmap_array
return
else:
np_array = value
memmap_array = self.memmap_array
Expand Down
1 change: 1 addition & 0 deletions torchrl/trainers/trainers.py
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,7 @@ def train(self):

if self.collected_frames > self.total_frames:
break
self.collector.shutdown()
self.save_trainer(force_save=True)

def __del__(self):
Expand Down