import torch


def _read_from_stack(att_stack, stack_ptr):
    """
    Read the value at the given stack pointer.
    给定栈指针，读取指针对应的值

    att_stack维度: (batch_size, 36, 2, 4)
    stack_ptr存batch_size个栈顶指针p，每个p为stack_len维的one hot向量，维度为(batch_size, stack_len(4))
    """
    batch_size, stack_len = stack_ptr.size()

    # 将栈指针的维度扩展为(batch_size, 1, 1, 4)，便于与注意力堆栈相乘
    stack_ptr_expand = stack_ptr.view(batch_size, 1, 1, stack_len)

    # The stack pointer is a one-hot vector, so just do dot product
    # 从最后一维的stack_len元素中取栈指针为1的位置的元素
    # 因为栈指针是一个one hot向量
    # 所以，att维度是(batch_size, att_dim(num_feat), glimpse)，最后一维每一行存了glimpse个元素，每个元素都对应着栈指针为1标记的元素
    att = torch.sum(att_stack * stack_ptr_expand, dim=-1)

    return att