2023-03-31 20:05:14 +02:00
|
|
|
"""Extension of torchrec.dataset.utils.Batch to cover any dataset.
|
|
|
|
"""
|
|
|
|
# flake8: noqa
|
2023-04-01 12:30:34 +02:00
|
|
|
from __future__ import (
|
|
|
|
annotations,
|
|
|
|
)
|
|
|
|
|
2023-03-31 20:05:14 +02:00
|
|
|
import abc
|
|
|
|
import dataclasses
|
2023-04-01 12:30:34 +02:00
|
|
|
from collections import (
|
|
|
|
UserDict,
|
|
|
|
)
|
|
|
|
from dataclasses import (
|
|
|
|
dataclass,
|
|
|
|
)
|
|
|
|
from typing import (
|
|
|
|
Any,
|
|
|
|
Dict,
|
|
|
|
List,
|
|
|
|
TypeVar,
|
|
|
|
)
|
2023-03-31 20:05:14 +02:00
|
|
|
|
|
|
|
import torch
|
2023-04-01 12:30:34 +02:00
|
|
|
from torchrec.streamable import (
|
|
|
|
Pipelineable,
|
|
|
|
)
|
|
|
|
|
|
|
|
_KT = TypeVar("_KT") # key type
|
|
|
|
_VT = TypeVar("_VT") # value type
|
2023-03-31 20:05:14 +02:00
|
|
|
|
|
|
|
|
|
|
|
class BatchBase(Pipelineable, abc.ABC):
|
|
|
|
@abc.abstractmethod
|
2023-04-01 12:30:34 +02:00
|
|
|
def as_dict(self) -> Dict[str, Any]:
|
2023-03-31 20:05:14 +02:00
|
|
|
raise NotImplementedError
|
|
|
|
|
2023-04-01 12:30:34 +02:00
|
|
|
def to(self, device: torch.device, non_blocking: bool = False) -> BatchBase:
|
2023-03-31 20:05:14 +02:00
|
|
|
args = {}
|
|
|
|
for feature_name, feature_value in self.as_dict().items():
|
|
|
|
args[feature_name] = feature_value.to(device=device, non_blocking=non_blocking)
|
|
|
|
return self.__class__(**args)
|
|
|
|
|
|
|
|
def record_stream(self, stream: torch.cuda.streams.Stream) -> None:
|
|
|
|
for feature_value in self.as_dict().values():
|
|
|
|
feature_value.record_stream(stream)
|
|
|
|
|
2023-04-01 12:30:34 +02:00
|
|
|
def pin_memory(self) -> BatchBase:
|
2023-03-31 20:05:14 +02:00
|
|
|
args = {}
|
|
|
|
for feature_name, feature_value in self.as_dict().items():
|
|
|
|
args[feature_name] = feature_value.pin_memory()
|
|
|
|
return self.__class__(**args)
|
|
|
|
|
|
|
|
def __repr__(self) -> str:
|
2023-04-01 12:30:34 +02:00
|
|
|
def obj2str(v: Any) -> str:
|
2023-03-31 20:05:14 +02:00
|
|
|
return f"{v.size()}" if hasattr(v, "size") else f"{v.length_per_key()}"
|
|
|
|
|
|
|
|
return "\n".join([f"{k}: {obj2str(v)}," for k, v in self.as_dict().items()])
|
|
|
|
|
|
|
|
@property
|
|
|
|
def batch_size(self) -> int:
|
|
|
|
for tensor in self.as_dict().values():
|
|
|
|
if tensor is None:
|
|
|
|
continue
|
|
|
|
if not isinstance(tensor, torch.Tensor):
|
|
|
|
continue
|
|
|
|
return tensor.shape[0]
|
|
|
|
raise Exception("Could not determine batch size from tensors.")
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
class DataclassBatch(BatchBase):
|
|
|
|
@classmethod
|
2023-04-01 12:30:34 +02:00
|
|
|
def feature_names(cls) -> List[str]:
|
2023-03-31 20:05:14 +02:00
|
|
|
return list(cls.__dataclass_fields__.keys())
|
|
|
|
|
2023-04-01 12:30:34 +02:00
|
|
|
def as_dict(self) -> Dict[str, Any]:
|
2023-03-31 20:05:14 +02:00
|
|
|
return {
|
|
|
|
feature_name: getattr(self, feature_name)
|
|
|
|
for feature_name in self.feature_names()
|
|
|
|
if hasattr(self, feature_name)
|
|
|
|
}
|
|
|
|
|
|
|
|
@staticmethod
|
2023-04-01 12:30:34 +02:00
|
|
|
def from_schema(name: str, schema: Any) -> type:
|
2023-03-31 20:05:14 +02:00
|
|
|
"""Instantiates a custom batch subclass if all columns can be represented as a torch.Tensor."""
|
|
|
|
return dataclasses.make_dataclass(
|
|
|
|
cls_name=name,
|
|
|
|
fields=[(name, torch.Tensor, dataclasses.field(default=None)) for name in schema.names],
|
|
|
|
bases=(DataclassBatch,),
|
|
|
|
)
|
|
|
|
|
|
|
|
@staticmethod
|
2023-04-01 12:30:34 +02:00
|
|
|
def from_fields(name: str, fields: Dict[str, Any]) -> type:
|
2023-03-31 20:05:14 +02:00
|
|
|
return dataclasses.make_dataclass(
|
|
|
|
cls_name=name,
|
|
|
|
fields=[(_name, _type, dataclasses.field(default=None)) for _name, _type in fields.items()],
|
|
|
|
bases=(DataclassBatch,),
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2023-04-01 12:30:34 +02:00
|
|
|
class DictionaryBatch(BatchBase, UserDict[_KT, _VT]):
|
|
|
|
def as_dict(self) -> Dict[str, Any]:
|
2023-03-31 20:05:14 +02:00
|
|
|
return self
|