[`PEFT`] Fix `save_pretrained` to make sure adapters weights are also saved on TPU
Author: shub-kris
Pull request: yes

Bug Fix for saving adapter weights when using PEFT

# What does this PR do?

This PR fixes  saving adapter weights when using PEFT on TPUs. Currently only the model weights are being saved and not the adapter weights. 

I tested it locally with this change on this [script](https://gist.github.com/shub-kris/16fa07d7c98a4890d28a8366a203f7af) and now it saves following whiles whenever checkpointing:

```
README.md            
adapter_model.safetensors  
rng_state.pth  
special_tokens_map.json  
tokenizer.model        
trainer_state.json
adapter_config.json  
optimizer.pt               
scheduler.pt   
tokenizer.json           
tokenizer_config.json  
training_args.bin
```


## 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?
- [x] 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?

Earlier discussed [here](https://huggingface.slack.com/archives/C01N44FJDHT/p1709227562328409)


## 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 and @younesbelkada
- vision models: @amyeroberts
- speech models: @sanchit-gandhi
- graph models: @clefourrier

Library:

- flax: @sanchit-gandhi
- generate: @gante
- pipelines: @Narsil
- tensorflow: @gante and @Rocketknight1
- tokenizers: @ArthurZucker
- trainer: @muellerzr and @pacman100

Integrations:

- deepspeed: HF Trainer/Accelerate: @pacman100
- ray/raytune: @richardliaw, @amogkam
- Big Model Inference: @SunMarc
- quantization (bitsandbytes, autogpt): @SunMarc and @younesbelkada

Documentation: @stevhliu and @MKhalusova

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_29388). All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

Hello there, What is the state of the PR? Is there a timeline when it will be merged and a new release of transformer will be out?

Just waiting for @shub-kris to come back ( he is off ) and transformers release will be in around 2 weeks

I ran some tests on a GKE Cluster with TPU V4 with 4 nodes.

https://gist.github.com/moficodes/1492228c80a3c08747a973b519cc7cda

This run fails with 

```bash
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/site-packages/safetensors/torch.py", line 13, in storage_ptr
    return tensor.untyped_storage().data_ptr()
RuntimeError: Attempted to access the data pointer on an invalid python storage.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "//fsdp.py", line 112, in <module>
    model.save_pretrained(new_model_id)
  File "/usr/local/lib/python3.10/site-packages/transformers/modeling_utils.py", line 2448, in save_pretrained
    safe_save_file(shard, os.path.join(save_directory, shard_file), metadata={"format": "pt"})
  File "/usr/local/lib/python3.10/site-packages/safetensors/torch.py", line 281, in save_file
    serialize_file(_flatten(tensors), filename, metadata=metadata)
  File "/usr/local/lib/python3.10/site-packages/safetensors/torch.py", line 470, in _flatten
    shared_pointers = _find_shared_tensors(tensors)
  File "/usr/local/lib/python3.10/site-packages/safetensors/torch.py", line 72, in _find_shared_tensors
    if v.device != torch.device("meta") and storage_ptr(v) != 0 and storage_size(v) != 0:
  File "/usr/local/lib/python3.10/site-packages/safetensors/torch.py", line 17, in storage_ptr
    return tensor.storage().data_ptr()
  File "/usr/local/lib/python3.10/site-packages/torch/storage.py", line 956, in data_ptr
    return self._data_ptr()
  File "/usr/local/lib/python3.10/site-packages/torch/storage.py", line 960, in _data_ptr
    return self._untyped_storage.data_ptr()
RuntimeError: Attempted to access the data pointer on an invalid python storage.
```

That looks like the original error. So not certain if the cause of the error was resolved.

> I ran some tests on a GKE Cluster with TPU V4 with 4 nodes.
> 
> https://gist.github.com/moficodes/1492228c80a3c08747a973b519cc7cda
> 
> This run fails with
> 
> ```shell
> Traceback (most recent call last):
>   File "/usr/local/lib/python3.10/site-packages/safetensors/torch.py", line 13, in storage_ptr
>     return tensor.untyped_storage().data_ptr()
> RuntimeError: Attempted to access the data pointer on an invalid python storage.
> 
> During handling of the above exception, another exception occurred:
> 
> Traceback (most recent call last):
>   File "//fsdp.py", line 112, in <module>
>     model.save_pretrained(new_model_id)
>   File "/usr/local/lib/python3.10/site-packages/transformers/modeling_utils.py", line 2448, in save_pretrained
>     safe_save_file(shard, os.path.join(save_directory, shard_file), metadata={"format": "pt"})
>   File "/usr/local/lib/python3.10/site-packages/safetensors/torch.py", line 281, in save_file
>     serialize_file(_flatten(tensors), filename, metadata=metadata)
>   File "/usr/local/lib/python3.10/site-packages/safetensors/torch.py", line 470, in _flatten
>     shared_pointers = _find_shared_tensors(tensors)
>   File "/usr/local/lib/python3.10/site-packages/safetensors/torch.py", line 72, in _find_shared_tensors
>     if v.device != torch.device("meta") and storage_ptr(v) != 0 and storage_size(v) != 0:
>   File "/usr/local/lib/python3.10/site-packages/safetensors/torch.py", line 17, in storage_ptr
>     return tensor.storage().data_ptr()
>   File "/usr/local/lib/python3.10/site-packages/torch/storage.py", line 956, in data_ptr
>     return self._data_ptr()
>   File "/usr/local/lib/python3.10/site-packages/torch/storage.py", line 960, in _data_ptr
>     return self._untyped_storage.data_ptr()
> RuntimeError: Attempted to access the data pointer on an invalid python storage.
> ```
> 
> That looks like the original error. So not certain if the cause of the error was resolved.

Hi @moficodes thanks for flagging this error, but on an initial glance, it doesn't look like the problem that this PR addresses. This PR aims to save the adapter weights, which were not being saved before this PR.

So, if you would have used trainer with this change it would save the adapter-weights too:

```
README.md            
adapter_model.safetensors  
rng_state.pth  
special_tokens_map.json  
tokenizer.model        
trainer_state.json
adapter_config.json  
optimizer.pt               
scheduler.pt   
tokenizer.json           
tokenizer_config.json  
training_args.bin
```
Earlier, `adapter_model.safetensors` and `adapter_config.json` were not being saved. A simple script to demonstrate is [here](https://gist.github.com/shub-kris/d1bdf330a2c95b9fa6b6db18b8a923e5) which you can run by

```bash
export XLA_USE_BF16=1 PJRT_DEVICE=TPU XLA_USE_SPMD=1  HF_TOKEN=<your-HF-TOKEN>
python save-gemma.py
```


So, it might happen that the error you are encountering is unrelated to what this PR tries to fix. 

I see. Will open a separate issue for it then. 

Thank you!

The error happens on the same line though.  `model.save_pretrained(new_model_id)` 

@LysandreJik can we merge this if it looks good to you, since @ArthurZucker is on holidays and I made the changes he asked and have tested it too locally.

@moficodes answered it here: https://github.com/huggingface/transformers/issues/29608#issuecomment-1993797013

@shub-kris Based on reviews and code, we can merge. There's currently a failing test which needs to be resolved first. Could you try rebasing on main to make sure you have all the latest updates, and trigger a fresh CI run? 

@amyeroberts Than you for looking into the PR. I have rebased but some checks are still failing because of this I guess: https://github.com/huggingface/transformers/runs/22627188153

@shub-kris Yep - a fix has just been merged into main. Apologies for the disruption. Could you try rebasing again? 

Thanks a lot @amyeroberts