import torch


def all_isfinite(x):
    """Check the entire nested dictionary/list of tensors is finite
    (i.e. not nan or inf)"""
    if isinstance(x, torch.Tensor):
        return bool(torch.all(torch.isfinite(x)))
    elif isinstance(x, list):
        return all([all_isfinite(xi) for xi in x])
    elif isinstance(x, list):
        return all([all_isfinite(x[k]) for k in x])

    # If it reaches here, it's an unsupported type. Returns True for such cases
    return True