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
59 changes: 56 additions & 3 deletions src/torchcodec/_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,14 @@ class Frame(Iterable):
duration_seconds: float
"""The duration of the frame, in seconds (float)."""

def __post_init__(self):
# This is called after __init__() when a Frame is created. We can run
# input validation checks here.
if not self.data.ndim == 3:
raise ValueError(f"data must be 3-dimensional, got {self.data.shape = }")
self.pts_seconds = float(self.pts_seconds)
self.duration_seconds = float(self.duration_seconds)

def __iter__(self) -> Iterator[Union[Tensor, float]]:
for field in dataclasses.fields(self):
yield getattr(self, field.name)
Expand All @@ -57,9 +65,54 @@ class FrameBatch(Iterable):
duration_seconds: Tensor
"""The duration of the frame, in seconds (1-D ``torch.Tensor`` of floats)."""

def __iter__(self) -> Iterator[Union[Tensor, float]]:
for field in dataclasses.fields(self):
yield getattr(self, field.name)
def __post_init__(self):
# This is called after __init__() when a FrameBatch is created. We can
# run input validation checks here.
if self.data.ndim < 4:
raise ValueError(
f"data must be at least 4-dimensional. Got {self.data.shape = } "
"For 3-dimensional data, create a Frame object instead."
)

leading_dims = self.data.shape[:-3]
if not (leading_dims == self.pts_seconds.shape == self.duration_seconds.shape):
raise ValueError(
"Tried to create a FrameBatch but the leading dimensions of the inputs do not match. "
f"Got {self.data.shape = } so we expected the shape of pts_seconds and "
f"duration_seconds to be {leading_dims = }, but got "
f"{self.pts_seconds.shape = } and {self.duration_seconds.shape = }."
)

def __iter__(self) -> Union[Iterator["FrameBatch"], Iterator[Frame]]:
cls = Frame if self.data.ndim == 4 else FrameBatch
for data, pts_seconds, duration_seconds in zip(
self.data, self.pts_seconds, self.duration_seconds
):
yield cls(
data=data,
pts_seconds=pts_seconds,
duration_seconds=duration_seconds,
)

def __getitem__(self, key) -> Union["FrameBatch", Frame]:
data = self.data[key]
pts_seconds = self.pts_seconds[key]
duration_seconds = self.duration_seconds[key]
if self.data.ndim == 4:
return Frame(
data=data,
pts_seconds=float(pts_seconds.item()),
duration_seconds=float(duration_seconds.item()),
)
else:
return FrameBatch(
data=data,
pts_seconds=pts_seconds,
duration_seconds=duration_seconds,
)
Comment on lines +101 to +112
Copy link
Contributor

Choose a reason for hiding this comment

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

Tensor has a .item() method for returning the underlying dtype.

Should we have something like that here? i.e. always return a FrameBatch but return a Frame if .item() is called?

Copy link
Contributor Author

@NicolasHug NicolasHug Oct 23, 2024

Choose a reason for hiding this comment

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

always return a FrameBatch but return a Frame if .item() is called?

I feel like this is what we're already doing, but perhaps I'm misunderstanding?

BTW, this quirk is only needed for mypy (sigh). Originally the code was simpler:

        cls = Frame if self.data.ndim == 4 else FrameBatch
        return cls(
            self.data[key],
            self.pts_seconds[key],
            self.duration_seconds[key],
        )

and everything was fine, and the Frame would get proper float value because of what we do in its post_init. But mypy was complaining so I had to go for this in 4661237 (#283)

Copy link
Contributor

Choose a reason for hiding this comment

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

I feel like this is what we're already doing, but perhaps I'm misunderstanding?

Don't we return a Frame for the special case of dimensions=4?

What I am saying is we should return a FrameBatch even in that case (of size 1). So we are consistent with Tensor

I'll leave it to you

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I don't have a super strong preference on this - let me open an issue so we can discuss during one of the meetings


def __len__(self):
return len(self.data)

def __repr__(self):
return _frame_repr(self)
121 changes: 121 additions & 0 deletions test/test_frame_dataclasses.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import pytest
import torch
from torchcodec import Frame, FrameBatch


def test_frame_unpacking():
data, pts_seconds, duration_seconds = Frame(torch.rand(3, 4, 5), 2, 3) # noqa


def test_frame_error():
with pytest.raises(ValueError, match="data must be 3-dimensional"):
Frame(
data=torch.rand(1, 2),
pts_seconds=1,
duration_seconds=1,
)
with pytest.raises(ValueError, match="data must be 3-dimensional"):
Frame(
data=torch.rand(1, 2, 3, 4),
pts_seconds=1,
duration_seconds=1,
)


def test_framebatch_error():
with pytest.raises(ValueError, match="data must be at least 4-dimensional"):
FrameBatch(
data=torch.rand(1, 2, 3),
pts_seconds=torch.rand(1),
duration_seconds=torch.rand(1),
)

with pytest.raises(
ValueError, match="leading dimensions of the inputs do not match"
):
FrameBatch(
data=torch.rand(3, 4, 2, 1),
pts_seconds=torch.rand(3), # ok
duration_seconds=torch.rand(2), # bad
)

with pytest.raises(
ValueError, match="leading dimensions of the inputs do not match"
):
FrameBatch(
data=torch.rand(3, 4, 2, 1),
pts_seconds=torch.rand(2), # bad
duration_seconds=torch.rand(3), # ok
)

with pytest.raises(
ValueError, match="leading dimensions of the inputs do not match"
):
FrameBatch(
data=torch.rand(5, 3, 4, 2, 1),
pts_seconds=torch.rand(5, 3), # ok
duration_seconds=torch.rand(5, 2), # bad
)

with pytest.raises(
ValueError, match="leading dimensions of the inputs do not match"
):
FrameBatch(
data=torch.rand(5, 3, 4, 2, 1),
pts_seconds=torch.rand(5, 2), # bad
duration_seconds=torch.rand(5, 3), # ok
)


def test_framebatch_iteration():
T, N, C, H, W = 7, 6, 3, 2, 4

fb = FrameBatch(
data=torch.rand(T, N, C, H, W),
pts_seconds=torch.rand(T, N),
duration_seconds=torch.rand(T, N),
)

for sub_fb in fb:
assert isinstance(sub_fb, FrameBatch)
assert sub_fb.data.shape == (N, C, H, W)
assert sub_fb.pts_seconds.shape == (N,)
assert sub_fb.duration_seconds.shape == (N,)
for frame in sub_fb:
assert isinstance(frame, Frame)
assert frame.data.shape == (C, H, W)
assert isinstance(frame.pts_seconds, float)
assert isinstance(frame.duration_seconds, float)

# Check unpacking behavior
first_sub_fb, *_ = fb
assert isinstance(first_sub_fb, FrameBatch)


def test_framebatch_indexing():
T, N, C, H, W = 7, 6, 3, 2, 4

fb = FrameBatch(
data=torch.rand(T, N, C, H, W),
pts_seconds=torch.rand(T, N),
duration_seconds=torch.rand(T, N),
)

for i in range(len(fb)):
assert isinstance(fb[i], FrameBatch)
assert fb[i].data.shape == (N, C, H, W)
assert fb[i].pts_seconds.shape == (N,)
assert fb[i].duration_seconds.shape == (N,)
for j in range(len(fb[i])):
assert isinstance(fb[i][j], Frame)
assert fb[i][j].data.shape == (C, H, W)
assert isinstance(fb[i][j].pts_seconds, float)
assert isinstance(fb[i][j].duration_seconds, float)

fb_fancy = fb[torch.arange(3)]
assert isinstance(fb_fancy, FrameBatch)
assert fb_fancy.data.shape == (3, N, C, H, W)

fb_fancy = fb[[[0], [1]]] # select T=0 and N=1.
assert isinstance(fb_fancy, FrameBatch)
assert fb_fancy.data.shape == (1, C, H, W)
Loading