Views
No views yet
@inproceedings{dou2021word,
title={Word Alignment by Fine-tuning Embeddings on Parallel Corpora},
author={Dou, Zi-Yi and Neubig, Graham},
booktitle={Conference of the European Chapter of the Association for Computational Linguistics (EACL)},
year={2021}
}awesome-align is a tool that can extract word alignments from multilingual BERT (mBERT) Demo and allows you to fine-tune mBERT on parallel corpora for better alignment quality (see our paper for more details).1from transformers import AutoModel, AutoTokenizer
2import itertools
3import torch
4
5# load model
6model = AutoModel.from_pretrained("aneuraz/awesome-align-with-co")
7tokenizer = AutoTokenizer.from_pretrained("aneuraz/awesome-align-with-co")
8
9# model parameters
10align_layer = 8
11threshold = 1e-3
12
13# define inputs
14src = 'awesome-align is awesome !'
15tgt = '牛对齐 是 牛 !'
16
17# pre-processing
18sent_src, sent_tgt = src.strip().split(), tgt.strip().split()
19token_src, token_tgt = [tokenizer.tokenize(word) for word in sent_src], [tokenizer.tokenize(word) for word in sent_tgt]
20wid_src, wid_tgt = [tokenizer.convert_tokens_to_ids(x) for x in token_src], [tokenizer.convert_tokens_to_ids(x) for x in token_tgt]
21ids_src, ids_tgt = tokenizer.prepare_for_model(list(itertools.chain(*wid_src)), return_tensors='pt', model_max_length=tokenizer.model_max_length, truncation=True)['input_ids'], tokenizer.prepare_for_model(list(itertools.chain(*wid_tgt)), return_tensors='pt', truncation=True, model_max_length=tokenizer.model_max_length)['input_ids']
22sub2word_map_src = []
23for i, word_list in enumerate(token_src):
24 sub2word_map_src += [i for x in word_list]
25sub2word_map_tgt = []
26for i, word_list in enumerate(token_tgt):
27 sub2word_map_tgt += [i for x in word_list]
28
29# alignment
30align_layer = 8
31threshold = 1e-3
32model.eval()
33with torch.no_grad():
34 out_src = model(ids_src.unsqueeze(0), output_hidden_states=True)[2][align_layer][0, 1:-1]
35 out_tgt = model(ids_tgt.unsqueeze(0), output_hidden_states=True)[2][align_layer][0, 1:-1]
36
37 dot_prod = torch.matmul(out_src, out_tgt.transpose(-1, -2))
38
39 softmax_srctgt = torch.nn.Softmax(dim=-1)(dot_prod)
40 softmax_tgtsrc = torch.nn.Softmax(dim=-2)(dot_prod)
41
42 softmax_inter = (softmax_srctgt > threshold)*(softmax_tgtsrc > threshold)
43
44align_subwords = torch.nonzero(softmax_inter, as_tuple=False)
45align_words = set()
46for i, j in align_subwords:
47 align_words.add( (sub2word_map_src[i], sub2word_map_tgt[j]) )
48
49print(align_words)