Views
No views yet
1import torch
2from transformers import BertTokenizer, AutoModel
3import numpy as np
4import pandas as pd
5import razdel
6import matplotlib.pyplot as plt
7from tqdm.auto import tqdm, trange1model_name = 'NM-development/labse-en-ru-ce-prototype'
2tokenizer = BertTokenizer.from_pretrained(model_name)
3model = AutoModel.from_pretrained(model_name)1file_ru = None
2file_nm = None
3
4
5with open(file_nm, 'r') as f1, open(file_ru, 'r') as f2:
6 nm_text = f1.read()
7 ru_text = f2.read()1def embed(text):
2 encoded_input = tokenizer(text, padding=True, truncation=True, max_length=128, return_tensors='pt')
3 with torch.inference_mode():
4 model_output = model(**encoded_input.to(model.device))
5 embeddings = model_output.pooler_output
6 embeddings = torch.nn.functional.normalize(embeddings)
7 return embeddings[0].cpu().numpy()
8
9def get_top_mean_by_row(x, k=5):
10 m, n = x.shape
11 k = min(k, n)
12 topk_indices = np.argpartition(x, -k, axis=1)[:, -k:]
13 rows, _ = np.indices((m, k))
14 return x[rows, topk_indices].mean(1)
15
16def align3(sims):
17 rewards = np.zeros_like(sims)
18 choices = np.zeros_like(sims).astype(int) # 1: choose this pair, 2: decrease i, 3: decrease j
19
20 # алгоритм, разрешающий пропускать сколько угодно пар, лишь бы была монотонность
21 for i in range(sims.shape[0]):
22 for j in range(0, sims.shape[1]):
23 # вариант первый: выровнять i-тое предложение с j-тым
24 score_add = sims[i, j]
25 if i > 0 and j > 0: # вот как тогда выровняются предыдущие
26 score_add += rewards[i-1, j-1]
27 choices[i, j] = 1
28 best = score_add
29 if i > 0 and rewards[i-1, j] > best:
30 best = rewards[i-1, j]
31 choices[i, j] = 2
32 if j > 0 and rewards[i, j-1] > best:
33 best = rewards[i, j-1]
34 choices[i, j] = 3
35 rewards[i, j] = best
36 alignment = []
37 i = sims.shape[0] - 1
38 j = sims.shape[1] - 1
39 while i > 0 and j > 0:
40 if choices[i, j] == 1:
41 alignment.append([i, j])
42 i -= 1
43 j -= 1
44 elif choices[i, j] == 2:
45 i -= 1
46 else:
47 j -= 1
48 return alignment[::-1]
49
50def make_sents(text):
51 sents = [s.text.replace('\n', ' ').strip() for p in text.split('\n\n') for s in razdel.sentenize(p)]
52 sents = [s for s in sents if s]
53 return sents1sents_nm = make_sents(nm_text)
2sents_ru = make_sents(ru_text)1emb_ru = np.stack([embed(s) for s in tqdm(sents_ru)])
2emb_nm = np.stack([embed(s) for s in tqdm(sents_nm)])1pen = np.array([[min(len(x), len(y)) / max(len(x), len(y)) for x in sents_nm] for y in sents_ru])
2sims = np.maximum(0, np.dot(emb_ru, emb_nm.T)) ** 1 * pen
3
4alpha = 0.2
5penalty = 0.2
6sims_rel = (sims.T - get_top_mean_by_row(sims) * alpha).T - get_top_mean_by_row(sims.T) * alpha - penalty
7
8alignment = align3(sims_rel)
9
10print(sum(sims[i, j] for i, j in alignment) / min(sims.shape))
11plt.figure(figsize=(12, 6))
12plt.subplot(1, 2, 1)
13plt.imshow(sims_rel)
14plt.subplot(1, 2, 2)
15plt.scatter(*list(zip(*alignment)), s=5);1nm_ru_parallel_corpus = pd.DataFrame({'nm_text' : [sents_nm[x[1]] for x in alignment], 'ru_text' : [sents_ru[x[0]] for x in alignment]})
2corpus_filename = 'nm_ru_corpus.json'
3with open(corpus_filename, 'w') as f:
4 nm_ru_parallel_corpus.to_json(f, force_ascii=False, indent=4)