Make cache traceable
Author: IlyasMoutawwakil
Pull request: yes

# What does this PR do?

In #35792 I came to the conclusion that tensor subclassing is a process that can only be achieved currently with some restriction (e.g. [`get_seq_length()` needs to return a tensor](https://github.com/huggingface/transformers/pull/35792/files#diff-357aea2fcf1b51b2a8ad17c7d30044159b1fe1a3f6bd832cced70aca84c8be66R526)), adding more developer cognitive load when adding a cache class. In this PR we make the cache traceable and exportable by not being a `Module` and registering cache tensors as buffers directly in `TorchExportableModuleWithStaticCache`.

## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
- [ ] 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).
- [ ] 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.

<!-- 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:
The docs for this PR live [here](https://moon-ci-docs.huggingface.co/docs/transformers/pr_35873). All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

Tests in `optimum-executorch` are passing as well https://github.com/huggingface/optimum-executorch/pull/4

Can you check that https://github.com/huggingface/huggingface-llama-recipes/blob/main/performance_optimization/prompt_reuse.py still works

> Also I remember we had a need for nn.Module: copy. We need to be able to copy the cache object (or clone) for prefix re-usage

There is a test for that I saw running locally https://github.com/huggingface/transformers/blob/main/tests/utils/test_cache_utils.py#L593C1-L622C60

Hey guys, i work on the torch.export team at PyTorch and i just wanted to verify that this change only works for Static kv cache right? 

> Hey guys, i work on the torch.export team at PyTorch and i just wanted to verify that this change only works for Static kv cache right?

Hey ! not sure I understand, the change applies to `Cache` class which is inherited by all cache classes. And specifically for torch.export it removes the need to have `Cache` a subclass of `torch.nn.Module`.

just updated the branch, will merge tonight after tests pass to be sure everything is good.

@IlyasMoutawwakil @ArthurZucker @gante @guangy10  detach Cahce from torch.nn.Module remove the .float() method from it which causes an error when calling  convert_to_fp32
<img width="577" alt="image" src="https://github.com/user-attachments/assets/9f6996a4-36d7-4723-8d00-db68ce85b52c" />


self.float() should only be called if self is tensor or module, can you explain why it's called in this case ?

I saw the same stack trace in another issue, but the user didn't share a script to reproduce it. @eljandoubi could you kindly share a script to reproduce the issue? 🙏 

@IlyasMoutawwakil the `_is_fp16_bf16_tensor` function checks if an object is tensor or has dtype attribute and that dtype is either fp16 or bf16.

@gante  I'm afraid that I can't but I can provide guidance.When fine-tuning PaliGemma 2 mix in mixed precision (bf16), the evaluation in the training loop of the HF `Trainer` is done in fp32 and so `convert_to_fp32` is called.

This sounds like it was a silent error, because calling `.float()` on a `Cache` instance (when it was a `nn.Module`), doesn't actually do anything, since `Cache.key_cache` / `Cache.value_cache` are just lists and not module parameters.

In the case of fine-tuning I believe you need to pass `use_cache=False` so that Cache is not returned (and thus converting it is not attempted). We can implement `.float()` method that actually does the conversion of `Cache.key_cache` / `Cache.value_cache` depending on whether we want to silence this issue or force user to set `use_cache=False` when training, wdyt @gante ?

@IlyasMoutawwakil  Thanks for enlightening me. I think set `use_cache=False` automatically in the `Trainer` like when using gradient checkpointing would be great. Plus ignore objects that have no `.float()` method in `_is_fp16_bf16_tensor`.

(see https://github.com/huggingface/transformers/pull/37044)