import torch


def to_device(x, device):
    """Cast a hierarchical object to pytorch device"""
    if isinstance(x, torch.Tensor):
        return x.to(device)
    elif isinstance(x, dict):
        for k in list(x.keys()):
            x[k] = to_device(x[k], device)
        return x
    elif isinstance(x, list) or isinstance(x, tuple):
        return type(x)(to_device(t, device) for t in x)
    else:
        raise ValueError('Wrong type !')