火炬集线器提供预先训练的模型,例如:https://pytorch.org/hub/pytorch_fairseq_translation/
这些模型可以在python中使用,也可以与CLI交互使用。通过命令行界面,可以使用--print-alignment标志获取对齐。在安装fairseq (和pytorch)之后,The following code可以在终端中工作
curl https://dl.fbaipublicfiles.com/fairseq/models/wmt14.v2.en-fr.fconv-py.tar.bz2 | tar xvjf -
MODEL_DIR=wmt14.en-fr.fconv-py
fairseq-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中,可以指定关键字args、verbose和print_alignment
import torch
en2fr = 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)但是,这只会将对齐作为日志记录消息输出。而对于FairSeq0.9,它似乎被破坏了,并导致错误消息(issue)。
有没有办法从python代码中访问对齐信息(甚至可能是完整的注意力矩阵)?
发布于 2020-03-23 01:30:36
我浏览了fairseq代码库,发现了一种输出对齐信息的简单方法。因为这需要编辑fairseq源代码本身,所以我不认为这是一个可接受的解决方案。但也许它对某些人有帮助(我仍然对如何正确地做这件事的答案非常感兴趣)。
编辑sample() function并重写返回语句。下面是整个函数(为了帮助您更好地找到它,在代码中),但只有最后一行应该被更改:
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]))https://stackoverflow.com/questions/60802614
复制相似问题