Skip to content

move_data_to_device fails with dataclasses with field(init=False) fields #9930

@ronif

Description

@ronif

🐛 Bug

move_data_to_device has special handling of dataclasses, but in case the dataclass has a non-init field, elem_type(**out) in apply_to_collection will fail

To Reproduce

from pytorch_lightning.utilities import move_data_to_device
import torch
from dataclasses import dataclass, field
from typing import NamedTuple, List

@dataclass
class Data:
    example_id: List[str]
    x: torch.Tensor
    y: int = field(init=False)

    def __post_init__(self):
        self.y = 3

batch_size = 5

batch = Data(
    example_id=[f"e-{i}" for i in range(batch_size)],
    x = torch.rand(batch_size),
)

assert batch.y == 3
device = torch.device("cuda:0")

move_data_to_device(batch=batch, device=device)

Expected behavior

Should run without exceptions

Environment

  • Packages:
    - numpy: 1.21.2
    - pyTorch_debug: False
    - pyTorch_version: 1.9.1
    - pytorch-lightning: 20211014
    - tqdm: 4.62.3
  • System:
    - OS: Linux
    - architecture:
    - 64bit
    -
    - processor: x86_64
    - python: 3.9.7

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workinghelp wantedOpen to be worked on

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions