torch hub提供了预训练模型,例如:https://pytorch.org/hub/pytorch_fairseq_translation/
这些模型可以在Python中使用,或者通过CLI交互式地使用。在CLI中,可以通过--print-alignment
标志获取对齐信息。以下代码在安装了fairseq(和pytorch)后可以在终端中运行:
curl https://dl.fbaipublicfiles.com/fairseq/models/wmt14.v2.en-fr.fconv-py.tar.bz2 | tar xvjf -MODEL_DIR=wmt14.en-fr.fconv-pyfairseq-interactive \ --path $MODEL_DIR/model.pt $MODEL_DIR \ --beam 5 --source-lang en --target-lang fr \ --tokenizer moses \ --bpe subword_nmt --bpe-codes $MODEL_DIR/bpecodes \ --print-alignment
在Python中,可以指定关键字参数verbose
和print_alignment
:
import torchen2fr = torch.hub.load('pytorch/fairseq', 'transformer.wmt14.en-fr', tokenizer='moses', bpe='subword_nmt')fr = en2fr.translate('Hello world!', beam=5, verbose=True, print_alignment=True)
然而,这只会将对齐信息作为日志消息输出。而且在fairseq 0.9版本中似乎出现了问题,会导致错误消息(问题)。
有没有办法从Python代码中访问对齐信息(或者甚至是完整的注意力矩阵)?
回答:
我浏览了fairseq的代码库,发现了一种输出对齐信息的临时方法。由于这需要编辑fairseq的源代码本身,我认为这不是一个可接受的解决方案。但也许对某人有帮助(我仍然非常感兴趣了解如何正确地做到这一点)。
编辑sample()函数并重写返回语句。这里是整个函数(以帮助您更好地找到它,在代码中),但只需更改最后一行:
def sample(self, sentences: List[str], beam: int = 1, verbose: bool = False, **kwargs) -> List[str]: if isinstance(sentences, str): return self.sample([sentences], beam=beam, verbose=verbose, **kwargs)[0] tokenized_sentences = [self.encode(sentence) for sentence in sentences] batched_hypos = self.generate(tokenized_sentences, beam, verbose, **kwargs) return list(zip([self.decode(hypos[0]['tokens']) for hypos in batched_hypos], [hypos[0]['alignment'] for hypos in batched_hypos]))