Fix contrastive search to correctly handle input with padding
Author: ducviet00
Pull request: yes
Labels: name: Generation

# What does this PR do?

This PR fixes contrastive search to correctly handle input padding in decoder-only & encoder-decoder models.

## Details

I encountered the issue and discovered that the Contrastive Search implementation is highly sensitive to padded tokens.

For example, with the prompt: `The whispered legends of the haunted mansion spoke`, the output from Hugging Face without padding is: 
- `The whispered legends of the haunted mansion spoke of the "souls of the dead" who were "falling out of the sky" and "falling into the sea."\n`

However, with padding tokens, the output becomes: 
- `The whispered legends of the haunted mansion spoke of the "soul of the dead" and the "blood of the dead."\nThe ghost of Dr. H. P. Lovecraft was a man`

You can check the Colab notebook that demonstrates the issue [here](https://colab.research.google.com/drive/1q14xn3RpCDYxur1C1ORc_bJ60Y7m4e_n?usp=sharing)

## How did I fix the issue
The issue arises when `input_ids` contain padded tokens; the `hidden_states` of the model then include embeddings for these padded tokens if the model doesn't eliminate them during processing. The `_ranking_fast` function also calculates values based on these padded tokens, leading to incorrect outputs. This is critical because it significantly degrades the model's performance.

To fix this, I created a `cosine_matrix_mask` based on the `attention_mask` and penalized the `cosine_matrix` using this mask (ignoring padding positions) by applying large negative values. After that, I padded the `cosine_matrix_mask` with ones to match the output length.

## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
- [x] Did you read the [contributor guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#create-a-pull-request),
      Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the [forum](https://discuss.huggingface.co/)? Please add a link
      to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes? Here are the
      [documentation guidelines](https://github.com/huggingface/transformers/tree/main/docs), and
      [here are tips on formatting docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [x] Did you write any new necessary tests?


## Who can review?
@gante @ArthurZucker @amyeroberts @Rocketknight1

<!-- Your PR will be replied to more quickly if you can figure out the right person to tag with @

 If you know how to use git blame, that is the easiest way, otherwise, here is a rough guide of **who to tag**.
 Please tag fewer than 3 people.

Models:

- text models: @ArthurZucker
- vision models: @amyeroberts, @qubvel
- speech models: @ylacombe, @eustlb
- graph models: @clefourrier

Library:

- flax: @sanchit-gandhi
- generate: @zucchini-nlp (visual-language models) or @gante (all others)
- pipelines: @Rocketknight1
- tensorflow: @gante and @Rocketknight1
- tokenizers: @ArthurZucker
- trainer: @muellerzr and @SunMarc
- chat templates: @Rocketknight1

Integrations:

- deepspeed: HF Trainer/Accelerate: @muellerzr
- ray/raytune: @richardliaw, @amogkam
- Big Model Inference: @SunMarc
- quantization (bitsandbytes, autogpt): @SunMarc

Documentation: @stevhliu

HF projects:

- accelerate: [different repo](https://github.com/huggingface/accelerate)
- datasets: [different repo](https://github.com/huggingface/datasets)
- diffusers: [different repo](https://github.com/huggingface/diffusers)
- rust tokenizers: [different repo](https://github.com/huggingface/tokenizers)

Maintained examples (not research project or legacy):

- Flax: @sanchit-gandhi
- PyTorch: See Models above and tag the person corresponding to the modality of the example.
- TensorFlow: @Rocketknight1

 -->


Comments:
@gante Thanks for your feedback! I initially thought encoder-decoder models wouldn’t be affected since `decoder_input_ids` don’t seem to need padding tokens, except in continuous batching (not in this case). Applying the `cosine_matrix_mask` to these models might add some minor overhead, though. I hadn’t considered the decoder prompt before, so thanks for pointing that out! 

I’ll push an update with support for encoder-decoder models based on your suggestions soon.

@gante 
I push an update to support encode-decoder models. I also added test for t5 model, with padding for `decoder_input_ids`. On the main branch, `outputs_with_padding`:
- `Ich muss diese Aufgabe noch vor Ende des Tages beenden.`

It should be: 
- `Ich muss diese Aufgabe vor Ende des Tages beenden.`

You can check the code inside `test_padding_input_contrastive_search_t5`, in `tests/generation/test_utils.py`

Hi @gante
PTAL 🤗

@ducviet00 thank you for making `transformers` better for everyone 💛