Sifal commited on
Commit
e6827ec
·
1 Parent(s): 15d1c70

Create utlis.py

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