MCPcopy Create free account
hub / github.com/LUMIA-Group/MemoryDecoder / post_forward_hook

Method post_forward_hook

knn_utils/saveEmbedMulti.py:155–186  ·  view source on GitHub ↗
(self, module, input, output)

Source from the content-addressed store, hash-verified

153 return self.original_forward_func(input_ids=input_ids, labels=labels, attention_mask=attention_mask, **kwargs)
154
155 def post_forward_hook(self, module, input, output):
156 batch, time_dim, vocab_size = output.shape
157 shift = 0 if self.is_encoder_decoder else 1
158 lm_logits = output
159 lm_logits = torch.nn.functional.log_softmax(lm_logits, dim=-1) # (batch, time, vocab)
160 queries = self.activation_capturer.captured # (batch, time, dim)
161
162 if self.labels is None:
163 nonpad_mask = torch.cat([
164 torch.zeros([batch, time_dim - 1], dtype=torch.bool),
165 torch.ones([batch, 1], dtype=torch.bool),
166 ], axis=-1).to(self.device)
167 else:
168 nonpad_mask = torch.cat([
169 self.labels[:, shift:] != -100,
170 torch.zeros([self.labels.shape[0], shift], dtype=torch.bool).to(self.device)
171 ], axis=-1)
172
173 lm_logits = lm_logits[nonpad_mask]
174 queries = queries[nonpad_mask] # (nonpad, dim)
175
176 dists, knns = self.get_knns(queries) # (nonpad batch * time, k)
177
178 # Compute knn probs
179 neg_dists = -dists
180 knn_log_probs = self.knns_to_log_prob(knns, neg_dists) # (nonpad b*t, vocab_size)
181
182 # Interpolate
183 interpolated_scores = KNNWrapperMulti.interpolate(dists, knn_log_probs, lm_logits, self.lmbda) # (nonpad b * t, vocab)
184 output[nonpad_mask] = interpolated_scores.to(output.dtype)
185
186 return output
187
188 def knns_to_probs(self, knns, neg_dists):
189 probs = torch.nn.functional.softmax(neg_dists / self.knn_temperature, dim=-1).to(torch.float32)

Callers

nothing calls this directly

Calls 3

get_knnsMethod · 0.95
knns_to_log_probMethod · 0.95
interpolateMethod · 0.80

Tested by

no test coverage detected