Skip to content
This repository was archived by the owner on Sep 10, 2025. It is now read-only.

Commit 208f2ea

Browse files
committed
repro unbounded beam_idx
1 parent d622466 commit 208f2ea

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

torchtext/prototype/generate.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -295,7 +295,27 @@ def update_func(emissions, N, T, prev_step_token_idxs, prev_step_hyp_idxs, prev_
295295
model_inputs.update(self._huggingface_model_input_values)
296296
if len(prev_step_hyp_idxs) > 1 and model_kwargs["past"] is not None:
297297
beam_idxs = torch.Tensor(prev_step_hyp_idxs).to(dtype=torch.int32)
298-
model_inputs["past_key_values"] = self.model._reorder_cache(model_kwargs["past"], beam_idxs)
298+
299+
# We could store this in model_kwargs
300+
num_hyps_in_prev_step = model_kwargs["past"][0][0].shape[0]
301+
302+
num_finished_hyps_in_step = num_hyps_in_prev_step - len(prev_step_hyp_idxs)
303+
if num_finished_hyps_in_step > 0:
304+
beam_idxs = F.pad(beam_idxs, (0, num_finished_hyps_in_step), "constant", 0)
305+
306+
reordered_cached = model_kwargs["past"] #self.model._reorder_cache(model_kwargs["past"], beam_idxs)
307+
308+
if num_finished_hyps_in_step > 0:
309+
sliced_cache = ()
310+
for states in reordered_cached:
311+
sliced_state = ()
312+
for state in states:
313+
sliced_state = sliced_state + (state[:len(prev_step_hyp_idxs)],)
314+
sliced_cache = sliced_cache + (sliced_state,)
315+
reordered_cached = sliced_cache
316+
317+
model_inputs["past_key_values"] = reordered_cached
318+
299319

300320
# Forward pass
301321
outputs = self.model(**model_inputs)

0 commit comments

Comments
 (0)