Pytorch 给出运行时错误无法转换为所需的输出类型 Long

问题描述 投票:0回答:2

以下代码给出运行时错误“结果类型 Float 无法转换为所需的输出类型 Long”。

我已经尝试执行以下操作:

来自:

torch.div(self.indices_buf, vocab_size, out=self.beams_buf)

致:

torch.div(self.indices_buf, vocab_size, out=self.beams_buf).type_as(torch.LongTensor)

有问题的代码:

class BeamSearch(Search):

    def __init__(self, tgt_dict):
        super().__init__(tgt_dict)

    def step(self, step, lprobs, scores):
        super()._init_buffers(lprobs)
        bsz, beam_size, vocab_size = lprobs.size()

        if step == 0:
            # at the first step all hypotheses are equally likely, so use
            # only the first beam
            lprobs = lprobs[:, ::beam_size, :].contiguous()
        else:
            # make probs contain cumulative scores for each hypothesis
            lprobs.add_(scores[:, :, step - 1].unsqueeze(-1))

        torch.topk(
            lprobs.view(bsz, -1),
            k=min(
                # Take the best 2 x beam_size predictions. We'll choose the first
                # beam_size of these which don't predict eos to continue with.
                beam_size * 2,
                lprobs.view(bsz, -1).size(1) - 1,  # -1 so we never select pad
            ),
            out=(self.scores_buf, self.indices_buf),
        )
        torch.div(self.indices_buf, vocab_size, out=self.beams_buf).type_as(torch.LongTensor)
        self.indices_buf.fmod_(vocab_size)
        return self.scores_buf, self.indices_buf, self.beams_buf

此代码来自 fairseq。

python deep-learning pytorch tensor fairseq
2个回答
0
投票

也许你可以试试这个 self.beams_buf = self.indices_buf // vocab_size


0
投票

发生错误是因为张量无法处理不同张量类型的数学运算。看起来

self.indices_buf
vocab_size
都应该是 Long 张量(整数类型的可迭代)。

尝试将两者都转换为 pytorch 的

LongTensor
类型,以确保没有类型不匹配:

self.indices_buf = Tensor(self.indices_buf).long()
vocab_size = Tensor(vocab_size).long()
© www.soinside.com 2019 - 2024. All rights reserved.