lavrenko commited on
Commit
ca939e7
·
1 Parent(s): 4426899

Guard shared prefill for non-standard input expansion

Browse files

Only enable shared prefill when beam expansion can be safely reversed. Fall back to the original beam-shaped forward path for models with custom input expansion or tensors whose leading dimension does not match the expanded beam batch.

Files changed (1) hide show
  1. custom_generate/generate.py +16 -1
custom_generate/generate.py CHANGED
@@ -241,6 +241,20 @@ def _group_beam_search(
241
  device = input_ids.device
242
 
243
  batch_beam_size, cur_len = input_ids.shape
 
 
 
 
 
 
 
 
 
 
 
 
 
 
244
  # Does not exist anymore in recent versions!
245
  if hasattr(model, "_get_initial_cache_position"):
246
  model_kwargs = model._get_initial_cache_position(cur_len, input_ids.device, model_kwargs)
@@ -314,9 +328,10 @@ def _group_beam_search(
314
  )
315
 
316
  # prefill one prompt per batch item before beams diverge
317
- # keep the original path when returned model outputs must remain beam-shaped
318
  shared_prefill = (
319
  is_first_iteration
 
320
  and not model.config.is_encoder_decoder
321
  and not (output_attentions or output_hidden_states or output_logits)
322
  )
 
241
  device = input_ids.device
242
 
243
  batch_beam_size, cur_len = input_ids.shape
244
+
245
+ # Shared prefill can only undo the standard beam expansion when every
246
+ # non-scalar tensor is expanded along the leading batch dimension.
247
+ can_share_prefill = (
248
+ type(model)._expand_inputs_for_generation
249
+ is GenerationMixin._expand_inputs_for_generation
250
+ and all(
251
+ not isinstance(value, torch.Tensor)
252
+ or value.ndim == 0
253
+ or value.shape[0] == batch_beam_size
254
+ for value in model_kwargs.values()
255
+ )
256
+ )
257
+
258
  # Does not exist anymore in recent versions!
259
  if hasattr(model, "_get_initial_cache_position"):
260
  model_kwargs = model._get_initial_cache_position(cur_len, input_ids.device, model_kwargs)
 
328
  )
329
 
330
  # prefill one prompt per batch item before beams diverge
331
+ # keep the original path when beam expansion cannot be safely undone
332
  shared_prefill = (
333
  is_first_iteration
334
+ and can_share_prefill
335
  and not model.config.is_encoder_decoder
336
  and not (output_attentions or output_hidden_states or output_logits)
337
  )