import torch


def get_pointing_gradient(pred_y, y, normalize=True):
    """Returns a gradient tensor for the pointing game.

    Args:
        pred_y (:class:`torch.Tensor`): 4D tensor that the model outputs.
        y (int): target label.
        normalize (bool): If True, normalize the gradient tensor s.t. it
            sums to 1. Default: ``True``.

    Returns:
        :class:`torch.Tensor`: gradient tensor with the same shape as
        :attr:`pred_y`.
    """
    assert isinstance(pred_y, torch.Tensor)
    assert len(pred_y.shape) == 4 or len(pred_y.shape) == 2
    assert pred_y.shape[0] == 1
    assert isinstance(y, int)
    backward_gradient = torch.zeros_like(pred_y)
    backward_gradient[0, y] = torch.exp(pred_y[0, y])
    if normalize:
        backward_gradient[0, y] /= backward_gradient[0, y].sum()
    return backward_gradient