Fix: Enable prefill phase key value caching of nemotron/minitron models
Author: jeongin601
Pull request: yes

# What does this PR do?

<!--
Congratulations! You've made it this far! You're not quite done yet though.

Once merged, your PR is going to appear in the release notes with the title you set, so make sure it's a great title that fully reflects the extent of your awesome contribution.

Then, please replace this with a description of the change and which issue is fixed (if applicable). Please also include relevant motivation and context. List any dependencies (if any) that are required for this change.

Once you're done, someone will review your PR shortly (see the section "Who can review?" below to tag some potential reviewers). They may suggest changes to make the code even better. If no one reviewed your PR after a week has passed, don't hesitate to post a new comment @-mentioning the same persons---sometimes notifications get lost.
-->

<!-- Remove if not applicable -->

Fixes #34739

## Problem

Current implementation does not enable key value caching of nemotron and minitron models.
This problem can be checked by a quick example code that generates key and value caches.

## Modification
I modified the code to enabled key value caching while prefill phase, in reference to` 'modeling_llama.py'` file.

## Key value caching example code
```python
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

# Load Minitron model and tokenizer from Hugging Face
model_name = "your-minitron-model-name"  # Replace with the actual Minitron model name
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)

# Set the model to evaluation mode
model.eval()

# Sample input text
input_text = "Hello, how are you?"

# Tokenize the input
input_ids = tokenizer(input_text, return_tensors="pt").input_ids

# First forward pass (prefill phase)
with torch.no_grad():
    outputs = model(input_ids, use_cache=True)  # Set use_cache=True
    logits = outputs.logits
    past_key_values = outputs.past_key_values

# Check the output
print("Logits shape:", logits.shape)
print("Number of layers in past_key_values:", len(past_key_values))
print("Shape of keys and values in the first layer:")
print("Key shape:", past_key_values[0][0].shape)
print("Value shape:", past_key_values[0][1].shape)

# Add new input to test cache utilization
new_input_text = " What about you?"
new_input_ids = tokenizer(new_input_text, return_tensors="pt").input_ids

# Pass the new input along with the previous key-value cache
with torch.no_grad():
    outputs_with_cache = model(new_input_ids, past_key_values=past_key_values, use_cache=True)

# Check results after caching
new_logits = outputs_with_cache.logits
new_past_key_values = outputs_with_cache.past_key_values

print("New logits shape:", new_logits.shape)
print("Number of layers in new past_key_values:", len(new_past_key_values))
```
### As-Is Result 
![스크린샷 2024-11-15 오후 1 15 33](https://github.com/user-attachments/assets/259002b2-f661-4d03-a865-4dbe21d21c8d)

Key value caching is not done.

### To-be Result
![스크린샷 2024-11-15 오후 4 15 44](https://github.com/user-attachments/assets/edb42ad8-2bc4-408c-8b0e-eda506b43728)

Key value caching is enabled

## 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?

Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.




@ArthurZucker
Can you please check my modification? :)

<!-- 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 @MekkCyber

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:
cc @ArthurZucker @gante @zucchini-nlp 

BTW seem to be related to #34274

The docs for this PR live [here](https://moon-ci-docs.huggingface.co/docs/transformers/pr_34742). All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

> One suggestion and we can merge!

I updated it! :) Thanks

Hi @jeongin601, thank you for this PR ❤️ !

It seems this PR has some regression: below is the 3 tests failing. Would you be up to take a look? You can find the job run log [here](https://github.com/huggingface/transformers/actions/runs/12022766734/job/33515773773).

In any case, thank you in advance.


```python
        "nemotron": {
            "single-gpu": [
                {
                    "test": "tests/models/nemotron/test_modeling_nemotron.py::NemotronModelTest::test_torchscript_output_attentions",
                    "commit": "318fe25f22a99ce1226f8d2aadc268b40f7e55af",
                    "pr_number": 34742,
                    "author": "jeongin601",
                    "merged_by": "zucchini-nlp"
                },
                {
                    "test": "tests/models/nemotron/test_modeling_nemotron.py::NemotronModelTest::test_torchscript_output_hidden_state",
                    "commit": "318fe25f22a99ce1226f8d2aadc268b40f7e55af",
                    "pr_number": 34742,
                    "author": "jeongin601",
                    "merged_by": "zucchini-nlp"
                },
                {
                    "test": "tests/models/nemotron/test_modeling_nemotron.py::NemotronModelTest::test_torchscript_simple",
                    "commit": "318fe25f22a99ce1226f8d2aadc268b40f7e55af",
                    "pr_number": 34742,
                    "author": "jeongin601",
                    "merged_by": "zucchini-nlp"
                }
            ]
        }
    },
```


@ArthurZucker @zucchini-nlp A kind remind: don't hesitate to ask for slow CI 🙂 - let's use the tools we have to make our life easier🙏 



Ah it makes sense, torchscript does not support `DynamicCache` class !

(AFAIR)

ah ok. I will check than. But if we eventually move forward to `DynamicCache` and drop legacy cache, it would mean torchscript is not going to work for many models ..?

Yeah 👀 unless used with optimum!