Update modeling_llama.py
Author: askxiaozhang
Pull request: yes

When I runned tokenizer.apply_chat_template in runing DeepSeek-Coder,happened this bug.So I Fixed about:
Traceback (most recent call last):
  File "/data/jiaqi/DeepSeek-Coder/main.py", line 79, in <module>
    model = AutoModelForCausalLM.from_pretrained(model_path, trust_remote_code=True).cuda()
  File "/data/anaconda3/envs/codellama/lib/python3.10/site-packages/transformers/models/auto/auto_factory.py", line 565, in from_pretrained
    model_class = _get_model_class(config, cls._model_mapping)
  File "/data/anaconda3/envs/codellama/lib/python3.10/site-packages/transformers/models/auto/auto_factory.py", line 387, in _get_model_class
    supported_models = model_mapping[type(config)]
  File "/data/anaconda3/envs/codellama/lib/python3.10/site-packages/transformers/models/auto/auto_factory.py", line 740, in __getitem__
    return self._load_attr_from_module(model_type, model_name)
  File "/data/anaconda3/envs/codellama/lib/python3.10/site-packages/transformers/models/auto/auto_factory.py", line 754, in _load_attr_from_module
    return getattribute_from_module(self._modules[module_name], attr)
  File "/data/anaconda3/envs/codellama/lib/python3.10/site-packages/transformers/models/auto/auto_factory.py", line 698, in getattribute_from_module
    if hasattr(module, attr):
  File "/data/anaconda3/envs/codellama/lib/python3.10/site-packages/transformers/utils/import_utils.py", line 1335, in __getattr__
    module = self._get_module(self._class_to_module[name])
  File "/data/anaconda3/envs/codellama/lib/python3.10/site-packages/transformers/utils/import_utils.py", line 1347, in _get_module
    raise RuntimeError(
RuntimeError: Failed to import transformers.models.llama.modeling_llama because of the following error (look up to see its traceback): module 'torch' has no attribute 'fx'

# 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 # (issue)


## 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#start-contributing-pull-requests),
      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:
Hi @askxiaozhang, 

So that we can understand whether this is the best fix for the bug - could you share your running environment when encountering this bug (run `transformers-cli env` in the terminal and copy-paste the output) as well as a minimal code snippet to reproduce the error? 

Note: any import of `fx` needs to be protected so that things don't crash if it's not installed e.g. [here ](https://github.com/huggingface/transformers/blob/3d1a7bf4761e332e78e07d147bacb0d26a522187/src/transformers/models/llama/modeling_llama.py#L54C1-L54C1)

> Hi @askxiaozhang,
> 
> So that we can understand whether this is the best fix for the bug - could you share your running environment when encountering this bug (run `transformers-cli env` in the terminal and copy-paste the output) as well as a minimal code snippet to reproduce the error?
> 
> Note: any import of `fx` needs to be protected so that things don't crash if it's not installed e.g. [here ](https://github.com/huggingface/transformers/blob/3d1a7bf4761e332e78e07d147bacb0d26a522187/src/transformers/models/llama/modeling_llama.py#L54C1-L54C1)
OK,thanks for your advice. There are some infomation:
- `transformers` version: 4.36.0.dev0
- Platform: Linux-5.4.119-19.0009.28-x86_64-with-glibc2.17
- Python version: 3.10.4
- Huggingface_hub version: 0.17.3
- Safetensors version: 0.4.0
- Accelerate version: 0.24.1
- Accelerate config:    not found
- PyTorch version (GPU?): 1.12.1 (True)
- Tensorflow version (GPU?): not installed (NA)
- Flax version (CPU?/GPU?/TPU?): not installed (NA)
- Jax version: not installed
- JaxLib version: not installed
- Using GPU in script?: <fill in>
- Using distributed or parallel set-up in script?: <fill in>

code snippet:
```
from transformers import AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(model_path, trust_remote_code=True).cuda()
messages=[
    { 'role': 'user', 'content': "write a quick sort algorithm in python"}
]
inputs = tokenizer.apply_chat_template(messages, return_tensors="pt").to(model.device)
outputs = model.generate(inputs, max_new_tokens=2048, do_sample=False, top_k=50, top_p=0.95, num_return_sequences=1, eos_token_id=32021)
print(tokenizer.decode(outputs[0][len(inputs[0]):], skip_special_tokens=True))
```

After I runned code:
```
Traceback (most recent call last):
  File "/data/anaconda3/envs/codellama/lib/python3.10/site-packages/transformers-4.36.0.dev0-py3.10.egg/transformers/utils/import_utils.py", line 1353, in _get_module
    return importlib.import_module("." + module_name, self.__name__)
  File "/data/anaconda3/envs/codellama/lib/python3.10/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/data/anaconda3/envs/codellama/lib/python3.10/site-packages/transformers-4.36.0.dev0-py3.10.egg/transformers/models/llama/modeling_llama.py", line 55, in <module>
    _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
AttributeError: module 'torch' has no attribute 'fx'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/data/jiaqi/DeepSeek-Coder/main.py", line 49, in <module>
    model = AutoModelForCausalLM.from_pretrained(model_path, trust_remote_code=True).cuda()
  File "/data/anaconda3/envs/codellama/lib/python3.10/site-packages/transformers-4.36.0.dev0-py3.10.egg/transformers/models/auto/auto_factory.py", line 565, in from_pretrained
    model_class = _get_model_class(config, cls._model_mapping)
  File "/data/anaconda3/envs/codellama/lib/python3.10/site-packages/transformers-4.36.0.dev0-py3.10.egg/transformers/models/auto/auto_factory.py", line 387, in _get_model_class
    supported_models = model_mapping[type(config)]
  File "/data/anaconda3/envs/codellama/lib/python3.10/site-packages/transformers-4.36.0.dev0-py3.10.egg/transformers/models/auto/auto_factory.py", line 740, in __getitem__
    return self._load_attr_from_module(model_type, model_name)
  File "/data/anaconda3/envs/codellama/lib/python3.10/site-packages/transformers-4.36.0.dev0-py3.10.egg/transformers/models/auto/auto_factory.py", line 754, in _load_attr_from_module
    return getattribute_from_module(self._modules[module_name], attr)
  File "/data/anaconda3/envs/codellama/lib/python3.10/site-packages/transformers-4.36.0.dev0-py3.10.egg/transformers/models/auto/auto_factory.py", line 698, in getattribute_from_module
    if hasattr(module, attr):
  File "/data/anaconda3/envs/codellama/lib/python3.10/site-packages/transformers-4.36.0.dev0-py3.10.egg/transformers/utils/import_utils.py", line 1343, in __getattr__
    module = self._get_module(self._class_to_module[name])
  File "/data/anaconda3/envs/codellama/lib/python3.10/site-packages/transformers-4.36.0.dev0-py3.10.egg/transformers/utils/import_utils.py", line 1355, in _get_module
    raise RuntimeError(
RuntimeError: Failed to import transformers.models.llama.modeling_llama because of the following error (look up to see its traceback):
module 'torch' has no attribute 'fx'
```
  

Hi @askxiaozhang. Thanks for providing further details! This issue should be resolved with #27570

This issue has been automatically marked as stale because it has not had recent activity. If you think this still needs to be addressed please comment on this thread.

Please note that issues that do not follow the [contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) are likely to be ignored.