Skip to content

Commit

Permalink
Allow bos_token_id is None during the generation with `inputs_embed…
Browse files Browse the repository at this point in the history
…s` (#29772)

* update

* add ut

* update
  • Loading branch information
LZHgrla authored and Ita Zaporozhets committed May 14, 2024
1 parent 53693ab commit 7008a05
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/transformers/generation/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -436,9 +436,6 @@ def _maybe_initialize_input_ids_for_generation(
shape = encoder_outputs.last_hidden_state.size()[:-1]
return torch.ones(shape, dtype=torch.long, device=self.device) * -100

if bos_token_id is None:
raise ValueError("`bos_token_id` has to be defined when no `input_ids` are provided.")

# If there is some tensor in `model_kwargs`, we can infer the batch size from it. This is helpful with
# soft-prompting or in multimodal implementations built on top of decoder-only language models.
batch_size = 1
Expand All @@ -449,6 +446,10 @@ def _maybe_initialize_input_ids_for_generation(

if "inputs_embeds" in model_kwargs:
return torch.ones((batch_size, 0), dtype=torch.long, device=self.device)

if bos_token_id is None:
raise ValueError("`bos_token_id` has to be defined when no `input_ids` are provided.")

return torch.ones((batch_size, 1), dtype=torch.long, device=self.device) * bos_token_id

def _prepare_attention_mask_for_generation(
Expand Down
11 changes: 11 additions & 0 deletions tests/generation/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1467,6 +1467,17 @@ def test_past_key_values_format(self):
past_kv[i][1].shape, (batch_size, num_attention_heads, seq_length, per_head_embed_dim)
)

def test_generate_from_inputs_embeds_with_bos_token_id_is_none(self):
article = "Today a dragon flew over Paris."
model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(torch_device)
tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
input_ids = tokenizer(article, return_tensors="pt").input_ids.to(torch_device)
inputs_embeds = model.get_input_embeddings()(input_ids)

model.generate(inputs_embeds=inputs_embeds, max_length=20, bos_token_id=None)
with self.assertRaises(ValueError):
model.generate(max_length=20, bos_token_id=None)

def test_generate_from_inputs_embeds_decoder_only(self):
# When supported, tests that the decoder model can generate from `inputs_embeds` instead of `input_ids`
# if fails, you should probably update the `prepare_inputs_for_generation` function
Expand Down

0 comments on commit 7008a05

Please sign in to comment.