@@ -227,9 +227,10 @@ def _generate_formula_tokens(
227227 import numpy as np
228228
229229 batch_size = int (encoder_hidden_states .shape [0 ])
230+ generation_limit = max (1 , int (max_new_tokens ))
230231 active_indices = np .arange (batch_size , dtype = np .int64 )
231232 active_input_ids = np .full (
232- (batch_size , 1 ), decoder_start_id , dtype = np .int64
233+ (batch_size , generation_limit ), decoder_start_id , dtype = np .int64
233234 )
234235 active_hidden_states = encoder_hidden_states
235236 token_ids : list [list [int ]] = [[] for _ in range (batch_size )]
@@ -241,11 +242,11 @@ def _generate_formula_tokens(
241242 input_ids_name = decoder_inputs [0 ].name
242243 hidden_states_name = decoder_inputs [1 ].name
243244
244- for _ in range (max ( 1 , int ( max_new_tokens )) ):
245+ for step in range (generation_limit ):
245246 logits = decoder_session .run (
246247 None ,
247248 {
248- input_ids_name : active_input_ids ,
249+ input_ids_name : active_input_ids [:, : step + 1 ] ,
249250 hidden_states_name : active_hidden_states ,
250251 },
251252 )[0 ]
@@ -275,14 +276,13 @@ def _generate_formula_tokens(
275276 keep_active_rows .append (active_row )
276277 if not keep_active_rows :
277278 break
278- active_input_ids = np .concatenate (
279- [
280- active_input_ids [keep_active_rows ],
281- next_tokens [keep_active_rows ].reshape (len (keep_active_rows ), 1 ),
282- ],
283- axis = 1 ,
284- )
285- active_hidden_states = active_hidden_states [keep_active_rows ]
286- active_indices = active_indices [keep_active_rows ]
279+ if len (keep_active_rows ) != len (active_indices ):
280+ # Encoder output can be several MiB. It stays constant between
281+ # decoding steps, so only copy it when finished batch rows leave.
282+ active_input_ids = active_input_ids [keep_active_rows ]
283+ active_hidden_states = active_hidden_states [keep_active_rows ]
284+ active_indices = active_indices [keep_active_rows ]
285+ if step + 1 < generation_limit :
286+ active_input_ids [:, step + 1 ] = next_tokens [keep_active_rows ]
287287
288288 return token_ids , token_scores , stopped_for_repetition
0 commit comments