import torch


def _allocate_grad(tensor, requires_grad):
    """Allocate a Tensor to store a gradient.

    If the provided Tensor requires a gradient, then a Tensor of the
    appropriate size will be allocated to store it. If it does not,
    then an empty Tensor will be created (so that it can be passed to
    save_for_backward either way without causing an error).

    Args:
        tensor: A Tensor that may or may not require a gradient
        requires_grad: Bool specifying whether tensor requires gradient

    Returns:
        Either a Tensor to store the gradient, or an empty Tensor.
    """

    if requires_grad:
        grad = torch.zeros_like(tensor)
    else:
        grad = torch.empty(0)

    return grad