Sifal commited on
Commit
cf62b9a
1 Parent(s): d8b103e

Delete utlis.py

Browse files
Files changed (1) hide show
  1. utlis.py +0 -168
utlis.py DELETED
@@ -1,168 +0,0 @@
1
- import yaml
2
- import torch
3
- from .model import Seq2SeqTransformer
4
- from transformers import AutoTokenizer
5
- from transformers import PreTrainedTokenizerFast
6
- from tokenizers.processors import TemplateProcessing
7
-
8
-
9
- def addPreprocessing(tokenizer):
10
- tokenizer._tokenizer.post_processor = TemplateProcessing(
11
- single=tokenizer.bos_token + " $A " + tokenizer.eos_token,
12
- special_tokens=[(tokenizer.eos_token, tokenizer.eos_token_id), (tokenizer.bos_token, tokenizer.bos_token_id)])
13
-
14
- def load_model(model_checkpoint_dir='model.pt',config_dir='config.yaml'):
15
-
16
- with open(config_dir, 'r') as yaml_file:
17
- loaded_model_params = yaml.safe_load(yaml_file)
18
-
19
- # Create a new instance of the model with the loaded configuration
20
- model = Seq2SeqTransformer(
21
- loaded_model_params["num_encoder_layers"],
22
- loaded_model_params["num_decoder_layers"],
23
- loaded_model_params["emb_size"],
24
- loaded_model_params["nhead"],
25
- loaded_model_params["source_vocab_size"],
26
- loaded_model_params["target_vocab_size"],
27
- loaded_model_params["ffn_hid_dim"]
28
- )
29
-
30
- checkpoint = torch.load(model_checkpoint_dir) if torch.cuda.is_available() else torch.load(model_checkpoint_dir,map_location=torch.device('cpu'))
31
- model.load_state_dict(checkpoint)
32
-
33
- return model
34
-
35
-
36
- def greedy_decode(model, src, src_mask, max_len, start_symbol):
37
- # Move inputs to the device
38
- src = src.to(device)
39
- src_mask = src_mask.to(device)
40
-
41
- # Encode the source sequence
42
- memory = model.encode(src, src_mask)
43
-
44
- # Initialize the target sequence with the start symbol
45
- ys = torch.tensor([[start_symbol]]).type(torch.long).to(device)
46
-
47
- for i in range(max_len - 1):
48
- memory = memory.to(device)
49
- # Create a target mask for autoregressive decoding
50
- tgt_mask = torch.tril(torch.full((ys.size(1), ys.size(1)), float('-inf'), device=device), diagonal=-1).transpose(0, 1).to(device)
51
- # Decode the target sequence
52
- out = model.decode(ys, memory, tgt_mask)
53
- # Generate the probability distribution over the vocabulary
54
- prob = model.generator(out[:, -1])
55
-
56
- # Select the next word with the highest probability
57
- _, next_word = torch.max(prob, dim=1)
58
- next_word = next_word.item()
59
-
60
- # Append the next word to the target sequence
61
- ys = torch.cat([ys,
62
- torch.ones(1, 1).type_as(src.data).fill_(next_word)], dim=1)
63
-
64
- # Check if the generated word is the end-of-sequence token
65
- if next_word == target_tokenizer.eos_token_id:
66
- break
67
-
68
- return ys
69
-
70
-
71
- def beam_search_decode(model, src, src_mask, max_len, start_symbol, beam_size ,length_penalty):
72
- # Move inputs to the device
73
- src = src.to(device)
74
- src_mask = src_mask.to(device)
75
-
76
- # Encode the source sequence
77
- memory = model.encode(src, src_mask) # b * seqlen_src * hdim
78
-
79
- # Initialize the beams (sequences, score)
80
- beams = [(torch.tensor([[start_symbol]]).type(torch.long).to(device), 0)]
81
-
82
- for i in range(max_len - 1):
83
- new_beams = []
84
- complete_beams = []
85
- cbl = []
86
-
87
- for ys, score in beams:
88
-
89
- # Create a target mask for autoregressive decoding
90
- tgt_mask = torch.tril(torch.full((ys.size(1), ys.size(1)), float('-inf'), device=device), diagonal=-1).transpose(0, 1).to(device)
91
- # Decode the target sequence
92
- out = model.decode(ys, memory, tgt_mask) # b * seqlen_tgt * hdim
93
- #print(f'shape out {out.shape}')
94
- # Generate the probability distribution over the vocabulary
95
- prob = model.generator(out[:, -1]) # b * tgt_vocab_size
96
- #print(f'shape prob {prob.shape}')
97
-
98
- # Get the top beam_size candidates for the next word
99
- _, top_indices = torch.topk(prob, beam_size, dim=1) # b * beam_size
100
-
101
- for j,next_word in enumerate(top_indices[0]):
102
-
103
- next_word = next_word.item()
104
-
105
- # Append the next word to the target sequence
106
- new_ys = torch.cat([ys, torch.full((1, 1), fill_value=next_word, dtype=src.dtype).to(device)], dim=1)
107
-
108
- length_factor = (5 + j / 6) ** length_penalty
109
- new_score = (score + prob[0][next_word].item()) / length_factor
110
-
111
- if next_word == target_tokenizer.eos_token_id:
112
- complete_beams.append((new_ys, new_score))
113
- else:
114
- new_beams.append((new_ys, new_score))
115
-
116
-
117
- # Sort the beams by score and select the top beam_size beams
118
- new_beams.sort(key=lambda x: x[1], reverse=True)
119
- try:
120
- beams = new_beams[:beam_size]
121
- except:
122
- beams = new_beams
123
-
124
- beams = new_beams + complete_beams
125
- beams.sort(key=lambda x: x[1], reverse=True)
126
-
127
- best_beam = beams[0][0]
128
- return best_beam
129
-
130
- def translate(model: torch.nn.Module, strategy:str = 'greedy' , src_sentence: str, lenght_extend :int = 5, beam_size: int = 5, length_penalty:float = 0.6):
131
- assert strategy in ['greedy','beam search'], 'the strategy for decoding has to be either greedy or beam search'
132
- # Tokenize the source sentence
133
- src = source_tokenizer(src_sentence, **token_config)['input_ids']
134
- num_tokens = src.shape[1]
135
- # Create a source mask
136
- src_mask = (torch.zeros(num_tokens, num_tokens)).type(torch.bool)
137
- if strategy == 'greedy':
138
- tgt_tokens = greedy_decode(model, src, src_mask, max_len=num_tokens + lenght_extend, start_symbol=target_tokenizer.bos_token_id).flatten()
139
- # Generate the target tokens using beam search decoding
140
- else:
141
- tgt_tokens = beam_search_decode(model, src, src_mask, max_len=num_tokens + lenght_extend, start_symbol=target_tokenizer.bos_token_id, beam_size=beam_size,length_penalty=length_penalty).flatten()
142
- # Decode the target tokens and clean up the result
143
- return target_tokenizer.decode(tgt_tokens, clean_up_tokenization_spaces=True, skip_special_tokens=True)
144
-
145
- special_tokens = {'unk_token':"[UNK]",
146
- 'cls_token':"[CLS]",
147
- 'eos_token': '[EOS]',
148
- 'sep_token':"[SEP]",
149
- 'pad_token':"[PAD]",
150
- 'mask_token':"[MASK]",
151
- 'bos_token':"[BOS]"}
152
-
153
- source_tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased", **special_tokens)
154
- target_tokenizer = PreTrainedTokenizerFast.from_pretrained('Sifal/E2KT')
155
-
156
- addPreprocessing(source_tokenizer)
157
- addPreprocessing(target_tokenizer)
158
-
159
- token_config = {
160
- "add_special_tokens": True,
161
- "return_tensors": True,
162
- }
163
-
164
- device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
165
-
166
- model = load_model()
167
- model.to(device)
168
- model.eval()