Disable torch.autocast in RotaryEmbedding of Gemma and LLaMa for meta device
Author: KJY-dev
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 -->
Disable torch.autocast in RotaryEmbedding of Gemma and LLaMa for meta device.
Similar to  (https://github.com/huggingface/transformers/pull/29439). 

## 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).
- [ ] 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 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:
Hey! Could you explain why we need this? Don't understand how one ends up needing to compute on meta? 

To check the model output shape, I created a llama model using the "meta" device.
```
import torch
from transformers import LlamaForCausalLM

def gen_dummy_attn_input(device):
    hidden_states = torch.randn(size=(1, 2048, 1440)).to(device)
    attention_mask = torch.randn(size=(1, 1, 2048, 2048)).to(device)
    position_ids = torch.ones(size=(1, 2048), dtype=torch.int64).to(device)
    output_attentions = False
    use_cache = False
    cache_position = torch.ones(size=(2048, ), dtype=torch.int64).to(device)
    return hidden_states, attention_mask, position_ids, output_attentions, use_cache, cache_position

model_name = '/llama_model'
model = LlamaForCausalLM.from_pretrained(model_name, torch_dtype='auto').to('meta').eval()
model.seqlen = 2048

attn = model.model.layers[0].self_attn
device = torch.device('meta')
hidden_states, attention_mask, position_ids, output_attentions, use_cache, cache_position = gen_dummy_attn_input(device)

attn_output = attn(
    hidden_states = hidden_states,
    attention_mask = attention_mask,
    position_ids = position_ids,
    output_attentions = output_attentions,
    use_cache = use_cache,
    cache_position = cache_position
)

pass
```

And this error occurred:
```
File "/usr/local/lib/python3.10/site-packages/torch/amp/autocast_mode.py", line 201, in __init__
    raise RuntimeError('User specified autocast device_type must be \'cuda\' or \'cpu\'')
RuntimeError: User specified autocast device_type must be 'cuda' or 'cpu'
````


So, similar to (https://github.com/huggingface/transformers/pull/29439), I temporarily disabled the meta device in torch.autocast, and it seemed to work fine.
https://github.com/huggingface/transformers/blob/f4364a6ff16e33186cb40f1d3fafd3792556d1b8/src/transformers/models/llama/modeling_llama.py#L139
```
# device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
device_type = device_type if isinstance(device_type, str) and device_type not in ["mps", "meta"] else "cpu"
```


Hi @KJY-dev, thanks for providing this example. 

A few points: 

1. You can create an empty model using accelerate's `init_empty_weights` functionality:

```py
from transformers import LlamaConfig, LlamaForCausalLM

config = LlamaConfig.from_pretrained(checkpoint)

with init_empty_weights():
    model = LlamaForCausalLM(config)
```

The call using `from_pretrained` and then moving to the meta device is unnecessarily expensive. 

2. Setting `model.seqlen = 2048` won't do anything. The model is loaded based on the checkpoint `model_name` provided and is already created after the `from_pretrained` call

3. You shouldn't need to create a model, you can see how the model is built, just from loading its config. The returned output from `LLamaForCausalLM` is [CausalLMOutputWithPast](https://github.com/huggingface/transformers/blob/b9ceb03df8a2585f3357aee715acb5c4217e9833/src/transformers/modeling_outputs.py#L678). The returned attentions, are for a single layer of the shape `(batch_size, num_heads, sequence_length, sequence_length)`. So, from the config, you'd have: 

```py
batch_size, seq_len = input_ids.shape
seq_len = min(config.max_position_embeddings, seq_len) 
output_shape = (batch_size, config.num_attention_heads, seq_len, seq_len)
```

@amyeroberts  Thank you for answer. 😄 
Thanks for the tip on how to create an empty model using `init_empty_weights`.

Then, is there a way to inference llama model on `meta`?
I want to get all layer output shapes, including all variable shapes in model's `forward` method. 
And for memory efficiency I would like to calculate output and variable shapes on `meta`.




@KJY-dev I don't believe you can do inference on the meta device - the tensors created have no data. If you create the model on the meta device, you can access the state dict, which will give you all of the layer's shapes. The forward method is effectively a black box, so you can't get the size of all the variables used without directly interrogating the code.